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