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