001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * This library is free software; you can redistribute it and/or modify it under
005     * the terms of the GNU Lesser General Public License as published by the Free
006     * Software Foundation; either version 2.1 of the License, or (at your option)
007     * any later version.
008     *
009     * This library is distributed in the hope that it will be useful, but WITHOUT
010     * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
011     * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
012     * details.
013     */
014    
015    package com.liferay.portal.editor.fckeditor.receiver.impl;
016    
017    import com.liferay.portal.editor.fckeditor.command.CommandArgument;
018    import com.liferay.portal.editor.fckeditor.exception.FCKException;
019    import com.liferay.portal.editor.fckeditor.receiver.CommandReceiver;
020    import com.liferay.portal.kernel.dao.orm.QueryUtil;
021    import com.liferay.portal.kernel.io.ByteArrayFileInputStream;
022    import com.liferay.portal.kernel.log.Log;
023    import com.liferay.portal.kernel.log.LogFactoryUtil;
024    import com.liferay.portal.kernel.util.CharPool;
025    import com.liferay.portal.kernel.util.ContentTypes;
026    import com.liferay.portal.kernel.util.GetterUtil;
027    import com.liferay.portal.kernel.util.HtmlUtil;
028    import com.liferay.portal.kernel.util.MimeTypesUtil;
029    import com.liferay.portal.kernel.util.ParamUtil;
030    import com.liferay.portal.kernel.util.PropsKeys;
031    import com.liferay.portal.kernel.util.StreamUtil;
032    import com.liferay.portal.kernel.util.StringBundler;
033    import com.liferay.portal.kernel.util.StringPool;
034    import com.liferay.portal.kernel.util.StringUtil;
035    import com.liferay.portal.kernel.util.UniqueList;
036    import com.liferay.portal.kernel.util.Validator;
037    import com.liferay.portal.model.Group;
038    import com.liferay.portal.model.Organization;
039    import com.liferay.portal.security.xml.SecureXMLFactoryProviderUtil;
040    import com.liferay.portal.service.GroupLocalServiceUtil;
041    import com.liferay.portal.service.OrganizationLocalServiceUtil;
042    import com.liferay.portal.theme.ThemeDisplay;
043    import com.liferay.portal.upload.LiferayFileItem;
044    import com.liferay.portal.upload.LiferayFileItemFactory;
045    import com.liferay.portal.upload.LiferayFileUpload;
046    import com.liferay.portal.upload.LiferayServletRequest;
047    import com.liferay.portal.upload.UploadServletRequestImpl;
048    import com.liferay.portal.util.PrefsPropsUtil;
049    import com.liferay.portal.util.PropsValues;
050    
051    import java.io.InputStream;
052    import java.io.PrintWriter;
053    
054    import java.util.HashMap;
055    import java.util.LinkedHashMap;
056    import java.util.List;
057    import java.util.Map;
058    
059    import javax.servlet.http.HttpServletRequest;
060    import javax.servlet.http.HttpServletResponse;
061    
062    import javax.xml.parsers.DocumentBuilder;
063    import javax.xml.parsers.DocumentBuilderFactory;
064    import javax.xml.parsers.ParserConfigurationException;
065    import javax.xml.transform.Transformer;
066    import javax.xml.transform.TransformerFactory;
067    import javax.xml.transform.dom.DOMSource;
068    import javax.xml.transform.stream.StreamResult;
069    
070    import org.apache.commons.fileupload.FileItem;
071    import org.apache.commons.fileupload.disk.DiskFileItem;
072    import org.apache.commons.fileupload.servlet.ServletFileUpload;
073    
074    import org.w3c.dom.Document;
075    import org.w3c.dom.Element;
076    import org.w3c.dom.Node;
077    
078    /**
079     * @author Ivica Cardic
080     * @author Raymond Aug??
081     */
082    public abstract class BaseCommandReceiver implements CommandReceiver {
083    
084            @Override
085            public void createFolder(
086                    CommandArgument commandArgument, HttpServletRequest request,
087                    HttpServletResponse response) {
088    
089                    Document document = _createDocument();
090    
091                    Node rootNode = _createRoot(
092                            document, commandArgument.getCommand(), commandArgument.getType(),
093                            commandArgument.getCurrentFolder(), StringPool.BLANK);
094    
095                    Element errorElement = document.createElement("Error");
096    
097                    rootNode.appendChild(errorElement);
098    
099                    String returnValue = "0";
100    
101                    try {
102                            returnValue = createFolder(commandArgument);
103                    }
104                    catch (FCKException fcke) {
105                            Throwable cause = fcke.getCause();
106    
107                            returnValue = "110";
108    
109                            if (cause != null) {
110                                    String causeString = GetterUtil.getString(cause.toString());
111    
112                                    if (causeString.contains("DuplicateFolderNameException")) {
113                                            returnValue = "101";
114                                    }
115                                    else if (causeString.contains("FolderNameException")) {
116                                            returnValue = "102";
117                                    }
118                                    else if (causeString.contains("NoSuchGroupException") ||
119                                                     causeString.contains("PrincipalException")) {
120    
121                                            returnValue = "103";
122                                    }
123                                    else {
124                                            throw fcke;
125                                    }
126                            }
127                    }
128    
129                    errorElement.setAttribute("number", returnValue);
130    
131                    _writeDocument(document, response);
132            }
133    
134            @Override
135            public void fileUpload(
136                    CommandArgument commandArgument, HttpServletRequest request,
137                    HttpServletResponse response) {
138    
139                    InputStream inputStream = null;
140    
141                    String returnValue = null;
142    
143                    try {
144                            ServletFileUpload servletFileUpload = new LiferayFileUpload(
145                                    new LiferayFileItemFactory(
146                                            UploadServletRequestImpl.getTempDir()), request);
147    
148                            servletFileUpload.setFileSizeMax(
149                                    PrefsPropsUtil.getLong(
150                                            PropsKeys.UPLOAD_SERVLET_REQUEST_IMPL_MAX_SIZE));
151    
152                            LiferayServletRequest liferayServletRequest =
153                                    new LiferayServletRequest(request);
154    
155                            List<FileItem> fileItems = servletFileUpload.parseRequest(
156                                    liferayServletRequest);
157    
158                            Map<String, Object> fields = new HashMap<String, Object>();
159    
160                            for (FileItem fileItem : fileItems) {
161                                    if (fileItem.isFormField()) {
162                                            fields.put(fileItem.getFieldName(), fileItem.getString());
163                                    }
164                                    else {
165                                            fields.put(fileItem.getFieldName(), fileItem);
166                                    }
167                            }
168    
169                            DiskFileItem diskFileItem = (DiskFileItem)fields.get("NewFile");
170    
171                            String fileName = StringUtil.replace(
172                                    diskFileItem.getName(), CharPool.BACK_SLASH, CharPool.SLASH);
173                            String[] fileNameArray = StringUtil.split(fileName, '/');
174                            fileName = fileNameArray[fileNameArray.length - 1];
175    
176                            String contentType = diskFileItem.getContentType();
177    
178                            if (Validator.isNull(contentType) ||
179                                    contentType.equals(ContentTypes.APPLICATION_OCTET_STREAM)) {
180    
181                                    contentType = MimeTypesUtil.getContentType(
182                                            diskFileItem.getStoreLocation());
183                            }
184    
185                            if (diskFileItem.isInMemory()) {
186                                    inputStream = diskFileItem.getInputStream();
187                            }
188                            else {
189                                    inputStream = new ByteArrayFileInputStream(
190                                            diskFileItem.getStoreLocation(),
191                                            LiferayFileItem.THRESHOLD_SIZE);
192                            }
193    
194                            long size = diskFileItem.getSize();
195    
196                            returnValue = fileUpload(
197                                    commandArgument, fileName, inputStream, contentType, size);
198                    }
199                    catch (Exception e) {
200                            FCKException fcke = null;
201    
202                            if (e instanceof FCKException) {
203                                    fcke = (FCKException)e;
204                            }
205                            else {
206                                    fcke = new FCKException(e);
207                            }
208    
209                            Throwable cause = fcke.getCause();
210    
211                            returnValue = "203";
212    
213                            if (cause != null) {
214                                    String causeString = GetterUtil.getString(cause.toString());
215    
216                                    if (causeString.contains("DuplicateFileException")) {
217                                            returnValue = "201";
218                                    }
219                                    else if (causeString.contains("NoSuchFolderException")||
220                                                     causeString.contains("NoSuchGroupException")) {
221    
222                                            returnValue = "204";
223                                    }
224                                    else if (causeString.contains("ImageNameException")) {
225                                            returnValue = "205";
226                                    }
227                                    else if (causeString.contains("FileExtensionException") ||
228                                                     causeString.contains("FileNameException")) {
229    
230                                            returnValue = "206";
231                                    }
232                                    else if (causeString.contains("PrincipalException")) {
233                                            returnValue = "207";
234                                    }
235                                    else if (causeString.contains("FileSizeException") ||
236                                                     causeString.contains("ImageSizeException") ||
237                                                     causeString.contains("SizeLimitExceededException")) {
238    
239                                            returnValue = "208";
240                                    }
241                                    else if (causeString.contains("SystemException")) {
242                                            returnValue = "209";
243                                    }
244                                    else if (causeString.contains("AssetCategoryException")) {
245                                            returnValue = "212";
246                                    }
247                                    else if (causeString.contains("AntivirusScannerException")) {
248                                            returnValue = "211";
249                                    }
250                                    else {
251                                            throw fcke;
252                                    }
253                            }
254    
255                            _writeUploadResponse(returnValue, response);
256                    }
257                    finally {
258                            StreamUtil.cleanUp(inputStream);
259                    }
260    
261                    _writeUploadResponse(returnValue, response);
262            }
263    
264            @Override
265            public void getFolders(
266                    CommandArgument commandArgument, HttpServletRequest request,
267                    HttpServletResponse response) {
268    
269                    Document document = _createDocument();
270    
271                    Node rootNode = _createRoot(
272                            document, commandArgument.getCommand(), commandArgument.getType(),
273                            commandArgument.getCurrentFolder(), getPath(commandArgument));
274    
275                    getFolders(commandArgument, document, rootNode);
276    
277                    _writeDocument(document, response);
278            }
279    
280            @Override
281            public void getFoldersAndFiles(
282                    CommandArgument commandArgument, HttpServletRequest request,
283                    HttpServletResponse response) {
284    
285                    Document document = _createDocument();
286    
287                    Node rootNode = _createRoot(
288                            document, commandArgument.getCommand(), commandArgument.getType(),
289                            commandArgument.getCurrentFolder(), getPath(commandArgument));
290    
291                    getFoldersAndFiles(commandArgument, document, rootNode);
292    
293                    _writeDocument(document, response);
294            }
295    
296            protected abstract String createFolder(CommandArgument commandArgument);
297    
298            protected abstract String fileUpload(
299                    CommandArgument commandArgument, String fileName,
300                    InputStream inputStream, String contentType, long size);
301    
302            protected abstract void getFolders(
303                    CommandArgument commandArgument, Document document, Node rootNode);
304    
305            protected abstract void getFoldersAndFiles(
306                    CommandArgument commandArgument, Document document, Node rootNode);
307    
308            protected String getPath(CommandArgument commandArgument) {
309                    return StringPool.BLANK;
310            }
311    
312            protected void getRootFolders(
313                            CommandArgument commandArgument, Document document,
314                            Element foldersElement)
315                    throws Exception {
316    
317                    List<Group> groups = new UniqueList<Group>();
318    
319                    LinkedHashMap<String, Object> groupParams =
320                            new LinkedHashMap<String, Object>();
321    
322                    groupParams.put("usersGroups", new Long(commandArgument.getUserId()));
323    
324                    groups.addAll(
325                            GroupLocalServiceUtil.search(
326                                    commandArgument.getCompanyId(), null, null, groupParams,
327                                    QueryUtil.ALL_POS, QueryUtil.ALL_POS));
328    
329                    List<Organization> userOrgs =
330                            OrganizationLocalServiceUtil.getUserOrganizations(
331                                    commandArgument.getUserId());
332    
333                    for (Organization organization : userOrgs) {
334                            groups.add(0, organization.getGroup());
335                    }
336    
337                    if (PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_ENABLED ||
338                            PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_ENABLED) {
339    
340                            Group userGroup = GroupLocalServiceUtil.getUserGroup(
341                                    commandArgument.getCompanyId(), commandArgument.getUserId());
342    
343                            groups.add(0, userGroup);
344                    }
345    
346                    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
347                            commandArgument.getCompanyId());
348    
349                    groups.add(0, companyGroup);
350    
351                    ThemeDisplay themeDisplay = commandArgument.getThemeDisplay();
352    
353                    long doAsGroupId = themeDisplay.getDoAsGroupId();
354    
355                    HttpServletRequest request = commandArgument.getHttpServletRequest();
356    
357                    String portletId = ParamUtil.getString(request, "p_p_id");
358    
359                    for (Group group : groups) {
360                            Element folderElement = document.createElement("Folder");
361    
362                            foldersElement.appendChild(folderElement);
363    
364                            long groupId = group.getGroupId();
365                            String descriptiveName = group.getDescriptiveName();
366    
367                            if (group.hasStagingGroup()) {
368                                    Group stagingGroup = group.getStagingGroup();
369    
370                                    if ((stagingGroup.getGroupId() == doAsGroupId) &&
371                                            group.isStagedPortlet(portletId) &&
372                                            !group.isStagedRemotely() && isStagedData(group)) {
373    
374                                            groupId = stagingGroup.getGroupId();
375                                            descriptiveName = stagingGroup.getDescriptiveName();
376                                    }
377                            }
378    
379                            folderElement.setAttribute(
380                                    "name", groupId + " - " + HtmlUtil.escape(descriptiveName));
381                    }
382            }
383    
384            protected String getSize() {
385                    return getSize(0);
386            }
387    
388            protected String getSize(long size) {
389                    return String.valueOf(Math.ceil(size / 1000));
390            }
391    
392            protected boolean isStagedData(Group group) {
393                    return true;
394            }
395    
396            private Document _createDocument() {
397                    try {
398                            DocumentBuilderFactory documentBuilderFactory =
399                                    SecureXMLFactoryProviderUtil.newDocumentBuilderFactory();
400    
401                            DocumentBuilder documentBuilder =
402                                    documentBuilderFactory.newDocumentBuilder();
403    
404                            return documentBuilder.newDocument();
405                    }
406                    catch (ParserConfigurationException pce) {
407                            throw new FCKException(pce);
408                    }
409            }
410    
411            private Node _createRoot(
412                    Document document, String command, String resourceType, String path,
413                    String url) {
414    
415                    Element rootElement = document.createElement("Connector");
416    
417                    document.appendChild(rootElement);
418    
419                    rootElement.setAttribute("command", command);
420                    rootElement.setAttribute("resourceType", resourceType);
421    
422                    Element currentFolderElement = document.createElement("CurrentFolder");
423    
424                    rootElement.appendChild(currentFolderElement);
425    
426                    currentFolderElement.setAttribute("path", path);
427                    currentFolderElement.setAttribute("url", url);
428    
429                    return rootElement;
430            }
431    
432            private void _writeDocument(
433                    Document document, HttpServletResponse response) {
434    
435                    try {
436                            Element documentElement = document.getDocumentElement();
437    
438                            documentElement.normalize();
439    
440                            TransformerFactory transformerFactory =
441                                    TransformerFactory.newInstance();
442    
443                            Transformer transformer = transformerFactory.newTransformer();
444    
445                            DOMSource domSource = new DOMSource(document);
446    
447                            if (_log.isDebugEnabled()) {
448                                    StreamResult streamResult = new StreamResult(System.out);
449    
450                                    transformer.transform(domSource, streamResult);
451                            }
452    
453                            response.setContentType("text/xml; charset=UTF-8");
454                            response.setHeader("Cache-Control", "no-cache");
455    
456                            PrintWriter printWriter = response.getWriter();
457    
458                            StreamResult streamResult = new StreamResult(printWriter);
459    
460                            transformer.transform(domSource, streamResult);
461    
462                            printWriter.flush();
463                            printWriter.close();
464                    }
465                    catch (Exception e) {
466                            throw new FCKException(e);
467                    }
468            }
469    
470            private void _writeUploadResponse(
471                    String returnValue, HttpServletResponse response) {
472    
473                    try {
474                            StringBundler sb = new StringBundler(7);
475    
476                            String newName = StringPool.BLANK;
477    
478                            sb.append("<script type=\"text/javascript\">");
479                            sb.append("window.parent.frames['frmUpload'].OnUploadCompleted(");
480                            sb.append(returnValue);
481                            sb.append(",'");
482                            sb.append(newName);
483                            sb.append("');");
484                            sb.append("</script>");
485    
486                            response.setContentType("text/html; charset=UTF-8");
487                            response.setHeader("Cache-Control", "no-cache");
488    
489                            PrintWriter printWriter = null;
490    
491                            printWriter = response.getWriter();
492    
493                            printWriter.print(sb.toString());
494    
495                            printWriter.flush();
496                            printWriter.close();
497                    }
498                    catch (Exception e) {
499                            throw new FCKException(e);
500                    }
501            }
502    
503            private static Log _log = LogFactoryUtil.getLog(BaseCommandReceiver.class);
504    
505    }