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