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.model.User;
37  import com.liferay.portal.service.GroupLocalServiceUtil;
38  import com.liferay.portal.service.UserLocalServiceUtil;
39  import com.liferay.portal.upload.LiferayFileItemFactory;
40  import com.liferay.portal.upload.UploadServletRequestImpl;
41  import com.liferay.portal.util.PropsValues;
42  
43  import java.io.File;
44  import java.io.PrintWriter;
45  
46  import java.util.HashMap;
47  import java.util.LinkedHashMap;
48  import java.util.List;
49  import java.util.Map;
50  
51  import javax.servlet.http.HttpServletRequest;
52  import javax.servlet.http.HttpServletResponse;
53  
54  import javax.xml.parsers.DocumentBuilder;
55  import javax.xml.parsers.DocumentBuilderFactory;
56  import javax.xml.parsers.ParserConfigurationException;
57  import javax.xml.transform.Transformer;
58  import javax.xml.transform.TransformerFactory;
59  import javax.xml.transform.dom.DOMSource;
60  import javax.xml.transform.stream.StreamResult;
61  
62  import org.apache.commons.fileupload.FileItem;
63  import org.apache.commons.fileupload.FileUploadException;
64  import org.apache.commons.fileupload.disk.DiskFileItem;
65  import org.apache.commons.fileupload.servlet.ServletFileUpload;
66  
67  import org.w3c.dom.Document;
68  import org.w3c.dom.Element;
69  import org.w3c.dom.Node;
70  
71  /**
72   * <a href="BaseCommandReceiver.java.html"><b><i>View Source</i></b></a>
73   *
74   * @author Ivica Cardic
75   *
76   */
77  public abstract class BaseCommandReceiver implements CommandReceiver {
78  
79      public void createFolder(
80          CommandArgument argument, HttpServletRequest request,
81          HttpServletResponse response) {
82  
83          Document doc = _createDocument();
84  
85          Node root = _createRoot(
86              doc, argument.getCommand(), argument.getType(),
87              argument.getCurrentFolder(), StringPool.BLANK);
88  
89          Element errorEl = doc.createElement("Error");
90  
91          root.appendChild(errorEl);
92  
93          String returnValue = "0";
94  
95          try {
96              returnValue = createFolder(argument);
97          }
98          catch (FCKException fcke) {
99              Throwable cause = fcke.getCause();
100 
101             returnValue = "110";
102 
103             if (cause != null) {
104                 String causeString = GetterUtil.getString(cause.toString());
105 
106                 if (causeString.indexOf("DuplicateFolderNameException") != -1) {
107                     returnValue = "101";
108                 }
109                 else if (causeString.indexOf("FolderNameException") != -1) {
110                     returnValue = "102";
111                 }
112                 else if (causeString.indexOf("NoSuchGroupException") != -1) {
113                     returnValue = "103";
114                 }
115                 else {
116                     throw fcke;
117                 }
118             }
119         }
120 
121         errorEl.setAttribute("number", returnValue);
122 
123         _writeDocument(doc, response);
124     }
125 
126     public void getFolders(
127         CommandArgument argument, HttpServletRequest request,
128         HttpServletResponse response) {
129 
130         Document doc = _createDocument();
131 
132         Node root = _createRoot(
133             doc, argument.getCommand(), argument.getType(),
134             argument.getCurrentFolder(), getPath(argument));
135 
136         getFolders(argument, doc, root);
137 
138         _writeDocument(doc, response);
139     }
140 
141     public void getFoldersAndFiles(
142         CommandArgument argument, HttpServletRequest request,
143         HttpServletResponse response) {
144 
145         Document doc = _createDocument();
146 
147         Node root = _createRoot(
148             doc, argument.getCommand(), argument.getType(),
149             argument.getCurrentFolder(), getPath(argument));
150 
151         getFoldersAndFiles(argument, doc, root);
152 
153         _writeDocument(doc, response);
154     }
155 
156     public void fileUpload(
157         CommandArgument argument, HttpServletRequest request,
158         HttpServletResponse response) {
159 
160         ServletFileUpload upload = new ServletFileUpload(
161             new LiferayFileItemFactory(
162                 UploadServletRequestImpl.DEFAULT_TEMP_DIR));
163 
164         List<FileItem> items = null;
165 
166         try {
167             items = upload.parseRequest(request);
168         }
169         catch (FileUploadException fue) {
170             throw new FCKException(fue);
171         }
172 
173         Map<String, Object> fields = new HashMap<String, Object>();
174 
175         for (FileItem item : items) {
176             if (item.isFormField()) {
177                 fields.put(item.getFieldName(), item.getString());
178             }
179             else {
180                 fields.put(item.getFieldName(), item);
181             }
182         }
183 
184         DiskFileItem fileItem = (DiskFileItem)fields.get("NewFile");
185 
186         String fileName = StringUtil.replace(fileItem.getName(), "\\", "/");
187         String[] fileNameArray = StringUtil.split(fileName, "/");
188         fileName = fileNameArray[fileNameArray.length - 1];
189 
190         String extension = _getExtension(fileName);
191 
192         String returnValue = null;
193 
194         try {
195             returnValue = fileUpload(
196                 argument, fileName, fileItem.getStoreLocation(), extension);
197         }
198         catch (FCKException fcke) {
199             Throwable cause = fcke.getCause();
200 
201             returnValue = "203";
202 
203             if (cause != null) {
204                 String causeString = GetterUtil.getString(cause.toString());
205 
206                 if ((causeString.indexOf("NoSuchFolderException") != -1) ||
207                     (causeString.indexOf("NoSuchGroupException") != -1)) {
208 
209                     returnValue = "204";
210                 }
211                 else if (causeString.indexOf("ImageNameException") != -1) {
212                     returnValue = "205";
213                 }
214                 else if (causeString.indexOf("FileNameException") != -1) {
215                     returnValue = "206";
216                 }
217                 else if (causeString.indexOf("PrincipalException") != -1) {
218                     returnValue = "207";
219                 }
220                 else {
221                     throw fcke;
222                 }
223             }
224 
225             _writeUploadResponse(returnValue, response);
226         }
227 
228         _writeUploadResponse(returnValue, response);
229     }
230 
231     protected abstract String createFolder(CommandArgument argument);
232 
233     protected abstract String fileUpload(
234         CommandArgument argument, String fileName, File file, String extension);
235 
236     protected abstract void getFolders(
237         CommandArgument argument, Document doc, Node root);
238 
239     protected abstract void getFoldersAndFiles(
240         CommandArgument argument, Document doc, Node root);
241 
242     protected void getRootFolders(
243             CommandArgument argument, Document doc, Element foldersEl)
244         throws Exception {
245 
246         LinkedHashMap<String, Object> groupParams =
247             new LinkedHashMap<String, Object>();
248 
249         groupParams.put("usersGroups", new Long(argument.getUserId()));
250 
251         List<Group> groups = GroupLocalServiceUtil.search(
252             argument.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS,
253             QueryUtil.ALL_POS);
254 
255         User user = UserLocalServiceUtil.getUserById(argument.getUserId());
256 
257         List<Organization> userOrgs = user.getOrganizations();
258 
259         for (Organization organization : userOrgs) {
260             groups.add(0, organization.getGroup());
261         }
262 
263         if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED ||
264             PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
265 
266             Group userGroup = user.getGroup();
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 }