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.exportimport.lar;
016    
017    import com.liferay.portal.NoSuchLayoutException;
018    import com.liferay.portal.kernel.dao.orm.ActionableDynamicQuery;
019    import com.liferay.portal.kernel.dao.orm.Disjunction;
020    import com.liferay.portal.kernel.dao.orm.DynamicQuery;
021    import com.liferay.portal.kernel.dao.orm.Property;
022    import com.liferay.portal.kernel.dao.orm.PropertyFactoryUtil;
023    import com.liferay.portal.kernel.dao.orm.RestrictionsFactoryUtil;
024    import com.liferay.portal.kernel.exception.PortalException;
025    import com.liferay.portal.kernel.json.JSONArray;
026    import com.liferay.portal.kernel.json.JSONFactoryUtil;
027    import com.liferay.portal.kernel.json.JSONObject;
028    import com.liferay.portal.kernel.log.Log;
029    import com.liferay.portal.kernel.log.LogFactoryUtil;
030    import com.liferay.portal.kernel.repository.model.FileEntry;
031    import com.liferay.portal.kernel.util.ArrayUtil;
032    import com.liferay.portal.kernel.util.CharPool;
033    import com.liferay.portal.kernel.util.DateFormatFactoryUtil;
034    import com.liferay.portal.kernel.util.DateRange;
035    import com.liferay.portal.kernel.util.Digester;
036    import com.liferay.portal.kernel.util.DigesterUtil;
037    import com.liferay.portal.kernel.util.FileUtil;
038    import com.liferay.portal.kernel.util.GetterUtil;
039    import com.liferay.portal.kernel.util.HttpUtil;
040    import com.liferay.portal.kernel.util.ListUtil;
041    import com.liferay.portal.kernel.util.LocaleUtil;
042    import com.liferay.portal.kernel.util.MapUtil;
043    import com.liferay.portal.kernel.util.ParamUtil;
044    import com.liferay.portal.kernel.util.StreamUtil;
045    import com.liferay.portal.kernel.util.StringBundler;
046    import com.liferay.portal.kernel.util.StringPool;
047    import com.liferay.portal.kernel.util.StringUtil;
048    import com.liferay.portal.kernel.util.SystemProperties;
049    import com.liferay.portal.kernel.util.TempFileEntryUtil;
050    import com.liferay.portal.kernel.util.Time;
051    import com.liferay.portal.kernel.util.Validator;
052    import com.liferay.portal.kernel.xml.Document;
053    import com.liferay.portal.kernel.xml.Element;
054    import com.liferay.portal.kernel.xml.ElementHandler;
055    import com.liferay.portal.kernel.xml.ElementProcessor;
056    import com.liferay.portal.kernel.zip.ZipReader;
057    import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil;
058    import com.liferay.portal.kernel.zip.ZipWriter;
059    import com.liferay.portal.kernel.zip.ZipWriterFactoryUtil;
060    import com.liferay.portal.model.Company;
061    import com.liferay.portal.model.Group;
062    import com.liferay.portal.model.GroupConstants;
063    import com.liferay.portal.model.Layout;
064    import com.liferay.portal.model.LayoutConstants;
065    import com.liferay.portal.model.LayoutFriendlyURL;
066    import com.liferay.portal.model.LayoutSet;
067    import com.liferay.portal.model.Organization;
068    import com.liferay.portal.model.Portlet;
069    import com.liferay.portal.model.PortletConstants;
070    import com.liferay.portal.model.StagedGroupedModel;
071    import com.liferay.portal.model.StagedModel;
072    import com.liferay.portal.model.SystemEventConstants;
073    import com.liferay.portal.model.User;
074    import com.liferay.portal.security.xml.SecureXMLFactoryProviderUtil;
075    import com.liferay.portal.service.CompanyLocalServiceUtil;
076    import com.liferay.portal.service.GroupLocalServiceUtil;
077    import com.liferay.portal.service.LayoutFriendlyURLLocalServiceUtil;
078    import com.liferay.portal.service.LayoutLocalServiceUtil;
079    import com.liferay.portal.service.LayoutServiceUtil;
080    import com.liferay.portal.service.OrganizationLocalServiceUtil;
081    import com.liferay.portal.service.PortletLocalServiceUtil;
082    import com.liferay.portal.service.SystemEventLocalServiceUtil;
083    import com.liferay.portal.service.UserLocalServiceUtil;
084    import com.liferay.portal.service.persistence.OrganizationUtil;
085    import com.liferay.portal.theme.ThemeDisplay;
086    import com.liferay.portal.util.PortalUtil;
087    import com.liferay.portal.util.PortletKeys;
088    import com.liferay.portal.util.PropsValues;
089    import com.liferay.portlet.asset.model.AssetCategory;
090    import com.liferay.portlet.asset.model.AssetVocabulary;
091    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
092    import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil;
093    import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil;
094    import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil;
095    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
096    import com.liferay.portlet.documentlibrary.model.DLFileEntryType;
097    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
098    import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
099    import com.liferay.portlet.documentlibrary.service.DLFileEntryTypeLocalServiceUtil;
100    import com.liferay.portlet.documentlibrary.service.persistence.DLFileEntryTypeUtil;
101    import com.liferay.portlet.documentlibrary.util.DLUtil;
102    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
103    import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
104    import com.liferay.portlet.dynamicdatamapping.service.persistence.DDMStructureUtil;
105    
106    import java.io.File;
107    import java.io.InputStream;
108    
109    import java.util.ArrayList;
110    import java.util.Calendar;
111    import java.util.Collections;
112    import java.util.Date;
113    import java.util.HashMap;
114    import java.util.LinkedHashMap;
115    import java.util.List;
116    import java.util.Locale;
117    import java.util.Map;
118    import java.util.regex.Matcher;
119    import java.util.regex.Pattern;
120    
121    import javax.portlet.PortletPreferences;
122    import javax.portlet.PortletRequest;
123    
124    import org.xml.sax.InputSource;
125    import org.xml.sax.XMLReader;
126    
127    /**
128     * @author Zsolt Berentey
129     * @author Levente Hud??k
130     * @author Julio Camarero
131     * @author Mate Thurzo
132     */
133    public class ExportImportHelperImpl implements ExportImportHelper {
134    
135            @Override
136            public long[] getAllLayoutIds(long groupId, boolean privateLayout) {
137                    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
138                            groupId, privateLayout);
139    
140                    return getLayoutIds(layouts);
141            }
142    
143            @Override
144            public Map<Long, Boolean> getAllLayoutIdsMap(
145                    long groupId, boolean privateLayout) {
146    
147                    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
148                            groupId, privateLayout, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
149    
150                    Map<Long, Boolean> layoutIdMap = new HashMap<>();
151    
152                    for (Layout layout : layouts) {
153                            layoutIdMap.put(layout.getPlid(), true);
154                    }
155    
156                    return layoutIdMap;
157            }
158    
159            /**
160             * @deprecated As of 7.0.0, moved to {@link
161             *             ExportImportDateUtil#getCalendar(PortletRequest, String,
162             *             boolean)}
163             */
164            @Deprecated
165            @Override
166            public Calendar getCalendar(
167                    PortletRequest portletRequest, String paramPrefix,
168                    boolean timeZoneSensitive) {
169    
170                    return ExportImportDateUtil.getCalendar(
171                            portletRequest, paramPrefix, timeZoneSensitive);
172            }
173    
174            /**
175             * @deprecated As of 7.0.0, moved to {@link
176             *             ExportImportDateUtil#getDateRange(PortletRequest, long,
177             *             boolean, long, String, String)}
178             */
179            @Deprecated
180            @Override
181            public DateRange getDateRange(
182                            PortletRequest portletRequest, long groupId, boolean privateLayout,
183                            long plid, String portletId, String defaultRange)
184                    throws Exception {
185    
186                    return ExportImportDateUtil.getDateRange(
187                            portletRequest, groupId, privateLayout, plid, portletId,
188                            defaultRange);
189            }
190    
191            @Override
192            public Layout getExportableLayout(ThemeDisplay themeDisplay)
193                    throws PortalException {
194    
195                    Layout layout = themeDisplay.getLayout();
196    
197                    if (!layout.isTypeControlPanel()) {
198                            return layout;
199                    }
200    
201                    Group scopeGroup = themeDisplay.getScopeGroup();
202    
203                    if (scopeGroup.isLayout()) {
204                            layout = LayoutLocalServiceUtil.getLayout(scopeGroup.getClassPK());
205                    }
206                    else if (!scopeGroup.isCompany()) {
207                            long defaultPlid = LayoutLocalServiceUtil.getDefaultPlid(
208                                    themeDisplay.getSiteGroupId());
209    
210                            if (defaultPlid > 0) {
211                                    layout = LayoutLocalServiceUtil.getLayout(defaultPlid);
212                            }
213                    }
214    
215                    return layout;
216            }
217    
218            @Override
219            public String getExportableRootPortletId(long companyId, String portletId)
220                    throws Exception {
221    
222                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
223                            companyId, portletId);
224    
225                    if ((portlet == null) || portlet.isUndeployedPortlet()) {
226                            return null;
227                    }
228    
229                    return PortletConstants.getRootPortletId(portletId);
230            }
231    
232            /**
233             * @deprecated As of 7.0.0, replaced by {@link
234             *             #getExportPortletControlsMap(long, String, Map)}
235             */
236            @Deprecated
237            @Override
238            public boolean[] getExportPortletControls(
239                            long companyId, String portletId,
240                            Map<String, String[]> parameterMap)
241                    throws Exception {
242    
243                    return getExportPortletControls(
244                            companyId, portletId, parameterMap, "layout-set");
245            }
246    
247            /**
248             * @deprecated As of 7.0.0, replaced by {@link
249             *             #getExportPortletControlsMap(long, String, Map, String)}
250             */
251            @Deprecated
252            @Override
253            public boolean[] getExportPortletControls(
254                            long companyId, String portletId,
255                            Map<String, String[]> parameterMap, String type)
256                    throws Exception {
257    
258                    Map<String, Boolean> exportPortletControlsMap =
259                            getExportPortletControlsMap(
260                                    companyId, portletId, parameterMap, type);
261    
262                    return new boolean[] {
263                            exportPortletControlsMap.get(
264                                    PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
265                            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
266                            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
267                            exportPortletControlsMap.get(
268                                    PortletDataHandlerKeys.PORTLET_USER_PREFERENCES)
269                    };
270            }
271    
272            @Override
273            public Map<String, Boolean> getExportPortletControlsMap(
274                            long companyId, String portletId,
275                            Map<String, String[]> parameterMap)
276                    throws Exception {
277    
278                    return getExportPortletControlsMap(
279                            companyId, portletId, parameterMap, "layout-set");
280            }
281    
282            @Override
283            public Map<String, Boolean> getExportPortletControlsMap(
284                            long companyId, String portletId,
285                            Map<String, String[]> parameterMap, String type)
286                    throws Exception {
287    
288                    Map<String, Boolean> exportPortletControlsMap = new HashMap<>();
289    
290                    boolean exportPortletData = getExportPortletData(
291                            companyId, portletId, parameterMap);
292    
293                    exportPortletControlsMap.put(
294                            PortletDataHandlerKeys.PORTLET_DATA, exportPortletData);
295    
296                    exportPortletControlsMap.putAll(
297                            getExportPortletSetupControlsMap(
298                                    companyId, portletId, parameterMap, type));
299    
300                    return exportPortletControlsMap;
301            }
302    
303            /**
304             * @deprecated As of 7.0.0, replaced by {@link
305             *             #getImportPortletControlsMap(long, String, Map, Element,
306             *             ManifestSummary)}
307             */
308            @Deprecated
309            @Override
310            public boolean[] getImportPortletControls(
311                            long companyId, String portletId,
312                            Map<String, String[]> parameterMap, Element portletDataElement)
313                    throws Exception {
314    
315                    return getImportPortletControls(
316                            companyId, portletId, parameterMap, portletDataElement, null);
317            }
318    
319            /**
320             * @deprecated As of 7.0.0, replaced by {@link
321             *             #getImportPortletControlsMap(long, String, Map, Element,
322             *             ManifestSummary)}
323             */
324            @Deprecated
325            @Override
326            public boolean[] getImportPortletControls(
327                            long companyId, String portletId,
328                            Map<String, String[]> parameterMap, Element portletDataElement,
329                            ManifestSummary manifestSummary)
330                    throws Exception {
331    
332                    Map<String, Boolean> importPortletControlsMap =
333                            getImportPortletControlsMap(
334                                    companyId, portletId, parameterMap, portletDataElement,
335                                    manifestSummary);
336    
337                    return new boolean[] {
338                            importPortletControlsMap.get(
339                                    PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
340                            importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
341                            importPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
342                            importPortletControlsMap.get(
343                                    PortletDataHandlerKeys.PORTLET_USER_PREFERENCES)
344                    };
345            }
346    
347            @Override
348            public Map<String, Boolean> getImportPortletControlsMap(
349                            long companyId, String portletId,
350                            Map<String, String[]> parameterMap, Element portletDataElement,
351                            ManifestSummary manifestSummary)
352                    throws Exception {
353    
354                    boolean importCurPortletData = getImportPortletData(
355                            companyId, portletId, parameterMap, portletDataElement);
356    
357                    Map<String, Boolean> importPortletControlsMap = new HashMap<>();
358    
359                    importPortletControlsMap.put(
360                            PortletDataHandlerKeys.PORTLET_DATA, importCurPortletData);
361    
362                    importPortletControlsMap.putAll(
363                            getImportPortletSetupControlsMap(
364                                    companyId, portletId, parameterMap, manifestSummary));
365    
366                    return importPortletControlsMap;
367            }
368    
369            @Override
370            public Map<Long, Boolean> getLayoutIdMap(PortletRequest portletRequest)
371                    throws PortalException {
372    
373                    Map<Long, Boolean> layoutIdMap = new LinkedHashMap<>();
374    
375                    String layoutIdsJSON = ParamUtil.getString(portletRequest, "layoutIds");
376    
377                    if (Validator.isNull(layoutIdsJSON)) {
378                            return layoutIdMap;
379                    }
380    
381                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray(layoutIdsJSON);
382    
383                    for (int i = 0; i < jsonArray.length(); ++i) {
384                            JSONObject jsonObject = jsonArray.getJSONObject(i);
385    
386                            long plid = jsonObject.getLong("plid");
387                            boolean includeChildren = jsonObject.getBoolean("includeChildren");
388    
389                            layoutIdMap.put(plid, includeChildren);
390                    }
391    
392                    return layoutIdMap;
393            }
394    
395            @Override
396            public long[] getLayoutIds(List<Layout> layouts) {
397                    long[] layoutIds = new long[layouts.size()];
398    
399                    for (int i = 0; i < layouts.size(); i++) {
400                            Layout layout = layouts.get(i);
401    
402                            layoutIds[i] = layout.getLayoutId();
403                    }
404    
405                    return layoutIds;
406            }
407    
408            @Override
409            public long[] getLayoutIds(Map<Long, Boolean> layoutIdMap)
410                    throws PortalException {
411    
412                    return getLayoutIds(layoutIdMap, GroupConstants.DEFAULT_LIVE_GROUP_ID);
413            }
414    
415            @Override
416            public long[] getLayoutIds(
417                            Map<Long, Boolean> layoutIdMap, long targetGroupId)
418                    throws PortalException {
419    
420                    if (MapUtil.isEmpty(layoutIdMap)) {
421                            return new long[0];
422                    }
423    
424                    List<Layout> layouts = new ArrayList<>();
425    
426                    for (Map.Entry<Long, Boolean> entry : layoutIdMap.entrySet()) {
427                            long plid = GetterUtil.getLong(String.valueOf(entry.getKey()));
428                            boolean includeChildren = entry.getValue();
429    
430                            Layout layout = LayoutLocalServiceUtil.getLayout(plid);
431    
432                            if (!layouts.contains(layout)) {
433                                    layouts.add(layout);
434                            }
435    
436                            List<Layout> parentLayouts = Collections.emptyList();
437    
438                            if (targetGroupId != GroupConstants.DEFAULT_LIVE_GROUP_ID) {
439                                    parentLayouts = getMissingParentLayouts(layout, targetGroupId);
440                            }
441    
442                            for (Layout parentLayout : parentLayouts) {
443                                    if (!layouts.contains(parentLayout)) {
444                                            layouts.add(parentLayout);
445                                    }
446                            }
447    
448                            if (includeChildren) {
449                                    for (Layout childLayout : layout.getAllChildren()) {
450                                            if (!layouts.contains(childLayout)) {
451                                                    layouts.add(childLayout);
452                                            }
453                                    }
454                            }
455                    }
456    
457                    return getLayoutIds(layouts);
458            }
459    
460            @Override
461            public long[] getLayoutIds(PortletRequest portletRequest)
462                    throws PortalException {
463    
464                    return getLayoutIds(
465                            getLayoutIdMap(portletRequest),
466                            GroupConstants.DEFAULT_LIVE_GROUP_ID);
467            }
468    
469            @Override
470            public long[] getLayoutIds(
471                            PortletRequest portletRequest, long targetGroupId)
472                    throws PortalException {
473    
474                    return getLayoutIds(getLayoutIdMap(portletRequest), targetGroupId);
475            }
476    
477            @Override
478            public ZipWriter getLayoutSetZipWriter(long groupId) {
479                    StringBundler sb = new StringBundler(4);
480    
481                    sb.append(groupId);
482                    sb.append(StringPool.DASH);
483                    sb.append(Time.getShortTimestamp());
484                    sb.append(".lar");
485    
486                    return getZipWriter(sb.toString());
487            }
488    
489            /**
490             * @deprecated As of 7.0.0, replaced by {@link
491             *             #getManifestSummary(PortletDataContext)}
492             */
493            @Deprecated
494            @Override
495            public ManifestSummary getManifestSummary(
496                            long userId, long groupId, Map<String, String[]> parameterMap,
497                            File file)
498                    throws Exception {
499    
500                    final Group group = GroupLocalServiceUtil.getGroup(groupId);
501                    String userIdStrategy = MapUtil.getString(
502                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
503                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
504    
505                    PortletDataContext portletDataContext =
506                            PortletDataContextFactoryUtil.createImportPortletDataContext(
507                                    group.getCompanyId(), groupId, parameterMap,
508                                    getUserIdStrategy(userId, userIdStrategy), zipReader);
509    
510                    try {
511                            return getManifestSummary(portletDataContext);
512                    }
513                    finally {
514                            zipReader.close();
515                    }
516            }
517    
518            @Override
519            public ManifestSummary getManifestSummary(
520                            long userId, long groupId, Map<String, String[]> parameterMap,
521                            FileEntry fileEntry)
522                    throws Exception {
523    
524                    File file = FileUtil.createTempFile("lar");
525                    InputStream inputStream = DLFileEntryLocalServiceUtil.getFileAsStream(
526                            fileEntry.getFileEntryId(), fileEntry.getVersion(), false);
527                    ZipReader zipReader = null;
528    
529                    ManifestSummary manifestSummary = null;
530    
531                    try {
532                            FileUtil.write(file, inputStream);
533    
534                            Group group = GroupLocalServiceUtil.getGroup(groupId);
535                            String userIdStrategy = MapUtil.getString(
536                                    parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
537    
538                            zipReader = ZipReaderFactoryUtil.getZipReader(file);
539    
540                            PortletDataContext portletDataContext =
541                                    PortletDataContextFactoryUtil.createImportPortletDataContext(
542                                            group.getCompanyId(), groupId, parameterMap,
543                                            getUserIdStrategy(userId, userIdStrategy), zipReader);
544    
545                            manifestSummary = getManifestSummary(portletDataContext);
546                    }
547                    finally {
548                            StreamUtil.cleanUp(inputStream);
549    
550                            if (zipReader != null) {
551                                    zipReader.close();
552                            }
553    
554                            FileUtil.delete(file);
555                    }
556    
557                    return manifestSummary;
558            }
559    
560            @Override
561            public ManifestSummary getManifestSummary(
562                            PortletDataContext portletDataContext)
563                    throws Exception {
564    
565                    XMLReader xmlReader = SecureXMLFactoryProviderUtil.newXMLReader();
566    
567                    Group group = GroupLocalServiceUtil.getGroup(
568                            portletDataContext.getGroupId());
569                    ManifestSummary manifestSummary = new ManifestSummary();
570    
571                    ElementHandler elementHandler = new ElementHandler(
572                            new ManifestSummaryElementProcessor(group, manifestSummary),
573                            new String[] {"header", "portlet", "staged-model"});
574    
575                    xmlReader.setContentHandler(elementHandler);
576    
577                    xmlReader.parse(
578                            new InputSource(
579                                    portletDataContext.getZipEntryAsInputStream("/manifest.xml")));
580    
581                    return manifestSummary;
582            }
583    
584            /**
585             * @see com.liferay.portal.lar.backgroundtask.LayoutRemoteStagingBackgroundTaskExecutor#getMissingRemoteParentLayouts(
586             *      com.liferay.portal.security.auth.HttpPrincipal, Layout, long)
587             */
588            @Override
589            public List<Layout> getMissingParentLayouts(Layout layout, long liveGroupId)
590                    throws PortalException {
591    
592                    List<Layout> missingParentLayouts = new ArrayList<>();
593    
594                    long parentLayoutId = layout.getParentLayoutId();
595    
596                    Layout parentLayout = null;
597    
598                    while (parentLayoutId > 0) {
599                            parentLayout = LayoutLocalServiceUtil.getLayout(
600                                    layout.getGroupId(), layout.isPrivateLayout(), parentLayoutId);
601    
602                            try {
603                                    LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(
604                                            parentLayout.getUuid(), liveGroupId,
605                                            parentLayout.isPrivateLayout());
606    
607                                    // If one parent is found, all others are assumed to exist
608    
609                                    break;
610                            }
611                            catch (NoSuchLayoutException nsle) {
612                                    missingParentLayouts.add(parentLayout);
613    
614                                    parentLayoutId = parentLayout.getParentLayoutId();
615                            }
616                    }
617    
618                    return missingParentLayouts;
619            }
620    
621            @Override
622            public long getModelDeletionCount(
623                            final PortletDataContext portletDataContext,
624                            final StagedModelType stagedModelType)
625                    throws PortalException {
626    
627                    ActionableDynamicQuery actionableDynamicQuery =
628                            SystemEventLocalServiceUtil.getActionableDynamicQuery();
629    
630                    actionableDynamicQuery.setAddCriteriaMethod(
631                            new ActionableDynamicQuery.AddCriteriaMethod() {
632    
633                                    @Override
634                                    public void addCriteria(DynamicQuery dynamicQuery) {
635                                            doAddCriteria(
636                                                    portletDataContext, stagedModelType, dynamicQuery);
637                                    }
638    
639                            });
640                    actionableDynamicQuery.setCompanyId(portletDataContext.getCompanyId());
641    
642                    return actionableDynamicQuery.performCount();
643            }
644    
645            @Override
646            public ZipWriter getPortletZipWriter(String portletId) {
647                    StringBundler sb = new StringBundler(4);
648    
649                    sb.append(portletId);
650                    sb.append(StringPool.DASH);
651                    sb.append(Time.getShortTimestamp());
652                    sb.append(".lar");
653    
654                    return getZipWriter(sb.toString());
655            }
656    
657            @Override
658            public String getSelectedLayoutsJSON(
659                    long groupId, boolean privateLayout, String selectedNodes) {
660    
661                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
662    
663                    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
664                            groupId, privateLayout, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
665    
666                    for (Layout layout : layouts) {
667                            populateLayoutsJSON(
668                                    jsonArray, layout, StringUtil.split(selectedNodes, 0L));
669                    }
670    
671                    return jsonArray.toString();
672            }
673    
674            @Override
675            public FileEntry getTempFileEntry(
676                            long groupId, long userId, String folderName)
677                    throws PortalException {
678    
679                    String[] tempFileNames = LayoutServiceUtil.getTempFileNames(
680                            groupId, folderName);
681    
682                    if (tempFileNames.length == 0) {
683                            return null;
684                    }
685    
686                    return TempFileEntryUtil.getTempFileEntry(
687                            groupId, userId,
688                            DigesterUtil.digestHex(Digester.SHA_256, folderName),
689                            tempFileNames[0]);
690            }
691    
692            @Override
693            public UserIdStrategy getUserIdStrategy(long userId, String userIdStrategy)
694                    throws PortalException {
695    
696                    User user = UserLocalServiceUtil.getUserById(userId);
697    
698                    if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) {
699                            return new AlwaysCurrentUserIdStrategy(user);
700                    }
701    
702                    return new CurrentUserIdStrategy(user);
703            }
704    
705            @Override
706            public boolean isReferenceWithinExportScope(
707                    PortletDataContext portletDataContext, StagedModel stagedModel) {
708    
709                    if (!(stagedModel instanceof StagedGroupedModel)) {
710                            return true;
711                    }
712    
713                    StagedGroupedModel stagedGroupedModel = (StagedGroupedModel)stagedModel;
714    
715                    if (portletDataContext.getGroupId() ==
716                                    stagedGroupedModel.getGroupId()) {
717    
718                            return true;
719                    }
720    
721                    Group group = null;
722    
723                    try {
724                            group = GroupLocalServiceUtil.getGroup(
725                                    stagedGroupedModel.getGroupId());
726                    }
727                    catch (Exception e) {
728                            return false;
729                    }
730    
731                    String className = group.getClassName();
732    
733                    if (className.equals(Layout.class.getName())) {
734                            Layout scopeLayout = null;
735    
736                            try {
737                                    scopeLayout = LayoutLocalServiceUtil.getLayout(
738                                            group.getClassPK());
739                            }
740                            catch (Exception e) {
741                                    return false;
742                            }
743    
744                            if (scopeLayout.getGroupId() == portletDataContext.getGroupId()) {
745                                    return true;
746                            }
747                    }
748    
749                    return false;
750            }
751    
752            /**
753             * @deprecated As of 7.0.0, replaced by {@link
754             *             #replaceExportContentReferences(PortletDataContext,
755             *             StagedModel, String, boolean)}
756             */
757            @Deprecated
758            @Override
759            public String replaceExportContentReferences(
760                            PortletDataContext portletDataContext,
761                            StagedModel entityStagedModel, Element entityElement,
762                            String content, boolean exportReferencedContent)
763                    throws Exception {
764    
765                    return replaceExportContentReferences(
766                            portletDataContext, entityStagedModel, content,
767                            exportReferencedContent);
768            }
769    
770            @Override
771            public String replaceExportContentReferences(
772                            PortletDataContext portletDataContext,
773                            StagedModel entityStagedModel, String content,
774                            boolean exportReferencedContent)
775                    throws Exception {
776    
777                    return replaceExportContentReferences(
778                            portletDataContext, entityStagedModel, content,
779                            exportReferencedContent, true);
780            }
781    
782            @Override
783            public String replaceExportContentReferences(
784                            PortletDataContext portletDataContext,
785                            StagedModel entityStagedModel, String content,
786                            boolean exportReferencedContent, boolean escapeContent)
787                    throws Exception {
788    
789                    content = replaceExportDLReferences(
790                            portletDataContext, entityStagedModel, content,
791                            exportReferencedContent);
792    
793                    content = replaceExportLayoutReferences(portletDataContext, content);
794                    content = replaceExportLinksToLayouts(
795                            portletDataContext, entityStagedModel, content);
796    
797                    if (escapeContent) {
798                            content = StringUtil.replace(
799                                    content, StringPool.AMPERSAND_ENCODED, StringPool.AMPERSAND);
800                    }
801    
802                    return content;
803            }
804    
805            /**
806             * @deprecated As of 7.0.0, replaced by {@link
807             *             #replaceExportDLReferences(PortletDataContext, StagedModel,
808             *             String, boolean)}
809             */
810            @Deprecated
811            @Override
812            public String replaceExportDLReferences(
813                            PortletDataContext portletDataContext,
814                            StagedModel entityStagedModel, Element entityElement,
815                            String content, boolean exportReferencedContent)
816                    throws Exception {
817    
818                    return replaceExportDLReferences(
819                            portletDataContext, entityStagedModel, content,
820                            exportReferencedContent);
821            }
822    
823            @Override
824            public String replaceExportDLReferences(
825                            PortletDataContext portletDataContext,
826                            StagedModel entityStagedModel, String content,
827                            boolean exportReferencedContent)
828                    throws Exception {
829    
830                    Group group = GroupLocalServiceUtil.getGroup(
831                            portletDataContext.getGroupId());
832    
833                    if (group.isStagingGroup()) {
834                            group = group.getLiveGroup();
835                    }
836    
837                    if (group.isStaged() && !group.isStagedRemotely() &&
838                            !group.isStagedPortlet(PortletKeys.DOCUMENT_LIBRARY)) {
839    
840                            return content;
841                    }
842    
843                    StringBuilder sb = new StringBuilder(content);
844    
845                    String contextPath = PortalUtil.getPathContext();
846    
847                    String[] patterns = {
848                            contextPath.concat("/c/document_library/get_file?"),
849                            contextPath.concat("/documents/"),
850                            contextPath.concat("/image/image_gallery?")
851                    };
852    
853                    int beginPos = -1;
854                    int endPos = content.length();
855    
856                    while (true) {
857                            beginPos = StringUtil.lastIndexOfAny(content, patterns, endPos);
858    
859                            if (beginPos == -1) {
860                                    break;
861                            }
862    
863                            Map<String, String[]> dlReferenceParameters =
864                                    getDLReferenceParameters(
865                                            portletDataContext, content,
866                                            beginPos + contextPath.length(), endPos);
867    
868                            FileEntry fileEntry = getFileEntry(dlReferenceParameters);
869    
870                            if (fileEntry == null) {
871                                    endPos = beginPos - 1;
872    
873                                    continue;
874                            }
875    
876                            endPos = MapUtil.getInteger(dlReferenceParameters, "endPos");
877    
878                            try {
879                                    if (exportReferencedContent) {
880                                            StagedModelDataHandlerUtil.exportReferenceStagedModel(
881                                                    portletDataContext, entityStagedModel, fileEntry,
882                                                    PortletDataContext.REFERENCE_TYPE_DEPENDENCY);
883                                    }
884                                    else {
885                                            Element entityElement =
886                                                    portletDataContext.getExportDataElement(
887                                                            entityStagedModel);
888    
889                                            portletDataContext.addReferenceElement(
890                                                    entityStagedModel, entityElement, fileEntry,
891                                                    PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
892                                    }
893    
894                                    String path = ExportImportPathUtil.getModelPath(fileEntry);
895    
896                                    sb.replace(beginPos, endPos, "[$dl-reference=" + path + "$]");
897    
898                                    deleteTimestampParameters(sb, beginPos);
899                            }
900                            catch (Exception e) {
901                                    if (_log.isDebugEnabled()) {
902                                            _log.debug(e, e);
903                                    }
904                                    else if (_log.isWarnEnabled()) {
905                                            _log.warn(e.getMessage());
906                                    }
907                            }
908    
909                            endPos = beginPos - 1;
910                    }
911    
912                    return sb.toString();
913            }
914    
915            @Override
916            public String replaceExportLayoutReferences(
917                            PortletDataContext portletDataContext, String content)
918                    throws Exception {
919    
920                    Group group = GroupLocalServiceUtil.getGroup(
921                            portletDataContext.getScopeGroupId());
922    
923                    StringBuilder sb = new StringBuilder(content);
924    
925                    String[] patterns = {"href=", "[["};
926    
927                    int beginPos = -1;
928                    int endPos = content.length();
929                    int offset = 0;
930    
931                    while (true) {
932                            if (beginPos > -1) {
933                                    endPos = beginPos - 1;
934                            }
935    
936                            beginPos = StringUtil.lastIndexOfAny(content, patterns, endPos);
937    
938                            if (beginPos == -1) {
939                                    break;
940                            }
941    
942                            if (content.startsWith("href=", beginPos)) {
943                                    offset = 5;
944    
945                                    char c = content.charAt(beginPos + offset);
946    
947                                    if ((c == CharPool.APOSTROPHE) || (c == CharPool.QUOTE)) {
948                                            offset++;
949                                    }
950                            }
951                            else if (content.charAt(beginPos) == CharPool.OPEN_BRACKET) {
952                                    offset = 2;
953                            }
954    
955                            endPos = StringUtil.indexOfAny(
956                                    content, _LAYOUT_REFERENCE_STOP_CHARS, beginPos + offset,
957                                    endPos);
958    
959                            if (endPos == -1) {
960                                    continue;
961                            }
962    
963                            String url = content.substring(beginPos + offset, endPos);
964    
965                            StringBundler urlSB = new StringBundler(5);
966    
967                            try {
968                                    url = replaceExportHostname(portletDataContext, url, urlSB);
969    
970                                    if (!url.startsWith(StringPool.SLASH)) {
971                                            continue;
972                                    }
973    
974                                    String pathContext = PortalUtil.getPathContext();
975    
976                                    if (pathContext.length() > 1) {
977                                            if (!url.startsWith(pathContext)) {
978                                                    continue;
979                                            }
980    
981                                            urlSB.append(DATA_HANDLER_PATH_CONTEXT);
982    
983                                            url = url.substring(pathContext.length());
984                                    }
985    
986                                    if (!url.startsWith(StringPool.SLASH)) {
987                                            continue;
988                                    }
989    
990                                    int pos = url.indexOf(StringPool.SLASH, 1);
991    
992                                    String localePath = StringPool.BLANK;
993    
994                                    Locale locale = null;
995    
996                                    if (pos != -1) {
997                                            localePath = url.substring(0, pos);
998    
999                                            locale = LocaleUtil.fromLanguageId(
1000                                                    localePath.substring(1), true, false);
1001                                    }
1002    
1003                                    if (locale != null) {
1004                                            String urlWithoutLocale = url.substring(
1005                                                    localePath.length());
1006    
1007                                            if (urlWithoutLocale.startsWith(
1008                                                            _PRIVATE_GROUP_SERVLET_MAPPING) ||
1009                                                    urlWithoutLocale.startsWith(
1010                                                            _PRIVATE_USER_SERVLET_MAPPING) ||
1011                                                    urlWithoutLocale.startsWith(
1012                                                            _PUBLIC_GROUP_SERVLET_MAPPING)) {
1013    
1014                                                    urlSB.append(localePath);
1015    
1016                                                    url = urlWithoutLocale;
1017                                            }
1018                                    }
1019    
1020                                    if (url.startsWith(_PRIVATE_GROUP_SERVLET_MAPPING)) {
1021                                            urlSB.append(DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING);
1022    
1023                                            url = url.substring(
1024                                                    _PRIVATE_GROUP_SERVLET_MAPPING.length() - 1);
1025                                    }
1026                                    else if (url.startsWith(_PRIVATE_USER_SERVLET_MAPPING)) {
1027                                            urlSB.append(DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING);
1028    
1029                                            url = url.substring(
1030                                                    _PRIVATE_USER_SERVLET_MAPPING.length() - 1);
1031                                    }
1032                                    else if (url.startsWith(_PUBLIC_GROUP_SERVLET_MAPPING)) {
1033                                            urlSB.append(DATA_HANDLER_PUBLIC_SERVLET_MAPPING);
1034    
1035                                            url = url.substring(
1036                                                    _PUBLIC_GROUP_SERVLET_MAPPING.length() - 1);
1037                                    }
1038                                    else {
1039                                            String urlSBString = urlSB.toString();
1040    
1041                                            LayoutSet layoutSet = null;
1042    
1043                                            if (urlSBString.contains(
1044                                                            DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL) ||
1045                                                    urlSBString.contains(
1046                                                            DATA_HANDLER_PUBLIC_LAYOUT_SET_URL)) {
1047    
1048                                                    layoutSet = group.getPublicLayoutSet();
1049                                            }
1050                                            else if (urlSBString.contains(
1051                                                                    DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL) ||
1052                                                             urlSBString.contains(
1053                                                                     DATA_HANDLER_PRIVATE_LAYOUT_SET_URL)) {
1054    
1055                                                    layoutSet = group.getPrivateLayoutSet();
1056                                            }
1057    
1058                                            if (layoutSet == null) {
1059                                                    continue;
1060                                            }
1061    
1062                                            boolean privateLayout = layoutSet.isPrivateLayout();
1063    
1064                                            LayoutFriendlyURL layoutFriendlyUrl =
1065                                                    LayoutFriendlyURLLocalServiceUtil.
1066                                                            fetchFirstLayoutFriendlyURL(
1067                                                                    group.getGroupId(), privateLayout, url);
1068    
1069                                            if (layoutFriendlyUrl == null) {
1070                                                    continue;
1071                                            }
1072    
1073                                            if (privateLayout) {
1074                                                    if (group.isUser()) {
1075                                                            urlSB.append(
1076                                                                    DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING);
1077                                                    }
1078                                                    else {
1079                                                            urlSB.append(
1080                                                                    DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING);
1081                                                    }
1082                                            }
1083                                            else {
1084                                                    urlSB.append(DATA_HANDLER_PUBLIC_SERVLET_MAPPING);
1085                                            }
1086    
1087                                            urlSB.append(DATA_HANDLER_GROUP_FRIENDLY_URL);
1088    
1089                                            continue;
1090                                    }
1091    
1092                                    String groupFriendlyURL = group.getFriendlyURL();
1093    
1094                                    if (url.equals(groupFriendlyURL) ||
1095                                            url.startsWith(groupFriendlyURL + StringPool.SLASH)) {
1096    
1097                                            urlSB.append(DATA_HANDLER_GROUP_FRIENDLY_URL);
1098    
1099                                            url = url.substring(groupFriendlyURL.length());
1100                                    }
1101                            }
1102                            finally {
1103                                    if (urlSB.length() > 0) {
1104                                            urlSB.append(url);
1105    
1106                                            url = urlSB.toString();
1107                                    }
1108    
1109                                    sb.replace(beginPos + offset, endPos, url);
1110                            }
1111                    }
1112    
1113                    return sb.toString();
1114            }
1115    
1116            /**
1117             * @deprecated As of 7.0.0, replaced by {@link
1118             *             #replaceExportLayoutReferences(PortletDataContext, String)}
1119             */
1120            @Deprecated
1121            @Override
1122            public String replaceExportLayoutReferences(
1123                            PortletDataContext portletDataContext, String content,
1124                            boolean exportReferencedContent)
1125                    throws Exception {
1126    
1127                    return replaceExportLayoutReferences(portletDataContext, content);
1128            }
1129    
1130            /**
1131             * @deprecated As of 7.0.0, replaced by {@link
1132             *             #replaceExportLinksToLayouts(PortletDataContext, StagedModel,
1133             *             String)}
1134             */
1135            @Deprecated
1136            @Override
1137            public String replaceExportLinksToLayouts(
1138                            PortletDataContext portletDataContext,
1139                            StagedModel entityStagedModel, Element entityElement,
1140                            String content, boolean exportReferencedContent)
1141                    throws Exception {
1142    
1143                    return replaceExportLinksToLayouts(
1144                            portletDataContext, entityStagedModel, content);
1145            }
1146    
1147            @Override
1148            public String replaceExportLinksToLayouts(
1149                            PortletDataContext portletDataContext,
1150                            StagedModel entityStagedModel, String content)
1151                    throws Exception {
1152    
1153                    List<String> oldLinksToLayout = new ArrayList<>();
1154                    List<String> newLinksToLayout = new ArrayList<>();
1155    
1156                    Matcher matcher = _exportLinksToLayoutPattern.matcher(content);
1157    
1158                    while (matcher.find()) {
1159                            long layoutId = GetterUtil.getLong(matcher.group(1));
1160    
1161                            String type = matcher.group(2);
1162    
1163                            boolean privateLayout = type.startsWith("private");
1164    
1165                            try {
1166                                    Layout layout = LayoutLocalServiceUtil.getLayout(
1167                                            portletDataContext.getScopeGroupId(), privateLayout,
1168                                            layoutId);
1169    
1170                                    String oldLinkToLayout = matcher.group(0);
1171    
1172                                    StringBundler sb = new StringBundler(5);
1173    
1174                                    sb.append(type);
1175                                    sb.append(StringPool.AT);
1176                                    sb.append(layout.getPlid());
1177    
1178                                    String newLinkToLayout = StringUtil.replace(
1179                                            oldLinkToLayout, type, sb.toString());
1180    
1181                                    oldLinksToLayout.add(oldLinkToLayout);
1182                                    newLinksToLayout.add(newLinkToLayout);
1183    
1184                                    Element entityElement = portletDataContext.getExportDataElement(
1185                                            entityStagedModel);
1186    
1187                                    portletDataContext.addReferenceElement(
1188                                            entityStagedModel, entityElement, layout,
1189                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1190                            }
1191                            catch (Exception e) {
1192                                    if (_log.isDebugEnabled() || _log.isWarnEnabled()) {
1193                                            String message =
1194                                                    "Unable to get layout with ID " + layoutId +
1195                                                            " in group " + portletDataContext.getScopeGroupId();
1196    
1197                                            if (_log.isDebugEnabled()) {
1198                                                    _log.debug(message, e);
1199                                            }
1200                                            else {
1201                                                    _log.warn(message);
1202                                            }
1203                                    }
1204                            }
1205                    }
1206    
1207                    content = StringUtil.replace(
1208                            content, ArrayUtil.toStringArray(oldLinksToLayout.toArray()),
1209                            ArrayUtil.toStringArray(newLinksToLayout.toArray()));
1210    
1211                    return content;
1212            }
1213    
1214            /**
1215             * @deprecated As of 7.0.0, replaced by {@link
1216             *             #replaceImportContentReferences(PortletDataContext,
1217             *             StagedModel, String)}
1218             */
1219            @Deprecated
1220            @Override
1221            public String replaceImportContentReferences(
1222                            PortletDataContext portletDataContext, Element entityElement,
1223                            String content, boolean importReferencedContent)
1224                    throws Exception {
1225    
1226                    return content;
1227            }
1228    
1229            @Override
1230            public String replaceImportContentReferences(
1231                            PortletDataContext portletDataContext,
1232                            StagedModel entityStagedModel, String content)
1233                    throws Exception {
1234    
1235                    content = replaceImportDLReferences(
1236                            portletDataContext, entityStagedModel, content);
1237    
1238                    content = replaceImportLayoutReferences(portletDataContext, content);
1239                    content = replaceImportLinksToLayouts(portletDataContext, content);
1240    
1241                    return content;
1242            }
1243    
1244            /**
1245             * @deprecated As of 7.0.0, replaced by {@link
1246             *             #replaceImportDLReferences(PortletDataContext, StagedModel,
1247             *             String)}
1248             */
1249            @Deprecated
1250            @Override
1251            public String replaceImportDLReferences(
1252                            PortletDataContext portletDataContext, Element entityElement,
1253                            String content, boolean importReferencedContent)
1254                    throws Exception {
1255    
1256                    return content;
1257            }
1258    
1259            @Override
1260            public String replaceImportDLReferences(
1261                            PortletDataContext portletDataContext,
1262                            StagedModel entityStagedModel, String content)
1263                    throws Exception {
1264    
1265                    List<Element> referenceElements =
1266                            portletDataContext.getReferenceElements(
1267                                    entityStagedModel, DLFileEntry.class);
1268    
1269                    for (Element referenceElement : referenceElements) {
1270                            long classPK = GetterUtil.getLong(
1271                                    referenceElement.attributeValue("class-pk"));
1272    
1273                            Element referenceDataElement =
1274                                    portletDataContext.getReferenceDataElement(
1275                                            entityStagedModel, DLFileEntry.class, classPK);
1276    
1277                            String path = null;
1278    
1279                            if (referenceDataElement != null) {
1280                                    path = referenceDataElement.attributeValue("path");
1281                            }
1282    
1283                            long groupId = GetterUtil.getLong(
1284                                    referenceElement.attributeValue("group-id"));
1285    
1286                            if (Validator.isNull(path)) {
1287                                    String className = referenceElement.attributeValue(
1288                                            "class-name");
1289    
1290                                    path = ExportImportPathUtil.getModelPath(
1291                                            groupId, className, classPK);
1292                            }
1293    
1294                            if (!content.contains("[$dl-reference=" + path + "$]")) {
1295                                    continue;
1296                            }
1297    
1298                            StagedModelDataHandlerUtil.importReferenceStagedModel(
1299                                    portletDataContext, entityStagedModel, DLFileEntry.class,
1300                                    classPK);
1301    
1302                            Map<Long, Long> dlFileEntryIds =
1303                                    (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1304                                            DLFileEntry.class);
1305    
1306                            long fileEntryId = MapUtil.getLong(
1307                                    dlFileEntryIds, classPK, classPK);
1308    
1309                            FileEntry importedFileEntry = null;
1310    
1311                            try {
1312                                    importedFileEntry = DLAppLocalServiceUtil.getFileEntry(
1313                                            fileEntryId);
1314                            }
1315                            catch (PortalException pe) {
1316                                    if (_log.isDebugEnabled()) {
1317                                            _log.debug(pe, pe);
1318                                    }
1319                                    else if (_log.isWarnEnabled()) {
1320                                            _log.warn(pe.getMessage());
1321                                    }
1322    
1323                                    continue;
1324                            }
1325    
1326                            String url = DLUtil.getPreviewURL(
1327                                    importedFileEntry, importedFileEntry.getFileVersion(), null,
1328                                    StringPool.BLANK, false, false);
1329    
1330                            content = StringUtil.replace(
1331                                    content, "[$dl-reference=" + path + "$]", url);
1332                    }
1333    
1334                    return content;
1335            }
1336    
1337            @Override
1338            public String replaceImportLayoutReferences(
1339                            PortletDataContext portletDataContext, String content)
1340                    throws Exception {
1341    
1342                    String companyPortalURL = StringPool.BLANK;
1343                    String privateLayoutSetPortalURL = StringPool.BLANK;
1344                    String publicLayoutSetPortalURL = StringPool.BLANK;
1345    
1346                    Group group = GroupLocalServiceUtil.getGroup(
1347                            portletDataContext.getScopeGroupId());
1348    
1349                    Company company = CompanyLocalServiceUtil.getCompany(
1350                            group.getCompanyId());
1351    
1352                    LayoutSet privateLayoutSet = group.getPrivateLayoutSet();
1353                    LayoutSet publicLayoutSet = group.getPublicLayoutSet();
1354    
1355                    int serverPort = PortalUtil.getPortalServerPort(false);
1356    
1357                    if (serverPort != -1) {
1358                            if (Validator.isNotNull(company.getVirtualHostname())) {
1359                                    companyPortalURL = PortalUtil.getPortalURL(
1360                                            company.getVirtualHostname(), serverPort, false);
1361                            }
1362    
1363                            if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
1364                                    privateLayoutSetPortalURL = PortalUtil.getPortalURL(
1365                                            privateLayoutSet.getVirtualHostname(), serverPort, false);
1366                            }
1367    
1368                            if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
1369                                    publicLayoutSetPortalURL = PortalUtil.getPortalURL(
1370                                            publicLayoutSet.getVirtualHostname(), serverPort, false);
1371                            }
1372                    }
1373    
1374                    int secureSecurePort = PortalUtil.getPortalServerPort(true);
1375    
1376                    String companySecurePortalURL = StringPool.BLANK;
1377                    String privateLayoutSetSecurePortalURL = StringPool.BLANK;
1378                    String publicLayoutSetSecurePortalURL = StringPool.BLANK;
1379    
1380                    if (secureSecurePort != -1) {
1381                            if (Validator.isNotNull(company.getVirtualHostname())) {
1382                                    companySecurePortalURL = PortalUtil.getPortalURL(
1383                                            company.getVirtualHostname(), secureSecurePort, true);
1384                            }
1385    
1386                            if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
1387                                    privateLayoutSetSecurePortalURL = PortalUtil.getPortalURL(
1388                                            privateLayoutSet.getVirtualHostname(), secureSecurePort,
1389                                            true);
1390                            }
1391    
1392                            if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
1393                                    publicLayoutSetSecurePortalURL = PortalUtil.getPortalURL(
1394                                            publicLayoutSet.getVirtualHostname(), secureSecurePort,
1395                                            true);
1396                            }
1397                    }
1398    
1399                    content = StringUtil.replace(
1400                            content, DATA_HANDLER_COMPANY_SECURE_URL, companySecurePortalURL);
1401                    content = StringUtil.replace(
1402                            content, DATA_HANDLER_COMPANY_URL, companyPortalURL);
1403                    content = StringUtil.replace(
1404                            content, DATA_HANDLER_GROUP_FRIENDLY_URL, group.getFriendlyURL());
1405                    content = StringUtil.replace(
1406                            content, DATA_HANDLER_PATH_CONTEXT, PortalUtil.getPathContext());
1407                    content = StringUtil.replace(
1408                            content, DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING,
1409                            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING);
1410                    content = StringUtil.replace(
1411                            content, DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL,
1412                            privateLayoutSetSecurePortalURL);
1413                    content = StringUtil.replace(
1414                            content, DATA_HANDLER_PRIVATE_LAYOUT_SET_URL,
1415                            privateLayoutSetPortalURL);
1416                    content = StringUtil.replace(
1417                            content, DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING,
1418                            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING);
1419                    content = StringUtil.replace(
1420                            content, DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL,
1421                            publicLayoutSetSecurePortalURL);
1422                    content = StringUtil.replace(
1423                            content, DATA_HANDLER_PUBLIC_LAYOUT_SET_URL,
1424                            publicLayoutSetPortalURL);
1425                    content = StringUtil.replace(
1426                            content, DATA_HANDLER_PUBLIC_SERVLET_MAPPING,
1427                            PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING);
1428    
1429                    return content;
1430            }
1431    
1432            /**
1433             * @deprecated As of 7.0.0, replaced by {@link
1434             *             #replaceImportLayoutReferences(PortletDataContext, String)}
1435             */
1436            @Deprecated
1437            @Override
1438            public String replaceImportLayoutReferences(
1439                            PortletDataContext portletDataContext, String content,
1440                            boolean importReferencedContent)
1441                    throws Exception {
1442    
1443                    return replaceImportLayoutReferences(portletDataContext, content);
1444            }
1445    
1446            @Override
1447            public String replaceImportLinksToLayouts(
1448                            PortletDataContext portletDataContext, String content)
1449                    throws Exception {
1450    
1451                    List<String> oldLinksToLayout = new ArrayList<>();
1452                    List<String> newLinksToLayout = new ArrayList<>();
1453    
1454                    Matcher matcher = _importLinksToLayoutPattern.matcher(content);
1455    
1456                    Map<Long, Long> layoutPlids =
1457                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1458                                    Layout.class);
1459    
1460                    String layoutsImportMode = MapUtil.getString(
1461                            portletDataContext.getParameterMap(),
1462                            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE,
1463                            PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID);
1464    
1465                    while (matcher.find()) {
1466                            long oldPlid = GetterUtil.getLong(matcher.group(4));
1467    
1468                            Long newPlid = MapUtil.getLong(layoutPlids, oldPlid);
1469    
1470                            long oldGroupId = GetterUtil.getLong(matcher.group(6));
1471    
1472                            long newGroupId = oldGroupId;
1473    
1474                            long oldLayoutId = GetterUtil.getLong(matcher.group(1));
1475    
1476                            long newLayoutId = oldLayoutId;
1477    
1478                            Layout layout = LayoutLocalServiceUtil.fetchLayout(newPlid);
1479    
1480                            if (layout != null) {
1481                                    newGroupId = layout.getGroupId();
1482                                    newLayoutId = layout.getLayoutId();
1483                            }
1484                            else if (_log.isWarnEnabled()) {
1485                                    _log.warn("Unable to get layout with plid " + oldPlid);
1486                            }
1487    
1488                            String oldLinkToLayout = matcher.group(0);
1489    
1490                            String newLinkToLayout = StringUtil.replaceFirst(
1491                                    oldLinkToLayout,
1492                                    new String[] {
1493                                            StringPool.AT + oldPlid, String.valueOf(oldLayoutId)
1494                                    },
1495                                    new String[] {StringPool.BLANK, String.valueOf(newLayoutId)});
1496    
1497                            if ((layout != null) && layout.isPublicLayout() &&
1498                                    layoutsImportMode.equals(
1499                                            PortletDataHandlerKeys.
1500                                                    LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {
1501    
1502                                    newLinkToLayout = StringUtil.replace(
1503                                            newLinkToLayout, "private-group", "public");
1504                            }
1505    
1506                            if ((oldGroupId != 0) && (oldGroupId != newGroupId)) {
1507                                    newLinkToLayout = StringUtil.replaceLast(
1508                                            newLinkToLayout, String.valueOf(oldGroupId),
1509                                            String.valueOf(newGroupId));
1510                            }
1511    
1512                            oldLinksToLayout.add(oldLinkToLayout);
1513                            newLinksToLayout.add(newLinkToLayout);
1514                    }
1515    
1516                    content = StringUtil.replace(
1517                            content, ArrayUtil.toStringArray(oldLinksToLayout.toArray()),
1518                            ArrayUtil.toStringArray(newLinksToLayout.toArray()));
1519    
1520                    return content;
1521            }
1522    
1523            /**
1524             * @deprecated As of 7.0.0, replaced by {@link
1525             *             #replaceImportLinksToLayouts(PortletDataContext, String)}
1526             */
1527            @Deprecated
1528            @Override
1529            public String replaceImportLinksToLayouts(
1530                            PortletDataContext portletDataContext, String content,
1531                            boolean importReferencedContent)
1532                    throws Exception {
1533    
1534                    return replaceImportLinksToLayouts(portletDataContext, content);
1535            }
1536    
1537            @Override
1538            public void updateExportPortletPreferencesClassPKs(
1539                            PortletDataContext portletDataContext, Portlet portlet,
1540                            PortletPreferences portletPreferences, String key, String className)
1541                    throws Exception {
1542    
1543                    String[] oldValues = portletPreferences.getValues(key, null);
1544    
1545                    if (oldValues == null) {
1546                            return;
1547                    }
1548    
1549                    String[] newValues = new String[oldValues.length];
1550    
1551                    for (int i = 0; i < oldValues.length; i++) {
1552                            String oldValue = oldValues[i];
1553    
1554                            String newValue = oldValue;
1555    
1556                            String[] primaryKeys = StringUtil.split(oldValue);
1557    
1558                            for (String primaryKey : primaryKeys) {
1559                                    if (!Validator.isNumber(primaryKey)) {
1560                                            break;
1561                                    }
1562    
1563                                    long primaryKeyLong = GetterUtil.getLong(primaryKey);
1564    
1565                                    String uuid = getExportPortletPreferencesUuid(
1566                                            portletDataContext, portlet, className, primaryKeyLong);
1567    
1568                                    if (Validator.isNull(uuid)) {
1569                                            if (_log.isWarnEnabled()) {
1570                                                    _log.warn(
1571                                                            "Unable to get UUID for class " + className +
1572                                                                    " with primary key " + primaryKeyLong);
1573                                            }
1574    
1575                                            continue;
1576                                    }
1577    
1578                                    newValue = StringUtil.replace(newValue, primaryKey, uuid);
1579                            }
1580    
1581                            newValues[i] = newValue;
1582                    }
1583    
1584                    portletPreferences.setValues(key, newValues);
1585            }
1586    
1587            /**
1588             * @deprecated As of 7.0.0, replaced by {@link
1589             *             #updateExportPortletPreferencesClassPKs(PortletDataContext,
1590             *             Portlet, PortletPreferences, String, String)}
1591             */
1592            @Deprecated
1593            @Override
1594            public void updateExportPortletPreferencesClassPKs(
1595                            PortletDataContext portletDataContext, Portlet portlet,
1596                            PortletPreferences portletPreferences, String key, String className,
1597                            Element rootElement)
1598                    throws Exception {
1599    
1600                    updateExportPortletPreferencesClassPKs(
1601                            portletDataContext, portlet, portletPreferences, key, className);
1602            }
1603    
1604            @Override
1605            public void updateImportPortletPreferencesClassPKs(
1606                            PortletDataContext portletDataContext,
1607                            PortletPreferences portletPreferences, String key, Class<?> clazz,
1608                            long companyGroupId)
1609                    throws Exception {
1610    
1611                    String[] oldValues = portletPreferences.getValues(key, null);
1612    
1613                    if (oldValues == null) {
1614                            return;
1615                    }
1616    
1617                    Map<Long, Long> primaryKeys =
1618                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(clazz);
1619    
1620                    String[] newValues = new String[oldValues.length];
1621    
1622                    for (int i = 0; i < oldValues.length; i++) {
1623                            String oldValue = oldValues[i];
1624    
1625                            String newValue = oldValue;
1626    
1627                            String[] uuids = StringUtil.split(oldValue);
1628    
1629                            for (String uuid : uuids) {
1630                                    Long newPrimaryKey = getImportPortletPreferencesNewPrimaryKey(
1631                                            portletDataContext, clazz, companyGroupId, primaryKeys,
1632                                            uuid);
1633    
1634                                    if (Validator.isNull(newPrimaryKey)) {
1635                                            if (_log.isWarnEnabled()) {
1636                                                    StringBundler sb = new StringBundler(8);
1637    
1638                                                    sb.append("Unable to get primary key for ");
1639                                                    sb.append(clazz);
1640                                                    sb.append(" with UUID ");
1641                                                    sb.append(uuid);
1642                                                    sb.append(" in company group ");
1643                                                    sb.append(companyGroupId);
1644                                                    sb.append(" or in group ");
1645                                                    sb.append(portletDataContext.getScopeGroupId());
1646    
1647                                                    _log.warn(sb.toString());
1648                                            }
1649                                    }
1650                                    else {
1651                                            newValue = StringUtil.replace(
1652                                                    newValue, uuid, newPrimaryKey.toString());
1653                                    }
1654                            }
1655    
1656                            newValues[i] = newValue;
1657                    }
1658    
1659                    portletPreferences.setValues(key, newValues);
1660            }
1661    
1662            /**
1663             * @deprecated As of 7.0.0, replaced by {@link
1664             *             #validateMissingReferences(PortletDataContext)}
1665             */
1666            @Deprecated
1667            @Override
1668            public MissingReferences validateMissingReferences(
1669                            long userId, long groupId, Map<String, String[]> parameterMap,
1670                            File file)
1671                    throws Exception {
1672    
1673                    Group group = GroupLocalServiceUtil.getGroup(groupId);
1674                    String userIdStrategy = MapUtil.getString(
1675                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
1676                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
1677    
1678                    PortletDataContext portletDataContext =
1679                            PortletDataContextFactoryUtil.createImportPortletDataContext(
1680                                    group.getCompanyId(), groupId, parameterMap,
1681                                    getUserIdStrategy(userId, userIdStrategy), zipReader);
1682    
1683                    try {
1684                            return validateMissingReferences(portletDataContext);
1685                    }
1686                    finally {
1687                            zipReader.close();
1688                    }
1689            }
1690    
1691            @Override
1692            public MissingReferences validateMissingReferences(
1693                            final PortletDataContext portletDataContext)
1694                    throws Exception {
1695    
1696                    final MissingReferences missingReferences = new MissingReferences();
1697    
1698                    XMLReader xmlReader = SecureXMLFactoryProviderUtil.newXMLReader();
1699    
1700                    ElementHandler elementHandler = new ElementHandler(
1701                            new ElementProcessor() {
1702    
1703                                    @Override
1704                                    public void processElement(Element element) {
1705                                            MissingReference missingReference =
1706                                                    validateMissingReference(portletDataContext, element);
1707    
1708                                            if (missingReference != null) {
1709                                                    missingReferences.add(missingReference);
1710                                            }
1711                                    }
1712    
1713                            },
1714                            new String[] {"missing-reference"});
1715    
1716                    xmlReader.setContentHandler(elementHandler);
1717    
1718                    xmlReader.parse(
1719                            new InputSource(
1720                                    portletDataContext.getZipEntryAsInputStream("/manifest.xml")));
1721    
1722                    return missingReferences;
1723            }
1724    
1725            @Override
1726            public void writeManifestSummary(
1727                    Document document, ManifestSummary manifestSummary) {
1728    
1729                    Element rootElement = document.getRootElement();
1730    
1731                    Element manifestSummaryElement = rootElement.addElement(
1732                            "manifest-summary");
1733    
1734                    for (String manifestSummaryKey :
1735                                    manifestSummary.getManifestSummaryKeys()) {
1736    
1737                            Element element = manifestSummaryElement.addElement("staged-model");
1738    
1739                            element.addAttribute("manifest-summary-key", manifestSummaryKey);
1740    
1741                            long modelAdditionCount = manifestSummary.getModelAdditionCount(
1742                                    manifestSummaryKey);
1743    
1744                            if (modelAdditionCount > 0) {
1745                                    element.addAttribute(
1746                                            "addition-count", String.valueOf(modelAdditionCount));
1747                            }
1748    
1749                            long modelDeletionCount = manifestSummary.getModelDeletionCount(
1750                                    manifestSummaryKey);
1751    
1752                            if (modelDeletionCount > 0) {
1753                                    element.addAttribute(
1754                                            "deletion-count", String.valueOf(modelDeletionCount));
1755                            }
1756                    }
1757            }
1758    
1759            protected void addCreateDateProperty(
1760                    PortletDataContext portletDataContext, DynamicQuery dynamicQuery) {
1761    
1762                    if (!portletDataContext.hasDateRange()) {
1763                            return;
1764                    }
1765    
1766                    Property createDateProperty = PropertyFactoryUtil.forName("createDate");
1767    
1768                    Date startDate = portletDataContext.getStartDate();
1769    
1770                    dynamicQuery.add(createDateProperty.ge(startDate));
1771    
1772                    Date endDate = portletDataContext.getEndDate();
1773    
1774                    dynamicQuery.add(createDateProperty.le(endDate));
1775            }
1776    
1777            protected void deleteTimestampParameters(StringBuilder sb, int beginPos) {
1778                    beginPos = sb.indexOf(StringPool.CLOSE_BRACKET, beginPos);
1779    
1780                    if ((beginPos == -1) || (beginPos == (sb.length() - 1)) ||
1781                            (sb.charAt(beginPos + 1) != CharPool.QUESTION)) {
1782    
1783                            return;
1784                    }
1785    
1786                    int endPos = StringUtil.indexOfAny(
1787                            sb.toString(), _DL_REFERENCE_LEGACY_STOP_CHARS, beginPos + 2);
1788    
1789                    if (endPos == -1) {
1790                            return;
1791                    }
1792    
1793                    String urlParams = sb.substring(beginPos + 1, endPos);
1794    
1795                    urlParams = HttpUtil.removeParameter(urlParams, "t");
1796    
1797                    sb.replace(beginPos + 1, endPos, urlParams);
1798            }
1799    
1800            protected void doAddCriteria(
1801                    PortletDataContext portletDataContext, StagedModelType stagedModelType,
1802                    DynamicQuery dynamicQuery) {
1803    
1804                    Disjunction disjunction = RestrictionsFactoryUtil.disjunction();
1805    
1806                    Property groupIdProperty = PropertyFactoryUtil.forName("groupId");
1807    
1808                    disjunction.add(groupIdProperty.eq(0L));
1809                    disjunction.add(
1810                            groupIdProperty.eq(portletDataContext.getScopeGroupId()));
1811    
1812                    dynamicQuery.add(disjunction);
1813    
1814                    Property classNameIdProperty = PropertyFactoryUtil.forName(
1815                            "classNameId");
1816    
1817                    dynamicQuery.add(
1818                            classNameIdProperty.eq(stagedModelType.getClassNameId()));
1819    
1820                    if (stagedModelType.getReferrerClassNameId() >= 0) {
1821                            Property referrerClassNameIdProperty = PropertyFactoryUtil.forName(
1822                                    "referrerClassNameId");
1823    
1824                            dynamicQuery.add(
1825                                    referrerClassNameIdProperty.eq(
1826                                            stagedModelType.getReferrerClassNameId()));
1827                    }
1828    
1829                    Property typeProperty = PropertyFactoryUtil.forName("type");
1830    
1831                    dynamicQuery.add(typeProperty.eq(SystemEventConstants.TYPE_DELETE));
1832    
1833                    addCreateDateProperty(portletDataContext, dynamicQuery);
1834            }
1835    
1836            protected Map<String, String[]> getDLReferenceParameters(
1837                    PortletDataContext portletDataContext, String content, int beginPos,
1838                    int endPos) {
1839    
1840                    boolean legacyURL = true;
1841                    char[] stopChars = _DL_REFERENCE_LEGACY_STOP_CHARS;
1842    
1843                    if (content.startsWith("/documents/", beginPos)) {
1844                            legacyURL = false;
1845                            stopChars = _DL_REFERENCE_STOP_CHARS;
1846                    }
1847    
1848                    endPos = StringUtil.indexOfAny(content, stopChars, beginPos, endPos);
1849    
1850                    if (endPos == -1) {
1851                            return null;
1852                    }
1853    
1854                    Map<String, String[]> map = new HashMap<>();
1855    
1856                    String dlReference = content.substring(beginPos, endPos);
1857    
1858                    while (dlReference.contains(StringPool.AMPERSAND_ENCODED)) {
1859                            dlReference = dlReference.replace(
1860                                    StringPool.AMPERSAND_ENCODED, StringPool.AMPERSAND);
1861                    }
1862    
1863                    if (!legacyURL) {
1864                            String[] pathArray = dlReference.split(StringPool.SLASH);
1865    
1866                            if (pathArray.length < 3) {
1867                                    return map;
1868                            }
1869    
1870                            map.put("groupId", new String[] {pathArray[2]});
1871    
1872                            if (pathArray.length == 4) {
1873                                    map.put("uuid", new String[] {pathArray[3]});
1874                            }
1875                            else if (pathArray.length == 5) {
1876                                    map.put("folderId", new String[] {pathArray[3]});
1877                                    map.put(
1878                                            "title", new String[] {HttpUtil.decodeURL(pathArray[4])});
1879                            }
1880                            else if (pathArray.length > 5) {
1881                                    map.put("uuid", new String[] {pathArray[5]});
1882                            }
1883                    }
1884                    else {
1885                            dlReference = dlReference.substring(
1886                                    dlReference.indexOf(CharPool.QUESTION) + 1);
1887    
1888                            map = HttpUtil.parameterMapFromString(dlReference);
1889    
1890                            if (map.containsKey("img_id")) {
1891                                    map.put("image_id", map.get("img_id"));
1892                            }
1893                            else if (map.containsKey("i_id")) {
1894                                    map.put("image_id", map.get("i_id"));
1895                            }
1896                    }
1897    
1898                    map.put("endPos", new String[] {String.valueOf(endPos)});
1899    
1900                    String groupIdString = MapUtil.getString(map, "groupId");
1901    
1902                    if (groupIdString.equals("@group_id@")) {
1903                            groupIdString = String.valueOf(
1904                                    portletDataContext.getScopeGroupId());
1905    
1906                            map.put("groupId", new String[] {groupIdString});
1907                    }
1908    
1909                    return map;
1910            }
1911    
1912            protected boolean getExportPortletData(
1913                            long companyId, String portletId,
1914                            Map<String, String[]> parameterMap)
1915                    throws Exception {
1916    
1917                    boolean exportPortletData = MapUtil.getBoolean(
1918                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
1919                    boolean exportPortletDataAll = MapUtil.getBoolean(
1920                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
1921    
1922                    if (_log.isDebugEnabled()) {
1923                            _log.debug("Export portlet data " + exportPortletData);
1924                            _log.debug("Export all portlet data " + exportPortletDataAll);
1925                    }
1926    
1927                    if (!exportPortletData) {
1928                            return false;
1929                    }
1930    
1931                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
1932                            companyId, portletId);
1933    
1934                    if ((portlet == null) || portlet.isUndeployedPortlet()) {
1935                            return false;
1936                    }
1937    
1938                    PortletDataHandler portletDataHandler =
1939                            portlet.getPortletDataHandlerInstance();
1940    
1941                    if (portletDataHandler == null) {
1942                            return false;
1943                    }
1944    
1945                    if (exportPortletDataAll || !portletDataHandler.isDataSiteLevel()) {
1946                            return true;
1947                    }
1948    
1949                    return MapUtil.getBoolean(
1950                            parameterMap,
1951                            PortletDataHandlerKeys.PORTLET_DATA + StringPool.UNDERLINE +
1952                                    portlet.getRootPortletId());
1953            }
1954    
1955            protected String getExportPortletPreferencesUuid(
1956                            PortletDataContext portletDataContext, Portlet portlet,
1957                            String className, long primaryKeyLong)
1958                    throws Exception {
1959    
1960                    String uuid = null;
1961    
1962                    Element rootElement = portletDataContext.getExportDataRootElement();
1963    
1964                    if (className.equals(AssetCategory.class.getName())) {
1965                            AssetCategory assetCategory =
1966                                    AssetCategoryLocalServiceUtil.fetchCategory(primaryKeyLong);
1967    
1968                            if (assetCategory != null) {
1969                                    uuid = assetCategory.getUuid();
1970    
1971                                    portletDataContext.addReferenceElement(
1972                                            portlet, rootElement, assetCategory,
1973                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1974                            }
1975                    }
1976                    else if (className.equals(AssetVocabulary.class.getName())) {
1977                            AssetVocabulary assetVocabulary =
1978                                    AssetVocabularyLocalServiceUtil.fetchAssetVocabulary(
1979                                            primaryKeyLong);
1980    
1981                            if (assetVocabulary != null) {
1982                                    uuid = assetVocabulary.getUuid();
1983    
1984                                    portletDataContext.addReferenceElement(
1985                                            portlet, rootElement, assetVocabulary,
1986                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1987                            }
1988                    }
1989                    else if (className.equals(DDMStructure.class.getName())) {
1990                            DDMStructure ddmStructure =
1991                                    DDMStructureLocalServiceUtil.fetchStructure(primaryKeyLong);
1992    
1993                            if (ddmStructure != null) {
1994                                    uuid = ddmStructure.getUuid();
1995    
1996                                    portletDataContext.addReferenceElement(
1997                                            portlet, rootElement, ddmStructure,
1998                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1999                            }
2000                    }
2001                    else if (className.equals(DLFileEntryType.class.getName())) {
2002                            DLFileEntryType dlFileEntryType =
2003                                    DLFileEntryTypeLocalServiceUtil.fetchFileEntryType(
2004                                            primaryKeyLong);
2005    
2006                            if (dlFileEntryType != null) {
2007                                    uuid = dlFileEntryType.getUuid();
2008    
2009                                    portletDataContext.addReferenceElement(
2010                                            portlet, rootElement, dlFileEntryType,
2011                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
2012                            }
2013                    }
2014                    else if (className.equals(Organization.class.getName())) {
2015                            Organization organization =
2016                                    OrganizationLocalServiceUtil.fetchOrganization(primaryKeyLong);
2017    
2018                            if (organization != null) {
2019                                    uuid = organization.getUuid();
2020    
2021                                    portletDataContext.addReferenceElement(
2022                                            portlet, rootElement, organization,
2023                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
2024                            }
2025                    }
2026    
2027                    return uuid;
2028            }
2029    
2030            protected Map<String, Boolean> getExportPortletSetupControlsMap(
2031                            long companyId, String portletId,
2032                            Map<String, String[]> parameterMap, String type)
2033                    throws Exception {
2034    
2035                    boolean exportPortletConfiguration = MapUtil.getBoolean(
2036                            parameterMap, PortletDataHandlerKeys.PORTLET_CONFIGURATION);
2037                    boolean exportPortletConfigurationAll = MapUtil.getBoolean(
2038                            parameterMap, PortletDataHandlerKeys.PORTLET_CONFIGURATION_ALL);
2039    
2040                    if (_log.isDebugEnabled()) {
2041                            _log.debug(
2042                                    "Export portlet configuration " + exportPortletConfiguration);
2043                    }
2044    
2045                    boolean exportCurPortletArchivedSetups = exportPortletConfiguration;
2046                    boolean exportCurPortletConfiguration = exportPortletConfiguration;
2047                    boolean exportCurPortletSetup = exportPortletConfiguration;
2048                    boolean exportCurPortletUserPreferences = exportPortletConfiguration;
2049    
2050                    String rootPortletId = getExportableRootPortletId(companyId, portletId);
2051    
2052                    if (exportPortletConfigurationAll ||
2053                            (exportPortletConfiguration && type.equals("layout-prototype"))) {
2054    
2055                            exportCurPortletConfiguration = true;
2056    
2057                            exportCurPortletArchivedSetups = MapUtil.getBoolean(
2058                                    parameterMap,
2059                                    PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS_ALL);
2060                            exportCurPortletSetup = MapUtil.getBoolean(
2061                                    parameterMap, PortletDataHandlerKeys.PORTLET_SETUP_ALL);
2062                            exportCurPortletUserPreferences = MapUtil.getBoolean(
2063                                    parameterMap,
2064                                    PortletDataHandlerKeys.PORTLET_USER_PREFERENCES_ALL);
2065                    }
2066                    else if (rootPortletId != null) {
2067                            exportCurPortletConfiguration =
2068                                    exportPortletConfiguration &&
2069                                            MapUtil.getBoolean(
2070                                                    parameterMap,
2071                                                    PortletDataHandlerKeys.PORTLET_CONFIGURATION +
2072                                                            StringPool.UNDERLINE + rootPortletId);
2073    
2074                            exportCurPortletArchivedSetups =
2075                                    exportCurPortletConfiguration &&
2076                                            MapUtil.getBoolean(
2077                                                    parameterMap,
2078                                                    PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS +
2079                                                            StringPool.UNDERLINE + rootPortletId);
2080                            exportCurPortletSetup =
2081                                    exportCurPortletConfiguration &&
2082                                            MapUtil.getBoolean(
2083                                                    parameterMap,
2084                                                    PortletDataHandlerKeys.PORTLET_SETUP +
2085                                                            StringPool.UNDERLINE + rootPortletId);
2086                            exportCurPortletUserPreferences =
2087                                    exportCurPortletConfiguration &&
2088                                            MapUtil.getBoolean(
2089                                                    parameterMap,
2090                                                    PortletDataHandlerKeys.PORTLET_USER_PREFERENCES +
2091                                                            StringPool.UNDERLINE + rootPortletId);
2092                    }
2093    
2094                    Map<String, Boolean> exportPortletSetupControlsMap = new HashMap<>();
2095    
2096                    exportPortletSetupControlsMap.put(
2097                            PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS,
2098                            exportCurPortletArchivedSetups);
2099                    exportPortletSetupControlsMap.put(
2100                            PortletDataHandlerKeys.PORTLET_CONFIGURATION,
2101                            exportCurPortletConfiguration);
2102                    exportPortletSetupControlsMap.put(
2103                            PortletDataHandlerKeys.PORTLET_SETUP, exportCurPortletSetup);
2104                    exportPortletSetupControlsMap.put(
2105                            PortletDataHandlerKeys.PORTLET_USER_PREFERENCES,
2106                            exportCurPortletUserPreferences);
2107    
2108                    return exportPortletSetupControlsMap;
2109            }
2110    
2111            protected FileEntry getFileEntry(Map<String, String[]> map) {
2112                    if (MapUtil.isEmpty(map)) {
2113                            return null;
2114                    }
2115    
2116                    FileEntry fileEntry = null;
2117    
2118                    try {
2119                            String uuid = MapUtil.getString(map, "uuid");
2120                            long groupId = MapUtil.getLong(map, "groupId");
2121    
2122                            if (Validator.isNotNull(uuid)) {
2123                                    fileEntry = DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(
2124                                            uuid, groupId);
2125                            }
2126                            else {
2127                                    if (map.containsKey("folderId")) {
2128                                            long folderId = MapUtil.getLong(map, "folderId");
2129                                            String name = MapUtil.getString(map, "name");
2130                                            String title = MapUtil.getString(map, "title");
2131    
2132                                            if (Validator.isNotNull(title)) {
2133                                                    fileEntry = DLAppLocalServiceUtil.getFileEntry(
2134                                                            groupId, folderId, title);
2135                                            }
2136                                            else {
2137                                                    DLFileEntry dlFileEntry =
2138                                                            DLFileEntryLocalServiceUtil.fetchFileEntryByName(
2139                                                                    groupId, folderId, name);
2140    
2141                                                    if (dlFileEntry != null) {
2142                                                            fileEntry = DLAppLocalServiceUtil.getFileEntry(
2143                                                                    dlFileEntry.getFileEntryId());
2144                                                    }
2145                                            }
2146                                    }
2147                                    else if (map.containsKey("image_id")) {
2148                                            DLFileEntry dlFileEntry =
2149                                                    DLFileEntryLocalServiceUtil.fetchFileEntryByAnyImageId(
2150                                                            MapUtil.getLong(map, "image_id"));
2151    
2152                                            if (dlFileEntry != null) {
2153                                                    fileEntry = DLAppLocalServiceUtil.getFileEntry(
2154                                                            dlFileEntry.getFileEntryId());
2155                                            }
2156                                    }
2157                            }
2158                    }
2159                    catch (Exception e) {
2160                            if (_log.isDebugEnabled()) {
2161                                    _log.debug(e, e);
2162                            }
2163                            else if (_log.isWarnEnabled()) {
2164                                    _log.warn(e.getMessage());
2165                            }
2166                    }
2167    
2168                    return fileEntry;
2169            }
2170    
2171            protected boolean getImportPortletData(
2172                            long companyId, String portletId,
2173                            Map<String, String[]> parameterMap, Element portletDataElement)
2174                    throws Exception {
2175    
2176                    boolean importPortletData = MapUtil.getBoolean(
2177                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
2178                    boolean importPortletDataAll = MapUtil.getBoolean(
2179                            parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
2180    
2181                    if (_log.isDebugEnabled()) {
2182                            _log.debug("Import portlet data " + importPortletData);
2183                            _log.debug("Import all portlet data " + importPortletDataAll);
2184                    }
2185    
2186                    if (!importPortletData) {
2187                            return false;
2188                    }
2189    
2190                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
2191                            companyId, portletId);
2192    
2193                    if (portlet == null) {
2194                            return false;
2195                    }
2196    
2197                    PortletDataHandler portletDataHandler =
2198                            portlet.getPortletDataHandlerInstance();
2199    
2200                    if ((portletDataHandler == null) ||
2201                            ((portletDataElement == null) &&
2202                             !portletDataHandler.isDisplayPortlet())) {
2203    
2204                            return false;
2205                    }
2206    
2207                    if (importPortletDataAll || !portletDataHandler.isDataSiteLevel()) {
2208                            return true;
2209                    }
2210    
2211                    return MapUtil.getBoolean(
2212                            parameterMap,
2213                            PortletDataHandlerKeys.PORTLET_DATA + StringPool.UNDERLINE +
2214                                    portlet.getRootPortletId());
2215            }
2216    
2217            protected Long getImportPortletPreferencesNewPrimaryKey(
2218                            PortletDataContext portletDataContext, Class<?> clazz,
2219                            long companyGroupId, Map<Long, Long> primaryKeys, String uuid)
2220                    throws Exception {
2221    
2222                    if (Validator.isNumber(uuid)) {
2223                            long oldPrimaryKey = GetterUtil.getLong(uuid);
2224    
2225                            return MapUtil.getLong(primaryKeys, oldPrimaryKey, oldPrimaryKey);
2226                    }
2227    
2228                    String className = clazz.getName();
2229    
2230                    if (className.equals(AssetCategory.class.getName())) {
2231                            AssetCategory assetCategory = AssetCategoryUtil.fetchByUUID_G(
2232                                    uuid, portletDataContext.getScopeGroupId());
2233    
2234                            if (assetCategory == null) {
2235                                    assetCategory = AssetCategoryUtil.fetchByUUID_G(
2236                                            uuid, companyGroupId);
2237                            }
2238    
2239                            if (assetCategory != null) {
2240                                    return assetCategory.getCategoryId();
2241                            }
2242                    }
2243                    else if (className.equals(AssetVocabulary.class.getName())) {
2244                            AssetVocabulary assetVocabulary = AssetVocabularyUtil.fetchByUUID_G(
2245                                    uuid, portletDataContext.getScopeGroupId());
2246    
2247                            if (assetVocabulary == null) {
2248                                    assetVocabulary = AssetVocabularyUtil.fetchByUUID_G(
2249                                            uuid, companyGroupId);
2250                            }
2251    
2252                            if (assetVocabulary != null) {
2253                                    return assetVocabulary.getVocabularyId();
2254                            }
2255                    }
2256                    else if (className.equals(DDMStructure.class.getName())) {
2257                            DDMStructure ddmStructure = DDMStructureUtil.fetchByUUID_G(
2258                                    uuid, portletDataContext.getScopeGroupId());
2259    
2260                            if (ddmStructure == null) {
2261                                    ddmStructure = DDMStructureUtil.fetchByUUID_G(
2262                                            uuid, companyGroupId);
2263                            }
2264    
2265                            if (ddmStructure != null) {
2266                                    return ddmStructure.getStructureId();
2267                            }
2268                    }
2269                    else if (className.equals(DLFileEntryType.class.getName())) {
2270                            DLFileEntryType dlFileEntryType = DLFileEntryTypeUtil.fetchByUUID_G(
2271                                    uuid, portletDataContext.getScopeGroupId());
2272    
2273                            if (dlFileEntryType == null) {
2274                                    dlFileEntryType = DLFileEntryTypeUtil.fetchByUUID_G(
2275                                            uuid, companyGroupId);
2276                            }
2277    
2278                            if (dlFileEntryType == null) {
2279                                    Element rootElement =
2280                                            portletDataContext.getImportDataRootElement();
2281    
2282                                    Element element = portletDataContext.getReferenceElement(
2283                                            rootElement, clazz, companyGroupId, uuid,
2284                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY);
2285    
2286                                    if (element != null) {
2287                                            String fileEntryTypeKey = element.attributeValue(
2288                                                    "file-entry-type-key");
2289    
2290                                            boolean preloaded = GetterUtil.getBoolean(
2291                                                    element.attributeValue("preloaded"));
2292    
2293                                            if (preloaded) {
2294                                                    dlFileEntryType =
2295                                                            DLFileEntryTypeLocalServiceUtil.fetchFileEntryType(
2296                                                                    companyGroupId, fileEntryTypeKey);
2297                                            }
2298                                    }
2299                            }
2300    
2301                            if (dlFileEntryType != null) {
2302                                    return dlFileEntryType.getFileEntryTypeId();
2303                            }
2304                    }
2305                    else if (className.equals(Organization.class.getName())) {
2306                            Organization organization = OrganizationUtil.fetchByUuid_C_First(
2307                                    uuid, portletDataContext.getCompanyId(), null);
2308    
2309                            if (organization != null) {
2310                                    return organization.getOrganizationId();
2311                            }
2312                    }
2313    
2314                    return null;
2315            }
2316    
2317            protected Map<String, Boolean> getImportPortletSetupControlsMap(
2318                            long companyId, String portletId,
2319                            Map<String, String[]> parameterMap, ManifestSummary manifestSummary)
2320                    throws Exception {
2321    
2322                    boolean importPortletConfiguration = MapUtil.getBoolean(
2323                            parameterMap, PortletDataHandlerKeys.PORTLET_CONFIGURATION);
2324                    boolean importPortletConfigurationAll = MapUtil.getBoolean(
2325                            parameterMap, PortletDataHandlerKeys.PORTLET_CONFIGURATION_ALL);
2326    
2327                    if (_log.isDebugEnabled()) {
2328                            _log.debug(
2329                                    "Import portlet configuration " + importPortletConfiguration);
2330                    }
2331    
2332                    boolean importCurPortletArchivedSetups = importPortletConfiguration;
2333                    boolean importCurPortletConfiguration = importPortletConfiguration;
2334                    boolean importCurPortletSetup = importPortletConfiguration;
2335                    boolean importCurPortletUserPreferences = importPortletConfiguration;
2336    
2337                    String rootPortletId = getExportableRootPortletId(companyId, portletId);
2338    
2339                    if (importPortletConfigurationAll) {
2340                            importCurPortletConfiguration = true;
2341    
2342                            if ((manifestSummary != null) &&
2343                                    (manifestSummary.getConfigurationPortletOptions(
2344                                            rootPortletId) == null)) {
2345    
2346                                    importCurPortletConfiguration = false;
2347                            }
2348    
2349                            importCurPortletArchivedSetups =
2350                                    importCurPortletConfiguration &&
2351                                            MapUtil.getBoolean(
2352                                                    parameterMap,
2353                                                    PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS_ALL);
2354                            importCurPortletSetup =
2355                                    importCurPortletConfiguration &&
2356                                            MapUtil.getBoolean(
2357                                                    parameterMap, PortletDataHandlerKeys.PORTLET_SETUP_ALL);
2358                            importCurPortletUserPreferences =
2359                                    importCurPortletConfiguration &&
2360                                            MapUtil.getBoolean(
2361                                                    parameterMap,
2362                                                    PortletDataHandlerKeys.PORTLET_USER_PREFERENCES_ALL);
2363                    }
2364                    else if (rootPortletId != null) {
2365                            importCurPortletConfiguration =
2366                                    importPortletConfiguration &&
2367                                            MapUtil.getBoolean(
2368                                                    parameterMap,
2369                                                    PortletDataHandlerKeys.PORTLET_CONFIGURATION +
2370                                                            StringPool.UNDERLINE + rootPortletId);
2371    
2372                            importCurPortletArchivedSetups =
2373                                    importCurPortletConfiguration &&
2374                                            MapUtil.getBoolean(
2375                                                    parameterMap,
2376                                                    PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS +
2377                                                            StringPool.UNDERLINE + rootPortletId);
2378                            importCurPortletSetup =
2379                                    importCurPortletConfiguration &&
2380                                            MapUtil.getBoolean(
2381                                                    parameterMap,
2382                                                    PortletDataHandlerKeys.PORTLET_SETUP +
2383                                                            StringPool.UNDERLINE + rootPortletId);
2384                            importCurPortletUserPreferences =
2385                                    importCurPortletConfiguration &&
2386                                            MapUtil.getBoolean(
2387                                                    parameterMap,
2388                                                    PortletDataHandlerKeys.PORTLET_USER_PREFERENCES +
2389                                                            StringPool.UNDERLINE + rootPortletId);
2390                    }
2391    
2392                    Map<String, Boolean> importPortletSetupMap = new HashMap<>();
2393    
2394                    importPortletSetupMap.put(
2395                            PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS,
2396                            importCurPortletArchivedSetups);
2397                    importPortletSetupMap.put(
2398                            PortletDataHandlerKeys.PORTLET_CONFIGURATION,
2399                            importCurPortletConfiguration);
2400                    importPortletSetupMap.put(
2401                            PortletDataHandlerKeys.PORTLET_SETUP, importCurPortletSetup);
2402                    importPortletSetupMap.put(
2403                            PortletDataHandlerKeys.PORTLET_USER_PREFERENCES,
2404                            importCurPortletUserPreferences);
2405    
2406                    return importPortletSetupMap;
2407            }
2408    
2409            protected ZipWriter getZipWriter(String fileName) {
2410                    if (!ExportImportThreadLocal.isStagingInProcess() ||
2411                            (PropsValues.STAGING_DELETE_TEMP_LAR_ON_FAILURE &&
2412                             PropsValues.STAGING_DELETE_TEMP_LAR_ON_SUCCESS)) {
2413    
2414                            return ZipWriterFactoryUtil.getZipWriter();
2415                    }
2416    
2417                    return ZipWriterFactoryUtil.getZipWriter(
2418                            new File(
2419                                    SystemProperties.get(SystemProperties.TMP_DIR) +
2420                                            StringPool.SLASH + fileName));
2421            }
2422    
2423            protected boolean populateLayoutsJSON(
2424                    JSONArray layoutsJSONArray, Layout layout, long[] selectedLayoutIds) {
2425    
2426                    List<Layout> childLayouts = layout.getChildren();
2427                    JSONArray childLayoutsJSONArray = null;
2428                    boolean includeChildren = true;
2429    
2430                    if (ListUtil.isNotEmpty(childLayouts)) {
2431                            childLayoutsJSONArray = JSONFactoryUtil.createJSONArray();
2432    
2433                            for (Layout childLayout : childLayouts) {
2434                                    if (!populateLayoutsJSON(
2435                                                    childLayoutsJSONArray, childLayout,
2436                                                    selectedLayoutIds)) {
2437    
2438                                            includeChildren = false;
2439                                    }
2440                            }
2441                    }
2442    
2443                    boolean checked = ArrayUtil.contains(
2444                            selectedLayoutIds, layout.getLayoutId());
2445    
2446                    if (checked) {
2447                            JSONObject layoutJSONObject = JSONFactoryUtil.createJSONObject();
2448    
2449                            layoutJSONObject.put("includeChildren", includeChildren);
2450                            layoutJSONObject.put("plid", layout.getPlid());
2451    
2452                            layoutsJSONArray.put(layoutJSONObject);
2453                    }
2454    
2455                    if (checked && includeChildren) {
2456                            return true;
2457                    }
2458    
2459                    if (childLayoutsJSONArray != null) {
2460    
2461                            // We want a 1 level array and not an array of arrays
2462    
2463                            for (int i = 0; i < childLayoutsJSONArray.length(); i++) {
2464                                    layoutsJSONArray.put(childLayoutsJSONArray.getJSONObject(i));
2465                            }
2466                    }
2467    
2468                    return false;
2469            }
2470    
2471            protected String replaceExportHostname(
2472                            PortletDataContext portletDataContext, String url,
2473                            StringBundler urlSB)
2474                    throws PortalException {
2475    
2476                    if (!HttpUtil.hasProtocol(url)) {
2477                            return url;
2478                    }
2479    
2480                    boolean secure = HttpUtil.isSecure(url);
2481    
2482                    int serverPort = PortalUtil.getPortalServerPort(secure);
2483    
2484                    if (serverPort == -1) {
2485                            return url;
2486                    }
2487    
2488                    Group group = GroupLocalServiceUtil.getGroup(
2489                            portletDataContext.getScopeGroupId());
2490    
2491                    LayoutSet publicLayoutSet = group.getPublicLayoutSet();
2492    
2493                    String publicLayoutSetVirtualHostname =
2494                            publicLayoutSet.getVirtualHostname();
2495    
2496                    String portalUrl = StringPool.BLANK;
2497    
2498                    if (Validator.isNotNull(publicLayoutSetVirtualHostname)) {
2499                            portalUrl = PortalUtil.getPortalURL(
2500                                    publicLayoutSetVirtualHostname, serverPort, secure);
2501    
2502                            if (url.startsWith(portalUrl)) {
2503                                    if (secure) {
2504                                            urlSB.append(DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL);
2505                                    }
2506                                    else {
2507                                            urlSB.append(DATA_HANDLER_PUBLIC_LAYOUT_SET_URL);
2508                                    }
2509    
2510                                    return url.substring(portalUrl.length());
2511                            }
2512                    }
2513    
2514                    LayoutSet privateLayoutSet = group.getPrivateLayoutSet();
2515    
2516                    String privateLayoutSetVirtualHostname =
2517                            privateLayoutSet.getVirtualHostname();
2518    
2519                    if (Validator.isNotNull(privateLayoutSetVirtualHostname)) {
2520                            portalUrl = PortalUtil.getPortalURL(
2521                                    privateLayoutSetVirtualHostname, serverPort, secure);
2522    
2523                            if (url.startsWith(portalUrl)) {
2524                                    if (secure) {
2525                                            urlSB.append(DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL);
2526                                    }
2527                                    else {
2528                                            urlSB.append(DATA_HANDLER_PRIVATE_LAYOUT_SET_URL);
2529                                    }
2530    
2531                                    return url.substring(portalUrl.length());
2532                            }
2533                    }
2534    
2535                    Company company = CompanyLocalServiceUtil.getCompany(
2536                            group.getCompanyId());
2537    
2538                    String companyVirtualHostname = company.getVirtualHostname();
2539    
2540                    if (Validator.isNotNull(companyVirtualHostname)) {
2541                            portalUrl = PortalUtil.getPortalURL(
2542                                    companyVirtualHostname, serverPort, secure);
2543    
2544                            if (url.startsWith(portalUrl)) {
2545                                    if (secure) {
2546                                            urlSB.append(DATA_HANDLER_COMPANY_SECURE_URL);
2547                                    }
2548                                    else {
2549                                            urlSB.append(DATA_HANDLER_COMPANY_URL);
2550                                    }
2551    
2552                                    return url.substring(portalUrl.length());
2553                            }
2554                    }
2555    
2556                    portalUrl = PortalUtil.getPortalURL("localhost", serverPort, secure);
2557    
2558                    if (url.startsWith(portalUrl)) {
2559                            return url.substring(portalUrl.length());
2560                    }
2561    
2562                    return url;
2563            }
2564    
2565            protected MissingReference validateMissingReference(
2566                    PortletDataContext portletDataContext, Element element) {
2567    
2568                    String className = element.attributeValue("class-name");
2569    
2570                    StagedModelDataHandler<?> stagedModelDataHandler =
2571                            StagedModelDataHandlerRegistryUtil.getStagedModelDataHandler(
2572                                    className);
2573    
2574                    if (!stagedModelDataHandler.validateReference(
2575                                    portletDataContext, element)) {
2576    
2577                            MissingReference missingReference = new MissingReference(element);
2578    
2579                            Map<Long, Long> groupIds =
2580                                    (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
2581                                            Group.class);
2582    
2583                            long groupId = MapUtil.getLong(
2584                                    groupIds,
2585                                    GetterUtil.getLong(element.attributeValue("group-id")));
2586    
2587                            missingReference.setGroupId(groupId);
2588    
2589                            return missingReference;
2590                    }
2591    
2592                    return null;
2593            }
2594    
2595            private static final char[] _DL_REFERENCE_LEGACY_STOP_CHARS = {
2596                    CharPool.APOSTROPHE, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
2597                    CharPool.CLOSE_PARENTHESIS, CharPool.GREATER_THAN, CharPool.LESS_THAN,
2598                    CharPool.PIPE, CharPool.QUOTE, CharPool.SPACE
2599            };
2600    
2601            private static final char[] _DL_REFERENCE_STOP_CHARS = {
2602                    CharPool.APOSTROPHE, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
2603                    CharPool.CLOSE_PARENTHESIS, CharPool.GREATER_THAN, CharPool.LESS_THAN,
2604                    CharPool.PIPE, CharPool.QUESTION, CharPool.QUOTE, CharPool.SPACE
2605            };
2606    
2607            private static final char[] _LAYOUT_REFERENCE_STOP_CHARS = {
2608                    CharPool.APOSTROPHE, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
2609                    CharPool.CLOSE_PARENTHESIS, CharPool.GREATER_THAN, CharPool.LESS_THAN,
2610                    CharPool.PIPE, CharPool.QUESTION, CharPool.QUOTE, CharPool.SPACE
2611            };
2612    
2613            private static final String _PRIVATE_GROUP_SERVLET_MAPPING =
2614                    PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING +
2615                            StringPool.SLASH;
2616    
2617            private static final String _PRIVATE_USER_SERVLET_MAPPING =
2618                    PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING +
2619                            StringPool.SLASH;
2620    
2621            private static final String _PUBLIC_GROUP_SERVLET_MAPPING =
2622                    PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING +
2623                            StringPool.SLASH;
2624    
2625            private static final Log _log = LogFactoryUtil.getLog(
2626                    ExportImportHelperImpl.class);
2627    
2628            private final Pattern _exportLinksToLayoutPattern = Pattern.compile(
2629                    "\\[([\\d]+)@(private(-group|-user)?|public)(@([\\d]+))?\\]");
2630            private final Pattern _importLinksToLayoutPattern = Pattern.compile(
2631                    "\\[([\\d]+)@(private(-group|-user)?|public)@([\\d]+)(@([\\d]+))?\\]");
2632    
2633            private class ManifestSummaryElementProcessor implements ElementProcessor {
2634    
2635                    public ManifestSummaryElementProcessor(
2636                            Group group, ManifestSummary manifestSummary) {
2637    
2638                            _group = group;
2639                            _manifestSummary = manifestSummary;
2640                    }
2641    
2642                    @Override
2643                    public void processElement(Element element) {
2644                            String elementName = element.getName();
2645    
2646                            if (elementName.equals("header")) {
2647                                    String exportDateString = element.attributeValue("export-date");
2648    
2649                                    Date exportDate = GetterUtil.getDate(
2650                                            exportDateString,
2651                                            DateFormatFactoryUtil.getSimpleDateFormat(
2652                                                    Time.RFC822_FORMAT));
2653    
2654                                    _manifestSummary.setExportDate(exportDate);
2655                            }
2656                            else if (elementName.equals("portlet")) {
2657                                    String portletId = element.attributeValue("portlet-id");
2658    
2659                                    Portlet portlet = null;
2660    
2661                                    try {
2662                                            portlet = PortletLocalServiceUtil.getPortletById(
2663                                                    _group.getCompanyId(), portletId);
2664                                    }
2665                                    catch (Exception e) {
2666                                            return;
2667                                    }
2668    
2669                                    PortletDataHandler portletDataHandler =
2670                                            portlet.getPortletDataHandlerInstance();
2671    
2672                                    if (portletDataHandler == null) {
2673                                            return;
2674                                    }
2675    
2676                                    String[] configurationPortletOptions = StringUtil.split(
2677                                            element.attributeValue("portlet-configuration"));
2678    
2679                                    if (!(portletDataHandler instanceof
2680                                                    DefaultConfigurationPortletDataHandler) &&
2681                                            portletDataHandler.isDataSiteLevel() &&
2682                                            GetterUtil.getBoolean(
2683                                                    element.attributeValue("portlet-data"))) {
2684    
2685                                            _manifestSummary.addDataPortlet(
2686                                                    portlet, configurationPortletOptions);
2687                                    }
2688                                    else {
2689                                            _manifestSummary.addLayoutPortlet(
2690                                                    portlet, configurationPortletOptions);
2691                                    }
2692                            }
2693                            else if (elementName.equals("staged-model")) {
2694                                    String manifestSummaryKey = element.attributeValue(
2695                                            "manifest-summary-key");
2696    
2697                                    long modelAdditionCount = GetterUtil.getLong(
2698                                            element.attributeValue("addition-count"));
2699    
2700                                    _manifestSummary.addModelAdditionCount(
2701                                            manifestSummaryKey, modelAdditionCount);
2702    
2703                                    long modelDeletionCount = GetterUtil.getLong(
2704                                            element.attributeValue("deletion-count"));
2705    
2706                                    _manifestSummary.addModelDeletionCount(
2707                                            manifestSummaryKey, modelDeletionCount);
2708                            }
2709                    }
2710    
2711                    private final Group _group;
2712                    private final ManifestSummary _manifestSummary;
2713    
2714            }
2715    
2716    }