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.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.FileVersion;
026    import com.liferay.portal.kernel.repository.model.Folder;
027    import com.liferay.portal.kernel.search.Document;
028    import com.liferay.portal.kernel.search.Field;
029    import com.liferay.portal.kernel.search.Hits;
030    import com.liferay.portal.kernel.util.ArrayUtil;
031    import com.liferay.portal.kernel.util.GetterUtil;
032    import com.liferay.portal.kernel.util.HtmlUtil;
033    import com.liferay.portal.kernel.util.HttpUtil;
034    import com.liferay.portal.kernel.util.LocaleUtil;
035    import com.liferay.portal.kernel.util.LocalizationUtil;
036    import com.liferay.portal.kernel.util.OrderByComparator;
037    import com.liferay.portal.kernel.util.ParamUtil;
038    import com.liferay.portal.kernel.util.PrefsParamUtil;
039    import com.liferay.portal.kernel.util.PrefsPropsUtil;
040    import com.liferay.portal.kernel.util.PropsKeys;
041    import com.liferay.portal.kernel.util.PropsUtil;
042    import com.liferay.portal.kernel.util.SetUtil;
043    import com.liferay.portal.kernel.util.StringBundler;
044    import com.liferay.portal.kernel.util.StringPool;
045    import com.liferay.portal.kernel.util.StringUtil;
046    import com.liferay.portal.kernel.util.Validator;
047    import com.liferay.portal.kernel.util.WebKeys;
048    import com.liferay.portal.kernel.workflow.WorkflowConstants;
049    import com.liferay.portal.model.Group;
050    import com.liferay.portal.model.Subscription;
051    import com.liferay.portal.service.SubscriptionLocalServiceUtil;
052    import com.liferay.portal.service.WorkflowDefinitionLinkLocalServiceUtil;
053    import com.liferay.portal.theme.PortletDisplay;
054    import com.liferay.portal.theme.ThemeDisplay;
055    import com.liferay.portal.util.PortalUtil;
056    import com.liferay.portal.util.PortletKeys;
057    import com.liferay.portal.util.PropsValues;
058    import com.liferay.portlet.PortletPreferencesFactoryUtil;
059    import com.liferay.portlet.PortletURLFactoryUtil;
060    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
061    import com.liferay.portlet.documentlibrary.model.DLFileEntryType;
062    import com.liferay.portlet.documentlibrary.model.DLFileEntryTypeConstants;
063    import com.liferay.portlet.documentlibrary.model.DLFileShortcut;
064    import com.liferay.portlet.documentlibrary.model.DLFolder;
065    import com.liferay.portlet.documentlibrary.model.DLFolderConstants;
066    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
067    import com.liferay.portlet.documentlibrary.service.DLFolderLocalServiceUtil;
068    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelCreateDateComparator;
069    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelModifiedDateComparator;
070    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelNameComparator;
071    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelReadCountComparator;
072    import com.liferay.portlet.documentlibrary.util.comparator.RepositoryModelSizeComparator;
073    import com.liferay.portlet.messageboards.model.MBMessage;
074    import com.liferay.portlet.messageboards.service.MBMessageLocalServiceUtil;
075    import com.liferay.portlet.trash.util.TrashUtil;
076    import com.liferay.util.ContentUtil;
077    
078    import java.util.ArrayList;
079    import java.util.Arrays;
080    import java.util.Collections;
081    import java.util.Date;
082    import java.util.HashMap;
083    import java.util.HashSet;
084    import java.util.List;
085    import java.util.Locale;
086    import java.util.Map;
087    import java.util.Set;
088    import java.util.TreeSet;
089    
090    import javax.portlet.PortletPreferences;
091    import javax.portlet.PortletRequest;
092    import javax.portlet.PortletURL;
093    import javax.portlet.RenderResponse;
094    
095    import javax.servlet.http.HttpServletRequest;
096    
097    /**
098     * @author Brian Wing Shun Chan
099     * @author Julio Camarero
100     */
101    public class DLImpl implements DL {
102    
103            public void addPortletBreadcrumbEntries(
104                            DLFileShortcut dlFileShortcut, HttpServletRequest request,
105                            RenderResponse renderResponse)
106                    throws Exception {
107    
108                    Folder folder = dlFileShortcut.getFolder();
109    
110                    if (folder.getFolderId() !=
111                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
112    
113                            addPortletBreadcrumbEntries(folder, request, renderResponse);
114                    }
115    
116                    DLFileShortcut unescapedDLFileShortcut =
117                            dlFileShortcut.toUnescapedModel();
118    
119                    PortletURL portletURL = renderResponse.createRenderURL();
120    
121                    portletURL.setParameter(
122                            "struts_action", "/document_library/view_file_entry");
123                    portletURL.setParameter(
124                            "fileEntryId", String.valueOf(dlFileShortcut.getToFileEntryId()));
125    
126                    PortalUtil.addPortletBreadcrumbEntry(
127                            request, unescapedDLFileShortcut.getToTitle(),
128                            portletURL.toString());
129            }
130    
131            public void addPortletBreadcrumbEntries(
132                            FileEntry fileEntry, HttpServletRequest request,
133                            RenderResponse renderResponse)
134                    throws Exception {
135    
136                    Folder folder = fileEntry.getFolder();
137    
138                    if (folder.getFolderId() !=
139                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
140    
141                            addPortletBreadcrumbEntries(folder, request, renderResponse);
142                    }
143    
144                    PortletURL portletURL = renderResponse.createRenderURL();
145    
146                    FileEntry unescapedFileEntry = fileEntry.toUnescapedModel();
147    
148                    portletURL.setParameter(
149                            "struts_action", "/document_library/view_file_entry");
150                    portletURL.setParameter(
151                            "fileEntryId", String.valueOf(fileEntry.getFileEntryId()));
152    
153                    PortalUtil.addPortletBreadcrumbEntry(
154                            request, unescapedFileEntry.getTitle(), portletURL.toString());
155            }
156    
157            public void addPortletBreadcrumbEntries(
158                            Folder folder, HttpServletRequest request,
159                            LiferayPortletResponse liferayPortletResponse)
160                    throws Exception {
161    
162                    ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
163                            WebKeys.THEME_DISPLAY);
164    
165                    PortletURL portletURL = liferayPortletResponse.createRenderURL();
166    
167                    portletURL.setParameter("struts_action", "/document_library/view");
168    
169                    Map<String, Object> data = new HashMap<String, Object>();
170    
171                    data.put("direction-right", Boolean.TRUE.toString());
172                    data.put("folder-id", getDefaultFolderId(request));
173    
174                    PortalUtil.addPortletBreadcrumbEntry(
175                            request, themeDisplay.translate("home"), portletURL.toString(),
176                            data);
177    
178                    addPortletBreadcrumbEntries(folder, request, portletURL);
179            }
180    
181            public void addPortletBreadcrumbEntries(
182                            Folder folder, HttpServletRequest request, PortletURL portletURL)
183                    throws Exception {
184    
185                    long defaultFolderId = getDefaultFolderId(request);
186    
187                    List<Folder> ancestorFolders = Collections.emptyList();
188    
189                    if ((folder != null) && (folder.getFolderId() != defaultFolderId)) {
190                            ancestorFolders = folder.getAncestors();
191    
192                            int indexOfRootFolder = -1;
193    
194                            for (int i = 0; i < ancestorFolders.size(); i++) {
195                                    Folder ancestorFolder = ancestorFolders.get(i);
196    
197                                    if (defaultFolderId == ancestorFolder.getFolderId()) {
198                                            indexOfRootFolder = i;
199                                    }
200                            }
201    
202                            if (indexOfRootFolder > -1) {
203                                    ancestorFolders = ancestorFolders.subList(0, indexOfRootFolder);
204                            }
205                    }
206    
207                    Collections.reverse(ancestorFolders);
208    
209                    for (Folder ancestorFolder : ancestorFolders) {
210                            portletURL.setParameter(
211                                    "folderId", String.valueOf(ancestorFolder.getFolderId()));
212    
213                            Map<String, Object> data = new HashMap<String, Object>();
214    
215                            data.put("direction-right", Boolean.TRUE.toString());
216                            data.put("folder-id", ancestorFolder.getFolderId());
217    
218                            PortalUtil.addPortletBreadcrumbEntry(
219                                    request, ancestorFolder.getName(), portletURL.toString(), data);
220                    }
221    
222                    long folderId = DLFolderConstants.DEFAULT_PARENT_FOLDER_ID;
223    
224                    if (folder != null) {
225                            folderId = folder.getFolderId();
226                    }
227    
228                    portletURL.setParameter("folderId", String.valueOf(folderId));
229    
230                    if ((folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) &&
231                            (folderId != defaultFolderId)) {
232    
233                            Folder unescapedFolder = folder.toUnescapedModel();
234    
235                            Map<String, Object> data = new HashMap<String, Object>();
236    
237                            data.put("direction-right", Boolean.TRUE.toString());
238                            data.put("folder-id", folderId);
239    
240                            PortalUtil.addPortletBreadcrumbEntry(
241                                    request, unescapedFolder.getName(), portletURL.toString(),
242                                    data);
243                    }
244            }
245    
246            public void addPortletBreadcrumbEntries(
247                            Folder folder, HttpServletRequest request,
248                            RenderResponse renderResponse)
249                    throws Exception {
250    
251                    String strutsAction = ParamUtil.getString(request, "struts_action");
252    
253                    long groupId = ParamUtil.getLong(request, "groupId");
254    
255                    PortletURL portletURL = renderResponse.createRenderURL();
256    
257                    if (strutsAction.equals("/document_library/select_file_entry") ||
258                            strutsAction.equals("/document_library/select_folder") ||
259                            strutsAction.equals("/document_library_display/select_folder") ||
260                            strutsAction.equals(
261                                    "/dynamic_data_mapping/select_document_library") ||
262                            strutsAction.equals("/image_gallery_display/select_folder")) {
263    
264                            ThemeDisplay themeDisplay = (ThemeDisplay)request.getAttribute(
265                                    WebKeys.THEME_DISPLAY);
266    
267                            portletURL.setParameter("struts_action", strutsAction);
268                            portletURL.setParameter("groupId", String.valueOf(groupId));
269                            portletURL.setWindowState(LiferayWindowState.POP_UP);
270    
271                            PortalUtil.addPortletBreadcrumbEntry(
272                                    request, themeDisplay.translate("home"), portletURL.toString());
273                    }
274                    else {
275                            portletURL.setParameter("struts_action", "/document_library/view");
276                    }
277    
278                    addPortletBreadcrumbEntries(folder, request, portletURL);
279            }
280    
281            public void addPortletBreadcrumbEntries(
282                            long folderId, HttpServletRequest request,
283                            RenderResponse renderResponse)
284                    throws Exception {
285    
286                    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
287                            Folder folder = DLAppLocalServiceUtil.getFolder(folderId);
288    
289                            if (folder.getFolderId() !=
290                                            DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
291    
292                                    addPortletBreadcrumbEntries(folder, request, renderResponse);
293                            }
294                    }
295            }
296    
297            public int compareVersions(String version1, String version2) {
298                    int[] splitVersion1 = StringUtil.split(version1, StringPool.PERIOD, 0);
299                    int[] splitVersion2 = StringUtil.split(version2, StringPool.PERIOD, 0);
300    
301                    if ((splitVersion1.length != 2) && (splitVersion2.length != 2)) {
302                            return 0;
303                    }
304                    else if (splitVersion1.length != 2) {
305                            return -1;
306                    }
307                    else if (splitVersion2.length != 2) {
308                            return 1;
309                    }
310    
311                    if (splitVersion1[0] > splitVersion2[0]) {
312                            return 1;
313                    }
314                    else if (splitVersion1[0] < splitVersion2[0]) {
315                            return -1;
316                    }
317                    else if (splitVersion1[1] > splitVersion2[1]) {
318                            return 1;
319                    }
320                    else if (splitVersion1[1] < splitVersion2[1]) {
321                            return -1;
322                    }
323    
324                    return 0;
325            }
326    
327            public String getAbsolutePath(PortletRequest portletRequest, long folderId)
328                    throws PortalException, SystemException {
329    
330                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
331                            WebKeys.THEME_DISPLAY);
332    
333                    if (folderId == DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
334                            return themeDisplay.translate("home");
335                    }
336    
337                    DLFolder dlFolder = DLFolderLocalServiceUtil.getFolder(folderId);
338    
339                    List<DLFolder> dlFolders = dlFolder.getAncestors();
340    
341                    Collections.reverse(dlFolders);
342    
343                    StringBundler sb = new StringBundler((dlFolders.size() * 3) + 5);
344    
345                    sb.append(themeDisplay.translate("home"));
346                    sb.append(StringPool.SPACE);
347    
348                    for (DLFolder curDLFolder : dlFolders) {
349                            sb.append(StringPool.RAQUO);
350                            sb.append(StringPool.SPACE);
351                            sb.append(curDLFolder.getName());
352                    }
353    
354                    sb.append(StringPool.RAQUO);
355                    sb.append(StringPool.SPACE);
356                    sb.append(dlFolder.getName());
357    
358                    return sb.toString();
359            }
360    
361            public Set<String> getAllMediaGalleryMimeTypes() {
362                    return _allMediaGalleryMimeTypes;
363            }
364    
365            public String getDDMStructureKey(DLFileEntryType dlFileEntryType) {
366                    return getDDMStructureKey(dlFileEntryType.getUuid());
367            }
368    
369            public String getDDMStructureKey(String fileEntryTypeUuid) {
370                    return "auto_" + fileEntryTypeUuid;
371            }
372    
373            public String getDeprecatedDDMStructureKey(
374                    DLFileEntryType dlFileEntryType) {
375    
376                    return getDeprecatedDDMStructureKey(
377                            dlFileEntryType.getFileEntryTypeId());
378            }
379    
380            public String getDeprecatedDDMStructureKey(long fileEntryTypeId) {
381                    return "auto_" + fileEntryTypeId;
382            }
383    
384            public String getDividedPath(long id) {
385                    StringBundler sb = new StringBundler(16);
386    
387                    long dividend = id;
388    
389                    while ((dividend / _DIVISOR) != 0) {
390                            sb.append(StringPool.SLASH);
391                            sb.append(dividend % _DIVISOR);
392    
393                            dividend = dividend / _DIVISOR;
394                    }
395    
396                    sb.append(StringPool.SLASH);
397                    sb.append(id);
398    
399                    return sb.toString();
400            }
401    
402            public String getDLControlPanelLink(
403                            PortletRequest portletRequest, long folderId)
404                    throws PortalException, SystemException {
405    
406                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
407                            WebKeys.THEME_DISPLAY);
408    
409                    PortletURL portletURL = PortletURLFactoryUtil.create(
410                            portletRequest, PortletKeys.DOCUMENT_LIBRARY,
411                            PortalUtil.getControlPanelPlid(themeDisplay.getCompanyId()),
412                            PortletRequest.RENDER_PHASE);
413    
414                    portletURL.setParameter("struts_action", "/document_library/view");
415                    portletURL.setParameter("folderId", String.valueOf(folderId));
416    
417                    return portletURL.toString();
418            }
419    
420            public Map<Locale, String> getEmailFileEntryAddedBodyMap(
421                    PortletPreferences preferences) {
422    
423                    Map<Locale, String> map = LocalizationUtil.getLocalizationMap(
424                            preferences, "emailFileEntryAddedBody");
425    
426                    Locale defaultLocale = LocaleUtil.getDefault();
427    
428                    String defaultValue = map.get(defaultLocale);
429    
430                    if (Validator.isNotNull(defaultValue)) {
431                            return map;
432                    }
433    
434                    map.put(
435                            defaultLocale,
436                            ContentUtil.get(
437                                    PropsUtil.get(PropsKeys.DL_EMAIL_FILE_ENTRY_ADDED_BODY)));
438    
439                    return map;
440            }
441    
442            public boolean getEmailFileEntryAddedEnabled(
443                    PortletPreferences preferences) {
444    
445                    String emailFileEntryAddedEnabled = preferences.getValue(
446                            "emailFileEntryAddedEnabled", StringPool.BLANK);
447    
448                    if (Validator.isNotNull(emailFileEntryAddedEnabled)) {
449                            return GetterUtil.getBoolean(emailFileEntryAddedEnabled);
450                    }
451                    else {
452                            return PropsValues.DL_EMAIL_FILE_ENTRY_ADDED_ENABLED;
453                    }
454            }
455    
456            public Map<Locale, String> getEmailFileEntryAddedSubjectMap(
457                    PortletPreferences preferences) {
458    
459                    Map<Locale, String> map = LocalizationUtil.getLocalizationMap(
460                            preferences, "emailFileEntryAddedSubject");
461    
462                    Locale defaultLocale = LocaleUtil.getDefault();
463    
464                    String defaultValue = map.get(defaultLocale);
465    
466                    if (Validator.isNotNull(defaultValue)) {
467                            return map;
468                    }
469    
470                    map.put(
471                            defaultLocale,
472                            ContentUtil.get(
473                                    PropsUtil.get(PropsKeys.DL_EMAIL_FILE_ENTRY_ADDED_SUBJECT)));
474    
475                    return map;
476            }
477    
478            public Map<Locale, String> getEmailFileEntryUpdatedBodyMap(
479                    PortletPreferences preferences) {
480    
481                    Map<Locale, String> map = LocalizationUtil.getLocalizationMap(
482                            preferences, "emailFileEntryUpdatedBody");
483    
484                    Locale defaultLocale = LocaleUtil.getDefault();
485    
486                    String defaultValue = map.get(defaultLocale);
487    
488                    if (Validator.isNotNull(defaultValue)) {
489                            return map;
490                    }
491    
492                    map.put(
493                            defaultLocale,
494                            ContentUtil.get(
495                                    PropsUtil.get(PropsKeys.DL_EMAIL_FILE_ENTRY_UPDATED_BODY)));
496    
497                    return map;
498            }
499    
500            public boolean getEmailFileEntryUpdatedEnabled(
501                    PortletPreferences preferences) {
502    
503                    String emailFileEntryUpdatedEnabled = preferences.getValue(
504                            "emailFileEntryUpdatedEnabled", StringPool.BLANK);
505    
506                    if (Validator.isNotNull(emailFileEntryUpdatedEnabled)) {
507                            return GetterUtil.getBoolean(emailFileEntryUpdatedEnabled);
508                    }
509                    else {
510                            return PropsValues.DL_EMAIL_FILE_ENTRY_UPDATED_ENABLED;
511                    }
512            }
513    
514            public Map<Locale, String> getEmailFileEntryUpdatedSubjectMap(
515                    PortletPreferences preferences) {
516    
517                    Map<Locale, String> map = LocalizationUtil.getLocalizationMap(
518                            preferences, "emailFileEntryUpdatedSubject");
519    
520                    Locale defaultLocale = LocaleUtil.getDefault();
521    
522                    String defaultValue = map.get(defaultLocale);
523    
524                    if (Validator.isNotNull(defaultValue)) {
525                            return map;
526                    }
527    
528                    map.put(
529                            defaultLocale,
530                            ContentUtil.get(
531                                    PropsUtil.get(PropsKeys.DL_EMAIL_FILE_ENTRY_UPDATED_SUBJECT)));
532    
533                    return map;
534            }
535    
536            public String getEmailFromAddress(
537                            PortletPreferences preferences, long companyId)
538                    throws SystemException {
539    
540                    return PortalUtil.getEmailFromAddress(
541                            preferences, companyId, PropsValues.DL_EMAIL_FROM_ADDRESS);
542            }
543    
544            public String getEmailFromName(
545                            PortletPreferences preferences, long companyId)
546                    throws SystemException {
547    
548                    return PortalUtil.getEmailFromName(
549                            preferences, companyId, PropsValues.DL_EMAIL_FROM_NAME);
550            }
551    
552            public List<Object> getEntries(Hits hits) {
553                    List<Object> entries = new ArrayList<Object>();
554    
555                    for (Document document : hits.getDocs()) {
556                            String entryClassName = GetterUtil.getString(
557                                    document.get(Field.ENTRY_CLASS_NAME));
558                            long entryClassPK = GetterUtil.getLong(
559                                    document.get(Field.ENTRY_CLASS_PK));
560    
561                            try {
562                                    Object obj = null;
563    
564                                    if (entryClassName.equals(DLFileEntry.class.getName())) {
565                                            obj = DLAppLocalServiceUtil.getFileEntry(entryClassPK);
566                                    }
567                                    else if (entryClassName.equals(MBMessage.class.getName())) {
568                                            long classPK = GetterUtil.getLong(
569                                                    document.get(Field.CLASS_PK));
570    
571                                            DLAppLocalServiceUtil.getFileEntry(classPK);
572    
573                                            obj = MBMessageLocalServiceUtil.getMessage(entryClassPK);
574                                    }
575    
576                                    entries.add(obj);
577                            }
578                            catch (Exception e) {
579                                    if (_log.isWarnEnabled()) {
580                                            _log.warn(
581                                                    "Documents and Media search index is stale and " +
582                                                            "contains entry {className=" + entryClassName +
583                                                                    ", classPK=" + entryClassPK + "}");
584                                    }
585                            }
586                    }
587    
588                    return entries;
589            }
590    
591            public String getFileEntryImage(
592                    FileEntry fileEntry, ThemeDisplay themeDisplay) {
593    
594                    StringBundler sb = new StringBundler(5);
595    
596                    sb.append("<img style=\"border-width: 0; text-align: left;\" src=\"");
597                    sb.append(themeDisplay.getPathThemeImages());
598                    sb.append("/file_system/small/");
599                    sb.append(fileEntry.getIcon());
600                    sb.append(".png\">");
601    
602                    return sb.toString();
603            }
604    
605            public Set<Long> getFileEntryTypeSubscriptionClassPKs(long userId)
606                    throws SystemException {
607    
608                    List<Subscription> subscriptions =
609                            SubscriptionLocalServiceUtil.getUserSubscriptions(
610                                    userId, DLFileEntryType.class.getName());
611    
612                    Set<Long> classPKs = new HashSet<Long>(subscriptions.size());
613    
614                    for (Subscription subscription : subscriptions) {
615                            classPKs.add(subscription.getClassPK());
616                    }
617    
618                    return classPKs;
619            }
620    
621            public String getFileIcon(String extension) {
622                    if (!_fileIcons.contains(extension)) {
623                            extension = _DEFAULT_FILE_ICON;
624                    }
625    
626                    return extension;
627            }
628    
629            public String getGenericName(String extension) {
630                    String genericName = _genericNames.get(extension);
631    
632                    if (genericName == null) {
633                            genericName = _DEFAULT_GENERIC_NAME;
634                    }
635    
636                    return genericName;
637            }
638    
639            public String getImagePreviewURL(
640                            FileEntry fileEntry, FileVersion fileVersion,
641                            ThemeDisplay themeDisplay)
642                    throws Exception {
643    
644                    String previewQueryString = null;
645    
646                    if (PropsValues.DL_FILE_ENTRY_THUMBNAIL_ENABLED) {
647                            if (ImageProcessorUtil.hasImages(fileVersion)) {
648                                    previewQueryString = "&imagePreview=1";
649                            }
650                            else if (PDFProcessorUtil.hasImages(fileVersion)) {
651                                    previewQueryString = "&previewFileIndex=1";
652                            }
653                            else if (VideoProcessorUtil.hasVideo(fileVersion)) {
654                                    previewQueryString = "&videoThumbnail=1";
655                            }
656                    }
657    
658                    return getImageSrc(
659                            fileEntry, fileVersion, themeDisplay, previewQueryString);
660            }
661    
662            public String getImagePreviewURL(
663                            FileEntry fileEntry, ThemeDisplay themeDisplay)
664                    throws Exception {
665    
666                    return getImagePreviewURL(
667                            fileEntry, fileEntry.getFileVersion(), themeDisplay);
668            }
669    
670            public String[] getMediaGalleryMimeTypes(
671                    PortletPreferences portletPreferences, PortletRequest portletRequest) {
672    
673                    String mimeTypes = PrefsParamUtil.getString(
674                            portletPreferences, portletRequest, "mimeTypes",
675                            _allMediaGalleryMimeTypesString);
676    
677                    String[] mimeTypesArray = StringUtil.split(mimeTypes);
678    
679                    Arrays.sort(mimeTypesArray);
680    
681                    return mimeTypesArray;
682            }
683    
684            public String getPreviewURL(
685                    FileEntry fileEntry, FileVersion fileVersion, ThemeDisplay themeDisplay,
686                    String queryString) {
687    
688                    return getPreviewURL(
689                            fileEntry, fileVersion, themeDisplay, queryString, true, true);
690            }
691    
692            /**
693             * @deprecated As of 6.2.0, replaced by {@link #getPreviewURL(FileEntry,
694             *             FileVersion, ThemeDisplay, String, boolean, boolean)}
695             */
696            public String getPreviewURL(
697                    FileEntry fileEntry, FileVersion fileVersion, ThemeDisplay themeDisplay,
698                    String queryString, boolean appendToken) {
699    
700                    return getPreviewURL(
701                            fileEntry, fileVersion, themeDisplay, queryString, true, true);
702            }
703    
704            public String getPreviewURL(
705                    FileEntry fileEntry, FileVersion fileVersion, ThemeDisplay themeDisplay,
706                    String queryString, boolean appendVersion, boolean absoluteURL) {
707    
708                    StringBundler sb = new StringBundler(17);
709    
710                    if (themeDisplay != null) {
711                            if (absoluteURL) {
712                                    sb.append(themeDisplay.getPortalURL());
713                            }
714                    }
715    
716                    sb.append(PortalUtil.getPathContext());
717                    sb.append("/documents/");
718                    sb.append(fileEntry.getRepositoryId());
719                    sb.append(StringPool.SLASH);
720                    sb.append(fileEntry.getFolderId());
721                    sb.append(StringPool.SLASH);
722    
723                    String title = fileEntry.getTitle();
724    
725                    if (fileVersion.isInTrash()) {
726                            title = TrashUtil.getOriginalTitle(fileEntry.getTitle());
727                    }
728    
729                    sb.append(HttpUtil.encodeURL(HtmlUtil.unescape(title)));
730    
731                    sb.append(StringPool.SLASH);
732                    sb.append(fileEntry.getUuid());
733    
734                    if (appendVersion) {
735                            sb.append("?version=");
736                            sb.append(fileVersion.getVersion());
737                    }
738    
739                    if (ImageProcessorUtil.isImageSupported(fileVersion)) {
740                            if (appendVersion) {
741                                    sb.append("&t=");
742                            }
743                            else {
744                                    sb.append("?t=");
745                            }
746    
747                            Date modifiedDate = fileVersion.getModifiedDate();
748    
749                            sb.append(modifiedDate.getTime());
750                    }
751    
752                    sb.append(queryString);
753    
754                    if (themeDisplay != null) {
755                            PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
756    
757                            if (portletDisplay != null) {
758                                    String portletId = portletDisplay.getId();
759    
760                                    if (portletId.equals(PortletKeys.TRASH)) {
761                                            sb.append("&status=");
762                                            sb.append(WorkflowConstants.STATUS_IN_TRASH);
763                                    }
764                            }
765                    }
766    
767                    String previewURL = sb.toString();
768    
769                    if ((themeDisplay != null) && themeDisplay.isAddSessionIdToURL()) {
770                            return PortalUtil.getURLWithSessionId(
771                                    previewURL, themeDisplay.getSessionId());
772                    }
773    
774                    return previewURL;
775            }
776    
777            public OrderByComparator getRepositoryModelOrderByComparator(
778                    String orderByCol, String orderByType) {
779    
780                    boolean orderByAsc = true;
781    
782                    if (orderByType.equals("desc")) {
783                            orderByAsc = false;
784                    }
785    
786                    OrderByComparator orderByComparator = null;
787    
788                    if (orderByCol.equals("creationDate")) {
789                            orderByComparator = new RepositoryModelCreateDateComparator(
790                                    orderByAsc);
791                    }
792                    else if (orderByCol.equals("downloads")) {
793                            orderByComparator = new RepositoryModelReadCountComparator(
794                                    orderByAsc);
795                    }
796                    else if (orderByCol.equals("modifiedDate")) {
797                            orderByComparator = new RepositoryModelModifiedDateComparator(
798                                    orderByAsc);
799                    }
800                    else if (orderByCol.equals("size")) {
801                            orderByComparator = new RepositoryModelSizeComparator(orderByAsc);
802                    }
803                    else {
804                            orderByComparator = new RepositoryModelNameComparator(orderByAsc);
805                    }
806    
807                    return orderByComparator;
808            }
809    
810            public String getTempFileId(long id, String version) {
811                    return getTempFileId(id, version, null);
812            }
813    
814            public String getTempFileId(long id, String version, String languageId) {
815                    if (Validator.isNull(languageId)) {
816                            return String.valueOf(id).concat(StringPool.PERIOD).concat(version);
817                    }
818    
819                    StringBundler sb = new StringBundler(5);
820    
821                    sb.append(id);
822                    sb.append(StringPool.PERIOD);
823                    sb.append(version);
824                    sb.append(StringPool.PERIOD);
825                    sb.append(languageId);
826    
827                    return sb.toString();
828            }
829    
830            public String getThumbnailSrc(
831                            FileEntry fileEntry, DLFileShortcut dlFileShortcut,
832                            ThemeDisplay themeDisplay)
833                    throws Exception {
834    
835                    return getThumbnailSrc(
836                            fileEntry, fileEntry.getFileVersion(), dlFileShortcut,
837                            themeDisplay);
838            }
839    
840            public String getThumbnailSrc(
841                            FileEntry fileEntry, FileVersion fileVersion,
842                            DLFileShortcut dlFileShortcut, ThemeDisplay themeDisplay)
843                    throws Exception {
844    
845                    String thumbnailQueryString = null;
846    
847                    if (PropsValues.DL_FILE_ENTRY_THUMBNAIL_ENABLED) {
848                            if (ImageProcessorUtil.hasImages(fileVersion)) {
849                                    thumbnailQueryString = "&imageThumbnail=1";
850                            }
851                            else if (PDFProcessorUtil.hasImages(fileVersion)) {
852                                    thumbnailQueryString = "&documentThumbnail=1";
853                            }
854                            else if (VideoProcessorUtil.hasVideo(fileVersion)) {
855                                    thumbnailQueryString = "&videoThumbnail=1";
856                            }
857                    }
858    
859                    return getImageSrc(
860                            fileEntry, fileVersion, themeDisplay, thumbnailQueryString);
861            }
862    
863            public String getThumbnailStyle() throws Exception {
864                    return getThumbnailStyle(true, 0);
865            }
866    
867            public String getThumbnailStyle(boolean max, int margin) throws Exception {
868                    StringBundler sb = new StringBundler(5);
869    
870                    if (max) {
871                            sb.append("max-height: ");
872                    }
873                    else {
874                            sb.append("height: ");
875                    }
876    
877                    sb.append(
878                            PrefsPropsUtil.getLong(
879                                    PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_HEIGHT) + 2 * margin);
880    
881                    if (max) {
882                            sb.append("px; max-width: ");
883                    }
884                    else {
885                            sb.append("px; width: ");
886                    }
887    
888                    sb.append(
889                            PrefsPropsUtil.getLong(
890                                    PropsKeys.DL_FILE_ENTRY_THUMBNAIL_MAX_WIDTH) + 2 * margin);
891                    sb.append("px;");
892    
893                    return sb.toString();
894            }
895    
896            public String getTitleWithExtension(FileEntry fileEntry) {
897                    String title = fileEntry.getTitle();
898                    String extension = fileEntry.getExtension();
899    
900                    return getTitleWithExtension(title, extension);
901            }
902    
903            public String getTitleWithExtension(String title, String extension) {
904                    if (Validator.isNotNull(extension)) {
905                            String periodAndExtension = StringPool.PERIOD + extension;
906    
907                            if (!title.endsWith(periodAndExtension)) {
908                                    title += periodAndExtension;
909                            }
910                    }
911    
912                    return title;
913            }
914    
915            public String getWebDavURL(
916                            ThemeDisplay themeDisplay, Folder folder, FileEntry fileEntry)
917                    throws PortalException, SystemException {
918    
919                    return getWebDavURL(themeDisplay, folder, fileEntry, false);
920            }
921    
922            public String getWebDavURL(
923                            ThemeDisplay themeDisplay, Folder folder, FileEntry fileEntry,
924                            boolean manualCheckInRequired)
925                    throws PortalException, SystemException {
926    
927                    return getWebDavURL(
928                            themeDisplay, folder, fileEntry, manualCheckInRequired, false);
929            }
930    
931            public String getWebDavURL(
932                            ThemeDisplay themeDisplay, Folder folder, FileEntry fileEntry,
933                            boolean manualCheckInRequired, boolean openDocumentUrl)
934                    throws PortalException, SystemException {
935    
936                    StringBundler webDavURL = new StringBundler(8);
937    
938                    boolean secure = false;
939    
940                    if (themeDisplay.isSecure() ||
941                            PropsValues.WEBDAV_SERVLET_HTTPS_REQUIRED) {
942    
943                            secure = true;
944                    }
945    
946                    String portalURL = PortalUtil.getPortalURL(
947                            themeDisplay.getServerName(), themeDisplay.getServerPort(), secure);
948    
949                    webDavURL.append(portalURL);
950    
951                    webDavURL.append(themeDisplay.getPathContext());
952                    webDavURL.append("/webdav");
953    
954                    if (manualCheckInRequired) {
955                            webDavURL.append(MANUAL_CHECK_IN_REQUIRED_PATH);
956                    }
957    
958                    String fileEntryTitle = null;
959    
960                    if (fileEntry != null) {
961                            String extension = fileEntry.getExtension();
962    
963                            fileEntryTitle = HtmlUtil.unescape(fileEntry.getTitle());
964    
965                            if (openDocumentUrl && isOfficeExtension(extension) &&
966                                    !fileEntryTitle.endsWith(StringPool.PERIOD + extension)) {
967    
968                                    webDavURL.append(OFFICE_EXTENSION_PATH);
969    
970                                    fileEntryTitle += StringPool.PERIOD + extension;
971                            }
972                    }
973    
974                    Group group = themeDisplay.getScopeGroup();
975    
976                    webDavURL.append(group.getFriendlyURL());
977                    webDavURL.append("/document_library");
978    
979                    StringBuilder sb = new StringBuilder();
980    
981                    if ((folder != null) &&
982                            (folder.getFolderId() !=
983                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)) {
984    
985                            Folder curFolder = folder;
986    
987                            while (true) {
988                                    sb.insert(0, HttpUtil.encodeURL(curFolder.getName(), true));
989                                    sb.insert(0, StringPool.SLASH);
990    
991                                    if (curFolder.getParentFolderId() ==
992                                                    DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
993    
994                                            break;
995                                    }
996    
997                                    curFolder = DLAppLocalServiceUtil.getFolder(
998                                            curFolder.getParentFolderId());
999                            }
1000                    }
1001    
1002                    if (fileEntry != null) {
1003                            sb.append(StringPool.SLASH);
1004                            sb.append(HttpUtil.encodeURL(fileEntryTitle, true));
1005                    }
1006    
1007                    webDavURL.append(sb.toString());
1008    
1009                    return webDavURL.toString();
1010            }
1011    
1012            public boolean hasWorkflowDefinitionLink(
1013                            long companyId, long groupId, long folderId, long fileEntryTypeId)
1014                    throws Exception {
1015    
1016                    while (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
1017                            DLFolder dlFolder = DLFolderLocalServiceUtil.fetchDLFolder(
1018                                    folderId);
1019    
1020                            if (dlFolder == null) {
1021                                    return false;
1022                            }
1023    
1024                            if (dlFolder.isOverrideFileEntryTypes()) {
1025                                    break;
1026                            }
1027    
1028                            folderId = dlFolder.getParentFolderId();
1029                    }
1030    
1031                    if (WorkflowDefinitionLinkLocalServiceUtil.hasWorkflowDefinitionLink(
1032                                    companyId, groupId, DLFolderConstants.getClassName(), folderId,
1033                                    fileEntryTypeId) ||
1034                            WorkflowDefinitionLinkLocalServiceUtil.hasWorkflowDefinitionLink(
1035                                    companyId, groupId, DLFolderConstants.getClassName(), folderId,
1036                                    DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_ALL)) {
1037    
1038                            return true;
1039                    }
1040    
1041                    return false;
1042            }
1043    
1044            public boolean isAutoGeneratedDLFileEntryTypeDDMStructureKey(
1045                    String ddmStructureKey) {
1046    
1047                    if (ddmStructureKey.startsWith("auto_")) {
1048                            return true;
1049                    }
1050    
1051                    return false;
1052            }
1053    
1054            public boolean isOfficeExtension(String extension) {
1055                    if (extension.equalsIgnoreCase("doc") ||
1056                            extension.equalsIgnoreCase("docx") ||
1057                            extension.equalsIgnoreCase("dot") ||
1058                            extension.equalsIgnoreCase("ppt") ||
1059                            extension.equalsIgnoreCase("pptx") ||
1060                            extension.equalsIgnoreCase("xls") ||
1061                            extension.equalsIgnoreCase("xlsx")) {
1062    
1063                            return true;
1064                    }
1065    
1066                    return false;
1067            }
1068    
1069            public boolean isSubscribedToFileEntryType(
1070                            long companyId, long groupId, long userId, long fileEntryTypeId)
1071                    throws SystemException {
1072    
1073                    if (fileEntryTypeId ==
1074                                    DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_BASIC_DOCUMENT) {
1075    
1076                            fileEntryTypeId = groupId;
1077                    }
1078    
1079                    return SubscriptionLocalServiceUtil.isSubscribed(
1080                            companyId, userId, DLFileEntryType.class.getName(),
1081                            fileEntryTypeId);
1082            }
1083    
1084            public boolean isSubscribedToFolder(
1085                            long companyId, long groupId, long userId, long folderId)
1086                    throws PortalException, SystemException {
1087    
1088                    return isSubscribedToFolder(companyId, groupId, userId, folderId, true);
1089            }
1090    
1091            public boolean isSubscribedToFolder(
1092                            long companyId, long groupId, long userId, long folderId,
1093                            boolean recursive)
1094                    throws PortalException, SystemException {
1095    
1096                    List<Long> ancestorFolderIds = new ArrayList<Long>();
1097    
1098                    if (folderId != DLFolderConstants.DEFAULT_PARENT_FOLDER_ID) {
1099                            Folder folder = DLAppLocalServiceUtil.getFolder(folderId);
1100    
1101                            if (recursive) {
1102                                    ancestorFolderIds = folder.getAncestorFolderIds();
1103    
1104                                    ancestorFolderIds.add(groupId);
1105                            }
1106    
1107                            ancestorFolderIds.add(0, folderId);
1108                    }
1109                    else {
1110                            ancestorFolderIds.add(groupId);
1111                    }
1112    
1113                    long[] folderIdsArray = ArrayUtil.toLongArray(ancestorFolderIds);
1114    
1115                    return SubscriptionLocalServiceUtil.isSubscribed(
1116                            companyId, userId, Folder.class.getName(), folderIdsArray);
1117            }
1118    
1119            protected long getDefaultFolderId(HttpServletRequest request)
1120                    throws Exception {
1121    
1122                    PortletPreferences portletPreferences =
1123                            PortletPreferencesFactoryUtil.getPortletPreferences(
1124                                    request, PortalUtil.getPortletId(request));
1125    
1126                    return GetterUtil.getLong(
1127                            portletPreferences.getValue(
1128                                    "rootFolderId",
1129                                    String.valueOf(DLFolderConstants.DEFAULT_PARENT_FOLDER_ID)));
1130            }
1131    
1132            protected String getImageSrc(
1133                            FileEntry fileEntry, FileVersion fileVersion,
1134                            ThemeDisplay themeDisplay, String queryString)
1135                    throws Exception {
1136    
1137                    StringBundler sb = new StringBundler(4);
1138    
1139                    sb.append(themeDisplay.getPathThemeImages());
1140                    sb.append("/file_system/large/");
1141                    sb.append(getGenericName(fileEntry.getExtension()));
1142                    sb.append(".png");
1143    
1144                    String thumbnailSrc = sb.toString();
1145    
1146                    if (Validator.isNotNull(queryString)) {
1147                            thumbnailSrc = getPreviewURL(
1148                                    fileEntry, fileVersion, themeDisplay, queryString, true, true);
1149                    }
1150    
1151                    return thumbnailSrc;
1152            }
1153    
1154            private static void _populateGenericNamesMap(String genericName) {
1155                    String[] extensions = PropsUtil.getArray(
1156                            PropsKeys.DL_FILE_GENERIC_EXTENSIONS, new Filter(genericName));
1157    
1158                    for (String extension : extensions) {
1159                            _genericNames.put(extension, genericName);
1160                    }
1161            }
1162    
1163            private static final String _DEFAULT_FILE_ICON = "page";
1164    
1165            private static final String _DEFAULT_GENERIC_NAME = "default";
1166    
1167            private static final long _DIVISOR = 256;
1168    
1169            private static Log _log = LogFactoryUtil.getLog(DLImpl.class);
1170    
1171            private static Set<String> _allMediaGalleryMimeTypes =
1172                    new TreeSet<String>();
1173            private static String _allMediaGalleryMimeTypesString;
1174            private static Set<String> _fileIcons = new HashSet<String>();
1175            private static Map<String, String> _genericNames =
1176                    new HashMap<String, String>();
1177    
1178            static {
1179                    _allMediaGalleryMimeTypes.addAll(
1180                            SetUtil.fromArray(
1181                                    PropsUtil.getArray(
1182                                            PropsKeys.DL_FILE_ENTRY_PREVIEW_AUDIO_MIME_TYPES)));
1183                    _allMediaGalleryMimeTypes.addAll(
1184                            SetUtil.fromArray(
1185                                    PropsUtil.getArray(
1186                                            PropsKeys.DL_FILE_ENTRY_PREVIEW_VIDEO_MIME_TYPES)));
1187                    _allMediaGalleryMimeTypes.addAll(
1188                            SetUtil.fromArray(
1189                                    PropsUtil.getArray(
1190                                            PropsKeys.DL_FILE_ENTRY_PREVIEW_IMAGE_MIME_TYPES)));
1191    
1192                    _allMediaGalleryMimeTypesString = StringUtil.merge(
1193                            _allMediaGalleryMimeTypes);
1194    
1195                    String[] fileIcons = null;
1196    
1197                    try {
1198                            fileIcons = PropsUtil.getArray(PropsKeys.DL_FILE_ICONS);
1199                    }
1200                    catch (Exception e) {
1201                            if (_log.isDebugEnabled()) {
1202                                    _log.debug(e, e);
1203                            }
1204    
1205                            fileIcons = new String[] {StringPool.BLANK};
1206                    }
1207    
1208                    for (int i = 0; i < fileIcons.length; i++) {
1209    
1210                            // Only process non wildcard extensions
1211    
1212                            if (!StringPool.STAR.equals(fileIcons[i])) {
1213    
1214                                    // Strip starting period
1215    
1216                                    String extension = fileIcons[i];
1217    
1218                                    if (extension.length() > 0) {
1219                                            extension = extension.substring(1);
1220                                    }
1221    
1222                                    _fileIcons.add(extension);
1223                            }
1224                    }
1225    
1226                    String[] genericNames = PropsUtil.getArray(
1227                            PropsKeys.DL_FILE_GENERIC_NAMES);
1228    
1229                    for (String genericName : genericNames) {
1230                            _populateGenericNamesMap(genericName);
1231                    }
1232            }
1233    
1234    }