/**
   * @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;
  }
  /**
   * Create a new content, setting the content values with the specified list of param values
   *
   * @param structureName The content structure name
   * @param parametersName The fields names
   * @param values The fields values
   * @return Contentlet
   * @throws DotDataException
   */
  private static Contentlet setAllFields(
      String structureName, List<String> parametersName, List<String[]> values)
      throws DotDataException {
    LanguageAPI lAPI = APILocator.getLanguageAPI();
    Structure st = StructureCache.getStructureByName(structureName);
    Contentlet contentlet = new Contentlet();
    contentlet.setStructureInode(st.getInode());
    contentlet.setLanguageId(lAPI.getDefaultLanguage().getId());

    for (int i = 0; i < parametersName.size(); i++) {
      String fieldname = parametersName.get(i);
      String[] fieldValue = values.get(i);
      setField(st, contentlet, fieldname, fieldValue);
    }

    return contentlet;
  }
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;
  }
  private void _defaultStructure(ActionForm form, ActionRequest req, ActionResponse res) {
    try {

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

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

      StructureFactory.disableDefault();
      structure.setDefaultStructure(true);
      StructureFactory.saveStructure(structure);
      String message = "message.structure.defaultstructure";
      SessionMessages.add(req, "message", message);
    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
    }
  }
  @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;
  }
  /**
   * 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;
  }
  private void _resetIntervals(ActionForm form, ActionRequest req, ActionResponse res) {
    try {
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);

      int limit = 200;
      int offset = 0;
      List<Contentlet> contents =
          conAPI.findByStructure(structure, _getUser(req), false, limit, offset);
      int size = contents.size();
      while (size > 0) {
        for (Contentlet cont : contents) {
          cont.setReviewInterval(structure.getReviewInterval());
        }
        offset += limit;
        contents = conAPI.findByStructure(structure, _getUser(req), false, limit, offset);
        size = contents.size();
      }
    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
    }
  }
  @SuppressWarnings("deprecation")
  private void _loadForm(ActionForm form, ActionRequest req, ActionResponse res) {
    try {
      StructureForm structureForm = (StructureForm) form;
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);
      BeanUtils.copyProperties(structureForm, structure);
      structureForm.setFields(structure.getFields());

      if (structure.getReviewInterval() != null) {
        String interval = structure.getReviewInterval();
        Pattern p = Pattern.compile("(\\d+)([dmy])");
        Matcher m = p.matcher(interval);
        boolean b = m.matches();
        if (b) {
          structureForm.setReviewContent(true);
          String g1 = m.group(1);
          String g2 = m.group(2);
          structureForm.setReviewIntervalNum(g1);
          structureForm.setReviewIntervalSelect(g2);
        }
      }
      if (UtilMethods.isSet(structure.getDetailPage())) {
        Identifier ident = APILocator.getIdentifierAPI().find(structure.getDetailPage());
        HTMLPage page = HTMLPageFactory.getLiveHTMLPageByIdentifier(ident);
        if (InodeUtils.isSet(page.getInode())) {
          structureForm.setDetailPage(page.getIdentifier());
        }
      }

    } catch (Exception ex) {
      Logger.debug(EditStructureAction.class, ex.toString());
    }
  }
Beispiel #9
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());
      }
    }
  }
Beispiel #11
0
  public static InputStream buildVelocity(
      Container container, Identifier identifier, boolean EDIT_MODE) {

    InputStream result;
    StringBuilder sb = new StringBuilder();

    boolean isDynamic = UtilMethods.isSet(container.getLuceneQuery());

    //  let's write this puppy out to our file
    sb.append("#set($SERVER_NAME =\"$host.getHostname()\" )");
    sb.append("#set($CONTAINER_IDENTIFIER_INODE = '").append(identifier.getInode()).append("')");
    sb.append("#set($CONTAINER_INODE = '").append(container.getInode()).append("')");
    sb.append("#set($CONTAINER_MAX_CONTENTLETS = ")
        .append(container.getMaxContentlets())
        .append(")");
    Structure st =
        (Structure) InodeFactory.getInode(container.getStructureInode(), Structure.class);
    sb.append("#set($CONTAINER_STRUCTURE_NAME = \"")
        .append((UtilMethods.isSet(st.getName()) ? st.getName() : ""))
        .append("\")");
    sb.append("#set($STATIC_CONTAINER = ")
        .append(!UtilMethods.isSet(container.getLuceneQuery()))
        .append(")");
    sb.append("#set($SORT_PAGE = \"").append(container.getSortContentletsBy()).append("\")");
    sb.append("#set($containerInode = '").append(container.getInode()).append("')");

    if (EDIT_MODE) {
      // Permissions to read/use the container in order to be able to add content to it and reorder
      // content
      sb.append("#set($USE_CONTAINER_PERMISSION = $USE_CONTAINER_PERMISSION")
          .append(identifier.getInode())
          .append(")");

      // Permissions to edit the container based on write permission ).append( access to the portlet
      sb.append("#set($EDIT_CONTAINER_PERMISSION = $EDIT_CONTAINER_PERMISSION")
          .append(identifier.getInode())
          .append(")");

      // Permissions over the structure to add new contents
      sb.append("#set($ADD_CONTENT_PERMISSION = $ADD_CONTENT_PERMISSION")
          .append(identifier.getInode())
          .append(")");
    }

    sb.append("#set($CONTENTLETS = $contentletList").append(identifier.getInode()).append(")");
    sb.append("#set($CONTAINER_NUM_CONTENTLETS = $totalSize")
        .append(identifier.getInode())
        .append(")");

    sb.append("#set($CONTAINER_NAME = \"")
        .append(UtilMethods.espaceForVelocity(container.getTitle()))
        .append("\")");
    sb.append("#set($CONTAINER_STRUCTURE_NAME = \"")
        .append(UtilMethods.espaceForVelocity(st.getName()))
        .append("\")");
    if (UtilMethods.isSet(container.getNotes()))
      sb.append("#set($CONTAINER_NOTES = \"")
          .append(UtilMethods.espaceForVelocity(container.getNotes()))
          .append("\")");
    else sb.append("#set($CONTAINER_NOTES = \"\")");

    /*
     * isDynamic means that the content list will be pulled from lucene.
     */
    if (isDynamic) {
      String luceneQuery = container.getLuceneQuery();
      sb.append("#set($CONTENTS_PER_PAGE = \"$CONTAINER_MAX_CONTENTLETS\")");
      sb.append("#if($request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_per_page\"))");
      sb.append("#set($CONTENTS_PER_PAGE = $request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_per_page\"))");
      sb.append("#end");
      sb.append("#set($CURRENT_PAGE = \"1\")");
      sb.append("#if($request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_page\"))");
      sb.append("#set($CURRENT_PAGE = $request.getParameter(\"cont_")
          .append(identifier.getInode())
          .append("_page\"))");
      sb.append("#end");
      sb.append("#set($LUCENE_QUERY = \"").append(luceneQuery).append("\")");
    }

    // if the container needs to get its contentlets
    if (container.getMaxContentlets() > 0) {
      sb.append("#if($EDIT_MODE)");

      // To edit the look, see WEB-INF/velocity/static/preview/container_controls.vtl
      sb.append("<div class='dotContainer'>");
      sb.append("#end");

      // pre loop if it exists
      if (UtilMethods.isSet(container.getPreLoop())) {
        sb.append(container.getPreLoop());
      }

      // let's do the search of contentlets using lucene query
      if (isDynamic) {
        Structure containerStructure =
            (Structure) InodeFactory.getInode(container.getStructureInode(), Structure.class);

        sb.append("#set($contentletResultsMap")
            .append(identifier.getInode())
            .append(" = $contents.searchWithLuceneQuery(\"")
            .append(containerStructure.getInode())
            .append("\", ")
            .append("\"$LUCENE_QUERY\", ")
            .append("\"$SORT_PAGE\", ")
            .append("$CURRENT_PAGE, $CONTENTS_PER_PAGE)) ");
        sb.append("#set($contentletList")
            .append(identifier.getInode())
            .append(" = $contents.getContentIdentifiersFromLuceneHits($contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"assets\")))");

        sb.append("#set($HAS_NEXT_PAGE = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"has_next_page\"))");
        sb.append("#set($HAS_PREVIOUS_PAGE = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"has_previous_page\"))");
        sb.append("#set($TOTAL_CONTENTS = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"total_records_int\"))");
        sb.append("#set($TOTAL_PAGES = $contentletResultsMap")
            .append(identifier.getInode())
            .append(".get(\"total_pages_int\"))");
        sb.append("#set($CONTENTLETS = $contentletList").append(identifier.getInode()).append(")");
        sb.append("#set($CONTAINER_NUM_CONTENTLETS = $totalSize")
            .append(identifier.getInode())
            .append(")");
      }

      sb.append("#foreach ($contentletId in $contentletList")
          .append(identifier.getInode())
          .append(")");

      // ##Checking of contentlet is parseable and not throwing errors
      if (EDIT_MODE) {
        sb.append("#if($webapi.canParseContent($contentletId,true))");
      }
      // sb.append("\n#if($webapi.canParseContent($contentletId,"+EDIT_MODE+")) ");
      sb.append(" #set($_show_working_=false) ");
      // if timemachine future enabled
      sb.append(" #if($request.session.getAttribute(\"tm_date\")) ");
      sb.append(
          "  #set($_tmdate=$date.toDate($webapi.parseLong($request.session.getAttribute(\"tm_date\")))) ");
      sb.append("  #set($_ident=$webapi.findIdentifierById($contentletId)) ");

      // if the content has expired we rewrite the identifier so it isn't loaded
      sb.append(
          "  #if($UtilMethods.isSet($_ident.sysExpireDate) && $_tmdate.after($_ident.sysExpireDate))");
      sb.append("   #set($contentletId='') ");
      sb.append("  #end ");

      // if the content should be published then force to show the working version
      sb.append(
          "  #if($UtilMethods.isSet($_ident.sysPublishDate) && $_tmdate.after($_ident.sysPublishDate))");
      sb.append("   #set($_show_working_=true) ");
      sb.append("  #end ");

      sb.append(" #end ");

      sb.append("#set($CONTENT_INODE = '')");
      sb.append(" #if($contentletId != '') ");
      sb.append("  #getContentDetail($contentletId) ");
      sb.append(" #end ");
      sb.append("#if($CONTENT_INODE != '')");

      if (!EDIT_MODE) {
        sb.append(
            "#set($_hasPermissionToViewContent = $contents.doesUserHasPermission($CONTENT_INODE, 1, $user, true))");
        // ##Checking permission to see content
        sb.append("#if($_hasPermissionToViewContent)");
      }

      String code = container.getCode();

      // ### HEADER ###
      String startTag = "${contentletStart}";
      if (!code.contains(startTag)) {
        sb.append("#if($EDIT_MODE)");
        sb.append("<div class=\"dotContentlet\">");
        // An empty div is added here because in Internet Explorer, there is a styling issue
        // http://jira.dotmarketing.net/browse/DOTCMS-1974
        sb.append("<div>");
        sb.append(" #end ");
      } else {
        String headerString =
            "#if($EDIT_MODE)" + "<div class=\"dotContentlet\">" + "<div>" + "#end ";
        code = code.replace(startTag, headerString);
      }
      // ### END HEADER ###

      // ### BODY ###
      String endTag = "${contentletEnd}";
      boolean containsEndTag = code.contains(endTag);
      if (containsEndTag) {
        String footerString =
            "#if($EDIT_MODE && ${contentletId.indexOf(\".structure\")}==-1)"
                + "$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')"
                + "#end"
                + "#if($EDIT_MODE)"
                + "<div class=\"dotClear\"></div></div>"
                + "#end ";
        code = code.replace(endTag, footerString);
      }

      sb.append("#if($isWidget == true)");
      sb.append("$widgetCode");
      sb.append(" #else");
      sb.append(code);
      sb.append(" #end ");
      // The empty div added for styling issue in Internet Explorer is closed here
      // http://jira.dotmarketing.net/browse/DOTCMS-1974
      sb.append("#if($EDIT_MODE)");
      sb.append("</div>");
      sb.append("#end ");
      // ### END BODY ###

      // ### FOOTER ###

      if (!containsEndTag) {
        sb.append("#if($EDIT_MODE && ${contentletId.indexOf(\".structure\")}==-1)");
        sb.append("#getContentDetail($contentletId)");
        sb.append("$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')");
        sb.append("#end ");
        sb.append("#if($EDIT_MODE) ");
        sb.append("<div class=\"dotClear\"></div></div>");
        sb.append("#end ");
      }
      // ### END FOOTER ###

      if (!EDIT_MODE) {
        // ##End of checking permission to see content
        sb.append("#end ");
      }
      // ##Ends the inner canParse call
      sb.append("#end ");
      // ##Case the contentlet is not parseable and throwing errors
      if (EDIT_MODE) {
        sb.append("#else ");
        sb.append("#set($CONTENT_INODE =\"$webapi.getContentInode($contentletId)\")");
        sb.append(
            "#set($EDIT_CONTENT_PERMISSION =\"$webapi.getContentPermissions($contentletId)\")");
        sb.append("<div class=\"dotContentlet\">");
        sb.append("	Content Parse Error. Check your Content Code. ");
        sb.append("$velutil.mergeTemplate('static/preview_mode/content_controls.vtl')");
        sb.append("<div class=\"dotClear\"></div></div>");
        sb.append("#end ");
      }

      // ##End of foreach loop
      sb.append("#end ");

      // post loop if it exists

      if (UtilMethods.isSet(container.getPostLoop())) {
        sb.append(container.getPostLoop());
      }
      // close our container preview mode div
      sb.append("#if($EDIT_MODE)");
      sb.append("$velutil.mergeTemplate('static/preview_mode/container_controls.vtl')");
      sb.append("</div>");
      sb.append("#end ");

    } else {

      sb.append(container.getCode());
    }

    try {
      String folderPath = (!EDIT_MODE) ? "live" + File.separator : "working" + File.separator;
      String velocityRootPath = Config.getStringProperty("VELOCITY_ROOT");
      if (velocityRootPath.startsWith("/WEB-INF")) {
        velocityRootPath = Config.CONTEXT.getRealPath(velocityRootPath);
      }
      velocityRootPath += File.separator;
      String filePath =
          folderPath
              + identifier.getInode()
              + "."
              + Config.getStringProperty("VELOCITY_CONTAINER_EXTENSION");

      if (Config.getBooleanProperty("SHOW_VELOCITYFILES", false)) {
        java.io.BufferedOutputStream tmpOut =
            new java.io.BufferedOutputStream(
                new java.io.FileOutputStream(
                    new java.io.File(
                        ConfigUtils.getDynamicVelocityPath() + 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(ContentletServices.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;
  }
  @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 #13
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 #14
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;
    }
  }
  private void _saveStructure(ActionForm form, ActionRequest req, ActionResponse res) {
    try {
      boolean newStructure = false;
      StructureForm structureForm = (StructureForm) form;
      Structure structure = (Structure) req.getAttribute(WebKeys.Structure.STRUCTURE);

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

      if (!UtilMethods.isSet(structureForm.getHost())
          && (!UtilMethods.isSet(structureForm.getFolder())
              || structureForm.getFolder().equals("SYSTEM_FOLDER"))) {
        throw new DotDataException(LanguageUtil.get(user, "Host-or-folder-is-required"));
      }

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

      // Check if another structure with the same name exist
      String auxStructureName = structureForm.getName();
      auxStructureName = (auxStructureName != null ? auxStructureName.trim() : "");

      @SuppressWarnings("deprecation")
      Structure auxStructure = StructureCache.getStructureByType(auxStructureName);

      if (InodeUtils.isSet(auxStructure.getInode())
          && !auxStructure.getInode().equalsIgnoreCase(structure.getInode())) {
        throw new DotDataException(
            LanguageUtil.get(user, "There-is-another-structure-with-the-same-name"));
      }

      Arrays.sort(reservedStructureNames);
      if (!InodeUtils.isSet(structureForm.getInode())
          && (Arrays.binarySearch(reservedStructureNames, auxStructureName) >= 0)) {
        throw new DotDataException("Invalid Reserved Structure Name : " + auxStructureName);
      }

      // Validate if is a new structure and if the name hasn't change
      if (!InodeUtils.isSet(structure.getInode())) {
        newStructure = true;
      } else {
        String structureName = structure.getName();
        String structureFormName = structureForm.getName();
        if (UtilMethods.isSet(structureName)
            && UtilMethods.isSet(structureFormName)
            && !structureName.equals(structureFormName)
            && !structure.isFixed()) {

          StructureCache.removeStructure(structure);
        }
      }

      // If the structure is fixed the name cannot be changed
      if (structure.isFixed()) {
        structureForm.setName(structure.getName());
      }

      // if I'm editing a structure the structureType couldn't not be
      // change
      if (UtilMethods.isSet(structure.getInode()) && InodeUtils.isSet(structure.getInode())) {
        // reset the structure type to it's original value
        structureForm.setStructureType(structure.getStructureType());
      }
      if (UtilMethods.isSet(structure.getVelocityVarName())) {
        structureForm.setVelocityVarName(structure.getVelocityVarName());
      }
      if (UtilMethods.isSet(structureForm.getHost())) {
        if (!structureForm.getHost().equals(Host.SYSTEM_HOST)
            && hostAPI.findSystemHost().getIdentifier().equals(structureForm.getHost())) {
          structureForm.setHost(Host.SYSTEM_HOST);
        }
        structureForm.setFolder("SYSTEM_FOLDER");
      } else if (UtilMethods.isSet(structureForm.getFolder())) {
        structureForm.setHost(folderAPI.find(structureForm.getFolder(), user, false).getHostId());
      }

      if (UtilMethods.isSet(structureForm.getHost())
          && (!UtilMethods.isSet(structureForm.getFolder())
              || structureForm.getFolder().equals("SYSTEM_FOLDER"))) {
        Host host = hostAPI.find(structureForm.getHost(), user, false);
        if (host != null) {
          if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
            if (!perAPI.doesUserHavePermissions(
                host,
                "PARENT:"
                    + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN
                    + ", STRUCTURES:"
                    + PermissionAPI.PERMISSION_PUBLISH,
                user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          } else {
            if (!perAPI.doesUserHavePermission(
                host, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          }
        }
      }

      if (UtilMethods.isSet(structureForm.getFolder())
          && !structureForm.getFolder().equals("SYSTEM_FOLDER")) {
        Folder folder = folderAPI.find(structureForm.getFolder(), user, false);
        if (folder != null) {
          if (structure.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
            if (!perAPI.doesUserHavePermissions(
                folder,
                "PARENT:"
                    + PermissionAPI.PERMISSION_CAN_ADD_CHILDREN
                    + ", STRUCTURES:"
                    + PermissionAPI.PERMISSION_PUBLISH,
                user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          } else {
            if (!perAPI.doesUserHavePermission(
                folder, PermissionAPI.PERMISSION_CAN_ADD_CHILDREN, user)) {
              throw new DotDataException(
                  LanguageUtil.get(
                      user, "User-does-not-have-add-children-permission-on-host-folder"));
            }
          }
        }
      }

      BeanUtils.copyProperties(structure, structureForm);

      // if htmlpage doesn't exist page id should be an identifier. Should
      // be refactored once we get identifierAPI/HTMLPage API done
      String pageDetail = structureForm.getDetailPage();

      if (newStructure) {
        String structureVelocityName =
            VelocityUtil.convertToVelocityVariable(structure.getName(), true);
        List<String> velocityvarnames = StructureFactory.getAllVelocityVariablesNames();
        int found = 0;
        if (VelocityUtil.isNotAllowedVelocityVariableName(structureVelocityName)) {
          found++;
        }

        for (String velvar : velocityvarnames) {
          if (velvar != null) {
            if (structureVelocityName.equalsIgnoreCase(velvar)) {
              found++;
            } else if (velvar.toLowerCase().contains(structureVelocityName.toLowerCase())) {
              String number = velvar.substring(structureVelocityName.length());
              if (RegEX.contains(number, "^[0-9]+$")) {
                found++;
              }
            }
          }
        }
        if (found > 0) {
          structureVelocityName = structureVelocityName + Integer.toString(found);
        }
        structure.setVelocityVarName(structureVelocityName);
      }

      if (UtilMethods.isSet(pageDetail)) {
        structure.setDetailPage(pageDetail);
      }

      // Saving interval review properties
      if (structureForm.isReviewContent()) {
        structure.setReviewInterval(
            structureForm.getReviewIntervalNum() + structureForm.getReviewIntervalSelect());
      } else {
        structure.setReviewInterval(null);
        structure.setReviewerRole(null);
      }

      // If there is no default structure this would be
      Structure defaultStructure = StructureFactory.getDefaultStructure();
      if (!InodeUtils.isSet(defaultStructure.getInode())) {
        structure.setDefaultStructure(true);
      }
      if (newStructure) {
        structure.setFixed(false);
        structure.setOwner(user.getUserId());
      }
      // validate iit is a form structure set it as system by default
      if (structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
        structure.setSystem(true);
      }
      StructureFactory.saveStructure(structure);
      structureForm.setUrlMapPattern(structure.getUrlMapPattern());

      WorkflowScheme scheme = APILocator.getWorkflowAPI().findSchemeForStruct(structure);

      String schemeId = req.getParameter("workflowScheme");

      if (scheme != null && UtilMethods.isSet(schemeId) && !schemeId.equals(scheme.getId())) {
        scheme = APILocator.getWorkflowAPI().findScheme(schemeId);
        APILocator.getWorkflowAPI().saveSchemeForStruct(structure, scheme);
      }

      // if the structure is a widget we need to add the base fields.
      if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_WIDGET) {
        wAPI.createBaseWidgetFields(structure);
      }

      // if the structure is a form we need to add the base fields.
      if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FORM) {
        fAPI.createBaseFormFields(structure);
      }

      // if the structure is a form we need to add the base fields.
      if (newStructure && structureForm.getStructureType() == Structure.STRUCTURE_TYPE_FILEASSET) {
        APILocator.getFileAssetAPI().createBaseFileAssetFields(structure);
      }
      if (!newStructure) {
        perAPI.resetPermissionReferences(structure);
      }

      // Saving the structure in cache
      StructureCache.removeStructure(structure);
      StructureCache.addStructure(structure);
      StructureServices.removeStructureFile(structure);

      String message = "message.structure.savestructure";
      if (structure.getStructureType() == 3) {
        message = "message.form.saveform";
      }
      SessionMessages.add(req, "message", message);
      AdminLogger.log(
          EditStructureAction.class,
          "_saveStructure",
          "Structure saved : " + structure.getName(),
          user);
    } catch (Exception ex) {
      Logger.error(this.getClass(), ex.toString());
      String message = ex.toString();
      SessionMessages.add(req, "error", message);
    }
  }