Example #1
0
  public String getPrivateCollection() {
    String collectionId =
        Entity.SEPARATOR
            + "private"
            + REFERENCE_ROOT
            + Entity.SEPARATOR
            + ToolManager.getCurrentPlacement().getContext()
            + Entity.SEPARATOR;

    try {
      AssessmentService.getContentHostingService().checkCollection(collectionId);
    } catch (IdUnusedException e) {
      try {
        ResourcePropertiesEdit resourceProperties =
            AssessmentService.getContentHostingService().newResourceProperties();
        resourceProperties.addProperty(
            ResourceProperties.PROP_DISPLAY_NAME, ToolManager.getCurrentPlacement().getContext());
        // resourceProperties.addProperty(ResourceProperties.PROP_HIDDEN_WITH_ACCESSIBLE_CONTENT,
        // "true");

        ContentCollectionEdit edit =
            (ContentCollectionEdit)
                AssessmentService.getContentHostingService()
                    .addCollection(collectionId, resourceProperties);

        edit.setPublicAccess();
        AssessmentService.getContentHostingService().commitCollection(edit);
      } catch (Exception ee) {
        log.warn(ee.getMessage());
      }
    } catch (Exception e) {
      log.warn(e.getMessage());
    }

    try {
      if (
      /*!"true".equals(AssessmentService.getContentHostingService().getProperties(Entity.SEPARATOR + "private"+ Entity.SEPARATOR).get(ResourceProperties.PROP_HIDDEN_WITH_ACCESSIBLE_CONTENT)) || */ !AssessmentService
          .getContentHostingService()
          .isPubView(collectionId)) {

        ContentCollectionEdit edit =
            AssessmentService.getContentHostingService().editCollection(collectionId);
        ResourcePropertiesEdit resourceProperties = edit.getPropertiesEdit();
        // resourceProperties.addProperty(ResourceProperties.PROP_HIDDEN_WITH_ACCESSIBLE_CONTENT,
        // "true");

        edit.setPublicAccess();

        AssessmentService.getContentHostingService().commitCollection(edit);
      }
    } catch (Exception e) {
      log.warn(e.getMessage());
    }

    return collectionId + "uploads" + Entity.SEPARATOR;
  }
Example #2
0
  /**
   * Update/save any change(s)
   *
   * @return return "compse" for immediately navigating to compose page
   */
  public String processUpdateOptions() {

    log.info(
        "Mailtool-Options Updated"
            + " for SITE["
            + getSiteID()
            + "] By["
            + m_userDirectoryService.getCurrentUser().getId()
            + "-"
            + getCurrentUser().getEmail()
            + "]");

    if (isShowRenamingRoles()) {
      int i = 1;
      Configuration c = null;
      Iterator iter = renamedRoles.iterator();

      while (iter.hasNext()) {
        c = (Configuration) iter.next();
        if (c.getSingularNew().trim().equals("") != true && c.getSingularNew() != null)
          setConfigParam("role" + i + "singular", c.getSingularNew());
        if (c.getPluralNew().trim().equals("") != true && c.getPluralNew() != null)
          setConfigParam("role" + i + "plural", c.getPluralNew());
        i++;
      }
    }
    setConfigParam("recipview", getViewChoice());
    setConfigParam("sendmecopy", isSendMeCopy() ? "yes" : "no");
    setConfigParam("emailarchive", isArchiveMessage() ? "yes" : "no");
    String reply = getReplyToSelected().trim().toLowerCase();
    if (reply.equals("yes")) {
      setConfigParam("replyto", "yes");
    } else if (reply.equals("no")) {
      setConfigParam("replyto", "no");
    } else if (reply.equals("otheremail")) {
      setConfigParam("replyto", getReplyToOtherEmail().trim());
    }
    if (getTextFormat().trim().toLowerCase().equals("htmltext")) {
      setConfigParam("messageformat", "htmltext");
    } else {
      setConfigParam("messageformat", "plaintext");
    }
    ToolManager.getCurrentPlacement().save();
    // reset Mailtool (with updated options)
    ToolSession ts =
        SessionManager.getCurrentSession()
            .getToolSession(ToolManager.getCurrentPlacement().getId());
    ts.clearAttributes();
    return "compose"; // go to Compose
  }
Example #3
0
  /* (non-Javadoc)
   * @see org.sakaiproject.cheftool.VelocityPortletPaneledAction#toolModeDispatch(java.lang.String, java.lang.String, javax.servlet.http.HttpServletRequest, javax.servlet.http.HttpServletResponse)
   */
  protected void toolModeDispatch(
      String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
      throws ToolException {
    ToolSession toolSession = SessionManager.getCurrentToolSession();
    SessionState state = getState(req);

    if (MODE_DONE.equals(toolSession.getAttribute(LINK_MODE))) {

      Tool tool = ToolManager.getCurrentTool();

      String url =
          (String)
              SessionManager.getCurrentToolSession()
                  .getAttribute(tool.getId() + Tool.HELPER_DONE_URL);

      SessionManager.getCurrentToolSession().removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);
      SessionManager.getCurrentToolSession().removeAttribute(LINK_MODE);

      try {
        res.sendRedirect(url);
      } catch (IOException e) {
        logger.warn("IOException: ", e);
      }
      return;
    } else if (sendToHelper(req, res, req.getPathInfo())) {
      return;
    } else {
      super.toolModeDispatch(methodBase, methodExt, req, res);
    }
  }
Example #4
0
  public String processCreateNew() {
    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      return "permission_error";
    }
    this.userId = SessionManager.getCurrentSessionUserId();
    this.siteId = ToolManager.getCurrentPlacement().getContext();
    this.currentGradebook = gradebookManager.createEmptyGradebook(this.userId, this.siteId);
    this.oldGradebook = gradebookManager.createEmptyGradebook(this.userId, this.siteId);
    this.csv = null;
    this.newTemplate = null;
    this.delimiter = COMMA_DELIM_STR;

    return "create_gradebook";
  }
Example #5
0
  // XXX this should not be here!! The RequestHelper should perform this
  // functionality.
  private boolean isPageToolDefault(HttpServletRequest request) {
    // SAK-13408 - Tomcat and WAS have different URL structures; Attempting to add a
    // link or image would lead to site unavailable errors in websphere if the tomcat
    // URL structure is used.
    if ("websphere".equals(ServerConfigurationService.getString("servlet.container"))) {
      String tid = org.sakaiproject.tool.cover.ToolManager.getCurrentPlacement().getId();
      if (request.getPathInfo() != null
          && request.getPathInfo().startsWith("/tool/" + tid + "/helper/")) {
        return false;
      }
    } else {
      if (request.getPathInfo() != null && request.getPathInfo().startsWith("/helper/")) {
        return false;
      }
    }

    String action = request.getParameter(RequestHelper.ACTION);
    if (action != null && action.length() > 0) {
      return false;
    }

    String pageName = request.getParameter(ViewBean.PAGE_NAME_PARAM);
    if (pageName == null || pageName.trim().length() == 0) {
      return true;
    } else {
      return false;
    }
  }
Example #6
0
  public String getUrl() {

    if (type == TYPE_FORUM_TOPIC) {
      if (topic == null) topic = getTopicById(true, id);
      if (topic == null)
        return "javascript:alert('" + messageLocator.getMessage("simplepage.forumdeleted") + "')";
    } else {
      if (forum == null) forum = getForumById(true, id);
      if (forum == null)
        return "javascript:alert('" + messageLocator.getMessage("simplepage.forumdeleted") + "')";
    }

    Site site = null;
    try {
      site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
    } catch (Exception impossible) {
      return null;
    }
    ToolConfiguration tool = site.getToolForCommonId("sakai.forums");

    // LSNBLDR-21. If the tool is not in the current site we shouldn't return a url
    if (tool == null) {
      return null;
    }

    String placement = tool.getId();

    if (type == TYPE_FORUM_TOPIC)
      // if /direct doesn't work, but that was only in one beta release
      //  return "/messageforums-tool/jsp/discussionForum/message/dfAllMessagesDirect.jsf?topicId="
      // + id + "&placementId=" + placement;
      return "/direct/forum_topic/" + id;
    else return "/direct/forum/" + id;
  }
  protected void toolModeDispatch(
      String methodBase, String methodExt, HttpServletRequest req, HttpServletResponse res)
      throws ToolException {
    SessionState sstate = getState(req);
    ToolSession toolSession = SessionManager.getCurrentToolSession();

    String mode = (String) sstate.getAttribute(STATE_MODE);
    Object started = toolSession.getAttribute(STARTED);

    if (mode == null && started != null) {
      toolSession.removeAttribute(STARTED);
      Tool tool = ToolManager.getCurrentTool();

      String url =
          (String)
              SessionManager.getCurrentToolSession()
                  .getAttribute(tool.getId() + Tool.HELPER_DONE_URL);

      SessionManager.getCurrentToolSession().removeAttribute(tool.getId() + Tool.HELPER_DONE_URL);

      try {
        res.sendRedirect(url);
      } catch (IOException e) {
        Log.warn("chef", this + " : ", e);
      }
      return;
    }

    super.toolModeDispatch(methodBase, methodExt, req, res);
  }
 private String getContextId() {
   if (TestUtil.isRunningTests()) {
     return "test-context";
   }
   Placement placement = ToolManager.getCurrentPlacement();
   String presentSiteId = placement.getContext();
   return presentSiteId;
 }
Example #9
0
  /**
   * Get the current site id
   *
   * @throws SessionDataException
   * @return Site id (GUID)
   */
  private String getSiteId() throws SessionDataException {
    Placement placement = ToolManager.getCurrentPlacement();

    if (placement == null) {
      throw new SessionDataException("No current tool placement");
    }
    return placement.getContext();
  }
Example #10
0
  // find topics in site, but organized by forum
  public List<LessonEntity> getEntitiesInSite(SimplePageBean bean) {

    List<LessonEntity> ret = new ArrayList<LessonEntity>();

    // LSNBLDR-21. If the tool is not in the current site we shouldn't query
    // for topics owned by the tool.
    Site site = null;
    try {
      site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
    } catch (Exception impossible) {
      return ret;
    }

    ToolConfiguration tool = site.getToolForCommonId("sakai.forums");

    if (tool == null) {

      // Forums is not in this site. Move on to the next provider.

      if (nextEntity != null) ret.addAll(nextEntity.getEntitiesInSite());

      return ret;
    }

    // ForumEntity e = new ForumEntity(TYPE_FORUM_TOPIC, 3L, 2);

    // e.setGroups(Arrays.asList("1c24287b-b880-43da-8cdd-c6cdc1249c5c",
    // "75184424-853e-4dd4-9e92-980c851f0580"));
    // e.setGroups(Arrays.asList("75184424-853e-4dd4-9e92-980c851f0580"));

    SortedSet<DiscussionForum> forums =
        new TreeSet<DiscussionForum>(new ForumBySortIndexAscAndCreatedDateDesc());
    for (DiscussionForum forum : forumManager.getForumsForMainPage()) forums.add(forum);

    // security. assume this is only used in places where it's OK, so skip security checks
    for (DiscussionForum forum : forums) {
      if (!forum.getDraft()) {
        ForumEntity entity = new ForumEntity(TYPE_FORUM_FORUM, forum.getId(), 1);
        entity.forum = forum;
        ret.add(entity);
        for (Object o : forum.getTopicsSet()) {
          DiscussionTopic topic = (DiscussionTopic) o;
          if (topic.getDraft().equals(Boolean.FALSE)) {
            entity = new ForumEntity(TYPE_FORUM_TOPIC, topic.getId(), 2);
            entity.topic = topic;
            ret.add(entity);
          }
        }
      }
    }

    if (nextEntity != null) ret.addAll(nextEntity.getEntitiesInSite(bean));

    return ret;
  }
  public void doEdit(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = getTitleString(request);
    if (title != null) response.setTitle(title);

    Context context = new VelocityContext();
    context.put("tlang", rb);
    context.put("validator", validator);
    sendAlert(request, context);

    PortletURL url = response.createActionURL();
    context.put("actionUrl", url.toString());
    context.put("doCancel", "sakai.cancel");
    context.put("doUpdate", "sakai.update");

    // get current site
    Placement placement = ToolManager.getCurrentPlacement();
    String siteId = "";

    // find the right LTIContent object for this page
    String source = placement.getPlacementConfig().getProperty(SOURCE);
    Long key = getContentIdFromSource(source);
    if (key == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find content id placement=" + placement.getId() + " source=" + source);
      return;
    }

    Map<String, Object> content = m_ltiService.getContent(key);
    if (content == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find content item placement=" + placement.getId() + " key=" + key);
      return;
    }

    // attach the ltiToolId to each model attribute, so that we could have the tool configuration
    // page for multiple tools
    String foundLtiToolId = content.get(m_ltiService.LTI_TOOL_ID).toString();
    Map<String, Object> tool = m_ltiService.getTool(Long.valueOf(foundLtiToolId));
    if (tool == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find tool placement=" + placement.getId() + " key=" + foundLtiToolId);
      return;
    }

    String[] contentToolModel = m_ltiService.getContentModel(Long.valueOf(foundLtiToolId));
    String formInput = m_ltiService.formInput(content, contentToolModel);
    context.put("formInput", formInput);

    vHelper.doTemplate(vengine, "/vm/edit.vm", context, out);
  }
Example #12
0
  public String processGradebookUpdate() {
    try {
      if (!this.checkAccess()) {
        throw new PermissionException(
            SessionManager.getCurrentSessionUserId(), "syllabus_access_athz", "");
      }

    } catch (PermissionException e) {
      // logger.info(this + ".getEntries() in PostemTool " + e);
      FacesContext.getCurrentInstance()
          .addMessage(
              null,
              MessageUtils.getMessage(
                  FacesMessage.SEVERITY_ERROR,
                  "error_permission",
                  (new Object[] {e.toString()}),
                  FacesContext.getCurrentInstance()));
      this.currentGradebook = null;
      this.csv = null;
      this.newTemplate = null;
      return "permission_error";
    }
    this.userId = SessionManager.getCurrentSessionUserId();
    this.siteId = ToolManager.getCurrentPlacement().getContext();

    Long currentGbId = ((Gradebook) gradebookTable.getRowData()).getId();
    currentGradebook = gradebookManager.getGradebookByIdWithHeadingsAndStudents(currentGbId);

    oldGradebook =
        gradebookManager.createEmptyGradebook(
            currentGradebook.getCreator(), currentGradebook.getContext());
    oldGradebook.setId(currentGradebook.getId());
    oldGradebook.setStudents(currentGradebook.getStudents());

    gradebooks = null;

    /*
     * if(new Boolean(true).equals(currentGradebook.getReleased())) {
     * this.release = "Yes"; } else { this.release = "No"; }
     */

    if (currentGradebook.getFileReference() != null) {
      attachment =
          EntityManager.newReference(
              contentHostingService.getReference(currentGradebook.getFileReference()));
    }

    this.csv = null;
    this.newTemplate = null;
    this.delimiter = COMMA_DELIM_STR;

    return "create_gradebook";
  }
Example #13
0
  /**
   * Get the current site id
   *
   * @param state SessionState
   * @throws SessionDataException
   * @return Site id (GUID)
   */
  private String getSiteId(SessionState state) throws SessionDataException {
    // Check if it is state (i.e. we are a helper in site.info)
    String retval = (String) state.getAttribute(STATE_SITE_INSTANCE_ID);
    if (retval != null) return retval;

    // If it is not in state, we must be stand alone
    Placement placement = ToolManager.getCurrentPlacement();

    if (placement == null) {
      throw new SessionDataException("No current tool placement");
    }
    return placement.getContext();
  }
  public boolean setTemporaryPlacement(Site site) {
    if (site == null) return false;

    Placement ppp = ToolManager.getCurrentPlacement();
    if (ppp != null && site.getId().equals(ppp.getContext())) {
      return true;
    }

    // Create a site-only placement
    Placement placement =
        new org.sakaiproject.util.Placement(
            "portal-temporary", /* toolId */
            null, /* tool */
            null,
            /* config */ null, /* context */
            site.getId(), /* title */
            null);

    ThreadLocalManager.set(CURRENT_PLACEMENT, placement);

    // Debugging
    ppp = ToolManager.getCurrentPlacement();
    if (ppp == null) {
      System.out.println("WARNING portal-temporary placement not set - null");
    } else {
      String cont = ppp.getContext();
      if (site.getId().equals(cont)) {
        return true;
      } else {
        System.out.println(
            "WARNING portal-temporary placement mismatch site="
                + site.getId()
                + " context="
                + cont);
      }
    }
    return false;
  }
Example #15
0
    public BaseResourceEdit(String id, SyllabusData data) {
      Placement placement = ToolManager.getCurrentPlacement();
      String currentSiteId = placement.getContext();

      m_id = id;

      m_data = data;

      m_reference = Entity.SEPARATOR + currentSiteId + Entity.SEPARATOR + m_id;

      m_properties = new BaseResourcePropertiesEdit();

      m_properties.addProperty(ResourceProperties.PROP_DISPLAY_NAME, data.getTitle());
    }
  /**
   * Check if the current user has permission as author.
   *
   * @return true if the current user has permission to perform this action, false if not.
   */
  public boolean getIsInstructor() {
    FacesContext context = FacesContext.getCurrentInstance();
    ResourceLoader bundle = new ResourceLoader("org.etudes.tool.melete.bundle.Messages");

    try {
      return meleteSecurityService.allowAuthor(ToolManager.getCurrentPlacement().getContext());
    } catch (Exception e) {
      String errMsg = bundle.getString("auth_failed");
      context.addMessage(
          null, new FacesMessage(FacesMessage.SEVERITY_ERROR, "auth_failed", errMsg));
      logger.warn(e.toString());
    }
    return false;
  }
Example #17
0
  /**
   * This method perform Remove process for removing attendee from the waiting list in the
   * event/meeting.
   *
   * @param meeting a SignupMeeting object.
   * @param timeslot a SignupTimeslot object.
   * @param waiter a SignupAttendee object.
   * @return a SignupMeeting object, which is a refreshed updat-to-date data.
   * @throws Exception throw if anything goes wrong.
   */
  public SignupMeeting removeFromWaitingList(
      SignupMeeting meeting, SignupTimeslot timeslot, SignupAttendee waiter) throws Exception {
    try {

      handleVersion(meeting, timeslot, waiter);
      if (ToolManager.getCurrentPlacement() != null) {
        String signupEventType =
            isOrganizer
                ? SignupEventTypes.EVENT_SIGNUP_REMOVE_ATTENDEE_WL_L
                : SignupEventTypes.EVENT_SIGNUP_REMOVE_ATTENDEE_WL_S;
        Utilities.postEventTracking(
            signupEventType,
            ToolManager.getCurrentPlacement().getContext()
                + " meetingId:"
                + meeting.getId()
                + " -removed from wlist on TS:"
                + SignupDateFormat.format_date_h_mm_a(timeslot.getStartTime()));
      }
      logger.debug(
          "Meeting Name:"
              + meeting.getTitle()
              + " - UserId:"
              + currentUserId
              + " - has removed attendee(userId):"
              + waiter.getAttendeeUserId()
              + " from waiting list"
              + " at timeslot started at:"
              + SignupDateFormat.format_date_h_mm_a(timeslot.getStartTime()));
    } catch (PermissionException pe) {
      throw new SignupUserActionException(Utilities.rb.getString("no.permissoin.do_it"));
    } finally {
      meeting = reloadMeeting(meeting.getId());
    }
    // TODO calendar event id;
    return meeting;
  }
Example #18
0
  // return the list of groups if the item is only accessible to specific groups
  // null if it's accessible to the whole site.
  public List<String> getGroups(boolean nocache) {

    // don't need cache, since simplepagebean is now caching groups
    //	List<String>ret = (List<String>)topicCache.get(id);
    //	if (!nocache && ret != null) {
    //	    if (ret.size() == 0)
    //		return null;
    //	    else
    //		return ret;
    //	} else {
    //	}

    if (type != TYPE_FORUM_TOPIC) return null;

    List<String> ret = new ArrayList<String>();

    if (topic == null) topic = getTopicById(true, id);
    if (topic == null) return null;

    Set<DBMembershipItem> oldMembershipItemSet =
        uiPermissionsManager.getTopicItemsSet((DiscussionTopic) topic);

    Collection<Group> groups = null;

    try {
      Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
      groups = site.getGroups();
    } catch (Exception e) {
      System.out.println("Unable to get site info for getGroups " + e);
    }

    // now change any existing ones into null
    for (DBMembershipItem item : oldMembershipItemSet) {
      if (item.getPermissionLevelName().equals("Contributor")
          && item.getType().equals(MembershipItem.TYPE_GROUP)) {
        String name = item.getName(); // oddly, this is the actual name, not the ID
        for (Group group : groups) {
          if (name.equals(group.getTitle())) ret.add(group.getId());
        }
      }
    }

    //	topicCache.put(id, ret, DEFAULT_EXPIRATION);
    if (ret.size() == 0) return null;
    else return ret;
  }
  /**
   * Add a published assessment to gradebook.
   *
   * @param publishedAssessment the published assessment
   * @param g the Gradebook Service
   * @return false: cannot add to gradebook
   * @throws java.lang.Exception
   */
  public boolean addToGradebook(PublishedAssessmentData publishedAssessment, GradebookService g)
      throws Exception {
    // log.info("total point(s) is/are =" +
    //          publishedAssessment.getTotalScore().longValue());
    // log.info("gradebookId =" + GradebookFacade.getGradebookUId());
    boolean added = false;
    // log.info("GradebookService instance=" + g);
    String gradebookUId = GradebookFacade.getGradebookUId();
    if (gradebookUId == null) {
      return false;
    }

    // log.info("inside addToGradebook, gradebook exists? " +
    //          g.isGradebookDefined(gradebookUId));
    if (g.isGradebookDefined(gradebookUId)) {

      // Tool name code added by Josh Holtzman
      Tool tool = ToolManager.getTool("sakai.samigo");
      String appName = null;

      if (tool == null) {
        log.warn(
            "could not get tool named sakai.samigo, "
                + "so we're going to assume we're called 'Tests & Quizzes'");
        appName = "Tests & Quizzes";
      } else {
        appName = tool.getTitle();
      }

      String title = StringEscapeUtils.unescapeHtml(publishedAssessment.getTitle());
      if (!g.isAssignmentDefined(gradebookUId, title)) {
        g.addExternalAssessment(
            gradebookUId,
            publishedAssessment.getPublishedAssessmentId().toString(),
            null,
            title,
            publishedAssessment.getTotalScore().doubleValue(),
            publishedAssessment.getAssessmentAccessControl().getDueDate(),
            appName); // Use the app name from sakai
        added = true;
      }
    }
    return added;
  }
  public void processActionEdit(ActionRequest request, ActionResponse response)
      throws PortletException, IOException {
    // TODO: Check Role

    // Stay in EDIT mode unless we are successful
    response.setPortletMode(PortletMode.EDIT);

    Placement placement = ToolManager.getCurrentPlacement();
    // get the site toolConfiguration, if this is part of a site.
    ToolConfiguration toolConfig = SiteService.findTool(placement.getId());
    String id = request.getParameter(LTIService.LTI_ID);
    String toolId = request.getParameter(LTIService.LTI_TOOL_ID);
    Properties reqProps = new Properties();
    Enumeration names = request.getParameterNames();
    while (names.hasMoreElements()) {
      String name = (String) names.nextElement();
      reqProps.setProperty(name, request.getParameter(name));
    }
    Object retval = m_ltiService.updateContent(Long.parseLong(id), reqProps);
    placement.save();

    response.setPortletMode(PortletMode.VIEW);
  }
Example #21
0
  /*
   * public void setRelease(String release) { this.release = release; }
   *
   * public String getRelease() { return release; }
   */
  public ArrayList getGradebooks() {
    if (userId == null) {
      userId = SessionManager.getCurrentSessionUserId();

      if (userId != null) {
        try {
          userEid = UserDirectoryService.getUserEid(userId);
        } catch (UserNotDefinedException e) {
          LOG.error("UserNotDefinedException", e);
        }
      }
    }

    Placement placement = ToolManager.getCurrentPlacement();
    String currentSiteId = placement.getContext();

    siteId = currentSiteId;
    try {
      if (checkAccess()) {
        // logger.info("**** Getting by context!");
        gradebooks =
            new ArrayList(gradebookManager.getGradebooksByContext(siteId, sortBy, ascending));
      } else {
        // logger.info("**** Getting RELEASED by context!");
        gradebooks =
            new ArrayList(
                gradebookManager.getReleasedGradebooksByContext(siteId, sortBy, ascending));
      }
    } catch (Exception e) {
      gradebooks = null;
    }

    if (gradebooks != null && gradebooks.size() > 0) gradebooksExist = true;
    else gradebooksExist = false;

    return gradebooks;
  }
Example #22
0
 public boolean checkAccess() {
   // return true;
   return SiteService.allowUpdateSite(ToolManager.getCurrentPlacement().getContext());
 }
Example #23
0
 public String getTitle() {
   return ToolManager.getCurrentTool().getTitle();
 }
Example #24
0
 private String getCurrentSiteId() {
   Placement placement = ToolManager.getCurrentPlacement();
   return placement.getContext();
 }
  public ModelAndView handleRequest(
      Object requestModel, Map request, Map session, Map application, Errors errors) {
    Presentation pres = (Presentation) requestModel;

    if (pres.getSecretExportKey() == null) {
      if (!pres.getIsPublic()) {
        if (getAuthManager().getAgent().isInRole(Agent.ROLE_ANONYMOUS)) {
          try {
            Site site = SiteService.getSite(pres.getSiteId());
            ToolConfiguration toolConfig =
                site.getToolForCommonId(PresentationFunctionConstants.PRES_TOOL_ID);
            String placement = toolConfig.getId();
            ToolSession ts = SessionManager.getCurrentSession().getToolSession(placement);
            SessionManager.setCurrentToolSession(ts);

            SessionManager.getCurrentSession()
                .setAttribute(Tool.HELPER_DONE_URL, pres.getExternalUri());

            Map model = new Hashtable();
            model.put("sakai.tool.placement.id", placement);
            return new ModelAndView("authnRedirect", model);

          } catch (IdUnusedException e) {
            logger.error("", e);
          }
        } else {

          getAuthzManager()
              .checkPermission(PresentationFunctionConstants.VIEW_PRESENTATION, pres.getId());
        }
      }

      if (pres.isExpired()
          && !pres.getOwner().getId().equals(getAuthManager().getAgent().getId())) {
        return new ModelAndView("expired");
      }
    }

    if (!pres.isPreview()) {
      logViewedPresentation(pres);
    }

    Hashtable model = new Hashtable();

    try {
      model.put("presentation", pres);
      Document doc = null;

      if (pres.getPresentationType().equals(Presentation.TEMPLATE_TYPE))
        doc = getPresentationManager().createDocument(pres);
      else {
        String page = (String) request.get("page");
        if (pres.isPreview()) {
          doc = getPresentationManager().getPresentationPreviewLayoutAsXml(pres, page);
        } else {
          doc = getPresentationManager().getPresentationLayoutAsXml(pres, page);
        }
      }
      Site site = SiteService.getSite(pres.getSiteId());
      getAuthzManager().pushAuthzGroups(site.getId());
      ToolConfiguration toolConfig =
          site.getToolForCommonId(PresentationFunctionConstants.PRES_TOOL_ID);
      String placement = toolConfig.getId();
      model.put("placementId", placement);
      if (doc != null) model.put("document", doc);
      else return new ModelAndView("notFound", model);
      model.put("renderer", getTransformer(pres, request));
      model.put("uriResolver", getUriResolver());

      if (!getAuthManager().getAgent().isInRole(Agent.ROLE_ANONYMOUS)) {
        model.put("currentAgent", getAuthManager().getAgent());
      }

      if (!pres.isPreview()) {
        model.put(
            "comments",
            getPresentationManager()
                .getPresentationComments(pres.getId(), getAuthManager().getAgent()));

        boolean allowComments =
            getAuthzManager()
                .isAuthorized(PresentationFunctionConstants.COMMENT_PRESENTATION, pres.getId());
        model.put("allowComments", allowComments);
      } else {
        model.put("allowComments", pres.isAllowComments());
      }

      if (request.get(BindException.ERROR_KEY_PREFIX + "newComment") == null) {
        request.put(
            BindException.ERROR_KEY_PREFIX + "newComment",
            new BindException(new PresentationComment(), "newComment"));
      }

    } catch (PersistenceException e) {
      logger.error("", e);
      throw new OspException(e);
    } catch (IdUnusedException e) {
      logger.error("", e);
    }

    boolean headers = pres.getTemplate().isIncludeHeaderAndFooter();
    String viewName = "withoutHeader";

    if (headers) {
      if (ToolManager.getCurrentPlacement() == null) {
        viewName = "withHeaderStandalone";
      } else {
        viewName = "withHeader";
      }
    }
    return new ModelAndView(viewName, model);
  }
  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"
        });
  }
  // Render the portlet - this is not supposed to change the state of the portlet
  // Render may be called many times so if it changes the state - that is tacky
  // Render will be called when someone presses "refresh" or when another portlet
  // onthe same page is handed an Action.
  public void doView(RenderRequest request, RenderResponse response)
      throws PortletException, IOException {
    response.setContentType("text/html");

    // System.out.println("==== doView called ====");

    // Grab that underlying request to get a GET parameter
    ServletRequest req = (ServletRequest) ThreadLocalManager.get(CURRENT_HTTP_REQUEST);
    String popupDone = req.getParameter("sakai.popup");

    PrintWriter out = response.getWriter();
    Placement placement = ToolManager.getCurrentPlacement();
    response.setTitle(placement.getTitle());
    String source = placement.getPlacementConfig().getProperty(SOURCE);
    if (source == null) source = "";
    String height = placement.getPlacementConfig().getProperty(HEIGHT);
    if (height == null) height = "1200px";
    boolean maximize = "true".equals(placement.getPlacementConfig().getProperty(MAXIMIZE));

    boolean popup = false; // Comes from content item
    boolean oldPopup = "true".equals(placement.getPlacementConfig().getProperty(POPUP));

    // Retrieve the corresponding content item and tool to check the launch
    Map<String, Object> content = null;
    Map<String, Object> tool = null;
    Long key = getContentIdFromSource(source);
    if (key == null) {
      out.println(rb.getString("get.info.notconfig"));
      M_log.warn("Cannot find content id placement=" + placement.getId() + " source=" + source);
      return;
    }
    try {
      content = m_ltiService.getContent(key);
      // If we are supposed to popup (per the content), do so and optionally
      // copy the calue into the placement to communicate with the portal
      popup = getLongNull(content.get("newpage")) == 1;
      if (oldPopup != popup) {
        placement.getPlacementConfig().setProperty(POPUP, popup ? "true" : "false");
        placement.save();
      }
      String launch = (String) content.get("launch");
      Long tool_id = getLongNull(content.get("tool_id"));
      if (launch == null && tool_id != null) {
        tool = m_ltiService.getTool(tool_id);
        launch = (String) tool.get("launch");
      }

      // Force http:// to pop-up if we are https://
      String serverUrl = ServerConfigurationService.getServerUrl();
      if (request.isSecure() || (serverUrl != null && serverUrl.startsWith("https://"))) {
        if (launch != null && launch.startsWith("http://")) popup = true;
      }
    } catch (Exception e) {
      out.println(rb.getString("get.info.notconfig"));
      e.printStackTrace();
      return;
    }

    if (source != null && source.trim().length() > 0) {

      Context context = new VelocityContext();
      context.put("tlang", rb);
      context.put("validator", validator);
      context.put("source", source);
      context.put("height", height);
      sendAlert(request, context);
      context.put("popupdone", Boolean.valueOf(popupDone != null));
      context.put("popup", Boolean.valueOf(popup));
      context.put("maximize", Boolean.valueOf(maximize));

      vHelper.doTemplate(vengine, "/vm/main.vm", context, out);
    } else {
      out.println(rb.getString("get.info.notconfig"));
    }

    // System.out.println("==== doView complete ====");
  }
 // If the property is final, the property wins.  If it is not final,
 // the portlet preferences take precedence.
 public String getTitleString(RenderRequest request) {
   Placement placement = ToolManager.getCurrentPlacement();
   return placement.getTitle();
 }
Example #29
0
  public void doTool(
      HttpServletRequest req,
      HttpServletResponse res,
      Session session,
      String placementId,
      String toolContextPath,
      String toolPathInfo)
      throws ToolException, IOException {

    if (portal.redirectIfLoggedOut(res)) return;

    // find the tool from some site
    ToolConfiguration siteTool = SiteService.findTool(placementId);
    if (siteTool == null) {
      portal.doError(req, res, session, Portal.ERROR_WORKSITE);
      return;
    }

    // Reset the tool state if requested
    if (portalService.isResetRequested(req)) {
      Session s = SessionManager.getCurrentSession();
      ToolSession ts = s.getToolSession(placementId);
      ts.clearAttributes();
      portalService.setResetState(null);
      M_log.debug("Tool state reset");
    }

    // find the tool registered for this

    ActiveTool tool = ActiveToolManager.getActiveTool(siteTool.getToolId());
    if (tool == null) {
      portal.doError(req, res, session, Portal.ERROR_WORKSITE);
      return;
    }

    // permission check - visit the site (unless the tool is configured to
    // bypass)
    Site site = null;
    if (tool.getAccessSecurity() == Tool.AccessSecurity.PORTAL) {
      try {
        site = SiteService.getSiteVisit(siteTool.getSiteId());
      } catch (IdUnusedException e) {
        portal.doError(req, res, session, Portal.ERROR_WORKSITE);
        return;
      } catch (PermissionException e) {
        // if not logged in, give them a chance
        if (session.getUserId() == null) {
          portal.doLogin(req, res, session, URLUtils.getSafePathInfo(req), false);
        } else {
          portal.doError(req, res, session, Portal.ERROR_WORKSITE);
        }
        return;
      }
    }

    // Check to see if the tool is visible
    if (!ToolManager.isVisible(site, siteTool)) {
      portal.doError(req, res, session, Portal.ERROR_WORKSITE);
      return;
    }

    if (portal.isPortletPlacement(siteTool)) {

      String siteType = portal.calcSiteType(siteTool.getSiteId());

      // form a context sensitive title
      String title =
          ServerConfigurationService.getString("ui.service", "Sakai")
              + " : "
              + portal.getSiteHelper().getUserSpecificSiteTitle(site, false)
              + " : "
              + siteTool.getTitle();

      PortalRenderContext rcontext =
          portal.startPageContext(siteType, title, siteTool.getSkin(), req);

      Map m = portal.includeTool(res, req, siteTool);
      rcontext.put("tool", m);

      portal.sendResponse(rcontext, res, "tool", null);

    } else {
      M_log.debug("forwardtool in ToolHandler");
      portal.forwardTool(
          tool, req, res, siteTool, siteTool.getSkin(), toolContextPath, toolPathInfo);
    }
  }
Example #30
0
 /** Returns context id (/site/site id) */
 private String getContextId() {
   return "/site/" + ToolManager.getCurrentPlacement().getContext();
 }