private void sendResults(
      HashMap<String, List<String>> results,
      String reportEmail,
      String subject,
      String logPath,
      String fileName) {
    StringBuilder message = new StringBuilder(1024);
    message.ensureCapacity(256);

    List<String> messages = ((List<String>) results.get("errors"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nError Found:\n\n");
      Logger.info(ContentImporterThread.class, "\nError Found:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    messages = ((List<String>) results.get("warnings"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nWarnings Found:\n\n");
      Logger.info(ContentImporterThread.class, "\nWarnings Found:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    messages = ((List<String>) results.get("results"));
    if ((messages != null) && (0 < messages.size())) {
      message.append("\nResults:\n\n");
      Logger.info(ContentImporterThread.class, "\nResults:\n");

      for (String tempMsg : messages) {
        message.append(tempMsg + "\n");
        Logger.info(ContentImporterThread.class, tempMsg);
      }
    }

    Company company = PublicCompanyFactory.getDefaultCompany();

    contentImporterLogger(logPath, fileName, message.toString());
    if (UtilMethods.isSet(reportEmail)) {
      Mailer m = new Mailer();
      m.setToEmail(reportEmail);
      m.setFromEmail(company.getEmailAddress());
      m.setCc(null);
      m.setBcc(null);
      m.setSubject(subject);
      m.setTextBody(message.toString());

      if (!m.sendMessage()) {
        Logger.info(ContentImporterThread.class, "Email couldn't be sent.");
      }
    }
  }
예제 #2
0
  public static FileAsset saveTempFile(
      User user, Host host, java.io.File uploadedFile, String folderPath, String title)
      throws Exception {

    Folder folder = APILocator.getFolderAPI().findFolderByPath(folderPath, host, user, false);

    byte[] bytes = FileUtil.getBytes(uploadedFile);

    if (bytes != null) {

      String name = UtilMethods.getFileName(title);
      int counter = 1;
      while (APILocator.getFileAPI().fileNameExists(folder, name)) {
        name = name + counter;
        counter++;
      }

      Contentlet cont = new Contentlet();
      cont.setStructureInode(folder.getDefaultFileType());
      cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(name));
      cont.setFolder(folder.getInode());
      cont.setHost(host.getIdentifier());
      cont.setBinary(FileAssetAPI.BINARY_FIELD, uploadedFile);
      APILocator.getContentletAPI().checkin(cont, user, false);
      APILocator.getVersionableAPI().setLive(cont);
      return APILocator.getFileAssetAPI().fromContentlet(cont);
    }

    return null;
  }
예제 #3
0
  public SSLContext getSSLContext() {
    TrustManager mytm[] = null;
    KeyManager mykm[] = null;

    try {
      if (UtilMethods.isSet(truststore_path) && UtilMethods.isSet(truststore_password)) {
        mytm =
            new TrustManager[] {
              new MyX509TrustManager(truststore_path, truststore_password.toCharArray())
            };
      }

      if (UtilMethods.isSet(keystore_path) && UtilMethods.isSet(keystore_password)) {
        mykm =
            new KeyManager[] {new MyX509KeyManager(keystore_path, keystore_password.toCharArray())};
      }
    } catch (Exception ex) {
      Logger.error(this.getClass(), ex.toString());
      Logger.debug(this.getClass(), ex.getMessage(), ex);
    }

    SSLContext ctx = null;
    try {
      ctx = SSLContext.getInstance("SSL");
      ctx.init(mykm, mytm, null);
    } catch (java.security.GeneralSecurityException ex) {
      Logger.error(this.getClass(), ex.getMessage(), ex);
    }
    return ctx;
  }
예제 #4
0
  /**
   * Copy a file into the given directory OR host
   *
   * @param file File to be copied
   * @param parent Destination Folder
   * @param host Destination host
   * @return true if copy success, false otherwise
   * @throws IOException
   * @throws DotHibernateException
   */
  private File copyFile(File file, Folder parent, Host host) throws DotDataException, IOException {

    File newFile = new File();

    newFile.copy(file);

    // gets filename before extension
    String fileName = com.dotmarketing.util.UtilMethods.getFileName(file.getFileName());
    // gets file extension
    String fileExtension = com.dotmarketing.util.UtilMethods.getFileExtension(file.getFileName());

    Boolean fileNameExists;
    if (parent != null) {
      fileNameExists = fileNameExists(parent, file.getFileName());
    } else {
      fileNameExists =
          fileNameExists(APILocator.getFolderAPI().findSystemFolder(), file.getFileName());
    }

    // Setting file name
    if (fileNameExists) {
      // adds "copy" word to the filename
      newFile.setFileName(fileName + "_copy." + fileExtension);
      newFile.setFriendlyName(file.getFriendlyName() + " (COPY) ");
    } else {
      newFile.setFileName(fileName + "." + fileExtension);
    }

    Identifier identifier;
    if (parent != null) {
      identifier = APILocator.getIdentifierAPI().createNew(newFile, parent);
    } else {
      identifier = APILocator.getIdentifierAPI().createNew(newFile, host);
    }
    newFile.setIdentifier(identifier.getInode());

    // persists the webasset
    HibernateUtil.saveOrUpdate(newFile);

    saveFileData(file, newFile, null);

    Logger.debug(FileFactory.class, "identifier=" + identifier.getURI());

    WorkingCache.removeAssetFromCache(newFile);
    WorkingCache.addToWorkingAssetToCache(newFile);
    PermissionAPI permissionAPI = APILocator.getPermissionAPI();

    try {
      APILocator.getVersionableAPI().setWorking(newFile);
      if (file.isLive()) APILocator.getVersionableAPI().setLive(newFile);
    } catch (DotStateException e) {
      Logger.error(this, e.getMessage());
    } catch (DotSecurityException e) {
      Logger.error(this, e.getMessage());
    }
    // Copy permissions
    permissionAPI.copyPermissions(file, newFile);

    return newFile;
  }
예제 #5
0
  @SuppressWarnings({"unchecked", "deprecation"})
  public boolean renameFile(File file, String newName)
      throws DotStateException, DotDataException, DotSecurityException {

    // getting old file properties
    String oldFileName = file.getFileName();
    String ext = UtilMethods.getFileExtension(oldFileName);
    Folder folder =
        APILocator.getFolderAPI()
            .findParentFolder(file, APILocator.getUserAPI().getSystemUser(), false);

    Identifier ident = APILocator.getIdentifierAPI().find(file);

    String newFileName = newName;
    if (UtilMethods.isSet(ext)) {
      newFileName = newFileName + "." + ext;
    }

    if (fileNameExists(folder, newFileName) || file.isLocked()) return false;

    List<Versionable> versions = APILocator.getVersionableAPI().findAllVersions(ident);

    boolean islive = false;

    for (Versionable version : versions) {
      File f = (File) version;

      // sets filename for this new file
      f.setFileName(newFileName);

      HibernateUtil.saveOrUpdate(f);

      if (f.isLive()) islive = true;
    }

    LiveCache.removeAssetFromCache(file);
    WorkingCache.removeAssetFromCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    ident.setURI(APILocator.getIdentifierAPI().find(folder).getPath() + newFileName);
    // HibernateUtil.saveOrUpdate(ident);
    APILocator.getIdentifierAPI().save(ident);

    if (islive) {
      LiveCache.removeAssetFromCache(file);
      LiveCache.addToLiveAssetToCache(file);
    }
    WorkingCache.removeAssetFromCache(file);
    WorkingCache.addToWorkingAssetToCache(file);
    CacheLocator.getIdentifierCache().removeFromCacheByVersionable(file);

    // RefreshMenus.deleteMenus();
    RefreshMenus.deleteMenu(file);
    CacheLocator.getNavToolCache().removeNav(folder.getHostId(), folder.getInode());

    return true;
  }
예제 #6
0
  protected void doAdminMode(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    // LIVE MODE - LIVE PAGE

    com.liferay.portal.model.User backendUser = null;
    backendUser = com.liferay.portal.util.PortalUtil.getUser(request);

    response.setContentType(CHARSET);
    Context context = VelocityUtil.getWebContext(request, response);

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

    Host host = hostWebAPI.getCurrentHost(request);

    Identifier id = APILocator.getIdentifierAPI().find(host, uri);
    request.setAttribute("idInode", id.getInode());

    HTMLPage htmlPage =
        (HTMLPage)
            APILocator.getVersionableAPI()
                .findWorkingVersion(id, APILocator.getUserAPI().getSystemUser(), false);
    HTMLPageAPI htmlPageAPI = APILocator.getHTMLPageAPI();
    VelocityUtil.makeBackendContext(
        context, htmlPage, "", id.getURI(), request, true, false, false, host);

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

    Template template = null;

    if (request.getParameter("leftMenu") != null) {
      template = VelocityUtil.getEngine().getTemplate("/preview_left_menu.vl");
    } else if (request.getParameter("mainFrame") != null) {
      template =
          VelocityUtil.getEngine()
              .getTemplate("/live/" + id.getInode() + "." + VELOCITY_HTMLPAGE_EXTENSION);
    } else {
      template = VelocityUtil.getEngine().getTemplate("/preview_mode.vl");
    }

    Logger.debug(VelocityServlet.class, "Got the template!!!!" + id.getInode());

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

      template.merge(context, out);

    } catch (ParseErrorException e) {
      out.append(e.getMessage());
    }
  }
  private void contentImporterLogger(String filePath, String fileName, String message) {
    BufferedWriter out = null;
    try {
      File folderPath = new File(filePath);
      if (!folderPath.exists()) {
        folderPath.mkdirs();
      }

      File outputFile =
          new File(
              folderPath.getPath()
                  + File.separator
                  + fileName
                  + " - "
                  + UtilMethods.dateToHTMLDate(new Date(), "yyyyMMddHHmmss")
                  + ".txt");
      if (!outputFile.exists()) outputFile.createNewFile();

      out = new BufferedWriter(new FileWriter(outputFile));
      out.write(message);

    } catch (Exception e1) {
      Logger.error(this, e1.toString());
    } finally {
      if (out != null) {
        try {
          out.close();
        } catch (Exception e2) {
        }
      }
    }
  }
  private void moveImportedFile(String filePath) {
    try {
      String processedFilePath =
          pluginAPI.loadProperty("org.dotcms.plugins.contentImporter", "processedFilePath");
      File processedFilePathDir = new File(processedFilePath);
      if (!processedFilePathDir.exists()) processedFilePathDir.mkdirs();

      File file = new File(filePath);
      String fileName = file.getName();
      String fileNameNoExt = "";
      String fileExt = "";
      int index = fileName.lastIndexOf(".");
      if (-1 < index) {
        fileNameNoExt = fileName.substring(0, index);
        fileExt = fileName.substring(index + 1);
      }

      file.renameTo(
          new File(
              processedFilePathDir.getPath()
                  + File.separator
                  + fileNameNoExt
                  + " - "
                  + UtilMethods.dateToHTMLDate(new Date(), "yyyyMMddHHmmss")
                  + "."
                  + fileExt));
    } catch (Exception e) {
      Logger.info(this, e.toString());
    }
  }
예제 #9
0
  /**
   * Method that will verify if a given template title is already used by another template
   *
   * @param title template title to verify
   * @param templateInode template inode in case we are editing a template, null or empty in case of
   *     a new template
   * @param hostIdentifier current host identifier
   * @return
   * @throws DotDataException
   * @throws SystemException
   * @throws PortalException
   * @throws DotSecurityException
   */
  public boolean duplicatedTitle(String title, String templateInode, String hostIdentifier)
      throws DotDataException, SystemException, PortalException, DotSecurityException {

    HttpServletRequest req = WebContextFactory.get().getHttpServletRequest();
    User user = userWebAPI.getLoggedInUser(req);
    boolean respectFrontendRoles = userWebAPI.isLoggedToFrontend(req);

    // Getting the current host
    Host host = hostAPI.find(hostIdentifier, user, respectFrontendRoles);

    // The template name must be unique
    Template foundTemplate =
        FactoryLocator.getTemplateFactory().findWorkingTemplateByName(title, host);
    boolean duplicatedTitle = false;
    if (foundTemplate != null && InodeUtils.isSet(foundTemplate.getInode())) {
      if (!UtilMethods.isSet(templateInode)) {
        duplicatedTitle = true;
      } else {
        if (!foundTemplate.getInode().equals(templateInode)) {
          duplicatedTitle = true;
        }
      }
    }

    return duplicatedTitle;
  }
  private void loadEveryDayForm(ActionForm form, ActionRequest req) {
    String[] everyDay = req.getParameterValues("everyDay");

    ContentImporterForm contentImporterForm = (ContentImporterForm) form;
    if (UtilMethods.isSet(everyDay) && contentImporterForm.isEveryInfo()) {
      for (String dayOfWeek : everyDay) {
        if (dayOfWeek.equals("MON")) contentImporterForm.setMonday(true);
        else if (dayOfWeek.equals("TUE")) contentImporterForm.setTuesday(true);
        else if (dayOfWeek.equals("WED")) contentImporterForm.setWednesday(true);
        else if (dayOfWeek.equals("THU")) contentImporterForm.setThusday(true);
        else if (dayOfWeek.equals("FRI")) contentImporterForm.setFriday(true);
        else if (dayOfWeek.equals("SAT")) contentImporterForm.setSaturday(true);
        else if (dayOfWeek.equals("SUN")) contentImporterForm.setSunday(true);
      }

      contentImporterForm.setEveryInfo(true);
      contentImporterForm.setEvery("isDays");
    } else {
      contentImporterForm.setEvery("");
      contentImporterForm.setMonday(false);
      contentImporterForm.setTuesday(false);
      contentImporterForm.setWednesday(false);
      contentImporterForm.setThusday(false);
      contentImporterForm.setFriday(false);
      contentImporterForm.setSaturday(false);
      contentImporterForm.setSunday(false);
    }
  }
예제 #11
0
  @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());
    }
  }
예제 #12
0
  public java.io.File getAssetIOFile(File file) throws IOException {

    String fileName = file.getFileName();
    String suffix = UtilMethods.getFileExtension(fileName);

    String assetsPath = APILocator.getFileAPI().getRealAssetsRootPath();
    String fileInode = file.getInode();

    // creates the path where to save the working file based on the inode
    String fileFolderPath = String.valueOf(fileInode);
    if (fileFolderPath.length() == 1) {
      fileFolderPath = fileFolderPath + "0";
    }

    fileFolderPath =
        assetsPath
            + java.io.File.separator
            + fileFolderPath.substring(0, 1)
            + java.io.File.separator
            + fileFolderPath.substring(1, 2);

    new java.io.File(fileFolderPath).mkdirs();

    String filePath = fileFolderPath + java.io.File.separator + fileInode + "." + suffix;

    // creates the new file as
    // inode{1}/inode{2}/inode.file_extension
    java.io.File assetFile = new java.io.File(filePath);
    if (!assetFile.exists()) assetFile.createNewFile();

    return assetFile;
  }
예제 #13
0
  /**
   * This method trys to build a cache key based on the information given in the request - if the
   * page can't be cached, or caching is not availbale then return null
   *
   * @param request
   * @return
   */
  private String getPageCacheKey(HttpServletRequest request) {
    // no license
    if (LicenseUtil.getLevel() < 100) {
      return null;
    }
    // don't cache posts
    if (!"GET".equalsIgnoreCase(request.getMethod())) {
      return null;
    }
    // nocache passed either as a session var, as a request var or as a
    // request attribute
    if ("no".equals(request.getParameter("dotcache"))
        || "no".equals(request.getAttribute("dotcache"))
        || "no".equals(request.getSession().getAttribute("dotcache"))) {
      return null;
    }

    String idInode = (String) request.getAttribute("idInode");

    User user =
        (com.liferay.portal.model.User)
            request.getSession().getAttribute(com.dotmarketing.util.WebKeys.CMS_USER);

    HTMLPage page = null;
    try {
      page = APILocator.getHTMLPageAPI().loadLivePageById(idInode, user, true);
    } catch (Exception e) {
      Logger.error(
          HTMLPageWebAPI.class,
          "unable to load live version of page: " + idInode + " because " + e.getMessage());
      return null;
    }
    if (page == null || page.getCacheTTL() < 1) {
      return null;
    }

    StringBuilder sb = new StringBuilder();
    sb.append(page.getInode());
    sb.append("_" + page.getModDate().getTime());

    String userId = (user != null) ? user.getUserId() : "PUBLIC";
    sb.append("_" + userId);

    String language =
        (String) request.getSession().getAttribute(com.dotmarketing.util.WebKeys.HTMLPAGE_LANGUAGE);
    sb.append("_" + language);

    String urlMap = (String) request.getAttribute(WebKeys.WIKI_CONTENTLET_INODE);
    if (urlMap != null) {
      sb.append("_" + urlMap);
    }

    if (UtilMethods.isSet(request.getQueryString())) {
      sb.append("_" + request.getQueryString());
    }

    return sb.toString();
  }
예제 #14
0
  /**
   * Create a work flow task for the new content created and send a email to the corresponding role
   * moderator users
   *
   * @param contentlet The content
   * @param user The user that add the content
   * @param moderatorRole The role to assign the work flow
   * @throws DotDataException
   * @throws DotDataException
   */
  public static void createWorkFlowTask(Contentlet contentlet, String userId, String moderatorRole)
      throws DotDataException {

    User user = getUserFromId(userId);
    StringBuffer changeHist = new StringBuffer("Task Added<br>");
    WorkflowTask task = new WorkflowTask();

    changeHist.append("Title: " + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle()) + "<br>");
    task.setTitle(
        "A new content titled: "
            + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle())
            + " has been posted.");
    task.setDescription(
        "A new content titled \""
            + UtilHTML.escapeHTMLSpecialChars(contentlet.getTitle().trim())
            + "\" has been posted by "
            + UtilHTML.escapeHTMLSpecialChars(user.getFullName())
            + " ("
            + user.getEmailAddress()
            + ")");
    changeHist.append(
        "Description: " + UtilHTML.escapeHTMLSpecialChars(task.getDescription()) + "<br>");

    Role role = roleAPI.loadRoleByKey(moderatorRole);
    task.setBelongsTo(role.getId());
    task.setAssignedTo("Nobody");
    task.setModDate(new Date());
    task.setCreationDate(new Date());
    task.setCreatedBy(user.getUserId());

    task.setStatus(WorkflowStatuses.OPEN.toString());
    changeHist.append("Due Date: " + UtilMethods.dateToHTMLDate(task.getDueDate()) + " -> <br>");
    task.setDueDate(null);
    task.setWebasset(contentlet.getInode());

    // HibernateUtil.saveOrUpdate(task);

    // Save the work flow comment
    WorkflowComment taskComment = new WorkflowComment();
    taskComment.setComment(task.getDescription());
    taskComment.setCreationDate(new Date());
    taskComment.setPostedBy(user.getUserId());
    HibernateUtil.saveOrUpdate(taskComment);
    relAPI.addRelationship(task.getInode(), taskComment.getInode(), "child");

    // Save the work flow history
    WorkflowHistory hist = new WorkflowHistory();
    hist.setChangeDescription("Task Creation");
    hist.setCreationDate(new Date());
    hist.setMadeBy(user.getUserId());
    HibernateUtil.saveOrUpdate(hist);
    relAPI.addRelationship(task.getInode(), hist.getInode(), "child");

    // WorkflowEmailUtil.sendWorkflowChangeEmails (task, "New user content has been submitted", "New
    // Task", null);

  }
예제 #15
0
  /**
   * 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;
  }
예제 #16
0
  public Map<String, Object> getEvent(String id, boolean live)
      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;

    Event ev = eventAPI.find(id, live, user, respectFrontendRoles);

    Map<String, Object> eventMap = ev.getMap();

    // Loading categories
    List<Map<String, Object>> categoryMaps = new ArrayList<Map<String, Object>>();
    List<Category> eventCategories = categoryAPI.getParents(ev, user, respectFrontendRoles);
    for (Category cat : eventCategories) {
      categoryMaps.add(cat.getMap());
    }
    eventMap.put("categories", categoryMaps);
    eventMap.put("rating", RatingAPI.getAverageRating(ev.getIdentifier()));
    eventMap.put("votes", RatingAPI.getRatingVotesNumber(ev.getIdentifier()));
    eventMap.put(
        "hasReadPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles));
    eventMap.put(
        "hasWritePermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles));
    eventMap.put(
        "hasPublishPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles));
    eventMap.put(
        "readPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_READ, user, respectFrontendRoles));
    eventMap.put(
        "writePermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_WRITE, user, respectFrontendRoles));
    eventMap.put(
        "publishPermission",
        perAPI.doesUserHavePermission(
            ev, PermissionAPI.PERMISSION_PUBLISH, user, respectFrontendRoles));
    eventMap.put("isDisconnected", UtilMethods.isSet(ev.getDisconnectedFrom()));
    CommentsWebAPI cAPI = new CommentsWebAPI();
    cAPI.setUser(user);
    cAPI.setRespectFrontendRoles(respectFrontendRoles);
    eventMap.put("commentsCount", cAPI.getCommentsCount(ev.getInode()));

    return eventMap;
  }
  private void _deleteScheduler(
      ActionRequest req, ActionResponse res, PortletConfig config, ActionForm form, User user)
      throws Exception {
    ContentImporterForm contentImporterForm = (ContentImporterForm) form;

    if (UtilMethods.isSet(contentImporterForm.getJobGroup()))
      QuartzUtils.removeJob(contentImporterForm.getJobName(), contentImporterForm.getJobGroup());
    else QuartzUtils.removeJob(req.getParameter("name"), req.getParameter("group"));

    SessionMessages.add(req, "message", "message.Scheduler.delete");
  }
예제 #18
0
  /**
   * 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());
      }
    }
  }
  public void init() {
    String file = getInitParameter("log4j-init-file");
    String path = null;
    try {
      path = new ClassPathResource("log4j.xml").getFile().getPath();
    } catch (IOException e) {
      Logger.error(Log4JInitializationServlet.class, e.getMessage(), e);
    }

    // if the log4j-init-file is not set, then no point in trying
    if (file != null && UtilMethods.isSet(path)) {
      PropertyConfigurator.configure(path);
    }
  }
예제 #20
0
  @SuppressWarnings("unchecked")
  public File saveFile(
      File newFile, java.io.File dataFile, Folder parentFolder, Identifier identifier)
      throws DotDataException {

    boolean localTransation = false;

    try {
      localTransation = DbConnectionFactory.getConnection().getAutoCommit();
      if (localTransation) {
        HibernateUtil.startTransaction();
      }
      // old working file
      File oldFile = null;
      // if new identifier
      if (identifier == null || !InodeUtils.isSet(identifier.getInode())) {
        identifier = APILocator.getIdentifierAPI().createNew(newFile, parentFolder);
        newFile.setIdentifier(identifier.getInode());
        HibernateUtil.save(newFile);
        APILocator.getVersionableAPI().setWorking(newFile);
        saveFileData(newFile, null, dataFile);
      } else {
        APILocator.getVersionableAPI().removeLive(identifier.getId());
      }
      if (UtilMethods.isSet(dataFile)) {
        HibernateUtil.save(newFile);
        saveFileData(newFile, null, dataFile);
      }
      if (oldFile != null && InodeUtils.isSet(oldFile.getInode())) {
        APILocator.getFileAPI().invalidateCache(oldFile);
        fileCache.remove(oldFile);
        WorkingCache.removeAssetFromCache(oldFile);
      }
      LiveCache.removeAssetFromCache(newFile);
      if (newFile.isLive()) {
        LiveCache.addToLiveAssetToCache(newFile);
      }
      WorkingCache.addToWorkingAssetToCache(newFile);

      if (localTransation) {
        HibernateUtil.commitTransaction();
      }
    } catch (Exception e) {
      if (localTransation) {
        HibernateUtil.rollbackTransaction();
      }
      throw new DotDataException(e.getMessage(), e);
    }
    return newFile;
  }
예제 #21
0
 public Map<String, Object> fetchTemplateImage(String id)
     throws DotDataException, DotSecurityException {
   Map<String, Object> toReturn = new HashMap<String, Object>();
   Template template = null;
   try {
     template =
         templateAPI.findWorkingTemplate(id, APILocator.getUserAPI().getSystemUser(), false);
   } catch (DotSecurityException e) {
     Logger.error(this, e.getMessage());
   }
   if (template != null) {
     Identifier imageIdentifier = APILocator.getIdentifierAPI().find(template.getImage());
     if (UtilMethods.isSet(imageIdentifier.getAssetType())
         && imageIdentifier.getAssetType().equals("contentlet")) {
       Contentlet imageContentlet = TemplateFactory.getImageContentlet(template);
       if (imageContentlet != null) {
         toReturn.put("inode", imageContentlet.getInode());
         toReturn.put("name", imageContentlet.getTitle());
         toReturn.put("identifier", imageContentlet.getIdentifier());
         toReturn.put(
             "extension",
             com.dotmarketing.util.UtilMethods.getFileExtension(imageContentlet.getTitle()));
       }
     } else {
       File imgFile = TemplateFactory.getImageFile(template);
       if (imgFile != null) {
         toReturn.put("inode", imgFile.getInode());
         toReturn.put("name", imgFile.getFileName());
         toReturn.put("identifier", imgFile.getIdentifier());
         toReturn.put(
             "extension",
             com.dotmarketing.util.UtilMethods.getFileExtension(imgFile.getFileName()));
       }
     }
   }
   return toReturn;
 }
  private Map<String, String> getSchedulerProperties(
      ActionRequest req, ContentImporterForm contentImporterForm) {
    Map<String, String> properties = new HashMap<String, String>(5);
    Enumeration<String> propertiesNames = req.getParameterNames();

    if (UtilMethods.isSet(contentImporterForm.getMap())) {
      properties = contentImporterForm.getMap();
    } else {
      String propertyName;
      String propertyValue;

      for (; propertiesNames.hasMoreElements(); ) {
        propertyName = propertiesNames.nextElement();
        if (propertyName.startsWith("propertyName")) {
          propertyValue = req.getParameter("propertyValue" + propertyName.substring(12));

          if (UtilMethods.isSet(req.getParameter(propertyName)) && UtilMethods.isSet(propertyValue))
            properties.put(req.getParameter(propertyName), propertyValue);
        }
      }
    }

    return properties;
  }
예제 #23
0
  public ActionErrors validate(ActionMapping mapping, HttpServletRequest request) {
    if (request.getParameter("cmd") != null && request.getParameter("cmd").equals(Constants.ADD)) {

      ActionErrors ae = super.validate(mapping, request);

      if (!UtilMethods.isSet(mailingList) && !UtilMethods.isSet(userFilterInode)) {
        ae.add(ActionMessages.GLOBAL_MESSAGE, new ActionMessage("Please-select-a-Mailing-List"));
      }

      if ((UtilMethods.isSet(webExpirationDate)) && (expirationDate == null)) {
        ae.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.campaign.error.expiration.date.incomplete"));
      }
      if (expirationDate != null && (expirationDate.before(new Date()))) {
        ae.add(
            ActionMessages.GLOBAL_MESSAGE,
            new ActionMessage("message.campaign.error.wrong.expiration.date"));
      }

      return ae;
    }
    return null;
  }
예제 #24
0
  public List<Map<String, Object>> findEventsForDay(
      String hostId,
      String dateStr,
      String[] tags,
      String[] keywords,
      String[] categoriesInodes,
      boolean live,
      boolean includeArchived,
      int offset,
      int limit)
      throws DotDataException, DotSecurityException, PortalException, SystemException,
          java.text.ParseException {

    Date fromDate = null;
    Date toDate = null;
    if (UtilMethods.isSet(dateStr)) {
      String date = dateFormat.format(dateFormat2.parse(dateStr));
      fromDate = dateFormat.parse(date);
    }

    Calendar fromDateCal = Calendar.getInstance();
    Calendar toDateCal = Calendar.getInstance();
    fromDateCal.setTime(fromDate);
    toDateCal.setTime(fromDate);

    fromDateCal.set(Calendar.HOUR, 0);
    fromDateCal.set(Calendar.MINUTE, 0);
    fromDateCal.set(Calendar.SECOND, 0);

    toDateCal.set(Calendar.HOUR, 23);
    toDateCal.set(Calendar.MINUTE, 59);
    toDateCal.set(Calendar.SECOND, 59);

    fromDate = fromDateCal.getTime();
    toDate = toDateCal.getTime();

    return findEventsByHostId(
        hostId,
        fromDate,
        toDate,
        tags,
        keywords,
        categoriesInodes,
        live,
        includeArchived,
        offset,
        limit);
  }
예제 #25
0
  /**
   * Save the file uploaded
   *
   * @param user the user that save the file
   * @param host Current host
   * @param uploadedFile
   * @param folder The folder where the file is going to be save
   * @param title The filename
   * @return File
   * @throws Exception
   */
  @SuppressWarnings("unchecked")
  private static FileAsset saveFile(
      User user, Host host, java.io.File uploadedFile, String folderPath, String title)
      throws Exception {

    Folder folder = APILocator.getFolderAPI().findFolderByPath(folderPath, host, user, false);
    if (!UtilMethods.isSet(folder.getInode())) {
      User systemUser = APILocator.getUserAPI().getSystemUser();
      folder =
          APILocator.getFolderAPI()
              .createFolders(folderPath, host, APILocator.getUserAPI().getSystemUser(), false);
    }

    byte[] bytes = FileUtil.getBytes(uploadedFile);

    if (bytes != null) {
      String newFileName = "";
      String name = UtilMethods.getFileName(title);
      int counter = 1;
      String fileName = name + "." + UtilMethods.getFileExtension(title);
      while (APILocator.getFileAPI().fileNameExists(folder, fileName)) {
        newFileName = name + "(" + counter + ")";
        fileName = newFileName + "." + UtilMethods.getFileExtension(title);
        counter++;
      }
      while (APILocator.getFileAssetAPI().fileNameExists(host, folder, name, "")) {
        newFileName = name + "(" + counter + ")";
        fileName = newFileName + "." + UtilMethods.getFileExtension(title);
        counter++;
      }
      if (UtilMethods.isSet(newFileName)) {
        name = newFileName;
      }
      Contentlet cont = new Contentlet();
      cont.setStructureInode(folder.getDefaultFileType());
      cont.setStringProperty(FileAssetAPI.TITLE_FIELD, UtilMethods.getFileName(name));
      cont.setFolder(folder.getInode());
      cont.setHost(host.getIdentifier());
      cont.setBinary(FileAssetAPI.BINARY_FIELD, uploadedFile);
      if (StructureCache.getStructureByInode(cont.getStructureInode()).getStructureType()
          == Structure.STRUCTURE_TYPE_FILEASSET) cont.setStringProperty("fileName", title);
      cont = APILocator.getContentletAPI().checkin(cont, user, false);
      if (APILocator.getPermissionAPI()
          .doesUserHavePermission(cont, PermissionAPI.PERMISSION_PUBLISH, user))
        APILocator.getVersionableAPI().setLive(cont);
      return APILocator.getFileAssetAPI().fromContentlet(cont);
    }

    return null;
  }
예제 #26
0
  public void unarchiveEvent(String identifier)
      throws PortalException, SystemException, DotDataException, DotSecurityException {
    HibernateUtil.startTransaction();
    WebContext ctx = WebContextFactory.get();
    HttpServletRequest request = ctx.getHttpServletRequest();

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

    Event ev = eventAPI.find(identifier, false, user, respectFrontendRoles);
    try {

      if (UtilMethods.isSet(ev.getDisconnectedFrom())) {
        Event baseEvent = null;
        try {
          baseEvent = eventAPI.find(ev.getDisconnectedFrom(), false, user, respectFrontendRoles);
        } catch (Exception e) {
          Logger.error(this, "Base event not found");
        }
        if (baseEvent != null) {
          try {
            Date originalStartDate = ev.getOriginalStartDate();
            baseEvent.addDateToIgnore(originalStartDate);
            APILocator.getContentletAPI()
                .checkin(
                    baseEvent,
                    categoryAPI.getParents(baseEvent, user, true),
                    perAPI.getPermissions(baseEvent),
                    user,
                    false);
          } catch (Exception e) {
            Logger.error(this, "Could not delete event from recurrence");
          }
        }
      }
      contAPI.unarchive(ev, user, respectFrontendRoles);

    } catch (Exception e) {
      Logger.error(this, e.getMessage());
    }

    HibernateUtil.commitTransaction();
    if (!contAPI.isInodeIndexed(ev.getInode())) {
      Logger.error(this, "Timed out while waiting for index to return");
    }
  }
예제 #27
0
  public String get(String key, String languageId) {
    String value = null;
    try {
      Language lang = langAPI.getLanguage(languageId);
      value = langAPI.getStringKey(lang, key);

      if ((!UtilMethods.isSet(value) || value.equals(key))
          && Config.getBooleanProperty("DEFAULT_CONTENT_TO_DEFAULT_LANGUAGE")) {
        lang = langAPI.getDefaultLanguage();
        value = langAPI.getStringKey(lang, key);
      }
    } catch (Exception e) {
      Logger.error(this, e.toString());
    }

    return (value == null) ? "" : value;
  }
예제 #28
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;
  }
  public String getErrorMessage(Exception e) {
    java.io.StringWriter sw = new StringWriter();
    VelocityEngine ve = VelocityUtil.getEngine();
    VelocityContext context = new VelocityContext();

    context.put("veloError", e);

    context.put("prettyError", UtilMethods.htmlifyString(e.toString()));
    org.apache.velocity.Template template;
    try {
      template = ve.getTemplate(errorTemplate);
      context.put("error", this);
      template.merge(context, sw);
    } catch (Exception ex) {
      Logger.error(this.getClass(), "Unable to show velocityError", ex);
    }
    return sw.toString();
  }
예제 #30
0
  /**
   * Get the user if the user is not logged return default AnonymousUser
   *
   * @param userId The userId
   * @return User
   * @exception DotDataException
   */
  public static User getUserFromId(String userId) throws DotDataException {
    User user = null;
    try {
      if (UtilMethods.isSet(userId)) {

        user =
            APILocator.getUserAPI()
                .loadUserById(userId, APILocator.getUserAPI().getSystemUser(), true);

      } else {
        user = APILocator.getUserAPI().getAnonymousUser();
      }
    } catch (NoSuchUserException e) {
      Logger.error(SubmitContentUtil.class, e.getMessage(), e);
    } catch (DotSecurityException e) {
      Logger.error(SubmitContentUtil.class, e.getMessage(), e);
    }
    return user;
  }