MDL32392 delete unused is_min_version() in some DB drivers
[moodle.git] / blog / lib.php
blobab9fd52fb856f5d2f013d2cda2857a828d8ff0d8
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Core global functions for Blog.
21 * @package moodlecore
22 * @subpackage blog
23 * @copyright 2009 Nicolas Connault
24 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 defined('MOODLE_INTERNAL') || die();
29 /**
30 * Library of functions and constants for blog
32 require_once($CFG->dirroot .'/blog/rsslib.php');
33 require_once($CFG->dirroot.'/tag/lib.php');
35 /**
36 * User can edit a blog entry if this is their own blog entry and they have
37 * the capability moodle/blog:create, or if they have the capability
38 * moodle/blog:manageentries.
40 * This also applies to deleting of entries.
42 function blog_user_can_edit_entry($blogentry) {
43 global $USER;
45 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
47 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
48 return true; // can edit any blog entry
51 if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
52 return true; // can edit own when having blog:create capability
55 return false;
59 /**
60 * Checks to see if a user can view the blogs of another user.
61 * Only blog level is checked here, the capabilities are enforced
62 * in blog/index.php
64 function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
65 global $CFG, $USER, $DB;
67 if (empty($CFG->bloglevel)) {
68 return false; // blog system disabled
71 if (isloggedin() && $USER->id == $targetuserid) {
72 return true; // can view own entries in any case
75 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
76 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
77 return true; // can manage all entries
80 // coming for 1 entry, make sure it's not a draft
81 if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
82 return false; // can not view draft of others
85 // coming for 0 entry, make sure user is logged in, if not a public blog
86 if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
87 return false;
90 switch ($CFG->bloglevel) {
91 case BLOG_GLOBAL_LEVEL:
92 return true;
93 break;
95 case BLOG_SITE_LEVEL:
96 if (isloggedin()) { // not logged in viewers forbidden
97 return true;
99 return false;
100 break;
102 case BLOG_USER_LEVEL:
103 default:
104 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
105 return has_capability('moodle/user:readuserblogs', $personalcontext);
106 break;
112 * remove all associations for the blog entries of a particular user
113 * @param int userid - id of user whose blog associations will be deleted
115 function blog_remove_associations_for_user($userid) {
116 global $DB;
117 throw new coding_exception('function blog_remove_associations_for_user() is not finished');
119 $blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
120 foreach ($blogentries as $entry) {
121 if (blog_user_can_edit_entry($entry)) {
122 blog_remove_associations_for_entry($entry->id);
129 * remove all associations for the blog entries of a particular course
130 * @param int courseid - id of user whose blog associations will be deleted
132 function blog_remove_associations_for_course($courseid) {
133 global $DB;
134 $context = get_context_instance(CONTEXT_COURSE, $courseid);
135 $DB->delete_records('blog_association', array('contextid' => $context->id));
139 * Given a record in the {blog_external} table, checks the blog's URL
140 * for new entries not yet copied into Moodle.
141 * Also attempts to identify and remove deleted blog entries
143 * @param object $externalblog
144 * @return boolean False if the Feed is invalid
146 function blog_sync_external_entries($externalblog) {
147 global $CFG, $DB;
148 require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
150 $rssfile = new moodle_simplepie_file($externalblog->url);
151 $filetest = new SimplePie_Locator($rssfile);
153 if (!$filetest->is_feed($rssfile)) {
154 $externalblog->failedlastsync = 1;
155 $DB->update_record('blog_external', $externalblog);
156 return false;
157 } else if (!empty($externalblog->failedlastsync)) {
158 $externalblog->failedlastsync = 0;
159 $DB->update_record('blog_external', $externalblog);
162 $rss = new moodle_simplepie($externalblog->url);
164 if (empty($rss->data)) {
165 return null;
167 //used to identify blog posts that have been deleted from the source feed
168 $oldesttimestamp = null;
169 $uniquehashes = array();
171 foreach ($rss->get_items() as $entry) {
172 // If filtertags are defined, use them to filter the entries by RSS category
173 if (!empty($externalblog->filtertags)) {
174 $containsfiltertag = false;
175 $categories = $entry->get_categories();
176 $filtertags = explode(',', $externalblog->filtertags);
177 $filtertags = array_map('trim', $filtertags);
178 $filtertags = array_map('strtolower', $filtertags);
180 foreach ($categories as $category) {
181 if (in_array(trim(strtolower($category->term)), $filtertags)) {
182 $containsfiltertag = true;
186 if (!$containsfiltertag) {
187 continue;
191 $uniquehashes[] = $entry->get_permalink();
193 $newentry = new stdClass();
194 $newentry->userid = $externalblog->userid;
195 $newentry->module = 'blog_external';
196 $newentry->content = $externalblog->id;
197 $newentry->uniquehash = $entry->get_permalink();
198 $newentry->publishstate = 'site';
199 $newentry->format = FORMAT_HTML;
200 // Clean subject of html, just in case
201 $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
202 // Observe 128 max chars in DB
203 // TODO: +1 to raise this to 255
204 if (textlib::strlen($newentry->subject) > 128) {
205 $newentry->subject = textlib::substr($newentry->subject, 0, 125) . '...';
207 $newentry->summary = $entry->get_description();
209 //used to decide whether to insert or update
210 //uses enty permalink plus creation date if available
211 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
213 //our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
214 $entrydate = $entry->get_date('U');
215 if (!empty($entrydate)) {
216 $existingpostconditions['created'] = $entrydate;
219 //the post ID or false if post not found in DB
220 $postid = $DB->get_field('post', 'id', $existingpostconditions);
222 $timestamp = null;
223 if (empty($entrydate)) {
224 $timestamp = time();
225 } else {
226 $timestamp = $entrydate;
229 //only set created if its a new post so we retain the original creation timestamp if the post is edited
230 if ($postid === false) {
231 $newentry->created = $timestamp;
233 $newentry->lastmodified = $timestamp;
235 if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
236 //found an older post
237 $oldesttimestamp = $timestamp;
240 if (textlib::strlen($newentry->uniquehash) > 255) {
241 // The URL for this item is too long for the field. Rather than add
242 // the entry without the link we will skip straight over it.
243 // RSS spec says recommended length 500, we use 255.
244 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
245 continue;
248 if ($postid === false) {
249 $id = $DB->insert_record('post', $newentry);
251 // Set tags
252 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
253 tag_set('post', $id, $tags);
255 } else {
256 $newentry->id = $postid;
257 $DB->update_record('post', $newentry);
261 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
262 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
263 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
264 $sql = "SELECT id, uniquehash
265 FROM {post}
266 WHERE module = 'blog_external'
267 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
268 AND created > :ts";
269 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
271 $todelete = array();
272 foreach($dbposts as $dbpost) {
273 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
274 $todelete[] = $dbpost->id;
277 $DB->delete_records_list('post', 'id', $todelete);
279 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
283 * Given an external blog object, deletes all related blog entries from the post table.
284 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
285 * @param object $externablog
287 function blog_delete_external_entries($externalblog) {
288 global $DB;
289 require_capability('moodle/blog:manageexternal', get_context_instance(CONTEXT_SYSTEM));
290 $DB->delete_records_select('post',
291 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
292 array($externalblog->id));
296 * Returns a URL based on the context of the current page.
297 * This URL points to blog/index.php and includes filter parameters appropriate for the current page.
299 * @param stdclass $context
300 * @return string
302 function blog_get_context_url($context=null) {
303 global $CFG;
305 $viewblogentriesurl = new moodle_url('/blog/index.php');
307 if (empty($context)) {
308 global $PAGE;
309 $context = $PAGE->context;
312 // Change contextlevel to SYSTEM if viewing the site course
313 if ($context->contextlevel == CONTEXT_COURSE && $context->instanceid == SITEID) {
314 $context = context_system::instance();
317 $filterparam = '';
318 $strlevel = '';
320 switch ($context->contextlevel) {
321 case CONTEXT_SYSTEM:
322 case CONTEXT_BLOCK:
323 case CONTEXT_COURSECAT:
324 break;
325 case CONTEXT_COURSE:
326 $filterparam = 'courseid';
327 $strlevel = get_string('course');
328 break;
329 case CONTEXT_MODULE:
330 $filterparam = 'modid';
331 $strlevel = print_context_name($context);
332 break;
333 case CONTEXT_USER:
334 $filterparam = 'userid';
335 $strlevel = get_string('user');
336 break;
339 if (!empty($filterparam)) {
340 $viewblogentriesurl->param($filterparam, $context->instanceid);
343 return $viewblogentriesurl;
347 * This function checks that blogs are enabled, and that the user can see blogs at all
348 * @return bool
350 function blog_is_enabled_for_user() {
351 global $CFG;
352 //return (!empty($CFG->bloglevel) && $CFG->bloglevel <= BLOG_GLOBAL_LEVEL && isloggedin() && !isguestuser());
353 return (!empty($CFG->bloglevel) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
357 * This function gets all of the options available for the current user in respect
358 * to blogs.
360 * It loads the following if applicable:
361 * - Module options {@see blog_get_options_for_module}
362 * - Course options {@see blog_get_options_for_course}
363 * - User specific options {@see blog_get_options_for_user}
364 * - General options (BLOG_LEVEL_GLOBAL)
366 * @param moodle_page $page The page to load for (normally $PAGE)
367 * @param stdClass $userid Load for a specific user
368 * @return array An array of options organised by type.
370 function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
371 global $CFG, $DB, $USER;
373 $options = array();
375 // If blogs are enabled and the user is logged in and not a guest
376 if (blog_is_enabled_for_user()) {
377 // If the context is the user then assume we want to load for the users context
378 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
379 $userid = $page->context->instanceid;
381 // Check the userid var
382 if (!is_null($userid) && $userid!==$USER->id) {
383 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
384 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
385 } else {
386 $user = null;
389 if ($CFG->useblogassociations && $page->cm !== null) {
390 // Load for the module associated with the page
391 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
392 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
393 // Load the options for the course associated with the page
394 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
397 // Get the options for the user
398 if ($user !== null and !isguestuser($user)) {
399 // Load for the requested user
400 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
402 // Load for the current user
403 if (isloggedin() and !isguestuser()) {
404 $options[CONTEXT_USER] = blog_get_options_for_user();
408 // If blog level is global then display a link to view all site entries
409 if (!empty($CFG->bloglevel) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', get_context_instance(CONTEXT_SYSTEM))) {
410 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
411 'string' => get_string('viewsiteentries', 'blog'),
412 'link' => new moodle_url('/blog/index.php')
416 // Return the options
417 return $options;
421 * Get all of the blog options that relate to the passed user.
423 * If no user is passed the current user is assumed.
425 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
426 * @param stdClass $user
427 * @return array The array of options for the requested user
429 function blog_get_options_for_user(stdClass $user=null) {
430 global $CFG, $USER;
431 // Cache
432 static $useroptions = array();
434 $options = array();
435 // Blogs must be enabled and the user must be logged in
436 if (!blog_is_enabled_for_user()) {
437 return $options;
440 // Sort out the user var
441 if ($user === null || $user->id == $USER->id) {
442 $user = $USER;
443 $iscurrentuser = true;
444 } else {
445 $iscurrentuser = false;
448 // If we've already generated serve from the cache
449 if (array_key_exists($user->id, $useroptions)) {
450 return $useroptions[$user->id];
453 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
454 $canview = has_capability('moodle/blog:view', $sitecontext);
456 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
457 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
458 $options['userentries'] = array(
459 'string' => get_string('viewuserentries', 'blog', fullname($user)),
460 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
462 } else {
463 // It's the current user
464 if ($canview) {
465 // We can view our own blogs .... BIG surprise
466 $options['view'] = array(
467 'string' => get_string('viewallmyentries', 'blog'),
468 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
471 if (has_capability('moodle/blog:create', $sitecontext)) {
472 // We can add to our own blog
473 $options['add'] = array(
474 'string' => get_string('addnewentry', 'blog'),
475 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
479 if ($canview && $CFG->enablerssfeeds) {
480 $options['rss'] = array(
481 'string' => get_string('rssfeed', 'blog'),
482 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
486 // Cache the options
487 $useroptions[$user->id] = $options;
488 // Return the options
489 return $options;
493 * Get the blog options that relate to the given course for the given user.
495 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
496 * @param stdClass $course The course to load options for
497 * @param stdClass $user The user to load options for null == current user
498 * @return array The array of options
500 function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
501 global $CFG, $USER;
502 // Cache
503 static $courseoptions = array();
505 $options = array();
507 // User must be logged in and blogs must be enabled
508 if (!blog_is_enabled_for_user()) {
509 return $options;
512 // Check that the user can associate with the course
513 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
514 if (!has_capability('moodle/blog:associatecourse', $sitecontext)) {
515 return $options;
517 // Generate the cache key
518 $key = $course->id.':';
519 if (!empty($user)) {
520 $key .= $user->id;
521 } else {
522 $key .= $USER->id;
524 // Serve from the cache if we've already generated for this course
525 if (array_key_exists($key, $courseoptions)) {
526 return $courseoptions[$key];
529 $coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
530 $canparticipate = (is_enrolled($coursecontext) or is_viewing($coursecontext));
532 if (has_capability('moodle/blog:view', $coursecontext)) {
533 // We can view!
534 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
535 // View entries about this course
536 $options['courseview'] = array(
537 'string' => get_string('viewcourseblogs', 'blog'),
538 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id))
541 // View MY entries about this course
542 $options['courseviewmine'] = array(
543 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
544 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$USER->id))
546 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
547 // View the provided users entries about this course
548 $options['courseviewuser'] = array(
549 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
550 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$user->id))
555 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
556 // We can blog about this course
557 $options['courseadd'] = array(
558 'string' => get_string('blogaboutthiscourse', 'blog'),
559 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'courseid'=>$course->id))
564 // Cache the options for this course
565 $courseoptions[$key] = $options;
566 // Return the options
567 return $options;
571 * Get the blog options relating to the given module for the given user
573 * @staticvar array $moduleoptions Cache
574 * @param stdClass|cm_info $module The module to get options for
575 * @param stdClass $user The user to get options for null == currentuser
576 * @return array
578 function blog_get_options_for_module($module, $user=null) {
579 global $CFG, $USER;
580 // Cache
581 static $moduleoptions = array();
583 $options = array();
584 // User must be logged in, blogs must be enabled
585 if (!blog_is_enabled_for_user()) {
586 return $options;
589 // Check the user can associate with the module
590 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
591 if (!has_capability('moodle/blog:associatemodule', $sitecontext)) {
592 return $options;
595 // Generate the cache key
596 $key = $module->id.':';
597 if (!empty($user)) {
598 $key .= $user->id;
599 } else {
600 $key .= $USER->id;
602 if (array_key_exists($key, $moduleoptions)) {
603 // Serve from the cache so we don't have to regenerate
604 return $moduleoptions[$module->id];
607 $modcontext = get_context_instance(CONTEXT_MODULE, $module->id);
608 $canparticipate = (is_enrolled($modcontext) or is_viewing($modcontext));
610 if (has_capability('moodle/blog:view', $modcontext)) {
611 // We can view!
612 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
613 // View all entries about this module
614 $a = new stdClass;
615 $a->type = $module->modname;
616 $options['moduleview'] = array(
617 'string' => get_string('viewallmodentries', 'blog', $a),
618 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
621 // View MY entries about this module
622 $options['moduleviewmine'] = array(
623 'string' => get_string('viewmyentriesaboutmodule', 'blog', $module->modname),
624 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
626 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
627 // View the given users entries about this module
628 $a = new stdClass;
629 $a->mod = $module->modname;
630 $a->user = fullname($user);
631 $options['moduleviewuser'] = array(
632 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
633 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
638 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
639 // The user can blog about this module
640 $options['moduleadd'] = array(
641 'string' => get_string('blogaboutthismodule', 'blog', $module->modname),
642 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
645 // Cache the options
646 $moduleoptions[$key] = $options;
647 // Return the options
648 return $options;
652 * This function encapsulates all the logic behind the complex
653 * navigation, titles and headings of the blog listing page, depending
654 * on URL params. It looks at URL params and at the current context level.
655 * It builds and returns an array containing:
657 * 1. heading: The heading displayed above the blog entries
658 * 2. stradd: The text to be used as the "Add entry" link
659 * 3. strview: The text to be used as the "View entries" link
660 * 4. url: The moodle_url object used as the base for add and view links
661 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
663 * All other variables are set directly in $PAGE
665 * It uses the current URL to build these variables.
666 * A number of mutually exclusive use cases are used to structure this function.
668 * @return array
670 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
671 global $CFG, $PAGE, $DB, $USER;
673 $id = optional_param('id', null, PARAM_INT);
674 $tag = optional_param('tag', null, PARAM_NOTAGS);
675 $tagid = optional_param('tagid', $tagid, PARAM_INT);
676 $userid = optional_param('userid', $userid, PARAM_INT);
677 $modid = optional_param('modid', null, PARAM_INT);
678 $entryid = optional_param('entryid', null, PARAM_INT);
679 $groupid = optional_param('groupid', $groupid, PARAM_INT);
680 $courseid = optional_param('courseid', $courseid, PARAM_INT);
681 $search = optional_param('search', null, PARAM_RAW);
682 $action = optional_param('action', null, PARAM_ALPHA);
683 $confirm = optional_param('confirm', false, PARAM_BOOL);
685 // Ignore userid when action == add
686 if ($action == 'add' && $userid) {
687 unset($userid);
688 $PAGE->url->remove_params(array('userid'));
689 } else if ($action == 'add' && $entryid) {
690 unset($entryid);
691 $PAGE->url->remove_params(array('entryid'));
694 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
696 $blogurl = new moodle_url('/blog/index.php');
698 // If the title is not yet set, it's likely that the context isn't set either, so skip this part
699 $pagetitle = $PAGE->title;
700 if (!empty($pagetitle)) {
701 $contexturl = blog_get_context_url();
703 // Look at the context URL, it may have additional params that are not in the current URL
704 if (!$blogurl->compare($contexturl)) {
705 $blogurl = $contexturl;
706 if (empty($courseid)) {
707 $courseid = $blogurl->param('courseid');
709 if (empty($modid)) {
710 $modid = $blogurl->param('modid');
715 $headers['stradd'] = get_string('addnewentry', 'blog');
716 $headers['strview'] = null;
718 $site = $DB->get_record('course', array('id' => SITEID));
719 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
720 // Common Lang strings
721 $strparticipants = get_string("participants");
722 $strblogentries = get_string("blogentries", 'blog');
724 // Prepare record objects as needed
725 if (!empty($courseid)) {
726 $headers['filters']['course'] = $courseid;
727 $course = $DB->get_record('course', array('id' => $courseid));
730 if (!empty($userid)) {
731 $headers['filters']['user'] = $userid;
732 $user = $DB->get_record('user', array('id' => $userid));
735 if (!empty($groupid)) { // groupid always overrides courseid
736 $headers['filters']['group'] = $groupid;
737 $group = $DB->get_record('groups', array('id' => $groupid));
738 $course = $DB->get_record('course', array('id' => $group->courseid));
741 $PAGE->set_pagelayout('standard');
743 if (!empty($modid) && $CFG->useblogassociations && has_capability('moodle/blog:associatemodule', $sitecontext)) { // modid always overrides courseid, so the $course object may be reset here
744 $headers['filters']['module'] = $modid;
745 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
746 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
747 $course = $DB->get_record('course', array('id' => $courseid));
748 $cm = $DB->get_record('course_modules', array('id' => $modid));
749 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
750 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
751 $a = new stdClass();
752 $a->type = get_string('modulename', $cm->modname);
753 $PAGE->set_cm($cm, $course);
754 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
755 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
758 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
759 // Note: if action is set to 'add' or 'edit', we do this at the end
760 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
761 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
762 $PAGE->navbar->add($strblogentries, $blogurl);
763 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
764 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
765 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
766 // $headers['strview'] = get_string('viewsiteentries', 'blog');
769 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
770 if (!empty($entryid)) {
771 $headers['filters']['entry'] = $entryid;
772 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
773 $user = $DB->get_record_sql($sql, array($entryid));
774 $entry = $DB->get_record('post', array('id' => $entryid));
776 $blogurl->param('userid', $user->id);
778 if (!empty($course)) {
779 $mycourseid = $course->id;
780 $blogurl->param('courseid', $mycourseid);
781 } else {
782 $mycourseid = $site->id;
784 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
786 $PAGE->navbar->add($strblogentries, $blogurl);
788 $blogurl->remove_params('userid');
789 $PAGE->navbar->add($entry->subject, $blogurl);
790 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
791 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
792 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
794 // We ignore tag and search params
795 if (empty($action) || !$CFG->useblogassociations) {
796 $headers['url'] = $blogurl;
797 return $headers;
801 // Case 3: A user's blog entries
802 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
803 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
804 $blogurl->param('userid', $userid);
805 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
806 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
807 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
808 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
810 } else
812 // Case 4: No blog associations, no userid
813 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
814 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
815 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
816 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
817 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
818 } else
820 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
821 if (!empty($userid) && !empty($modid) && empty($entryid)) {
822 $shortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
823 $blogurl->param('userid', $userid);
824 $blogurl->param('modid', $modid);
826 // Course module navigation is handled by build_navigation as the second param
827 $headers['cm'] = $cm;
828 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
829 $PAGE->navbar->add($strblogentries, $blogurl);
831 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
832 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
834 $a = new stdClass();
835 $a->user = fullname($user);
836 $a->mod = $cm->name;
837 $a->type = get_string('modulename', $cm->modname);
838 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
839 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
840 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
841 } else
843 // Case 6: Blog entries associated with a course by a specific user
844 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
845 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
846 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
847 $blogurl->param('userid', $userid);
848 $blogurl->param('courseid', $courseid);
850 $PAGE->navbar->add($strblogentries, $blogurl);
852 $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
853 $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
855 $a = new stdClass();
856 $a->user = fullname($user);
857 $a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
858 $a->type = get_string('course');
859 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
860 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
861 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
863 // Remove the userid from the URL to inform the blog_menu block correctly
864 $blogurl->remove_params(array('userid'));
865 } else
867 // Case 7: Blog entries by members of a group, associated with that group's course
868 if (!empty($groupid) && empty($modid) && empty($entryid)) {
869 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
870 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
871 $blogurl->param('courseid', $course->id);
873 $PAGE->navbar->add($strblogentries, $blogurl);
874 $blogurl->remove_params(array('courseid'));
875 $blogurl->param('groupid', $groupid);
876 $PAGE->navbar->add($group->name, $blogurl);
878 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
879 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
881 $a = new stdClass();
882 $a->group = $group->name;
883 $a->course = format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
884 $a->type = get_string('course');
885 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
886 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
887 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
888 } else
890 // Case 8: Blog entries by members of a group, associated with an activity in that course
891 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
892 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
893 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
894 $headers['cm'] = $cm;
895 $blogurl->param('modid', $modid);
896 $PAGE->navbar->add($strblogentries, $blogurl);
898 $blogurl->param('groupid', $groupid);
899 $PAGE->navbar->add($group->name, $blogurl);
901 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
902 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
904 $a = new stdClass();
905 $a->group = $group->name;
906 $a->mod = $cm->name;
907 $a->type = get_string('modulename', $cm->modname);
908 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
909 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
910 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
912 } else
914 // Case 9: All blog entries associated with an activity
915 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
916 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
917 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
918 $PAGE->set_cm($cm, $course);
919 $blogurl->param('modid', $modid);
920 $PAGE->navbar->add($strblogentries, $blogurl);
921 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
922 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
923 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
924 $a = new stdClass();
925 $a->type = get_string('modulename', $cm->modname);
926 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
927 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
928 } else
930 // Case 10: All blog entries associated with a course
931 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
932 $siteshortname = format_string($site->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, SITEID)));
933 $courseshortname = format_string($course->shortname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id)));
934 $blogurl->param('courseid', $courseid);
935 $PAGE->navbar->add($strblogentries, $blogurl);
936 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
937 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
938 $a = new stdClass();
939 $a->type = get_string('course');
940 $headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => get_context_instance(CONTEXT_COURSE, $course->id))));
941 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
942 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
943 $blogurl->remove_params(array('userid'));
946 if (!in_array($action, array('edit', 'add'))) {
947 // Append Tag info
948 if (!empty($tagid)) {
949 $headers['filters']['tag'] = $tagid;
950 $blogurl->param('tagid', $tagid);
951 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
952 $PAGE->navbar->add($tagrec->name, $blogurl);
953 } elseif (!empty($tag)) {
954 $blogurl->param('tag', $tag);
955 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
958 // Append Search info
959 if (!empty($search)) {
960 $headers['filters']['search'] = $search;
961 $blogurl->param('search', $search);
962 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
966 // Append edit mode info
967 if (!empty($action) && $action == 'add') {
969 } else if (!empty($action) && $action == 'edit') {
970 $PAGE->navbar->add(get_string('editentry', 'blog'));
973 if (empty($headers['url'])) {
974 $headers['url'] = $blogurl;
976 return $headers;
980 * Shortcut function for getting a count of blog entries associated with a course or a module
981 * @param int $courseid The ID of the course
982 * @param int $cmid The ID of the course_modules
983 * @return string The number of associated entries
985 function blog_get_associated_count($courseid, $cmid=null) {
986 global $DB;
987 $context = get_context_instance(CONTEXT_COURSE, $courseid);
988 if ($cmid) {
989 $context = get_context_instance(CONTEXT_MODULE, $cmid);
991 return $DB->count_records('blog_association', array('contextid' => $context->id));
995 * Running addtional permission check on plugin, for example, plugins
996 * may have switch to turn on/off comments option, this callback will
997 * affect UI display, not like pluginname_comment_validate only throw
998 * exceptions.
999 * Capability check has been done in comment->check_permissions(), we
1000 * don't need to do it again here.
1002 * @package core_blog
1003 * @category comment
1005 * @param stdClass $comment_param {
1006 * context => context the context object
1007 * courseid => int course id
1008 * cm => stdClass course module object
1009 * commentarea => string comment area
1010 * itemid => int itemid
1012 * @return array
1014 function blog_comment_permissions($comment_param) {
1015 return array('post'=>true, 'view'=>true);
1019 * Validate comment parameter before perform other comments actions
1021 * @package core_blog
1022 * @category comment
1024 * @param stdClass $comment {
1025 * context => context the context object
1026 * courseid => int course id
1027 * cm => stdClass course module object
1028 * commentarea => string comment area
1029 * itemid => int itemid
1031 * @return boolean
1033 function blog_comment_validate($comment_param) {
1034 global $DB;
1035 // validate comment itemid
1036 if (!$entry = $DB->get_record('post', array('id'=>$comment_param->itemid))) {
1037 throw new comment_exception('invalidcommentitemid');
1039 // validate comment area
1040 if ($comment_param->commentarea != 'format_blog') {
1041 throw new comment_exception('invalidcommentarea');
1043 // validation for comment deletion
1044 if (!empty($comment_param->commentid)) {
1045 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
1046 if ($record->commentarea != 'format_blog') {
1047 throw new comment_exception('invalidcommentarea');
1049 if ($record->contextid != $comment_param->context->id) {
1050 throw new comment_exception('invalidcontext');
1052 if ($record->itemid != $comment_param->itemid) {
1053 throw new comment_exception('invalidcommentitemid');
1055 } else {
1056 throw new comment_exception('invalidcommentid');
1059 return true;
1063 * Return a list of page types
1064 * @param string $pagetype current page type
1065 * @param stdClass $parentcontext Block's parent context
1066 * @param stdClass $currentcontext Current context of block
1068 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1069 return array(
1070 '*'=>get_string('page-x', 'pagetype'),
1071 'blog-*'=>get_string('page-blog-x', 'blog'),
1072 'blog-index'=>get_string('page-blog-index', 'blog'),
1073 'blog-edit'=>get_string('page-blog-edit', 'blog')