/**
  * Queries for draft posts, including necessary joins with other fields.
  * @param string $where Text of WHERE clause e.g. 'fdr.id=14'. May refer
  *   to aliases fdr (drafts), fd (discussions), fp (posts; post being 
  *   replied to), fpfirst (first post in discussion), and u (user being
  *   replied to)
  * @return array Array of forum_draft objects (empty if none)
  */
 static function query_drafts($where)
 {
     global $CFG;
     $result = array();
     $rs = get_recordset_sql("\nSELECT\n    fdr.*, fd.id AS discussionid, fpfirst.subject AS discussionsubject, \n    f.course AS courseid,\n    " . forum_utils::select_username_fields('u', false) . "\nFROM\n    {$CFG->prefix}forumng_drafts fdr\n    LEFT JOIN {$CFG->prefix}forumng_posts fp ON fdr.parentpostid = fp.id\n    LEFT JOIN {$CFG->prefix}forumng_discussions fd ON fp.discussionid = fd.id\n    LEFT JOIN {$CFG->prefix}forumng_posts fpfirst ON fd.postid = fpfirst.id\n    LEFT JOIN {$CFG->prefix}user u ON fp.userid = u.id\n    INNER JOIN {$CFG->prefix}forumng f ON fdr.forumid = f.id\nWHERE\n    {$where}\nORDER BY\n    fdr.saved DESC\n    ");
     if (!$rs) {
         throw new forum_exception("Failed to query for draft posts");
     }
     while ($rec = rs_fetch_next_record($rs)) {
         $result[] = new forum_draft($rec);
     }
     rs_close($rs);
     return $result;
 }
 /**
  * Creates the mail queue and runs query to obtain list of posts that should
  * be mailed.
  * @param bool $tracetimes True if it should call mtrace to display
  *   performance information
  */
 function __construct($tracetimes)
 {
     global $CFG;
     $this->time = time();
     $this->forum = null;
     $this->discussion = null;
     $this->storedrecord = null;
     $this->postcount = 0;
     // Check if an earlier run got aborted. In that case we mark all
     // messages as mailed anyway because it's better to skip some than
     // to send out double-posts.
     if ($pending = get_config('forumng', $this->get_pending_flag_name())) {
         $this->mark_mailed($pending);
     }
     // Note that we are mid-run
     set_config($this->get_pending_flag_name(), $this->time, 'forumng');
     $querychunk = $this->get_query_chunk($this->time);
     if (!($this->rs = get_recordset_sql($sql = "\nSELECT\n    " . forum_utils::select_forum_fields('f') . ",\n    " . forum_utils::select_discussion_fields('fd') . ",\n    " . forum_utils::select_post_fields('discussionpost') . ",\n    " . forum_utils::select_post_fields('fp') . ",\n    " . forum_utils::select_post_fields('reply') . ",\n    " . forum_utils::select_course_module_fields('cm') . ",\n    " . forum_utils::select_context_fields('x') . ",\n    " . forum_utils::select_username_fields('u', true) . ",\n    " . forum_utils::select_username_fields('eu') . ",\n    " . forum_utils::select_username_fields('replyu') . ",\n    " . forum_utils::select_username_fields('replyeu') . ",\n    " . forum_utils::select_course_fields('c') . ",\n    clonecm.id AS cloneid\n{$querychunk}\nORDER BY\n    clonecm.course, f.id, fd.id, fp.id"))) {
         throw new forum_exception("Mail queue query failed");
     }
 }
 /**
  * Obtains list of forum subscribers.
  * @param int $groupid If specified, restricts list to this group id
  * @return array Array of partial user objects (with enough info to send
  *   email and display them); additionally, if the forum is in group mode,
  *   this includes an ->accessallgroups boolean
  */
 public function get_subscribers($groupid = forum::ALL_GROUPS)
 {
     global $CFG;
     // Array that will contain result
     $users = array();
     // Get permitted groups
     $groups = $this->get_permitted_groups();
     $subscriptionoption = $this->get_effective_subscription_option();
     switch ($subscriptionoption) {
         case self::SUBSCRIPTION_NOT_PERMITTED:
             return array();
         case self::SUBSCRIPTION_FORCED:
         case self::SUBSCRIPTION_INITIALLY_SUBSCRIBED:
             $users = $this->get_auto_subscribers($groupid);
             //add $wholeforum = 1 and an empty array() for discussionid
             //for people who initially subscribed
             foreach ($users as $user) {
                 $user->wholeforum = true;
                 $user->discussionids = array();
                 $user->groupids = array();
             }
             break;
         default:
             // The other two cases (initial subscribe, and manual subscribe)
             // fall through to the standard code below.
     }
     $context = $this->get_context();
     // For shared forums, we only return the subscribers for the current
     // clone
     $clonecheck = "";
     if ($this->is_shared()) {
         $clonecheck = 'AND s.clonecmid = ' . $this->get_course_module_id();
     }
     // Obtain the list of users who have access all groups on the forum,
     // unless it's in no-groups mode
     $groupmode = $this->get_group_mode();
     if ($groupmode) {
         //Get a list of user who can access all groups
         $aagusers = get_users_by_capability($context, 'moodle/site:accessallgroups', 'u.id');
         $aagusers = $aagusers ? $aagusers : array();
     }
     // Get the list of subscribed users.
     if ($groupid == forum::ALL_GROUPS || $groupid == forum::NO_GROUPS) {
         $groupcheck = '';
     } else {
         $groupcheck = "INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid=u.id AND gm.groupid={$groupid}";
     }
     $rs = get_recordset_sql($sql = "\nSELECT\n    " . forum_utils::select_username_fields('u', true) . ",\n    s.subscribed, s.discussionid, s.groupid, fd.groupid AS discussiongroupid, discussiongm.id AS discussiongroupmember,\n    subscriptiongm.id AS subscriptiongroupmember\nFROM\n    {$CFG->prefix}forumng_subscriptions s\n    INNER JOIN {$CFG->prefix}user u ON u.id=s.userid\n    {$groupcheck}\n    LEFT JOIN {$CFG->prefix}forumng_discussions fd ON fd.id = s.discussionid\n    LEFT JOIN {$CFG->prefix}groups_members discussiongm ON fd.groupid = discussiongm.groupid AND s.userid = discussiongm.userid\n    LEFT JOIN {$CFG->prefix}groups_members subscriptiongm ON s.groupid = subscriptiongm.groupid AND s.userid = subscriptiongm.userid\nWHERE\n    s.forumid={$this->forumfields->id}\n    AND (fd.forumid={$this->forumfields->id} OR s.discussionid IS NULL)\n    {$clonecheck}");
     if (!$rs) {
         throw new forum_exception('Failed to get subscriber list [' . $sql . ']');
     }
     // Filter the result against the list of allowed users
     $allowedusers = null;
     while ($rec = rs_fetch_next_record($rs)) {
         //subscribed to the whole forum when subscribed == 1 and disucssionid =='';
         // *** Put the allowedusers checks in same part of code so not duplicated
         if ($rec->subscribed) {
             // This is a 'subscribe' request
             if (!$allowedusers) {
                 // Obtain the list of users who are allowed to see the forum.
                 // As get_users_by_capability can be expensive, we only do this
                 // once we know there actually are subscribers.
                 $allowedusers = get_users_by_capability($context, 'mod/forumng:viewdiscussion', 'u.id', '', '', '', $groups, '', true, false, true);
                 $allowedusers = $allowedusers ? $allowedusers : array();
             }
             // Get reference to current user, or make new object if required
             if (!array_key_exists($rec->u_id, $users)) {
                 $user = forum_utils::extract_subobject($rec, 'u_');
                 $user->wholeforum = false;
                 $user->discussionids = array();
                 $user->groupids = array();
                 $newuser = true;
             } else {
                 $user = $users[$rec->u_id];
                 $newuser = false;
             }
             $ok = false;
             //Subscribed to a discussion
             if ($rec->discussionid) {
                 $groupok = !$rec->discussiongroupid || $rec->discussiongroupmember || $groupmode == VISIBLEGROUPS || array_key_exists($user->id, $aagusers);
                 if (array_key_exists($user->id, $allowedusers) && $groupok) {
                     $ok = true;
                     $user->discussionids[$rec->discussionid] = $rec->discussiongroupid;
                 }
                 //Subscribed to a group
             } else {
                 if ($rec->groupid) {
                     $groupok = $groupmode == VISIBLEGROUPS || $groupmode == SEPARATEGROUPS && ($rec->subscriptiongroupmember || array_key_exists($user->id, $aagusers));
                     if (array_key_exists($user->id, $allowedusers) && $groupok) {
                         $user->groupids[$rec->groupid] = $rec->groupid;
                         $ok = true;
                     }
                     //Subscribed to the whole forum
                 } else {
                     // extra conditions for forum not separate groups or accessallgroups
                     $groupok = $groupmode != SEPARATEGROUPS || array_key_exists($user->id, $aagusers);
                     if (array_key_exists($user->id, $allowedusers) && $groupok) {
                         $user->wholeforum = true;
                         $ok = true;
                     }
                 }
             }
             // If this is a new user object, add it to the array provided the row was valid
             if ($newuser && $ok) {
                 $users[$user->id] = $user;
             }
         } else {
             // This is an 'unsubscribe' request. These are only allowed
             // for initial-subscription, otherwise ignored
             if ($subscriptionoption == self::SUBSCRIPTION_INITIALLY_SUBSCRIBED && array_key_exists($user->id, $users)) {
                 // set wholeforum = false for user (if they are in the array)
                 $users[$rec->u_id]->unsubscribe = true;
                 $users[$rec->u_id]->wholeforum = false;
             }
         }
     }
     rs_close($rs);
     //1. loop through array and clear the discussions/groupids array if wholeforum is true
     //2. Find any user unsubscribed from initial subscribed forum. If the user has been subscribed to discussions/groups
     //   remove the $user->unsubscribe flag; Otherwise remove the user from the list.
     foreach ($users as $key => $user) {
         if ($user->wholeforum) {
             $user->discussionids = array();
             $user->groupids = array();
         }
         // Remove discussionids for discussions that are already covered by group subscriptions
         // TODO
         if (count($user->discussionids) != 0 && count($user->groupids) != 0) {
             foreach ($user->discussionids as $id => $dgroupid) {
                 if (!$dgroupid || array_key_exists($dgroupid, $user->groupids)) {
                     unset($user->discussionids[$id]);
                 }
             }
         }
         // If the user has unsubscribed from an initial subscription, then remove the entry
         // from the results array unless there are s subscriptions to discussions or groups
         if (!empty($user->unsubscribe)) {
             //Remove the unsubscribe as the user is likely to subscribed to discussions or groups
             unset($user->unsubscribe);
             if (count($user->discussionids) == 0 && count($user->groupids) == 0) {
                 unset($users[$key]);
             }
         }
     }
     // Add access-all-groups information if applicable
     if ($groupmode) {
         foreach ($users as $key => $user) {
             $user->accessallgroups = array_key_exists($user->id, $aagusers);
         }
     }
     return $users;
 }
 /**
  * Obtains a list of everybody who has read this discussion (only works
  * if the discussion is within the 'read' period). The list is in date order
  * (most recent first). Each returned item has ->time (time last read) and
  * ->user (Moodle user object) fields.
  * @param int $groupid Group ID or forum::ALL_GROUPS
  * @return array Array of information about readers
  */
 public function get_readers($groupid = forum::ALL_GROUPS)
 {
     global $CFG;
     $context = $this->get_forum()->get_context();
     // Create comma separated list of context ids
     $context_ids = str_replace('/', ',', substr($context->path, 1));
     $id = $this->discussionfields->id;
     $groupjoin = $groupquery = '';
     $groupwhere = '';
     if ($groupid) {
         $groupjoin = " INNER JOIN {$CFG->prefix}groups_members gm ON gm.userid=fr.userid\n    INNER JOIN {$CFG->prefix}groups g ON gm.groupid = g.id";
         $groupwhere = " AND g.id={$groupid}";
     }
     $result = get_records_sql("\nSELECT\n    fr.id,\n    " . forum_utils::select_username_fields('u', false) . ",\n    fr.time,\n    u.idnumber AS u_idnumber\nFROM\n    {$CFG->prefix}forumng_read fr\n    INNER JOIN {$CFG->prefix}user u ON u.id = fr.userid\n    {$groupjoin}\nWHERE\n    fr.discussionid = {$id}\n    {$groupquery}\n    AND fr.userid in(SELECT userid FROM {$CFG->prefix}role_assignments ra  \n        WHERE ra.contextid in({$context_ids})AND ra.roleid in ({$CFG->forumng_monitorroles}))\n            {$groupwhere}\nORDER BY\n    fr.time DESC");
     $result = $result ? $result : array();
     foreach ($result as $item) {
         $item->user = forum_utils::extract_subobject($item, 'u_');
     }
     return $result;
 }
 /**
  * Internal function. Queries for posts.
  * @param string $where Where clause (fp is alias for post table)
  * @param string $order Sort order; the default is fp.id - note this is preferable
  *   to fp.timecreated because it works correctly if there are two posts in
  *   the same second
  * @param bool $ratings True if ratings should be included in the query
  * @param bool $flags True if flags should be included in the query
  * @param bool $effectivesubjects True if the query should include the
  *   (complicated!) logic to obtain the 'effective subject'. This may result
  *   in additional queries afterward for posts which are very deeply nested.
  * @param int $userid 0 = current user (at present this is only used for
  *   flags)
  * @return array Resulting posts as array of Moodle records, empty array
  *   if none
  */
 static function query_posts($where, $order = 'fp.id', $ratings = true, $flags = false, $effectivesubjects = false, $userid = 0, $joindiscussion = false, $discussionsubject = false, $limitfrom = '', $limitnum = '')
 {
     global $CFG, $USER;
     $userid = forum_utils::get_real_userid($userid);
     // We include ratings if these are enabled, otherwise save the database
     // some effort and don't bother
     if ($ratings) {
         $ratingsquery = ",\n(SELECT AVG(rating) FROM {$CFG->prefix}forumng_ratings\n    WHERE postid=fp.id) AS averagerating,\n(SELECT COUNT(1) FROM {$CFG->prefix}forumng_ratings\n    WHERE postid=fp.id) AS numratings,\n(SELECT rating FROM {$CFG->prefix}forumng_ratings\n    WHERE postid=fp.id AND userid={$USER->id}) AS ownrating";
     } else {
         $ratingsquery = '';
     }
     if ($flags) {
         $flagsjoin = "\n    LEFT JOIN {$CFG->prefix}forumng_flags ff ON ff.postid = fp.id AND ff.userid = {$userid}";
         $flagsquery = ",ff.flagged";
     } else {
         $flagsjoin = '';
         $flagsquery = '';
     }
     if ($joindiscussion) {
         $discussionjoin = "\n    INNER JOIN {$CFG->prefix}forumng_discussions fd ON fp.discussionid = fd.id";
         $discussionquery = ',' . forum_utils::select_discussion_fields('fd');
         if ($discussionsubject) {
             $discussionjoin .= "\n    INNER JOIN {$CFG->prefix}forumng_posts fdfp ON fd.postid = fdfp.id";
             $discussionquery .= ', fdfp.subject AS fd_subject';
         }
     } else {
         $discussionjoin = '';
         $discussionquery = '';
     }
     if ($effectivesubjects) {
         $maxdepth = self::PARENTPOST_DEPTH_PER_QUERY;
         $subjectsjoin = '';
         $subjectsquery = ", p{$maxdepth}.parentpostid AS nextparent ";
         for ($depth = 2; $depth <= $maxdepth; $depth++) {
             $subjectsquery .= ", p{$depth}.subject AS s{$depth}, p{$depth}.deleted AS d{$depth}";
             $prev = 'p' . ($depth - 1);
             if ($prev == 'p1') {
                 $prev = 'fp';
             }
             $subjectsjoin .= "LEFT JOIN {$CFG->prefix}forumng_posts p{$depth}\n                    ON p{$depth}.id = {$prev}.parentpostid ";
         }
     } else {
         $subjectsjoin = '';
         $subjectsquery = '';
     }
     // Retrieve posts from discussion with incorporated user information
     // and ratings info if specified
     $results = forum_utils::get_records_sql("\nSELECT\n    fp.*,\n    " . forum_utils::select_username_fields('u') . ",\n    " . forum_utils::select_username_fields('eu') . ",\n    " . forum_utils::select_username_fields('du') . "\n    {$ratingsquery}\n    {$flagsquery}\n    {$subjectsquery}\n    {$discussionquery}\nFROM\n    {$CFG->prefix}forumng_posts fp\n    INNER JOIN {$CFG->prefix}user u ON fp.userid=u.id\n    LEFT JOIN {$CFG->prefix}user eu ON fp.edituserid=eu.id\n    LEFT JOIN {$CFG->prefix}user du ON fp.deleteuserid=du.id    \n    {$discussionjoin}\n    {$flagsjoin}\n    {$subjectsjoin}\nWHERE\n    {$where}\nORDER BY\n    {$order}\n", $limitfrom, $limitnum);
     if ($effectivesubjects) {
         // Figure out the effective subject for each result
         foreach ($results as $result) {
             $got = false;
             if ($result->subject !== null) {
                 $result->effectivesubject = $result->subject;
                 $got = true;
                 continue;
             }
             for ($depth = 2; $depth <= $maxdepth; $depth++) {
                 $var = "s{$depth}";
                 $var2 = "d{$depth}";
                 if (!$got && $result->{$var} !== null && $result->{$var2} == 0) {
                     $result->effectivesubject = get_string('re', 'forumng', $result->{$var});
                     $got = true;
                 }
                 unset($result->{$var});
                 unset($result->{$var2});
             }
             if (!$got) {
                 // Do extra queries to pick up subjects for posts where it
                 // was unknown within the default depth. We can use the
                 // 'nextparent' to get the ID of the parent post of the last
                 // one that we checked already
                 $result->effectivesubject = self::inner_get_recursive_subject($result->nextparent);
             }
         }
     }
     return $results;
 }