Ejemplo n.º 1
0
  public void printComment(
      SimplePageComment comment,
      UIContainer tofill,
      boolean highlight,
      boolean anonymous,
      boolean showModifiers,
      CommentsViewParameters params,
      SimplePageItem commentsItem,
      SimplePage currentPage) {
    if (canEditPage && itemToPageowner != null && comment.getItemId() != lastTitle) {
      UIBranchContainer commentContainer = UIBranchContainer.make(tofill, "commentList:");
      UIOutput.make(
          commentContainer,
          "commentTitle",
          messageLocator
              .getMessage("simplepage.comments-grading")
              .replace("{}", itemToPageowner.get(comment.getItemId())));
      lastTitle = comment.getItemId();
    }

    // print title if this is a comment on a different page. Normally this
    // shold only happen for subpages of student pages
    String pageTitle = null;
    if (currentPage.getPageId() != comment.getPageId()) {
      SimplePage commentPage = simplePageBean.getPage(comment.getPageId());
      pageTitle = commentPage.getTitle();
    }

    UIBranchContainer commentContainer = UIBranchContainer.make(tofill, "commentList:");
    UIOutput.make(commentContainer, "commentDiv");
    if (highlight) commentContainer.decorate(new UIStyleDecorator("highlight-comment"));

    if (!filter && params.author != null && params.author.equals(comment.getAuthor())) {
      commentContainer.decorate(new UIStyleDecorator("backgroundHighlight"));
    }

    String author;

    if (!anonymous) {
      try {
        User user = UserDirectoryService.getUser(comment.getAuthor());
        author = user.getDisplayName();
      } catch (Exception ex) {
        author = messageLocator.getMessage("simplepage.comment-unknown-user");
        ex.printStackTrace();
      }
    } else {
      author = anonymousLookup.get(comment.getAuthor());

      if (comment.getAuthor().equals(owner)) {
        author = messageLocator.getMessage("simplepage.comment-author-owner");
      }

      if (author == null) author = "Anonymous User"; // Shouldn't ever occur

      if (simplePageBean.getEditPrivs() == 0) {
        try {
          User user = UserDirectoryService.getUser(comment.getAuthor());
          author += " (" + user.getDisplayName() + ")";
        } catch (Exception ex) {
          author += " (" + messageLocator.getMessage("simplepage.comment-unknown-user") + ")";
        }
      } else if (comment.getAuthor().equals(currentUserId)) {
        author += " (" + messageLocator.getMessage("simplepage.comment-you") + ")";
      }
    }

    UIOutput authorOutput = UIOutput.make(commentContainer, "userId", author);

    if (comment.getAuthor().equals(currentUserId)) {
      authorOutput.decorate(new UIStyleDecorator("specialCommenter"));
      authorOutput.decorate(new UIStyleDecorator("personalComment"));
    } else if (comment.getAuthor().equals(owner)) {
      authorOutput.decorate(new UIStyleDecorator("specialCommenter"));
      authorOutput.decorate(new UIStyleDecorator("ownerComment"));
    }

    if (pageTitle != null) UIOutput.make(commentContainer, "pageTitle", pageTitle);

    String timeDifference = getTimeDifference(comment.getTimePosted().getTime());

    UIOutput.make(commentContainer, "timePosted", timeDifference);

    if (showModifiers) {
      UIOutput.make(commentContainer, "deleteSpan");

      CommentsViewParameters eParams = (CommentsViewParameters) params.copy();
      eParams.placementId = params.placementId;
      eParams.deleteComment = comment.getUUID();
      eParams.pageId = params.pageId;
      eParams.siteId = params.siteId;

      UIInternalLink.make(commentContainer, "deleteCommentURL", eParams);
      UIOutput.make(commentContainer, "deleteComment")
          .decorate(
              new UIFreeAttributeDecorator(
                  "title",
                  messageLocator.getMessage("simplepage.comment-delete").replace("{}", author)));
      UIOutput.make(commentContainer, "editComment")
          .decorate(
              new UIFreeAttributeDecorator("onclick", "edit($(this), " + comment.getId() + ");"))
          .decorate(
              new UIFreeAttributeDecorator(
                  "title",
                  messageLocator.getMessage("simplepage.comment-edit").replace("{}", author)));

      if (!filter && simplePageBean.getEditPrivs() == 0 && commentsItem.getGradebookId() != null) {
        UIOutput.make(commentContainer, "gradingSpan");
        UIOutput.make(commentContainer, "commentsUUID", comment.getUUID());
        UIOutput.make(
            commentContainer,
            "commentPoints",
            (comment.getPoints() == null ? "" : String.valueOf(comment.getPoints())));
        UIOutput.make(commentContainer, "pointsBox")
            .decorate(
                new UIFreeAttributeDecorator(
                    "title",
                    messageLocator
                        .getMessage("simplepage.grade-for-student")
                        .replace("{}", author)));

        UIOutput.make(commentContainer, "maxpoints", " / " + commentsItem.getGradebookPoints());
        UIOutput.make(commentContainer, "authorUUID", comment.getAuthor());
      }
    }

    if (filter && simplePageBean.getEditPrivs() == 0) {
      UIOutput.make(commentContainer, "contextSpan");

      // because this is called via /faces, the full Sakai context is not set up.
      // in particular, UIInternalLink will generate the wrong thing. Thus we
      // make up a full URL ourselves.
      String pars =
          "/portal/tool/"
              + URLEncoder.encode(params.placementId)
              + "/ShowPage?path=none"
              + "&author="
              + URLEncoder.encode(comment.getAuthor());
      // Need to provide the item ID
      if (!params.studentContentItem && params.pageItemId != -1L) {
        pars += "&itemId=" + URLEncoder.encode(Long.toString(params.pageItemId));
      }
      UILink contextLink =
          UILink.make(
              commentContainer,
              "contextLink",
              messageLocator.getMessage("simplepage.show-context"),
              pars);
      if (itemToPageowner == null)
        contextLink.decorate(
            new UIFreeAttributeDecorator(
                "title",
                messageLocator
                    .getMessage("simplepage.context-link-title-1")
                    .replace("{}", author)));
      else
        contextLink.decorate(
            new UIFreeAttributeDecorator(
                "title",
                messageLocator
                    .getMessage("simplepage.context-link-title-2")
                    .replace("{1}", author)
                    .replace("{2}", itemToPageowner.get(comment.getItemId()))));
    }

    String dateString = df.format(comment.getTimePosted());

    if (!filter)
      UIOutput.make(commentContainer, "replyTo")
          .decorate(
              new UIFreeAttributeDecorator(
                  "onclick",
                  "replyToComment($(this),'"
                      + messageLocator
                          .getMessage("simplepage.in-reply-to")
                          .replace("{1}", author)
                          .replace("{2}", dateString)
                      + "')"))
          .decorate(
              new UIFreeAttributeDecorator(
                  "title",
                  messageLocator.getMessage("simplepage.comment-reply").replace("{}", author)));

    if (!comment.getHtml()) {
      UIOutput.make(commentContainer, "comment", comment.getComment());
    } else {
      UIVerbatim.make(commentContainer, "comment", comment.getComment());
    }
  }
Ejemplo n.º 2
0
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    String currentuserid = externalLogic.getCurrentUserId();

    PollViewParameters ecvp = (PollViewParameters) viewparams;
    Poll poll = null;
    boolean isNew = true;

    UIForm newPoll = UIForm.make(tofill, "add-poll-form");
    LOG.debug("Poll of id: " + ecvp.id);
    if (ecvp.id == null || "New 0".equals(ecvp.id)) {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title");
      // build an empty poll
      LOG.debug("this is a new poll");
      poll = new Poll();
    } else {
      UIMessage.make(tofill, "new_poll_title", "new_poll_title_edit");

      String strId = ecvp.id;
      LOG.debug("got id of " + strId);
      poll = pollListManager.getPollById(Long.valueOf(strId));
      voteBean.setPoll(poll);
      newPoll.parameters.add(new UIELBinding("#{poll.pollId}", poll.getPollId()));

      isNew = false;
    }

    if (!externalLogic.isUserAdmin()
        && !externalLogic.isAllowedInLocation(
            PollListManager.PERMISSION_ADD,
            externalLogic.getCurrentLocationReference(),
            externalLogic.getCurrentuserReference())) {
      tml.addMessage(new TargettedMessage("new_poll_noperms"));
      return;
    }

    // only display for exisiting polls
    if (!isNew) {
      // fill the options list
      UIBranchContainer actionBlock = UIBranchContainer.make(newPoll, "option-headers:");
      UIMessage.make(actionBlock, "options-title", "new_poll_option_title");
      UIInternalLink.make(
          actionBlock,
          "option-add",
          UIMessage.make("new_poll_option_add"),
          new OptionViewParameters(PollOptionProducer.VIEW_ID, null, poll.getPollId().toString()));

      List<Vote> votes = pollVoteManager.getAllVotesForPoll(poll);
      if (votes != null && votes.size() > 0) {
        LOG.debug("Poll has " + votes.size() + " votes");
        UIBranchContainer errorRow = UIBranchContainer.make(tofill, "error-row:", "0");
        UIMessage.make(errorRow, "error", "warn_poll_has_votes");
      }

      List<Option> options = pollListManager.getVisibleOptionsForPoll(poll.getPollId());
      for (int i = 0; i < options.size(); i++) {
        Option o = (Option) options.get(i);
        UIBranchContainer oRow =
            UIBranchContainer.make(actionBlock, "options-row:", o.getOptionId().toString());
        UIVerbatim.make(oRow, "options-name", o.getOptionText());

        UIInternalLink editOption =
            UIInternalLink.make(
                oRow,
                "option-edit",
                UIMessage.make("new_poll_option_edit"),
                new OptionViewParameters(PollOptionProducer.VIEW_ID, o.getOptionId().toString()));

        editOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_edit")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));

        UIInternalLink deleteOption =
            UIInternalLink.make(
                oRow,
                "option-delete",
                UIMessage.make("new_poll_option_delete"),
                new OptionViewParameters(
                    PollOptionDeleteProducer.VIEW_ID, o.getOptionId().toString()));

        deleteOption.decorators =
            new DecoratorList(
                new UITooltipDecorator(
                    messageLocator.getMessage("new_poll_option_delete")
                        + ":"
                        + FormattedText.convertFormattedTextToPlaintext(o.getOptionText())));
      }
    }

    UIMessage.make(tofill, "new-poll-descr", "new_poll_title");
    UIMessage.make(tofill, "new-poll-question-label", "new_poll_question_label");
    UIMessage pollDescr = UIMessage.make(tofill, "new-poll-descr-label", "new_poll_descr_label");
    UIMessage.make(tofill, "new-poll-descr-label2", "new_poll_descr_label2");

    // UIMessage.make(tofill, "new-poll-open-label", "new_poll_open_label");
    // UIMessage.make(tofill, "new-poll-close-label", "new_poll_close_label");

    UIMessage.make(tofill, "new-poll-limits", "new_poll_limits");
    // UIMessage pollMin = UIMessage.make(tofill, "new-poll-min-limits", "new_poll_min_limits");
    // UIMessage pollMax =  UIMessage.make(tofill, "new-poll-max-limits", "new_poll_max_limits");

    // the form fields
    UIInput.make(newPoll, "new-poll-text", "#{poll.text}", poll.getText());

    if (!externalLogic.isMobileBrowser()) {
      // show WYSIWYG editor
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr:",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      richTextEvolver.evolveTextInput(itemDescr);
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    } else {
      // do not show WYSIWYG editor in the mobile view
      UIInput itemDescr =
          UIInput.make(
              newPoll,
              "newpolldescr_mobile",
              "#{poll.details}",
              poll.getDetails()); // $NON-NLS-1$ //$NON-NLS-2$
      UILabelTargetDecorator.targetLabel(pollDescr, itemDescr);
    }

    UIInput voteOpen =
        UIInput.make(newPoll, "openDate-iso8601", "poll.voteOpenStr", poll.getVoteOpenStr());
    UIInput voteClose =
        UIInput.make(newPoll, "closeDate-iso8601", "poll.voteCloseStr", poll.getVoteCloseStr());
    // UILabelTargetDecorator.targetLabel(pollOpen, voteOpen);
    // UILabelTargetDecorator.targetLabel(pollClose, voteClose);

    /*
     * access options
     */
    UIMessage pollAccessLabel =
        UIMessage.make(newPoll, "poll_access_label", "new_poll_access_label");
    UIBoundBoolean accessPublic =
        UIBoundBoolean.make(newPoll, "access-public", "poll.isPublic", poll.getIsPublic());
    UIMessage newPollAccessPublicLabel =
        UIMessage.make(newPoll, "new_poll_access_public_label", "new_poll_access_public");

    // SAK-25399: Do not display the public access by default
    if (!externalLogic.isShowPublicAccess()) {
      newPoll.remove(pollAccessLabel);
      newPoll.remove(accessPublic);
      newPoll.remove(newPollAccessPublicLabel);
    }

    String[] minVotes =
        new String[] {
          "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    String[] maxVotes =
        new String[] {
          "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15"
        };
    UISelect min =
        UISelect.make(
            newPoll,
            "min-votes",
            minVotes,
            "#{poll.minOptions}",
            Integer.toString(poll.getMinOptions()));
    UISelect max =
        UISelect.make(
            newPoll,
            "max-votes",
            maxVotes,
            "#{poll.maxOptions}",
            Integer.toString(poll.getMaxOptions()));

    /*
     * 	open - can be viewd at any time
     * 	never - not diplayed
     * 	afterVoting - after user has voted
     * 	afterClosing
     *
     */

    String[] values = new String[] {"open", "afterVoting", "afterClosing", "never"};
    String[] labels =
        new String[] {
          messageLocator.getMessage("new_poll_open"),
          messageLocator.getMessage("new_poll_aftervoting"),
          messageLocator.getMessage("new_poll_afterClosing"),
          messageLocator.getMessage("new_poll_never")
        };

    UISelect radioselect =
        UISelect.make(
            newPoll, "release-select", values, "#{poll.displayResult}", poll.getDisplayResult());

    radioselect.optionnames = UIOutputMany.make(labels);

    String selectID = radioselect.getFullID();
    // StringList optList = new StringList();
    UIMessage.make(newPoll, "add_results_label", "new_poll_results_label");
    for (int i = 0; i < values.length; ++i) {

      UIBranchContainer radiobranch =
          UIBranchContainer.make(newPoll, "releaserow:", Integer.toString(i));
      UISelectChoice choice = UISelectChoice.make(radiobranch, "release", selectID, i);
      UISelectLabel lb = UISelectLabel.make(radiobranch, "releaseLabel", selectID, i);
      UILabelTargetDecorator.targetLabel(lb, choice);
    }

    LOG.debug("About to close the form");
    newPoll.parameters.add(new UIELBinding("#{poll.owner}", currentuserid));
    String siteId = externalLogic.getCurrentLocationId();
    newPoll.parameters.add(new UIELBinding("#{poll.siteId}", siteId));

    if (isNew || poll.getPollOptions() == null || poll.getPollOptions().size() == 0) {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_saveoption"),
          "#{pollToolBean.processActionAdd}");
    } else {
      UICommand.make(
          newPoll,
          "submit-new-poll",
          UIMessage.make("new_poll_submit"),
          "#{pollToolBean.processActionAdd}");
    }

    UICommand cancel =
        UICommand.make(
            newPoll, "cancel", UIMessage.make("new_poll_cancel"), "#{pollToolBean.cancel}");
    cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
    LOG.debug("Finished generating view");
  }
  /* (non-Javadoc)
   * @see uk.org.ponder.rsf.view.ComponentProducer#fillComponents(uk.org.ponder.rsf.components.UIContainer, uk.org.ponder.rsf.viewstate.ViewParameters, uk.org.ponder.rsf.view.ComponentChecker)
   */
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {

    EvalViewParameters evalViewParams = (EvalViewParameters) viewparams;
    if (evalViewParams.evaluationId == null) {
      throw new IllegalArgumentException("Cannot access this view unless the evaluationId is set");
    }

    String actionBean = "setupEvalBean.";
    String evaluationOTP = "evaluationBeanLocator." + evalViewParams.evaluationId + ".";
    /**
     * This is the evaluation we are working with on this page, this should ONLY be read from, do
     * not change any of these fields
     */
    EvalEvaluation evaluation = evaluationService.getEvaluationById(evalViewParams.evaluationId);
    String currentEvalState = evaluationService.returnAndFixEvalState(evaluation, true);

    // local variables used in the render logic
    String currentUserId = commonLogic.getCurrentUserId();
    boolean userAdmin = commonLogic.isUserAdmin(currentUserId);
    boolean createTemplate = authoringService.canCreateTemplate(currentUserId);
    boolean beginEvaluation = evaluationService.canBeginEvaluation(currentUserId);

    DateFormat dateFormat = DateFormat.getDateInstance(DateFormat.LONG, locale);
    DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT, locale);

    /*
     * top links here
     */
    UIInternalLink.make(
        tofill,
        "summary-link",
        UIMessage.make("summary.page.title"),
        new SimpleViewParameters(SummaryProducer.VIEW_ID));

    if (userAdmin) {
      UIInternalLink.make(
          tofill,
          "administrate-link",
          UIMessage.make("administrate.page.title"),
          new SimpleViewParameters(AdministrateProducer.VIEW_ID));
      UIInternalLink.make(
          tofill,
          "control-scales-link",
          UIMessage.make("controlscales.page.title"),
          new SimpleViewParameters(ControlScalesProducer.VIEW_ID));
    }

    if (createTemplate) {
      UIInternalLink.make(
          tofill,
          "control-templates-link",
          UIMessage.make("controltemplates.page.title"),
          new SimpleViewParameters(ControlTemplatesProducer.VIEW_ID));
      UIInternalLink.make(
          tofill,
          "control-items-link",
          UIMessage.make("controlitems.page.title"),
          new SimpleViewParameters(ControlItemsProducer.VIEW_ID));
    }

    if (beginEvaluation) {
      UIInternalLink.make(
          tofill,
          "control-evaluations-link",
          UIMessage.make("controlevaluations.page.title"),
          new SimpleViewParameters(ControlEvaluationsProducer.VIEW_ID));
    } else {
      throw new SecurityException(
          "User attempted to access " + VIEW_ID + " when they are not allowed");
    }

    UIInternalLink.make(
        tofill,
        "eval-settings-link",
        UIMessage.make("evalsettings.page.title"),
        new EvalViewParameters(EvaluationSettingsProducer.VIEW_ID, evalViewParams.evaluationId));
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
      // creating a new eval
      UIMessage.make(tofill, "eval-start-text", "starteval.page.title");
    }

    UIForm form = UIForm.make(tofill, "evalSettingsForm");

    // REOPENING eval (SPECIAL CASE)
    Date reOpenDueDate = null;
    Date reOpenStopDate = null;
    boolean reOpening = false;
    if (evalViewParams.reOpening) {
      Boolean enableReOpen = (Boolean) settings.get(EvalSettings.ENABLE_EVAL_REOPEN);
      if (enableReOpen) {
        // check if already active, do nothing if not closed
        if (EvalUtils.checkStateAfter(
            currentEvalState, EvalConstants.EVALUATION_STATE_CLOSED, false)) {
          // force the due and stop dates to something reasonable
          Calendar calendar = new GregorianCalendar();
          calendar.setTime(new Date());
          calendar.add(Calendar.DATE, 1);
          reOpenDueDate = calendar.getTime();

          Boolean useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
          if (useStopDate) {
            // assign stop date to equal due date for now
            reOpenStopDate = calendar.getTime();
          }

          // finally force the state to appear active
          currentEvalState = EvalConstants.EVALUATION_STATE_ACTIVE;
          form.parameters.add(
              new UIELBinding(actionBean + "reOpening", true)); // so we know we are reopening
          reOpening = true;
        }
      }
    }

    // EVALUATION TITLE/INSTRUCTIONS

    if (EvalUtils.checkStateBefore(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true)) {
      UIInput.make(form, "title", evaluationOTP + "title");
    } else {
      UIOutput.make(tofill, "title_disabled", evaluation.getTitle());
    }

    if (EvalUtils.checkStateBefore(currentEvalState, EvalConstants.EVALUATION_STATE_CLOSED, true)) {
      UIInput instructionsInput =
          UIInput.make(form, "instructions:", evaluationOTP + "instructions");
      instructionsInput.decorators = new DecoratorList(new UITextDimensionsDecorator(60, 4));
      richTextEvolver.evolveTextInput(instructionsInput);
    } else {
      UIVerbatim.make(tofill, "instructions_disabled", evaluation.getInstructions());
    }

    // only put up the controls/auto binding if this is not already set
    if (evaluation.getTemplate() == null) {
      // Make bottom table containing the list of templates if no template set
      if (evalViewParams.templateId == null) {
        // get the templates usable by this user
        List<EvalTemplate> templateList =
            authoringService.getTemplatesForUser(currentUserId, null, false);
        if (templateList.size() > 0) {
          UIBranchContainer chooseTemplate = UIBranchContainer.make(form, "chooseTemplate:");

          String[] values = new String[templateList.size()];
          String[] labels = new String[templateList.size()];

          // TODO - this is not a good way to do this
          UISelect radios =
              UISelect.make(
                  chooseTemplate, "templateRadio", null, null, actionBean + "templateId", null);
          String selectID = radios.getFullID();
          for (int i = 0; i < templateList.size(); i++) {
            EvalTemplate template = templateList.get(i);
            values[i] = template.getId().toString();
            labels[i] = template.getTitle();
            UIBranchContainer radiobranch =
                UIBranchContainer.make(chooseTemplate, "templateOptions:", i + "");
            UISelectChoice.make(radiobranch, "radioValue", selectID, i);
            UISelectLabel.make(radiobranch, "radioLabel", selectID, i);
            EvalUser owner = commonLogic.getEvalUserById(template.getOwner());
            UIOutput.make(radiobranch, "radioOwner", owner.displayName);
            UIInternalLink.make(
                radiobranch,
                "viewPreview_link",
                UIMessage.make("starteval.view.preview.link"),
                new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, template.getId()));
          }
          // need to assign the choices and labels at the end here since we used nulls at the
          // beginning
          radios.optionlist = UIOutputMany.make(values);
          radios.optionnames = UIOutputMany.make(labels);
        } else {
          throw new IllegalStateException(
              "User got to evaluation settings when they have no access to any templates... "
                  + "producer suicide was the only way out");
        }
      } else {
        // just bind in the template explicitly to the evaluation
        form.parameters.add(
            new UIELBinding(
                evaluationOTP + "template",
                new ELReference("templateBeanLocator." + evalViewParams.templateId)));
      }
    } else {
      EvalTemplate template = authoringService.getTemplateById(evaluation.getTemplate().getId());
      UIBranchContainer showTemplateBranch = UIBranchContainer.make(tofill, "showTemplate:");
      UIMessage.make(
          showTemplateBranch,
          "eval_template_title",
          "evalsettings.template.title.display",
          new Object[] {template.getTitle()});
      UIInternalLink.make(
          showTemplateBranch,
          "eval_template_preview_link",
          UIMessage.make("evalsettings.template.preview.link"),
          new EvalViewParameters(PreviewEvalProducer.VIEW_ID, null, template.getId()));
      if (!template.getLocked().booleanValue()
          && authoringService.canModifyTemplate(currentUserId, template.getId())) {
        UIInternalLink.make(
            showTemplateBranch,
            "eval_template_modify_link",
            UIMessage.make("general.command.edit"),
            new TemplateViewParameters(ModifyTemplateItemsProducer.VIEW_ID, template.getId()));
      }
    }

    // EVALUATION DATES

    Date today = new Date();
    UIMessage.make(
        tofill,
        "current_date",
        "evalsettings.dates.current",
        new Object[] {dateFormat.format(today), timeFormat.format(today)});

    // retrieve the global setting for use of date only or date and time picker
    Boolean useDateTime = (Boolean) settings.get(EvalSettings.EVAL_USE_DATE_TIME);

    // Start Date
    UIBranchContainer showStartDate = UIBranchContainer.make(form, "showStartDate:");
    generateDateSelector(
        showStartDate,
        "startDate",
        evaluationOTP + "startDate",
        null,
        currentEvalState,
        EvalConstants.EVALUATION_STATE_ACTIVE,
        useDateTime);

    // Due Date
    UIBranchContainer showDueDate = UIBranchContainer.make(form, "showDueDate:");
    generateDateSelector(
        showDueDate,
        "dueDate",
        evaluationOTP + "dueDate",
        reOpenDueDate,
        currentEvalState,
        EvalConstants.EVALUATION_STATE_GRACEPERIOD,
        useDateTime);

    // Stop Date - Show the "Stop date" text box only if allowed in the System settings
    Boolean useStopDate = (Boolean) settings.get(EvalSettings.EVAL_USE_STOP_DATE);
    if (useStopDate) {
      UIBranchContainer showStopDate = UIBranchContainer.make(form, "showStopDate:");
      generateDateSelector(
          showStopDate,
          "stopDate",
          evaluationOTP + "stopDate",
          reOpenStopDate,
          currentEvalState,
          EvalConstants.EVALUATION_STATE_CLOSED,
          useDateTime);
    }

    // EVALUATION RESULTS VIEWING/SHARING

    // radio buttons for the results sharing options
    UISelect resultsSharingRadios =
        UISelect.make(
                form,
                "dummyRadioSharing",
                EvalToolConstants.EVAL_RESULTS_SHARING_VALUES,
                EvalToolConstants.EVAL_RESULTS_SHARING_LABELS_PROPS,
                evaluationOTP + "resultsSharing",
                null)
            .setMessageKeys();
    String resultsSharingId = resultsSharingRadios.getFullID();
    for (int i = 0; i < EvalToolConstants.EVAL_RESULTS_SHARING_VALUES.length; ++i) {
      UIBranchContainer radiobranch = UIBranchContainer.make(form, "resultsSharingChoice:", i + "");
      UISelectChoice choice = UISelectChoice.make(radiobranch, "radioValue", resultsSharingId, i);
      UISelectLabel.make(radiobranch, "radioLabel", resultsSharingId, i)
          .decorate(new UILabelTargetDecorator(choice));
    }

    // show the view date only if allowed by system settings
    if (((Boolean) settings.get(EvalSettings.EVAL_USE_VIEW_DATE)).booleanValue()) {
      UIBranchContainer showViewDate = UIBranchContainer.make(form, "showViewDate:");
      generateDateSelector(
          showViewDate,
          "viewDate",
          evaluationOTP + "viewDate",
          null,
          currentEvalState,
          EvalConstants.EVALUATION_STATE_VIEWABLE,
          useDateTime);
    }

    // all types of users view results on the same date or we can configure the results viewing
    // separately
    boolean sameViewDateForAll = (Boolean) settings.get(EvalSettings.EVAL_USE_SAME_VIEW_DATES);

    // Student view date
    Boolean studentViewResults = (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_VIEW_RESULTS);
    UIBranchContainer showResultsToStudents =
        UIBranchContainer.make(form, "showResultsToStudents:");
    generateSettingsControlledCheckbox(
        showResultsToStudents,
        "studentViewResults",
        evaluationOTP + "studentViewResults",
        studentViewResults,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_VIEWABLE, true));
    generateViewDateControl(
        showResultsToStudents,
        "studentsViewDate",
        evaluationOTP + "studentsDate",
        studentViewResults,
        useDateTime,
        sameViewDateForAll);

    // Instructor view date
    Boolean instructorViewResults =
        (Boolean) settings.get(EvalSettings.INSTRUCTOR_ALLOWED_VIEW_RESULTS);
    UIBranchContainer showResultsToInst = UIBranchContainer.make(form, "showResultsToInst:");
    generateSettingsControlledCheckbox(
        showResultsToInst,
        "instructorViewResults",
        evaluationOTP + "instructorViewResults",
        instructorViewResults,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_VIEWABLE, true));
    generateViewDateControl(
        showResultsToInst,
        "instructorsViewDate",
        evaluationOTP + "instructorsDate",
        instructorViewResults,
        useDateTime,
        sameViewDateForAll);

    // RESPONDENT SETTINGS

    // Student Allowed Leave Unanswered
    Boolean studentUnanswersAllowed =
        (Boolean) settings.get(EvalSettings.STUDENT_ALLOWED_LEAVE_UNANSWERED);
    UIBranchContainer showBlankQuestionAllowedToStut =
        UIBranchContainer.make(form, "showBlankQuestionAllowedToStut:");
    generateSettingsControlledCheckbox(
        showBlankQuestionAllowedToStut,
        "blankResponsesAllowed",
        evaluationOTP + "blankResponsesAllowed",
        studentUnanswersAllowed,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true));

    // Student Modify Responses
    Boolean studentModifyReponses = (Boolean) settings.get(EvalSettings.STUDENT_MODIFY_RESPONSES);
    UIBranchContainer showModifyResponsesAllowedToStu =
        UIBranchContainer.make(form, "showModifyResponsesAllowedToStu:");
    generateSettingsControlledCheckbox(
        showModifyResponsesAllowedToStu,
        "modifyResponsesAllowed",
        evaluationOTP + "modifyResponsesAllowed",
        studentModifyReponses,
        form,
        EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true));

    // ADMIN SETTINGS SECTION

    UISelect authControlSelect =
        UISelect.make(
                form,
                "auth-control-choose",
                EvalToolConstants.AUTHCONTROL_VALUES,
                EvalToolConstants.AUTHCONTROL_LABELS,
                evaluationOTP + "authControl")
            .setMessageKeys();
    if (EvalUtils.checkStateAfter(currentEvalState, EvalConstants.EVALUATION_STATE_ACTIVE, true)) {
      RSFUtils.disableComponent(authControlSelect);
    }

    if (userAdmin) {
      // If the person is an admin (any kind), then we need to show these instructor opt in/out
      // settings

      UIMessage.make(
          form, "instructor-opt-instructions", "evalsettings.admin.settings.instructions");
      UIMessage.make(form, "instructor-opt-header", "evalsettings.instructor.opt.desc");

      // If "EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE" is set as configurable
      // i.e. NULL in the database then show the instructor opt select box. Else just show the value
      // as label
      String instUseFromAboveValue =
          (String) settings.get(EvalSettings.INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE);
      if (instUseFromAboveValue == null
          || EvalToolConstants.ADMIN_BOOLEAN_CONFIGURABLE.equals(instUseFromAboveValue)) {
        UISelect instOpt =
            UISelect.make(
                    form,
                    "instructorOpt",
                    EvalToolConstants.INSTRUCTOR_OPT_VALUES,
                    EvalToolConstants.INSTRUCTOR_OPT_LABELS,
                    evaluationOTP + "instructorOpt")
                .setMessageKeys();
        if (EvalUtils.checkStateAfter(
            currentEvalState, EvalConstants.EVALUATION_STATE_INQUEUE, true)) {
          RSFUtils.disableComponent(instOpt);
        }
      } else {
        int index =
            ArrayUtil.indexOf(EvalToolConstants.INSTRUCTOR_OPT_VALUES, instUseFromAboveValue);
        String instUseFromAboveLabel = EvalToolConstants.INSTRUCTOR_OPT_LABELS[index];
        // Displaying the label corresponding to INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value set as
        // system property
        UIMessage.make(form, "instructorOptLabel", instUseFromAboveLabel);
        // Doing the binding of this INSTRUCTOR_MUST_USE_EVALS_FROM_ABOVE value so that it can be
        // saved in the database
        form.parameters.add(
            new UIELBinding(evaluationOTP + "instructorOpt", instUseFromAboveValue));
      }
    }

    // EVALUATION REMINDERS SECTION

    // email available template link
    UIInternalLink.make(
        form,
        "emailAvailable_link",
        UIMessage.make("evalsettings.available.mail.link"),
        new EmailViewParameters(
            PreviewEmailProducer.VIEW_ID,
            null,
            EvalConstants.EMAIL_TEMPLATE_AVAILABLE,
            evaluation.getId()));

    // email reminder control
    UISelect reminderDaysSelect =
        UISelect.make(
                form,
                "reminderDays",
                EvalToolConstants.REMINDER_EMAIL_DAYS_VALUES,
                EvalToolConstants.REMINDER_EMAIL_DAYS_LABELS,
                evaluationOTP + "reminderDays")
            .setMessageKeys();
    if (EvalUtils.checkStateAfter(
        currentEvalState, EvalConstants.EVALUATION_STATE_GRACEPERIOD, true)) {
      RSFUtils.disableComponent(reminderDaysSelect);
    }

    // email reminder template link
    UIInternalLink.make(
        form,
        "emailReminder_link",
        UIMessage.make("evalsettings.reminder.mail.link"),
        new EmailViewParameters(
            PreviewEmailProducer.VIEW_ID,
            null,
            EvalConstants.EMAIL_TEMPLATE_REMINDER,
            evaluation.getId()));

    // email from address control
    String defaultEmail = (String) settings.get(EvalSettings.FROM_EMAIL_ADDRESS);
    UIMessage.make(
        form, "eval-from-email-note", "evalsettings.email.sent.from", new String[] {defaultEmail});
    UIInput.make(form, "reminderFromEmail", evaluationOTP + "reminderFromEmail");

    // EVALUATION EXTRAS SECTION
    Boolean categoriesEnabled = (Boolean) settings.get(EvalSettings.ENABLE_EVAL_CATEGORIES);
    if (categoriesEnabled) {
      UIBranchContainer extrasBranch = UIBranchContainer.make(form, "showEvalExtras:");

      // eval category
      if (categoriesEnabled) {
        UIBranchContainer categoryBranch = UIBranchContainer.make(extrasBranch, "showCategory:");
        UIInput.make(categoryBranch, "eval-category", evaluationOTP + "evalCategory");
        if (evaluation.getEvalCategory() != null) {
          UILink.make(
                  categoryBranch,
                  "eval-category-direct-link",
                  UIMessage.make("general.direct.link"),
                  commonLogic.getEntityURL(
                      EvalCategoryEntityProvider.ENTITY_PREFIX, evaluation.getEvalCategory()))
              .decorate(new UITooltipDecorator(UIMessage.make("general.direct.link.title")));
        }
      }
    }

    // EVAL SETTINGS SAVING CONTROLS
    // if this evaluation is already saved, show "Save Settings" button else this is the "Continue
    // to Assign to Courses" button
    String messageKey = "evalsettings.save.settings.link";
    if (EvalConstants.EVALUATION_STATE_PARTIAL.equals(evaluation.getState())) {
      messageKey = "evalsettings.continue.assigning.link";
    }
    if (reOpening) {
      messageKey = "evalsettings.reopening.eval.link";
    }
    UICommand.make(
        form,
        "continueAssigning",
        UIMessage.make(messageKey),
        actionBean + "completeSettingsAction");
    UIMessage.make(tofill, "cancel-button", "general.cancel.button");

    // this fills in the javascript call (areaId, selectId, selectValue, reminderId)
    // NOTE: RSF bug causes us to have to generate the ids manually
    // (http://www.caret.cam.ac.uk/jira/browse/RSF-65)
    UIInitBlock.make(
        tofill,
        "initJavascript",
        "EvalSystem.initEvalSettings",
        new Object[] {
          "evaluation_reminder_area",
          authControlSelect.getFullID() + "-selection",
          EvalConstants.EVALUATION_AUTHCONTROL_NONE,
          reminderDaysSelect.getFullID() + "-selection"
        });
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    ViewSubmissionsViewParams params = (ViewSubmissionsViewParams) viewparams;
    // make sure that we have an AssignmentID to work with
    if (params.assignmentId == null) {
      // ERROR SHOULD BE SET, OTHERWISE TAKE BACK TO ASSIGNMENT_LIST
      messages.addMessage(new TargettedMessage("GeneralActionError"));
      return;
    }
    assignmentId = params.assignmentId;
    Assignment2 assignment = assignmentLogic.getAssignmentByIdWithAssociatedData(assignmentId);

    String currUserId = externalLogic.getCurrentUserId();

    boolean contentReviewEnabled =
        assignment.isContentReviewEnabled()
            && contentReviewLogic.isContentReviewAvailable(assignment.getContextId());

    // let's double check that none of the associated groups were deleted from the site
    boolean displayGroupDeletionWarning = false;
    if (assignment.getAssignmentGroupSet() != null
        && !assignment.getAssignmentGroupSet().isEmpty()) {
      Collection<Group> siteGroups = externalLogic.getSiteGroups(assignment.getContextId());
      List<String> groupIds = new ArrayList<String>();
      if (siteGroups != null) {
        for (Group group : siteGroups) {
          groupIds.add(group.getId());
        }
      }

      for (AssignmentGroup assignGroup : assignment.getAssignmentGroupSet()) {
        if (!groupIds.contains(assignGroup.getGroupId())) {
          displayGroupDeletionWarning = true;
          break;
        }
      }
    }

    if (displayGroupDeletionWarning) {
      UIOutput.make(
          tofill,
          "deleted_group",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.group_deleted"));
    }

    // Edit Permission
    boolean userMayEditAssign =
        permissionLogic.isUserAllowedToEditAssignment(currUserId, assignment);
    boolean userMayManageSubmissions =
        permissionLogic.isUserAllowedToManageSubmissionsForAssignment(currUserId, assignment);

    // get parameters
    if (params.sort_by == null) params.sort_by = DEFAULT_SORT_BY;
    if (params.sort_dir == null) params.sort_dir = DEFAULT_SORT_DIR;

    UIVerbatim.make(
        tofill, "defaultSortBy", HTMLUtil.emitJavascriptVar("defaultSortBy", DEFAULT_SORT_BY));

    // we need to retrieve the history for the release/retract feedback logic
    List<AssignmentSubmission> submissions =
        submissionLogic.getViewableSubmissionsWithHistoryForAssignmentId(
            assignmentId, params.groupId);
    List<String> studentIdList = new ArrayList<String>();
    if (submissions != null) {
      for (AssignmentSubmission submission : submissions) {
        studentIdList.add(submission.getUserId());
      }
    }

    // The following is some code to populate the sort order/page size, if
    // it's already been put in session state by the entity provider.
    Long pagesize = null;
    String orderBy = null;
    Boolean ascending = null;
    ToolSession toolSession = sessionManager.getCurrentToolSession();
    if (toolSession.getAttribute(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR)
        != null) {
      Map attr =
          (Map)
              toolSession.getAttribute(
                  Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR);
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE)) {
        pagesize =
            (Long)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_PAGE_SIZE);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY)) {
        orderBy =
            (String)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ORDER_BY);
      }
      if (attr.containsKey(
          Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING)) {
        ascending =
            (Boolean)
                attr.get(Assignment2SubmissionEntityProvider.SUBMISSIONVIEW_SESSION_ATTR_ASCENDING);
      }
    }

    // if assign is graded, retrieve the gb details, if appropriate
    GradebookItem gbItem = null;
    boolean gbItemExists = false;
    boolean gradesReleased = false;
    // user may view the associated gradebook item
    boolean userMayViewGbItem = false;
    // user has grading privileges for this gb item
    boolean userMayGrade = false;
    boolean userMayReleaseGrades = false;

    if (assignment.isGraded() && assignment.getGradebookItemId() != null) {
      userMayViewGbItem =
          gradebookLogic.isCurrentUserAbleToViewGradebookItem(
              assignment.getContextId(), assignment.getGradebookItemId());

      if (userMayViewGbItem) {
        // user may grade if there is at least one gradable student among the submissions
        List<String> gradableStudents =
            gradebookLogic.getFilteredStudentsForGradebookItem(
                currUserId,
                assignment.getContextId(),
                assignment.getGradebookItemId(),
                AssignmentConstants.GRADE,
                studentIdList);
        userMayGrade = gradableStudents != null && !gradableStudents.isEmpty();
        userMayReleaseGrades = gradebookLogic.isCurrentUserAbleToEdit(assignment.getContextId());

        try {
          gbItem =
              gradebookLogic.getGradebookItemById(
                  assignment.getContextId(), assignment.getGradebookItemId());
          gbItemExists = true;
          gradesReleased = gbItem.isReleased();
        } catch (GradebookItemNotFoundException ginfe) {
          if (log.isDebugEnabled())
            log.debug("Gb item with id: " + assignment.getGradebookItemId() + " no longer exists!");
          gbItem = null;
        }
      }
    }

    // if user has grading privileges but item no longer exists, display warning
    // to user
    if (assignment.isGraded() && userMayViewGbItem && !gbItemExists) {
      UIOutput.make(
          tofill,
          "no_gb_item",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.gb_item_deleted"));
    }

    // We need to check if it's a non electronic submission.  If it is, we don't want to have
    // the submitted columns appear (Submitted and Submission Status).
    // We pass in the boolean parameter nonElectronicSubmission to viewSubmission.js (specifically
    // snn2subview.init()),
    // where logic is there to use this parameter.
    boolean nonElectronicSubmission = false;

    if (assignment.getSubmissionType() == AssignmentConstants.SUBMIT_NON_ELECTRONIC) {
      nonElectronicSubmission = true;
    }

    UIInitBlock.make(
        tofill,
        "asnn2subview-init",
        "asnn2subview.init",
        new Object[] {
          assignmentId,
          externalLogic.getCurrentContextId(),
          placement.getId(),
          submissions.size(),
          assignment.isGraded(),
          contentReviewEnabled,
          nonElectronicSubmission,
          pagesize,
          orderBy,
          ascending,
          gradesReleased,
          params.pageIndex
        });

    // Breadcrumbs
    UIInternalLink.make(
        tofill,
        "breadcrumb",
        messageLocator.getMessage("assignment2.assignment_list-sortview.heading"),
        new SimpleViewParameters(ListProducer.VIEW_ID));
    UIMessage.make(
        tofill,
        "last_breadcrumb",
        "assignment2.assignment_grade-assignment.heading",
        new Object[] {assignment.getTitle()});

    // ACTION BAR
    boolean displayReleaseGrades = false;
    boolean displayReleaseFB = false;
    boolean displayDownloadAll = false;
    boolean displayUploadAll = false;

    if (userMayEditAssign || userMayManageSubmissions) {
      UIOutput.make(tofill, "navIntraTool");
    }

    // RELEASE GRADES
    // don't display this option if the gb item doesn't exist anymore
    if (userMayReleaseGrades && assignment.isGraded() && gbItemExists) {
      displayReleaseGrades = true;

      // determine if grades have been released yet
      String releaseLinkText =
          messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.release");
      if (gradesReleased) {
        releaseLinkText =
            messageLocator.getMessage("assignment2.assignment_grade-assignment.grades.retract");
      }

      UIForm releaseGradesForm = UIForm.make(tofill, "release_grades_form");
      UICommand releaseGradesButton = UICommand.make(releaseGradesForm, "release_grades");

      UIOutput.make(tofill, "release_grades_li");
      UIInternalLink releaseGradesLink =
          UIInternalLink.make(tofill, "release_grades_link", releaseLinkText, viewparams);
      Map<String, String> idmap = new HashMap<String, String>();
      idmap.put(
          "onclick",
          "asnn2.releaseGradesDialog('"
              + releaseGradesButton.getFullID()
              + "', '"
              + assignment.getContextId()
              + "', '"
              + assignment.getGradebookItemId()
              + "', '"
              + !gradesReleased
              + "'); return false;");
      releaseGradesLink.decorate(new UIFreeAttributeDecorator(idmap));

      makeReleaseGradesDialog(gradesReleased, assignment, tofill);
    }

    // RELEASE FEEDBACK
    if (userMayManageSubmissions) {
      displayReleaseFB = true;
      makeReleaseFeedbackLink(tofill, params, submissions);
    }

    // DOWNLOAD ALL
    if (userMayManageSubmissions) {
      displayDownloadAll = true;

      ZipViewParams zvp = new ZipViewParams("zipSubmissions", assignmentId);
      UIInternalLink.make(
          tofill,
          "downloadall",
          UIMessage.make("assignment2.assignment_grade-assignment.downloadall.button"),
          zvp);
    }

    // UPLOAD GRADES & FEEDBACK
    if (userMayManageSubmissions) {
      displayUploadAll = true;

      AssignmentViewParams avp = new AssignmentViewParams("uploadall", assignmentId);
      if (assignment.isGraded() && gbItemExists && userMayGrade) {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.graded"),
            avp);
      } else {
        UIInternalLink.make(
            tofill,
            "uploadall",
            UIMessage.make("assignment2.uploadall.breadcrumb.upload.ungraded"),
            avp);
      }
    }

    // handle those pesky separators
    if (displayReleaseGrades && (displayReleaseFB || displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_grades_sep");
    }

    if (displayReleaseFB && (displayUploadAll || displayDownloadAll)) {
      UIOutput.make(tofill, "release_feedback_sep");
    }

    if (displayDownloadAll && displayUploadAll) {
      UIOutput.make(tofill, "downloadall_sep");
    }

    UIMessage.make(tofill, "page-title", "assignment2.assignment_grade-assignment.title");

    // now make the "View By Sections/Groups" filter
    makeViewByGroupFilter(tofill, params, assignment);

    /*
     * Form for assigning a grade to all submissions without a grade.
     * Do not allow grading if gbItem is null - it must have been deleted
     */
    if (submissions != null
        && !submissions.isEmpty()
        && userMayGrade
        && assignment.isGraded()
        && gbItemExists) {
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form0:");
      createApplyToUngradedWidget(assignment, tofill, params, "unassigned-apply-form1:");
    }

    // Confirmation Dialogs
    // These are only added here for internationalization. They are not part
    // of a real form.
    UICommand.make(
        tofill,
        "release-feedback-confirm",
        UIMessage.make("assignment2.dialogs.release_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "release-feedback-cancel",
        UIMessage.make("assignment2.dialogs.release_all_feedback.cancel"));

    UICommand.make(
        tofill,
        "retract-feedback-confirm",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.confirm"));
    UICommand.make(
        tofill,
        "retract-feedback-cancel",
        UIMessage.make("assignment2.dialogs.retract_all_feedback.cancel"));
  }