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.kernel.util.WebKeys;
045    import com.liferay.portal.model.Layout;
046    import com.liferay.portal.model.LayoutTypePortletConstants;
047    import com.liferay.portal.model.Portlet;
048    import com.liferay.portal.security.permission.ActionKeys;
049    import com.liferay.portal.security.permission.PermissionChecker;
050    import com.liferay.portal.security.permission.comparator.ModelResourceComparator;
051    import com.liferay.portal.service.PortletLocalServiceUtil;
052    import com.liferay.portal.theme.PortletDisplay;
053    import com.liferay.portal.theme.ThemeDisplay;
054    import com.liferay.portal.util.PortalUtil;
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.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 List<AssetEntry> getAssetEntries(Hits hits) {
471                    List<AssetEntry> assetEntries = new ArrayList<>();
472    
473                    if (hits.getDocs() == null) {
474                            return assetEntries;
475                    }
476    
477                    for (Document document : hits.getDocs()) {
478                            String className = GetterUtil.getString(
479                                    document.get(Field.ENTRY_CLASS_NAME));
480                            long classPK = GetterUtil.getLong(
481                                    document.get(Field.ENTRY_CLASS_PK));
482    
483                            try {
484                                    AssetEntry assetEntry = AssetEntryLocalServiceUtil.getEntry(
485                                            className, classPK);
486    
487                                    assetEntries.add(assetEntry);
488                            }
489                            catch (Exception e) {
490                            }
491                    }
492    
493                    return assetEntries;
494            }
495    
496            public static String getAssetKeywords(String className, long classPK) {
497                    List<AssetTag> tags = AssetTagLocalServiceUtil.getTags(
498                            className, classPK);
499                    List<AssetCategory> categories =
500                            AssetCategoryLocalServiceUtil.getCategories(className, classPK);
501    
502                    StringBuffer sb = new StringBuffer();
503    
504                    sb.append(ListUtil.toString(tags, AssetTag.NAME_ACCESSOR));
505    
506                    if (!tags.isEmpty()) {
507                            sb.append(StringPool.COMMA);
508                    }
509    
510                    sb.append(ListUtil.toString(categories, AssetCategory.NAME_ACCESSOR));
511    
512                    return sb.toString();
513            }
514    
515            public static String getDefaultAssetPublisherId(Layout layout) {
516                    return layout.getTypeSettingsProperty(
517                            LayoutTypePortletConstants.DEFAULT_ASSET_PUBLISHER_PORTLET_ID,
518                            StringPool.BLANK);
519            }
520    
521            public static Set<String> getLayoutTagNames(HttpServletRequest request) {
522                    Set<String> tagNames = (Set<String>)request.getAttribute(
523                            WebKeys.ASSET_LAYOUT_TAG_NAMES);
524    
525                    if (tagNames == null) {
526                            tagNames = new HashSet<>();
527    
528                            request.setAttribute(WebKeys.ASSET_LAYOUT_TAG_NAMES, tagNames);
529                    }
530    
531                    return tagNames;
532            }
533    
534            public static boolean hasSubtype(
535                    String subtypeClassName, Map<String, PortletURL> addPortletURLs) {
536    
537                    for (Map.Entry<String, PortletURL> entry : addPortletURLs.entrySet()) {
538                            String className = entry.getKey();
539    
540                            if (className.startsWith(subtypeClassName) &&
541                                    !className.equals(subtypeClassName)) {
542    
543                                    return true;
544                            }
545                    }
546    
547                    return false;
548            }
549    
550            public static boolean isDefaultAssetPublisher(
551                    Layout layout, String portletId, String portletResource) {
552    
553                    String defaultAssetPublisherPortletId = getDefaultAssetPublisherId(
554                            layout);
555    
556                    if (Validator.isNull(defaultAssetPublisherPortletId)) {
557                            return false;
558                    }
559    
560                    if (defaultAssetPublisherPortletId.equals(portletId) ||
561                            defaultAssetPublisherPortletId.equals(portletResource)) {
562    
563                            return true;
564                    }
565    
566                    return false;
567            }
568    
569            public static boolean isValidWord(String word) {
570                    if (Validator.isNull(word)) {
571                            return false;
572                    }
573    
574                    char[] wordCharArray = word.toCharArray();
575    
576                    for (char c : wordCharArray) {
577                            for (char invalidChar : INVALID_CHARACTERS) {
578                                    if (c == invalidChar) {
579                                            if (_log.isDebugEnabled()) {
580                                                    _log.debug(
581                                                            "Word " + word + " is not valid because " + c +
582                                                                    " is not allowed");
583                                            }
584    
585                                            return false;
586                                    }
587                            }
588                    }
589    
590                    return true;
591            }
592    
593            public static Hits search(
594                            HttpServletRequest request, AssetEntryQuery assetEntryQuery,
595                            int start, int end)
596                    throws Exception {
597    
598                    SearchContext searchContext = SearchContextFactory.getInstance(request);
599    
600                    return search(searchContext, assetEntryQuery, start, end);
601            }
602    
603            public static Hits search(
604                            SearchContext searchContext, AssetEntryQuery assetEntryQuery,
605                            int start, int end)
606                    throws Exception {
607    
608                    AssetSearcher assetSearcher = getAssetSearcher(
609                            searchContext, assetEntryQuery, start, end);
610    
611                    return assetSearcher.search(searchContext);
612            }
613    
614            public static BaseModelSearchResult<AssetEntry> searchAssetEntries(
615                            AssetEntryQuery assetEntryQuery, long[] assetCategoryIds,
616                            String[] assetTagNames, Map<String, Serializable> attributes,
617                            long companyId, String keywords, Layout layout, Locale locale,
618                            long scopeGroupId, TimeZone timeZone, long userId, int start,
619                            int end)
620                    throws Exception {
621    
622                    SearchContext searchContext = SearchContextFactory.getInstance(
623                            assetCategoryIds, assetTagNames, attributes, companyId, keywords,
624                            layout, locale, scopeGroupId, timeZone, userId);
625    
626                    return searchAssetEntries(searchContext, assetEntryQuery, start, end);
627            }
628    
629            public static BaseModelSearchResult<AssetEntry> searchAssetEntries(
630                            HttpServletRequest request, AssetEntryQuery assetEntryQuery,
631                            int start, int end)
632                    throws Exception {
633    
634                    SearchContext searchContext = SearchContextFactory.getInstance(request);
635    
636                    return searchAssetEntries(searchContext, assetEntryQuery, start, end);
637            }
638    
639            public static BaseModelSearchResult<AssetEntry> searchAssetEntries(
640                            SearchContext searchContext, AssetEntryQuery assetEntryQuery,
641                            int start, int end)
642                    throws Exception {
643    
644                    AssetSearcher assetSearcher = getAssetSearcher(
645                            searchContext, assetEntryQuery, start, end);
646    
647                    Hits hits = assetSearcher.search(searchContext);
648    
649                    List<AssetEntry> assetEntries = getAssetEntries(hits);
650    
651                    return new BaseModelSearchResult<>(assetEntries, hits.getLength());
652            }
653    
654            public static String substituteCategoryPropertyVariables(
655                    long groupId, long categoryId, String s) {
656    
657                    String result = s;
658    
659                    AssetCategory category = null;
660    
661                    if (categoryId > 0) {
662                            category = AssetCategoryLocalServiceUtil.fetchCategory(categoryId);
663                    }
664    
665                    if (category != null) {
666                            List<AssetCategoryProperty> categoryProperties =
667                                    AssetCategoryPropertyLocalServiceUtil.getCategoryProperties(
668                                            categoryId);
669    
670                            for (AssetCategoryProperty categoryProperty : categoryProperties) {
671                                    result = StringUtil.replace(
672                                            result, "[$" + categoryProperty.getKey() + "$]",
673                                            categoryProperty.getValue());
674                            }
675                    }
676    
677                    return StringUtil.stripBetween(result, "[$", "$]");
678            }
679    
680            public static String toWord(String text) {
681                    if (Validator.isNull(text)) {
682                            return text;
683                    }
684    
685                    char[] textCharArray = text.toCharArray();
686    
687                    for (int i = 0; i < textCharArray.length; i++) {
688                            char c = textCharArray[i];
689    
690                            for (char invalidChar : INVALID_CHARACTERS) {
691                                    if (c == invalidChar) {
692                                            textCharArray[i] = CharPool.SPACE;
693    
694                                            break;
695                                    }
696                            }
697                    }
698    
699                    return new String(textCharArray);
700            }
701    
702            protected static AssetSearcher getAssetSearcher(
703                            SearchContext searchContext, AssetEntryQuery assetEntryQuery,
704                            int start, int end)
705                    throws Exception {
706    
707                    Indexer<?> searcher = AssetSearcher.getInstance();
708    
709                    AssetSearcher assetSearcher = (AssetSearcher)searcher;
710    
711                    assetSearcher.setAssetEntryQuery(assetEntryQuery);
712    
713                    Layout layout = assetEntryQuery.getLayout();
714    
715                    if (layout != null) {
716                            searchContext.setAttribute(Field.LAYOUT_UUID, layout.getUuid());
717                    }
718    
719                    String ddmStructureFieldName = (String)assetEntryQuery.getAttribute(
720                            "ddmStructureFieldName");
721                    Serializable ddmStructureFieldValue = assetEntryQuery.getAttribute(
722                            "ddmStructureFieldValue");
723    
724                    if (Validator.isNotNull(ddmStructureFieldName) &&
725                            Validator.isNotNull(ddmStructureFieldValue)) {
726    
727                            searchContext.setAttribute(
728                                    "ddmStructureFieldName", ddmStructureFieldName);
729                            searchContext.setAttribute(
730                                    "ddmStructureFieldValue", ddmStructureFieldValue);
731                    }
732    
733                    String paginationType = GetterUtil.getString(
734                            assetEntryQuery.getPaginationType(), "more");
735    
736                    if (!paginationType.equals("none") &&
737                            !paginationType.equals("simple")) {
738    
739                            searchContext.setAttribute("paginationType", paginationType);
740                    }
741    
742                    searchContext.setClassTypeIds(assetEntryQuery.getClassTypeIds());
743                    searchContext.setEnd(end);
744                    searchContext.setGroupIds(assetEntryQuery.getGroupIds());
745    
746                    if (Validator.isNotNull(assetEntryQuery.getKeywords())) {
747                            searchContext.setLike(true);
748                    }
749    
750                    searchContext.setSorts(
751                            getSorts(assetEntryQuery, searchContext.getLocale()));
752                    searchContext.setStart(start);
753    
754                    return assetSearcher;
755            }
756    
757            protected static String getDDMFormFieldType(String sortField)
758                    throws PortalException {
759    
760                    String[] sortFields = sortField.split(
761                            DDMStructureManager.STRUCTURE_INDEXER_FIELD_SEPARATOR);
762    
763                    long ddmStructureId = GetterUtil.getLong(sortFields[2]);
764                    String fieldName = sortFields[3];
765    
766                    DDMStructure ddmStructure = DDMStructureManagerUtil.getStructure(
767                            ddmStructureId);
768    
769                    return ddmStructure.getFieldType(fieldName);
770            }
771    
772            protected static String getOrderByCol(
773                    String sortField, String fieldType, int sortType, Locale locale) {
774    
775                    if (sortField.startsWith(
776                                    DDMStructureManager.STRUCTURE_INDEXER_FIELD_PREFIX)) {
777    
778                            sortField = sortField.concat(StringPool.UNDERLINE).concat(
779                                    LocaleUtil.toLanguageId(locale));
780    
781                            if (!fieldType.equals("ddm-date") &&
782                                    ((sortType == Sort.DOUBLE_TYPE) ||
783                                     (sortType == Sort.FLOAT_TYPE) || (sortType == Sort.INT_TYPE) ||
784                                     (sortType == Sort.LONG_TYPE))) {
785    
786                                    sortField = sortField.concat(StringPool.UNDERLINE).concat(
787                                            "Number");
788                            }
789    
790                            sortField = DocumentImpl.getSortableFieldName(sortField);
791                    }
792                    else if (sortField.equals("modifiedDate")) {
793                            sortField = Field.MODIFIED_DATE;
794                    }
795                    else if (sortField.equals("title")) {
796                            sortField = DocumentImpl.getSortableFieldName(
797                                    "localized_title_".concat(LocaleUtil.toLanguageId(locale)));
798                    }
799    
800                    return sortField;
801            }
802    
803            protected static Sort getSort(
804                            String orderByType, String sortField, Locale locale)
805                    throws Exception {
806    
807                    String ddmFormFieldType = sortField;
808    
809                    if (ddmFormFieldType.startsWith(
810                                    DDMStructureManager.STRUCTURE_INDEXER_FIELD_PREFIX)) {
811    
812                            ddmFormFieldType = getDDMFormFieldType(ddmFormFieldType);
813                    }
814    
815                    int sortType = getSortType(ddmFormFieldType);
816    
817                    return SortFactoryUtil.getSort(
818                            AssetEntry.class, sortType,
819                            getOrderByCol(sortField, ddmFormFieldType, sortType, locale),
820                            !sortField.startsWith(
821                                    DDMStructureManager.STRUCTURE_INDEXER_FIELD_PREFIX),
822                            orderByType);
823            }
824    
825            protected static Sort[] getSorts(
826                            AssetEntryQuery assetEntryQuery, Locale locale)
827                    throws Exception {
828    
829                    Sort sort1 = getSort(
830                            assetEntryQuery.getOrderByType1(), assetEntryQuery.getOrderByCol1(),
831                            locale);
832                    Sort sort2 = getSort(
833                            assetEntryQuery.getOrderByType2(), assetEntryQuery.getOrderByCol2(),
834                            locale);
835    
836                    return new Sort[] {sort1, sort2};
837            }
838    
839            protected static int getSortType(String fieldType) {
840                    int sortType = Sort.STRING_TYPE;
841    
842                    if (fieldType.equals(Field.CREATE_DATE) ||
843                            fieldType.equals(Field.EXPIRATION_DATE) ||
844                            fieldType.equals(Field.PUBLISH_DATE) ||
845                            fieldType.equals("ddm-date") || fieldType.equals("modifiedDate")) {
846    
847                            sortType = Sort.LONG_TYPE;
848                    }
849                    else if (fieldType.equals(Field.PRIORITY) ||
850                                     fieldType.equals(Field.RATINGS) ||
851                                     fieldType.equals("ddm-decimal") ||
852                                     fieldType.equals("ddm-number")) {
853    
854                            sortType = Sort.DOUBLE_TYPE;
855                    }
856                    else if (fieldType.equals(Field.VIEW_COUNT) ||
857                                     fieldType.equals("ddm-integer")) {
858    
859                            sortType = Sort.INT_TYPE;
860                    }
861    
862                    return sortType;
863            }
864    
865            private static final Log _log = LogFactoryUtil.getLog(AssetUtil.class);
866    
867    }