MDL-35854 fix username generator
[moodle.git] / blog / lib.php
bloba063a73c86431748415a2b3e03de8fe5e17d306a
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 // 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 = context_user::instance($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 = context_course::instance($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', context_system::instance());
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->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
356 * This function gets all of the options available for the current user in respect
357 * to blogs.
359 * It loads the following if applicable:
360 * - Module options {@see blog_get_options_for_module}
361 * - Course options {@see blog_get_options_for_course}
362 * - User specific options {@see blog_get_options_for_user}
363 * - General options (BLOG_LEVEL_GLOBAL)
365 * @param moodle_page $page The page to load for (normally $PAGE)
366 * @param stdClass $userid Load for a specific user
367 * @return array An array of options organised by type.
369 function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
370 global $CFG, $DB, $USER;
372 $options = array();
374 // If blogs are enabled and the user is logged in and not a guest
375 if (blog_is_enabled_for_user()) {
376 // If the context is the user then assume we want to load for the users context
377 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
378 $userid = $page->context->instanceid;
380 // Check the userid var
381 if (!is_null($userid) && $userid!==$USER->id) {
382 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
383 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
384 } else {
385 $user = null;
388 if ($CFG->useblogassociations && $page->cm !== null) {
389 // Load for the module associated with the page
390 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
391 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
392 // Load the options for the course associated with the page
393 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
396 // Get the options for the user
397 if ($user !== null and !isguestuser($user)) {
398 // Load for the requested user
399 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
401 // Load for the current user
402 if (isloggedin() and !isguestuser()) {
403 $options[CONTEXT_USER] = blog_get_options_for_user();
407 // If blog level is global then display a link to view all site entries
408 if (!empty($CFG->enableblogs) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', context_system::instance())) {
409 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
410 'string' => get_string('viewsiteentries', 'blog'),
411 'link' => new moodle_url('/blog/index.php')
415 // Return the options
416 return $options;
420 * Get all of the blog options that relate to the passed user.
422 * If no user is passed the current user is assumed.
424 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
425 * @param stdClass $user
426 * @return array The array of options for the requested user
428 function blog_get_options_for_user(stdClass $user=null) {
429 global $CFG, $USER;
430 // Cache
431 static $useroptions = array();
433 $options = array();
434 // Blogs must be enabled and the user must be logged in
435 if (!blog_is_enabled_for_user()) {
436 return $options;
439 // Sort out the user var
440 if ($user === null || $user->id == $USER->id) {
441 $user = $USER;
442 $iscurrentuser = true;
443 } else {
444 $iscurrentuser = false;
447 // If we've already generated serve from the cache
448 if (array_key_exists($user->id, $useroptions)) {
449 return $useroptions[$user->id];
452 $sitecontext = context_system::instance();
453 $canview = has_capability('moodle/blog:view', $sitecontext);
455 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
456 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
457 $options['userentries'] = array(
458 'string' => get_string('viewuserentries', 'blog', fullname($user)),
459 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
461 } else {
462 // It's the current user
463 if ($canview) {
464 // We can view our own blogs .... BIG surprise
465 $options['view'] = array(
466 'string' => get_string('viewallmyentries', 'blog'),
467 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
470 if (has_capability('moodle/blog:create', $sitecontext)) {
471 // We can add to our own blog
472 $options['add'] = array(
473 'string' => get_string('addnewentry', 'blog'),
474 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
478 if ($canview && $CFG->enablerssfeeds) {
479 $options['rss'] = array(
480 'string' => get_string('rssfeed', 'blog'),
481 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
485 // Cache the options
486 $useroptions[$user->id] = $options;
487 // Return the options
488 return $options;
492 * Get the blog options that relate to the given course for the given user.
494 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
495 * @param stdClass $course The course to load options for
496 * @param stdClass $user The user to load options for null == current user
497 * @return array The array of options
499 function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
500 global $CFG, $USER;
501 // Cache
502 static $courseoptions = array();
504 $options = array();
506 // User must be logged in and blogs must be enabled
507 if (!blog_is_enabled_for_user()) {
508 return $options;
511 // Check that the user can associate with the course
512 $sitecontext = context_system::instance();
513 $coursecontext = context_course::instance($course->id);
514 if (!has_capability('moodle/blog:associatecourse', $coursecontext)) {
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 $canparticipate = (is_enrolled($coursecontext) or is_viewing($coursecontext));
531 if (has_capability('moodle/blog:view', $coursecontext)) {
532 // We can view!
533 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
534 // View entries about this course
535 $options['courseview'] = array(
536 'string' => get_string('viewcourseblogs', 'blog'),
537 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id))
540 // View MY entries about this course
541 $options['courseviewmine'] = array(
542 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
543 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$USER->id))
545 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
546 // View the provided users entries about this course
547 $options['courseviewuser'] = array(
548 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
549 'link' => new moodle_url('/blog/index.php', array('courseid'=>$course->id, 'userid'=>$user->id))
554 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
555 // We can blog about this course
556 $options['courseadd'] = array(
557 'string' => get_string('blogaboutthiscourse', 'blog'),
558 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'courseid'=>$course->id))
563 // Cache the options for this course
564 $courseoptions[$key] = $options;
565 // Return the options
566 return $options;
570 * Get the blog options relating to the given module for the given user
572 * @staticvar array $moduleoptions Cache
573 * @param stdClass|cm_info $module The module to get options for
574 * @param stdClass $user The user to get options for null == currentuser
575 * @return array
577 function blog_get_options_for_module($module, $user=null) {
578 global $CFG, $USER;
579 // Cache
580 static $moduleoptions = array();
582 $options = array();
583 // User must be logged in, blogs must be enabled
584 if (!blog_is_enabled_for_user()) {
585 return $options;
588 // Check the user can associate with the module
589 $modcontext = context_module::instance($module->id);
590 $sitecontext = context_system::instance();
591 if (!has_capability('moodle/blog:associatemodule', $modcontext)) {
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 $canparticipate = (is_enrolled($modcontext) or is_viewing($modcontext));
609 if (has_capability('moodle/blog:view', $modcontext)) {
610 // Save correct module name for later usage.
611 $modulename = get_string('modulename', $module->modname);
613 // We can view!
614 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
615 // View all entries about this module
616 $a = new stdClass;
617 $a->type = $modulename;
618 $options['moduleview'] = array(
619 'string' => get_string('viewallmodentries', 'blog', $a),
620 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
623 // View MY entries about this module
624 $options['moduleviewmine'] = array(
625 'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
626 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
628 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
629 // View the given users entries about this module
630 $a = new stdClass;
631 $a->mod = $modulename;
632 $a->user = fullname($user);
633 $options['moduleviewuser'] = array(
634 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
635 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
640 if (has_capability('moodle/blog:create', $sitecontext) and $canparticipate) {
641 // The user can blog about this module
642 $options['moduleadd'] = array(
643 'string' => get_string('blogaboutthismodule', 'blog', $modulename),
644 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
647 // Cache the options
648 $moduleoptions[$key] = $options;
649 // Return the options
650 return $options;
654 * This function encapsulates all the logic behind the complex
655 * navigation, titles and headings of the blog listing page, depending
656 * on URL params. It looks at URL params and at the current context level.
657 * It builds and returns an array containing:
659 * 1. heading: The heading displayed above the blog entries
660 * 2. stradd: The text to be used as the "Add entry" link
661 * 3. strview: The text to be used as the "View entries" link
662 * 4. url: The moodle_url object used as the base for add and view links
663 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
665 * All other variables are set directly in $PAGE
667 * It uses the current URL to build these variables.
668 * A number of mutually exclusive use cases are used to structure this function.
670 * @return array
672 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
673 global $CFG, $PAGE, $DB, $USER;
675 $id = optional_param('id', null, PARAM_INT);
676 $tag = optional_param('tag', null, PARAM_NOTAGS);
677 $tagid = optional_param('tagid', $tagid, PARAM_INT);
678 $userid = optional_param('userid', $userid, PARAM_INT);
679 $modid = optional_param('modid', null, PARAM_INT);
680 $entryid = optional_param('entryid', null, PARAM_INT);
681 $groupid = optional_param('groupid', $groupid, PARAM_INT);
682 $courseid = optional_param('courseid', $courseid, PARAM_INT);
683 $search = optional_param('search', null, PARAM_RAW);
684 $action = optional_param('action', null, PARAM_ALPHA);
685 $confirm = optional_param('confirm', false, PARAM_BOOL);
687 // Ignore userid when action == add
688 if ($action == 'add' && $userid) {
689 unset($userid);
690 $PAGE->url->remove_params(array('userid'));
691 } else if ($action == 'add' && $entryid) {
692 unset($entryid);
693 $PAGE->url->remove_params(array('entryid'));
696 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
698 $blogurl = new moodle_url('/blog/index.php');
700 // If the title is not yet set, it's likely that the context isn't set either, so skip this part
701 $pagetitle = $PAGE->title;
702 if (!empty($pagetitle)) {
703 $contexturl = blog_get_context_url();
705 // Look at the context URL, it may have additional params that are not in the current URL
706 if (!$blogurl->compare($contexturl)) {
707 $blogurl = $contexturl;
708 if (empty($courseid)) {
709 $courseid = $blogurl->param('courseid');
711 if (empty($modid)) {
712 $modid = $blogurl->param('modid');
717 $headers['stradd'] = get_string('addnewentry', 'blog');
718 $headers['strview'] = null;
720 $site = $DB->get_record('course', array('id' => SITEID));
721 $sitecontext = context_system::instance();
722 // Common Lang strings
723 $strparticipants = get_string("participants");
724 $strblogentries = get_string("blogentries", 'blog');
726 // Prepare record objects as needed
727 if (!empty($courseid)) {
728 $headers['filters']['course'] = $courseid;
729 $course = $DB->get_record('course', array('id' => $courseid));
732 if (!empty($userid)) {
733 $headers['filters']['user'] = $userid;
734 $user = $DB->get_record('user', array('id' => $userid));
737 if (!empty($groupid)) { // groupid always overrides courseid
738 $headers['filters']['group'] = $groupid;
739 $group = $DB->get_record('groups', array('id' => $groupid));
740 $course = $DB->get_record('course', array('id' => $group->courseid));
743 $PAGE->set_pagelayout('standard');
745 // modid always overrides courseid, so the $course object may be reset here
746 if (!empty($modid) && $CFG->useblogassociations) {
748 $headers['filters']['module'] = $modid;
749 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
750 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
751 $course = $DB->get_record('course', array('id' => $courseid));
752 $cm = $DB->get_record('course_modules', array('id' => $modid));
753 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
754 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
755 $a = new stdClass();
756 $a->type = get_string('modulename', $cm->modname);
757 $PAGE->set_cm($cm, $course);
758 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
759 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
762 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
763 // Note: if action is set to 'add' or 'edit', we do this at the end
764 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
765 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
766 $PAGE->navbar->add($strblogentries, $blogurl);
767 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
768 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
769 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
770 // $headers['strview'] = get_string('viewsiteentries', 'blog');
773 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
774 if (!empty($entryid)) {
775 $headers['filters']['entry'] = $entryid;
776 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
777 $user = $DB->get_record_sql($sql, array($entryid));
778 $entry = $DB->get_record('post', array('id' => $entryid));
780 $blogurl->param('userid', $user->id);
782 if (!empty($course)) {
783 $mycourseid = $course->id;
784 $blogurl->param('courseid', $mycourseid);
785 } else {
786 $mycourseid = $site->id;
788 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
790 $PAGE->navbar->add($strblogentries, $blogurl);
792 $blogurl->remove_params('userid');
793 $PAGE->navbar->add($entry->subject, $blogurl);
794 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
795 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
796 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
798 // We ignore tag and search params
799 if (empty($action) || !$CFG->useblogassociations) {
800 $headers['url'] = $blogurl;
801 return $headers;
805 // Case 3: A user's blog entries
806 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
807 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
808 $blogurl->param('userid', $userid);
809 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
810 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
811 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
812 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
814 } else
816 // Case 4: No blog associations, no userid
817 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
818 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
819 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
820 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
821 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
822 } else
824 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
825 if (!empty($userid) && !empty($modid) && empty($entryid)) {
826 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
827 $blogurl->param('userid', $userid);
828 $blogurl->param('modid', $modid);
830 // Course module navigation is handled by build_navigation as the second param
831 $headers['cm'] = $cm;
832 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
833 $PAGE->navbar->add($strblogentries, $blogurl);
835 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
836 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
838 $a = new stdClass();
839 $a->user = fullname($user);
840 $a->mod = $cm->name;
841 $a->type = get_string('modulename', $cm->modname);
842 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
843 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
844 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
845 } else
847 // Case 6: Blog entries associated with a course by a specific user
848 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
849 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
850 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
851 $blogurl->param('userid', $userid);
852 $blogurl->param('courseid', $courseid);
854 $PAGE->navbar->add($strblogentries, $blogurl);
856 $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
857 $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
859 $a = new stdClass();
860 $a->user = fullname($user);
861 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
862 $a->type = get_string('course');
863 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
864 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
865 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
867 // Remove the userid from the URL to inform the blog_menu block correctly
868 $blogurl->remove_params(array('userid'));
869 } else
871 // Case 7: Blog entries by members of a group, associated with that group's course
872 if (!empty($groupid) && empty($modid) && empty($entryid)) {
873 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
874 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
875 $blogurl->param('courseid', $course->id);
877 $PAGE->navbar->add($strblogentries, $blogurl);
878 $blogurl->remove_params(array('courseid'));
879 $blogurl->param('groupid', $groupid);
880 $PAGE->navbar->add($group->name, $blogurl);
882 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
883 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
885 $a = new stdClass();
886 $a->group = $group->name;
887 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
888 $a->type = get_string('course');
889 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
890 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
891 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
892 } else
894 // Case 8: Blog entries by members of a group, associated with an activity in that course
895 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
896 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
897 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
898 $headers['cm'] = $cm;
899 $blogurl->param('modid', $modid);
900 $PAGE->navbar->add($strblogentries, $blogurl);
902 $blogurl->param('groupid', $groupid);
903 $PAGE->navbar->add($group->name, $blogurl);
905 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
906 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
908 $a = new stdClass();
909 $a->group = $group->name;
910 $a->mod = $cm->name;
911 $a->type = get_string('modulename', $cm->modname);
912 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
913 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
914 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
916 } else
918 // Case 9: All blog entries associated with an activity
919 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
920 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
921 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
922 $PAGE->set_cm($cm, $course);
923 $blogurl->param('modid', $modid);
924 $PAGE->navbar->add($strblogentries, $blogurl);
925 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
926 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
927 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
928 $a = new stdClass();
929 $a->type = get_string('modulename', $cm->modname);
930 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
931 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
932 } else
934 // Case 10: All blog entries associated with a course
935 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
936 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
937 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
938 $blogurl->param('courseid', $courseid);
939 $PAGE->navbar->add($strblogentries, $blogurl);
940 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
941 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
942 $a = new stdClass();
943 $a->type = get_string('course');
944 $headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
945 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
946 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
947 $blogurl->remove_params(array('userid'));
950 if (!in_array($action, array('edit', 'add'))) {
951 // Append Tag info
952 if (!empty($tagid)) {
953 $headers['filters']['tag'] = $tagid;
954 $blogurl->param('tagid', $tagid);
955 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
956 $PAGE->navbar->add($tagrec->name, $blogurl);
957 } elseif (!empty($tag)) {
958 $blogurl->param('tag', $tag);
959 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
962 // Append Search info
963 if (!empty($search)) {
964 $headers['filters']['search'] = $search;
965 $blogurl->param('search', $search);
966 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
970 // Append edit mode info
971 if (!empty($action) && $action == 'add') {
973 } else if (!empty($action) && $action == 'edit') {
974 $PAGE->navbar->add(get_string('editentry', 'blog'));
977 if (empty($headers['url'])) {
978 $headers['url'] = $blogurl;
980 return $headers;
984 * Shortcut function for getting a count of blog entries associated with a course or a module
985 * @param int $courseid The ID of the course
986 * @param int $cmid The ID of the course_modules
987 * @return string The number of associated entries
989 function blog_get_associated_count($courseid, $cmid=null) {
990 global $DB;
991 $context = context_course::instance($courseid);
992 if ($cmid) {
993 $context = context_module::instance($cmid);
995 return $DB->count_records('blog_association', array('contextid' => $context->id));
999 * Running addtional permission check on plugin, for example, plugins
1000 * may have switch to turn on/off comments option, this callback will
1001 * affect UI display, not like pluginname_comment_validate only throw
1002 * exceptions.
1003 * Capability check has been done in comment->check_permissions(), we
1004 * don't need to do it again here.
1006 * @package core_blog
1007 * @category comment
1009 * @param stdClass $comment_param {
1010 * context => context the context object
1011 * courseid => int course id
1012 * cm => stdClass course module object
1013 * commentarea => string comment area
1014 * itemid => int itemid
1016 * @return array
1018 function blog_comment_permissions($comment_param) {
1019 return array('post'=>true, 'view'=>true);
1023 * Validate comment parameter before perform other comments actions
1025 * @package core_blog
1026 * @category comment
1028 * @param stdClass $comment {
1029 * context => context the context object
1030 * courseid => int course id
1031 * cm => stdClass course module object
1032 * commentarea => string comment area
1033 * itemid => int itemid
1035 * @return boolean
1037 function blog_comment_validate($comment_param) {
1038 global $DB;
1039 // validate comment itemid
1040 if (!$entry = $DB->get_record('post', array('id'=>$comment_param->itemid))) {
1041 throw new comment_exception('invalidcommentitemid');
1043 // validate comment area
1044 if ($comment_param->commentarea != 'format_blog') {
1045 throw new comment_exception('invalidcommentarea');
1047 // validation for comment deletion
1048 if (!empty($comment_param->commentid)) {
1049 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
1050 if ($record->commentarea != 'format_blog') {
1051 throw new comment_exception('invalidcommentarea');
1053 if ($record->contextid != $comment_param->context->id) {
1054 throw new comment_exception('invalidcontext');
1056 if ($record->itemid != $comment_param->itemid) {
1057 throw new comment_exception('invalidcommentitemid');
1059 } else {
1060 throw new comment_exception('invalidcommentid');
1063 return true;
1067 * Return a list of page types
1068 * @param string $pagetype current page type
1069 * @param stdClass $parentcontext Block's parent context
1070 * @param stdClass $currentcontext Current context of block
1072 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1073 return array(
1074 '*'=>get_string('page-x', 'pagetype'),
1075 'blog-*'=>get_string('page-blog-x', 'blog'),
1076 'blog-index'=>get_string('page-blog-index', 'blog'),
1077 'blog-edit'=>get_string('page-blog-edit', 'blog')