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