/**
   * @param folder This is the folder where the assets are stored
   * @param fileAssetsList This is the list of all the file assets
   * @return
   */
  private static List<String> findFileAssetsList(File folder, List<String> fileAssetsList) {
    File[] files = folder.listFiles();
    if (0 < files.length) {
      List<Structure> structures = StructureFactory.getStructures();
      List<Field> binaryFields = new ArrayList<Field>();
      List<Field> fields;
      for (Structure structure : structures) {
        fields = FieldsCache.getFieldsByStructureInode(structure.getInode());

        for (Field field : fields) {
          if (field.getFieldType().equals(Field.FieldType.BINARY.toString()))
            binaryFields.add(field);
        }
      }

      boolean isBinaryField;
      for (int j = 0; j < files.length; j++) {
        fileAssetsList.add(files[j].getPath());
        if (files[j].isDirectory()) {

          isBinaryField = false;
          for (Field field : binaryFields) {
            if (field.getVelocityVarName().equals(files[j].getName())) {
              isBinaryField = true;
              break;
            }
          }

          if (!isBinaryField) findFileAssetsList(files[j], fileAssetsList);
        }
      }
    }
    return fileAssetsList;
  }
  /**
   * Check if a para is tupe file or image
   *
   * @param structure
   * @param paramName
   * @return boolean
   */
  public static boolean imageOrFileParam(Structure structure, String paramName) {

    Field field = structure.getFieldVar(paramName);
    if (UtilMethods.isSet(field)
        && (field.getFieldType().equals(Field.FieldType.FILE.toString())
            || field.getFieldType().equals(Field.FieldType.IMAGE.toString()))) {
      return true;
    }
    return false;
  }
Beispiel #3
0
  public List<Map<String, Object>> findLocations(String filter)
      throws DotDataException, DotSecurityException, PortalException, SystemException {

    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

    // Retrieving the current user
    User user = userAPI.getLoggedInUser(request);
    boolean respectFrontendRoles = true;

    // Searching for buildings
    Structure buildingStructure = eventAPI.getBuildingStructure();
    Field titleField = buildingStructure.getFieldVar("title");
    String luceneQuery = "+structureInode:" + buildingStructure.getInode();
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();
    List<Contentlet> matches =
        contAPI.search(
            luceneQuery, -1, 0, titleField.getFieldContentlet(), user, respectFrontendRoles);
    List<Map<String, Object>> facilitiesList =
        findChildFacilities(matches, filter, user, respectFrontendRoles);

    for (Contentlet cont : matches) {
      List<Map<String, Object>> facilitiesListCont = new ArrayList<Map<String, Object>>();
      Map<String, Object> contMap = cont.getMap();
      if (!UtilMethods.isSet(filter)
          || facilitiesList.size() > 0
          || ((String) contMap.get("title")).contains(filter)) {
        for (Map<String, Object> facility : facilitiesList) {
          for (Contentlet building : (ArrayList<Contentlet>) facility.get("buildings")) {
            if (building.getIdentifier().equals(cont.getIdentifier())
                && !facilitiesListCont.contains(facility)) {
              Map<String, Object> facilityMap = new HashMap<String, Object>();
              facilityMap.putAll(facility);
              facilityMap.put("buildings", null);
              facilitiesListCont.add(facilityMap);
              break;
            }
          }
        }
        contMap.put("facilities", facilitiesListCont);
        results.add(contMap);
      }
    }
    return results;
  }
  @SuppressWarnings("deprecation")
  private Structure _loadStructure(ActionForm form, ActionRequest req, ActionResponse res)
      throws ActionException, DotDataException {

    User user = _getUser(req);
    Structure structure = new Structure();
    String inodeString = req.getParameter("inode");
    if (InodeUtils.isSet(inodeString)) {
      /*
       * long inode = Long.parseLong(inodeString); if (inode != 0) {
       * structure = StructureFactory.getStructureByInode(inode); }
       */

      if (InodeUtils.isSet(inodeString)) {
        structure = StructureFactory.getStructureByInode(inodeString);
      }
    }
    req.setAttribute(WebKeys.Structure.STRUCTURE, structure);

    boolean searchable = false;

    List<Field> fields = structure.getFields();
    for (Field f : fields) {
      if (f.isIndexed()) {
        searchable = true;
        break;
      }
    }

    if (!searchable && InodeUtils.isSet(structure.getInode())) {
      String message = "warning.structure.notsearchable";
      SessionMessages.add(req, "message", message);
    }

    if (structure.isFixed()) {
      String message = "warning.object.isfixed";
      SessionMessages.add(req, "message", message);
    }

    // Checking permissions
    _checkUserPermissions(structure, user, PermissionAPI.PERMISSION_READ);

    return structure;
  }
Beispiel #5
0
  private List<Map<String, Object>> findChildFacilities(
      List<Contentlet> buildingConts, String filter, User user, boolean respectFrontendRoles)
      throws DotDataException, DotSecurityException {
    List<Map<String, Object>> results = new ArrayList<Map<String, Object>>();

    // Searching for children facilities
    Structure facilityStructure = eventAPI.getFacilityStructure();
    // Facility Structure might be absent http://jira.dotmarketing.net/browse/DOTCMS-6275
    if (facilityStructure.getName() != null) {
      Field titleField = facilityStructure.getFieldVar("title");
      String luceneQuery = "+structureInode:" + facilityStructure.getInode() + " +(";
      for (Contentlet cont : buildingConts) {
        luceneQuery += " Building-Facility:" + cont.getIdentifier() + " ";
      }
      luceneQuery += ") ";
      if (UtilMethods.isSet(filter))
        luceneQuery += " +" + titleField.getFieldContentlet() + ":" + filter.trim() + "*";

      List<Contentlet> matches =
          contAPI.search(
              luceneQuery, -1, 0, titleField.getFieldContentlet(), user, respectFrontendRoles);
      List<Relationship> rels =
          RelationshipFactory.getAllRelationshipsByStructure(eventAPI.getBuildingStructure());
      for (Contentlet cont : matches) {
        List<Contentlet> relCont = new ArrayList<Contentlet>();
        for (Relationship rel : rels) {
          if (rel.getChildStructure().equals(eventAPI.getFacilityStructure())
              && rel.getParentStructure().equals(eventAPI.getBuildingStructure())) {
            relCont.addAll(
                APILocator.getContentletAPI()
                    .getRelatedContent(cont, rel, user, respectFrontendRoles));
          }
        }
        Map<String, Object> contMap = cont.getMap();
        contMap.put("buildings", relCont);
        results.add(contMap);
      }
    }
    return results;
  }
  /**
   * Set the field value, to a content according the content structure
   *
   * @param structure The content structure
   * @param contentlet The content
   * @param fieldName The field name
   * @param value The field value
   * @throws DotDataException
   */
  private static void setField(
      Structure structure, Contentlet contentlet, String fieldName, String[] values)
      throws DotDataException {

    Field field = structure.getFieldVar(fieldName);
    String value = "";
    if (UtilMethods.isSet(field) && APILocator.getFieldAPI().valueSettable(field)) {
      try {
        if (field.getFieldType().equals(Field.FieldType.HOST_OR_FOLDER.toString())) {
          value = VelocityUtil.cleanVelocity(values[0]);
          Host host =
              APILocator.getHostAPI().find(value, APILocator.getUserAPI().getSystemUser(), false);
          if (host != null && InodeUtils.isSet(host.getIdentifier())) {
            contentlet.setHost(host.getIdentifier());
            contentlet.setFolder(FolderAPI.SYSTEM_FOLDER);
          } else {
            Folder folder =
                APILocator.getFolderAPI()
                    .find(value, APILocator.getUserAPI().getSystemUser(), false);
            if (folder != null && InodeUtils.isSet(folder.getInode())) {
              contentlet.setHost(folder.getHostId());
              contentlet.setFolder(folder.getInode());
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.MULTI_SELECT.toString())
            || field.getFieldType().equals(Field.FieldType.CHECKBOX.toString())) {
          if (field.getFieldContentlet().startsWith("float")
              || field.getFieldContentlet().startsWith("integer")) {
            value = values[0];
          } else {
            for (String temp : values) {
              value = temp + "," + value;
            }
          }
        } else if (field.getFieldType().equals(Field.FieldType.DATE.toString())) {
          value = VelocityUtil.cleanVelocity(values[0]);
          if (value instanceof String) {
            value = value + " 00:00:00";
          }
        } else {

          value = VelocityUtil.cleanVelocity(values[0]);
        }
        conAPI.setContentletProperty(contentlet, field, value);

      } catch (Exception e) {
        Logger.debug(SubmitContentUtil.class, e.getMessage());
      }
    }
  }
  @SuppressWarnings("unchecked")
  public static Contentlet createContent(
      Structure st,
      ArrayList<Category> cats,
      String userId,
      List<String> parametersName,
      List<String[]> values,
      String options,
      List<Map<String, Object>> fileParameters,
      boolean autoPublish,
      Host formHost,
      String moderatorRole)
      throws DotContentletStateException, DotDataException, DotSecurityException {

    Contentlet contentlet = null;

    /*try {*/
    /** Get the current user */
    User user = getUserFromId(userId);

    /** Content inherit structure permissions */
    List<Permission> permissionList = perAPI.getPermissions(st);

    /** Set the content values */
    contentlet = SubmitContentUtil.setAllFields(st.getName(), parametersName, values);

    /** Get the required relationships */
    Map<Relationship, List<Contentlet>> relationships =
        SubmitContentUtil.getRelationships(st, contentlet, options, user);

    /** Validating content fields */
    // conAPI.validateContentlet(contentlet,relationships,cats);

    /** Set the binary field values http://jira.dotmarketing.net/browse/DOTCMS-3463 */
    if (fileParameters.size() > 0) {
      for (Map<String, Object> value : fileParameters) {
        Field field = (Field) value.get("field");
        java.io.File file = (java.io.File) value.get(field.getVelocityVarName());
        if (file != null) {
          try {
            contentlet.setBinary(field.getVelocityVarName(), file);
          } catch (IOException e) {

          }
        }
      }
    }

    if (st.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
      contentlet.setHost(formHost.getIdentifier());
      Host host =
          APILocator.getHostAPI()
              .find(formHost.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      if (!perAPI.doesUserHavePermissions(
          host,
          "PARENT:"
              + PermissionAPI.PERMISSION_READ
              + ", CONTENTLETS:"
              + PermissionAPI.PERMISSION_WRITE
              + "",
          user)) {
        throw new DotSecurityException("User doesn't have write permissions to Contentlet");
      }
    }

    /** If the moderator field is set, a work flow task is created */
    if (UtilMethods.isSet(moderatorRole)) {

      if (!UtilMethods.isSet(contentlet.getStringProperty(Contentlet.WORKFLOW_ACTION_KEY)))
        contentlet.setStringProperty(
            Contentlet.WORKFLOW_ACTION_KEY,
            APILocator.getWorkflowAPI().findEntryAction(contentlet, user).getId());

      String contentletTitle = "";

      List<Field> fields = FieldsCache.getFieldsByStructureInode(contentlet.getStructureInode());

      for (Field fld : fields) {
        if (fld.isListed()) {
          contentletTitle = contentlet.getMap().get(fld.getVelocityVarName()).toString();
          contentletTitle =
              contentletTitle.length() > 250 ? contentletTitle.substring(0, 250) : contentletTitle;
        }
      }
      contentlet.setStringProperty(
          Contentlet.WORKFLOW_COMMENTS_KEY,
          "A new content titled \""
              + UtilHTML.escapeHTMLSpecialChars(contentletTitle.trim())
              + "\" has been posted by "
              + UtilHTML.escapeHTMLSpecialChars(user.getFullName())
              + " ("
              + user.getEmailAddress()
              + ")");

      contentlet.setStringProperty(
          Contentlet.WORKFLOW_ASSIGN_KEY, roleAPI.loadRoleByKey(moderatorRole).getId());
    }

    /** Saving Content */
    contentlet = conAPI.checkin(contentlet, relationships, cats, permissionList, user, true);

    APILocator.getVersionableAPI().setWorking(contentlet);
    if (autoPublish) APILocator.getVersionableAPI().setLive(contentlet);

    /** Saving file and images */
    if (fileParameters.size() > 0) {

      for (Map<String, Object> value : fileParameters) {
        Field field = (Field) value.get("field");
        // http://jira.dotmarketing.net/browse/DOTCMS-3463
        if (field.getFieldType().equals(Field.FieldType.IMAGE.toString())
            || field.getFieldType().equals(Field.FieldType.FILE.toString())) {
          java.io.File uploadedFile = (java.io.File) value.get("file");
          try {
            if (!UtilMethods.isSet(FileUtil.getBytes(uploadedFile))) continue;
          } catch (IOException e) {
            Logger.error(SubmitContentUtil.class, e.getMessage());
          }
          String title = (String) value.get("title");
          Host host = (Host) value.get("host");
          contentlet = addFileToContentlet(contentlet, field, host, uploadedFile, user, title);
        }
      }
      if (autoPublish) { // DOTCMS-5188
        contentlet =
            conAPI.checkinWithoutVersioning(
                contentlet, relationships, cats, permissionList, user, true);
        conAPI.publish(contentlet, APILocator.getUserAPI().getSystemUser(), false);
      } else {
        contentlet =
            conAPI.checkinWithoutVersioning(
                contentlet, relationships, cats, permissionList, user, true);
        conAPI.unpublish(contentlet, APILocator.getUserAPI().getSystemUser(), false);
      }
    }

    /*}catch(Exception e){

    	Logger.error(SubmitContentUtil.class, e.getMessage());
    	throw new DotContentletStateException("Unable to perform checkin. "+e.getMessage());

    }*/

    return contentlet;
  }
Beispiel #8
0
  @SuppressWarnings("unchecked")
  protected void doEditMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = request.getRequestURI();
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    StringBuilder preExecuteCode = new StringBuilder();
    Boolean widgetPreExecute = false;

    // Getting the user to check the permissions
    com.liferay.portal.model.User backendUser = null;
    try {
      backendUser = com.liferay.portal.util.PortalUtil.getUser(request);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying getUser: "******"idInode", String.valueOf(id.getInode()));
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode());

    Template template = null;
    Template hostVariablesTemplate = null;

    // creates the context where to place the variables
    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

    HTMLPage htmlPage =
        (HTMLPage)
            APILocator.getVersionableAPI()
                .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    // to check user has permission to write on this page
    boolean hasAddChildrenPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_CAN_ADD_CHILDREN, backendUser);
    boolean hasWritePermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, backendUser);
    boolean hasPublishPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, backendUser);
    context.put("ADD_CHILDREN_HTMLPAGE_PERMISSION", new Boolean(hasAddChildrenPermOverHTMLPage));
    context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage));
    context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage));
    context.put("canAddForm", new Boolean(LicenseUtil.getLevel() > 199 ? true : false));
    context.put("canViewDiff", new Boolean(LicenseUtil.getLevel() > 199 ? true : false));

    boolean canUserWriteOnTemplate =
        permissionAPI.doesUserHavePermission(
                htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, backendUser)
            && portletAPI.hasTemplateManagerRights(backendUser);
    context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate);

    com.dotmarketing.portlets.templates.model.Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, true);
    if (cmsTemplate == null) { // DOTCMS-4051
      cmsTemplate = new com.dotmarketing.portlets.templates.model.Template();
      Logger.debug(VelocityServlet.class, "HTMLPAGE TEMPLATE NOT FOUND");
    }

    Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate);

    Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode());

    VelocityUtil.makeBackendContext(
        context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, true, false, host);
    // added to show tabs
    context.put("previewPage", "1");
    // get the containers for the page and stick them in context
    List<Container> containers =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);
    for (Container c : containers) {

      context.put(
          String.valueOf("container" + c.getIdentifier()),
          "/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      boolean hasWritePermissionOnContainer =
          permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, backendUser, false)
              && portletAPI.hasContainerManagerRights(backendUser);
      boolean hasReadPermissionOnContainer =
          permissionAPI.doesUserHavePermission(c, PERMISSION_READ, backendUser, false);
      context.put("EDIT_CONTAINER_PERMISSION" + c.getIdentifier(), hasWritePermissionOnContainer);
      if (Config.getBooleanProperty("SIMPLE_PAGE_CONTENT_PERMISSIONING", true))
        context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), true);
      else
        context.put("USE_CONTAINER_PERMISSION" + c.getIdentifier(), hasReadPermissionOnContainer);

      // to check user has permission to write this container
      Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class);
      boolean hasWritePermOverTheStructure =
          permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, backendUser);
      context.put(
          "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure));

      Logger.debug(
          VelocityServlet.class,
          String.valueOf("container" + c.getIdentifier())
              + "=/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      List<Contentlet> contentlets = null;

      boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery());

      // get contentlets only for main frame
      if (request.getParameter("mainFrame") != null) {
        if (staticContainer) {
          Logger.debug(VelocityServlet.class, "Static Container!!!!");

          Logger.debug(
              VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode());

          // The container doesn't have categories
          Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
          Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getInode(),
                  idenContainer.getInode(),
                  sort,
                  true,
                  -1,
                  backendUser,
                  true);
          Logger.debug(
              VelocityServlet.class,
              "Getting contentlets for language="
                  + (String)
                      request
                          .getSession()
                          .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)
                  + " contentlets ="
                  + contentlets.size());

        } else {
          String luceneQuery = c.getLuceneQuery();
          int limit = c.getMaxContentlets();
          String sortBy = c.getSortContentletsBy();
          int offset = 0;
          contentlets = conAPI.search(luceneQuery, limit, offset, sortBy, backendUser, true);
        }

        if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) {
          Set<String> contentletIdentList = new HashSet<String>();
          List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
          for (Contentlet cont : contentlets) {
            if (!contentletIdentList.contains(cont.getIdentifier())) {
              contentletIdentList.add(cont.getIdentifier());
              contentletsFilter.add(cont);
            }
          }
          contentlets = contentletsFilter;
        }
        List<String> contentletList = new ArrayList<String>();

        if (contentlets != null) {
          Iterator<Contentlet> iter = contentlets.iterator();
          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet =
                permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, backendUser);

            context.put(
                "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(),
                new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
              }
            }
          }
        }
        // sets contentletlist with all the files to load per
        // container
        context.put("contentletList" + c.getIdentifier(), contentletList);
        context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size()));
        // ### Add the structure fake contentlet ###
        if (contentletList.size() == 0) {
          Structure structure = ContainerFactory.getContainerStructure(c);
          contentletList.add(structure.getInode() + "");
          // sets contentletlist with all the files to load per
          // container
          context.remove("contentletList" + c.getIdentifier());
          context.remove("totalSize" + c.getIdentifier());
          // http://jira.dotmarketing.net/browse/DOTCMS-2876
          context.put("contentletList" + c.getIdentifier(), new long[0]);
          context.put("totalSize" + c.getIdentifier(), 0);
        }
        // ### END Add the structure fake contentlet ###

      }
    }

    Logger.debug(
        VelocityServlet.class,
        "Before finding template: /working/"
            + templateIdentifier.getInode()
            + "."
            + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));

    Logger.debug(
        VelocityServlet.class,
        "Velocity directory:"
            + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH));

    if (request.getParameter("leftMenu") != null) {
      /*
       * try to get the messages from the session
       */

      List<String> list = new ArrayList<String>();
      if (SessionMessages.contains(request, "message")) {
        list.add((String) SessionMessages.get(request, "message"));
        SessionMessages.clear(request);
      }
      if (SessionMessages.contains(request, "custommessage")) {
        list.add((String) SessionMessages.get(request, "custommessage"));
        SessionMessages.clear(request);
      }

      if (list.size() > 0) {
        ArrayList<String> mymessages = new ArrayList<String>();
        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
          try {
            String message = (String) it.next();
            Company comp = PublicCompanyFactory.getDefaultCompany();
            mymessages.add(LanguageUtil.get(comp.getCompanyId(), backendUser.getLocale(), message));
          } catch (Exception e) {
          }
        }
        context.put("vmessages", mymessages);
      }

      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      hostVariablesTemplate =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + host.getIdentifier()
                      + "."
                      + Config.getStringProperty("VELOCITY_HOST_EXTENSION"));
      template =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + templateIdentifier.getInode()
                      + "."
                      + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));
    } else {
      // Return a resource not found right away if the page is not found,
      // not try to load the frames
      if (!InodeUtils.isSet(templateIdentifier.getInode())) throw new ResourceNotFoundException("");
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    PrintWriter out = response.getWriter();
    request.setAttribute("velocityContext", context);
    try {
      if (widgetPreExecute) {
        VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString());
      }
      if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out);
      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }
Beispiel #9
0
  @SuppressWarnings("unchecked")
  public void doPreviewMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {

    String uri = URLDecoder.decode(request.getRequestURI(), UtilMethods.getCharsetConfiguration());
    uri = UtilMethods.cleanURI(uri);

    Host host = hostWebAPI.getCurrentHost(request);

    StringBuilder preExecuteCode = new StringBuilder();
    Boolean widgetPreExecute = false;

    // Getting the user to check the permissions
    com.liferay.portal.model.User user = null;
    HttpSession session = request.getSession(false);
    try {
      if (session != null)
        user =
            (com.liferay.portal.model.User)
                session.getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);
    } catch (Exception nsue) {
      Logger.warn(this, "Exception trying getUser: "******"idInode", id.getInode());
    Logger.debug(VelocityServlet.class, "VELOCITY HTML INODE=" + id.getInode());

    Template template = null;
    Template hostVariablesTemplate = null;

    // creates the context where to place the variables
    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

    HTMLPage htmlPage =
        (HTMLPage) APILocator.getVersionableAPI().findWorkingVersion(id, user, true);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    // to check user has permission to write on this page
    boolean hasWritePermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_WRITE, user);
    boolean hasPublishPermOverHTMLPage =
        permissionAPI.doesUserHavePermission(htmlPage, PERMISSION_PUBLISH, user);
    context.put("EDIT_HTMLPAGE_PERMISSION", new Boolean(hasWritePermOverHTMLPage));
    context.put("PUBLISH_HTMLPAGE_PERMISSION", new Boolean(hasPublishPermOverHTMLPage));

    boolean canUserWriteOnTemplate =
        permissionAPI.doesUserHavePermission(
            htmlPageAPI.getTemplateForWorkingHTMLPage(htmlPage), PERMISSION_WRITE, user, true);
    context.put("EDIT_TEMPLATE_PERMISSION", canUserWriteOnTemplate);

    com.dotmarketing.portlets.templates.model.Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, true);
    Identifier templateIdentifier = APILocator.getIdentifierAPI().find(cmsTemplate);

    Logger.debug(VelocityServlet.class, "VELOCITY TEMPLATE INODE=" + cmsTemplate.getInode());

    VelocityUtil.makeBackendContext(
        context, htmlPage, cmsTemplate.getInode(), id.getURI(), request, true, false, true, host);
    context.put("previewPage", "2");
    context.put("livePage", "0");
    // get the containers for the page and stick them in context
    List<Container> containers =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);
    for (Container c : containers) {

      context.put(
          String.valueOf("container" + c.getIdentifier()),
          "/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      context.put(
          "EDIT_CONTAINER_PERMISSION" + c.getIdentifier(),
          permissionAPI.doesUserHavePermission(c, PERMISSION_WRITE, user, true));

      // to check user has permission to write this container
      Structure st = (Structure) InodeFactory.getInode(c.getStructureInode(), Structure.class);

      boolean hasWritePermOverTheStructure =
          permissionAPI.doesUserHavePermission(st, PERMISSION_WRITE, user, true);
      context.put(
          "ADD_CONTENT_PERMISSION" + c.getIdentifier(), new Boolean(hasWritePermOverTheStructure));

      Logger.debug(
          VelocityServlet.class,
          String.valueOf("container" + c.getIdentifier())
              + "=/working/"
              + c.getIdentifier()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"));

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      boolean staticContainer = !UtilMethods.isSet(c.getLuceneQuery());

      List<Contentlet> contentlets = null;

      // get contentlets only for main frame
      if (request.getParameter("mainFrame") != null) {
        if (staticContainer) {
          Logger.debug(VelocityServlet.class, "Static Container!!!!");

          Logger.debug(
              VelocityServlet.class, "html=" + htmlPage.getInode() + " container=" + c.getInode());

          // The container doesn't have categories
          Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
          Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getInode(), idenContainer.getInode(), sort, true, -1, user, true);
          Logger.debug(
              VelocityServlet.class,
              "Getting contentlets for language="
                  + (String)
                      request
                          .getSession()
                          .getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE)
                  + " contentlets ="
                  + contentlets.size());
        }

        if (UtilMethods.isSet(contentlets) && contentlets.size() > 0) {
          Set<String> contentletIdentList = new HashSet<String>();
          List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
          for (Contentlet cont : contentlets) {
            if (!contentletIdentList.contains(cont.getIdentifier())) {
              contentletIdentList.add(cont.getIdentifier());
              contentletsFilter.add(cont);
            }
          }
          contentlets = contentletsFilter;
        }
        List<String> contentletList = new ArrayList<String>();

        if (contentlets != null && contentlets.size() > 0) {
          Iterator<Contentlet> iter = contentlets.iterator();
          int count = 0;

          while (iter.hasNext() && (count < c.getMaxContentlets())) {
            count++;

            Contentlet contentlet = (Contentlet) iter.next();
            Identifier contentletIdentifier = APILocator.getIdentifierAPI().find(contentlet);

            boolean hasWritePermOverContentlet =
                permissionAPI.doesUserHavePermission(contentlet, PERMISSION_WRITE, user, true);

            context.put(
                "EDIT_CONTENT_PERMISSION" + contentletIdentifier.getInode(),
                new Boolean(hasWritePermOverContentlet));

            contentletList.add(String.valueOf(contentletIdentifier.getInode()));
            Logger.debug(this, "Adding contentlet=" + contentletIdentifier.getInode());
            Structure contStructure = contentlet.getStructure();
            if (contStructure.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
              Field field = contStructure.getFieldVar("widgetPreexecute");
              if (field != null && UtilMethods.isSet(field.getValues())) {
                preExecuteCode.append(field.getValues().trim() + "\n");
                widgetPreExecute = true;
              }
            }
          }
        }

        // sets contentletlist with all the files to load per
        // container
        context.put("contentletList" + c.getIdentifier(), contentletList);
        context.put("totalSize" + c.getIdentifier(), new Integer(contentletList.size()));
      }
    }

    Logger.debug(
        VelocityServlet.class,
        "Before finding template: /working/"
            + templateIdentifier.getInode()
            + "."
            + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));

    Logger.debug(
        VelocityServlet.class,
        "Velocity directory:"
            + VelocityUtil.getEngine().getProperty(RuntimeConstants.FILE_RESOURCE_LOADER_PATH));

    if (request.getParameter("leftMenu") != null) {
      /*
       * try to get the messages from the session
       */

      List<String> list = new ArrayList<String>();
      if (SessionMessages.contains(request, "message")) {
        list.add((String) SessionMessages.get(request, "message"));
        SessionMessages.clear(request);
      }
      if (SessionMessages.contains(request, "custommessage")) {
        list.add((String) SessionMessages.get(request, "custommessage"));
        SessionMessages.clear(request);
      }

      if (list.size() > 0) {
        ArrayList<String> mymessages = new ArrayList<String>();
        Iterator<String> it = list.iterator();

        while (it.hasNext()) {
          try {
            String message = (String) it.next();
            Company comp = PublicCompanyFactory.getDefaultCompany();
            mymessages.add(LanguageUtil.get(comp.getCompanyId(), user.getLocale(), message));
          } catch (Exception e) {
          }
        }
        context.put("vmessages", mymessages);
      }

      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      hostVariablesTemplate =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + host.getIdentifier()
                      + "."
                      + Config.getStringProperty("VELOCITY_HOST_EXTENSION"));
      template =
          VelocityUtil.getEngine()
              .getTemplate(
                  "/working/"
                      + templateIdentifier.getInode()
                      + "."
                      + Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"));
    } else {
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    PrintWriter out = response.getWriter();
    request.setAttribute("velocityContext", context);
    try {

      if (widgetPreExecute) {
        VelocityUtil.getEngine().evaluate(context, out, "", preExecuteCode.toString());
      }
      if (hostVariablesTemplate != null) hostVariablesTemplate.merge(context, out);
      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }
  private void _deleteStructure(ActionForm form, ActionRequest req, ActionResponse res)
      throws Exception {

    try {
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);

      User user = _getUser(req);
      HttpServletRequest httpReq = ((ActionRequestImpl) req).getHttpServletRequest();

      // Checking permissions
      _checkDeletePermissions(structure, user, httpReq);

      // checking if there is containers using this structure
      List<Container> containers =
          APILocator.getContainerAPI().findContainersForStructure(structure.getInode());
      if (containers.size() > 0) {
        StringBuilder names = new StringBuilder();
        for (int i = 0; i < containers.size(); i++)
          names.append(containers.get(i).getFriendlyName()).append(", ");
        Logger.warn(
            EditStructureAction.class,
            "Structure "
                + structure.getName()
                + " can't be deleted because the following containers are using it: "
                + names);
        SessionMessages.add(req, "message", "message.structure.notdeletestructure.container");
        return;
      }

      if (!structure.isDefaultStructure()) {

        @SuppressWarnings("rawtypes")
        List fields = FieldFactory.getFieldsByStructure(structure.getInode());

        @SuppressWarnings("rawtypes")
        Iterator fieldsIter = fields.iterator();

        while (fieldsIter.hasNext()) {
          Field field = (Field) fieldsIter.next();
          FieldFactory.deleteField(field);
        }

        int limit = 200;
        int offset = 0;
        List<Contentlet> contentlets =
            conAPI.findByStructure(structure, user, false, limit, offset);
        int size = contentlets.size();
        while (size > 0) {
          conAPI.delete(contentlets, user, false);
          contentlets = conAPI.findByStructure(structure, user, false, limit, offset);
          size = contentlets.size();
        }

        if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {

          @SuppressWarnings({"deprecation", "static-access"})
          Structure st =
              StructureCache.getStructureByName(fAPI.FORM_WIDGET_STRUCTURE_NAME_FIELD_NAME);

          if (UtilMethods.isSet(st) && UtilMethods.isSet(st.getInode())) {

            @SuppressWarnings({"deprecation", "static-access"})
            Field field = st.getField(fAPI.FORM_WIDGET_FORM_ID_FIELD_NAME);

            List<Contentlet> widgetresults =
                conAPI.search(
                    "+structureInode:"
                        + st.getInode()
                        + " +"
                        + field.getFieldContentlet()
                        + ":"
                        + structure.getInode(),
                    0,
                    0,
                    "",
                    user,
                    false);
            if (widgetresults.size() > 0) {
              conAPI.delete(widgetresults, user, false);
            }
          }
        }

        // http://jira.dotmarketing.net/browse/DOTCMS-6435
        if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) {
          StructureFactory.updateFolderFileAssetReferences(structure);
        }

        List<Relationship> relationships = RelationshipFactory.getRelationshipsByParent(structure);
        for (Relationship rel : relationships) {
          RelationshipFactory.deleteRelationship(rel);
        }
        relationships = RelationshipFactory.getRelationshipsByChild(structure);
        for (Relationship rel : relationships) {
          RelationshipFactory.deleteRelationship(rel);
        }

        PermissionAPI perAPI = APILocator.getPermissionAPI();
        perAPI.removePermissions(structure);

        StructureFactory.deleteStructure(structure);

        // Removing the structure from cache
        FieldsCache.removeFields(structure);
        StructureCache.removeStructure(structure);
        StructureServices.removeStructureFile(structure);

        SessionMessages.add(req, "message", "message.structure.deletestructure");
      } else {
        SessionMessages.add(req, "message", "message.structure.notdeletestructure");
      }
    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
      throw ex;
    }
  }
Beispiel #11
0
  public Map<String, Object> saveEvent(List<String> formData, boolean isAutoSave, boolean isCheckin)
      throws LanguageException, PortalException, SystemException, DotDataException,
          DotSecurityException, java.text.ParseException {

    HibernateUtil.startTransaction();
    ContentletWebAPI contentletWebAPI = WebAPILocator.getContentletWebAPI();
    int tempCount =
        0; // To store multiple values opposite to a name. Ex: selected permissions & categories
    String newInode = "";

    String referer = "";
    String language = "";
    String strutsAction = "";
    String recurrenceDaysOfWeek = "";

    Map<String, Object> contentletFormData = new HashMap<String, Object>();
    Map<String, Object> callbackData = new HashMap<String, Object>();
    List<String> saveContentErrors = new ArrayList<String>();

    HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
    User user = com.liferay.portal.util.PortalUtil.getUser((HttpServletRequest) req);
    List<Field> fields =
        com.dotmarketing.cache.FieldsCache.getFieldsByStructureInode(
            eventAPI.getEventStructure().getInode());
    String titleField = "";
    String urlTitleField = "";
    String urlTitleFieldValue = "";
    String titleFieldValue = "";

    for (Field field : fields) {
      if (field.getVelocityVarName().equals("urlTitle")) {
        urlTitleField = field.getFieldContentlet();
      }
      if (field.getVelocityVarName().equals("title")) {
        titleField = field.getFieldContentlet();
      }
      if (UtilMethods.isSet(titleField) && UtilMethods.isSet(urlTitleField)) {
        break;
      }
    }

    // get the struts_action from the form data
    for (Iterator<String> iterator = formData.iterator(); iterator.hasNext(); ) {
      String element = iterator.next();
      if (element != null) {
        String elementName =
            element.substring(0, element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR));

        if (elementName.startsWith("_EXT") && elementName.endsWith("cmd")) {
          strutsAction = elementName.substring(0, elementName.indexOf("cmd"));
          break;
        }
      }
    }

    // Storing form data into map.
    for (Iterator<String> iterator = formData.iterator(); iterator.hasNext(); ) {
      String element = iterator.next();

      if (!com.dotmarketing.util.UtilMethods.isSet(element)) continue;

      String elementName =
          element.substring(0, element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR));
      Object elementValue =
          element.substring(
              element.indexOf(WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR)
                  + WebKeys.CONTENTLET_FORM_NAME_VALUE_SEPARATOR.length());

      if (element.startsWith(strutsAction))
        elementName =
            elementName.substring(elementName.indexOf(strutsAction) + strutsAction.length());

      // Placed increments as Map holds unique keys.
      if (elementName.equals("read")
          || elementName.equals("write")
          || elementName.equals("publish")) {

        tempCount++;
        elementName = "selected_permission_" + tempCount + elementName;
      }

      if (elementName.equals(titleField)) {
        titleFieldValue = (String) elementValue;
      }

      if (elementName.equals(urlTitleField)) {
        urlTitleFieldValue = (String) elementValue;
      }

      if (elementName.equals("categories")) {
        tempCount++;
        elementName = elementName + tempCount + "_";
      }
      // http://jira.dotmarketing.net/browse/DOTCMS-3232
      if (elementName.equalsIgnoreCase("hostId")) {
        callbackData.put("hostOrFolder", true);
      }
      if (elementName.startsWith("binary")) {
        String binaryFileValue = (String) elementValue;
        if (UtilMethods.isSet(binaryFileValue) && !binaryFileValue.equals("---removed---")) {
          binaryFileValue = ContentletUtil.sanitizeFileName(binaryFileValue);

          File binaryFile =
              new File(
                  APILocator.getFileAPI().getRealAssetPathTmpBinary()
                      + File.separator
                      + user.getUserId()
                      + File.separator
                      + elementName
                      + File.separator
                      + binaryFileValue);
          if (binaryFile.exists()) binaryFile.delete();
          elementValue = binaryFile;
        } else {
          elementValue = null;
        }
      }

      if (!UtilMethods.isSet(elementName)) continue;

      if (elementValue == null) elementValue = "";

      if (elementName.equals("referer")) referer = (String) elementValue;

      if (elementName.equals("languageId")) language = (String) elementValue;

      if (elementName.equals("recurrenceDaysOfWeek")) {
        recurrenceDaysOfWeek = recurrenceDaysOfWeek + elementValue + ",";
      }
      contentletFormData.put(elementName, elementValue);
    }

    contentletFormData.put("recurrenceDaysOfWeek", recurrenceDaysOfWeek);

    if (!UtilMethods.isSet(urlTitleFieldValue) && UtilMethods.isSet(titleFieldValue)) {

      urlTitleFieldValue = titleFieldValue.toLowerCase();
      urlTitleFieldValue = urlTitleFieldValue.replace("/^\\s+|\\s+$/g", "");
      urlTitleFieldValue = urlTitleFieldValue.replace("/[^a-zA-Z 0-9]+/g", " ");
      urlTitleFieldValue = urlTitleFieldValue.replace("/\\s/g", "-");
      while (urlTitleFieldValue.indexOf("--") > -1) {
        urlTitleFieldValue = urlTitleFieldValue.replace("--", "-");
      }
      contentletFormData.put(urlTitleField, urlTitleFieldValue);
    }

    String d1 = (String) contentletFormData.get("date1");
    String d2 = (String) contentletFormData.get("date2");
    String d3 = (String) contentletFormData.get("recurrenceEnds");
    DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm");
    DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd");
    Date eventStartDate = null;
    Date eventEndDate = null;
    Date recurrenceEndDate = null;
    try {
      eventStartDate = df.parse(d1);
      eventEndDate = df.parse(d2);
      if (UtilMethods.isSet(d3)) {
        recurrenceEndDate = df2.parse(d3);
      }
    } catch (java.text.ParseException e1) {

    }
    Boolean cont = true;

    if (eventEndDate.before(eventStartDate)) {
      String errorString = LanguageUtil.get(user, "message.event.endate.before.stardate");
      saveContentErrors.add(errorString);
    }

    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (contentletFormData.get("noEndDate") == null
          || !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString())) {
        if (recurrenceEndDate != null && recurrenceEndDate.before(eventStartDate)) {
          String errorString =
              LanguageUtil.get(user, "message.event.recurrence.endate.before.stardate");
          saveContentErrors.add(errorString);
        }
      }
    }

    Calendar start = Calendar.getInstance();
    start.setTime(eventStartDate);
    Calendar end = Calendar.getInstance();
    end.setTime(eventEndDate);

    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (end.after(start)
          && (end.get(Calendar.DAY_OF_MONTH) > start.get(Calendar.DAY_OF_MONTH)
              || end.get(Calendar.MONTH) > start.get(Calendar.MONTH)
              || end.get(Calendar.YEAR) > start.get(Calendar.YEAR))) {
        contentletFormData.put("recurrenceOccurs", "never");
      }
    }

    if (Boolean.parseBoolean(contentletFormData.get("recurrenceChanged").toString())) {
      if (!UtilMethods.isSet(contentletFormData.get("recurrenceInterval"))) {
        String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.interval");
        saveContentErrors.add(errorString);
      } else {
        try {
          Long.valueOf((String) contentletFormData.get("recurrenceInterval"));
        } catch (NumberFormatException nfe) {
          String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.interval");
          saveContentErrors.add(errorString);
        }
      }

      if (contentletFormData.get("recurrenceOccurs").toString().equals("monthly")) {
        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && !UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))) {
          String errorString =
              LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth");
          saveContentErrors.add(errorString);
        }

        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))) {
          try {
            Long.valueOf((String) contentletFormData.get("recurrenceDayOfMonth"));
          } catch (Exception e) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth");
            saveContentErrors.add(errorString);
          }
        } else {
          contentletFormData.put("recurrenceDayOfMonth", "0");
        }
      }

      if (contentletFormData.get("recurrenceOccurs").toString().equals("annually")) {

        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && !UtilMethods.isSet((String) contentletFormData.get("specificDayOfMonthRecY"))
            && !UtilMethods.isSet((String) contentletFormData.get("specificMonthOfYearRecY"))) {
          String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.date");
          saveContentErrors.add(errorString);
        }

        if (Boolean.parseBoolean(contentletFormData.get("isSpecificDate").toString())
            && UtilMethods.isSet((String) contentletFormData.get("specificDayOfMonthRecY"))
            && UtilMethods.isSet((String) contentletFormData.get("specificMonthOfYearRecY"))) {
          try {
            Long.valueOf((String) contentletFormData.get("specificDayOfMonthRecY"));
            contentletFormData.put(
                "recurrenceDayOfMonth", (String) contentletFormData.get("specificDayOfMonthRecY"));
          } catch (Exception e) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.invalid.dayofmonth");
            saveContentErrors.add(errorString);
          }
          try {
            Long.valueOf((String) contentletFormData.get("specificMonthOfYearRecY"));
            contentletFormData.put(
                "recurrenceMonthOfYear",
                (String) contentletFormData.get("specificMonthOfYearRecY"));
          } catch (Exception e) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.invalid.monthofyear");
            saveContentErrors.add(errorString);
          }
        } else {
          contentletFormData.put("recurrenceDayOfMonth", "0");
        }
      }
    }

    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (contentletFormData.get("noEndDate") == null
          || (contentletFormData.get("noEndDate") != null
              && !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString()))) {
        if (!UtilMethods.isSet((String) contentletFormData.get("recurrenceEnds"))) {
          String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.enddate");
          saveContentErrors.add(errorString);
        } else {
          try {
            eventRecurrenceEndDateF.parse((String) contentletFormData.get("recurrenceEnds"));
          } catch (Exception e) {
            String errorString = LanguageUtil.get(user, "message.event.recurrence.invalid.enddate");
            saveContentErrors.add(errorString);
          }
        }
      }
    }

    // http://jira.dotmarketing.net/browse/DOTCMS-6327
    if (!contentletFormData.get("recurrenceOccurs").toString().equals("never")) {
      if (contentletFormData.get("noEndDate") == null
          || !Boolean.parseBoolean(contentletFormData.get("noEndDate").toString())) {
        Integer interval =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceInterval"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceInterval"))
                : null;
        Integer recurrenceWeekOfMonth =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceWeekOfMonth"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceWeekOfMonth"))
                : null;
        Integer recurrenceDayOfWeek =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfWeek"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceDayOfWeek"))
                : null;
        Integer recurrenceMonthOfYear =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceMonthOfYear"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceMonthOfYear"))
                : null;
        Integer recurrenceDayOfMonth =
            UtilMethods.isSet((String) contentletFormData.get("recurrenceDayOfMonth"))
                ? Integer.valueOf((String) contentletFormData.get("recurrenceDayOfMonth"))
                : null;
        Occurrency occurency =
            Occurrency.findOcurrency((String) contentletFormData.get("recurrenceOccurs"));

        if (occurency != null) {
          Calendar firstOccurence =
              RecurrenceUtil.calculateFirstOccurence(
                  eventStartDate,
                  interval,
                  occurency,
                  recurrenceDaysOfWeek,
                  recurrenceWeekOfMonth,
                  recurrenceDayOfWeek,
                  recurrenceMonthOfYear,
                  recurrenceDayOfMonth);
          if (recurrenceEndDate.before(firstOccurence.getTime())) {
            String errorString =
                LanguageUtil.get(user, "message.event.recurrence.before.occurence");
            saveContentErrors.add(errorString);
          }
        }
      }
    }

    try {
      if (cont && (saveContentErrors == null || saveContentErrors.isEmpty())) {
        newInode = contentletWebAPI.saveContent(contentletFormData, isAutoSave, isCheckin, user);
      }
    } catch (DotContentletValidationException ve) {

      if (ve.hasRequiredErrors()) {
        List<Field> reqs =
            ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_REQUIRED);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.required");
          errorString = errorString.replace("{0}", field.getFieldName());
          saveContentErrors.add(errorString);
        }
      }

      if (ve.hasLengthErrors()) {
        List<Field> reqs =
            ve.getNotValidFields()
                .get(DotContentletValidationException.VALIDATION_FAILED_MAXLENGTH);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.maxlength");
          errorString = errorString.replace("{0}", field.getFieldName());
          errorString = errorString.replace("{1}", "225");
          saveContentErrors.add(errorString);
        }
      }

      if (ve.hasPatternErrors()) {
        List<Field> reqs =
            ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_PATTERN);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.format");
          errorString = errorString.replace("{0}", field.getFieldName());
          saveContentErrors.add(errorString);
        }
      }

      if (ve.hasRelationshipErrors()) {
        StringBuffer sb = new StringBuffer("<br>");
        Map<String, Map<Relationship, List<Contentlet>>> notValidRelationships =
            ve.getNotValidRelationship();
        Set<String> auxKeys = notValidRelationships.keySet();
        for (String key : auxKeys) {
          String errorMessage = "";
          if (key.equals(DotContentletValidationException.VALIDATION_FAILED_REQUIRED_REL)) {
            errorMessage = "<b>Required Relationship</b>";
          } else if (key.equals(
              DotContentletValidationException.VALIDATION_FAILED_INVALID_REL_CONTENT)) {
            errorMessage = "<b>Invalid Relationship-Contentlet</b>";
          } else if (key.equals(DotContentletValidationException.VALIDATION_FAILED_BAD_REL)) {
            errorMessage = "<b>Bad Relationship</b>";
          }

          sb.append(errorMessage + ":<br>");
          Map<Relationship, List<Contentlet>> relationshipContentlets =
              notValidRelationships.get(key);

          for (Entry<Relationship, List<Contentlet>> relationship :
              relationshipContentlets.entrySet()) {
            sb.append(relationship.getKey().getRelationTypeValue() + ", ");
          }
          sb.append("<br>");
        }
        sb.append("<br>");

        // need to update message to support multiple relationship validation errors
        String errorString = LanguageUtil.get(user, "message.relationship.required_ext");
        errorString = errorString.replace("{0}", sb.toString());
        saveContentErrors.add(errorString);
      }

      if (ve.hasUniqueErrors()) {
        List<Field> reqs =
            ve.getNotValidFields().get(DotContentletValidationException.VALIDATION_FAILED_UNIQUE);
        for (Field field : reqs) {
          String errorString = LanguageUtil.get(user, "message.contentlet.unique");
          errorString = errorString.replace("{0}", field.getFieldName());
          saveContentErrors.add(errorString);
        }
      }

      if (ve.getMessage()
          .contains(
              "The content form submission data id different from the content which is trying to be edited")) {
        String errorString = LanguageUtil.get(user, "message.contentlet.invalid.form");
        saveContentErrors.add(errorString);
      }

    } catch (DotSecurityException dse) {
      String errorString = LanguageUtil.get(user, "message.insufficient.permissions.to.save");
      saveContentErrors.add(errorString);

    } catch (Exception e) {
      if (e.getMessage().equals(Constants.COMMON_ERROR)) {
        String errorString = LanguageUtil.get(user, "message.contentlet.save.error");
        saveContentErrors.add(errorString);
        SessionMessages.clear(req.getSession());
      } else {
        saveContentErrors.add(e.getLocalizedMessage());
      }

    } finally {
      if (!isAutoSave && (saveContentErrors != null && saveContentErrors.size() > 0)) {
        callbackData.put("saveContentErrors", saveContentErrors);
        SessionMessages.clear(req.getSession());
      }
    }

    if (InodeUtils.isSet(newInode)) callbackData.put("contentletInode", newInode);

    if (!isAutoSave && (saveContentErrors == null || saveContentErrors.size() == 0)) {

      Logger.debug(this, "AFTER PUBLISH LANGUAGE=" + language);

      if (UtilMethods.isSet(language) && referer.indexOf("language") > -1) {
        Logger.debug(this, "Replacing referer language=" + referer);
        referer =
            referer.replaceAll(
                "language=([0-9])*",
                com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE + "=" + language);
        Logger.debug(this, "Referer after being replaced=" + referer);
      }
    }

    boolean savingRecurrence = false;
    callbackData.put("referer", referer);
    HibernateUtil.commitTransaction();
    if (UtilMethods.isSet(newInode) && !savingRecurrence) {
      if (!contAPI.isInodeIndexed(newInode)) {
        Logger.error(this, "Timed out while waiting for index to return");
      }
    }
    return callbackData;
  }
Beispiel #12
0
  @SuppressWarnings("unchecked")
  public static InputStream buildStream(HTMLPage htmlPage, Identifier identifier, boolean EDIT_MODE)
      throws DotDataException, DotSecurityException {
    String folderPath = (!EDIT_MODE) ? "live/" : "working/";
    InputStream result;
    StringBuilder sb = new StringBuilder();

    ContentletAPI conAPI = APILocator.getContentletAPI();
    Template cmsTemplate =
        com.dotmarketing.portlets.htmlpages.factories.HTMLPageFactory.getHTMLPageTemplate(
            htmlPage, EDIT_MODE);
    if (cmsTemplate == null || !InodeUtils.isSet(cmsTemplate.getInode())) {
      Logger.error(
          This.class,
          "PAGE DOES NOT HAVE A VALID TEMPLATE (template unpublished?) : page id "
              + htmlPage.getIdentifier()
              + ":"
              + identifier.getURI());
    }

    // gets pageChannel for this path
    java.util.StringTokenizer st =
        new java.util.StringTokenizer(String.valueOf(identifier.getURI()), "/");
    String pageChannel = null;
    if (st.hasMoreTokens()) {
      pageChannel = st.nextToken();
    }

    // set the page cache var
    if (htmlPage.getCacheTTL() > 0 && LicenseUtil.getLevel() > 99) {
      sb.append("#set($dotPageCacheDate = \"").append(new java.util.Date()).append("\")");
      sb.append("#set($dotPageCacheTTL = \"").append(htmlPage.getCacheTTL()).append("\")");
    }

    // set the host variables
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();

    Host host = htmlPageAPI.getParentHost(htmlPage);
    sb.append("#if(!$doNotParseTemplate)");
    sb.append("$velutil.mergeTemplate('")
        .append(folderPath)
        .append(host.getIdentifier())
        .append(".")
        .append(Config.getStringProperty("VELOCITY_HOST_EXTENSION"))
        .append("')");
    sb.append(" #end ");

    // creates the context where to place the variables
    // Build a context to pass to the page
    sb.append("#if(!$doNotSetPageInfo)");
    sb.append("#set ( $quote = '\"' )");
    sb.append("#set ($HTMLPAGE_INODE = \"")
        .append(String.valueOf(htmlPage.getInode()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_IDENTIFIER = \"")
        .append(String.valueOf(htmlPage.getIdentifier()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_TITLE = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getTitle()))
        .append("\" )");
    sb.append(
            "#set ($HTMLPAGE_FRIENDLY_NAME = \""
                + UtilMethods.espaceForVelocity(htmlPage.getFriendlyName()))
        .append("\" )");
    sb.append("#set ($TEMPLATE_INODE = \"")
        .append(String.valueOf(cmsTemplate.getInode()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_META = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getMetadata()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_META = \"#fixBreaks($HTMLPAGE_META)\")");

    sb.append("#set ($HTMLPAGE_DESCRIPTION = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getSeoDescription()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_DESCRIPTION = \"#fixBreaks($HTMLPAGE_DESCRIPTION)\")");

    sb.append("#set ($HTMLPAGE_KEYWORDS = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getSeoKeywords()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_KEYWORDS = \"#fixBreaks($HTMLPAGE_KEYWORDS)\")");

    sb.append("#set ($HTMLPAGE_SECURE = \"")
        .append(String.valueOf(htmlPage.isHttpsRequired()))
        .append("\" )");
    sb.append("#set ($VTLSERVLET_URI = \"")
        .append(UtilMethods.encodeURIComponent(identifier.getURI()))
        .append("\" )");
    sb.append("#set ($HTMLPAGE_REDIRECT = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getRedirect()))
        .append("\" )");

    sb.append("#set ($pageTitle = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getTitle()))
        .append("\" )");
    sb.append("#set ($pageChannel = \"").append(pageChannel).append("\" )");
    sb.append("#set ($friendlyName = \"")
        .append(UtilMethods.espaceForVelocity(htmlPage.getFriendlyName()))
        .append("\" )");

    Date moddate = null;
    if (UtilMethods.isSet(htmlPage.getModDate())) {
      moddate = htmlPage.getModDate();
    } else {
      moddate = htmlPage.getStartDate();
    }

    moddate = new Timestamp(moddate.getTime());

    sb.append("#set ($HTML_PAGE_LAST_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"")
        .append(moddate)
        .append("\"))");
    sb.append("#set ($HTMLPAGE_MOD_DATE= $date.toDate(\"yyyy-MM-dd HH:mm:ss.SSS\", \"")
        .append(moddate)
        .append("\"))");
    sb.append(" #end ");

    // get the containers for the page and stick them in context
    // List identifiers = InodeFactory.getChildrenClass(cmsTemplate, Identifier.class);

    List<Container> containerList =
        APILocator.getTemplateAPI()
            .getContainersInTemplate(cmsTemplate, APILocator.getUserAPI().getSystemUser(), false);

    Iterator i = containerList.iterator();
    while (i.hasNext()) {
      Container ident = (Container) i.next();

      Container c = null;
      if (EDIT_MODE) {
        c =
            (Container)
                APILocator.getVersionableAPI()
                    .findWorkingVersion(
                        ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      } else {
        c =
            (Container)
                APILocator.getVersionableAPI()
                    .findLiveVersion(
                        ident.getIdentifier(), APILocator.getUserAPI().getSystemUser(), false);
      }
      // sets container to load the container file
      sb.append("#set ($container")
          .append(ident.getIdentifier())
          .append(" = \"")
          .append(folderPath)
          .append(ident.getIdentifier())
          .append(".")
          .append(Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION"))
          .append("\" )");

      String sort = (c.getSortContentletsBy() == null) ? "tree_order" : c.getSortContentletsBy();

      boolean dynamicContainer = UtilMethods.isSet(c.getLuceneQuery());

      int langCounter = 0;

      List<Contentlet> contentlets = new ArrayList<Contentlet>();
      List<Contentlet> contentletsFull = new ArrayList<Contentlet>();
      if (!dynamicContainer) {
        Identifier idenHtmlPage = APILocator.getIdentifierAPI().find(htmlPage);
        Identifier idenContainer = APILocator.getIdentifierAPI().find(c);
        // The container doesn't have categories
        try {
          contentlets =
              conAPI.findPageContentlets(
                  idenHtmlPage.getId(),
                  idenContainer.getId(),
                  sort,
                  EDIT_MODE,
                  -1,
                  APILocator.getUserAPI().getSystemUser(),
                  false);
          if (EDIT_MODE) contentletsFull = contentlets;
          else
            contentletsFull =
                conAPI.findPageContentlets(
                    idenHtmlPage.getId(),
                    idenContainer.getId(),
                    sort,
                    true,
                    -1,
                    APILocator.getUserAPI().getSystemUser(),
                    false);
        } catch (Exception e) {
          Logger.error(PageServices.class, "Unable to retrive contentlets on page", e);
        }
        Logger.debug(
            PageServices.class,
            "HTMLPage= "
                + htmlPage.getInode()
                + " Container="
                + c.getInode()
                + " Language=-1 Contentlets="
                + contentlets.size());
      }
      // this is to filter the contentlets list removing the repited identifiers
      if (contentlets.size() > 0) {
        Set<String> contentletIdentList = new HashSet<String>();
        List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
        for (Contentlet cont : contentlets) {
          if (!contentletIdentList.contains(cont.getIdentifier())) {
            contentletIdentList.add(cont.getIdentifier());
            contentletsFilter.add(cont);
          }
        }
        contentlets = contentletsFilter;
      }
      if (contentletsFull.size() > 0) {
        Set<String> contentletIdentList = new HashSet<String>();
        List<Contentlet> contentletsFilter = new ArrayList<Contentlet>();
        for (Contentlet cont : contentletsFull) {
          if (!contentletIdentList.contains(cont.getIdentifier())) {
            contentletIdentList.add(cont.getIdentifier());
            contentletsFilter.add(cont);
          }
        }
        contentletsFull = contentletsFilter;
      }

      StringBuilder widgetpree = new StringBuilder();
      StringBuilder widgetpreeFull = new StringBuilder();

      StringBuilder contentletList = new StringBuilder();
      int count = 0;
      for (Contentlet contentlet : contentlets) {
        contentletList
            .append(count == 0 ? "" : ",")
            .append('"')
            .append(contentlet.getIdentifier())
            .append('"');
        if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
          Field field = contentlet.getStructure().getFieldVar("widgetPreexecute");
          if (field != null && UtilMethods.isSet(field.getValues()))
            widgetpree.append(field.getValues().trim());
        }
        if (++count >= c.getMaxContentlets()) break;
      }

      StringBuilder contentletListFull = new StringBuilder();
      int countFull = 0;
      for (Contentlet contentlet : contentletsFull) {
        contentletListFull
            .append(countFull == 0 ? "" : ",")
            .append('"')
            .append(contentlet.getIdentifier())
            .append('"');
        if (contentlet.getStructure().getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
          Field field = contentlet.getStructure().getFieldVar("widgetPreexecute");
          if (field != null && UtilMethods.isSet(field.getValues()))
            widgetpreeFull.append(field.getValues().trim());
        }
        if (++countFull >= c.getMaxContentlets()) break;
      }

      sb.append("#if($request.session.getAttribute(\"tm_date\"))");
      sb.append(widgetpreeFull);
      sb.append("#set ($contentletList")
          .append(ident.getIdentifier())
          .append(" = [")
          .append(contentletListFull.toString())
          .append("] )");
      sb.append("#set ($totalSize")
          .append(ident.getIdentifier())
          .append("=")
          .append(countFull)
          .append(")");
      sb.append("#else ");
      sb.append(widgetpree);
      sb.append("#set ($contentletList")
          .append(ident.getIdentifier())
          .append(" = [")
          .append(contentletList.toString())
          .append("] )");
      sb.append("#set ($totalSize")
          .append(ident.getIdentifier())
          .append("=")
          .append(count)
          .append(")");
      sb.append("#end ");
      langCounter++;
    }

    if (htmlPage.isHttpsRequired()) {
      sb.append(" #if(!$ADMIN_MODE  && !$request.isSecure())");
      sb.append("    #if($request.getQueryString())");
      sb.append(
          "        #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')?$request.getQueryString()\")");
      sb.append("    #else ");
      sb.append(
          "        #set ($REDIRECT_URL = \"https://${request.getServerName()}$request.getAttribute('javax.servlet.forward.request_uri')\")");
      sb.append("    #end ");
      sb.append("    $response.sendRedirect(\"$REDIRECT_URL\")");
      sb.append(" #end ");
    }

    sb.append("#if($HTMLPAGE_REDIRECT != \"\")");
    sb.append("    $response.sendRedirect(\"$HTMLPAGE_REDIRECT\")");
    sb.append("#end");

    Identifier iden = APILocator.getIdentifierAPI().find(cmsTemplate);

    sb.append("#if(!$doNotParseTemplate)");
    if (cmsTemplate.isDrawed()) { // We have a designed template
      // Setting some theme variables
      sb.append("#set ($dotTheme = $templatetool.theme(\"")
          .append(cmsTemplate.getTheme())
          .append("\",\"")
          .append(host.getIdentifier())
          .append("\"))");
      sb.append("#set ($dotThemeLayout = $templatetool.themeLayout(\"")
          .append(cmsTemplate.getInode())
          .append("\" ))");
      // Merging our template
      sb.append("$velutil.mergeTemplate(\"$dotTheme.templatePath\")");
    } else {
      sb.append("$velutil.mergeTemplate('")
          .append(folderPath)
          .append(iden.getInode())
          .append(".")
          .append(Config.getStringProperty("VELOCITY_TEMPLATE_EXTENSION"))
          .append("')");
    }
    sb.append("#end");

    try {

      if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) {
        String realFolderPath =
            (!EDIT_MODE) ? "live" + java.io.File.separator : "working" + java.io.File.separator;
        String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
        String filePath =
            realFolderPath
                + identifier.getInode()
                + "."
                + Config.getStringProperty("VELOCITY_HTMLPAGE_EXTENSION");
        if (velocityRootPath.startsWith("/WEB-INF")) {
          velocityRootPath = com.liferay.util.FileUtil.getRealPath(velocityRootPath);
        }
        velocityRootPath += java.io.File.separator;

        java.io.BufferedOutputStream tmpOut =
            new java.io.BufferedOutputStream(
                new java.io.FileOutputStream(
                    new java.io.File(
                        ConfigUtils.getDynamicVelocityPath() + java.io.File.separator + filePath)));
        // Specify a proper character encoding
        OutputStreamWriter out =
            new OutputStreamWriter(tmpOut, UtilMethods.getCharsetConfiguration());

        out.write(sb.toString());

        out.flush();
        out.close();
        tmpOut.close();
      }
    } catch (Exception e) {
      Logger.error(PageServices.class, e.toString(), e);
    }
    try {
      result = new ByteArrayInputStream(sb.toString().getBytes("UTF-8"));
    } catch (UnsupportedEncodingException e1) {
      result = new ByteArrayInputStream(sb.toString().getBytes());
      Logger.error(ContainerServices.class, e1.getMessage(), e1);
    }
    return result;
  }