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