001    /**
002     * Copyright (c) 2000-2013 Liferay, Inc. All rights reserved.
003     *
004     * The contents of this file are subject to the terms of the Liferay Enterprise
005     * Subscription License ("License"). You may not use this file except in
006     * compliance with the License. You can obtain a copy of the License by
007     * contacting Liferay, Inc. See the License for the specific language governing
008     * permissions and limitations under the License, including but not limited to
009     * distribution rights of the Software.
010     *
011     *
012     *
013     */
014    
015    package com.liferay.portal.lar;
016    
017    import com.liferay.portal.LARFileException;
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.ExportImportHelper;
031    import com.liferay.portal.kernel.lar.ExportImportHelperUtil;
032    import com.liferay.portal.kernel.lar.ExportImportPathUtil;
033    import com.liferay.portal.kernel.lar.ManifestSummary;
034    import com.liferay.portal.kernel.lar.MissingReference;
035    import com.liferay.portal.kernel.lar.MissingReferences;
036    import com.liferay.portal.kernel.lar.PortletDataContext;
037    import com.liferay.portal.kernel.lar.PortletDataContextFactoryUtil;
038    import com.liferay.portal.kernel.lar.PortletDataHandler;
039    import com.liferay.portal.kernel.lar.PortletDataHandlerControl;
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.CalendarFactoryUtil;
051    import com.liferay.portal.kernel.util.CharPool;
052    import com.liferay.portal.kernel.util.DateFormatFactoryUtil;
053    import com.liferay.portal.kernel.util.DateRange;
054    import com.liferay.portal.kernel.util.Digester;
055    import com.liferay.portal.kernel.util.DigesterUtil;
056    import com.liferay.portal.kernel.util.FileUtil;
057    import com.liferay.portal.kernel.util.GetterUtil;
058    import com.liferay.portal.kernel.util.HttpUtil;
059    import com.liferay.portal.kernel.util.LocaleUtil;
060    import com.liferay.portal.kernel.util.MapUtil;
061    import com.liferay.portal.kernel.util.ParamUtil;
062    import com.liferay.portal.kernel.util.StreamUtil;
063    import com.liferay.portal.kernel.util.StringBundler;
064    import com.liferay.portal.kernel.util.StringPool;
065    import com.liferay.portal.kernel.util.StringUtil;
066    import com.liferay.portal.kernel.util.TempFileUtil;
067    import com.liferay.portal.kernel.util.Time;
068    import com.liferay.portal.kernel.util.TimeZoneUtil;
069    import com.liferay.portal.kernel.util.Validator;
070    import com.liferay.portal.kernel.xml.Document;
071    import com.liferay.portal.kernel.xml.Element;
072    import com.liferay.portal.kernel.xml.ElementHandler;
073    import com.liferay.portal.kernel.xml.ElementProcessor;
074    import com.liferay.portal.kernel.zip.ZipReader;
075    import com.liferay.portal.kernel.zip.ZipReaderFactoryUtil;
076    import com.liferay.portal.lar.backgroundtask.StagingIndexingBackgroundTaskExecutor;
077    import com.liferay.portal.model.Company;
078    import com.liferay.portal.model.Group;
079    import com.liferay.portal.model.Layout;
080    import com.liferay.portal.model.LayoutConstants;
081    import com.liferay.portal.model.LayoutFriendlyURL;
082    import com.liferay.portal.model.LayoutSet;
083    import com.liferay.portal.model.Organization;
084    import com.liferay.portal.model.Portlet;
085    import com.liferay.portal.model.PortletConstants;
086    import com.liferay.portal.model.StagedModel;
087    import com.liferay.portal.model.SystemEventConstants;
088    import com.liferay.portal.model.User;
089    import com.liferay.portal.service.BackgroundTaskLocalServiceUtil;
090    import com.liferay.portal.service.CompanyLocalServiceUtil;
091    import com.liferay.portal.service.GroupLocalServiceUtil;
092    import com.liferay.portal.service.LayoutFriendlyURLLocalServiceUtil;
093    import com.liferay.portal.service.LayoutLocalServiceUtil;
094    import com.liferay.portal.service.LayoutServiceUtil;
095    import com.liferay.portal.service.LayoutSetLocalServiceUtil;
096    import com.liferay.portal.service.OrganizationLocalServiceUtil;
097    import com.liferay.portal.service.PortletLocalServiceUtil;
098    import com.liferay.portal.service.ServiceContext;
099    import com.liferay.portal.service.UserLocalServiceUtil;
100    import com.liferay.portal.service.persistence.OrganizationUtil;
101    import com.liferay.portal.service.persistence.SystemEventActionableDynamicQuery;
102    import com.liferay.portal.theme.ThemeDisplay;
103    import com.liferay.portal.util.PortalUtil;
104    import com.liferay.portal.util.PortletKeys;
105    import com.liferay.portal.util.PropsValues;
106    import com.liferay.portal.util.WebKeys;
107    import com.liferay.portlet.PortletPreferencesFactoryUtil;
108    import com.liferay.portlet.asset.model.AssetCategory;
109    import com.liferay.portlet.asset.model.AssetVocabulary;
110    import com.liferay.portlet.asset.service.AssetCategoryLocalServiceUtil;
111    import com.liferay.portlet.asset.service.AssetVocabularyLocalServiceUtil;
112    import com.liferay.portlet.asset.service.persistence.AssetCategoryUtil;
113    import com.liferay.portlet.asset.service.persistence.AssetVocabularyUtil;
114    import com.liferay.portlet.documentlibrary.lar.FileEntryUtil;
115    import com.liferay.portlet.documentlibrary.model.DLFileEntry;
116    import com.liferay.portlet.documentlibrary.model.DLFileEntryType;
117    import com.liferay.portlet.documentlibrary.service.DLAppLocalServiceUtil;
118    import com.liferay.portlet.documentlibrary.service.DLFileEntryLocalServiceUtil;
119    import com.liferay.portlet.documentlibrary.service.DLFileEntryTypeLocalServiceUtil;
120    import com.liferay.portlet.documentlibrary.service.persistence.DLFileEntryTypeUtil;
121    import com.liferay.portlet.documentlibrary.util.DLUtil;
122    import com.liferay.portlet.dynamicdatamapping.model.DDMStructure;
123    import com.liferay.portlet.dynamicdatamapping.model.DDMTemplate;
124    import com.liferay.portlet.dynamicdatamapping.service.DDMStructureLocalServiceUtil;
125    import com.liferay.portlet.dynamicdatamapping.service.persistence.DDMStructureUtil;
126    import com.liferay.portlet.journal.model.JournalArticle;
127    
128    import java.io.File;
129    import java.io.InputStream;
130    import java.io.Serializable;
131    import java.io.StringReader;
132    
133    import java.util.ArrayList;
134    import java.util.Calendar;
135    import java.util.Date;
136    import java.util.HashMap;
137    import java.util.LinkedHashMap;
138    import java.util.List;
139    import java.util.Locale;
140    import java.util.Map;
141    import java.util.TimeZone;
142    import java.util.regex.Matcher;
143    import java.util.regex.Pattern;
144    
145    import javax.portlet.PortletPreferences;
146    import javax.portlet.PortletRequest;
147    
148    import org.apache.xerces.parsers.SAXParser;
149    
150    import org.xml.sax.InputSource;
151    
152    /**
153     * @author Zsolt Berentey
154     * @author Levente Hudák
155     * @author Julio Camarero
156     */
157    public class ExportImportHelperImpl implements ExportImportHelper {
158    
159            @Override
160            public void reindex(PortletDataContext portletDataContext, long userId)
161                    throws PortalException, SystemException {
162    
163                    Map<String, Serializable> taskContextMap =
164                            new HashMap<String, Serializable>();
165    
166                    PortletDataContext clonedPortletDataContext =
167                            PortletDataContextFactoryUtil.clonePortletDataContext(
168                                    portletDataContext);
169    
170                    Map<String, Map<?, ?>> newPrimaryKeysMaps =
171                            clonedPortletDataContext.getNewPrimaryKeysMaps();
172    
173                    for (String key : _EXTRANEOUS_REINDEX_PRIMARY_KEYS_MAPS_KEYS) {
174                            newPrimaryKeysMaps.remove(key);
175                    }
176    
177                    taskContextMap.put("portletDataContext", clonedPortletDataContext);
178                    taskContextMap.put("userId", userId);
179    
180                    BackgroundTaskLocalServiceUtil.addBackgroundTask(
181                            userId, clonedPortletDataContext.getGroupId(), StringPool.BLANK,
182                            null, StagingIndexingBackgroundTaskExecutor.class, taskContextMap,
183                            new ServiceContext());
184            }
185    
186            @Override
187            public Calendar getCalendar(
188                    PortletRequest portletRequest, String paramPrefix,
189                    boolean timeZoneSensitive) {
190    
191                    ThemeDisplay themeDisplay = (ThemeDisplay)portletRequest.getAttribute(
192                            WebKeys.THEME_DISPLAY);
193    
194                    int dateMonth = ParamUtil.getInteger(
195                            portletRequest, paramPrefix + "Month");
196                    int dateDay = ParamUtil.getInteger(portletRequest, paramPrefix + "Day");
197                    int dateYear = ParamUtil.getInteger(
198                            portletRequest, paramPrefix + "Year");
199                    int dateHour = ParamUtil.getInteger(
200                            portletRequest, paramPrefix + "Hour");
201                    int dateMinute = ParamUtil.getInteger(
202                            portletRequest, paramPrefix + "Minute");
203                    int dateAmPm = ParamUtil.getInteger(
204                            portletRequest, paramPrefix + "AmPm");
205    
206                    if (dateAmPm == Calendar.PM) {
207                            dateHour += 12;
208                    }
209    
210                    Locale locale = null;
211                    TimeZone timeZone = null;
212    
213                    if (timeZoneSensitive) {
214                            locale = themeDisplay.getLocale();
215                            timeZone = themeDisplay.getTimeZone();
216                    }
217                    else {
218                            locale = LocaleUtil.getDefault();
219                            timeZone = TimeZoneUtil.getTimeZone(StringPool.UTC);
220                    }
221    
222                    Calendar calendar = CalendarFactoryUtil.getCalendar(timeZone, locale);
223    
224                    calendar.set(Calendar.MONTH, dateMonth);
225                    calendar.set(Calendar.DATE, dateDay);
226                    calendar.set(Calendar.YEAR, dateYear);
227                    calendar.set(Calendar.HOUR_OF_DAY, dateHour);
228                    calendar.set(Calendar.MINUTE, dateMinute);
229                    calendar.set(Calendar.SECOND, 0);
230                    calendar.set(Calendar.MILLISECOND, 0);
231    
232                    return calendar;
233            }
234    
235            @Override
236            public DateRange getDateRange(
237                            PortletRequest portletRequest, long groupId, boolean privateLayout,
238                            long plid, String portletId, String defaultRange)
239                    throws Exception {
240    
241                    Date startDate = null;
242                    Date endDate = null;
243    
244                    String range = ParamUtil.getString(
245                            portletRequest, "range", defaultRange);
246    
247                    if (range.equals("dateRange")) {
248                            Calendar startCalendar = getCalendar(
249                                    portletRequest, "startDate", true);
250    
251                            startDate = startCalendar.getTime();
252    
253                            Calendar endCalendar = getCalendar(portletRequest, "endDate", true);
254    
255                            endDate = endCalendar.getTime();
256                    }
257                    else if (range.equals("fromLastPublishDate")) {
258                            long lastPublishDate = 0;
259    
260                            if (Validator.isNotNull(portletId) && (plid > 0)) {
261                                    Layout layout = LayoutLocalServiceUtil.getLayout(plid);
262    
263                                    PortletPreferences preferences =
264                                            PortletPreferencesFactoryUtil.getStrictPortletSetup(
265                                                    layout, portletId);
266    
267                                    lastPublishDate = GetterUtil.getLong(
268                                            preferences.getValue(
269                                                    "last-publish-date", StringPool.BLANK));
270                            }
271                            else {
272                                    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(
273                                            groupId, privateLayout);
274    
275                                    lastPublishDate = GetterUtil.getLong(
276                                            layoutSet.getSettingsProperty("last-publish-date"));
277                            }
278    
279                            if (lastPublishDate > 0) {
280                                    endDate = new Date();
281    
282                                    startDate = new Date(lastPublishDate);
283                            }
284                    }
285                    else if (range.equals("last")) {
286                            int rangeLast = ParamUtil.getInteger(portletRequest, "last");
287    
288                            Date now = new Date();
289    
290                            startDate = new Date(now.getTime() - (rangeLast * Time.HOUR));
291    
292                            endDate = now;
293                    }
294    
295                    return new DateRange(startDate, endDate);
296            }
297    
298            @Override
299            public Layout getExportableLayout(ThemeDisplay themeDisplay)
300                    throws PortalException, SystemException {
301    
302                    Layout layout = themeDisplay.getLayout();
303    
304                    if (!layout.isTypeControlPanel()) {
305                            return layout;
306                    }
307    
308                    Group scopeGroup = themeDisplay.getScopeGroup();
309    
310                    if (scopeGroup.isLayout()) {
311                            layout = LayoutLocalServiceUtil.getLayout(scopeGroup.getClassPK());
312                    }
313                    else if (!scopeGroup.isCompany()) {
314                            long defaultPlid = LayoutLocalServiceUtil.getDefaultPlid(
315                                    themeDisplay.getSiteGroupId());
316    
317                            if (defaultPlid > 0) {
318                                    layout = LayoutLocalServiceUtil.getLayout(defaultPlid);
319                            }
320                    }
321    
322                    return layout;
323            }
324    
325            @Override
326            public String getExportableRootPortletId(long companyId, String portletId)
327                    throws Exception {
328    
329                    Portlet portlet = PortletLocalServiceUtil.getPortletById(
330                            companyId, portletId);
331    
332                    if (portlet == null) {
333                            return null;
334                    }
335    
336                    return PortletConstants.getRootPortletId(portletId);
337            }
338    
339            @Override
340            public Map<Long, Boolean> getLayoutIdMap(PortletRequest portletRequest)
341                    throws Exception {
342    
343                    Map<Long, Boolean> layoutIdMap = new LinkedHashMap<Long, Boolean>();
344    
345                    String layoutIdsJSON = ParamUtil.getString(portletRequest, "layoutIds");
346    
347                    if (Validator.isNull(layoutIdsJSON)) {
348                            return layoutIdMap;
349                    }
350    
351                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray(layoutIdsJSON);
352    
353                    for (int i = 0; i < jsonArray.length(); ++i) {
354                            JSONObject jsonObject = jsonArray.getJSONObject(i);
355    
356                            long plid = jsonObject.getLong("plid");
357                            boolean includeChildren = jsonObject.getBoolean("includeChildren");
358    
359                            layoutIdMap.put(plid, includeChildren);
360                    }
361    
362                    return layoutIdMap;
363            }
364    
365            @Override
366            public long[] getLayoutIds(List<Layout> layouts) {
367                    long[] layoutIds = new long[layouts.size()];
368    
369                    for (int i = 0; i < layouts.size(); i++) {
370                            Layout layout = layouts.get(i);
371    
372                            layoutIds[i] = layout.getLayoutId();
373                    }
374    
375                    return layoutIds;
376            }
377    
378            @Override
379            public ManifestSummary getManifestSummary(
380                            long userId, long groupId, Map<String, String[]> parameterMap,
381                            File file)
382                    throws Exception {
383    
384                    final Group group = GroupLocalServiceUtil.getGroup(groupId);
385                    String userIdStrategy = MapUtil.getString(
386                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
387                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
388    
389                    PortletDataContext portletDataContext =
390                            PortletDataContextFactoryUtil.createImportPortletDataContext(
391                                    group.getCompanyId(), groupId, parameterMap,
392                                    getUserIdStrategy(userId, userIdStrategy), zipReader);
393    
394                    final ManifestSummary manifestSummary = new ManifestSummary();
395    
396                    SAXParser saxParser = new SAXParser();
397    
398                    ElementHandler elementHandler = new ElementHandler(
399                            new ManifestSummaryElementProcessor(group, manifestSummary),
400                            new String[] {"header", "portlet", "staged-model"});
401    
402                    saxParser.setContentHandler(elementHandler);
403    
404                    InputStream is = portletDataContext.getZipEntryAsInputStream(
405                            "/manifest.xml");
406    
407                    if (is == null) {
408                            throw new LARFileException("manifest.xml is not in the LAR");
409                    }
410    
411                    String manifestXMLContent = StringUtil.read(is);
412    
413                    saxParser.parse(new InputSource(new StringReader(manifestXMLContent)));
414    
415                    return manifestSummary;
416            }
417    
418            @Override
419            public ManifestSummary getManifestSummary(
420                            long userId, long groupId, Map<String, String[]> parameterMap,
421                            FileEntry fileEntry)
422                    throws Exception {
423    
424                    File file = FileUtil.createTempFile("lar");
425                    InputStream inputStream = DLFileEntryLocalServiceUtil.getFileAsStream(
426                            userId, fileEntry.getFileEntryId(), fileEntry.getVersion(), false);
427    
428                    ManifestSummary manifestSummary = null;
429    
430                    try {
431                            FileUtil.write(file, inputStream);
432    
433                            manifestSummary = getManifestSummary(
434                                    userId, groupId, parameterMap, file);
435                    }
436                    finally {
437                            StreamUtil.cleanUp(inputStream);
438    
439                            FileUtil.delete(file);
440                    }
441    
442                    return manifestSummary;
443            }
444    
445            @Override
446            public long getModelDeletionCount(
447                            final PortletDataContext portletDataContext,
448                            final StagedModelType stagedModelType)
449                    throws PortalException, SystemException {
450    
451                    ActionableDynamicQuery actionableDynamicQuery =
452                            new SystemEventActionableDynamicQuery() {
453    
454                            protected void addCreateDateProperty(DynamicQuery dynamicQuery) {
455                                    if (!portletDataContext.hasDateRange()) {
456                                            return;
457                                    }
458    
459                                    Property createDateProperty = PropertyFactoryUtil.forName(
460                                            "createDate");
461    
462                                    Date startDate = portletDataContext.getStartDate();
463    
464                                    dynamicQuery.add(createDateProperty.ge(startDate));
465    
466                                    Date endDate = portletDataContext.getEndDate();
467    
468                                    dynamicQuery.add(createDateProperty.le(endDate));
469                            }
470    
471                            @Override
472                            protected void addCriteria(DynamicQuery dynamicQuery) {
473                                    Disjunction disjunction = RestrictionsFactoryUtil.disjunction();
474    
475                                    Property groupIdProperty = PropertyFactoryUtil.forName(
476                                            "groupId");
477    
478                                    disjunction.add(groupIdProperty.eq(0L));
479                                    disjunction.add(
480                                            groupIdProperty.eq(portletDataContext.getScopeGroupId()));
481    
482                                    dynamicQuery.add(disjunction);
483    
484                                    Property classNameIdProperty = PropertyFactoryUtil.forName(
485                                            "classNameId");
486    
487                                    dynamicQuery.add(
488                                            classNameIdProperty.eq(stagedModelType.getClassNameId()));
489    
490                                    if (stagedModelType.getReferrerClassNameId() >= 0) {
491                                            Property referrerClassNameIdProperty =
492                                                    PropertyFactoryUtil.forName("referrerClassNameId");
493    
494                                            dynamicQuery.add(
495                                                    referrerClassNameIdProperty.eq(
496                                                            stagedModelType.getReferrerClassNameId()));
497                                    }
498    
499                                    Property typeProperty = PropertyFactoryUtil.forName("type");
500    
501                                    dynamicQuery.add(
502                                            typeProperty.eq(SystemEventConstants.TYPE_DELETE));
503    
504                                    addCreateDateProperty(dynamicQuery);
505                            }
506    
507                            @Override
508                            protected void performAction(Object object) {
509                            }
510    
511                    };
512    
513                    actionableDynamicQuery.setCompanyId(portletDataContext.getCompanyId());
514    
515                    return actionableDynamicQuery.performCount();
516            }
517    
518            @Override
519            public String getSelectedLayoutsJSON(
520                            long groupId, boolean privateLayout, String selectedNodes)
521                    throws SystemException {
522    
523                    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();
524    
525                    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(
526                            groupId, privateLayout, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
527    
528                    for (Layout layout : layouts) {
529                            populateLayoutsJSON(
530                                    jsonArray, layout, StringUtil.split(selectedNodes, 0L));
531                    }
532    
533                    return jsonArray.toString();
534            }
535    
536            @Override
537            public FileEntry getTempFileEntry(
538                            long groupId, long userId, String folderName)
539                    throws PortalException, SystemException {
540    
541                    String[] tempFileEntryNames = LayoutServiceUtil.getTempFileEntryNames(
542                            groupId, folderName);
543    
544                    if (tempFileEntryNames.length == 0) {
545                            return null;
546                    }
547    
548                    return TempFileUtil.getTempFile(
549                            groupId, userId, tempFileEntryNames[0],
550                            DigesterUtil.digestHex(Digester.SHA_256, folderName));
551            }
552    
553            @Override
554            public String replaceExportContentReferences(
555                            PortletDataContext portletDataContext,
556                            StagedModel entityStagedModel, Element entityElement,
557                            String content, boolean exportReferencedContent)
558                    throws Exception {
559    
560                    content = ExportImportHelperUtil.replaceExportDLReferences(
561                            portletDataContext, entityStagedModel, entityElement, content,
562                            exportReferencedContent);
563    
564                    content = ExportImportHelperUtil.replaceExportLayoutReferences(
565                            portletDataContext, content, exportReferencedContent);
566                    content = ExportImportHelperUtil.replaceExportLinksToLayouts(
567                            portletDataContext, entityStagedModel, entityElement, content,
568                            exportReferencedContent);
569    
570                    Element groupElement = entityElement.getParent();
571    
572                    String groupElementName = groupElement.getName();
573    
574                    if (!groupElementName.equals(JournalArticle.class.getSimpleName())) {
575                            content = StringUtil.replace(
576                                    content, StringPool.AMPERSAND_ENCODED, StringPool.AMPERSAND);
577                    }
578    
579                    return content;
580            }
581    
582            @Override
583            public String replaceExportDLReferences(
584                            PortletDataContext portletDataContext,
585                            StagedModel entityStagedModel, Element entityElement,
586                            String content, boolean exportReferencedContent)
587                    throws Exception {
588    
589                    Group group = GroupLocalServiceUtil.getGroup(
590                            portletDataContext.getGroupId());
591    
592                    if (group.isStagingGroup()) {
593                            group = group.getLiveGroup();
594                    }
595    
596                    if (group.isStaged() && !group.isStagedRemotely() &&
597                            !group.isStagedPortlet(PortletKeys.DOCUMENT_LIBRARY)) {
598    
599                            return content;
600                    }
601    
602                    StringBuilder sb = new StringBuilder(content);
603    
604                    String contextPath = PortalUtil.getPathContext();
605    
606                    String[] patterns = {
607                            contextPath.concat("/c/document_library/get_file?"),
608                            contextPath.concat("/documents/"),
609                            contextPath.concat("/image/image_gallery?")
610                    };
611    
612                    int beginPos = -1;
613                    int endPos = content.length();
614    
615                    while (true) {
616                            beginPos = StringUtil.lastIndexOfAny(content, patterns, endPos);
617    
618                            if (beginPos == -1) {
619                                    break;
620                            }
621    
622                            Map<String, String[]> dlReferenceParameters =
623                                    getDLReferenceParameters(
624                                            portletDataContext, content,
625                                            beginPos + contextPath.length(), endPos);
626    
627                            FileEntry fileEntry = getFileEntry(dlReferenceParameters);
628    
629                            if (fileEntry == null) {
630                                    endPos = beginPos - 1;
631    
632                                    continue;
633                            }
634    
635                            endPos = MapUtil.getInteger(dlReferenceParameters, "endPos");
636    
637                            try {
638                                    String rootPortletId = portletDataContext.getRootPortletId();
639    
640                                    if ((rootPortletId != null) &&
641                                            rootPortletId.equals(PortletKeys.JOURNAL_CONTENT)) {
642    
643                                            Map<String, String[]> parameterMap =
644                                                    portletDataContext.getParameterMap();
645    
646                                            String[] referencedContentBehaviorArray = parameterMap.get(
647                                                    PortletDataHandlerControl.getNamespacedControlName(
648                                                            "journal-content", "referenced-content-behavior"));
649    
650                                            String referencedContentBehavior = "include-always";
651    
652                                            if (!ArrayUtil.isEmpty(referencedContentBehaviorArray)) {
653                                                    referencedContentBehavior =
654                                                            referencedContentBehaviorArray[0];
655                                            }
656    
657                                            if (referencedContentBehavior.equals("include-always") ||
658                                                    (referencedContentBehavior.equals(
659                                                            "include-if-modified") &&
660                                                     portletDataContext.isWithinDateRange(
661                                                            fileEntry.getModifiedDate()))) {
662    
663                                                    StagedModelDataHandlerUtil.exportReferenceStagedModel(
664                                                            portletDataContext, entityStagedModel, fileEntry,
665                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY);
666                                            }
667                                            else {
668                                                    portletDataContext.addReferenceElement(
669                                                            entityStagedModel, entityElement, fileEntry,
670                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
671                                            }
672                                    }
673                                    else {
674                                            if (exportReferencedContent) {
675                                                    StagedModelDataHandlerUtil.exportReferenceStagedModel(
676                                                            portletDataContext, entityStagedModel, fileEntry,
677                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY);
678                                            }
679                                            else {
680                                                    portletDataContext.addReferenceElement(
681                                                            entityStagedModel, entityElement, fileEntry,
682                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
683                                            }
684                                    }
685    
686                                    String path = ExportImportPathUtil.getModelPath(fileEntry);
687    
688                                    sb.replace(beginPos, endPos, "[$dl-reference=" + path + "$]");
689    
690                                    deleteTimestampParameters(sb, beginPos);
691                            }
692                            catch (Exception e) {
693                                    if (_log.isDebugEnabled()) {
694                                            _log.debug(e, e);
695                                    }
696                                    else if (_log.isWarnEnabled()) {
697                                            StringBundler exceptionSB = new StringBundler(6);
698    
699                                            exceptionSB.append("Unable to process file entry ");
700                                            exceptionSB.append(fileEntry.getFileEntryId());
701                                            exceptionSB.append(" for ");
702                                            exceptionSB.append(entityStagedModel.getModelClassName());
703                                            exceptionSB.append(" with primary key ");
704                                            exceptionSB.append(entityStagedModel.getPrimaryKeyObj());
705    
706                                            _log.warn(exceptionSB.toString());
707                                    }
708                            }
709    
710                            endPos = beginPos - 1;
711                    }
712    
713                    return sb.toString();
714            }
715    
716            @Override
717            public String replaceExportLayoutReferences(
718                            PortletDataContext portletDataContext, String content,
719                            boolean exportReferencedContent)
720                    throws Exception {
721    
722                    Group group = GroupLocalServiceUtil.getGroup(
723                            portletDataContext.getScopeGroupId());
724    
725                    StringBuilder sb = new StringBuilder(content);
726    
727                    String[] patterns = {"href=", "[["};
728    
729                    int beginPos = -1;
730                    int endPos = content.length();
731                    int offset = 0;
732    
733                    while (true) {
734                            if (beginPos > -1) {
735                                    endPos = beginPos - 1;
736                            }
737    
738                            beginPos = StringUtil.lastIndexOfAny(content, patterns, endPos);
739    
740                            if (beginPos == -1) {
741                                    break;
742                            }
743    
744                            if (content.startsWith("href=", beginPos)) {
745                                    offset = 5;
746    
747                                    char c = content.charAt(beginPos + offset);
748    
749                                    if ((c == CharPool.APOSTROPHE) || (c == CharPool.QUOTE)) {
750                                            offset++;
751                                    }
752                            }
753                            else if (content.charAt(beginPos) == CharPool.OPEN_BRACKET) {
754                                    offset = 2;
755                            }
756    
757                            endPos = StringUtil.indexOfAny(
758                                    content, _LAYOUT_REFERENCE_STOP_CHARS, beginPos + offset,
759                                    endPos);
760    
761                            if (endPos == -1) {
762                                    continue;
763                            }
764    
765                            String url = content.substring(beginPos + offset, endPos);
766    
767                            StringBundler urlSB = new StringBundler(5);
768    
769                            try {
770                                    url = replaceExportHostname(portletDataContext, url, urlSB);
771    
772                                    if (!url.startsWith(StringPool.SLASH)) {
773                                            continue;
774                                    }
775    
776                                    String pathContext = PortalUtil.getPathContext();
777    
778                                    if (pathContext.length() > 1) {
779                                            if (!url.startsWith(pathContext)) {
780                                                    continue;
781                                            }
782    
783                                            urlSB.append(DATA_HANDLER_PATH_CONTEXT);
784    
785                                            url = url.substring(pathContext.length());
786                                    }
787    
788                                    if (!url.startsWith(StringPool.SLASH)) {
789                                            continue;
790                                    }
791    
792                                    int pos = url.indexOf(StringPool.SLASH, 1);
793    
794                                    String localePath = StringPool.BLANK;
795    
796                                    Locale locale = null;
797    
798                                    if (pos != -1) {
799                                            localePath = url.substring(0, pos);
800    
801                                            locale = LocaleUtil.fromLanguageId(
802                                                    localePath.substring(1), true, false);
803                                    }
804    
805                                    if (locale != null) {
806                                            String urlWithoutLocale = url.substring(
807                                                    localePath.length());
808    
809                                            if (urlWithoutLocale.startsWith(
810                                                            _PRIVATE_GROUP_SERVLET_MAPPING) ||
811                                                    urlWithoutLocale.startsWith(
812                                                            _PRIVATE_USER_SERVLET_MAPPING) ||
813                                                    urlWithoutLocale.startsWith(
814                                                            _PUBLIC_GROUP_SERVLET_MAPPING)) {
815    
816                                                    urlSB.append(localePath);
817    
818                                                    url = urlWithoutLocale;
819                                            }
820                                    }
821    
822                                    if (url.startsWith(_PRIVATE_GROUP_SERVLET_MAPPING)) {
823                                            urlSB.append(DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING);
824    
825                                            url = url.substring(
826                                                    _PRIVATE_GROUP_SERVLET_MAPPING.length() - 1);
827                                    }
828                                    else if (url.startsWith(_PRIVATE_USER_SERVLET_MAPPING)) {
829                                            urlSB.append(DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING);
830    
831                                            url = url.substring(
832                                                    _PRIVATE_USER_SERVLET_MAPPING.length() - 1);
833                                    }
834                                    else if (url.startsWith(_PUBLIC_GROUP_SERVLET_MAPPING)) {
835                                            urlSB.append(DATA_HANDLER_PUBLIC_SERVLET_MAPPING);
836    
837                                            url = url.substring(
838                                                    _PUBLIC_GROUP_SERVLET_MAPPING.length() - 1);
839                                    }
840                                    else {
841                                            String urlSBString = urlSB.toString();
842    
843                                            LayoutSet layoutSet = null;
844    
845                                            if (urlSBString.contains(
846                                                            DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL) ||
847                                                    urlSBString.contains(
848                                                            DATA_HANDLER_PUBLIC_LAYOUT_SET_URL)) {
849    
850                                                    layoutSet = group.getPublicLayoutSet();
851                                            }
852                                            else if (urlSBString.contains(
853                                                                    DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL) ||
854                                                             urlSBString.contains(
855                                                                    DATA_HANDLER_PRIVATE_LAYOUT_SET_URL)) {
856    
857                                                    layoutSet = group.getPrivateLayoutSet();
858                                            }
859    
860                                            if (layoutSet == null) {
861                                                    continue;
862                                            }
863    
864                                            boolean privateLayout = layoutSet.isPrivateLayout();
865    
866                                            LayoutFriendlyURL layoutFriendlyUrl =
867                                                    LayoutFriendlyURLLocalServiceUtil.
868                                                            fetchFirstLayoutFriendlyURL(
869                                                                    group.getGroupId(), privateLayout, url);
870    
871                                            if (layoutFriendlyUrl == null) {
872                                                    continue;
873                                            }
874    
875                                            if (privateLayout) {
876                                                    if (group.isUser()) {
877                                                            urlSB.append(
878                                                                    DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING);
879                                                    }
880                                                    else {
881                                                            urlSB.append(
882                                                                    DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING);
883                                                    }
884                                            }
885                                            else {
886                                                    urlSB.append(DATA_HANDLER_PUBLIC_SERVLET_MAPPING);
887                                            }
888    
889                                            urlSB.append(DATA_HANDLER_GROUP_FRIENDLY_URL);
890    
891                                            continue;
892                                    }
893    
894                                    String groupFriendlyURL = group.getFriendlyURL();
895    
896                                    if (url.equals(groupFriendlyURL) ||
897                                            url.startsWith(groupFriendlyURL + StringPool.SLASH)) {
898    
899                                            urlSB.append(DATA_HANDLER_GROUP_FRIENDLY_URL);
900    
901                                            url = url.substring(groupFriendlyURL.length());
902                                    }
903                            }
904                            finally {
905                                    if (urlSB.length() > 0) {
906                                            urlSB.append(url);
907    
908                                            url = urlSB.toString();
909                                    }
910    
911                                    sb.replace(beginPos + offset, endPos, url);
912                            }
913                    }
914    
915                    return sb.toString();
916            }
917    
918            @Override
919            public String replaceExportLinksToLayouts(
920                            PortletDataContext portletDataContext,
921                            StagedModel entityStagedModel, Element entityElement,
922                            String content, boolean exportReferencedContent)
923                    throws Exception {
924    
925                    List<String> oldLinksToLayout = new ArrayList<String>();
926                    List<String> newLinksToLayout = new ArrayList<String>();
927    
928                    Matcher matcher = _exportLinksToLayoutPattern.matcher(content);
929    
930                    while (matcher.find()) {
931                            long layoutId = GetterUtil.getLong(matcher.group(1));
932    
933                            String type = matcher.group(2);
934    
935                            boolean privateLayout = type.startsWith("private");
936    
937                            try {
938                                    Layout layout = LayoutLocalServiceUtil.getLayout(
939                                            portletDataContext.getScopeGroupId(), privateLayout,
940                                            layoutId);
941    
942                                    String oldLinkToLayout = matcher.group(0);
943    
944                                    StringBundler sb = new StringBundler(5);
945    
946                                    sb.append(type);
947                                    sb.append(StringPool.AT);
948                                    sb.append(layout.getUuid());
949                                    sb.append(StringPool.AT);
950                                    sb.append(layout.getFriendlyURL());
951    
952                                    String newLinkToLayout = StringUtil.replace(
953                                            oldLinkToLayout, type, sb.toString());
954    
955                                    oldLinksToLayout.add(oldLinkToLayout);
956                                    newLinksToLayout.add(newLinkToLayout);
957    
958                                    if (exportReferencedContent) {
959                                            StagedModelDataHandlerUtil.exportReferenceStagedModel(
960                                                    portletDataContext, entityStagedModel, layout,
961                                                    PortletDataContext.REFERENCE_TYPE_DEPENDENCY);
962                                    }
963                                    else {
964                                            portletDataContext.addReferenceElement(
965                                                    entityStagedModel, entityElement, layout,
966                                                    PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
967                                    }
968                            }
969                            catch (Exception e) {
970                                    if (_log.isDebugEnabled() || _log.isWarnEnabled()) {
971                                            String message =
972                                                    "Unable to get layout with ID " + layoutId +
973                                                            " in group " + portletDataContext.getScopeGroupId();
974    
975                                            if (_log.isWarnEnabled()) {
976                                                    _log.warn(message);
977                                            }
978                                            else {
979                                                    _log.debug(message, e);
980                                            }
981                                    }
982                            }
983                    }
984    
985                    content = StringUtil.replace(
986                            content, ArrayUtil.toStringArray(oldLinksToLayout.toArray()),
987                            ArrayUtil.toStringArray(newLinksToLayout.toArray()));
988    
989                    return content;
990            }
991    
992            @Override
993            public String replaceImportContentReferences(
994                            PortletDataContext portletDataContext, Element entityElement,
995                            String content, boolean importReferencedContent)
996                    throws Exception {
997    
998                    content = ExportImportHelperUtil.replaceImportDLReferences(
999                            portletDataContext, entityElement, content,
1000                            importReferencedContent);
1001    
1002                    content = ExportImportHelperUtil.replaceImportLayoutReferences(
1003                            portletDataContext, content, importReferencedContent);
1004                    content = ExportImportHelperUtil.replaceImportLinksToLayouts(
1005                            portletDataContext, content, importReferencedContent);
1006    
1007                    return content;
1008            }
1009    
1010            @Override
1011            public String replaceImportDLReferences(
1012                            PortletDataContext portletDataContext, Element entityElement,
1013                            String content, boolean importReferencedContent)
1014                    throws Exception {
1015    
1016                    String elementPath = entityElement.attributeValue("path");
1017    
1018                    StagedModel entityStagedModel =
1019                            (StagedModel)portletDataContext.getZipEntryAsObject(
1020                                    entityElement, elementPath);
1021    
1022                    List<Element> referenceElements =
1023                            portletDataContext.getReferenceElements(
1024                                    entityStagedModel, DLFileEntry.class);
1025    
1026                    for (Element referenceElement : referenceElements) {
1027                            long classPK = GetterUtil.getLong(
1028                                    referenceElement.attributeValue("class-pk"));
1029    
1030                            Element referenceDataElement =
1031                                    portletDataContext.getReferenceDataElement(
1032                                            entityStagedModel, DLFileEntry.class, classPK);
1033    
1034                            String path = null;
1035    
1036                            if (referenceDataElement != null) {
1037                                    path = referenceDataElement.attributeValue("path");
1038                            }
1039    
1040                            long groupId = GetterUtil.getLong(
1041                                    referenceElement.attributeValue("group-id"));
1042    
1043                            if (Validator.isNull(path)) {
1044                                    String className = referenceElement.attributeValue(
1045                                            "class-name");
1046    
1047                                    path = ExportImportPathUtil.getModelPath(
1048                                            groupId, className, classPK);
1049                            }
1050    
1051                            if (!content.contains("[$dl-reference=" + path + "$]")) {
1052                                    continue;
1053                            }
1054    
1055                            try {
1056                                    StagedModelDataHandlerUtil.importReferenceStagedModel(
1057                                            portletDataContext, entityStagedModel, DLFileEntry.class,
1058                                            classPK);
1059                            }
1060                            catch (Exception e) {
1061                                    if (_log.isDebugEnabled()) {
1062                                            _log.debug(e, e);
1063                                    }
1064                                    else if (_log.isWarnEnabled()) {
1065                                            StringBundler sb = new StringBundler(6);
1066    
1067                                            sb.append("Unable to process file entry ");
1068                                            sb.append(classPK);
1069                                            sb.append(" for ");
1070                                            sb.append(entityStagedModel.getModelClassName());
1071                                            sb.append(" with primary key ");
1072                                            sb.append(entityStagedModel.getPrimaryKeyObj());
1073    
1074                                            _log.warn(sb.toString());
1075                                    }
1076                            }
1077    
1078                            String uuid = referenceElement.attributeValue("uuid");
1079    
1080                            long importGroupId = groupId;
1081    
1082                            if (groupId == portletDataContext.getSourceCompanyGroupId()) {
1083                                    importGroupId = portletDataContext.getCompanyGroupId();
1084                            }
1085                            else if (groupId == portletDataContext.getSourceGroupId()) {
1086                                    importGroupId = portletDataContext.getGroupId();
1087                            }
1088    
1089                            FileEntry importedFileEntry = FileEntryUtil.fetchByUUID_R(
1090                                    uuid, importGroupId);
1091    
1092                            if (importedFileEntry == null) {
1093                                    continue;
1094                            }
1095    
1096                            String url = DLUtil.getPreviewURL(
1097                                    importedFileEntry, importedFileEntry.getFileVersion(), null,
1098                                    StringPool.BLANK, false, false);
1099    
1100                            content = StringUtil.replace(
1101                                    content, "[$dl-reference=" + path + "$]", url);
1102                    }
1103    
1104                    return content;
1105            }
1106    
1107            @Override
1108            public String replaceImportLayoutReferences(
1109                            PortletDataContext portletDataContext, String content,
1110                            boolean importReferencedContent)
1111                    throws Exception {
1112    
1113                    String companyPortalURL = StringPool.BLANK;
1114                    String privateLayoutSetPortalURL = StringPool.BLANK;
1115                    String publicLayoutSetPortalURL = StringPool.BLANK;
1116    
1117                    Group group = GroupLocalServiceUtil.getGroup(
1118                            portletDataContext.getScopeGroupId());
1119    
1120                    Company company = CompanyLocalServiceUtil.getCompany(
1121                            group.getCompanyId());
1122    
1123                    LayoutSet privateLayoutSet = group.getPrivateLayoutSet();
1124                    LayoutSet publicLayoutSet = group.getPublicLayoutSet();
1125    
1126                    int portalPort = PortalUtil.getPortalPort(false);
1127    
1128                    if (portalPort != -1) {
1129                            if (Validator.isNotNull(company.getVirtualHostname())) {
1130                                    companyPortalURL = PortalUtil.getPortalURL(
1131                                            company.getVirtualHostname(), portalPort, false);
1132                            }
1133    
1134                            if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
1135                                    privateLayoutSetPortalURL = PortalUtil.getPortalURL(
1136                                            privateLayoutSet.getVirtualHostname(), portalPort, false);
1137                            }
1138    
1139                            if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
1140                                    publicLayoutSetPortalURL = PortalUtil.getPortalURL(
1141                                            publicLayoutSet.getVirtualHostname(), portalPort, false);
1142                            }
1143                    }
1144    
1145                    int securePortalPort = PortalUtil.getPortalPort(true);
1146    
1147                    String companySecurePortalURL = StringPool.BLANK;
1148                    String privateLayoutSetSecurePortalURL = StringPool.BLANK;
1149                    String publicLayoutSetSecurePortalURL = StringPool.BLANK;
1150    
1151                    if (securePortalPort != -1) {
1152                            if (Validator.isNotNull(company.getVirtualHostname())) {
1153                                    companySecurePortalURL = PortalUtil.getPortalURL(
1154                                            company.getVirtualHostname(), securePortalPort, true);
1155                            }
1156    
1157                            if (Validator.isNotNull(privateLayoutSet.getVirtualHostname())) {
1158                                    privateLayoutSetSecurePortalURL = PortalUtil.getPortalURL(
1159                                            privateLayoutSet.getVirtualHostname(), securePortalPort,
1160                                            true);
1161                            }
1162    
1163                            if (Validator.isNotNull(publicLayoutSet.getVirtualHostname())) {
1164                                    publicLayoutSetSecurePortalURL = PortalUtil.getPortalURL(
1165                                            publicLayoutSet.getVirtualHostname(), securePortalPort,
1166                                            true);
1167                            }
1168                    }
1169    
1170                    content = StringUtil.replace(
1171                            content, DATA_HANDLER_COMPANY_SECURE_URL, companySecurePortalURL);
1172                    content = StringUtil.replace(
1173                            content, DATA_HANDLER_COMPANY_URL, companyPortalURL);
1174                    content = StringUtil.replace(
1175                            content, DATA_HANDLER_GROUP_FRIENDLY_URL, group.getFriendlyURL());
1176                    content = StringUtil.replace(
1177                            content, DATA_HANDLER_PATH_CONTEXT, PortalUtil.getPathContext());
1178                    content = StringUtil.replace(
1179                            content, DATA_HANDLER_PRIVATE_GROUP_SERVLET_MAPPING,
1180                            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING);
1181                    content = StringUtil.replace(
1182                            content, DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL,
1183                            privateLayoutSetSecurePortalURL);
1184                    content = StringUtil.replace(
1185                            content, DATA_HANDLER_PRIVATE_LAYOUT_SET_URL,
1186                            privateLayoutSetPortalURL);
1187                    content = StringUtil.replace(
1188                            content, DATA_HANDLER_PRIVATE_USER_SERVLET_MAPPING,
1189                            PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING);
1190                    content = StringUtil.replace(
1191                            content, DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL,
1192                            publicLayoutSetSecurePortalURL);
1193                    content = StringUtil.replace(
1194                            content, DATA_HANDLER_PUBLIC_LAYOUT_SET_URL,
1195                            publicLayoutSetPortalURL);
1196                    content = StringUtil.replace(
1197                            content, DATA_HANDLER_PUBLIC_SERVLET_MAPPING,
1198                            PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING);
1199    
1200                    return content;
1201            }
1202    
1203            @Override
1204            public String replaceImportLinksToLayouts(
1205                            PortletDataContext portletDataContext, String content,
1206                            boolean importReferencedContent)
1207                    throws Exception {
1208    
1209                    List<String> oldLinksToLayout = new ArrayList<String>();
1210                    List<String> newLinksToLayout = new ArrayList<String>();
1211    
1212                    Matcher matcher = _importLinksToLayoutPattern.matcher(content);
1213    
1214                    while (matcher.find()) {
1215                            long oldGroupId = GetterUtil.getLong(matcher.group(7));
1216    
1217                            long newGroupId = oldGroupId;
1218    
1219                            long oldLayoutId = GetterUtil.getLong(matcher.group(1));
1220    
1221                            long newLayoutId = oldLayoutId;
1222    
1223                            String type = matcher.group(2);
1224    
1225                            boolean privateLayout = type.startsWith("private");
1226    
1227                            String layoutUuid = matcher.group(4);
1228                            String friendlyURL = matcher.group(5);
1229    
1230                            try {
1231                                    Layout layout =
1232                                            LayoutLocalServiceUtil.fetchLayoutByUuidAndGroupId(
1233                                                    layoutUuid, portletDataContext.getScopeGroupId(),
1234                                                    privateLayout);
1235    
1236                                    if (layout == null) {
1237                                            layout = LayoutLocalServiceUtil.fetchLayoutByFriendlyURL(
1238                                                    portletDataContext.getScopeGroupId(), privateLayout,
1239                                                    friendlyURL);
1240                                    }
1241    
1242                                    if (layout == null) {
1243                                            if (_log.isWarnEnabled()) {
1244                                                    StringBundler sb = new StringBundler(9);
1245    
1246                                                    sb.append("Unable to get layout with UUID ");
1247                                                    sb.append(layoutUuid);
1248                                                    sb.append(", friendly URL ");
1249                                                    sb.append(friendlyURL);
1250                                                    sb.append(", or ");
1251                                                    sb.append("layout ID ");
1252                                                    sb.append(oldLayoutId);
1253                                                    sb.append(" in group ");
1254                                                    sb.append(portletDataContext.getScopeGroupId());
1255    
1256                                                    _log.warn(sb.toString());
1257                                            }
1258                                    }
1259                                    else {
1260                                            newGroupId = layout.getGroupId();
1261    
1262                                            newLayoutId = layout.getLayoutId();
1263                                    }
1264                            }
1265                            catch (SystemException se) {
1266                                    if (_log.isDebugEnabled() || _log.isWarnEnabled()) {
1267                                            String message =
1268                                                    "Unable to get layout in group " +
1269                                                            portletDataContext.getScopeGroupId();
1270    
1271                                            if (_log.isWarnEnabled()) {
1272                                                    _log.warn(message);
1273                                            }
1274                                            else {
1275                                                    _log.debug(message, se);
1276                                            }
1277                                    }
1278                            }
1279    
1280                            String oldLinkToLayout = matcher.group(0);
1281    
1282                            StringBundler sb = new StringBundler(4);
1283    
1284                            sb.append(StringPool.AT);
1285                            sb.append(layoutUuid);
1286                            sb.append(StringPool.AT);
1287                            sb.append(friendlyURL);
1288    
1289                            String newLinkToLayout = StringUtil.replaceFirst(
1290                                    oldLinkToLayout,
1291                                    new String[] {sb.toString(), String.valueOf(oldLayoutId)},
1292                                    new String[] {StringPool.BLANK, String.valueOf(newLayoutId)});
1293    
1294                            if ((oldGroupId != 0) && (oldGroupId != newGroupId)) {
1295                                    newLinkToLayout = StringUtil.replaceLast(
1296                                            newLinkToLayout, String.valueOf(oldGroupId),
1297                                            String.valueOf(newGroupId));
1298                            }
1299    
1300                            oldLinksToLayout.add(oldLinkToLayout);
1301                            newLinksToLayout.add(newLinkToLayout);
1302                    }
1303    
1304                    content = StringUtil.replace(
1305                            content, ArrayUtil.toStringArray(oldLinksToLayout.toArray()),
1306                            ArrayUtil.toStringArray(newLinksToLayout.toArray()));
1307    
1308                    return content;
1309            }
1310    
1311            @Override
1312            public void updateExportPortletPreferencesClassPKs(
1313                            PortletDataContext portletDataContext, Portlet portlet,
1314                            PortletPreferences portletPreferences, String key, String className,
1315                            Element rootElement)
1316                    throws Exception {
1317    
1318                    String[] oldValues = portletPreferences.getValues(key, null);
1319    
1320                    if (oldValues == null) {
1321                            return;
1322                    }
1323    
1324                    String[] newValues = new String[oldValues.length];
1325    
1326                    for (int i = 0; i < oldValues.length; i++) {
1327                            String oldValue = oldValues[i];
1328    
1329                            String newValue = oldValue;
1330    
1331                            String[] primaryKeys = StringUtil.split(oldValue);
1332    
1333                            for (String primaryKey : primaryKeys) {
1334                                    if (!Validator.isNumber(primaryKey)) {
1335                                            break;
1336                                    }
1337    
1338                                    long primaryKeyLong = GetterUtil.getLong(primaryKey);
1339    
1340                                    String uuid = null;
1341    
1342                                    if (className.equals(AssetCategory.class.getName())) {
1343                                            AssetCategory assetCategory =
1344                                                    AssetCategoryLocalServiceUtil.fetchCategory(
1345                                                            primaryKeyLong);
1346    
1347                                            if (assetCategory != null) {
1348                                                    uuid = assetCategory.getUuid();
1349    
1350                                                    portletDataContext.addReferenceElement(
1351                                                            portlet, rootElement, assetCategory,
1352                                                            AssetCategory.class,
1353                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1354                                            }
1355                                    }
1356                                    else if (className.equals(AssetVocabulary.class.getName())) {
1357                                            AssetVocabulary assetVocabulary =
1358                                                    AssetVocabularyLocalServiceUtil.fetchAssetVocabulary(
1359                                                            primaryKeyLong);
1360    
1361                                            if (assetVocabulary != null) {
1362                                                    uuid = assetVocabulary.getUuid();
1363    
1364                                                    portletDataContext.addReferenceElement(
1365                                                            portlet, rootElement, assetVocabulary,
1366                                                            AssetVocabulary.class,
1367                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1368                                            }
1369                                    }
1370                                    else if (className.equals(DDMStructure.class.getName())) {
1371                                            DDMStructure ddmStructure =
1372                                                    DDMStructureLocalServiceUtil.fetchStructure(
1373                                                            primaryKeyLong);
1374    
1375                                            if (ddmStructure != null) {
1376                                                    uuid = ddmStructure.getUuid();
1377    
1378                                                    portletDataContext.addReferenceElement(
1379                                                            portlet, rootElement, ddmStructure,
1380                                                            DDMStructure.class,
1381                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1382                                            }
1383                                    }
1384                                    else if (className.equals(DLFileEntryType.class.getName())) {
1385                                            DLFileEntryType dlFileEntryType =
1386                                                    DLFileEntryTypeLocalServiceUtil.fetchFileEntryType(
1387                                                            primaryKeyLong);
1388    
1389                                            if (dlFileEntryType != null) {
1390                                                    uuid = dlFileEntryType.getUuid();
1391    
1392                                                    portletDataContext.addReferenceElement(
1393                                                            portlet, rootElement, dlFileEntryType,
1394                                                            DLFileEntryType.class,
1395                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1396                                            }
1397                                    }
1398                                    else if (className.equals(Organization.class.getName())) {
1399                                            Organization organization =
1400                                                    OrganizationLocalServiceUtil.fetchOrganization(
1401                                                            primaryKeyLong);
1402    
1403                                            if (organization != null) {
1404                                                    uuid = organization.getUuid();
1405    
1406                                                    portletDataContext.addReferenceElement(
1407                                                            portlet, rootElement, organization,
1408                                                            Organization.class,
1409                                                            PortletDataContext.REFERENCE_TYPE_DEPENDENCY, true);
1410                                            }
1411                                    }
1412    
1413                                    if (Validator.isNull(uuid)) {
1414                                            if (_log.isWarnEnabled()) {
1415                                                    _log.warn(
1416                                                            "Unable to get UUID for class " + className +
1417                                                                    " with primary key " + primaryKeyLong);
1418                                            }
1419    
1420                                            continue;
1421                                    }
1422    
1423                                    newValue = StringUtil.replace(newValue, primaryKey, uuid);
1424                            }
1425    
1426                            newValues[i] = newValue;
1427                    }
1428    
1429                    portletPreferences.setValues(key, newValues);
1430            }
1431    
1432            @Override
1433            public void updateImportPortletPreferencesClassPKs(
1434                            PortletDataContext portletDataContext,
1435                            PortletPreferences portletPreferences, String key, Class<?> clazz,
1436                            long companyGroupId)
1437                    throws Exception {
1438    
1439                    String[] oldValues = portletPreferences.getValues(key, null);
1440    
1441                    if (oldValues == null) {
1442                            return;
1443                    }
1444    
1445                    Map<Long, Long> primaryKeys =
1446                            (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(clazz);
1447    
1448                    String[] newValues = new String[oldValues.length];
1449    
1450                    for (int i = 0; i < oldValues.length; i++) {
1451                            String oldValue = oldValues[i];
1452    
1453                            String newValue = oldValue;
1454    
1455                            String[] uuids = StringUtil.split(oldValue);
1456    
1457                            for (String uuid : uuids) {
1458                                    Long newPrimaryKey = null;
1459    
1460                                    if (Validator.isNumber(uuid)) {
1461                                            long oldPrimaryKey = GetterUtil.getLong(uuid);
1462    
1463                                            newPrimaryKey = MapUtil.getLong(
1464                                                    primaryKeys, oldPrimaryKey, oldPrimaryKey);
1465                                    }
1466                                    else {
1467                                            String className = clazz.getName();
1468    
1469                                            if (className.equals(AssetCategory.class.getName())) {
1470                                                    AssetCategory assetCategory =
1471                                                            AssetCategoryUtil.fetchByUUID_G(
1472                                                                    uuid, portletDataContext.getScopeGroupId());
1473    
1474                                                    if (assetCategory == null) {
1475                                                            assetCategory = AssetCategoryUtil.fetchByUUID_G(
1476                                                                    uuid, companyGroupId);
1477                                                    }
1478    
1479                                                    if (assetCategory != null) {
1480                                                            newPrimaryKey = assetCategory.getCategoryId();
1481                                                    }
1482                                            }
1483                                            else if (className.equals(
1484                                                                    AssetVocabulary.class.getName())) {
1485    
1486                                                    AssetVocabulary assetVocabulary =
1487                                                            AssetVocabularyUtil.fetchByUUID_G(
1488                                                                    uuid, portletDataContext.getScopeGroupId());
1489    
1490                                                    if (assetVocabulary == null) {
1491                                                            assetVocabulary = AssetVocabularyUtil.fetchByUUID_G(
1492                                                                    uuid, companyGroupId);
1493                                                    }
1494    
1495                                                    if (assetVocabulary != null) {
1496                                                            newPrimaryKey = assetVocabulary.getVocabularyId();
1497                                                    }
1498                                            }
1499                                            else if (className.equals(DDMStructure.class.getName())) {
1500                                                    DDMStructure ddmStructure =
1501                                                            DDMStructureUtil.fetchByUUID_G(
1502                                                                    uuid, portletDataContext.getScopeGroupId());
1503    
1504                                                    if (ddmStructure == null) {
1505                                                            ddmStructure = DDMStructureUtil.fetchByUUID_G(
1506                                                                    uuid, companyGroupId);
1507                                                    }
1508    
1509                                                    if (ddmStructure != null) {
1510                                                            newPrimaryKey = ddmStructure.getStructureId();
1511                                                    }
1512                                            }
1513                                            else if (className.equals(
1514                                                                    DLFileEntryType.class.getName())) {
1515    
1516                                                    DLFileEntryType dlFileEntryType =
1517                                                            DLFileEntryTypeUtil.fetchByUUID_G(
1518                                                                    uuid, portletDataContext.getScopeGroupId());
1519    
1520                                                    if (dlFileEntryType == null) {
1521                                                            dlFileEntryType = DLFileEntryTypeUtil.fetchByUUID_G(
1522                                                                    uuid, companyGroupId);
1523                                                    }
1524    
1525                                                    if (dlFileEntryType != null) {
1526                                                            newPrimaryKey =
1527                                                                    dlFileEntryType.getFileEntryTypeId();
1528                                                    }
1529                                            }
1530                                            else if (className.equals(Organization.class.getName())) {
1531                                                    Organization organization =
1532                                                            OrganizationUtil.fetchByUuid_C_First(
1533                                                                    uuid, portletDataContext.getCompanyId(), null);
1534    
1535                                                    if (organization != null) {
1536                                                            newPrimaryKey = organization.getOrganizationId();
1537                                                    }
1538                                            }
1539                                    }
1540    
1541                                    if (Validator.isNull(newPrimaryKey)) {
1542                                            if (_log.isWarnEnabled()) {
1543                                                    StringBundler sb = new StringBundler(8);
1544    
1545                                                    sb.append("Unable to get primary key for ");
1546                                                    sb.append(clazz);
1547                                                    sb.append(" with UUID ");
1548                                                    sb.append(uuid);
1549                                                    sb.append(" in company group ");
1550                                                    sb.append(companyGroupId);
1551                                                    sb.append(" or in group ");
1552                                                    sb.append(portletDataContext.getScopeGroupId());
1553    
1554                                                    _log.warn(sb.toString());
1555                                            }
1556                                    }
1557                                    else {
1558                                            newValue = StringUtil.replace(
1559                                                    newValue, uuid, newPrimaryKey.toString());
1560                                    }
1561                            }
1562    
1563                            newValues[i] = newValue;
1564                    }
1565    
1566                    portletPreferences.setValues(key, newValues);
1567            }
1568    
1569            @Override
1570            public MissingReferences validateMissingReferences(
1571                            long userId, long groupId, Map<String, String[]> parameterMap,
1572                            File file)
1573                    throws Exception {
1574    
1575                    final MissingReferences missingReferences = new MissingReferences();
1576    
1577                    Group group = GroupLocalServiceUtil.getGroup(groupId);
1578                    String userIdStrategy = MapUtil.getString(
1579                            parameterMap, PortletDataHandlerKeys.USER_ID_STRATEGY);
1580                    ZipReader zipReader = ZipReaderFactoryUtil.getZipReader(file);
1581    
1582                    final PortletDataContext portletDataContext =
1583                            PortletDataContextFactoryUtil.createImportPortletDataContext(
1584                                    group.getCompanyId(), groupId, parameterMap,
1585                                    getUserIdStrategy(userId, userIdStrategy), zipReader);
1586    
1587                    SAXParser saxParser = new SAXParser();
1588    
1589                    ElementHandler elementHandler = new ElementHandler(
1590                            new ElementProcessor() {
1591    
1592                                    @Override
1593                                    public void processElement(Element element) {
1594                                            MissingReference missingReference =
1595                                                    validateMissingReference(portletDataContext, element);
1596    
1597                                            if (missingReference != null) {
1598                                                    missingReferences.add(missingReference);
1599                                            }
1600                                    }
1601    
1602                            },
1603                            new String[] {"missing-reference"});
1604    
1605                    saxParser.setContentHandler(elementHandler);
1606    
1607                    saxParser.parse(
1608                            new InputSource(
1609                                    portletDataContext.getZipEntryAsInputStream("/manifest.xml")));
1610    
1611                    return missingReferences;
1612            }
1613    
1614            @Override
1615            public void writeManifestSummary(
1616                    Document document, ManifestSummary manifestSummary) {
1617    
1618                    Element rootElement = document.getRootElement();
1619    
1620                    Element manifestSummaryElement = rootElement.addElement(
1621                            "manifest-summary");
1622    
1623                    for (String manifestSummaryKey :
1624                                    manifestSummary.getManifestSummaryKeys()) {
1625    
1626                            Element element = manifestSummaryElement.addElement("staged-model");
1627    
1628                            element.addAttribute("manifest-summary-key", manifestSummaryKey);
1629    
1630                            long modelAdditionCount = manifestSummary.getModelAdditionCount(
1631                                    manifestSummaryKey);
1632    
1633                            if (modelAdditionCount > 0) {
1634                                    element.addAttribute(
1635                                            "addition-count", String.valueOf(modelAdditionCount));
1636                            }
1637    
1638                            long modelDeletionCount = manifestSummary.getModelDeletionCount(
1639                                    manifestSummaryKey);
1640    
1641                            if (modelDeletionCount > 0) {
1642                                    element.addAttribute(
1643                                            "deletion-count", String.valueOf(modelDeletionCount));
1644                            }
1645                    }
1646            }
1647    
1648            protected void deleteTimestampParameters(StringBuilder sb, int beginPos) {
1649                    beginPos = sb.indexOf(StringPool.CLOSE_BRACKET, beginPos);
1650    
1651                    if ((beginPos == -1) || (beginPos == (sb.length() - 1)) ||
1652                            (sb.charAt(beginPos + 1) != CharPool.QUESTION)) {
1653    
1654                            return;
1655                    }
1656    
1657                    int endPos = StringUtil.indexOfAny(
1658                            sb.toString(), _DL_REFERENCE_LEGACY_STOP_CHARS, beginPos + 2);
1659    
1660                    if (endPos == -1) {
1661                            return;
1662                    }
1663    
1664                    String urlParams = sb.substring(beginPos + 1, endPos);
1665    
1666                    urlParams = HttpUtil.removeParameter(urlParams, "t");
1667    
1668                    sb.replace(beginPos + 1, endPos, urlParams);
1669            }
1670    
1671            protected Map<String, String[]> getDLReferenceParameters(
1672                    PortletDataContext portletDataContext, String content, int beginPos,
1673                    int endPos) {
1674    
1675                    boolean legacyURL = true;
1676                    char[] stopChars = _DL_REFERENCE_LEGACY_STOP_CHARS;
1677    
1678                    if (content.startsWith("/documents/", beginPos)) {
1679                            legacyURL = false;
1680                            stopChars = _DL_REFERENCE_STOP_CHARS;
1681                    }
1682    
1683                    endPos = StringUtil.indexOfAny(content, stopChars, beginPos, endPos);
1684    
1685                    if (endPos == -1) {
1686                            return null;
1687                    }
1688    
1689                    Map<String, String[]> map = new HashMap<String, String[]>();
1690    
1691                    String dlReference = content.substring(beginPos, endPos);
1692    
1693                    while (dlReference.contains(StringPool.AMPERSAND_ENCODED)) {
1694                            dlReference = dlReference.replace(
1695                                    StringPool.AMPERSAND_ENCODED, StringPool.AMPERSAND);
1696                    }
1697    
1698                    if (!legacyURL) {
1699                            String[] pathArray = dlReference.split(StringPool.SLASH);
1700    
1701                            map.put("groupId", new String[] {pathArray[2]});
1702    
1703                            if (pathArray.length == 4) {
1704                                    map.put("uuid", new String[] {pathArray[3]});
1705                            }
1706                            else if (pathArray.length == 5) {
1707                                    map.put("folderId", new String[] {pathArray[3]});
1708                                    map.put(
1709                                            "title", new String[] {HttpUtil.decodeURL(pathArray[4])});
1710                            }
1711                            else if (pathArray.length > 5) {
1712                                    map.put("uuid", new String[] {pathArray[5]});
1713                            }
1714                    }
1715                    else {
1716                            dlReference = dlReference.substring(
1717                                    dlReference.indexOf(CharPool.QUESTION) + 1);
1718    
1719                            map = HttpUtil.parameterMapFromString(dlReference);
1720    
1721                            if (map.containsKey("img_id")) {
1722                                    map.put("image_id", map.get("img_id"));
1723                            }
1724                            else if (map.containsKey("i_id")) {
1725                                    map.put("image_id", map.get("i_id"));
1726                            }
1727                    }
1728    
1729                    map.put("endPos", new String[] {String.valueOf(endPos)});
1730    
1731                    String groupIdString = MapUtil.getString(map, "groupId");
1732    
1733                    if (groupIdString.equals("@group_id@")) {
1734                            groupIdString = String.valueOf(
1735                                    portletDataContext.getScopeGroupId());
1736    
1737                            map.put("groupId", new String[] {groupIdString});
1738                    }
1739    
1740                    return map;
1741            }
1742    
1743            protected FileEntry getFileEntry(Map<String, String[]> map) {
1744                    if (map == null) {
1745                            return null;
1746                    }
1747    
1748                    FileEntry fileEntry = null;
1749    
1750                    try {
1751                            String uuid = MapUtil.getString(map, "uuid");
1752                            long groupId = MapUtil.getLong(map, "groupId");
1753    
1754                            if (Validator.isNotNull(uuid)) {
1755                                    fileEntry =
1756                                            DLAppLocalServiceUtil.getFileEntryByUuidAndGroupId(
1757                                                    uuid, groupId);
1758                            }
1759                            else {
1760                                    if (map.containsKey("folderId")) {
1761                                            long folderId = MapUtil.getLong(map, "folderId");
1762                                            String name = MapUtil.getString(map, "name");
1763                                            String title = MapUtil.getString(map, "title");
1764    
1765                                            if (Validator.isNotNull(title)) {
1766                                                    fileEntry = DLAppLocalServiceUtil.getFileEntry(
1767                                                            groupId, folderId, title);
1768                                            }
1769                                            else {
1770                                                    DLFileEntry dlFileEntry =
1771                                                            DLFileEntryLocalServiceUtil.fetchFileEntryByName(
1772                                                                    groupId, folderId, name);
1773    
1774                                                    if (dlFileEntry != null) {
1775                                                            fileEntry = DLAppLocalServiceUtil.getFileEntry(
1776                                                                    dlFileEntry.getFileEntryId());
1777                                                    }
1778                                            }
1779                                    }
1780                                    else if (map.containsKey("image_id")) {
1781                                            DLFileEntry dlFileEntry =
1782                                                    DLFileEntryLocalServiceUtil.fetchFileEntryByAnyImageId(
1783                                                            MapUtil.getLong(map, "image_id"));
1784    
1785                                            if (dlFileEntry != null) {
1786                                                    fileEntry = DLAppLocalServiceUtil.getFileEntry(
1787                                                            dlFileEntry.getFileEntryId());
1788                                            }
1789                                    }
1790                            }
1791                    }
1792                    catch (Exception e) {
1793                            if (_log.isDebugEnabled()) {
1794                                    _log.debug(e, e);
1795                            }
1796                            else if (_log.isWarnEnabled()) {
1797                                    _log.warn(e.getMessage());
1798                            }
1799                    }
1800    
1801                    return fileEntry;
1802            }
1803    
1804            protected UserIdStrategy getUserIdStrategy(
1805                            long userId, String userIdStrategy)
1806                    throws Exception {
1807    
1808                    User user = UserLocalServiceUtil.getUserById(userId);
1809    
1810                    if (UserIdStrategy.ALWAYS_CURRENT_USER_ID.equals(userIdStrategy)) {
1811                            return new AlwaysCurrentUserIdStrategy(user);
1812                    }
1813    
1814                    return new CurrentUserIdStrategy(user);
1815            }
1816    
1817            protected boolean populateLayoutsJSON(
1818                            JSONArray layoutsJSONArray, Layout layout, long[] selectedLayoutIds)
1819                    throws SystemException {
1820    
1821                    List<Layout> childLayouts = layout.getChildren();
1822                    JSONArray childLayoutsJSONArray = null;
1823                    boolean includeChildren = true;
1824    
1825                    if (!childLayouts.isEmpty()) {
1826                            childLayoutsJSONArray = JSONFactoryUtil.createJSONArray();
1827    
1828                            for (Layout childLayout : childLayouts) {
1829                                    if (!populateLayoutsJSON(
1830                                                    childLayoutsJSONArray, childLayout,
1831                                                    selectedLayoutIds)) {
1832    
1833                                            includeChildren = false;
1834                                    }
1835                            }
1836                    }
1837    
1838                    boolean checked = ArrayUtil.contains(
1839                            selectedLayoutIds, layout.getLayoutId());
1840    
1841                    if (checked) {
1842                            JSONObject layoutJSONObject = JSONFactoryUtil.createJSONObject();
1843    
1844                            layoutJSONObject.put("includeChildren", includeChildren);
1845                            layoutJSONObject.put("plid", layout.getPlid());
1846    
1847                            layoutsJSONArray.put(layoutJSONObject);
1848                    }
1849    
1850                    if (checked && includeChildren) {
1851                            return true;
1852                    }
1853    
1854                    if (childLayoutsJSONArray != null) {
1855    
1856                            // We want a 1 level array and not an array of arrays
1857    
1858                            for (int i = 0; i < childLayoutsJSONArray.length(); i++) {
1859                                    layoutsJSONArray.put(childLayoutsJSONArray.getJSONObject(i));
1860                            }
1861                    }
1862    
1863                    return false;
1864            }
1865    
1866            protected String replaceExportHostname(
1867                            PortletDataContext portletDataContext, String url,
1868                            StringBundler urlSB)
1869                    throws PortalException, SystemException {
1870    
1871                    if (!HttpUtil.hasProtocol(url)) {
1872                            return url;
1873                    }
1874    
1875                    boolean secure = HttpUtil.isSecure(url);
1876    
1877                    int portalPort = PortalUtil.getPortalPort(secure);
1878    
1879                    if (portalPort == -1) {
1880                            return url;
1881                    }
1882    
1883                    Group group = GroupLocalServiceUtil.getGroup(
1884                            portletDataContext.getScopeGroupId());
1885    
1886                    LayoutSet publicLayoutSet = group.getPublicLayoutSet();
1887    
1888                    String publicLayoutSetVirtualHostname =
1889                            publicLayoutSet.getVirtualHostname();
1890    
1891                    String portalUrl = StringPool.BLANK;
1892    
1893                    if (Validator.isNotNull(publicLayoutSetVirtualHostname)) {
1894                            portalUrl = PortalUtil.getPortalURL(
1895                                    publicLayoutSetVirtualHostname, portalPort, secure);
1896    
1897                            if (url.startsWith(portalUrl)) {
1898                                    if (secure) {
1899                                            urlSB.append(DATA_HANDLER_PUBLIC_LAYOUT_SET_SECURE_URL);
1900                                    }
1901                                    else {
1902                                            urlSB.append(DATA_HANDLER_PUBLIC_LAYOUT_SET_URL);
1903                                    }
1904    
1905                                    return url.substring(portalUrl.length());
1906                            }
1907                    }
1908    
1909                    LayoutSet privateLayoutSet = group.getPrivateLayoutSet();
1910    
1911                    String privateLayoutSetVirtualHostname =
1912                            privateLayoutSet.getVirtualHostname();
1913    
1914                    if (Validator.isNotNull(privateLayoutSetVirtualHostname)) {
1915                            portalUrl = PortalUtil.getPortalURL(
1916                                    privateLayoutSetVirtualHostname, portalPort, secure);
1917    
1918                            if (url.startsWith(portalUrl)) {
1919                                    if (secure) {
1920                                            urlSB.append(DATA_HANDLER_PRIVATE_LAYOUT_SET_SECURE_URL);
1921                                    }
1922                                    else {
1923                                            urlSB.append(DATA_HANDLER_PRIVATE_LAYOUT_SET_URL);
1924                                    }
1925    
1926                                    return url.substring(portalUrl.length());
1927                            }
1928                    }
1929    
1930                    Company company = CompanyLocalServiceUtil.getCompany(
1931                            group.getCompanyId());
1932    
1933                    String companyVirtualHostname = company.getVirtualHostname();
1934    
1935                    if (Validator.isNotNull(companyVirtualHostname)) {
1936                            portalUrl = PortalUtil.getPortalURL(
1937                                    companyVirtualHostname, portalPort, secure);
1938    
1939                            if (url.startsWith(portalUrl)) {
1940                                    if (secure) {
1941                                            urlSB.append(DATA_HANDLER_COMPANY_SECURE_URL);
1942                                    }
1943                                    else {
1944                                            urlSB.append(DATA_HANDLER_COMPANY_URL);
1945                                    }
1946    
1947                                    return url.substring(portalUrl.length());
1948                            }
1949                    }
1950    
1951                    portalUrl = PortalUtil.getPortalURL("localhost", portalPort, secure);
1952    
1953                    if (url.startsWith(portalUrl)) {
1954                            return url.substring(portalUrl.length());
1955                    }
1956    
1957                    return url;
1958            }
1959    
1960            protected MissingReference validateMissingReference(
1961                    PortletDataContext portletDataContext, Element element) {
1962    
1963                    String className = element.attributeValue("class-name");
1964    
1965                    StagedModelDataHandler<?> stagedModelDataHandler =
1966                            StagedModelDataHandlerRegistryUtil.getStagedModelDataHandler(
1967                                    className);
1968    
1969                    if (!stagedModelDataHandler.validateReference(
1970                                    portletDataContext, element)) {
1971    
1972                            MissingReference missingReference = new MissingReference(element);
1973    
1974                            Map<Long, Long> groupIds =
1975                                    (Map<Long, Long>)portletDataContext.getNewPrimaryKeysMap(
1976                                            Group.class);
1977    
1978                            long groupId = MapUtil.getLong(
1979                                    groupIds,
1980                                    GetterUtil.getLong(element.attributeValue("group-id")));
1981    
1982                            missingReference.setGroupId(groupId);
1983    
1984                            return missingReference;
1985                    }
1986    
1987                    return null;
1988            }
1989    
1990            private static final char[] _DL_REFERENCE_LEGACY_STOP_CHARS = {
1991                    CharPool.APOSTROPHE, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
1992                    CharPool.CLOSE_PARENTHESIS, CharPool.GREATER_THAN, CharPool.LESS_THAN,
1993                    CharPool.PIPE, CharPool.QUOTE, CharPool.SPACE
1994            };
1995    
1996            private static final char[] _DL_REFERENCE_STOP_CHARS = {
1997                    CharPool.APOSTROPHE, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
1998                    CharPool.CLOSE_PARENTHESIS, CharPool.GREATER_THAN, CharPool.LESS_THAN,
1999                    CharPool.PIPE, CharPool.QUESTION, CharPool.QUOTE, CharPool.SPACE
2000            };
2001    
2002            private static final String[] _EXTRANEOUS_REINDEX_PRIMARY_KEYS_MAPS_KEYS = {
2003                    AssetCategory.class + ".uuid", DDMStructure.class + ".ddmStructureKey",
2004                    DDMTemplate.class + ".ddmTemplateKey", Layout.class + ".layout"};
2005    
2006            private static final char[] _LAYOUT_REFERENCE_STOP_CHARS = {
2007                    CharPool.APOSTROPHE, CharPool.CLOSE_BRACKET, CharPool.CLOSE_CURLY_BRACE,
2008                    CharPool.CLOSE_PARENTHESIS, CharPool.GREATER_THAN, CharPool.LESS_THAN,
2009                    CharPool.PIPE, CharPool.QUESTION, CharPool.QUOTE, CharPool.SPACE
2010            };
2011    
2012            private static final String _PRIVATE_GROUP_SERVLET_MAPPING =
2013                    PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_GROUP_SERVLET_MAPPING +
2014                            StringPool.SLASH;
2015    
2016            private static final String _PRIVATE_USER_SERVLET_MAPPING =
2017                    PropsValues.LAYOUT_FRIENDLY_URL_PRIVATE_USER_SERVLET_MAPPING +
2018                            StringPool.SLASH;
2019    
2020            private static final String _PUBLIC_GROUP_SERVLET_MAPPING =
2021                    PropsValues.LAYOUT_FRIENDLY_URL_PUBLIC_SERVLET_MAPPING +
2022                            StringPool.SLASH;
2023    
2024            private static Log _log = LogFactoryUtil.getLog(
2025                    ExportImportHelperImpl.class);
2026    
2027            private Pattern _exportLinksToLayoutPattern = Pattern.compile(
2028                    "\\[([\\d]+)@(private(-group|-user)?|public)(@([\\d]+))?\\]");
2029            private Pattern _importLinksToLayoutPattern = Pattern.compile(
2030                    "\\[([\\d]+)@(private(-group|-user)?|public)@(\\p{XDigit}{8}\\-" +
2031                            "(?:\\p{XDigit}{4}\\-){3}\\p{XDigit}{12})@([a-z0-9./_-]*)" +
2032                                    "(@([\\d]+))?\\]");
2033    
2034            private class ManifestSummaryElementProcessor implements ElementProcessor {
2035    
2036                    public ManifestSummaryElementProcessor(
2037                            Group group, ManifestSummary manifestSummary) {
2038    
2039                            _group = group;
2040                            _manifestSummary = manifestSummary;
2041                    }
2042    
2043                    @Override
2044                    public void processElement(Element element) {
2045                            String elementName = element.getName();
2046    
2047                            if (elementName.equals("header")) {
2048                                    String exportDateString = element.attributeValue("export-date");
2049    
2050                                    Date exportDate = GetterUtil.getDate(
2051                                            exportDateString,
2052                                            DateFormatFactoryUtil.getSimpleDateFormat(
2053                                                    Time.RFC822_FORMAT));
2054    
2055                                    _manifestSummary.setExportDate(exportDate);
2056                            }
2057                            else if (elementName.equals("portlet")) {
2058                                    String portletId = element.attributeValue("portlet-id");
2059    
2060                                    Portlet portlet = null;
2061    
2062                                    try {
2063                                            portlet = PortletLocalServiceUtil.getPortletById(
2064                                                    _group.getCompanyId(), portletId);
2065                                    }
2066                                    catch (Exception e) {
2067                                            return;
2068                                    }
2069    
2070                                    PortletDataHandler portletDataHandler =
2071                                            portlet.getPortletDataHandlerInstance();
2072    
2073                                    if (portletDataHandler == null) {
2074                                            return;
2075                                    }
2076    
2077                                    String[] configurationPortletOptions = StringUtil.split(
2078                                            element.attributeValue("portlet-configuration"));
2079    
2080                                    PortletDataHandlerControl[] portletDataHandlerControls =
2081                                            portletDataHandler.getImportConfigurationControls(
2082                                                    configurationPortletOptions);
2083    
2084                                    if (ArrayUtil.isNotEmpty(portletDataHandlerControls)) {
2085                                            _manifestSummary.addConfigurationPortlet(
2086                                                    portlet, configurationPortletOptions);
2087                                    }
2088    
2089                                    if (!(portletDataHandler instanceof
2090                                                    DefaultConfigurationPortletDataHandler) &&
2091                                            portletDataHandler.isDataSiteLevel() &&
2092                                            GetterUtil.getBoolean(
2093                                                    element.attributeValue("portlet-data"))) {
2094    
2095                                            _manifestSummary.addDataPortlet(portlet);
2096                                    }
2097                            }
2098                            else if (elementName.equals("staged-model")) {
2099                                    String manifestSummaryKey = element.attributeValue(
2100                                            "manifest-summary-key");
2101    
2102                                    long modelAdditionCount = GetterUtil.getLong(
2103                                            element.attributeValue("addition-count"));
2104    
2105                                    _manifestSummary.addModelAdditionCount(
2106                                            manifestSummaryKey, modelAdditionCount);
2107    
2108                                    long modelDeletionCount = GetterUtil.getLong(
2109                                            element.attributeValue("deletion-count"));
2110    
2111                                    _manifestSummary.addModelDeletionCount(
2112                                            manifestSummaryKey, modelDeletionCount);
2113                            }
2114                    }
2115    
2116                    private Group _group;
2117                    private ManifestSummary _manifestSummary;
2118    
2119            }
2120    
2121    }