]> git.mjollnir.org Git - moodle.git/commitdiff
MDL-13450 and MDL-13303 - sorry for changing forum API so late, but it was needed...
authorskodak <skodak>
Wed, 13 Feb 2008 17:03:25 +0000 (17:03 +0000)
committerskodak <skodak>
Wed, 13 Feb 2008 17:03:25 +0000 (17:03 +0000)
33 files changed:
blocks/messages/block_messages.php
blog/lib.php
course/lib.php
lib/accesslib.php
lib/grouplib.php
message/discussion.php
message/user.php
mod/chat/lib.php
mod/chat/report.php
mod/chat/view.php
mod/data/lib.php
mod/forum/discuss.php
mod/forum/lib.php
mod/forum/mod_form.php
mod/forum/post.php
mod/forum/restorelib.php
mod/forum/search.php
mod/forum/settings.php
mod/forum/subscriber.html
mod/forum/subscribers.php
mod/forum/user.php
mod/forum/view.php
mod/glossary/formats/TEMPLATE/TEMPLATE_format.php
mod/glossary/formats/encyclopedia/encyclopedia_format.php
mod/glossary/formats/fullwithauthor/fullwithauthor_format.php
mod/glossary/lib.php
mod/glossary/view.php
mod/quiz/review.php
mod/quiz/reviewquestion.php
notes/lib.php
user/edit_form.php
user/editadvanced_form.php
user/view.php

index 93589364e91d7104a0497e936cfeceb96f4d58b4..c56170001dcd13016d70da139c0297516279fd1d 100644 (file)
@@ -28,7 +28,7 @@ class block_messages extends block_base {
         $this->content->footer = '<a href="'.$CFG->wwwroot.'/message/index.php" onclick="this.target=\'message\'; return openpopup(\'/message/index.php\', \'message\', \'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500\', 0);">'.get_string('messages', 'message').'</a>...';
 
         $users = get_records_sql("SELECT m.useridfrom as id, COUNT(m.useridfrom) as count,
-                                         u.firstname, u.lastname, u.picture, u.lastaccess
+                                         u.firstname, u.lastname, u.picture, u.imagealt, u.lastaccess
                                        FROM {$CFG->prefix}user u, 
                                             {$CFG->prefix}message m 
                                        WHERE m.useridto = '$USER->id' 
@@ -43,7 +43,7 @@ class block_messages extends block_base {
             foreach ($users as $user) {
                 $timeago = format_time(time() - $user->lastaccess);
                 $this->content->text .= '<li class="listentry"><div class="user"><a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$this->instance->pageid.'" title="'.$timeago.'">';
-                $this->content->text .= print_user_picture($user->id, $this->instance->pageid, $user->picture, 0, true, false, '', false);
+                $this->content->text .= print_user_picture($user, $this->instance->pageid, $user->picture, 0, true, false, '', false);
                 $this->content->text .= fullname($user).'</a></div>';
                 $this->content->text .= '<div class="message"><a href="'.$CFG->wwwroot.'/message/discussion.php?id='.$user->id.'" onclick="this.target=\'message_'.$user->id.'\'; return openpopup(\'/message/discussion.php?id='.$user->id.'\', \'message_'.$user->id.'\', \'menubar=0,location=0,scrollbars,status,resizable,width=400,height=500\', 0);"><img class="iconsmall" src="'.$CFG->pixpath.'/t/message.gif" alt="" />&nbsp;'.$user->count.'</a>';
                 $this->content->text .= '</div></li>';
index 5a8ba603a2645abdc9b1d34966bf87d7008c3018..b1aa76e7906c241240c90ee77a11406f9305c168 100755 (executable)
         echo '<table cellspacing="0" class="forumpost blogpost blog'.$template['publishstate'].'" width="100%">';
 
         echo '<tr class="header"><td class="picture left">';
-        print_user_picture($template['userid'], SITEID, $user->picture);
+        print_user_picture($user, SITEID, $user->picture);
         echo '</td>';
 
         echo '<td class="topic starter"><div class="subject">'.$template['title'].'</div><div class="author">';
index 9f1a5353a79b3002b6873f0ddcff8c4d3196ecd6..a063c2fe56a21e31f64abdb884f97972747fe828 100644 (file)
@@ -1074,6 +1074,16 @@ function &get_fast_modinfo(&$course, $userid=0) {
 
     $modlurals = array();
 
+    $cmids    = array();
+    $contexts = null;
+    foreach ($info as $mod) {
+        $cmids[$mod->cm] = $mod->cm;
+    }
+    if ($cmids) {
+        // preload all module contexts with one query
+        $contexts = get_context_instance(CONTEXT_MODULE, $cmids);
+    }
+
     foreach ($info as $mod) {
         // reconstruct minimalistic $cm
         $cm = new object();
@@ -1097,11 +1107,11 @@ function &get_fast_modinfo(&$course, $userid=0) {
         }
         $cm->modplural = $modlurals[$cm->modname];
 
-        if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
+        if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $contexts[$cm->id], $userid)) {
             $cm->uservisible = false;
 
         } else if (!empty($CFG->enablegroupings) and !empty($cm->groupmembersonly)
-                and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id), $userid)) {
+                and !has_capability('moodle/site:accessallgroups', $contexts[$cm->id], $userid)) {
             if (is_null($modinfo->groups)) {
                 $modinfo->groups = groups_get_user_groups($course->id, $userid);
             }
@@ -1440,6 +1450,10 @@ function print_section_add_menus($course, $section, $modnames, $vertical=false,
             if (function_exists($gettypesfunc)) {
                 $types = $gettypesfunc();
                 foreach($types as $type) {
+                    if (!isset($type->modclass) or !isset($type->typestr)) {
+                        debugging('Incorrect ativity type in '.$modname);
+                        continue;
+                    }
                     if ($type->modclass == MOD_CLASS_RESOURCE) {
                         $resources[$type->type] = $type->typestr;
                     } else {
index e550f46c1b55ccbef2e5b4d80a46b47de958f35b..2f10620d165734d287b9421d6094c479fcb41ec9 100755 (executable)
@@ -2538,7 +2538,7 @@ function cleanup_contexts() {
  */
 function get_context_instance($contextlevel, $instance=0) {
 
-    global $context_cache, $context_cache_id;
+    global $context_cache, $context_cache_id, $CFG;
     static $allowed_contexts = array(CONTEXT_SYSTEM, CONTEXT_USER, CONTEXT_COURSECAT, CONTEXT_COURSE, CONTEXT_GROUP, CONTEXT_MODULE, CONTEXT_BLOCK);
 
     if ($contextlevel === 'clearcache') {
@@ -2561,30 +2561,79 @@ function get_context_instance($contextlevel, $instance=0) {
         error('Error: get_context_instance() called with incorrect context level "'.s($contextlevel).'"');
     }
 
-/// Check the cache
-    if (isset($context_cache[$contextlevel][$instance])) {  // Already cached
-        return $context_cache[$contextlevel][$instance];
+    if (!is_array($instance)) {
+    /// Check the cache
+        if (isset($context_cache[$contextlevel][$instance])) {  // Already cached
+            return $context_cache[$contextlevel][$instance];
+        }
+
+    /// Get it from the database, or create it
+        if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
+            $context = create_context($contextlevel, $instance);
+        }
+
+    /// Only add to cache if context isn't empty.
+        if (!empty($context)) {
+            $context_cache[$contextlevel][$instance] = $context;    // Cache it for later
+            $context_cache_id[$context->id]          = $context;    // Cache it for later
+        }
+
+        return $context;
     }
 
-/// Get it from the database, or create it
-    if (!$context = get_record('context', 'contextlevel', $contextlevel, 'instanceid', $instance)) {
-        $context = create_context($contextlevel, $instance);
+
+/// ok, somebody wants to load several contexts to save some db queries ;-)
+    $instances = $instance;
+    $result = array();
+
+    foreach ($instances as $key=>$instance) {
+    /// Check the cache first
+        if (isset($context_cache[$contextlevel][$instance])) {  // Already cached
+            $result[$instance] = $context_cache[$contextlevel][$instance];
+            unset($instances[$key]);
+            continue;
+        }
     }
 
-/// Only add to cache if context isn't empty.
-    if (!empty($context)) {
-        $context_cache[$contextlevel][$instance] = $context;    // Cache it for later
-        $context_cache_id[$context->id] = $context;      // Cache it for later
+    if ($instances) {
+        if (count($instances) > 1) {
+            $instanceids = implode(',', $instances);
+            $instanceids = "instanceid IN ($instanceids)";
+        } else {
+            $instance = reset($instances);
+            $instanceids = "instanceid = $instance";
+        }
+        
+        if (!$contexts = get_records_sql("SELECT instanceid, id, contextlevel, path, depth
+                                            FROM {$CFG->prefix}context
+                                           WHERE contextlevel=$contextlevel AND $instanceids")) {
+            $contexts = array();
+        }
+
+        foreach ($instances as $instance) {
+            if (isset($contexts[$instance])) {
+                $context = $contexts[$instance];
+            } else {
+                $context = create_context($contextlevel, $instance);
+            }
+
+            if (!empty($context)) {
+                $context_cache[$contextlevel][$instance] = $context;    // Cache it for later
+                $context_cache_id[$context->id] = $context;             // Cache it for later
+            }
+
+            $result[$instance] = $context;
+        }
     }
 
-    return $context;
+    return $result;
 }
 
 
 /**
  * Get a context instance as an object, from a given context id.
- * @param $id a context id.
- * @return object The context object.
+ * @param mixed $id a context id or array of ids.
+ * @return mixed object or array of the context object.
  */
 function get_context_instance_by_id($id) {
 
index 9c7000eec6682adb862b0bd0a2476c30835e0a7e..fa75173ac90198ca8f64056aa4ade1796fe3dee8 100644 (file)
@@ -93,12 +93,12 @@ function groups_get_grouping($groupingid) {
 /**
  * Gets array of all groups in a specified course.
  * @param int $courseid The id of the course.
- * @param int $userid optional user id, returns only groups of the user.
+ * @param mixed $userid optional user id or array of ids, returns only groups of the user.
  * @param int $groupingid optional returns only groups in the specified grouping.
  * @return array | false Returns an array of the group objects or false if no records
- * or an error occurred.
+ * or an error occurred. (userid field returned if array in $userid)
  */
-function groups_get_all_groups($courseid, $userid=0, $groupingid=0) {
+function groups_get_all_groups($courseid, $userid=0, $groupingid=0, $fields='g.*') {
     global $CFG;
 
     // groupings are ignored when not enabled
@@ -106,12 +106,18 @@ function groups_get_all_groups($courseid, $userid=0, $groupingid=0) {
         $groupingid = 0;
     }
 
-    if (!empty($userid)) {
-        $userfrom  = ", {$CFG->prefix}groups_members gm";
-        $userwhere = "AND g.id = gm.groupid AND gm.userid = '$userid'";
-    } else {
+    if (empty($userid)) {
         $userfrom  = "";
         $userwhere = "";
+
+    } else if (is_array($userid)) {
+        $userids = implode(',', $userid);
+        $userfrom  = ", {$CFG->prefix}groups_members gm";
+        $userwhere = "AND g.id = gm.groupid AND gm.userid IN ($userids)";
+
+    } else {
+        $userfrom  = ", {$CFG->prefix}groups_members gm";
+        $userwhere = "AND g.id = gm.groupid AND gm.userid = '$userid'";
     }
 
     if (!empty($groupingid)) {
@@ -122,7 +128,7 @@ function groups_get_all_groups($courseid, $userid=0, $groupingid=0) {
         $groupingwhere = "";
     }
 
-    return get_records_sql("SELECT g.*
+    return get_records_sql("SELECT $fields
                               FROM {$CFG->prefix}groups g $userfrom $groupingfrom
                              WHERE g.courseid = $courseid $userwhere $groupingwhere
                           ORDER BY name ASC");
index bfd4e20574f841232d2b800ced57f56c9f2f9a90..e1cbaca52435241ba95d053311d0db7e47aa7939 100644 (file)
     print_header(get_string('discussion', 'message').': '.fullname($user), '', '', 'edit-message');
     echo '<div class="message-discussion-noframes">';
     echo '<div id="userinfo">';
-    echo print_user_picture($user->id, SITEID, $user->picture, 48, true, true, 'userwindow');
+    echo print_user_picture($user, SITEID, $user->picture, 48, true, true, 'userwindow');
     echo '<div class="name"><h1>'.$userfullname.'</h1></div>';
     echo '<div class="commands"><ul>';
     if ($contact = get_record('message_contacts', 'userid', $USER->id, 'contactid', $user->id)) {
index 5d5565886f96906fb13a23f3436e647005347913..9546f618102db3a40abc6e4292e4a75a6ce74286 100644 (file)
@@ -52,7 +52,7 @@
     print_header('','','','','',false,'','',false,'');
     echo '<table width="100%" cellpadding="0" cellspacing="0"><tr>';
     echo '<td width="100">';
-    echo print_user_picture($user->id, SITEID, $user->picture, true, true, true, 'userwindow').'</td>';
+    echo print_user_picture($user, SITEID, $user->picture, true, true, true, 'userwindow').'</td>';
     echo '<td valign="middle" align="center">';
 
     echo '<div class="name">'.fullname($user).'</div>';
index 94ae5d916e2158033158c32b32dab502e317097c..e8531d882b8050d1891b14b24d8661d0fbec6a47 100644 (file)
@@ -386,7 +386,7 @@ function chat_get_users($chatid, $groupid=0, $groupingid=0) {
         $groupingjoin = '';
     }
 
-    return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, c.lastmessageping, c.firstping
+    return get_records_sql("SELECT DISTINCT u.id, u.firstname, u.lastname, u.picture, c.lastmessageping, c.firstping, u.imagealt
                               FROM {$CFG->prefix}chat_users c
                                 INNER JOIN {$CFG->prefix}user u ON u.id = c.userid
                                 $groupingjoin
index 9aaef0ab81a036432eca2d91b3ce3e7b993ae8fd..44cfcd25a0e8957ed4ce80f1fc79b9f722c1a26e 100644 (file)
                 arsort($sessionusers);
                 foreach ($sessionusers as $sessionuser => $usermessagecount) {
                     if ($user = get_record('user', 'id', $sessionuser)) {
-                        print_user_picture($user->id, $course->id, $user->picture);
+                        print_user_picture($user, $course->id, $user->picture);
                         echo '&nbsp;'.fullname($user, true); // XXX TODO  use capability instead of true
                         echo "&nbsp;($usermessagecount)<br />";
                     }
index 6fa8bd67d34b685c4833061bb282bc285e9fb6eb..9637f60366210cd4d8158af6d4b3aa5bb5654b0c 100644 (file)
                         $lastping = $timenow - $chatuser->lastmessageping;
                         echo '<tr><td class="chatuserimage">';
                         echo "<a href=\"$CFG->wwwroot/user/view.php?id=$chatuser->id&amp;course=$chat->course\">";
-                        print_user_picture($chatuser->id, 0, $chatuser->picture, false, false, false);
+                        print_user_picture($chatuser, 0, $chatuser->picture, false, false, false);
                         echo '</a></td><td class="chatuserdetails">';
                         echo '<p>';
                         echo fullname($chatuser).'<br />';
index 2e6dd4fa71f1c25755aa38fd51110ec5e06462d8..f35970584eb65dd65b6decf64a0181a1166e33e1 100755 (executable)
@@ -1376,7 +1376,7 @@ function data_print_comment($data, $comment, $page=0) {
     echo '<table cellspacing="0" align="center" width="50%" class="datacomment forumpost">';
 
     echo '<tr class="header"><td class="picture left">';
-    print_user_picture($comment->userid, $data->course, $user->picture);
+    print_user_picture($user, $data->course, $user->picture);
     echo '</td>';
 
     echo '<td class="topic starter" align="left"><div class="author">';
index e9bfb854b27fed71e893e7ea8a27a06eb8cd0ffc..ccc96374d80f388c561961b67f510e0f5cb7ae7b 100644 (file)
@@ -3,39 +3,38 @@
 //  Displays a post, and all the posts below it.
 //  If no post is given, displays all posts in a discussion
 
-    require_once("../../config.php");
-    
+    require_once('../../config.php');
+    require_once('lib.php');
+
     $d      = required_param('d', PARAM_INT);                // Discussion ID
     $parent = optional_param('parent', 0, PARAM_INT);        // If set, then display this post and all children.
     $mode   = optional_param('mode', 0, PARAM_INT);          // If set, changes the layout of the thread
     $move   = optional_param('move', 0, PARAM_INT);          // If set, moves this discussion to another forum
-    $fromforum = optional_param('fromforum', 0, PARAM_INT);  // Needs to be set when we want to move a discussion.
     $mark   = optional_param('mark', '', PARAM_ALPHA);       // Used for tracking read posts if user initiated.
     $postid = optional_param('postid', 0, PARAM_INT);        // Used for tracking read posts if user initiated.
 
-    if (!$discussion = get_record("forum_discussions", "id", $d)) {
+    if (!$discussion = get_record('forum_discussions', 'id', $d)) {
         error("Discussion ID was incorrect or no longer exists");
     }
 
-    if (!$course = get_record("course", "id", $discussion->course)) {
+    if (!$course = get_record('course', 'id', $discussion->course)) {
         error("Course ID is incorrect - discussion is faulty");
     }
 
-    if (!$forum = get_record("forum", "id", $discussion->forum)) {
+    if (!$forum = get_record('forum', 'id', $discussion->forum)) {
         notify("Bad forum ID stored in this discussion");
     }
 
     if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
         error('Course Module ID was incorrect');
     }
-    // move this down fix for MDL-6926
-    require_once("lib.php");
+
     require_course_login($course, true, $cm);
 
     $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
-    $canviewdiscussion = has_capability('mod/forum:viewdiscussion', $modcontext);
-    
-    if ($forum->type == "news") {
+    require_capability('mod/forum:viewdiscussion', $modcontext, NULL, true, 'noviewdiscussionspermission', 'forum');
+
+    if ($forum->type == 'news') {
         if (!($USER->id == $discussion->userid || (($discussion->timestart == 0
             || $discussion->timestart <= time())
             && ($discussion->timeend == 0 || $discussion->timeend > time())))) {
         }
     }
 
+/// move discussion if requested
+    if ($move > 0 and confirm_sesskey()) {
+        $return = $CFG->wwwroot.'/mod/forum/discussion.php?d='.$discussion->id;
+
+        require_capability('mod/forum:movediscussions', $modcontext);
 
-    if (!empty($move)) {
-        
-        if (!$sourceforum = get_record('forum', 'id', $fromforum)) {
-            error('Cannot find which forum this discussion is being moved from');
+        if ($forum->type == 'single') {
+            error('Cannot move discussion from a simple single discussion forum', $return);
         }
-        if ($sourceforum->type == 'single') {
-            error('Cannot move discussion from a simple single discussion forum');
+
+        if ($forumto = get_record('forum', 'id', $move)) {
+            error('You can\'t move to that forum - it doesn\'t exist!', $return);
         }
-        
-        require_capability('mod/forum:movediscussions', $modcontext);
 
-        if ($forum = get_record("forum", "id", $move)) {
-            if (!forum_move_attachments($discussion, $move)) {
-                notify("Errors occurred while moving attachment directories - check your file permissions");
-            }
-            set_field("forum_discussions", "forum", $forum->id, "id", $discussion->id);
-            $discussion->forum = $forum->id;
-            if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
-                add_to_log($course->id, "forum", "move discussion", "discuss.php?d=$discussion->id", "$discussion->id",
-                           $cm->id);
-            } else {
-                add_to_log($course->id, "forum", "move discussion", "discuss.php?d=$discussion->id", "$discussion->id");
-            }
-            $discussionmoved = true;
-            
-            require_once('rsslib.php');
-            require_once($CFG->libdir.'/rsslib.php');
-
-            // Delete the RSS files for the 2 forums because we want to force
-            // the regeneration of the feeds since the discussions have been
-            // moved.
-            if (!forum_rss_delete_file($forum) || !forum_rss_delete_file($sourceforum)) {
-                notify('Could not purge the cached RSS feeds for the source and/or'.
-                       'destination forum(s) - check your file permissionsforums');
-            }
-        } else {
-            error('You can\'t move to that forum - it doesn\'t exist!');
+        if (!$cmto = get_coursemodule_from_instance('forum', $forumto->id, $course->id)) {
+            error('Target forum not found in this course.', $return);
+        }
+
+        if (!coursemodule_visible_for_user($cmto)) {
+            error('Forum not visible', $return);
         }
+
+        if (!forum_move_attachments($discussion, $forumto)) {
+            notify("Errors occurred while moving attachment directories - check your file permissions");
+        }
+        set_field('forum_discussions', 'forum', $forumto->id, 'id', $discussion->id);
+        add_to_log($course->id, 'forum', 'move discussion', "discuss.php?d=$discussion->id", $discussion->id, $cmto->id);
+
+        require_once($CFG->libdir.'/rsslib.php');
+        require_once('rsslib.php');
+
+        // Delete the RSS files for the 2 forums because we want to force
+        // the regeneration of the feeds since the discussions have been
+        // moved.
+        if (!forum_rss_delete_file($forum) || !forum_rss_delete_file($sourceforum)) {
+            error('Could not purge the cached RSS feeds for the source and/or'.
+                   'destination forum(s) - check your file permissionsforums', $return);
+        }
+
+        redirect($return.'&amp;moved=-1&amp;sesskey='.sesskey());
     }
 
     $logparameters = "d=$discussion->id";
         $logparameters .= "&amp;parent=$parent";
     }
 
-    if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
-        add_to_log($course->id, "forum", "view discussion", "discuss.php?$logparameters", "$discussion->id", $cm->id);
-    } else {
-        add_to_log($course->id, "forum", "view discussion", "discuss.php?$logparameters", "$discussion->id");
-    }
+    add_to_log($course->id, 'forum', 'view discussion', "discuss.php?$logparameters", $discussion->id, $cm->id);
 
     unset($SESSION->fromdiscussion);
 
     $displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
 
     if ($parent) {
-        if (abs($displaymode) == 1) {  // If flat AND parent, then force nested display this time
-            $displaymode = 3;
+        // If flat AND parent, then force nested display this time
+        if ($displaymode == FORUM_MODE_FLATOLDEST or $displaymode == FORUM_MODE_FLATNEWEST) {
+            $displaymode = FORUM_MODE_NESTED;
         }
     } else {
         $parent = $discussion->firstpost;
     }
-    
-    if (!forum_user_can_view_post($parent, $course, $cm, $forum, $discussion)) {
-        error('You do not have permissions to view this post', "$CFG->wwwroot/mod/forum/view.php?f=$forum->id");
-    }
 
     if (! $post = forum_get_post_full($parent)) {
         error("Discussion no longer exists", "$CFG->wwwroot/mod/forum/view.php?f=$forum->id");
     }
 
-    $post->modcontext = $modcontext;
 
-    if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum) && 
-        $CFG->forum_usermarksread) {
-        if ($mark == 'read') {
-            forum_tp_add_read_record($USER->id, $postid, $discussion->id, $forum->id);
-        } else if ($mark == 'unread') {
-            forum_tp_delete_read_records($USER->id, $postid);
-        }
+    if (!forum_user_can_view_post($post, $course, $cm, $forum, $discussion)) {
+        error('You do not have permissions to view this post', "$CFG->wwwroot/mod/forum/view.php?id=$forum->id");
     }
 
+    if ($mark == 'read' or $mark == 'unread') {
+        if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum) &&
+            $CFG->forum_usermarksread) {
+            if ($mark == 'read') {
+                forum_tp_add_read_record($USER->id, $postid, $discussion->id, $forum->id);
+            } else {
+                // unread
+                forum_tp_delete_read_records($USER->id, $postid);
+            }
+        }
+    }
 
     $searchform = forum_search_form($course);
 
     $navlinks = array();
-    $navlinks[] = array('name' => format_string($discussion->name,true), 'link' => "discuss.php?d=$discussion->id", 'type' => 'title');
+    $navlinks[] = array('name' => format_string($discussion->name), 'link' => "discuss.php?d=$discussion->id", 'type' => 'title');
     if ($parent != $discussion->firstpost) {
-        $navlinks[] = array('name' => format_string($post->subject,true), 'type' => 'title');
+        $navlinks[] = array('name' => format_string($post->subject), 'type' => 'title');
     }
-    
-    $navigation = build_navigation($navlinks, $cm); 
+
+    $navigation = build_navigation($navlinks, $cm);
     print_header("$course->shortname: ".format_string($discussion->name), $course->fullname,
                      $navigation, "", "", true, $searchform, navmenu($course, $cm));
-    
+
 
 /// Check to see if groups are being used in this forum
 /// If so, make sure the current person is allowed to see this discussion
     } else {
         $capname = 'mod/forum:replypost';
     }
-    
+
     $canreply = false;
     if (has_capability($capname, $modcontext)) {
         $groupmode = groups_get_activity_groupmode($cm);
                         print_footer($course);
                         die;
                     }
-    
+
                 } else if ($groupmode == VISIBLEGROUPS) {
                     if ($discussion->groupid == -1 or groups_is_member($discussion->groupid)) {
                         $canreply = true;
                     }
                 }
-            }   
+            }
         } else {
             $canreply = true;
         }
     } else { // allow guests to see the link
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
-        if (has_capability('moodle/legacy:guest', $coursecontext, NULL, false)) {  // User is a guest here!
+        if (has_capability('moodle/legacy:guest', $coursecontext, NULL, false)) {
+            // User is a guest here ! guests are prompted to login later if try to reply
             $canreply = true;
         }
     }
 
     if ($forum->type != 'single'
                 && has_capability('mod/forum:movediscussions', $modcontext)) {
-        
+
         // Popup menu to move discussions to other forums. The discussion in a
         // single discussion forum can't be moved.
-        if ($forums = get_all_instances_in_course("forum", $course)) {
+        $modinfo = get_fast_modinfo($course);
+        if (isset($modinfo->instances['forum'])) {
             if ($course->format == 'weeks') {
                 $strsection = get_string("week");
             } else {
                 $strsection = get_string("topic");
             }
             $section = -1;
-            foreach ($forums as $courseforum) {
-                if (!empty($courseforum->section) and $section != $courseforum->section) {
-                    $forummenu[] = "-------------- $strsection $courseforum->section --------------";
+            $forummenu = array();
+            foreach ($modinfo->instances['forum'] as $forumcm) {
+                if (!$forumcm->uservisible) {
+                    continue;
                 }
-                $section = $courseforum->section;
-                if ($courseforum->id != $forum->id) {
-                    $url = "discuss.php?d=$discussion->id&amp;fromforum=$discussion->forum&amp;move=$courseforum->id";
-                    $forummenu[$url] = format_string($courseforum->name,true);
+
+                if (!empty($forumcm->sectionnum) and $section != $forumcm->sectionnum) {
+                    $forummenu[] = "-------------- $strsection $forumcm->sectionnum --------------";
+                }
+                $section = $forumcm->sectionnum;
+                if ($forumcm->instance != $forum->id) {
+                    $url = "discuss.php?d=$discussion->id&amp;move=$forumcm->instance&amp;sesskey=".sesskey();
+                    $forummenu[$url] = format_string($forumcm->name);
                 }
             }
             if (!empty($forummenu)) {
     echo "</td></tr></table>";
 
     if (!empty($forum->blockafter) && !empty($forum->blockperiod)) {
-        $a->blockafter = $forum->blockafter;
+        $a = new object();
+        $a->blockafter  = $forum->blockafter;
         $a->blockperiod = get_string('secondstotime'.$forum->blockperiod);
         notify(get_string('thisforumisthrottled','forum',$a));
     }
         notify(get_string('qandanotify','forum'));
     }
 
-    if (isset($discussionmoved)) {
-        notify(get_string("discussionmoved", "forum", format_string($forum->name,true)));
+    if ($move == -1 and confirm_sesskey()) {
+        notify(get_string('discussionmoved', 'forum', format_string($forum->name,true)));
     }
 
+    $canrate = has_capability('mod/forum:rate', $modcontext);
+    forum_print_discussion($course, $cm, $forum, $discussion, $post, $displaymode, $canreply, $canrate);
 
-/// Print the actual discussion
-    if (!$canviewdiscussion) {
-        notice(get_string('noviewdiscussionspermission', 'forum'));
-    } else {
-        $canrate = has_capability('mod/forum:rate', $modcontext);
-        forum_print_discussion($course, $forum, $discussion, $post, $displaymode, $canreply, $canrate);
-    }
-    
     print_footer($course);
-    
+
 
 ?>
index 22bd0beee902211fe60acd74f4fe329144f7cc7d..9685df6c072268683c3b16ee88b14415bef6d1bb 100644 (file)
@@ -26,33 +26,6 @@ define ('FORUM_AGGREGATE_MAX', 3);
 define ('FORUM_AGGREGATE_MIN', 4);
 define ('FORUM_AGGREGATE_SUM', 5);
 
-// this file may be included from some functions, we must define these as global explicitly
-global $FORUM_LAYOUT_MODES, $FORUM_TYPES, $FORUM_TYPES_ALL, $FORUM_OPEN_MODES;
-
-$FORUM_LAYOUT_MODES = array ( FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
-                              FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
-                              FORUM_MODE_THREADED   => get_string('modethreaded', 'forum'),
-                              FORUM_MODE_NESTED     => get_string('modenested', 'forum') );
-
-// These are course content forums that can be added to the course manually
-$FORUM_TYPES   = array ('general'    => get_string('generalforum', 'forum'),
-                        'eachuser'   => get_string('eachuserforum', 'forum'),
-                        'single'     => get_string('singleforum', 'forum'),
-                        'qanda'      => get_string('qandaforum', 'forum'));
-
-$FORUM_TYPES_ALL = array ('news'       => get_string('namenews','forum'),
-                          'social'     => get_string('namesocial','forum'),
-                          'general'    => get_string('generalforum', 'forum'),
-                          'eachuser'   => get_string('eachuserforum', 'forum'),
-                          'single'     => get_string('singleforum', 'forum'),
-                          'qanda'      => get_string('qandaforum', 'forum'));
-
-
-$FORUM_OPEN_MODES   = array ('2' => get_string('openmode2', 'forum'),
-                             '1' => get_string('openmode1', 'forum'),
-                             '0' => get_string('openmode0', 'forum') );
-
-
 /// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
 
 /**
@@ -378,7 +351,7 @@ function forum_cron() {
                 }
                 if (!isset($userto->canpost[$forum->id])) {
                     $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
-                    $userto->canpost[$forum->id] = forum_user_can_post($forum, $userto, null, $modcontext);
+                    $userto->canpost[$forum->id] = forum_user_can_post($forum, $userto, $cm, $modcontext);
                 }
                 if (!isset($userfrom->groups[$forum->id])) {
                     if (!isset($userfrom->groups)) {
@@ -640,7 +613,7 @@ function forum_cron() {
 
                     $strforums = get_string('forums', 'forum');
                     $canunsubscribe = ! forum_is_forcesubscribed($forum);
-                    $canreply = forum_user_can_post($forum, $userto);
+                    $canreply = forum_user_can_post($forum, $userto, $cm);
 
                     // Fill caches
                     if (!isset($userto->viewfullnames[$forum->id])) {
@@ -649,7 +622,7 @@ function forum_cron() {
                     }
                     if (!isset($userto->canpost[$forum->id])) {
                         $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
-                        $userto->canpost[$forum->id] = forum_user_can_post($forum, $userto, null, $modcontext);
+                        $userto->canpost[$forum->id] = forum_user_can_post($forum, $userto, $cm, $modcontext);
                     }
 
                     $posttext .= "\n \n";
@@ -952,10 +925,15 @@ function forum_user_complete($course, $user, $mod, $forum) {
     global $CFG;
 
     if ($posts = forum_get_user_posts($forum->id, $user->id)) {
-        foreach ($posts as $post) {
 
-            $post->forum = $forum->id;
-            forum_print_post($post, $course->id, $ownpost=false, $reply=false, $link=false, $rate=false);
+        if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
+            error('Course Module ID was incorrect');
+        }
+        $discussions = get_records('discussions', 'forum', $forum->id); // TODO: improve
+
+        foreach ($posts as $post) {
+            $discussion = $discussions[$forum->discussion];
+            forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false, false);
         }
 
     } else {
@@ -1445,6 +1423,36 @@ function forum_get_discussion_posts($discussion, $sort, $forumid) {
                                AND p.parent > 0 $sort");
 }
 
+/**
+ * Gets all posts in discussion including top parent.
+ */
+function forum_get_all_discussion_posts($discussionid, $sort) {
+    global $CFG;
+
+    if (!$posts = get_records_sql("SELECT p.*, u.firstname, u.lastname, u.email, u.picture, u.imagealt
+                              FROM {$CFG->prefix}forum_posts p
+                                   LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
+                             WHERE p.discussion = $discussionid
+                          ORDER BY $sort")) {
+        return array();
+    }
+
+    foreach ($posts as $pid=>$p) {
+        if (!$p->parent) {
+            continue;
+        }
+        if (!isset($posts[$p->parent])) {
+            continue; // parent does not exist??
+        }
+        if (!isset($posts[$p->parent]->children)) {
+            $posts[$p->parent]->children = array();
+        }
+        $posts[$p->parent]->children[$pid] =& $posts[$pid];
+    }
+
+    return $posts;
+}
+
 /**
  * Gets posts with all info ready for forum_print_post
  * We pass forumid in because we always know it so no need to make a
@@ -1480,7 +1488,7 @@ function forum_get_readable_forums($userid, $courseid=0) {
     if ($courseid) {
         $courses = get_records('course', 'id', $courseid);
     } else {
-        // If no course is specified, then the user can see SITE + his courses. 
+        // If no course is specified, then the user can see SITE + his courses.
         // And admins can see all courses, so pass the $doanything flag enabled
         $courses1 = get_records('course', 'id', SITEID);
         $courses2 = get_my_courses($userid, null, null, true);
@@ -1726,6 +1734,15 @@ function forum_search_posts($searchterms, $courseid=0, $limitfrom=0, $limitnum=5
     return get_records_sql($searchsql, $limitfrom, $limitnum);
 }
 
+function forum_get_all_discussion_ratings($discussion) {
+    global $CFG;
+    return get_records_sql("SELECT r.id, r.userid, p.id AS postid, r.rating
+                              FROM {$CFG->prefix}forum_ratings r,
+                                   {$CFG->prefix}forum_posts p
+                             WHERE r.post = p.id AND p.discussion = $discussion->id
+                             ORDER BY p.id ASC");
+}
+
 /**
  * Returns a list of ratings for a particular post - sorted.
  */
@@ -2260,24 +2277,24 @@ function forum_make_mail_post($course, $forum, $discussion, $post, $userfrom, $u
 
 /**
  * Print a forum post
- * 
+ *
  * @param object $post The post to print.
  * @param integer $courseid The course this post belongs to.
  * @param boolean $ownpost Whether this post belongs to the current user.
- * @param boolean $reply Whether to print a 'reply' link at the bottom of the message. 
+ * @param boolean $reply Whether to print a 'reply' link at the bottom of the message.
  * @param boolean $link Just print a shortened version of the post as a link to the full post.
- * @param object $ratings -- I don't really know -- 
+ * @param object $ratings -- I don't really know --
  * @param string $footer Extra stuff to print after the message.
  * @param string $highlight Space-separated list of terms to highlight.
  * @param int $post_read true, false or -99. If we already know whether this user
  *          has read this post, pass that in, otherwise, pass in -99, and this
  *          function will work it out.
  * @param boolean $dummyifcantsee When forum_user_can_see_post says that
- *          the current user can't see this post, if this argument is true 
+ *          the current user can't see this post, if this argument is true
  *          (the default) then print a dummy 'you can't see this post' post.
  *          If false, don't output anything at all.
  */
-function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link=false,
+function forum_print_post($post, $discussion, $forum, &$cm, $course, $ownpost=false, $reply=false, $link=false,
                           $ratings=NULL, $footer="", $highlight="", $post_read=-99, $dummyifcantsee=true) {
 
     global $USER, $CFG;
@@ -2286,20 +2303,31 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     static $strpruneheading, $displaymode;
     static $strmarkread, $strmarkunread, $istracked;
 
+    $post->course = $course->id;
+    $post->forum  = $forum->id;
 
-    if (empty($post->modcontext)) {   // Have to generate it, which is expensive!  Should always be set.
-        if (empty($post->forum)) {
-            $discussion = get_record('forum_discussions', 'id', $post->discussion);
-            $post->forum = $discussion->forum;
-        }
+    // caching
+    if (!isset($cm->cache)) {
+        $cm->cache = new object();
+    }
 
-        if (!$cm = get_coursemodule_from_instance('forum', $post->forum)) {
-            error('Course Module ID was incorrect');
-        }
-        $post->modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
+    if (!isset($cm->cache->caps)) {
+        $cm->cache->caps = array();
+        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
+        $cm->cache->caps['mod/forum:viewdiscussion']   = has_capability('mod/forum:viewdiscussion', $modcontext);
+        $cm->cache->caps['moodle/site:viewfullnames']  = has_capability('moodle/site:viewfullnames', $modcontext);
+        $cm->cache->caps['mod/forum:editanypost']      = has_capability('mod/forum:editanypost', $modcontext);
+        $cm->cache->caps['mod/forum:splitdiscussions'] = has_capability('mod/forum:splitdiscussions', $modcontext);
+        $cm->cache->caps['mod/forum:deleteownpost']    = has_capability('mod/forum:deleteownpost', $modcontext);
+        $cm->cache->caps['mod/forum:deleteanypost']    = has_capability('mod/forum:deleteanypost', $modcontext);
+        $cm->cache->caps['mod/forum:viewanyrating']    = has_capability('mod/forum:viewanyrating', $modcontext);
     }
 
-    if (!forum_user_can_see_post($post->forum,$post->discussion,$post)) {
+    if (!isset($cm->uservisible)) {
+        $cm->uservisible = coursemodule_visible_for_user($cm);
+    }
+
+    if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
         if (!$dummyifcantsee) {
             return;
         }
@@ -2330,19 +2358,19 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     }
 
     if (empty($stredit)) {
-        $stredit = get_string('edit', 'forum');
-        $strdelete = get_string('delete', 'forum');
-        $strreply = get_string('reply', 'forum');
-        $strparent = get_string('parent', 'forum');
+        $stredit         = get_string('edit', 'forum');
+        $strdelete       = get_string('delete', 'forum');
+        $strreply        = get_string('reply', 'forum');
+        $strparent       = get_string('parent', 'forum');
         $strpruneheading = get_string('pruneheading', 'forum');
-        $strprune = get_string('prune', 'forum');
-        $displaymode = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
-        $strmarkread = get_string('markread', 'forum');
-        $strmarkunread = get_string('markunread', 'forum');
+        $strprune        = get_string('prune', 'forum');
+        $displaymode     = get_user_preferences('forum_displaymode', $CFG->forum_displaymode);
+        $strmarkread     = get_string('markread', 'forum');
+        $strmarkunread   = get_string('markunread', 'forum');
 
         if (!empty($post->forum)) {
-            $istracked = (forum_tp_can_track_forums($post->forum) &&
-                          forum_tp_is_tracked($post->forum));
+            $istracked = (forum_tp_can_track_forums($forum) &&
+                          forum_tp_is_tracked($forum));
         } else {
             $istracked = false;
         }
@@ -2368,15 +2396,15 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     echo '<table cellspacing="0" class="forumpost'.$read_style.'">';
 
     // Picture
-    $postuser = new object;
-    $postuser->id = $post->userid;
+    $postuser = new object();
+    $postuser->id        = $post->userid;
     $postuser->firstname = $post->firstname;
-    $postuser->lastname = $post->lastname;
-    $postuser->imagealt = $post->imagealt;
-    $postuser->picture = $post->picture;
+    $postuser->lastname  = $post->lastname;
+    $postuser->imagealt  = $post->imagealt;
+    $postuser->picture   = $post->picture;
 
     echo '<tr class="header"><td class="picture left">';
-    print_user_picture($postuser, $courseid);
+    print_user_picture($postuser, $course->id);
     echo '</td>';
 
     if ($post->parent) {
@@ -2392,17 +2420,28 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     }
 
     echo '<div class="author">';
-    $fullname = fullname($post, has_capability('moodle/site:viewfullnames', $post->modcontext));
+    $fullname = fullname($postuser, $cm->cache->caps['moodle/site:viewfullnames']);
     $by = new object();
     $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
-                $post->userid.'&amp;course='.$courseid.'">'.$fullname.'</a>';
+                $post->userid.'&amp;course='.$course->id.'">'.$fullname.'</a>';
     $by->date = userdate($post->modified);
     print_string('bynameondate', 'forum', $by);
     echo '</div></td></tr>';
 
     echo '<tr><td class="left side">';
-    if ($group = groups_get_all_groups($courseid, $post->userid)) {
-        print_group_picture($group, $courseid, false, false, true);
+    if (isset($cm->cache->usersgroups)) {
+        $groups = array();
+        if (isset($cm->cache->usersgroups[$post->userid])) {
+            foreach ($cm->cache->usersgroups[$post->userid] as $gid) {
+                $groups[$gid] = $cm->cache->groups[$gid];
+            }
+        }
+    } else {
+        $groups = groups_get_all_groups($course->id, $post->userid, $cm->groupingid);
+    }
+
+    if ($groups) {
+        print_group_picture($groups, $course->id, false, false, true);
     } else {
         echo '&nbsp;';
     }
@@ -2412,8 +2451,6 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     echo '</td><td class="content">'."\n";
 
     if ($post->attachment) {
-        $post->course = $courseid;
-        $post->forum = get_field('forum_discussions', 'forum', 'id', $post->discussion);
         echo '<div class="attachments">';
         $attachedimages = forum_print_attachments($post);
         echo '</div>';
@@ -2422,12 +2459,12 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     }
 
 
-    $options = new Object;
-    $options->para = false;
+    $options = new object();
+    $options->para      = false;
     $options->trusttext = true;
     if ($link and (strlen(strip_tags($post->message)) > $CFG->forum_longpost)) {
         // Print shortened version
-        echo format_text(forum_shorten_post($post->message), $post->format, $options, $courseid);
+        echo format_text(forum_shorten_post($post->message), $post->format, $options, $course->id);
         $numwords = count_words(strip_tags($post->message));
         echo '<p><a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
         echo get_string('readtherest', 'forum');
@@ -2435,9 +2472,9 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     } else {
         // Print whole message
         if ($highlight) {
-            echo highlight($highlight, format_text($post->message, $post->format, $options, $courseid));
+            echo highlight($highlight, format_text($post->message, $post->format, $options, $course->id));
         } else {
-            echo format_text($post->message, $post->format, $options, $courseid);
+            echo format_text($post->message, $post->format, $options, $course->id);
         }
         echo $attachedimages;
     }
@@ -2450,7 +2487,7 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
     if ($istracked) {
         // SPECIAL CASE: The front page can display a news item post to non-logged in users.
         // Don't display the mark read / unread controls in this case.
-        if ($CFG->forum_usermarksread && !empty($USER)) {
+        if ($CFG->forum_usermarksread and isloggedin()) {
             if ($post_read) {
                 $mcmd = '&amp;mark=unread&amp;postid='.$post->id;
                 $mtxt = $strmarkunread;
@@ -2478,22 +2515,12 @@ function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link
         }
     }
 
-    if (!isset($post->forumtype)) {
-        $post->forumtype = get_field('forum', 'type', 'id', $post->forum);
-    }
-
-if (!isset($post->aggtype)) {
-        $post->aggtype = get_field('forum', 'assessed', 'id', $post->forum);
-    }
-
     $age = time() - $post->created;
     // Hack for allow to edit news posts those are not displayed yet until they are displayed
-    if (!$post->parent
-        && $post->forumtype == 'news'
-        && get_field_sql("SELECT id FROM {$CFG->prefix}forum_discussions WHERE id = $post->discussion AND timestart > ".time())) {
+    if (!$post->parent and $forum->type == 'news' and $discussion->timestart > time()) {
         $age = 0;
     }
-    $editanypost = has_capability('mod/forum:editanypost', $post->modcontext);
+    $editanypost = $cm->cache->caps['mod/forum:editanypost'];
 
     if ($ownpost or $editanypost) {
         if (($age < $CFG->maxeditingtime) or $editanypost) {
@@ -2501,16 +2528,16 @@ if (!isset($post->aggtype)) {
         }
     }
 
-    if (has_capability('mod/forum:splitdiscussions', $post->modcontext)
-                && $post->parent && $post->forumtype != 'single') {
+    if ($cm->cache->caps['mod/forum:splitdiscussions']
+                && $post->parent && $forum->type != 'single') {
 
         $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?prune='.$post->id.
                       '" title="'.$strpruneheading.'">'.$strprune.'</a>';
     }
 
     if (($ownpost and $age < $CFG->maxeditingtime
-                and has_capability('mod/forum:deleteownpost', $post->modcontext))
-                or has_capability('mod/forum:deleteanypost', $post->modcontext)) {
+                and $cm->cache->caps['mod/forum:deleteownpost'])
+                or $cm->cache->caps['mod/forum:deleteanypost']) {
         $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?delete='.$post->id.'">'.$strdelete.'</a>';
     }
 
@@ -2526,7 +2553,7 @@ if (!isset($post->aggtype)) {
 // Ratings
 
     $ratingsmenuused = false;
-    if (!empty($ratings) and !empty($USER->id)) {
+    if (!empty($ratings) and isloggedin()) {
         echo '<div class="ratings">';
         $useratings = true;
         if ($ratings->assesstimestart and $ratings->assesstimefinish) {
@@ -2537,21 +2564,41 @@ if (!isset($post->aggtype)) {
         if ($useratings) {
             $mypost = ($USER->id == $post->userid);
 
-            $canviewallratings = has_capability('mod/forum:viewanyrating', $post->modcontext);
+            $canviewallratings = $cm->cache->caps['mod/forum:viewanyrating'];
+
+            if (isset($cm->cache->ratings)) {
+                if (isset($cm->cache->ratings[$post->id])) {
+                    $allratings = $cm->cache->ratings[$post->id];
+                } else {
+                    $allratings = array(); // no reatings present yet
+                }
+            } else {
+                $allratings = NULL; // not preloaded
+            }
+
+            if (isset($cm->cache->myratings)) {
+                if (isset($cm->cache->myratings[$post->id])) {
+                    $myrating = $cm->cache->myratings[$post->id];
+                } else {
+                    $myrating = FORUM_UNSET_POST_RATING; // no reatings present yet
+                }
+            } else {
+                $myrating = NULL; // not preloaded
+            }
 
             if ($canviewallratings and !$mypost) {
-                forum_print_ratings_mean($post->id, $ratings->scale, $post->aggtype, $canviewallratings);
+                forum_print_ratings($post->id, $ratings->scale, $forum->assessed, $canviewallratings, $allratings);
                 if (!empty($ratings->allow)) {
                     echo '&nbsp;';
-                    forum_print_rating_menu($post->id, $USER->id, $ratings->scale);
+                    forum_print_rating_menu($post->id, $USER->id, $ratings->scale, $myrating);
                     $ratingsmenuused = true;
                 }
 
             } else if ($mypost) {
-                forum_print_ratings_mean($post->id, $ratings->scale, $post->aggtype, true);
+                forum_print_ratings($post->id, $ratings->scale, $forum->assessed, true, $allratings);
 
             } else if (!empty($ratings->allow) ) {
-                forum_print_rating_menu($post->id, $USER->id, $ratings->scale);
+                forum_print_rating_menu($post->id, $USER->id, $ratings->scale, $myrating);
                 $ratingsmenuused = true;
             }
         }
@@ -2577,8 +2624,8 @@ if (!isset($post->aggtype)) {
     }
     echo '</td></tr></table>'."\n\n";
 
-    if ($istracked && !$CFG->forum_usermarksread && !empty($post->forum)) {
-        forum_tp_mark_post_read($USER->id, $post, $post->forum);
+    if ($istracked && !$CFG->forum_usermarksread) {
+        forum_tp_mark_post_read($USER->id, $post, $forum->id);
     }
 
     return $ratingsmenuused;
@@ -2772,29 +2819,29 @@ function forum_shorten_post($message) {
  * Forumid prevents the double lookup of the forumid in discussion to determine the aggregate type
  * Scale is an array of ratings
  */
-function forum_print_ratings_mean($postid, $scale, $aggregatetype, $link=true) {
+function forum_print_ratings($postid, $scale, $aggregatetype, $link=true, $ratings=null) {
 
     $strratings = '';
 
     switch ($aggregatetype) {
         case FORUM_AGGREGATE_AVG :
-            $agg        = forum_get_ratings_mean($postid, $scale);
+            $agg        = forum_get_ratings_mean($postid, $scale, $ratings);
             $strratings = get_string("aggregateavg", "forum");
             break;
         case FORUM_AGGREGATE_COUNT :
-            $agg        = forum_get_ratings_count($postid, $scale);
+            $agg        = forum_get_ratings_count($postid, $scale, $ratings);
             $strratings = get_string("aggregatecount", "forum");
             break;
         case FORUM_AGGREGATE_MAX :
-            $agg        = forum_get_ratings_max($postid, $scale);
+            $agg        = forum_get_ratings_max($postid, $scale, $ratings);
             $strratings = get_string("aggregatemax", "forum");
             break;
         case FORUM_AGGREGATE_MIN :
-            $agg        = forum_get_ratings_min($postid, $scale);
+            $agg        = forum_get_ratings_min($postid, $scale, $ratings);
             $strratings = get_string("aggregatemin", "forum");
             break;
         case FORUM_AGGREGATE_SUM :
-            $agg        = forum_get_ratings_sum($postid, $scale);
+            $agg        = forum_get_ratings_sum($postid, $scale, $ratings);
             $strratings = get_string("aggregatesum", "forum");
             break;
     }
@@ -2823,7 +2870,7 @@ function forum_print_ratings_mean($postid, $scale, $aggregatetype, $link=true) {
  */
 function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
 
-    if (!$ratings) {
+    if (is_null($ratings)) {
         $ratings = array();
         if ($rates = get_records("forum_ratings", "post", $postid)) {
             foreach ($rates as $rate) {
@@ -2838,7 +2885,8 @@ function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
         return "";
 
     } else if ($count == 1) {
-        return $scale[$ratings[0]];
+        $rating = reset($ratings);
+        return $scale[$rating];
 
     } else {
         $total = 0;
@@ -2862,7 +2910,7 @@ function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
  */
 function forum_get_ratings_count($postid, $scale, $ratings=NULL) {
 
-    if (!$ratings) {
+    if (is_null($ratings)) {
         $ratings = array();
         if ($rates = get_records("forum_ratings", "post", $postid)) {
             foreach ($rates as $rate) {
@@ -2887,7 +2935,7 @@ function forum_get_ratings_count($postid, $scale, $ratings=NULL) {
  */
 function forum_get_ratings_max($postid, $scale, $ratings=NULL) {
 
-    if (!$ratings) {
+    if (is_null($ratings)) {
         $ratings = array();
         if ($rates = get_records("forum_ratings", "post", $postid)) {
             foreach ($rates as $rate) {
@@ -2903,7 +2951,8 @@ function forum_get_ratings_max($postid, $scale, $ratings=NULL) {
         return "";
 
     } else if ($count == 1) { //this works for max
-        return $scale[$ratings[0]];
+        $rating = reset($ratings);
+        return $scale[$rating];
 
     } else {
 
@@ -2922,7 +2971,7 @@ function forum_get_ratings_max($postid, $scale, $ratings=NULL) {
  */
 function forum_get_ratings_min($postid, $scale,  $ratings=NULL) {
 
-    if (!$ratings) {
+    if (is_null($ratings)) {
         $ratings = array();
         if ($rates = get_records("forum_ratings", "post", $postid)) {
             foreach ($rates as $rate) {
@@ -2938,7 +2987,8 @@ function forum_get_ratings_min($postid, $scale,  $ratings=NULL) {
         return "";
 
     } else if ($count == 1) {
-        return $scale[$ratings[0]]; //this works for min
+        $rating = reset($ratings);
+        return $scale[$rating]; //this works for min
 
     } else {
 
@@ -2958,7 +3008,7 @@ function forum_get_ratings_min($postid, $scale,  $ratings=NULL) {
  */
 function forum_get_ratings_sum($postid, $scale, $ratings=NULL) {
 
-    if (!$ratings) {
+    if (is_null($ratings)) {
         $ratings = array();
         if ($rates = get_records("forum_ratings", "post", $postid)) {
             foreach ($rates as $rate) {
@@ -2974,7 +3024,8 @@ function forum_get_ratings_sum($postid, $scale, $ratings=NULL) {
         return "";
 
     } else if ($count == 1) { //this works for max.
-        return $scale[$ratings[0]];
+        $rating = reset($ratings);
+        return $scale[$rating];
 
     } else {
         $total = 0;
@@ -2999,7 +3050,7 @@ function forum_get_ratings_sum($postid, $scale, $ratings=NULL) {
  */
 function forum_get_ratings_summary($postid, $scale, $ratings=NULL) {
 
-    if (!$ratings) {
+    if (is_null($ratings)) {
         $ratings = array();
         if ($rates = get_records("forum_ratings", "post", $postid)) {
             foreach ($rates as $rate) {
@@ -3037,19 +3088,23 @@ function forum_get_ratings_summary($postid, $scale, $ratings=NULL) {
  * If the post has already been - set that value.
  * Scale is an array of ratings
  */
-function forum_print_rating_menu($postid, $userid, $scale) {
+function forum_print_rating_menu($postid, $userid, $scale, $myrating=NULL) {
 
     static $strrate;
 
-    if (!$rating = get_record("forum_ratings", "userid", $userid, "post", $postid)) {
-        $rating->rating = FORUM_UNSET_POST_RATING;
+    if (is_null($myrating)) {
+        if (!$rating = get_record("forum_ratings", "userid", $userid, "post", $postid)) {
+            $myrating = FORUM_UNSET_POST_RATING;
+        } else {
+            $myrating = $rating->rating;
+        }
     }
 
     if (empty($strrate)) {
         $strrate = get_string("rate", "forum");
     }
     $scale = array(FORUM_UNSET_POST_RATING => $strrate.'...') + $scale;
-    choose_from_menu($scale, $postid, $rating->rating, '');
+    choose_from_menu($scale, $postid, $myrating, '');
 }
 
 /**
@@ -3061,12 +3116,10 @@ function forum_print_rating_menu($postid, $userid, $scale) {
  * @param $forumtype - optional
  */
 function forum_print_mode_form($id, $mode, $forumtype='') {
-    global $FORUM_LAYOUT_MODES;
-
     if ($forumtype == 'single') {
-        popup_form("view.php?f=$id&amp;mode=", $FORUM_LAYOUT_MODES, "mode", $mode, "");
+        popup_form("view.php?f=$id&amp;mode=", forum_get_layout_modes(), "mode", $mode, "");
     } else {
-        popup_form("discuss.php?d=$id&amp;mode=", $FORUM_LAYOUT_MODES, "mode", $mode, "");
+        popup_form("discuss.php?d=$id&amp;mode=", forum_get_layout_modes(), "mode", $mode, "");
     }
 }
 
@@ -3132,7 +3185,20 @@ function forum_go_back_to($default) {
 function forum_file_area_name($post) {
     global $CFG;
 
-    return "$post->course/$CFG->moddata/forum/$post->forum/$post->id";
+    if (!isset($post->forum)) {
+        debugging('missing forum');
+        if (!$discussion = get_record('forum_discussions', 'id', $post->discussion)) {
+            return false;
+        }
+        if (!$forum = get_record('forum', 'id', $discussion->forum)) {
+            return false;
+        }
+        $forumid = $forum->id;
+    } else {
+       $forumid = $post->forum;
+    }
+
+    return "$post->course/$CFG->moddata/forum/$forumid/$post->id";
 }
 
 /**
@@ -3594,11 +3660,11 @@ function forum_post_subscription($post) {
  * Generate and return the subscribe or unsubscribe link for a forum.
  * @param object $forum the forum. Fields used are $forum->id and $forum->forcesubscribe.
  * @param object $context the context object for this forum.
- * @param array $messages text used for the link in its various states 
+ * @param array $messages text used for the link in its various states
  *      (subscribed, unsubscribed, forcesubscribed or cantsubscribe).
  *      Any strings not passed in are taken from the $defaultmessages array
  *      at the top of the function.
- * @param 
+ * @param
  */
 function forum_get_subscribe_link($forum, $context, $messages = array(), $cantaccessagroup = false, $fakelink=true, $backtoindex=false) {
     global $CFG, $USER;
@@ -3644,8 +3710,8 @@ function forum_get_subscribe_link($forum, $context, $messages = array(), $cantac
             $link .= '</noscript>';
         }
 
-        return $link;  
-    }    
+        return $link;
+    }
 }
 
 
@@ -3696,7 +3762,7 @@ function forum_get_tracking_link($forum, $messages=array(), $fakelink=true) {
         $link .= '</noscript>';
     }
 
-    return $link;  
+    return $link;
 }
 
 
@@ -3746,9 +3812,10 @@ function forum_user_has_posted($forumid, $did, $userid) {
  */
 function forum_user_can_post_discussion($forum, $currentgroup=-1, $groupmode=-1, $cm=NULL, $context=NULL) {
 // $forum is an object
-    global $USER, $SESSION;
+    global $USER, $SESSION, $COURSE;
 
     if (!$cm) {
+        debugging('missing cm');
         if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
             error('Course Module ID was incorrect');
         }
@@ -3762,9 +3829,6 @@ function forum_user_can_post_discussion($forum, $currentgroup=-1, $groupmode=-1,
     }
 
     if ($groupmode == -1) {
-        if (!$course = get_record('course', 'id', $cm->course)) {
-            error('Can not find course');
-        }
         $groupmode = groups_get_activity_groupmode($cm);
     }
 
@@ -3811,6 +3875,7 @@ function forum_user_can_post($forum, $user=NULL, $cm=NULL, $context=NULL) {
 
     if (!$context) {
         if (!$cm) {
+            debugging('missing cm');
             if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
                 error('Course Module ID was incorrect');
             }
@@ -3873,11 +3938,13 @@ function forum_user_can_see_discussion($forum, $discussion, $context, $user=NULL
 
     // retrieve objects (yuk)
     if (is_numeric($forum)) {
+        debugging('missing full forum');
         if (!$forum = get_record('forum','id',$forum)) {
             return false;
         }
     }
     if (is_numeric($discussion)) {
+        debugging('missing full discussion');
         if (!$discussion = get_record('forum_discussions','id',$discussion)) {
             return false;
         }
@@ -3904,17 +3971,20 @@ function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NUL
 
     // retrieve objects (yuk)
     if (is_numeric($forum)) {
+        debugging('missinf full forum');
         if (!$forum = get_record('forum','id',$forum)) {
             return false;
         }
     }
 
     if (is_numeric($discussion)) {
+        debugging('missinf full discussion');
         if (!$discussion = get_record('forum_discussions','id',$discussion)) {
             return false;
         }
     }
     if (is_numeric($post)) {
+        debugging('missinf full post');
         if (!$post = get_record('forum_posts','id',$post)) {
             return false;
         }
@@ -3924,6 +3994,7 @@ function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NUL
     }
 
     if (!$cm) {
+        debugging('missing cm');
         if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
             error('Course Module ID was incorrect');
         }
@@ -3933,16 +4004,27 @@ function forum_user_can_see_post($forum, $discussion, $post, $user=NULL, $cm=NUL
         $user = $USER;
     }
 
-    $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
-
-    if (!has_capability('mod/forum:viewdiscussion', $modcontext, $user->id)) {
-        return false;
+    if (isset($cm->cache->caps['mod/forum:viewdiscussion'])) {
+        if (!$cm->cache->caps['mod/forum:viewdiscussion']) {
+            return false;
+        }
+    } else {
+        $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
+        if (!has_capability('mod/forum:viewdiscussion', $modcontext, $user->id)) {
+            return false;
+        }
     }
-    
-    if (!groups_course_module_visible($cm, $user->id)) {
-        return false;
+
+    if (isset($cm->uservisible)) {
+        if (!$cm->uservisible) {
+            return false;
+        }
+    } else {
+        if (!coursemodule_visible_for_user($cm, $user->id)) {
+            return false;
+        }
     }
-    
+
     if ($forum->type == 'qanda') {
         $firstpost = forum_get_firstpost_from_discussion($discussion->id);
 
@@ -4063,8 +4145,8 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
 
     $replies = forum_count_discussion_replies($forum->id);
 
-    $canreply = forum_user_can_post($forum);
-    $canviewparticipants = has_capability('moodle/course:viewparticipants',$context); 
+    $canreply = forum_user_can_post($forum, null, $cm, $context);
+    $canviewparticipants = has_capability('moodle/course:viewparticipants',$context);
 
     $discussioncount = 0;
     $olddiscussionlink = false;
@@ -4170,7 +4252,7 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
 
                 $discussion->forum = $forum->id;
 
-                forum_print_post($discussion, $course->id, $ownpost, $reply=0, $link, $assessed=false);
+                forum_print_post($discussion, $discussion, $forum, $cm, $course, $ownpost, 0, $link, false);
             break;
         }
     }
@@ -4195,7 +4277,7 @@ function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $dis
 /**
  * 
  */
-function forum_print_discussion($course, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
+function forum_print_discussion($course, $cm, $forum, $discussion, $post, $mode, $canreply=NULL, $canrate=false) {
 
     global $USER, $CFG;
 
@@ -4205,15 +4287,46 @@ function forum_print_discussion($course, $forum, $discussion, $post, $mode, $can
         $ownpost = false;
     }
     if ($canreply === NULL) {
-        $reply = forum_user_can_post($forum);
+        $reply = forum_user_can_post($forum, null, $cm);
     } else {
         $reply = $canreply;
     }
 
+    // $cm holds general cache for forum functions
+    $cm->cache = new object();
+    $cm->cache->groups      = groups_get_all_groups($course->id, 0, $cm->groupingid);
+    $cm->cache->usersgroups = array();
+
+    $posters = array();
+
+    // preload all posts - TODO: improve...
+    if ($mode == FORUM_MODE_FLATNEWEST) {
+        $sort = "created DESC";
+    } else {
+        $sort = "created ASC";
+    }
+
+    $posts = forum_get_all_discussion_posts($discussion->id, $sort);
+
+    foreach ($posts as $pid=>$p) {
+        $posters[$p->userid] = $p->userid;
+    }
+
+    // preload all groups of ppl that posted in this discussion
+    if ($postersgroups = groups_get_all_groups($course->id, $posters, $cm->groupingid, 'g.id, gm.userid')) {
+        foreach($postersgroups as $pg) {
+            if (!isset($cm->cache->usersgroups[$pg->userid])) {
+                $cm->cache->usersgroups[$pg->userid] = array();
+            }
+            $cm->cache->usersgroups[$pg->userid][$pg->id] = $pg->id;
+        }
+        unset($postersgroups);
+    }
+
     $ratings = NULL;
     $ratingsmenuused = false;
     $ratingsformused = false;
-    if ($forum->assessed and !empty($USER->id)) {
+    if ($forum->assessed and isloggedin()) {
         if ($ratings->scale = make_grades_menu($forum->scale)) {
             $ratings->assesstimestart = $forum->assesstimestart;
             $ratings->assesstimefinish = $forum->assesstimefinish;
@@ -4225,9 +4338,26 @@ function forum_print_discussion($course, $forum, $discussion, $post, $mode, $can
                 echo '<input type="hidden" name="forumid" value="'.$forum->id.'" />';
                 $ratingsformused = true;
             }
+
+            // preload all ratings - one query only and minimal memory
+            $cm->cache->ratings = array();
+            $cm->cache->myratings = array();
+            if ($postratings = forum_get_all_discussion_ratings($discussion)) {
+                foreach ($postratings as $pr) {
+                    if (!isset($cm->cache->ratings[$pr->postid])) {
+                        $cm->cache->ratings[$pr->postid] = array();
+                    }
+                    $cm->cache->ratings[$pr->postid][$pr->id] = $pr->rating;
+                    if ($pr->userid == $USER->id) {
+                        $cm->cache->myratings[$pr->postid] = $pr->rating;
+                    }
+                }
+                unset($postratings);
+            }
         }
     }
 
+
     $post->forum = $forum->id;   // Add the forum id to the post object, later used by forum_print_post
     $post->forumtype = $forum->type;
 
@@ -4244,18 +4374,7 @@ function forum_print_discussion($course, $forum, $discussion, $post, $mode, $can
         $user_read_array = array();
     }
 
-    if (empty($post->modcontext)) {   // Have to generate it, which is expensive!  Should always be set.
-        if (empty($post->forum)) {
-            $discussion = get_record('forum_discussions', 'id', $post->discussion);
-            $post->forum = $discussion->forum;
-        }
-        if (!$cm = get_coursemodule_from_instance('forum', $post->forum)) {
-            error('Course Module ID was incorrect');
-        }
-        $post->modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
-    }
-
-    if (forum_print_post($post, $course->id, $ownpost, $reply, $link=false, $ratings,
+    if (forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, false, $ratings,
                          '', '', (!$forumtracked || isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
         $ratingsmenuused = true;
     }
@@ -4264,22 +4383,19 @@ function forum_print_discussion($course, $forum, $discussion, $post, $mode, $can
         case FORUM_MODE_FLATOLDEST :
         case FORUM_MODE_FLATNEWEST :
         default:
-            if (forum_print_posts_flat($post->discussion, $course->id, $mode, $ratings, $reply,
-                                       $user_read_array, $post->forum, $post->modcontext)) {
+            if (forum_print_posts_flat($course, $cm, $forum, $discussion, $post, $mode, $ratings, $reply, $user_read_array, $posts)) {
                 $ratingsmenuused = true;
             }
             break;
 
         case FORUM_MODE_THREADED :
-            if (forum_print_posts_threaded($post->id, $course->id, 0, $ratings, $reply,
-                                           $user_read_array, $post->forum, $post->modcontext)) {
+            if (forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, 0, $ratings, $reply, $user_read_array, $posts)) {
                 $ratingsmenuused = true;
             }
             break;
 
         case FORUM_MODE_NESTED :
-            if (forum_print_posts_nested($post->id, $course->id, $ratings, $reply,
-                                         $user_read_array, $post->forum, $post->modcontext)) {
+            if (forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $ratings, $reply, $user_read_array, $posts)) {
                 $ratingsmenuused = true;
             }
             break;
@@ -4306,29 +4422,28 @@ function forum_print_discussion($course, $forum, $discussion, $post, $mode, $can
 /**
  * 
  */
-function forum_print_posts_flat($discussion, $courseid, $direction, $ratings, $reply, &$user_read_array, $forumid=0, $modcontext=NULL) {
+function forum_print_posts_flat($course, &$cm, $forum, $discussion, $post, $mode, $ratings, $reply, $user_read_array, $posts) {
     global $USER, $CFG;
 
     $link  = false;
     $ratingsmenuused = false;
 
-    if ($direction < 0) {
+    if ($mode == FORUM_MODE_FLATNEWEST) {
         $sort = "ORDER BY created DESC";
     } else {
         $sort = "ORDER BY created ASC";
     }
 
-    if ($posts = forum_get_discussion_posts($discussion, $sort, $forumid)) {
-        foreach ($posts as $post) {
-
-            $post->subject = format_string($post->subject);
-            $post->modcontext = $modcontext;
+    foreach ($posts as $post) {
+        if (!$post->parent) {
+            continue;
+        }
+        $post->subject = format_string($post->subject);
+        $ownpost = ($USER->id == $post->userid);
 
-            $ownpost = ($USER->id == $post->userid);
-            if (forum_print_post($post, $courseid, $ownpost, $reply, $link, $ratings,
-                                 '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
-                $ratingsmenuused = true;
-            }
+        if (forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link, $ratings,
+                             '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
+            $ratingsmenuused = true;
         }
     }
 
@@ -4339,16 +4454,18 @@ function forum_print_posts_flat($discussion, $courseid, $direction, $ratings, $r
 /**
  * TODO document
  */
-function forum_print_posts_threaded($parent, $courseid, $depth, $ratings, $reply, &$user_read_array, $forumid=0, $modcontext=NULL) {
+function forum_print_posts_threaded($course, &$cm, $forum, $discussion, $parent, $depth, $ratings, $reply, $user_read_array, $posts) {
     global $USER, $CFG;
 
     $link  = false;
     $ratingsmenuused = false;
 
-    $istracking = forum_tp_can_track_forums($forumid) && forum_tp_is_tracked($forumid);
+    $istracking = forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum);
 
-    if ($posts = forum_get_child_posts($parent, $forumid)) {
+    if (!empty($posts[$parent->id]->children)) {
+        $posts = $posts[$parent->id]->children;
 
+        $modcontext       = get_context_instance(CONTEXT_MODULE, $cm->id);
         $canviewfullnames = has_capability('moodle/site:viewfullnames', $modcontext);
 
         foreach ($posts as $post) {
@@ -4357,14 +4474,13 @@ function forum_print_posts_threaded($parent, $courseid, $depth, $ratings, $reply
             if ($depth > 0) {
                 $ownpost = ($USER->id == $post->userid);
                 $post->subject = format_string($post->subject);
-                $post->modcontext = $modcontext;
 
-                if (forum_print_post($post, $courseid, $ownpost, $reply, $link, $ratings,
+                if (forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link, $ratings,
                                      '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
                     $ratingsmenuused = true;
                 }
             } else {
-                if (!forum_user_can_see_post($post->forum,$post->discussion,$post)) {
+                if (!forum_user_can_see_post($forum, $discussion, $post, NULL, $cm)) {
                     continue;
                 }
                 $by = new object();
@@ -4386,8 +4502,7 @@ function forum_print_posts_threaded($parent, $courseid, $depth, $ratings, $reply
                 echo "</span>";
             }
 
-            if (forum_print_posts_threaded($post->id, $courseid, $depth-1, $ratings, $reply,
-                                           $user_read_array, $forumid, $modcontext)) {
+            if (forum_print_posts_threaded($course, $cm, $forum, $discussion, $post, $depth-1, $ratings, $reply, $user_read_array, $posts)) {
                 $ratingsmenuused = true;
             }
             echo "</div>\n";
@@ -4399,13 +4514,15 @@ function forum_print_posts_threaded($parent, $courseid, $depth, $ratings, $reply
 /**
  * 
  */
-function forum_print_posts_nested($parent, $courseid, $ratings, $reply, &$user_read_array, $forumid=0, $modcontext=NULL) {
+function forum_print_posts_nested($course, &$cm, $forum, $discussion, $parent, $ratings, $reply, $user_read_array, $posts) {
     global $USER, $CFG;
 
     $link  = false;
     $ratingsmenuused = false;
 
-    if ($posts = forum_get_child_posts($parent, $forumid)) {
+    if (!empty($posts[$parent->id]->children)) {
+        $posts = $posts[$parent->id]->children;
+
         foreach ($posts as $post) {
 
             echo '<div class="indent">';
@@ -4417,13 +4534,11 @@ function forum_print_posts_nested($parent, $courseid, $ratings, $reply, &$user_r
 
             $post->subject = format_string($post->subject);
 
-            $post->modcontext = $modcontext;
-
-            if (forum_print_post($post, $courseid, $ownpost, $reply, $link, $ratings,
+            if (forum_print_post($post, $discussion, $forum, $cm, $course, $ownpost, $reply, $link, $ratings,
                                  '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
                 $ratingsmenuused = true;
             }
-            if (forum_print_posts_nested($post->id, $courseid, $ratings, $reply, $user_read_array, $forumid, $modcontext)) {
+            if (forum_print_posts_nested($course, $cm, $forum, $discussion, $post, $ratings, $reply, $user_read_array, $posts)) {
                 $ratingsmenuused = true;
             }
             echo "</div>\n";
@@ -4634,13 +4749,13 @@ function forum_role_assign($userid, $context, $roleid) {
     $cap1 = role_context_capabilities($roleid, $context, 'moodle/course:view');
     // we are checking the role because has_capability() will pull this capability out
     // from other roles this user might have and resolve them, which is no good
-    // the role needs course view to 
+    // the role needs course view to
     if (isset($cap['mod/forum:initialsubscriptions']) && $cap['mod/forum:initialsubscriptions'] == CAP_ALLOW &&
         isset($cap1['moodle/course:view']) && $cap1['moodle/course:view'] == CAP_ALLOW) {
         return forum_add_user_default_subscriptions($userid, $context);
     } else {
         // MDL-8981, do not subscribe to forum
-        return true;   
+        return true;
     }
 }
 
@@ -5054,7 +5169,7 @@ function forum_tp_mark_discussion_read($userid, $discussionid, $forumid) {
 /**
  * 
  */
-function forum_tp_is_post_read($userid, &$post) {
+function forum_tp_is_post_read($userid, $post) {
     return (forum_tp_is_post_old($post) ||
             (get_record('forum_read', 'userid', $userid, 'postid', $post->id) !== false));
 }
@@ -5062,7 +5177,7 @@ function forum_tp_is_post_read($userid, &$post) {
 /**
  * 
  */
-function forum_tp_is_post_old(&$post, $time=null) {
+function forum_tp_is_post_old($post, $time=null) {
     global $CFG;
 
     if (is_null($time)) $time = time();
@@ -5516,7 +5631,7 @@ function forum_reset_gradebook($courseid, $type='') {
  * @return array status array
  */
 function forum_reset_userdata($data) {
-    global $CFG, $FORUM_TYPES_ALL;
+    global $CFG;
     require_once($CFG->libdir.'/filelib.php');
 
     $componentstr = get_string('modulenameplural', 'forum');
@@ -5533,12 +5648,13 @@ function forum_reset_userdata($data) {
         $removeposts = true;
         $typesql     = "";
         $types       = array();
+        $forum_types_all = forum_get_forum_types_all();
         foreach ($data->reset_forum_types as $type) {
-            if (!array_key_exists($type, $FORUM_TYPES_ALL)) {
+            if (!array_key_exists($type, $forum_types_all)) {
                 continue;
             }
             $typesql .= " AND f.type='$type'";
-            $types[] = $FORUM_TYPES_ALL[$type];
+            $types[] = $forum_types_all[$type];
         }
         $typesstr = get_string('resetforums', 'forum').': '.implode(', ', $types);
 
@@ -5635,13 +5751,11 @@ function forum_reset_userdata($data) {
  * @param $mform form passed by reference
  */
 function forum_reset_course_form_definition(&$mform) {
-    global $FORUM_TYPES_ALL;
-
     $mform->addElement('header', 'forumheader', get_string('modulenameplural', 'forum'));
 
     $mform->addElement('checkbox', 'reset_forum_all', get_string('resetforumsall','forum'));
 
-    $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), $FORUM_TYPES_ALL, array('multiple' => 'multiple'));
+    $mform->addElement('select', 'reset_forum_types', get_string('resetforums', 'forum'), forum_get_forum_types_all(), array('multiple' => 'multiple'));
     $mform->setAdvanced('reset_forum_types');
     $mform->disabledIf('reset_forum_types', 'reset_forum_all', 'checked');
 
@@ -5889,20 +6003,56 @@ function forum_convert_to_roles($forum, $forummodid, $teacherroles=array(),
 }
 
 /**
- * Returns array of forum aggregate types 
+ * Returns array of forum aggregate types
+ */
+function forum_get_aggregate_types() {
+    return array (FORUM_AGGREGATE_NONE  => get_string('aggregatenone', 'forum'),
+                  FORUM_AGGREGATE_AVG   => get_string('aggregateavg', 'forum'),
+                  FORUM_AGGREGATE_COUNT => get_string('aggregatecount', 'forum'),
+                  FORUM_AGGREGATE_MAX   => get_string('aggregatemax', 'forum'),
+                  FORUM_AGGREGATE_MIN   => get_string('aggregatemin', 'forum'),
+                  FORUM_AGGREGATE_SUM   => get_string('aggregatesum', 'forum'));
+}
+
+/**
+ * Returns array of forum layout modes
  */
-function forum_get_aggregate_types() { 
+function forum_get_layout_modes() {
+    return array (FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
+                  FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
+                  FORUM_MODE_THREADED   => get_string('modethreaded', 'forum'),
+                  FORUM_MODE_NESTED     => get_string('modenested', 'forum'));
+}
 
-    $forum_aggregate_types   = array (
-        FORUM_AGGREGATE_NONE => get_string('aggregatenone', 'forum'),
-        FORUM_AGGREGATE_AVG    => get_string('aggregateavg', 'forum'),
-        FORUM_AGGREGATE_COUNT   => get_string('aggregatecount', 'forum'),
-        FORUM_AGGREGATE_MAX     => get_string('aggregatemax', 'forum'),
-        FORUM_AGGREGATE_MIN      => get_string('aggregatemin', 'forum'),
-        FORUM_AGGREGATE_SUM      => get_string('aggregatesum', 'forum'));
+/**
+ * Returns array of forum types
+ */
+function forum_get_forum_types() {
+    return array ('general'  => get_string('generalforum', 'forum'),
+                  'eachuser' => get_string('eachuserforum', 'forum'),
+                  'single'   => get_string('singleforum', 'forum'),
+                  'qanda'    => get_string('qandaforum', 'forum'));
+}
 
-return $forum_aggregate_types;
+/**
+ * Returns array of all forum layout modes
+ */
+function forum_get_forum_types_all() {
+    return array ('news'     => get_string('namenews','forum'),
+                  'social'   => get_string('namesocial','forum'),
+                  'general'  => get_string('generalforum', 'forum'),
+                  'eachuser' => get_string('eachuserforum', 'forum'),
+                  'single'   => get_string('singleforum', 'forum'),
+                  'qanda'    => get_string('qandaforum', 'forum'));
+}
 
+/**
+ * Returns array of forum open modes
+ */
+function forum_get_open_modes() {
+    return array ('2' => get_string('openmode2', 'forum'),
+                  '1' => get_string('openmode1', 'forum'),
+                  '0' => get_string('openmode0', 'forum') );
 }
 
 ?>
index e4ff8b38adde925e6ef6dcbad7406f2482c06630..0b7ab14f24c971813d1129b6c84e1a45a81edc7f 100644 (file)
@@ -5,7 +5,7 @@ class mod_forum_mod_form extends moodleform_mod {
 
     function definition() {
 
-        global $CFG, $FORUM_TYPES, $COURSE;
+        global $CFG, $COURSE;
         $mform    =& $this->_form;
 
 //-------------------------------------------------------------------------------
@@ -15,8 +15,10 @@ class mod_forum_mod_form extends moodleform_mod {
         $mform->setType('name', PARAM_TEXT);
         $mform->addRule('name', null, 'required', null, 'client');
 
-        asort($FORUM_TYPES);
-        $mform->addElement('select', 'type', get_string('forumtype', 'forum'), $FORUM_TYPES);
+        $forum_types = forum_get_forum_types();
+
+        asort($forum_types);
+        $mform->addElement('select', 'type', get_string('forumtype', 'forum'), $forum_types);
         $mform->setHelpButton('type', array('forumtype', get_string('forumtype', 'forum'), 'forum'));
         $mform->setDefault('type', 'general');
 
@@ -163,7 +165,7 @@ class mod_forum_mod_form extends moodleform_mod {
     function data_preprocessing(&$default_values){
         if (empty($default_values['scale'])){
             $default_values['assessed'] = 0;
-        }        
+        }
 
         if (empty($default_values['assessed'])){
             $default_values['ratingtime'] = 0;
index e67ef474fb66559fd64d735031233ce5c5ea939d..e3d727d22b83e2f42fb421ad91b60038ee0060b1 100644 (file)
@@ -55,7 +55,7 @@
         if (!get_referer()) {   // No referer - probably coming in via email  See MDL-9052
             require_login();
         }
-        
+
         $navigation = build_navigation('', $cm);
         print_header($course->shortname, $course->fullname, $navigation, '' , '', true, "", navmenu($course, $cm));
 
         if (! $course = get_record("course", "id", $forum->course)) {
             error("The course number was incorrect ($forum->course)");
         }
+        if (! $cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
+            error("Incorrect course module");
+        }
+
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
-        if (! forum_user_can_post_discussion($forum)) {
+
+        if (! forum_user_can_post_discussion($forum, -1, -1, $cm)) {
             if (has_capability('moodle/legacy:guest', $coursecontext, NULL, false)) {  // User is a guest here!
                 $SESSION->wantsurl = $FULLME;
                 $SESSION->enrolcancel = $_SERVER['HTTP_REFERER'];
             }
         }
 
-        if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
-            if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $coursecontext)) {
-                error(get_string("activityiscurrentlyhidden"));
-            }
+        if (!$cm->visible and !has_capability('moodle/course:viewhiddenactivities', $coursecontext)) {
+            error(get_string("activityiscurrentlyhidden"));
         }
 
         if (isset($_SERVER["HTTP_REFERER"])) {
         $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
         $modcontext    = get_context_instance(CONTEXT_MODULE, $cm->id);
 
-        if (! forum_user_can_post($forum)) {
+        if (! forum_user_can_post($forum, null, $cm, $modcontext)) {
             if (has_capability('moodle/legacy:guest', $coursecontext, NULL, false)) {  // User is a guest here!
                 $SESSION->wantsurl = $FULLME;
                 $SESSION->enrolcancel = $_SERVER['HTTP_REFERER'];
                              "post.php?delete=$delete&amp;confirm=$delete",
                              $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
 
-                forum_print_post($post, $course->id, $ownpost=false, $reply=false, $link=false);
+                forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
                 if (empty($post->edit)) {
                     if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
                         $user_read_array = forum_tp_get_discussion_read_records($USER->id, $discussion->id);
                     } else {
                         $user_read_array = array();
                     }
-                    forum_print_posts_nested($post->id, $course->id, false, false, $user_read_array, $forum->id);
+                    $posts = forum_get_all_discussion_posts($discussion->id, "created ASC");
+                    forum_print_posts_nested($course, $cm, $forum, $discussion, $post, false, false, $user_read_array, $posts);
                 }
             } else {
                 print_header();
                 notice_yesno(get_string("deletesure", "forum", $replycount),
                              "post.php?delete=$delete&amp;confirm=$delete",
                              $CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#p'.$post->id);
-                forum_print_post($post, $forum->course, $ownpost=false, $reply=false, $link=false);
+                forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
             }
 
         }
         } else { // User just asked to prune something
 
             $course = get_record('course', 'id', $forum->course);
-            
+
             $navlinks = array();
             $navlinks[] = array('name' => format_string($post->subject, true), 'link' => "discuss.php?d=$discussion->id", 'type' => 'title');
             $navlinks[] = array('name' => get_string("prune", "forum"), 'link' => '', 'type' => 'title');
 
             include('prune.html');
 
-            forum_print_post($post, $forum->course, $ownpost=false, $reply=false, $link=false);
+            forum_print_post($post, $discussion, $forum, $cm, $course, false, false, false);
             echo '</center>';
         }
         print_footer($course);
             if (!forum_update_post($updatepost, $message)) {
                 error(get_string("couldnotupdate", "forum"), $errordestination);
             }
-            
+
             // MDL-11818
             if (($forum->type == 'single') && ($updatepost->parent == '0')){ // updating first post of single discussion type -> updating forum intro
                 $forum->intro = $updatepost->message;
                 if (!empty($message)) { // if we're printing stuff about the file upload
                     $timemessage = 4;
                 }
-                
+
                 if ($subscribemessage = forum_post_subscription($fromform)) {
                     $timemessage = 4;
                 }
                 if (!empty($message)) { // if we're printing stuff about the file upload
                     $timemessage = 4;
                 }
-                
+
                 if ($fromform->mailnow) {
                     $message .= get_string("postmailnow", "forum");
                     $timemessage = 4;
                 } else {
                     $message .= '<br />'.get_string("postadded", "forum", format_time($CFG->maxeditingtime));
-                }    
+                }
 
                 if ($subscribemessage = forum_post_subscription($discussion)) {
                     $timemessage = 4;
     if (empty($post->edit)) {
         $post->edit = '';
     }
-    
+
     if (empty($discussion->name)) {
         if (empty($discussion)) {
             $discussion = new object;
     $navlinks = array();
     if ($post->parent) {
         $navlinks[] = array('name' => format_string($toppost->subject, true), 'link' => "discuss.php?d=$discussion->id", 'type' => 'title');
-        $navlinks[] = array('name' => get_string('editing', 'forum'), 'link' => '', 'type' => 'title');            
+        $navlinks[] = array('name' => get_string('editing', 'forum'), 'link' => '', 'type' => 'title');
     } else {
         $navlinks[] = array('name' => format_string($toppost->subject), 'link' => '', 'type' => 'title');
     }
     $navigation = build_navigation($navlinks, $cm);
-     
+
     print_header("$course->shortname: $strdiscussionname ".
                   format_string($toppost->subject), $course->fullname,
                   $navigation, $mform_post->focus($forcefocus), "", true, "", navmenu($course, $cm));
-   
+
 // checkup
-    if (!empty($parent) && !forum_user_can_see_post($forum, $discussion, $post)) {
+    if (!empty($parent) && !forum_user_can_see_post($forum, $discussion, $post, null, $cm)) {
         error("You cannot reply to this post");
     }
-    if (empty($parent) && empty($edit) && !forum_user_can_post_discussion($forum)) {
+    if (empty($parent) && empty($edit) && !forum_user_can_post_discussion($forum, -1, -1, $cm, $modcontext)) {
         error("You cannot start a new discussion in this forum");
     }
 
     forum_check_throttling($forum);
 
     if (!empty($parent)) {
-        forum_print_post($parent, $course->id, $ownpost=false, $reply=false, $link=false);
+        if (! $discussion = get_record('forum_discussions', 'id', $parent->discussion)) {
+            error('This post is not part of a discussion!');
+        }
+
+        forum_print_post($parent, $discussion, $forum, $cm, $course, false, false, false);
         if (empty($post->edit)) {
             if (forum_tp_can_track_forums($forum) && forum_tp_is_tracked($forum)) {
                 $user_read_array = forum_tp_get_discussion_read_records($USER->id, $discussion->id);
                 $user_read_array = array();
             }
             if ($forum->type != 'qanda' || forum_user_can_see_discussion($forum, $discussion, $modcontext)) {
-                forum_print_posts_threaded($parent->id, $course->id, 0, false, false, $user_read_array, $discussion->forum, $modcontext);
+                $posts = forum_get_all_discussion_posts($discussion->id, "created ASC");
+                forum_print_posts_threaded($course, $cm, $forum, $discussion, $parent, 0, false, false, $user_read_array, $posts);
             }
         }
         $heading = get_string("yourreply", "forum");
index c0861bbe7cea9978a34072b034cfcfb9f91ea6c0..cbee2a96bf96e15955b5fd47594758f7dc936084 100644 (file)
                     $sd->format   = $defaultformat;
                     $sd->mailnow  = false;
                     //Insert dicussion/post data
-                    $sdid = forum_add_discussion($sd, $sd->intro);
+                    $sdid = forum_add_discussion($sd, $sd->intro, $forum);
                     //Now, mark the initial post of the discussion as mailed!
                     if ($sdid) {
                         set_field ('forum_posts','mailed', '1', 'discussion', $sdid);
index fce170afc693191534747dabb400d207d708b53f..f57ac7c931b03e5ab646ee98e326cbe1d8dcfc60 100644 (file)
     $strpage = get_string("page");
 
     if (!$search || $showform) {
-    
+
         $navlinks = array();
         $navlinks[] = array('name' => $strforums, 'link' => "index.php?id=$course->id", 'type' => 'activity');
         $navlinks[] = array('name' => $strsearch, 'link' => '', 'type' => 'title');
         $navigation = build_navigation($navlinks);
-        
+
         print_header_simple("$strsearch", "", $navigation, 'search.words',
                   "", "", "&nbsp;", navmenu($course));
 
         print_footer($course);
         exit;
     }
-    
-    
+
+
     print_header_simple("$strsearchresults", "", $navigation, '', "", "",  $searchform, navmenu($course));
 
     echo '<div class="reportlink">';
     foreach ($posts as $post) {
 
         // Replace the simple subject with the three items forum name -> thread name -> subject
-        // (if all three are appropriate) each as a link. 
+        // (if all three are appropriate) each as a link.
         if (! $discussion = get_record('forum_discussions', 'id', $post->discussion)) {
             error('Discussion ID was incorrect');
         }
             error("Could not find forum $discussion->forum");
         }
 
+        if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
+            error('Course Module ID was incorrect');
+        }
+
         $post->subject = highlight($strippedsearch, $post->subject);
         $discussion->name = highlight($strippedsearch, $discussion->name);
 
         $fulllink = "<a href=\"discuss.php?d=$post->discussion#p$post->id\">".get_string("postincontext", "forum")."</a>";
 
         // Now pring the post.
-        forum_print_post($post, $course->id, false, false, false, false,
+        forum_print_post($post, $discussion, $forum, $cm, $cours, false, false, false, false,
                 $fulllink, $strippedsearch, -99, false);
     }
 
@@ -359,12 +363,12 @@ function forum_print_big_search_form($course) {
 }
 
 /**
- * This function takes each word out of the search string, makes sure they are at least 
+ * This function takes each word out of the search string, makes sure they are at least
  * two characters long and returns an array containing every good word.
- * 
+ *
  * @param string $words String containing space-separated strings to search for
  * @param string $prefix String to prepend to the each token taken out of $words
- * @returns array 
+ * @returns array
  * @todo Take the hardcoded limit out of this function and put it into a user-specified parameter
  */
 function forum_clean_search_terms($words, $prefix='') {
index 4b8529ae860af5e506aa72f115e8a5a2b0d12d1f..323b7872f7be5983579ee7d19940c683d4ae2aec 100644 (file)
@@ -2,10 +2,8 @@
 
 require_once($CFG->dirroot.'/mod/forum/lib.php');
 
-global $FORUM_LAYOUT_MODES; // make sure we have the pesky global
-
 $settings->add(new admin_setting_configselect('forum_displaymode', get_string('displaymode', 'forum'),
-                   get_string('configdisplaymode', 'forum'), FORUM_MODE_NESTED, $FORUM_LAYOUT_MODES));
+                   get_string('configdisplaymode', 'forum'), FORUM_MODE_NESTED, forum_get_layout_modes()));
 
 $settings->add(new admin_setting_configcheckbox('forum_replytouser', get_string('replytouser', 'forum'),
                    get_string('configreplytouser', 'forum'), 1));
index 3eb59d1a59f0889cccf5b6062d715d8a63da8975..15a920da23f82e5fa781d5bef2899e05ce09ba22 100644 (file)
@@ -1,6 +1,6 @@
 
 <form id="subscriberform" method="post" action="subscribers.php">
-<input type="hidden" name="previoussearch" value="<?php echo $previoussearch ?>" />
+<input type="hidden" name="previoussearch" value="<?php p($previoussearch) ?>" />
 <input type="hidden" name="id" value="<?php echo $id?>" />
   <table align="center" border="0" cellpadding="5" cellspacing="0">
     <tr>
@@ -56,7 +56,7 @@
           ?>
          </select>
          <br />
-         <input type="text" name="searchtext" size="30" value="<?php echo $searchtext ?>" 
+         <input type="text" name="searchtext" size="30" value="<?php p($searchtext, true) ?>" 
                   onFocus ="getElementById('subscriberform').add.disabled=true;
                             getElementById('subscriberform').remove.disabled=true;
                             getElementById('subscriberform').removeselect.selectedIndex=-1;
index 3fa4f0a2eea13fe7499641ec6d8d9174c9afbdb0..6e0fbf179b97d9ee3e5f2a85fd15a59147a955f0 100644 (file)
@@ -67,7 +67,7 @@
             echo '<table align="center" cellpadding="5" cellspacing="5">';
             foreach ($users as $user) {
                 echo '<tr><td>';
-                print_user_picture($user->id, $course->id, $user->picture);
+                print_user_picture($user, $course->id);
                 echo '</td><td>';
                 echo fullname($user);
                 echo '</td><td>';
index 29547316316d243351bb540de637fedb134fbe7f..e84205a1f4ce1c958b20dc920c0129fcbc925e9b 100644 (file)
@@ -24,7 +24,7 @@
         error("Course id is incorrect.");
     }
 
-    $syscontext = get_context_instance(CONTEXT_SYSTEM, SITEID);
+    $syscontext = get_context_instance(CONTEXT_SYSTEM);
     $usercontext   = get_context_instance(CONTEXT_USER, $id);
     
     // do not force parents to enrol
         
         print_paging_bar($totalcount, $page, $perpage, 
                          "user.php?id=$user->id&amp;course=$course->id&amp;mode=$mode&amp;perpage=$perpage&amp;");
+
+        $discussions = array();
+        $forums      = array();
+        $cms         = array();
         
         foreach ($posts as $post) {
-    
-            if (! $discussion = get_record('forum_discussions', 'id', $post->discussion)) {
-                error('Discussion ID was incorrect');
+
+            if (!isset($discussions[$post->discussion])) {
+                if (! $discussion = get_record('forum_discussions', 'id', $post->discussion)) {
+                    error('Discussion ID was incorrect');
+                }
+                $discussions[$post->discussion] = $discussion;
+            } else {
+                $discussion = $discussions[$post->discussion];
             }
-            if (! $forum = get_record('forum', 'id', "$discussion->forum")) {
-                error("Could not find forum $discussion->forum");
+
+            if (!isset($forums[$discussion->forum])) {
+                if (! $forum = get_record('forum', 'id', $discussion->forum)) {
+                    error("Could not find forum $discussion->forum");
+                }
+                $forums[$discussion->forum] = $forum;
+            } else {
+                $forum = $forums[$discussion->forum];
             }
-            
+
+            if (!isset($cms[$forum->id])) {
+                if (!$cm = get_coursemodule_from_instance('forum', $forum->id)) {
+                    error('Course Module ID was incorrect');
+                }
+                $cms[$forum->id] = $cm;
+                unset($cm); // do not use cm directly, it would break caching
+            }
+
             $fullsubject = "<a href=\"view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
             if ($forum->type != 'single') {
                 $fullsubject .= " -> <a href=\"discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a>";
                 }
             }
             
-            $context = get_context_instance(CONTEXT_SYSTEM, SITEID);
-            if ($course->id == SITEID && has_capability('moodle/site:config', $context)) {
+            if ($course->id == SITEID && has_capability('moodle/site:config', $syscontext)) {
                 $postcoursename = get_field('course', 'shortname', 'id', $forum->course);
                 $fullsubject = '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$forum->course.'">'.$postcoursename.'</a> -> '. $fullsubject;
             }
             $fulllink = "<a href=\"discuss.php?d=$post->discussion#p$post->id\">".
                          get_string("postincontext", "forum")."</a>";
 
-            forum_print_post($post, $course->id, false, false, false, false, $fulllink);
+            forum_print_post($post, $discussion, $forum, $cms[$forum->id], $course, false, false, false, false, $fulllink);
             echo "<br />";
         }
     
index 4546cf2d317510053e16f50a6b051af813cd9875..af53e40745ce5d1525dff5631935b35db5565e93 100644 (file)
@@ -14,9 +14,9 @@
     $search      = optional_param('search', '');             // search string
 
 
+    $buttontext = '';
 
     if ($id) {
-
         if (! $cm = get_coursemodule_from_id('forum', $id)) {
             error("Course Module ID was incorrect");
         }
         $strforums = get_string("modulenameplural", "forum");
         $strforum = get_string("modulename", "forum");
 
-        if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
-            $buttontext = update_module_button($cm->id, $course->id, $strforum);
-        } else {
-            $cm->id = 0;
-            $cm->visible = 1;
-            $cm->course = $course->id;
-            $buttontext = "";
+        if (!$cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
+            error("Course Module missing");
         }
+
+        $buttontext = update_module_button($cm->id, $course->id, $strforum);
+
     } else {
         error('Must specify a course module or a forum ID');
     }
     if (empty($cm->visible) and !has_capability('moodle/course:viewhiddenactivities', $context)) {
         notice(get_string("activityiscurrentlyhidden"));
     }
-    
+
     if (!has_capability('mod/forum:viewdiscussion', $context)) {
         notice(get_string('noviewdiscussionspermission', 'forum'));
     }
-    
+
 /// find out current groups mode
     groups_print_activity_menu($cm, 'view.php?id=' . $cm->id);
     $currentgroup = groups_get_activity_group($cm);
                 echo "<span class=\"helplink\"><a href=\"subscribers.php?id=$forum->id\">$strshowsubscribers</a></span>";
             }
 
-            echo '<div class="helplink" id="subscriptionlink">', forum_get_subscribe_link($forum, $context, 
+            echo '<div class="helplink" id="subscriptionlink">', forum_get_subscribe_link($forum, $context,
                     array('forcesubscribed' => '', 'cantsubscribe' => '')), '</div>';
         }
 
 
 //    print_box_end();  // forumcontrol
 
-//    print_box('&nbsp;', 'clearer'); 
+//    print_box('&nbsp;', 'clearer');
 
 
     if (!empty($forum->blockafter) && !empty($forum->blockperiod)) {
             }
             $displaymode = get_user_preferences("forum_displaymode", $CFG->forum_displaymode);
             $canrate = has_capability('mod/forum:rate', $context);
-            forum_print_discussion($course, $forum, $discussion, $post, $displaymode, NULL, $canrate);
+            forum_print_discussion($course, $cm, $forum, $discussion, $post, $displaymode, NULL, $canrate);
             break;
 
         case 'eachuser':
             } else {
                 forum_print_latest_discussions($course, $forum, $CFG->forum_manydiscussions, 'header', '', $currentgroup, $groupmode, $page);
             }
-            
-            
+
+
             break;
     }
     print_footer($course);
index b13d962507573ebf3c0f0e459fa484a167224c86..cc545746056b980257fb78d31cfd15f3f27fd80a 100755 (executable)
@@ -16,7 +16,7 @@ function glossary_show_entry_TEMPLATE($course, $cm, $glossary, $entry, $mode='',
 
         //Use this function to show author's image
         //Comments: Configuration not supported
-        print_user_picture($user->id, $course->id, $user->picture);
+        print_user_picture($user, $course->id, $user->picture);
 
         //Line separator to show this template fine. :-)
         echo '<br />';
index b19ead33ff5fc8ba2593dd9681a29b4227a21d93..7d50b0eab983431496a5bd7638031c567e73b212 100644 (file)
@@ -13,7 +13,7 @@ function glossary_show_entry_encyclopedia($course, $cm, $glossary, $entry, $mode
         echo '<tr valign="top">';
         echo '<td class="left picture">';
         
-        print_user_picture($user->id, $course->id, $user->picture);
+        print_user_picture($user, $course->id, $user->picture);
     
         echo '</td>';
         echo '<th class="entryheader">';
index f251bfaf99675efea0252765a8956e10923388a7..d4f4863b88b22cf8c503547b5de399c5a8f75859 100644 (file)
@@ -13,7 +13,7 @@ function glossary_show_entry_fullwithauthor($course, $cm, $glossary, $entry, $mo
         echo '<tr valign="top">';
         
         echo '<td class="picture">';
-        print_user_picture($user->id, $course->id, $user->picture);
+        print_user_picture($user, $course->id, $user->picture);
         echo '</td>';
         
         echo '<th class="entryheader">';
index fd999fdadfcf662e8cabf91dc7cd481cb75c0f45..842be5cf14f72574b419ed7e03b0b7684744bb22 100644 (file)
@@ -1563,7 +1563,7 @@ function glossary_print_comment($course, $cm, $glossary, $entry, $comment) {
     echo '<table class="glossarycomment" cellspacing="0">';
     echo '<tr valign="top">';
     echo '<td class="left picture">';
-    print_user_picture($user->id, $course->id, $user->picture);
+    print_user_picture($user, $course->id, $user->picture);
     echo '</td>';
     echo '<td class="entryheader">';
 
index af508f2bca1b1e13bbca65d3c25a19acd2595b3a..166afef13b1e5fc5fa03244d0c124528a2e2cbc9 100644 (file)
                         echo '<th align="left">';
 
                         $user = get_record("user","id",$entry->userid);
-                        print_user_picture($user->id, $course->id, $user->picture);
+                        print_user_picture($user, $course->id, $user->picture);
                         $pivottoshow = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $course->id)));
                     } else {
                         echo '<th >';
index 29bdcaab9c9788dbef2cf70fa3793bbb2c00cbaa..0ca3c71539c1a88e03975ccfc77ded4c5da0fa0a 100644 (file)
     echo '<table class="generaltable generalbox quizreviewsummary"><tbody>';
     if ($attempt->userid <> $USER->id) {
         $student = get_record('user', 'id', $attempt->userid);
-        $picture = print_user_picture($student->id, $course->id, $student->picture, false, true);
+        $picture = print_user_picture($student, $course->id, $student->picture, false, true);
         echo '<tr><th scope="row" class="cell">', $picture, '</th><td class="cell"><a href="', $CFG->wwwroot,
             '/user/view.php?id=', $student->id, '&amp;course='.$course->id.'">',
             fullname($student, true), '</a></td></tr>';
index abb8dbb6634e593ea502e826a4be7f762914ebdd..cc8c7f805161a96a5b06faceb244df5358a62ba0 100644 (file)
     if ($attempt->userid <> $USER->id) {
         // Print user picture and name
         $student = get_record('user', 'id', $attempt->userid);
-        $picture = print_user_picture($student->id, $course->id, $student->picture, false, true);
+        $picture = print_user_picture($student, $course->id, $student->picture, false, true);
         $table->data[] = array($picture, fullname($student, true));
     }
     // print quiz name
index cf71631ece8c31ffac3381db346e6d90ef1286f2..e7276c3b076a45e06fb1912b293fe42c51d84b10 100644 (file)
@@ -172,7 +172,7 @@ function note_print($note, $detail = NOTES_SHOW_FULL) {
     if($detail & NOTES_SHOW_HEAD) {
         echo '<div class="header">';
         echo '<div class="user">';
-        print_user_picture($user->id, $note->courseid, $user->picture);
+        print_user_picture($user, $note->courseid, $user->picture);
         echo fullname($user) . '</div>';
         echo '<div class="info">' .
             get_string('bynameondate', 'notes', $authoring) .
index 5bb638438e7bd4a7d1f3aadf76b92241d01c656b..9f96fd902aebadfae40a24f404d590dbc82e4edb 100644 (file)
@@ -60,7 +60,7 @@ class user_edit_form extends moodleform {
             if (!empty($CFG->gdversion)) {
                 $image_el =& $mform->getElement('currentpicture');
                 if ($user and $user->picture) {
-                    $image_el->setValue(print_user_picture($user->id, SITEID, $user->picture, 64,true,false,'',true));
+                    $image_el->setValue(print_user_picture($user, SITEID, $user->picture, 64,true,false,'',true));
                 } else {
                     $image_el->setValue(get_string('none'));
                 }
index b734e57449a42395821fd59c1a3638c3ed6c97f9..ea4d98a0848885850d36314bde196bcc6041cbb8 100644 (file)
@@ -94,7 +94,7 @@ class user_editadvanced_form extends moodleform {
         if (!empty($CFG->gdversion)) {
             $image_el =& $mform->getElement('currentpicture');
             if ($user and $user->picture) {
-                $image_el->setValue(print_user_picture($user->id, SITEID, $user->picture, 64, true, false, '', true));
+                $image_el->setValue(print_user_picture($user, SITEID, $user->picture, 64, true, false, '', true));
             } else {
                 $image_el->setValue(get_string('none'));
             }
index 457d1aebe76990a861c05714f5deca698e3710a0..45337e5a1fae55abb38f9afb9e6f70e05a5a8276 100644 (file)
     echo '<table width="80%" class="userinfobox" summary="">';
     echo '<tr>';
     echo '<td class="side">';
-    print_user_picture($user->id, $course->id, $user->picture, true, false, false);
+    print_user_picture($user, $course->id, $user->picture, true, false, false);
     echo '</td><td class="content">';
 
     // Print the description