public void importFromLDAP(long companyId) throws Exception {
    if (!LDAPSettingsUtil.isImportEnabled(companyId)) {
      return;
    }

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

    if (LockLocalServiceUtil.hasLock(
        defaultUserId, PortalLDAPImporterUtil.class.getName(), companyId)) {

      if (_log.isDebugEnabled()) {
        _log.debug(
            "Skipping LDAP import for company "
                + companyId
                + "because another LDAP import is in process");
      }

      return;
    }

    LockLocalServiceUtil.lock(
        defaultUserId,
        PortalLDAPImporterUtil.class.getName(),
        companyId,
        PortalLDAPImporterImpl.class.getName(),
        false,
        PropsValues.LDAP_IMPORT_LOCK_EXPIRATION_TIME);

    long threadLocalCompanyId = CompanyThreadLocal.getCompanyId();

    try {
      if (threadLocalCompanyId == CompanyConstants.SYSTEM) {
        CompanyThreadLocal.setCompanyId(companyId);
      }

      long[] ldapServerIds =
          StringUtil.split(PrefsPropsUtil.getString(companyId, "ldap.server.ids"), 0L);

      for (long ldapServerId : ldapServerIds) {
        importFromLDAP(ldapServerId, companyId);
      }

      for (int ldapServerId = 0; ; ldapServerId++) {
        String postfix = LDAPSettingsUtil.getPropertyPostfix(ldapServerId);

        String providerUrl =
            PrefsPropsUtil.getString(companyId, PropsKeys.LDAP_BASE_PROVIDER_URL + postfix);

        if (Validator.isNull(providerUrl)) {
          break;
        }

        importFromLDAP(ldapServerId, companyId);
      }
    } finally {
      LockLocalServiceUtil.unlock(PortalLDAPImporterUtil.class.getName(), companyId);

      CompanyThreadLocal.setCompanyId(threadLocalCompanyId);
    }
  }
  @Override
  protected void doExportStagedModel(
      PortletDataContext portletDataContext, DLFileEntryType fileEntryType) throws Exception {

    Element fileEntryTypeElement = portletDataContext.getExportDataElement(fileEntryType);

    List<DDMStructure> ddmStructures = fileEntryType.getDDMStructures();

    for (DDMStructure ddmStructure : ddmStructures) {
      com.liferay.dynamic.data.mapping.model.DDMStructure structure =
          _ddmStructureLocalService.getStructure(ddmStructure.getStructureId());

      Element referenceElement =
          StagedModelDataHandlerUtil.exportReferenceStagedModel(
              portletDataContext,
              fileEntryType,
              structure,
              PortletDataContext.REFERENCE_TYPE_STRONG);

      referenceElement.addAttribute(
          "structure-id", StringUtil.valueOf(ddmStructure.getStructureId()));
    }

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(fileEntryType.getCompanyId());

    if (defaultUserId == fileEntryType.getUserId()) {
      fileEntryTypeElement.addAttribute("preloaded", "true");
    }

    portletDataContext.addClassedModel(
        fileEntryTypeElement, ExportImportPathUtil.getModelPath(fileEntryType), fileEntryType);
  }
  @Override
  public Map<String, String> getReferenceAttributes(
      PortletDataContext portletDataContext, DLFileEntryType fileEntryType) {

    Map<String, String> referenceAttributes = new HashMap<>();

    referenceAttributes.put("file-entry-type-key", fileEntryType.getFileEntryTypeKey());

    long defaultUserId = UserConstants.USER_ID_DEFAULT;

    try {
      defaultUserId = UserLocalServiceUtil.getDefaultUserId(fileEntryType.getCompanyId());
    } catch (Exception e) {
    }

    boolean preloaded = false;

    if ((fileEntryType.getFileEntryTypeId()
            == DLFileEntryTypeConstants.FILE_ENTRY_TYPE_ID_BASIC_DOCUMENT)
        || (defaultUserId == fileEntryType.getUserId())) {

      preloaded = true;
    }

    referenceAttributes.put("preloaded", String.valueOf(preloaded));

    return referenceAttributes;
  }
Beispiel #4
0
  @Override
  public Map<String, String> getReferenceAttributes(
      PortletDataContext portletDataContext, DLFileEntryType fileEntryType) {

    Map<String, String> referenceAttributes = new HashMap<String, String>();

    referenceAttributes.put("file-entry-type-key", fileEntryType.getFileEntryTypeKey());

    long defaultUserId = 0;

    try {
      defaultUserId = UserLocalServiceUtil.getDefaultUserId(fileEntryType.getCompanyId());
    } catch (Exception e) {
      return referenceAttributes;
    }

    boolean preloaded = false;

    if (defaultUserId == fileEntryType.getUserId()) {
      preloaded = true;
    }

    referenceAttributes.put("preloaded", String.valueOf(preloaded));

    return referenceAttributes;
  }
Beispiel #5
0
  @Override
  public Map<String, String> getReferenceAttributes(
      PortletDataContext portletDataContext, DDMStructure structure) {

    Map<String, String> referenceAttributes = new HashMap<String, String>();

    referenceAttributes.put("referenced-class-name", structure.getClassName());
    referenceAttributes.put("structure-key", structure.getStructureKey());

    long defaultUserId = 0;

    try {
      defaultUserId = UserLocalServiceUtil.getDefaultUserId(structure.getCompanyId());
    } catch (Exception e) {
      return referenceAttributes;
    }

    boolean preloaded = false;

    if (defaultUserId == structure.getUserId()) {
      preloaded = true;
    }

    referenceAttributes.put("preloaded", String.valueOf(preloaded));

    return referenceAttributes;
  }
 public long getUserId() {
   try {
     return UserLocalServiceUtil.getDefaultUserId(getCompanyId());
   } catch (Exception e) {
     return 0;
   }
 }
  protected UserGroup importUserGroup(
      long companyId, Attributes attributes, Properties groupMappings) throws Exception {

    AttributesTransformer attributesTransformer = AttributesTransformerFactory.getInstance();

    attributes = attributesTransformer.transformGroup(attributes);

    LDAPGroup ldapGroup =
        _ldapToPortalConverter.importLDAPGroup(companyId, attributes, groupMappings);

    UserGroup userGroup = null;

    try {
      userGroup = UserGroupLocalServiceUtil.getUserGroup(companyId, ldapGroup.getGroupName());

      UserGroupLocalServiceUtil.updateUserGroup(
          companyId,
          userGroup.getUserGroupId(),
          ldapGroup.getGroupName(),
          ldapGroup.getDescription());
    } catch (NoSuchUserGroupException nsuge) {
      if (_log.isDebugEnabled()) {
        _log.debug("Adding user group to portal " + ldapGroup.getGroupName());
      }

      long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

      LDAPUserGroupTransactionThreadLocal.setOriginatesFromLDAP(true);

      try {
        userGroup =
            UserGroupLocalServiceUtil.addUserGroup(
                defaultUserId, companyId, ldapGroup.getGroupName(), ldapGroup.getDescription());
      } catch (Exception e) {
        if (_log.isWarnEnabled()) {
          _log.warn("Unable to create user group " + ldapGroup.getGroupName());
        }

        if (_log.isDebugEnabled()) {
          _log.debug(e, e);
        }
      } finally {
        LDAPUserGroupTransactionThreadLocal.setOriginatesFromLDAP(false);
      }
    }

    addRole(companyId, ldapGroup, userGroup);

    return userGroup;
  }
  /**
   * Returns this service context's user ID or guest ID if no user ID is available.
   *
   * @return the user ID, or guest ID if there is no user in this service context, or <code>0</code>
   *     if there is no company in this service context
   * @throws PortalException if a default user for the company could not be found
   */
  public long getGuestOrUserId() throws PortalException {
    long userId = getUserId();

    if (userId > 0) {
      return userId;
    }

    long companyId = getCompanyId();

    if (companyId > 0) {
      return UserLocalServiceUtil.getDefaultUserId(getCompanyId());
    }

    return 0;
  }
  @Override
  protected void doUpgrade() throws Exception {
    String name = PrincipalThreadLocal.getName();

    try {
      long companyId = PortalUtil.getDefaultCompanyId();

      long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);

      PrincipalThreadLocal.setName(defaultUserId);

      clearData(companyId);
      setupPermissionsDefined(defaultUserId);
    } finally {
      PrincipalThreadLocal.setName(name);
    }
  }
  protected CalendarResource getCalendarResource(long companyId, long groupId)
      throws PortalException, SystemException {

    ServiceContext serviceContext = new ServiceContext();

    serviceContext.setCompanyId(companyId);

    long userId = UserLocalServiceUtil.getDefaultUserId(companyId);

    serviceContext.setUserId(userId);

    Group group = groupLocalService.getGroup(groupId);

    if (group.isUser()) {
      return CalendarResourceUtil.getUserCalendarResource(group.getCreatorUserId(), serviceContext);
    }

    return CalendarResourceUtil.getGroupCalendarResource(groupId, serviceContext);
  }
Beispiel #11
0
  public void run(String[] arg0) throws ActionException {

    File file = new File("old-users.csv");

    _log.debug("file ==> " + file.getAbsolutePath());

    InputStream inputStream = null;
    try {
      inputStream = new FileInputStream(file);
    } catch (FileNotFoundException e) {
      _log.debug("File not found...Existing....");
      return;
    }

    BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));

    long companyId = PortalUtil.getDefaultCompanyId();
    long creatorUserId = 0l;
    try {
      creatorUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
    } catch (PortalException e) {
      e.printStackTrace();
    } catch (SystemException e) {
      e.printStackTrace();
    }

    try {
      String line = StringPool.BLANK;
      while (Validator.isNotNull(line = br.readLine())) {
        insertOldUser(companyId, creatorUserId, line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }

    file.delete();
  }
  public void init(User user, boolean checkGuest) {
    this.user = user;

    if (user.isDefaultUser()) {
      this.defaultUserId = user.getUserId();
      this.signedIn = false;
    } else {
      try {
        this.defaultUserId = UserLocalServiceUtil.getDefaultUserId(user.getCompanyId());
      } catch (Exception e) {
        _log.error(e, e);
      }

      this.signedIn = true;
    }

    this.checkGuest = checkGuest;

    try {
      this.ownerRole = RoleLocalServiceUtil.getRole(user.getCompanyId(), RoleConstants.OWNER);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
Beispiel #13
0
  @Override
  protected void doExportStagedModel(PortletDataContext portletDataContext, DDMStructure structure)
      throws Exception {

    Element structureElement = portletDataContext.getExportDataElement(structure);

    if (structure.getParentStructureId() != DDMStructureConstants.DEFAULT_PARENT_STRUCTURE_ID) {

      DDMStructure parentStructure =
          DDMStructureLocalServiceUtil.getStructure(structure.getParentStructureId());

      StagedModelDataHandlerUtil.exportReferenceStagedModel(
          portletDataContext, structure, parentStructure, PortletDataContext.REFERENCE_TYPE_PARENT);
    }

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(structure.getCompanyId());

    if (defaultUserId == structure.getUserId()) {
      structureElement.addAttribute("preloaded", "true");
    }

    portletDataContext.addClassedModel(
        structureElement, ExportImportPathUtil.getModelPath(structure), structure);
  }
  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);
      }
    }
  }
  protected void importPortletPreferences(
      PortletDataContext portletDataContext,
      long companyId,
      long groupId,
      Layout layout,
      String portletId,
      Element parentElement,
      boolean importPortletSetup,
      boolean importPortletArchivedSetups,
      boolean importPortletUserPreferences,
      boolean preserveScopeLayoutId)
      throws Exception {

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(companyId);
    long plid = 0;
    String scopeType = StringPool.BLANK;
    String scopeLayoutUuid = StringPool.BLANK;

    if (layout != null) {
      plid = layout.getPlid();

      if (preserveScopeLayoutId && (portletId != null)) {
        javax.portlet.PortletPreferences jxPreferences =
            PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

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

        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }

    List<Element> portletPreferencesElements = parentElement.elements("portlet-preferences");

    for (Element portletPreferencesElement : portletPreferencesElements) {
      String path = portletPreferencesElement.attributeValue("path");

      if (portletDataContext.isPathNotProcessed(path)) {
        String xml = null;

        Element element = null;

        try {
          xml = portletDataContext.getZipEntryAsString(path);

          Document preferencesDocument = SAXReaderUtil.read(xml);

          element = preferencesDocument.getRootElement();
        } catch (DocumentException de) {
          throw new SystemException(de);
        }

        long ownerId = GetterUtil.getLong(element.attributeValue("owner-id"));
        int ownerType = GetterUtil.getInteger(element.attributeValue("owner-type"));

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) {
          continue;
        }

        if (((ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP)
                || (ownerType == PortletKeys.PREFS_OWNER_TYPE_LAYOUT))
            && !importPortletSetup) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && !importPortletArchivedSetups) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER)
            && (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT)
            && !importPortletUserPreferences) {

          continue;
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
          plid = PortletKeys.PREFS_PLID_SHARED;
          ownerId = portletDataContext.getScopeGroupId();
        }

        boolean defaultUser = GetterUtil.getBoolean(element.attributeValue("default-user"));

        if (portletId == null) {
          portletId = element.attributeValue("portlet-id");
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
          portletId = PortletConstants.getRootPortletId(portletId);

          String userUuid = element.attributeValue("archive-user-uuid");
          String name = element.attributeValue("archive-name");

          long userId = portletDataContext.getUserId(userUuid);

          PortletItem portletItem =
              PortletItemLocalServiceUtil.updatePortletItem(
                  userId, groupId, name, portletId, PortletPreferences.class.getName());

          plid = 0;
          ownerId = portletItem.getPortletItemId();
        }

        if (defaultUser) {
          ownerId = defaultUserId;
        }

        xml =
            checkPortletPreferences(
                portletDataContext, companyId, ownerId, ownerType, plid, portletId, xml);

        PortletPreferencesLocalServiceUtil.updatePreferences(
            ownerId, ownerType, plid, portletId, xml);
      }
    }

    if (preserveScopeLayoutId && (layout != null)) {
      javax.portlet.PortletPreferences jxPreferences =
          PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

      try {
        jxPreferences.setValue("lfrScopeType", scopeType);
        jxPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);

        jxPreferences.store();
      } finally {
        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }
  }
  protected void importPortletPreferences(
      PortletDataContext portletDataContext,
      long companyId,
      long groupId,
      Layout layout,
      Element parentElement,
      boolean preserveScopeLayoutId,
      boolean importPortletArchivedSetups,
      boolean importPortletData,
      boolean importPortletSetup,
      boolean importPortletUserPreferences)
      throws Exception {

    long plid = LayoutConstants.DEFAULT_PLID;
    String scopeType = StringPool.BLANK;
    String scopeLayoutUuid = StringPool.BLANK;

    if (layout != null) {
      plid = layout.getPlid();

      if (preserveScopeLayoutId) {
        javax.portlet.PortletPreferences jxPortletPreferences =
            PortletPreferencesFactoryUtil.getLayoutPortletSetup(
                layout, portletDataContext.getPortletId());

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

        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }

    List<Element> portletPreferencesElements = parentElement.elements("portlet-preferences");

    for (Element portletPreferencesElement : portletPreferencesElements) {
      String path = portletPreferencesElement.attributeValue("path");

      if (portletDataContext.isPathNotProcessed(path)) {
        String xml = null;

        Element element = null;

        try {
          xml = portletDataContext.getZipEntryAsString(path);

          Document preferencesDocument = SAXReaderUtil.read(xml);

          element = preferencesDocument.getRootElement();
        } catch (DocumentException de) {
          throw new SystemException(de);
        }

        long ownerId = GetterUtil.getLong(element.attributeValue("owner-id"));
        int ownerType = GetterUtil.getInteger(element.attributeValue("owner-type"));

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_COMPANY) || !importPortletSetup) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) && !importPortletArchivedSetups) {

          continue;
        }

        if ((ownerType == PortletKeys.PREFS_OWNER_TYPE_USER)
            && (ownerId != PortletKeys.PREFS_OWNER_ID_DEFAULT)
            && !importPortletUserPreferences) {

          continue;
        }

        long curPlid = plid;
        String curPortletId = portletDataContext.getPortletId();

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_GROUP) {
          curPlid = PortletKeys.PREFS_PLID_SHARED;
          curPortletId = portletDataContext.getRootPortletId();
          ownerId = portletDataContext.getScopeGroupId();
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_ARCHIVED) {
          String userUuid = element.attributeValue("archive-user-uuid");

          long userId = portletDataContext.getUserId(userUuid);

          String name = element.attributeValue("archive-name");

          curPortletId = portletDataContext.getRootPortletId();

          PortletItem portletItem =
              PortletItemLocalServiceUtil.updatePortletItem(
                  userId, groupId, name, curPortletId, PortletPreferences.class.getName());

          curPlid = LayoutConstants.DEFAULT_PLID;
          ownerId = portletItem.getPortletItemId();
        }

        if (ownerType == PortletKeys.PREFS_OWNER_TYPE_USER) {
          String userUuid = element.attributeValue("user-uuid");

          ownerId = portletDataContext.getUserId(userUuid);
        }

        boolean defaultUser = GetterUtil.getBoolean(element.attributeValue("default-user"));

        if (defaultUser) {
          ownerId = UserLocalServiceUtil.getDefaultUserId(companyId);
        }

        javax.portlet.PortletPreferences jxPortletPreferences =
            PortletPreferencesFactoryUtil.fromXML(
                companyId, ownerId, ownerType, curPlid, curPortletId, xml);

        Element importDataRootElement = portletDataContext.getImportDataRootElement();

        try {
          Element preferenceDataElement = portletPreferencesElement.element("preference-data");

          if (preferenceDataElement != null) {
            portletDataContext.setImportDataRootElement(preferenceDataElement);
          }

          Portlet portlet =
              PortletLocalServiceUtil.getPortletById(
                  portletDataContext.getCompanyId(), curPortletId);

          ExportImportPortletPreferencesProcessor exportImportPortletPreferencesProcessor =
              ExportImportPortletPreferencesProcessorRegistryUtil
                  .getExportImportPortletPreferencesProcessor(portlet.getRootPortletId());

          if (exportImportPortletPreferencesProcessor != null) {
            List<Capability> importCapabilities =
                exportImportPortletPreferencesProcessor.getImportCapabilities();

            if (ListUtil.isNotEmpty(importCapabilities)) {
              for (Capability importCapability : importCapabilities) {

                importCapability.process(portletDataContext, jxPortletPreferences);
              }
            }

            exportImportPortletPreferencesProcessor.processImportPortletPreferences(
                portletDataContext, jxPortletPreferences);
          } else {
            PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

            jxPortletPreferences =
                portletDataHandler.processImportPortletPreferences(
                    portletDataContext, curPortletId, jxPortletPreferences);
          }
        } finally {
          portletDataContext.setImportDataRootElement(importDataRootElement);
        }

        updatePortletPreferences(
            portletDataContext,
            ownerId,
            ownerType,
            curPlid,
            curPortletId,
            PortletPreferencesFactoryUtil.toXML(jxPortletPreferences),
            importPortletData);
      }
    }

    if (preserveScopeLayoutId && (layout != null)) {
      javax.portlet.PortletPreferences jxPortletPreferences =
          PortletPreferencesFactoryUtil.getLayoutPortletSetup(
              layout, portletDataContext.getPortletId());

      try {
        jxPortletPreferences.setValue("lfrScopeType", scopeType);
        jxPortletPreferences.setValue("lfrScopeLayoutUuid", scopeLayoutUuid);

        jxPortletPreferences.store();
      } finally {
        portletDataContext.setScopeType(scopeType);
        portletDataContext.setScopeLayoutUuid(scopeLayoutUuid);
      }
    }
  }
Beispiel #18
0
  public static void getPage(HttpServletRequest request) throws Exception {
    ThemeDisplay themeDisplay = (ThemeDisplay) request.getAttribute(WebKeys.THEME_DISPLAY);

    long nodeId = ParamUtil.getLong(request, "nodeId");
    String title = ParamUtil.getString(request, "title");
    double version = ParamUtil.getDouble(request, "version");

    WikiNode node = null;

    try {
      if (nodeId > 0) {
        node = WikiNodeServiceUtil.getNode(nodeId);
      }
    } catch (NoSuchNodeException nsne) {
    }

    if (node == null) {
      node = (WikiNode) request.getAttribute(WebKeys.WIKI_NODE);

      if (node != null) {
        nodeId = node.getNodeId();
      }
    }

    if (Validator.isNull(title)) {
      title = WikiPageConstants.FRONT_PAGE;
    }

    WikiPage page = null;

    try {
      page = WikiPageServiceUtil.getPage(nodeId, title, version);
    } catch (NoSuchPageException nspe) {
      if (title.equals(WikiPageConstants.FRONT_PAGE) && (version == 0)) {
        long userId = PortalUtil.getUserId(request);

        if (userId == 0) {
          long companyId = PortalUtil.getCompanyId(request);

          userId = UserLocalServiceUtil.getDefaultUserId(companyId);
        }

        ServiceContext serviceContext = new ServiceContext();

        Layout layout = themeDisplay.getLayout();

        serviceContext.setAddCommunityPermissions(true);

        if (layout.isPublicLayout()) {
          serviceContext.setAddGuestPermissions(true);
        } else {
          serviceContext.setAddGuestPermissions(false);
        }

        boolean workflowEnabled = WorkflowThreadLocal.isEnabled();

        try {
          WorkflowThreadLocal.setEnabled(false);

          page =
              WikiPageLocalServiceUtil.addPage(
                  userId, nodeId, title, null, WikiPageConstants.NEW, true, serviceContext);
        } finally {
          WorkflowThreadLocal.setEnabled(workflowEnabled);
        }
      } else {
        throw nspe;
      }
    }

    request.setAttribute(WebKeys.WIKI_PAGE, page);
  }
  @Override
  public PortletPreferencesIds getPortletPreferencesIds(
      long siteGroupId, long userId, Layout layout, String portletId, boolean modeEditGuest)
      throws PortalException {

    PermissionChecker permissionChecker = PermissionThreadLocal.getPermissionChecker();

    String originalPortletId = portletId;

    Portlet portlet = PortletLocalServiceUtil.getPortletById(layout.getCompanyId(), portletId);

    long ownerId = 0;
    int ownerType = 0;
    long plid = 0;

    if (modeEditGuest) {
      boolean hasUpdateLayoutPermission =
          LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE);

      if (!layout.isPrivateLayout() && hasUpdateLayoutPermission) {
      } else {

        // Only users with the correct permissions can update guest
        // preferences

        throw new PrincipalException();
      }
    }

    if (PortletConstants.hasUserId(originalPortletId)
        && (PortletConstants.getUserId(originalPortletId) == userId)) {

      ownerId = userId;
      ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
      plid = layout.getPlid();
    } else if (portlet.isPreferencesCompanyWide()) {
      ownerId = layout.getCompanyId();
      ownerType = PortletKeys.PREFS_OWNER_TYPE_COMPANY;
      plid = PortletKeys.PREFS_PLID_SHARED;
      portletId = PortletConstants.getRootPortletId(portletId);
    } else {
      if (portlet.isPreferencesUniquePerLayout()) {
        ownerId = PortletKeys.PREFS_OWNER_ID_DEFAULT;
        ownerType = PortletKeys.PREFS_OWNER_TYPE_LAYOUT;
        plid = layout.getPlid();

        if (portlet.isPreferencesOwnedByGroup()) {
        } else {
          if ((userId <= 0) || modeEditGuest) {
            userId = UserLocalServiceUtil.getDefaultUserId(layout.getCompanyId());
          }

          ownerId = userId;
          ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
        }
      } else {
        plid = PortletKeys.PREFS_PLID_SHARED;

        if (portlet.isPreferencesOwnedByGroup()) {
          ownerId = siteGroupId;
          ownerType = PortletKeys.PREFS_OWNER_TYPE_GROUP;
          portletId = PortletConstants.getRootPortletId(portletId);
        } else {
          if ((userId <= 0) || modeEditGuest) {
            userId = UserLocalServiceUtil.getDefaultUserId(layout.getCompanyId());
          }

          ownerId = userId;
          ownerType = PortletKeys.PREFS_OWNER_TYPE_USER;
        }
      }
    }

    return new PortletPreferencesIds(layout.getCompanyId(), ownerId, ownerType, plid, portletId);
  }
  protected File doExportPortletInfoAsFile(
      long plid,
      long groupId,
      String portletId,
      Map<String, String[]> parameterMap,
      Date startDate,
      Date endDate)
      throws Exception {

    boolean exportCategories = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.CATEGORIES);
    boolean exportPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);
    boolean exportPortletArchivedSetups =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS);

    boolean exportPortletData = false;

    if (parameterMap.containsKey(
        PortletDataHandlerKeys.PORTLET_DATA + "_" + PortletConstants.getRootPortletId(portletId))) {

      exportPortletData =
          MapUtil.getBoolean(
              parameterMap,
              PortletDataHandlerKeys.PORTLET_DATA
                  + "_"
                  + PortletConstants.getRootPortletId(portletId));
    } else {
      exportPortletData = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA);
    }

    boolean exportPortletDataAll =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_DATA_ALL);
    boolean exportPortletSetup =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_SETUP);
    boolean exportPortletUserPreferences =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PORTLET_USER_PREFERENCES);
    boolean exportUserPermissions =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.USER_PERMISSIONS);

    if (_log.isDebugEnabled()) {
      _log.debug("Export categories " + exportCategories);
      _log.debug("Export permissions " + exportPermissions);
      _log.debug("Export portlet archived setups " + exportPortletArchivedSetups);
      _log.debug("Export portlet data " + exportPortletData);
      _log.debug("Export all portlet data " + exportPortletDataAll);
      _log.debug("Export portlet setup " + exportPortletSetup);
      _log.debug("Export portlet user preferences " + exportPortletUserPreferences);
      _log.debug("Export user permissions " + exportUserPermissions);
    }

    if (exportPortletDataAll) {
      exportPortletData = true;
    }

    StopWatch stopWatch = null;

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

      stopWatch.start();
    }

    LayoutCache layoutCache = new LayoutCache();

    Layout layout = LayoutLocalServiceUtil.getLayout(plid);

    if (!layout.isTypeControlPanel() && !layout.isTypePanel() && !layout.isTypePortlet()) {

      throw new LayoutImportException("Layout type " + layout.getType() + " is not valid");
    }

    long defaultUserId = UserLocalServiceUtil.getDefaultUserId(layout.getCompanyId());

    ZipWriter zipWriter = ZipWriterFactoryUtil.getZipWriter();

    long scopeGroupId = groupId;

    javax.portlet.PortletPreferences jxPreferences =
        PortletPreferencesFactoryUtil.getLayoutPortletSetup(layout, portletId);

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

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

      if (scopeType.equals("company")) {
        scopeGroup = GroupLocalServiceUtil.getCompanyGroup(layout.getCompanyId());
      } else if (Validator.isNotNull(scopeLayoutUuid)) {
        scopeGroup = layout.getScopeGroup();
      }

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

    PortletDataContext portletDataContext =
        new PortletDataContextImpl(
            layout.getCompanyId(),
            scopeGroupId,
            parameterMap,
            new HashSet<String>(),
            startDate,
            endDate,
            zipWriter);

    portletDataContext.setPortetDataContextListener(
        new PortletDataContextListenerImpl(portletDataContext));

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

    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("type", "portlet");
    headerElement.addAttribute("group-id", String.valueOf(scopeGroupId));
    headerElement.addAttribute("private-layout", String.valueOf(layout.isPrivateLayout()));
    headerElement.addAttribute("root-portlet-id", PortletConstants.getRootPortletId(portletId));

    exportPortlet(
        portletDataContext,
        layoutCache,
        portletId,
        layout,
        rootElement,
        defaultUserId,
        exportPermissions,
        exportPortletArchivedSetups,
        exportPortletData,
        exportPortletSetup,
        exportPortletUserPreferences,
        exportUserPermissions);

    if (exportCategories) {
      exportAssetCategories(portletDataContext);
    }

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

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

    exportRatingsEntries(portletDataContext, rootElement);

    if (_log.isInfoEnabled()) {
      _log.info("Exporting portlet took " + stopWatch.getTime() + " ms");
    }

    try {
      portletDataContext.addZipEntry("/manifest.xml", document.formattedString());
    } catch (IOException ioe) {
      throw new SystemException(ioe);
    }

    return zipWriter.getFile();
  }