Merge branch 'MDL-51402' of git://github.com/timhunt/moodle
[moodle.git] / blog / lib.php
blobf99ed31695cd0c8cb20194ff66d92fbf8e4cd0ba
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * Core global functions for Blog.
20 * @package moodlecore
21 * @subpackage blog
22 * @copyright 2009 Nicolas Connault
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') || die();
29 * Library of functions and constants for blog
31 require_once($CFG->dirroot .'/blog/rsslib.php');
32 require_once($CFG->dirroot.'/tag/lib.php');
34 /**
35 * User can edit a blog entry if this is their own blog entry and they have
36 * the capability moodle/blog:create, or if they have the capability
37 * moodle/blog:manageentries.
39 * This also applies to deleting of entries.
41 function blog_user_can_edit_entry($blogentry) {
42 global $USER;
44 $sitecontext = context_system::instance();
46 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
47 return true; // Can edit any blog entry.
50 if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
51 return true; // Can edit own when having blog:create capability.
54 return false;
58 /**
59 * Checks to see if a user can view the blogs of another user.
60 * Only blog level is checked here, the capabilities are enforced
61 * in blog/index.php
63 function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
64 global $CFG, $USER, $DB;
66 if (empty($CFG->enableblogs)) {
67 return false; // Blog system disabled.
70 if (isloggedin() && $USER->id == $targetuserid) {
71 return true; // Can view own entries in any case.
74 $sitecontext = context_system::instance();
75 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
76 return true; // Can manage all entries.
79 // If blog is in draft state, then make sure user have proper capability.
80 if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
81 return false; // Can not view draft of others.
84 // If blog entry is not public, make sure user is logged in.
85 if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
86 return false;
89 // If blogentry is not passed or all above checks pass, then check capability based on system config.
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 // If user is viewing other user blog, then user should have user:readuserblogs capability.
105 $personalcontext = context_user::instance($targetuserid);
106 return has_capability('moodle/user:readuserblogs', $personalcontext);
107 break;
113 * remove all associations for the blog entries of a particular user
114 * @param int userid - id of user whose blog associations will be deleted
116 function blog_remove_associations_for_user($userid) {
117 global $DB;
118 throw new coding_exception('function blog_remove_associations_for_user() is not finished');
120 $blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
121 foreach ($blogentries as $entry) {
122 if (blog_user_can_edit_entry($entry)) {
123 blog_remove_associations_for_entry($entry->id);
130 * remove all associations for the blog entries of a particular course
131 * @param int courseid - id of user whose blog associations will be deleted
133 function blog_remove_associations_for_course($courseid) {
134 global $DB;
135 $context = context_course::instance($courseid);
136 $DB->delete_records('blog_association', array('contextid' => $context->id));
140 * Given a record in the {blog_external} table, checks the blog's URL
141 * for new entries not yet copied into Moodle.
142 * Also attempts to identify and remove deleted blog entries
144 * @param object $externalblog
145 * @return boolean False if the Feed is invalid
147 function blog_sync_external_entries($externalblog) {
148 global $CFG, $DB;
149 require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
151 $rss = new moodle_simplepie();
152 $rssfile = $rss->registry->create('File', array($externalblog->url));
153 $filetest = $rss->registry->create('Locator', array($rssfile));
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->set_feed_url($externalblog->url);
165 $rss->init();
167 if (empty($rss->data)) {
168 return null;
170 // Used to identify blog posts that have been deleted from the source feed.
171 $oldesttimestamp = null;
172 $uniquehashes = array();
174 foreach ($rss->get_items() as $entry) {
175 // If filtertags are defined, use them to filter the entries by RSS category.
176 if (!empty($externalblog->filtertags)) {
177 $containsfiltertag = false;
178 $categories = $entry->get_categories();
179 $filtertags = explode(',', $externalblog->filtertags);
180 $filtertags = array_map('trim', $filtertags);
181 $filtertags = array_map('strtolower', $filtertags);
183 if (!empty($categories)) {
184 foreach ($categories as $category) {
185 if (in_array(trim(strtolower($category->term)), $filtertags)) {
186 $containsfiltertag = true;
191 if (!$containsfiltertag) {
192 continue;
196 $uniquehashes[] = $entry->get_permalink();
198 $newentry = new stdClass();
199 $newentry->userid = $externalblog->userid;
200 $newentry->module = 'blog_external';
201 $newentry->content = $externalblog->id;
202 $newentry->uniquehash = $entry->get_permalink();
203 $newentry->publishstate = 'site';
204 $newentry->format = FORMAT_HTML;
205 // Clean subject of html, just in case.
206 $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
207 // Observe 128 max chars in DB.
208 // TODO: +1 to raise this to 255.
209 if (core_text::strlen($newentry->subject) > 128) {
210 $newentry->subject = core_text::substr($newentry->subject, 0, 125) . '...';
212 $newentry->summary = $entry->get_description();
214 // Used to decide whether to insert or update.
215 // Uses enty permalink plus creation date if available.
216 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
218 // Our DB doesnt allow null creation or modified timestamps so check the external blog supplied one.
219 $entrydate = $entry->get_date('U');
220 if (!empty($entrydate)) {
221 $existingpostconditions['created'] = $entrydate;
224 // The post ID or false if post not found in DB.
225 $postid = $DB->get_field('post', 'id', $existingpostconditions);
227 $timestamp = null;
228 if (empty($entrydate)) {
229 $timestamp = time();
230 } else {
231 $timestamp = $entrydate;
234 // Only set created if its a new post so we retain the original creation timestamp if the post is edited.
235 if ($postid === false) {
236 $newentry->created = $timestamp;
238 $newentry->lastmodified = $timestamp;
240 if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
241 // Found an older post.
242 $oldesttimestamp = $timestamp;
245 if (core_text::strlen($newentry->uniquehash) > 255) {
246 // The URL for this item is too long for the field. Rather than add
247 // the entry without the link we will skip straight over it.
248 // RSS spec says recommended length 500, we use 255.
249 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
250 continue;
253 if ($postid === false) {
254 $id = $DB->insert_record('post', $newentry);
256 // Set tags.
257 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
258 tag_set('post', $id, $tags, 'core', context_user::instance($externalblog->userid)->id);
260 } else {
261 $newentry->id = $postid;
262 $DB->update_record('post', $newentry);
266 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
267 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
268 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
269 $sql = "SELECT id, uniquehash
270 FROM {post}
271 WHERE module = 'blog_external'
272 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
273 AND created > :ts";
274 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
276 $todelete = array();
277 foreach ($dbposts as $dbpost) {
278 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
279 $todelete[] = $dbpost->id;
282 $DB->delete_records_list('post', 'id', $todelete);
284 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
288 * Given an external blog object, deletes all related blog entries from the post table.
289 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
290 * @param object $externablog
292 function blog_delete_external_entries($externalblog) {
293 global $DB;
294 require_capability('moodle/blog:manageexternal', context_system::instance());
295 $DB->delete_records_select('post',
296 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
297 array($externalblog->id));
301 * This function checks that blogs are enabled, and that the user can see blogs at all
302 * @return bool
304 function blog_is_enabled_for_user() {
305 global $CFG;
306 return (!empty($CFG->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
310 * This function gets all of the options available for the current user in respect
311 * to blogs.
313 * It loads the following if applicable:
314 * - Module options {@see blog_get_options_for_module}
315 * - Course options {@see blog_get_options_for_course}
316 * - User specific options {@see blog_get_options_for_user}
317 * - General options (BLOG_LEVEL_GLOBAL)
319 * @param moodle_page $page The page to load for (normally $PAGE)
320 * @param stdClass $userid Load for a specific user
321 * @return array An array of options organised by type.
323 function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
324 global $CFG, $DB, $USER;
326 $options = array();
328 // If blogs are enabled and the user is logged in and not a guest.
329 if (blog_is_enabled_for_user()) {
330 // If the context is the user then assume we want to load for the users context.
331 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
332 $userid = $page->context->instanceid;
334 // Check the userid var.
335 if (!is_null($userid) && $userid!==$USER->id) {
336 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
337 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
338 } else {
339 $user = null;
342 if ($CFG->useblogassociations && $page->cm !== null) {
343 // Load for the module associated with the page.
344 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
345 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
346 // Load the options for the course associated with the page.
347 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
350 // Get the options for the user.
351 if ($user !== null and !isguestuser($user)) {
352 // Load for the requested user.
353 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
355 // Load for the current user.
356 if (isloggedin() and !isguestuser()) {
357 $options[CONTEXT_USER] = blog_get_options_for_user();
361 // If blog level is global then display a link to view all site entries.
362 if (!empty($CFG->enableblogs)
363 && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL
364 && has_capability('moodle/blog:view', context_system::instance())) {
366 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
367 'string' => get_string('viewsiteentries', 'blog'),
368 'link' => new moodle_url('/blog/index.php')
372 // Return the options.
373 return $options;
377 * Get all of the blog options that relate to the passed user.
379 * If no user is passed the current user is assumed.
381 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
382 * @param stdClass $user
383 * @return array The array of options for the requested user
385 function blog_get_options_for_user(stdClass $user=null) {
386 global $CFG, $USER;
387 // Cache.
388 static $useroptions = array();
390 $options = array();
391 // Blogs must be enabled and the user must be logged in.
392 if (!blog_is_enabled_for_user()) {
393 return $options;
396 // Sort out the user var.
397 if ($user === null || $user->id == $USER->id) {
398 $user = $USER;
399 $iscurrentuser = true;
400 } else {
401 $iscurrentuser = false;
404 // If we've already generated serve from the cache.
405 if (array_key_exists($user->id, $useroptions)) {
406 return $useroptions[$user->id];
409 $sitecontext = context_system::instance();
410 $canview = has_capability('moodle/blog:view', $sitecontext);
412 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
413 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL.
414 $options['userentries'] = array(
415 'string' => get_string('viewuserentries', 'blog', fullname($user)),
416 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
418 } else {
419 // It's the current user.
420 if ($canview) {
421 // We can view our own blogs .... BIG surprise.
422 $options['view'] = array(
423 'string' => get_string('blogentries', 'blog'),
424 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
427 if (has_capability('moodle/blog:create', $sitecontext)) {
428 // We can add to our own blog.
429 $options['add'] = array(
430 'string' => get_string('addnewentry', 'blog'),
431 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
435 if ($canview && $CFG->enablerssfeeds) {
436 $options['rss'] = array(
437 'string' => get_string('rssfeed', 'blog'),
438 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
442 // Cache the options.
443 $useroptions[$user->id] = $options;
444 // Return the options.
445 return $options;
449 * Get the blog options that relate to the given course for the given user.
451 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
452 * @param stdClass $course The course to load options for
453 * @param stdClass $user The user to load options for null == current user
454 * @return array The array of options
456 function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
457 global $CFG, $USER;
458 // Cache.
459 static $courseoptions = array();
461 $options = array();
463 // User must be logged in and blogs must be enabled.
464 if (!blog_is_enabled_for_user()) {
465 return $options;
468 // Check that the user can associate with the course.
469 $sitecontext = context_system::instance();
470 // Generate the cache key.
471 $key = $course->id.':';
472 if (!empty($user)) {
473 $key .= $user->id;
474 } else {
475 $key .= $USER->id;
477 // Serve from the cache if we've already generated for this course.
478 if (array_key_exists($key, $courseoptions)) {
479 return $courseoptions[$key];
482 if (has_capability('moodle/blog:view', $sitecontext)) {
483 // We can view!
484 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
485 // View entries about this course.
486 $options['courseview'] = array(
487 'string' => get_string('viewcourseblogs', 'blog'),
488 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id))
491 // View MY entries about this course.
492 $options['courseviewmine'] = array(
493 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
494 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $USER->id))
496 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
497 // View the provided users entries about this course.
498 $options['courseviewuser'] = array(
499 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
500 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $user->id))
505 if (has_capability('moodle/blog:create', $sitecontext)) {
506 // We can blog about this course.
507 $options['courseadd'] = array(
508 'string' => get_string('blogaboutthiscourse', 'blog'),
509 'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'courseid' => $course->id))
513 // Cache the options for this course.
514 $courseoptions[$key] = $options;
515 // Return the options.
516 return $options;
520 * Get the blog options relating to the given module for the given user
522 * @staticvar array $moduleoptions Cache
523 * @param stdClass|cm_info $module The module to get options for
524 * @param stdClass $user The user to get options for null == currentuser
525 * @return array
527 function blog_get_options_for_module($module, $user=null) {
528 global $CFG, $USER;
529 // Cache.
530 static $moduleoptions = array();
532 $options = array();
533 // User must be logged in, blogs must be enabled.
534 if (!blog_is_enabled_for_user()) {
535 return $options;
538 $sitecontext = context_system::instance();
540 // Generate the cache key.
541 $key = $module->id.':';
542 if (!empty($user)) {
543 $key .= $user->id;
544 } else {
545 $key .= $USER->id;
547 if (array_key_exists($key, $moduleoptions)) {
548 // Serve from the cache so we don't have to regenerate.
549 return $moduleoptions[$key];
552 if (has_capability('moodle/blog:view', $sitecontext)) {
553 // Save correct module name for later usage.
554 $modulename = get_string('modulename', $module->modname);
556 // We can view!
557 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
558 // View all entries about this module.
559 $a = new stdClass;
560 $a->type = $modulename;
561 $options['moduleview'] = array(
562 'string' => get_string('viewallmodentries', 'blog', $a),
563 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
566 // View MY entries about this module.
567 $options['moduleviewmine'] = array(
568 'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
569 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
571 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
572 // View the given users entries about this module.
573 $a = new stdClass;
574 $a->mod = $modulename;
575 $a->user = fullname($user);
576 $options['moduleviewuser'] = array(
577 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
578 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
583 if (has_capability('moodle/blog:create', $sitecontext)) {
584 // The user can blog about this module.
585 $options['moduleadd'] = array(
586 'string' => get_string('blogaboutthismodule', 'blog', $modulename),
587 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
590 // Cache the options.
591 $moduleoptions[$key] = $options;
592 // Return the options.
593 return $options;
597 * This function encapsulates all the logic behind the complex
598 * navigation, titles and headings of the blog listing page, depending
599 * on URL params. It looks at URL params and at the current context level.
600 * It builds and returns an array containing:
602 * 1. heading: The heading displayed above the blog entries
603 * 2. stradd: The text to be used as the "Add entry" link
604 * 3. strview: The text to be used as the "View entries" link
605 * 4. url: The moodle_url object used as the base for add and view links
606 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
608 * All other variables are set directly in $PAGE
610 * It uses the current URL to build these variables.
611 * A number of mutually exclusive use cases are used to structure this function.
613 * @return array
615 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
616 global $CFG, $PAGE, $DB, $USER;
618 $id = optional_param('id', null, PARAM_INT);
619 $tag = optional_param('tag', null, PARAM_NOTAGS);
620 $tagid = optional_param('tagid', $tagid, PARAM_INT);
621 $userid = optional_param('userid', $userid, PARAM_INT);
622 $modid = optional_param('modid', null, PARAM_INT);
623 $entryid = optional_param('entryid', null, PARAM_INT);
624 $groupid = optional_param('groupid', $groupid, PARAM_INT);
625 $courseid = optional_param('courseid', $courseid, PARAM_INT);
626 $search = optional_param('search', null, PARAM_RAW);
627 $action = optional_param('action', null, PARAM_ALPHA);
628 $confirm = optional_param('confirm', false, PARAM_BOOL);
630 // Ignore userid when action == add.
631 if ($action == 'add' && $userid) {
632 unset($userid);
633 $PAGE->url->remove_params(array('userid'));
634 } else if ($action == 'add' && $entryid) {
635 unset($entryid);
636 $PAGE->url->remove_params(array('entryid'));
639 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
641 $blogurl = new moodle_url('/blog/index.php');
643 $headers['stradd'] = get_string('addnewentry', 'blog');
644 $headers['strview'] = null;
646 $site = $DB->get_record('course', array('id' => SITEID));
647 $sitecontext = context_system::instance();
648 // Common Lang strings.
649 $strparticipants = get_string("participants");
650 $strblogentries = get_string("blogentries", 'blog');
652 // Prepare record objects as needed.
653 if (!empty($courseid)) {
654 $headers['filters']['course'] = $courseid;
655 $course = $DB->get_record('course', array('id' => $courseid));
658 if (!empty($userid)) {
659 $headers['filters']['user'] = $userid;
660 $user = $DB->get_record('user', array('id' => $userid));
663 if (!empty($groupid)) { // The groupid always overrides courseid.
664 $headers['filters']['group'] = $groupid;
665 $group = $DB->get_record('groups', array('id' => $groupid));
666 $course = $DB->get_record('course', array('id' => $group->courseid));
669 $PAGE->set_pagelayout('standard');
671 // The modid always overrides courseid, so the $course object may be reset here.
672 if (!empty($modid) && $CFG->useblogassociations) {
674 $headers['filters']['module'] = $modid;
675 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case.
676 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
677 $course = $DB->get_record('course', array('id' => $courseid));
678 $cm = $DB->get_record('course_modules', array('id' => $modid));
679 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
680 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
681 $a = new stdClass();
682 $a->type = get_string('modulename', $cm->modname);
683 $PAGE->set_cm($cm, $course);
684 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
685 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
688 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
689 // Note: if action is set to 'add' or 'edit', we do this at the end.
690 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
691 $PAGE->navbar->add($strblogentries, $blogurl);
692 $PAGE->set_title($site->fullname);
693 $PAGE->set_heading($site->fullname);
694 $headers['heading'] = get_string('siteblogheading', 'blog');
697 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information.
698 if (!empty($entryid)) {
699 $headers['filters']['entry'] = $entryid;
700 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
701 $user = $DB->get_record_sql($sql, array($entryid));
702 $entry = $DB->get_record('post', array('id' => $entryid));
704 $blogurl->param('userid', $user->id);
706 if (!empty($course)) {
707 $mycourseid = $course->id;
708 $blogurl->param('courseid', $mycourseid);
709 } else {
710 $mycourseid = $site->id;
712 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
714 $PAGE->navbar->add($strblogentries, $blogurl);
716 $blogurl->remove_params('userid');
717 $PAGE->navbar->add($entry->subject, $blogurl);
718 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
719 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
720 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
722 // We ignore tag and search params.
723 if (empty($action) || !$CFG->useblogassociations) {
724 $headers['url'] = $blogurl;
725 return $headers;
729 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
730 // Case 3: A user's blog entries.
732 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
733 $blogurl->param('userid', $userid);
734 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
735 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
736 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
737 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
739 } else if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
740 // Case 4: No blog associations, no userid.
742 $PAGE->set_title($site->fullname);
743 $PAGE->set_heading($site->fullname);
744 $headers['heading'] = get_string('siteblogheading', 'blog');
745 } else if (!empty($userid) && !empty($modid) && empty($entryid)) {
746 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored).
748 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
749 $blogurl->param('userid', $userid);
750 $blogurl->param('modid', $modid);
752 // Course module navigation is handled by build_navigation as the second param.
753 $headers['cm'] = $cm;
754 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
755 $PAGE->navbar->add($strblogentries, $blogurl);
757 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
758 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
760 $a = new stdClass();
761 $a->user = fullname($user);
762 $a->mod = $cm->name;
763 $a->type = get_string('modulename', $cm->modname);
764 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
765 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
766 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
767 } else if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
768 // Case 6: Blog entries associated with a course by a specific user.
770 $blogurl->param('userid', $userid);
771 $blogurl->param('courseid', $courseid);
773 $PAGE->set_title($course->fullname);
774 $PAGE->set_heading($course->fullname);
776 $a = new stdClass();
777 $a->user = fullname($user);
778 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
779 $a->type = get_string('course');
780 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
781 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
782 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
784 // Remove the userid from the URL to inform the blog_menu block correctly.
785 $blogurl->remove_params(array('userid'));
786 } else if (!empty($groupid) && empty($modid) && empty($entryid)) {
787 // Case 7: Blog entries by members of a group, associated with that group's course.
789 $blogurl->param('courseid', $course->id);
791 $PAGE->navbar->add($strblogentries, $blogurl);
792 $blogurl->remove_params(array('courseid'));
793 $blogurl->param('groupid', $groupid);
794 $PAGE->navbar->add($group->name, $blogurl);
796 $PAGE->set_title($course->fullname);
797 $PAGE->set_heading($course->fullname);
799 $a = new stdClass();
800 $a->group = $group->name;
801 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
802 $a->type = get_string('course');
803 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
804 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
805 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
806 } else if (!empty($groupid) && !empty($modid) && empty($entryid)) {
807 // Case 8: Blog entries by members of a group, associated with an activity in that course.
809 $headers['cm'] = $cm;
810 $blogurl->param('modid', $modid);
811 $PAGE->navbar->add($strblogentries, $blogurl);
813 $blogurl->param('groupid', $groupid);
814 $PAGE->navbar->add($group->name, $blogurl);
816 $PAGE->set_title($course->fullname);
817 $PAGE->set_heading($course->fullname);
819 $a = new stdClass();
820 $a->group = $group->name;
821 $a->mod = $cm->name;
822 $a->type = get_string('modulename', $cm->modname);
823 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
824 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
825 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
827 } else if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
828 // Case 9: All blog entries associated with an activity.
830 $PAGE->set_cm($cm, $course);
831 $blogurl->param('modid', $modid);
832 $PAGE->navbar->add($strblogentries, $blogurl);
833 $PAGE->set_title($course->fullname);
834 $PAGE->set_heading($course->fullname);
835 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
836 $a = new stdClass();
837 $a->type = get_string('modulename', $cm->modname);
838 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
839 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
840 } else if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
841 // Case 10: All blog entries associated with a course.
843 $blogurl->param('courseid', $courseid);
844 $PAGE->navbar->add($strblogentries, $blogurl);
845 $PAGE->set_title($course->fullname);
846 $PAGE->set_heading($course->fullname);
847 $a = new stdClass();
848 $a->type = get_string('course');
849 $headers['heading'] = get_string('blogentriesabout',
850 'blog',
851 format_string($course->fullname,
852 true,
853 array('context' => context_course::instance($course->id))));
854 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
855 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
856 $blogurl->remove_params(array('userid'));
859 if (!in_array($action, array('edit', 'add'))) {
860 // Append Tag info.
861 if (!empty($tagid)) {
862 $headers['filters']['tag'] = $tagid;
863 $blogurl->param('tagid', $tagid);
864 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
865 $PAGE->navbar->add($tagrec->name, $blogurl);
866 } else if (!empty($tag)) {
867 if ($tagrec = $DB->get_record('tag', array('name' => $tag))) {
868 $tagid = $tagrec->id;
869 $headers['filters']['tag'] = $tagid;
870 $blogurl->param('tag', $tag);
871 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
875 // Append Search info.
876 if (!empty($search)) {
877 $headers['filters']['search'] = $search;
878 $blogurl->param('search', $search);
879 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
883 // Append edit mode info.
884 if (!empty($action) && $action == 'add') {
886 } else if (!empty($action) && $action == 'edit') {
887 $PAGE->navbar->add(get_string('editentry', 'blog'));
890 if (empty($headers['url'])) {
891 $headers['url'] = $blogurl;
893 return $headers;
897 * Shortcut function for getting a count of blog entries associated with a course or a module
898 * @param int $courseid The ID of the course
899 * @param int $cmid The ID of the course_modules
900 * @return string The number of associated entries
902 function blog_get_associated_count($courseid, $cmid=null) {
903 global $DB;
904 $context = context_course::instance($courseid);
905 if ($cmid) {
906 $context = context_module::instance($cmid);
908 return $DB->count_records('blog_association', array('contextid' => $context->id));
912 * Running addtional permission check on plugin, for example, plugins
913 * may have switch to turn on/off comments option, this callback will
914 * affect UI display, not like pluginname_comment_validate only throw
915 * exceptions.
916 * blog_comment_validate will be called before viewing/adding/deleting
917 * comment, so don't repeat checks.
918 * Capability check has been done in comment->check_permissions(), we
919 * don't need to do it again here.
921 * @package core_blog
922 * @category comment
924 * @param stdClass $comment_param {
925 * context => context the context object
926 * courseid => int course id
927 * cm => stdClass course module object
928 * commentarea => string comment area
929 * itemid => int itemid
931 * @return array
933 function blog_comment_permissions($comment_param) {
934 global $DB;
936 // If blog is public and current user is guest, then don't let him post comments.
937 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), 'publishstate', MUST_EXIST);
939 if ($blogentry->publishstate != 'public') {
940 if (!isloggedin() || isguestuser()) {
941 return array('post' => false, 'view' => true);
944 return array('post' => true, 'view' => true);
948 * Validate comment parameter before perform other comments actions
950 * @package core_blog
951 * @category comment
953 * @param stdClass $comment {
954 * context => context the context object
955 * courseid => int course id
956 * cm => stdClass course module object
957 * commentarea => string comment area
958 * itemid => int itemid
960 * @return boolean
962 function blog_comment_validate($comment_param) {
963 global $CFG, $DB, $USER;
965 // Check if blogs are enabled user can comment.
966 if (empty($CFG->enableblogs) || empty($CFG->blogusecomments)) {
967 throw new comment_exception('nopermissiontocomment');
970 // Validate comment area.
971 if ($comment_param->commentarea != 'format_blog') {
972 throw new comment_exception('invalidcommentarea');
975 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), '*', MUST_EXIST);
977 // Validation for comment deletion.
978 if (!empty($comment_param->commentid)) {
979 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
980 if ($record->commentarea != 'format_blog') {
981 throw new comment_exception('invalidcommentarea');
983 if ($record->contextid != $comment_param->context->id) {
984 throw new comment_exception('invalidcontext');
986 if ($record->itemid != $comment_param->itemid) {
987 throw new comment_exception('invalidcommentitemid');
989 } else {
990 throw new comment_exception('invalidcommentid');
994 // Validate if user has blog view permission.
995 $sitecontext = context_system::instance();
996 return has_capability('moodle/blog:view', $sitecontext) &&
997 blog_user_can_view_user_entry($blogentry->userid, $blogentry);
1001 * Return a list of page types
1002 * @param string $pagetype current page type
1003 * @param stdClass $parentcontext Block's parent context
1004 * @param stdClass $currentcontext Current context of block
1006 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1007 return array(
1008 '*'=>get_string('page-x', 'pagetype'),
1009 'blog-*'=>get_string('page-blog-x', 'blog'),
1010 'blog-index'=>get_string('page-blog-index', 'blog'),
1011 'blog-edit'=>get_string('page-blog-edit', 'blog')
1016 * Add nodes to myprofile page.
1018 * @param \core_user\output\myprofile\tree $tree Tree object
1019 * @param stdClass $user user object
1020 * @param bool $iscurrentuser
1021 * @param stdClass $course Course object
1023 * @return bool
1025 function core_blog_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
1026 global $CFG;
1027 if (!blog_is_enabled_for_user() || isguestuser($user)) {
1028 // The guest user cannot post, so it is not possible to view any posts.
1029 // Also blogs might be disabled.
1030 // May as well just bail aggressively here.
1031 return true;
1033 if (!blog_user_can_view_user_entry($user->id)) {
1034 return true;
1036 $url = new moodle_url("/blog/index.php", array('userid' => $user->id));
1037 if (!empty($course)) {
1038 $url->param('courseid', $course->id);
1040 if ($iscurrentuser) {
1041 $title = get_string('blogentries', 'core_blog');
1042 } else {
1043 $title = get_string('myprofileuserblogs', 'core_blog');
1045 $blognode = new core_user\output\myprofile\node('miscellaneous', 'blogs', $title, null, $url);
1046 $tree->add_node($blognode);
1047 return true;