MDL-30985 Fixed up event API phpdocs
[moodle.git] / blog / lib.php
blob080df708c88f71140912475c9e204cb9a0782fe5
1 <?php
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.
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/>.
18 /**
19 * Core global functions for Blog.
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
27 defined('MOODLE_INTERNAL') || die();
29 /**
30 * Library of functions and constants for blog
32 require_once($CFG->dirroot .'/blog/rsslib.php');
33 require_once($CFG->dirroot.'/tag/lib.php');
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.
40 * This also applies to deleting of entries.
42 function blog_user_can_edit_entry($blogentry) {
43 global $USER;
45 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
47 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
48 return true; // can edit any blog entry
51 if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
52 return true; // can edit own when having blog:create capability
55 return false;
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
64 function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
65 global $CFG, $USER, $DB;
67 if (empty($CFG->bloglevel)) {
68 return false; // blog system disabled
71 if (isloggedin() && $USER->id == $targetuserid) {
72 return true; // can view own entries in any case
75 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
76 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
77 return true; // can manage all entries
80 // coming for 1 entry, make sure it's not a draft
81 if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
82 return false; // can not view draft of others
85 // coming for 0 entry, make sure user is logged in, if not a public blog
86 if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
87 return false;
90 switch ($CFG->bloglevel) {
91 case BLOG_GLOBAL_LEVEL:
92 return true;
93 break;
95 case BLOG_SITE_LEVEL:
96 if (isloggedin()) { // not logged in viewers forbidden
97 return true;
99 return false;
100 break;
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;
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
115 function blog_remove_associations_for_user($userid) {
116 global $DB;
117 throw new coding_exception('function blog_remove_associations_for_user() is not finished');
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);
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
132 function 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));
139 * Given a record in the {blog_external} table, checks the blog's URL
140 * for new entries not yet copied into Moodle.
141 * Also attempts to identify and remove deleted blog entries
143 * @param object $externalblog
144 * @return boolean False if the Feed is invalid
146 function blog_sync_external_entries($externalblog) {
147 global $CFG, $DB;
148 require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
150 $rssfile = new moodle_simplepie_file($externalblog->url);
151 $filetest = new SimplePie_Locator($rssfile);
153 $textlib = textlib_get_instance(); // Going to use textlib services
155 if (!$filetest->is_feed($rssfile)) {
156 $externalblog->failedlastsync = 1;
157 $DB->update_record('blog_external', $externalblog);
158 return false;
159 } else if (!empty($externalblog->failedlastsync)) {
160 $externalblog->failedlastsync = 0;
161 $DB->update_record('blog_external', $externalblog);
164 $rss = new moodle_simplepie($externalblog->url);
166 if (empty($rss->data)) {
167 return null;
169 //used to identify blog posts that have been deleted from the source feed
170 $oldesttimestamp = null;
171 $uniquehashes = array();
173 foreach ($rss->get_items() as $entry) {
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);
182 foreach ($categories as $category) {
183 if (in_array(trim(strtolower($category->term)), $filtertags)) {
184 $containsfiltertag = true;
188 if (!$containsfiltertag) {
189 continue;
193 $uniquehashes[] = $entry->get_permalink();
195 $newentry = new stdClass();
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;
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) . '...';
209 $newentry->summary = $entry->get_description();
211 //used to decide whether to insert or update
212 //uses enty permalink plus creation date if available
213 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
215 //our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
216 $entrydate = $entry->get_date('U');
217 if (!empty($entrydate)) {
218 $existingpostconditions['created'] = $entrydate;
221 //the post ID or false if post not found in DB
222 $postid = $DB->get_field('post', 'id', $existingpostconditions);
224 $timestamp = null;
225 if (empty($entrydate)) {
226 $timestamp = time();
227 } else {
228 $timestamp = $entrydate;
231 //only set created if its a new post so we retain the original creation timestamp if the post is edited
232 if ($postid === false) {
233 $newentry->created = $timestamp;
235 $newentry->lastmodified = $timestamp;
237 if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
238 //found an older post
239 $oldesttimestamp = $timestamp;
242 $textlib = textlib_get_instance();
243 if ($textlib->strlen($newentry->uniquehash) > 255) {
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;
251 if ($postid === false) {
252 $id = $DB->insert_record('post', $newentry);
254 // Set tags
255 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
256 tag_set('post', $id, $tags);
258 } else {
259 $newentry->id = $postid;
260 $DB->update_record('post', $newentry);
264 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
265 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
266 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
267 $sql = "SELECT id, uniquehash
268 FROM {post}
269 WHERE module = 'blog_external'
270 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
271 AND created > :ts";
272 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
274 $todelete = array();
275 foreach($dbposts as $dbpost) {
276 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
277 $todelete[] = $dbpost->id;
280 $DB->delete_records_list('post', 'id', $todelete);
282 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
286 * Given an external blog object, deletes all related blog entries from the post table.
287 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
288 * @param object $externablog
290 function blog_delete_external_entries($externalblog) {
291 global $DB;
292 require_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM));
293 $DB->delete_records_select('post',
294 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
295 array($externalblog->id));
299 * Returns a URL based on the context of the current page.
300 * This URL points to blog/index.php and includes filter parameters appropriate for the current page.
302 * @param stdclass $context
303 * @return string
305 function blog_get_context_url($context=null) {
306 global $CFG;
308 $viewblogentriesurl = new moodle_url('/blog/index.php');
310 if (empty($context)) {
311 global $PAGE;
312 $context = $PAGE->context;
315 // Change contextlevel to SYSTEM if viewing the site course
316 if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
317 $context = context_system::instance();
320 $filterparam = '';
321 $strlevel = '';
323 switch ($context->contextlevel) {
324 case CONTEXT_SYSTEM:
325 case CONTEXT_BLOCK:
326 case CONTEXT_COURSECAT:
327 break;
328 case CONTEXT_COURSE:
329 $filterparam = 'courseid';
330 $strlevel = get_string('course');
331 break;
332 case CONTEXT_MODULE:
333 $filterparam = 'modid';
334 $strlevel = print_context_name($context);
335 break;
336 case CONTEXT_USER:
337 $filterparam = 'userid';
338 $strlevel = get_string('user');
339 break;
342 if (!empty($filterparam)) {
343 $viewblogentriesurl->param($filterparam, $context->instanceid);
346 return $viewblogentriesurl;
350 * This function checks that blogs are enabled, and that the user can see blogs at all
351 * @return bool
353 function blog_is_enabled_for_user() {
354 global $CFG;
355 //return (!empty($CFG->bloglevel) && $CFG->bloglevel <= BLOG_GLOBAL_LEVEL && isloggedin() && !isguestuser());
356 return (!empty($CFG->bloglevel) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
360 * This function gets all of the options available for the current user in respect
361 * to blogs.
363 * It loads the following if applicable:
364 * - Module options {@see blog_get_options_for_module}
365 * - Course options {@see blog_get_options_for_course}
366 * - User specific options {@see blog_get_options_for_user}
367 * - General options (BLOG_LEVEL_GLOBAL)
369 * @param moodle_page $page The page to load for (normally $PAGE)
370 * @param stdClass $userid Load for a specific user
371 * @return array An array of options organised by type.
373 function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
374 global $CFG, $DB, $USER;
376 $options = array();
378 // If blogs are enabled and the user is logged in and not a guest
379 if (blog_is_enabled_for_user()) {
380 // If the context is the user then assume we want to load for the users context
381 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
382 $userid = $page->context->instanceid;
384 // Check the userid var
385 if (!is_null($userid) && $userid!==$USER->id) {
386 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
387 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
388 } else {
389 $user = null;
392 if ($CFG->useblogassociations && $page->cm !== null) {
393 // Load for the module associated with the page
394 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
395 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
396 // Load the options for the course associated with the page
397 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
400 // Get the options for the user
401 if ($user !== null and !isguestuser($user)) {
402 // Load for the requested user
403 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
405 // Load for the current user
406 if (isloggedin() and !isguestuser()) {
407 $options[CONTEXT_USER] = blog_get_options_for_user();
411 // If blog level is global then display a link to view all site entries
412 if (!empty($CFG->bloglevel) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
413 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
414 'string' => get_string('viewsiteentries', 'blog'),
415 'link' => new moodle_url('/blog/index.php')
419 // Return the options
420 return $options;
424 * Get all of the blog options that relate to the passed user.
426 * If no user is passed the current user is assumed.
428 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
429 * @param stdClass $user
430 * @return array The array of options for the requested user
432 function blog_get_options_for_user(stdClass $user=null) {
433 global $CFG, $USER;
434 // Cache
435 static $useroptions = array();
437 $options = array();
438 // Blogs must be enabled and the user must be logged in
439 if (!blog_is_enabled_for_user()) {
440 return $options;
443 // Sort out the user var
444 if ($user === null || $user->id == $USER->id) {
445 $user = $USER;
446 $iscurrentuser = true;
447 } else {
448 $iscurrentuser = false;
451 // If we've already generated serve from the cache
452 if (array_key_exists($user->id, $useroptions)) {
453 return $useroptions[$user->id];
456 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
457 $canview = has_capability('moodle/blog:view', $sitecontext);
459 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
460 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
461 $options['userentries'] = array(
462 'string' => get_string('viewuserentries', 'blog', fullname($user)),
463 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
465 } else {
466 // It's the current user
467 if ($canview) {
468 // We can view our own blogs .... BIG surprise
469 $options['view'] = array(
470 'string' => get_string('viewallmyentries', 'blog'),
471 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
474 if (has_capability('moodle/blog:create', $sitecontext)) {
475 // We can add to our own blog
476 $options['add'] = array(
477 'string' => get_string('addnewentry', 'blog'),
478 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
482 if ($canview && $CFG->enablerssfeeds) {
483 $options['rss'] = array(
484 'string' => get_string('rssfeed', 'blog'),
485 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
489 // Cache the options
490 $useroptions[$user->id] = $options;
491 // Return the options
492 return $options;
496 * Get the blog options that relate to the given course for the given user.
498 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
499 * @param stdClass $course The course to load options for
500 * @param stdClass $user The user to load options for null == current user
501 * @return array The array of options
503 function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
504 global $CFG, $USER;
505 // Cache
506 static $courseoptions = array();
508 $options = array();
510 // User must be logged in and blogs must be enabled
511 if (!blog_is_enabled_for_user()) {
512 return $options;
515 // Check that the user can associate with the course
516 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
517 if (!has_capability('moodle/blog:associatecourse', $sitecontext)) {
518 return $options;
520 // Generate the cache key
521 $key = $course->id.':';
522 if (!empty($user)) {
523 $key .= $user->id;
524 } else {
525 $key .= $USER->id;
527 // Serve from the cache if we've already generated for this course
528 if (array_key_exists($key, $courseoptions)) {
529 return $courseoptions[$key];
532 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
533 $canparticipate = (is_enrolled($coursecontext) or is_viewing($coursecontext));
535 if (has_capability('moodle/blog:view', $coursecontext)) {
536 // We can view!
537 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
538 // View entries about this course
539 $options['courseview'] = array(
540 'string' => get_string('viewcourseblogs', 'blog'),
541 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id))
544 // View MY entries about this course
545 $options['courseviewmine'] = array(
546 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
547 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$USER->id))
549 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
550 // View the provided users entries about this course
551 $options['courseviewuser'] = array(
552 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
553 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$user->id))
558 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
559 // We can blog about this course
560 $options['courseadd'] = array(
561 'string' => get_string('blogaboutthiscourse', 'blog'),
562 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'courseid'=>$course->id))
567 // Cache the options for this course
568 $courseoptions[$key] = $options;
569 // Return the options
570 return $options;
574 * Get the blog options relating to the given module for the given user
576 * @staticvar array $moduleoptions Cache
577 * @param stdClass|cm_info $module The module to get options for
578 * @param stdClass $user The user to get options for null == currentuser
579 * @return array
581 function blog_get_options_for_module($module, $user=null) {
582 global $CFG, $USER;
583 // Cache
584 static $moduleoptions = array();
586 $options = array();
587 // User must be logged in, blogs must be enabled
588 if (!blog_is_enabled_for_user()) {
589 return $options;
592 // Check the user can associate with the module
593 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
594 if (!has_capability('moodle/blog:associatemodule', $sitecontext)) {
595 return $options;
598 // Generate the cache key
599 $key = $module->id.':';
600 if (!empty($user)) {
601 $key .= $user->id;
602 } else {
603 $key .= $USER->id;
605 if (array_key_exists($key, $moduleoptions)) {
606 // Serve from the cache so we don't have to regenerate
607 return $moduleoptions[$module->id];
610 $modcontext = get_context_instance(CONTEXT_MODULE, $module->id);
611 $canparticipate = (is_enrolled($modcontext) or is_viewing($modcontext));
613 if (has_capability('moodle/blog:view', $modcontext)) {
614 // We can view!
615 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
616 // View all entries about this module
617 $a = new stdClass;
618 $a->type = $module->modname;
619 $options['moduleview'] = array(
620 'string' => get_string('viewallmodentries', 'blog', $a),
621 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
624 // View MY entries about this module
625 $options['moduleviewmine'] = array(
626 'string' => get_string('viewmyentriesaboutmodule', 'blog', $module->modname),
627 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
629 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
630 // View the given users entries about this module
631 $a = new stdClass;
632 $a->mod = $module->modname;
633 $a->user = fullname($user);
634 $options['moduleviewuser'] = array(
635 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
636 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
641 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
642 // The user can blog about this module
643 $options['moduleadd'] = array(
644 'string' => get_string('blogaboutthismodule', 'blog', $module->modname),
645 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
648 // Cache the options
649 $moduleoptions[$key] = $options;
650 // Return the options
651 return $options;
655 * This function encapsulates all the logic behind the complex
656 * navigation, titles and headings of the blog listing page, depending
657 * on URL params. It looks at URL params and at the current context level.
658 * It builds and returns an array containing:
660 * 1. heading: The heading displayed above the blog entries
661 * 2. stradd: The text to be used as the "Add entry" link
662 * 3. strview: The text to be used as the "View entries" link
663 * 4. url: The moodle_url object used as the base for add and view links
664 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
666 * All other variables are set directly in $PAGE
668 * It uses the current URL to build these variables.
669 * A number of mutually exclusive use cases are used to structure this function.
671 * @return array
673 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
674 global $CFG, $PAGE, $DB, $USER;
676 $id = optional_param('id', null, PARAM_INT);
677 $tag = optional_param('tag', null, PARAM_NOTAGS);
678 $tagid = optional_param('tagid', $tagid, PARAM_INT);
679 $userid = optional_param('userid', $userid, PARAM_INT);
680 $modid = optional_param('modid', null, PARAM_INT);
681 $entryid = optional_param('entryid', null, PARAM_INT);
682 $groupid = optional_param('groupid', $groupid, PARAM_INT);
683 $courseid = optional_param('courseid', $courseid, PARAM_INT);
684 $search = optional_param('search', null, PARAM_RAW);
685 $action = optional_param('action', null, PARAM_ALPHA);
686 $confirm = optional_param('confirm', false, PARAM_BOOL);
688 // Ignore userid when action == add
689 if ($action == 'add' && $userid) {
690 unset($userid);
691 $PAGE->url->remove_params(array('userid'));
692 } else if ($action == 'add' && $entryid) {
693 unset($entryid);
694 $PAGE->url->remove_params(array('entryid'));
697 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
699 $blogurl = new moodle_url('/blog/index.php');
701 // If the title is not yet set, it's likely that the context isn't set either, so skip this part
702 $pagetitle = $PAGE->title;
703 if (!empty($pagetitle)) {
704 $contexturl = blog_get_context_url();
706 // Look at the context URL, it may have additional params that are not in the current URL
707 if (!$blogurl->compare($contexturl)) {
708 $blogurl = $contexturl;
709 if (empty($courseid)) {
710 $courseid = $blogurl->param('courseid');
712 if (empty($modid)) {
713 $modid = $blogurl->param('modid');
718 $headers['stradd'] = get_string('addnewentry', 'blog');
719 $headers['strview'] = null;
721 $site = $DB->get_record('course', array('id' => SITEID));
722 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
723 // Common Lang strings
724 $strparticipants = get_string("participants");
725 $strblogentries = get_string("blogentries", 'blog');
727 // Prepare record objects as needed
728 if (!empty($courseid)) {
729 $headers['filters']['course'] = $courseid;
730 $course = $DB->get_record('course', array('id' => $courseid));
733 if (!empty($userid)) {
734 $headers['filters']['user'] = $userid;
735 $user = $DB->get_record('user', array('id' => $userid));
738 if (!empty($groupid)) { // groupid always overrides courseid
739 $headers['filters']['group'] = $groupid;
740 $group = $DB->get_record('groups', array('id' => $groupid));
741 $course = $DB->get_record('course', array('id' => $group->courseid));
744 $PAGE->set_pagelayout('standard');
746 if (!empty($modid) && $CFG->useblogassociations && has_capability('moodle/blog:associatemodule', $sitecontext)) { // modid always overrides courseid, so the $course object may be reset here
747 $headers['filters']['module'] = $modid;
748 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
749 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
750 $course = $DB->get_record('course', array('id' => $courseid));
751 $cm = $DB->get_record('course_modules', array('id' => $modid));
752 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
753 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
754 $a = new stdClass();
755 $a->type = get_string('modulename', $cm->modname);
756 $PAGE->set_cm($cm, $course);
757 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
758 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
761 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
762 // Note: if action is set to 'add' or 'edit', we do this at the end
763 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
764 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
765 $PAGE->navbar->add($strblogentries, $blogurl);
766 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
767 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
768 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
769 // $headers['strview'] = get_string('viewsiteentries', 'blog');
772 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
773 if (!empty($entryid)) {
774 $headers['filters']['entry'] = $entryid;
775 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
776 $user = $DB->get_record_sql($sql, array($entryid));
777 $entry = $DB->get_record('post', array('id' => $entryid));
779 $blogurl->param('userid', $user->id);
781 if (!empty($course)) {
782 $mycourseid = $course->id;
783 $blogurl->param('courseid', $mycourseid);
784 } else {
785 $mycourseid = $site->id;
787 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
789 $PAGE->navbar->add($strblogentries, $blogurl);
791 $blogurl->remove_params('userid');
792 $PAGE->navbar->add($entry->subject, $blogurl);
793 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
794 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
795 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
797 // We ignore tag and search params
798 if (empty($action) || !$CFG->useblogassociations) {
799 $headers['url'] = $blogurl;
800 return $headers;
804 // Case 3: A user's blog entries
805 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
806 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
807 $blogurl->param('userid', $userid);
808 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
809 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
810 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
811 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
813 } else
815 // Case 4: No blog associations, no userid
816 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
817 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
818 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
819 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
820 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
821 } else
823 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
824 if (!empty($userid) && !empty($modid) && empty($entryid)) {
825 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
826 $blogurl->param('userid', $userid);
827 $blogurl->param('modid', $modid);
829 // Course module navigation is handled by build_navigation as the second param
830 $headers['cm'] = $cm;
831 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
832 $PAGE->navbar->add($strblogentries, $blogurl);
834 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
835 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
837 $a = new stdClass();
838 $a->user = fullname($user);
839 $a->mod = $cm->name;
840 $a->type = get_string('modulename', $cm->modname);
841 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
842 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
843 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
844 } else
846 // Case 6: Blog entries associated with a course by a specific user
847 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
848 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
849 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
850 $blogurl->param('userid', $userid);
851 $blogurl->param('courseid', $courseid);
853 $PAGE->navbar->add($strblogentries, $blogurl);
855 $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
856 $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
858 $a = new stdClass();
859 $a->user = fullname($user);
860 $a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
861 $a->type = get_string('course');
862 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
863 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
864 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
866 // Remove the userid from the URL to inform the blog_menu block correctly
867 $blogurl->remove_params(array('userid'));
868 } else
870 // Case 7: Blog entries by members of a group, associated with that group's course
871 if (!empty($groupid) && empty($modid) && empty($entryid)) {
872 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
873 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
874 $blogurl->param('courseid', $course->id);
876 $PAGE->navbar->add($strblogentries, $blogurl);
877 $blogurl->remove_params(array('courseid'));
878 $blogurl->param('groupid', $groupid);
879 $PAGE->navbar->add($group->name, $blogurl);
881 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
882 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
884 $a = new stdClass();
885 $a->group = $group->name;
886 $a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
887 $a->type = get_string('course');
888 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
889 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
890 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
891 } else
893 // Case 8: Blog entries by members of a group, associated with an activity in that course
894 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
895 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
896 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
897 $headers['cm'] = $cm;
898 $blogurl->param('modid', $modid);
899 $PAGE->navbar->add($strblogentries, $blogurl);
901 $blogurl->param('groupid', $groupid);
902 $PAGE->navbar->add($group->name, $blogurl);
904 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
905 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
907 $a = new stdClass();
908 $a->group = $group->name;
909 $a->mod = $cm->name;
910 $a->type = get_string('modulename', $cm->modname);
911 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
912 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
913 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
915 } else
917 // Case 9: All blog entries associated with an activity
918 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
919 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
920 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
921 $PAGE->set_cm($cm, $course);
922 $blogurl->param('modid', $modid);
923 $PAGE->navbar->add($strblogentries, $blogurl);
924 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
925 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
926 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
927 $a = new stdClass();
928 $a->type = get_string('modulename', $cm->modname);
929 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
930 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
931 } else
933 // Case 10: All blog entries associated with a course
934 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
935 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
936 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
937 $blogurl->param('courseid', $courseid);
938 $PAGE->navbar->add($strblogentries, $blogurl);
939 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
940 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
941 $a = new stdClass();
942 $a->type = get_string('course');
943 $headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))));
944 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
945 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
946 $blogurl->remove_params(array('userid'));
949 if (!in_array($action, array('edit', 'add'))) {
950 // Append Tag info
951 if (!empty($tagid)) {
952 $headers['filters']['tag'] = $tagid;
953 $blogurl->param('tagid', $tagid);
954 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
955 $PAGE->navbar->add($tagrec->name, $blogurl);
956 } elseif (!empty($tag)) {
957 $blogurl->param('tag', $tag);
958 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
961 // Append Search info
962 if (!empty($search)) {
963 $headers['filters']['search'] = $search;
964 $blogurl->param('search', $search);
965 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
969 // Append edit mode info
970 if (!empty($action) && $action == 'add') {
972 } else if (!empty($action) && $action == 'edit') {
973 $PAGE->navbar->add(get_string('editentry', 'blog'));
976 if (empty($headers['url'])) {
977 $headers['url'] = $blogurl;
979 return $headers;
983 * Shortcut function for getting a count of blog entries associated with a course or a module
984 * @param int $courseid The ID of the course
985 * @param int $cmid The ID of the course_modules
986 * @return string The number of associated entries
988 function blog_get_associated_count($courseid, $cmid=null) {
989 global $DB;
990 $context = get_context_instance(CONTEXT_COURSE, $courseid);
991 if ($cmid) {
992 $context = get_context_instance(CONTEXT_MODULE, $cmid);
994 return $DB->count_records('blog_association', array('contextid' => $context->id));
998 * Running addtional permission check on plugin, for example, plugins
999 * may have switch to turn on/off comments option, this callback will
1000 * affect UI display, not like pluginname_comment_validate only throw
1001 * exceptions.
1002 * Capability check has been done in comment->check_permissions(), we
1003 * don't need to do it again here.
1005 * @package core_blog
1006 * @category comment
1008 * @param stdClass $comment_param {
1009 * context => context the context object
1010 * courseid => int course id
1011 * cm => stdClass course module object
1012 * commentarea => string comment area
1013 * itemid => int itemid
1015 * @return array
1017 function blog_comment_permissions($comment_param) {
1018 return array('post'=>true, 'view'=>true);
1022 * Validate comment parameter before perform other comments actions
1024 * @package core_blog
1025 * @category comment
1027 * @param stdClass $comment {
1028 * context => context the context object
1029 * courseid => int course id
1030 * cm => stdClass course module object
1031 * commentarea => string comment area
1032 * itemid => int itemid
1034 * @return boolean
1036 function blog_comment_validate($comment_param) {
1037 global $DB;
1038 // validate comment itemid
1039 if (!$entry = $DB->get_record('post', array('id'=>$comment_param->itemid))) {
1040 throw new comment_exception('invalidcommentitemid');
1042 // validate comment area
1043 if ($comment_param->commentarea != 'format_blog') {
1044 throw new comment_exception('invalidcommentarea');
1046 // validation for comment deletion
1047 if (!empty($comment_param->commentid)) {
1048 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
1049 if ($record->commentarea != 'format_blog') {
1050 throw new comment_exception('invalidcommentarea');
1052 if ($record->contextid != $comment_param->context->id) {
1053 throw new comment_exception('invalidcontext');
1055 if ($record->itemid != $comment_param->itemid) {
1056 throw new comment_exception('invalidcommentitemid');
1058 } else {
1059 throw new comment_exception('invalidcommentid');
1062 return true;
1066 * Return a list of page types
1067 * @param string $pagetype current page type
1068 * @param stdClass $parentcontext Block's parent context
1069 * @param stdClass $currentcontext Current context of block
1071 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1072 return array(
1073 '*'=>get_string('page-x', 'pagetype'),
1074 'blog-*'=>get_string('page-blog-x', 'blog'),
1075 'blog-index'=>get_string('page-blog-index', 'blog'),
1076 'blog-edit'=>get_string('page-blog-edit', 'blog')