Exemplo n.º 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;
  }
Exemplo n.º 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
  }
Exemplo n.º 3
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";
  }
Exemplo n.º 4
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;
  }
Exemplo n.º 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;
    }
  }
Exemplo n.º 6
0
 private String getContextId() {
   if (TestUtil.isRunningTests()) {
     return "test-context";
   }
   Placement placement = ToolManager.getCurrentPlacement();
   String presentSiteId = placement.getContext();
   return presentSiteId;
 }
Exemplo n.º 7
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();
  }
Exemplo n.º 8
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);
  }
Exemplo n.º 10
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";
  }
Exemplo n.º 11
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();
  }
Exemplo n.º 12
0
  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;
  }
Exemplo n.º 13
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;
  }
Exemplo n.º 15
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;
  }
Exemplo n.º 16
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;
  }
Exemplo n.º 17
0
  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);
  }
Exemplo n.º 18
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;
  }
Exemplo n.º 19
0
 public boolean checkAccess() {
   // return true;
   return SiteService.allowUpdateSite(ToolManager.getCurrentPlacement().getContext());
 }
Exemplo n.º 20
0
  // set the item to be accessible only to the specific groups.
  // null to make it accessible to the whole site
  public void setGroups(Collection<String> groups) {

    if (type != TYPE_FORUM_TOPIC) return;

    // Setgroups with a non-null list: we set all contributor entries to none, and then set the
    //    specified groups to contribtor. By only handling groups, we avoid interfering with
    //    anything you might do in the tool. But the moment you use access control, we take
    //    over. Sorry. Once we've done that you could go back into the tool and hack, but I
    //    don't recommend that.
    // Setgroups with a null list: we set all contributor entries to none, and then set all roles
    //    other than maintain to contributor.

    setMasks();

    // System.out.println("topic 1 " + topic + " " + groups);
    //	if (topic == null)
    topic = getTopicById(true, id);
    // System.out.println("topic 2 " + topic);
    if (topic == null) return;

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

    // topicCache.remove(id);

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

    DBMembershipItem membershipItem = null;

    boolean haveOwner = false;
    boolean changed = false;

    if (groups != null && groups.size() > 0) {

      // this is the groups we've been asked to use
      // remove groups form this as we see them if they already have access
      // so at the end we just add the ones remaining
      List<String> groupNames = new ArrayList<String>();
      Set<String> addGroupNames = new HashSet<String>();
      for (String groupId : groups) {
        groupNames.add(site.getGroup(groupId).getTitle());
        addGroupNames.add(site.getGroup(groupId).getTitle());
      }
      //	    System.out.println("groups " + groups + " " + groupNames + " " + addGroupNames);
      //	    System.out.println("oldMembership " + oldMembershipItemSet.size());

      // delete groups from here as they are done.

      // if we've seen an owner. Otherwise set the maintain role as owner

      // Setgroups with a non-null list: we set all contributor entries to none, and then set the
      //    specified groups to contribtor. However we don't touch owner.
      // By only handling groups, we avoid interfering with
      //    anything you might do in the tool. But the moment you use access control, we take
      //    over. Sorry. Once we've done that you could go back into the tool and hack, but I
      //    don't recommend that.

      for (DBMembershipItem item : oldMembershipItemSet) {
        // kill everything except our own groups
        // this will leave the owner but remove all other roles
        // System.out.println("item " + item.getType() + " " + item.getName() + " " +
        // item.getPermissionLevelName());
        if (item.getType().equals(MembershipItem.TYPE_GROUP)
            && groupNames.contains(item.getName())) {
          //		    System.out.println("found group " + item.getName());
          addGroupNames.remove(item.getName()); // we've seen it
          // if it's one of our groups make it a contributor if it's not already an owner
          if (!item.getPermissionLevelName().equals("Contributor")
              && !item.getPermissionLevelName().equals("Owner")) {

            PermissionLevel contributorLevel =
                permissionLevelManager.createPermissionLevel(
                    "Contributor", IdManager.createUuid(), contributorMask);
            permissionLevelManager.savePermissionLevel(contributorLevel);

            item.setPermissionLevel(contributorLevel);
            item.setPermissionLevelName("Contributor");
            permissionLevelManager.saveDBMembershipItem(item);
          }
        } else if (!item.getPermissionLevelName()
            .equals("Owner")) { // only group members are contributors
          // remove contributor from anything else, both groups and roles
          // System.out.println("set none");
          //		    System.out.println("setgroups make none " + item.getName());
          PermissionLevel noneLevel =
              permissionLevelManager.createPermissionLevel(
                  "None", IdManager.createUuid(), noneMask);
          permissionLevelManager.savePermissionLevel(noneLevel);

          item.setPermissionLevel(noneLevel);
          item.setPermissionLevelName("None");
          permissionLevelManager.saveDBMembershipItem(item);
        }
      }
      for (String newGroupName : addGroupNames) {
        // System.out.println("addgroup " + newGroupName);
        changed = true;
        PermissionLevel contributorLevel =
            permissionLevelManager.createPermissionLevel(
                "Contributor", IdManager.createUuid(), contributorMask);
        permissionLevelManager.savePermissionLevel(contributorLevel);
        membershipItem =
            permissionLevelManager.createDBMembershipItem(
                newGroupName, "Contributor", MembershipItem.TYPE_GROUP);
        membershipItem.setPermissionLevel(contributorLevel);
        permissionLevelManager.saveDBMembershipItem(membershipItem);
        oldMembershipItemSet.add(membershipItem);
      }

    } else {
      // Setgroups with a null list: we set all contributor entries to none, and then set all roles
      //    to contributor.  However we don't touch Owners.

      for (DBMembershipItem item : oldMembershipItemSet) {
        if (item.getPermissionLevelName().equals("Owner")) {
          haveOwner = true;
        } else if (item.getType().equals(MembershipItem.TYPE_ROLE)) {
          // default state has all roles except owner as contributor
          if (!item.getPermissionLevelName().equals("Contributor")) {
            PermissionLevel contributorLevel =
                permissionLevelManager.createPermissionLevel(
                    "Contributor", IdManager.createUuid(), contributorMask);
            permissionLevelManager.savePermissionLevel(contributorLevel);

            item.setPermissionLevel(contributorLevel);
            item.setPermissionLevelName("Contributor");
            permissionLevelManager.saveDBMembershipItem(item);
          }
        } else if (!item.getPermissionLevelName().equals("None")) {
          // kill other contributors
          PermissionLevel noneLevel =
              permissionLevelManager.createPermissionLevel(
                  "None", IdManager.createUuid(), noneMask);
          permissionLevelManager.savePermissionLevel(noneLevel);

          item.setPermissionLevel(noneLevel);
          item.setPermissionLevelName("None");
          permissionLevelManager.saveDBMembershipItem(item);
        }
      }
    }

    if (changed) {
      // System.out.println("changed");
      // have to refresh the topic or the save won't work
      topic = getTopicById(true, id);
      topic.setMembershipItemSet(oldMembershipItemSet);
      forumManager.saveDiscussionForumTopic((DiscussionTopic) topic);

      //	    topic.setVersion(null);
      //	    try {
      //		System.out.println("simplepagetool dao " + simplePageToolDao);
      //		hibernateTemplate.merge(topic);
      //	    } catch (Exception e){
      //		System.out.println("Unable to save forum topic " + e);
      //	    }

    }
  }
Exemplo n.º 21
0
 private String getCurrentSiteId() {
   Placement placement = ToolManager.getCurrentPlacement();
   return placement.getContext();
 }
Exemplo n.º 22
0
 protected String getSiteID() {
   return (ToolManager.getCurrentPlacement().getContext());
 }
Exemplo n.º 23
0
 private String getSiteRealmID() {
   return ("/site/" + ToolManager.getCurrentPlacement().getContext());
 }
Exemplo n.º 24
0
  // 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 ====");
  }
Exemplo n.º 25
0
 // 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();
 }
Exemplo n.º 26
0
 protected String getConfigParam(String parameter) {
   String p = ToolManager.getCurrentPlacement().getPlacementConfig().getProperty(parameter);
   if (p == null) return "";
   return p;
 }
Exemplo n.º 27
0
 protected void setConfigParam(String parameter, String newvalue) {
   ToolManager.getCurrentPlacement().getPlacementConfig().setProperty(parameter, newvalue);
 }
Exemplo n.º 28
0
 /** Returns context id (/site/site id) */
 private String getContextId() {
   return "/site/" + ToolManager.getCurrentPlacement().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);
  }
Exemplo n.º 30
0
  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"
        });
  }