public Image updateImage(long imageId, InputStream is) throws PortalException, SystemException {

    Image image = getImage(is);

    return updateImage(
        imageId,
        image.getTextObj(),
        image.getType(),
        image.getHeight(),
        image.getWidth(),
        image.getSize());
  }
Пример #2
0
  @Override
  public File getSmallImageFile() throws PortalException, SystemException {
    if (_smallImageFile == null) {
      Image smallImage = fetchSmallImage();

      if (smallImage != null) {
        _smallImageFile = getSmallImageFile(smallImage.getTextObj());
      }
    }

    return _smallImageFile;
  }
  protected byte[] getImageBytes(HttpServletRequest request, Image image) {
    try {
      if (!PropsValues.IMAGE_AUTO_SCALE) {
        return image.getTextObj();
      }

      ImageBag imageBag = null;

      if (image.getImageId() == 0) {
        imageBag = ImageToolUtil.read(image.getTextObj());

        RenderedImage renderedImage = imageBag.getRenderedImage();

        image.setHeight(renderedImage.getHeight());
        image.setWidth(renderedImage.getWidth());
      }

      int height = ParamUtil.getInteger(request, "height", image.getHeight());
      int width = ParamUtil.getInteger(request, "width", image.getWidth());

      if ((height >= image.getHeight()) && (width >= image.getWidth())) {
        return image.getTextObj();
      }

      if (image.getImageId() != 0) {
        imageBag = ImageToolUtil.read(image.getTextObj());
      }

      RenderedImage renderedImage = ImageToolUtil.scale(imageBag.getRenderedImage(), height, width);

      return ImageToolUtil.getBytes(renderedImage, imageBag.getType());
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        _log.warn("Error scaling image " + image.getImageId(), e);
      }
    }

    return image.getTextObj();
  }
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, BlogsEntry entry)
      throws Exception {

    Element entryElement = portletDataContext.getExportDataElement(entry);

    if (entry.isSmallImage()) {
      Image smallImage = _imageLocalService.fetchImage(entry.getSmallImageId());

      if (smallImage != null) {
        String smallImagePath =
            ExportImportPathUtil.getModelPath(
                entry, smallImage.getImageId() + StringPool.PERIOD + smallImage.getType());

        entryElement.addAttribute("small-image-path", smallImagePath);

        entry.setSmallImageType(smallImage.getType());

        portletDataContext.addZipEntry(smallImagePath, smallImage.getTextObj());
      }
    }

    if (entry.getSmallImageFileEntryId() != 0) {
      FileEntry fileEntry =
          PortletFileRepositoryUtil.getPortletFileEntry(entry.getSmallImageFileEntryId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, entry, fileEntry, PortletDataContext.REFERENCE_TYPE_WEAK);
    }

    if (entry.getCoverImageFileEntryId() != 0) {
      FileEntry fileEntry =
          PortletFileRepositoryUtil.getPortletFileEntry(entry.getCoverImageFileEntryId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, entry, fileEntry, PortletDataContext.REFERENCE_TYPE_WEAK);
    }

    String content =
        _blogsEntryExportImportContentProcessor.replaceExportContentReferences(
            portletDataContext,
            entry,
            entry.getContent(),
            portletDataContext.getBooleanParameter("blogs", "referenced-content"),
            true);

    entry.setContent(content);

    portletDataContext.addClassedModel(
        entryElement, ExportImportPathUtil.getModelPath(entry), entry);
  }
  protected List<byte[]> getImages(UploadPortletRequest uploadPortletRequest, String imagePrefix)
      throws Exception {

    List<byte[]> images = new ArrayList<>();

    for (String name : getSortedParameterNames(uploadPortletRequest, imagePrefix)) {

      String contentType = uploadPortletRequest.getContentType(name);

      if (!MimeTypesUtil.isWebImage(contentType)) {
        throw new ProductEntryScreenshotsException();
      }

      int priority = GetterUtil.getInteger(name.substring(imagePrefix.length()));

      boolean preserveScreenshot =
          ParamUtil.getBoolean(uploadPortletRequest, "preserveScreenshot" + priority);

      byte[] bytes = null;

      if (preserveScreenshot) {
        SCProductScreenshot productScreenshot =
            getProductScreenshot(uploadPortletRequest, priority);

        Image image = null;

        if (imagePrefix.equals("fullImage")) {
          image = ImageLocalServiceUtil.getImage(productScreenshot.getFullImageId());
        } else {
          image = ImageLocalServiceUtil.getImage(productScreenshot.getThumbnailId());
        }

        bytes = image.getTextObj();
      } else {
        InputStream inputStream = uploadPortletRequest.getFileAsStream(name);

        if (inputStream != null) {
          bytes = FileUtil.getBytes(inputStream);
        }
      }

      if (ArrayUtil.isNotEmpty(bytes)) {
        images.add(bytes);
      } else {
        throw new ProductEntryScreenshotsException();
      }
    }

    return images;
  }
  protected void exportLayoutIconImage(
      PortletDataContext portletDataContext, Layout layout, Element layoutElement)
      throws Exception {

    Image image = _imageLocalService.getImage(layout.getIconImageId());

    if (image != null) {
      String iconPath =
          ExportImportPathUtil.getModelPath(
              portletDataContext.getScopeGroupId(), Image.class.getName(), image.getImageId());

      Element iconImagePathElement = layoutElement.addElement("icon-image-path");

      iconImagePathElement.addText(iconPath);

      portletDataContext.addZipEntry(iconPath, image.getTextObj());
    }
  }
  protected Image getUserPortraitImageResized(Image image, long imageId)
      throws PortalException, SystemException {

    if (image == null) {
      return null;
    }

    if ((image.getHeight() > PropsValues.USERS_IMAGE_MAX_HEIGHT)
        || (image.getWidth() > PropsValues.USERS_IMAGE_MAX_WIDTH)) {

      User user = UserLocalServiceUtil.getUserByPortraitId(imageId);

      UserLocalServiceUtil.updatePortrait(user.getUserId(), image.getTextObj());

      return ImageLocalServiceUtil.getImage(imageId);
    }

    return image;
  }
Пример #8
0
  protected byte[] getImageBytes(UploadRequest uploadRequest, String fieldNameValue)
      throws Exception {

    File file = uploadRequest.getFile(fieldNameValue + "File");

    byte[] bytes = FileUtil.getBytes(file);

    if (ArrayUtil.isNotEmpty(bytes)) {
      return bytes;
    }

    String url = uploadRequest.getParameter(fieldNameValue + "URL");

    long imageId = GetterUtil.getLong(HttpUtil.getParameter(url, "img_id", false));

    Image image = ImageLocalServiceUtil.fetchImage(imageId);

    if (image == null) {
      return null;
    }

    return image.getTextObj();
  }
Пример #9
0
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, DDMTemplate template)
      throws Exception {

    Element dlFileEntryTypesElement =
        portletDataContext.getExportDataGroupElement(DLFileEntryType.class);
    Element dlFoldersElement = portletDataContext.getExportDataGroupElement(DLFolder.class);
    Element dlFileEntriesElement = portletDataContext.getExportDataGroupElement(DLFileEntry.class);
    Element dlFileRanksElement = portletDataContext.getExportDataGroupElement(DLFileRank.class);
    Element dlRepositoriesElement = portletDataContext.getExportDataGroupElement(Repository.class);
    Element dlRepositoryEntriesElement =
        portletDataContext.getExportDataGroupElement(RepositoryEntry.class);

    Element templateElement = portletDataContext.getExportDataStagedModelElement(template);

    if (template.isSmallImage()) {
      Image smallImage = ImageUtil.fetchByPrimaryKey(template.getSmallImageId());

      if (Validator.isNotNull(template.getSmallImageURL())) {
        String smallImageURL =
            DDMPortletDataHandler.exportReferencedContent(
                portletDataContext,
                dlFileEntryTypesElement,
                dlFoldersElement,
                dlFileEntriesElement,
                dlFileRanksElement,
                dlRepositoriesElement,
                dlRepositoryEntriesElement,
                templateElement,
                template.getSmallImageURL().concat(StringPool.SPACE));

        template.setSmallImageURL(smallImageURL);
      } else if (smallImage != null) {
        String smallImagePath =
            StagedModelPathUtil.getPath(
                template,
                smallImage.getImageId() + StringPool.PERIOD + template.getSmallImageType());

        templateElement.addAttribute("small-image-path", smallImagePath);

        template.setSmallImageType(smallImage.getType());

        portletDataContext.addZipEntry(smallImagePath, smallImage.getTextObj());
      }
    }

    if (portletDataContext.getBooleanParameter(
        DDMPortletDataHandler.NAMESPACE, "embedded-assets")) {

      String content =
          DDMPortletDataHandler.exportReferencedContent(
              portletDataContext,
              dlFileEntryTypesElement,
              dlFoldersElement,
              dlFileEntriesElement,
              dlFileRanksElement,
              dlRepositoriesElement,
              dlRepositoryEntriesElement,
              templateElement,
              template.getScript());

      template.setScript(content);
    }

    portletDataContext.addClassedModel(
        templateElement,
        StagedModelPathUtil.getPath(template),
        template,
        DDMPortletDataHandler.NAMESPACE);
  }
Пример #10
0
  protected void exportLayout(
      PortletDataContext portletDataContext,
      Portlet layoutConfigurationPortlet,
      LayoutCache layoutCache,
      List<Portlet> portlets,
      Map<String, Object[]> portletIds,
      boolean exportPermissions,
      boolean exportUserPermissions,
      Layout layout,
      Element layoutsElement)
      throws Exception {

    String path = portletDataContext.getLayoutPath(layout.getLayoutId()) + "/layout.xml";

    if (!portletDataContext.isPathNotProcessed(path)) {
      return;
    }

    LayoutRevision layoutRevision = null;

    if (LayoutStagingUtil.isBranchingLayout(layout)) {
      ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

      long layoutSetBranchId = ParamUtil.getLong(serviceContext, "layoutSetBranchId");

      if (layoutSetBranchId <= 0) {
        return;
      }

      layoutRevision = LayoutRevisionUtil.fetchByL_H_P(layoutSetBranchId, true, layout.getPlid());

      if (layoutRevision == null) {
        return;
      }

      LayoutStagingHandler layoutStagingHandler = LayoutStagingUtil.getLayoutStagingHandler(layout);

      layoutStagingHandler.setLayoutRevision(layoutRevision);
    }

    Element layoutElement = layoutsElement.addElement("layout");

    if (layoutRevision != null) {
      layoutElement.addAttribute(
          "layout-revision-id", String.valueOf(layoutRevision.getLayoutRevisionId()));
      layoutElement.addAttribute(
          "layout-branch-id", String.valueOf(layoutRevision.getLayoutBranchId()));
      layoutElement.addAttribute(
          "layout-branch-name", String.valueOf(layoutRevision.getLayoutBranch().getName()));
    }

    layoutElement.addAttribute("layout-uuid", layout.getUuid());
    layoutElement.addAttribute("layout-id", String.valueOf(layout.getLayoutId()));

    long parentLayoutId = layout.getParentLayoutId();

    if (parentLayoutId != LayoutConstants.DEFAULT_PARENT_LAYOUT_ID) {
      Layout parentLayout =
          LayoutLocalServiceUtil.getLayout(
              layout.getGroupId(), layout.isPrivateLayout(), parentLayoutId);

      if (parentLayout != null) {
        layoutElement.addAttribute("parent-layout-uuid", parentLayout.getUuid());
      }
    }

    boolean deleteLayout =
        MapUtil.getBoolean(portletDataContext.getParameterMap(), "delete_" + layout.getPlid());

    if (deleteLayout) {
      layoutElement.addAttribute("delete", String.valueOf(true));

      return;
    }

    portletDataContext.setPlid(layout.getPlid());

    if (layout.isIconImage()) {
      Image image = ImageLocalServiceUtil.getImage(layout.getIconImageId());

      if (image != null) {
        String iconPath = getLayoutIconPath(portletDataContext, layout, image);

        layoutElement.addElement("icon-image-path").addText(iconPath);

        portletDataContext.addZipEntry(iconPath, image.getTextObj());
      }
    }

    _portletExporter.exportPortletData(
        portletDataContext, layoutConfigurationPortlet, layout, null, layoutElement);

    // Layout permissions

    if (exportPermissions) {
      _permissionExporter.exportLayoutPermissions(
          portletDataContext,
          layoutCache,
          portletDataContext.getCompanyId(),
          portletDataContext.getScopeGroupId(),
          layout,
          layoutElement,
          exportUserPermissions);
    }

    if (layout.isTypeArticle()) {
      exportJournalArticle(portletDataContext, layout, layoutElement);
    } else if (layout.isTypeLinkToLayout()) {
      UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

      long linkToLayoutId =
          GetterUtil.getLong(
              typeSettingsProperties.getProperty("linkToLayoutId", StringPool.BLANK));

      if (linkToLayoutId > 0) {
        try {
          Layout linkedToLayout =
              LayoutLocalServiceUtil.getLayout(
                  portletDataContext.getScopeGroupId(), layout.isPrivateLayout(), linkToLayoutId);

          exportLayout(
              portletDataContext,
              layoutConfigurationPortlet,
              layoutCache,
              portlets,
              portletIds,
              exportPermissions,
              exportUserPermissions,
              linkedToLayout,
              layoutsElement);
        } catch (NoSuchLayoutException nsle) {
        }
      }
    } else if (layout.isTypePortlet()) {
      for (Portlet portlet : portlets) {
        if (portlet.isScopeable() && layout.hasScopeGroup()) {
          String key =
              PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portlet.getPortletId());

          portletIds.put(
              key,
              new Object[] {
                portlet.getPortletId(),
                layout.getPlid(),
                layout.getScopeGroup().getGroupId(),
                StringPool.BLANK,
                layout.getUuid()
              });
        }
      }

      LayoutTypePortlet layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType();

      for (String portletId : layoutTypePortlet.getPortletIds()) {
        javax.portlet.PortletPreferences jxPreferences =
            PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

        String scopeType = GetterUtil.getString(jxPreferences.getValue("lfrScopeType", null));
        String scopeLayoutUuid =
            GetterUtil.getString(jxPreferences.getValue("lfrScopeLayoutUuid", null));

        long scopeGroupId = portletDataContext.getScopeGroupId();

        if (Validator.isNotNull(scopeType)) {
          Group scopeGroup = null;

          if (scopeType.equals("company")) {
            scopeGroup = GroupLocalServiceUtil.getCompanyGroup(layout.getCompanyId());
          } else if (scopeType.equals("layout")) {
            Layout scopeLayout = null;

            scopeLayout =
                LayoutLocalServiceUtil.fetchLayoutByUuidAndGroupId(
                    scopeLayoutUuid, portletDataContext.getGroupId());

            if (scopeLayout == null) {
              continue;
            }

            scopeGroup = scopeLayout.getScopeGroup();
          } else {
            throw new IllegalArgumentException("Scope type " + scopeType + " is invalid");
          }

          if (scopeGroup != null) {
            scopeGroupId = scopeGroup.getGroupId();
          }
        }

        String key = PortletPermissionUtil.getPrimaryKey(layout.getPlid(), portletId);

        portletIds.put(
            key,
            new Object[] {portletId, layout.getPlid(), scopeGroupId, scopeType, scopeLayoutUuid});
      }
    }

    fixTypeSettings(layout);

    layoutElement.addAttribute("path", path);

    portletDataContext.addExpando(layoutElement, path, layout);

    portletDataContext.addZipEntry(path, layout);
  }
Пример #11
0
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean publishToRemote =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PUBLISH_TO_REMOTE);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export user permissions " + exportUserPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            companyId, groupId, parameterMap, new HashSet<String>(), startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("group-id", String.valueOf(groupId));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if (image != null) {
        String logoPath = getLayoutSetLogoPath(portletDataContext);

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Portlet layoutConfigurationPortlet =
        PortletLocalServiceUtil.getPortletById(
            portletDataContext.getCompanyId(), PortletKeys.LAYOUT_CONFIGURATION);

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = null;

    if ((layoutIds == null) || (layoutIds.length == 0)) {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);
    } else {
      layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout, layoutIds);
    }

    List<Portlet> portlets = getAlwaysExportablePortlets(companyId);

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      if (group.isStagingGroup()) {
        group = group.getLiveGroup();
      }

      for (Portlet portlet : portlets) {
        String portletId = portlet.getRootPortletId();

        if (!group.isStagedPortlet(portletId)) {
          continue;
        }

        String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

        if (portletIds.get(key) == null) {
          portletIds.put(
              key,
              new Object[] {
                portletId, firstLayout.getPlid(), groupId, StringPool.BLANK, StringPool.BLANK
              });
        }
      }
    }

    Element layoutsElement = rootElement.addElement("layouts");

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuid(layoutSetPrototypeUuid);

      layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

      if (publishToRemote) {
        String path = getLayoutSetPrototype(portletDataContext, layoutSetPrototypeUuid);

        File layoutSetPrototypeFile = null;

        InputStream inputStream = null;

        try {
          layoutSetPrototypeFile =
              SitesUtil.exportLayoutSetPrototype(layoutSetPrototype, serviceContext);

          inputStream = new FileInputStream(layoutSetPrototypeFile);

          portletDataContext.addZipEntry(path.concat(".lar"), inputStream);
          portletDataContext.addZipEntry(path.concat(".xml"), layoutSetPrototype);
        } finally {
          StreamUtil.cleanUp(inputStream);

          FileUtil.delete(layoutSetPrototypeFile);
        }
      }
    }

    for (Layout layout : layouts) {
      exportLayout(
          portletDataContext,
          layoutConfigurationPortlet,
          layoutCache,
          portlets,
          portletIds,
          exportPermissions,
          exportUserPermissions,
          layout,
          layoutsElement);
    }

    if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM < 5) {
      Element rolesElement = rootElement.addElement("roles");

      if (exportPermissions) {
        _permissionExporter.exportLayoutRoles(layoutCache, companyId, groupId, rolesElement);
      }
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long plid = 0;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.getLayout(plid);

      portletDataContext.setPlid(layout.getPlid());
      portletDataContext.setOldPlid(layout.getPlid());
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, portletDataContext, parameterMap);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletArchivedSetups,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletUserPreferences,
          exportUserPermissions);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }
  protected File doExportLayoutsAsFile(
      long groupId,
      boolean privateLayout,
      long[] layoutIds,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportIgnoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportTheme = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME);
    boolean exportThemeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.THEME_REFERENCE);
    boolean exportLogo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean exportLayoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean updateLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (_log.isDebugEnabled()) {
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export theme " + exportTheme);
    }

    LayoutSet layoutSet = LayoutSetLocalServiceUtil.getLayoutSet(groupId, privateLayout);

    long companyId = layoutSet.getCompanyId();
    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (serviceContext == null) {
      serviceContext = new ServiceContext();

      serviceContext.setCompanyId(companyId);
      serviceContext.setSignedIn(false);
      serviceContext.setUserId(defaultUserId);

      ServiceContextThreadLocal.pushServiceContext(serviceContext);
    }

    serviceContext.setAttribute("exporting", Boolean.TRUE);

    long layoutSetBranchId = MapUtil.getLong(parameterMap, "layoutSetBranchId");

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    long lastPublishDate = System.currentTimeMillis();

    if (endDate != null) {
      lastPublishDate = endDate.getTime();
    }

    if (exportIgnoreLastPublishDate) {
      endDate = null;
      startDate = null;
    }

    StopWatch stopWatch = null;

    if (_log.isInfoEnabled()) {
      stopWatch = new StopWatch();

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    PortletDataContext portletDataContext =
        PortletDataContextFactoryUtil.createExportPortletDataContext(
            companyId, groupId, parameterMap, startDate, endDate, zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

    Document document = SAXReaderUtil.createDocument();

    Element rootElement = document.addElement("root");

    portletDataContext.setExportDataRootElement(rootElement);

    Element headerElement = rootElement.addElement("header");

    headerElement.addAttribute(
        "available-locales",
        StringUtil.merge(LanguageUtil.getAvailableLocales(portletDataContext.getScopeGroupId())));
    headerElement.addAttribute("build-number", String.valueOf(ReleaseInfo.getBuildNumber()));
    headerElement.addAttribute("export-date", Time.getRFC822());

    if (portletDataContext.hasDateRange()) {
      headerElement.addAttribute("start-date", String.valueOf(portletDataContext.getStartDate()));
      headerElement.addAttribute("end-date", String.valueOf(portletDataContext.getEndDate()));
    }

    headerElement.addAttribute("company-id", String.valueOf(portletDataContext.getCompanyId()));
    headerElement.addAttribute(
        "company-group-id", String.valueOf(portletDataContext.getCompanyGroupId()));
    headerElement.addAttribute("group-id", String.valueOf(groupId));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute("private-layout", String.valueOf(privateLayout));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

    if (group.isLayoutPrototype()) {
      type = "layout-prototype";

      LayoutPrototype layoutPrototype =
          LayoutPrototypeLocalServiceUtil.getLayoutPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutPrototype.getUuid());
    } else if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototype(group.getClassPK());

      headerElement.addAttribute("type-uuid", layoutSetPrototype.getUuid());
    }

    headerElement.addAttribute("type", type);

    if (exportTheme || exportThemeSettings) {
      headerElement.addAttribute("theme-id", layoutSet.getThemeId());
      headerElement.addAttribute("color-scheme-id", layoutSet.getColorSchemeId());
    }

    if (exportLogo) {
      Image image = ImageLocalServiceUtil.getImage(layoutSet.getLogoId());

      if ((image != null) && (image.getTextObj() != null)) {
        String logoPath = ExportImportPathUtil.getRootPath(portletDataContext);

        logoPath += "/logo";

        headerElement.addAttribute("logo-path", logoPath);

        portletDataContext.addZipEntry(logoPath, image.getTextObj());
      }
    }

    if (exportLayoutSetSettings) {
      Element settingsElement = headerElement.addElement("settings");

      settingsElement.addCDATA(layoutSet.getSettings());
    }

    Element cssElement = headerElement.addElement("css");

    cssElement.addCDATA(layoutSet.getCss());

    Map<String, Object[]> portletIds = new LinkedHashMap<String, Object[]>();

    List<Layout> layouts = LayoutLocalServiceUtil.getLayouts(groupId, privateLayout);

    List<Portlet> portlets = getDataSiteLevelPortlets(companyId);

    long plid = LayoutConstants.DEFAULT_PLID;

    if (!layouts.isEmpty()) {
      Layout firstLayout = layouts.get(0);

      plid = firstLayout.getPlid();
    }

    if (group.isStagingGroup()) {
      group = group.getLiveGroup();
    }

    for (Portlet portlet : portlets) {
      String portletId = portlet.getRootPortletId();

      if (!group.isStagedPortlet(portletId)) {
        continue;
      }

      String key = PortletPermissionUtil.getPrimaryKey(0, portletId);

      if (portletIds.get(key) == null) {
        portletIds.put(
            key, new Object[] {portletId, plid, groupId, StringPool.BLANK, StringPool.BLANK});
      }
    }

    Element missingReferencesElement = rootElement.addElement("missing-references");

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    portletDataContext.addDeletionSystemEventStagedModelTypes(new StagedModelType(Layout.class));

    Element layoutsElement = portletDataContext.getExportDataGroupElement(Layout.class);

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (Validator.isNotNull(layoutSetPrototypeUuid)) {
      LayoutSetPrototype layoutSetPrototype =
          LayoutSetPrototypeLocalServiceUtil.getLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototypeUuid, companyId);

      layoutsElement.addAttribute("layout-set-prototype-uuid", layoutSetPrototypeUuid);

      layoutsElement.addAttribute(
          "layout-set-prototype-name", layoutSetPrototype.getName(LocaleUtil.getDefault()));
    }

    for (Layout layout : layouts) {
      exportLayout(portletDataContext, portlets, layoutIds, portletIds, layout);
    }

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

    Element portletsElement = rootElement.addElement("portlets");

    for (Map.Entry<String, Object[]> portletIdsEntry : portletIds.entrySet()) {

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      plid = LayoutConstants.DEFAULT_PLID;
      long scopeGroupId = 0;
      String scopeType = StringPool.BLANK;
      String scopeLayoutUuid = null;

      if (portletObjects.length == 4) {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[3];
      } else {
        portletId = (String) portletIdsEntry.getValue()[0];
        plid = (Long) portletIdsEntry.getValue()[1];
        scopeGroupId = (Long) portletIdsEntry.getValue()[2];
        scopeType = (String) portletIdsEntry.getValue()[3];
        scopeLayoutUuid = (String) portletIdsEntry.getValue()[4];
      }

      Layout layout = LayoutLocalServiceUtil.fetchLayout(plid);

      if (layout == null) {
        if (!group.isCompany() && (plid <= LayoutConstants.DEFAULT_PLID)) {

          continue;
        }

        if (_log.isWarnEnabled()) {
          _log.warn("Assuming global scope because no layout was found");
        }

        layout = new LayoutImpl();

        layout.setGroupId(groupId);
        layout.setCompanyId(companyId);
      }

      portletDataContext.setPlid(plid);
      portletDataContext.setOldPlid(plid);
      portletDataContext.setScopeGroupId(scopeGroupId);
      portletDataContext.setScopeType(scopeType);
      portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);

      boolean[] exportPortletControls =
          getExportPortletControls(companyId, portletId, parameterMap, type);

      _portletExporter.exportPortlet(
          portletDataContext,
          layoutCache,
          portletId,
          layout,
          portletsElement,
          defaultUserId,
          exportPermissions,
          exportPortletControls[0],
          exportPortletControls[1],
          exportPortletControls[2],
          exportPortletControls[3]);
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    exportAssetCategories(
        portletDataContext, exportPortletDataAll, exportCategories, group.isCompany());

    _portletExporter.exportAssetLinks(portletDataContext);
    _portletExporter.exportAssetTags(portletDataContext);
    _portletExporter.exportComments(portletDataContext);
    _portletExporter.exportExpandoTables(portletDataContext);
    _portletExporter.exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

    if (exportPermissions) {
      _permissionExporter.exportPortletDataPermissions(portletDataContext);
    }

    _portletExporter.exportRatingsEntries(portletDataContext, rootElement);

    if (exportTheme && !portletDataContext.isPerformDirectBinaryImport()) {
      exportTheme(layoutSet, zipWriter);
    }

    ExportImportHelperUtil.writeManifestSummary(document, portletDataContext.getManifestSummary());

    if (_log.isInfoEnabled()) {
      if (stopWatch != null) {
        _log.info("Exporting layouts takes " + stopWatch.getTime() + " ms");
      } else {
        _log.info("Exporting layouts is finished");
      }
    }

    portletDataContext.addZipEntry("/manifest.xml", document.formattedString());

    try {
      return zipWriter.getFile();
    } finally {
      if (updateLastPublishDate) {
        updateLastPublishDate(layoutSet, lastPublishDate);
      }
    }
  }
  public JournalTemplate copyTemplate(
      long userId, long groupId, String oldTemplateId, String newTemplateId, boolean autoTemplateId)
      throws PortalException, SystemException {

    // Template

    User user = userPersistence.findByPrimaryKey(userId);
    oldTemplateId = oldTemplateId.trim().toUpperCase();
    newTemplateId = newTemplateId.trim().toUpperCase();
    Date now = new Date();

    JournalTemplate oldTemplate = journalTemplatePersistence.findByG_T(groupId, oldTemplateId);

    if (autoTemplateId) {
      newTemplateId = String.valueOf(counterLocalService.increment());
    } else {
      validate(newTemplateId);

      JournalTemplate newTemplate = journalTemplatePersistence.fetchByG_T(groupId, newTemplateId);

      if (newTemplate != null) {
        throw new DuplicateTemplateIdException();
      }
    }

    long id = counterLocalService.increment();

    JournalTemplate newTemplate = journalTemplatePersistence.create(id);

    newTemplate.setGroupId(groupId);
    newTemplate.setCompanyId(user.getCompanyId());
    newTemplate.setUserId(user.getUserId());
    newTemplate.setUserName(user.getFullName());
    newTemplate.setCreateDate(now);
    newTemplate.setModifiedDate(now);
    newTemplate.setTemplateId(newTemplateId);
    newTemplate.setStructureId(oldTemplate.getStructureId());
    newTemplate.setNameMap(oldTemplate.getNameMap());
    newTemplate.setDescriptionMap(oldTemplate.getDescriptionMap());
    newTemplate.setXsl(oldTemplate.getXsl());
    newTemplate.setLangType(oldTemplate.getLangType());
    newTemplate.setCacheable(oldTemplate.isCacheable());
    newTemplate.setSmallImage(oldTemplate.isSmallImage());
    newTemplate.setSmallImageId(counterLocalService.increment());
    newTemplate.setSmallImageURL(oldTemplate.getSmallImageURL());

    journalTemplatePersistence.update(newTemplate, false);

    // Small image

    if (oldTemplate.getSmallImage()) {
      Image image = imageLocalService.getImage(oldTemplate.getSmallImageId());

      byte[] smallImageBytes = image.getTextObj();

      imageLocalService.updateImage(newTemplate.getSmallImageId(), smallImageBytes);
    }

    // Resources

    addTemplateResources(newTemplate, true, true);

    return newTemplate;
  }