public KaleoTaskInstanceToken addKaleoTaskInstanceToken(
      long kaleoInstanceTokenId,
      long kaleoTaskId,
      String kaleoTaskName,
      Collection<KaleoTaskAssignment> kaleoTaskAssignments,
      Date dueDate,
      Map<String, Serializable> workflowContext,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    KaleoInstanceToken kaleoInstanceToken =
        kaleoInstanceTokenPersistence.findByPrimaryKey(kaleoInstanceTokenId);

    User user = userPersistence.findByPrimaryKey(serviceContext.getGuestOrUserId());
    Date now = new Date();

    long kaleoTaskInstanceTokenId = counterLocalService.increment();

    KaleoTaskInstanceToken kaleoTaskInstanceToken =
        kaleoTaskInstanceTokenPersistence.create(kaleoTaskInstanceTokenId);

    long groupId = StagingUtil.getLiveGroupId(serviceContext.getScopeGroupId());

    kaleoTaskInstanceToken.setGroupId(groupId);

    kaleoTaskInstanceToken.setCompanyId(user.getCompanyId());
    kaleoTaskInstanceToken.setUserId(user.getUserId());
    kaleoTaskInstanceToken.setUserName(user.getFullName());
    kaleoTaskInstanceToken.setCreateDate(now);
    kaleoTaskInstanceToken.setModifiedDate(now);
    kaleoTaskInstanceToken.setDueDate(dueDate);
    kaleoTaskInstanceToken.setKaleoDefinitionId(kaleoInstanceToken.getKaleoDefinitionId());
    kaleoTaskInstanceToken.setKaleoInstanceId(kaleoInstanceToken.getKaleoInstanceId());
    kaleoTaskInstanceToken.setKaleoInstanceTokenId(kaleoInstanceTokenId);

    kaleoTaskInstanceToken.setKaleoTaskId(kaleoTaskId);
    kaleoTaskInstanceToken.setKaleoTaskName(kaleoTaskName);

    if (workflowContext != null) {
      kaleoTaskInstanceToken.setClassName(
          (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_NAME));

      if (workflowContext.containsKey(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)) {

        kaleoTaskInstanceToken.setClassPK(
            GetterUtil.getLong(
                (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)));
      }
    }

    kaleoTaskInstanceToken.setCompleted(false);
    kaleoTaskInstanceToken.setWorkflowContext(WorkflowContextUtil.convert(workflowContext));

    kaleoTaskInstanceTokenPersistence.update(kaleoTaskInstanceToken, false);

    kaleoTaskAssignmentInstanceLocalService.addTaskAssignmentInstances(
        kaleoTaskInstanceToken, kaleoTaskAssignments, workflowContext, serviceContext);

    return kaleoTaskInstanceToken;
  }
  @Override
  public KaleoInstance addKaleoInstance(
      long kaleoDefinitionId,
      String kaleoDefinitionName,
      int kaleoDefinitionVersion,
      Map<String, Serializable> workflowContext,
      ServiceContext serviceContext)
      throws PortalException, SystemException {

    User user = userPersistence.fetchByPrimaryKey(serviceContext.getUserId());

    if (user == null) {
      user = userLocalService.getDefaultUser(serviceContext.getCompanyId());
    }

    Date now = new Date();

    long kaleoInstanceId = counterLocalService.increment();

    KaleoInstance kaleoInstance = kaleoInstancePersistence.create(kaleoInstanceId);

    long groupId = StagingUtil.getLiveGroupId(serviceContext.getScopeGroupId());

    kaleoInstance.setGroupId(groupId);

    kaleoInstance.setCompanyId(user.getCompanyId());
    kaleoInstance.setUserId(user.getUserId());
    kaleoInstance.setUserName(user.getFullName());
    kaleoInstance.setCreateDate(now);
    kaleoInstance.setModifiedDate(now);
    kaleoInstance.setKaleoDefinitionId(kaleoDefinitionId);
    kaleoInstance.setKaleoDefinitionName(kaleoDefinitionName);
    kaleoInstance.setKaleoDefinitionVersion(kaleoDefinitionVersion);
    kaleoInstance.setClassName(
        (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_NAME));

    if (workflowContext.containsKey(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)) {

      kaleoInstance.setClassPK(
          GetterUtil.getLong(
              (String) workflowContext.get(WorkflowConstants.CONTEXT_ENTRY_CLASS_PK)));
    }

    kaleoInstance.setCompleted(false);
    kaleoInstance.setWorkflowContext(WorkflowContextUtil.convert(workflowContext));

    kaleoInstancePersistence.update(kaleoInstance);

    return kaleoInstance;
  }
  @Override
  public boolean isStagedPortlet(String portletId) {
    UnicodeProperties typeSettingsProperties = getParentLiveGroupTypeSettingsProperties();

    portletId = PortletConstants.getRootPortletId(portletId);

    String typeSettingsProperty =
        typeSettingsProperties.getProperty(StagingUtil.getStagedPortletId(portletId));

    if (Validator.isNotNull(typeSettingsProperty)) {
      return GetterUtil.getBoolean(typeSettingsProperty);
    }

    try {
      Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId);

      String portletDataHandlerClass = portlet.getPortletDataHandlerClass();

      if (Validator.isNull(portletDataHandlerClass)) {
        return true;
      }

      for (Map.Entry<String, String> entry : typeSettingsProperties.entrySet()) {

        String key = entry.getKey();

        if (!key.contains(StagingConstants.STAGED_PORTLET)) {
          continue;
        }

        String stagedPortletId =
            StringUtil.replace(key, StagingConstants.STAGED_PORTLET, StringPool.BLANK);

        Portlet stagedPortlet = PortletLocalServiceUtil.getPortletById(stagedPortletId);

        if (portletDataHandlerClass.equals(stagedPortlet.getPortletDataHandlerClass())) {

          return GetterUtil.getBoolean(entry.getValue());
        }
      }
    } catch (Exception e) {
    }

    return true;
  }
  protected void importLayout(
      PortletDataContext portletDataContext,
      User user,
      LayoutCache layoutCache,
      List<Layout> previousLayouts,
      List<Layout> newLayouts,
      Map<Long, Layout> newLayoutsMap,
      Set<Long> newLayoutIds,
      String portletsMergeMode,
      String themeId,
      String colorSchemeId,
      String layoutsImportMode,
      boolean privateLayout,
      boolean importPermissions,
      boolean importPublicLayoutPermissions,
      boolean importUserPermissions,
      boolean importThemeSettings,
      Element rootElement,
      Element layoutElement)
      throws Exception {

    long groupId = portletDataContext.getGroupId();

    String layoutUuid = GetterUtil.getString(layoutElement.attributeValue("layout-uuid"));

    long layoutId = GetterUtil.getInteger(layoutElement.attributeValue("layout-id"));

    long oldLayoutId = layoutId;

    boolean deleteLayout = GetterUtil.getBoolean(layoutElement.attributeValue("delete"));

    if (deleteLayout) {
      Layout layout = LayoutLocalServiceUtil.fetchLayoutByUuidAndGroupId(layoutUuid, groupId);

      if (layout != null) {
        newLayoutsMap.put(oldLayoutId, layout);

        ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

        LayoutLocalServiceUtil.deleteLayout(layout, false, serviceContext);
      }

      return;
    }

    String path = layoutElement.attributeValue("path");

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

    Layout layout = (Layout) portletDataContext.getZipEntryAsObject(path);

    Layout existingLayout = null;
    Layout importedLayout = null;

    String friendlyURL = layout.getFriendlyURL();

    if (layoutsImportMode.equals(PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_ADD_AS_NEW)) {

      layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      friendlyURL = StringPool.SLASH + layoutId;
    } else if (layoutsImportMode.equals(
        PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_NAME)) {

      Locale locale = LocaleUtil.getDefault();

      String localizedName = layout.getName(locale);

      for (Layout curLayout : previousLayouts) {
        if (localizedName.equals(curLayout.getName(locale))
            || friendlyURL.equals(curLayout.getFriendlyURL())) {

          existingLayout = curLayout;

          break;
        }
      }

      if (existingLayout == null) {
        layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      }
    } else if (layoutsImportMode.equals(
        PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

      existingLayout = LayoutUtil.fetchByG_P_SPLU(groupId, privateLayout, layout.getUuid());

      if (SitesUtil.isLayoutModifiedSinceLastMerge(existingLayout)) {
        newLayoutsMap.put(oldLayoutId, existingLayout);

        return;
      }
    } else {

      // The default behaviour of import mode is
      // PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_MERGE_BY_LAYOUT_UUID

      existingLayout = LayoutUtil.fetchByUUID_G(layout.getUuid(), groupId);

      if (existingLayout == null) {
        existingLayout = LayoutUtil.fetchByG_P_F(groupId, privateLayout, friendlyURL);
      }

      if (existingLayout == null) {
        layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      }
    }

    if (_log.isDebugEnabled()) {
      if (existingLayout == null) {
        _log.debug(
            "Layout with {groupId="
                + groupId
                + ",privateLayout="
                + privateLayout
                + ",layoutId="
                + layoutId
                + "} does not exist");
      } else {
        _log.debug(
            "Layout with {groupId="
                + groupId
                + ",privateLayout="
                + privateLayout
                + ",layoutId="
                + layoutId
                + "} exists");
      }
    }

    if (existingLayout == null) {
      long plid = CounterLocalServiceUtil.increment();

      importedLayout = LayoutUtil.create(plid);

      if (layoutsImportMode.equals(
          PortletDataHandlerKeys.LAYOUTS_IMPORT_MODE_CREATED_FROM_PROTOTYPE)) {

        importedLayout.setSourcePrototypeLayoutUuid(layout.getUuid());

        layoutId = LayoutLocalServiceUtil.getNextLayoutId(groupId, privateLayout);
      } else {
        importedLayout.setUuid(layout.getUuid());
        importedLayout.setCreateDate(layout.getCreateDate());
        importedLayout.setModifiedDate(layout.getModifiedDate());
        importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
        importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());
        importedLayout.setSourcePrototypeLayoutUuid(layout.getSourcePrototypeLayoutUuid());
      }

      importedLayout.setGroupId(groupId);
      importedLayout.setPrivateLayout(privateLayout);
      importedLayout.setLayoutId(layoutId);

      // Resources

      boolean addGroupPermissions = true;

      Group group = importedLayout.getGroup();

      if (privateLayout && group.isUser()) {
        addGroupPermissions = false;
      }

      boolean addGuestPermissions = false;

      if (!privateLayout || layout.isTypeControlPanel()) {
        addGuestPermissions = true;
      }

      ResourceLocalServiceUtil.addResources(
          user.getCompanyId(),
          groupId,
          user.getUserId(),
          Layout.class.getName(),
          importedLayout.getPlid(),
          false,
          addGroupPermissions,
          addGuestPermissions);

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

      importedLayout.setLayoutSet(layoutSet);
    } else {
      importedLayout = existingLayout;
    }

    newLayoutsMap.put(oldLayoutId, importedLayout);

    long parentLayoutId = layout.getParentLayoutId();

    Node parentLayoutNode =
        rootElement.selectSingleNode("./layouts/layout[@layout-id='" + parentLayoutId + "']");

    String parentLayoutUuid =
        GetterUtil.getString(layoutElement.attributeValue("parent-layout-uuid"));

    if ((parentLayoutId != LayoutConstants.DEFAULT_PARENT_LAYOUT_ID)
        && (parentLayoutNode != null)) {

      importLayout(
          portletDataContext,
          user,
          layoutCache,
          previousLayouts,
          newLayouts,
          newLayoutsMap,
          newLayoutIds,
          portletsMergeMode,
          themeId,
          colorSchemeId,
          layoutsImportMode,
          privateLayout,
          importPermissions,
          importPublicLayoutPermissions,
          importUserPermissions,
          importThemeSettings,
          rootElement,
          (Element) parentLayoutNode);

      Layout parentLayout = newLayoutsMap.get(parentLayoutId);

      parentLayoutId = parentLayout.getLayoutId();
    } else if (Validator.isNotNull(parentLayoutUuid)) {
      Layout parentLayout =
          LayoutLocalServiceUtil.getLayoutByUuidAndGroupId(parentLayoutUuid, groupId);

      parentLayoutId = parentLayout.getLayoutId();
    }

    if (_log.isDebugEnabled()) {
      _log.debug(
          "Importing layout with layout id "
              + layoutId
              + " and parent layout id "
              + parentLayoutId);
    }

    importedLayout.setCompanyId(user.getCompanyId());
    importedLayout.setParentLayoutId(parentLayoutId);
    importedLayout.setName(layout.getName());
    importedLayout.setTitle(layout.getTitle());
    importedLayout.setDescription(layout.getDescription());
    importedLayout.setKeywords(layout.getKeywords());
    importedLayout.setRobots(layout.getRobots());
    importedLayout.setType(layout.getType());

    if (layout.isTypeArticle()) {
      importJournalArticle(portletDataContext, layout, layoutElement);

      importedLayout.setTypeSettings(layout.getTypeSettings());
    } else if (layout.isTypePortlet()
        && Validator.isNotNull(layout.getTypeSettings())
        && !portletsMergeMode.equals(PortletDataHandlerKeys.PORTLETS_MERGE_MODE_REPLACE)) {

      mergePortlets(importedLayout, layout.getTypeSettings(), portletsMergeMode);
    } else if (layout.isTypeLinkToLayout()) {
      UnicodeProperties typeSettingsProperties = layout.getTypeSettingsProperties();

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

      if (linkToLayoutId > 0) {
        Node linkedLayoutNode =
            rootElement.selectSingleNode("./layouts/layout[@layout-id='" + linkToLayoutId + "']");

        if (linkedLayoutNode != null) {
          importLayout(
              portletDataContext,
              user,
              layoutCache,
              previousLayouts,
              newLayouts,
              newLayoutsMap,
              newLayoutIds,
              portletsMergeMode,
              themeId,
              colorSchemeId,
              layoutsImportMode,
              privateLayout,
              importPermissions,
              importPublicLayoutPermissions,
              importUserPermissions,
              importThemeSettings,
              rootElement,
              (Element) linkedLayoutNode);

          Layout linkedLayout = newLayoutsMap.get(linkToLayoutId);

          typeSettingsProperties.setProperty(
              "privateLayout", String.valueOf(linkedLayout.getPrivateLayout()));
          typeSettingsProperties.setProperty(
              "linkToLayoutId", String.valueOf(linkedLayout.getLayoutId()));
        } else {
          if (_log.isWarnEnabled()) {
            StringBundler sb = new StringBundler();

            sb.append("Unable to link layout with friendly URL ");
            sb.append(layout.getFriendlyURL());
            sb.append(" and layout id ");
            sb.append(layout.getLayoutId());
            sb.append(" to layout with layout id ");
            sb.append(linkToLayoutId);

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

      importedLayout.setTypeSettings(layout.getTypeSettings());
    } else {
      importedLayout.setTypeSettings(layout.getTypeSettings());
    }

    importedLayout.setHidden(layout.isHidden());
    importedLayout.setFriendlyURL(friendlyURL);

    if (importThemeSettings) {
      importedLayout.setThemeId(layout.getThemeId());
      importedLayout.setColorSchemeId(layout.getColorSchemeId());
    } else {
      importedLayout.setThemeId(StringPool.BLANK);
      importedLayout.setColorSchemeId(StringPool.BLANK);
    }

    importedLayout.setWapThemeId(layout.getWapThemeId());
    importedLayout.setWapColorSchemeId(layout.getWapColorSchemeId());
    importedLayout.setCss(layout.getCss());
    importedLayout.setPriority(layout.getPriority());
    importedLayout.setLayoutPrototypeUuid(layout.getLayoutPrototypeUuid());
    importedLayout.setLayoutPrototypeLinkEnabled(layout.isLayoutPrototypeLinkEnabled());

    StagingUtil.updateLastImportSettings(layoutElement, importedLayout, portletDataContext);

    fixTypeSettings(importedLayout);

    importedLayout.setIconImage(false);

    if (layout.isIconImage()) {
      String iconImagePath = layoutElement.elementText("icon-image-path");

      byte[] iconBytes = portletDataContext.getZipEntryAsByteArray(iconImagePath);

      if ((iconBytes != null) && (iconBytes.length > 0)) {
        importedLayout.setIconImage(true);

        if (importedLayout.getIconImageId() == 0) {
          long iconImageId = CounterLocalServiceUtil.increment();

          importedLayout.setIconImageId(iconImageId);
        }

        ImageLocalServiceUtil.updateImage(importedLayout.getIconImageId(), iconBytes);
      }
    } else {
      ImageLocalServiceUtil.deleteImage(importedLayout.getIconImageId());
    }

    ServiceContext serviceContext =
        portletDataContext.createServiceContext(layoutElement, importedLayout, null);

    importedLayout.setExpandoBridgeAttributes(serviceContext);

    LayoutUtil.update(importedLayout, false);

    portletDataContext.setPlid(importedLayout.getPlid());
    portletDataContext.setOldPlid(layout.getPlid());

    newLayoutIds.add(importedLayout.getLayoutId());

    newLayouts.add(importedLayout);

    // Layout permissions

    if (importPermissions) {
      _permissionImporter.importLayoutPermissions(
          layoutCache,
          portletDataContext.getCompanyId(),
          groupId,
          user.getUserId(),
          importedLayout,
          layoutElement,
          rootElement,
          importUserPermissions);
    }

    if (importPublicLayoutPermissions) {
      String resourceName = Layout.class.getName();
      String resourcePrimKey = String.valueOf(importedLayout.getPlid());

      Role guestRole =
          RoleLocalServiceUtil.getRole(importedLayout.getCompanyId(), RoleConstants.GUEST);

      if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 5) {
        Resource resource =
            layoutCache.getResource(
                importedLayout.getCompanyId(),
                groupId,
                resourceName,
                ResourceConstants.SCOPE_INDIVIDUAL,
                resourcePrimKey,
                false);

        PermissionLocalServiceUtil.setRolePermissions(
            guestRole.getRoleId(), new String[] {ActionKeys.VIEW}, resource.getResourceId());
      } else if (PropsValues.PERMISSIONS_USER_CHECK_ALGORITHM == 6) {
        ResourcePermissionLocalServiceUtil.setResourcePermissions(
            importedLayout.getCompanyId(),
            resourceName,
            ResourceConstants.SCOPE_INDIVIDUAL,
            resourcePrimKey,
            guestRole.getRoleId(),
            new String[] {ActionKeys.VIEW});
      } else {
        Resource resource =
            layoutCache.getResource(
                importedLayout.getCompanyId(),
                groupId,
                resourceName,
                ResourceConstants.SCOPE_INDIVIDUAL,
                resourcePrimKey,
                false);

        PermissionLocalServiceUtil.setGroupPermissions(
            groupId, new String[] {ActionKeys.VIEW}, resource.getResourceId());
      }
    }

    _portletImporter.importPortletData(
        portletDataContext, PortletKeys.LAYOUT_CONFIGURATION, null, layoutElement);
  }
  protected Object[] updateGroup(ActionRequest actionRequest) throws Exception {

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

    long userId = PortalUtil.getUserId(actionRequest);

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

    long parentGroupId =
        ParamUtil.getLong(
            actionRequest,
            "parentGroupSearchContainerPrimaryKeys",
            GroupConstants.DEFAULT_PARENT_GROUP_ID);
    String name = null;
    String description = null;
    int type = 0;
    String friendlyURL = null;
    boolean active = false;

    ServiceContext serviceContext =
        ServiceContextFactory.getInstance(Group.class.getName(), actionRequest);

    Group liveGroup = null;
    String oldFriendlyURL = null;
    String oldStagingFriendlyURL = null;

    if (liveGroupId <= 0) {

      // Add group

      name = ParamUtil.getString(actionRequest, "name");
      description = ParamUtil.getString(actionRequest, "description");
      type = ParamUtil.getInteger(actionRequest, "type");
      friendlyURL = ParamUtil.getString(actionRequest, "friendlyURL");
      active = ParamUtil.getBoolean(actionRequest, "active");

      liveGroup =
          GroupServiceUtil.addGroup(
              parentGroupId,
              GroupConstants.DEFAULT_LIVE_GROUP_ID,
              name,
              description,
              type,
              friendlyURL,
              true,
              active,
              serviceContext);

      LiveUsers.joinGroup(themeDisplay.getCompanyId(), liveGroup.getGroupId(), userId);
    } else {

      // Update group

      liveGroup = GroupLocalServiceUtil.getGroup(liveGroupId);

      oldFriendlyURL = liveGroup.getFriendlyURL();

      name = ParamUtil.getString(actionRequest, "name", liveGroup.getName());
      description = ParamUtil.getString(actionRequest, "description", liveGroup.getDescription());
      type = ParamUtil.getInteger(actionRequest, "type", liveGroup.getType());
      friendlyURL = ParamUtil.getString(actionRequest, "friendlyURL", liveGroup.getFriendlyURL());
      active = ParamUtil.getBoolean(actionRequest, "active", liveGroup.getActive());

      liveGroup =
          GroupServiceUtil.updateGroup(
              liveGroupId,
              parentGroupId,
              name,
              description,
              type,
              friendlyURL,
              active,
              serviceContext);

      if (type == GroupConstants.TYPE_SITE_OPEN) {
        List<MembershipRequest> membershipRequests =
            MembershipRequestLocalServiceUtil.search(
                liveGroupId,
                MembershipRequestConstants.STATUS_PENDING,
                QueryUtil.ALL_POS,
                QueryUtil.ALL_POS);

        for (MembershipRequest membershipRequest : membershipRequests) {
          MembershipRequestServiceUtil.updateStatus(
              membershipRequest.getMembershipRequestId(),
              themeDisplay.translate("your-membership-has-been-approved"),
              MembershipRequestConstants.STATUS_APPROVED,
              serviceContext);

          LiveUsers.joinGroup(
              themeDisplay.getCompanyId(),
              membershipRequest.getGroupId(),
              new long[] {membershipRequest.getUserId()});
        }
      }
    }

    // Settings

    UnicodeProperties typeSettingsProperties = liveGroup.getTypeSettingsProperties();

    String customJspServletContextName =
        ParamUtil.getString(
            actionRequest,
            "customJspServletContextName",
            typeSettingsProperties.getProperty("customJspServletContextName"));

    typeSettingsProperties.setProperty("customJspServletContextName", customJspServletContextName);

    typeSettingsProperties.setProperty(
        "defaultSiteRoleIds",
        ListUtil.toString(getRoles(actionRequest), Role.ROLE_ID_ACCESSOR, StringPool.COMMA));
    typeSettingsProperties.setProperty(
        "defaultTeamIds",
        ListUtil.toString(getTeams(actionRequest), Team.TEAM_ID_ACCESSOR, StringPool.COMMA));

    String[] analyticsTypes =
        PrefsPropsUtil.getStringArray(
            themeDisplay.getCompanyId(), PropsKeys.ADMIN_ANALYTICS_TYPES, StringPool.NEW_LINE);

    for (String analyticsType : analyticsTypes) {
      if (analyticsType.equalsIgnoreCase("google")) {
        String googleAnalyticsId =
            ParamUtil.getString(
                actionRequest,
                "googleAnalyticsId",
                typeSettingsProperties.getProperty("googleAnalyticsId"));

        typeSettingsProperties.setProperty("googleAnalyticsId", googleAnalyticsId);
      } else {
        String analyticsScript =
            ParamUtil.getString(
                actionRequest,
                SitesUtil.ANALYTICS_PREFIX + analyticsType,
                typeSettingsProperties.getProperty(analyticsType));

        typeSettingsProperties.setProperty(
            SitesUtil.ANALYTICS_PREFIX + analyticsType, analyticsScript);
      }
    }

    String publicRobots =
        ParamUtil.getString(
            actionRequest, "publicRobots", liveGroup.getTypeSettingsProperty("false-robots.txt"));
    String privateRobots =
        ParamUtil.getString(
            actionRequest, "privateRobots", liveGroup.getTypeSettingsProperty("true-robots.txt"));

    typeSettingsProperties.setProperty("false-robots.txt", publicRobots);
    typeSettingsProperties.setProperty("true-robots.txt", privateRobots);

    int trashEnabled =
        ParamUtil.getInteger(
            actionRequest,
            "trashEnabled",
            GetterUtil.getInteger(typeSettingsProperties.getProperty("trashEnabled")));

    typeSettingsProperties.setProperty("trashEnabled", String.valueOf(trashEnabled));

    int trashEntriesMaxAgeCompany =
        PrefsPropsUtil.getInteger(themeDisplay.getCompanyId(), PropsKeys.TRASH_ENTRIES_MAX_AGE);

    int defaultTrashEntriesMaxAgeGroup =
        GetterUtil.getInteger(
            typeSettingsProperties.getProperty("trashEntriesMaxAge"), trashEntriesMaxAgeCompany);

    int trashEntriesMaxAgeGroup =
        ParamUtil.getInteger(actionRequest, "trashEntriesMaxAge", defaultTrashEntriesMaxAgeGroup);

    if (trashEntriesMaxAgeGroup != trashEntriesMaxAgeCompany) {
      typeSettingsProperties.setProperty(
          "trashEntriesMaxAge", String.valueOf(trashEntriesMaxAgeGroup));
    } else {
      typeSettingsProperties.remove("trashEntriesMaxAge");
    }

    // Virtual hosts

    LayoutSet publicLayoutSet = liveGroup.getPublicLayoutSet();

    String publicVirtualHost =
        ParamUtil.getString(
            actionRequest, "publicVirtualHost", publicLayoutSet.getVirtualHostname());

    LayoutSetServiceUtil.updateVirtualHost(liveGroup.getGroupId(), false, publicVirtualHost);

    LayoutSet privateLayoutSet = liveGroup.getPrivateLayoutSet();

    String privateVirtualHost =
        ParamUtil.getString(
            actionRequest, "privateVirtualHost", privateLayoutSet.getVirtualHostname());

    LayoutSetServiceUtil.updateVirtualHost(liveGroup.getGroupId(), true, privateVirtualHost);

    // Staging

    if (liveGroup.hasStagingGroup()) {
      Group stagingGroup = liveGroup.getStagingGroup();

      oldStagingFriendlyURL = stagingGroup.getFriendlyURL();

      friendlyURL =
          ParamUtil.getString(actionRequest, "stagingFriendlyURL", stagingGroup.getFriendlyURL());

      GroupServiceUtil.updateFriendlyURL(stagingGroup.getGroupId(), friendlyURL);

      LayoutSet stagingPublicLayoutSet = stagingGroup.getPublicLayoutSet();

      publicVirtualHost =
          ParamUtil.getString(
              actionRequest,
              "stagingPublicVirtualHost",
              stagingPublicLayoutSet.getVirtualHostname());

      LayoutSetServiceUtil.updateVirtualHost(stagingGroup.getGroupId(), false, publicVirtualHost);

      LayoutSet stagingPrivateLayoutSet = stagingGroup.getPrivateLayoutSet();

      privateVirtualHost =
          ParamUtil.getString(
              actionRequest,
              "stagingPrivateVirtualHost",
              stagingPrivateLayoutSet.getVirtualHostname());

      LayoutSetServiceUtil.updateVirtualHost(stagingGroup.getGroupId(), true, privateVirtualHost);
    }

    liveGroup =
        GroupServiceUtil.updateGroup(liveGroup.getGroupId(), typeSettingsProperties.toString());

    // Layout set prototypes

    if (!liveGroup.isStaged()) {
      long privateLayoutSetPrototypeId =
          ParamUtil.getLong(actionRequest, "privateLayoutSetPrototypeId");
      long publicLayoutSetPrototypeId =
          ParamUtil.getLong(actionRequest, "publicLayoutSetPrototypeId");

      boolean privateLayoutSetPrototypeLinkEnabled =
          ParamUtil.getBoolean(
              actionRequest,
              "privateLayoutSetPrototypeLinkEnabled",
              privateLayoutSet.isLayoutSetPrototypeLinkEnabled());
      boolean publicLayoutSetPrototypeLinkEnabled =
          ParamUtil.getBoolean(
              actionRequest,
              "publicLayoutSetPrototypeLinkEnabled",
              publicLayoutSet.isLayoutSetPrototypeLinkEnabled());

      if ((privateLayoutSetPrototypeId == 0)
          && (publicLayoutSetPrototypeId == 0)
          && !privateLayoutSetPrototypeLinkEnabled
          && !publicLayoutSetPrototypeLinkEnabled) {

        long layoutSetPrototypeId = ParamUtil.getLong(actionRequest, "layoutSetPrototypeId");
        int layoutSetVisibility = ParamUtil.getInteger(actionRequest, "layoutSetVisibility");
        boolean layoutSetPrototypeLinkEnabled =
            ParamUtil.getBoolean(
                actionRequest, "layoutSetPrototypeLinkEnabled", (layoutSetPrototypeId > 0));

        if (layoutSetVisibility == _LAYOUT_SET_VISIBILITY_PRIVATE) {
          privateLayoutSetPrototypeId = layoutSetPrototypeId;

          privateLayoutSetPrototypeLinkEnabled = layoutSetPrototypeLinkEnabled;
        } else {
          publicLayoutSetPrototypeId = layoutSetPrototypeId;

          publicLayoutSetPrototypeLinkEnabled = layoutSetPrototypeLinkEnabled;
        }
      }

      SitesUtil.updateLayoutSetPrototypesLinks(
          liveGroup,
          publicLayoutSetPrototypeId,
          privateLayoutSetPrototypeId,
          publicLayoutSetPrototypeLinkEnabled,
          privateLayoutSetPrototypeLinkEnabled);
    }

    // Staging

    String redirect = ParamUtil.getString(actionRequest, "redirect");

    long refererPlid = GetterUtil.getLong(HttpUtil.getParameter(redirect, "refererPlid", false));

    if (!privateLayoutSet.isLayoutSetPrototypeLinkActive()
        && !publicLayoutSet.isLayoutSetPrototypeLinkActive()) {

      if ((refererPlid > 0)
          && liveGroup.hasStagingGroup()
          && (themeDisplay.getScopeGroupId() != liveGroup.getGroupId())) {

        Layout firstLayout =
            LayoutLocalServiceUtil.fetchFirstLayout(
                liveGroup.getGroupId(), false, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);

        if (firstLayout == null) {
          firstLayout =
              LayoutLocalServiceUtil.fetchFirstLayout(
                  liveGroup.getGroupId(), true, LayoutConstants.DEFAULT_PARENT_LAYOUT_ID);
        }

        if (firstLayout != null) {
          refererPlid = firstLayout.getPlid();
        } else {
          refererPlid = 0;
        }
      }

      StagingUtil.updateStaging(actionRequest, liveGroup);
    }

    return new Object[] {liveGroup, oldFriendlyURL, oldStagingFriendlyURL, refererPlid};
  }
  private LayoutRevision _getLayoutRevision(Layout layout, LayoutRevision layoutRevision)
      throws PortalException, SystemException {

    if (layoutRevision != null) {
      return layoutRevision;
    }

    ServiceContext serviceContext = ServiceContextThreadLocal.getServiceContext();

    if (!serviceContext.isSignedIn()) {
      LayoutRevision lastLayoutRevision = null;

      lastLayoutRevision =
          LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(), true);

      if (lastLayoutRevision == null) {
        lastLayoutRevision =
            LayoutRevisionLocalServiceUtil.fetchLastLayoutRevision(layout.getPlid(), false);
      }

      return lastLayoutRevision;
    }

    User user = UserLocalServiceUtil.getUser(serviceContext.getUserId());

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

    LayoutSet layoutSet = layout.getLayoutSet();

    LayoutSetBranch layoutSetBranch =
        LayoutSetBranchLocalServiceUtil.getUserLayoutSetBranch(
            serviceContext.getUserId(),
            layout.getGroupId(),
            layout.isPrivateLayout(),
            layoutSet.getLayoutSetId(),
            layoutSetBranchId);

    layoutSetBranchId = layoutSetBranch.getLayoutSetBranchId();

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

    if (layoutRevisionId <= 0) {
      layoutRevisionId =
          StagingUtil.getRecentLayoutRevisionId(user, layoutSetBranchId, layout.getPlid());
    }

    if (layoutRevisionId > 0) {
      layoutRevision = LayoutRevisionLocalServiceUtil.fetchLayoutRevision(layoutRevisionId);

      if (layoutRevision.getStatus() != WorkflowConstants.STATUS_INACTIVE) {

        return layoutRevision;
      }

      layoutRevision = null;
    }

    List<LayoutRevision> layoutRevisions =
        LayoutRevisionLocalServiceUtil.getLayoutRevisions(
            layoutSetBranchId,
            layout.getPlid(),
            QueryUtil.ALL_POS,
            QueryUtil.ALL_POS,
            new LayoutRevisionCreateDateComparator(true));

    if (!layoutRevisions.isEmpty()) {
      layoutRevision = layoutRevisions.get(0);

      for (LayoutRevision curLayoutRevision : layoutRevisions) {
        if (curLayoutRevision.isHead()) {
          layoutRevision = curLayoutRevision;

          break;
        }
      }
    }

    if (layoutRevision != null) {
      StagingUtil.setRecentLayoutRevisionId(
          user, layoutSetBranchId, layout.getPlid(), layoutRevision.getLayoutRevisionId());

      return layoutRevision;
    }

    LayoutBranch layoutBranch =
        LayoutBranchLocalServiceUtil.getMasterLayoutBranch(
            layoutSetBranchId, layout.getPlid(), serviceContext);

    if (!MergeLayoutPrototypesThreadLocal.isInProgress()) {
      serviceContext.setWorkflowAction(WorkflowConstants.ACTION_SAVE_DRAFT);
    }

    return LayoutRevisionLocalServiceUtil.addLayoutRevision(
        serviceContext.getUserId(),
        layoutSetBranchId,
        layoutBranch.getLayoutBranchId(),
        LayoutRevisionConstants.DEFAULT_PARENT_LAYOUT_REVISION_ID,
        false,
        layout.getPlid(),
        LayoutConstants.DEFAULT_PLID,
        layout.isPrivateLayout(),
        layout.getName(),
        layout.getTitle(),
        layout.getDescription(),
        layout.getKeywords(),
        layout.getRobots(),
        layout.getTypeSettings(),
        layout.getIconImage(),
        layout.getIconImageId(),
        layout.getThemeId(),
        layout.getColorSchemeId(),
        layout.getWapThemeId(),
        layout.getWapColorSchemeId(),
        layout.getCss(),
        serviceContext);
  }
  public static String getLayoutsJSON(
      HttpServletRequest request,
      long groupId,
      boolean privateLayout,
      long parentLayoutId,
      long[] expandedLayoutIds)
      throws Exception {

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

    JSONArray jsonArray = JSONFactoryUtil.createJSONArray();

    List<Layout> layoutAncestors = null;

    long selPlid = ParamUtil.getLong(request, "selPlid");

    if (selPlid != 0) {
      Layout selLayout = LayoutLocalServiceUtil.getLayout(selPlid);

      layoutAncestors = selLayout.getAncestors();
    }

    List<Layout> layouts = getLayouts(request, groupId, privateLayout, parentLayoutId);

    for (Layout layout : layouts) {
      JSONObject jsonObject = JSONFactoryUtil.createJSONObject();

      if ((layoutAncestors != null) && layoutAncestors.contains(layout)
          || ArrayUtil.contains(expandedLayoutIds, layout.getLayoutId())) {

        String childrenJSON = StringPool.BLANK;

        if (layout instanceof VirtualLayout) {
          VirtualLayout virtualLayout = (VirtualLayout) layout;

          childrenJSON =
              getLayoutsJSON(
                  request,
                  virtualLayout.getSourceGroupId(),
                  virtualLayout.getPrivateLayout(),
                  virtualLayout.getLayoutId(),
                  expandedLayoutIds);

        } else {
          childrenJSON =
              getLayoutsJSON(
                  request,
                  groupId,
                  layout.getPrivateLayout(),
                  layout.getLayoutId(),
                  expandedLayoutIds);
        }

        jsonObject.put("children", JSONFactoryUtil.createJSONArray(childrenJSON));
      }

      jsonObject.put("contentDisplayPage", layout.isContentDisplayPage());
      jsonObject.put("friendlyURL", layout.getFriendlyURL());

      if (layout instanceof VirtualLayout) {
        VirtualLayout virtualLayout = (VirtualLayout) layout;

        jsonObject.put("groupId", virtualLayout.getSourceGroupId());
      } else {
        jsonObject.put("groupId", layout.getGroupId());
      }

      jsonObject.put("hasChildren", layout.hasChildren());
      jsonObject.put("layoutId", layout.getLayoutId());
      jsonObject.put("name", layout.getName(themeDisplay.getLocale()));
      jsonObject.put("parentLayoutId", layout.getParentLayoutId());
      jsonObject.put("plid", layout.getPlid());
      jsonObject.put("priority", layout.getPriority());
      jsonObject.put("privateLayout", layout.isPrivateLayout());
      jsonObject.put("type", layout.getType());
      jsonObject.put("updateable", SitesUtil.isLayoutUpdateable(layout));
      jsonObject.put("uuid", layout.getUuid());

      LayoutRevision layoutRevision = LayoutStagingUtil.getLayoutRevision(layout);

      if (layoutRevision != null) {
        User user = themeDisplay.getUser();

        long recentLayoutSetBranchId =
            StagingUtil.getRecentLayoutSetBranchId(user, layout.getLayoutSet().getLayoutSetId());

        if (StagingUtil.isIncomplete(layout, recentLayoutSetBranchId)) {
          jsonObject.put("incomplete", true);
        }

        long layoutSetBranchId = layoutRevision.getLayoutSetBranchId();

        LayoutSetBranch layoutSetBranch =
            LayoutSetBranchLocalServiceUtil.getLayoutSetBranch(layoutSetBranchId);

        LayoutBranch layoutBranch = layoutRevision.getLayoutBranch();

        if (!layoutBranch.isMaster()) {
          jsonObject.put("layoutBranchId", layoutBranch.getLayoutBranchId());
          jsonObject.put("layoutBranchName", layoutBranch.getName());
        }

        jsonObject.put("layoutRevisionId", layoutRevision.getLayoutRevisionId());
        jsonObject.put("layoutSetBranchId", layoutSetBranchId);
        jsonObject.put("layoutSetBranchName", layoutSetBranch.getName());
      }

      jsonArray.put(jsonObject);
    }

    return jsonArray.toString();
  }
  protected void enableLocalStaging(boolean stageJournal, boolean stagePolls) throws Exception {

    Group group = ServiceTestUtil.addGroup();

    ServiceTestUtil.addLayout(group.getGroupId(), "Page1");
    ServiceTestUtil.addLayout(group.getGroupId(), "Page2");

    int initialPagesCount = LayoutLocalServiceUtil.getLayoutsCount(group, false);

    // Create content

    JournalArticle journalArticle = addJournalArticle(group.getGroupId(), "Title", "content");

    PollsQuestion pollsQuestion = addPollsQuestion(group.getGroupId(), "Question", "Description");

    ServiceContext serviceContext = ServiceTestUtil.getServiceContext();

    serviceContext.setAddGroupPermissions(true);
    serviceContext.setAddGuestPermissions(true);
    serviceContext.setScopeGroupId(group.getGroupId());

    Map<String, String[]> parameters = StagingUtil.getStagingParameters();

    parameters.put(PortletDataHandlerKeys.PORTLET_DATA_ALL, new String[] {String.valueOf(false)});

    parameters.put(
        PortletDataHandlerKeys.PORTLET_DATA + "_" + PortletKeys.JOURNAL,
        new String[] {String.valueOf(stageJournal)});

    parameters.put(
        PortletDataHandlerKeys.PORTLET_DATA + "_" + PortletKeys.POLLS,
        new String[] {String.valueOf(stagePolls)});

    for (String parameterName : parameters.keySet()) {
      serviceContext.setAttribute(parameterName, parameters.get(parameterName)[0]);
    }

    serviceContext.setAttribute(
        StagingConstants.STAGED_PORTLET + PortletKeys.JOURNAL, stageJournal);

    serviceContext.setAttribute(StagingConstants.STAGED_PORTLET + PortletKeys.POLLS, stagePolls);

    // Enable staging

    StagingUtil.enableLocalStaging(
        TestPropsValues.getUserId(), group, group, false, false, serviceContext);

    Group stagingGroup = group.getStagingGroup();

    Assert.assertNotNull(stagingGroup);

    Assert.assertEquals(
        LayoutLocalServiceUtil.getLayoutsCount(stagingGroup, false), initialPagesCount);

    // Update content in staging

    JournalArticle stagingJournalArticle =
        JournalArticleLocalServiceUtil.getArticleByUrlTitle(
            stagingGroup.getGroupId(), journalArticle.getUrlTitle());

    stagingJournalArticle =
        updateJournalArticle(stagingJournalArticle, "Title2", stagingJournalArticle.getContent());

    PollsQuestion stagingQuestion =
        PollsQuestionLocalServiceUtil.getPollsQuestionByUuidAndGroupId(
            pollsQuestion.getUuid(), stagingGroup.getGroupId());

    stagingQuestion = updatePollsQuestion(stagingQuestion, "Question2", "Description2");

    // Publish to live

    StagingUtil.publishLayouts(
        TestPropsValues.getUserId(),
        stagingGroup.getGroupId(),
        group.getGroupId(),
        false,
        parameters,
        null,
        null);

    // Retrieve content from live after publishing

    journalArticle = JournalArticleLocalServiceUtil.getArticle(journalArticle.getId());
    pollsQuestion = PollsQuestionLocalServiceUtil.getQuestion(pollsQuestion.getQuestionId());

    if (stagePolls) {
      for (Locale locale : _locales) {
        Assert.assertEquals(pollsQuestion.getTitle(locale), stagingQuestion.getTitle(locale));
      }
    } else {
      for (Locale locale : _locales) {
        Assert.assertFalse(pollsQuestion.getTitle(locale).equals(stagingQuestion.getTitle(locale)));
      }
    }

    if (stageJournal) {
      for (Locale locale : _locales) {
        Assert.assertEquals(
            journalArticle.getTitle(locale), stagingJournalArticle.getTitle(locale));
      }
    } else {
      for (Locale locale : _locales) {
        Assert.assertFalse(
            journalArticle.getTitle(locale).equals(stagingJournalArticle.getTitle(locale)));
      }
    }
  }
Exemple #9
0
  public long getSiteGroupIdOrLiveGroupId() throws PortalException, SystemException {

    return StagingUtil.getLiveGroupId(_siteGroupId);
  }