Fixes for capability checks.
[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
f2f56406 97 if (!$forum->userating) {
98 $forum->assessed = 0;
99 }
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
3ad7a8c7 148 if (empty($forum->userating)) {
f2f56406 149 $forum->assessed = 0;
150 }
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
1b5910c4 856function forum_print_recent_activity($course, $isteacher, $timestart) {
65b0e537 857/// Given a course and a date, prints a summary of all the new
cc3655a2 858/// messages posted in the course since that date
859
3d891989 860 global $CFG;
caadf009 861
862 $heading = false;
863 $content = false;
864
8f7dc7f1 865 if (!$logs = get_records_select('log', 'time > \''.$timestart.'\' AND '.
866 'course = \''.$course->id.'\' AND '.
867 'module = \'forum\' AND '.
868 'action LIKE \'add %\' ', 'time ASC')){
1b5910c4 869 return false;
870 }
871
8f7dc7f1 872 $strftimerecent = get_string('strftimerecent');
dcde9f02 873
d05956ac 874 $isteacheredit = isteacheredit($course->id);
875 $mygroupid = mygroupid($course->id);
876
877 $groupmode = array(); /// To cache group modes
878
1b5910c4 879 foreach ($logs as $log) {
880 //Get post info, I'll need it later
ac1d9a22 881 if ($post = forum_get_post_from_log($log)) {
882 //Create a temp valid module structure (course,id)
883 $tempmod->course = $log->course;
884 $tempmod->id = $post->forum;
885 //Obtain the visible property from the instance
8f7dc7f1 886 $modvisible = instance_is_visible('forum', $tempmod);
ac1d9a22 887 }
d05956ac 888
ac1d9a22 889 //Only if the post exists and mod is visible
890 if ($post && $modvisible) {
891 /// Check whether this is for teachers only
8f7dc7f1 892 $teacheronly = '';
893 if ($post->forumtype == 'teacher') {
894 if ($isteacher) {
895 $teacheronly = 'class=\'teacheronly\'';
896 } else {
897 continue;
b91d6dcd 898 }
ac1d9a22 899 }
900 /// Check whether this is belongs to a discussion in a group that
901 /// should NOT be accessible to the current user
b91d6dcd 902
ac1d9a22 903 if (!$isteacheredit and $post->groupid != -1) { /// Editing teachers or open discussions
904 if (!isset($cm[$post->forum])) {
8f7dc7f1 905 $cm[$post->forum] = get_coursemodule_from_instance('forum', $post->forum, $course->id);
906 $groupmode[$post->forum] = groupmode($course, $cm[$post->forum]);
436a7cae 907 }
8f7dc7f1 908 if ($groupmode[$post->forum]) {
fa22fd5f 909 //hope i didn't break anything
910 if (!@in_array($mygroupid, $post->groupid))/*$mygroupid != $post->groupid*/{
ac1d9a22 911 continue;
912 }
1b5910c4 913 }
caadf009 914 }
ac1d9a22 915
916 if (! $heading) {
8f7dc7f1 917 print_headline(get_string('newforumposts', 'forum').':');
ac1d9a22 918 $heading = true;
919 $content = true;
920 }
921 $date = userdate($post->modified, $strftimerecent);
8f7dc7f1 922
923 $subjectclass = ($log->action == 'add discussion') ? ' bold' : '';
924
a4f7aac1 925 echo '<div class="head'.$teacheronly.'">'.
926 '<div class="date">'.$date.'</div>'.
927 '<div class="name">'.fullname($post, $isteacher).'</div>'.
928 '</div>';
929 echo '<div class="info'.$subjectclass.'">';
8f7dc7f1 930 echo '"<a href="'.$CFG->wwwroot.'/mod/forum/'.str_replace('&', '&amp;', $log->url).'">';
17dc3f3c 931 $post->subject = break_up_long_words(format_string($post->subject,true));
8f7dc7f1 932 echo $post->subject;
933 echo '</a>"</div>';
caadf009 934 }
935 }
1b5910c4 936
caadf009 937 return $content;
938}
939
940
941function forum_grades($forumid) {
942/// Must return an array of grades, indexed by user, and a max grade.
caadf009 943
4db9d14d 944 if (!$forum = get_record("forum", "id", $forumid)) {
945 return false;
946 }
947 if (!$forum->assessed) {
948 return false;
949 }
d6bdd9d5 950 $scalemenu = make_grades_menu($forum->scale);
02ebf404 951
952 $currentuser = 0;
953 $ratingsuser = array();
954
1f48942e 955 if ($ratings = forum_get_user_grades($forumid)) {
02ebf404 956 foreach ($ratings as $rating) { // Ordered by user
957 if ($currentuser and $rating->userid != $currentuser) {
958 if (!empty($ratingsuser)) {
d6bdd9d5 959 if ($forum->scale < 0) {
960 $return->grades[$currentuser] = forum_get_ratings_mean(0, $scalemenu, $ratingsuser);
961 $return->grades[$currentuser] .= "<br />".forum_get_ratings_summary(0, $scalemenu, $ratingsuser);
962 } else {
963 $total = 0;
964 $count = 0;
965 foreach ($ratingsuser as $ra) {
966 $total += $ra;
967 $count ++;
968 }
969 $return->grades[$currentuser] = format_float($total/$count, 2);
970 }
02ebf404 971 } else {
972 $return->grades[$currentuser] = "";
973 }
974 $ratingsuser = array();
caadf009 975 }
02ebf404 976 $ratingsuser[] = $rating->rating;
977 $currentuser = $rating->userid;
caadf009 978 }
02ebf404 979 if (!empty($ratingsuser)) {
d6bdd9d5 980 if ($forum->scale < 0) {
981 $return->grades[$currentuser] = forum_get_ratings_mean(0, $scalemenu, $ratingsuser);
982 $return->grades[$currentuser] .= "<br />".forum_get_ratings_summary(0, $scalemenu, $ratingsuser);
983 } else {
984 $total = 0;
985 $count = 0;
986 foreach ($ratingsuser as $ra) {
987 $total += $ra;
988 $count ++;
989 }
990 $return->grades[$currentuser] = format_float((float)$total/(float)$count, 2);
991 }
02ebf404 992 } else {
993 $return->grades[$currentuser] = "";
caadf009 994 }
995 } else {
996 $return->grades = array();
997 }
998
d6bdd9d5 999 if ($forum->scale < 0) {
1000 $return->maxgrade = "";
1001 } else {
1002 $return->maxgrade = $forum->scale;
1003 }
caadf009 1004 return $return;
1005}
1006
05855091 1007function forum_get_participants($forumid) {
1008//Returns the users with data in one forum
65b0e537 1009//(users with records in forum_subscriptions, forum_posts and forum_ratings, students)
05855091 1010
1011 global $CFG;
1012
1013 //Get students from forum_subscriptions
95e72c12 1014 $st_subscriptions = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 1015 FROM {$CFG->prefix}user u,
1016 {$CFG->prefix}forum_subscriptions s
1017 WHERE s.forum = '$forumid' and
65b0e537 1018 u.id = s.userid");
05855091 1019 //Get students from forum_posts
95e72c12 1020 $st_posts = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 1021 FROM {$CFG->prefix}user u,
1022 {$CFG->prefix}forum_discussions d,
1023 {$CFG->prefix}forum_posts p
1024 WHERE d.forum = '$forumid' and
1025 p.discussion = d.id and
1026 u.id = p.userid");
1027
1028 //Get students from forum_ratings
95e72c12 1029 $st_ratings = get_records_sql("SELECT DISTINCT u.id, u.id
05855091 1030 FROM {$CFG->prefix}user u,
1031 {$CFG->prefix}forum_discussions d,
1032 {$CFG->prefix}forum_posts p,
1033 {$CFG->prefix}forum_ratings r
1034 WHERE d.forum = '$forumid' and
1035 p.discussion = d.id and
1036 r.post = p.id and
1037 u.id = r.userid");
1038
1039 //Add st_posts to st_subscriptions
1040 if ($st_posts) {
1041 foreach ($st_posts as $st_post) {
1042 $st_subscriptions[$st_post->id] = $st_post;
1043 }
1044 }
1045 //Add st_ratings to st_subscriptions
1046 if ($st_ratings) {
1047 foreach ($st_ratings as $st_rating) {
1048 $st_subscriptions[$st_rating->id] = $st_rating;
1049 }
1050 }
1051 //Return st_subscriptions array (it contains an array of unique users)
1052 return ($st_subscriptions);
1053}
caadf009 1054
0f1a97c2 1055function forum_scale_used ($forumid,$scaleid) {
1056//This function returns if a scale is being used by one forum
65b0e537 1057
0f1a97c2 1058 $return = false;
65b0e537 1059
0f1a97c2 1060 $rec = get_record("forum","id","$forumid","scale","-$scaleid");
65b0e537 1061
fa22fd5f 1062 if (!empty($rec) && !empty($scaleid)) {
0f1a97c2 1063 $return = true;
1064 }
65b0e537 1065
0f1a97c2 1066 return $return;
1067}
1068
9fa49e22 1069/// SQL FUNCTIONS ///////////////////////////////////////////////////////////
1070
1f48942e 1071function forum_get_post_full($postid) {
1072/// Gets a post with all info ready for forum_print_post
77efef3e 1073/// Most of these joins are just to get the forum id
1f48942e 1074 global $CFG;
1075
8fbdc992 1076 return get_record_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture
6572ab71 1077 FROM {$CFG->prefix}forum_posts p
1078 LEFT JOIN {$CFG->prefix}forum_discussions d ON p.discussion = d.id
6572ab71 1079 LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
1080 WHERE p.id = '$postid'");
1f48942e 1081}
1082
77efef3e 1083function forum_get_discussion_posts($discussion, $sort, $forumid) {
1f48942e 1084/// Gets posts with all info ready for forum_print_post
77efef3e 1085/// We pass forumid in because we always know it so no need to make a
1086/// complicated join to find it out.
1f48942e 1087 global $CFG;
1088
77efef3e 1089 return get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture
10426cef 1090 FROM {$CFG->prefix}forum_posts p
10426cef 1091 LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
65b0e537 1092 WHERE p.discussion = $discussion
10426cef 1093 AND p.parent > 0 $sort");
1f48942e 1094}
1095
77efef3e 1096function forum_get_child_posts($parent, $forumid) {
1f48942e 1097/// Gets posts with all info ready for forum_print_post
77efef3e 1098/// We pass forumid in because we always know it so no need to make a
1099/// complicated join to find it out.
1f48942e 1100 global $CFG;
1101
77efef3e 1102 return get_records_sql("SELECT p.*, $forumid AS forum, u.firstname, u.lastname, u.email, u.picture
10426cef 1103 FROM {$CFG->prefix}forum_posts p
10426cef 1104 LEFT JOIN {$CFG->prefix}user u ON p.userid = u.id
65b0e537 1105 WHERE p.parent = '$parent'
1f48942e 1106 ORDER BY p.created ASC");
1107}
1108
bbbf2d40 1109/**
1110 * Returns a list of posts found using an array of search terms.
1111 * e.g. word +word -word
1112 * @param $searchterms
1113 * @param $courseid
1114 * @param $page
1115 * @param $recordsperpage=50
1116 * @param &$totalcount
1117 * @param $groupid - either a single groupid or an array of groupids.
1118 * this specifies the groups the search is to be carried
1119 * for. However, please note that, unless the user has
9af1611a 1120 * the capability 'moodle/site:accessallgroups',
bbbf2d40 1121 * we will restrict the search to a subset of groups from
1122 * $groupid. The subset consists of the groups the user
1123 * really is in.
1124 * @param $extrasql
1125 */
1126function forum_search_posts($searchterms, $courseid, $page=0, $recordsperpage=50,
1127 &$totalcount, $groupid=0, $extrasql='') {
1f48942e 1128
6af7cc22 1129 global $CFG, $USER;
855c0839 1130 require_once($CFG->libdir.'/searchlib.php');
e3ff14ca 1131
bbbf2d40 1132 $forummodule = get_record("modules", "name", "forum");
1133 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
1134 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id); // Will need to fix this.
1135
1136 // Take into account forum visibility.
0468976c 1137 if (has_capability('moodle/course:viewhiddenactivities', $coursecontext)) {
bbbf2d40 1138 $onlyvisible = '';
1139 $onlyvisibletable = '';
9fa49e22 1140 } else {
bbbf2d40 1141 $onlyvisible = "AND d.forum = f.id
1142 AND f.id = cm.instance
1143 AND cm.visible = 1
1144 AND cm.module = $forummodule->id";
1145
1146 $onlyvisibletable = ", {$CFG->prefix}course_modules cm, {$CFG->prefix}forum f";
1147 }
1148
1149 // Take into account user groups.
0468976c 1150 if (has_capability('moodle/site:accessallgroups', $modcontext)) {
c7a5b3b1 1151 $selectgroup = '';
453b5314 1152 $coursetable = '';
bbbf2d40 1153
a702e657 1154 if ($courseid == SITEID && isadmin()) {
1155 $selectcourse = '';
1156 } else {
1157 $selectcourse = " AND d.course = '$courseid'";
1158 }
bbbf2d40 1159 } else {
1160 $searchgroupid = mygroupid($courseid);
1161 if ($groupid) {
1162 // Okay we don't necessarily trust the groups specified. We'll
1163 // force the search to occur for a subset of the groups the user
1164 // is really in.
1165 $novalidgroups = false;
1166
1167 if (is_array($groupid)) {
1168 foreach ($searchgroupid as $index => $validgroupid) {
1169 if (array_search($validgroupid, $groupid) === false) {
1170 unset($searchgroupid[$index]);
1171 }
1172 }
1173 if (count($searchgroupid) == 0) {
1174 $novalidgroups = true;
1175 }
1176 } else {
1177 if (array_search($groupid, $searchgroupid) === false) {
1178 $novalidgroups = true;
1179 }
1180 }
1181 if ($novalidgroups) {
1182 error('The user does not belong in the group(s) specified '.
1183 'by $groupid and the user does not have the '.
1184 'required permission to view posts from all '.
1185 'groups.');
1186 }
1187 }
1188 $separategroups = SEPARATEGROUPS;
1189 $selectgroup = " AND ( NOT (cm.groupmode='$separategroups'".
1190 " OR (c.groupmode='$separategroups' AND c.groupmodeforce='1') )";//.
1191 foreach ($searchgroupid as $index => $value){
1192 $selectgroup .= " OR d.groupid = '$value'";
1193 }
1194 $selectgroup .= ")";
1195 // " OR d.groupid = '$groupid')";
1196 $selectcourse = " AND d.course = '$courseid' AND c.id='$courseid'";
1197 $coursetable = ", {$CFG->prefix}course c";
9fa49e22 1198 }
1199
6af7cc22 1200 $timelimit = '';
86e75a7b 1201 if (!empty($CFG->forum_enabletimedposts) && (!((isadmin() and !empty($CFG->admineditalways)) || isteacher($courseid)))) {
6af7cc22 1202 $now = time();
c7ac6225 1203 $timelimit = " AND (d.userid = $USER->id OR ((d.timestart = 0 OR d.timestart <= $now) AND (d.timeend = 0 OR d.timeend > $now)))";
6af7cc22 1204 }
1205
e6ae4dc8 1206 $limit = sql_paging_limit($page, $recordsperpage);
97485d07 1207
63d99fcb 1208 /// Some differences in syntax for PostgreSQL
1209 if ($CFG->dbtype == "postgres7") {
a74f950c 1210 $LIKE = "ILIKE"; // case-insensitive
2b4c64e9 1211 $NOTLIKE = "NOT ILIKE"; // case-insensitive
1212 $REGEXP = "~*";
1213 $NOTREGEXP = "!~*";
b800ac5a 1214 } else {
a74f950c 1215 $LIKE = "LIKE";
2b4c64e9 1216 $NOTLIKE = "NOT LIKE";
a74f950c 1217 $REGEXP = "REGEXP";
2b4c64e9 1218 $NOTREGEXP = "NOT REGEXP";
c4c57597 1219 }
1220
b800ac5a 1221 $messagesearch = "";
855c0839 1222 $searchstring = "";
1223 // Need to concat these back together for parser to work.
1224 foreach($searchterms as $searchterm){
1225 if ($searchstring != "") {
1226 $searchstring .= " ";
63d99fcb 1227 }
855c0839 1228 $searchstring .= $searchterm;
b800ac5a 1229 }
1230
855c0839 1231 // We need to allow quoted strings for the search. The quotes *should* be stripped
1232 // by the parser, but this should be examined carefully for security implications.
1233 $searchstring = str_replace("\\\"","\"",$searchstring);
1234 $parser = new search_parser();
f99fcffe 1235 $lexer = new search_lexer($parser);
e6ae4dc8 1236
855c0839 1237 if ($lexer->parse($searchstring)) {
1238 $parsearray = $parser->get_parsed_array();
77ffdf4b 1239 $messagesearch = search_generate_SQL($parsearray,'p.message','p.subject','p.userid','u.id','u.firstname','u.lastname','p.modified', 'd.forum');
855c0839 1240 }
bbbf2d40 1241
1242 /*
65b0e537 1243 $selectsql = "{$CFG->prefix}forum_posts p,
1244 {$CFG->prefix}forum_discussions d,
453b5314 1245 {$CFG->prefix}user u $onlyvisibletable $coursetable
855c0839 1246 WHERE ($messagesearch)
65b0e537 1247 AND p.userid = u.id
6af7cc22 1248 AND p.discussion = d.id $selectcourse $notteacherforum $onlyvisible $selectgroup $timelimit $extrasql";
bbbf2d40 1249 */
1250
1251 $selectsql = "{$CFG->prefix}forum_posts p,
1252 {$CFG->prefix}forum_discussions d,
1253 {$CFG->prefix}user u $onlyvisibletable $coursetable
1254 WHERE ($messagesearch)
1255 AND p.userid = u.id
1256 AND p.discussion = d.id $selectcourse $onlyvisible $selectgroup $timelimit $extrasql";
1257
8b9c7aa0 1258 $totalcount = count_records_sql("SELECT COUNT(*) FROM $selectsql");
b800ac5a 1259
77efef3e 1260 return get_records_sql("SELECT p.*,d.forum, u.firstname,u.lastname,u.email,u.picture FROM
8b9c7aa0 1261 $selectsql ORDER BY p.modified DESC $limit");
9fa49e22 1262}
1263
63d99fcb 1264
9fa49e22 1265function forum_get_ratings($postid, $sort="u.firstname ASC") {
1266/// Returns a list of ratings for a particular post - sorted.
1267 global $CFG;
65b0e537 1268 return get_records_sql("SELECT u.*, r.rating, r.time
1269 FROM {$CFG->prefix}forum_ratings r,
9fa49e22 1270 {$CFG->prefix}user u
65b0e537 1271 WHERE r.post = '$postid'
1272 AND r.userid = u.id
9fa49e22 1273 ORDER BY $sort");
1274}
1275
3ecca1ee 1276function forum_get_unmailed_posts($starttime, $endtime) {
1f48942e 1277/// Returns a list of all new posts that have not been mailed yet
1278 global $CFG;
fbc21e82 1279 $now = time();
65b0e537 1280 return get_records_sql("SELECT p.*, d.course
1281 FROM {$CFG->prefix}forum_posts p,
1f48942e 1282 {$CFG->prefix}forum_discussions d
65b0e537 1283 WHERE p.mailed = 0
b12d055a 1284 AND (p.created >= '$starttime' OR d.timestart > 0)
41547057 1285 AND (p.created < '$endtime' OR p.mailnow = 1)
c274b0e0 1286 AND p.discussion = d.id
fbc21e82 1287 AND ((d.timestart = 0 OR d.timestart <= '$now')
1288 AND (d.timeend = 0 OR d.timeend > '$now'))
0fcac008 1289 ORDER BY p.modified ASC");
1f48942e 1290}
1291
3ecca1ee 1292function forum_mark_old_posts_as_mailed($endtime) {
1293/// Marks posts before a certain time as being mailed already
1294 global $CFG;
0f620d4b 1295/// Find out posts those are not showing immediately so we can exclude them
1296 $now = time();
1297 $delayed_posts = get_records_sql("SELECT p.id, p.discussion
1298 FROM {$CFG->prefix}forum_posts p,
1299 {$CFG->prefix}forum_discussions d
1300 WHERE p.mailed = 0
1301 AND p.discussion = d.id
1302 AND d.timestart > '$now'");
1303 $delayed_ids = array();
1304 if ($delayed_posts) {
1305 foreach ($delayed_posts as $post) {
1306 $delayed_ids[] = $post->id;
1307 }
1308 } else {
1309 $delayed_ids[] = 0;
1310 }
c274b0e0 1311 return execute_sql("UPDATE {$CFG->prefix}forum_posts
1312 SET mailed = '1'
41547057 1313 WHERE id NOT IN (".implode(',',$delayed_ids).") AND (created < '$endtime' OR mailnow = 1) AND mailed ='0'");
3ecca1ee 1314}
1315
1f48942e 1316function forum_get_user_posts($forumid, $userid) {
1317/// Get all the posts for a user in a forum suitable for forum_print_post
1318 global $CFG;
1319
77efef3e 1320 return get_records_sql("SELECT p.*, d.forum, u.firstname, u.lastname, u.email, u.picture
65b0e537 1321 FROM {$CFG->prefix}forum f,
1322 {$CFG->prefix}forum_discussions d,
1323 {$CFG->prefix}forum_posts p,
1324 {$CFG->prefix}user u
1325 WHERE f.id = '$forumid'
1326 AND d.forum = f.id
1f48942e 1327 AND p.discussion = d.id
65b0e537 1328 AND p.userid = '$userid'
ebc3bd2b 1329 AND p.userid = u.id
1f48942e 1330 ORDER BY p.modified ASC");
1331}
1332
1333function forum_get_post_from_log($log) {
1334/// Given a log entry, return the forum post details for it.
1335 global $CFG;
1336
1337 if ($log->action == "add post") {
1338
8f7dc7f1 1339 return get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1340 u.firstname, u.lastname, u.email, u.picture
65b0e537 1341 FROM {$CFG->prefix}forum_discussions d,
1342 {$CFG->prefix}forum_posts p,
8f7dc7f1 1343 {$CFG->prefix}forum f,
65b0e537 1344 {$CFG->prefix}user u
1345 WHERE p.id = '$log->info'
1346 AND d.id = p.discussion
1347 AND p.userid = u.id
8f7dc7f1 1348 AND u.deleted <> '1'
1349 AND f.id = d.forum");
1f48942e 1350
1351
1352 } else if ($log->action == "add discussion") {
1353
8f7dc7f1 1354 return get_record_sql("SELECT p.*, f.type AS forumtype, d.forum, d.groupid,
1355 u.firstname, u.lastname, u.email, u.picture
65b0e537 1356 FROM {$CFG->prefix}forum_discussions d,
1357 {$CFG->prefix}forum_posts p,
8f7dc7f1 1358 {$CFG->prefix}forum f,
65b0e537 1359 {$CFG->prefix}user u
1360 WHERE d.id = '$log->info'
1361 AND d.firstpost = p.id
1362 AND p.userid = u.id
8f7dc7f1 1363 AND u.deleted <> '1'
1364 AND f.id = d.forum");
1f48942e 1365 }
1366 return NULL;
1367}
1368
d05956ac 1369function forum_get_firstpost_from_discussion($discussionid) {
1370/// Given a discussion id, return the first post from the discussion
1371 global $CFG;
1372
1373 return get_record_sql("SELECT p.*
65b0e537 1374 FROM {$CFG->prefix}forum_discussions d,
d05956ac 1375 {$CFG->prefix}forum_posts p
65b0e537 1376 WHERE d.id = '$discussionid'
d05956ac 1377 AND d.firstpost = p.id ");
1378}
1379
1f48942e 1380
1381function forum_get_user_grades($forumid) {
1382/// Get all user grades for a forum
1383 global $CFG;
1384
ebc3bd2b 1385 return get_records_sql("SELECT r.id, p.userid, r.rating
65b0e537 1386 FROM {$CFG->prefix}forum_discussions d,
1387 {$CFG->prefix}forum_posts p,
1f48942e 1388 {$CFG->prefix}forum_ratings r
65b0e537 1389 WHERE d.forum = '$forumid'
1f48942e 1390 AND p.discussion = d.id
02ebf404 1391 AND r.post = p.id
1392 ORDER by p.userid ");
1f48942e 1393}
1394
1395
a48e8c4b 1396function forum_count_discussion_replies($forum='0', $course='0', $user='0') {
1397// Returns an array of counts of replies to each discussion (optionally in one forum or course and/or user)
1f48942e 1398 global $CFG;
1399
a48e8c4b 1400 $forumselect = $courseselect = $userselect = '';
1401
1f48942e 1402 if ($forum) {
1403 $forumselect = " AND d.forum = '$forum'";
a48e8c4b 1404 }
1405 if ($course) {
1406 $courseselect = " AND d.course = '$course'";
1407 }
1408 if ($user) {
1409 $userselect = " AND d.userid = '$user'";
1f48942e 1410 }
3599e487 1411 return get_records_sql("SELECT p.discussion, (count(*)) as replies, max(p.id) as lastpostid
65b0e537 1412 FROM {$CFG->prefix}forum_posts p,
1f48942e 1413 {$CFG->prefix}forum_discussions d
a48e8c4b 1414 WHERE p.parent > 0 $forumselect $courseselect $userselect
1c887009 1415 AND p.discussion = d.id
1f48942e 1416 GROUP BY p.discussion");
1417}
1418
1419function forum_count_unrated_posts($discussionid, $userid) {
1420// How many unrated posts are in the given discussion for a given user?
1421 global $CFG;
1422 if ($posts = get_record_sql("SELECT count(*) as num
1423 FROM {$CFG->prefix}forum_posts
65b0e537 1424 WHERE parent > 0
1425 AND discussion = '$discussionid'
ebc3bd2b 1426 AND userid <> '$userid' ")) {
1f48942e 1427
65b0e537 1428 if ($rated = get_record_sql("SELECT count(*) as num
1429 FROM {$CFG->prefix}forum_posts p,
1f48942e 1430 {$CFG->prefix}forum_ratings r
1431 WHERE p.discussion = '$discussionid'
65b0e537 1432 AND p.id = r.post
ebc3bd2b 1433 AND r.userid = '$userid'")) {
1f48942e 1434 $difference = $posts->num - $rated->num;
1435 if ($difference > 0) {
1436 return $difference;
1437 } else {
1438 return 0; // Just in case there was a counting error
1439 }
1440 } else {
1441 return $posts->num;
1442 }
1443 } else {
1444 return 0;
1445 }
1446}
1447
65b0e537 1448function forum_get_discussions($forum="0", $forumsort="d.timemodified DESC",
13597d01 1449 $user=0, $fullpost=true, $visiblegroups=-1, $limit=0, $userlastmodified=false) {
1f48942e 1450/// Get all discussions in a forum
fbc21e82 1451 global $CFG, $USER;
0fcac008 1452
3d284127 1453 $timelimit = '';
1454
1455 if (!empty($CFG->forum_enabletimedposts)) {
7613e6d7 1456
1457 if (!$cm = get_coursemodule_from_instance('forum', $forum)) {
1458 error('Course Module ID was incorrect');
1459 }
1460 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1461
0468976c 1462 if (!has_capability('mod/forum:viewhiddentimedposts', $modcontext)) {
3d284127 1463 $now = time();
1464 $timelimit = " AND ((d.timestart = 0 OR d.timestart <= '$now') AND (d.timeend = 0 OR d.timeend > '$now')";
1465 if (!empty($USER->id)) {
1466 $timelimit .= " OR d.userid = '$USER->id'";
1467 }
1468 $timelimit .= ')';
fbc21e82 1469 }
fbc21e82 1470 }
1f48942e 1471
1472 if ($user) {
1473 $userselect = " AND u.id = '$user' ";
1474 } else {
1475 $userselect = "";
1476 }
2862b309 1477
90ec387a 1478 if ($limit) {
1479 $limit = " LIMIT $limit ";
1480 } else {
1481 $limit = "";
1482 }
8f0cd6ef 1483
2862b309 1484 if ($visiblegroups == -1) {
02509fe6 1485 $groupselect = "";
2862b309 1486 } else {
1487 $groupselect = " AND (d.groupid = '$visiblegroups' OR d.groupid = '-1') ";
02509fe6 1488 }
2862b309 1489
29507631 1490 if (empty($forumsort)) {
1491 $forumsort = "d.timemodified DESC";
1492 }
2ab968e9 1493 if (empty($fullpost)) {
b879effb 1494 $postdata = "p.id,p.subject,p.modified,p.discussion,p.userid";
2ab968e9 1495 } else {
1496 $postdata = "p.*";
1497 }
9197e147 1498
13597d01 1499 if (empty($userlastmodified)) { // We don't need to know this
1500 $umfields = '';
1501 $umtable = '';
13597d01 1502 } else {
096de9ad 1503 $umfields = ', um.firstname AS umfirstname, um.lastname AS umlastname';
cfdc10e6 1504 $umtable = ' LEFT JOIN '.$CFG->prefix.'user um on (d.usermodified = um.id)';
13597d01 1505 }
1506
80d3523e 1507 //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.
1508 if ($CFG->dbtype == 'postgres7') {
1509 return get_records_sql("SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid,
13597d01 1510 u.firstname, u.lastname, u.email, u.picture $umfields
93d58b30 1511 FROM {$CFG->prefix}forum_discussions d
1512 JOIN {$CFG->prefix}forum_posts p ON p.discussion = d.id
1513 JOIN {$CFG->prefix}user u ON p.userid = u.id
13597d01 1514 $umtable
65b0e537 1515 WHERE d.forum = '$forum'
65b0e537 1516 AND p.parent = 0
0fcac008 1517 $timelimit $groupselect $userselect
1518 ORDER BY $forumsort $limit");
80d3523e 1519 } else {
1520 return get_records_sql("SELECT $postdata, d.name, d.timemodified, d.usermodified, d.groupid,
1521 u.firstname, u.lastname, u.email, u.picture $umfields
fd6590a9 1522 FROM ({$CFG->prefix}forum_posts p,
b73b9d81 1523 {$CFG->prefix}user u,
fd6590a9 1524 {$CFG->prefix}forum_discussions d)
80d3523e 1525 $umtable
1526 WHERE d.forum = '$forum'
1527 AND p.discussion = d.id
1528 AND p.parent = 0
80329e02 1529 AND p.userid = u.id $timelimit $groupselect $userselect
0fcac008 1530 ORDER BY $forumsort $limit");
80d3523e 1531 }
1f48942e 1532}
1533
1534
1535
b656e2a9 1536function forum_get_user_discussions($courseid, $userid, $groupid=0) {
1537/// Get all discussions started by a particular user in a course (or group)
4f321bdb 1538/// This function no longer used ...
1f48942e 1539 global $CFG;
1540
b656e2a9 1541 if ($groupid) {
1542 $groupselect = " AND d.groupid = '$groupid' ";
1543 } else {
1544 $groupselect = "";
1545 }
1546
2862b309 1547 return get_records_sql("SELECT p.*, d.groupid, u.firstname, u.lastname, u.email, u.picture,
ebc3bd2b 1548 f.type as forumtype, f.name as forumname, f.id as forumid
65b0e537 1549 FROM {$CFG->prefix}forum_discussions d,
1550 {$CFG->prefix}forum_posts p,
1551 {$CFG->prefix}user u,
1f48942e 1552 {$CFG->prefix}forum f
65b0e537 1553 WHERE d.course = '$courseid'
1554 AND p.discussion = d.id
1555 AND p.parent = 0
1556 AND p.userid = u.id
1557 AND u.id = '$userid'
b656e2a9 1558 AND d.forum = f.id $groupselect
b8bf90c5 1559 ORDER BY p.created DESC");
1f48942e 1560}
1561
6673d7bd 1562function forum_subscribed_users($course, $forum, $groupid=0) {
1f48942e 1563/// Returns list of user objects that are subscribed to this forum
1564 global $CFG;
1565
6673d7bd 1566 if ($groupid) {
1567 $grouptables = ", {$CFG->prefix}groups_members g";
1568 $groupselect = " AND g.groupid = '$groupid' AND u.id = g.userid";
1569 } else {
1570 $grouptables = "";
1571 $groupselect = "";
1572 }
1573
709f0ec8 1574 if (forum_is_forcesubscribed($forum->id)) {
7b5944cd 1575 if ($forum->type == "teacher") {
1576 return get_course_teachers($course->id); // Only teachers can be subscribed to teacher forums
adaf3928 1577 } else {
7b5944cd 1578 return get_course_users($course->id); // Otherwise get everyone in the course
1f48942e 1579 }
1580 }
aaf7a9dc 1581 return get_records_sql("SELECT u.id, u.username, u.firstname, u.lastname, u.maildisplay, u.mailformat, u.maildigest, u.emailstop,
4822e9d2 1582 u.email, u.city, u.country, u.lastaccess, u.lastlogin, u.picture, u.timezone, u.lang, u.trackforums
65b0e537 1583 FROM {$CFG->prefix}user u,
6673d7bd 1584 {$CFG->prefix}forum_subscriptions s $grouptables
1f48942e 1585 WHERE s.forum = '$forum->id'
65b0e537 1586 AND s.userid = u.id
6673d7bd 1587 AND u.deleted <> 1 $groupselect
7c81b6e2 1588 ORDER BY u.email ASC");
1f48942e 1589}
9fa49e22 1590
067675c0 1591
1592
caadf009 1593/// OTHER FUNCTIONS ///////////////////////////////////////////////////////////
f93f848a 1594
1595
11b0c469 1596function forum_get_course_forum($courseid, $type) {
1597// How to set up special 1-per-course forums
a6fcdf98 1598 global $CFG;
1599
29cbd93a 1600 if ($forums = get_records_select("forum", "course = '$courseid' AND type = '$type'", "id ASC")) {
65b0e537 1601 // There should always only be ONE, but with the right combination of
29cbd93a 1602 // errors there might be more. In this case, just return the oldest one (lowest ID).
1603 foreach ($forums as $forum) {
1604 return $forum; // ie the first one
11b0c469 1605 }
8daaf761 1606 }
e6874d9f 1607
8daaf761 1608 // Doesn't exist, so create one now.
1609 $forum->course = $courseid;
1610 $forum->type = "$type";
1611 switch ($forum->type) {
1612 case "news":
65a3ef30 1613 $forum->name = addslashes(get_string("namenews", "forum"));
1614 $forum->intro = addslashes(get_string("intronews", "forum"));
906fef94 1615 $forum->forcesubscribe = FORUM_FORCESUBSCRIBE;
8daaf761 1616 $forum->open = 1; // 0 - no, 1 - posts only, 2 - discuss and post
1617 $forum->assessed = 0;
709f0ec8 1618 if ($courseid == SITEID) {
1619 $forum->name = get_string("sitenews");
1620 $forum->forcesubscribe = 0;
8f0cd6ef 1621 }
8daaf761 1622 break;
1623 case "social":
65a3ef30 1624 $forum->name = addslashes(get_string("namesocial", "forum"));
1625 $forum->intro = addslashes(get_string("introsocial", "forum"));
8daaf761 1626 $forum->open = 2; // 0 - no, 1 - posts only, 2 - discuss and post
1627 $forum->assessed = 0;
1628 $forum->forcesubscribe = 0;
1629 break;
1630 case "teacher":
65a3ef30 1631 $forum->name = addslashes(get_string("nameteacher", "forum"));
1632 $forum->intro = addslashes(get_string("introteacher", "forum"));
a796d0b8 1633 $forum->open = 2; // 0 - no, 1 - posts only, 2 - discuss and post
8daaf761 1634 $forum->assessed = 0;
1635 $forum->forcesubscribe = 0;
1636 break;
1637 default:
1638 notify("That forum type doesn't exist!");
1639 return false;
1640 break;
1641 }
1642
1643 $forum->timemodified = time();
1644 $forum->id = insert_record("forum", $forum);
1645
1646 if ($forum->type != "teacher") {
1647 if (! $module = get_record("modules", "name", "forum")) {
1648 notify("Could not find forum module!!");
1649 return false;
1650 }
1651 $mod->course = $courseid;
1652 $mod->module = $module->id;
1653 $mod->instance = $forum->id;
1654 $mod->section = 0;
1655 if (! $mod->coursemodule = add_course_module($mod) ) { // assumes course/lib.php is loaded
1656 notify("Could not add a new course module to the course '$course->fullname'");
1657 return false;
1658 }
1659 if (! $sectionid = add_mod_to_section($mod) ) { // assumes course/lib.php is loaded
1660 notify("Could not add the new course module to that section");
1661 return false;
1662 }
1663 if (! set_field("course_modules", "section", $sectionid, "id", $mod->coursemodule)) {
1664 notify("Could not update the course module with the correct section");
1665 return false;
1666 }
1667 include_once("$CFG->dirroot/course/lib.php");
d769d2ee 1668 rebuild_course_cache($courseid);
82aa0e8d 1669 }
65b0e537 1670
8daaf761 1671 return get_record("forum", "id", "$forum->id");
82aa0e8d 1672}
1673
f93f848a 1674
65b0e537 1675function forum_make_mail_post(&$post, $user, $touser, $course,
11b0c469 1676 $ownpost=false, $reply=false, $link=false, $rate=false, $footer="") {
65b0e537 1677// Given the data about a posting, builds up the HTML to display it and
501cdbd8 1678// returns the HTML in a string. This is designed for sending via HTML email.
1679
d30867b0 1680 global $CFG;
501cdbd8 1681
0d851f90 1682 static $formattedtext; // Cached version of formatted text for a post
1683 static $formattedtextid; // The ID number of the post
1684
7613e6d7 1685
1686 if (!$forumid = get_record('discussion', 'id', $post->discussion)) {
1687 error('Could not get the forum id for the discussion the post belongs to');
1688 }
1689 if (!$cm = get_coursemodule_from_instance('forum', $forumid)) {
1690 error('Course Module ID was incorrect');
1691 }
1692 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
1693
1694
0d851f90 1695 if (empty($formattedtextid) or $formattedtextid != $post->id) { // Recalculate the formatting
326ce3c4 1696 $options = new Object;
1697 $options->para = true;
1698 $formattedtext = format_text($post->message, $post->format, $options, $course->id);
0d851f90 1699 $formattedtextid = $post->id;
1700 }
1701
add3201e 1702 $output = '<table border="0" cellpadding="3" cellspacing="0" class="forumpost">';
501cdbd8 1703
add3201e 1704 $output .= '<tr class="header"><td width="35" valign="top" class="picture left">';
501cdbd8 1705 $output .= print_user_picture($user->id, $course->id, $user->picture, false, true);
add3201e 1706 $output .= '</td>';
501cdbd8 1707
1708 if ($post->parent) {
add3201e 1709 $output .= '<td class="topic">';
501cdbd8 1710 } else {
add3201e 1711 $output .= '<td class="topic starter">';
501cdbd8 1712 }
add3201e 1713 $output .= '<div class="subject">'.format_string($post->subject).'</div>';
1b26d5e7 1714
0468976c 1715 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', $modcontext));
add3201e 1716 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$course->id.'">'.$fullname.'</a>';
1717 $by->date = userdate($post->modified, '', $touser->timezone);
1718 $output .= '<div class="author">'.get_string('bynameondate', 'forum', $by).'</div>';
1719
1720 $output .= '</td></tr>';
1721
7b54f563 1722 $output .= '<tr><td class="left side" valign="top">';
add3201e 1723 if ($group = user_group($course->id, $user->id)) {
f393f545 1724 $output .= print_group_picture($group, $course->id, false, true, true);
add3201e 1725 } else {
1726 $output .= '&nbsp;';
1727 }
1b26d5e7 1728
add3201e 1729 $output .= '</td><td class="content">';
501cdbd8 1730
7f6689e4 1731 if ($post->attachment) {
1732 $post->course = $course->id;
add3201e 1733 $post->forum = get_field('forum_discussions', 'forum', 'id', $post->discussion);
1734 $output .= '<div class="attachments">';
1735 $output .= forum_print_attachments($post, 'html');
72d497d4 1736 $output .= "</div>";
7f6689e4 1737 }
1738
0d851f90 1739 $output .= $formattedtext;
501cdbd8 1740
add3201e 1741
1742/// Commands
1743
1744 $commands = array();
501cdbd8 1745
2e2e71a8 1746 if ($post->parent) {
add3201e 1747 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1748 $post->discussion.'&amp;parent='.$post->parent.'">'.get_string('parent', 'forum').'</a>';
2e2e71a8 1749 }
ce45515e 1750
501cdbd8 1751 if ($ownpost) {
add3201e 1752 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?delete='.$post->id.'">'.
1753 get_string('delete', 'forum').'</a>';
1754 }
1755
1756 if ($reply) {
1757 $commands[] = '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.
1758 get_string('reply', 'forum').'</a>';
501cdbd8 1759 }
1760
add3201e 1761 $output .= '<div class="commands">';
1762 $output .= implode(' | ', $commands);
1763 $output .= '</div>';
1764
1765
1766/// Context link to post if required
65b0e537 1767
501cdbd8 1768 if ($link) {
add3201e 1769 $output .= '<div class="link">';
77e75a76 1770 $output .= '<a target="_blank" href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#'.$post->id.'">'.
add3201e 1771 get_string('postincontext', 'forum').'</a>';
1772 $output .= '</div>';
501cdbd8 1773 }
add3201e 1774
501cdbd8 1775 if ($footer) {
add3201e 1776 $output .= '<div class="footer">'.$footer.'</div>';
501cdbd8 1777 }
add3201e 1778 $output .= '</td></tr></table>'."\n\n";
1779
501cdbd8 1780
1781 return $output;
1782}
1783
1784
65b0e537 1785function forum_print_post(&$post, $courseid, $ownpost=false, $reply=false, $link=false,
f37da850 1786 $ratings=NULL, $footer="", $highlight="", $post_read=-99) {
74f5d1e3 1787
098d27d4 1788 global $USER, $CFG, $SESSION;
501cdbd8 1789
359f2758 1790 static $stredit, $strdelete, $strreply, $strparent, $strprune, $strpruneheading, $threadedmode, $isteacher, $adminedit;
2e2e71a8 1791
77efef3e 1792 static $strmarkread, $strmarkunread, $istracked;
f37da850 1793
098d27d4 1794 if (!forum_user_can_see_post($post->forum,$post->discussion,$post)) {
1795 if (empty($SESSION->forum_search)) {
1796 // just viewing, return
1797 return;
1798 }
1799 echo '<a name="'.$post->id.'"></a>';
1800 echo '<table cellspacing="0" class="forumpost">';
1801 echo '<tr class="header"><td class="picture left">';
1802 // print_user_picture($post->userid, $courseid, $post->picture);
1803 echo '</td>';
1804 if ($post->parent) {
1805 echo '<td class="topic">';
1806 } else {
1807 echo '<td class="topic starter">';
1808 }
1809 echo '<div class="subject">'.get_string('forumsubjecthidden','forum').'</div>';
1810 echo '<div class="author">';
1811 print_string('forumauthorhidden','forum');
1812 echo '</div></td></tr>';
1813
1814 echo '<tr><td class="left side">';
1815 echo '&nbsp;';
1816
1817 /// Actual content
1818
1819 echo '</td><td class="content">'."\n";
1820 echo get_string('forumbodyhidden','forum');
1821 echo '</td></tr></table>';
1822 return;
1823 }
1824
2e2e71a8 1825 if (empty($stredit)) {
359f2758 1826 $stredit = get_string('edit', 'forum');
1827 $strdelete = get_string('delete', 'forum');
1828 $strreply = get_string('reply', 'forum');
1829 $strparent = get_string('parent', 'forum');
1830 $strpruneheading = get_string('pruneheading', 'forum');
d494dd83 1831 $strprune = get_string('prune', 'forum');
2e2e71a8 1832 $threadedmode = (!empty($USER->mode) and ($USER->mode == FORUM_MODE_THREADED));
3bd98ad4 1833 $isteacher = isteacher($courseid);
b8be40ce 1834 $adminedit = (isadmin() and !empty($CFG->admineditalways));
f37da850 1835 $strmarkread = get_string('markread', 'forum');
1836 $strmarkunread = get_string('markunread', 'forum');
77efef3e 1837
1838 if (!empty($post->forum)) {
1839 $istracked = (forum_tp_can_track_forums($post->forum) &&
1840 forum_tp_is_tracked($post->forum));
1841 } else {
1842 $istracked = false;
1843 }
f37da850 1844 }
1845
eaf50aef 1846 if ($istracked) {
f37da850 1847 if ($post_read == -99) { // If we don't know yet...
489de4ae 1848 /// The front page can display a news item post to non-logged in users. This should
1849 /// always appear as 'read'.
1850 $post_read = empty($USER) || forum_tp_is_post_read($USER->id, $post);
f37da850 1851 }
1852 if ($post_read) {
1853 $read_style = ' read';
1854 } else {
1855 $read_style = ' unread';
1856 echo '<a name="unread"></a>';
1857 }
1858 } else {
1859 $read_style = '';
2e2e71a8 1860 }
1861
f37da850 1862 echo '<a name="'.$post->id.'"></a>';
33200577 1863 echo '<table cellspacing="0" class="forumpost'.$read_style.'">';
501cdbd8 1864
d3583b41 1865 echo '<tr class="header"><td class="picture left">';
501cdbd8 1866 print_user_picture($post->userid, $courseid, $post->picture);
d3583b41 1867 echo '</td>';
501cdbd8 1868
1869 if ($post->parent) {
d3583b41 1870 echo '<td class="topic">';
501cdbd8 1871 } else {
d3583b41 1872 echo '<td class="topic starter">';
501cdbd8 1873 }
83ec9098 1874
d3583b41 1875 echo '<div class="subject">'.$post->subject.'</div>';
e3ff14ca 1876
d3583b41 1877 echo '<div class="author">';
3bd98ad4 1878 $fullname = fullname($post, $isteacher);
d3583b41 1879 $by->name = '<a href="'.$CFG->wwwroot.'/user/view.php?id='.
1880 $post->userid.'&amp;course='.$courseid.'">'.$fullname.'</a>';
d62413e8 1881 $by->date = userdate($post->modified);
d3583b41 1882 print_string('bynameondate', 'forum', $by);
1883 echo '</div></td></tr>';
1b26d5e7 1884
d3583b41 1885 echo '<tr><td class="left side">';
507407a7 1886 if ($group = user_group($courseid, $post->userid)) {
a4fbb0b2 1887 print_group_picture($group, $courseid, false, false, true);
507407a7 1888 } else {
d3583b41 1889 echo '&nbsp;';
507407a7 1890 }
d3583b41 1891
1892/// Actual content
1893
1894 echo '</td><td class="content">'."\n";
501cdbd8 1895
7f6689e4 1896 if ($post->attachment) {
1897 $post->course = $courseid;
d3583b41 1898 $post->forum = get_field('forum_discussions', 'forum', 'id', $post->discussion);
1899 echo '<div class="attachments">';
72d497d4 1900 $attachedimages = forum_print_attachments($post);
d3583b41 1901 echo '</div>';
e9c2dc1f 1902 } else {
d3583b41 1903 $attachedimages = '';
7f6689e4 1904 }
1905
d3583b41 1906
326ce3c4 1907 $options = new Object;
1908 $options->para = false;
5be7800c 1909 if ($link and (strlen(strip_tags($post->message)) > $CFG->forum_longpost)) {
aa153f29 1910 // Print shortened version
326ce3c4 1911 echo format_text(forum_shorten_post($post->message), $post->format, $options, $courseid);
c585fa17 1912 $numwords = count_words(strip_tags($post->message));
d3583b41 1913 echo '<p><a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
1914 echo get_string('readtherest', 'forum');
1915 echo '</a> ('.get_string('numwords', '', $numwords).')...</p>';
501cdbd8 1916 } else {
aa153f29 1917 // Print whole message
88438a58 1918 if ($highlight) {
326ce3c4 1919 echo highlight($highlight, format_text($post->message, $post->format, $options, $courseid));
88438a58 1920 } else {
326ce3c4 1921 echo format_text($post->message, $post->format, $options, $courseid);
88438a58 1922 }
65b0e537 1923 echo $attachedimages;
501cdbd8 1924 }
1925
d3583b41 1926
1927/// Commands
1928
359f2758 1929 $commands = array();
501cdbd8 1930
eaf50aef 1931 if ($istracked) {
489de4ae 1932 /// SPECIAL CASE: The front page can display a news item post to non-logged in users.
1933 /// Don't display the mark read / unread controls in this case.
1934 if ($CFG->forum_usermarksread && !empty($USER)) {
f37da850 1935 if ($post_read) {
1936 $mcmd = '&amp;mark=unread&amp;postid='.$post->id;
1937 $mtxt = $strmarkunread;
1938 } else {
1939 $mcmd = '&amp;mark=read&amp;postid='.$post->id;
1940 $mtxt = $strmarkread;
1941 }
1942 if ($threadedmode) {
d3583b41 1943 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1944 $post->discussion.'&amp;parent='.$post->id.$mcmd.'">'.$mtxt.'</a>';
f37da850 1945 } else {
d3583b41 1946 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1947 $post->discussion.$mcmd.'#'.$post->id.'">'.$mtxt.'</a>';
f37da850 1948 }
1949 }
1950 }
1951
2e2e71a8 1952 if ($post->parent) {
1953 if ($threadedmode) {
d3583b41 1954 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1955 $post->discussion.'&amp;parent='.$post->parent.'">'.$strparent.'</a>';
2e2e71a8 1956 } else {
d3583b41 1957 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.
1958 $post->discussion.'#'.$post->parent.'">'.$strparent.'</a>';
2e2e71a8 1959 }
1960 }
1961
501cdbd8 1962 $age = time() - $post->created;
fbc21e82 1963 /// Hack for allow to edit news posts those are not displayed yet until they are displayed
1964 if (!$post->parent
1965 && get_field('forum', 'type', 'id', $post->forum) == 'news'
1966 && get_field_sql("SELECT id FROM {$CFG->prefix}forum_discussions WHERE id = $post->discussion AND timestart > ".time())) {
1967 $age = 0;
1968 }
b8be40ce 1969 if ($ownpost or $adminedit) {
1970 if (($age < $CFG->maxeditingtime) or $adminedit) {
d3583b41 1971 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?edit='.$post->id.'">'.$stredit.'</a>';
501cdbd8 1972 }
64eacd6f 1973 }
aaf7a9dc 1974
cf84431b 1975 if (isteacheredit($courseid) and $post->parent) {
d3583b41 1976 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?prune='.$post->id.
1977 '" title="'.$strpruneheading.'">'.$strprune.'</a>';
cf84431b 1978 }
aaf7a9dc 1979
ac00b904 1980 if (($ownpost and $age < $CFG->maxeditingtime) or $isteacher) {
d3583b41 1981 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?delete='.$post->id.'">'.$strdelete.'</a>';
64eacd6f 1982 }
359f2758 1983
64eacd6f 1984 if ($reply) {
d3583b41 1985 $commands[] = '<a href="'.$CFG->wwwroot.'/mod/forum/post.php?reply='.$post->id.'">'.$strreply.'</a>';
501cdbd8 1986 }
501cdbd8 1987
d3583b41 1988 echo '<div class="commands">';
1989 echo implode(' | ', $commands);
1990 echo '</div>';
1991
1992
1993/// Ratings
74f5d1e3 1994
1995 $ratingsmenuused = false;
02ebf404 1996 if (!empty($ratings) and !empty($USER->id)) {
d3583b41 1997 echo '<div class="ratings">';
98914efd 1998 $useratings = true;
1999 if ($ratings->assesstimestart and $ratings->assesstimefinish) {
2000 if ($post->created < $ratings->assesstimestart or $post->created > $ratings->assesstimefinish) {
2001 $useratings = false;
2002 }
2003 }
2004 if ($useratings) {
3bd98ad4 2005 $mypost = ($USER->id == $post->userid);
2006
2007 if (($isteacher or $ratings->assesspublic) and !$mypost) {
2008 forum_print_ratings_mean($post->id, $ratings->scale, $isteacher);
d395046a 2009 if (!empty($ratings->allow)) {
d3583b41 2010 echo '&nbsp;';
d395046a 2011 forum_print_rating_menu($post->id, $USER->id, $ratings->scale);
2012 $ratingsmenuused = true;
2013 }
3bd98ad4 2014
2015 } else if ($mypost) {
2016 forum_print_ratings_mean($post->id, $ratings->scale, true);
2017
98914efd 2018 } else if (!empty($ratings->allow) ) {
2019 forum_print_rating_menu($post->id, $USER->id, $ratings->scale);
74f5d1e3 2020 $ratingsmenuused = true;
2a3cda19 2021 }
501cdbd8 2022 }
d3583b41 2023 echo '</div>';
501cdbd8 2024 }
65b0e537 2025
d3583b41 2026/// Link to post if required
2027
501cdbd8 2028 if ($link) {
d3583b41 2029 echo '<div class="link">';
501cdbd8 2030 if ($post->replies == 1) {
d3583b41 2031 $replystring = get_string('repliesone', 'forum', $post->replies);
501cdbd8 2032 } else {
d3583b41 2033 $replystring = get_string('repliesmany', 'forum', $post->replies);
501cdbd8 2034 }
d3583b41 2035 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.
2036 get_string('discussthistopic', 'forum').'</a>&nbsp;('.$replystring.')';
2037 echo '</div>';
501cdbd8 2038 }
d3583b41 2039
501cdbd8 2040 if ($footer) {
d3583b41 2041 echo '<div class="footer">'.$footer.'</div>';
501cdbd8 2042 }
d3583b41 2043 echo '</td></tr></table>'."\n\n";
74f5d1e3 2044
eaf50aef 2045 if ($istracked && !$CFG->forum_usermarksread && !empty($post->forum)) {
f37da850 2046 forum_tp_mark_post_read($USER->id, $post, $post->forum);
2047 }
2048
74f5d1e3 2049 return $ratingsmenuused;
501cdbd8 2050}
eaf50aef 2051/**
2052* This function prints the overview of a discussion in the forum listing.
2053* It needs some discussion information and some post information, these
2054* happen to be combined for efficiency in the $post parameter by the function
2055* that calls this one: forum_print_latest_discussions()
2056*
2057* @param object $post The post object (passed by reference for speed).
2058* @param object $forum The forum object.
2059* @param int $group Current group.
2060* @param string $datestring Format to use for the dates.
2061* @param boolean $cantrack Is tracking enabled for this forum.
2062* @param boolean $forumtracked Is the user tracking this forum.
2063*/
2064function forum_print_discussion_header(&$post, $forum, $group=-1, $datestring="", $cantrack=true, $forumtracked=true) {
43921b8a 2065
d30867b0 2066 global $USER, $CFG;
3335f6fb 2067
f51e8d7e 2068 static $rowcount;
5733262d 2069 static $strmarkalldread;
f51e8d7e 2070
2071 if (!isset($rowcount)) {
2072 $rowcount = 0;
5733262d 2073 $strmarkalldread = get_string('markalldread', 'forum');
f51e8d7e 2074 } else {
2075 $rowcount = ($rowcount + 1) % 2;
2076 }
2077
17dc3f3c 2078 $post->subject = format_string($post->subject,true);
436a7cae 2079
f51e8d7e 2080 echo "\n\n";
2081 echo '<tr class="discussion r'.$rowcount.'">';
3335f6fb 2082
29507631 2083 // Topic
f51e8d7e 2084 echo '<td class="topic starter">';
2085 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">'.$post->subject.'</a>';
29507631 2086 echo "</td>\n";
2087
2088 // Picture
f51e8d7e 2089 echo '<td class="picture">';
a796d0b8 2090 print_user_picture($post->userid, $forum->course, $post->picture);
29507631 2091 echo "</td>\n";
3335f6fb 2092
29507631 2093 // User name
a796d0b8 2094 $fullname = fullname($post, isteacher($forum->course));
f51e8d7e 2095 echo '<td class="author">';
2096 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->userid.'&amp;course='.$forum->course.'">'.$fullname.'</a>';
29507631 2097 echo "</td>\n";
2098
3a68fbbb 2099 // Group picture
425b4f1a 2100 if ($group !== -1) { // Groups are active - group is a group data object or NULL
f51e8d7e 2101 echo '<td class="picture group">';
c2b552fe 2102 if (!empty($group->picture) and empty($group->hidepicture)) {
3a68fbbb 2103 print_group_picture($group, $forum->course, false, false, true);
2104 } else if (isset($group->id)) {
fa22fd5f 2105 echo '<a href="'.$CFG->wwwroot.'/user/index.php?id='.$forum->course.'&amp;group='.$group->id.'">'.$group->name.'</a>';
3a68fbbb 2106 }
2107 echo "</td>\n";
2108 }
2109
f51e8d7e 2110 if ($forum->open or $forum->type == 'teacher') { // Show the column with replies
2111 echo '<td class="replies">';
2112 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'">';
2113 echo $post->replies.'</a>';
a796d0b8 2114 echo "</td>\n";
e3ff14ca 2115
eaf50aef 2116 if ($cantrack) {
f51e8d7e 2117 echo '<td class="replies">';
eaf50aef 2118 if ($forumtracked) {
2119 if ($post->unread > 0) {
2120 echo '<span class="unread">';
2121 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2122 echo $post->unread;
2123 echo '</a>';
c39748f4 2124 echo '<a title="'.$strmarkalldread.'" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
eaf50aef 2125 $forum->id.'&amp;d='.$post->discussion.'&amp;mark=read&amp;returnpage=view.php">' .
fee287f3 2126 '<img src="'.$CFG->pixpath.'/t/clear.gif" height="11" width="11" /></a>';
eaf50aef 2127 echo '</span>';
2128 } else {
2129 echo '<span class="read">';
2130 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.'#unread">';
2131 echo $post->unread;
2132 echo '</a>';
2133 echo '</span>';
2134 }
f51e8d7e 2135 } else {
343af274 2136 echo '<span class="read">';
eaf50aef 2137 echo '-';
343af274 2138 echo '</span>';
3a68fbbb 2139 }
f37da850 2140 echo "</td>\n";
2141 }
a796d0b8 2142 }
3335f6fb 2143
f51e8d7e 2144 echo '<td class="lastpost">';
43921b8a 2145 $usedate = (empty($post->timemodified)) ? $post->modified : $post->timemodified; // Just in case
839f2456 2146 $parenturl = (empty($post->lastpostid)) ? '' : '&amp;parent='.$post->lastpostid;
098d27d4 2147 $usermodified->id = $post->usermodified;
268c6485 2148 $usermodified->firstname = $post->umfirstname;
2149 $usermodified->lastname = $post->umlastname;
f51e8d7e 2150 echo '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$post->usermodified.'&amp;course='.$forum->course.'">'.
2151 fullname($usermodified).'</a><br />';
ac00b904 2152 echo '<a href="'.$CFG->wwwroot.'/mod/forum/discuss.php?d='.$post->discussion.$parenturl.'">'.
43921b8a 2153 userdate($usedate, $datestring).'</a>';
29507631 2154 echo "</td>\n";
2155
f51e8d7e 2156 echo "</tr>\n\n";
3335f6fb 2157
3335f6fb 2158}
2159
2160
aa153f29 2161function forum_shorten_post($message) {
c585fa17 2162// Given a post object that we already know has a long message
65b0e537 2163// this function truncates the message nicely to the first
5be7800c 2164// sane place between $CFG->forum_longpost and $CFG->forum_shortpost
2165
2166 global $CFG;
c585fa17 2167
2168 $i = 0;
2169 $tag = false;
2170 $length = strlen($message);
2171 $count = 0;
2172 $stopzone = false;
2173 $truncate = 0;
2174
2175 for ($i=0; $i<$length; $i++) {
a8afb411 2176 $char = $message[$i];
c585fa17 2177
2178 switch ($char) {
65b0e537 2179 case "<":
c585fa17 2180 $tag = true;
2181 break;
65b0e537 2182 case ">":
c585fa17 2183 $tag = false;
2184 break;
2185 default:
2186 if (!$tag) {
2187 if ($stopzone) {
67f0b4cc 2188 if ($char == ".") {
a8afb411 2189 $truncate = $i+1;
c585fa17 2190 break 2;
2191 }
2192 }
2193 $count++;
2194 }
a8afb411 2195 break;
c585fa17 2196 }
2197 if (!$stopzone) {
5be7800c 2198 if ($count > $CFG->forum_shortpost) {
c585fa17 2199 $stopzone = true;
2200 }
2201 }
2202 }
aa153f29 2203
c585fa17 2204 if (!$truncate) {
a8afb411 2205 $truncate = $i;
c585fa17 2206 }
2207
67f0b4cc 2208 return substr($message, 0, $truncate);
aa153f29 2209}
2210
501cdbd8 2211
3bd98ad4 2212function forum_print_ratings_mean($postid, $scale, $link=true) {
02ebf404 2213/// Print the multiple ratings on a post given to the current user by others.
2214/// Scale is an array of ratings
2215
2216 static $strrate;
05c47ef7 2217
2218 $mean = forum_get_ratings_mean($postid, $scale);
65b0e537 2219
05c47ef7 2220 if ($mean !== "") {
02ebf404 2221
2222 if (empty($strratings)) {
2223 $strratings = get_string("ratings", "forum");
501cdbd8 2224 }
501cdbd8 2225
02ebf404 2226 echo "$strratings: ";
3bd98ad4 2227 if ($link) {
2228 link_to_popup_window ("/mod/forum/report.php?id=$postid", "ratings", $mean, 400, 600);
2229 } else {
2230 echo "$mean ";
2231 }
501cdbd8 2232 }
2233}
2234
501cdbd8 2235
0761d83f 2236function forum_get_ratings_mean($postid, $scale, $ratings=NULL) {
2237/// Return the mean rating of a post given to the current user by others.
02ebf404 2238/// Scale is an array of possible ratings in the scale
2239/// Ratings is an optional simple array of actual ratings (just integers)
2240
2241 if (!$ratings) {
2242 $ratings = array();
2243 if ($rates = get_records("forum_ratings", "post", $postid)) {
2244 foreach ($rates as $rate) {
2245 $ratings[] = $rate->rating;
2246 }
501cdbd8 2247 }
501cdbd8 2248 }
02ebf404 2249
0761d83f 2250 $count = count($ratings);
2251
2252 if ($count == 0) {
02ebf404 2253 return "";
02ebf404 2254
0761d83f 2255 } else if ($count == 1) {
2256 return $scale[$ratings[0]];
2257
02ebf404 2258 } else {
0761d83f 2259 $total = 0;
2260 foreach ($ratings as $rating) {
2261 $total += $rating;
2262 }
2263 $mean = round( ((float)$total/(float)$count) + 0.001); // Little fudge factor so that 0.5 goes UP
65b0e537 2264
0761d83f 2265 if (isset($scale[$mean])) {
2266 return $scale[$mean]." ($count)";
2267 } else {
2268 return "$mean ($count)"; // Should never happen, hopefully
2269 }
02ebf404 2270 }
2271}
2272
2273function forum_get_ratings_summary($postid, $scale, $ratings=NULL) {
2274/// Return a summary of post ratings given to the current user by others.
2275/// Scale is an array of possible ratings in the scale
2276/// Ratings is an optional simple array of actual ratings (just integers)
2277
2278 if (!$ratings) {
2279 $ratings = array();
2280 if ($rates = get_records("forum_ratings", "post", $postid)) {
2281 foreach ($rates as $rate) {
2282 $rating[] = $rate->rating;
2283 }
2284 }
2285 }
2286
2287
2288 if (!$count = count($ratings)) {
2289 return "";
2290 }
2291
2292
2293 foreach ($scale as $key => $scaleitem) {
2294 $sumrating[$key] = 0;
2295 }
2296
2297 foreach ($ratings as $rating) {
2298 $sumrating[$rating]++;
2299 }
2300
2301 $summary = "";
2302 foreach ($scale as $key => $scaleitem) {
2303 $summary = $sumrating[$key].$summary;
2304 if ($key > 1) {
2305 $summary = "/$summary";
2306 }
2307 }
2308 return $summary;
2309}
2310
2311function forum_print_rating_menu($postid, $userid, $scale) {
65b0e537 2312/// Print the menu of ratings as part of a larger form.
02ebf404 2313/// If the post has already been - set that value.
2314/// Scale is an array of ratings
2315
2316 static $strrate;
2317
2318 if (!$rating = get_record("forum_ratings", "userid", $userid, "post", $postid)) {
2319 $rating->rating = 0;
2320 }
2321
2322 if (empty($strrate)) {
2323 $strrate = get_string("rate", "forum");
2324 }
2325
2326 choose_from_menu($scale, $postid, $rating->rating, "$strrate...");
501cdbd8 2327}
2328
7a12aab4 2329function forum_print_mode_form($discussion, $mode) {
2330 GLOBAL $FORUM_LAYOUT_MODES;
501cdbd8 2331
839f2456 2332 echo "<div align=\"center\">";
2333 popup_form("discuss.php?d=$discussion&amp;mode=", $FORUM_LAYOUT_MODES, "mode", $mode, "");
2334 echo "</div>\n";
501cdbd8 2335}
2336
6f1cc8d6 2337function forum_search_form($course, $search='') {
501cdbd8 2338 global $CFG;
2339
bbbf2d40 2340 $output = '<table border="0" cellpadding="0" cellspacing="0"><tr><td nowrap="nowrap">';
2341 $output .= helpbutton('search', get_string('search'), 'moodle', true, false, '', true);
2342 $output .= '&nbsp;<form name="search" action="'.$CFG->wwwroot.'/mod/forum/search.php" style="display:inline">';
6f1cc8d6 2343 $output .= '<input name="search" type="text" size="18" value="'.$search.'" alt="search" />';
2344 $output .= '<input value="'.get_string('searchforums', 'forum').'" type="submit" />';
2345 $output .= '<input name="id" type="hidden" value="'.$course->id.'" />';
2346 $output .= '</form>';
bbbf2d40 2347 $output .= '</td></tr></table>';
5e367a2d 2348
6f1cc8d6 2349 return $output;
501cdbd8 2350}
2351
2352
11b0c469 2353function forum_set_return() {
607809b3 2354 global $CFG, $SESSION;
501cdbd8 2355
28e1e8b9 2356 if (! isset($SESSION->fromdiscussion)) {
48d38fad 2357 if (!empty($_SERVER['HTTP_REFERER'])) {
2358 $referer = $_SERVER['HTTP_REFERER'];
2359 } else {
2360 $referer = "";
2361 }
28e1e8b9 2362 // If the referer is NOT a login screen then save it.
48d38fad 2363 if (! strncasecmp("$CFG->wwwroot/login", $referer, 300)) {
607809b3 2364 $SESSION->fromdiscussion = $_SERVER["HTTP_REFERER"];
28e1e8b9 2365 }
501cdbd8 2366 }
2367}
2368
2369
11b0c469 2370function forum_go_back_to($default) {
501cdbd8 2371 global $SESSION;
2372
9c9f7d77 2373 if (!empty($SESSION->fromdiscussion)) {
501cdbd8 2374 $returnto = $SESSION->fromdiscussion;
2375 unset($SESSION->fromdiscussion);
2376 return $returnto;
2377 } else {
2378 return $default;
2379 }
2380}
2381
7f6689e4 2382function forum_file_area_name($post) {
2383// Creates a directory file name, suitable for make_upload_directory()
2384 global $CFG;
2385
2386 return "$post->course/$CFG->moddata/forum/$post->forum/$post->id";
2387}
2388
2389function forum_file_area($post) {
2390 return make_upload_directory( forum_file_area_name($post) );
2391}
2392
2393function forum_delete_old_attachments($post, $exception="") {
2394// Deletes all the user files in the attachments area for a post
2395// EXCEPT for any file named $exception
2396
2397 if ($basedir = forum_file_area($post)) {
2398 if ($files = get_directory_list($basedir)) {
2399 foreach ($files as $file) {
2400 if ($file != $exception) {
2401 unlink("$basedir/$file");
2402 notify("Existing file '$file' has been deleted!");
2403 }
2404 }
2405 }
2406 if (!$exception) { // Delete directory as well, if empty
2407 rmdir("$basedir");
2408 }
2409 }
2410}
2411
cc2b7ea5 2412function forum_move_attachments($discussion, $forumid) {
65b0e537 2413/// Given a discussion object that is being moved to forumid,
2414/// this function checks all posts in that discussion
2415/// for attachments, and if any are found, these are
cc2b7ea5 2416/// moved to the new forum directory.
2417
2418 global $CFG;
2419
18b8fbfa 2420 require_once($CFG->dirroot.'/lib/uploadlib.php');
2421
cc2b7ea5 2422 $return = true;
2423
2424 if ($posts = get_records_select("forum_posts", "discussion = '$discussion->id' AND attachment <> ''")) {
2425 foreach ($posts as $oldpost) {
2426 $oldpost->course = $discussion->course;
2427 $oldpost->forum = $discussion->forum;
2428 $oldpostdir = "$CFG->dataroot/".forum_file_area_name($oldpost);
2429 if (is_dir($oldpostdir)) {
2430 $newpost = $oldpost;
2431 $newpost->forum = $forumid;
03c9562b 2432 $newpostdir = forum_file_area_name($newpost);
2433 // take off the last directory because otherwise we're renaming to a directory that already exists
2434 // and this is unhappy in certain situations, eg over an nfs mount and potentially on windows too.
2435 make_upload_directory(substr($newpostdir,0,strrpos($newpostdir,'/')));
2436 $newpostdir = $CFG->dataroot.'/'.forum_file_area_name($newpost);
18b8fbfa 2437 $files = get_directory_list($oldpostdir); // get it before we rename it.
cc2b7ea5 2438 if (! @rename($oldpostdir, $newpostdir)) {
2439 $return = false;
2440 }
18b8fbfa 2441 foreach ($files as $file) {
2442 clam_change_log($oldpostdir.'/'.$file,$newpostdir.'/'.$file);
2443 }
cc2b7ea5 2444 }
2445 }
2446 }
2447 return $return;
2448}
2449
7f6689e4 2450function forum_print_attachments($post, $return=NULL) {
2451// if return=html, then return a html string.
2452// if return=text, then return a text-only string.
72d497d4 2453// otherwise, print HTML for non-images, and return image HTML
7f6689e4 2454
2455 global $CFG;
2456
2457 $filearea = forum_file_area_name($post);
2458
72d497d4 2459 $imagereturn = "";
2460 $output = "";
2461
7f6689e4 2462 if ($basedir = forum_file_area($post)) {
2463 if ($files = get_directory_list($basedir)) {
2464 $strattachment = get_string("attachment", "forum");
2465 foreach ($files as $file) {
2466 $icon = mimeinfo("icon", $file);
2467 if ($CFG->slasharguments) {
2a1975cb 2468 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
7f6689e4 2469 } else {
2a1975cb 2470 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
7f6689e4 2471 }
2a1975cb 2472 $image = "<img border=\"0\" src=\"$CFG->pixpath/f/$icon\" height=\"16\" width=\"16\" alt=\"\" />";
7f6689e4 2473
2474 if ($return == "html") {
2a1975cb 2475 $output .= "<a href=\"$ffurl\">$image</a> ";
2476 $output .= "<a href=\"$ffurl\">$file</a><br />";
7f6689e4 2477
2478 } else if ($return == "text") {
2a1975cb 2479 $output .= "$strattachment $file:\n$ffurl\n";
7f6689e4 2480
2481 } else {
72d497d4 2482 if ($icon == "image.gif") { // Image attachments don't get printed as links
2a1975cb 2483 $imagereturn .= "<br /><img src=\"$ffurl\" alt=\"\" />";
72d497d4 2484 } else {
2a1975cb 2485 echo "<a href=\"$ffurl\">$image</a> ";
bce7a133 2486 echo filter_text("<a href=\"$ffurl\">$file</a><br />");
72d497d4 2487 }
7f6689e4 2488 }
2489 }
2490 }
2491 }
72d497d4 2492
7f6689e4 2493 if ($return) {
2494 return $output;
2495 }
72d497d4 2496
2497 return $imagereturn;
7f6689e4 2498}
db290a6e 2499/**
e3ff14ca 2500 * If successful, this function returns the name of the file
db290a6e 2501 * @param $post is a full post record, including course and forum
2502 * @param $newfile is a full upload array from $_FILES
2503 * @param $message is a string to hold the messages.
e3ff14ca 2504 */
7f6689e4 2505
db290a6e 2506function forum_add_attachment($post, $inputname,&$message) {
7f6689e4 2507
9dd0b378 2508 global $CFG;
2509
4909e176 2510 if (!$forum = get_record("forum", "id", $post->forum)) {
2511 return "";
2512 }
2513
2514 if (!$course = get_record("course", "id", $forum->course)) {
2515 return "";
2516 }
2517
5ddaa2e2 2518 require_once($CFG->dirroot.'/lib/uploadlib.php');
db290a6e 2519 $um = new upload_manager($inputname,true,false,$course,false,$forum->maxbytes,true,true);
5ddaa2e2 2520 $dir = forum_file_area_name($post);
2521 if ($um->process_file_uploads($dir)) {
db290a6e 2522 $message .= $um->get_errors();
5ddaa2e2 2523 return $um->get_new_filename();
7f6689e4 2524 }
db290a6e 2525 $message .= $um->get_errors();
7f6689e4 2526}
501cdbd8 2527
db290a6e 2528function forum_add_new_post($post,&$message) {
501cdbd8 2529
f37da850 2530 global $USER, $CFG;
e3ff14ca 2531
ffe11640 2532 $post->created = $post->modified = time();
501cdbd8 2533 $post->mailed = "0";
a56f0d60 2534 $post->userid = $USER->id;
7f6689e4 2535 $post->attachment = "";
2536
65b0e537 2537 if (! $post->id = insert_record("forum_posts", $post)) {
7f6689e4 2538 return false;
2539 }
2540
db290a6e 2541 if ($post->attachment = forum_add_attachment($post, 'attachment',$message)) {
7f6689e4 2542 set_field("forum_posts", "attachment", $post->attachment, "id", $post->id);
2543 }
29507631 2544
2545 // Update discussion modified date
2546 set_field("forum_discussions", "timemodified", $post->modified, "id", $post->discussion);
016cd6af 2547 set_field("forum_discussions", "usermodified", $post->userid, "id", $post->discussion);
65b0e537 2548
eaf50aef 2549 if (forum_tp_can_track_forums($post->forum) && forum_tp_is_tracked($post->forum)) {
f37da850 2550 forum_tp_mark_post_read($post->userid, $post, $post->forum);
2551 }
2552
7f6689e4 2553 return $post->id;
501cdbd8 2554}
2555
db290a6e 2556function forum_update_post($post,&$message) {
501cdbd8 2557
f37da850 2558 global $USER, $CFG;
a56f0d60 2559
ffe11640 2560 $post->modified = time();
0936de64 2561
0ab85112 2562 if (!$post->parent) { // Post is a discussion starter - update discussion title too
2563 set_field("forum_discussions", "name", $post->subject, "id", $post->discussion);
2564 }
29507631 2565
db290a6e 2566 if ($newfilename = forum_add_attachment($post, 'attachment',$message)) {
7f6689e4 2567 $post->attachment = $newfilename;
2568 } else {
2569 unset($post->attachment);
2570 }
29507631 2571
2572 // Update discussion modified date
2573 set_field("forum_discussions", "timemodified", $post->modified, "id", $post->discussion);
016cd6af 2574 set_field("forum_discussions", "usermodified", $post->userid, "id", $post->discussion);
29507631 2575
eaf50aef 2576 if (forum_tp_can_track_forums($post->forum) && forum_tp_is_tracked($post->forum)) {
f37da850 2577 forum_tp_mark_post_read($post->userid, $post, $post->forum);
2578 }
2579
ffe11640 2580 return update_record("forum_posts", $post);
501cdbd8 2581}
2582
db290a6e 2583function forum_add_discussion($discussion,&$message) {
65b0e537 2584// Given an object containing all the necessary data,
501cdbd8 2585// create a new discussion and return the id
2586
f37da850 2587 GLOBAL $USER, $CFG;
501cdbd8 2588
2589 $timenow = time();
2590
65b0e537 2591 // The first post is stored as a real post, and linked
501cdbd8 2592 // to from the discuss entry.
2593
2594 $post->discussion = 0;
2595 $post->parent = 0;
ebc3bd2b 2596 $post->userid = $USER->id;
501cdbd8 2597 $post->created = $timenow;
2598 $post->modified = $timenow;
2599 $post->mailed = 0;
2600 $post->subject = $discussion->name;
2601 $post->message = $discussion->intro;
7f6689e4 2602 $post->attachment = "";
2603 $post->forum = $discussion->forum;
2604 $post->course = $discussion->course;
9f0b8269 2605 $post->format = $discussion->format;
41547057 2606 $post->mailnow = $discussion->mailnow;
501cdbd8 2607
2608 if (! $post->id = insert_record("forum_posts", $post) ) {
2609 return 0;
2610 }
2611
db290a6e 2612 if ($post->attachment = forum_add_attachment($post, 'attachment',$message)) {
7f6689e4 2613 set_field("forum_posts", "attachment", $post->attachment, "id", $post->id); //ignore errors
2614 }
2615
65b0e537 2616 // Now do the main entry for the discussion,
02509fe6 2617 // linking to this first post
04eba58f 2618
caadf009 2619 $discussion->firstpost = $post->id;
2620 $discussion->timemodified = $timenow;
016cd6af 2621 $discussion->usermodified = $post->userid;
a56f0d60 2622 $discussion->userid = $USER->id;
04eba58f 2623
4e00a4d9 2624 if (! $post->discussion = insert_record("forum_discussions", $discussion) ) {
caadf009 2625 delete_records("forum_posts", "id", $post->id);
2626 return 0;
04eba58f 2627 }
2628
caadf009 2629 // Finally, set the pointer on the post.
4e00a4d9 2630 if (! set_field("forum_posts", "discussion", $post->discussion, "id", $post->id)) {
caadf009 2631 delete_records("forum_posts", "id", $post->id);
4e00a4d9 2632 delete_records("forum_discussions", "id", $post->discussion);
caadf009 2633 return 0;
04eba58f 2634 }
04eba58f 2635
eaf50aef 2636 if (forum_tp_can_track_forums($post->forum) && forum_tp_is_tracked($post->forum)) {
f37da850 2637 forum_tp_mark_post_read($post->userid, $post, $post->forum);
2638 }
2639
4e00a4d9 2640 return $post->discussion;
caadf009 2641}
04eba58f 2642
04eba58f 2643
e2c1dbe9 2644function forum_delete_discussion($discussion, $fulldelete=false) {
caadf009 2645// $discussion is a discussion record object
04eba58f 2646
2647 $result = true;
2648
caadf009 2649 if ($posts = get_records("forum_posts", "discussion", $discussion->id)) {
2650 foreach ($posts as $post) {
2651 $post->course = $discussion->course;
2652 $post->forum = $discussion->forum;
2653 if (! delete_records("forum_ratings", "post", "$post->id")) {
2654 $result = false;
2655 }
e2c1dbe9 2656 if (! forum_delete_post($post, $fulldelete)) {
04eba58f 2657 $result = false;
2658 }
2659 }
2660 }
2661
f37da850 2662 forum_tp_delete_read_records(-1, -1, $discussion->id);
2663
caadf009 2664 if (! delete_records("forum_discussions", "id", "$discussion->id")) {
04eba58f 2665 $result = false;
2666 }
2667
2668 return $result;
2669}
2670
2671
b82faacd 2672function forum_delete_post($post, $children=false) {
1da8c568 2673 if ($childposts = get_records('forum_posts', 'parent', $post->id)) {
2674 if ($children) {
b82faacd 2675 foreach ($childposts as $childpost) {
2676 forum_delete_post($childpost, true);
2677 }
1da8c568 2678 } else {
2679 return false;
b82faacd 2680 }
2681 }
caadf009 2682 if (delete_records("forum_posts", "id", $post->id)) {
2683 delete_records("forum_ratings", "post", $post->id); // Just in case
f37da850 2684
b82faacd 2685 forum_tp_delete_read_records(-1, $post->id);
f37da850 2686
caadf009 2687 if ($post->attachment) {
2688 $discussion = get_record("forum_discussions", "id", $post->discussion);
2689 $post->course = $discussion->course;
2690 $post->forum = $discussion->forum;
2691 forum_delete_old_attachments($post);
2692 }
1da8c568 2693
2694 /// Just in case we are deleting the last post
2695 forum_discussion_update_last_post($post->discussion);
2696
caadf009 2697 return true;
2698 }
2699 return false;
2700}
501cdbd8 2701
b82faacd 2702function forum_count_replies($post, $children=true) {
2703 $count = 0;
2704
2705 if ($children) {
2706 if ($childposts = get_records('forum_posts', 'parent', $post->id)) {
2707 foreach ($childposts as $childpost) {
2708 $count ++; // For this child
2709 $count += forum_count_replies($childpost, true);
2710 }
2711 }
2712 } else {
2713 $count += count_records('forum_posts', 'parent', $post->id);
2714 }
2715
2716 return $count;
2717}
2718
2719
501cdbd8 2720function forum_forcesubscribe($forumid, $value=1) {
2721 return set_field("forum", "forcesubscribe", $value, "id", $forumid);
2722}
2723
2724function forum_is_forcesubscribed($forumid) {
709f0ec8 2725 return (get_field("forum", "forcesubscribe", "id", $forumid) == 1);
501cdbd8 2726}
2727
2728function forum_is_subscribed($userid, $forumid) {
2729 if (forum_is_forcesubscribed($forumid)) {
2730 return true;
2731 }
ebc3bd2b 2732 return record_exists("forum_subscriptions", "userid", $userid, "forum", $forumid);
86970225 2733}
2734
501cdbd8 2735function forum_subscribe($userid, $forumid) {
9fa49e22 2736/// Adds user to the subscriber list
2737
6673d7bd 2738 if (record_exists("forum_subscriptions", "userid", $userid, "forum", $forumid)) {
2739 return true;
2740 }
2741
ebc3bd2b 2742 $sub->userid = $userid;
9fa49e22 2743 $sub->forum = $forumid;
501cdbd8 2744
9fa49e22 2745 return insert_record("forum_subscriptions", $sub);
501cdbd8 2746}
2747
2748function forum_unsubscribe($userid, $forumid) {
9fa49e22 2749/// Removes user from the subscriber list
ebc3bd2b 2750 return delete_records("forum_subscriptions", "userid", $userid, "forum", $forumid);
501cdbd8 2751}
2752
0a9f61b5 2753function forum_post_subscription($post) {
2754/// Given a new post, subscribes or unsubscribes as appropriate.
2755/// Returns some text which describes what happened.
2756
2757 global $USER;
2758
2759 if (empty($post->subscribe) and empty($post->unsubscribe)) {
2760 return "";
2761 }
2762
2763 if (!$forum = get_record("forum", "id", $post->forum)) {
2764 return "";
2765 }
2766
067675c0 2767 $info->name = fullname($USER);
0a9f61b5 2768 $info->forum = $forum->name;
2769
2770 if (!empty($post->subscribe)) {
2771 forum_subscribe($USER->id, $post->forum);
2772 return "<p>".get_string("nowsubscribed", "forum", $info)."</p>";
2773 }
2774
2775 forum_unsubscribe($USER->id, $post->forum);
2776 return "<p>".get_string("nownotsubscribed", "forum", $info)."</p>";
2777}
2778
501cdbd8 2779
11b0c469 2780function forum_user_has_posted_discussion($forumid, $userid) {
29507631 2781 if ($discussions = forum_get_discussions($forumid, "", $userid)) {
501cdbd8 2782 return true;
2783 } else {
2784 return false;
2785 }
2786}
2787
bbbf2d40 2788function forum_user_has_posted($forumid, $did, $userid) {
098d27d4 2789 return record_exists('forum_posts','discussion',$did,'userid',$userid);
2790}
2791
bbbf2d40 2792function forum_user_can_post_discussion($forum, $currentgroup=false, $groupmode='') {
501cdbd8 2793// $forum is an object
fa22fd5f 2794 global $USER, $SESSION;
bbbf2d40 2795
2796 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2797 error('Course Module ID was incorrect');
2798 }
2799 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2800
0468976c 2801 if (!has_capability('mod/forum:startdiscussion', $context)) {
bbbf2d40 2802 return false;
2803 }
2804
501cdbd8 2805 if ($forum->type == "eachuser") {
bbbf2d40 2806 return (!forum_user_has_posted_discussion($forum->id, $USER->id));
9197e147 2807 } else if ($currentgroup) {
0468976c 2808 return (has_capability('moodle/site:accessallgroups', $context)
bbbf2d40 2809 or (ismember($currentgroup) and $forum->open == 2));
501cdbd8 2810 } else {
fa22fd5f 2811 //else it might be group 0 in visible mode
2812 if ($groupmode == VISIBLEGROUPS){
bbbf2d40 2813 return ($forum->open == 2 and ismember($currentgroup));
fa22fd5f 2814 }
2815 else {
2816 return ($forum->open == 2);
2817 }
501cdbd8 2818 }
2819}
2820
bbbf2d40 2821/**
2822 * This function checks whether the user can reply to posts in a forum
2823 * discussion. Use forum_user_can_post_discussion() to check whether the user
2824 * can start dicussions.
2825 * @param $forum - forum object
2826 * @param $user - user object
2827 */
f690562f 2828function forum_user_can_post($forum, $user=NULL) {
f690562f 2829
bbbf2d40 2830 if (!$forum->open) {
2831 // No point doing the more expensive has_capability checks.
2832 return false;
2833 }
2834
2835 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2836 error('Course Module ID was incorrect');
f690562f 2837 }
bbbf2d40 2838 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
70c476a7 2839
bbbf2d40 2840 if (isset($user)) {
0468976c 2841 $canreply = has_capability('mod/forum:replypost', $context, false, $user->id);
70c476a7 2842 } else {
0468976c 2843 $canreply = has_capability('mod/forum:replypost', $context, false);
70c476a7 2844 }
bbbf2d40 2845
2846 return $canreply;
70c476a7 2847}
501cdbd8 2848
bbbf2d40 2849
073286f0 2850//checks to see if a user can view a particular post
ff1dc046 2851function forum_user_can_view_post($post, $course, $cm, $forum, $discussion, $user=NULL){
073286f0 2852
2853 global $CFG, $USER;
bbbf2d40 2854
073286f0 2855 if (!$user){
2856 $user = $USER;
2857 }
bbbf2d40 2858
2859 $modcontext = get_context_instance(CONTEXT_MODULE, $cm->id);
0468976c 2860 if (!has_capability('mod/forum:viewdiscussion', $modcontext)) {
bbbf2d40 2861 return false;
073286f0 2862 }
bbbf2d40 2863
2864 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
0468976c 2865 if (!has_capability('moodle/course:view', $coursecontext)) {
073286f0 2866 return false;
2867 }
2868
ff1dc046 2869/// If it's a grouped discussion, make sure the user is a member
2870 if ($discussion->groupid > 0) {
2871 if ($cm->groupmode == SEPARATEGROUPS) {
bbbf2d40 2872 return ismember($discussion->groupid) ||
0468976c 2873 has_capability('moodle/site:accessallgroups', $modcontext);
ff1dc046 2874 }
073286f0 2875 }
ff1dc046 2876 return true;
073286f0 2877}
501cdbd8 2878
bbbf2d40 2879
2880function forum_user_can_see_discussion($forum, $discussion, $contextid, $user=NULL) {
098d27d4 2881 global $USER;
2882
2883 if (empty($user) || empty($user->id)) {
2884 $user = $USER;
2885 }
2886
2887 // retrive objects (yuk)
2888 if (is_numeric($forum)) {
2889 if (!$forum = get_record('forum','id',$forum)) {
2890 return false;
2891 }
2892 }
2893 if (is_numeric($discussion)) {
2894 if (!$discussion = get_record('forum_discussions','id',$discussion)) {
2895 return false;
2896 }
2897 }
bbbf2d40 2898
2899 if (!has_capability('mod/forum:viewdiscussion', $contextid)) {
2900 return false;
2901 }
2902
2903 if ($forum->type == 'qanda' &&
2904 !forum_user_has_posted($forum->id, $discussion->id, $user->id) &&
2905 !has_capability('mod/forum:viewqandawithoutposting', $contextid)) {
2906 return false;
098d27d4 2907 }
2908 return true;
2909}
2910
2911
bbbf2d40 2912function forum_user_can_see_post($forum, $discussion, $post, $user=NULL) {
098d27d4 2913 global $USER;
2914
098d27d4 2915 // retrive objects (yuk)
2916 if (is_numeric($forum)) {
2917 if (!$forum = get_record('forum','id',$forum)) {
2918 return false;
2919 }
2920 }
bbbf2d40 2921
098d27d4 2922 if (is_numeric($discussion)) {
2923 if (!$discussion = get_record('forum_discussions','id',$discussion)) {
2924 return false;
2925 }
2926 }
2927 if (is_numeric($post)) {
2928 if (!$post = get_record('forum_posts','id',$post)) {
2929 return false;
2930 }
2931 }
098d27d4 2932 if (!isset($post->id) && isset($post->parent)) {
2933 $post->id = $post->parent;
2934 }
2935
bbbf2d40 2936 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2937 error('Course Module ID was incorrect');
2938 }
2939 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2940
2941 if (empty($user) || empty($user->id)) {
2942 $user = $USER;
2943 }
2944
0468976c 2945 if (!has_capability('mod/forum:viewdiscussion', $context, false, $user->id)) {
bbbf2d40 2946 return false;
2947 }
2948
098d27d4 2949 if ($forum->type == 'qanda') {
2950 $firstpost = forum_get_firstpost_from_discussion($discussion->id);
bbbf2d40 2951
2952 return (forum_user_has_posted($forum->id,$discussion->id,$user->id) ||
2953 $firstpost->id == $post->id ||
0468976c 2954 has_capability('mod/forum:viewqandawithoutposting', $context, false, $user->id));
098d27d4 2955 }
2956 return true;
2957}
2958
2959
eaf50aef 2960/**
2961* Prints the discussion view screen for a forum.
2962*
2963* @param object $course The current course object.
2964* @param object $forum Forum to be printed.
2965* @param int $maxdiscussions The maximum number of discussions per page(optional).
2966* @param string $displayformat The display format to use (optional).
2967* @param string $sort Sort arguments for database query (optional).
2968* @param int $currentgroup Group to display discussions for (optional).
2969* @param int $groupmode Group mode of the forum (optional).
2970* @param int $page Page mode, page to display (optional).
2971*
2972*/
af328e4b 2973function forum_print_latest_discussions($course, $forum, $maxdiscussions=5, $displayformat='plain', $sort='',
2974 $currentgroup=-1, $groupmode=-1, $page=-1) {
c585fa17 2975 global $CFG, $USER;
bbbf2d40 2976
2977 if (!$cm = get_coursemodule_from_instance('forum', $forum->id, $forum->course)) {
2978 error('Course Module ID was incorrect');
2979 }
2980 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
2981
65b0e537 2982
af328e4b 2983/// Sort out some defaults
2984
2985 if ((!$maxdiscussions) && ($displayformat == 'plain')) {
2986 $displayformat = 'header'; // Abbreviate display by default
2987 }
2988
2989 $fullpost = false;
2990 if ($displayformat == 'plain') {
2991 $fullpost = true;
f93f848a 2992 }
2993
af328e4b 2994
2995/// Decide if current user is allowed to see ALL the current discussions or not
2996
2997/// First check the group stuff
2998
2862b309 2999 if ($groupmode == -1) { /// We need to reconstruct groupmode because none was given
d5bbc556 3000 if ($cm = get_coursemodule_from_instance('forum', $forum->id, $course->id)) {
2862b309 3001 $groupmode = groupmode($course, $cm);
3002 } else {
3003 $groupmode = SEPARATEGROUPS;
3004 }
3005 }
8f0cd6ef 3006
af328e4b 3007 if ($currentgroup == -1) { /// We need to reconstruct currentgroup because none was given
3008 $currentgroup = get_current_group($course->id);
3009 }
3010
bbbf2d40 3011 if (!$currentgroup and ($groupmode != SEPARATEGROUPS or
0468976c 3012 has_capability('moodle/site:accessallgroups', $context)) ) {
af328e4b 3013 $visiblegroups = -1;
3014 } else {
3015 $visiblegroups = $currentgroup;
3016 }
3017
3018/// If the user can post discussions, then this is a good place to put the button for it
fa22fd5f 3019 //add group mode in there, to test for visible group
3020 if (forum_user_can_post_discussion($forum, $currentgroup, $groupmode)) {
af328e4b 3021 echo '<div class="singlebutton forumaddnew">';
49aa3742 3022 echo "<form name=\"newdiscussionform\" method=\"get\" action=\"$CFG->wwwroot/mod/forum/post.php\">";
3023 echo "<input type=\"hidden\" name=\"forum\" value=\"$forum->id\" />";
3024 echo '<input type="submit" value="';
098d27d4 3025 echo ($forum->type == 'news') ? get_string('addanewtopic', 'forum')
3026 : (($forum->type == 'qanda')
3027 ? get_string('addanewquestion','forum')
3028 : get_string('addanewdiscussion', 'forum'));
49aa3742 3029 echo '" />';
3030 echo '</form>';
3479c82f 3031 echo "</div>\n";
77305fe6 3032 }
3033
2862b309 3034
3035/// Get all the recent discussions we're allowed to see
3036
096de9ad 3037 $getuserlastmodified = ($displayformat == 'header');
3038
3039 if (! $discussions = forum_get_discussions($forum->id, $sort, 0, $fullpost, $visiblegroups,0,$getuserlastmodified) ) {
af328e4b 3040 echo '<div class="forumnodiscuss">';
d5bbc556 3041 if ($forum->type == 'news') {
3042 echo '('.get_string('nonews', 'forum').')';
098d27d4 3043 } else if ($forum->type == 'qanda') {
3044 echo '('.get_string('noquestions','forum').')';
0351b1f9 3045 } else {
d5bbc556 3046 echo '('.get_string('nodiscussions', 'forum').')';
0351b1f9 3047 }
f13075f1 3048 echo "</div>\n";
2ab968e9 3049 return;
3050 }
65b0e537 3051
af328e4b 3052/// If no discussions then don't use paging (to avoid some divide by 0 errors)
3053
3054 if ($maxdiscussions <= 0) {
f6bb7eaa 3055 $page = -1;
af328e4b 3056 $maxdiscussions = 0;
f6bb7eaa 3057 }
3058
af328e4b 3059/// If we want paging
3060
f6bb7eaa 3061 if ($page != -1) {
3062 ///Get the number of discussions found
3063 $numdiscussions = count($discussions);
3064
3065 ///Show the paging bar
af328e4b 3066 print_paging_bar($numdiscussions, $page, $maxdiscussions, "view.php?f=$forum->id&");
f6bb7eaa 3067
3068 //Calculate the page "window"
af328e4b 3069 $pagestart = ($page * $maxdiscussions) + 1;
3070 $pageend = $pagestart + $maxdiscussions - 1;
f6bb7eaa 3071 }
3072
af328e4b 3073
3335f6fb 3074 $replies = forum_count_discussion_replies($forum->id);
f93f848a 3075
3260de67 3076 $canreply = forum_user_can_post($forum);
3077
af328e4b 3078
3335f6fb 3079 $discussioncount = 0;
c20b762a 3080 $olddiscussionlink = false;
f51e8d7e 3081 $strdatestring = get_string('strftimerecentfull');
f93f848a 3082
1d2256d0 3083 /// Check if the forum is tracked.
eaf50aef 3084 if ($cantrack = forum_tp_can_track_forums($forum)) {
77efef3e 3085 $forumtracked = forum_tp_is_tracked($forum);
1d2256d0 3086 } else {
3087 $forumtracked = false;
3088 }
3089
af328e4b 3090 if ($displayformat == 'header') {
5c8d1866 3091 echo '<table cellspacing="0" class="forumheaderlist">';
f51e8d7e 3092 echo '<thead>';
3093 echo '<tr>';
7ff9860d 3094 echo '<th class="header topic">'.get_string('discussion', 'forum').'</th>';
3095 echo '<th class="header author" colspan="2">'.get_string('startedby', 'forum').'</th>';
3a68fbbb 3096 if ($groupmode > 0) {
7ff9860d 3097 echo '<th class="header group">'.get_string('group').'</th>';
3a68fbbb 3098 }
f51e8d7e 3099 if ($forum->open or $forum->type == 'teacher') {
7ff9860d 3100 echo '<th class="header replies">'.get_string('replies', 'forum').'</th>';
eaf50aef 3101 /// If the forum can be tracked, display the unread column.
3102 if ($cantrack) {
524f9dbe 3103 echo '<th class="header replies">'.get_string('unread', 'forum');
3104 if ($forumtracked) {
3105 echo '&nbsp;<a title="'.get_string('markallread', 'forum').
3106 '" href="'.$CFG->wwwroot.'/mod/forum/markposts.php?f='.
3107 $forum->id.'&amp;mark=read&amp;returnpage=view.php">'.
3108 '<img src="'.$CFG->pixpath.'/t/clear.gif" height="11" width="11" border="0" /></a>';
3109 }
3110 echo '</th>';
47d06301 3111 }
f37da850 3112 }
7ff9860d 3113 echo '<th class="header lastpost">'.get_string('lastpost', 'forum').'</th>';
f51e8d7e 3114 echo '</tr>';
3115 echo '</thead>';
3116 echo '<tbody>';
29507631 3117 }
3118
3335f6fb 3119 foreach ($discussions as $discussion) {
3120 $discussioncount++;
f93f848a 3121
af328e4b 3122 if ($page != -1) { // We are using paging
3123 if ($discussioncount < $pagestart) { // Not there yet
f6bb7eaa 3124 continue;
3125 }
af328e4b 3126 if ($discussioncount > $pageend) { // All done, finish the loop
3127 break;
3128 }
f6bb7eaa 3129 //Without paging, old approach
af328e4b 3130 } else if ($maxdiscussions && ($discussioncount > $maxdiscussions)) {
c20b762a 3131 $olddiscussionlink = true;
3335f6fb 3132 break;
3133 }