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