In course overview in my moodle page, dim hidden courses
[moodle.git] / mod / forum / lib.php
CommitLineData
41905731 1<?php // $Id$
f93f848a 2
f1e0649c 3require_once($CFG->libdir.'/filelib.php');
7f6689e4 4
501cdbd8 5/// CONSTANTS ///////////////////////////////////////////////////////////
f93f848a 6
d3583b41 7define('FORUM_MODE_FLATOLDEST', 1);
8define('FORUM_MODE_FLATNEWEST', -1);
9define('FORUM_MODE_THREADED', 2);
10define('FORUM_MODE_NESTED', 3);
2e2e71a8 11
d3583b41 12define('FORUM_FORCESUBSCRIBE', 1);
13define('FORUM_INITIALSUBSCRIBE', 2);
709f0ec8 14
eaf50aef 15define('FORUM_TRACKING_OFF', 0);
16define('FORUM_TRACKING_OPTIONAL', 1);
17define('FORUM_TRACKING_ON', 2);
18
d3583b41 19$FORUM_LAYOUT_MODES = array ( FORUM_MODE_FLATOLDEST => get_string('modeflatoldestfirst', 'forum'),
20 FORUM_MODE_FLATNEWEST => get_string('modeflatnewestfirst', 'forum'),
21 FORUM_MODE_THREADED => get_string('modethreaded', 'forum'),
22 FORUM_MODE_NESTED => get_string('modenested', 'forum') );
f93f848a 23
11b0c469 24// These are course content forums that can be added to the course manually
d3583b41 25$FORUM_TYPES = array ('general' => get_string('generalforum', 'forum'),
26 'eachuser' => get_string('eachuserforum', 'forum'),
27 'single' => get_string('singleforum', 'forum') );
f93f848a 28
d3583b41 29$FORUM_OPEN_MODES = array ('2' => get_string('openmode2', 'forum'),
30 '1' => get_string('openmode1', 'forum'),
31 '0' => get_string('openmode0', 'forum') );
70c476a7 32
5be7800c 33if (!isset($CFG->forum_displaymode)) {
d3583b41 34 set_config('forum_displaymode', FORUM_MODE_NESTED);
65b0e537 35}
73bb0835 36
5be7800c 37if (!isset($CFG->forum_shortpost)) {
d3583b41 38 set_config('forum_shortpost', 300); // Less non-HTML characters than this is short
65b0e537 39}
4d871a72 40
5be7800c 41if (!isset($CFG->forum_longpost)) {
d3583b41 42 set_config('forum_longpost', 600); // More non-HTML characters than this is long
65b0e537 43}
4d871a72 44
5be7800c 45if (!isset($CFG->forum_manydiscussions)) {
d3583b41 46 set_config('forum_manydiscussions', 100); // Number of discussions on a page
65b0e537 47}
e07635f4 48
4909e176 49if (!isset($CFG->forum_maxbytes)) {
d3583b41 50 set_config('forum_maxbytes', 512000); // Default maximum size for all forums
65b0e537 51}
4909e176 52
f37da850 53if (!isset($CFG->forum_trackreadposts)) {
d3583b41 54 set_config('forum_trackreadposts', true); // Default whether user needs to mark a post as read
f37da850 55}
56
57if (!isset($CFG->forum_oldpostdays)) {
81c679ce 58 set_config('forum_oldpostdays', 14); // Default number of days that a post is considered old
f37da850 59}
60
61if (!isset($CFG->forum_usermarksread)) {
d3583b41 62 set_config('forum_usermarksread', false); // Default whether user needs to mark a post as read
f37da850 63}
64
65if (!isset($CFG->forum_cleanreadtime)) {
d3583b41 66 set_config('forum_cleanreadtime', 2); // Default time (hour) to execute 'clean_read_records' cron
f37da850 67}
68
1246ea56 69if (!isset($CFG->forum_replytouser)) {
d3583b41 70 set_config('forum_replytouser', true); // Default maximum size for all forums
1246ea56 71}
72
27888a20 73if (empty($USER->id) or isguest()) {
74 $CFG->forum_trackreadposts = false; // This feature never works when a user isn't logged in
75}
4909e176 76
e07635f4 77
caadf009 78/// STANDARD FUNCTIONS ///////////////////////////////////////////////////////////
79
80function forum_add_instance($forum) {
65b0e537 81// Given an object containing all the necessary data,
82// (defined by the form in mod.html) this function
83// will create a new instance and return the id number
caadf009 84// of the new instance.
85
86 global $CFG;
87
88 $forum->timemodified = time();
89
f2f56406 90 if (!$forum->userating) {
91 $forum->assessed = 0;
92 }
93
98914efd 94 if (!empty($forum->ratingtime)) {
65b0e537 95 $forum->assesstimestart = make_timestamp($forum->startyear, $forum->startmonth, $forum->startday,
98914efd 96 $forum->starthour, $forum->startminute, 0);
65b0e537 97 $forum->assesstimefinish = make_timestamp($forum->finishyear, $forum->finishmonth, $forum->finishday,
98914efd 98 $forum->finishhour, $forum->finishminute, 0);
99 } else {
100 $forum->assesstimestart = 0;
101 $forum->assesstimefinish = 0;
102 }
caadf009 103
d3583b41 104 if (! $forum->id = insert_record('forum', $forum)) {
cb9a975f 105 return false;
106 }
107
d3583b41 108 if ($forum->type == 'single') { // Create related discussion.
caadf009 109 $discussion->course = $forum->course;
110 $discussion->forum = $forum->id;
111 $discussion->name = $forum->name;
112 $discussion->intro = $forum->intro;
113 $discussion->assessed = $forum->assessed;
93c86520 114 $discussion->format = $forum->format;
caadf009 115
93c86520 116 if (! forum_add_discussion($discussion, $discussion->intro)) {
d3583b41 117 error('Could not add the discussion for this forum');
caadf009 118 }
119 }
8f0cd6ef 120
709f0ec8 121 if ($forum->forcesubscribe == FORUM_INITIALSUBSCRIBE) { // all users should be subscribed initially
122 $users = get_course_users($forum->course);
123 foreach ($users as $user) {
124 forum_subscribe($user->id, $forum->id);
125 }
126 }
caadf009 127
128 return $forum->id;
129}
130
131
132function forum_update_instance($forum) {
65b0e537 133// Given an object containing all the necessary data,
134// (defined by the form in mod.html) this function
caadf009 135// will update an existing instance with new data.
136
137 $forum->timemodified = time();
138 $forum->id = $forum->instance;
139
3ad7a8c7 140 if (empty($forum->userating)) {
f2f56406 141 $forum->assessed = 0;
142 }
143
98914efd 144 if (!empty($forum->ratingtime)) {
65b0e537 145 $forum->assesstimestart = make_timestamp($forum->startyear, $forum->startmonth, $forum->startday,
98914efd 146 $forum->starthour, $forum->startminute, 0);
65b0e537 147 $forum->assesstimefinish = make_timestamp($forum->finishyear, $forum->finishmonth, $forum->finishday,
98914efd 148 $forum->finishhour, $forum->finishminute, 0);
149 } else {
150 $forum->assesstimestart = 0;
151 $forum->assesstimefinish = 0;
152 }
153
d3583b41 154 if ($forum->type == 'single') { // Update related discussion and post.
155 if (! $discussion = get_record('forum_discussions', 'forum', $forum->id)) {
156 if ($discussions = get_records('forum_discussions', 'forum', $forum->id, 'timemodified ASC')) {
157 notify('Warning! There is more than one discussion in this forum - using the most recent');
caadf009 158 $discussion = array_pop($discussions);
159 } else {
d3583b41 160 error('Could not find the discussion in this forum');
caadf009 161 }
162 }
d3583b41 163 if (! $post = get_record('forum_posts', 'id', $discussion->firstpost)) {
164 error('Could not find the first post in this forum discussion');
caadf009 165 }
166
167 $post->subject = $forum->name;
168 $post->message = $forum->intro;
169 $post->modified = $forum->timemodified;
170
d3583b41 171 if (! update_record('forum_posts', $post)) {
172 error('Could not update the first post');
caadf009 173 }
174
175 $discussion->name = $forum->name;
176
d3583b41 177 if (! update_record('forum_discussions', $discussion)) {
178 error('Could not update the discussion');
caadf009 179 }
180 }
181
d3583b41 182 return update_record('forum', $forum);
caadf009 183}
184
185
186function forum_delete_instance($id) {
65b0e537 187// Given an ID of an instance of this module,
188// this function will permanently delete the instance
189// and any data that depends on it.
caadf009 190
d3583b41 191 if (! $forum = get_record('forum', 'id', $id)) {
caadf009 192 return false;
193 }
194
195 $result = true;
196
d3583b41 197 if ($discussions = get_records('forum_discussions', 'forum', $forum->id)) {
caadf009 198 foreach ($discussions as $discussion) {
e2c1dbe9 199 if (! forum_delete_discussion($discussion, true)) {
caadf009 200 $result = false;
201 }
202 }
203 }
204
d3583b41 205 if (! delete_records('forum_subscriptions', 'forum', $forum->id)) {
caadf009 206 $result = false;
207 }
208
f37da850 209 forum_tp_delete_read_records(-1, -1, -1, $forum->id);
210
d3583b41 211 if (! delete_records('forum', 'id', $forum->id)) {
caadf009 212 $result = false;
213 }
214
215 return $result;
216}
217
218
219function forum_cron () {
edffca15 220/// Function to be run periodically according to the moodle cron
221/// Finds all posts that have yet to be mailed out, and mails them
222/// out to all subscribers
caadf009 223
d30867b0 224 global $CFG, $USER;
aaf7a9dc 225 static $strforums = NULL;
857b798b 226
227 if ($strforums === NULL) {
aaf7a9dc 228 $strforums = get_string('forums', 'forum');
229 }
230
1066e0dc 231 if (!empty($USER->id)) { // Remember real USER account if necessary
ec2137ba 232 $realuser = $USER;
233 }
234
3ecca1ee 235 /// Posts older than 2 days will not be mailed. This is to avoid the problem where
236 /// cron has not been running for a long time, and then suddenly people are flooded
237 /// with mail from the past few weeks or months
caadf009 238
3ecca1ee 239 $timenow = time();
240 $endtime = $timenow - $CFG->maxeditingtime;
38ad519c 241 $starttime = $endtime - 48 * 3600; /// Two days earlier
3ecca1ee 242
243 if ($posts = forum_get_unmailed_posts($starttime, $endtime)) {
caadf009 244
65b0e537 245 /// Mark them all now as being mailed. It's unlikely but possible there
246 /// might be an error later so that a post is NOT actually mailed out,
edffca15 247 /// but since mail isn't crucial, we can accept this risk. Doing it now
248 /// prevents the risk of duplicated mails, which is a worse problem.
249
3ecca1ee 250 if (!forum_mark_old_posts_as_mailed($endtime)) {
d3583b41 251 mtrace('Errors occurred while trying to mark some posts as being mailed.');
3ecca1ee 252 return false; // Don't continue trying to mail them, in case we are in a cron loop
edffca15 253 }
254
ca8e8a10 255 @set_time_limit(0); /// so that script does not get timed out when posting to many users
aaf7a9dc 256
857b798b 257 $urlinfo = parse_url($CFG->wwwroot);
258 $hostname = $urlinfo['host'];
259
caadf009 260 foreach ($posts as $post) {
261
d3583b41 262 mtrace(get_string('processingpost', 'forum', $post->id), '');
caadf009 263
d3583b41 264 if (! $userfrom = get_record('user', 'id', $post->userid)) {
265 mtrace('Could not find user '.$post->userid);
caadf009 266 continue;
267 }
268
857b798b 269
49d9b738 270
caadf009 271 if (! $discussion = get_record("forum_discussions", "id", "$post->discussion")) {
b140ae85 272 mtrace("Could not find discussion $post->discussion");
caadf009 273 continue;
274 }
275
276 if (! $forum = get_record("forum", "id", "$discussion->forum")) {
b140ae85 277 mtrace("Could not find forum $discussion->forum");
caadf009 278 continue;
279 }
280
281 if (! $course = get_record("course", "id", "$forum->course")) {
b140ae85 282 mtrace("Could not find course $forum->course");
caadf009 283 continue;
284 }
285
fd8585a0 286 $cleanforumname = str_replace('"', "'", strip_tags($forum->name));
287 $userfrom->customheaders = array ( // Headers to make emails easier to track
288 'Precedence: Bulk',
289 'List-Id: "'.$cleanforumname.'" <moodleforum'.$forum->id.'@'.$hostname.'>',
290 'List-Help: '.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id,
291 'Message-Id: <moodlepost'.$post->id.'@'.$hostname.'>',
292 'In-Reply-To: <moodlepost'.$post->parent.'@'.$hostname.'>',
293 'References: <moodlepost'.$post->parent.'@'.$hostname.'>',
294 'X-Course-Id: '.$course->id,
ddff0984 295 'X-Course-Name: '.strip_tags($course->fullname)
fd8585a0 296 );
297
298
e1fb2e6e 299 if (!empty($course->lang)) {
300 $CFG->courselang = $course->lang;
301 } else {
302 unset($CFG->courselang);
303 }
9c84314e 304
9197e147 305 $groupmode = false;
306 if ($cm = get_coursemodule_from_instance("forum", $forum->id, $course->id)) {
2862b309 307 if ($groupmode = groupmode($course, $cm) and $discussion->groupid > 0) { // Groups are being used
2f9c977e 308 if (!$group = get_record("groups", "id", $discussion->groupid)) { // Can't find group
9197e147 309 continue; // Be safe and don't send it to anyone
310 }
311 }
69d79bc3 312 } else {
313 $cm->id = 0;
314 }
9197e147 315
caadf009 316 if ($users = forum_subscribed_users($course, $forum)) {
caadf009 317
318 $mailcount=0;
3d94772d 319 $errorcount=0;
caadf009 320 foreach ($users as $userto) {
9197e147 321 if ($groupmode) { // Look for a reason not to send this email
322 if (!isteacheredit($course->id, $userto->id)) {
2862b309 323 if (!empty($group->id)) {
324 if (!ismember($group->id, $userto->id)) {
325 continue;
326 }
9197e147 327 }
328 }
329 }
65b0e537 330
aaf7a9dc 331 if ($userto->maildigest > 0) {
332 // This user wants the mails to be in digest form
333 $queue = New stdClass;
334 $queue->userid = $userto->id;
335 $queue->discussionid = $discussion->id;
336 $queue->postid = $post->id;
337 if(!insert_record('forum_queue', $queue)) {
b140ae85 338 mtrace("Error: mod/forum/cron.php: Could not queue for digest mail for id $post->id to user $userto->id ($userto->email) .. not trying again.");
aaf7a9dc 339 }
340 continue;
341 }
65b0e537 342
343 /// Override the language and timezone of the "current" user, so that
ec2137ba 344 /// mail is customised for the receiver.
345 $USER->lang = $userto->lang;
346 $USER->timezone = $userto->timezone;
347
17dc3f3c 348 $postsubject = "$course->shortname: ".format_string($post->subject,true);
aaf7a9dc 349 $posttext = forum_make_mail_text($course, $forum, $discussion, $post, $userfrom, $userto);
350 $posthtml = forum_make_mail_html($course, $forum, $discussion, $post, $userfrom, $userto);
caadf009 351
8f0cd6ef 352 if (!$mailresult = email_to_user($userto, $userfrom, $postsubject, $posttext,
50a26903 353 $posthtml, '', '', $CFG->forum_replytouser)) {
b140ae85 354 mtrace("Error: mod/forum/cron.php: Could not send out mail for id $post->id to user $userto->id".
355 " ($userto->email) .. not trying again.");
8f0cd6ef 356 add_to_log($course->id, 'forum', 'mail error', "discuss.php?d=$discussion->id#$post->id",
17dc3f3c 357 substr(format_string($post->subject,true),0,30), $cm->id, $userto->id);
aaf7a9dc 358 $errorcount++;
b6268a0e 359 } else if ($mailresult === 'emailstop') {
8f0cd6ef 360 add_to_log($course->id, 'forum', 'mail blocked', "discuss.php?d=$discussion->id#$post->id",
17dc3f3c 361 substr(format_string($post->subject,true),0,30), $cm->id, $userto->id);
caadf009 362 } else {
aaf7a9dc 363 $mailcount++;
f37da850 364
365 /// Mark post as read if forum_usermarksread is set off
eaf50aef 366 if (!$CFG->forum_usermarksread && forum_tp_can_track_forums($forum, $userto) &&
367 forum_tp_is_tracked($forum, $userto->id)) {
f37da850 368 if (!forum_tp_mark_post_read($userto->id, $post, $forum->id)) {
369 mtrace("Error: mod/forum/cron.php: Could not mark post $post->id read for user $userto->id".
370 " while sending email.");
371 }
372 }
caadf009 373 }
aaf7a9dc 374 }
375
b140ae85 376 mtrace(".... mailed to $mailcount users.");
aaf7a9dc 377 if ($errorcount) {
378 set_field("forum_posts", "mailed", "2", "id", "$post->id");
379 }
380 }
381 }
382 }
383
6e6a64b3 384 unset($CFG->courselang);
385
944a2b28 386 if (!empty($realuser)) { // Restore real USER timezone if necessary
387 $sitetimezone = $realuser->timezone;
b140ae85 388 $USER->lang = $realuser->lang;
944a2b28 389 } else {
390 $sitetimezone = $CFG->timezone;
b140ae85 391 $USER->lang = $CFG->lang;
944a2b28 392 }
393
aaf7a9dc 394 /// Now see if there are any digest mails waiting to be sent, and if we should send them
aaf7a9dc 395
8f0cd6ef 396 if (!isset($CFG->digestmailtimelast)) { // To catch the first time
ca8e8a10 397 set_config('digestmailtimelast', 0);
398 }
399
400 $timenow = time();
944a2b28 401 $digesttime = usergetmidnight($timenow, $sitetimezone) + ($CFG->digestmailtime * 3600);
ca8e8a10 402
403 if ($CFG->digestmailtimelast < $digesttime and $timenow > $digesttime) {
b140ae85 404
ca8e8a10 405 set_config('digestmailtimelast', $timenow);
aaf7a9dc 406
b140ae85 407 mtrace('Sending forum digests: '.userdate($timenow, '', $sitetimezone));
408
aaf7a9dc 409 $digestposts = get_records('forum_queue');
410 if(!empty($digestposts)) {
411
412 // We have work to do
413 $usermailcount = 0;
414 $site = get_site();
415
416 $users = array();
417 $posts = array();
418 $discussions = array();
419 $discussionposts = array();
420 $userdiscussions = array();
421 foreach($digestposts as $digestpost) {
422 if(!isset($users[$digestpost->userid])) {
423 $users[$digestpost->userid] = get_record('user', 'id', $digestpost->userid);
424 }
425 if(!isset($discussions[$digestpost->discussionid])) {
426 $discussions[$digestpost->discussionid] = get_record('forum_discussions', 'id', $digestpost->discussionid);
427 }
428 if(!isset($posts[$digestpost->postid])) {
429 $posts[$digestpost->postid] = get_record('forum_posts', 'id', $digestpost->postid);
430 }
431 $userdiscussions[$digestpost->userid][$digestpost->discussionid] = $digestpost->discussionid;
432 $discussionposts[$digestpost->discussionid][$digestpost->postid] = $digestpost->postid;
433 }
434
435 // Data collected, start sending out emails to each user
436
437 foreach($userdiscussions as $userid => $thesediscussions) {
438
b140ae85 439 mtrace(get_string('processingdigest', 'forum', $userid),'... ');
aaf7a9dc 440
441 // First of all delete all the queue entries for this user
442 delete_records('forum_queue', 'userid', $userid);
443 $userto = $users[$userid];
444
445 /// Override the language and timezone of the "current" user, so that
446 /// mail is customised for the receiver.
a0330747 447 $USER->lang = $userto->lang;
448 $USER->timezone = $userto->timezone;
aaf7a9dc 449
450
451 $postsubject = get_string('digestmailsubject', 'forum', $site->shortname);
452 $headerdata = New stdClass;
453 $headerdata->sitename = $site->fullname;
839f2456 454 $headerdata->userprefs = $CFG->wwwroot.'/user/edit.php?id='.$userid.'&amp;course='.$site->id;
aaf7a9dc 455
456 $posttext = get_string('digestmailheader', 'forum', $headerdata)."\n\n";
457 $headerdata->userprefs = '<a target="_blank" href="'.$headerdata->userprefs.'">'.get_string('digestmailprefs', 'forum').'</a>';
9c674431 458
78c0d909 459 $posthtml = "<head>";
460 foreach ($CFG->stylesheets as $stylesheet) {
461 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
462 }
463 $posthtml .= "</head>\n<body>\n";
a0330747 464 $posthtml .= '<p>'.get_string('digestmailheader', 'forum', $headerdata).'</p><br /><hr size="1" noshade="noshade" />';
aaf7a9dc 465
466 foreach($thesediscussions as $discussionid) {
467 $discussion = $discussions[$discussionid];
468 if(empty($discussion)) {
b140ae85 469 mtrace("Error: Could not find discussion $discussionid");
aaf7a9dc 470 continue;
caadf009 471 }
aaf7a9dc 472
473 if (! $forum = get_record("forum", "id", "$discussion->forum")) {
b140ae85 474 mtrace("Could not find forum $discussion->forum");
aaf7a9dc 475 continue;
f690562f 476 }
aaf7a9dc 477 if (! $course = get_record("course", "id", "$forum->course")) {
b140ae85 478 mtrace("Could not find course $forum->course");
aaf7a9dc 479 continue;
caadf009 480 }
65b0e537 481
aaf7a9dc 482 $canunsubscribe = ! forum_is_forcesubscribed($forum->id);
483 $canreply = forum_user_can_post($forum, $userto);
caadf009 484
caadf009 485
aaf7a9dc 486 $posttext .= "\n \n";
487 $posttext .= '=====================================================================';
488 $posttext .= "\n \n";
3849dae8 489 $posttext .= "$course->shortname -> $strforums -> ".format_string($forum->name,true);
aaf7a9dc 490 if ($discussion->name != $forum->name) {
c78ac798 491 $posttext .= " -> ".format_string($discussion->name,true);
caadf009 492 }
aaf7a9dc 493 $posttext .= "\n";
65b0e537 494
aaf7a9dc 495 $posthtml .= "<p><font face=\"sans-serif\">".
496 "<a target=\"_blank\" href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> -> ".
497 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/index.php?id=$course->id\">$strforums</a> -> ".
3849dae8 498 "<a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/view.php?f=$forum->id\">".format_string($forum->name,true)."</a>";
aaf7a9dc 499 if ($discussion->name == $forum->name) {
500 $posthtml .= "</font></p>";
caadf009 501 } else {
c78ac798 502 $posthtml .= " -> <a target=\"_blank\" href=\"$CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id\">".format_string($discussion->name,true)."</a></font></p>";
caadf009 503 }
aaf7a9dc 504 $posthtml .= '<p>';
505
e1c6dde1 506 $postsarray = $discussionposts[$discussionid];
507 sort($postsarray);
508
f37da850 509 /// Create an empty array to use for marking read posts.
510 /// (I'm sure there's already a structure I can use here, but I can't be sure.)
511 $markread = array();
512
857b798b 513 foreach ($postsarray as $postid) {
aaf7a9dc 514 if (! $post = get_record("forum_posts", "id", "$postid")) {
b140ae85 515 mtrace("Error: Could not find post $postid");
aaf7a9dc 516 continue;
517 }
518 if (! $userfrom = get_record("user", "id", "$post->userid")) {
b140ae85 519 mtrace("Error: Could not find user $post->userid");
aaf7a9dc 520 continue;
521 }
522
857b798b 523 $userfrom->customheaders = array ("Precedence: Bulk");
524
525 if ($userto->maildigest == 2) {
aaf7a9dc 526 // Subjects only
527 $by = New stdClass;
528 $by->name = fullname($userfrom);
529 $by->date = userdate($post->modified);
17dc3f3c 530 $posttext .= "\n".format_string($post->subject,true).' '.get_string("bynameondate", "forum", $by);
aaf7a9dc 531 $posttext .= "\n---------------------------------------------------------------------";
532
839f2456 533 $by->name = "<a target=\"_blank\" href=\"$CFG->wwwroot/user/view.php?id=$userfrom->id&amp;course=$course->id\">$by->name</a>";
17dc3f3c 534 $posthtml .= '<div><a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'#'.$post->id.'">'.format_string($post->subject,true).'</a> '.get_string("bynameondate", "forum", $by).'</div>';
857b798b 535
536 } else {
aaf7a9dc 537 // The full treatment
538 $posttext .= forum_make_mail_text($course, $forum, $discussion, $post, $userfrom, $userto, true);
add3201e 539 $posthtml .= forum_make_mail_post($post, $userfrom, $userto, $course, false, $canreply, true, false);
f37da850 540
541 /// Create an array of postid's for this user to mark as read.
eaf50aef 542 if (!$CFG->forum_usermarksread &&
543 forum_tp_can_track_forums($forum, $userto) &&
544 forum_tp_is_tracked($forum, $userto->id)) {
f37da850 545 $markread[$post->id]->post = $post;
546 $markread[$post->id]->forumid = $forum->id;
547 }
aaf7a9dc 548 }
549 }
550 if ($canunsubscribe) {
551 $posthtml .= "\n<div align=\"right\"><font size=\"1\"><a href=\"$CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\">".get_string("unsubscribe", "forum")."</a></font></div>";
857b798b 552 } else {
aaf7a9dc 553 $posthtml .= "\n<div align=\"right\"><font size=\"1\">".get_string("everyoneissubscribed", "forum")."</font></div>";
554 }
555 $posthtml .= '<hr size="1" noshade="noshade" /></p>';
caadf009 556 }
a0330747 557 $posthtml .= '</body>';
caadf009 558
379a42cb 559 if($userto->mailformat != 1) {
560 // This user DOESN'T want to receive HTML
561 $posthtml = '';
562 }
563
8f0cd6ef 564 if (!$mailresult = email_to_user($userto, $site->shortname, $postsubject, $posttext, $posthtml,
50a26903 565 '', '', $CFG->forum_replytouser)) {
b140ae85 566 mtrace("ERROR!");
aaf7a9dc 567 echo "Error: mod/forum/cron.php: Could not send out digest mail to user $userto->id ($userto->email)... not trying again.\n";
568 add_to_log($course->id, 'forum', 'mail digest error', '', '', $cm->id, $userto->id);
b6268a0e 569 } else if ($mailresult === 'emailstop') {
50a26903 570 add_to_log($course->id, 'forum', 'mail digest blocked', '', '', $cm->id, $userto->id);
aaf7a9dc 571 } else {
b140ae85 572 mtrace("success.");
aaf7a9dc 573 $usermailcount++;
e3ff14ca 574
6ea5ebd4 575 /// Mark post as read if forum_usermarksread is set off
576 if (!$CFG->forum_usermarksread &&
577 forum_tp_can_track_forums($forum->id, $userto) &&
578 forum_tp_is_tracked($forum->id, $userto->id)) {
579 foreach ($markread as $postinfo) {
580 if (!forum_tp_mark_post_read($userto->id, $postinfo->post, $postinfo->forumid)) {
581 mtrace("Error: mod/forum/cron.php: Could not mark post $postid read for user $userto->id".
582 " while sending digest email.");
f37da850 583 }
584 }
6ea5ebd4 585 }
3d94772d 586 }
caadf009 587 }
caadf009 588 }
589 }
590
d658167f 591 if(!empty($usermailcount)) {
b140ae85 592 mtrace(get_string('digestsentusers', 'forum', $usermailcount));
aaf7a9dc 593 }
594
ec2137ba 595 if (!empty($realuser)) { // Restore real USER if necessary
596 $USER = $realuser;
597 }
598
f37da850 599 if (($lastreadclean = get_record("config", "name", "forum_lastreadclean"))) {
600 $cleantime = mktime($CFG->forum_cleanreadtime, 0);
601 $timenow = time();
602 if (($timenow > $cleantime) && ($lastreadclean->value+(24*3600) < $timenow)) {
603 $lastreadclean->value = $timenow;
604 update_record("config", $lastreadclean);
605 forum_tp_clean_read_records();
606 }
607 } else {
608 $lastreadclean->name = 'forum_lastreadclean';
609 $lastreadclean->value = time();
610 insert_record("config", $lastreadclean);
611 }
612
613
caadf009 614 return true;
615}
616
aaf7a9dc 617function forum_make_mail_text($course, $forum, $discussion, $post, $userfrom, $userto, $bare = false) {
618 global $CFG;
619
aaf7a9dc 620 $by = New stdClass;
621 $by->name = fullname($userfrom, isteacher($course->id, $userto->id));
622 $by->date = userdate($post->modified, "", $userto->timezone);
623
624 $strbynameondate = get_string('bynameondate', 'forum', $by);
625
64762ddc 626 $strforums = get_string('forums', 'forum');
627
aaf7a9dc 628 $canunsubscribe = ! forum_is_forcesubscribed($forum->id);
629 $canreply = forum_user_can_post($forum, $userto);
630
631 $posttext = '';
632
633 if(!$bare) {
3849dae8 634 $posttext = "$course->shortname -> $strforums -> ".format_string($forum->name,true);
aaf7a9dc 635
636 if ($discussion->name != $forum->name) {
c78ac798 637 $posttext .= " -> ".format_string($discussion->name,true);
aaf7a9dc 638 }
639 }
640
641 $posttext .= "\n---------------------------------------------------------------------\n";
17dc3f3c 642 $posttext .= format_string($post->subject,true);
aaf7a9dc 643 if($bare) {
644 $posttext .= " ($CFG->wwwroot/mod/forum/discuss.php?d=$discussion->id#$post->id)";
645 }
646 $posttext .= "\n".$strbynameondate."\n";
647 $posttext .= "---------------------------------------------------------------------\n";
648 $posttext .= format_text_email($post->message, $post->format);
649 $posttext .= "\n\n";
650 if ($post->attachment) {
651 $post->course = $course->id;
652 $post->forum = $forum->id;
653 $posttext .= forum_print_attachments($post, "text");
654 }
655 if (!$bare && $canreply) {
656 $posttext .= "---------------------------------------------------------------------\n";
657 $posttext .= get_string("postmailinfo", "forum", $course->shortname)."\n";
658 $posttext .= "$CFG->wwwroot/mod/forum/post.php?reply=$post->id\n";
659 }
660 if (!$bare && $canunsubscribe) {
661 $posttext .= "\n---------------------------------------------------------------------\n";
662 $posttext .= get_string("unsubscribe", "forum");
663 $posttext .= ": $CFG->wwwroot/mod/forum/subscribe.php?id=$forum->id\n";
664 }
665
666 return $posttext;
667}
668
669function forum_make_mail_html($course, $forum, $discussion, $post, $userfrom, $userto) {
670 global $CFG;
671
a0288610 672 if ($userto->mailformat != 1) { // Needs to be HTML
673 return '';
674 }
aaf7a9dc 675
a0288610 676 $strforums = get_string('forums', 'forum');
677 $canreply = forum_user_can_post($forum, $userto);
678 $canunsubscribe = ! forum_is_forcesubscribed($forum->id);
aaf7a9dc 679
a0288610 680 $posthtml = '<head>';
681 foreach ($CFG->stylesheets as $stylesheet) {
682 $posthtml .= '<link rel="stylesheet" type="text/css" href="'.$stylesheet.'" />'."\n";
683 }
684 $posthtml .= '</head>';
f2379d2d 685 $posthtml .= "\n<body id=\"email\">\n\n";
aaf7a9dc 686
f2379d2d 687 $posthtml .= '<div class="navbar">'.
a0288610 688 '<a target="_blank" href="'.$CFG->wwwroot.'/course/view.php?id='.$course->id.'">'.$course->shortname.'</a> &raquo; '.
689 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/index.php?id='.$course->id.'">'.$strforums.'</a> &raquo; '.
690 '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'">'.format_string($forum->name,true).'</a>';
691 if ($discussion->name == $forum->name) {
692 $posthtml .= '</div>';
aaf7a9dc 693 } else {
a0288610 694 $posthtml .= ' &raquo; <a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$discussion->id.'">'.
695 format_string($discussion->name,true).'</a></div>';
aaf7a9dc 696 }
a0288610 697 $posthtml .= forum_make_mail_post($post, $userfrom, $userto, $course, false, $canreply, true, false);
698
699 if ($canunsubscribe) {
700 $posthtml .= '<br /><div class="unsubscribelink"><a href="'.$CFG->wwwroot.'/mod/forum/subscribe.php?id='.$forum->id.'">'.
701 get_string('unsubscribe', 'forum').'</a></div>';
702 }
703
f2379d2d 704 $posthtml .= '</body>';
705
a0288610 706 return $posthtml;
aaf7a9dc 707}
708
caadf009 709function forum_user_outline($course, $user, $mod, $forum) {
710
1f48942e 711 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
caadf009 712 $result->info = get_string("numposts", "forum", count($posts));
713
714 $lastpost = array_pop($posts);
715 $result->time = $lastpost->modified;
716 return $result;
717 }
718 return NULL;
719}
720
721
722function forum_user_complete($course, $user, $mod, $forum) {
723 global $CFG;
724
1f48942e 725 if ($posts = forum_get_user_posts($forum->id, $user->id)) {
caadf009 726 foreach ($posts as $post) {
e3ff14ca 727
f37da850 728 $post->forum = $forum->id;
497588fe 729 forum_print_post($post, $course->id, $ownpost=false, $reply=false, $link=false, $rate=false);
caadf009 730 }
731
732 } else {
41905731 733 echo "<p>".get_string("noposts", "forum")."</p>";
caadf009 734 }
caadf009 735}
736
0d6b9d4f 737function forum_print_overview($course, $cm,$lastaccess) {
738 global $USER, $CFG;
739 $forum = get_record("forum","id","$cm->instance");
740 $str = '<a title="'.get_string('forums').'" href="mod/forum/view.php?id='.$cm->id.'">'
741 .get_string('forum','forum').': '.$forum->name.'</a><br />';
742 if ($numnew = count_records_select("log","time > $lastaccess AND "
743 ." course = $course->id AND "
744 ." module = 'forum' AND cmid = $cm->id "
745 ." AND action LIKE 'add %' AND userid != $USER->id")) {
746 $str .= get_string('overviewnumpostssince','forum',$numnew)."<br />";
747 $p = 1;
748 }
125b1645 749 if ($CFG->forum_trackreadposts && forum_tp_can_track_forums($forum)) {
90558ec4 750 if (isset($forum->groupmode)) {
751 $groupmode = groupmode($course, $forum); /// Can do this because forum->groupmode is defined
752 } else {
753 $groupmode = NOGROUPS;
754 }
0d6b9d4f 755 $groupid = ($groupmode==SEPARATEGROUPS && !isteacheredit($course->id)) ? $currentgroup : false;
756 $unread = forum_tp_count_forum_posts($forum->id, $groupid) -
757 forum_tp_count_forum_read_records($USER->id, $forum->id, $groupid);
758 if ($unread > 0) {
759 $a->unread = $unread;
760 $str .= get_string('overviewnumunread','forum',$unread).'<br />';
761 $p = 1;
762 }
763 }
764 if (!empty($p)) {
765 echo $str;
766 }
767}
768
1b5910c4 769function forum_print_recent_activity($course, $isteacher, $timestart) {
65b0e537 770/// Given a course and a date, prints a summary of all the new
cc3655a2 771/// messages posted in the course since that date
772
3d891989 773 global $CFG;
caadf009 774
775 $heading = false;
776 $content = false;
777
8f7dc7f1 778 if (!$logs = get_records_select('log', 'time > \''.$timestart.'\' AND '.
779 'course = \''.$course->id.'\' AND '.
780 'module = \'forum\' AND '.
781 'action LIKE \'add %\' ', 'time ASC')){
1b5910c4 782 return false;
783 }
784
8f7dc7f1 785 $strftimerecent = get_string('strftimerecent');
dcde9f02 786
d05956ac 787 $isteacheredit = isteacheredit($course->id);
788 $mygroupid = mygroupid($course->id);
789
790 $groupmode = array(); /// To cache group modes
791
1b5910c4 792 foreach ($logs as $log) {
793 //Get post info, I'll need it later
ac1d9a22 794 if ($post = forum_get_post_from_log($log)) {
795 //Create a temp valid module structure (course,id)
796 $tempmod->course = $log->course;
797 $tempmod->id = $post->forum;
798 //Obtain the visible property from the instance
8f7dc7f1 799 $modvisible = instance_is_visible('forum', $tempmod);
ac1d9a22 800 }
d05956ac 801
ac1d9a22 802 //Only if the post exists and mod is visible
803 if ($post && $modvisible) {
804 /// Check whether this is for teachers only
8f7dc7f1 805 $teacheronly = '';
806 if ($post->forumtype == 'teacher') {
807 if ($isteacher) {
808 $teacheronly = 'class=\'teacheronly\'';
809 } else {
810 continue;
b91d6dcd 811 }
ac1d9a22 812 }
813 /// Check whether this is belongs to a discussion in a group that
814 /// should NOT be accessible to the current user
b91d6dcd 815
ac1d9a22 816 if (!$isteacheredit and $post->groupid != -1) { /// Editing teachers or open discussions
817 if (!isset($cm[$post->forum])) {
8f7dc7f1 818 $cm[$post->forum] = get_coursemodule_from_instance('forum', $post->forum, $course->id);
819 $groupmode[$post->forum] = groupmode($course, $cm[$post->forum]);
436a7cae 820 }
8f7dc7f1 821 if ($groupmode[$post->forum]) {
ac1d9a22 822 if ($mygroupid != $post->groupid) {
823 continue;
824 }
1b5910c4 825 }
caadf009 826 }
ac1d9a22 827
828 if (! $heading) {
8f7dc7f1 829 print_headline(get_string('newforumposts', 'forum').':');
ac1d9a22 830 $heading = true;
831 $content = true;
832 }
833 $date = userdate($post->modified, $strftimerecent);
8f7dc7f1 834
835 $subjectclass = ($log->action == 'add discussion') ? ' bold' : '';
836
a4f7aac1 837 echo '<div class="head'.$teacheronly.'">'.
838 '<div class="date">'.$date.'</div>'.
839 '<div class="name">'.fullname($post, $isteacher).'</div>'.
840 '</div>';
841 echo '<div class="info'.$subjectclass.'">';
8f7dc7f1 842 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/'.str_replace('&', '&amp;', $log->url).'">';
17dc3f3c 843 $post->subject = break_up_long_words(format_string($post->subject,true));
8f7dc7f1 844 echo $post->subject;
845 echo '</a>"</div>';
caadf009 846 }
847 }
1b5910c4 848
caadf009 849 return $content;
850}
851
852
853function forum_grades($forumid) {
854/// Must return an array of grades, indexed by user, and a max grade.
caadf009 855
4db9d14d 856 if (!$forum = get_record("forum", "id", $forumid)) {
857 return false;
858 }
859 if (!$forum->assessed) {
860 return false;
861 }
d6bdd9d5 862 $scalemenu = make_grades_menu($forum->scale);
02ebf404 863
864 $currentuser = 0;
865 $ratingsuser = array();
866
1f48942e 867 if ($ratings = forum_get_user_grades($forumid)) {
02ebf404 868 foreach ($ratings as $rating) { // Ordered by user
869 if ($currentuser and $rating->userid != $currentuser) {
870 if (!empty($ratingsuser)) {
d6bdd9d5 871 if ($forum->scale < 0) {
872 $return->grades[$currentuser] = forum_get_ratings_mean(0, $scalemenu, $ratingsuser);
873 $return->grades[$currentuser] .= "<br />".forum_get_ratings_summary(0, $scalemenu, $ratingsuser);
874 } else {
875 $total = 0;
876 $count = 0;
877 foreach ($ratingsuser as $ra) {
878 $total += $ra;
879 $count ++;
880 }
881 $return->grades[$currentuser] = format_float($total/$count, 2);
882 }
02ebf404 883 } else {
884 $return->grades[$currentuser] = "";
885 }
886 $ratingsuser = array();
caadf009 887 }
02ebf404 888 $ratingsuser[] = $rating->rating;
889 $currentuser = $rating->userid;
caadf009 890 }
02ebf404 891 if (!empty($ratingsuser)) {
d6bdd9d5 892 if ($forum->scale < 0) {
893 $return->grades[$currentuser] = forum_get_ratings_mean(0, $scalemenu, $ratingsuser);
894 $return->grades[$currentuser] .= "<br />".forum_get_ratings_summary(0, $scalemenu, $ratingsuser);
895 } else {
896 $total = 0;
897 $count = 0;
898 foreach ($ratingsuser as $ra) {
899 $total += $ra;
900 $count ++;
901 }
902 $return->grades[$currentuser] = format_float((float)$total/(float)$count, 2);
903 }
02ebf404 904 } else {
905 $return->grades[$currentuser] = "";
caadf009 906 }
907 } else {
908 $return->grades = array();
909 }
910
d6bdd9d5 911 if ($forum->scale < 0) {
912 $return->maxgrade = "";
913 } else {
914 $return->maxgrade = $forum->scale;
915 }
caadf009 916 return $return;
917}
918
05855091 919function forum_get_participants($forumid) {
920//Returns the users with data in one forum
65b0e537 921//(users with records in forum_subscriptions, forum_posts and forum_ratings, students)
05855091 922
923 global $CFG;
924
925 //Get students from forum_subscriptions
95e72c12 926 $st_subscriptions = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 927 FROM {$CFG->prefix}user u,
928 {$CFG->prefix}forum_subscriptions s
929 WHERE s.forum = '$forumid' and
65b0e537 930 u.id = s.userid");
05855091 931 //Get students from forum_posts
95e72c12 932 $st_posts = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 933 FROM {$CFG->prefix}user u,
934 {$CFG->prefix}forum_discussions d,
935 {$CFG->prefix}forum_posts p
936 WHERE d.forum = '$forumid' and
937 p.discussion = d.id and
938 u.id = p.userid");
939
940 //Get students from forum_ratings
95e72c12 941 $st_ratings = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 942 FROM {$CFG->prefix}user u,
943 {$CFG->prefix}forum_discussions d,
944 {$CFG->prefix}forum_posts p,
945 {$CFG->prefix}forum_ratings r
946 WHERE d.forum = '$forumid' and
947 p.discussion = d.id and
948 r.post = p.id and
949 u.id = r.userid");
950
951 //Add st_posts to st_subscriptions
952 if ($st_posts) {
953 foreach ($st_posts as $st_post) {
954 $st_subscriptions[$st_post->id] = $st_post;
955 }
956 }
957 //Add st_ratings to st_subscriptions
958 if ($st_ratings) {
959 foreach ($st_ratings as $st_rating) {
960 $st_subscriptions[$st_rating->id] = $st_rating;
961 }
962 }
963 //Return st_subscriptions array (it contains an array of unique users)
964 return ($st_subscriptions);
965}
caadf009 966
0f1a97c2 967function forum_scale_used ($forumid,$scaleid) {
968//This function returns if a scale is being used by one forum
65b0e537 969
0f1a97c2 970 $return = false;
65b0e537 971
0f1a97c2 972 $rec = get_record("forum","id","$forumid","scale","-$scaleid");
65b0e537 973
974 if (!empty($rec) && !empty($scaleid)) {
0f1a97c2 975 $return = true;
976 }
65b0e537 977
0f1a97c2 978 return $return;
979}
980
9fa49e22 981/// SQL FUNCTIONS ///////////////////////////////////////////////////////////
982
1f48942e 983function forum_get_post_full($postid) {
984/// Gets a post with all info ready for forum_print_post
77efef3e 985/// Most of these joins are just to get the forum id
1f48942e 986 global $CFG;
987
8fbdc992 988 return get_record_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture
6572ab71 989 FROM {$CFG->prefix}forum_posts p
990 LEFT JOIN {$CFG->prefix}forum_discussions d ON p.discussion = d.id
6572ab71 991 LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
992 WHERE p.id = '$postid'");
1f48942e 993}
994
77efef3e 995function forum_get_discussion_posts($discussion, $sort, $forumid) {
1f48942e 996/// Gets posts with all info ready for forum_print_post
77efef3e 997/// We pass forumid in because we always know it so no need to make a
998/// complicated join to find it out.
1f48942e 999 global $CFG;
1000
77efef3e 1001 return get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture
10426cef 1002 FROM {$CFG->prefix}forum_posts p
10426cef 1003 LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
65b0e537 1004 WHERE p.discussion = $discussion
10426cef 1005 AND p.parent > 0 $sort");
1f48942e 1006}
1007
77efef3e 1008function forum_get_child_posts($parent, $forumid) {
1f48942e 1009/// Gets posts with all info ready for forum_print_post
77efef3e 1010/// We pass forumid in because we always know it so no need to make a
1011/// complicated join to find it out.
1f48942e 1012 global $CFG;
1013
77efef3e 1014 return get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture
10426cef 1015 FROM {$CFG->prefix}forum_posts p
10426cef 1016 LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
65b0e537 1017 WHERE p.parent = '$parent'
1f48942e 1018 ORDER BY p.created ASC");
1019}
1020
1021
4f321bdb 1022function forum_search_posts($searchterms, $courseid, $page=0, $recordsperpage=50, &$totalcount, $groupid=0, $extrasql='') {
8b9c7aa0 1023/// Returns a list of posts found using an array of search terms
1024/// eg word +word -word
1025///
9fa49e22 1026 global $CFG;
855c0839 1027 require_once($CFG->libdir.'/searchlib.php');
e3ff14ca 1028
9fa49e22 1029 if (!isteacher($courseid)) {
1030 $notteacherforum = "AND f.type <> 'teacher'";
4cabd355 1031 $forummodule = get_record("modules", "name", "forum");
453b5314 1032 $onlyvisible = "AND d.forum = f.id AND f.id = cm.instance AND cm.visible = 1 AND cm.module = $forummodule->id";
1033 $onlyvisibletable = ", {$CFG->prefix}course_modules cm, {$CFG->prefix}forum f";
c7a5b3b1 1034 if ($groupid) {
1035 $separategroups = SEPARATEGROUPS;
4dca83a7 1036 $selectgroup = " AND ( NOT (cm.groupmode='$separategroups'".
1037 " OR (c.groupmode='$separategroups' AND c.groupmodeforce='1') )".
1038 " OR d.groupid = '$groupid')";
453b5314 1039 $selectcourse = " AND d.course = '$courseid' AND c.id='$courseid'";
1040 $coursetable = ", {$CFG->prefix}course c";
c7a5b3b1 1041 } else {
1042 $selectgroup = '';
453b5314 1043 $selectcourse = " AND d.course = '$courseid'";
1044 $coursetable = '';
c7a5b3b1 1045 }
9fa49e22 1046 } else {
1047 $notteacherforum = "";
c7a5b3b1 1048 $selectgroup = '';
4cabd355 1049 $onlyvisible = "";
1050 $onlyvisibletable = "";
453b5314 1051 $coursetable = '';
a702e657 1052 if ($courseid == SITEID && isadmin()) {
1053 $selectcourse = '';
1054 } else {
1055 $selectcourse = " AND d.course = '$courseid'";
1056 }
9fa49e22 1057 }
1058
e6ae4dc8 1059 $limit = sql_paging_limit($page, $recordsperpage);
97485d07 1060
63d99fcb 1061 /// Some differences in syntax for PostgreSQL
1062 if ($CFG->dbtype == "postgres7") {
a74f950c 1063 $LIKE = "ILIKE"; // case-insensitive
2b4c64e9 1064 $NOTLIKE = "NOT ILIKE"; // case-insensitive
1065 $REGEXP = "~*";
1066 $NOTREGEXP = "!~*";
b800ac5a 1067 } else {
a74f950c 1068 $LIKE = "LIKE";
2b4c64e9 1069 $NOTLIKE = "NOT LIKE";
a74f950c 1070 $REGEXP = "REGEXP";
2b4c64e9 1071 $NOTREGEXP = "NOT REGEXP";
c4c57597 1072 }
1073
b800ac5a 1074 $messagesearch = "";
855c0839 1075 $searchstring = "";
1076 // Need to concat these back together for parser to work.
1077 foreach($searchterms as $searchterm){
1078 if ($searchstring != "") {
1079 $searchstring .= " ";
63d99fcb 1080 }
855c0839 1081 $searchstring .= $searchterm;
b800ac5a 1082 }
1083
855c0839 1084 // We need to allow quoted strings for the search. The quotes *should* be stripped
1085 // by the parser, but this should be examined carefully for security implications.
1086 $searchstring = str_replace("\\\"","\"",$searchstring);
1087 $parser = new search_parser();
f99fcffe 1088 $lexer = new search_lexer($parser);
e6ae4dc8 1089
855c0839 1090 if ($lexer->parse($searchstring)) {
1091 $parsearray = $parser->get_parsed_array();
77ffdf4b 1092 $messagesearch = search_generate_SQL($parsearray,'p.message','p.subject','p.userid','u.id','u.firstname','u.lastname','p.modified', 'd.forum');
855c0839 1093 }
e3ff14ca 1094
65b0e537 1095 $selectsql = "{$CFG->prefix}forum_posts p,
1096 {$CFG->prefix}forum_discussions d,
453b5314 1097 {$CFG->prefix}user u $onlyvisibletable $coursetable
855c0839 1098 WHERE ($messagesearch)
65b0e537 1099 AND p.userid = u.id
453b5314 1100 AND p.discussion = d.id $selectcourse $notteacherforum $onlyvisible $selectgroup $extrasql";
65b0e537 1101
8b9c7aa0 1102 $totalcount = count_records_sql("SELECT COUNT(*) FROM $selectsql");
b800ac5a 1103
77efef3e 1104 return get_records_sql("SELECT p.*,d.forum, u.firstname,u.lastname,u.email,u.picture FROM
8b9c7aa0 1105 $selectsql ORDER BY p.modified DESC $limit");
9fa49e22 1106}
1107
63d99fcb 1108
9fa49e22 1109function forum_get_ratings($postid, $sort="u.firstname ASC") {
1110/// Returns a list of ratings for a particular post - sorted.
1111 global $CFG;
65b0e537 1112 return get_records_sql("SELECT u.*, r.rating, r.time
1113 FROM {$CFG->prefix}forum_ratings r,
9fa49e22 1114 {$CFG->prefix}user u
65b0e537 1115 WHERE r.post = '$postid'
1116 AND r.userid = u.id
9fa49e22 1117 ORDER BY $sort");
1118}
1119
3ecca1ee 1120function forum_get_unmailed_posts($starttime, $endtime) {
1f48942e 1121/// Returns a list of all new posts that have not been mailed yet
1122 global $CFG;
65b0e537 1123 return get_records_sql("SELECT p.*, d.course
1124 FROM {$CFG->prefix}forum_posts p,
1f48942e 1125 {$CFG->prefix}forum_discussions d
65b0e537 1126 WHERE p.mailed = 0
3ecca1ee 1127 AND p.created >= '$starttime'
1128 AND p.created < '$endtime'
c274b0e0 1129 AND p.discussion = d.id
1130 ORDER BY p.modified ASC");
1f48942e 1131}
1132
3ecca1ee 1133function forum_mark_old_posts_as_mailed($endtime) {
1134/// Marks posts before a certain time as being mailed already
1135 global $CFG;
c274b0e0 1136 return execute_sql("UPDATE {$CFG->prefix}forum_posts
1137 SET mailed = '1'
0362d553 1138 WHERE created < '$endtime' AND mailed ='0'");
3ecca1ee 1139}
1140
1f48942e 1141function forum_get_user_posts($forumid, $userid) {
1142/// Get all the posts for a user in a forum suitable for forum_print_post
1143 global $CFG;
1144
77efef3e 1145 return get_records_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture
65b0e537 1146 FROM {$CFG->prefix}forum f,
1147 {$CFG->prefix}forum_discussions d,
1148 {$CFG->prefix}forum_posts p,
1149 {$CFG->prefix}user u
1150 WHERE f.id = '$forumid'
1151 AND d.forum = f.id
1f48942e 1152 AND p.discussion = d.id
65b0e537 1153 AND p.userid = '$userid'
ebc3bd2b 1154 AND p.userid = u.id
1f48942e 1155 ORDER BY p.modified ASC");
1156}
1157
1158function forum_get_post_from_log($log) {
1159/// Given a log entry, return the forum post details for it.
1160 global $CFG;
1161
1162 if ($log->action == "add post") {
1163
8f7dc7f1 1164 return get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1165 u.firstname, u.lastname, u.email, u.picture
65b0e537 1166 FROM {$CFG->prefix}forum_discussions d,
1167 {$CFG->prefix}forum_posts p,
8f7dc7f1 1168 {$CFG->prefix}forum f,
65b0e537 1169 {$CFG->prefix}user u
1170 WHERE p.id = '$log->info'
1171 AND d.id = p.discussion
1172 AND p.userid = u.id
8f7dc7f1 1173 AND u.deleted <> '1'
1174 AND f.id = d.forum");
1f48942e 1175
1176
1177 } else if ($log->action == "add discussion") {
1178
8f7dc7f1 1179 return get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1180 u.firstname, u.lastname, u.email, u.picture
65b0e537 1181 FROM {$CFG->prefix}forum_discussions d,
1182 {$CFG->prefix}forum_posts p,
8f7dc7f1 1183 {$CFG->prefix}forum f,
65b0e537 1184 {$CFG->prefix}user u
1185 WHERE d.id = '$log->info'
1186 AND d.firstpost = p.id
1187 AND p.userid = u.id
8f7dc7f1 1188 AND u.deleted <> '1'
1189 AND f.id = d.forum");
1f48942e 1190 }
1191 return NULL;
1192}
1193
d05956ac 1194function forum_get_firstpost_from_discussion($discussionid) {
1195/// Given a discussion id, return the first post from the discussion
1196 global $CFG;
1197
1198 return get_record_sql("SELECT p.*
65b0e537 1199 FROM {$CFG->prefix}forum_discussions d,
d05956ac 1200 {$CFG->prefix}forum_posts p
65b0e537 1201 WHERE d.id = '$discussionid'
d05956ac 1202 AND d.firstpost = p.id ");
1203}
1204
1f48942e 1205
1206function forum_get_user_grades($forumid) {
1207/// Get all user grades for a forum
1208 global $CFG;
1209
ebc3bd2b 1210 return get_records_sql("SELECT r.id, p.userid, r.rating
65b0e537 1211 FROM {$CFG->prefix}forum_discussions d,
1212 {$CFG->prefix}forum_posts p,
1f48942e 1213 {$CFG->prefix}forum_ratings r
65b0e537 1214 WHERE d.forum = '$forumid'
1f48942e 1215 AND p.discussion = d.id
02ebf404 1216 AND r.post = p.id
1217 ORDER by p.userid ");
1f48942e 1218}
1219
1220
a48e8c4b 1221function forum_count_discussion_replies($forum='0', $course='0', $user='0') {
1222// Returns an array of counts of replies to each discussion (optionally in one forum or course and/or user)
1f48942e 1223 global $CFG;
1224
a48e8c4b 1225 $forumselect = $courseselect = $userselect = '';
1226
1f48942e 1227 if ($forum) {
1228 $forumselect = " AND d.forum = '$forum'";
a48e8c4b 1229 }
1230 if ($course) {
1231 $courseselect = " AND d.course = '$course'";
1232 }
1233 if ($user) {
1234 $userselect = " AND d.userid = '$user'";
1f48942e 1235 }
3599e487 1236 return get_records_sql("SELECT p.discussion, (count(*)) as replies, max(p.id) as lastpostid
65b0e537 1237 FROM {$CFG->prefix}forum_posts p,
1f48942e 1238 {$CFG->prefix}forum_discussions d
a48e8c4b 1239 WHERE p.parent > 0 $forumselect $courseselect $userselect
1c887009 1240 AND p.discussion = d.id
1f48942e 1241 GROUP BY p.discussion");
1242}
1243
1244function forum_count_unrated_posts($discussionid, $userid) {
1245// How many unrated posts are in the given discussion for a given user?
1246 global $CFG;
1247 if ($posts = get_record_sql("SELECT count(*) as num
1248 FROM {$CFG->prefix}forum_posts
65b0e537 1249 WHERE parent > 0
1250 AND discussion = '$discussionid'
ebc3bd2b 1251 AND userid <> '$userid' ")) {
1f48942e 1252
65b0e537 1253 if ($rated = get_record_sql("SELECT count(*) as num
1254 FROM {$CFG->prefix}forum_posts p,
1f48942e 1255 {$CFG->prefix}forum_ratings r
1256 WHERE p.discussion = '$discussionid'
65b0e537 1257 AND p.id = r.post
ebc3bd2b 1258 AND r.userid = '$userid'")) {
1f48942e 1259 $difference = $posts->num - $rated->num;
1260 if ($difference > 0) {
1261 return $difference;
1262 } else {
1263 return 0; // Just in case there was a counting error
1264 }
1265 } else {
1266 return $posts->num;
1267 }
1268 } else {
1269 return 0;
1270 }
1271}
1272
65b0e537 1273function forum_get_discussions($forum="0", $forumsort="d.timemodified DESC",
13597d01 1274 $user=0, $fullpost=true, $visiblegroups=-1, $limit=0, $userlastmodified=false) {
1f48942e 1275/// Get all discussions in a forum
1276 global $CFG;
1277
1278 if ($user) {
1279 $userselect = " AND u.id = '$user' ";
1280 } else {
1281 $userselect = "";
1282 }
2862b309 1283
90ec387a 1284 if ($limit) {
1285 $limit = " LIMIT $limit ";
1286 } else {
1287 $limit = "";
1288 }
8f0cd6ef 1289
2862b309 1290 if ($visiblegroups == -1) {
02509fe6 1291 $groupselect = "";
2862b309 1292 } else {
1293 $groupselect = " AND (d.groupid = '$visiblegroups' OR d.groupid = '-1') ";
02509fe6 1294 }
2862b309 1295
29507631 1296 if (empty($forumsort)) {
1297 $forumsort = "d.timemodified DESC";
1298 }
2ab968e9 1299 if (empty($fullpost)) {
b879effb 1300 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2ab968e9 1301 } else {
1302 $postdata = "p.*";
1303 }
9197e147 1304
13597d01 1305 if (empty($userlastmodified)) { // We don't need to know this
1306 $umfields = '';
1307 $umtable = '';
13597d01 1308 } else {
096de9ad 1309 $umfields = ', um.firstname AS umfirstname, um.lastname AS umlastname';
cfdc10e6 1310 $umtable = ' LEFT JOIN '.$CFG->prefix.'user um on (d.usermodified = um.id)';
13597d01 1311 }
1312
80d3523e 1313 //TODO: there must be a nice way to do this that keeps both postgres and mysql 3.2x happy but I can't find it right now.
1314 if ($CFG->dbtype == 'postgres7') {
1315 return get_records_sql("SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid,
13597d01 1316 u.firstname, u.lastname, u.email, u.picture $umfields
93d58b30 1317 FROM {$CFG->prefix}forum_discussions d
1318 JOIN {$CFG->prefix}forum_posts p ON p.discussion = d.id
1319 JOIN {$CFG->prefix}user u ON p.userid = u.id
13597d01 1320 $umtable
65b0e537 1321 WHERE d.forum = '$forum'
65b0e537 1322 AND p.parent = 0
93d58b30 1323 $groupselect $userselect
90ec387a 1324 ORDER BY $forumsort $limit");
80d3523e 1325 } else {
1326 return get_records_sql("SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid,
1327 u.firstname, u.lastname, u.email, u.picture $umfields
1328 FROM {$CFG->prefix}forum_discussions d,
1329 {$CFG->prefix}forum_posts p,
1330 {$CFG->prefix}user u
1331 $umtable
1332 WHERE d.forum = '$forum'
1333 AND p.discussion = d.id
1334 AND p.parent = 0
1335 AND p.userid = u.id $groupselect $userselect
1336 ORDER BY $forumsort $limit");
1337 }
1f48942e 1338}
1339
1340
1341
b656e2a9 1342function forum_get_user_discussions($courseid, $userid, $groupid=0) {
1343/// Get all discussions started by a particular user in a course (or group)
4f321bdb 1344/// This function no longer used ...
1f48942e 1345 global $CFG;
1346
b656e2a9 1347 if ($groupid) {
1348 $groupselect = " AND d.groupid = '$groupid' ";
1349 } else {
1350 $groupselect = "";
1351 }
1352
2862b309 1353 return get_records_sql("SELECT p.*, d.groupid, u.firstname, u.lastname, u.email, u.picture,
ebc3bd2b 1354 f.type as forumtype, f.name as forumname, f.id as forumid
65b0e537 1355 FROM {$CFG->prefix}forum_discussions d,
1356 {$CFG->prefix}forum_posts p,
1357 {$CFG->prefix}user u,
1f48942e 1358 {$CFG->prefix}forum f
65b0e537 1359 WHERE d.course = '$courseid'
1360 AND p.discussion = d.id
1361 AND p.parent = 0
1362 AND p.userid = u.id
1363 AND u.id = '$userid'
b656e2a9 1364 AND d.forum = f.id $groupselect
b8bf90c5 1365 ORDER BY p.created DESC");
1f48942e 1366}
1367
1368
6673d7bd 1369function forum_subscribed_users($course, $forum, $groupid=0) {
1f48942e 1370/// Returns list of user objects that are subscribed to this forum
1371 global $CFG;
1372
6673d7bd 1373 if ($groupid) {
1374 $grouptables = ", {$CFG->prefix}groups_members g";
1375 $groupselect = " AND g.groupid = '$groupid' AND u.id = g.userid";
1376 } else {
1377 $grouptables = "";
1378 $groupselect = "";
1379 }
1380
709f0ec8 1381 if (forum_is_forcesubscribed($forum->id)) {
7b5944cd 1382 if ($forum->type == "teacher") {
1383 return get_course_teachers($course->id); // Only teachers can be subscribed to teacher forums
adaf3928 1384 } else {
7b5944cd 1385 return get_course_users($course->id); // Otherwise get everyone in the course
1f48942e 1386 }
1387 }
aaf7a9dc 1388 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest, u.emailstop,
4822e9d2 1389 u.email, u.city, u.country, u.lastaccess, u.lastlogin, u.picture, u.timezone, u.lang, u.trackforums
65b0e537 1390 FROM {$CFG->prefix}user u,
6673d7bd 1391 {$CFG->prefix}forum_subscriptions s $grouptables
1f48942e 1392 WHERE s.forum = '$forum->id'
65b0e537 1393 AND s.userid = u.id
6673d7bd 1394 AND u.deleted <> 1 $groupselect
7c81b6e2 1395 ORDER BY u.email ASC");
1f48942e 1396}
9fa49e22 1397
067675c0 1398
1399
caadf009 1400/// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
f93f848a 1401
1402
11b0c469 1403function forum_get_course_forum($courseid, $type) {
1404// How to set up special 1-per-course forums
a6fcdf98 1405 global $CFG;
1406
29cbd93a 1407 if ($forums = get_records_select("forum", "course = '$courseid' AND type = '$type'", "id ASC")) {
65b0e537 1408 // There should always only be ONE, but with the right combination of
29cbd93a 1409 // errors there might be more. In this case, just return the oldest one (lowest ID).
1410 foreach ($forums as $forum) {
1411 return $forum; // ie the first one
11b0c469 1412 }
8daaf761 1413 }
e6874d9f 1414
8daaf761 1415 // Doesn't exist, so create one now.
1416 $forum->course = $courseid;
1417 $forum->type = "$type";
1418 switch ($forum->type) {
1419 case "news":
65a3ef30 1420 $forum->name = addslashes(get_string("namenews", "forum"));
1421 $forum->intro = addslashes(get_string("intronews", "forum"));
906fef94 1422 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
8daaf761 1423 $forum->open = 1; // 0 - no, 1 - posts only, 2 - discuss and post
1424 $forum->assessed = 0;
709f0ec8 1425 if ($courseid == SITEID) {
1426 $forum->name = get_string("sitenews");
1427 $forum->forcesubscribe = 0;
8f0cd6ef 1428 }
8daaf761 1429 break;
1430 case "social":
65a3ef30 1431 $forum->name = addslashes(get_string("namesocial", "forum"));
1432 $forum->intro = addslashes(get_string("introsocial", "forum"));
8daaf761 1433 $forum->open = 2; // 0 - no, 1 - posts only, 2 - discuss and post
1434 $forum->assessed = 0;
1435 $forum->forcesubscribe = 0;
1436 break;
1437 case "teacher":
65a3ef30 1438 $forum->name = addslashes(get_string("nameteacher", "forum"));
1439 $forum->intro = addslashes(get_string("introteacher", "forum"));
a796d0b8 1440 $forum->open = 2; // 0 - no, 1 - posts only, 2 - discuss and post
8daaf761 1441 $forum->assessed = 0;
1442 $forum->forcesubscribe = 0;
1443 break;
1444 default:
1445 notify("That forum type doesn't exist!");
1446 return false;
1447 break;
1448 }
1449
1450 $forum->timemodified = time();
1451 $forum->id = insert_record("forum", $forum);
1452
1453 if ($forum->type != "teacher") {
1454 if (! $module = get_record("modules", "name", "forum")) {
1455 notify("Could not find forum module!!");
1456 return false;
1457 }
1458 $mod->course = $courseid;
1459 $mod->module = $module->id;
1460 $mod->instance = $forum->id;
1461 $mod->section = 0;
1462 if (! $mod->coursemodule = add_course_module($mod) ) { // assumes course/lib.php is loaded
1463 notify("Could not add a new course module to the course '$course->fullname'");
1464 return false;
1465 }
1466 if (! $sectionid = add_mod_to_section($mod) ) { // assumes course/lib.php is loaded
1467 notify("Could not add the new course module to that section");
1468 return false;
1469 }
1470 if (! set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
1471 notify("Could not update the course module with the correct section");
1472 return false;
1473 }
1474 include_once("$CFG->dirroot/course/lib.php");
d769d2ee 1475 rebuild_course_cache($courseid);
82aa0e8d 1476 }
65b0e537 1477
8daaf761 1478 return get_record("forum", "id", "$forum->id");
82aa0e8d 1479}
1480
f93f848a 1481
65b0e537 1482function forum_make_mail_post(&$post, $user, $touser, $course,
11b0c469 1483 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
65b0e537 1484// Given the data about a posting, builds up the HTML to display it and
501cdbd8 1485// returns the HTML in a string. This is designed for sending via HTML email.
1486
d30867b0 1487 global $CFG;
501cdbd8 1488
0d851f90 1489 static $formattedtext; // Cached version of formatted text for a post
1490 static $formattedtextid; // The ID number of the post
1491
1492 if (empty($formattedtextid) or $formattedtextid != $post->id) { // Recalculate the formatting
326ce3c4 1493 $options = new Object;
1494 $options->para = true;
1495 $formattedtext = format_text($post->message, $post->format, $options, $course->id);
0d851f90 1496 $formattedtextid = $post->id;
1497 }
1498
add3201e 1499 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
501cdbd8 1500
add3201e 1501 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
501cdbd8 1502 $output .= print_user_picture($user->id, $course->id, $user->picture, false, true);
add3201e 1503 $output .= '</td>';
501cdbd8 1504
1505 if ($post->parent) {
add3201e 1506 $output .= '<td class="topic">';
501cdbd8 1507 } else {
add3201e 1508 $output .= '<td class="topic starter">';
501cdbd8 1509 }
add3201e 1510 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
1b26d5e7 1511
1512 $fullname = fullname($user, isteacher($course->id));
add3201e 1513 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1514 $by->date = userdate($post->modified, '', $touser->timezone);
1515 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
1516
1517 $output .= '</td></tr>';
1518
1519 $output .= '<tr><td class="left side">';
1520 if ($group = user_group($course->id, $user->id)) {
1521 $output .= print_group_picture($group, $courseid, false, true, true);
1522 } else {
1523 $output .= '&nbsp;';
1524 }
1b26d5e7 1525
add3201e 1526 $output .= '</td><td class="content">';
501cdbd8 1527
7f6689e4 1528 if ($post->attachment) {
1529 $post->course = $course->id;
add3201e 1530 $post->forum = get_field('forum_discussions', 'forum', 'id', $post->discussion);
1531 $output .= '<div class="attachments">';
1532 $output .= forum_print_attachments($post, 'html');
72d497d4 1533 $output .= "</div>";
7f6689e4 1534 }
1535
0d851f90 1536 $output .= $formattedtext;
501cdbd8 1537
add3201e 1538
1539/// Commands
1540
1541 $commands = array();
501cdbd8 1542
2e2e71a8 1543 if ($post->parent) {
add3201e 1544 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1545 $post->discussion.'&amp;parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
2e2e71a8 1546 }
ce45515e 1547
501cdbd8 1548 if ($ownpost) {
add3201e 1549 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?delete='.$post->id.'">'.
1550 get_string('delete', 'forum').'</a>';
1551 }
1552
1553 if ($reply) {
1554 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
1555 get_string('reply', 'forum').'</a>';
501cdbd8 1556 }
1557
add3201e 1558 $output .= '<div class="commands">';
1559 $output .= implode(' | ', $commands);
1560 $output .= '</div>';
1561
1562
1563/// Context link to post if required
65b0e537 1564
501cdbd8 1565 if ($link) {
add3201e 1566 $output .= '<div class="link">';
77e75a76 1567 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#'.$post->id.'">'.
add3201e 1568 get_string('postincontext', 'forum').'</a>';
1569 $output .= '</div>';
501cdbd8 1570 }
add3201e 1571
501cdbd8 1572 if ($footer) {
add3201e 1573 $output .= '<div class="footer">'.$footer.'</div>';
501cdbd8 1574 }
add3201e 1575 $output .= '</td></tr></table>'."\n\n";
1576
501cdbd8 1577
1578 return $output;
1579}
1580
1581
65b0e537 1582function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link=false,
f37da850 1583 $ratings=NULL, $footer="", $highlight="", $post_read=-99) {
74f5d1e3 1584
d30867b0 1585 global $USER, $CFG;
501cdbd8 1586
359f2758 1587 static $stredit, $strdelete, $strreply, $strparent, $strprune, $strpruneheading, $threadedmode, $isteacher, $adminedit;
2e2e71a8 1588
77efef3e 1589 static $strmarkread, $strmarkunread, $istracked;
f37da850 1590
2e2e71a8 1591 if (empty($stredit)) {
359f2758 1592 $stredit = get_string('edit', 'forum');
1593 $strdelete = get_string('delete', 'forum');
1594 $strreply = get_string('reply', 'forum');
1595 $strparent = get_string('parent', 'forum');
1596 $strpruneheading = get_string('pruneheading', 'forum');
d494dd83 1597 $strprune = get_string('prune', 'forum');
2e2e71a8 1598 $threadedmode = (!empty($USER->mode) and ($USER->mode == FORUM_MODE_THREADED));
3bd98ad4 1599 $isteacher = isteacher($courseid);
b8be40ce 1600 $adminedit = (isadmin() and !empty($CFG->admineditalways));
f37da850 1601 $strmarkread = get_string('markread', 'forum');
1602 $strmarkunread = get_string('markunread', 'forum');
77efef3e 1603
1604 if (!empty($post->forum)) {
1605 $istracked = (forum_tp_can_track_forums($post->forum) &&
1606 forum_tp_is_tracked($post->forum));
1607 } else {
1608 $istracked = false;
1609 }
f37da850 1610 }
1611
eaf50aef 1612 if ($istracked) {
f37da850 1613 if ($post_read == -99) { // If we don't know yet...
489de4ae 1614 /// The front page can display a news item post to non-logged in users. This should
1615 /// always appear as 'read'.
1616 $post_read = empty($USER) || forum_tp_is_post_read($USER->id, $post);
f37da850 1617 }
1618 if ($post_read) {
1619 $read_style = ' read';
1620 } else {
1621 $read_style = ' unread';
1622 echo '<a name="unread"></a>';
1623 }
1624 } else {
1625 $read_style = '';
2e2e71a8 1626 }
1627
f37da850 1628 echo '<a name="'.$post->id.'"></a>';
33200577 1629 echo '<table cellspacing="0" class="forumpost'.$read_style.'">';
501cdbd8 1630
d3583b41 1631 echo '<tr class="header"><td class="picture left">';
501cdbd8 1632 print_user_picture($post->userid, $courseid, $post->picture);
d3583b41 1633 echo '</td>';
501cdbd8 1634
1635 if ($post->parent) {
d3583b41 1636 echo '<td class="topic">';
501cdbd8 1637 } else {
d3583b41 1638 echo '<td class="topic starter">';
501cdbd8 1639 }
83ec9098 1640
d3583b41 1641 echo '<div class="subject">'.$post->subject.'</div>';
e3ff14ca 1642
d3583b41 1643 echo '<div class="author">';
3bd98ad4 1644 $fullname = fullname($post, $isteacher);
d3583b41 1645 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
1646 $post->userid.'&amp;course='.$courseid.'">'.$fullname.'</a>';
d62413e8 1647 $by->date = userdate($post->modified);
d3583b41 1648 print_string('bynameondate', 'forum', $by);
1649 echo '</div></td></tr>';
1b26d5e7 1650
d3583b41 1651 echo '<tr><td class="left side">';
507407a7 1652 if ($group = user_group($courseid, $post->userid)) {
a4fbb0b2 1653 print_group_picture($group, $courseid, false, false, true);
507407a7 1654 } else {
d3583b41 1655 echo '&nbsp;';
507407a7 1656 }
d3583b41 1657
1658/// Actual content
1659
1660 echo '</td><td class="content">'."\n";
501cdbd8 1661
7f6689e4 1662 if ($post->attachment) {
1663 $post->course = $courseid;
d3583b41 1664 $post->forum = get_field('forum_discussions', 'forum', 'id', $post->discussion);
1665 echo '<div class="attachments">';
72d497d4 1666 $attachedimages = forum_print_attachments($post);
d3583b41 1667 echo '</div>';
e9c2dc1f 1668 } else {
d3583b41 1669 $attachedimages = '';
7f6689e4 1670 }
1671
d3583b41 1672
326ce3c4 1673 $options = new Object;
1674 $options->para = false;
5be7800c 1675 if ($link and (strlen(strip_tags($post->message)) > $CFG->forum_longpost)) {
aa153f29 1676 // Print shortened version
326ce3c4 1677 echo format_text(forum_shorten_post($post->message), $post->format, $options, $courseid);
c585fa17 1678 $numwords = count_words(strip_tags($post->message));
d3583b41 1679 echo '<p><a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1680 echo get_string('readtherest', 'forum');
1681 echo '</a> ('.get_string('numwords', '', $numwords).')...</p>';
501cdbd8 1682 } else {
aa153f29 1683 // Print whole message
88438a58 1684 if ($highlight) {
326ce3c4 1685 echo highlight($highlight, format_text($post->message, $post->format, $options, $courseid));
88438a58 1686 } else {
326ce3c4 1687 echo format_text($post->message, $post->format, $options, $courseid);
88438a58 1688 }
65b0e537 1689 echo $attachedimages;
501cdbd8 1690 }
1691
d3583b41 1692
1693/// Commands
1694
359f2758 1695 $commands = array();
501cdbd8 1696
eaf50aef 1697 if ($istracked) {
489de4ae 1698 /// SPECIAL CASE: The front page can display a news item post to non-logged in users.
1699 /// Don't display the mark read / unread controls in this case.
1700 if ($CFG->forum_usermarksread && !empty($USER)) {
f37da850 1701 if ($post_read) {
1702 $mcmd = '&amp;mark=unread&amp;postid='.$post->id;
1703 $mtxt = $strmarkunread;
1704 } else {
1705 $mcmd = '&amp;mark=read&amp;postid='.$post->id;
1706 $mtxt = $strmarkread;
1707 }
1708 if ($threadedmode) {
d3583b41 1709 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1710 $post->discussion.'&amp;parent='.$post->id.$mcmd.'">'.$mtxt.'</a>';
f37da850 1711 } else {
d3583b41 1712 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1713 $post->discussion.$mcmd.'#'.$post->id.'">'.$mtxt.'</a>';
f37da850 1714 }
1715 }
1716 }
1717
2e2e71a8 1718 if ($post->parent) {
1719 if ($threadedmode) {
d3583b41 1720 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1721 $post->discussion.'&amp;parent='.$post->parent.'">'.$strparent.'</a>';
2e2e71a8 1722 } else {
d3583b41 1723 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1724 $post->discussion.'#'.$post->parent.'">'.$strparent.'</a>';
2e2e71a8 1725 }
1726 }
1727
501cdbd8 1728 $age = time() - $post->created;
b8be40ce 1729 if ($ownpost or $adminedit) {
1730 if (($age < $CFG->maxeditingtime) or $adminedit) {
d3583b41 1731 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?edit='.$post->id.'">'.$stredit.'</a>';
501cdbd8 1732 }
64eacd6f 1733 }
aaf7a9dc 1734
cf84431b 1735 if (isteacheredit($courseid) and $post->parent) {
d3583b41 1736 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?prune='.$post->id.
1737 '" title="'.$strpruneheading.'">'.$strprune.'</a>';
cf84431b 1738 }
aaf7a9dc 1739
ac00b904 1740 if (($ownpost and $age < $CFG->maxeditingtime) or $isteacher) {
d3583b41 1741 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?delete='.$post->id.'">'.$strdelete.'</a>';
64eacd6f 1742 }
359f2758 1743
64eacd6f 1744 if ($reply) {
d3583b41 1745 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.$strreply.'</a>';
501cdbd8 1746 }
501cdbd8 1747
d3583b41 1748 echo '<div class="commands">';
1749 echo implode(' | ', $commands);
1750 echo '</div>';
1751
1752
1753/// Ratings
74f5d1e3 1754
1755 $ratingsmenuused = false;
02ebf404 1756 if (!empty($ratings) and !empty($USER->id)) {
d3583b41 1757 echo '<div class="ratings">';
98914efd 1758 $useratings = true;
1759 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
1760 if ($post->created < $ratings->assesstimestart or $post->created > $ratings->assesstimefinish) {
1761 $useratings = false;
1762 }
1763 }
1764 if ($useratings) {
3bd98ad4 1765 $mypost = ($USER->id == $post->userid);
1766
1767 if (($isteacher or $ratings->assesspublic) and !$mypost) {
1768 forum_print_ratings_mean($post->id, $ratings->scale, $isteacher);
d395046a 1769 if (!empty($ratings->allow)) {
d3583b41 1770 echo '&nbsp;';
d395046a 1771 forum_print_rating_menu($post->id, $USER->id, $ratings->scale);
1772 $ratingsmenuused = true;
1773 }
3bd98ad4 1774
1775 } else if ($mypost) {
1776 forum_print_ratings_mean($post->id, $ratings->scale, true);
1777
98914efd 1778 } else if (!empty($ratings->allow) ) {
1779 forum_print_rating_menu($post->id, $USER->id, $ratings->scale);
74f5d1e3 1780 $ratingsmenuused = true;
2a3cda19 1781 }
501cdbd8 1782 }
d3583b41 1783 echo '</div>';
501cdbd8 1784 }
65b0e537 1785
d3583b41 1786/// Link to post if required
1787
501cdbd8 1788 if ($link) {
d3583b41 1789 echo '<div class="link">';
501cdbd8 1790 if ($post->replies == 1) {
d3583b41 1791 $replystring = get_string('repliesone', 'forum', $post->replies);
501cdbd8 1792 } else {
d3583b41 1793 $replystring = get_string('repliesmany', 'forum', $post->replies);
501cdbd8 1794 }
d3583b41 1795 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.
1796 get_string('discussthistopic', 'forum').'</a>&nbsp;('.$replystring.')';
1797 echo '</div>';
501cdbd8 1798 }
d3583b41 1799
501cdbd8 1800 if ($footer) {
d3583b41 1801 echo '<div class="footer">'.$footer.'</div>';
501cdbd8 1802 }
d3583b41 1803 echo '</td></tr></table>'."\n\n";
74f5d1e3 1804
eaf50aef 1805 if ($istracked && !$CFG->forum_usermarksread && !empty($post->forum)) {
f37da850 1806 forum_tp_mark_post_read($USER->id, $post, $post->forum);
1807 }
1808
74f5d1e3 1809 return $ratingsmenuused;
501cdbd8 1810}
eaf50aef 1811/**
1812* This function prints the overview of a discussion in the forum listing.
1813* It needs some discussion information and some post information, these
1814* happen to be combined for efficiency in the $post parameter by the function
1815* that calls this one: forum_print_latest_discussions()
1816*
1817* @param object $post The post object (passed by reference for speed).
1818* @param object $forum The forum object.
1819* @param int $group Current group.
1820* @param string $datestring Format to use for the dates.
1821* @param boolean $cantrack Is tracking enabled for this forum.
1822* @param boolean $forumtracked Is the user tracking this forum.
1823*/
1824function forum_print_discussion_header(&$post, $forum, $group=-1, $datestring="", $cantrack=true, $forumtracked=true) {
43921b8a 1825
d30867b0 1826 global $USER, $CFG;
3335f6fb 1827
f51e8d7e 1828 static $rowcount;
5733262d 1829 static $strmarkalldread;
f51e8d7e 1830
1831 if (!isset($rowcount)) {
1832 $rowcount = 0;
5733262d 1833 $strmarkalldread = get_string('markalldread', 'forum');
f51e8d7e 1834 } else {
1835 $rowcount = ($rowcount + 1) % 2;
1836 }
1837
17dc3f3c 1838 $post->subject = format_string($post->subject,true);
436a7cae 1839
f51e8d7e 1840 echo "\n\n";
1841 echo '<tr class="discussion r'.$rowcount.'">';
3335f6fb 1842
29507631 1843 // Topic
f51e8d7e 1844 echo '<td class="topic starter">';
1845 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
29507631 1846 echo "</td>\n";
1847
1848 // Picture
f51e8d7e 1849 echo '<td class="picture">';
a796d0b8 1850 print_user_picture($post->userid, $forum->course, $post->picture);
29507631 1851 echo "</td>\n";
3335f6fb 1852
29507631 1853 // User name
a796d0b8 1854 $fullname = fullname($post, isteacher($forum->course));
f51e8d7e 1855 echo '<td class="author">';
1856 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
29507631 1857 echo "</td>\n";
1858
3a68fbbb 1859 // Group picture
425b4f1a 1860 if ($group !== -1) { // Groups are active - group is a group data object or NULL
f51e8d7e 1861 echo '<td class="picture group">';
c2b552fe 1862 if (!empty($group->picture) and empty($group->hidepicture)) {
3a68fbbb 1863 print_group_picture($group, $forum->course, false, false, true);
1864 } else if (isset($group->id)) {
1865 echo '<a href="'.$CFG->wwwroot.'/course/group.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
1866 }
1867 echo "</td>\n";
1868 }
1869
f51e8d7e 1870 if ($forum->open or $forum->type == 'teacher') { // Show the column with replies
1871 echo '<td class="replies">';
1872 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1873 echo $post->replies.'</a>';
a796d0b8 1874 echo "</td>\n";
e3ff14ca 1875
eaf50aef 1876 if ($cantrack) {
f51e8d7e 1877 echo '<td class="replies">';
eaf50aef 1878 if ($forumtracked) {
1879 if ($post->unread > 0) {
1880 echo '<span class="unread">';
1881 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
1882 echo $post->unread;
1883 echo '</a>';
c39748f4 1884 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
eaf50aef 1885 $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;returnpage=view.php">' .
fee287f3 1886 '<img src="'.$CFG->pixpath.'/t/clear.gif" height="11" width="11" /></a>';
eaf50aef 1887 echo '</span>';
1888 } else {
1889 echo '<span class="read">';
1890 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
1891 echo $post->unread;
1892 echo '</a>';
1893 echo '</span>';
1894 }
f51e8d7e 1895 } else {
343af274 1896 echo '<span class="read">';
eaf50aef 1897 echo '-';
343af274 1898 echo '</span>';
3a68fbbb 1899 }
f37da850 1900 echo "</td>\n";
1901 }
a796d0b8 1902 }
3335f6fb 1903
f51e8d7e 1904 echo '<td class="lastpost">';
43921b8a 1905 $usedate = (empty($post->timemodified)) ? $post->modified : $post->timemodified; // Just in case
839f2456 1906 $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
268c6485 1907 $usermodified->firstname = $post->umfirstname;
1908 $usermodified->lastname = $post->umlastname;
f51e8d7e 1909 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
1910 fullname($usermodified).'</a><br />';
ac00b904 1911 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
43921b8a 1912 userdate($usedate, $datestring).'</a>';
29507631 1913 echo "</td>\n";
1914
f51e8d7e 1915 echo "</tr>\n\n";
3335f6fb 1916
3335f6fb 1917}
1918
1919
aa153f29 1920function forum_shorten_post($message) {
c585fa17 1921// Given a post object that we already know has a long message
65b0e537 1922// this function truncates the message nicely to the first
5be7800c 1923// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
1924
1925 global $CFG;
c585fa17 1926
1927 $i = 0;
1928 $tag = false;
1929 $length = strlen($message);
1930 $count = 0;
1931 $stopzone = false;
1932 $truncate = 0;
1933
1934 for ($i=0; $i<$length; $i++) {
a8afb411 1935 $char = $message[$i];
c585fa17 1936
1937 switch ($char) {
65b0e537 1938 case "<":
c585fa17 1939 $tag = true;
1940 break;
65b0e537 1941 case ">":
c585fa17 1942 $tag = false;
1943 break;
1944 default:
1945 if (!$tag) {
1946 if ($stopzone) {
67f0b4cc 1947 if ($char == ".") {
a8afb411 1948 $truncate = $i+1;
c585fa17 1949 break 2;
1950 }
1951 }
1952 $count++;
1953 }
a8afb411 1954 break;
c585fa17 1955 }
1956 if (!$stopzone) {
5be7800c 1957 if ($count > $CFG->forum_shortpost) {
c585fa17 1958 $stopzone = true;
1959 }
1960 }
1961 }
aa153f29 1962
c585fa17 1963 if (!$truncate) {
a8afb411 1964 $truncate = $i;
c585fa17 1965 }
1966
67f0b4cc 1967 return substr($message, 0, $truncate);
aa153f29 1968}
1969
501cdbd8 1970
3bd98ad4 1971function forum_print_ratings_mean($postid, $scale, $link=true) {
02ebf404 1972/// Print the multiple ratings on a post given to the current user by others.
1973/// Scale is an array of ratings
1974
1975 static $strrate;
05c47ef7 1976
1977 $mean = forum_get_ratings_mean($postid, $scale);
65b0e537 1978
05c47ef7 1979 if ($mean !== "") {
02ebf404 1980
1981 if (empty($strratings)) {
1982 $strratings = get_string("ratings", "forum");
501cdbd8 1983 }
501cdbd8 1984
02ebf404 1985 echo "$strratings: ";
3bd98ad4 1986 if ($link) {
1987 link_to_popup_window ("/mod/forum/report.php?id=$postid", "ratings", $mean, 400, 600);
1988 } else {
1989 echo "$mean ";
1990 }
501cdbd8 1991 }
1992}
1993
501cdbd8 1994
0761d83f 1995function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
1996/// Return the mean rating of a post given to the current user by others.
02ebf404 1997/// Scale is an array of possible ratings in the scale
1998/// Ratings is an optional simple array of actual ratings (just integers)
1999
2000 if (!$ratings) {
2001 $ratings = array();
2002 if ($rates = get_records("forum_ratings", "post", $postid)) {
2003 foreach ($rates as $rate) {
2004 $ratings[] = $rate->rating;
2005 }
501cdbd8 2006 }
501cdbd8 2007 }
02ebf404 2008
0761d83f 2009 $count = count($ratings);
2010
2011 if ($count == 0) {
02ebf404 2012 return "";
02ebf404 2013
0761d83f 2014 } else if ($count == 1) {
2015 return $scale[$ratings[0]];
2016
02ebf404 2017 } else {
0761d83f 2018 $total = 0;
2019 foreach ($ratings as $rating) {
2020 $total += $rating;
2021 }
2022 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
65b0e537 2023
0761d83f 2024 if (isset($scale[$mean])) {
2025 return $scale[$mean]." ($count)";
2026 } else {
2027 return "$mean ($count)"; // Should never happen, hopefully
2028 }
02ebf404 2029 }
2030}
2031
2032function forum_get_ratings_summary($postid, $scale, $ratings=NULL) {
2033/// Return a summary of post ratings given to the current user by others.
2034/// Scale is an array of possible ratings in the scale
2035/// Ratings is an optional simple array of actual ratings (just integers)
2036
2037 if (!$ratings) {
2038 $ratings = array();
2039 if ($rates = get_records("forum_ratings", "post", $postid)) {
2040 foreach ($rates as $rate) {
2041 $rating[] = $rate->rating;
2042 }
2043 }
2044 }
2045
2046
2047 if (!$count = count($ratings)) {
2048 return "";
2049 }
2050
2051
2052 foreach ($scale as $key => $scaleitem) {
2053 $sumrating[$key] = 0;
2054 }
2055
2056 foreach ($ratings as $rating) {
2057 $sumrating[$rating]++;
2058 }
2059
2060 $summary = "";
2061 foreach ($scale as $key => $scaleitem) {
2062 $summary = $sumrating[$key].$summary;
2063 if ($key > 1) {
2064 $summary = "/$summary";
2065 }
2066 }
2067 return $summary;
2068}
2069
2070function forum_print_rating_menu($postid, $userid, $scale) {
65b0e537 2071/// Print the menu of ratings as part of a larger form.
02ebf404 2072/// If the post has already been - set that value.
2073/// Scale is an array of ratings
2074
2075 static $strrate;
2076
2077 if (!$rating = get_record("forum_ratings", "userid", $userid, "post", $postid)) {
2078 $rating->rating = 0;
2079 }
2080
2081 if (empty($strrate)) {
2082 $strrate = get_string("rate", "forum");
2083 }
2084
2085 choose_from_menu($scale, $postid, $rating->rating, "$strrate...");
501cdbd8 2086}
2087
7a12aab4 2088function forum_print_mode_form($discussion, $mode) {
2089 GLOBAL $FORUM_LAYOUT_MODES;
501cdbd8 2090
839f2456 2091 echo "<div align=\"center\">";
2092 popup_form("discuss.php?d=$discussion&amp;mode=", $FORUM_LAYOUT_MODES, "mode", $mode, "");
2093 echo "</div>\n";
501cdbd8 2094}
2095
6f1cc8d6 2096function forum_search_form($course, $search='') {
501cdbd8 2097 global $CFG;
2098
6f1cc8d6 2099 $output = '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
2100 $output .= helpbutton('search', get_string('search'), 'moodle', true, false, '', true);
2101 $output .= '&nbsp;<form name="search" action="'.$CFG->wwwroot.'/mod/forum/search.php" style="display:inline">';
2102 $output .= '<input name="search" type="text" size="18" value="'.$search.'" alt="search" />';
2103 $output .= '<input value="'.get_string('searchforums', 'forum').'" type="submit" />';
2104 $output .= '<input name="id" type="hidden" value="'.$course->id.'" />';
2105 $output .= '</form>';
2106 $output .= '</td></tr></table>';
5e367a2d 2107
6f1cc8d6 2108 return $output;
501cdbd8 2109}
2110
2111
11b0c469 2112function forum_set_return() {
607809b3 2113 global $CFG, $SESSION;
501cdbd8 2114
28e1e8b9 2115 if (! isset($SESSION->fromdiscussion)) {
48d38fad 2116 if (!empty($_SERVER['HTTP_REFERER'])) {
2117 $referer = $_SERVER['HTTP_REFERER'];
2118 } else {
2119 $referer = "";
2120 }
28e1e8b9 2121 // If the referer is NOT a login screen then save it.
48d38fad 2122 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
607809b3 2123 $SESSION->fromdiscussion = $_SERVER["HTTP_REFERER"];
28e1e8b9 2124 }
501cdbd8 2125 }
2126}
2127
2128
11b0c469 2129function forum_go_back_to($default) {
501cdbd8 2130 global $SESSION;
2131
9c9f7d77 2132 if (!empty($SESSION->fromdiscussion)) {
501cdbd8 2133 $returnto = $SESSION->fromdiscussion;
2134 unset($SESSION->fromdiscussion);
2135 return $returnto;
2136 } else {
2137 return $default;
2138 }
2139}
2140
7f6689e4 2141function forum_file_area_name($post) {
2142// Creates a directory file name, suitable for make_upload_directory()
2143 global $CFG;
2144
2145 return "$post->course/$CFG->moddata/forum/$post->forum/$post->id";
2146}
2147
2148function forum_file_area($post) {
2149 return make_upload_directory( forum_file_area_name($post) );
2150}
2151
2152function forum_delete_old_attachments($post, $exception="") {
2153// Deletes all the user files in the attachments area for a post
2154// EXCEPT for any file named $exception
2155
2156 if ($basedir = forum_file_area($post)) {
2157 if ($files = get_directory_list($basedir)) {
2158 foreach ($files as $file) {
2159 if ($file != $exception) {
2160 unlink("$basedir/$file");
2161 notify("Existing file '$file' has been deleted!");
2162 }
2163 }
2164 }
2165 if (!$exception) { // Delete directory as well, if empty
2166 rmdir("$basedir");
2167 }
2168 }
2169}
2170
cc2b7ea5 2171function forum_move_attachments($discussion, $forumid) {
65b0e537 2172/// Given a discussion object that is being moved to forumid,
2173/// this function checks all posts in that discussion
2174/// for attachments, and if any are found, these are
cc2b7ea5 2175/// moved to the new forum directory.
2176
2177 global $CFG;
2178
18b8fbfa 2179 require_once($CFG->dirroot.'/lib/uploadlib.php');
2180
cc2b7ea5 2181 $return = true;
2182
2183 if ($posts = get_records_select("forum_posts", "discussion = '$discussion->id' AND attachment <> ''")) {
2184 foreach ($posts as $oldpost) {
2185 $oldpost->course = $discussion->course;
2186 $oldpost->forum = $discussion->forum;
2187 $oldpostdir = "$CFG->dataroot/".forum_file_area_name($oldpost);
2188 if (is_dir($oldpostdir)) {
2189 $newpost = $oldpost;
2190 $newpost->forum = $forumid;
7f0c3a44 2191 $newpostdir = forum_file_area($newpost);
18b8fbfa 2192 $files = get_directory_list($oldpostdir); // get it before we rename it.
cc2b7ea5 2193 if (! @rename($oldpostdir, $newpostdir)) {
2194 $return = false;
2195 }
18b8fbfa 2196 foreach ($files as $file) {
2197 clam_change_log($oldpostdir.'/'.$file,$newpostdir.'/'.$file);
2198 }
cc2b7ea5 2199 }
2200 }
2201 }
2202 return $return;
2203}
2204
7f6689e4 2205function forum_print_attachments($post, $return=NULL) {
2206// if return=html, then return a html string.
2207// if return=text, then return a text-only string.
72d497d4 2208// otherwise, print HTML for non-images, and return image HTML
7f6689e4 2209
2210 global $CFG;
2211
2212 $filearea = forum_file_area_name($post);
2213
72d497d4 2214 $imagereturn = "";
2215 $output = "";
2216
7f6689e4 2217 if ($basedir = forum_file_area($post)) {
2218 if ($files = get_directory_list($basedir)) {
2219 $strattachment = get_string("attachment", "forum");
2220 foreach ($files as $file) {
2221 $icon = mimeinfo("icon", $file);
2222 if ($CFG->slasharguments) {
2a1975cb 2223 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
7f6689e4 2224 } else {
2a1975cb 2225 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
7f6689e4 2226 }
2a1975cb 2227 $image = "<img border=\"0\" src=\"$CFG->pixpath/f/$icon\" height=\"16\" width=\"16\" alt=\"\" />";
7f6689e4 2228
2229 if ($return == "html") {
2a1975cb 2230 $output .= "<a href=\"$ffurl\">$image</a> ";
2231 $output .= "<a href=\"$ffurl\">$file</a><br />";
7f6689e4 2232
2233 } else if ($return == "text") {
2a1975cb 2234 $output .= "$strattachment $file:\n$ffurl\n";
7f6689e4 2235
2236 } else {
72d497d4 2237 if ($icon == "image.gif") { // Image attachments don't get printed as links
2a1975cb 2238 $imagereturn .= "<br /><img src=\"$ffurl\" alt=\"\" />";
72d497d4 2239 } else {
2a1975cb 2240 echo "<a href=\"$ffurl\">$image</a> ";
2241 echo "<a href=\"$ffurl\">$file</a><br />";
72d497d4 2242 }
7f6689e4 2243 }
2244 }
2245 }
2246 }
72d497d4 2247
7f6689e4 2248 if ($return) {
2249 return $output;
2250 }
72d497d4 2251
2252 return $imagereturn;
7f6689e4 2253}
db290a6e 2254/**
e3ff14ca 2255 * If successful, this function returns the name of the file
db290a6e 2256 * @param $post is a full post record, including course and forum
2257 * @param $newfile is a full upload array from $_FILES
2258 * @param $message is a string to hold the messages.
e3ff14ca 2259 */
7f6689e4 2260
db290a6e 2261function forum_add_attachment($post, $inputname,&$message) {
7f6689e4 2262
9dd0b378 2263 global $CFG;
2264
4909e176 2265 if (!$forum = get_record("forum", "id", $post->forum)) {
2266 return "";
2267 }
2268
2269 if (!$course = get_record("course", "id", $forum->course)) {
2270 return "";
2271 }
2272
5ddaa2e2 2273 require_once($CFG->dirroot.'/lib/uploadlib.php');
db290a6e 2274 $um = new upload_manager($inputname,true,false,$course,false,$forum->maxbytes,true,true);
5ddaa2e2 2275 $dir = forum_file_area_name($post);
2276 if ($um->process_file_uploads($dir)) {
db290a6e 2277 $message .= $um->get_errors();
5ddaa2e2 2278 return $um->get_new_filename();
7f6689e4 2279 }
db290a6e 2280 $message .= $um->get_errors();
7f6689e4 2281}
501cdbd8 2282
db290a6e 2283function forum_add_new_post($post,&$message) {
501cdbd8 2284
f37da850 2285 global $USER, $CFG;
e3ff14ca 2286
ffe11640 2287 $post->created = $post->modified = time();
501cdbd8 2288 $post->mailed = "0";
a56f0d60 2289 $post->userid = $USER->id;
7f6689e4 2290 $post->attachment = "";
2291
65b0e537 2292 if (! $post->id = insert_record("forum_posts", $post)) {
7f6689e4 2293 return false;
2294 }
2295
db290a6e 2296 if ($post->attachment = forum_add_attachment($post, 'attachment',$message)) {
7f6689e4 2297 set_field("forum_posts", "attachment", $post->attachment, "id", $post->id);
2298 }
29507631 2299
2300 // Update discussion modified date
2301 set_field("forum_discussions", "timemodified", $post->modified, "id", $post->discussion);
016cd6af 2302 set_field("forum_discussions", "usermodified", $post->userid, "id", $post->discussion);
65b0e537 2303
eaf50aef 2304 if (forum_tp_can_track_forums($post->forum) && forum_tp_is_tracked($post->forum)) {
f37da850 2305 forum_tp_mark_post_read($post->userid, $post, $post->forum);
2306 }
2307
7f6689e4 2308 return $post->id;
501cdbd8 2309}
2310
db290a6e 2311function forum_update_post($post,&$message) {
501cdbd8 2312
f37da850 2313 global $USER, $CFG;
a56f0d60 2314
ffe11640 2315 $post->modified = time();
0936de64 2316
2317 if ($USER->id != $post->userid) { // Not the original author
2318 $data->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$USER->id.'&course='.$post->course.'">'.
2319 fullname($USER).'</a>';
2320 $data->date = userdate($post->modified);
2321 $editedby = get_string('editedby', 'forum', $data);
2322 if ($post->format == FORMAT_HTML) {
7f65461c 2323 $post->message .= '<p>(<span class="edited">'.$editedby.'</span>)</p>';
0936de64 2324 } else {
2325 $post->message .= "\n\n(".$editedby.')';
2326 }
2327 }
501cdbd8 2328
0ab85112 2329 if (!$post->parent) { // Post is a discussion starter - update discussion title too
2330 set_field("forum_discussions", "name", $post->subject, "id", $post->discussion);
2331 }
29507631 2332
db290a6e 2333 if ($newfilename = forum_add_attachment($post, 'attachment',$message)) {
7f6689e4 2334 $post->attachment = $newfilename;
2335 } else {
2336 unset($post->attachment);
2337 }
29507631 2338
2339 // Update discussion modified date
2340 set_field("forum_discussions", "timemodified", $post->modified, "id", $post->discussion);
016cd6af 2341 set_field("forum_discussions", "usermodified", $post->userid, "id", $post->discussion);
29507631 2342
eaf50aef 2343 if (forum_tp_can_track_forums($post->forum) && forum_tp_is_tracked($post->forum)) {
f37da850 2344 forum_tp_mark_post_read($post->userid, $post, $post->forum);
2345 }
2346
ffe11640 2347 return update_record("forum_posts", $post);
501cdbd8 2348}
2349
db290a6e 2350function forum_add_discussion($discussion,&$message) {
65b0e537 2351// Given an object containing all the necessary data,
501cdbd8 2352// create a new discussion and return the id
2353
f37da850 2354 GLOBAL $USER, $CFG;
501cdbd8 2355
2356 $timenow = time();
2357
65b0e537 2358 // The first post is stored as a real post, and linked
501cdbd8 2359 // to from the discuss entry.
2360
2361 $post->discussion = 0;
2362 $post->parent = 0;
ebc3bd2b 2363 $post->userid = $USER->id;
501cdbd8 2364 $post->created = $timenow;
2365 $post->modified = $timenow;
2366 $post->mailed = 0;
2367 $post->subject = $discussion->name;
2368 $post->message = $discussion->intro;
7f6689e4 2369 $post->attachment = "";
2370 $post->forum = $discussion->forum;
2371 $post->course = $discussion->course;
9f0b8269 2372 $post->format = $discussion->format;
501cdbd8 2373
2374 if (! $post->id = insert_record("forum_posts", $post) ) {
2375 return 0;
2376 }
2377
db290a6e 2378 if ($post->attachment = forum_add_attachment($post, 'attachment',$message)) {
7f6689e4 2379 set_field("forum_posts", "attachment", $post->attachment, "id", $post->id); //ignore errors
2380 }
2381
65b0e537 2382 // Now do the main entry for the discussion,
02509fe6 2383 // linking to this first post
04eba58f 2384
caadf009 2385 $discussion->firstpost = $post->id;
2386 $discussion->timemodified = $timenow;
016cd6af 2387 $discussion->usermodified = $post->userid;
a56f0d60 2388 $discussion->userid = $USER->id;
04eba58f 2389
4e00a4d9 2390 if (! $post->discussion = insert_record("forum_discussions", $discussion) ) {
caadf009 2391 delete_records("forum_posts", "id", $post->id);
2392 return 0;
04eba58f 2393 }
2394
caadf009 2395 // Finally, set the pointer on the post.
4e00a4d9 2396 if (! set_field("forum_posts", "discussion", $post->discussion, "id", $post->id)) {
caadf009 2397 delete_records("forum_posts", "id", $post->id);
4e00a4d9 2398 delete_records("forum_discussions", "id", $post->discussion);
caadf009 2399 return 0;
04eba58f 2400 }
04eba58f 2401
eaf50aef 2402 if (forum_tp_can_track_forums($post->forum) && forum_tp_is_tracked($post->forum)) {
f37da850 2403 forum_tp_mark_post_read($post->userid, $post, $post->forum);
2404 }
2405
4e00a4d9 2406 return $post->discussion;
caadf009 2407}
04eba58f 2408
04eba58f 2409
e2c1dbe9 2410function forum_delete_discussion($discussion, $fulldelete=false) {
caadf009 2411// $discussion is a discussion record object
04eba58f 2412
2413 $result = true;
2414
caadf009 2415 if ($posts = get_records("forum_posts", "discussion", $discussion->id)) {
2416 foreach ($posts as $post) {
2417 $post->course = $discussion->course;
2418 $post->forum = $discussion->forum;
2419 if (! delete_records("forum_ratings", "post", "$post->id")) {
2420 $result = false;
2421 }
e2c1dbe9 2422 if (! forum_delete_post($post, $fulldelete)) {
04eba58f 2423 $result = false;
2424 }
2425 }
2426 }
2427
f37da850 2428 forum_tp_delete_read_records(-1, -1, $discussion->id);
2429
caadf009 2430 if (! delete_records("forum_discussions", "id", "$discussion->id")) {
04eba58f 2431 $result = false;
2432 }
2433
2434 return $result;
2435}
2436
2437
b82faacd 2438function forum_delete_post($post, $children=false) {
1da8c568 2439 if ($childposts = get_records('forum_posts', 'parent', $post->id)) {
2440 if ($children) {
b82faacd 2441 foreach ($childposts as $childpost) {
2442 forum_delete_post($childpost, true);
2443 }
1da8c568 2444 } else {
2445 return false;
b82faacd 2446 }
2447 }
caadf009 2448 if (delete_records("forum_posts", "id", $post->id)) {
2449 delete_records("forum_ratings", "post", $post->id); // Just in case
f37da850 2450
b82faacd 2451 forum_tp_delete_read_records(-1, $post->id);
f37da850 2452
caadf009 2453 if ($post->attachment) {
2454 $discussion = get_record("forum_discussions", "id", $post->discussion);
2455 $post->course = $discussion->course;
2456 $post->forum = $discussion->forum;
2457 forum_delete_old_attachments($post);
2458 }
1da8c568 2459
2460 /// Just in case we are deleting the last post
2461 forum_discussion_update_last_post($post->discussion);
2462
caadf009 2463 return true;
2464 }
2465 return false;
2466}
501cdbd8 2467
b82faacd 2468function forum_count_replies($post, $children=true) {
2469 $count = 0;
2470
2471 if ($children) {
2472 if ($childposts = get_records('forum_posts', 'parent', $post->id)) {
2473 foreach ($childposts as $childpost) {
2474 $count ++; // For this child
2475 $count += forum_count_replies($childpost, true);
2476 }
2477 }
2478 } else {
2479 $count += count_records('forum_posts', 'parent', $post->id);
2480 }
2481
2482 return $count;
2483}
2484
2485
501cdbd8 2486function forum_forcesubscribe($forumid, $value=1) {
2487 return set_field("forum", "forcesubscribe", $value, "id", $forumid);
2488}
2489
2490function forum_is_forcesubscribed($forumid) {
709f0ec8 2491 return (get_field("forum", "forcesubscribe", "id", $forumid) == 1);
501cdbd8 2492}
2493
2494function forum_is_subscribed($userid, $forumid) {
2495 if (forum_is_forcesubscribed($forumid)) {
2496 return true;
2497 }
ebc3bd2b 2498 return record_exists("forum_subscriptions", "userid", $userid, "forum", $forumid);
86970225 2499}
2500
501cdbd8 2501function forum_subscribe($userid, $forumid) {
9fa49e22 2502/// Adds user to the subscriber list
2503
6673d7bd 2504 if (record_exists("forum_subscriptions", "userid", $userid, "forum", $forumid)) {
2505 return true;
2506 }
2507
ebc3bd2b 2508 $sub->userid = $userid;
9fa49e22 2509 $sub->forum = $forumid;
501cdbd8 2510
9fa49e22 2511 return insert_record("forum_subscriptions", $sub);
501cdbd8 2512}
2513
2514function forum_unsubscribe($userid, $forumid) {
9fa49e22 2515/// Removes user from the subscriber list
ebc3bd2b 2516 return delete_records("forum_subscriptions", "userid", $userid, "forum", $forumid);
501cdbd8 2517}
2518
0a9f61b5 2519function forum_post_subscription($post) {
2520/// Given a new post, subscribes or unsubscribes as appropriate.
2521/// Returns some text which describes what happened.
2522
2523 global $USER;
2524
2525 if (empty($post->subscribe) and empty($post->unsubscribe)) {
2526 return "";
2527 }
2528
2529 if (!$forum = get_record("forum", "id", $post->forum)) {
2530 return "";
2531 }
2532
067675c0 2533 $info->name = fullname($USER);
0a9f61b5 2534 $info->forum = $forum->name;
2535
2536 if (!empty($post->subscribe)) {
2537 forum_subscribe($USER->id, $post->forum);
2538 return "<p>".get_string("nowsubscribed", "forum", $info)."</p>";
2539 }
2540
2541 forum_unsubscribe($USER->id, $post->forum);
2542 return "<p>".get_string("nownotsubscribed", "forum", $info)."</p>";
2543}
2544
501cdbd8 2545
11b0c469 2546function forum_user_has_posted_discussion($forumid, $userid) {
29507631 2547 if ($discussions = forum_get_discussions($forumid, "", $userid)) {
501cdbd8 2548 return true;
2549 } else {
2550 return false;
2551 }
2552}
2553
9197e147 2554function forum_user_can_post_discussion($forum, $currentgroup=false) {
501cdbd8 2555// $forum is an object
2556 global $USER;
2557
2558 if ($forum->type == "eachuser") {
11b0c469 2559 return (! forum_user_has_posted_discussion($forum->id, $USER->id));
501cdbd8 2560 } else if ($forum->type == "teacher") {
2561 return isteacher($forum->course);
9197e147 2562 } else if ($currentgroup) {
d591b40f 2563 return (isteacheredit($forum->course) or (ismember($currentgroup) and $forum->open == 2));
501cdbd8 2564 } else if (isteacher($forum->course)) {
2565 return true;
2566 } else {
70c476a7 2567 return ($forum->open == 2);
501cdbd8 2568 }
2569}
2570
f690562f 2571function forum_user_can_post($forum, $user=NULL) {
2572// $forum, $user are objects
2573
2574 if ($user) {
2575 $isteacher = isteacher($forum->course, $user->id);
2576 } else {
2577 $isteacher = isteacher($forum->course);
2578 }
70c476a7 2579
2580 if ($forum->type == "teacher") {
f690562f 2581 return $isteacher;
2582 } else if ($isteacher) {
70c476a7 2583 return true;
2584 } else {
2585 return $forum->open;
2586 }
2587}
501cdbd8 2588
501cdbd8 2589
eaf50aef 2590/**
2591* Prints the discussion view screen for a forum.
2592*
2593* @param object $course The current course object.
2594* @param object $forum Forum to be printed.
2595* @param int $maxdiscussions The maximum number of discussions per page(optional).
2596* @param string $displayformat The display format to use (optional).
2597* @param string $sort Sort arguments for database query (optional).
2598* @param int $currentgroup Group to display discussions for (optional).
2599* @param int $groupmode Group mode of the forum (optional).
2600* @param int $page Page mode, page to display (optional).
2601*
2602*/
af328e4b 2603function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $displayformat='plain', $sort='',
2604 $currentgroup=-1, $groupmode=-1, $page=-1) {
c585fa17 2605 global $CFG, $USER;
65b0e537 2606
f93f848a 2607
af328e4b 2608/// Sort out some defaults
2609
2610 if ((!$maxdiscussions) && ($displayformat == 'plain')) {
2611 $displayformat = 'header'; // Abbreviate display by default
2612 }
2613
2614 $fullpost = false;
2615 if ($displayformat == 'plain') {
2616 $fullpost = true;
f93f848a 2617 }
2618
af328e4b 2619
2620/// Decide if current user is allowed to see ALL the current discussions or not
2621
2622/// First check the group stuff
2623
2862b309 2624 if ($groupmode == -1) { /// We need to reconstruct groupmode because none was given
d5bbc556 2625 if ($cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
2862b309 2626 $groupmode = groupmode($course, $cm);
2627 } else {
2628 $groupmode = SEPARATEGROUPS;
2629 }
2630 }
8f0cd6ef 2631
af328e4b 2632 if ($currentgroup == -1) { /// We need to reconstruct currentgroup because none was given
2633 $currentgroup = get_current_group($course->id);
2634 }
2635
2636 if (!$currentgroup and ($groupmode != SEPARATEGROUPS or isteacheredit($course->id)) ) {
2637 $visiblegroups = -1;
2638 } else {
2639 $visiblegroups = $currentgroup;
2640 }
2641
2642/// If the user can post discussions, then this is a good place to put the button for it
2862b309 2643
9197e147 2644 if (forum_user_can_post_discussion($forum, $currentgroup)) {
af328e4b 2645 echo '<div class="singlebutton forumaddnew">';
49aa3742 2646 echo "<form name=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
2647 echo "<input type=\"hidden\" name=\"forum\" value=\"$forum->id\" />";
2648 echo '<input type="submit" value="';
d5bbc556 2649 echo ($forum->type == 'news') ? get_string('addanewtopic', 'forum') : get_string('addanewdiscussion', 'forum');
49aa3742 2650 echo '" />';
2651 echo '</form>';
3479c82f 2652 echo "</div>\n";
77305fe6 2653 }
2654
2862b309 2655
2656/// Get all the recent discussions we're allowed to see
2657
096de9ad 2658 $getuserlastmodified = ($displayformat == 'header');
2659
2660 if (! $discussions = forum_get_discussions($forum->id, $sort, 0, $fullpost, $visiblegroups,0,$getuserlastmodified) ) {
af328e4b 2661 echo '<div class="forumnodiscuss">';
d5bbc556 2662 if ($forum->type == 'news') {
2663 echo '('.get_string('nonews', 'forum').')';
0351b1f9 2664 } else {
d5bbc556 2665 echo '('.get_string('nodiscussions', 'forum').')';
0351b1f9 2666 }
f13075f1 2667 echo "</div>\n";
2ab968e9 2668 return;
2669 }
65b0e537 2670
af328e4b 2671/// If no discussions then don't use paging (to avoid some divide by 0 errors)
2672
2673 if ($maxdiscussions <= 0) {
f6bb7eaa 2674 $page = -1;
af328e4b 2675 $maxdiscussions = 0;
f6bb7eaa 2676 }
2677
af328e4b 2678/// If we want paging
2679
f6bb7eaa 2680 if ($page != -1) {
2681 ///Get the number of discussions found
2682 $numdiscussions = count($discussions);
2683
2684 ///Show the paging bar
af328e4b 2685 print_paging_bar($numdiscussions, $page, $maxdiscussions, "view.php?f=$forum->id&");
f6bb7eaa 2686
2687 //Calculate the page "window"
af328e4b 2688 $pagestart = ($page * $maxdiscussions) + 1;
2689 $pageend = $pagestart + $maxdiscussions - 1;
f6bb7eaa 2690 }
2691
af328e4b 2692
3335f6fb 2693 $replies = forum_count_discussion_replies($forum->id);
f93f848a 2694
3260de67 2695 $canreply = forum_user_can_post($forum);
2696
af328e4b 2697
3335f6fb 2698 $discussioncount = 0;
c20b762a 2699 $olddiscussionlink = false;
f51e8d7e 2700 $strdatestring = get_string('strftimerecentfull');
f93f848a 2701
1d2256d0 2702 /// Check if the forum is tracked.
eaf50aef 2703 if ($cantrack = forum_tp_can_track_forums($forum)) {
77efef3e 2704 $forumtracked = forum_tp_is_tracked($forum);
1d2256d0 2705 } else {
2706 $forumtracked = false;
2707 }
2708
af328e4b 2709 if ($displayformat == 'header') {
5c8d1866 2710 echo '<table cellspacing="0" class="forumheaderlist">';
f51e8d7e 2711 echo '<thead>';
2712 echo '<tr>';
7ff9860d 2713 echo '<th class="header topic">'.get_string('discussion', 'forum').'</th>';
2714 echo '<th class="header author" colspan="2">'.get_string('startedby', 'forum').'</th>';
3a68fbbb 2715 if ($groupmode > 0) {
7ff9860d 2716 echo '<th class="header group">'.get_string('group').'</th>';
3a68fbbb 2717 }
f51e8d7e 2718 if ($forum->open or $forum->type == 'teacher') {
7ff9860d 2719 echo '<th class="header replies">'.get_string('replies', 'forum').'</th>';
eaf50aef 2720 /// If the forum can be tracked, display the unread column.
2721 if ($cantrack) {
524f9dbe 2722 echo '<th class="header replies">'.get_string('unread', 'forum');
2723 if ($forumtracked) {
2724 echo '&nbsp;<a title="'.get_string('markallread', 'forum').
2725 '" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
2726 $forum->id.'&amp;mark=read&amp;returnpage=view.php">'.
2727 '<img src="'.$CFG->pixpath.'/t/clear.gif" height="11" width="11" border="0" /></a>';
2728 }
2729 echo '</th>';
47d06301 2730 }
f37da850 2731 }
7ff9860d 2732 echo '<th class="header lastpost">'.get_string('lastpost', 'forum').'</th>';
f51e8d7e 2733 echo '</tr>';
2734 echo '</thead>';
2735 echo '<tbody>';
29507631 2736 }
2737
3335f6fb 2738 foreach ($discussions as $discussion) {
2739 $discussioncount++;
f93f848a 2740
af328e4b 2741 if ($page != -1) { // We are using paging
2742 if ($discussioncount < $pagestart) { // Not there yet
f6bb7eaa 2743 continue;
2744 }
af328e4b 2745 if ($discussioncount > $pageend) { // All done, finish the loop
2746 break;
2747 }
f6bb7eaa 2748 //Without paging, old approach
af328e4b 2749 } else if ($maxdiscussions && ($discussioncount > $maxdiscussions)) {
c20b762a 2750 $olddiscussionlink = true;
3335f6fb 2751 break;
2752 }
e3ff14ca 2753
9c9f7d77 2754 if (!empty($replies[$discussion->discussion])) {
3335f6fb 2755 $discussion->replies = $replies[$discussion->discussion]->replies;
3599e487 2756 $discussion->lastpostid = $replies[$discussion->discussion]->lastpostid;
3335f6fb 2757 } else {
2758 $discussion->replies = 0;
2759 }
af328e4b 2760
489de4ae 2761 /// SPECIAL CASE: The front page can display a news item post to non-logged in users.
2762 /// All posts are read in this case.
eaf50aef 2763 if (!$forumtracked) {
2764 $discussion->unread = '-';
2765 } else if (empty($USER)) {
2766 $discussion->unread = 0;
2767 } else {
2768 $discussion->unread = forum_tp_count_discussion_unread_posts($USER->id, $discussion->discussion);
f37da850 2769 }
2770
f7477444 2771 if (!empty($USER->id)) {
2772 $ownpost = ($discussion->userid == $USER->id);
2773 } else {
2774 $ownpost=false;
2775 }
cf84431b 2776 // Use discussion name instead of subject of first post
2777 $discussion->subject = $discussion->name;
2778
af328e4b 2779 switch ($displayformat) {
2780 case 'header':
3a68fbbb 2781 if ($groupmode > 0) {
2782 if (isset($groups[$discussion->groupid])) {
2783 $group = $groups[$discussion->groupid];
2784 } else {
2785 $group = $groups[$discussion->groupid] = get_record('groups', 'id', $discussion->groupid);
2786 }
2787 } else {
2788 $group = -1;
2789 }
eaf50aef 2790 forum_print_discussion_header($discussion, $forum, $group, $strdatestring, $cantrack, $forumtracked);
3335f6fb 2791 break;
2792 default:
3260de67 2793 if ($canreply or $discussion->replies) {
2794 $link = true;
2795 } else {
2796 $link = false;
2797 }
f37da850 2798
af328e4b 2799 $discussion->forum = $forum->id;
f37da850 2800
af328e4b 2801 forum_print_post($discussion, $course->id, $ownpost, $reply=0, $link, $assessed=false);
3335f6fb 2802 break;
f93f848a 2803 }
2804 }
29507631 2805
af328e4b 2806 if ($displayformat == "header") {
f51e8d7e 2807 echo '</tbody>';
2808 echo '</table>';
29507631 2809 }
c20b762a 2810
2811 if ($olddiscussionlink) {
af328e4b 2812 echo '<div class="forumolddiscuss">';
2813 echo '<a href="'.$CFG->wwwroot.'/mod/forum/view.php?f='.$forum->id.'&amp;showall=1">';
2814 echo get_string('olderdiscussions', 'forum').'</a> ...</div>';
c20b762a 2815 }
f6bb7eaa 2816
c8680d86 2817 if ($page != -1) { ///Show the paging bar
af328e4b 2818 print_paging_bar($numdiscussions, $page, $maxdiscussions, "view.php?f=$forum->id&");
f6bb7eaa 2819 }
f93f848a 2820}
2821
af328e4b 2822
c6d691dc 2823function forum_print_discussion($course, $forum, $discussion, $post, $mode, $canreply=NULL) {
501cdbd8 2824
f37da850 2825 global $USER, $CFG;
501cdbd8 2826
61e96406 2827 if (!empty($USER->id)) {
2828 $ownpost = ($USER->id == $post->userid);
2829 } else {
2830 $ownpost = false;
2831 }
c6d691dc 2832 if ($canreply === NULL) {
2833 $reply = forum_user_can_post($forum);
2834 } else {
2835 $reply = $canreply;
2836 }
501cdbd8 2837
02ebf404 2838 $ratings = NULL;
74f5d1e3 2839 $ratingsmenuused = false;
61e96406 2840 if ($forum->assessed and !empty($USER->id)) {
d6bdd9d5 2841 if ($ratings->scale = make_grades_menu($forum->scale)) {
3bd98ad4 2842 $ratings->assesspublic = $forum->assesspublic;
98914efd 2843 $ratings->assesstimestart = $forum->assesstimestart;
2844 $ratings->assesstimefinish = $forum->assesstimefinish;
0efb3c3d 2845 $ratings->allow = (($forum->assessed != 2 or isteacher($course->id)) && !isguest());
3bd98ad4 2846
0efb3c3d 2847 if ($ratings->allow) {
2848 echo '<form name="form" method="post" action="rate.php">';
2849 echo '<input type="hidden" name="id" value="'.$course->id.'" />';
2850 }
9d1b97c5 2851 }
2852 }
2853
77efef3e 2854 $post->forum = $forum->id; // Add the forum id to the post object, later used by forum_print_post
f37da850 2855
c78ac798 2856 $post->subject = format_string($post->subject);
2857
eaf50aef 2858 if (forum_tp_can_track_forums($forum)) {
77efef3e 2859 if ($forumtracked = forum_tp_is_tracked($forum)) {
eaf50aef 2860 $user_read_array = forum_tp_get_discussion_read_records($USER->id, $post->discussion);
2861 } else {
2862 $user_read_array = array();
2863 }
f37da850 2864 } else {
eaf50aef 2865 $forumtracked = false;
f37da850 2866 $user_read_array = array();
2867 }
2868
2869 if (forum_print_post($post, $course->id, $ownpost, $reply, $link=false, $ratings,
143b43cb 2870 '', '', (!$forumtracked || isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
74f5d1e3 2871 $ratingsmenuused = true;
2872 }
501cdbd8 2873
2874 switch ($mode) {
2e2e71a8 2875 case FORUM_MODE_FLATOLDEST :
2876 case FORUM_MODE_FLATNEWEST :
65b0e537 2877 default:
f37da850 2878 if (forum_print_posts_flat($post->discussion, $course->id, $mode, $ratings, $reply,
2879 $user_read_array, $post->forum)) {
74f5d1e3 2880 $ratingsmenuused = true;
2881 }
501cdbd8 2882 break;
2883
2e2e71a8 2884 case FORUM_MODE_THREADED :
f37da850 2885 if (forum_print_posts_threaded($post->id, $course->id, 0, $ratings, $reply,
2886 $user_read_array, $post->forum)) {
74f5d1e3 2887 $ratingsmenuused = true;
2888 }
501cdbd8 2889 break;
2890
2e2e71a8 2891 case FORUM_MODE_NESTED :
f37da850 2892 if (forum_print_posts_nested($post->id, $course->id, $ratings, $reply,
2893 $user_read_array, $post->forum)) {
74f5d1e3 2894 $ratingsmenuused = true;
2895 }
501cdbd8 2896 break;
2897 }
2898
74f5d1e3 2899 if ($ratingsmenuused) {
b4510d53 2900 echo "<center><input type=\"submit\" value=\"".get_string("sendinratings", "forum")."\" />";
fa01ae8b 2901 if ($forum->scale < 0) {
2902 if ($scale = get_record("scale", "id", abs($forum->scale))) {
2903 print_scale_menu_helpbutton($course->id, $scale );
2904 }
2905 }
02ebf404 2906 echo "</center>";
2907 echo "</form>";
501cdbd8 2908 }
2909}
2910
77efef3e 2911
83a305a7 2912function forum_print_posts_flat($discussion, $courseid, $direction, $ratings, $reply, &$user_read_array, $forumid=0) {
f37da850 2913 global $USER, $CFG;
501cdbd8 2914
501cdbd8 2915 $link = false;
74f5d1e3 2916 $ratingsmenuused = false;
501cdbd8 2917
2918 if ($direction < 0) {
2919 $sort = "ORDER BY created DESC";
2920 } else {
2921 $sort = "ORDER BY created ASC";
2922 }
2923
77efef3e 2924 if ($posts = forum_get_discussion_posts($discussion, $sort, $forumid)) {
501cdbd8 2925 foreach ($posts as $post) {
f37da850 2926
c78ac798 2927 $post->subject = format_string($post->subject);
2928
ebc3bd2b 2929 $ownpost = ($USER->id == $post->userid);
83a305a7 2930 if (forum_print_post($post, $courseid, $ownpost, $reply, $link, $ratings,
f37da850 2931 '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
74f5d1e3 2932 $ratingsmenuused = true;
2933 }
501cdbd8 2934 }
501cdbd8 2935 }
74f5d1e3 2936
2937 return $ratingsmenuused;
501cdbd8 2938}
2939
77efef3e 2940
83a305a7 2941function forum_print_posts_threaded($parent, $courseid, $depth, $ratings, $reply, &$user_read_array, $forumid=0) {
f37da850 2942 global $USER, $CFG;
501cdbd8 2943
501cdbd8 2944 $link = false;
74f5d1e3 2945 $ratingsmenuused = false;
501cdbd8 2946
eaf50aef 2947 $istracking = forum_tp_can_track_forums($forumid) && forum_tp_is_tracked($forumid);
77efef3e 2948
2949 if ($posts = forum_get_child_posts($parent, $forumid)) {
501cdbd8 2950 foreach ($posts as $post) {
2951
7105cf8d 2952 echo '<div class="indent">';
501cdbd8 2953 if ($depth > 0) {
ebc3bd2b 2954 $ownpost = ($USER->id == $post->userid);
f37da850 2955
c78ac798 2956 $post->subject = format_string($post->subject);
2957
83a305a7 2958 if (forum_print_post($post, $courseid, $ownpost, $reply, $link, $ratings,
f37da850 2959 '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
74f5d1e3 2960 $ratingsmenuused = true;
2961 }
501cdbd8 2962 } else {
83a305a7 2963 $by->name = fullname($post, isteacher($courseid));
d62413e8 2964 $by->date = userdate($post->modified);
f37da850 2965
eaf50aef 2966 if ($istracking) {
f37da850 2967 if (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)) {
2968 $style = '<span class="forumthread read">';
2969 } else {
2970 $style = '<span class="forumthread unread">';
2971 }
2972 } else {
2973 $style = '<span class="forumthread">';
2974 }
2975 echo $style."<a name=\"$post->id\"></a>".
17dc3f3c 2976 "<a href=\"discuss.php?d=$post->discussion&amp;parent=$post->id\">".format_string($post->subject,true)."</a> ";
8c3c8481 2977 print_string("bynameondate", "forum", $by);
f37da850 2978 echo "</span>";
501cdbd8 2979 }
2980
83a305a7 2981 if (forum_print_posts_threaded($post->id, $courseid, $depth-1, $ratings, $reply,
f37da850 2982 $user_read_array, $forumid)) {
74f5d1e3 2983 $ratingsmenuused = true;
2984 }
bb3b56c6 2985 echo "</div>\n";
501cdbd8 2986 }
501cdbd8 2987 }
74f5d1e3 2988 return $ratingsmenuused;
501cdbd8 2989}
2990
83a305a7 2991function forum_print_posts_nested($parent, $courseid, $ratings, $reply, &$user_read_array, $forumid=0) {
f37da850 2992 global $USER, $CFG;
501cdbd8 2993
501cdbd8 2994 $link = false;
74f5d1e3 2995 $ratingsmenuused = false;
501cdbd8 2996
77efef3e 2997 if ($posts = forum_get_child_posts($parent, $forumid)) {
501cdbd8 2998 foreach ($posts as $post) {
2999
7105cf8d 3000 echo '<div class="indent">';
61e96406 3001 if (empty($USER->id)) {
3002 $ownpost = false;
3003 } else {
3004 $ownpost = ($USER->id == $post->userid);
3005 }
c78ac798 3006
3007 $post->subject = format_string($post->subject);
f37da850 3008
83a305a7 3009 if (forum_print_post($post, $courseid, $ownpost, $reply, $link, $ratings,
f37da850 3010 '', '', (isset($user_read_array[$post->id]) || forum_tp_is_post_old($post)))) {
74f5d1e3 3011 $ratingsmenuused = true;
3012 }
83a305a7 3013 if (forum_print_posts_nested($post->id, $courseid, $ratings, $reply, $user_read_array, $forumid)) {
74f5d1e3 3014 $ratingsmenuused = true;
3015 }
bb3b56c6 3016 echo "</div>\n";
501cdbd8 3017 }
501cdbd8 3018 }
74f5d1e3 3019 return $ratingsmenuused;
501cdbd8 3020}
3021
2862b309 3022function forum_get_recent_mod_activity(&$activities, &$index, $sincetime, $courseid, $cmid="0", $user="", $groupid="") {
a57a7794 3023// Returns all forum posts since a given time. If forum is specified then
3024// this restricts the results
3025
3026 global $CFG;
3027
2862b309 3028 if ($cmid) {
3029 $forumselect = " AND cm.id = '$cmid'";
a57a7794 3030 } else {
3031 $forumselect = "";
3032 }
3033
3034 if ($user) {
3035 $userselect = " AND u.id = '$user'";
3036 } else {
3037 $userselect = "";
3038 }
3039
a57a7794 3040 $posts = get_records_sql("SELECT p.*, d.name, u.firstname, u.lastname,
3041 u.picture, d.groupid, cm.instance, f.name, cm.section
3042 FROM {$CFG->prefix}forum_posts p,
3043 {$CFG->prefix}forum_discussions d,
3044 {$CFG->prefix}user u,
3045 {$CFG->prefix}course_modules cm,
3046 {$CFG->prefix}forum f
3047 WHERE p.modified > '$sincetime' $forumselect
3048 AND p.userid = u.id $userselect
3049 AND d.course = '$courseid'
8f0cd6ef 3050 AND p.discussion = d.id
a57a7794 3051 AND cm.instance = f.id
3052 AND cm.course = d.course
3053 AND cm.course = f.course
3054 AND f.id = d.forum
5b257acd 3055 ORDER BY p.discussion ASC,p.created ASC");
a57a7794 3056
2862b309 3057 if (empty($posts)) {
3058 return;
3059 }
3060
3061 $isteacheredit = isteacheredit($courseid);
a57a7794 3062
90708fc1 3063 foreach ($posts as $post) {
a57a7794 3064
2862b309 3065 if ($groupid and ($post->groupid != -1 and $groupid != $post->groupid and !$isteacheredit)) {
3066 continue;
3067 }
a57a7794 3068
ac21ad39 3069 $tmpactivity = new Object;
3070
2862b309 3071 $tmpactivity->type = "forum";
3072 $tmpactivity->defaultindex = $index;
3073 $tmpactivity->instance = $post->instance;
3074 $tmpactivity->name = $post->name;
3075 $tmpactivity->section = $post->section;
65b0e537 3076
2862b309 3077 $tmpactivity->content->id = $post->id;
3078 $tmpactivity->content->discussion = $post->discussion;
3079 $tmpactivity->content->subject = $post->subject;
3080 $tmpactivity->content->parent = $post->parent;
a57a7794 3081
2862b309 3082 $tmpactivity->user->userid = $post->userid;
3083 $tmpactivity->user->fullname = fullname($post);
3084 $tmpactivity->user->picture = $post->picture;
65b0e537 3085
2862b309 3086 $tmpactivity->timestamp = $post->modified;
3087 $activities[] = $tmpactivity;
3088
3089 $index++;
90708fc1 3090 }
a57a7794 3091
90708fc1 3092 return;
a57a7794 3093}
3094
3095function forum_print_recent_mod_activity($activity, $course, $detail=false) {
3096
d30867b0 3097 global $CFG;
a57a7794 3098
3099 echo '<table border="0" cellpadding="3" cellspacing="0">';
3100
3101 if ($activity->content->parent) {
3102 $openformat = "<font size=\"2\"><i>";
3103 $closeformat = "</i></font>";
3104 } else {
3105 $openformat = "<b>";
3106 $closeformat = "</b>";
3107 }
3108
d30867b0 3109 echo "<tr><td class=\"forumpostpicture\" width=\"35\" valign=\"top\">";
a57a7794 3110 print_user_picture($activity->user->userid, $course, $activity