/**
   * Add all the specified people to the list of email recipients, and send it
   *
   * @param c Context
   * @param epeople Eperson[] of recipients
   * @param email Email object containing the message
   */
  private static void emailRecipients(Context c, EPerson[] epa, Email email)
      throws SQLException, MessagingException {
    for (int i = 0; i < epa.length; i++) {
      email.addRecipient(epa[i].getEmail());
    }

    email.send();
  }
  protected void notifyOfReject(
      Context context, BasicWorkflowItem workflowItem, EPerson e, String reason) {
    try {
      // Get the item title
      String title = getItemTitle(workflowItem);

      // Get the collection
      Collection coll = workflowItem.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(workflowItem.getSubmitter().getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(getMyDSpaceLink());

      email.send();
    } catch (RuntimeException re) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + re.getMessage()));

      throw re;
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              context,
              "notify_of_reject",
              "cannot email user eperson_id="
                  + e.getID()
                  + " eperson_email="
                  + e.getEmail()
                  + " workflow_item_id="
                  + workflowItem.getID()
                  + ":  "
                  + ex.getMessage()));
    }
  }
  @Override
  public void alertUsersOnTaskActivation(
      Context c, XmlWorkflowItem wfi, String emailTemplate, List<EPerson> epa, String... arguments)
      throws IOException, SQLException, MessagingException {
    if (noEMail.containsKey(wfi.getItem().getID())) {
      // suppress email, and delete key
      noEMail.remove(wfi.getItem().getID());
    } else {
      Email mail = Email.getEmail(I18nUtil.getEmailFilename(c.getCurrentLocale(), emailTemplate));
      for (String argument : arguments) {
        mail.addArgument(argument);
      }
      for (EPerson anEpa : epa) {
        mail.addRecipient(anEpa.getEmail());
      }

      mail.send();
    }
  }
  // send notices of curation activity
  @Override
  public void notifyOfCuration(
      Context c,
      BasicWorkflowItem wi,
      List<EPerson> ePeople,
      String taskName,
      String action,
      String message)
      throws SQLException, IOException {
    try {
      // Get the item title
      String title = getItemTitle(wi);

      // Get the submitter's name
      String submitter = getSubmitterName(wi);

      // Get the collection
      Collection coll = wi.getCollection();

      for (EPerson epa : ePeople) {
        Locale supportedLocale = I18nUtil.getEPersonLocale(epa);
        Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "flowtask_notify"));
        email.addArgument(title);
        email.addArgument(coll.getName());
        email.addArgument(submitter);
        email.addArgument(taskName);
        email.addArgument(message);
        email.addArgument(action);
        email.addRecipient(epa.getEmail());
        email.send();
      }
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              c,
              "notifyOfCuration",
              "cannot email users of workflow_item_id " + wi.getID() + ":  " + e.getMessage()));
    }
  }
  protected void notifyOfReject(Context c, XmlWorkflowItem wi, EPerson e, String reason) {
    try {
      // Get the item title
      String title = wi.getItem().getName();

      // Get the collection
      Collection coll = wi.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(wi.getSubmitter().getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(ConfigurationManager.getProperty("dspace.url") + "/mydspace");

      email.send();
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              c,
              "notify_of_reject",
              "cannot email user"
                  + " eperson_id"
                  + e.getID()
                  + " eperson_email"
                  + e.getEmail()
                  + " workflow_item_id"
                  + wi.getID()));
    }
  }
  private static void notifyOfReject(Context c, WorkflowItem wi, EPerson e, String reason) {
    try {
      // Get the item title
      String title = getItemTitle(wi);

      // Get the collection
      Collection coll = wi.getCollection();

      // Get rejector's name
      String rejector = getEPersonName(e);
      Locale supportedLocale = I18nUtil.getEPersonLocale(e);
      Email email =
          ConfigurationManager.getEmail(
              I18nUtil.getEmailFilename(supportedLocale, "submit_reject"));

      email.addRecipient(getSubmitterEPerson(wi).getEmail());
      email.addArgument(title);
      email.addArgument(coll.getMetadata("name"));
      email.addArgument(rejector);
      email.addArgument(reason);
      email.addArgument(getMyDSpaceLink());

      email.send();
    } catch (Exception ex) {
      // log this email error
      log.warn(
          LogManager.getHeader(
              c,
              "notify_of_reject",
              "cannot email user"
                  + " eperson_id"
                  + e.getID()
                  + " eperson_email"
                  + e.getEmail()
                  + " workflow_item_id"
                  + wi.getID()));
    }
  }
  /**
   * notify the submitter that the item is archived
   *
   * @param context The relevant DSpace Context.
   * @param item which item was archived
   * @param coll collection name to display in template
   * @throws SQLException An exception that provides information on a database access error or other
   *     errors.
   * @throws IOException A general class of exceptions produced by failed or interrupted I/O
   *     operations.
   */
  protected void notifyOfArchive(Context context, Item item, Collection coll)
      throws SQLException, IOException {
    try {
      // Get submitter
      EPerson ep = item.getSubmitter();
      // Get the Locale
      Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));

      // Get the item handle to email to user
      String handle = handleService.findHandle(context, item);

      // Get title
      List<MetadataValue> titles =
          itemService.getMetadata(item, MetadataSchema.DC_SCHEMA, "title", null, Item.ANY);
      String title = "";
      try {
        title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled");
      } catch (MissingResourceException e) {
        title = "Untitled";
      }
      if (titles.size() > 0) {
        title = titles.iterator().next().getValue();
      }

      email.addRecipient(ep.getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(handleService.getCanonicalForm(handle));

      email.send();
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              context, "notifyOfArchive", "cannot email user" + " item_id=" + item.getID()));
    }
  }
  /** notify the submitter that the item is archived */
  protected void notifyOfArchive(Context context, Item item, Collection coll)
      throws SQLException, IOException {
    try {
      // Get submitter
      EPerson ep = item.getSubmitter();
      // Get the Locale
      Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
      Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));

      // Get the item handle to email to user
      String handle = handleService.findHandle(context, item);

      // Get title
      String title = item.getName();
      if (StringUtils.isBlank(title)) {
        try {
          title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled");
        } catch (MissingResourceException e) {
          title = "Untitled";
        }
      }

      email.addRecipient(ep.getEmail());
      email.addArgument(title);
      email.addArgument(coll.getName());
      email.addArgument(handleService.getCanonicalForm(handle));

      email.send();
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              context,
              "notifyOfArchive",
              "cannot email user; item_id=" + item.getID() + ":  " + e.getMessage()));
    }
  }
  /** notify the submitter that the item is archived */
  private static void notifyOfArchive(Context c, Item i, Collection coll)
      throws SQLException, IOException {
    try {
      // Get submitter
      EPerson ep = i.getSubmitter();
      // Get the Locale
      Locale supportedLocale = I18nUtil.getEPersonLocale(ep);
      Email email =
          ConfigurationManager.getEmail(
              I18nUtil.getEmailFilename(supportedLocale, "submit_archive"));

      // Get the item handle to email to user
      String handle = HandleManager.findHandle(c, i);

      // Get title
      DCValue[] titles = i.getDC("title", null, Item.ANY);
      String title = "";
      try {
        title = I18nUtil.getMessage("org.dspace.workflow.WorkflowManager.untitled");
      } catch (MissingResourceException e) {
        title = "Untitled";
      }
      if (titles.length > 0) {
        title = titles[0].value;
      }

      email.addRecipient(ep.getEmail());
      email.addArgument(title);
      email.addArgument(coll.getMetadata("name"));
      email.addArgument(HandleManager.getCanonicalForm(handle));

      email.send();
    } catch (MessagingException e) {
      log.warn(
          LogManager.getHeader(
              c, "notifyOfArchive", "cannot email user" + " item_id=" + i.getID()));
    }
  }
  /**
   * Sends an email to the given e-person with details of new items in the given dspace object (MUST
   * be a community or a collection), items that appeared yesterday. No e-mail is sent if there
   * aren't any new items in any of the dspace objects.
   *
   * @param context DSpace context object
   * @param eperson eperson to send to
   * @param rpkeys List of DSpace Objects
   * @param test
   * @throws SearchServiceException
   */
  public static void sendEmail(
      Researcher researcher,
      Context context,
      EPerson eperson,
      List<String> rpkeys,
      boolean test,
      List<String> relationFields)
      throws IOException, MessagingException, SQLException, SearchServiceException {

    CrisSearchService searchService = researcher.getCrisSearchService();

    // Get a resource bundle according to the eperson language preferences
    Locale supportedLocale = I18nUtil.getEPersonLocale(eperson);

    StringBuffer emailText = new StringBuffer();
    boolean isFirst = true;

    for (String rpkey : rpkeys) {
      SolrQuery query = new SolrQuery();
      query.setFields("search.resourceid");
      query.addFilterQuery(
          "{!field f=search.resourcetype}" + Constants.ITEM, "{!field f=inarchive}true");

      for (String tmpRelations : relationFields) {
        String fq = "{!field f=" + tmpRelations + "}" + rpkey;
        query.addFilterQuery(fq);
      }

      query.setRows(Integer.MAX_VALUE);

      if (ConfigurationManager.getBooleanProperty("eperson.subscription.onlynew", false)) {
        // get only the items archived yesterday
        query.setQuery("dateaccessioned:(NOW/DAY-1DAY)");
      } else {
        // get all item modified yesterday but not published the day
        // before
        // and all the item modified today and archived yesterday
        query.setQuery(
            "(item.lastmodified:(NOW/DAY-1DAY) AND dateaccessioned:(NOW/DAY-1DAY)) OR ((item.lastmodified:(NOW/DAY) AND dateaccessioned:(NOW/DAY-1DAY)))");
      }

      QueryResponse qResponse = searchService.search(query);
      SolrDocumentList results = qResponse.getResults();

      // Only add to buffer if there are new items
      if (results.getNumFound() > 0) {

        if (!isFirst) {
          emailText.append("\n---------------------------------------\n");
        } else {
          isFirst = false;
        }

        emailText
            .append(I18nUtil.getMessage("org.dspace.eperson.Subscribe.new-items", supportedLocale))
            .append(" ")
            .append(rpkey)
            .append(": ")
            .append(results.getNumFound())
            .append("\n\n");

        for (SolrDocument solrDoc : results) {

          Item item = Item.find(context, (Integer) solrDoc.getFieldValue("search.resourceid"));

          DCValue[] titles = item.getDC("title", null, Item.ANY);
          emailText
              .append("      ")
              .append(I18nUtil.getMessage("org.dspace.eperson.Subscribe.title", supportedLocale))
              .append(" ");

          if (titles.length > 0) {
            emailText.append(titles[0].value);
          } else {
            emailText.append(
                I18nUtil.getMessage("org.dspace.eperson.Subscribe.untitled", supportedLocale));
          }

          DCValue[] authors = item.getDC("contributor", Item.ANY, Item.ANY);

          if (authors.length > 0) {
            emailText
                .append("\n    ")
                .append(
                    I18nUtil.getMessage("org.dspace.eperson.Subscribe.authors", supportedLocale))
                .append(" ")
                .append(authors[0].value);

            for (int k = 1; k < authors.length; k++) {
              emailText.append("\n             ").append(authors[k].value);
            }
          }

          emailText
              .append("\n         ")
              .append(I18nUtil.getMessage("org.dspace.eperson.Subscribe.id", supportedLocale))
              .append(" ")
              .append(HandleManager.getCanonicalForm(item.getHandle()))
              .append("\n\n");
          context.removeCached(item, item.getID());
        }
      }
    }

    // Send an e-mail if there were any new items
    if (emailText.length() > 0) {

      if (test) {
        log.info(LogManager.getHeader(context, "subscription:", "eperson=" + eperson.getEmail()));
        log.info(LogManager.getHeader(context, "subscription:", "text=" + emailText.toString()));

      } else {

        Email email =
            ConfigurationManager.getEmail(
                I18nUtil.getEmailFilename(supportedLocale, "subscription"));
        email.addRecipient(eperson.getEmail());
        email.addArgument(emailText.toString());
        email.send();

        log.info(
            LogManager.getHeader(context, "sent_subscription", "eperson_id=" + eperson.getID()));
      }
    }
  }
  private static void notifyGroupOfTask(Context c, WorkflowItem wi, Group mygroup, EPerson[] epa)
      throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    Integer myID = new Integer(wi.getItem().getID());

    if (noEMail.containsKey(myID)) {
      // suppress email, and delete key
      noEMail.remove(myID);
    } else {
      try {
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        String message = "";

        for (int i = 0; i < epa.length; i++) {
          Locale supportedLocale = I18nUtil.getEPersonLocale(epa[i]);
          Email email =
              ConfigurationManager.getEmail(
                  I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
          email.addArgument(title);
          email.addArgument(coll.getMetadata("name"));
          email.addArgument(submitter);

          ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
          log.info("Locale des Resource Bundles: " + messages.getLocale().getDisplayName());
          switch (wi.getState()) {
            case WFSTATE_STEP1POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

              break;

            case WFSTATE_STEP2POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

              break;

            case WFSTATE_STEP3POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

              break;
          }
          email.addArgument(message);
          email.addArgument(getMyDSpaceLink());
          email.addRecipient(epa[i].getEmail());
          email.send();
        }
      } catch (MessagingException e) {
        log.warn(
            LogManager.getHeader(
                c,
                "notifyGroupofTask",
                "cannot email user"
                    + " group_id"
                    + mygroup.getID()
                    + " workflow_item_id"
                    + wi.getID()));
      }
    }
  }
  protected void notifyGroupOfTask(
      Context c, BasicWorkflowItem wi, Group mygroup, List<EPerson> epa)
      throws SQLException, IOException {
    // check to see if notification is turned off
    // and only do it once - delete key after notification has
    // been suppressed for the first time
    UUID myID = wi.getItem().getID();

    if (noEMail.containsKey(myID)) {
      // suppress email, and delete key
      noEMail.remove(myID);
    } else {
      try {
        // Get the item title
        String title = getItemTitle(wi);

        // Get the submitter's name
        String submitter = getSubmitterName(wi);

        // Get the collection
        Collection coll = wi.getCollection();

        String message = "";

        for (EPerson anEpa : epa) {
          Locale supportedLocale = I18nUtil.getEPersonLocale(anEpa);
          Email email = Email.getEmail(I18nUtil.getEmailFilename(supportedLocale, "submit_task"));
          email.addArgument(title);
          email.addArgument(coll.getName());
          email.addArgument(submitter);

          ResourceBundle messages = ResourceBundle.getBundle("Messages", supportedLocale);
          switch (wi.getState()) {
            case WFSTATE_STEP1POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step1");

              break;

            case WFSTATE_STEP2POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step2");

              break;

            case WFSTATE_STEP3POOL:
              message = messages.getString("org.dspace.workflow.WorkflowManager.step3");

              break;
          }
          email.addArgument(message);
          email.addArgument(getMyDSpaceLink());
          email.addRecipient(anEpa.getEmail());
          email.send();
        }
      } catch (MessagingException e) {
        String gid = (mygroup != null) ? String.valueOf(mygroup.getID()) : "none";
        log.warn(
            LogManager.getHeader(
                c,
                "notifyGroupofTask",
                "cannot email user group_id="
                    + gid
                    + " workflow_item_id="
                    + wi.getID()
                    + ":  "
                    + e.getMessage()));
      }
    }
  }
  public Map act(
      Redirector redirector,
      SourceResolver resolver,
      Map objectModel,
      String source,
      Parameters parameters)
      throws Exception {
    Request request = ObjectModelHelper.getRequest(objectModel);

    String requesterName = request.getParameter("requesterName");
    String requesterEmail = request.getParameter("requesterEmail");
    String allFiles = request.getParameter("allFiles");
    String message = request.getParameter("message");
    String bitstreamId = request.getParameter("bitstreamId");

    // User email from context
    Context context = ContextUtil.obtainContext(objectModel);
    EPerson loggedin = context.getCurrentUser();
    String eperson = null;
    if (loggedin != null) {
      eperson = loggedin.getEmail();
    }

    // Check all data is there
    if (StringUtils.isEmpty(requesterName)
        || StringUtils.isEmpty(requesterEmail)
        || StringUtils.isEmpty(allFiles)
        || StringUtils.isEmpty(message)) {
      // Either the user did not fill out the form or this is the
      // first time they are visiting the page.
      Map<String, String> map = new HashMap<String, String>();
      map.put("bitstreamId", bitstreamId);

      if (StringUtils.isEmpty(requesterEmail)) {
        map.put("requesterEmail", eperson);
      } else {
        map.put("requesterEmail", requesterEmail);
      }
      map.put("requesterName", requesterName);
      map.put("allFiles", allFiles);
      map.put("message", message);
      return map;
    }
    DSpaceObject dso = HandleUtil.obtainHandle(objectModel);
    if (!(dso instanceof Item)) {
      throw new Exception("Invalid DspaceObject at ItemRequest.");
    }

    Item item = (Item) dso;
    String title = "";
    Metadatum[] titleDC = item.getDC("title", null, Item.ANY);
    if (titleDC == null || titleDC.length == 0) {
      titleDC = item.getDC("title", Item.ANY, Item.ANY); // dc.title with qualifier term
    }
    if (titleDC != null && titleDC.length > 0) {
      title = titleDC[0].value;
    }

    RequestItemAuthor requestItemAuthor =
        new DSpace()
            .getServiceManager()
            .getServiceByName(
                RequestItemAuthorExtractor.class.getName(), RequestItemAuthorExtractor.class)
            .getRequestItemAuthor(context, item);

    RequestItem requestItem =
        new RequestItem(
            item.getID(),
            Integer.parseInt(bitstreamId),
            requesterEmail,
            requesterName,
            message,
            Boolean.getBoolean(allFiles));

    // All data is there, send the email
    Email email =
        Email.getEmail(
            I18nUtil.getEmailFilename(context.getCurrentLocale(), "request_item.author"));
    email.addRecipient(requestItemAuthor.getEmail());

    email.addArgument(requesterName);
    email.addArgument(requesterEmail);
    email.addArgument(
        allFiles.equals("true")
            ? I18nUtil.getMessage("itemRequest.all")
            : Bitstream.find(context, Integer.parseInt(bitstreamId)).getName());
    email.addArgument(HandleManager.getCanonicalForm(item.getHandle()));
    email.addArgument(title); // request item title
    email.addArgument(message); // message
    email.addArgument(getLinkTokenEmail(context, requestItem));
    email.addArgument(requestItemAuthor.getFullName()); //   corresponding author name
    email.addArgument(requestItemAuthor.getEmail()); //   corresponding author email
    email.addArgument(ConfigurationManager.getProperty("dspace.name"));
    email.addArgument(ConfigurationManager.getProperty("mail.helpdesk"));

    email.setReplyTo(requesterEmail);

    email.send();
    // Finished, allow to pass.
    return null;
  }
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    // Obtain information from request
    // The page where the user came from
    String fromPage = request.getHeader("Referer");

    // Prevent spammers and splogbots from poisoning the feedback page
    String host = ConfigurationManager.getProperty("dspace.hostname");

    String basicHost = "";
    if (host.equals("localhost")
        || host.equals("127.0.0.1")
        || host.equals(InetAddress.getLocalHost().getHostAddress())) basicHost = host;
    else {
      // cut off all but the hostname, to cover cases where more than one URL
      // arrives at the installation; e.g. presence or absence of "www"
      int lastDot = host.lastIndexOf(".");
      basicHost = host.substring(host.substring(0, lastDot).lastIndexOf("."));
    }

    if (fromPage == null || fromPage.indexOf(basicHost) == -1) {
      throw new AuthorizeException();
    }

    // The email address they provided
    String formEmail = request.getParameter("email");

    // Browser
    String userAgent = request.getHeader("User-Agent");

    // Session id
    String sessionID = request.getSession().getId();

    // User email from context
    EPerson currentUser = context.getCurrentUser();
    String authEmail = null;

    if (currentUser != null) {
      authEmail = currentUser.getEmail();
    }

    // Has the user just posted their feedback?
    if (request.getParameter("submit") != null) {
      EmailValidator ev = EmailValidator.getInstance();
      String feedback = request.getParameter("feedback");

      // Check all data is there
      if ((formEmail == null)
          || formEmail.equals("")
          || (feedback == null)
          || feedback.equals("")
          || !ev.isValid(formEmail)) {
        log.info(LogManager.getHeader(context, "show_feedback_form", "problem=true"));
        request.setAttribute("feedback.problem", new Boolean(true));
        JSPManager.showJSP(request, response, "/feedback/form.jsp");

        return;
      }

      // All data is there, send the email
      try {
        Email email =
            ConfigurationManager.getEmail(
                I18nUtil.getEmailFilename(context.getCurrentLocale(), "feedback"));
        email.addRecipient(ConfigurationManager.getProperty("feedback.recipient"));

        email.addArgument(new Date()); // Date
        email.addArgument(formEmail); // Email
        email.addArgument(authEmail); // Logged in as
        email.addArgument(fromPage); // Referring page
        email.addArgument(userAgent); // User agent
        email.addArgument(sessionID); // Session ID
        email.addArgument(feedback); // The feedback itself

        // Replying to feedback will reply to email on form
        email.setReplyTo(formEmail);

        email.send();

        log.info(LogManager.getHeader(context, "sent_feedback", "from=" + formEmail));

        JSPManager.showJSP(request, response, "/feedback/acknowledge.jsp");
      } catch (MessagingException me) {
        log.warn(LogManager.getHeader(context, "error_mailing_feedback", ""), me);

        JSPManager.showInternalError(request, response);
      }
    } else {
      // Display feedback form
      log.info(LogManager.getHeader(context, "show_feedback_form", "problem=false"));
      request.setAttribute("authenticated.email", authEmail);
      JSPManager.showJSP(request, response, "/feedback/form.jsp");
    }
  }
Example #15
0
  /**
   * Send an alert to the designated "alert recipient" - that is, when a database error or internal
   * error occurs, this person is sent an e-mail with details.
   *
   * <p>The recipient is configured via the "alert.recipient" property in <code>dspace.cfg</code>.
   * If this property is omitted, no alerts are sent.
   *
   * <p>This method "swallows" any exception that might occur - it will just be logged. This is
   * because this method will usually be invoked as part of an error handling routine anyway.
   *
   * @param request the HTTP request leading to the error
   * @param exception the exception causing the error, or null
   */
  public static void sendAlert(HttpServletRequest request, Exception exception) {
    String logInfo = UIUtil.getRequestLogInfo(request);
    Context c = (Context) request.getAttribute("dspace.context");
    Locale locale = getSessionLocale(request);
    EPerson user = null;

    try {
      String recipient = ConfigurationManager.getProperty("alert.recipient");

      if (recipient != null) {
        Email email =
            ConfigurationManager.getEmail(I18nUtil.getEmailFilename(locale, "internal_error"));
        email.addRecipient(recipient);
        email.addArgument(ConfigurationManager.getProperty("dspace.url"));
        email.addArgument(new Date());
        email.addArgument(request.getSession().getId());
        email.addArgument(logInfo);

        String stackTrace;

        if (exception != null) {
          StringWriter sw = new StringWriter();
          PrintWriter pw = new PrintWriter(sw);
          exception.printStackTrace(pw);
          pw.flush();
          stackTrace = sw.toString();
        } else {
          stackTrace = "No exception";
        }

        email.addArgument(stackTrace);
        try {
          user = c.getCurrentUser();
        } catch (Exception e) {
          log.warn("No context, the database might be down or the connection pool exhausted.");
        }

        if (user != null) {
          email.addArgument(user.getFullName() + " (" + user.getEmail() + ")");
        } else {
          email.addArgument("Anonymous");
        }
        email.addArgument(request.getRemoteAddr());
        email.send();
      }
    } catch (Exception e) {
      // Not much we can do here!
      log.warn("Unable to send email alert", e);
    }
  }
  protected void doDSGet(Context context, HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException, SQLException, AuthorizeException {
    ExternalIdentifierDAO identifierDAO = ExternalIdentifierDAOFactory.getInstance(context);

    // Obtain information from request
    String uri = request.getParameter("uri");
    ExternalIdentifier identifier = identifierDAO.retrieve(uri);
    ObjectIdentifier oi = identifier.getObjectIdentifier();

    // Lookup Item title & collection
    Item item = null;
    String link = "";
    String title = null;
    String collName = null;
    if (identifier != null) {
      item = (Item) oi.getObject(context);
      link = item.getIdentifier().getURL().toString();
      request.setAttribute("link", link);

      if (item != null) {
        DCValue[] titleDC = item.getDC("title", null, Item.ANY);
        if (titleDC != null || titleDC.length > 0) {
          title = titleDC[0].value;
        }
        Collection[] colls = item.getCollections();
        collName = colls[0].getMetadata("name");
      }
    } else {
      String path = request.getPathInfo();
      log.info(LogManager.getHeader(context, "invalid_id", "path=" + path));
      JSPManager.showInvalidIDError(request, response, path, -1);
      return;
    }
    if (title == null) {
      title = "";
    }
    if (collName == null) {
      collName = "";
    }
    request.setAttribute("suggest.title", title);

    // User email from context
    EPerson currentUser = context.getCurrentUser();
    String authEmail = null;
    String userName = null;

    if (currentUser != null) {
      authEmail = currentUser.getEmail();
      userName = currentUser.getFullName();
    }

    if (request.getParameter("submit") != null) {
      String recipAddr = request.getParameter("recip_email");
      // the only required field is recipient email address
      if (recipAddr == null || recipAddr.equals("")) {
        log.info(LogManager.getHeader(context, "show_suggest_form", "problem=true"));
        request.setAttribute("suggest.problem", new Boolean(true));
        JSPManager.showJSP(request, response, "/suggest/suggest.jsp");
        return;
      }
      String recipName = request.getParameter("recip_name");
      if (recipName == null || "".equals(recipName)) {
        try {
          recipName =
              I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.recipient", context);
        } catch (MissingResourceException e) {
          log.warn(
              LogManager.getHeader(
                  context,
                  "show_suggest_form",
                  "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender"));
          recipName = "colleague";
        }
      }
      String senderName = request.getParameter("sender_name");
      if (senderName == null || "".equals(senderName)) {
        // use userName if available
        if (userName != null) {
          senderName = userName;
        } else {
          try {
            senderName =
                I18nUtil.getMessage("org.dspace.app.webui.servlet.SuggestServlet.sender", context);
          } catch (MissingResourceException e) {
            log.warn(
                LogManager.getHeader(
                    context,
                    "show_suggest_form",
                    "Missing Resource: org.dspace.app.webui.servlet.SuggestServlet.sender"));
            senderName = "A DSpace User";
          }
        }
      }
      String senderAddr = request.getParameter("sender_email");
      if (senderAddr == null || "".equals(senderAddr)) {
        // use authEmail if available
        if (authEmail != null) {
          senderAddr = authEmail;
        }
      }
      String itemUri = identifier.getURI().toString();
      String message = request.getParameter("message");
      String siteName = ConfigurationManager.getProperty("dspace.name");

      // All data is there, send the email
      try {
        Email email =
            ConfigurationManager.getEmail(
                I18nUtil.getEmailFilename(context.getCurrentLocale(), "suggest"));
        email.addRecipient(recipAddr); // recipient address
        email.addArgument(recipName); // 1st arg - recipient name
        email.addArgument(senderName); // 2nd arg - sender name
        email.addArgument(siteName); // 3rd arg - repository name
        email.addArgument(title); // 4th arg - item title
        email.addArgument(itemUri); // 5th arg - item identifier URI
        email.addArgument(link); // 6th arg - item local URL
        email.addArgument(collName); // 7th arg - collection name
        email.addArgument(message); // 8th arg - user comments

        // Set sender's address as 'reply-to' address if supplied
        if (senderAddr != null && !"".equals(senderAddr)) {
          email.setReplyTo(senderAddr);
        }

        // Only actually send the email if feature is enabled
        if (ConfigurationManager.getBooleanProperty("webui.suggest.enable", false)) {
          email.send();
        } else {
          throw new MessagingException(
              "Suggest item email not sent - webui.suggest.enable = false");
        }

        log.info(LogManager.getHeader(context, "sent_suggest", "from=" + senderAddr));

        JSPManager.showJSP(request, response, "/suggest/suggest_ok.jsp");
      } catch (MessagingException me) {
        log.warn(LogManager.getHeader(context, "error_mailing_suggest", ""), me);
        JSPManager.showInternalError(request, response);
      }
    } else {
      // Display suggest form
      log.info(LogManager.getHeader(context, "show_suggest_form", "problem=false"));
      request.setAttribute("authenticated.email", authEmail);
      request.setAttribute("eperson.name", userName);
      JSPManager.showJSP(request, response, "/suggest/suggest.jsp"); // asd
    }
  }