Merge branch 'MDL-24898_strip_and_trunc_subjects_wip' of git://github.com/stronk7...
[moodle.git] / blog / lib.php
CommitLineData
cae83708 1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
cae83708 18/**
19 * Core global functions for Blog.
20 *
21 * @package moodlecore
22 * @subpackage blog
23 * @copyright 2009 Nicolas Connault
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 */
26
35716b86
PS
27defined('MOODLE_INTERNAL') || die();
28
cae83708 29/**
30 * Library of functions and constants for blog
31 */
32require_once($CFG->dirroot .'/blog/rsslib.php');
33require_once($CFG->dirroot.'/tag/lib.php');
34
cae83708 35/**
36 * User can edit a blog entry if this is their own blog entry and they have
37 * the capability moodle/blog:create, or if they have the capability
38 * moodle/blog:manageentries.
39 *
40 * This also applies to deleting of entries.
41 */
1c7b8b93
NC
42function blog_user_can_edit_entry($blogentry) {
43 global $USER;
6524adcf 44
cae83708 45 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
4a173181 46
cae83708 47 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
48 return true; // can edit any blog entry
49 }
c2ee4e87 50
1c7b8b93 51 if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
cae83708 52 return true; // can edit own when having blog:create capability
53 }
4a173181 54
cae83708 55 return false;
56}
d02240f3 57
3bfcfdca 58
cae83708 59/**
60 * Checks to see if a user can view the blogs of another user.
61 * Only blog level is checked here, the capabilities are enforced
62 * in blog/index.php
63 */
1c7b8b93 64function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
cae83708 65 global $CFG, $USER, $DB;
c2ee4e87 66
cae83708 67 if (empty($CFG->bloglevel)) {
68 return false; // blog system disabled
69 }
70
2c27b6ae 71 if (isloggedin() && $USER->id == $targetuserid) {
cae83708 72 return true; // can view own entries in any case
73 }
74
75 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
76 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
77 return true; // can manage all entries
78 }
c2ee4e87 79
cae83708 80 // coming for 1 entry, make sure it's not a draft
1c7b8b93 81 if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
cae83708 82 return false; // can not view draft of others
83 }
84
bb8a75e7 85 // coming for 0 entry, make sure user is logged in, if not a public blog
1c7b8b93 86 if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
cae83708 87 return false;
88 }
d02240f3 89
cae83708 90 switch ($CFG->bloglevel) {
91 case BLOG_GLOBAL_LEVEL:
92 return true;
93 break;
c2ee4e87 94
cae83708 95 case BLOG_SITE_LEVEL:
4f0c2d00 96 if (isloggedin()) { // not logged in viewers forbidden
cae83708 97 return true;
c2ee4e87 98 }
cae83708 99 return false;
100 break;
d02240f3 101
cae83708 102 case BLOG_USER_LEVEL:
103 default:
104 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
105 return has_capability('moodle/user:readuserblogs', $personalcontext);
106 break;
4a173181 107
cae83708 108 }
109}
110
111/**
112 * remove all associations for the blog entries of a particular user
113 * @param int userid - id of user whose blog associations will be deleted
114 */
115function blog_remove_associations_for_user($userid) {
1c7b8b93 116 global $DB;
d91181dc
PS
117 throw new coding_exception('function blog_remove_associations_for_user() is not finished');
118 /*
1c7b8b93
NC
119 $blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
120 foreach ($blogentries as $entry) {
121 if (blog_user_can_edit_entry($entry)) {
122 blog_remove_associations_for_entry($entry->id);
123 }
b0e90a0c 124 }
d91181dc 125 */
cae83708 126}
127
128/**
1c7b8b93
NC
129 * remove all associations for the blog entries of a particular course
130 * @param int courseid - id of user whose blog associations will be deleted
cae83708 131 */
1c7b8b93
NC
132function blog_remove_associations_for_course($courseid) {
133 global $DB;
134 $context = get_context_instance(CONTEXT_COURSE, $courseid);
135 $DB->delete_records('blog_association', array('contextid' => $context->id));
cae83708 136}
137
cae83708 138/**
139 * Given a record in the {blog_external} table, checks the blog's URL
b7c1da93 140 * for new entries not yet copied into Moodle.
50ff50da 141 * Also attempts to identify and remove deleted blog entries
cae83708 142 *
1c7b8b93
NC
143 * @param object $externalblog
144 * @return boolean False if the Feed is invalid
cae83708 145 */
1c7b8b93 146function blog_sync_external_entries($externalblog) {
cae83708 147 global $CFG, $DB;
e14de6f9 148 require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
4a173181 149
1c7b8b93
NC
150 $rssfile = new moodle_simplepie_file($externalblog->url);
151 $filetest = new SimplePie_Locator($rssfile);
152
a537e507
EL
153 $textlib = textlib_get_instance(); // Going to use textlib services
154
1c7b8b93
NC
155 if (!$filetest->is_feed($rssfile)) {
156 $externalblog->failedlastsync = 1;
157 $DB->update_record('blog_external', $externalblog);
158 return false;
8397492b 159 } else if (!empty($externalblog->failedlastsync)) {
1c7b8b93
NC
160 $externalblog->failedlastsync = 0;
161 $DB->update_record('blog_external', $externalblog);
c2ee4e87 162 }
4a173181 163
1c7b8b93 164 $rss = new moodle_simplepie($externalblog->url);
c2ee4e87 165
e14de6f9 166 if (empty($rss->data)) {
cae83708 167 return null;
168 }
50ff50da 169 //used to identify blog posts that have been deleted from the source feed
cc52e53d 170 $oldesttimestamp = null;
50ff50da 171 $uniquehashes = array();
b13ee30e 172
e14de6f9 173 foreach ($rss->get_items() as $entry) {
1c7b8b93
NC
174 // If filtertags are defined, use them to filter the entries by RSS category
175 if (!empty($externalblog->filtertags)) {
176 $containsfiltertag = false;
177 $categories = $entry->get_categories();
178 $filtertags = explode(',', $externalblog->filtertags);
179 $filtertags = array_map('trim', $filtertags);
180 $filtertags = array_map('strtolower', $filtertags);
181
182 foreach ($categories as $category) {
183 if (in_array(trim(strtolower($category->term)), $filtertags)) {
184 $containsfiltertag = true;
185 }
186 }
187
188 if (!$containsfiltertag) {
189 continue;
c2ee4e87 190 }
191 }
c484c852 192
50ff50da 193 $uniquehashes[] = $entry->get_permalink();
1c7b8b93 194
e463f508 195 $newentry = new stdClass();
1c7b8b93
NC
196 $newentry->userid = $externalblog->userid;
197 $newentry->module = 'blog_external';
198 $newentry->content = $externalblog->id;
199 $newentry->uniquehash = $entry->get_permalink();
200 $newentry->publishstate = 'site';
201 $newentry->format = FORMAT_HTML;
a537e507
EL
202 // Clean subject of html, just in case
203 $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
204 // Observe 128 max chars in DB
205 // TODO: +1 to raise this to 255
206 if ($textlib->strlen($newentry->subject) > 128) {
207 $newentry->subject = $textlib->substr($newentry->subject, 0, 125) . '...';
208 }
1c7b8b93 209 $newentry->summary = $entry->get_description();
c484c852 210
9829e3d8 211 //used to decide whether to insert or update
212 //uses enty permalink plus creation date if available
bb8a75e7 213 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
99cd408f 214
9829e3d8 215 //our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
99cd408f 216 $entrydate = $entry->get_date('U');
afce96f0 217 if (!empty($entrydate)) {
218 $existingpostconditions['created'] = $entrydate;
219 }
c484c852 220
e5137f24 221 //the post ID or false if post not found in DB
afce96f0 222 $postid = $DB->get_field('post', 'id', $existingpostconditions);
c484c852 223
afce96f0 224 $timestamp = null;
99cd408f 225 if (empty($entrydate)) {
afce96f0 226 $timestamp = time();
99cd408f 227 } else {
afce96f0 228 $timestamp = $entrydate;
99cd408f 229 }
c484c852 230
afce96f0 231 //only set created if its a new post so we retain the original creation timestamp if the post is edited
bb8a75e7 232 if ($postid === false) {
afce96f0 233 $newentry->created = $timestamp;
234 }
235 $newentry->lastmodified = $timestamp;
694fb770 236
bb8a75e7 237 if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
cc52e53d 238 //found an older post
239 $oldesttimestamp = $timestamp;
240 }
1c7b8b93 241
3b59524d 242 $textlib = textlib_get_instance();
ca824b38 243 if ($textlib->strlen($newentry->uniquehash) > 255) {
3b59524d
SH
244 // The URL for this item is too long for the field. Rather than add
245 // the entry without the link we will skip straight over it.
246 // RSS spec says recommended length 500, we use 255.
247 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
248 continue;
249 }
250
bb8a75e7 251 if ($postid === false) {
9829e3d8 252 $id = $DB->insert_record('post', $newentry);
1c7b8b93 253
9829e3d8 254 // Set tags
255 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
256 tag_set('post', $id, $tags);
257 }
258 } else {
259 $newentry->id = $postid;
afce96f0 260 $DB->update_record('post', $newentry);
1c7b8b93 261 }
cae83708 262 }
c484c852 263
50ff50da 264 //Look at the posts we have in the database to check if any of them have been deleted from the feed.
b7c1da93 265 //Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
50ff50da 266 //may just not be returned anymore. We cant tell the difference so we leave older posts alone.
29487578 267 $dbposts = $DB->get_records_select('post', 'created > :ts', array('ts' => $oldesttimestamp), '', 'id, uniquehash');
50ff50da 268 $todelete = array();
269 foreach($dbposts as $dbpost) {
29487578 270 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
50ff50da 271 $todelete[] = $dbpost->id;
272 }
273 }
274 $DB->delete_records_list('post', 'id', $todelete);
c2ee4e87 275
e5137f24 276 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
1c7b8b93
NC
277}
278
279/**
280 * Given an external blog object, deletes all related blog entries from the post table.
281 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
282 * @param object $externablog
283 */
284function blog_delete_external_entries($externalblog) {
285 global $DB;
286 require_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM));
a742eb1f
EL
287 $DB->delete_records_select('post',
288 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
289 array($externalblog->id));
cae83708 290}
d02240f3 291
cae83708 292/**
293 * Returns a URL based on the context of the current page.
294 * This URL points to blog/index.php and includes filter parameters appropriate for the current page.
295 *
296 * @param stdclass $context
297 * @return string
298 */
299function blog_get_context_url($context=null) {
300 global $CFG;
c2ee4e87 301
a6855934 302 $viewblogentriesurl = new moodle_url('/blog/index.php');
c2ee4e87 303
cae83708 304 if (empty($context)) {
305 global $PAGE;
5515b536 306 $context = $PAGE->context;
cae83708 307 }
c2ee4e87 308
cae83708 309 // Change contextlevel to SYSTEM if viewing the site course
310 if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
311 $context->contextlevel = CONTEXT_SYSTEM;
312 }
c2ee4e87 313
cae83708 314 $filterparam = '';
315 $strlevel = '';
c2ee4e87 316
cae83708 317 switch ($context->contextlevel) {
318 case CONTEXT_SYSTEM:
319 case CONTEXT_BLOCK:
320 case CONTEXT_COURSECAT:
c2ee4e87 321 break;
cae83708 322 case CONTEXT_COURSE:
323 $filterparam = 'courseid';
324 $strlevel = get_string('course');
c2ee4e87 325 break;
cae83708 326 case CONTEXT_MODULE:
327 $filterparam = 'modid';
328 $strlevel = print_context_name($context);
c2ee4e87 329 break;
cae83708 330 case CONTEXT_USER:
331 $filterparam = 'userid';
332 $strlevel = get_string('user');
c2ee4e87 333 break;
516194d0 334 }
335
cae83708 336 if (!empty($filterparam)) {
b0e90a0c 337 $viewblogentriesurl->param($filterparam, $context->instanceid);
cae83708 338 }
bbbf2d40 339
b0e90a0c 340 return $viewblogentriesurl;
cae83708 341}
342
27bad0a6 343/**
593270c6 344 * This function checks that blogs are enabled, and that the user can see blogs at all
27bad0a6
SH
345 * @return bool
346 */
347function blog_is_enabled_for_user() {
348 global $CFG;
593270c6
MD
349 //return (!empty($CFG->bloglevel) && $CFG->bloglevel <= BLOG_GLOBAL_LEVEL && isloggedin() && !isguestuser());
350 return (!empty($CFG->bloglevel) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
27bad0a6
SH
351}
352
353/**
354 * This function gets all of the options available for the current user in respect
355 * to blogs.
897aa80c 356 *
27bad0a6
SH
357 * It loads the following if applicable:
358 * - Module options {@see blog_get_options_for_module}
359 * - Course options {@see blog_get_options_for_course}
360 * - User specific options {@see blog_get_options_for_user}
361 * - General options (BLOG_LEVEL_GLOBAL)
362 *
363 * @param moodle_page $page The page to load for (normally $PAGE)
364 * @param stdClass $userid Load for a specific user
365 * @return array An array of options organised by type.
366 */
367function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
368 global $CFG, $DB, $USER;
369
370 $options = array();
371
372 // If blogs are enabled and the user is logged in and not a guest
373 if (blog_is_enabled_for_user()) {
374 // If the context is the user then assume we want to load for the users context
375 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
376 $userid = $page->context->instanceid;
377 }
378 // Check the userid var
379 if (!is_null($userid) && $userid!==$USER->id) {
380 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
381 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
382 } else {
383 $user = null;
384 }
385
386 if ($CFG->useblogassociations && $page->cm !== null) {
387 // Load for the module associated with the page
388 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
389 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
390 // Load the options for the course associated with the page
391 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
392 }
393
394 // Get the options for the user
395 if ($user !== null) {
396 // Load for the requested user
397 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
398 }
399 // Load for the current user
400 $options[CONTEXT_USER] = blog_get_options_for_user();
401 }
402
403 // If blog level is global then display a link to view all site entries
404 if (!empty($CFG->bloglevel) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
405 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
406 'string' => get_string('viewsiteentries', 'blog'),
407 'link' => new moodle_url('/blog/index.php')
408 ));
409 }
410
411 // Return the options
412 return $options;
413}
414
415/**
416 * Get all of the blog options that relate to the passed user.
417 *
418 * If no user is passed the current user is assumed.
419 *
420 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
421 * @param stdClass $user
422 * @return array The array of options for the requested user
423 */
424function blog_get_options_for_user(stdClass $user=null) {
425 global $CFG, $USER;
426 // Cache
427 static $useroptions = array();
428
429 $options = array();
430 // Blogs must be enabled and the user must be logged in
431 if (!blog_is_enabled_for_user()) {
432 return $options;
433 }
434
435 // Sort out the user var
436 if ($user === null || $user->id == $USER->id) {
437 $user = $USER;
438 $iscurrentuser = true;
439 } else {
440 $iscurrentuser = false;
441 }
442
443 // If we've already generated serve from the cache
444 if (array_key_exists($user->id, $useroptions)) {
445 return $useroptions[$user->id];
446 }
447
448 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
449 $canview = has_capability('moodle/blog:view', $sitecontext);
450
451 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
452 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
453 $options['userentries'] = array(
454 'string' => get_string('viewuserentries', 'blog', fullname($user)),
455 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
456 );
457 } else {
458 // It's the current user
459 if ($canview) {
460 // We can view our own blogs .... BIG surprise
461 $options['view'] = array(
462 'string' => get_string('viewallmyentries', 'blog'),
463 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
464 );
465 }
466 if (has_capability('moodle/blog:create', $sitecontext)) {
467 // We can add to our own blog
468 $options['add'] = array(
469 'string' => get_string('addnewentry', 'blog'),
470 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
471 );
472 }
473 }
474 // Cache the options
475 $useroptions[$user->id] = $options;
476 // Return the options
477 return $options;
478}
479
480/**
481 * Get the blog options that relate to the given course for the given user.
482 *
483 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
484 * @param stdClass $course The course to load options for
485 * @param stdClass $user The user to load options for null == current user
486 * @return array The array of options
487 */
488function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
489 global $CFG, $USER;
490 // Cache
491 static $courseoptions = array();
897aa80c 492
27bad0a6
SH
493 $options = array();
494
495 // User must be logged in and blogs must be enabled
496 if (!blog_is_enabled_for_user()) {
497 return $options;
498 }
499
500 // Check that the user can associate with the course
501 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
502 if (!has_capability('moodle/blog:associatecourse', $sitecontext)) {
503 return $options;
504 }
505 // Generate the cache key
506 $key = $course->id.':';
507 if (!empty($user)) {
508 $key .= $user->id;
509 } else {
510 $key .= $USER->id;
511 }
512 // Serve from the cache if we've already generated for this course
513 if (array_key_exists($key, $courseoptions)) {
af8fe217 514 return $courseoptions[$key];
27bad0a6 515 }
897aa80c 516
27bad0a6
SH
517 if (has_capability('moodle/blog:view', get_context_instance(CONTEXT_COURSE, $course->id))) {
518 // We can view!
519 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
520 // View entries about this course
521 $options['courseview'] = array(
522 'string' => get_string('viewcourseblogs', 'blog'),
523 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id))
524 );
525 }
526 // View MY entries about this course
527 $options['courseviewmine'] = array(
528 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
529 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$USER->id))
530 );
531 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
532 // View the provided users entries about this course
533 $options['courseviewuser'] = array(
534 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
535 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$user->id))
536 );
537 }
538 }
539
540 if (has_capability('moodle/blog:create', $sitecontext)) {
541 // We can blog about this course
542 $options['courseadd'] = array(
cfa11fd6 543 'string' => get_string('blogaboutthiscourse', 'blog'),
27bad0a6
SH
544 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'courseid'=>$course->id))
545 );
546 }
547
548
549 // Cache the options for this course
550 $courseoptions[$key] = $options;
551 // Return the options
552 return $options;
553}
554
555/**
556 * Get the blog options relating to the given module for the given user
557 *
558 * @staticvar array $moduleoptions Cache
78f0f64d 559 * @param stdClass|cm_info $module The module to get options for
27bad0a6
SH
560 * @param stdClass $user The user to get options for null == currentuser
561 * @return array
562 */
78f0f64d 563function blog_get_options_for_module($module, $user=null) {
27bad0a6
SH
564 global $CFG, $USER;
565 // Cache
566 static $moduleoptions = array();
567
568 $options = array();
569 // User must be logged in, blogs must be enabled
570 if (!blog_is_enabled_for_user()) {
571 return $options;
572 }
573
574 // Check the user can associate with the module
575 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
576 if (!has_capability('moodle/blog:associatemodule', $sitecontext)) {
577 return $options;
578 }
579
580 // Generate the cache key
581 $key = $module->id.':';
582 if (!empty($user)) {
583 $key .= $user->id;
584 } else {
585 $key .= $USER->id;
586 }
587 if (array_key_exists($key, $moduleoptions)) {
588 // Serve from the cache so we don't have to regenerate
589 return $moduleoptions[$module->id];
590 }
591
592 if (has_capability('moodle/blog:view', get_context_instance(CONTEXT_MODULE, $module->id))) {
593 // We can view!
594 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
595 // View all entries about this module
596 $a = new stdClass;
597 $a->type = $module->modname;
598 $options['moduleview'] = array(
599 'string' => get_string('viewallmodentries', 'blog', $a),
600 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
601 );
602 }
603 // View MY entries about this module
604 $options['moduleviewmine'] = array(
605 'string' => get_string('viewmyentriesaboutmodule', 'blog', $module->modname),
606 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
607 );
608 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
609 // View the given users entries about this module
610 $a = new stdClass;
611 $a->mod = $module->modname;
612 $a->user = fullname($user);
613 $options['moduleviewuser'] = array(
614 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
615 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
616 );
617 }
618 }
619
620 if (has_capability('moodle/blog:create', $sitecontext)) {
621 // The user can blog about this module
622 $options['moduleadd'] = array(
623 'string' => get_string('blogaboutthismodule', 'blog', $module->modname),
624 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
625 );
626 }
627 // Cache the options
628 $moduleoptions[$key] = $options;
629 // Return the options
630 return $options;
631}
632
cae83708 633/**
634 * This function encapsulates all the logic behind the complex
635 * navigation, titles and headings of the blog listing page, depending
1c7b8b93
NC
636 * on URL params. It looks at URL params and at the current context level.
637 * It builds and returns an array containing:
638 *
639 * 1. heading: The heading displayed above the blog entries
640 * 2. stradd: The text to be used as the "Add entry" link
641 * 3. strview: The text to be used as the "View entries" link
642 * 4. url: The moodle_url object used as the base for add and view links
643 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
cae83708 644 *
c5dc10ee 645 * All other variables are set directly in $PAGE
cae83708 646 *
647 * It uses the current URL to build these variables.
648 * A number of mutually exclusive use cases are used to structure this function.
649 *
650 * @return array
651 */
451f1e38 652function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
cae83708 653 global $CFG, $PAGE, $DB, $USER;
654
9366362a 655 $id = optional_param('id', null, PARAM_INT);
cae83708 656 $tag = optional_param('tag', null, PARAM_NOTAGS);
451f1e38
AD
657 $tagid = optional_param('tagid', $tagid, PARAM_INT);
658 $userid = optional_param('userid', $userid, PARAM_INT);
cae83708 659 $modid = optional_param('modid', null, PARAM_INT);
660 $entryid = optional_param('entryid', null, PARAM_INT);
451f1e38
AD
661 $groupid = optional_param('groupid', $groupid, PARAM_INT);
662 $courseid = optional_param('courseid', $courseid, PARAM_INT);
cae83708 663 $search = optional_param('search', null, PARAM_RAW);
664 $action = optional_param('action', null, PARAM_ALPHA);
665 $confirm = optional_param('confirm', false, PARAM_BOOL);
666
1c7b8b93
NC
667 // Ignore userid when action == add
668 if ($action == 'add' && $userid) {
669 unset($userid);
670 $PAGE->url->remove_params(array('userid'));
671 } else if ($action == 'add' && $entryid) {
672 unset($entryid);
673 $PAGE->url->remove_params(array('entryid'));
674 }
675
676 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
cae83708 677
a6855934 678 $blogurl = new moodle_url('/blog/index.php');
1c7b8b93
NC
679
680 // If the title is not yet set, it's likely that the context isn't set either, so skip this part
6f5e0852 681 $pagetitle = $PAGE->title;
1c7b8b93
NC
682 if (!empty($pagetitle)) {
683 $contexturl = blog_get_context_url();
684
685 // Look at the context URL, it may have additional params that are not in the current URL
686 if (!$blogurl->compare($contexturl)) {
687 $blogurl = $contexturl;
688 if (empty($courseid)) {
689 $courseid = $blogurl->param('courseid');
690 }
691 if (empty($modid)) {
692 $modid = $blogurl->param('modid');
693 }
694 }
695 }
696
697 $headers['stradd'] = get_string('addnewentry', 'blog');
698 $headers['strview'] = null;
cae83708 699
1c7b8b93
NC
700 $site = $DB->get_record('course', array('id' => SITEID));
701 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
cae83708 702 // Common Lang strings
703 $strparticipants = get_string("participants");
704 $strblogentries = get_string("blogentries", 'blog');
705
706 // Prepare record objects as needed
707 if (!empty($courseid)) {
1c7b8b93 708 $headers['filters']['course'] = $courseid;
cae83708 709 $course = $DB->get_record('course', array('id' => $courseid));
710 }
e96f2a77 711
cae83708 712 if (!empty($userid)) {
1c7b8b93 713 $headers['filters']['user'] = $userid;
cae83708 714 $user = $DB->get_record('user', array('id' => $userid));
516194d0 715 }
bbbf2d40 716
cae83708 717 if (!empty($groupid)) { // groupid always overrides courseid
1c7b8b93 718 $headers['filters']['group'] = $groupid;
cae83708 719 $group = $DB->get_record('groups', array('id' => $groupid));
720 $course = $DB->get_record('course', array('id' => $group->courseid));
721 }
bbbf2d40 722
897aa80c 723 $PAGE->set_pagelayout('standard');
27bad0a6 724
1c7b8b93
NC
725 if (!empty($modid) && $CFG->useblogassociations && has_capability('moodle/blog:associatemodule', $sitecontext)) { // modid always overrides courseid, so the $course object may be reset here
726 $headers['filters']['module'] = $modid;
cae83708 727 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
1c7b8b93
NC
728 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
729 $course = $DB->get_record('course', array('id' => $courseid));
cae83708 730 $cm = $DB->get_record('course_modules', array('id' => $modid));
731 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
732 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
e463f508 733 $a = new stdClass();
1c7b8b93 734 $a->type = get_string('modulename', $cm->modname);
c5dc10ee 735 $PAGE->set_cm($cm, $course);
1c7b8b93
NC
736 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
737 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 738 }
b73d1ca4 739
1c7b8b93
NC
740 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
741 // Note: if action is set to 'add' or 'edit', we do this at the end
742 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
743 $PAGE->navbar->add($strblogentries, $blogurl);
4a8b890a 744 $PAGE->set_title("$site->shortname: " . get_string('blog', 'blog'));
745 $PAGE->set_heading("$site->shortname: " . get_string('blog', 'blog'));
57513281 746 $headers['heading'] = get_string('siteblog', 'blog', $site->shortname);
1c7b8b93 747 // $headers['strview'] = get_string('viewsiteentries', 'blog');
4a8b890a 748 }
c2ee4e87 749
1c7b8b93 750 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
cae83708 751 if (!empty($entryid)) {
1c7b8b93
NC
752 $headers['filters']['entry'] = $entryid;
753 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
cae83708 754 $user = $DB->get_record_sql($sql, array($entryid));
1c7b8b93 755 $entry = $DB->get_record('post', array('id' => $entryid));
c2ee4e87 756
1c7b8b93 757 $blogurl->param('userid', $user->id);
c2ee4e87 758
cae83708 759 if (!empty($course)) {
9366362a 760 $mycourseid = $course->id;
1c7b8b93 761 $blogurl->param('courseid', $mycourseid);
c2ee4e87 762 } else {
9366362a 763 $mycourseid = $site->id;
c2ee4e87 764 }
e14de6f9 765
1c7b8b93
NC
766 $PAGE->navbar->add($strblogentries, $blogurl);
767
768 $blogurl->remove_params('userid');
769 $PAGE->navbar->add($entry->subject, $blogurl);
c5dc10ee 770
771 $PAGE->set_title("$site->shortname: " . fullname($user) . ": $entry->subject");
772 $PAGE->set_heading("$site->shortname: " . fullname($user) . ": $entry->subject");
cae83708 773 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
774
775 // We ignore tag and search params
1c7b8b93
NC
776 if (empty($action) || !$CFG->useblogassociations) {
777 $headers['url'] = $blogurl;
9366362a 778 return $headers;
779 }
c2ee4e87 780 }
240075cd 781
1c7b8b93
NC
782 // Case 3: A user's blog entries
783 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
784 $blogurl->param('userid', $userid);
c5dc10ee 785 $PAGE->set_title("$site->shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
786 $PAGE->set_heading("$site->shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
cae83708 787 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
27bad0a6 788 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
1c7b8b93
NC
789
790 } else
cae83708 791
1c7b8b93
NC
792 // Case 4: No blog associations, no userid
793 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
1c7b8b93
NC
794 $PAGE->set_title("$site->shortname: " . get_string('blog', 'blog'));
795 $PAGE->set_heading("$site->shortname: " . get_string('blog', 'blog'));
57513281 796 $headers['heading'] = get_string('siteblog', 'blog', $site->shortname);
cae83708 797 } else
798
1c7b8b93 799 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
9366362a 800 if (!empty($userid) && !empty($modid) && empty($entryid)) {
1c7b8b93
NC
801 $blogurl->param('userid', $userid);
802 $blogurl->param('modid', $modid);
cae83708 803
804 // Course module navigation is handled by build_navigation as the second param
805 $headers['cm'] = $cm;
c5dc10ee 806 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
1c7b8b93 807 $PAGE->navbar->add($strblogentries, $blogurl);
cae83708 808
c5dc10ee 809 $PAGE->set_title("$site->shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
810 $PAGE->set_heading("$site->shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
cae83708 811
e463f508 812 $a = new stdClass();
cae83708 813 $a->user = fullname($user);
814 $a->mod = $cm->name;
1c7b8b93 815 $a->type = get_string('modulename', $cm->modname);
cae83708 816 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
1c7b8b93
NC
817 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
818 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 819 } else
820
1c7b8b93 821 // Case 6: Blog entries associated with a course by a specific user
9366362a 822 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
1c7b8b93
NC
823 $blogurl->param('userid', $userid);
824 $blogurl->param('courseid', $courseid);
2c27b6ae 825
1c7b8b93 826 $PAGE->navbar->add($strblogentries, $blogurl);
cae83708 827
c5dc10ee 828 $PAGE->set_title("$site->shortname: $course->shortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
829 $PAGE->set_heading("$site->shortname: $course->shortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
cae83708 830
e463f508 831 $a = new stdClass();
cae83708 832 $a->user = fullname($user);
833 $a->course = $course->fullname;
1c7b8b93 834 $a->type = get_string('course');
cae83708 835 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
1c7b8b93
NC
836 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
837 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
838
839 // Remove the userid from the URL to inform the blog_menu block correctly
840 $blogurl->remove_params(array('userid'));
cae83708 841 } else
842
1c7b8b93 843 // Case 7: Blog entries by members of a group, associated with that group's course
9366362a 844 if (!empty($groupid) && empty($modid) && empty($entryid)) {
1c7b8b93 845 $blogurl->param('courseid', $course->id);
e14de6f9 846
1c7b8b93
NC
847 $PAGE->navbar->add($strblogentries, $blogurl);
848 $blogurl->remove_params(array('courseid'));
849 $blogurl->param('groupid', $groupid);
850 $PAGE->navbar->add($group->name, $blogurl);
cae83708 851
c5dc10ee 852 $PAGE->set_title("$site->shortname: $course->shortname: " . get_string('blogentries', 'blog') . ": $group->name");
853 $PAGE->set_heading("$site->shortname: $course->shortname: " . get_string('blogentries', 'blog') . ": $group->name");
cae83708 854
e463f508 855 $a = new stdClass();
cae83708 856 $a->group = $group->name;
857 $a->course = $course->fullname;
1c7b8b93 858 $a->type = get_string('course');
cae83708 859 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
1c7b8b93
NC
860 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
861 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
cae83708 862 } else
863
1c7b8b93 864 // Case 8: Blog entries by members of a group, associated with an activity in that course
9366362a 865 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
cae83708 866 $headers['cm'] = $cm;
1c7b8b93
NC
867 $blogurl->param('modid', $modid);
868 $PAGE->navbar->add($strblogentries, $blogurl);
cae83708 869
1c7b8b93
NC
870 $blogurl->param('groupid', $groupid);
871 $PAGE->navbar->add($group->name, $blogurl);
cae83708 872
c5dc10ee 873 $PAGE->set_title("$site->shortname: $course->shortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
874 $PAGE->set_heading("$site->shortname: $course->shortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
cae83708 875
e463f508 876 $a = new stdClass();
cae83708 877 $a->group = $group->name;
878 $a->mod = $cm->name;
1c7b8b93 879 $a->type = get_string('modulename', $cm->modname);
cae83708 880 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
1c7b8b93
NC
881 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
882 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 883
884 } else
885
1c7b8b93 886 // Case 9: All blog entries associated with an activity
9366362a 887 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
c5dc10ee 888 $PAGE->set_cm($cm, $course);
1c7b8b93
NC
889 $blogurl->param('modid', $modid);
890 $PAGE->navbar->add($strblogentries, $blogurl);
c5dc10ee 891 $PAGE->set_title("$site->shortname: $course->shortname: $cm->name: " . get_string('blogentries', 'blog'));
892 $PAGE->set_heading("$site->shortname: $course->shortname: $cm->name: " . get_string('blogentries', 'blog'));
cae83708 893 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
e463f508 894 $a = new stdClass();
1c7b8b93
NC
895 $a->type = get_string('modulename', $cm->modname);
896 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
897 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 898 } else
899
1c7b8b93 900 // Case 10: All blog entries associated with a course
9366362a 901 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
1c7b8b93
NC
902 $blogurl->param('courseid', $courseid);
903 $PAGE->navbar->add($strblogentries, $blogurl);
c5dc10ee 904 $PAGE->set_title("$site->shortname: $course->shortname: " . get_string('blogentries', 'blog'));
905 $PAGE->set_heading("$site->shortname: $course->shortname: " . get_string('blogentries', 'blog'));
e463f508 906 $a = new stdClass();
1c7b8b93 907 $a->type = get_string('course');
cae83708 908 $headers['heading'] = get_string('blogentriesabout', 'blog', $course->fullname);
1c7b8b93
NC
909 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
910 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
911 $blogurl->remove_params(array('userid'));
912 }
913
914 if (!in_array($action, array('edit', 'add'))) {
915 // Append Tag info
916 if (!empty($tagid)) {
917 $headers['filters']['tag'] = $tagid;
918 $blogurl->param('tagid', $tagid);
919 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
920 $PAGE->navbar->add($tagrec->name, $blogurl);
921 } elseif (!empty($tag)) {
922 $blogurl->param('tag', $tag);
923 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
924 }
240075cd 925
1c7b8b93
NC
926 // Append Search info
927 if (!empty($search)) {
928 $headers['filters']['search'] = $search;
929 $blogurl->param('search', $search);
930 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
931 }
ee00eb8c 932 }
933
cae83708 934 // Append edit mode info
935 if (!empty($action) && $action == 'add') {
f36b47ef 936
cae83708 937 } else if (!empty($action) && $action == 'edit') {
c5dc10ee 938 $PAGE->navbar->add(get_string('editentry', 'blog'));
240075cd 939 }
ee00eb8c 940
1c7b8b93
NC
941 if (empty($headers['url'])) {
942 $headers['url'] = $blogurl;
943 }
cae83708 944 return $headers;
945}
23677261 946
1c7b8b93
NC
947/**
948 * Shortcut function for getting a count of blog entries associated with a course or a module
949 * @param int $courseid The ID of the course
950 * @param int $cmid The ID of the course_modules
951 * @return string The number of associated entries
952 */
953function blog_get_associated_count($courseid, $cmid=null) {
954 global $DB;
955 $context = get_context_instance(CONTEXT_COURSE, $courseid);
956 if ($cmid) {
957 $context = get_context_instance(CONTEXT_MODULE, $cmid);
958 }
959 return $DB->count_records('blog_association', array('contextid' => $context->id));
593270c6 960}