1   /**
2    * Copyright (c) 2000-2008 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.util.GetterUtil;
29  import com.liferay.portal.kernel.util.StringMaker;
30  import com.liferay.portal.kernel.util.StringPool;
31  import com.liferay.portal.kernel.util.StringUtil;
32  import com.liferay.portal.model.Group;
33  import com.liferay.portal.model.Organization;
34  import com.liferay.portal.model.User;
35  import com.liferay.portal.service.GroupLocalServiceUtil;
36  import com.liferay.portal.service.UserLocalServiceUtil;
37  import com.liferay.util.dao.hibernate.QueryUtil;
38  import com.liferay.util.servlet.UploadServletRequest;
39  import com.liferay.util.servlet.fileupload.LiferayFileItemFactory;
40  
41  import java.io.File;
42  import java.io.PrintWriter;
43  
44  import java.util.HashMap;
45  import java.util.LinkedHashMap;
46  import java.util.List;
47  import java.util.Map;
48  
49  import javax.servlet.http.HttpServletRequest;
50  import javax.servlet.http.HttpServletResponse;
51  
52  import javax.xml.parsers.DocumentBuilder;
53  import javax.xml.parsers.DocumentBuilderFactory;
54  import javax.xml.parsers.ParserConfigurationException;
55  import javax.xml.transform.Transformer;
56  import javax.xml.transform.TransformerFactory;
57  import javax.xml.transform.dom.DOMSource;
58  import javax.xml.transform.stream.StreamResult;
59  
60  import org.apache.commons.fileupload.FileItem;
61  import org.apache.commons.fileupload.FileUploadException;
62  import org.apache.commons.fileupload.disk.DiskFileItem;
63  import org.apache.commons.fileupload.servlet.ServletFileUpload;
64  import org.apache.commons.logging.Log;
65  import org.apache.commons.logging.LogFactory;
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 arg, HttpServletRequest req, HttpServletResponse res) {
81  
82          Document doc = _createDocument();
83  
84          Node root = _createRoot(
85              doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
86              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(arg);
96          }
97          catch (FCKException fcke) {
98              returnValue = "110";
99          }
100 
101         errorEl.setAttribute("number", returnValue);
102 
103         _writeDocument(doc, res);
104     }
105 
106     public void getFolders(
107         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
108 
109         Document doc = _createDocument();
110 
111         Node root = _createRoot(
112             doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
113             getPath(arg));
114 
115         getFolders(arg, doc, root);
116 
117         _writeDocument(doc, res);
118     }
119 
120     public void getFoldersAndFiles(
121         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
122 
123         Document doc = _createDocument();
124 
125         Node root = _createRoot(
126             doc, arg.getCommand(), arg.getType(), arg.getCurrentFolder(),
127             getPath(arg));
128 
129         getFoldersAndFiles(arg, doc, root);
130 
131         _writeDocument(doc, res);
132     }
133 
134     public void fileUpload(
135         CommandArgument arg, HttpServletRequest req, HttpServletResponse res) {
136 
137         ServletFileUpload upload = new ServletFileUpload(
138             new LiferayFileItemFactory(UploadServletRequest.DEFAULT_TEMP_DIR));
139 
140         List<FileItem> items = null;
141 
142         try {
143             items = upload.parseRequest(req);
144         }
145         catch (FileUploadException fue) {
146             throw new FCKException(fue);
147         }
148 
149         Map<String, Object> fields = new HashMap<String, Object>();
150 
151         for (FileItem item : items) {
152             if (item.isFormField()) {
153                 fields.put(item.getFieldName(), item.getString());
154             }
155             else {
156                 fields.put(item.getFieldName(), item);
157             }
158         }
159 
160         DiskFileItem fileItem = (DiskFileItem)fields.get("NewFile");
161 
162         String fileName = StringUtil.replace(fileItem.getName(), "\\", "/");
163         String[] fileNameArray = StringUtil.split(fileName, "/");
164         fileName = fileNameArray[fileNameArray.length - 1];
165 
166         String extension = _getExtension(fileName);
167 
168         String returnValue = null;
169 
170         try {
171             returnValue = fileUpload(
172                 arg, fileName, fileItem.getStoreLocation(), extension);
173         }
174         catch (FCKException fcke) {
175             Throwable cause = fcke.getCause();
176 
177             returnValue = "203";
178 
179             if (cause != null) {
180                 String causeString = GetterUtil.getString(cause.toString());
181 
182                 if ((causeString.indexOf("NoSuchFolderException") != -1) ||
183                     (causeString.indexOf("NoSuchGroupException") != -1)) {
184 
185                     returnValue = "204";
186                 }
187                 else if (causeString.indexOf("ImageNameException") != -1) {
188                     returnValue = "205";
189                 }
190                 else if (causeString.indexOf("FileNameException") != -1) {
191                     returnValue = "206";
192                 }
193                 else if (causeString.indexOf("PrincipalException") != -1) {
194                     returnValue = "207";
195                 }
196                 else {
197                     throw fcke;
198                 }
199             }
200 
201             _writeUploadResponse(returnValue, res);
202         }
203 
204         _writeUploadResponse(returnValue, res);
205     }
206 
207     protected abstract String createFolder(CommandArgument arg);
208 
209     protected abstract String fileUpload(
210         CommandArgument arg, String fileName, File file, String extension);
211 
212     protected abstract void getFolders(
213         CommandArgument arg, Document doc, Node root);
214 
215     protected abstract void getFoldersAndFiles(
216         CommandArgument arg, Document doc, Node root);
217 
218     protected void getRootFolders(
219             CommandArgument arg, Document doc, Element foldersEl)
220         throws Exception {
221 
222         LinkedHashMap<String, Object> groupParams =
223             new LinkedHashMap<String, Object>();
224 
225         groupParams.put("usersGroups", new Long(arg.getUserId()));
226 
227         List<Group> groups = GroupLocalServiceUtil.search(
228             arg.getCompanyId(), null, null, groupParams, QueryUtil.ALL_POS,
229             QueryUtil.ALL_POS);
230 
231         User user = UserLocalServiceUtil.getUserById(arg.getUserId());
232 
233         List<Organization> userOrgs = user.getOrganizations();
234 
235         for (Organization organization : userOrgs) {
236             groups.add(0, organization.getGroup());
237         }
238 
239         if (user.isLayoutsRequired()) {
240             Group userGroup = user.getGroup();
241 
242             groups.add(0, userGroup);
243         }
244 
245         for (Group group : groups) {
246             Element folderEl = doc.createElement("Folder");
247 
248             foldersEl.appendChild(folderEl);
249 
250             folderEl.setAttribute(
251                 "name",
252                 group.getGroupId() + " - " + group.getDescriptiveName());
253         }
254     }
255 
256     protected String getPath(CommandArgument arg) {
257         return StringPool.BLANK;
258     }
259 
260     protected String getSize() {
261         return getSize(0);
262     }
263 
264     protected String getSize(int size) {
265         return String.valueOf(Math.ceil(size / 1000));
266     }
267 
268     private Document _createDocument() {
269         try {
270             Document doc = null;
271 
272             DocumentBuilderFactory factory =
273                 DocumentBuilderFactory.newInstance();
274 
275             DocumentBuilder builder = null;
276 
277             builder = factory.newDocumentBuilder();
278 
279             doc = builder.newDocument();
280 
281             return doc;
282         }
283         catch (ParserConfigurationException pce) {
284             throw new FCKException(pce);
285         }
286     }
287 
288     private Node _createRoot(
289         Document doc, String commandStr, String typeStr, String currentPath,
290         String currentUrl) {
291 
292         Element root = doc.createElement("Connector");
293 
294         doc.appendChild(root);
295 
296         root.setAttribute("command", commandStr);
297         root.setAttribute("resourceType", typeStr);
298 
299         Element el = doc.createElement("CurrentFolder");
300 
301         root.appendChild(el);
302 
303         el.setAttribute("path", currentPath);
304         el.setAttribute("url", currentUrl);
305 
306         return root;
307     }
308 
309     private String _getExtension(String fileName) {
310         return fileName.substring(fileName.lastIndexOf(".") + 1);
311     }
312 
313     private void _writeDocument(Document doc, HttpServletResponse res) {
314         try {
315             doc.getDocumentElement().normalize();
316 
317             TransformerFactory transformerFactory =
318                 TransformerFactory.newInstance();
319 
320             Transformer transformer = transformerFactory.newTransformer();
321 
322             DOMSource source = new DOMSource(doc);
323 
324             if (_log.isDebugEnabled()) {
325                 StreamResult result = new StreamResult(System.out);
326 
327                 transformer.transform(source, result);
328             }
329 
330             res.setContentType("text/xml; charset=UTF-8");
331             res.setHeader("Cache-Control", "no-cache");
332 
333             PrintWriter out = res.getWriter();
334 
335             StreamResult result = new StreamResult(out);
336 
337             transformer.transform(source, result);
338 
339             out.flush();
340             out.close();
341         }
342         catch (Exception e) {
343             throw new FCKException(e);
344         }
345     }
346 
347     private void _writeUploadResponse(
348         String returnValue, HttpServletResponse res) {
349 
350         try {
351             StringMaker sm = new StringMaker();
352 
353             String newName = StringPool.BLANK;
354 
355             sm.append("<script type=\"text/javascript\">");
356             sm.append("window.parent.frames['frmUpload'].OnUploadCompleted(");
357             sm.append(returnValue);
358             sm.append(",'");
359             sm.append(newName);
360             sm.append("');");
361             sm.append("</script>");
362 
363             res.setContentType("text/html; charset=UTF-8");
364             res.setHeader("Cache-Control", "no-cache");
365 
366             PrintWriter out = null;
367 
368             out = res.getWriter();
369 
370             out.print(sm.toString());
371 
372             out.flush();
373             out.close();
374         }
375         catch (Exception e) {
376             throw new FCKException(e);
377         }
378     }
379 
380     private static Log _log = LogFactory.getLog(BaseCommandReceiver.class);
381 
382 }