1   /**
2    * Copyright (c) 2000-2009 Liferay, Inc. All rights reserved.
3    *
4    * Permission is hereby granted, free of charge, to any person obtaining a copy
5    * of this software and associated documentation files (the "Software"), to deal
6    * in the Software without restriction, including without limitation the rights
7    * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8    * copies of the Software, and to permit persons to whom the Software is
9    * furnished to do so, subject to the following conditions:
10   *
11   * The above copyright notice and this permission notice shall be included in
12   * all copies or substantial portions of the Software.
13   *
14   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15   * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16   * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17   * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18   * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19   * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
20   * SOFTWARE.
21   */
22  
23  package com.liferay.portal.editor.fckeditor.receiver.impl;
24  
25  import com.liferay.portal.editor.fckeditor.command.CommandArgument;
26  import com.liferay.portal.editor.fckeditor.exception.FCKException;
27  import com.liferay.portal.editor.fckeditor.receiver.CommandReceiver;
28  import com.liferay.portal.kernel.dao.orm.QueryUtil;
29  import com.liferay.portal.kernel.log.Log;
30  import com.liferay.portal.kernel.log.LogFactoryUtil;
31  import com.liferay.portal.kernel.util.GetterUtil;
32  import com.liferay.portal.kernel.util.StringPool;
33  import com.liferay.portal.kernel.util.StringUtil;
34  import com.liferay.portal.model.Group;
35  import com.liferay.portal.model.Organization;
36  import com.liferay.portal.service.GroupLocalServiceUtil;
37  import com.liferay.portal.service.OrganizationLocalServiceUtil;
38  import com.liferay.portal.upload.LiferayFileItemFactory;
39  import com.liferay.portal.upload.UploadServletRequestImpl;
40  import com.liferay.portal.util.PropsValues;
41  
42  import java.io.File;
43  import java.io.PrintWriter;
44  
45  import java.util.HashMap;
46  import java.util.LinkedHashMap;
47  import java.util.List;
48  import java.util.Map;
49  
50  import javax.servlet.http.HttpServletRequest;
51  import javax.servlet.http.HttpServletResponse;
52  
53  import javax.xml.parsers.DocumentBuilder;
54  import javax.xml.parsers.DocumentBuilderFactory;
55  import javax.xml.parsers.ParserConfigurationException;
56  import javax.xml.transform.Transformer;
57  import javax.xml.transform.TransformerFactory;
58  import javax.xml.transform.dom.DOMSource;
59  import javax.xml.transform.stream.StreamResult;
60  
61  import org.apache.commons.fileupload.FileItem;
62  import org.apache.commons.fileupload.FileUploadException;
63  import org.apache.commons.fileupload.disk.DiskFileItem;
64  import org.apache.commons.fileupload.servlet.ServletFileUpload;
65  
66  import org.w3c.dom.Document;
67  import org.w3c.dom.Element;
68  import org.w3c.dom.Node;
69  
70  /**
71   * <a href="BaseCommandReceiver.java.html"><b><i>View Source</i></b></a>
72   *
73   * @author Ivica Cardic
74   *
75   */
76  public abstract class BaseCommandReceiver implements CommandReceiver {
77  
78      public void createFolder(
79          CommandArgument argument, HttpServletRequest request,
80          HttpServletResponse response) {
81  
82          Document doc = _createDocument();
83  
84          Node root = _createRoot(
85              doc, argument.getCommand(), argument.getType(),
86              argument.getCurrentFolder(), StringPool.BLANK);
87  
88          Element errorEl = doc.createElement("Error");
89  
90          root.appendChild(errorEl);
91  
92          String returnValue = "0";
93  
94          try {
95              returnValue = createFolder(argument);
96          }
97          catch (FCKException fcke) {
98              Throwable cause = fcke.getCause();
99  
100             returnValue = "110";
101 
102             if (cause != null) {
103                 String causeString = GetterUtil.getString(cause.toString());
104 
105                 if (causeString.indexOf("DuplicateFolderNameException") != -1) {
106                     returnValue = "101";
107                 }
108                 else if (causeString.indexOf("FolderNameException") != -1) {
109                     returnValue = "102";
110                 }
111                 else if (causeString.indexOf("NoSuchGroupException") != -1) {
112                     returnValue = "103";
113                 }
114                 else {
115                     throw fcke;
116                 }
117             }
118         }
119 
120         errorEl.setAttribute("number", returnValue);
121 
122         _writeDocument(doc, response);
123     }
124 
125     public void getFolders(
126         CommandArgument argument, HttpServletRequest request,
127         HttpServletResponse response) {
128 
129         Document doc = _createDocument();
130 
131         Node root = _createRoot(
132             doc, argument.getCommand(), argument.getType(),
133             argument.getCurrentFolder(), getPath(argument));
134 
135         getFolders(argument, doc, root);
136 
137         _writeDocument(doc, response);
138     }
139 
140     public void getFoldersAndFiles(
141         CommandArgument argument, HttpServletRequest request,
142         HttpServletResponse response) {
143 
144         Document doc = _createDocument();
145 
146         Node root = _createRoot(
147             doc, argument.getCommand(), argument.getType(),
148             argument.getCurrentFolder(), getPath(argument));
149 
150         getFoldersAndFiles(argument, doc, root);
151 
152         _writeDocument(doc, response);
153     }
154 
155     public void fileUpload(
156         CommandArgument argument, HttpServletRequest request,
157         HttpServletResponse response) {
158 
159         ServletFileUpload upload = new ServletFileUpload(
160             new LiferayFileItemFactory(
161                 UploadServletRequestImpl.DEFAULT_TEMP_DIR));
162 
163         List<FileItem> items = null;
164 
165         try {
166             items = upload.parseRequest(request);
167         }
168         catch (FileUploadException fue) {
169             throw new FCKException(fue);
170         }
171 
172         Map<String, Object> fields = new HashMap<String, Object>();
173 
174         for (FileItem item : items) {
175             if (item.isFormField()) {
176                 fields.put(item.getFieldName(), item.getString());
177             }
178             else {
179                 fields.put(item.getFieldName(), item);
180             }
181         }
182 
183         DiskFileItem fileItem = (DiskFileItem)fields.get("NewFile");
184 
185         String fileName = StringUtil.replace(fileItem.getName(), "\\", "/");
186         String[] fileNameArray = StringUtil.split(fileName, "/");
187         fileName = fileNameArray[fileNameArray.length - 1];
188 
189         String extension = _getExtension(fileName);
190 
191         String returnValue = null;
192 
193         try {
194             returnValue = fileUpload(
195                 argument, fileName, fileItem.getStoreLocation(), extension);
196         }
197         catch (FCKException fcke) {
198             Throwable cause = fcke.getCause();
199 
200             returnValue = "203";
201 
202             if (cause != null) {
203                 String causeString = GetterUtil.getString(cause.toString());
204 
205                 if ((causeString.indexOf("NoSuchFolderException") != -1) ||
206                     (causeString.indexOf("NoSuchGroupException") != -1)) {
207 
208                     returnValue = "204";
209                 }
210                 else if (causeString.indexOf("ImageNameException") != -1) {
211                     returnValue = "205";
212                 }
213                 else if (causeString.indexOf("FileNameException") != -1) {
214                     returnValue = "206";
215                 }
216                 else if (causeString.indexOf("PrincipalException") != -1) {
217                     returnValue = "207";
218                 }
219                 else {
220                     throw fcke;
221                 }
222             }
223 
224             _writeUploadResponse(returnValue, response);
225         }
226 
227         _writeUploadResponse(returnValue, response);
228     }
229 
230     protected abstract String createFolder(CommandArgument argument);
231 
232     protected abstract String fileUpload(
233         CommandArgument argument, String fileName, File file, String extension);
234 
235     protected abstract void getFolders(
236         CommandArgument argument, Document doc, Node root);
237 
238     protected abstract void getFoldersAndFiles(
239         CommandArgument argument, Document doc, Node root);
240 
241     protected void getRootFolders(
242             CommandArgument argument, Document doc, Element foldersEl)
243         throws Exception {
244 
245         LinkedHashMap<String, Object> groupParams =
246             new LinkedHashMap<String, Object>();
247 
248         groupParams.put("usersGroups", new Long(argument.getUserId()));
249 
250         List<Group> groups = GroupLocalServiceUtil.search(
251             argument.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS,
252             QueryUtil.ALL_POS);
253 
254         List<Organization> userOrgs =
255             OrganizationLocalServiceUtil.getUserOrganizations(
256                 argument.getUserId(), true);
257 
258         for (Organization organization : userOrgs) {
259             groups.add(0, organization.getGroup());
260         }
261 
262         if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED ||
263             PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
264 
265             Group userGroup = GroupLocalServiceUtil.getUserGroup(
266                 argument.getCompanyId(), argument.getUserId());
267 
268             groups.add(0, userGroup);
269         }
270 
271         for (Group group : groups) {
272             Element folderEl = doc.createElement("Folder");
273 
274             foldersEl.appendChild(folderEl);
275 
276             folderEl.setAttribute(
277                 "name",
278                 group.getGroupId() + " - " + group.getDescriptiveName());
279         }
280     }
281 
282     protected String getPath(CommandArgument argument) {
283         return StringPool.BLANK;
284     }
285 
286     protected String getSize() {
287         return getSize(0);
288     }
289 
290     protected String getSize(int size) {
291         return String.valueOf(Math.ceil(size / 1000));
292     }
293 
294     private Document _createDocument() {
295         try {
296             Document doc = null;
297 
298             DocumentBuilderFactory factory =
299                 DocumentBuilderFactory.newInstance();
300 
301             DocumentBuilder builder = null;
302 
303             builder = factory.newDocumentBuilder();
304 
305             doc = builder.newDocument();
306 
307             return doc;
308         }
309         catch (ParserConfigurationException pce) {
310             throw new FCKException(pce);
311         }
312     }
313 
314     private Node _createRoot(
315         Document doc, String commandStr, String typeStr, String currentPath,
316         String currentUrl) {
317 
318         Element root = doc.createElement("Connector");
319 
320         doc.appendChild(root);
321 
322         root.setAttribute("command", commandStr);
323         root.setAttribute("resourceType", typeStr);
324 
325         Element el = doc.createElement("CurrentFolder");
326 
327         root.appendChild(el);
328 
329         el.setAttribute("path", currentPath);
330         el.setAttribute("url", currentUrl);
331 
332         return root;
333     }
334 
335     private String _getExtension(String fileName) {
336         return fileName.substring(fileName.lastIndexOf(".") + 1);
337     }
338 
339     private void _writeDocument(Document doc, HttpServletResponse response) {
340         try {
341             doc.getDocumentElement().normalize();
342 
343             TransformerFactory transformerFactory =
344                 TransformerFactory.newInstance();
345 
346             Transformer transformer = transformerFactory.newTransformer();
347 
348             DOMSource source = new DOMSource(doc);
349 
350             if (_log.isDebugEnabled()) {
351                 StreamResult result = new StreamResult(System.out);
352 
353                 transformer.transform(source, result);
354             }
355 
356             response.setContentType("text/xml; charset=UTF-8");
357             response.setHeader("Cache-Control", "no-cache");
358 
359             PrintWriter out = response.getWriter();
360 
361             StreamResult result = new StreamResult(out);
362 
363             transformer.transform(source, result);
364 
365             out.flush();
366             out.close();
367         }
368         catch (Exception e) {
369             throw new FCKException(e);
370         }
371     }
372 
373     private void _writeUploadResponse(
374         String returnValue, HttpServletResponse response) {
375 
376         try {
377             StringBuilder sb = new StringBuilder();
378 
379             String newName = StringPool.BLANK;
380 
381             sb.append("<script type=\"text/javascript\">");
382             sb.append("window.parent.frames['frmUpload'].OnUploadCompleted(");
383             sb.append(returnValue);
384             sb.append(",'");
385             sb.append(newName);
386             sb.append("');");
387             sb.append("</script>");
388 
389             response.setContentType("text/html; charset=UTF-8");
390             response.setHeader("Cache-Control", "no-cache");
391 
392             PrintWriter out = null;
393 
394             out = response.getWriter();
395 
396             out.print(sb.toString());
397 
398             out.flush();
399             out.close();
400         }
401         catch (Exception e) {
402             throw new FCKException(e);
403         }
404     }
405 
406     private static Log _log = LogFactoryUtil.getLog(BaseCommandReceiver.class);
407 
408 }