001    /**
002     * Copyright (c) 2000-2011 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.portlet.documentlibrary.util;
016    
017    import com.liferay.portal.kernel.configuration.Filter;
018    import com.liferay.portal.kernel.exception.PortalException;
019    import com.liferay.portal.kernel.exception.SystemException;
020    import com.liferay.portal.kernel.log.Log;
021    import com.liferay.portal.kernel.log.LogFactoryUtil;
022    import com.liferay.portal.kernel.portlet.LiferayPortletResponse;
023    import com.liferay.portal.kernel.portlet.LiferayWindowState;
024    import com.liferay.portal.kernel.repository.model.FileEntry;
025    import com.liferay.portal.kernel.repository.model.Folder;
026    import com.liferay.portal.kernel.util.GetterUtil;
027    import com.liferay.portal.kernel.util.OrderByComparator;
028    import com.liferay.portal.kernel.util.ParamUtil;
029    import com.liferay.portal.kernel.util.PrefsParamUtil;
030    import com.liferay.portal.kernel.util.PrefsPropsUtil;
031    import com.liferay.portal.kernel.util.PropsKeys;
032    import com.liferay.portal.kernel.util.PropsUtil;
033    import com.liferay.portal.kernel.util.SetUtil;
034    import com.liferay.portal.kernel.util.StringBundler;
035    import com.liferay.portal.kernel.util.StringPool;
036    import com.liferay.portal.kernel.util.StringUtil;
037    import com.liferay.portal.kernel.util.Validator;
038    import com.liferay.portal.kernel.util.WebKeys;
039    import com.liferay.portal.model.Group;
040    import com.liferay.portal.service.GroupLocalServiceUtil;
041    import com.liferay.portal.theme.ThemeDisplay;
042    import com.liferay.portal.util.PortalUtil;
043    import com.liferay.portlet.PortletPreferencesFactoryUtil;
044    import com.liferay.portlet.documentlibrary.model.DLFileShortcut;
045    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
046    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
047    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelCreateDateComparator;
048    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelModifiedDateComparator;
049    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelNameComparator;
050    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelReadCountComparator;
051    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelSizeComparator;
052    
053    import java.util.Arrays;
054    import java.util.Collections;
055    import java.util.HashMap;
056    import java.util.HashSet;
057    import java.util.List;
058    import java.util.Map;
059    import java.util.Set;
060    import java.util.TreeSet;
061    
062    import javax.portlet.PortletPreferences;
063    import javax.portlet.PortletRequest;
064    import javax.portlet.PortletURL;
065    import javax.portlet.RenderResponse;
066    
067    import javax.servlet.http.HttpServletRequest;
068    
069    /**
070     * @author Brian Wing Shun Chan
071     * @author Julio Camarero
072     */
073    public class DLUtil {
074    
075            public static void addPortletBreadcrumbEntries(
076                            DLFileShortcut dlFileShortcut, HttpServletRequest request,
077                            RenderResponse renderResponse, boolean showGlobally)
078                    throws Exception {
079    
080                    Folder folder = dlFileShortcut.getFolder();
081    
082                    if (folder.getFolderId() !=
083                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
084    
085                            addPortletBreadcrumbEntries(
086                                    folder, request, renderResponse, showGlobally);
087                    }
088    
089                    PortletURL portletURL = renderResponse.createRenderURL();
090    
091                    portletURL.setParameter(
092                            "struts_action", "/document_library/view_file_entry");
093                    portletURL.setParameter(
094                            "fileEntryId",
095                            String.valueOf(dlFileShortcut.getToFileEntryId()));
096    
097                    PortalUtil.addPortletBreadcrumbEntry(
098                            request, dlFileShortcut.getToTitle(), portletURL.toString());
099            }
100    
101            public static void addPortletBreadcrumbEntries(
102                            FileEntry fileEntry, HttpServletRequest request,
103                            RenderResponse renderResponse, boolean showGlobally)
104                    throws Exception {
105    
106                    Folder folder = fileEntry.getFolder();
107    
108                    if (folder.getFolderId() !=
109                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
110    
111                            addPortletBreadcrumbEntries(
112                                    folder, request, renderResponse, showGlobally);
113                    }
114    
115                    PortletURL portletURL = renderResponse.createRenderURL();
116    
117                    portletURL.setParameter(
118                            "struts_action", "/document_library/view_file_entry");
119                    portletURL.setParameter(
120                            "fileEntryId", String.valueOf(fileEntry.getFileEntryId()));
121    
122                    PortalUtil.addPortletBreadcrumbEntry(
123                            request, fileEntry.getTitle(), portletURL.toString());
124            }
125    
126            public static void addPortletBreadcrumbEntries(
127                            Folder folder, HttpServletRequest request,
128                            LiferayPortletResponse liferayPortletResponse)
129                    throws Exception {
130    
131                    ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
132                            WebKeys.THEME_DISPLAY);
133    
134                    PortletURL portletURL = liferayPortletResponse.createRenderURL();
135    
136                    portletURL.setParameter("struts_action", "/document_library/view");
137                    portletURL.setParameter("viewEntries", Boolean.TRUE.toString());
138                    portletURL.setParameter("viewFolders", Boolean.TRUE.toString());
139    
140                    Map<String, Object> data = new HashMap<String, Object>();
141    
142                    data.put("folder-id", _getDefaultFolderId(request));
143    
144                    PortalUtil.addPortletBreadcrumbEntry(
145                            request, themeDisplay.translate("home"), portletURL.toString(),
146                            data);
147    
148                    addPortletBreadcrumbEntries(folder, request, portletURL, false);
149            }
150    
151            public static void addPortletBreadcrumbEntries(
152                            Folder folder, HttpServletRequest request,
153                            PortletURL portletURL, boolean showGlobally)
154                    throws Exception {
155    
156                    long defaultFolderId = _getDefaultFolderId(request);
157    
158                    List<Folder> ancestorFolders = Collections.emptyList();
159    
160                    if ((folder != null) && (folder.getFolderId() != defaultFolderId)) {
161                            ancestorFolders = folder.getAncestors();
162    
163                            int indexOfRootFolder = -1;
164    
165                            for (int i = 0; i < ancestorFolders.size(); i++) {
166                                    Folder ancestorFolder = ancestorFolders.get(i);
167    
168                                    if (defaultFolderId == ancestorFolder.getFolderId()) {
169                                            indexOfRootFolder = i;
170                                    }
171                            }
172    
173                            if (indexOfRootFolder > -1) {
174                                    ancestorFolders = ancestorFolders.subList(0, indexOfRootFolder);
175                            }
176                    }
177    
178                    Collections.reverse(ancestorFolders);
179    
180                    for (Folder ancestorFolder : ancestorFolders) {
181                            portletURL.setParameter(
182                                    "folderId", String.valueOf(ancestorFolder.getFolderId()));
183    
184                            Map<String, Object> data = new HashMap<String, Object>();
185    
186                            data.put("folder-id", ancestorFolder.getFolderId());
187                            data.put("show-globally", String.valueOf(showGlobally));
188    
189                            PortalUtil.addPortletBreadcrumbEntry(
190                                    request, ancestorFolder.getName(), portletURL.toString(), data);
191                    }
192    
193                    long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
194    
195                    if (folder != null) {
196                            folderId = folder.getFolderId();
197                    }
198    
199                    portletURL.setParameter("folderId", String.valueOf(folderId));
200    
201                    if ((folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) &&
202                            (folderId != defaultFolderId)) {
203    
204                            Map<String, Object> data = new HashMap<String, Object>();
205    
206                            data.put("folder-id", folderId);
207                            data.put("show-globally", String.valueOf(showGlobally));
208    
209                            PortalUtil.addPortletBreadcrumbEntry(
210                                    request, folder.getName(), portletURL.toString(), data);
211                    }
212            }
213    
214            public static void addPortletBreadcrumbEntries(
215                            Folder folder, HttpServletRequest request,
216                            RenderResponse renderResponse, boolean showGlobally)
217                    throws Exception {
218    
219                    String strutsAction = ParamUtil.getString(request, "struts_action");
220    
221                    long groupId = ParamUtil.getLong(request, "groupId");
222    
223                    PortletURL portletURL = renderResponse.createRenderURL();
224    
225                    if (strutsAction.equals("/journal/select_document_library") ||
226                            strutsAction.equals("/document_library/select_file_entry") ||
227                            strutsAction.equals("/document_library/select_folder") ||
228                            strutsAction.equals("/document_library_display/select_folder") ||
229                            strutsAction.equals("/image_gallery_display/select_folder")) {
230    
231                            ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
232                                    WebKeys.THEME_DISPLAY);
233    
234                            portletURL.setWindowState(LiferayWindowState.POP_UP);
235    
236                            portletURL.setParameter("struts_action", strutsAction);
237                            portletURL.setParameter("groupId", String.valueOf(groupId));
238    
239                            Map<String, Object> data = new HashMap<String, Object>();
240    
241                            data.put("folder-id", _getDefaultFolderId(request));
242                            data.put("view-entries", Boolean.TRUE.toString());
243                            data.put("view-folders", Boolean.TRUE.toString());
244    
245                            PortalUtil.addPortletBreadcrumbEntry(
246                                    request, themeDisplay.translate("home"), portletURL.toString(),
247                                    data);
248                    }
249                    else {
250                            portletURL.setParameter("struts_action", "/document_library/view");
251                    }
252    
253                    addPortletBreadcrumbEntries(folder, request, portletURL, showGlobally);
254            }
255    
256            public static void addPortletBreadcrumbEntries(
257                            long folderId, HttpServletRequest request,
258                            RenderResponse renderResponse, boolean showGlobally)
259                    throws Exception {
260    
261                    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
262                            Folder folder = DLAppLocalServiceUtil.getFolder(folderId);
263    
264                            if (folder.getFolderId() !=
265                                            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
266    
267                                    addPortletBreadcrumbEntries(
268                                            folder, request, renderResponse, showGlobally);
269                            }
270                    }
271            }
272    
273            public static int compareVersions(String version1, String version2) {
274                    int[] splitVersion1 = StringUtil.split(version1, StringPool.PERIOD, 0);
275                    int[] splitVersion2 = StringUtil.split(version2, StringPool.PERIOD, 0);
276    
277                    if ((splitVersion1.length != 2) && (splitVersion2.length != 2)) {
278                            return 0;
279                    }
280                    else if ((splitVersion1.length != 2)) {
281                            return -1;
282                    }
283                    else if ((splitVersion2.length != 2)) {
284                            return 1;
285                    }
286    
287                    if (splitVersion1[0] > splitVersion2[0]) {
288                            return 1;
289                    }
290                    else if (splitVersion1[0] < splitVersion2[0]) {
291                            return -1;
292                    }
293                    else if (splitVersion1[1] > splitVersion2[1]) {
294                            return 1;
295                    }
296                    else if (splitVersion1[1] < splitVersion2[1]) {
297                            return -1;
298                    }
299    
300                    return 0;
301            }
302    
303            public static Set<String> getAllMediaGalleryMimeTypes() {
304                    return _instance._allMediaGalleryMimeTypes;
305            }
306    
307            public static String getDividedPath(long id) {
308                    StringBundler sb = new StringBundler(16);
309    
310                    long dividend = id;
311    
312                    while ((dividend / _DIVISOR) != 0) {
313                            sb.append(StringPool.SLASH);
314                            sb.append(dividend % _DIVISOR);
315    
316                            dividend = dividend / _DIVISOR;
317                    }
318    
319                    sb.append(StringPool.SLASH);
320                    sb.append(id);
321    
322                    return sb.toString();
323            }
324    
325            public static String getFileIcon(String extension) {
326                    return _instance._getFileIcon(extension);
327            }
328    
329            public static String getGenericName(String extension) {
330                    return _instance._getGenericName(extension);
331            }
332    
333            public static long[] getGroupIds(long groupId)
334                    throws PortalException, SystemException {
335    
336                    Group scopeGroup = GroupLocalServiceUtil.getGroup(groupId);
337    
338                    Group companyGroup = GroupLocalServiceUtil.getCompanyGroup(
339                            scopeGroup.getCompanyId());
340    
341                    if (scopeGroup.isLayout()) {
342                            return new long[] {
343                                    scopeGroup.getParentGroupId(), companyGroup.getGroupId()
344                            };
345                    }
346                    else {
347                            return new long[] {groupId, companyGroup.getGroupId()};
348                    }
349            }
350    
351            public static long[] getGroupIds(ThemeDisplay themeDisplay)
352                    throws PortalException, SystemException {
353    
354                    return getGroupIds(themeDisplay.getScopeGroupId());
355            }
356    
357            public static String[] getMediaGalleryMimeTypes(
358                    PortletPreferences portletPreferences, PortletRequest portletRequest) {
359    
360                    String mimeTypes = PrefsParamUtil.getString(
361                            portletPreferences, portletRequest, "mimeTypes",
362                            _instance._allMediaGalleryMimeTypesString);
363    
364                    String[] mimeTypesArray = StringUtil.split(mimeTypes);
365    
366                    Arrays.sort(mimeTypesArray);
367    
368                    return mimeTypesArray;
369            }
370    
371            public static OrderByComparator getRepositoryModelOrderByComparator(
372                    String orderByCol, String orderByType) {
373    
374                    boolean orderByAsc = true;
375    
376                    if (orderByType.equals("desc")) {
377                            orderByAsc = false;
378                    }
379    
380                    OrderByComparator orderByComparator = null;
381    
382                    if (orderByCol.equals("creationDate")) {
383                            orderByComparator = new RepositoryModelCreateDateComparator(
384                                    orderByAsc);
385                    }
386                    else if (orderByCol.equals("downloads")) {
387                            orderByComparator = new RepositoryModelReadCountComparator(
388                                    orderByAsc);
389                    }
390                    else if (orderByCol.equals("modifiedDate")) {
391                            orderByComparator = new RepositoryModelModifiedDateComparator(
392                                    orderByAsc);
393                    }
394                    else if (orderByCol.equals("size")) {
395                            orderByComparator = new RepositoryModelSizeComparator(orderByAsc);
396                    }
397                    else {
398                            orderByComparator = new RepositoryModelNameComparator(orderByAsc);
399                    }
400    
401                    return orderByComparator;
402            }
403    
404            public static String getTempFileId(long id, String version) {
405                    return getTempFileId(id, version, null);
406            }
407    
408            public static String getTempFileId(
409                    long id, String version, String languageId) {
410    
411                    if (Validator.isNull(languageId)) {
412                            return String.valueOf(id).concat(StringPool.PERIOD).concat(version);
413                    }
414    
415                    StringBundler sb = new StringBundler(5);
416    
417                    sb.append(id);
418                    sb.append(StringPool.PERIOD);
419                    sb.append(version);
420                    sb.append(StringPool.PERIOD);
421                    sb.append(languageId);
422    
423                    return sb.toString();
424            }
425    
426            private static long _getDefaultFolderId(HttpServletRequest request)
427                    throws Exception {
428    
429                    PortletPreferences portletPreferences =
430                            PortletPreferencesFactoryUtil.getPortletPreferences(
431                                    request, PortalUtil.getPortletId(request));
432    
433                    return GetterUtil.getLong(
434                            portletPreferences.getValue(
435                                    "rootFolderId",
436                                    String.valueOf(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)));
437            }
438    
439            private DLUtil() {
440                    _allMediaGalleryMimeTypes.addAll(
441                            SetUtil.fromArray(
442                                    PropsUtil.getArray(
443                                            PropsKeys.DL_FILE_ENTRY_PREVIEW_AUDIO_MIME_TYPES)));
444                    _allMediaGalleryMimeTypes.addAll(
445                            SetUtil.fromArray(
446                                    PropsUtil.getArray(
447                                            PropsKeys.DL_FILE_ENTRY_PREVIEW_VIDEO_MIME_TYPES)));
448                    _allMediaGalleryMimeTypes.addAll(
449                            SetUtil.fromArray(
450                                    PropsUtil.getArray(
451                                            PropsKeys.DL_FILE_ENTRY_PREVIEW_IMAGE_MIME_TYPES)));
452    
453                    _allMediaGalleryMimeTypesString = StringUtil.merge(
454                            _allMediaGalleryMimeTypes);
455    
456                    String[] fileIcons = null;
457    
458                    try {
459                            fileIcons = PrefsPropsUtil.getStringArray(
460                                    PropsKeys.DL_FILE_ICONS, StringPool.COMMA);
461                    }
462                    catch (Exception e) {
463                            _log.error(e, e);
464    
465                            fileIcons = new String[] {StringPool.BLANK};
466                    }
467    
468                    for (int i = 0; i < fileIcons.length; i++) {
469    
470                            // Only process non wildcard extensions
471    
472                            if (!StringPool.STAR.equals(fileIcons[i])) {
473    
474                                    // Strip starting period
475    
476                                    String extension = fileIcons[i];
477                                    extension = extension.substring(1, extension.length());
478    
479                                    _fileIcons.add(extension);
480                            }
481                    }
482    
483                    String[] genericNames = PropsUtil.getArray(
484                            PropsKeys.DL_FILE_GENERIC_NAMES);
485    
486                    for (String genericName : genericNames) {
487                            _populateGenericNamesMap(genericName);
488                    }
489            }
490    
491            private String _getFileIcon(String extension) {
492                    if (!_fileIcons.contains(extension)) {
493                            extension = _DEFAULT_FILE_ICON;
494                    }
495    
496                    return extension;
497            }
498    
499            private String _getGenericName(String extension) {
500                    String genericName = _genericNames.get(extension);
501    
502                    if (genericName == null) {
503                            genericName = _DEFAULT_GENERIC_NAME;
504                    }
505    
506                    return genericName;
507            }
508    
509            private void _populateGenericNamesMap(String genericName) {
510                    String[] extensions = PropsUtil.getArray(
511                            PropsKeys.DL_FILE_GENERIC_EXTENSIONS, new Filter(genericName));
512    
513                    for (String extension : extensions) {
514                            _genericNames.put(extension, genericName);
515                    }
516            }
517    
518            private static final String _DEFAULT_FILE_ICON = "page";
519    
520            private static final String _DEFAULT_GENERIC_NAME = "default";
521    
522            private static final long _DIVISOR = 256;;
523    
524            private static Log _log = LogFactoryUtil.getLog(DLUtil.class);
525    
526            private static DLUtil _instance = new DLUtil();
527    
528            private Set<String> _allMediaGalleryMimeTypes = new TreeSet<String>();
529            private String _allMediaGalleryMimeTypesString;
530            private Set<String> _fileIcons = new HashSet<String>();
531            private Map<String, String> _genericNames = new HashMap<String, String>();
532    
533    }