private static LayoutSet _getParentLayoutSet(LayoutSet layoutSet) throws Exception {

    Group group = layoutSet.getGroup();

    if (group.isSite()) {
      Group parentGroup = group.getParentGroup();

      if (parentGroup != null) {
        return LayoutSetLocalServiceUtil.getLayoutSet(
            parentGroup.getGroupId(), layoutSet.isPrivateLayout());
      }
    } else if (group.isUser()) {
      User user = UserLocalServiceUtil.getUser(group.getClassPK());

      List<Organization> organizations =
          OrganizationLocalServiceUtil.getUserOrganizations(user.getUserId());

      if (!organizations.isEmpty()) {
        Organization organization = organizations.get(0);

        Group parentGroup = organization.getGroup();

        return LayoutSetLocalServiceUtil.getLayoutSet(
            parentGroup.getGroupId(), layoutSet.isPrivateLayout());
      }
    }

    return null;
  }
  public void editLayoutSet(ActionRequest actionRequest, ActionResponse actionResponse)
      throws Exception {

    ThemeDisplay themeDisplay = (ThemeDisplay) actionRequest.getAttribute(WebKeys.THEME_DISPLAY);

    long layoutSetId = ParamUtil.getLong(actionRequest, "layoutSetId");

    long liveGroupId = ParamUtil.getLong(actionRequest, "liveGroupId");
    long stagingGroupId = ParamUtil.getLong(actionRequest, "stagingGroupId");
    boolean privateLayout = ParamUtil.getBoolean(actionRequest, "privateLayout");

    LayoutSet layoutSet = layoutSetLocalService.getLayoutSet(layoutSetId);

    updateLogo(actionRequest, liveGroupId, stagingGroupId, privateLayout);

    updateLookAndFeel(
        actionRequest,
        themeDisplay.getCompanyId(),
        liveGroupId,
        stagingGroupId,
        privateLayout,
        layoutSet.getSettingsProperties());

    updateMergePages(actionRequest, liveGroupId);

    updateRobots(actionRequest, liveGroupId, privateLayout);

    updateSettings(
        actionRequest,
        liveGroupId,
        stagingGroupId,
        privateLayout,
        layoutSet.getSettingsProperties());
  }
  protected String getThemeId() {
    try {
      Layout layout = getLayout();

      LayoutSet layoutSet = layout.getLayoutSet();

      return layoutSet.getThemeId();
    } catch (Exception e) {
      _log.error(e, e);
    }

    return null;
  }
  protected boolean isLayoutSetPrototype() {
    try {
      Layout layout = getLayout();

      LayoutSet layoutSet = layout.getLayoutSet();

      Group group = layoutSet.getGroup();

      return group.isLayoutSetPrototype();
    } catch (Exception e) {
      _log.error(e, e);
    }

    return false;
  }
  private static void _addGroupsBreadcrumbEntries(
      List<BreadcrumbEntry> breadcrumbEntries,
      ThemeDisplay themeDisplay,
      LayoutSet layoutSet,
      boolean includeParentGroups)
      throws Exception {

    Group group = layoutSet.getGroup();

    if (group.isControlPanel()) {
      return;
    }

    if (includeParentGroups) {
      LayoutSet parentLayoutSet = _getParentLayoutSet(layoutSet);

      if (parentLayoutSet != null) {
        _addGroupsBreadcrumbEntries(breadcrumbEntries, themeDisplay, parentLayoutSet, true);
      }
    }

    int layoutsPageCount = 0;

    if (layoutSet.isPrivateLayout()) {
      layoutsPageCount = group.getPrivateLayoutsPageCount();
    } else {
      layoutsPageCount = group.getPublicLayoutsPageCount();
    }

    if ((layoutsPageCount > 0) && !group.isGuest()) {
      String layoutSetFriendlyURL = PortalUtil.getLayoutSetFriendlyURL(layoutSet, themeDisplay);

      if (themeDisplay.isAddSessionIdToURL()) {
        layoutSetFriendlyURL =
            PortalUtil.getURLWithSessionId(layoutSetFriendlyURL, themeDisplay.getSessionId());
      }

      BreadcrumbEntry breadcrumbEntry = new BreadcrumbEntry();

      breadcrumbEntry.setTitle(group.getDescriptiveName(themeDisplay.getLocale()));
      breadcrumbEntry.setURL(layoutSetFriendlyURL);

      breadcrumbEntries.add(breadcrumbEntry);
    }
  }
  protected void updateLayoutSetPrototype(Layout layout, Date modifiedDate) {
    if (layout == null) {
      return;
    }

    Group group = null;

    try {
      group = layout.getGroup();

      if (!group.isLayoutSetPrototype()) {
        return;
      }
    } catch (PortalException pe) {
      return;
    }

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

      layoutSetPrototype.setModifiedDate(modifiedDate);

      LayoutSetPrototypeLocalServiceUtil.updateLayoutSetPrototype(layoutSetPrototype);

      LayoutSet layoutSet = layoutSetPrototype.getLayoutSet();

      layoutSet.setModifiedDate(layout.getModifiedDate());

      UnicodeProperties settingsProperties = layoutSet.getSettingsProperties();

      settingsProperties.remove(Sites.MERGE_FAIL_COUNT);

      LayoutSetLocalServiceUtil.updateLayoutSet(layoutSet);
    } catch (Exception e) {
      _log.error(e, e);
    }
  }
  @Override
  protected void doImportStagedModel(
      PortletDataContext portletDataContext, MDRRuleGroupInstance ruleGroupInstance)
      throws Exception {

    long userId = portletDataContext.getUserId(ruleGroupInstance.getUserUuid());

    Map<Long, Long> ruleGroupIds =
        (Map<Long, Long>) portletDataContext.getNewPrimaryKeysMap(MDRRuleGroup.class);

    Long ruleGroupId =
        MapUtil.getLong(
            ruleGroupIds, ruleGroupInstance.getRuleGroupId(), ruleGroupInstance.getRuleGroupId());

    long classPK = 0;

    Element ruleGroupInstanceElement =
        portletDataContext.getImportDataStagedModelElement(ruleGroupInstance);

    String layoutUuid = ruleGroupInstanceElement.attributeValue("layout-uuid");

    try {
      if (Validator.isNotNull(layoutUuid)) {
        Layout layout =
            _layoutLocalService.getLayoutByUuidAndGroupId(
                layoutUuid,
                portletDataContext.getScopeGroupId(),
                portletDataContext.isPrivateLayout());

        classPK = layout.getPrimaryKey();
      } else {
        LayoutSet layoutSet =
            _layoutSetLocalService.getLayoutSet(
                portletDataContext.getScopeGroupId(), portletDataContext.isPrivateLayout());

        classPK = layoutSet.getLayoutSetId();
      }
    } catch (Exception e) {
      if (_log.isWarnEnabled()) {
        StringBundler sb = new StringBundler(5);

        sb.append("Layout ");
        sb.append(layoutUuid);
        sb.append(" is missing for rule group instance ");
        sb.append(ruleGroupInstance.getRuleGroupInstanceId());
        sb.append(", skipping this rule group instance.");

        _log.warn(sb.toString());
      }

      return;
    }

    ServiceContext serviceContext = portletDataContext.createServiceContext(ruleGroupInstance);

    serviceContext.setUserId(userId);

    MDRRuleGroupInstance importedRuleGroupInstance = null;

    if (portletDataContext.isDataStrategyMirror()) {
      MDRRuleGroupInstance existingMDRRuleGroupInstance =
          fetchStagedModelByUuidAndGroupId(
              ruleGroupInstance.getUuid(), portletDataContext.getScopeGroupId());

      if (existingMDRRuleGroupInstance == null) {
        serviceContext.setUuid(ruleGroupInstance.getUuid());

        importedRuleGroupInstance =
            _mdrRuleGroupInstanceLocalService.addRuleGroupInstance(
                portletDataContext.getScopeGroupId(),
                ruleGroupInstance.getClassName(),
                classPK,
                ruleGroupId,
                ruleGroupInstance.getPriority(),
                serviceContext);
      } else {
        importedRuleGroupInstance =
            _mdrRuleGroupInstanceLocalService.updateRuleGroupInstance(
                existingMDRRuleGroupInstance.getRuleGroupInstanceId(),
                ruleGroupInstance.getPriority());
      }
    } else {
      importedRuleGroupInstance =
          _mdrRuleGroupInstanceLocalService.addRuleGroupInstance(
              portletDataContext.getScopeGroupId(),
              ruleGroupInstance.getClassName(),
              classPK,
              ruleGroupId,
              ruleGroupInstance.getPriority(),
              serviceContext);
    }

    portletDataContext.importClassedModel(ruleGroupInstance, importedRuleGroupInstance);
  }
  protected File doExport(PortletDataContext portletDataContext, long[] layoutIds)
      throws Exception {

    Map<String, String[]> parameterMap = portletDataContext.getParameterMap();

    boolean ignoreLastPublishDate =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.IGNORE_LAST_PUBLISH_DATE);
    boolean layoutSetPrototypeSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_PROTOTYPE_SETTINGS);
    boolean layoutSetSettings =
        MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LAYOUT_SET_SETTINGS);
    boolean logo = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.LOGO);
    boolean permissions = MapUtil.getBoolean(parameterMap, PortletDataHandlerKeys.PERMISSIONS);

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

    LayoutSet layoutSet =
        _layoutSetLocalService.getLayoutSet(
            portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());

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

    ServiceContext serviceContext = ServiceContextThreadLocal.popServiceContext();

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

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

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

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

    serviceContext.setAttribute("layoutSetBranchId", layoutSetBranchId);

    ServiceContextThreadLocal.pushServiceContext(serviceContext);

    if (ignoreLastPublishDate) {
      portletDataContext.setEndDate(null);
      portletDataContext.setStartDate(null);
    }

    StopWatch stopWatch = new StopWatch();

    stopWatch.start();

    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(portletDataContext.getGroupId()));
    headerElement.addAttribute(
        "user-personal-site-group-id",
        String.valueOf(portletDataContext.getUserPersonalSiteGroupId()));
    headerElement.addAttribute(
        "private-layout", String.valueOf(portletDataContext.isPrivateLayout()));

    Group group = layoutSet.getGroup();

    String type = "layout-set";

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

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

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

      layoutIds =
          ExportImportHelperUtil.getAllLayoutIds(
              portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());
    } else if (group.isLayoutSetPrototype()) {
      type = "layout-set-prototype";

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

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

    headerElement.addAttribute("type", type);

    LayoutSetBranch layoutSetBranch =
        _layoutSetBranchLocalService.fetchLayoutSetBranch(layoutSetBranchId);

    if (logo) {
      Image image = null;

      if (layoutSetBranch != null) {
        image = _imageLocalService.getImage(layoutSetBranch.getLogoId());
      } else {
        image = _imageLocalService.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());
      }
    }

    String layoutSetPrototypeUuid = layoutSet.getLayoutSetPrototypeUuid();

    if (layoutSetPrototypeSettings && Validator.isNotNull(layoutSetPrototypeUuid)) {

      LayoutSetPrototype layoutSetPrototype =
          _layoutSetPrototypeLocalService.getLayoutSetPrototypeByUuidAndCompanyId(
              layoutSetPrototypeUuid, companyId);

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

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

    portletDataContext.setMissingReferencesElement(missingReferencesElement);

    if (layoutSetBranch != null) {
      _themeExporter.exportTheme(portletDataContext, layoutSetBranch);
    } else {
      _themeExporter.exportTheme(portletDataContext, layoutSet);
    }

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

      if (layoutSetBranch != null) {
        settingsElement.addCDATA(layoutSetBranch.getSettings());
      } else {
        settingsElement.addCDATA(layoutSet.getSettings());
      }
    }

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

    List<Layout> layouts =
        _layoutLocalService.getLayouts(
            portletDataContext.getGroupId(), portletDataContext.isPrivateLayout());

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

    // Collect data portlets

    for (Portlet portlet : ExportImportHelperUtil.getDataSiteLevelPortlets(companyId)) {

      String portletId = portlet.getRootPortletId();

      if (ExportImportThreadLocal.isStagingInProcess() && !group.isStagedPortlet(portletId)) {

        continue;
      }

      // Calculate the amount of exported data

      if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
        PortletDataHandler portletDataHandler = portlet.getPortletDataHandlerInstance();

        portletDataHandler.prepareManifestSummary(portletDataContext);
      }

      // Add portlet ID to exportable portlets list

      portletIds.put(
          PortletPermissionUtil.getPrimaryKey(0, portletId),
          new Object[] {
            portletId,
            LayoutConstants.DEFAULT_PLID,
            portletDataContext.getGroupId(),
            StringPool.BLANK,
            StringPool.BLANK
          });

      if (!portlet.isScopeable()) {
        continue;
      }

      // Scoped data

      for (Layout layout : layouts) {
        if (!ArrayUtil.contains(layoutIds, layout.getLayoutId())
            || !layout.isTypePortlet()
            || !layout.hasScopeGroup()) {

          continue;
        }

        Group scopeGroup = layout.getScopeGroup();

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

    // Collect layout portlets

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

    if (BackgroundTaskThreadLocal.hasBackgroundTask()) {
      ManifestSummary manifestSummary = portletDataContext.getManifestSummary();

      PortletDataHandlerStatusMessageSenderUtil.sendStatusMessage(
          "layout", ArrayUtil.toStringArray(portletIds.keySet()), manifestSummary);

      manifestSummary.resetCounters();
    }

    // Export actual data

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

    // Force to always have a layout group element

    portletDataContext.getExportDataGroupElement(Layout.class);

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

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

    Element servicesElement = rootElement.addElement("services");

    long previousScopeGroupId = portletDataContext.getScopeGroupId();

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

      Object[] portletObjects = portletIdsEntry.getValue();

      String portletId = null;
      long 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 = _layoutLocalService.fetchLayout(plid);

      if (layout == null) {
        layout = new LayoutImpl();

        layout.setCompanyId(companyId);
        layout.setGroupId(portletDataContext.getGroupId());
      }

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

      Map<String, Boolean> exportPortletControlsMap =
          ExportImportHelperUtil.getExportPortletControlsMap(
              companyId, portletId, parameterMap, type);

      try {
        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_STARTED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));

        _portletExportController.exportPortlet(
            portletDataContext,
            layout,
            portletsElement,
            permissions,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_ARCHIVED_SETUPS),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_DATA),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP),
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_USER_PREFERENCES));
        _portletExportController.exportService(
            portletDataContext,
            servicesElement,
            exportPortletControlsMap.get(PortletDataHandlerKeys.PORTLET_SETUP));

        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_SUCCEEDED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext));
      } catch (Throwable t) {
        _exportImportLifecycleManager.fireExportImportLifecycleEvent(
            EVENT_PORTLET_EXPORT_FAILED,
            getProcessFlag(),
            PortletDataContextFactoryUtil.clonePortletDataContext(portletDataContext),
            t);

        throw t;
      }
    }

    portletDataContext.setScopeGroupId(previousScopeGroupId);

    _portletExportController.exportAssetLinks(portletDataContext);
    _portletExportController.exportExpandoTables(portletDataContext);
    _portletExportController.exportLocks(portletDataContext);

    _deletionSystemEventExporter.exportDeletionSystemEvents(portletDataContext);

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

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

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

    boolean updateLastPublishDate =
        MapUtil.getBoolean(
            portletDataContext.getParameterMap(), PortletDataHandlerKeys.UPDATE_LAST_PUBLISH_DATE);

    if (ExportImportThreadLocal.isStagingInProcess() && updateLastPublishDate) {

      ExportImportProcessCallbackRegistryUtil.registerCallback(
          new UpdateLayoutSetLastPublishDateCallable(
              portletDataContext.getDateRange(),
              portletDataContext.getGroupId(),
              portletDataContext.isPrivateLayout()));
    }

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

    ZipWriter zipWriter = portletDataContext.getZipWriter();

    return zipWriter.getFile();
  }