2 // This file is part of Moodle - http://moodle.org/
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 * Core global functions for Blog.
22 * @copyright 2009 Nicolas Connault
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 defined('MOODLE_INTERNAL') ||
die();
29 * Library of functions and constants for blog
31 require_once($CFG->dirroot
.'/blog/rsslib.php');
34 * User can edit a blog entry if this is their own blog entry and they have
35 * the capability moodle/blog:create, or if they have the capability
36 * moodle/blog:manageentries.
38 * This also applies to deleting of entries.
40 function blog_user_can_edit_entry($blogentry) {
43 $sitecontext = context_system
::instance();
45 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
46 return true; // Can edit any blog entry.
49 if ($blogentry->userid
== $USER->id
&& has_capability('moodle/blog:create', $sitecontext)) {
50 return true; // Can edit own when having blog:create capability.
58 * Checks to see if a user can view the blogs of another user.
59 * Only blog level is checked here, the capabilities are enforced
62 function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
63 global $CFG, $USER, $DB;
65 if (empty($CFG->enableblogs
)) {
66 return false; // Blog system disabled.
69 if (isloggedin() && $USER->id
== $targetuserid) {
70 return true; // Can view own entries in any case.
73 $sitecontext = context_system
::instance();
74 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
75 return true; // Can manage all entries.
78 // If blog is in draft state, then make sure user have proper capability.
79 if ($blogentry && $blogentry->publishstate
== 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
80 return false; // Can not view draft of others.
83 // If blog entry is not public, make sure user is logged in.
84 if ($blogentry && $blogentry->publishstate
!= 'public' && !isloggedin()) {
88 // If blogentry is not passed or all above checks pass, then check capability based on system config.
89 switch ($CFG->bloglevel
) {
90 case BLOG_GLOBAL_LEVEL
:
95 if (isloggedin()) { // Not logged in viewers forbidden.
101 case BLOG_USER_LEVEL
:
103 // If user is viewing other user blog, then user should have user:readuserblogs capability.
104 $personalcontext = context_user
::instance($targetuserid);
105 return has_capability('moodle/user:readuserblogs', $personalcontext);
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) {
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) {
134 $context = context_course
::instance($courseid);
135 $DB->delete_records('blog_association', array('contextid' => $context->id
));
139 * Remove module associated blogs and blog tag instances.
141 * @param int $modcontextid Module context ID.
143 function blog_remove_associations_for_module($modcontextid) {
146 if (!empty($assocblogids = $DB->get_fieldset_select('blog_association', 'blogid',
147 'contextid = :contextid', ['contextid' => $modcontextid]))) {
148 list($sql, $params) = $DB->get_in_or_equal($assocblogids, SQL_PARAMS_NAMED
);
150 $DB->delete_records_select('tag_instance', "itemid $sql", $params);
151 $DB->delete_records_select('post', "id $sql AND module = :module",
152 array_merge($params, ['module' => 'blog']));
153 $DB->delete_records('blog_association', ['contextid' => $modcontextid]);
158 * Given a record in the {blog_external} table, checks the blog's URL
159 * for new entries not yet copied into Moodle.
160 * Also attempts to identify and remove deleted blog entries
162 * @param object $externalblog
163 * @return boolean False if the Feed is invalid
165 function blog_sync_external_entries($externalblog) {
167 require_once($CFG->libdir
. '/simplepie/moodle_simplepie.php');
169 $rss = new moodle_simplepie();
170 $rssfile = $rss->registry
->create('File', array($externalblog->url
));
171 $filetest = $rss->registry
->create('Locator', array($rssfile));
173 if (!$filetest->is_feed($rssfile)) {
174 $externalblog->failedlastsync
= 1;
175 $DB->update_record('blog_external', $externalblog);
177 } else if (!empty($externalblog->failedlastsync
)) {
178 $externalblog->failedlastsync
= 0;
179 $DB->update_record('blog_external', $externalblog);
182 $rss->set_feed_url($externalblog->url
);
185 if (empty($rss->data
)) {
188 // Used to identify blog posts that have been deleted from the source feed.
189 $oldesttimestamp = null;
190 $uniquehashes = array();
192 foreach ($rss->get_items() as $entry) {
193 // If filtertags are defined, use them to filter the entries by RSS category.
194 if (!empty($externalblog->filtertags
)) {
195 $containsfiltertag = false;
196 $categories = $entry->get_categories();
197 $filtertags = explode(',', $externalblog->filtertags
);
198 $filtertags = array_map('trim', $filtertags);
199 $filtertags = array_map('strtolower', $filtertags);
201 if (!empty($categories)) {
202 foreach ($categories as $category) {
203 if (in_array(trim(strtolower($category->term
)), $filtertags)) {
204 $containsfiltertag = true;
209 if (!$containsfiltertag) {
214 $uniquehashes[] = $entry->get_permalink();
216 $newentry = new stdClass();
217 $newentry->userid
= $externalblog->userid
;
218 $newentry->module
= 'blog_external';
219 $newentry->content
= $externalblog->id
;
220 $newentry->uniquehash
= $entry->get_permalink();
221 $newentry->publishstate
= 'site';
222 $newentry->format
= FORMAT_HTML
;
223 // Clean subject of html, just in case.
224 $newentry->subject
= clean_param($entry->get_title(), PARAM_TEXT
);
225 // Observe 128 max chars in DB.
226 // TODO: +1 to raise this to 255.
227 if (core_text
::strlen($newentry->subject
) > 128) {
228 $newentry->subject
= core_text
::substr($newentry->subject
, 0, 125) . '...';
230 $newentry->summary
= $entry->get_description();
232 // Used to decide whether to insert or update.
233 // Uses enty permalink plus creation date if available.
234 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
236 // Our DB doesnt allow null creation or modified timestamps so check the external blog supplied one.
237 $entrydate = $entry->get_date('U');
238 if (!empty($entrydate)) {
239 $existingpostconditions['created'] = $entrydate;
242 // The post ID or false if post not found in DB.
243 $postid = $DB->get_field('post', 'id', $existingpostconditions);
246 if (empty($entrydate)) {
249 $timestamp = $entrydate;
252 // Only set created if its a new post so we retain the original creation timestamp if the post is edited.
253 if ($postid === false) {
254 $newentry->created
= $timestamp;
256 $newentry->lastmodified
= $timestamp;
258 if (empty($oldesttimestamp) ||
$timestamp < $oldesttimestamp) {
259 // Found an older post.
260 $oldesttimestamp = $timestamp;
263 if (core_text
::strlen($newentry->uniquehash
) > 255) {
264 // The URL for this item is too long for the field. Rather than add
265 // the entry without the link we will skip straight over it.
266 // RSS spec says recommended length 500, we use 255.
267 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER
);
271 if ($postid === false) {
272 $id = $DB->insert_record('post', $newentry);
275 if ($tags = core_tag_tag
::get_item_tags_array('core', 'blog_external', $externalblog->id
)) {
276 core_tag_tag
::set_item_tags('core', 'post', $id, context_user
::instance($externalblog->userid
), $tags);
279 $newentry->id
= $postid;
280 $DB->update_record('post', $newentry);
284 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
285 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
286 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
287 $sql = "SELECT id, uniquehash
289 WHERE module = 'blog_external'
290 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
292 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id
, 'ts' => $oldesttimestamp));
295 foreach ($dbposts as $dbpost) {
296 if ( !in_array($dbpost->uniquehash
, $uniquehashes) ) {
297 $todelete[] = $dbpost->id
;
300 $DB->delete_records_list('post', 'id', $todelete);
302 $DB->update_record('blog_external', array('id' => $externalblog->id
, 'timefetched' => time()));
306 * Given an external blog object, deletes all related blog entries from the post table.
307 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
308 * @param object $externablog
310 function blog_delete_external_entries($externalblog) {
312 require_capability('moodle/blog:manageexternal', context_system
::instance());
313 $DB->delete_records_select('post',
314 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
315 array($externalblog->id
));
319 * This function checks that blogs are enabled, and that the user can see blogs at all
322 function blog_is_enabled_for_user() {
324 return (!empty($CFG->enableblogs
) && (isloggedin() ||
($CFG->bloglevel
== BLOG_GLOBAL_LEVEL
)));
328 * This function gets all of the options available for the current user in respect
331 * It loads the following if applicable:
332 * - Module options {@see blog_get_options_for_module}
333 * - Course options {@see blog_get_options_for_course}
334 * - User specific options {@see blog_get_options_for_user}
335 * - General options (BLOG_LEVEL_GLOBAL)
337 * @param moodle_page $page The page to load for (normally $PAGE)
338 * @param stdClass $userid Load for a specific user
339 * @return array An array of options organised by type.
341 function blog_get_all_options(moodle_page
$page, stdClass
$userid = null) {
342 global $CFG, $DB, $USER;
346 // If blogs are enabled and the user is logged in and not a guest.
347 if (blog_is_enabled_for_user()) {
348 // If the context is the user then assume we want to load for the users context.
349 if (is_null($userid) && $page->context
->contextlevel
== CONTEXT_USER
) {
350 $userid = $page->context
->instanceid
;
352 // Check the userid var.
353 if (!is_null($userid) && $userid !== $USER->id
) {
354 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
355 $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST
);
360 if ($CFG->useblogassociations
&& $page->cm
!== null) {
361 // Load for the module associated with the page.
362 $options[CONTEXT_MODULE
] = blog_get_options_for_module($page->cm
, $user);
363 } else if ($CFG->useblogassociations
&& $page->course
->id
!= SITEID
) {
364 // Load the options for the course associated with the page.
365 $options[CONTEXT_COURSE
] = blog_get_options_for_course($page->course
, $user);
368 // Get the options for the user.
369 if ($user !== null and !isguestuser($user)) {
370 // Load for the requested user.
371 $options[CONTEXT_USER +
1] = blog_get_options_for_user($user);
373 // Load for the current user.
374 if (isloggedin() and !isguestuser()) {
375 $options[CONTEXT_USER
] = blog_get_options_for_user();
379 // If blog level is global then display a link to view all site entries.
380 if (!empty($CFG->enableblogs
)
381 && $CFG->bloglevel
>= BLOG_GLOBAL_LEVEL
382 && has_capability('moodle/blog:view', context_system
::instance())) {
384 $options[CONTEXT_SYSTEM
] = array('viewsite' => array(
385 'string' => get_string('viewsiteentries', 'blog'),
386 'link' => new moodle_url('/blog/index.php')
390 // Return the options.
395 * Get all of the blog options that relate to the passed user.
397 * If no user is passed the current user is assumed.
399 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
400 * @param stdClass $user
401 * @return array The array of options for the requested user
403 function blog_get_options_for_user(stdClass
$user=null) {
406 static $useroptions = array();
409 // Blogs must be enabled and the user must be logged in.
410 if (!blog_is_enabled_for_user()) {
414 // Sort out the user var.
415 if ($user === null ||
$user->id
== $USER->id
) {
417 $iscurrentuser = true;
419 $iscurrentuser = false;
422 // If we've already generated serve from the cache.
423 if (array_key_exists($user->id
, $useroptions)) {
424 return $useroptions[$user->id
];
427 $sitecontext = context_system
::instance();
428 $canview = has_capability('moodle/blog:view', $sitecontext);
430 if (!$iscurrentuser && $canview && ($CFG->bloglevel
>= BLOG_SITE_LEVEL
)) {
431 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL.
432 $options['userentries'] = array(
433 'string' => get_string('viewuserentries', 'blog', fullname($user)),
434 'link' => new moodle_url('/blog/index.php', array('userid' => $user->id
))
437 // It's the current user.
439 // We can view our own blogs .... BIG surprise.
440 $options['view'] = array(
441 'string' => get_string('blogentries', 'blog'),
442 'link' => new moodle_url('/blog/index.php', array('userid' => $USER->id
))
445 if (has_capability('moodle/blog:create', $sitecontext)) {
446 // We can add to our own blog.
447 $options['add'] = array(
448 'string' => get_string('addnewentry', 'blog'),
449 'link' => new moodle_url('/blog/edit.php', array('action' => 'add'))
453 if ($canview && $CFG->enablerssfeeds
) {
454 $options['rss'] = array(
455 'string' => get_string('rssfeed', 'blog'),
456 'link' => new moodle_url(rss_get_url($sitecontext->id
, $USER->id
, 'blog', 'user/'.$user->id
))
460 // Cache the options.
461 $useroptions[$user->id
] = $options;
462 // Return the options.
467 * Get the blog options that relate to the given course for the given user.
469 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
470 * @param stdClass $course The course to load options for
471 * @param stdClass $user The user to load options for null == current user
472 * @return array The array of options
474 function blog_get_options_for_course(stdClass
$course, stdClass
$user=null) {
477 static $courseoptions = array();
481 // User must be logged in and blogs must be enabled.
482 if (!blog_is_enabled_for_user()) {
486 // Check that the user can associate with the course.
487 $sitecontext = context_system
::instance();
488 // Generate the cache key.
489 $key = $course->id
.':';
495 // Serve from the cache if we've already generated for this course.
496 if (array_key_exists($key, $courseoptions)) {
497 return $courseoptions[$key];
500 if (has_capability('moodle/blog:view', $sitecontext)) {
502 if ($CFG->bloglevel
>= BLOG_SITE_LEVEL
) {
503 // View entries about this course.
504 $options['courseview'] = array(
505 'string' => get_string('viewcourseblogs', 'blog'),
506 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id
))
509 // View MY entries about this course.
510 $options['courseviewmine'] = array(
511 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
512 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id
, 'userid' => $USER->id
))
514 if (!empty($user) && ($CFG->bloglevel
>= BLOG_SITE_LEVEL
)) {
515 // View the provided users entries about this course.
516 $options['courseviewuser'] = array(
517 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
518 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id
, 'userid' => $user->id
))
523 if (has_capability('moodle/blog:create', $sitecontext)) {
524 // We can blog about this course.
525 $options['courseadd'] = array(
526 'string' => get_string('blogaboutthiscourse', 'blog'),
527 'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'courseid' => $course->id
))
531 // Cache the options for this course.
532 $courseoptions[$key] = $options;
533 // Return the options.
538 * Get the blog options relating to the given module for the given user
540 * @staticvar array $moduleoptions Cache
541 * @param stdClass|cm_info $module The module to get options for
542 * @param stdClass $user The user to get options for null == currentuser
545 function blog_get_options_for_module($module, $user=null) {
548 static $moduleoptions = array();
551 // User must be logged in, blogs must be enabled.
552 if (!blog_is_enabled_for_user()) {
556 $sitecontext = context_system
::instance();
558 // Generate the cache key.
559 $key = $module->id
.':';
565 if (array_key_exists($key, $moduleoptions)) {
566 // Serve from the cache so we don't have to regenerate.
567 return $moduleoptions[$key];
570 if (has_capability('moodle/blog:view', $sitecontext)) {
571 // Save correct module name for later usage.
572 $modulename = get_string('modulename', $module->modname
);
575 if ($CFG->bloglevel
>= BLOG_SITE_LEVEL
) {
576 // View all entries about this module.
578 $a->type
= $modulename;
579 $options['moduleview'] = array(
580 'string' => get_string('viewallmodentries', 'blog', $a),
581 'link' => new moodle_url('/blog/index.php', array('modid' => $module->id
))
584 // View MY entries about this module.
585 $options['moduleviewmine'] = array(
586 'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
587 'link' => new moodle_url('/blog/index.php', array('modid' => $module->id
, 'userid' => $USER->id
))
589 if (!empty($user) && ($CFG->bloglevel
>= BLOG_SITE_LEVEL
)) {
590 // View the given users entries about this module.
592 $a->mod
= $modulename;
593 $a->user
= fullname($user);
594 $options['moduleviewuser'] = array(
595 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
596 'link' => new moodle_url('/blog/index.php', array('modid' => $module->id
, 'userid' => $user->id
))
601 if (has_capability('moodle/blog:create', $sitecontext)) {
602 // The user can blog about this module.
603 $options['moduleadd'] = array(
604 'string' => get_string('blogaboutthismodule', 'blog', $modulename),
605 'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'modid' => $module->id
))
608 // Cache the options.
609 $moduleoptions[$key] = $options;
610 // Return the options.
615 * This function encapsulates all the logic behind the complex
616 * navigation, titles and headings of the blog listing page, depending
617 * on URL params. It looks at URL params and at the current context level.
618 * It builds and returns an array containing:
620 * 1. heading: The heading displayed above the blog entries
621 * 2. stradd: The text to be used as the "Add entry" link
622 * 3. strview: The text to be used as the "View entries" link
623 * 4. url: The moodle_url object used as the base for add and view links
624 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
626 * All other variables are set directly in $PAGE
628 * It uses the current URL to build these variables.
629 * A number of mutually exclusive use cases are used to structure this function.
631 * @param int $courseid course id the the blog is associated to (can be null).
632 * @param int $groupid group id to filter blogs I can see (can be null)
633 * @param int $userid blog author id (can be null)
634 * @param int $tagid tag id to filter (can be null)
635 * @param string $tag tag name to filter (can be null)
636 * @param int $modid module id the blog is associated to (can be null).
637 * @param int $entryid blog entry id to filter(can be null)
638 * @param string $search string to search (can be null)
641 function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null, $tag=null, $modid=null, $entryid=null,
643 global $CFG, $PAGE, $DB, $USER;
645 $id = optional_param('id', null, PARAM_INT
);
646 $tag = optional_param('tag', $tag, PARAM_NOTAGS
);
647 $tagid = optional_param('tagid', $tagid, PARAM_INT
);
648 $userid = optional_param('userid', $userid, PARAM_INT
);
649 $modid = optional_param('modid', $modid, PARAM_INT
);
650 $entryid = optional_param('entryid', $entryid, PARAM_INT
);
651 $groupid = optional_param('groupid', $groupid, PARAM_INT
);
652 $courseid = optional_param('courseid', $courseid, PARAM_INT
);
653 $search = optional_param('search', $search, PARAM_RAW
);
654 $action = optional_param('action', null, PARAM_ALPHA
);
655 $confirm = optional_param('confirm', false, PARAM_BOOL
);
657 // Ignore userid when action == add.
658 if ($action == 'add' && $userid) {
660 $PAGE->url
->remove_params(array('userid'));
661 } else if ($action == 'add' && $entryid) {
663 $PAGE->url
->remove_params(array('entryid'));
666 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
668 $blogurl = new moodle_url('/blog/index.php');
670 $headers['stradd'] = get_string('addnewentry', 'blog');
671 $headers['strview'] = null;
673 $site = $DB->get_record('course', array('id' => SITEID
));
674 $sitecontext = context_system
::instance();
675 // Common Lang strings.
676 $strparticipants = get_string("participants");
677 $strblogentries = get_string("blogentries", 'blog');
679 // Prepare record objects as needed.
680 if (!empty($courseid)) {
681 $headers['filters']['course'] = $courseid;
682 $course = $DB->get_record('course', array('id' => $courseid));
685 if (!empty($userid)) {
686 $headers['filters']['user'] = $userid;
687 $user = $DB->get_record('user', array('id' => $userid));
690 if (!empty($groupid)) { // The groupid always overrides courseid.
691 $headers['filters']['group'] = $groupid;
692 $group = $DB->get_record('groups', array('id' => $groupid));
693 $course = $DB->get_record('course', array('id' => $group->courseid
));
696 $PAGE->set_pagelayout('standard');
698 // The modid always overrides courseid, so the $course object may be reset here.
699 if (!empty($modid) && $CFG->useblogassociations
) {
701 $headers['filters']['module'] = $modid;
702 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case.
703 $courseid = $DB->get_field('course_modules', 'course', array('id' => $modid));
704 $course = $DB->get_record('course', array('id' => $courseid));
705 $cm = $DB->get_record('course_modules', array('id' => $modid));
706 $cm->modname
= $DB->get_field('modules', 'name', array('id' => $cm->module
));
707 $cm->name
= $DB->get_field($cm->modname
, 'name', array('id' => $cm->instance
));
709 $a->type
= get_string('modulename', $cm->modname
);
710 $PAGE->set_cm($cm, $course);
711 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
712 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
715 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
716 // Note: if action is set to 'add' or 'edit', we do this at the end.
717 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
718 $PAGE->navbar
->add($strblogentries, $blogurl);
719 $PAGE->set_title($site->fullname
);
720 $PAGE->set_heading($site->fullname
);
721 $headers['heading'] = get_string('siteblogheading', 'blog');
724 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information.
725 if (!empty($entryid)) {
726 $headers['filters']['entry'] = $entryid;
727 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
728 $user = $DB->get_record_sql($sql, array($entryid));
729 $entry = $DB->get_record('post', array('id' => $entryid));
731 $blogurl->param('userid', $user->id
);
733 if (!empty($course)) {
734 $mycourseid = $course->id
;
735 $blogurl->param('courseid', $mycourseid);
737 $mycourseid = $site->id
;
739 $shortname = format_string($site->shortname
, true, array('context' => context_course
::instance(SITEID
)));
741 $PAGE->navbar
->add($strblogentries, $blogurl);
743 $blogurl->remove_params('userid');
744 $PAGE->navbar
->add($entry->subject
, $blogurl);
745 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
746 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
747 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
749 // We ignore tag and search params.
750 if (empty($action) ||
!$CFG->useblogassociations
) {
751 $headers['url'] = $blogurl;
756 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) ||
!$CFG->useblogassociations
)) {
757 // Case 3: A user's blog entries.
759 $shortname = format_string($site->shortname
, true, array('context' => context_course
::instance(SITEID
)));
760 $blogurl->param('userid', $userid);
761 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
762 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
763 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
764 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
766 } else if (!$CFG->useblogassociations
&& empty($userid) && !in_array($action, array('edit', 'add'))) {
767 // Case 4: No blog associations, no userid.
769 $PAGE->set_title($site->fullname
);
770 $PAGE->set_heading($site->fullname
);
771 $headers['heading'] = get_string('siteblogheading', 'blog');
772 } else if (!empty($userid) && !empty($modid) && empty($entryid)) {
773 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored).
775 $shortname = format_string($site->shortname
, true, array('context' => context_course
::instance(SITEID
)));
776 $blogurl->param('userid', $userid);
777 $blogurl->param('modid', $modid);
779 // Course module navigation is handled by build_navigation as the second param.
780 $headers['cm'] = $cm;
781 $PAGE->navbar
->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
782 $PAGE->navbar
->add($strblogentries, $blogurl);
784 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
785 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
788 $a->user
= fullname($user);
790 $a->type
= get_string('modulename', $cm->modname
);
791 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
792 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
793 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
794 } else if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
795 // Case 6: Blog entries associated with a course by a specific user.
797 $blogurl->param('userid', $userid);
798 $blogurl->param('courseid', $courseid);
800 $PAGE->set_title($course->fullname
);
801 $PAGE->set_heading($course->fullname
);
804 $a->user
= fullname($user);
805 $a->course
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
806 $a->type
= get_string('course');
807 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
808 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
809 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
811 // Remove the userid from the URL to inform the blog_menu block correctly.
812 $blogurl->remove_params(array('userid'));
813 } else if (!empty($groupid) && empty($modid) && empty($entryid)) {
814 // Case 7: Blog entries by members of a group, associated with that group's course.
816 $blogurl->param('courseid', $course->id
);
818 $PAGE->navbar
->add($strblogentries, $blogurl);
819 $blogurl->remove_params(array('courseid'));
820 $blogurl->param('groupid', $groupid);
821 $PAGE->navbar
->add($group->name
, $blogurl);
823 $PAGE->set_title($course->fullname
);
824 $PAGE->set_heading($course->fullname
);
827 $a->group
= $group->name
;
828 $a->course
= format_string($course->fullname
, true, array('context' => context_course
::instance($course->id
)));
829 $a->type
= get_string('course');
830 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
831 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
832 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
833 } else if (!empty($groupid) && !empty($modid) && empty($entryid)) {
834 // Case 8: Blog entries by members of a group, associated with an activity in that course.
836 $headers['cm'] = $cm;
837 $blogurl->param('modid', $modid);
838 $PAGE->navbar
->add($strblogentries, $blogurl);
840 $blogurl->param('groupid', $groupid);
841 $PAGE->navbar
->add($group->name
, $blogurl);
843 $PAGE->set_title($course->fullname
);
844 $PAGE->set_heading($course->fullname
);
847 $a->group
= $group->name
;
849 $a->type
= get_string('modulename', $cm->modname
);
850 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
851 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
852 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
854 } else if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
855 // Case 9: All blog entries associated with an activity.
857 $PAGE->set_cm($cm, $course);
858 $blogurl->param('modid', $modid);
859 $PAGE->navbar
->add($strblogentries, $blogurl);
860 $PAGE->set_title($course->fullname
);
861 $PAGE->set_heading($course->fullname
);
862 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name
);
864 $a->type
= get_string('modulename', $cm->modname
);
865 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
866 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
867 } else if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
868 // Case 10: All blog entries associated with a course.
870 $blogurl->param('courseid', $courseid);
871 $PAGE->navbar
->add($strblogentries, $blogurl);
872 $PAGE->set_title($course->fullname
);
873 $PAGE->set_heading($course->fullname
);
875 $a->type
= get_string('course');
876 $headers['heading'] = get_string('blogentriesabout',
878 format_string($course->fullname
,
880 array('context' => context_course
::instance($course->id
))));
881 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
882 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
883 $blogurl->remove_params(array('userid'));
886 if (!in_array($action, array('edit', 'add'))) {
888 if (!empty($tagid)) {
889 $headers['filters']['tag'] = $tagid;
890 $blogurl->param('tagid', $tagid);
891 $tagrec = $DB->get_record('tag', array('id' => $tagid));
892 $PAGE->navbar
->add($tagrec->name
, $blogurl);
893 } else if (!empty($tag)) {
894 if ($tagrec = $DB->get_record('tag', array('name' => $tag))) {
895 $tagid = $tagrec->id
;
896 $headers['filters']['tag'] = $tagid;
897 $blogurl->param('tag', $tag);
898 $PAGE->navbar
->add(get_string('tagparam', 'blog', $tag), $blogurl);
902 // Append Search info.
903 if (!empty($search) && has_capability('moodle/blog:search', $sitecontext)) {
904 $headers['filters']['search'] = $search;
905 $blogurl->param('search', $search);
906 $PAGE->navbar
->add(get_string('searchterm', 'blog', $search), $blogurl->out());
910 // Append edit mode info.
911 if (!empty($action) && $action == 'add') {
913 } else if (!empty($action) && $action == 'edit') {
914 $PAGE->navbar
->add(get_string('editentry', 'blog'));
917 if (empty($headers['url'])) {
918 $headers['url'] = $blogurl;
924 * Shortcut function for getting a count of blog entries associated with a course or a module
925 * @param int $courseid The ID of the course
926 * @param int $cmid The ID of the course_modules
927 * @return string The number of associated entries
929 function blog_get_associated_count($courseid, $cmid=null) {
931 $context = context_course
::instance($courseid);
933 $context = context_module
::instance($cmid);
935 return $DB->count_records('blog_association', array('contextid' => $context->id
));
939 * Running addtional permission check on plugin, for example, plugins
940 * may have switch to turn on/off comments option, this callback will
941 * affect UI display, not like pluginname_comment_validate only throw
943 * blog_comment_validate will be called before viewing/adding/deleting
944 * comment, so don't repeat checks.
945 * Capability check has been done in comment->check_permissions(), we
946 * don't need to do it again here.
951 * @param stdClass $commentparam {
952 * context => context the context object
953 * courseid => int course id
954 * cm => stdClass course module object
955 * commentarea => string comment area
956 * itemid => int itemid
960 function blog_comment_permissions($commentparam) {
963 // If blog is public and current user is guest, then don't let him post comments.
964 $blogentry = $DB->get_record('post', array('id' => $commentparam->itemid
), 'publishstate', MUST_EXIST
);
966 if ($blogentry->publishstate
!= 'public') {
967 if (!isloggedin() ||
isguestuser()) {
968 return array('post' => false, 'view' => true);
971 return array('post' => true, 'view' => true);
975 * Validate comment parameter before perform other comments actions
980 * @param stdClass $comment {
981 * context => context the context object
982 * courseid => int course id
983 * cm => stdClass course module object
984 * commentarea => string comment area
985 * itemid => int itemid
989 function blog_comment_validate($commentparam) {
990 global $CFG, $DB, $USER;
992 // Check if blogs are enabled user can comment.
993 if (empty($CFG->enableblogs
) ||
empty($CFG->blogusecomments
)) {
994 throw new comment_exception('nopermissiontocomment');
997 // Validate comment area.
998 if ($commentparam->commentarea
!= 'format_blog') {
999 throw new comment_exception('invalidcommentarea');
1002 $blogentry = $DB->get_record('post', array('id' => $commentparam->itemid
), '*', MUST_EXIST
);
1004 // Validation for comment deletion.
1005 if (!empty($commentparam->commentid
)) {
1006 if ($record = $DB->get_record('comments', array('id' => $commentparam->commentid
))) {
1007 if ($record->commentarea
!= 'format_blog') {
1008 throw new comment_exception('invalidcommentarea');
1010 if ($record->contextid
!= $commentparam->context
->id
) {
1011 throw new comment_exception('invalidcontext');
1013 if ($record->itemid
!= $commentparam->itemid
) {
1014 throw new comment_exception('invalidcommentitemid');
1017 throw new comment_exception('invalidcommentid');
1021 // Validate if user has blog view permission.
1022 $sitecontext = context_system
::instance();
1023 return has_capability('moodle/blog:view', $sitecontext) &&
1024 blog_user_can_view_user_entry($blogentry->userid
, $blogentry);
1028 * Return a list of page types
1029 * @param string $pagetype current page type
1030 * @param stdClass $parentcontext Block's parent context
1031 * @param stdClass $currentcontext Current context of block
1033 function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1035 '*' => get_string('page-x', 'pagetype'),
1036 'blog-*' => get_string('page-blog-x', 'blog'),
1037 'blog-index' => get_string('page-blog-index', 'blog'),
1038 'blog-edit' => get_string('page-blog-edit', 'blog')
1043 * Add nodes to myprofile page.
1045 * @param \core_user\output\myprofile\tree $tree Tree object
1046 * @param stdClass $user user object
1047 * @param bool $iscurrentuser
1048 * @param stdClass $course Course object
1052 function core_blog_myprofile_navigation(core_user\output\myprofile\tree
$tree, $user, $iscurrentuser, $course) {
1054 if (!blog_is_enabled_for_user() ||
isguestuser($user)) {
1055 // The guest user cannot post, so it is not possible to view any posts.
1056 // Also blogs might be disabled.
1057 // May as well just bail aggressively here.
1060 if (!blog_user_can_view_user_entry($user->id
)) {
1063 $url = new moodle_url("/blog/index.php", array('userid' => $user->id
));
1064 if (!empty($course)) {
1065 $url->param('courseid', $course->id
);
1067 if ($iscurrentuser) {
1068 $title = get_string('blogentries', 'core_blog');
1070 $title = get_string('myprofileuserblogs', 'core_blog');
1072 $blognode = new core_user\output\myprofile\node
('miscellaneous', 'blogs', $title, null, $url);
1073 $tree->add_node($blognode);
1078 * Returns posts tagged with a specified tag.
1080 * @param core_tag_tag $tag
1081 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1082 * are displayed on the page and the per-page limit may be bigger
1083 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1084 * to display items in the same context first
1085 * @param int $ctx context id where to search for records
1086 * @param bool $rec search in subcontexts as well
1087 * @param int $page 0-based number of page being displayed
1088 * @return \core_tag\output\tagindex
1090 function blog_get_tagged_posts($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = true, $page = 0) {
1091 global $CFG, $OUTPUT;
1092 require_once($CFG->dirroot
.'/user/lib.php');
1094 $systemcontext = context_system
::instance();
1095 $perpage = $exclusivemode ?
20 : 5;
1096 $context = $ctx ? context
::instance_by_id($ctx) : context_system
::instance();
1099 if (empty($CFG->enableblogs
) ||
!has_capability('moodle/blog:view', $systemcontext)) {
1100 // Blogs are not enabled or are not visible to the current user.
1102 } else if ($context->contextlevel
!= CONTEXT_SYSTEM
&& empty($CFG->useblogassociations
)) {
1103 // No blog entries can be associated to the non-system context.
1105 } else if (!$rec && $context->contextlevel
!= CONTEXT_COURSE
&& $context->contextlevel
!= CONTEXT_MODULE
) {
1106 // No blog entries can be associated with category or block context.
1109 require_once($CFG->dirroot
.'/blog/locallib.php');
1111 $filters = array('tag' => $tag->id
);
1113 if ($context->contextlevel
!= CONTEXT_SYSTEM
) {
1114 $filters['context'] = $context->id
;
1116 } else if ($context->contextlevel
== CONTEXT_COURSE
) {
1117 $filters['course'] = $context->instanceid
;
1118 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1119 $filters['module'] = $context->instanceid
;
1121 $bloglisting = new blog_listing($filters);
1122 $blogs = $bloglisting->get_entries($page * $perpage, $perpage);
1123 $totalcount = $bloglisting->count_entries();
1124 $totalpages = ceil($totalcount / $perpage);
1125 if (!empty($blogs)) {
1126 $tagfeed = new core_tag\output\tagfeed
();
1127 foreach ($blogs as $blog) {
1128 $user = fullclone($blog);
1129 $user->id
= $blog->userid
;
1131 $img = $OUTPUT->user_picture($user, array('size' => 35));
1132 $subject = format_string($blog->subject
);
1134 if ($blog->publishstate
== 'draft') {
1140 $url = new moodle_url('/blog/index.php', array('entryid' => $blog->id
));
1141 $subject = html_writer
::link($url, $subject, array('class' => $class));
1143 $fullname = fullname($user);
1144 if (user_can_view_profile($user)) {
1145 $profilelink = new moodle_url('/user/view.php', array('id' => $blog->userid
));
1146 $fullname = html_writer
::link($profilelink, $fullname);
1148 $details = $fullname . ', ' . userdate($blog->created
);
1150 $tagfeed->add($img, $subject, $details);
1153 $items = $tagfeed->export_for_template($OUTPUT);
1154 $content = $OUTPUT->render_from_template('core_tag/tagfeed', $items);
1156 $urlparams = array('tagid' => $tag->id
);
1157 if ($context->contextlevel
== CONTEXT_COURSE
) {
1158 $urlparams['courseid'] = $context->instanceid
;
1159 } else if ($context->contextlevel
== CONTEXT_MODULE
) {
1160 $urlparams['modid'] = $context->instanceid
;
1162 $allblogsurl = new moodle_url('/blog/index.php', $urlparams);
1164 $rv = new core_tag\output\tagindex
($tag, 'core', 'post',
1166 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1167 $rv->exclusiveurl
= $allblogsurl;
1172 $rv = new core_tag\output\tagindex
($tag, 'core', 'post',
1174 $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1175 $rv->exclusiveurl
= null;
1180 * Validate the access to a blog.
1182 * @param int $courseid course id the the blog is associated to (can be null).
1183 * @param int $modid module id the blog is associated to (can be null).
1184 * @param int $groupid group id to filter blogs I can see (can be null)
1185 * @param int $entryid blog entry id (can be null)
1186 * @param int $userid blog author id (can be null)
1187 * @return array with the calculated course and id
1190 function blog_validate_access($courseid, $modid, $groupid, $entryid, $userid) {
1191 global $CFG, $DB, $USER, $COURSE;
1193 $sitecontext = context_system
::instance();
1195 // Add courseid if modid or groupid is specified: This is used for navigation and title.
1196 if (!empty($modid) && empty($courseid)) {
1197 $courseid = $DB->get_field('course_modules', 'course', array('id' => $modid));
1200 if (!empty($groupid) && empty($courseid)) {
1201 $courseid = $DB->get_field('groups', 'courseid', array('id' => $groupid));
1204 if (!$userid && has_capability('moodle/blog:view', $sitecontext) && $CFG->bloglevel
> BLOG_USER_LEVEL
) {
1206 if (!$entryobject = $DB->get_record('post', array('id' => $entryid))) {
1207 print_error('nosuchentry', 'blog');
1209 $userid = $entryobject->userid
;
1211 } else if (!$userid) {
1212 $userid = $USER->id
;
1215 if (!empty($modid)) {
1216 if ($CFG->bloglevel
< BLOG_SITE_LEVEL
) {
1217 print_error(get_string('nocourseblogs', 'blog'));
1219 if (!$mod = $DB->get_record('course_modules', array('id' => $modid))) {
1220 print_error(get_string('invalidmodid', 'blog'));
1222 $courseid = $mod->course
;
1225 if ((empty($courseid) ?
true : $courseid == SITEID
) && empty($userid)) {
1226 if ($CFG->bloglevel
< BLOG_SITE_LEVEL
) {
1227 print_error('siteblogdisable', 'blog');
1229 if (!has_capability('moodle/blog:view', $sitecontext)) {
1230 print_error('cannotviewsiteblog', 'blog');
1233 $COURSE = $DB->get_record('course', array('format' => 'site'));
1234 $courseid = $COURSE->id
;
1237 if (!empty($courseid)) {
1238 if (!$course = $DB->get_record('course', array('id' => $courseid))) {
1239 print_error('invalidcourseid');
1242 $courseid = $course->id
;
1244 if (!has_capability('moodle/blog:view', $sitecontext)) {
1245 print_error('cannotviewcourseblog', 'blog');
1248 $coursecontext = context_course
::instance(SITEID
);
1251 if (!empty($groupid)) {
1252 if ($CFG->bloglevel
< BLOG_SITE_LEVEL
) {
1253 print_error('groupblogdisable', 'blog');
1256 if (! $group = groups_get_group($groupid)) {
1257 print_error(get_string('invalidgroupid', 'blog'));
1260 if (!$course = $DB->get_record('course', array('id' => $group->courseid
))) {
1261 print_error('invalidcourseid');
1264 $coursecontext = context_course
::instance($course->id
);
1265 $courseid = $course->id
;
1267 if (!has_capability('moodle/blog:view', $sitecontext)) {
1268 print_error(get_string('cannotviewcourseorgroupblog', 'blog'));
1271 if (groups_get_course_groupmode($course) == SEPARATEGROUPS
&&
1272 !has_capability('moodle/site:accessallgroups', $coursecontext)) {
1274 if (!groups_is_member($groupid)) {
1275 print_error('notmemberofgroup');
1280 if (!empty($userid)) {
1281 if ($CFG->bloglevel
< BLOG_USER_LEVEL
) {
1282 print_error('blogdisable', 'blog');
1285 if (!$user = $DB->get_record('user', array('id' => $userid))) {
1286 print_error('invaliduserid');
1289 if ($user->deleted
) {
1290 print_error('userdeleted');
1293 if ($USER->id
== $userid) {
1294 if (!has_capability('moodle/blog:create', $sitecontext)
1295 && !has_capability('moodle/blog:view', $sitecontext)) {
1296 print_error('donothaveblog', 'blog');
1299 if (!has_capability('moodle/blog:view', $sitecontext) ||
!blog_user_can_view_user_entry($userid)) {
1300 print_error('cannotviewcourseblog', 'blog');
1304 return array($courseid, $userid);