MDL-44616 behat: Adding steps to test MDLQA-1709 and MDLQA-62
[moodle.git] / blog / lib.php
blob9190e46588134c6bea667f4c5c18cd325efd7e99
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 $rss = new moodle_simplepie();
153 $rssfile = $rss->registry->create('File', array($externalblog->url));
154 $filetest = $rss->registry->create('Locator', array($rssfile));
156 if (!$filetest->is_feed($rssfile)) {
157 $externalblog->failedlastsync = 1;
158 $DB->update_record('blog_external', $externalblog);
159 return false;
160 } else if (!empty($externalblog->failedlastsync)) {
161 $externalblog->failedlastsync = 0;
162 $DB->update_record('blog_external', $externalblog);
165 $rss->set_feed_url($externalblog->url);
166 $rss->init();
168 if (empty($rss->data)) {
169 return null;
171 //used to identify blog posts that have been deleted from the source feed
172 $oldesttimestamp = null;
173 $uniquehashes = array();
175 foreach ($rss->get_items() as $entry) {
176 // If filtertags are defined, use them to filter the entries by RSS category
177 if (!empty($externalblog->filtertags)) {
178 $containsfiltertag = false;
179 $categories = $entry->get_categories();
180 $filtertags = explode(',', $externalblog->filtertags);
181 $filtertags = array_map('trim', $filtertags);
182 $filtertags = array_map('strtolower', $filtertags);
184 foreach ($categories as $category) {
185 if (in_array(trim(strtolower($category->term)), $filtertags)) {
186 $containsfiltertag = true;
190 if (!$containsfiltertag) {
191 continue;
195 $uniquehashes[] = $entry->get_permalink();
197 $newentry = new stdClass();
198 $newentry->userid = $externalblog->userid;
199 $newentry->module = 'blog_external';
200 $newentry->content = $externalblog->id;
201 $newentry->uniquehash = $entry->get_permalink();
202 $newentry->publishstate = 'site';
203 $newentry->format = FORMAT_HTML;
204 // Clean subject of html, just in case
205 $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
206 // Observe 128 max chars in DB
207 // TODO: +1 to raise this to 255
208 if (core_text::strlen($newentry->subject) > 128) {
209 $newentry->subject = core_text::substr($newentry->subject, 0, 125) . '...';
211 $newentry->summary = $entry->get_description();
213 //used to decide whether to insert or update
214 //uses enty permalink plus creation date if available
215 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
217 //our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
218 $entrydate = $entry->get_date('U');
219 if (!empty($entrydate)) {
220 $existingpostconditions['created'] = $entrydate;
223 //the post ID or false if post not found in DB
224 $postid = $DB->get_field('post', 'id', $existingpostconditions);
226 $timestamp = null;
227 if (empty($entrydate)) {
228 $timestamp = time();
229 } else {
230 $timestamp = $entrydate;
233 //only set created if its a new post so we retain the original creation timestamp if the post is edited
234 if ($postid === false) {
235 $newentry->created = $timestamp;
237 $newentry->lastmodified = $timestamp;
239 if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
240 //found an older post
241 $oldesttimestamp = $timestamp;
244 if (core_text::strlen($newentry->uniquehash) > 255) {
245 // The URL for this item is too long for the field. Rather than add
246 // the entry without the link we will skip straight over it.
247 // RSS spec says recommended length 500, we use 255.
248 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
249 continue;
252 if ($postid === false) {
253 $id = $DB->insert_record('post', $newentry);
255 // Set tags
256 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
257 tag_set('post', $id, $tags, 'core', context_user::instance($externalblog->userid)->id);
259 } else {
260 $newentry->id = $postid;
261 $DB->update_record('post', $newentry);
265 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
266 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
267 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
268 $sql = "SELECT id, uniquehash
269 FROM {post}
270 WHERE module = 'blog_external'
271 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
272 AND created > :ts";
273 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
275 $todelete = array();
276 foreach($dbposts as $dbpost) {
277 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
278 $todelete[] = $dbpost->id;
281 $DB->delete_records_list('post', 'id', $todelete);
283 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
287 * Given an external blog object, deletes all related blog entries from the post table.
288 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
289 * @param object $externablog
291 function blog_delete_external_entries($externalblog) {
292 global $DB;
293 require_capability('moodle/blog:manageexternal', context_system::instance());
294 $DB->delete_records_select('post',
295 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
296 array($externalblog->id));
300 * This function checks that blogs are enabled, and that the user can see blogs at all
301 * @return bool
303 function blog_is_enabled_for_user() {
304 global $CFG;
305 return (!empty($CFG->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
309 * This function gets all of the options available for the current user in respect
310 * to blogs.
312 * It loads the following if applicable:
313 * - Module options {@see blog_get_options_for_module}
314 * - Course options {@see blog_get_options_for_course}
315 * - User specific options {@see blog_get_options_for_user}
316 * - General options (BLOG_LEVEL_GLOBAL)
318 * @param moodle_page $page The page to load for (normally $PAGE)
319 * @param stdClass $userid Load for a specific user
320 * @return array An array of options organised by type.
322 function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
323 global $CFG, $DB, $USER;
325 $options = array();
327 // If blogs are enabled and the user is logged in and not a guest
328 if (blog_is_enabled_for_user()) {
329 // If the context is the user then assume we want to load for the users context
330 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
331 $userid = $page->context->instanceid;
333 // Check the userid var
334 if (!is_null($userid) && $userid!==$USER->id) {
335 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
336 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
337 } else {
338 $user = null;
341 if ($CFG->useblogassociations && $page->cm !== null) {
342 // Load for the module associated with the page
343 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
344 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
345 // Load the options for the course associated with the page
346 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
349 // Get the options for the user
350 if ($user !== null and !isguestuser($user)) {
351 // Load for the requested user
352 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
354 // Load for the current user
355 if (isloggedin() and !isguestuser()) {
356 $options[CONTEXT_USER] = blog_get_options_for_user();
360 // If blog level is global then display a link to view all site entries
361 if (!empty($CFG->enableblogs) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', context_system::instance())) {
362 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
363 'string' => get_string('viewsiteentries', 'blog'),
364 'link' => new moodle_url('/blog/index.php')
368 // Return the options
369 return $options;
373 * Get all of the blog options that relate to the passed user.
375 * If no user is passed the current user is assumed.
377 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
378 * @param stdClass $user
379 * @return array The array of options for the requested user
381 function blog_get_options_for_user(stdClass $user=null) {
382 global $CFG, $USER;
383 // Cache
384 static $useroptions = array();
386 $options = array();
387 // Blogs must be enabled and the user must be logged in
388 if (!blog_is_enabled_for_user()) {
389 return $options;
392 // Sort out the user var
393 if ($user === null || $user->id == $USER->id) {
394 $user = $USER;
395 $iscurrentuser = true;
396 } else {
397 $iscurrentuser = false;
400 // If we've already generated serve from the cache
401 if (array_key_exists($user->id, $useroptions)) {
402 return $useroptions[$user->id];
405 $sitecontext = context_system::instance();
406 $canview = has_capability('moodle/blog:view', $sitecontext);
408 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
409 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
410 $options['userentries'] = array(
411 'string' => get_string('viewuserentries', 'blog', fullname($user)),
412 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
414 } else {
415 // It's the current user
416 if ($canview) {
417 // We can view our own blogs .... BIG surprise
418 $options['view'] = array(
419 'string' => get_string('viewallmyentries', 'blog'),
420 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
423 if (has_capability('moodle/blog:create', $sitecontext)) {
424 // We can add to our own blog
425 $options['add'] = array(
426 'string' => get_string('addnewentry', 'blog'),
427 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
431 if ($canview && $CFG->enablerssfeeds) {
432 $options['rss'] = array(
433 'string' => get_string('rssfeed', 'blog'),
434 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
438 // Cache the options
439 $useroptions[$user->id] = $options;
440 // Return the options
441 return $options;
445 * Get the blog options that relate to the given course for the given user.
447 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
448 * @param stdClass $course The course to load options for
449 * @param stdClass $user The user to load options for null == current user
450 * @return array The array of options
452 function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
453 global $CFG, $USER;
454 // Cache
455 static $courseoptions = array();
457 $options = array();
459 // User must be logged in and blogs must be enabled
460 if (!blog_is_enabled_for_user()) {
461 return $options;
464 // Check that the user can associate with the course
465 $sitecontext = context_system::instance();
466 // Generate the cache key
467 $key = $course->id.':';
468 if (!empty($user)) {
469 $key .= $user->id;
470 } else {
471 $key .= $USER->id;
473 // Serve from the cache if we've already generated for this course
474 if (array_key_exists($key, $courseoptions)) {
475 return $courseoptions[$key];
479 if (has_capability('moodle/blog:view', $sitecontext)) {
480 // We can view!
481 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
482 // View entries about this course
483 $options['courseview'] = array(
484 'string' => get_string('viewcourseblogs', 'blog'),
485 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id))
488 // View MY entries about this course
489 $options['courseviewmine'] = array(
490 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
491 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $USER->id))
493 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
494 // View the provided users entries about this course
495 $options['courseviewuser'] = array(
496 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
497 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $user->id))
502 if (has_capability('moodle/blog:create', $sitecontext)) {
503 // We can blog about this course
504 $options['courseadd'] = array(
505 'string' => get_string('blogaboutthiscourse', 'blog'),
506 'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'courseid' => $course->id))
511 // Cache the options for this course
512 $courseoptions[$key] = $options;
513 // Return the options
514 return $options;
518 * Get the blog options relating to the given module for the given user
520 * @staticvar array $moduleoptions Cache
521 * @param stdClass|cm_info $module The module to get options for
522 * @param stdClass $user The user to get options for null == currentuser
523 * @return array
525 function blog_get_options_for_module($module, $user=null) {
526 global $CFG, $USER;
527 // Cache
528 static $moduleoptions = array();
530 $options = array();
531 // User must be logged in, blogs must be enabled
532 if (!blog_is_enabled_for_user()) {
533 return $options;
536 $sitecontext = context_system::instance();
538 // Generate the cache key
539 $key = $module->id.':';
540 if (!empty($user)) {
541 $key .= $user->id;
542 } else {
543 $key .= $USER->id;
545 if (array_key_exists($key, $moduleoptions)) {
546 // Serve from the cache so we don't have to regenerate
547 return $moduleoptions[$key];
551 if (has_capability('moodle/blog:view', $sitecontext)) {
552 // Save correct module name for later usage.
553 $modulename = get_string('modulename', $module->modname);
555 // We can view!
556 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
557 // View all entries about this module
558 $a = new stdClass;
559 $a->type = $modulename;
560 $options['moduleview'] = array(
561 'string' => get_string('viewallmodentries', 'blog', $a),
562 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
565 // View MY entries about this module
566 $options['moduleviewmine'] = array(
567 'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
568 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
570 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
571 // View the given users entries about this module
572 $a = new stdClass;
573 $a->mod = $modulename;
574 $a->user = fullname($user);
575 $options['moduleviewuser'] = array(
576 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
577 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
582 if (has_capability('moodle/blog:create', $sitecontext)) {
583 // The user can blog about this module
584 $options['moduleadd'] = array(
585 'string' => get_string('blogaboutthismodule', 'blog', $modulename),
586 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
589 // Cache the options
590 $moduleoptions[$key] = $options;
591 // Return the options
592 return $options;
596 * This function encapsulates all the logic behind the complex
597 * navigation, titles and headings of the blog listing page, depending
598 * on URL params. It looks at URL params and at the current context level.
599 * It builds and returns an array containing:
601 * 1. heading: The heading displayed above the blog entries
602 * 2. stradd: The text to be used as the "Add entry" link
603 * 3. strview: The text to be used as the "View entries" link
604 * 4. url: The moodle_url object used as the base for add and view links
605 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
607 * All other variables are set directly in $PAGE
609 * It uses the current URL to build these variables.
610 * A number of mutually exclusive use cases are used to structure this function.
612 * @return array
614 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
615 global $CFG, $PAGE, $DB, $USER;
617 $id = optional_param('id', null, PARAM_INT);
618 $tag = optional_param('tag', null, PARAM_NOTAGS);
619 $tagid = optional_param('tagid', $tagid, PARAM_INT);
620 $userid = optional_param('userid', $userid, PARAM_INT);
621 $modid = optional_param('modid', null, PARAM_INT);
622 $entryid = optional_param('entryid', null, PARAM_INT);
623 $groupid = optional_param('groupid', $groupid, PARAM_INT);
624 $courseid = optional_param('courseid', $courseid, PARAM_INT);
625 $search = optional_param('search', null, PARAM_RAW);
626 $action = optional_param('action', null, PARAM_ALPHA);
627 $confirm = optional_param('confirm', false, PARAM_BOOL);
629 // Ignore userid when action == add
630 if ($action == 'add' && $userid) {
631 unset($userid);
632 $PAGE->url->remove_params(array('userid'));
633 } else if ($action == 'add' && $entryid) {
634 unset($entryid);
635 $PAGE->url->remove_params(array('entryid'));
638 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
640 $blogurl = new moodle_url('/blog/index.php');
642 $headers['stradd'] = get_string('addnewentry', 'blog');
643 $headers['strview'] = null;
645 $site = $DB->get_record('course', array('id' => SITEID));
646 $sitecontext = context_system::instance();
647 // Common Lang strings
648 $strparticipants = get_string("participants");
649 $strblogentries = get_string("blogentries", 'blog');
651 // Prepare record objects as needed
652 if (!empty($courseid)) {
653 $headers['filters']['course'] = $courseid;
654 $course = $DB->get_record('course', array('id' => $courseid));
657 if (!empty($userid)) {
658 $headers['filters']['user'] = $userid;
659 $user = $DB->get_record('user', array('id' => $userid));
662 if (!empty($groupid)) { // groupid always overrides courseid
663 $headers['filters']['group'] = $groupid;
664 $group = $DB->get_record('groups', array('id' => $groupid));
665 $course = $DB->get_record('course', array('id' => $group->courseid));
668 $PAGE->set_pagelayout('standard');
670 // modid always overrides courseid, so the $course object may be reset here
671 if (!empty($modid) && $CFG->useblogassociations) {
673 $headers['filters']['module'] = $modid;
674 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
675 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
676 $course = $DB->get_record('course', array('id' => $courseid));
677 $cm = $DB->get_record('course_modules', array('id' => $modid));
678 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
679 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
680 $a = new stdClass();
681 $a->type = get_string('modulename', $cm->modname);
682 $PAGE->set_cm($cm, $course);
683 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
684 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
687 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
688 // Note: if action is set to 'add' or 'edit', we do this at the end
689 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
690 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
691 $PAGE->navbar->add($strblogentries, $blogurl);
692 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
693 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
694 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
695 // $headers['strview'] = get_string('viewsiteentries', 'blog');
698 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
699 if (!empty($entryid)) {
700 $headers['filters']['entry'] = $entryid;
701 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
702 $user = $DB->get_record_sql($sql, array($entryid));
703 $entry = $DB->get_record('post', array('id' => $entryid));
705 $blogurl->param('userid', $user->id);
707 if (!empty($course)) {
708 $mycourseid = $course->id;
709 $blogurl->param('courseid', $mycourseid);
710 } else {
711 $mycourseid = $site->id;
713 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
715 $PAGE->navbar->add($strblogentries, $blogurl);
717 $blogurl->remove_params('userid');
718 $PAGE->navbar->add($entry->subject, $blogurl);
719 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
720 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
721 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
723 // We ignore tag and search params
724 if (empty($action) || !$CFG->useblogassociations) {
725 $headers['url'] = $blogurl;
726 return $headers;
730 // Case 3: A user's blog entries
731 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
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
741 // Case 4: No blog associations, no userid
742 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
743 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
744 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
745 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
746 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
747 } else
749 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
750 if (!empty($userid) && !empty($modid) && empty($entryid)) {
751 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
752 $blogurl->param('userid', $userid);
753 $blogurl->param('modid', $modid);
755 // Course module navigation is handled by build_navigation as the second param
756 $headers['cm'] = $cm;
757 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
758 $PAGE->navbar->add($strblogentries, $blogurl);
760 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
761 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
763 $a = new stdClass();
764 $a->user = fullname($user);
765 $a->mod = $cm->name;
766 $a->type = get_string('modulename', $cm->modname);
767 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
768 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
769 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
770 } else
772 // Case 6: Blog entries associated with a course by a specific user
773 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
774 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
775 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
776 $blogurl->param('userid', $userid);
777 $blogurl->param('courseid', $courseid);
779 $PAGE->navbar->add($strblogentries, $blogurl);
781 $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
782 $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
784 $a = new stdClass();
785 $a->user = fullname($user);
786 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
787 $a->type = get_string('course');
788 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
789 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
790 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
792 // Remove the userid from the URL to inform the blog_menu block correctly
793 $blogurl->remove_params(array('userid'));
794 } else
796 // Case 7: Blog entries by members of a group, associated with that group's course
797 if (!empty($groupid) && empty($modid) && empty($entryid)) {
798 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
799 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
800 $blogurl->param('courseid', $course->id);
802 $PAGE->navbar->add($strblogentries, $blogurl);
803 $blogurl->remove_params(array('courseid'));
804 $blogurl->param('groupid', $groupid);
805 $PAGE->navbar->add($group->name, $blogurl);
807 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
808 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
810 $a = new stdClass();
811 $a->group = $group->name;
812 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
813 $a->type = get_string('course');
814 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
815 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
816 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
817 } else
819 // Case 8: Blog entries by members of a group, associated with an activity in that course
820 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
821 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
822 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
823 $headers['cm'] = $cm;
824 $blogurl->param('modid', $modid);
825 $PAGE->navbar->add($strblogentries, $blogurl);
827 $blogurl->param('groupid', $groupid);
828 $PAGE->navbar->add($group->name, $blogurl);
830 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
831 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
833 $a = new stdClass();
834 $a->group = $group->name;
835 $a->mod = $cm->name;
836 $a->type = get_string('modulename', $cm->modname);
837 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
838 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
839 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
841 } else
843 // Case 9: All blog entries associated with an activity
844 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
845 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
846 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
847 $PAGE->set_cm($cm, $course);
848 $blogurl->param('modid', $modid);
849 $PAGE->navbar->add($strblogentries, $blogurl);
850 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
851 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
852 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
853 $a = new stdClass();
854 $a->type = get_string('modulename', $cm->modname);
855 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
856 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
857 } else
859 // Case 10: All blog entries associated with a course
860 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
861 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
862 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
863 $blogurl->param('courseid', $courseid);
864 $PAGE->navbar->add($strblogentries, $blogurl);
865 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
866 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
867 $a = new stdClass();
868 $a->type = get_string('course');
869 $headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
870 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
871 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
872 $blogurl->remove_params(array('userid'));
875 if (!in_array($action, array('edit', 'add'))) {
876 // Append Tag info
877 if (!empty($tagid)) {
878 $headers['filters']['tag'] = $tagid;
879 $blogurl->param('tagid', $tagid);
880 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
881 $PAGE->navbar->add($tagrec->name, $blogurl);
882 } elseif (!empty($tag)) {
883 if ($tagrec = $DB->get_record('tag', array('name' => $tag))) {
884 $tagid = $tagrec->id;
885 $headers['filters']['tag'] = $tagid;
886 $blogurl->param('tag', $tag);
887 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
891 // Append Search info
892 if (!empty($search)) {
893 $headers['filters']['search'] = $search;
894 $blogurl->param('search', $search);
895 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
899 // Append edit mode info
900 if (!empty($action) && $action == 'add') {
902 } else if (!empty($action) && $action == 'edit') {
903 $PAGE->navbar->add(get_string('editentry', 'blog'));
906 if (empty($headers['url'])) {
907 $headers['url'] = $blogurl;
909 return $headers;
913 * Shortcut function for getting a count of blog entries associated with a course or a module
914 * @param int $courseid The ID of the course
915 * @param int $cmid The ID of the course_modules
916 * @return string The number of associated entries
918 function blog_get_associated_count($courseid, $cmid=null) {
919 global $DB;
920 $context = context_course::instance($courseid);
921 if ($cmid) {
922 $context = context_module::instance($cmid);
924 return $DB->count_records('blog_association', array('contextid' => $context->id));
928 * Running addtional permission check on plugin, for example, plugins
929 * may have switch to turn on/off comments option, this callback will
930 * affect UI display, not like pluginname_comment_validate only throw
931 * exceptions.
932 * blog_comment_validate will be called before viewing/adding/deleting
933 * comment, so don't repeat checks.
934 * Capability check has been done in comment->check_permissions(), we
935 * don't need to do it again here.
937 * @package core_blog
938 * @category comment
940 * @param stdClass $comment_param {
941 * context => context the context object
942 * courseid => int course id
943 * cm => stdClass course module object
944 * commentarea => string comment area
945 * itemid => int itemid
947 * @return array
949 function blog_comment_permissions($comment_param) {
950 global $DB;
952 // If blog is public and current user is guest, then don't let him post comments.
953 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), 'publishstate', MUST_EXIST);
955 if ($blogentry->publishstate != 'public') {
956 if (!isloggedin() || isguestuser()) {
957 return array('post' => false, 'view' => true);
960 return array('post' => true, 'view' => true);
964 * Validate comment parameter before perform other comments actions
966 * @package core_blog
967 * @category comment
969 * @param stdClass $comment {
970 * context => context the context object
971 * courseid => int course id
972 * cm => stdClass course module object
973 * commentarea => string comment area
974 * itemid => int itemid
976 * @return boolean
978 function blog_comment_validate($comment_param) {
979 global $CFG, $DB, $USER;
981 // Check if blogs are enabled user can comment.
982 if (empty($CFG->enableblogs) || empty($CFG->blogusecomments)) {
983 throw new comment_exception('nopermissiontocomment');
986 // Validate comment area.
987 if ($comment_param->commentarea != 'format_blog') {
988 throw new comment_exception('invalidcommentarea');
991 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), '*', MUST_EXIST);
993 // Validation for comment deletion.
994 if (!empty($comment_param->commentid)) {
995 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
996 if ($record->commentarea != 'format_blog') {
997 throw new comment_exception('invalidcommentarea');
999 if ($record->contextid != $comment_param->context->id) {
1000 throw new comment_exception('invalidcontext');
1002 if ($record->itemid != $comment_param->itemid) {
1003 throw new comment_exception('invalidcommentitemid');
1005 } else {
1006 throw new comment_exception('invalidcommentid');
1010 // Validate if user has blog view permission.
1011 $sitecontext = context_system::instance();
1012 return has_capability('moodle/blog:view', $sitecontext) &&
1013 blog_user_can_view_user_entry($blogentry->userid, $blogentry);
1017 * Return a list of page types
1018 * @param string $pagetype current page type
1019 * @param stdClass $parentcontext Block's parent context
1020 * @param stdClass $currentcontext Current context of block
1022 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1023 return array(
1024 '*'=>get_string('page-x', 'pagetype'),
1025 'blog-*'=>get_string('page-blog-x', 'blog'),
1026 'blog-index'=>get_string('page-blog-index', 'blog'),
1027 'blog-edit'=>get_string('page-blog-edit', 'blog')