Example #1
0
/**
 * Prints the discussion view screen for a forum.
 *
 * @global object
 * @global object
 * @param object $course The current course object.
 * @param object $forum Forum to be printed.
 * @param int $maxdiscussions .
 * @param string $displayformat The display format to use (optional).
 * @param string $sort Sort arguments for database query (optional).
 * @param int $groupmode Group mode of the forum (optional).
 * @param void $unused (originally current group)
 * @param int $page Page mode, page to display (optional).
 * @param int $perpage The maximum number of discussions per page(optional)
 *
 */
function forum_print_latest_discussions($course, $forum, $maxdiscussions=-1, $displayformat='plain', $sort='',
                                        $currentgroup=-1, $groupmode=-1, $page=-1, $perpage=100, $cm=NULL) {
    global $CFG, $USER, $OUTPUT;

    if (!$cm) {
        if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
            print_error('invalidcoursemodule');
        }
    }
    $context = context_module::instance($cm->id);

    if (empty($sort)) {
        $sort = "d.timemodified DESC";
    }

    $olddiscussionlink = false;

 // Sort out some defaults
    if ($perpage <= 0) {
        $perpage = 0;
        $page    = -1;
    }

    if ($maxdiscussions == 0) {
        // all discussions - backwards compatibility
        $page    = -1;
        $perpage = 0;
        if ($displayformat == 'plain') {
            $displayformat = 'header';  // Abbreviate display by default
        }

    } else if ($maxdiscussions > 0) {
        $page    = -1;
        $perpage = $maxdiscussions;
    }

    $fullpost = false;
    if ($displayformat == 'plain') {
        $fullpost = true;
    }


// Decide if current user is allowed to see ALL the current discussions or not

// First check the group stuff
    if ($currentgroup == -1 or $groupmode == -1) {
        $groupmode    = groups_get_activity_groupmode($cm, $course);
        $currentgroup = groups_get_activity_group($cm);
    }

    $groups = array(); //cache

// If the user can post discussions, then this is a good place to put the
// button for it. We do not show the button if we are showing site news
// and the current user is a guest.

    $canstart = forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context);
    if (!$canstart and $forum->type !== 'news') {
        if (isguestuser() or !isloggedin()) {
            $canstart = true;
        }
        if (!is_enrolled($context) and !is_viewing($context)) {
            // allow guests and not-logged-in to see the button - they are prompted to log in after clicking the link
            // normal users with temporary guest access see this button too, they are asked to enrol instead
            // do not show the button to users with suspended enrolments here
            $canstart = enrol_selfenrol_available($course->id);
        }
    }

    if ($canstart) {
        echo '<div class="singlebutton forumaddnew">';
        echo "<form id=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
        echo '<div>';
        echo "<input type=\"hidden\" name=\"forum\" value=\"$forum->id\" />";
        switch ($forum->type) {
            case 'news':
            case 'blog':
                $buttonadd = get_string('addanewtopic', 'forum');
                break;
            case 'qanda':
                $buttonadd = get_string('addanewquestion', 'forum');
                break;
            default:
                $buttonadd = get_string('addanewdiscussion', 'forum');
                break;
        }
        echo '<input type="submit" value="'.$buttonadd.'" />';
        echo '</div>';
        echo '</form>';
        echo "</div>\n";

    } else if (isguestuser() or !isloggedin() or $forum->type == 'news') {
        // no button and no info

    } else if ($groupmode and has_capability('mod/forum:startdiscussion', $context)) {
        // inform users why they can not post new discussion
        if ($currentgroup) {
            echo $OUTPUT->notification(get_string('cannotadddiscussion', 'forum'));
        } else {
            echo $OUTPUT->notification(get_string('cannotadddiscussionall', 'forum'));
        }
    }

// Get all the recent discussions we're allowed to see

    $getuserlastmodified = ($displayformat == 'header');

    if (! $discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage) ) {
        echo '<div class="forumnodiscuss">';
        if ($forum->type == 'news') {
            echo '('.get_string('nonews', 'forum').')';
        } else if ($forum->type == 'qanda') {
            echo '('.get_string('noquestions','forum').')';
        } else {
            echo '('.get_string('nodiscussions', 'forum').')';
        }
        echo "</div>\n";
        return;
    }

// If we want paging
    if ($page != -1) {
        ///Get the number of discussions found
        $numdiscussions = forum_get_discussions_count($cm);

        ///Show the paging bar
        echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
        if ($numdiscussions > 1000) {
            // saves some memory on sites with very large forums
            $replies = forum_count_discussion_replies($forum->id, $sort, $maxdiscussions, $page, $perpage);
        } else {
            $replies = forum_count_discussion_replies($forum->id);
        }

    } else {
        $replies = forum_count_discussion_replies($forum->id);

        if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
            $olddiscussionlink = true;
        }
    }

    $canviewparticipants = has_capability('moodle/course:viewparticipants',$context);

    $strdatestring = get_string('strftimerecentfull');

    // Check if the forum is tracked.
    if ($cantrack = forum_tp_can_track_forums($forum)) {
        $forumtracked = forum_tp_is_tracked($forum);
    } else {
        $forumtracked = false;
    }

    if ($forumtracked) {
        $unreads = forum_get_discussions_unread($cm);
    } else {
        $unreads = array();
    }

    if ($displayformat == 'header') {
        echo '<table cellspacing="0" class="forumheaderlist">';
        echo '<thead>';
        echo '<tr>';
        echo '<th class="header topic" scope="col">'.get_string('discussion', 'forum').'</th>';
        echo '<th class="header author" colspan="2" scope="col">'.get_string('startedby', 'forum').'</th>';
        if ($groupmode > 0) {
            echo '<th class="header group" scope="col">'.get_string('group').'</th>';
        }
        if (has_capability('mod/forum:viewdiscussion', $context)) {
            echo '<th class="header replies" scope="col">'.get_string('replies', 'forum').'</th>';
            // If the forum can be tracked, display the unread column.
            if ($cantrack) {
                echo '<th class="header replies" scope="col">'.get_string('unread', 'forum');
                if ($forumtracked) {
                    echo '<a title="'.get_string('markallread', 'forum').
                         '" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
                         $forum->id.'&amp;mark=read&amp;returnpage=view.php">'.
                         '<img src="'.$OUTPUT->pix_url('t/markasread') . '" class="iconsmall" alt="'.get_string('markallread', 'forum').'" /></a>';
                }
                echo '</th>';
            }
        }
        echo '<th class="header lastpost" scope="col">'.get_string('lastpost', 'forum').'</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
    }

    foreach ($discussions as $discussion) {
        if (!empty($replies[$discussion->discussion])) {
            $discussion->replies = $replies[$discussion->discussion]->replies;
            $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
        } else {
            $discussion->replies = 0;
        }

        // SPECIAL CASE: The front page can display a news item post to non-logged in users.
        // All posts are read in this case.
        if (!$forumtracked) {
            $discussion->unread = '-';
        } else if (empty($USER)) {
            $discussion->unread = 0;
        } else {
            if (empty($unreads[$discussion->discussion])) {
                $discussion->unread = 0;
            } else {
                $discussion->unread = $unreads[$discussion->discussion];
            }
        }

        if (isloggedin()) {
            $ownpost = ($discussion->userid == $USER->id);
        } else {
            $ownpost=false;
        }
        // Use discussion name instead of subject of first post
        $discussion->subject = $discussion->name;

        switch ($displayformat) {
            case 'header':
                if ($groupmode > 0) {
                    if (isset($groups[$discussion->groupid])) {
                        $group = $groups[$discussion->groupid];
                    } else {
                        $group = $groups[$discussion->groupid] = groups_get_group($discussion->groupid);
                    }
                } else {
                    $group = -1;
                }
                forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked,
                    $canviewparticipants, $context);
            break;
            default:
                $link = false;

                if ($discussion->replies) {
                    $link = true;
                } else {
                    $modcontext = context_module::instance($cm->id);
                    $link = forum_user_can_see_discussion($forum, $discussion, $modcontext, $USER);
                }

                $discussion->forum = $forum->id;

                forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false,
                        '', null, true, $forumtracked);
            break;
        }
    }

    if ($displayformat == "header") {
        echo '</tbody>';
        echo '</table>';
    }

    if ($olddiscussionlink) {
        if ($forum->type == 'news') {
            $strolder = get_string('oldertopics', 'forum');
        } else {
            $strolder = get_string('olderdiscussions', 'forum');
        }
        echo '<div class="forumolddiscuss">';
        echo '<a href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'&amp;showall=1">';
        echo $strolder.'</a> ...</div>';
    }

    if ($page != -1) { ///Show the paging bar
        echo $OUTPUT->paging_bar($numdiscussions, $page, $perpage, "view.php?f=$forum->id");
    }
}
Example #2
0
 /**
  * Returns a list of forum discussions as well as a summary of the discussion
  * in a provided list of forums.
  *
  * @param array $forumids the forum ids
  * @param int $limitfrom limit from SQL data
  * @param int $limitnum limit number SQL data
  *
  * @return array the forum discussion details
  * @since Moodle 2.5
  */
 public static function get_forum_discussions($forumids, $limitfrom = 0, $limitnum = 0)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . "/mod/forum/lib.php";
     // Validate the parameter.
     $params = self::validate_parameters(self::get_forum_discussions_parameters(), array('forumids' => $forumids, 'limitfrom' => $limitfrom, 'limitnum' => $limitnum));
     $forumids = $params['forumids'];
     $limitfrom = $params['limitfrom'];
     $limitnum = $params['limitnum'];
     // Array to store the forum discussions to return.
     $arrdiscussions = array();
     // Keep track of the users we have looked up in the DB.
     $arrusers = array();
     // Loop through them.
     foreach ($forumids as $id) {
         // Get the forum object.
         $forum = $DB->get_record('forum', array('id' => $id), '*', MUST_EXIST);
         $course = get_course($forum->course);
         $modinfo = get_fast_modinfo($course);
         $forums = $modinfo->get_instances_of('forum');
         $cm = $forums[$forum->id];
         // Get the module context.
         $modcontext = context_module::instance($cm->id);
         // Validate the context.
         self::validate_context($modcontext);
         require_capability('mod/forum:viewdiscussion', $modcontext);
         // Get the discussions for this forum.
         $params = array();
         $groupselect = "";
         $groupmode = groups_get_activity_groupmode($cm, $course);
         if ($groupmode and $groupmode != VISIBLEGROUPS and !has_capability('moodle/site:accessallgroups', $modcontext)) {
             // Get all the discussions from all the groups this user belongs to.
             $usergroups = groups_get_user_groups($course->id);
             if (!empty($usergroups['0'])) {
                 list($sql, $params) = $DB->get_in_or_equal($usergroups['0']);
                 $groupselect = "AND (groupid {$sql} OR groupid = -1)";
             }
         }
         array_unshift($params, $id);
         $select = "forum = ? {$groupselect}";
         if ($discussions = $DB->get_records_select('forum_discussions', $select, $params, 'timemodified DESC', '*', $limitfrom, $limitnum)) {
             // Check if they can view full names.
             $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
             // Get the unreads array, this takes a forum id and returns data for all discussions.
             $unreads = array();
             if ($cantrack = forum_tp_can_track_forums($forum)) {
                 if ($forumtracked = forum_tp_is_tracked($forum)) {
                     $unreads = forum_get_discussions_unread($cm);
                 }
             }
             // The forum function returns the replies for all the discussions in a given forum.
             $replies = forum_count_discussion_replies($id);
             foreach ($discussions as $discussion) {
                 // This function checks capabilities, timed discussions, groups and qanda forums posting.
                 if (!forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
                     continue;
                 }
                 $usernamefields = user_picture::fields();
                 // If we don't have the users details then perform DB call.
                 if (empty($arrusers[$discussion->userid])) {
                     $arrusers[$discussion->userid] = $DB->get_record('user', array('id' => $discussion->userid), $usernamefields, MUST_EXIST);
                 }
                 // Get the subject.
                 $subject = $DB->get_field('forum_posts', 'subject', array('id' => $discussion->firstpost), MUST_EXIST);
                 // Create object to return.
                 $return = new stdClass();
                 $return->id = (int) $discussion->id;
                 $return->course = $discussion->course;
                 $return->forum = $discussion->forum;
                 $return->name = $discussion->name;
                 $return->userid = $discussion->userid;
                 $return->groupid = $discussion->groupid;
                 $return->assessed = $discussion->assessed;
                 $return->timemodified = (int) $discussion->timemodified;
                 $return->usermodified = $discussion->usermodified;
                 $return->timestart = $discussion->timestart;
                 $return->timeend = $discussion->timeend;
                 $return->firstpost = (int) $discussion->firstpost;
                 $return->firstuserfullname = fullname($arrusers[$discussion->userid], $canviewfullname);
                 $return->firstuserimagealt = $arrusers[$discussion->userid]->imagealt;
                 $return->firstuserpicture = $arrusers[$discussion->userid]->picture;
                 $return->firstuseremail = $arrusers[$discussion->userid]->email;
                 $return->subject = $subject;
                 $return->numunread = '';
                 if ($cantrack && $forumtracked) {
                     if (isset($unreads[$discussion->id])) {
                         $return->numunread = (int) $unreads[$discussion->id];
                     }
                 }
                 // Check if there are any replies to this discussion.
                 if (!empty($replies[$discussion->id])) {
                     $return->numreplies = (int) $replies[$discussion->id]->replies;
                     $return->lastpost = (int) $replies[$discussion->id]->lastpostid;
                 } else {
                     // No replies, so the last post will be the first post.
                     $return->numreplies = 0;
                     $return->lastpost = (int) $discussion->firstpost;
                 }
                 // Get the last post as well as the user who made it.
                 $lastpost = $DB->get_record('forum_posts', array('id' => $return->lastpost), '*', MUST_EXIST);
                 if (empty($arrusers[$lastpost->userid])) {
                     $arrusers[$lastpost->userid] = $DB->get_record('user', array('id' => $lastpost->userid), $usernamefields, MUST_EXIST);
                 }
                 $return->lastuserid = $lastpost->userid;
                 $return->lastuserfullname = fullname($arrusers[$lastpost->userid], $canviewfullname);
                 $return->lastuserimagealt = $arrusers[$lastpost->userid]->imagealt;
                 $return->lastuserpicture = $arrusers[$lastpost->userid]->picture;
                 $return->lastuseremail = $arrusers[$lastpost->userid]->email;
                 // Add the discussion statistics to the array to return.
                 $arrdiscussions[$return->id] = (array) $return;
             }
         }
     }
     return $arrdiscussions;
 }
Example #3
0
    /**
     * Returns a list of forum discussions as well as a summary of the discussion
     * in a provided list of forums.
     *
     * @param array $forumids the forum ids
     * @return array the forum discussion details
     * @since Moodle 2.5
     */
    public static function get_forum_discussions($forumids) {
        global $CFG, $DB, $USER;

        require_once($CFG->dirroot . "/mod/forum/lib.php");

        // Validate the parameter.
        $params = self::validate_parameters(self::get_forum_discussions_parameters(), array('forumids' => $forumids));
        $forumids = $params['forumids'];

        // Array to store the forum discussions to return.
        $arrdiscussions = array();
        // Keep track of the course ids we have performed a require_course_login check on to avoid repeating.
        $arrcourseschecked = array();
        // Store the modinfo for the forums in an individual courses.
        $arrcoursesforuminfo = array();
        // Keep track of the users we have looked up in the DB.
        $arrusers = array();

        // Loop through them.
        foreach ($forumids as $id) {
            // Get the forum object.
            $forum = $DB->get_record('forum', array('id' => $id), '*', MUST_EXIST);
            // Check that that user can view this course if check not performed yet.
            if (!in_array($forum->course, $arrcourseschecked)) {
                // Check the user can function in this context.
                self::validate_context(context_course::instance($forum->course));
                // Add to the array.
                $arrcourseschecked[] = $forum->course;
            }
            // Get the modinfo for the course if we haven't already.
            if (!isset($arrcoursesforuminfo[$forum->course])) {
                $modinfo = get_fast_modinfo($forum->course);
                $arrcoursesforuminfo[$forum->course] = $modinfo->get_instances_of('forum');
            }
            // Check if this forum does not exist in the modinfo array, should always be false unless DB is borked.
            if (empty($arrcoursesforuminfo[$forum->course][$forum->id])) {
                throw new moodle_exception('invalidmodule', 'error');
            }
            // We now have the course module.
            $cm = $arrcoursesforuminfo[$forum->course][$forum->id];
            // If the forum is not visible throw an exception.
            if (!$cm->uservisible) {
                throw new moodle_exception('nopermissiontoshow', 'error');
            }
            // Get the module context.
            $modcontext = context_module::instance($cm->id);
            // Check they have the view forum capability.
            require_capability('mod/forum:viewdiscussion', $modcontext);
            // Check if they can view full names.
            $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
            // Get the unreads array, this takes a forum id and returns data for all discussions.
            $unreads = array();
            if ($cantrack = forum_tp_can_track_forums($forum)) {
                if ($forumtracked = forum_tp_is_tracked($forum)) {
                    $unreads = forum_get_discussions_unread($cm);
                }
            }
            // The forum function returns the replies for all the discussions in a given forum.
            $replies = forum_count_discussion_replies($id);
            // Get the discussions for this forum.
            if ($discussions = $DB->get_records('forum_discussions', array('forum' => $id))) {
                foreach ($discussions as $discussion) {
                    // If the forum is of type qanda and the user has not posted in the discussion
                    // we need to ensure that they have the required capability.
                    if ($forum->type == 'qanda' && !forum_user_has_posted($discussion->forum, $discussion->id, $USER->id)) {
                        require_capability('mod/forum:viewqandawithoutposting', $modcontext);
                    }
                    // If we don't have the users details then perform DB call.
                    if (empty($arrusers[$discussion->userid])) {
                        $arrusers[$discussion->userid] = $DB->get_record('user', array('id' => $discussion->userid),
                            'firstname, lastname, email, picture, imagealt', MUST_EXIST);
                    }
                    // Get the subject.
                    $subject = $DB->get_field('forum_posts', 'subject', array('id' => $discussion->firstpost), MUST_EXIST);
                    // Create object to return.
                    $return = new stdClass();
                    $return->id = (int) $discussion->id;
                    $return->course = $discussion->course;
                    $return->forum = $discussion->forum;
                    $return->name = $discussion->name;
                    $return->userid = $discussion->userid;
                    $return->groupid = $discussion->groupid;
                    $return->assessed = $discussion->assessed;
                    $return->timemodified = (int) $discussion->timemodified;
                    $return->usermodified = $discussion->usermodified;
                    $return->timestart = $discussion->timestart;
                    $return->timeend = $discussion->timeend;
                    $return->firstpost = (int) $discussion->firstpost;
                    $return->firstuserfullname = fullname($arrusers[$discussion->userid], $canviewfullname);
                    $return->firstuserimagealt = $arrusers[$discussion->userid]->imagealt;
                    $return->firstuserpicture = $arrusers[$discussion->userid]->picture;
                    $return->firstuseremail = $arrusers[$discussion->userid]->email;
                    $return->subject = $subject;
                    $return->numunread = '';
                    if ($cantrack && $forumtracked) {
                        if (isset($unreads[$discussion->id])) {
                            $return->numunread = (int) $unreads[$discussion->id];
                        }
                    }
                    // Check if there are any replies to this discussion.
                    if (!empty($replies[$discussion->id])) {
                         $return->numreplies = (int) $replies[$discussion->id]->replies;
                         $return->lastpost = (int) $replies[$discussion->id]->lastpostid;
                     } else { // No replies, so the last post will be the first post.
                        $return->numreplies = 0;
                        $return->lastpost = (int) $discussion->firstpost;
                     }
                    // Get the last post as well as the user who made it.
                    $lastpost = $DB->get_record('forum_posts', array('id' => $return->lastpost), '*', MUST_EXIST);
                    if (empty($arrusers[$lastpost->userid])) {
                        $arrusers[$lastpost->userid] = $DB->get_record('user', array('id' => $lastpost->userid),
                            'firstname, lastname, email, picture, imagealt', MUST_EXIST);
                    }
                    $return->lastuserid = $lastpost->userid;
                    $return->lastuserfullname = fullname($arrusers[$lastpost->userid], $canviewfullname);
                    $return->lastuserimagealt = $arrusers[$lastpost->userid]->imagealt;
                    $return->lastuserpicture = $arrusers[$lastpost->userid]->picture;
                    $return->lastuseremail = $arrusers[$lastpost->userid]->email;
                    // Add the discussion statistics to the array to return.
                    $arrdiscussions[$return->id] = (array) $return;
                }
            }
        }

        return $arrdiscussions;
    }
Example #4
0
 /**
  * Returns a list of forum discussions optionally sorted and paginated.
  *
  * @param int $forumid the forum instance id
  * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
  * @param string $sortdirection sort direction: ASC or DESC
  * @param int $page page number
  * @param int $perpage items per page
  *
  * @return array the forum discussion details including warnings
  * @since Moodle 2.8
  */
 public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC', $page = -1, $perpage = 0)
 {
     global $CFG, $DB, $USER;
     require_once $CFG->dirroot . "/mod/forum/lib.php";
     $warnings = array();
     $discussions = array();
     $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(), array('forumid' => $forumid, 'sortby' => $sortby, 'sortdirection' => $sortdirection, 'page' => $page, 'perpage' => $perpage));
     // Compact/extract functions are not recommended.
     $forumid = $params['forumid'];
     $sortby = $params['sortby'];
     $sortdirection = $params['sortdirection'];
     $page = $params['page'];
     $perpage = $params['perpage'];
     $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
     if (!in_array($sortby, $sortallowedvalues)) {
         throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' . 'allowed values are: ' . implode(',', $sortallowedvalues));
     }
     $sortdirection = strtoupper($sortdirection);
     $directionallowedvalues = array('ASC', 'DESC');
     if (!in_array($sortdirection, $directionallowedvalues)) {
         throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
     }
     $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
     $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
     $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
     // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
     $modcontext = context_module::instance($cm->id);
     self::validate_context($modcontext);
     // Check they have the view forum capability.
     require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
     $sort = 'd.' . $sortby . ' ' . $sortdirection;
     $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage);
     if ($alldiscussions) {
         $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
         // Get the unreads array, this takes a forum id and returns data for all discussions.
         $unreads = array();
         if ($cantrack = forum_tp_can_track_forums($forum)) {
             if ($forumtracked = forum_tp_is_tracked($forum)) {
                 $unreads = forum_get_discussions_unread($cm);
             }
         }
         // The forum function returns the replies for all the discussions in a given forum.
         $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage);
         foreach ($alldiscussions as $discussion) {
             // This function checks for qanda forums.
             // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
             $discussionrec = clone $discussion;
             $discussionrec->id = $discussion->discussion;
             if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
                 $warning = array();
                 // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
                 $warning['item'] = 'post';
                 $warning['itemid'] = $discussion->id;
                 $warning['warningcode'] = '1';
                 $warning['message'] = 'You can\'t see this discussion';
                 $warnings[] = $warning;
                 continue;
             }
             $discussion->numunread = 0;
             if ($cantrack && $forumtracked) {
                 if (isset($unreads[$discussion->discussion])) {
                     $discussion->numunread = (int) $unreads[$discussion->discussion];
                 }
             }
             $discussion->numreplies = 0;
             if (!empty($replies[$discussion->discussion])) {
                 $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
             }
             // Load user objects from the results of the query.
             $user = new stdclass();
             $user->id = $discussion->userid;
             $user = username_load_fields_from_object($user, $discussion);
             $discussion->userfullname = fullname($user, $canviewfullname);
             // We can have post written by users that are deleted. In this case, those users don't have a valid context.
             $usercontext = context_user::instance($user->id, IGNORE_MISSING);
             if ($usercontext) {
                 $discussion->userpictureurl = moodle_url::make_webservice_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', 'f1')->out(false);
             } else {
                 $discussion->userpictureurl = '';
             }
             $usermodified = new stdclass();
             $usermodified->id = $discussion->usermodified;
             $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um');
             $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
             // We can have post written by users that are deleted. In this case, those users don't have a valid context.
             $usercontext = context_user::instance($usermodified->id, IGNORE_MISSING);
             if ($usercontext) {
                 $discussion->usermodifiedpictureurl = moodle_url::make_webservice_pluginfile_url($usercontext->id, 'user', 'icon', null, '/', 'f1')->out(false);
             } else {
                 $discussion->usermodifiedpictureurl = '';
             }
             // Rewrite embedded images URLs.
             list($discussion->message, $discussion->messageformat) = external_format_text($discussion->message, $discussion->messageformat, $modcontext->id, 'mod_forum', 'post', $discussion->id);
             // List attachments.
             if (!empty($discussion->attachment)) {
                 $discussion->attachments = array();
                 $fs = get_file_storage();
                 if ($files = $fs->get_area_files($modcontext->id, 'mod_forum', 'attachment', $discussion->id, "filename", false)) {
                     foreach ($files as $file) {
                         $filename = $file->get_filename();
                         $discussion->attachments[] = array('filename' => $filename, 'mimetype' => $file->get_mimetype(), 'fileurl' => file_encode_url($CFG->wwwroot . '/webservice/pluginfile.php', '/' . $modcontext->id . '/mod_forum/attachment/' . $discussion->id . '/' . $filename));
                     }
                 }
             }
             $discussions[] = $discussion;
         }
     }
     $result = array();
     $result['discussions'] = $discussions;
     $result['warnings'] = $warnings;
     return $result;
 }
Example #5
0
 /**
  * Returns a list of forum discussions optionally sorted and paginated.
  *
  * @param int $forumid the forum instance id
  * @param string $sortby sort by this element (id, timemodified, timestart or timeend)
  * @param string $sortdirection sort direction: ASC or DESC
  * @param int $page page number
  * @param int $perpage items per page
  *
  * @return array the forum discussion details including warnings
  * @since Moodle 2.8
  */
 public static function get_forum_discussions_paginated($forumid, $sortby = 'timemodified', $sortdirection = 'DESC', $page = -1, $perpage = 0)
 {
     global $CFG, $DB, $USER, $PAGE;
     require_once $CFG->dirroot . "/mod/forum/lib.php";
     $warnings = array();
     $discussions = array();
     $params = self::validate_parameters(self::get_forum_discussions_paginated_parameters(), array('forumid' => $forumid, 'sortby' => $sortby, 'sortdirection' => $sortdirection, 'page' => $page, 'perpage' => $perpage));
     // Compact/extract functions are not recommended.
     $forumid = $params['forumid'];
     $sortby = $params['sortby'];
     $sortdirection = $params['sortdirection'];
     $page = $params['page'];
     $perpage = $params['perpage'];
     $sortallowedvalues = array('id', 'timemodified', 'timestart', 'timeend');
     if (!in_array($sortby, $sortallowedvalues)) {
         throw new invalid_parameter_exception('Invalid value for sortby parameter (value: ' . $sortby . '),' . 'allowed values are: ' . implode(',', $sortallowedvalues));
     }
     $sortdirection = strtoupper($sortdirection);
     $directionallowedvalues = array('ASC', 'DESC');
     if (!in_array($sortdirection, $directionallowedvalues)) {
         throw new invalid_parameter_exception('Invalid value for sortdirection parameter (value: ' . $sortdirection . '),' . 'allowed values are: ' . implode(',', $directionallowedvalues));
     }
     $forum = $DB->get_record('forum', array('id' => $forumid), '*', MUST_EXIST);
     $course = $DB->get_record('course', array('id' => $forum->course), '*', MUST_EXIST);
     $cm = get_coursemodule_from_instance('forum', $forum->id, $course->id, false, MUST_EXIST);
     // Validate the module context. It checks everything that affects the module visibility (including groupings, etc..).
     $modcontext = context_module::instance($cm->id);
     self::validate_context($modcontext);
     // Check they have the view forum capability.
     require_capability('mod/forum:viewdiscussion', $modcontext, null, true, 'noviewdiscussionspermission', 'forum');
     $sort = 'd.pinned DESC, d.' . $sortby . ' ' . $sortdirection;
     $alldiscussions = forum_get_discussions($cm, $sort, true, -1, -1, true, $page, $perpage, FORUM_POSTS_ALL_USER_GROUPS);
     if ($alldiscussions) {
         $canviewfullname = has_capability('moodle/site:viewfullnames', $modcontext);
         // Get the unreads array, this takes a forum id and returns data for all discussions.
         $unreads = array();
         if ($cantrack = forum_tp_can_track_forums($forum)) {
             if ($forumtracked = forum_tp_is_tracked($forum)) {
                 $unreads = forum_get_discussions_unread($cm);
             }
         }
         // The forum function returns the replies for all the discussions in a given forum.
         $replies = forum_count_discussion_replies($forumid, $sort, -1, $page, $perpage);
         foreach ($alldiscussions as $discussion) {
             // This function checks for qanda forums.
             // Note that the forum_get_discussions returns as id the post id, not the discussion id so we need to do this.
             $discussionrec = clone $discussion;
             $discussionrec->id = $discussion->discussion;
             if (!forum_user_can_see_discussion($forum, $discussionrec, $modcontext)) {
                 $warning = array();
                 // Function forum_get_discussions returns forum_posts ids not forum_discussions ones.
                 $warning['item'] = 'post';
                 $warning['itemid'] = $discussion->id;
                 $warning['warningcode'] = '1';
                 $warning['message'] = 'You can\'t see this discussion';
                 $warnings[] = $warning;
                 continue;
             }
             $discussion->numunread = 0;
             if ($cantrack && $forumtracked) {
                 if (isset($unreads[$discussion->discussion])) {
                     $discussion->numunread = (int) $unreads[$discussion->discussion];
                 }
             }
             $discussion->numreplies = 0;
             if (!empty($replies[$discussion->discussion])) {
                 $discussion->numreplies = (int) $replies[$discussion->discussion]->replies;
             }
             $discussion->name = external_format_string($discussion->name, $modcontext->id);
             $discussion->subject = external_format_string($discussion->subject, $modcontext->id);
             // Rewrite embedded images URLs.
             list($discussion->message, $discussion->messageformat) = external_format_text($discussion->message, $discussion->messageformat, $modcontext->id, 'mod_forum', 'post', $discussion->id);
             // List attachments.
             if (!empty($discussion->attachment)) {
                 $discussion->attachments = external_util::get_area_files($modcontext->id, 'mod_forum', 'attachment', $discussion->id);
             }
             $messageinlinefiles = external_util::get_area_files($modcontext->id, 'mod_forum', 'post', $discussion->id);
             if (!empty($messageinlinefiles)) {
                 $discussion->messageinlinefiles = $messageinlinefiles;
             }
             $discussion->locked = forum_discussion_is_locked($forum, $discussion);
             $discussion->canreply = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
             if (forum_is_author_hidden($discussion, $forum)) {
                 $discussion->userid = null;
                 $discussion->userfullname = null;
                 $discussion->userpictureurl = null;
                 $discussion->usermodified = null;
                 $discussion->usermodifiedfullname = null;
                 $discussion->usermodifiedpictureurl = null;
             } else {
                 $picturefields = explode(',', user_picture::fields());
                 // Load user objects from the results of the query.
                 $user = new stdclass();
                 $user->id = $discussion->userid;
                 $user = username_load_fields_from_object($user, $discussion, null, $picturefields);
                 // Preserve the id, it can be modified by username_load_fields_from_object.
                 $user->id = $discussion->userid;
                 $discussion->userfullname = fullname($user, $canviewfullname);
                 $userpicture = new user_picture($user);
                 $userpicture->size = 1;
                 // Size f1.
                 $discussion->userpictureurl = $userpicture->get_url($PAGE)->out(false);
                 $usermodified = new stdclass();
                 $usermodified->id = $discussion->usermodified;
                 $usermodified = username_load_fields_from_object($usermodified, $discussion, 'um', $picturefields);
                 // Preserve the id (it can be overwritten due to the prefixed $picturefields).
                 $usermodified->id = $discussion->usermodified;
                 $discussion->usermodifiedfullname = fullname($usermodified, $canviewfullname);
                 $userpicture = new user_picture($usermodified);
                 $userpicture->size = 1;
                 // Size f1.
                 $discussion->usermodifiedpictureurl = $userpicture->get_url($PAGE)->out(false);
             }
             $discussions[] = $discussion;
         }
     }
     $result = array();
     $result['discussions'] = $discussions;
     $result['warnings'] = $warnings;
     return $result;
 }
Example #6
0
/**
 * Prints the discussion view screen for a forum.
 *
 * @param object $course The current course object.
 * @param object $forum Forum to be printed.
 * @param int $maxdiscussions .
 * @param string $displayformat The display format to use (optional).
 * @param string $sort Sort arguments for database query (optional).
 * @param int $groupmode Group mode of the forum (optional).
 * @param void $unused (originally current group)
 * @param int $page Page mode, page to display (optional).
 * @param int perpage The maximum number of discussions per page(optional)
 *
 */
function forum_print_latest_discussions($course, $forum, $maxdiscussions = -1, $displayformat = 'plain', $sort = '', $currentgroup = -1, $groupmode = -1, $page = -1, $perpage = 100, $cm = NULL)
{
    global $CFG, $USER;
    if (!$cm) {
        if (!($cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course))) {
            error('Course Module ID was incorrect');
        }
    }
    $context = get_context_instance(CONTEXT_MODULE, $cm->id);
    if (empty($sort)) {
        $sort = "d.timemodified DESC";
    }
    $olddiscussionlink = false;
    // Sort out some defaults
    if ($perpage <= 0) {
        $perpage = 0;
        $page = -1;
    }
    if ($maxdiscussions == 0) {
        // all discussions - backwards compatibility
        $page = -1;
        $perpage = 0;
        if ($displayformat == 'plain') {
            $displayformat = 'header';
            // Abbreviate display by default
        }
    } else {
        if ($maxdiscussions > 0) {
            $page = -1;
            $perpage = $maxdiscussions;
        }
    }
    $fullpost = false;
    if ($displayformat == 'plain') {
        $fullpost = true;
    }
    // Decide if current user is allowed to see ALL the current discussions or not
    // First check the group stuff
    if ($currentgroup == -1 or $groupmode == -1) {
        $groupmode = groups_get_activity_groupmode($cm, $course);
        $currentgroup = groups_get_activity_group($cm);
    }
    // If the user can post discussions, then this is a good place to put the
    // button for it. We do not show the button if we are showing site news
    // and the current user is a guest.
    // MARCOND: Modificado para não mostrar o botão de inclusão de noticias
    // quando mostrando forums pertencentes a front page
    if (forum_user_can_post_discussion($forum, $currentgroup, $groupmode, $cm, $context) || ($forum->type != 'news' and $forum->course != '1' and (isguestuser() or !isloggedin() or has_capability('moodle/legacy:guest', $context, NULL, false)))) {
        echo '<div class="singlebutton forumaddnew">';
        echo "<form id=\"newdiscussionform\" method=\"get\" action=\"{$CFG->wwwroot}/mod/forum/post.php\">";
        echo '<div>';
        echo "<input type=\"hidden\" name=\"forum\" value=\"{$forum->id}\" />";
        echo '<input type="submit" value="';
        echo $forum->type == 'news' ? get_string('addanewtopic', 'forum') : ($forum->type == 'qanda' ? get_string('addanewquestion', 'forum') : get_string('addanewdiscussion', 'forum'));
        echo '" />';
        echo '</div>';
        echo '</form>';
        echo "</div>\n";
    } else {
        if (isguestuser() or !isloggedin() or $forum->type == 'news') {
            // no button and no info
        } else {
            if ($groupmode and has_capability('mod/forum:startdiscussion', $context)) {
                // inform users why they can not post new discussion
                if ($currentgroup) {
                    notify(get_string('cannotadddiscussion', 'forum'));
                } else {
                    notify(get_string('cannotadddiscussionall', 'forum'));
                }
            }
        }
    }
    // Get all the recent discussions we're allowed to see
    $getuserlastmodified = $displayformat == 'header';
    if (!($discussions = forum_get_discussions($cm, $sort, $fullpost, null, $maxdiscussions, $getuserlastmodified, $page, $perpage))) {
        echo '<div class="forumnodiscuss">';
        if ($forum->type == 'news') {
            echo '(' . get_string('nonews', 'forum') . ')';
        } else {
            if ($forum->type == 'qanda') {
                echo '(' . get_string('noquestions', 'forum') . ')';
            } else {
                echo '(' . get_string('nodiscussions', 'forum') . ')';
            }
        }
        echo "</div>\n";
        return;
    }
    // If we want paging
    if ($page != -1) {
        ///Get the number of discussions found
        $numdiscussions = forum_get_discussions_count($cm);
        ///Show the paging bar
        print_paging_bar($numdiscussions, $page, $perpage, "view.php?f={$forum->id}&amp;");
        if ($numdiscussions > 1000) {
            // saves some memory on sites with very large forums
            $replies = forum_count_discussion_replies($forum->id, $sort, $maxdiscussions, $page, $perpage);
        } else {
            $replies = forum_count_discussion_replies($forum->id);
        }
    } else {
        $replies = forum_count_discussion_replies($forum->id);
        if ($maxdiscussions > 0 and $maxdiscussions <= count($discussions)) {
            $olddiscussionlink = true;
        }
    }
    $canviewparticipants = has_capability('moodle/course:viewparticipants', $context);
    $strdatestring = get_string('strftimerecentfull');
    // Check if the forum is tracked.
    if ($cantrack = forum_tp_can_track_forums($forum)) {
        $forumtracked = forum_tp_is_tracked($forum);
    } else {
        $forumtracked = false;
    }
    if ($forumtracked) {
        $unreads = forum_get_discussions_unread($cm);
    } else {
        $unreads = array();
    }
    if ($displayformat == 'header') {
        echo '<table cellspacing="0" class="forumheaderlist">';
        echo '<thead>';
        echo '<tr>';
        echo '<th class="header topic" scope="col">' . get_string('discussion', 'forum') . '</th>';
        echo '<th class="header author" colspan="2" scope="col">' . get_string('startedby', 'forum') . '</th>';
        if ($groupmode > 0) {
            echo '<th class="header group" scope="col">' . get_string('group') . '</th>';
        }
        if (has_capability('mod/forum:viewdiscussion', $context)) {
            echo '<th class="header replies" scope="col">' . get_string('replies', 'forum') . '</th>';
            // If the forum can be tracked, display the unread column.
            if ($cantrack) {
                echo '<th class="header replies" scope="col">' . get_string('unread', 'forum');
                if ($forumtracked) {
                    echo '&nbsp;<a title="' . get_string('markallread', 'forum') . '" href="' . $CFG->wwwroot . '/mod/forum/markposts.php?f=' . $forum->id . '&amp;mark=read&amp;returnpage=view.php">' . '<img src="' . $CFG->pixpath . '/t/clear.gif" class="iconsmall" alt="' . get_string('markallread', 'forum') . '" /></a>';
                }
                echo '</th>';
            }
        }
        echo '<th class="header lastpost" scope="col">' . get_string('lastpost', 'forum') . '</th>';
        echo '</tr>';
        echo '</thead>';
        echo '<tbody>';
    }
    foreach ($discussions as $discussion) {
        if (!empty($replies[$discussion->discussion])) {
            $discussion->replies = $replies[$discussion->discussion]->replies;
            $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
        } else {
            $discussion->replies = 0;
        }
        // SPECIAL CASE: The front page can display a news item post to non-logged in users.
        // All posts are read in this case.
        if (!$forumtracked) {
            $discussion->unread = '-';
        } else {
            if (empty($USER)) {
                $discussion->unread = 0;
            } else {
                if (empty($unreads[$discussion->discussion])) {
                    $discussion->unread = 0;
                } else {
                    $discussion->unread = $unreads[$discussion->discussion];
                }
            }
        }
        if (!empty($USER->id)) {
            $ownpost = $discussion->userid == $USER->id;
        } else {
            $ownpost = false;
        }
        // Use discussion name instead of subject of first post
        $discussion->subject = $discussion->name;
        switch ($displayformat) {
            case 'header':
                if ($groupmode > 0) {
                    if (isset($groups[$discussion->groupid])) {
                        $group = $groups[$discussion->groupid];
                    } else {
                        $group = $groups[$discussion->groupid] = groups_get_group($discussion->groupid);
                    }
                } else {
                    $group = -1;
                }
                forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked, $canviewparticipants, $context);
                break;
            default:
                $link = false;
                if ($discussion->replies) {
                    $link = true;
                } else {
                    $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
                    $link = forum_user_can_post($forum, $discussion, $USER, $cm, $course, $modcontext);
                }
                $link = true;
                // MARCOND: Para imprimir os resumos na FrontPage
                $discussion->forum = $forum->id;
                forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false);
                break;
        }
    }
    if ($displayformat == "header") {
        echo '</tbody>';
        echo '</table>';
    }
    if ($olddiscussionlink) {
        if ($forum->type == 'news') {
            $strolder = get_string('oldertopics', 'forum');
        } else {
            $strolder = get_string('olderdiscussions', 'forum');
        }
        echo '<div class="forumolddiscuss">';
        echo '<a href="' . $CFG->wwwroot . '/mod/forum/view.php?f=' . $forum->id . '&amp;showall=1">';
        echo $strolder . '</a> ...</div>';
    }
    if ($page != -1) {
        ///Show the paging bar
        print_paging_bar($numdiscussions, $page, $perpage, "view.php?f={$forum->id}&amp;");
    }
}