private Object getTopic(Long topicId, String siteId, String userId) {

    if (LOG.isDebugEnabled()) {
      LOG.debug("getTopic(" + topicId + "," + siteId + "," + userId + ")");
    }

    // This call gets the attachments for the messages but not the topic. Unexpected, yes. Cool,
    // not.
    DiscussionTopic fatTopic =
        (DiscussionTopic) forumManager.getTopicByIdWithMessagesAndAttachments(topicId);

    if (!uiPermissionsManager.isRead(
        topicId,
        fatTopic.getDraft(),
        false,
        userId,
        forumManager.getContextForTopicById(topicId))) {
      LOG.error("'" + userId + "' is not authorised to read topic '" + topicId + "'.");
      throw new EntityException(
          "You are not authorised to read this topic.", "", HttpServletResponse.SC_UNAUTHORIZED);
    }

    SparseTopic sparseTopic = new SparseTopic(fatTopic);

    // Setup the total and read message counts on the topic
    List<Long> topicIds = new ArrayList<Long>();
    topicIds.add(fatTopic.getId());

    List<Object[]> totalCounts = forumManager.getMessageCountsForMainPage(topicIds);
    if (totalCounts.size() > 0) {
      sparseTopic.setTotalMessages((Integer) totalCounts.get(0)[1]);
    } else {
      sparseTopic.setTotalMessages(0);
    }

    List<Object[]> readCounts = forumManager.getReadMessageCountsForMainPage(topicIds);
    if (readCounts.size() > 0) {
      sparseTopic.setReadMessages((Integer) readCounts.get(0)[1]);
    } else {
      sparseTopic.setReadMessages(0);
    }

    List<SparseMessage> messages = new ArrayList<SparseMessage>();
    for (Message fatMessage : (List<Message>) fatTopic.getMessages()) {
      SparseMessage sparseMessage =
          new SparseMessage(
              fatMessage,
              /* readStatus = */ false,
              /* addAttachments = */ true,
              developerHelperService.getServerURL());
      messages.add(sparseMessage);
    }

    List<SparseThread> threads =
        new MessageUtils().getThreadsWithCounts(messages, forumManager, userId);

    sparseTopic.setThreads(threads);

    return sparseTopic;
  }
  private List<?> getAllForaForSite(String siteId, String userId) {

    if (LOG.isDebugEnabled()) {
      LOG.debug("getAllForaForSite(" + siteId + "," + userId + ")");
    }

    List<SparsestForum> sparseFora = new ArrayList<SparsestForum>();

    List<DiscussionForum> fatFora = forumManager.getDiscussionForumsWithTopics(siteId);

    for (DiscussionForum fatForum : fatFora) {

      if (!checkAccess(fatForum, userId, siteId)) {
        LOG.warn(
            "Access denied for user id '"
                + userId
                + "' to forum '"
                + fatForum.getId()
                + "'. This forum will not be returned.");
        continue;
      }

      List<Long> topicIds = new ArrayList<Long>();
      for (Topic topic : (List<Topic>) fatForum.getTopics()) {
        topicIds.add(topic.getId());
      }

      List<Object[]> topicTotals = forumManager.getMessageCountsForMainPage(topicIds);
      List<Object[]> topicReadTotals = forumManager.getReadMessageCountsForMainPage(topicIds);

      SparsestForum sparseForum = new SparsestForum(fatForum, developerHelperService);

      int totalForumMessages = 0;
      for (Object[] topicTotal : topicTotals) {
        totalForumMessages += (Integer) topicTotal[1];
      }
      sparseForum.setTotalMessages(totalForumMessages);

      int totalForumReadMessages = 0;
      for (Object[] topicReadTotal : topicReadTotals) {
        totalForumReadMessages += (Integer) topicReadTotal[1];
      }
      sparseForum.setReadMessages(totalForumReadMessages);

      sparseFora.add(sparseForum);
    }

    return sparseFora;
  }
  private boolean checkAccess(BaseForum baseForum, String userId, String siteId) {

    if (baseForum instanceof OpenForum) {

      // If the supplied user is the super user or an instructor, return true.
      if (securityService.isSuperUser(userId)
          || forumManager.isInstructor(
              userId, Entity.SEPARATOR + SiteService.SITE_SUBTYPE + Entity.SEPARATOR + siteId)) {
        return true;
      }

      OpenForum of = (OpenForum) baseForum;

      // If this is not a draft and is available, return true.
      if (!of.getDraft() && of.getAvailability()) {
        return true;
      }

      // If this is a draft/unavailable forum AND was authored by the current user, return true.
      if ((of.getDraft() || !of.getAvailability()) && of.getCreatedBy().equals(userId)) {
        return true;
      }
    } else if (baseForum instanceof PrivateForum) {
      PrivateForum pf = (PrivateForum) baseForum;
      // If the current user is the creator, return true.
      if (pf.getCreatedBy().equals(userId)) {
        return true;
      }
    }

    return false;
  }
  private Object getMessage(Long messageId, String siteId, String userId) {

    if (LOG.isDebugEnabled()) {
      LOG.debug("getMessage(" + messageId + "," + siteId + "," + userId + ")");
    }

    Message fatMessage = forumManager.getMessageById(messageId);

    Topic fatTopic =
        forumManager.getTopicByIdWithMessagesAndAttachments(fatMessage.getTopic().getId());

    // This sets the attachments on the message.We have to do this as
    // getMessageById doesn't populate the attachments.
    setAttachments(fatMessage, fatTopic.getMessages());

    if (!uiPermissionsManager.isRead(
        fatTopic.getId(),
        ((DiscussionTopic) fatTopic).getDraft(),
        false,
        userId,
        forumManager.getContextForTopicById(fatTopic.getId()))) {
      LOG.error("'" + userId + "' is not authorised to read message '" + messageId + "'.");
      throw new EntityException(
          "You are not authorised to read this message.", "", HttpServletResponse.SC_UNAUTHORIZED);
    }

    List<SparseMessage> messages = new ArrayList<SparseMessage>();

    for (Message fm : (List<Message>) fatTopic.getMessages()) {
      messages.add(
          new SparseMessage(
              fm,
              /* readStatus =*/ false,
              /* addAttachments =*/ true,
              developerHelperService.getServerURL()));
    }

    SparseMessage sparseThread =
        new SparseMessage(
            fatMessage, false, /* readStatus =*/ true, developerHelperService.getServerURL());

    new MessageUtils().attachReplies(sparseThread, messages, forumManager, userId);

    return sparseThread;
  }
Example #5
0
  // returns SakaiId of thing just created
  public String importObject(
      String title,
      String topicTitle,
      String text,
      boolean texthtml,
      String base,
      String baseDir,
      String siteId,
      List<String> attachmentHrefs,
      boolean hide) {

    DiscussionForum ourForum = null;
    DiscussionTopic ourTopic = null;

    int forumtry = 0;
    int topictry = 0;

    for (; ; ) {

      ourForum = null;

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

      for (DiscussionForum forum : forums) {
        if (forum.getTitle().equals(title)) {
          ourForum = forum;
          break;
        }
      }

      if (ourForum == null) {
        if (forumtry > 0) {
          System.out.println("oops, forum still not there the second time");
          return null;
        }
        forumtry++;

        // if a new site, may need to create the area or we'll get a backtrace when creating forum
        areaManager.getDiscussionArea(siteId);

        ourForum = discussionForumManager.createForum();
        ourForum.setTitle(title);
        discussionForumManager.saveForum(siteId, ourForum);

        continue; // reread, better be there this time
      }

      // forum now exists, and was just reread

      ourTopic = null;

      for (Object o : ourForum.getTopicsSet()) {
        DiscussionTopic topic = (DiscussionTopic) o;
        if (topic.getTitle().equals(topicTitle)) {
          ourTopic = topic;
          break;
        }
      }

      if (ourTopic != null) // ok, forum and topic exist
      break;

      if (topictry > 0) {
        System.out.println("oops, topic still not there the second time");
        return null;
      }
      topictry++;

      // create it

      ourTopic = discussionForumManager.createTopic(ourForum);
      ourTopic.setTitle(topicTitle);

      if (attachmentHrefs != null && attachmentHrefs.size() > 0) {
        for (String href : attachmentHrefs) {
          // we don't have any real label for attachments. About all we can do is use the filename,
          // without path
          String label = href;
          int slash = label.lastIndexOf("/");
          if (slash >= 0) label = label.substring(slash + 1);
          if (label.equals("")) label = "Attachment";

          // basedir is a folder in contenthosting starting with /group/ where our content has been
          // loaded
          // discussionForum needs a Sakai content resource ID for the attachment
          Attachment thisDFAttach =
              discussionForumManager.createDFAttachment(removeDotDot(baseDir + href), label);
          ourTopic.addAttachment(thisDFAttach);
        }
      }

      String shortText = null;
      if (texthtml) {
        ourTopic.setExtendedDescription(text.replaceAll("\\$IMS-CC-FILEBASE\\$", base));
        shortText = FormattedText.convertFormattedTextToPlaintext(text);
      } else {
        ourTopic.setExtendedDescription(FormattedText.convertPlaintextToFormattedText(text));
        shortText = text;
      }
      shortText = org.apache.commons.lang.StringUtils.abbreviate(shortText, 254);

      ourTopic.setShortDescription(shortText);

      // there's a better way to do attachments, but it's too complex for now

      if (hide) discussionForumManager.saveTopicAsDraft(ourTopic);
      else discussionForumManager.saveTopic(ourTopic);

      // now go back and mmake sure everything is there

    }

    return "/" + FORUM_TOPIC + "/" + ourTopic.getId();
  }
Example #6
0
  // seems not to be used anymore
  public boolean removeEntityControl(String siteId, String groupId) throws IOException {

    if (type != TYPE_FORUM_TOPIC) return false;

    setMasks();

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

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

    Set membershipItemSet = new HashSet();

    String groupName = null;
    String maintainRole = null;
    try {
      Site site = SiteService.getSite(ToolManager.getCurrentPlacement().getContext());
      groupName = site.getGroup(groupId).getTitle();
      maintainRole = authzGroupService.getAuthzGroup("/site/" + site.getId()).getMaintainRole();
    } catch (Exception e) {
      System.out.println("Unable to get site info for AddEntityControl " + e);
    }

    PermissionLevel ownerLevel =
        permissionLevelManager.createPermissionLevel(
            "Owner", typeManager.getOwnerLevelType(), ownerMask);
    permissionLevelManager.savePermissionLevel(ownerLevel);

    DBMembershipItem membershipItem =
        permissionLevelManager.createDBMembershipItem(
            maintainRole, "Owner", MembershipItem.TYPE_ROLE);
    membershipItem.setPermissionLevel(ownerLevel);
    permissionLevelManager.saveDBMembershipItem(membershipItem);

    membershipItemSet.add(membershipItem);

    // now change any existing ones into null
    for (DBMembershipItem item : oldMembershipItemSet) {
      if (item.getType().equals(MembershipItem.TYPE_ROLE)) {
        if (!maintainRole.equals(item.getName())) { // that was done above, other roles contributor
          PermissionLevel contributorLevel =
              permissionLevelManager.createPermissionLevel(
                  "Contributor", typeManager.getContributorLevelType(), contributorMask);
          permissionLevelManager.savePermissionLevel(contributorLevel);

          membershipItem =
              permissionLevelManager.createDBMembershipItem(
                  item.getName(), "Contributor", item.getType());
          membershipItem.setPermissionLevel(contributorLevel);
          permissionLevelManager.saveDBMembershipItem(membershipItem);
          membershipItemSet.add(membershipItem);
        }
      } else { // everything else off
        PermissionLevel noneLevel =
            permissionLevelManager.createPermissionLevel(
                "None", typeManager.getNoneLevelType(), noneMask);
        permissionLevelManager.savePermissionLevel(noneLevel);

        membershipItem =
            permissionLevelManager.createDBMembershipItem(item.getName(), "None", item.getType());
        membershipItem.setPermissionLevel(noneLevel);
        permissionLevelManager.saveDBMembershipItem(membershipItem);
        membershipItemSet.add(membershipItem);
      }
    }

    permissionLevelManager.deleteMembershipItems(oldMembershipItemSet);

    topic.setMembershipItemSet(membershipItemSet);
    discussionForumManager.saveTopic((DiscussionTopic) topic);

    return true;
  };
  /** This will return a SparseForum populated down to the topics with their attachments. */
  private Object getForum(Long forumId, String siteId, String userId) {

    if (LOG.isDebugEnabled()) {
      LOG.debug("getForum(" + forumId + "," + siteId + "," + userId + ")");
    }

    DiscussionForum fatForum = forumManager.getForumByIdWithTopicsAttachmentsAndMessages(forumId);

    if (checkAccess(fatForum, userId, siteId)) {

      SparseForum sparseForum = new SparseForum(fatForum, developerHelperService);

      List<DiscussionTopic> fatTopics = (List<DiscussionTopic>) fatForum.getTopics();

      // Gather all the topic ids so we can make the minimum number
      // of calls for the message counts.
      List<Long> topicIds = new ArrayList<Long>();
      for (DiscussionTopic topic : fatTopics) {
        topicIds.add(topic.getId());
      }

      List<Object[]> topicTotals = forumManager.getMessageCountsForMainPage(topicIds);
      List<Object[]> topicReadTotals = forumManager.getReadMessageCountsForMainPage(topicIds);

      int totalForumMessages = 0;
      for (Object[] topicTotal : topicTotals) {
        totalForumMessages += (Integer) topicTotal[1];
      }
      sparseForum.setTotalMessages(totalForumMessages);

      int totalForumReadMessages = 0;
      for (Object[] topicReadTotal : topicReadTotals) {
        totalForumReadMessages += (Integer) topicReadTotal[1];
      }
      sparseForum.setReadMessages(totalForumReadMessages);

      // Reduce the fat topics to sparse topics while setting the total and read
      // counts. A SparseTopic will only be created if the currrent user has read access.
      List<SparsestTopic> sparseTopics = new ArrayList<SparsestTopic>();
      for (DiscussionTopic fatTopic : fatTopics) {

        // Only add this topic to the list if the current user has read permission
        if (!uiPermissionsManager.isRead(fatTopic, fatForum, userId, siteId)) {
          // No read permission, skip this topic.
          continue;
        }

        SparsestTopic sparseTopic = new SparsestTopic(fatTopic);
        for (Object[] topicTotal : topicTotals) {
          if (topicTotal[0].equals(sparseTopic.getId())) {
            sparseTopic.setTotalMessages((Integer) topicTotal[1]);
          }
        }
        for (Object[] topicReadTotal : topicReadTotals) {
          if (topicReadTotal[0].equals(sparseTopic.getId())) {
            sparseTopic.setReadMessages((Integer) topicReadTotal[1]);
          }
        }

        List<SparseAttachment> attachments = new ArrayList<SparseAttachment>();
        for (Attachment attachment : (List<Attachment>) fatTopic.getAttachments()) {
          String url =
              developerHelperService.getServerURL()
                  + "/access/content"
                  + attachment.getAttachmentId();
          attachments.add(new SparseAttachment(attachment.getAttachmentName(), url));
        }
        sparseTopic.setAttachments(attachments);

        sparseTopics.add(sparseTopic);
      }

      sparseForum.setTopics(sparseTopics);

      return sparseForum;
    } else {
      LOG.error("Not authorised to access forum '" + forumId + "'");
      throw new EntityException(
          "You are not authorised to access this forum.", "", HttpServletResponse.SC_UNAUTHORIZED);
    }
  }