Merge branch 'wip-MDL-39456-m24' of git://github.com/samhemelryk/moodle into MOODLE_2...
[moodle.git] / blog / lib.php
blob21621b6a4c3d32d7771a40f5cc7dc6b3ddc628ae
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 = context_system::instance();
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->enableblogs)) {
68 return false; // Blog system disabled.
71 if (isloggedin() && $USER->id == $targetuserid) {
72 return true; // Can view own entries in any case.
75 $sitecontext = context_system::instance();
76 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
77 return true; // Can manage all entries.
80 // If blog is in draft state, then make sure user have proper capability.
81 if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
82 return false; // Can not view draft of others.
85 // If blog entry is not public, make sure user is logged in.
86 if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
87 return false;
90 // If blogentry is not passed or all above checks pass, then check capability based on system config.
91 switch ($CFG->bloglevel) {
92 case BLOG_GLOBAL_LEVEL:
93 return true;
94 break;
96 case BLOG_SITE_LEVEL:
97 if (isloggedin()) { // Not logged in viewers forbidden.
98 return true;
100 return false;
101 break;
103 case BLOG_USER_LEVEL:
104 default:
105 // If user is viewing other user blog, then user should have user:readuserblogs capability.
106 $personalcontext = context_user::instance($targetuserid);
107 return has_capability('moodle/user:readuserblogs', $personalcontext);
108 break;
114 * remove all associations for the blog entries of a particular user
115 * @param int userid - id of user whose blog associations will be deleted
117 function blog_remove_associations_for_user($userid) {
118 global $DB;
119 throw new coding_exception('function blog_remove_associations_for_user() is not finished');
121 $blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
122 foreach ($blogentries as $entry) {
123 if (blog_user_can_edit_entry($entry)) {
124 blog_remove_associations_for_entry($entry->id);
131 * remove all associations for the blog entries of a particular course
132 * @param int courseid - id of user whose blog associations will be deleted
134 function blog_remove_associations_for_course($courseid) {
135 global $DB;
136 $context = context_course::instance($courseid);
137 $DB->delete_records('blog_association', array('contextid' => $context->id));
141 * Given a record in the {blog_external} table, checks the blog's URL
142 * for new entries not yet copied into Moodle.
143 * Also attempts to identify and remove deleted blog entries
145 * @param object $externalblog
146 * @return boolean False if the Feed is invalid
148 function blog_sync_external_entries($externalblog) {
149 global $CFG, $DB;
150 require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
152 $rssfile = new moodle_simplepie_file($externalblog->url);
153 $filetest = new SimplePie_Locator($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 = 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 if (textlib::strlen($newentry->uniquehash) > 255) {
243 // The URL for this item is too long for the field. Rather than add
244 // the entry without the link we will skip straight over it.
245 // RSS spec says recommended length 500, we use 255.
246 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
247 continue;
250 if ($postid === false) {
251 $id = $DB->insert_record('post', $newentry);
253 // Set tags
254 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
255 tag_set('post', $id, $tags);
257 } else {
258 $newentry->id = $postid;
259 $DB->update_record('post', $newentry);
263 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
264 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
265 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
266 $sql = "SELECT id, uniquehash
267 FROM {post}
268 WHERE module = 'blog_external'
269 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
270 AND created > :ts";
271 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
273 $todelete = array();
274 foreach($dbposts as $dbpost) {
275 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
276 $todelete[] = $dbpost->id;
279 $DB->delete_records_list('post', 'id', $todelete);
281 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
285 * Given an external blog object, deletes all related blog entries from the post table.
286 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
287 * @param object $externablog
289 function blog_delete_external_entries($externalblog) {
290 global $DB;
291 require_capability('moodle/blog:manageexternal', context_system::instance());
292 $DB->delete_records_select('post',
293 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
294 array($externalblog->id));
298 * Returns a URL based on the context of the current page.
299 * This URL points to blog/index.php and includes filter parameters appropriate for the current page.
301 * @param stdclass $context
302 * @return string
304 function blog_get_context_url($context=null) {
305 global $CFG;
307 $viewblogentriesurl = new moodle_url('/blog/index.php');
309 if (empty($context)) {
310 global $PAGE;
311 $context = $PAGE->context;
314 // Change contextlevel to SYSTEM if viewing the site course
315 if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
316 $context = context_system::instance();
319 $filterparam = '';
320 $strlevel = '';
322 switch ($context->contextlevel) {
323 case CONTEXT_SYSTEM:
324 case CONTEXT_BLOCK:
325 case CONTEXT_COURSECAT:
326 break;
327 case CONTEXT_COURSE:
328 $filterparam = 'courseid';
329 $strlevel = get_string('course');
330 break;
331 case CONTEXT_MODULE:
332 $filterparam = 'modid';
333 $strlevel = print_context_name($context);
334 break;
335 case CONTEXT_USER:
336 $filterparam = 'userid';
337 $strlevel = get_string('user');
338 break;
341 if (!empty($filterparam)) {
342 $viewblogentriesurl->param($filterparam, $context->instanceid);
345 return $viewblogentriesurl;
349 * This function checks that blogs are enabled, and that the user can see blogs at all
350 * @return bool
352 function blog_is_enabled_for_user() {
353 global $CFG;
354 return (!empty($CFG->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
358 * This function gets all of the options available for the current user in respect
359 * to blogs.
361 * It loads the following if applicable:
362 * - Module options {@see blog_get_options_for_module}
363 * - Course options {@see blog_get_options_for_course}
364 * - User specific options {@see blog_get_options_for_user}
365 * - General options (BLOG_LEVEL_GLOBAL)
367 * @param moodle_page $page The page to load for (normally $PAGE)
368 * @param stdClass $userid Load for a specific user
369 * @return array An array of options organised by type.
371 function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
372 global $CFG, $DB, $USER;
374 $options = array();
376 // If blogs are enabled and the user is logged in and not a guest
377 if (blog_is_enabled_for_user()) {
378 // If the context is the user then assume we want to load for the users context
379 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
380 $userid = $page->context->instanceid;
382 // Check the userid var
383 if (!is_null($userid) && $userid!==$USER->id) {
384 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
385 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
386 } else {
387 $user = null;
390 if ($CFG->useblogassociations && $page->cm !== null) {
391 // Load for the module associated with the page
392 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
393 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
394 // Load the options for the course associated with the page
395 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
398 // Get the options for the user
399 if ($user !== null and !isguestuser($user)) {
400 // Load for the requested user
401 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
403 // Load for the current user
404 if (isloggedin() and !isguestuser()) {
405 $options[CONTEXT_USER] = blog_get_options_for_user();
409 // If blog level is global then display a link to view all site entries
410 if (!empty($CFG->enableblogs) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', context_system::instance())) {
411 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
412 'string' => get_string('viewsiteentries', 'blog'),
413 'link' => new moodle_url('/blog/index.php')
417 // Return the options
418 return $options;
422 * Get all of the blog options that relate to the passed user.
424 * If no user is passed the current user is assumed.
426 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
427 * @param stdClass $user
428 * @return array The array of options for the requested user
430 function blog_get_options_for_user(stdClass $user=null) {
431 global $CFG, $USER;
432 // Cache
433 static $useroptions = array();
435 $options = array();
436 // Blogs must be enabled and the user must be logged in
437 if (!blog_is_enabled_for_user()) {
438 return $options;
441 // Sort out the user var
442 if ($user === null || $user->id == $USER->id) {
443 $user = $USER;
444 $iscurrentuser = true;
445 } else {
446 $iscurrentuser = false;
449 // If we've already generated serve from the cache
450 if (array_key_exists($user->id, $useroptions)) {
451 return $useroptions[$user->id];
454 $sitecontext = context_system::instance();
455 $canview = has_capability('moodle/blog:view', $sitecontext);
457 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
458 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
459 $options['userentries'] = array(
460 'string' => get_string('viewuserentries', 'blog', fullname($user)),
461 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
463 } else {
464 // It's the current user
465 if ($canview) {
466 // We can view our own blogs .... BIG surprise
467 $options['view'] = array(
468 'string' => get_string('viewallmyentries', 'blog'),
469 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
472 if (has_capability('moodle/blog:create', $sitecontext)) {
473 // We can add to our own blog
474 $options['add'] = array(
475 'string' => get_string('addnewentry', 'blog'),
476 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
480 if ($canview && $CFG->enablerssfeeds) {
481 $options['rss'] = array(
482 'string' => get_string('rssfeed', 'blog'),
483 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
487 // Cache the options
488 $useroptions[$user->id] = $options;
489 // Return the options
490 return $options;
494 * Get the blog options that relate to the given course for the given user.
496 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
497 * @param stdClass $course The course to load options for
498 * @param stdClass $user The user to load options for null == current user
499 * @return array The array of options
501 function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
502 global $CFG, $USER;
503 // Cache
504 static $courseoptions = array();
506 $options = array();
508 // User must be logged in and blogs must be enabled
509 if (!blog_is_enabled_for_user()) {
510 return $options;
513 // Check that the user can associate with the course
514 $sitecontext = context_system::instance();
515 $coursecontext = context_course::instance($course->id);
516 if (!has_capability('moodle/blog:associatecourse', $coursecontext)) {
517 return $options;
519 // Generate the cache key
520 $key = $course->id.':';
521 if (!empty($user)) {
522 $key .= $user->id;
523 } else {
524 $key .= $USER->id;
526 // Serve from the cache if we've already generated for this course
527 if (array_key_exists($key, $courseoptions)) {
528 return $courseoptions[$key];
531 $canparticipate = (is_enrolled($coursecontext) or is_viewing($coursecontext));
533 if (has_capability('moodle/blog:view', $coursecontext)) {
534 // We can view!
535 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
536 // View entries about this course
537 $options['courseview'] = array(
538 'string' => get_string('viewcourseblogs', 'blog'),
539 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id))
542 // View MY entries about this course
543 $options['courseviewmine'] = array(
544 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
545 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$USER->id))
547 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
548 // View the provided users entries about this course
549 $options['courseviewuser'] = array(
550 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
551 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$user->id))
556 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
557 // We can blog about this course
558 $options['courseadd'] = array(
559 'string' => get_string('blogaboutthiscourse', 'blog'),
560 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'courseid'=>$course->id))
565 // Cache the options for this course
566 $courseoptions[$key] = $options;
567 // Return the options
568 return $options;
572 * Get the blog options relating to the given module for the given user
574 * @staticvar array $moduleoptions Cache
575 * @param stdClass|cm_info $module The module to get options for
576 * @param stdClass $user The user to get options for null == currentuser
577 * @return array
579 function blog_get_options_for_module($module, $user=null) {
580 global $CFG, $USER;
581 // Cache
582 static $moduleoptions = array();
584 $options = array();
585 // User must be logged in, blogs must be enabled
586 if (!blog_is_enabled_for_user()) {
587 return $options;
590 // Check the user can associate with the module
591 $modcontext = context_module::instance($module->id);
592 $sitecontext = context_system::instance();
593 if (!has_capability('moodle/blog:associatemodule', $modcontext)) {
594 return $options;
597 // Generate the cache key
598 $key = $module->id.':';
599 if (!empty($user)) {
600 $key .= $user->id;
601 } else {
602 $key .= $USER->id;
604 if (array_key_exists($key, $moduleoptions)) {
605 // Serve from the cache so we don't have to regenerate
606 return $moduleoptions[$key];
609 $canparticipate = (is_enrolled($modcontext) or is_viewing($modcontext));
611 if (has_capability('moodle/blog:view', $modcontext)) {
612 // Save correct module name for later usage.
613 $modulename = get_string('modulename', $module->modname);
615 // We can view!
616 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
617 // View all entries about this module
618 $a = new stdClass;
619 $a->type = $modulename;
620 $options['moduleview'] = array(
621 'string' => get_string('viewallmodentries', 'blog', $a),
622 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
625 // View MY entries about this module
626 $options['moduleviewmine'] = array(
627 'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
628 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
630 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
631 // View the given users entries about this module
632 $a = new stdClass;
633 $a->mod = $modulename;
634 $a->user = fullname($user);
635 $options['moduleviewuser'] = array(
636 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
637 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
642 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
643 // The user can blog about this module
644 $options['moduleadd'] = array(
645 'string' => get_string('blogaboutthismodule', 'blog', $modulename),
646 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
649 // Cache the options
650 $moduleoptions[$key] = $options;
651 // Return the options
652 return $options;
656 * This function encapsulates all the logic behind the complex
657 * navigation, titles and headings of the blog listing page, depending
658 * on URL params. It looks at URL params and at the current context level.
659 * It builds and returns an array containing:
661 * 1. heading: The heading displayed above the blog entries
662 * 2. stradd: The text to be used as the "Add entry" link
663 * 3. strview: The text to be used as the "View entries" link
664 * 4. url: The moodle_url object used as the base for add and view links
665 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
667 * All other variables are set directly in $PAGE
669 * It uses the current URL to build these variables.
670 * A number of mutually exclusive use cases are used to structure this function.
672 * @return array
674 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
675 global $CFG, $PAGE, $DB, $USER;
677 $id = optional_param('id', null, PARAM_INT);
678 $tag = optional_param('tag', null, PARAM_NOTAGS);
679 $tagid = optional_param('tagid', $tagid, PARAM_INT);
680 $userid = optional_param('userid', $userid, PARAM_INT);
681 $modid = optional_param('modid', null, PARAM_INT);
682 $entryid = optional_param('entryid', null, PARAM_INT);
683 $groupid = optional_param('groupid', $groupid, PARAM_INT);
684 $courseid = optional_param('courseid', $courseid, PARAM_INT);
685 $search = optional_param('search', null, PARAM_RAW);
686 $action = optional_param('action', null, PARAM_ALPHA);
687 $confirm = optional_param('confirm', false, PARAM_BOOL);
689 // Ignore userid when action == add
690 if ($action == 'add' && $userid) {
691 unset($userid);
692 $PAGE->url->remove_params(array('userid'));
693 } else if ($action == 'add' && $entryid) {
694 unset($entryid);
695 $PAGE->url->remove_params(array('entryid'));
698 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
700 $blogurl = new moodle_url('/blog/index.php');
702 // If the title is not yet set, it's likely that the context isn't set either, so skip this part
703 $pagetitle = $PAGE->title;
704 if (!empty($pagetitle)) {
705 $contexturl = blog_get_context_url();
707 // Look at the context URL, it may have additional params that are not in the current URL
708 if (!$blogurl->compare($contexturl)) {
709 $blogurl = $contexturl;
710 if (empty($courseid)) {
711 $courseid = $blogurl->param('courseid');
713 if (empty($modid)) {
714 $modid = $blogurl->param('modid');
719 $headers['stradd'] = get_string('addnewentry', 'blog');
720 $headers['strview'] = null;
722 $site = $DB->get_record('course', array('id' => SITEID));
723 $sitecontext = context_system::instance();
724 // Common Lang strings
725 $strparticipants = get_string("participants");
726 $strblogentries = get_string("blogentries", 'blog');
728 // Prepare record objects as needed
729 if (!empty($courseid)) {
730 $headers['filters']['course'] = $courseid;
731 $course = $DB->get_record('course', array('id' => $courseid));
734 if (!empty($userid)) {
735 $headers['filters']['user'] = $userid;
736 $user = $DB->get_record('user', array('id' => $userid));
739 if (!empty($groupid)) { // groupid always overrides courseid
740 $headers['filters']['group'] = $groupid;
741 $group = $DB->get_record('groups', array('id' => $groupid));
742 $course = $DB->get_record('course', array('id' => $group->courseid));
745 $PAGE->set_pagelayout('standard');
747 // modid always overrides courseid, so the $course object may be reset here
748 if (!empty($modid) && $CFG->useblogassociations) {
750 $headers['filters']['module'] = $modid;
751 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
752 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
753 $course = $DB->get_record('course', array('id' => $courseid));
754 $cm = $DB->get_record('course_modules', array('id' => $modid));
755 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
756 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
757 $a = new stdClass();
758 $a->type = get_string('modulename', $cm->modname);
759 $PAGE->set_cm($cm, $course);
760 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
761 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
764 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
765 // Note: if action is set to 'add' or 'edit', we do this at the end
766 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
767 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
768 $PAGE->navbar->add($strblogentries, $blogurl);
769 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
770 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
771 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
772 // $headers['strview'] = get_string('viewsiteentries', 'blog');
775 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
776 if (!empty($entryid)) {
777 $headers['filters']['entry'] = $entryid;
778 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
779 $user = $DB->get_record_sql($sql, array($entryid));
780 $entry = $DB->get_record('post', array('id' => $entryid));
782 $blogurl->param('userid', $user->id);
784 if (!empty($course)) {
785 $mycourseid = $course->id;
786 $blogurl->param('courseid', $mycourseid);
787 } else {
788 $mycourseid = $site->id;
790 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
792 $PAGE->navbar->add($strblogentries, $blogurl);
794 $blogurl->remove_params('userid');
795 $PAGE->navbar->add($entry->subject, $blogurl);
796 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
797 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
798 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
800 // We ignore tag and search params
801 if (empty($action) || !$CFG->useblogassociations) {
802 $headers['url'] = $blogurl;
803 return $headers;
807 // Case 3: A user's blog entries
808 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
809 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
810 $blogurl->param('userid', $userid);
811 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
812 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
813 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
814 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
816 } else
818 // Case 4: No blog associations, no userid
819 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
820 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
821 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
822 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
823 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
824 } else
826 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
827 if (!empty($userid) && !empty($modid) && empty($entryid)) {
828 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
829 $blogurl->param('userid', $userid);
830 $blogurl->param('modid', $modid);
832 // Course module navigation is handled by build_navigation as the second param
833 $headers['cm'] = $cm;
834 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
835 $PAGE->navbar->add($strblogentries, $blogurl);
837 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
838 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
840 $a = new stdClass();
841 $a->user = fullname($user);
842 $a->mod = $cm->name;
843 $a->type = get_string('modulename', $cm->modname);
844 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
845 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
846 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
847 } else
849 // Case 6: Blog entries associated with a course by a specific user
850 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
851 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
852 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
853 $blogurl->param('userid', $userid);
854 $blogurl->param('courseid', $courseid);
856 $PAGE->navbar->add($strblogentries, $blogurl);
858 $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
859 $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
861 $a = new stdClass();
862 $a->user = fullname($user);
863 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
864 $a->type = get_string('course');
865 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
866 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
867 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
869 // Remove the userid from the URL to inform the blog_menu block correctly
870 $blogurl->remove_params(array('userid'));
871 } else
873 // Case 7: Blog entries by members of a group, associated with that group's course
874 if (!empty($groupid) && empty($modid) && empty($entryid)) {
875 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
876 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
877 $blogurl->param('courseid', $course->id);
879 $PAGE->navbar->add($strblogentries, $blogurl);
880 $blogurl->remove_params(array('courseid'));
881 $blogurl->param('groupid', $groupid);
882 $PAGE->navbar->add($group->name, $blogurl);
884 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
885 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
887 $a = new stdClass();
888 $a->group = $group->name;
889 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
890 $a->type = get_string('course');
891 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
892 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
893 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
894 } else
896 // Case 8: Blog entries by members of a group, associated with an activity in that course
897 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
898 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
899 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
900 $headers['cm'] = $cm;
901 $blogurl->param('modid', $modid);
902 $PAGE->navbar->add($strblogentries, $blogurl);
904 $blogurl->param('groupid', $groupid);
905 $PAGE->navbar->add($group->name, $blogurl);
907 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
908 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
910 $a = new stdClass();
911 $a->group = $group->name;
912 $a->mod = $cm->name;
913 $a->type = get_string('modulename', $cm->modname);
914 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
915 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
916 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
918 } else
920 // Case 9: All blog entries associated with an activity
921 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
922 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
923 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
924 $PAGE->set_cm($cm, $course);
925 $blogurl->param('modid', $modid);
926 $PAGE->navbar->add($strblogentries, $blogurl);
927 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
928 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
929 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
930 $a = new stdClass();
931 $a->type = get_string('modulename', $cm->modname);
932 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
933 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
934 } else
936 // Case 10: All blog entries associated with a course
937 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
938 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
939 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
940 $blogurl->param('courseid', $courseid);
941 $PAGE->navbar->add($strblogentries, $blogurl);
942 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
943 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
944 $a = new stdClass();
945 $a->type = get_string('course');
946 $headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
947 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
948 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
949 $blogurl->remove_params(array('userid'));
952 if (!in_array($action, array('edit', 'add'))) {
953 // Append Tag info
954 if (!empty($tagid)) {
955 $headers['filters']['tag'] = $tagid;
956 $blogurl->param('tagid', $tagid);
957 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
958 $PAGE->navbar->add($tagrec->name, $blogurl);
959 } elseif (!empty($tag)) {
960 $blogurl->param('tag', $tag);
961 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
964 // Append Search info
965 if (!empty($search)) {
966 $headers['filters']['search'] = $search;
967 $blogurl->param('search', $search);
968 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
972 // Append edit mode info
973 if (!empty($action) && $action == 'add') {
975 } else if (!empty($action) && $action == 'edit') {
976 $PAGE->navbar->add(get_string('editentry', 'blog'));
979 if (empty($headers['url'])) {
980 $headers['url'] = $blogurl;
982 return $headers;
986 * Shortcut function for getting a count of blog entries associated with a course or a module
987 * @param int $courseid The ID of the course
988 * @param int $cmid The ID of the course_modules
989 * @return string The number of associated entries
991 function blog_get_associated_count($courseid, $cmid=null) {
992 global $DB;
993 $context = context_course::instance($courseid);
994 if ($cmid) {
995 $context = context_module::instance($cmid);
997 return $DB->count_records('blog_association', array('contextid' => $context->id));
1001 * Running addtional permission check on plugin, for example, plugins
1002 * may have switch to turn on/off comments option, this callback will
1003 * affect UI display, not like pluginname_comment_validate only throw
1004 * exceptions.
1005 * blog_comment_validate will be called before viewing/adding/deleting
1006 * comment, so don't repeat checks.
1007 * Capability check has been done in comment->check_permissions(), we
1008 * don't need to do it again here.
1010 * @package core_blog
1011 * @category comment
1013 * @param stdClass $comment_param {
1014 * context => context the context object
1015 * courseid => int course id
1016 * cm => stdClass course module object
1017 * commentarea => string comment area
1018 * itemid => int itemid
1020 * @return array
1022 function blog_comment_permissions($comment_param) {
1023 global $DB;
1025 // If blog is public and current user is guest, then don't let him post comments.
1026 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), 'publishstate', MUST_EXIST);
1028 if ($blogentry->publishstate != 'public') {
1029 if (!isloggedin() || isguestuser()) {
1030 return array('post' => false, 'view' => true);
1033 return array('post' => true, 'view' => true);
1037 * Validate comment parameter before perform other comments actions
1039 * @package core_blog
1040 * @category comment
1042 * @param stdClass $comment {
1043 * context => context the context object
1044 * courseid => int course id
1045 * cm => stdClass course module object
1046 * commentarea => string comment area
1047 * itemid => int itemid
1049 * @return boolean
1051 function blog_comment_validate($comment_param) {
1052 global $CFG, $DB, $USER;
1054 // Check if blogs are enabled user can comment.
1055 if (empty($CFG->enableblogs) || empty($CFG->blogusecomments)) {
1056 throw new comment_exception('nopermissiontocomment');
1059 // Validate comment area.
1060 if ($comment_param->commentarea != 'format_blog') {
1061 throw new comment_exception('invalidcommentarea');
1064 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), '*', MUST_EXIST);
1066 // Validation for comment deletion.
1067 if (!empty($comment_param->commentid)) {
1068 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
1069 if ($record->commentarea != 'format_blog') {
1070 throw new comment_exception('invalidcommentarea');
1072 if ($record->contextid != $comment_param->context->id) {
1073 throw new comment_exception('invalidcontext');
1075 if ($record->itemid != $comment_param->itemid) {
1076 throw new comment_exception('invalidcommentitemid');
1078 } else {
1079 throw new comment_exception('invalidcommentid');
1083 // Validate if user has blog view permission.
1084 $sitecontext = context_system::instance();
1085 return has_capability('moodle/blog:view', $sitecontext) &&
1086 blog_user_can_view_user_entry($blogentry->userid, $blogentry);
1090 * Return a list of page types
1091 * @param string $pagetype current page type
1092 * @param stdClass $parentcontext Block's parent context
1093 * @param stdClass $currentcontext Current context of block
1095 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1096 return array(
1097 '*'=>get_string('page-x', 'pagetype'),
1098 'blog-*'=>get_string('page-blog-x', 'blog'),
1099 'blog-index'=>get_string('page-blog-index', 'blog'),
1100 'blog-edit'=>get_string('page-blog-edit', 'blog')