001    /**
002     * Copyright (c) 2000-present 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.asset.util;
016    
017    import com.liferay.asset.kernel.AssetRendererFactoryRegistryUtil;
018    import com.liferay.asset.kernel.model.AssetCategory;
019    import com.liferay.asset.kernel.model.AssetCategoryProperty;
020    import com.liferay.asset.kernel.model.AssetEntry;
021    import com.liferay.asset.kernel.model.AssetRendererFactory;
022    import com.liferay.asset.kernel.model.AssetTag;
023    import com.liferay.asset.kernel.model.AssetVocabulary;
024    import com.liferay.asset.kernel.model.ClassType;
025    import com.liferay.asset.kernel.model.ClassTypeReader;
026    import com.liferay.asset.kernel.service.AssetCategoryLocalServiceUtil;
027    import com.liferay.asset.kernel.service.AssetCategoryPropertyLocalServiceUtil;
028    import com.liferay.asset.kernel.service.AssetEntryLocalServiceUtil;
029    import com.liferay.asset.kernel.service.AssetTagLocalServiceUtil;
030    import com.liferay.asset.kernel.service.persistence.AssetEntryQuery;
031    import com.liferay.dynamic.data.mapping.kernel.DDMStructure;
032    import com.liferay.dynamic.data.mapping.kernel.DDMStructureManager;
033    import com.liferay.dynamic.data.mapping.kernel.DDMStructureManagerUtil;
034    import com.liferay.portal.kernel.exception.PortalException;
035    import com.liferay.portal.kernel.log.Log;
036    import com.liferay.portal.kernel.log.LogFactoryUtil;
037    import com.liferay.portal.kernel.model.Layout;
038    import com.liferay.portal.kernel.model.LayoutTypePortletConstants;
039    import com.liferay.portal.kernel.model.Portlet;
040    import com.liferay.portal.kernel.portlet.LiferayPortletRequest;
041    import com.liferay.portal.kernel.portlet.LiferayPortletResponse;
042    import com.liferay.portal.kernel.portlet.LiferayWindowState;
043    import com.liferay.portal.kernel.search.BaseModelSearchResult;
044    import com.liferay.portal.kernel.search.Document;
045    import com.liferay.portal.kernel.search.DocumentImpl;
046    import com.liferay.portal.kernel.search.Field;
047    import com.liferay.portal.kernel.search.Hits;
048    import com.liferay.portal.kernel.search.Indexer;
049    import com.liferay.portal.kernel.search.SearchContext;
050    import com.liferay.portal.kernel.search.SearchContextFactory;
051    import com.liferay.portal.kernel.search.Sort;
052    import com.liferay.portal.kernel.search.SortFactoryUtil;
053    import com.liferay.portal.kernel.security.permission.ActionKeys;
054    import com.liferay.portal.kernel.security.permission.PermissionChecker;
055    import com.liferay.portal.kernel.security.permission.comparator.ModelResourceComparator;
056    import com.liferay.portal.kernel.service.PortletLocalServiceUtil;
057    import com.liferay.portal.kernel.theme.PortletDisplay;
058    import com.liferay.portal.kernel.theme.ThemeDisplay;
059    import com.liferay.portal.kernel.util.ArrayUtil;
060    import com.liferay.portal.kernel.util.CharPool;
061    import com.liferay.portal.kernel.util.GetterUtil;
062    import com.liferay.portal.kernel.util.HttpUtil;
063    import com.liferay.portal.kernel.util.ListUtil;
064    import com.liferay.portal.kernel.util.LocaleUtil;
065    import com.liferay.portal.kernel.util.ParamUtil;
066    import com.liferay.portal.kernel.util.PortalUtil;
067    import com.liferay.portal.kernel.util.PredicateFilter;
068    import com.liferay.portal.kernel.util.StringPool;
069    import com.liferay.portal.kernel.util.StringUtil;
070    import com.liferay.portal.kernel.util.Validator;
071    import com.liferay.portal.kernel.util.WebKeys;
072    import com.liferay.portlet.asset.service.permission.AssetCategoryPermission;
073    import com.liferay.portlet.asset.service.permission.AssetVocabularyPermission;
074    
075    import java.io.Serializable;
076    
077    import java.util.ArrayList;
078    import java.util.Collections;
079    import java.util.HashMap;
080    import java.util.HashSet;
081    import java.util.List;
082    import java.util.Locale;
083    import java.util.Map;
084    import java.util.Set;
085    import java.util.TimeZone;
086    import java.util.TreeMap;
087    
088    import javax.portlet.PortletMode;
089    import javax.portlet.PortletURL;
090    
091    import javax.servlet.http.HttpServletRequest;
092    
093    /**
094     * @author Brian Wing Shun Chan
095     * @author Jorge Ferrer
096     */
097    public class AssetUtil {
098    
099            public static final int ASSET_ENTRY_ABSTRACT_LENGTH = 200;
100    
101            public static final String CLASSNAME_SEPARATOR = "_CLASSNAME_";
102    
103            public static final char[] INVALID_CHARACTERS = new char[] {
104                    CharPool.AMPERSAND, CharPool.APOSTROPHE, CharPool.AT,
105                    CharPool.BACK_SLASH, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
106                    CharPool.COLON, CharPool.COMMA, CharPool.EQUAL, CharPool.GREATER_THAN,
107                    CharPool.FORWARD_SLASH, CharPool.LESS_THAN, CharPool.NEW_LINE,
108                    CharPool.OPEN_BRACKET, CharPool.OPEN_CURLY_BRACE, CharPool.PERCENT,
109                    CharPool.PIPE, CharPool.PLUS, CharPool.POUND, CharPool.PRIME,
110                    CharPool.QUESTION, CharPool.QUOTE, CharPool.RETURN, CharPool.SEMICOLON,
111                    CharPool.SLASH, CharPool.STAR, CharPool.TILDE
112            };
113    
114            public static Set<String> addLayoutTags(
115                    HttpServletRequest request, List<AssetTag> tags) {
116    
117                    Set<String> layoutTags = getLayoutTagNames(request);
118    
119                    for (AssetTag tag : tags) {
120                            layoutTags.add(tag.getName());
121                    }
122    
123                    return layoutTags;
124            }
125    
126            public static void addPortletBreadcrumbEntries(
127                            long assetCategoryId, HttpServletRequest request,
128                            PortletURL portletURL)
129                    throws Exception {
130    
131                    AssetCategory assetCategory = AssetCategoryLocalServiceUtil.getCategory(
132                            assetCategoryId);
133    
134                    List<AssetCategory> ancestorCategories = assetCategory.getAncestors();
135    
136                    Collections.reverse(ancestorCategories);
137    
138                    for (AssetCategory ancestorCategory : ancestorCategories) {
139                            portletURL.setParameter(
140                                    "categoryId", String.valueOf(ancestorCategory.getCategoryId()));
141    
142                            PortalUtil.addPortletBreadcrumbEntry(
143                                    request, ancestorCategory.getTitleCurrentValue(),
144                                    portletURL.toString());
145                    }
146    
147                    portletURL.setParameter("categoryId", String.valueOf(assetCategoryId));
148    
149                    PortalUtil.addPortletBreadcrumbEntry(
150                            request, assetCategory.getTitleCurrentValue(),
151                            portletURL.toString());
152            }
153    
154            public static String checkViewURL(
155                    AssetEntry assetEntry, boolean viewInContext, String viewURL,
156                    String currentURL, ThemeDisplay themeDisplay) {
157    
158                    if (Validator.isNull(viewURL)) {
159                            return viewURL;
160                    }
161    
162                    viewURL = HttpUtil.setParameter(
163                            viewURL, "inheritRedirect", viewInContext);
164    
165                    Layout layout = themeDisplay.getLayout();
166    
167                    String assetEntryLayoutUuid = assetEntry.getLayoutUuid();
168    
169                    if (!viewInContext ||
170                            (Validator.isNotNull(assetEntryLayoutUuid) &&
171                             !assetEntryLayoutUuid.equals(layout.getUuid()))) {
172    
173                            viewURL = HttpUtil.setParameter(viewURL, "redirect", currentURL);
174                    }
175    
176                    return viewURL;
177            }
178    
179            public static long[] filterCategoryIds(
180                            PermissionChecker permissionChecker, long[] categoryIds)
181                    throws PortalException {
182    
183                    List<Long> viewableCategoryIds = new ArrayList<>();
184    
185                    for (long categoryId : categoryIds) {
186                            AssetCategory category =
187                                    AssetCategoryLocalServiceUtil.fetchCategory(categoryId);
188    
189                            if ((category != null) &&
190                                    AssetCategoryPermission.contains(
191                                            permissionChecker, categoryId, ActionKeys.VIEW)) {
192    
193                                    viewableCategoryIds.add(categoryId);
194                            }
195                    }
196    
197                    return ArrayUtil.toArray(
198                            viewableCategoryIds.toArray(new Long[viewableCategoryIds.size()]));
199            }
200    
201            public static List<AssetVocabulary> filterVocabularies(
202                    List<AssetVocabulary> vocabularies, String className,
203                    final long classTypePK) {
204    
205                    final long classNameId = PortalUtil.getClassNameId(className);
206    
207                    PredicateFilter<AssetVocabulary> predicateFilter =
208                            new PredicateFilter<AssetVocabulary>() {
209    
210                                    @Override
211                                    public boolean filter(AssetVocabulary assetVocabulary) {
212                                            return
213                                                    assetVocabulary.isAssociatedToClassNameIdAndClassTypePK(
214                                                            classNameId, classTypePK);
215                                    }
216    
217                            };
218    
219                    return ListUtil.filter(vocabularies, predicateFilter);
220            }
221    
222            public static long[] filterVocabularyIds(
223                            PermissionChecker permissionChecker, long[] vocabularyIds)
224                    throws PortalException {
225    
226                    List<Long> viewableVocabularyIds = new ArrayList<>();
227    
228                    for (long vocabularyId : vocabularyIds) {
229                            if (AssetVocabularyPermission.contains(
230                                            permissionChecker, vocabularyId, ActionKeys.VIEW)) {
231    
232                                    viewableVocabularyIds.add(vocabularyId);
233                            }
234                    }
235    
236                    return ArrayUtil.toArray(
237                            viewableVocabularyIds.toArray(
238                                    new Long[viewableVocabularyIds.size()]));
239            }
240    
241            public static PortletURL getAddPortletURL(
242                            LiferayPortletRequest liferayPortletRequest,
243                            LiferayPortletResponse liferayPortletResponse, long groupId,
244                            String className, long classTypeId, long[] allAssetCategoryIds,
245                            String[] allAssetTagNames, String redirect)
246                    throws Exception {
247    
248                    ThemeDisplay themeDisplay =
249                            (ThemeDisplay)liferayPortletRequest.getAttribute(
250                                    WebKeys.THEME_DISPLAY);
251    
252                    AssetRendererFactory<?> assetRendererFactory =
253                            AssetRendererFactoryRegistryUtil.getAssetRendererFactoryByClassName(
254                                    className);
255    
256                    if ((assetRendererFactory == null) ||
257                            !assetRendererFactory.hasAddPermission(
258                                    themeDisplay.getPermissionChecker(), groupId, classTypeId)) {
259    
260                            return null;
261                    }
262    
263                    PortletURL addPortletURL = assetRendererFactory.getURLAdd(
264                            liferayPortletRequest, liferayPortletResponse, classTypeId);
265    
266                    if (addPortletURL == null) {
267                            return null;
268                    }
269    
270                    if (redirect != null) {
271                            addPortletURL.setParameter("redirect", redirect);
272                    }
273    
274                    String referringPortletResource = ParamUtil.getString(
275                            liferayPortletRequest, "portletResource");
276    
277                    if (Validator.isNotNull(referringPortletResource)) {
278                            addPortletURL.setParameter(
279                                    "referringPortletResource", referringPortletResource);
280                    }
281                    else {
282                            PortletDisplay portletDisplay = themeDisplay.getPortletDisplay();
283    
284                            addPortletURL.setParameter(
285                                    "referringPortletResource", portletDisplay.getId());
286    
287                            if (allAssetCategoryIds != null) {
288                                    Map<Long, String> assetVocabularyAssetCategoryIds =
289                                            new HashMap<>();
290    
291                                    for (long assetCategoryId : allAssetCategoryIds) {
292                                            AssetCategory assetCategory =
293                                                    AssetCategoryLocalServiceUtil.fetchAssetCategory(
294                                                            assetCategoryId);
295    
296                                            if (assetCategory == null) {
297                                                    continue;
298                                            }
299    
300                                            long assetVocabularyId = assetCategory.getVocabularyId();
301    
302                                            if (assetVocabularyAssetCategoryIds.containsKey(
303                                                            assetVocabularyId)) {
304    
305                                                    String assetCategoryIds =
306                                                            assetVocabularyAssetCategoryIds.get(
307                                                                    assetVocabularyId);
308    
309                                                    assetVocabularyAssetCategoryIds.put(
310                                                            assetVocabularyId,
311                                                            assetCategoryIds + StringPool.COMMA +
312                                                                    assetCategoryId);
313                                            }
314                                            else {
315                                                    assetVocabularyAssetCategoryIds.put(
316                                                            assetVocabularyId, String.valueOf(assetCategoryId));
317                                            }
318                                    }
319    
320                                    for (Map.Entry<Long, String> entry :
321                                                    assetVocabularyAssetCategoryIds.entrySet()) {
322    
323                                            long assetVocabularyId = entry.getKey();
324                                            String assetCategoryIds = entry.getValue();
325    
326                                            addPortletURL.setParameter(
327                                                    "assetCategoryIds_" + assetVocabularyId,
328                                                    assetCategoryIds);
329                                    }
330                            }
331    
332                            if (allAssetTagNames != null) {
333                                    addPortletURL.setParameter(
334                                            "assetTagNames", StringUtil.merge(allAssetTagNames));
335                            }
336                    }
337    
338                    addPortletURL.setPortletMode(PortletMode.VIEW);
339                    addPortletURL.setWindowState(LiferayWindowState.POP_UP);
340    
341                    return addPortletURL;
342            }
343    
344            /**
345             * @deprecated As of 7.0.0, replaced by {@link
346             *             #getAddPortletURL(LiferayPortletRequest,
347             *             LiferayPortletResponse, long, String, long, long[], String[],
348             *             String)}
349             */
350            @Deprecated
351            public static PortletURL getAddPortletURL(
352                            LiferayPortletRequest liferayPortletRequest,
353                            LiferayPortletResponse liferayPortletResponse, String className,
354                            long classTypeId, long[] allAssetCategoryIds,
355                            String[] allAssetTagNames, String redirect)
356                    throws Exception {
357    
358                    ThemeDisplay themeDisplay =
359                            (ThemeDisplay)liferayPortletRequest.getAttribute(
360                                    WebKeys.THEME_DISPLAY);
361    
362                    return getAddPortletURL(
363                            liferayPortletRequest, liferayPortletResponse,
364                            themeDisplay.getScopeGroupId(), className, classTypeId,
365                            allAssetCategoryIds, allAssetTagNames, redirect);
366            }
367    
368            public static Map<String, PortletURL> getAddPortletURLs(
369                            LiferayPortletRequest liferayPortletRequest,
370                            LiferayPortletResponse liferayPortletResponse, long groupId,
371                            long[] classNameIds, long[] classTypeIds,
372                            long[] allAssetCategoryIds, String[] allAssetTagNames,
373                            String redirect)
374                    throws Exception {
375    
376                    ThemeDisplay themeDisplay =
377                            (ThemeDisplay)liferayPortletRequest.getAttribute(
378                                    WebKeys.THEME_DISPLAY);
379    
380                    Map<String, PortletURL> addPortletURLs = new TreeMap<>(
381                            new ModelResourceComparator(themeDisplay.getLocale()));
382    
383                    for (long classNameId : classNameIds) {
384                            String className = PortalUtil.getClassName(classNameId);
385    
386                            AssetRendererFactory<?> assetRendererFactory =
387                                    AssetRendererFactoryRegistryUtil.
388                                            getAssetRendererFactoryByClassName(className);
389    
390                            if (Validator.isNull(assetRendererFactory.getPortletId())) {
391                                    continue;
392                            }
393    
394                            Portlet portlet = PortletLocalServiceUtil.getPortletById(
395                                    themeDisplay.getCompanyId(),
396                                    assetRendererFactory.getPortletId());
397    
398                            if (!portlet.isActive()) {
399                                    continue;
400                            }
401    
402                            ClassTypeReader classTypeReader =
403                                    assetRendererFactory.getClassTypeReader();
404    
405                            List<ClassType> classTypes = classTypeReader.getAvailableClassTypes(
406                                    PortalUtil.getCurrentAndAncestorSiteGroupIds(
407                                            themeDisplay.getScopeGroupId()),
408                                    themeDisplay.getLocale());
409    
410                            if ((classTypeIds.length == 0) || classTypes.isEmpty()) {
411                                    PortletURL addPortletURL = getAddPortletURL(
412                                            liferayPortletRequest, liferayPortletResponse, groupId,
413                                            className, 0, allAssetCategoryIds, allAssetTagNames,
414                                            redirect);
415    
416                                    if (addPortletURL != null) {
417                                            addPortletURLs.put(className, addPortletURL);
418                                    }
419                            }
420    
421                            for (ClassType classType : classTypes) {
422                                    long classTypeId = classType.getClassTypeId();
423    
424                                    if (ArrayUtil.contains(classTypeIds, classTypeId) ||
425                                            (classTypeIds.length == 0)) {
426    
427                                            PortletURL addPortletURL = getAddPortletURL(
428                                                    liferayPortletRequest, liferayPortletResponse, groupId,
429                                                    className, classTypeId, allAssetCategoryIds,
430                                                    allAssetTagNames, redirect);
431    
432                                            if (addPortletURL != null) {
433                                                    String mesage =
434                                                            className + CLASSNAME_SEPARATOR +
435                                                                    classType.getName();
436    
437                                                    addPortletURLs.put(mesage, addPortletURL);
438                                            }
439                                    }
440                            }
441                    }
442    
443                    return addPortletURLs;
444            }
445    
446            /**
447             * @deprecated As of 7.0.0, replaced by {@link
448             *             #getAddPortletURLs(LiferayPortletRequest,
449             *             LiferayPortletResponse, long, long[], long[], long[],
450             *             String[], String)}
451             */
452            @Deprecated
453            public static Map<String, PortletURL> getAddPortletURLs(
454                            LiferayPortletRequest liferayPortletRequest,
455                            LiferayPortletResponse liferayPortletResponse, long[] classNameIds,
456                            long[] classTypeIds, long[] allAssetCategoryIds,
457                            String[] allAssetTagNames, String redirect)
458                    throws Exception {
459    
460                    ThemeDisplay themeDisplay =
461                            (ThemeDisplay)liferayPortletRequest.getAttribute(
462                                    WebKeys.THEME_DISPLAY);
463    
464                    return getAddPortletURLs(
465                            liferayPortletRequest, liferayPortletResponse,
466                            themeDisplay.getScopeGroupId(), classNameIds, classTypeIds,
467                            allAssetCategoryIds, allAssetTagNames, redirect);
468            }
469    
470            public static String getAddURLPopUp(
471                    long groupId, long plid, PortletURL addPortletURL, String portletId,
472                    boolean addDisplayPageParameter, Layout layout) {
473    
474                    addPortletURL.setParameter(
475                            "hideDefaultSuccessMessage", Boolean.TRUE.toString());
476                    addPortletURL.setParameter("groupId", String.valueOf(groupId));
477                    addPortletURL.setParameter("showHeader", Boolean.FALSE.toString());
478    
479                    String addPortletURLString = addPortletURL.toString();
480    
481                    addPortletURLString = HttpUtil.addParameter(
482                            addPortletURLString, "refererPlid", plid);
483    
484                    if (addDisplayPageParameter && (layout != null)) {
485                            String namespace = PortalUtil.getPortletNamespace(portletId);
486    
487                            addPortletURLString = HttpUtil.addParameter(
488                                    addPortletURLString, namespace + "layoutUuid",
489                                    layout.getUuid());
490                    }
491    
492                    return addPortletURLString;
493            }
494    
495            public static List<AssetEntry> getAssetEntries(Hits hits) {
496                    List<AssetEntry> assetEntries = new ArrayList<>();
497    
498                    if (hits.getDocs() == null) {
499                            return assetEntries;
500                    }
501    
502                    for (Document document : hits.getDocs()) {
503                            String className = GetterUtil.getString(
504                                    document.get(Field.ENTRY_CLASS_NAME));
505                            long classPK = GetterUtil.getLong(
506                                    document.get(Field.ENTRY_CLASS_PK));
507    
508                            try {
509                                    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(
510                                            className, classPK);
511    
512                                    assetEntries.add(assetEntry);
513                            }
514                            catch (Exception e) {
515                            }
516                    }
517    
518                    return assetEntries;
519            }
520    
521            public static String getAssetKeywords(String className, long classPK) {
522                    List<AssetTag> tags = AssetTagLocalServiceUtil.getTags(
523                            className, classPK);
524                    List<AssetCategory> categories =
525                            AssetCategoryLocalServiceUtil.getCategories(className, classPK);
526    
527                    StringBuffer sb = new StringBuffer();
528    
529                    sb.append(ListUtil.toString(tags, AssetTag.NAME_ACCESSOR));
530    
531                    if (!tags.isEmpty()) {
532                            sb.append(StringPool.COMMA);
533                    }
534    
535                    sb.append(ListUtil.toString(categories, AssetCategory.NAME_ACCESSOR));
536    
537                    return sb.toString();
538            }
539    
540            public static String getClassName(String className) {
541                    int pos = className.indexOf(AssetUtil.CLASSNAME_SEPARATOR);
542    
543                    if (pos != -1) {
544                            className = className.substring(0, pos);
545                    }
546    
547                    return className;
548            }
549    
550            public static String getClassNameMessage(String className, Locale locale) {
551                    String message = null;
552    
553                    int pos = className.indexOf(AssetUtil.CLASSNAME_SEPARATOR);
554    
555                    if (pos != -1) {
556                            message = className.substring(
557                                    pos + AssetUtil.CLASSNAME_SEPARATOR.length());
558    
559                            className = className.substring(0, pos);
560                    }
561    
562                    AssetRendererFactory<?> assetRendererFactory =
563                            AssetRendererFactoryRegistryUtil.getAssetRendererFactoryByClassName(
564                                    className);
565    
566                    if (pos == -1) {
567                            message = assetRendererFactory.getTypeName(locale);
568                    }
569    
570                    return message;
571            }
572    
573            public static String getDefaultAssetPublisherId(Layout layout) {
574                    return layout.getTypeSettingsProperty(
575                            LayoutTypePortletConstants.DEFAULT_ASSET_PUBLISHER_PORTLET_ID,
576                            StringPool.BLANK);
577            }
578    
579            public static Set<String> getLayoutTagNames(HttpServletRequest request) {
580                    Set<String> tagNames = (Set<String>)request.getAttribute(
581                            WebKeys.ASSET_LAYOUT_TAG_NAMES);
582    
583                    if (tagNames == null) {
584                            tagNames = new HashSet<>();
585    
586                            request.setAttribute(WebKeys.ASSET_LAYOUT_TAG_NAMES, tagNames);
587                    }
588    
589                    return tagNames;
590            }
591    
592            public static boolean hasSubtype(
593                    String subtypeClassName, Map<String, PortletURL> addPortletURLs) {
594    
595                    for (Map.Entry<String, PortletURL> entry : addPortletURLs.entrySet()) {
596                            String className = entry.getKey();
597    
598                            if (className.startsWith(subtypeClassName) &&
599                                    !className.equals(subtypeClassName)) {
600    
601                                    return true;
602                            }
603                    }
604    
605                    return false;
606            }
607    
608            public static boolean isDefaultAssetPublisher(
609                    Layout layout, String portletId, String portletResource) {
610    
611                    String defaultAssetPublisherPortletId = getDefaultAssetPublisherId(
612                            layout);
613    
614                    if (Validator.isNull(defaultAssetPublisherPortletId)) {
615                            return false;
616                    }
617    
618                    if (defaultAssetPublisherPortletId.equals(portletId) ||
619                            defaultAssetPublisherPortletId.equals(portletResource)) {
620    
621                            return true;
622                    }
623    
624                    return false;
625            }
626    
627            public static boolean isValidWord(String word) {
628                    if (Validator.isNull(word)) {
629                            return false;
630                    }
631    
632                    char[] wordCharArray = word.toCharArray();
633    
634                    for (char c : wordCharArray) {
635                            for (char invalidChar : INVALID_CHARACTERS) {
636                                    if (c == invalidChar) {
637                                            if (_log.isDebugEnabled()) {
638                                                    _log.debug(
639                                                            "Word " + word + " is not valid because " + c +
640                                                                    " is not allowed");
641                                            }
642    
643                                            return false;
644                                    }
645                            }
646                    }
647    
648                    return true;
649            }
650    
651            public static Hits search(
652                            HttpServletRequest request, AssetEntryQuery assetEntryQuery,
653                            int start, int end)
654                    throws Exception {
655    
656                    SearchContext searchContext = SearchContextFactory.getInstance(request);
657    
658                    return search(searchContext, assetEntryQuery, start, end);
659            }
660    
661            public static Hits search(
662                            SearchContext searchContext, AssetEntryQuery assetEntryQuery,
663                            int start, int end)
664                    throws Exception {
665    
666                    AssetSearcher assetSearcher = getAssetSearcher(
667                            searchContext, assetEntryQuery, start, end);
668    
669                    return assetSearcher.search(searchContext);
670            }
671    
672            public static BaseModelSearchResult<AssetEntry> searchAssetEntries(
673                            AssetEntryQuery assetEntryQuery, long[] assetCategoryIds,
674                            String[] assetTagNames, Map<String, Serializable> attributes,
675                            long companyId, String keywords, Layout layout, Locale locale,
676                            long scopeGroupId, TimeZone timeZone, long userId, int start,
677                            int end)
678                    throws Exception {
679    
680                    SearchContext searchContext = SearchContextFactory.getInstance(
681                            assetCategoryIds, assetTagNames, attributes, companyId, keywords,
682                            layout, locale, scopeGroupId, timeZone, userId);
683    
684                    return searchAssetEntries(searchContext, assetEntryQuery, start, end);
685            }
686    
687            public static BaseModelSearchResult<AssetEntry> searchAssetEntries(
688                            HttpServletRequest request, AssetEntryQuery assetEntryQuery,
689                            int start, int end)
690                    throws Exception {
691    
692                    SearchContext searchContext = SearchContextFactory.getInstance(request);
693    
694                    return searchAssetEntries(searchContext, assetEntryQuery, start, end);
695            }
696    
697            public static BaseModelSearchResult<AssetEntry> searchAssetEntries(
698                            SearchContext searchContext, AssetEntryQuery assetEntryQuery,
699                            int start, int end)
700                    throws Exception {
701    
702                    AssetSearcher assetSearcher = getAssetSearcher(
703                            searchContext, assetEntryQuery, start, end);
704    
705                    Hits hits = assetSearcher.search(searchContext);
706    
707                    List<AssetEntry> assetEntries = getAssetEntries(hits);
708    
709                    return new BaseModelSearchResult<>(assetEntries, hits.getLength());
710            }
711    
712            public static String substituteCategoryPropertyVariables(
713                    long groupId, long categoryId, String s) {
714    
715                    String result = s;
716    
717                    AssetCategory category = null;
718    
719                    if (categoryId > 0) {
720                            category = AssetCategoryLocalServiceUtil.fetchCategory(categoryId);
721                    }
722    
723                    if (category != null) {
724                            List<AssetCategoryProperty> categoryProperties =
725                                    AssetCategoryPropertyLocalServiceUtil.getCategoryProperties(
726                                            categoryId);
727    
728                            for (AssetCategoryProperty categoryProperty : categoryProperties) {
729                                    result = StringUtil.replace(
730                                            result, "[$" + categoryProperty.getKey() + "$]",
731                                            categoryProperty.getValue());
732                            }
733                    }
734    
735                    return StringUtil.stripBetween(result, "[$", "$]");
736            }
737    
738            public static String toWord(String text) {
739                    if (Validator.isNull(text)) {
740                            return text;
741                    }
742    
743                    char[] textCharArray = text.toCharArray();
744    
745                    for (int i = 0; i < textCharArray.length; i++) {
746                            char c = textCharArray[i];
747    
748                            for (char invalidChar : INVALID_CHARACTERS) {
749                                    if (c == invalidChar) {
750                                            textCharArray[i] = CharPool.SPACE;
751    
752                                            break;
753                                    }
754                            }
755                    }
756    
757                    return new String(textCharArray);
758            }
759    
760            protected static AssetSearcher getAssetSearcher(
761                            SearchContext searchContext, AssetEntryQuery assetEntryQuery,
762                            int start, int end)
763                    throws Exception {
764    
765                    Indexer<?> searcher = AssetSearcher.getInstance();
766    
767                    AssetSearcher assetSearcher = (AssetSearcher)searcher;
768    
769                    assetSearcher.setAssetEntryQuery(assetEntryQuery);
770    
771                    Layout layout = assetEntryQuery.getLayout();
772    
773                    if (layout != null) {
774                            searchContext.setAttribute(Field.LAYOUT_UUID, layout.getUuid());
775                    }
776    
777                    String ddmStructureFieldName = (String)assetEntryQuery.getAttribute(
778                            "ddmStructureFieldName");
779                    Serializable ddmStructureFieldValue = assetEntryQuery.getAttribute(
780                            "ddmStructureFieldValue");
781    
782                    if (Validator.isNotNull(ddmStructureFieldName) &&
783                            Validator.isNotNull(ddmStructureFieldValue)) {
784    
785                            searchContext.setAttribute(
786                                    "ddmStructureFieldName", ddmStructureFieldName);
787                            searchContext.setAttribute(
788                                    "ddmStructureFieldValue", ddmStructureFieldValue);
789                    }
790    
791                    String paginationType = GetterUtil.getString(
792                            assetEntryQuery.getPaginationType(), "more");
793    
794                    if (!paginationType.equals("none") &&
795                            !paginationType.equals("simple")) {
796    
797                            searchContext.setAttribute("paginationType", paginationType);
798                    }
799    
800                    searchContext.setClassTypeIds(assetEntryQuery.getClassTypeIds());
801                    searchContext.setEnd(end);
802                    searchContext.setGroupIds(assetEntryQuery.getGroupIds());
803    
804                    if (Validator.isNotNull(assetEntryQuery.getKeywords())) {
805                            searchContext.setLike(true);
806                    }
807    
808                    searchContext.setSorts(
809                            getSorts(assetEntryQuery, searchContext.getLocale()));
810                    searchContext.setStart(start);
811    
812                    return assetSearcher;
813            }
814    
815            protected static String getDDMFormFieldType(String sortField)
816                    throws PortalException {
817    
818                    String[] sortFields = sortField.split(
819                            DDMStructureManager.STRUCTURE_INDEXER_FIELD_SEPARATOR);
820    
821                    long ddmStructureId = GetterUtil.getLong(sortFields[2]);
822                    String fieldName = sortFields[3];
823    
824                    DDMStructure ddmStructure = DDMStructureManagerUtil.getStructure(
825                            ddmStructureId);
826    
827                    return ddmStructure.getFieldType(fieldName);
828            }
829    
830            protected static String getOrderByCol(
831                    String sortField, String fieldType, int sortType, Locale locale) {
832    
833                    if (sortField.startsWith(
834                                    DDMStructureManager.STRUCTURE_INDEXER_FIELD_PREFIX)) {
835    
836                            sortField = sortField.concat(StringPool.UNDERLINE).concat(
837                                    LocaleUtil.toLanguageId(locale));
838    
839                            if (!fieldType.equals("ddm-date") &&
840                                    ((sortType == Sort.DOUBLE_TYPE) ||
841                                     (sortType == Sort.FLOAT_TYPE) || (sortType == Sort.INT_TYPE) ||
842                                     (sortType == Sort.LONG_TYPE))) {
843    
844                                    sortField = sortField.concat(StringPool.UNDERLINE).concat(
845                                            "Number");
846                            }
847    
848                            sortField = DocumentImpl.getSortableFieldName(sortField);
849                    }
850                    else if (sortField.equals("modifiedDate")) {
851                            sortField = Field.MODIFIED_DATE;
852                    }
853                    else if (sortField.equals("title")) {
854                            sortField = DocumentImpl.getSortableFieldName(
855                                    "localized_title_".concat(LocaleUtil.toLanguageId(locale)));
856                    }
857    
858                    return sortField;
859            }
860    
861            protected static Sort getSort(
862                            String orderByType, String sortField, Locale locale)
863                    throws Exception {
864    
865                    String ddmFormFieldType = sortField;
866    
867                    if (ddmFormFieldType.startsWith(
868                                    DDMStructureManager.STRUCTURE_INDEXER_FIELD_PREFIX)) {
869    
870                            ddmFormFieldType = getDDMFormFieldType(ddmFormFieldType);
871                    }
872    
873                    int sortType = getSortType(ddmFormFieldType);
874    
875                    return SortFactoryUtil.getSort(
876                            AssetEntry.class, sortType,
877                            getOrderByCol(sortField, ddmFormFieldType, sortType, locale),
878                            !sortField.startsWith(
879                                    DDMStructureManager.STRUCTURE_INDEXER_FIELD_PREFIX),
880                            orderByType);
881            }
882    
883            protected static Sort[] getSorts(
884                            AssetEntryQuery assetEntryQuery, Locale locale)
885                    throws Exception {
886    
887                    Sort sort1 = getSort(
888                            assetEntryQuery.getOrderByType1(), assetEntryQuery.getOrderByCol1(),
889                            locale);
890                    Sort sort2 = getSort(
891                            assetEntryQuery.getOrderByType2(), assetEntryQuery.getOrderByCol2(),
892                            locale);
893    
894                    return new Sort[] {sort1, sort2};
895            }
896    
897            protected static int getSortType(String fieldType) {
898                    int sortType = Sort.STRING_TYPE;
899    
900                    if (fieldType.equals(Field.CREATE_DATE) ||
901                            fieldType.equals(Field.EXPIRATION_DATE) ||
902                            fieldType.equals(Field.PUBLISH_DATE) ||
903                            fieldType.equals("ddm-date") || fieldType.equals("modifiedDate")) {
904    
905                            sortType = Sort.LONG_TYPE;
906                    }
907                    else if (fieldType.equals(Field.PRIORITY) ||
908                                     fieldType.equals(Field.RATINGS) ||
909                                     fieldType.equals("ddm-decimal") ||
910                                     fieldType.equals("ddm-number")) {
911    
912                            sortType = Sort.DOUBLE_TYPE;
913                    }
914                    else if (fieldType.equals(Field.VIEW_COUNT) ||
915                                     fieldType.equals("ddm-integer")) {
916    
917                            sortType = Sort.INT_TYPE;
918                    }
919    
920                    return sortType;
921            }
922    
923            private static final Log _log = LogFactoryUtil.getLog(AssetUtil.class);
924    
925    }