/**
   * 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);

  }
  /**
   * Returns a JSON representation of the environments (with servers) that the Role with the given
   * roleid can push to <br>
   * Each Environment node contains: id, name.
   *
   * <p>Usage: /loadenvironments/{roleid}
   *
   * @throws JSONException
   */
  @GET
  @Path("/loadenvironments/{params:.*}")
  @Produces("application/json")
  public Response loadEnvironments(
      @Context HttpServletRequest request, @PathParam("params") String params)
      throws DotStateException, DotDataException, DotSecurityException, LanguageException,
          JSONException {

    InitDataObject initData = init(params, true, request, true);

    // Creating an utility response object
    ResourceResponse responseResource = new ResourceResponse(initData.getParamsMap());

    String roleId = initData.getParamsMap().get("roleid");

    // Using JsonArray instead of manually creating the json object
    JSONArray jsonEnvironments = new JSONArray();

    // First objects is expected to be blank
    JSONObject jsonEnvironmentFirst = new JSONObject();
    jsonEnvironmentFirst.put("id", "0");
    jsonEnvironmentFirst.put("name", "");

    jsonEnvironments.add(jsonEnvironmentFirst);

    Role role = APILocator.getRoleAPI().loadRoleById(roleId);
    User user = APILocator.getUserAPI().loadUserById(role.getRoleKey());
    boolean isAdmin = APILocator.getUserAPI().isCMSAdmin(user);

    List<Role> roles = APILocator.getRoleAPI().loadRolesForUser(user.getUserId(), true);
    Set<Environment> environments = new HashSet<Environment>();
    if (isAdmin) {
      List<Environment> app = APILocator.getEnvironmentAPI().findEnvironmentsWithServers();
      for (Environment e : app) environments.add(e);
    } else
      for (Role r : roles)
        environments.addAll(APILocator.getEnvironmentAPI().findEnvironmentsByRole(r.getId()));

    // For each env, create one json and add it to the array
    for (Environment e : environments) {

      JSONObject environmentBundle = new JSONObject();
      environmentBundle.put("id", e.getId());
      // Escape name for cases like: dotcms's
      environmentBundle.put("name", StringEscapeUtils.unescapeJava(e.getName()));

      jsonEnvironments.add(environmentBundle);
    }

    CacheControl cc = new CacheControl();
    cc.setNoCache(true);
    return Response.ok(jsonEnvironments.toString(), MediaType.APPLICATION_JSON_TYPE)
        .cacheControl(cc)
        .build();
  }
  /**
   * Returns a JSON representation of the environments that the Role with the given roleid can push
   * to <br>
   * Each Environment node contains: id, name.
   *
   * <p>Usage: /loadenvironments/{roleid}
   */
  @GET
  @Path("/loadenvironments/{params:.*}")
  @Produces("application/json")
  public String loadEnvironments(
      @Context HttpServletRequest request, @PathParam("params") String params)
      throws DotStateException, DotDataException, DotSecurityException, LanguageException {
    InitDataObject initData = init(params, true, request, true);

    String roleId = initData.getParamsMap().get("roleid");

    StringBuilder json = new StringBuilder();

    json.append("[");

    json.append("{id: '0', ");
    json.append("name: '' }, ");

    int environmentCounter = 0;

    Role role = APILocator.getRoleAPI().loadRoleById(roleId);
    User user = APILocator.getUserAPI().loadUserById(role.getRoleKey());
    boolean isAdmin = APILocator.getUserAPI().isCMSAdmin(user);

    List<Role> roles = APILocator.getRoleAPI().loadRolesForUser(user.getUserId(), true);
    Set<Environment> environments = new HashSet<Environment>();
    if (isAdmin) {
      List<Environment> app = APILocator.getEnvironmentAPI().findAllEnvironments();
      for (Environment e : app) environments.add(e);
    } else
      for (Role r : roles)
        environments.addAll(APILocator.getEnvironmentAPI().findEnvironmentsByRole(r.getId()));

    for (Environment e : environments) {

      json.append("{id: '").append(e.getId()).append("', ");
      json.append("name: '").append(e.getName()).append("' } ");

      if (environmentCounter + 1 < environments.size()) {
        json.append(", ");
      }

      environmentCounter++;
    }

    json.append("]");

    return json.toString();
  }
  private void createAccount(WebForm form, HttpServletRequest request) throws Exception {

    User user =
        APILocator.getUserAPI()
            .loadByUserByEmail(form.getEmail(), APILocator.getUserAPI().getSystemUser(), false);
    User defaultUser = APILocator.getUserAPI().getDefaultUser();
    Date today = new Date();

    if (user.isNew() || (!user.isNew() && user.getLastLoginDate() == null)) {

      // ### CREATE USER ###
      Company company = PublicCompanyFactory.getDefaultCompany();
      user.setEmailAddress(form.getEmail().trim().toLowerCase());
      user.setFirstName(form.getFirstName() == null ? "" : form.getFirstName());
      user.setMiddleName(form.getMiddleName() == null ? "" : form.getMiddleName());
      user.setLastName(form.getLastName() == null ? "" : form.getLastName());
      user.setNickName("");
      user.setCompanyId(company.getCompanyId());
      user.setPasswordEncrypted(true);
      user.setGreeting("Welcome, " + user.getFullName() + "!");

      // Set defaults values
      if (user.isNew()) {
        // if it's a new user we set random password
        String pass = PublicEncryptionFactory.getRandomPassword();
        user.setPassword(PublicEncryptionFactory.digestString(pass));
        user.setLanguageId(defaultUser.getLanguageId());
        user.setTimeZoneId(defaultUser.getTimeZoneId());
        user.setSkinId(defaultUser.getSkinId());
        user.setDottedSkins(defaultUser.isDottedSkins());
        user.setRoundedSkins(defaultUser.isRoundedSkins());
        user.setResolution(defaultUser.getResolution());
        user.setRefreshRate(defaultUser.getRefreshRate());
        user.setLayoutIds("");
        user.setActive(true);
        user.setCreateDate(today);
      }
      APILocator.getUserAPI().save(user, APILocator.getUserAPI().getSystemUser(), false);
      // ### END CREATE USER ###

      // ### CREATE USER_PROXY ###
      UserProxy userProxy =
          com.dotmarketing.business.APILocator.getUserProxyAPI()
              .getUserProxy(user.getUserId(), APILocator.getUserAPI().getSystemUser(), false);
      userProxy.setPrefix("");
      userProxy.setTitle(form.getTitle());
      userProxy.setOrganization(form.getOrganization());
      userProxy.setUserId(user.getUserId());
      com.dotmarketing.business.APILocator.getUserProxyAPI()
          .saveUserProxy(userProxy, APILocator.getUserAPI().getSystemUser(), false);
      // ### END CRETE USER_PROXY ###

      // saving user inode on web form
      form.setUserInode(userProxy.getInode());
      if (UtilMethods.isSet(form.getFormType())) {
        HibernateUtil.saveOrUpdate(form);
      }

      ///// WE CAN DO THIS! BUT WE NEED TO ADD CATEGORIES TO WEBFORM AND ALSO CHANGE THE PROCESSES
      // THAT
      //// CREATE THE EXCEL DOWNLOAD FROM WEB FORMS. I DIDN'T ADD IT SO I COMMENTED THIS CODE FOR
      // NOW
      // get the old categories, wipe them out
      /*
      List<Category> categories = InodeFactory.getParentsOfClass(userProxy, Category.class);
      for (int i = 0; i < categories.size(); i++) {
      	categories.get(i).deleteChild(userProxy);
      }
       */
      // Save the new categories
      /*String[] arr = form.getCategories();
      if (arr != null) {
      	for (int i = 0; i < arr.length; i++) {
      		Category node = (Category) InodeFactory.getInode(arr[i], Category.class);
      		node.addChild(userProxy);
      	}
      }*/

      // ### CREATE ADDRESS ###
      try {
        List<Address> addresses = PublicAddressFactory.getAddressesByUserId(user.getUserId());
        Address address =
            (addresses.size() > 0 ? addresses.get(0) : PublicAddressFactory.getInstance());
        address.setStreet1(form.getAddress1() == null ? "" : form.getAddress1());
        address.setStreet2(form.getAddress2() == null ? "" : form.getAddress2());
        address.setCity(form.getCity() == null ? "" : form.getCity());
        address.setState(form.getState() == null ? "" : form.getState());
        address.setZip(form.getZip() == null ? "" : form.getZip());
        String phone = form.getPhone();
        address.setPhone(phone == null ? "" : phone);
        address.setUserId(user.getUserId());
        address.setCompanyId(company.getCompanyId());
        PublicAddressFactory.save(address);
      } catch (Exception ex) {
        Logger.error(this, ex.getMessage(), ex);
      }

      Role defaultRole =
          com.dotmarketing.business.APILocator.getRoleAPI()
              .loadRoleByKey(Config.getStringProperty("CMS_VIEWER_ROLE"));
      String roleId = defaultRole.getId();
      if (InodeUtils.isSet(roleId)) {
        com.dotmarketing.business.APILocator.getRoleAPI().addRoleToUser(roleId, user);
      }
    }
    // ### END CREATE ADDRESS ###

    // ### BUILD THE USER COMMENT ###
    addUserComments(user.getUserId(), form, request);
    // ### END BUILD THE USER COMMENT ###

    /* associate user with their clickstream request */
    if (Config.getBooleanProperty("ENABLE_CLICKSTREAM_TRACKING", false)) {
      ClickstreamFactory.setClickStreamUser(user.getUserId(), request);
    }
  }