Esempio n. 1
0
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    CommentsViewParameters params = (CommentsViewParameters) viewparams;
    filter = params.filter;

    // set up locale
    String langLoc[] = localeGetter.get().toString().split("_");
    if (langLoc.length >= 2) {
      if ("en".equals(langLoc[0]) && "ZA".equals(langLoc[1])) {
        M_locale = new Locale("en", "GB");
      } else {
        M_locale = new Locale(langLoc[0], langLoc[1]);
      }
    } else {
      M_locale = new Locale(langLoc[0]);
    }

    df =
        DateFormat.getDateTimeInstance(
            DateFormat.DEFAULT, DateFormat.DEFAULT, new ResourceLoader().getLocale());
    df.setTimeZone(TimeService.getLocalTimeZone());
    dfTime = DateFormat.getTimeInstance(DateFormat.SHORT, M_locale);
    dfTime.setTimeZone(TimeService.getLocalTimeZone());
    dfDate = DateFormat.getDateInstance(DateFormat.MEDIUM, M_locale);
    dfDate.setTimeZone(TimeService.getLocalTimeZone());

    // errors redirect back to ShowPage. But if this is embedded in the page, ShowPage
    // will call us again. This is very hard for the user to recover from. So trap
    // all possible errors. It may result in an incomplete page or something invalid,
    // but better that than an infinite recursion.

    try {

      SimplePage currentPage = simplePageToolDao.getPage(params.pageId);
      simplePageBean.setCurrentSiteId(params.siteId);
      simplePageBean.setCurrentPage(currentPage);
      simplePageBean.setCurrentPageId(params.pageId);

      UIOutput.make(tofill, "mainlist")
          .decorate(
              new UIFreeAttributeDecorator(
                  "aria-label", messageLocator.getMessage("simplepage.comments-section")));

      SimplePageItem commentsItem = simplePageToolDao.findItem(params.itemId);
      if (commentsItem != null
          && commentsItem.getSakaiId() != null
          && !commentsItem.getSakaiId().equals("")) {
        SimpleStudentPage studentPage =
            simplePageToolDao.findStudentPage(Long.valueOf(commentsItem.getSakaiId()));
        if (studentPage != null) {
          owner = studentPage.getOwner();
        }
      }

      if (params.deleteComment != null) {
        simplePageBean.deleteComment(params.deleteComment);
      }

      List<SimplePageComment> comments;

      if (!filter && !params.studentContentItem) {
        comments = (List<SimplePageComment>) simplePageToolDao.findComments(params.itemId);
      } else if (filter && !params.studentContentItem) {
        comments =
            (List<SimplePageComment>)
                simplePageToolDao.findCommentsOnItemByAuthor(params.itemId, params.author);
      } else if (filter && params.studentContentItem) {
        List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(params.itemId);
        Site site = SiteService.getSite(currentPage.getSiteId());
        itemToPageowner = new HashMap<Long, String>();
        List<Long> commentsItemIds = new ArrayList<Long>();
        for (SimpleStudentPage p : studentPages) {
          // If the page is deleted, don't show the comments
          if (!p.isDeleted()) {
            commentsItemIds.add(p.getCommentsSection());
            String pageOwner = p.getOwner();
            String pageGroup = p.getGroup();
            if (pageGroup != null) pageOwner = pageGroup;
            try {
              String o = null;
              if (pageGroup != null) o = site.getGroup(pageGroup).getTitle();
              else o = UserDirectoryService.getUser(pageOwner).getDisplayName();
              if (o != null) pageOwner = o;
            } catch (Exception ignore) {
            }
            ;
            itemToPageowner.put(p.getCommentsSection(), pageOwner);
          }
        }

        comments = simplePageToolDao.findCommentsOnItemsByAuthor(commentsItemIds, params.author);
      } else {
        List<SimpleStudentPage> studentPages = simplePageToolDao.findStudentPages(params.itemId);

        List<Long> commentsItemIds = new ArrayList<Long>();
        for (SimpleStudentPage p : studentPages) {
          commentsItemIds.add(p.getCommentsSection());
        }

        comments = simplePageToolDao.findCommentsOnItems(commentsItemIds);
      }

      // Make sure everything is chronological
      Collections.sort(
          comments,
          new Comparator<SimplePageComment>() {
            public int compare(SimplePageComment c1, SimplePageComment c2) {
              if (itemToPageowner != null) {
                String o1 = itemToPageowner.get(c1.getItemId());
                String o2 = itemToPageowner.get(c2.getItemId());
                if (o1 != o2) {
                  if (o1 == null) return 1;
                  return o1.compareTo(o2);
                }
              }
              return c1.getTimePosted().compareTo(c2.getTimePosted());
            }
          });

      currentUserId = UserDirectoryService.getCurrentUser().getId();

      boolean anonymous = simplePageBean.findItem(params.itemId).isAnonymous();
      if (anonymous) {
        int i = 1;
        for (SimplePageComment comment : comments) {
          if (!anonymousLookup.containsKey(comment.getAuthor())) {
            anonymousLookup.put(
                comment.getAuthor(), messageLocator.getMessage("simplepage.anonymous") + " " + i);
            i++;
          }
        }
      }

      boolean highlighted = false;

      // We don't want page owners to edit or grade comments on their page
      // at the moment.  Perhaps add option?
      canEditPage = simplePageBean.getEditPrivs() == 0;

      boolean showGradingMessage =
          canEditPage && commentsItem.getGradebookId() != null && !params.filter;

      Date lastViewed = null; // remains null if never viewed before
      SimplePageLogEntry log = simplePageBean.getLogEntry(params.itemId);
      if (log != null) lastViewed = log.getLastViewed();

      int newItems = 0;

      // Remove any "phantom" comments. So that the anonymous order stays the same,
      // comments are deleted by removing all content.  Also check to see if any comments
      // have been graded yet.  Finally, if we're filtering, it takes out comments not by
      // this author.
      for (int i = comments.size() - 1; i >= 0; i--) {
        if (comments.get(i).getComment() == null || comments.get(i).getComment().equals("")) {
          comments.remove(i);
        } else if (params.filter && !comments.get(i).getAuthor().equals(params.author)) {
          comments.remove(i);
        } else {
          if (showGradingMessage && comments.get(i).getPoints() != null) showGradingMessage = false;
          if (lastViewed == null) newItems++; // all items are new if never viewed
          else if (comments.get(i).getTimePosted().after(lastViewed)) newItems++;
        }
      }

      // update date only if we actually are going to see all the comments, and it's
      // not a weird view (i.e. filter is on)
      //   The situation with items <= 5 is actually dubious. The user has them on the
      // screen, but there's no way to know whether he's actually seen them. Some users
      // are going to be surprised either way we do it.
      if (params.showAllComments || params.showNewComments || (!params.filter && newItems <= 5)) {
        if (log != null) {
          simplePageBean.update(log);
        } else {
          log = simplePageToolDao.makeLogEntry(currentUserId, params.itemId, null);
          simplePageBean.saveItem(log);
        }
      }

      // Make sure we don't show the grading message if there's nothing to grade.
      if (comments.size() == 0) {
        showGradingMessage = false;
      }

      boolean editable = false;

      if (comments.size() <= 5 || params.showAllComments || params.filter) {
        for (int i = 0; i < comments.size(); i++) {
          // We don't want them editing on the grading screen, which is why we also check filter.
          boolean canEdit =
              simplePageBean.canModifyComment(comments.get(i), canEditPage) && !params.filter;

          printComment(
              comments.get(i),
              tofill,
              (params.postedComment == comments.get(i).getId()),
              anonymous,
              canEdit,
              params,
              commentsItem,
              currentPage);
          if (!highlighted) {
            highlighted = (params.postedComment == comments.get(i).getId());
          }

          if (!editable) editable = canEdit;
        }
      } else {

        UIBranchContainer container = UIBranchContainer.make(tofill, "commentList:");
        UIOutput.make(container, "commentDiv");
        // UIBranchContainer container = UIBranchContainer.make(tofill, "commentDiv:");
        CommentsViewParameters eParams = new CommentsViewParameters(VIEW_ID);
        eParams.placementId = params.placementId;
        eParams.itemId = params.itemId;
        eParams.showAllComments = true;
        eParams.showNewComments = false;
        eParams.pageId = params.pageId;
        eParams.siteId = params.siteId;
        UIInternalLink.make(container, "to-load", eParams);
        UIOutput.make(
            container,
            "load-more-link",
            messageLocator
                .getMessage("simplepage.see_all_comments")
                .replace("{}", Integer.toString(comments.size())));

        if (!params.showNewComments && newItems > 5) {
          container = UIBranchContainer.make(tofill, "commentList:");
          UIOutput.make(container, "commentDiv");
          // UIBranchContainer container = UIBranchContainer.make(tofill, "commentDiv:");
          eParams = new CommentsViewParameters(VIEW_ID);
          eParams.placementId = params.placementId;
          eParams.itemId = params.itemId;
          eParams.showAllComments = false;
          eParams.showNewComments = true;
          eParams.pageId = params.pageId;
          eParams.siteId = params.siteId;
          UIInternalLink.make(container, "to-load", eParams);
          UIOutput.make(
              container,
              "load-more-link",
              messageLocator
                  .getMessage("simplepage.see_new_comments")
                  .replace("{}", Integer.toString(newItems)));
        }

        int start = comments.size() - 5;
        if (params.showNewComments) start = 0;

        // Show 5 most recent comments
        for (int i = start; i < comments.size(); i++) {
          if (!params.showNewComments
              || lastViewed == null
              || comments.get(i).getTimePosted().after(lastViewed)) {
            boolean canEdit = simplePageBean.canModifyComment(comments.get(i), canEditPage);
            printComment(
                comments.get(i),
                tofill,
                (params.postedComment == comments.get(i).getId()),
                anonymous,
                canEdit,
                params,
                commentsItem,
                currentPage);
            if (!highlighted) {
              highlighted = (params.postedComment == comments.get(i).getId());
            }

            if (!editable) editable = canEdit;
          }
        }
      }

      if (highlighted) {
        // We have something to highlight
        UIOutput.make(tofill, "highlightScript");
      }

      if (showGradingMessage) {
        UIOutput.make(tofill, "gradingAlert");
      }

      if (anonymous && canEditPage && comments.size() > 0 && lastViewed == null) {
        // Tells the admin that they can see the names, but everyone else can't
        UIOutput.make(tofill, "anonymousAlert");
      } else if (editable && simplePageBean.getEditPrivs() != 0) {
        // Warns user that they only have 30 mins to edit.
        UIOutput.make(tofill, "editAlert");
      }

    } catch (Exception e) {
      e.printStackTrace();
      System.out.println("comments error " + e);
    }
    ;
  }
  /* (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"
        });
  }
Esempio n. 3
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());
    }
  }
  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");
  }
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    CommentsGradingPaneViewParameters params = (CommentsGradingPaneViewParameters) viewparams;

    SimplePage currentPage = simplePageToolDao.getPage(params.pageId);
    simplePageBean.setCurrentSiteId(params.siteId);
    simplePageBean.setCurrentPage(currentPage);
    simplePageBean.setCurrentPageId(params.pageId);

    GeneralViewParameters backParams =
        new GeneralViewParameters(ShowPageProducer.VIEW_ID, params.pageId);
    backParams.setItemId(params.pageItemId);
    backParams.setPath("log");

    UIOutput.make(tofill, "html")
        .decorate(new UIFreeAttributeDecorator("lang", localeGetter.get().getLanguage()))
        .decorate(new UIFreeAttributeDecorator("xml:lang", localeGetter.get().getLanguage()));

    UIInternalLink.make(
        tofill, "back-link", messageLocator.getMessage("simplepage.go-back"), backParams);

    if (simplePageBean.getEditPrivs() != 0) {
      UIOutput.make(tofill, "permissionsError");
      return;
    }

    String heading = null;
    if (params.studentContentItem) {
      heading = messageLocator.getMessage("simplepage.student-comments-grading");
    } else {
      heading = messageLocator.getMessage("simplepage.comments-grading");
    }

    SimplePageItem commentItem = simplePageToolDao.findItem(params.commentsItemId);
    SimplePage containingPage = simplePageToolDao.getPage(commentItem.getPageId());
    heading = heading.replace("{}", containingPage.getTitle());

    UIOutput.make(tofill, "page-header", heading);

    List<SimplePageComment> comments;

    if (!params.studentContentItem) {
      comments = simplePageToolDao.findComments(params.commentsItemId);
    } else {
      List<SimpleStudentPage> studentPages =
          simplePageToolDao.findStudentPages(params.commentsItemId);

      List<Long> commentsItemIds = new ArrayList<Long>();
      for (SimpleStudentPage p : studentPages) {
        // If the page is deleted, don't show the comments
        if (!p.isDeleted()) {
          commentsItemIds.add(p.getCommentsSection());
        }
      }

      comments = simplePageToolDao.findCommentsOnItems(commentsItemIds);
    }

    ArrayList<String> userIds = new ArrayList<String>();
    HashMap<String, SimpleUser> users = new HashMap<String, SimpleUser>();

    for (SimplePageComment comment : comments) {
      if (comment.getComment() == null || comment.getComment().equals("")) {
        continue;
      }

      if (!userIds.contains(comment.getAuthor())) {
        userIds.add(comment.getAuthor());
        try {
          SimpleUser user = new SimpleUser();
          user.displayName = UserDirectoryService.getUser(comment.getAuthor()).getDisplayName();
          user.postCount++;
          user.userId = comment.getAuthor();
          user.grade = comment.getPoints();
          user.uuid = comment.getUUID();

          if (params.studentContentItem) {
            user.pages.add(comment.getPageId());
          }

          users.put(comment.getAuthor(), user);
        } catch (Exception ex) {
        }
      } else {
        SimpleUser user = users.get(comment.getAuthor());
        if (user != null) {
          user.postCount++;

          if (params.studentContentItem && !user.pages.contains(comment.getPageId())) {
            user.pages.add(comment.getPageId());
          }
        }
      }
    }

    ArrayList<SimpleUser> simpleUsers = new ArrayList<SimpleUser>(users.values());
    Collections.sort(simpleUsers);

    if (params.studentContentItem) {
      UIOutput.make(
          tofill, "unique-header", messageLocator.getMessage("simplepage.grading-unique"));
    }

    if (simpleUsers.size() > 0) {
      UIOutput.make(tofill, "gradingTable");
    } else {
      UIOutput.make(tofill, "noEntriesWarning");
    }

    if (params.studentContentItem) UIOutput.make(tofill, "clickfiller");

    UIOutput.make(tofill, "clickToSubmit", messageLocator.getMessage("simplepage.update-points"))
        .decorate(
            new UIFreeAttributeDecorator(
                "title", messageLocator.getMessage("simplepage.update-points")));

    for (SimpleUser user : simpleUsers) {
      UIBranchContainer branch = UIBranchContainer.make(tofill, "student-row:");

      UIOutput.make(branch, "first-row");
      UIOutput.make(branch, "details-row");
      UIOutput detailsCell = UIOutput.make(branch, "details-cell");

      // Set the column span based on which type of item it is.  Student content
      // items have an extra column, so we have to accommodate.
      if (params.studentContentItem) {
        detailsCell.decorate(new UIFreeAttributeDecorator("colspan", "5"));
      } else {
        detailsCell.decorate(new UIFreeAttributeDecorator("colspan", "4"));
      }
      UIOutput.make(branch, "student-name", user.displayName);
      UIOutput.make(branch, "student-total", String.valueOf(user.postCount));

      if (params.studentContentItem) {
        UIOutput.make(branch, "student-unique", String.valueOf(user.pages.size()));
      }

      // Add the link that will be fetched using Ajax
      CommentsViewParameters eParams = new CommentsViewParameters(CommentsProducer.VIEW_ID);
      eParams.placementId = ToolManager.getCurrentPlacement().getId();
      eParams.itemId = params.commentsItemId;
      eParams.author = user.userId;
      eParams.filter = true;
      eParams.pageItemId = params.pageItemId;
      eParams.studentContentItem = params.studentContentItem;
      eParams.siteId = simplePageBean.getCurrentSiteId();
      eParams.pageId = containingPage.getPageId();
      UIInternalLink.make(branch, "commentsLink", eParams);

      // The grading stuff
      UIOutput.make(branch, "student-grade");
      UIOutput.make(branch, "gradingSpan");
      UIOutput.make(branch, "commentsUUID", user.uuid);
      UIOutput.make(
          branch, "commentPoints", (user.grade == null ? "" : String.valueOf(user.grade)));
      UIOutput.make(branch, "pointsBox")
          .decorate(
              new UIFreeAttributeDecorator(
                  "title",
                  messageLocator
                      .getMessage("simplepage.grade-for-student")
                      .replace("{}", user.displayName)));
      UIOutput.make(
          branch,
          "maxpoints",
          " / "
              + (params.studentContentItem
                  ? commentItem.getAltPoints()
                  : commentItem.getGradebookPoints()));
      UIOutput.make(
              branch, "clickToExpand", messageLocator.getMessage("simplepage.click-to-expand"))
          .decorate(
              new UIFreeAttributeDecorator(
                  "title",
                  messageLocator
                      .getMessage("simplepage.expand-for-student")
                      .replace("{}", user.displayName)));

      UIOutput.make(branch, "authorUUID", user.userId);
    }

    UIForm gradingForm = UIForm.make(tofill, "gradingForm");

    gradingForm.viewparams = new SimpleViewParameters(UVBProducer.VIEW_ID);

    UIInput idInput = UIInput.make(gradingForm, "gradingForm-id", "gradingBean.id");
    UIInput jsIdInput = UIInput.make(gradingForm, "gradingForm-jsId", "gradingBean.jsId");
    UIInput pointsInput = UIInput.make(gradingForm, "gradingForm-points", "gradingBean.points");
    UIInput typeInput = UIInput.make(gradingForm, "gradingForm-type", "gradingBean.type");
    Object sessionToken = SessionManager.getCurrentSession().getAttribute("sakai.csrf.token");
    UIInput csrfInput =
        UIInput.make(
            gradingForm,
            "csrf",
            "gradingBean.csrfToken",
            (sessionToken == null ? "" : sessionToken.toString()));

    UIInitBlock.make(
        tofill,
        "gradingForm-init",
        "initGradingForm",
        new Object[] {
          idInput, pointsInput, jsIdInput, typeInput, csrfInput, "gradingBean.results"
        });
  }
  private void makeReleaseFeedbackLink(
      UIContainer tofill,
      ViewSubmissionsViewParams viewparams,
      List<AssignmentSubmission> submissionsWithHistory) {
    // check to see if there is anything to release yet
    boolean feedbackExists = false;
    // determine if we are releasing or retracting
    boolean release = false;

    if (submissionsWithHistory != null) {
      for (AssignmentSubmission submission : submissionsWithHistory) {
        if (submission.getSubmissionHistorySet() != null) {
          for (AssignmentSubmissionVersion version : submission.getSubmissionHistorySet()) {
            // only look at versions that have had feedback activity
            if (version.getLastFeedbackDate() != null) {
              feedbackExists = true;
              // if there is at least one version with unreleased feedback,
              // we will show the "Release" link
              if (!version.isFeedbackReleased()) {
                release = true;
              }
            }
          }
        }
      }
    }

    if (feedbackExists) {
      String releaseLinkText;
      if (release) {
        releaseLinkText =
            messageLocator.getMessage("assignment2.assignment_grade-assignment.feedback.release");
      } else {
        releaseLinkText =
            messageLocator.getMessage("assignment2.assignment_grade-assignment.feedback.retract");
      }
      UIForm releaseFeedbackForm = UIForm.make(tofill, "release-feedback-form");
      releaseFeedbackForm.parameters.add(
          new UIELBinding("#{ReleaseFeedbackAction.assignmentId}", assignmentId));
      releaseFeedbackForm.parameters.add(
          new UIELBinding("#{ReleaseFeedbackAction.releaseFeedback}", release));
      UICommand submitAllFeedbackButton =
          UICommand.make(
              releaseFeedbackForm,
              "release_feedback",
              releaseLinkText,
              "#{ReleaseFeedbackAction.execute}");

      UIInternalLink releaseFeedbackLink =
          UIInternalLink.make(tofill, "release-feedback-link", releaseLinkText, viewparams);
      Map<String, String> idmap = new HashMap<String, String>();
      //  idmap.put("onclick",
      // "document.getElementById('"+submitAllFeedbackButton.getFullID()+"').click(); return
      // false;");
      idmap.put(
          "onclick",
          "asnn2.releaseFeedbackDialog('"
              + submitAllFeedbackButton.getFullID()
              + "', "
              + release
              + "); return false;");
      releaseFeedbackLink.decorate(new UIFreeAttributeDecorator(idmap));
    } else {
      // show a disabled link if no feedback to release or retract
      UIOutput.make(
          tofill,
          "release_feedback_disabled",
          messageLocator.getMessage("assignment2.assignment_grade-assignment.feedback.release"));
    }
  }
  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"));
  }
Esempio n. 8
0
  public void fillComponents(
      UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
    if (((GeneralViewParameters) viewparams).getSendingPage() != -1) {
      // will fail if page not in this site
      // security then depends upon making sure that we only deal with this page
      try {
        simplePageBean.updatePageObject(((GeneralViewParameters) viewparams).getSendingPage());
      } catch (Exception e) {
        System.out.println("PagePicker permission exception " + e);
        return;
      }
    }

    UIOutput.make(tofill, "html")
        .decorate(new UIFreeAttributeDecorator("lang", localeGetter.get().getLanguage()))
        .decorate(new UIFreeAttributeDecorator("xml:lang", localeGetter.get().getLanguage()));

    boolean canEditPage = (simplePageBean.getEditPrivs() == 0);

    String source = ((GeneralViewParameters) viewparams).getSource();
    // summaryPage is the "index of pages". It has status icons and links, but isn't a chooser
    // otherwise we have the chooser page for the "add subpage" command
    boolean summaryPage = "summary".equals(source);

    if (summaryPage) {
      GeneralViewParameters view = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
      // path defaults to null, which is next
      UIOutput.make(tofill, "return-div");
      UIInternalLink.make(tofill, "return", messageLocator.getMessage("simplepage.return"), view);
      UIOutput.make(tofill, "title", messageLocator.getMessage("simplepage.page.index"));
    } else {
      UIOutput.make(tofill, "title", messageLocator.getMessage("simplepage.page.chooser"));
    }

    // Explain which pages may be deleted
    if (summaryPage && canEditPage) {
      UIOutput.make(tofill, "deleteAlert");
    }

    // this looks at pages in the site, which should be safe
    // but need to make sure the item we update is legal

    Long itemId = ((GeneralViewParameters) viewparams).getItemId();

    simplePageBean.setItemId(itemId);

    SimplePage page = simplePageBean.getCurrentPage();
    currentPageId = page.getPageId();

    if (itemId != null && itemId != -1) {
      SimplePageItem currentItem = simplePageToolDao.findItem(itemId);
      if (currentItem == null) return;
      // trying to hack on item not on this page
      if (currentItem.getPageId() != page.getPageId()) return;
    }

    // list we're going to display
    List<PageEntry> entries = new ArrayList<PageEntry>();

    // build map of all pages, so we can see if any are left over
    Map<Long, SimplePage> pageMap = new HashMap<Long, SimplePage>();

    Set<Long> sharedPages = new HashSet<Long>();

    // all pages
    List<SimplePage> pages = simplePageToolDao.getSitePages(simplePageBean.getCurrentSiteId());
    for (SimplePage p : pages) pageMap.put(p.getPageId(), p);

    // set of all top level pages, actually the items pointing to them
    List<SimplePageItem> sitePages =
        simplePageToolDao.findItemsInSite(toolManager.getCurrentPlacement().getContext());
    Set<Long> topLevelPages = new HashSet<Long>();
    for (SimplePageItem i : sitePages) topLevelPages.add(Long.valueOf(i.getSakaiId()));

    // this adds everything you can find from top level pages to entries. But make sure user can see
    // the tool
    for (SimplePageItem sitePageItem : sitePages) {
      // System.out.println("findallpages " + sitePageItem.getName() + " " + true);
      findAllPages(
          sitePageItem, entries, pageMap, topLevelPages, sharedPages, 0, true, canEditPage);
    }

    // warn students if we aren't showing all the pages
    if (!canEditPage && somePagesHavePrerequisites) UIOutput.make(tofill, "onlyseen");

    // now add everything we didn't find that way
    if (canEditPage && pageMap.size() > 0) {
      // marker
      PageEntry marker = new PageEntry();
      marker.level = -1;
      entries.add(marker);
      for (SimplePage p : pageMap.values()) {
        if (p.getOwner() == null) {
          PageEntry entry = new PageEntry();
          entry.pageId = p.getPageId();
          entry.itemId = null;
          entry.title = p.getTitle();
          entry.level = 0;

          // TopLevel determines if we can select the page.
          // Since this means that the page is detached, it isn't
          // a conflict to be able to select it.
          entry.toplevel = false;

          entries.add(entry);
        }
      }
    }

    if (canEditPage && sharedPages.size() > 0) UIOutput.make(tofill, "sharedpageexplanation");

    UIForm form = UIForm.make(tofill, "page-picker");
    Object sessionToken = SessionManager.getCurrentSession().getAttribute("sakai.csrf.token");
    if (sessionToken != null)
      UIInput.make(form, "csrf", "simplePageBean.csrfToken", sessionToken.toString());

    ArrayList<String> values = new ArrayList<String>();
    ArrayList<String> initValues = new ArrayList<String>();
    for (PageEntry entry : entries) {
      if (entry.level >= 0) {
        values.add(entry.pageId.toString());
        initValues.add("");
      }
    }

    UISelect select = null;
    if (summaryPage)
      select =
          UISelect.makeMultiple(
              form,
              "page-span",
              values.toArray(new String[1]),
              "#{simplePageBean.selectedEntities}",
              initValues.toArray(new String[1]));
    else
      select =
          UISelect.make(
              form,
              "page-span",
              values.toArray(new String[1]),
              "#{simplePageBean.selectedEntity}",
              null);

    int index = 0;
    boolean showDeleteButton = false;

    for (PageEntry entry : entries) {

      UIBranchContainer row = UIBranchContainer.make(form, "page:");
      if (entry.toplevel)
        row.decorate(
            new UIFreeAttributeDecorator("style", "list-style-type:none; margin-top:0.5em"));

      if (entry.level < 0) {
        UIOutput.make(row, "heading", messageLocator.getMessage("simplepage.chooser.unused"));
        if (summaryPage) UIOutput.make(row, "chooseall");
      }
      // if no itemid, it's unused. Only canedit people will see it
      else if (summaryPage && entry.itemId != null) {
        int level = entry.level;
        if (level > 5) level = 5;
        String imagePath = "/lessonbuilder-tool/images/";
        SimplePageItem item = simplePageBean.findItem(entry.itemId);
        SimplePageLogEntry logEntry = simplePageBean.getLogEntry(entry.itemId);
        String note = null;
        if (logEntry != null && logEntry.isComplete()) {
          imagePath += "checkmark.png";
          note = messageLocator.getMessage("simplepage.status.completed");
        } else if (logEntry != null && !logEntry.getDummy()) {
          imagePath += "hourglass.png";
          note = messageLocator.getMessage("simplepage.status.inprogress");
        } else if (!canEditPage && somePagesHavePrerequisites) {
          // it's too complex to compute prerequisites for all pages, and
          // I'm concerned that faculty may not be careful in setting them
          // for pages that would normally not be accessible. So if there are
          // any prerequisites in the site, only show pages that are
          // in progress or done.
          continue;
        } else {
          imagePath += "not-required.png";
        }
        UIOutput.make(row, "status-image").decorate(new UIFreeAttributeDecorator("src", imagePath));
        GeneralViewParameters p = new GeneralViewParameters(ShowPageProducer.VIEW_ID);
        p.setSendingPage(entry.pageId);
        p.setItemId(entry.itemId);
        // reset the path to the saved one
        p.setPath("log");
        UIInternalLink.make(row, "link", p)
            .decorate(new UIFreeAttributeDecorator("style", "padding-left: " + (2 * level) + "em"));
        String levelstr = null;
        if (level > 0)
          levelstr =
              messageLocator
                  .getMessage("simplepage.status.level")
                  .replace("{}", Integer.toString(level));
        if (levelstr != null) {
          if (note != null) note = levelstr + " " + note;
          else note = levelstr;
        }
        if (note != null) UIOutput.make(row, "link-note", note + " ");
        UIOutput.make(row, "link-text", entry.title);

        if (enableShowItems) {
          UIOutput.make(row, "item-list-toggle");
          UIOutput.make(row, "itemListContainer")
              .decorate(
                  new UIFreeAttributeDecorator("style", "margin-left: " + (3 * level) + "em"));
          UIOutput.make(row, "itemList");

          Set<String> myGroups = simplePageBean.getMyGroups();

          for (SimplePageItem pageItem : simplePageToolDao.findItemsOnPage(entry.pageId)) {

            // if item is group controlled, skip if user isn't in one of the groups
            Collection<String> itemGroups = null;
            try {
              itemGroups = simplePageBean.getItemGroups(pageItem, null, false);
            } catch (IdUnusedException e) {
              // underlying assignment, etc, doesn't exist. skip the item
              continue;
            }
            if (itemGroups != null) {
              boolean groupsOk = false;
              for (String group : itemGroups) {
                if (myGroups.contains(group)) {
                  groupsOk = true;
                  break;
                }
              }
              if (!groupsOk) continue;
            }

            UIBranchContainer itemListItem = UIBranchContainer.make(row, "item:");

            if (pageItem.isRequired()) {
              UIOutput.make(itemListItem, "required-image");
            } else {
              UIOutput.make(itemListItem, "not-required-image");
            }

            UIOutput.make(itemListItem, "item-icon").decorate(getImageSourceDecorator(pageItem));

            if (pageItem.isPrerequisite()) {
              itemListItem.decorate(new UIFreeAttributeDecorator("class", "disabled-text-item"));
            }

            if (SimplePageItem.TEXT == pageItem.getType()) {
              UIOutput.make(
                      itemListItem,
                      "name",
                      messageLocator.getMessage("simplepage.chooser.textitemplaceholder"))
                  .decorate(new UIFreeAttributeDecorator("class", "text-item-placeholder"));
            } else if (SimplePageItem.BREAK == pageItem.getType()) {
              String text = null;
              if ("section".equals(pageItem.getFormat()))
                text = messageLocator.getMessage("simplepage.break-here");
              else text = messageLocator.getMessage("simplepage.break-column-here");
              UIOutput.make(itemListItem, "name", text)
                  .decorate(new UIFreeAttributeDecorator("class", "text-item-placeholder"));

            } else {
              UIOutput.make(itemListItem, "name", pageItem.getName());
            }
            // UIOutput.make(itemListItem, "page1",
            // Boolean.toString(lessonsAccess.isItemAccessible(pageItem.getId(),simplePageBean.getCurrentSiteId(),"c08d3ac9-c717-472a-ad91-7ce0b434f42f", simplePageBean)));
          }
        }
        index++;

        // for pagepicker or summary if canEdit and page doesn't have an item
      } else {
        int level = entry.level;
        if (level > 5) level = 5;
        if (!summaryPage /*&& !entry.toplevel*/) { // i.e. pagepicker; for the moment to edit
                                                   // something you need to attach it to something
          UISelectChoice.make(row, "select", select.getFullID(), index)
              .decorate(
                  new UIFreeAttributeDecorator(
                      "title", entry.title + " " + messageLocator.getMessage("simplepage.select")));
        } else if (summaryPage) { // i.e. summary if canEdit and page doesn't have an item
          UISelectChoice.make(row, "select-for-deletion", select.getFullID(), index)
              .decorate(
                  new UIFreeAttributeDecorator(
                      "title",
                      entry.title
                          + " "
                          + messageLocator.getMessage("simplepage.select-for-deletion")));
          showDeleteButton = true; // at least one item to delete
        }

        GeneralViewParameters params = new GeneralViewParameters();
        params.viewID = PreviewProducer.VIEW_ID;
        params.setSendingPage(entry.pageId);

        UIInternalLink.make(row, "link", params)
            .decorate(new UIFreeAttributeDecorator("style", "padding-left: " + (2 * level) + "em"))
            .decorate(new UIFreeAttributeDecorator("target", "_blank"));
        String levelstr =
            messageLocator
                    .getMessage("simplepage.status.level")
                    .replace("{}", Integer.toString(level))
                + " ";
        if (level > 0) UIOutput.make(row, "link-note", levelstr);
        UIOutput.make(row, "link-text", entry.title);

        index++;
      }

      if (canEditPage
          && entry != null
          && entry.pageId != null
          && sharedPages.contains(entry.pageId)) {
        UIOutput.make(row, "shared");
      }

      // debug code for development. this will be removed at some point
      // UIOutput.make(row, "page2",
      // lessonsAccess.printPath(lessonsAccess.getPagePaths(entry.pageId)));
      // UIOutput.make(row, "page1", Boolean.toString(lessonsAccess.isPageAccessible(entry.pageId,
      // simplePageBean.getCurrentSiteId(), "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
      // simplePageBean)));

      if (ServerConfigurationService.getBoolean("lessonbuilder.accessibilitydebug", false)) {
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isPageAccessible(
                entry.pageId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                null)) {
          UIOutput.make(row, "page1");
        }
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isPageAccessible(
                entry.pageId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                simplePageBean)) {
          UIOutput.make(row, "page2");
        }
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isItemAccessible(
                entry.itemId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                null)) {
          UIOutput.make(row, "item1");
        }
        if (entry != null
            && entry.pageId != null
            && lessonsAccess.isItemAccessible(
                entry.itemId,
                simplePageBean.getCurrentSiteId(),
                "c08d3ac9-c717-472a-ad91-7ce0b434f42f",
                simplePageBean)) {
          UIOutput.make(row, "item2");
        }
      }
    }

    if (!summaryPage) {

      UIInput.make(form, "item-id", "#{simplePageBean.itemId}");

      if (itemId == -1 && !((GeneralViewParameters) viewparams).newTopLevel) {
        UIOutput.make(form, "hr");
        UIOutput.make(form, "options");
        UIBoundBoolean.make(form, "subpage-next", "#{simplePageBean.subpageNext}", false);
        UIBoundBoolean.make(form, "subpage-button", "#{simplePageBean.subpageButton}", false);
      }

      String returnView = ((GeneralViewParameters) viewparams).getReturnView();
      if (returnView != null && returnView.equals("reorder")) {
        // return to Reorder, to add items from this page
        UICommand.make(
            form,
            "submit",
            messageLocator.getMessage("simplepage.chooser.select"),
            "#{simplePageBean.selectPage}");
      } else if (((GeneralViewParameters) viewparams).newTopLevel) {
        UIInput.make(
            form,
            "addBefore",
            "#{simplePageBean.addBefore}",
            ((GeneralViewParameters) viewparams).getAddBefore());
        UICommand.make(
            form,
            "submit",
            messageLocator.getMessage("simplepage.chooser.select"),
            "#{simplePageBean.addOldPage}");
      } else {
        UIInput.make(
            form,
            "addBefore",
            "#{simplePageBean.addBefore}",
            ((GeneralViewParameters) viewparams).getAddBefore());
        UICommand.make(
            form,
            "submit",
            messageLocator.getMessage("simplepage.chooser.select"),
            "#{simplePageBean.createSubpage}");
      }
      UICommand.make(
          form,
          "cancel",
          messageLocator.getMessage("simplepage.cancel"),
          "#{simplePageBean.cancel}");
    } else if (showDeleteButton) {
      UICommand.make(
          form,
          "submit",
          messageLocator.getMessage("simplepage.delete-selected"),
          "#{simplePageBean.deletePages}");
    }
  }