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