MDL-46218 reshuffled access checks in blog and notes
[moodle.git] / blog / lib.php
CommitLineData
cae83708 1<?php
2
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.
14//
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/>.
17
cae83708 18/**
19 * Core global functions for Blog.
20 *
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
25 */
26
35716b86
PS
27defined('MOODLE_INTERNAL') || die();
28
cae83708 29/**
30 * Library of functions and constants for blog
31 */
32require_once($CFG->dirroot .'/blog/rsslib.php');
33require_once($CFG->dirroot.'/tag/lib.php');
34
cae83708 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.
39 *
40 * This also applies to deleting of entries.
41 */
1c7b8b93
NC
42function blog_user_can_edit_entry($blogentry) {
43 global $USER;
6524adcf 44
41b38360 45 $sitecontext = context_system::instance();
4a173181 46
cae83708 47 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
48 return true; // can edit any blog entry
49 }
c2ee4e87 50
1c7b8b93 51 if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
cae83708 52 return true; // can edit own when having blog:create capability
53 }
4a173181 54
cae83708 55 return false;
56}
d02240f3 57
3bfcfdca 58
cae83708 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
63 */
1c7b8b93 64function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
cae83708 65 global $CFG, $USER, $DB;
c2ee4e87 66
850d2db8 67 if (empty($CFG->enableblogs)) {
89f5e430 68 return false; // Blog system disabled.
cae83708 69 }
70
2c27b6ae 71 if (isloggedin() && $USER->id == $targetuserid) {
89f5e430 72 return true; // Can view own entries in any case.
cae83708 73 }
74
41b38360 75 $sitecontext = context_system::instance();
cae83708 76 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
89f5e430 77 return true; // Can manage all entries.
cae83708 78 }
c2ee4e87 79
89f5e430 80 // If blog is in draft state, then make sure user have proper capability.
1c7b8b93 81 if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
89f5e430 82 return false; // Can not view draft of others.
cae83708 83 }
84
9a909b1a 85 // If blog entry is not public, make sure user is logged in.
1c7b8b93 86 if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
cae83708 87 return false;
88 }
d02240f3 89
89f5e430 90 // If blogentry is not passed or all above checks pass, then check capability based on system config.
cae83708 91 switch ($CFG->bloglevel) {
92 case BLOG_GLOBAL_LEVEL:
93 return true;
94 break;
c2ee4e87 95
cae83708 96 case BLOG_SITE_LEVEL:
89f5e430 97 if (isloggedin()) { // Not logged in viewers forbidden.
cae83708 98 return true;
c2ee4e87 99 }
cae83708 100 return false;
101 break;
d02240f3 102
cae83708 103 case BLOG_USER_LEVEL:
104 default:
89f5e430 105 // If user is viewing other user blog, then user should have user:readuserblogs capability.
41b38360 106 $personalcontext = context_user::instance($targetuserid);
cae83708 107 return has_capability('moodle/user:readuserblogs', $personalcontext);
108 break;
4a173181 109
cae83708 110 }
111}
112
113/**
114 * remove all associations for the blog entries of a particular user
115 * @param int userid - id of user whose blog associations will be deleted
116 */
117function blog_remove_associations_for_user($userid) {
1c7b8b93 118 global $DB;
d91181dc
PS
119 throw new coding_exception('function blog_remove_associations_for_user() is not finished');
120 /*
1c7b8b93
NC
121 $blogentries = blog_fetch_entries(array('user' => $userid), 'lasmodified DESC');
122 foreach ($blogentries as $entry) {
123 if (blog_user_can_edit_entry($entry)) {
124 blog_remove_associations_for_entry($entry->id);
125 }
b0e90a0c 126 }
d91181dc 127 */
cae83708 128}
129
130/**
1c7b8b93
NC
131 * remove all associations for the blog entries of a particular course
132 * @param int courseid - id of user whose blog associations will be deleted
cae83708 133 */
1c7b8b93
NC
134function blog_remove_associations_for_course($courseid) {
135 global $DB;
41b38360 136 $context = context_course::instance($courseid);
1c7b8b93 137 $DB->delete_records('blog_association', array('contextid' => $context->id));
cae83708 138}
139
cae83708 140/**
141 * Given a record in the {blog_external} table, checks the blog's URL
b7c1da93 142 * for new entries not yet copied into Moodle.
50ff50da 143 * Also attempts to identify and remove deleted blog entries
cae83708 144 *
1c7b8b93
NC
145 * @param object $externalblog
146 * @return boolean False if the Feed is invalid
cae83708 147 */
1c7b8b93 148function blog_sync_external_entries($externalblog) {
cae83708 149 global $CFG, $DB;
e14de6f9 150 require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
4a173181 151
d958e6bd
PS
152 $rss = new moodle_simplepie();
153 $rssfile = $rss->registry->create('File', array($externalblog->url));
154 $filetest = $rss->registry->create('Locator', array($rssfile));
1c7b8b93
NC
155
156 if (!$filetest->is_feed($rssfile)) {
157 $externalblog->failedlastsync = 1;
158 $DB->update_record('blog_external', $externalblog);
159 return false;
8397492b 160 } else if (!empty($externalblog->failedlastsync)) {
1c7b8b93
NC
161 $externalblog->failedlastsync = 0;
162 $DB->update_record('blog_external', $externalblog);
c2ee4e87 163 }
4a173181 164
d958e6bd
PS
165 $rss->set_feed_url($externalblog->url);
166 $rss->init();
c2ee4e87 167
e14de6f9 168 if (empty($rss->data)) {
cae83708 169 return null;
170 }
50ff50da 171 //used to identify blog posts that have been deleted from the source feed
cc52e53d 172 $oldesttimestamp = null;
50ff50da 173 $uniquehashes = array();
b13ee30e 174
e14de6f9 175 foreach ($rss->get_items() as $entry) {
1c7b8b93
NC
176 // If filtertags are defined, use them to filter the entries by RSS category
177 if (!empty($externalblog->filtertags)) {
178 $containsfiltertag = false;
179 $categories = $entry->get_categories();
180 $filtertags = explode(',', $externalblog->filtertags);
181 $filtertags = array_map('trim', $filtertags);
182 $filtertags = array_map('strtolower', $filtertags);
183
184 foreach ($categories as $category) {
185 if (in_array(trim(strtolower($category->term)), $filtertags)) {
186 $containsfiltertag = true;
187 }
188 }
189
190 if (!$containsfiltertag) {
191 continue;
c2ee4e87 192 }
193 }
c484c852 194
50ff50da 195 $uniquehashes[] = $entry->get_permalink();
1c7b8b93 196
e463f508 197 $newentry = new stdClass();
1c7b8b93
NC
198 $newentry->userid = $externalblog->userid;
199 $newentry->module = 'blog_external';
200 $newentry->content = $externalblog->id;
201 $newentry->uniquehash = $entry->get_permalink();
202 $newentry->publishstate = 'site';
203 $newentry->format = FORMAT_HTML;
a537e507
EL
204 // Clean subject of html, just in case
205 $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
206 // Observe 128 max chars in DB
207 // TODO: +1 to raise this to 255
2f1e464a
PS
208 if (core_text::strlen($newentry->subject) > 128) {
209 $newentry->subject = core_text::substr($newentry->subject, 0, 125) . '...';
a537e507 210 }
1c7b8b93 211 $newentry->summary = $entry->get_description();
c484c852 212
9829e3d8 213 //used to decide whether to insert or update
214 //uses enty permalink plus creation date if available
bb8a75e7 215 $existingpostconditions = array('uniquehash' => $entry->get_permalink());
99cd408f 216
9829e3d8 217 //our DB doesnt allow null creation or modified timestamps so check the external blog supplied one
99cd408f 218 $entrydate = $entry->get_date('U');
afce96f0 219 if (!empty($entrydate)) {
220 $existingpostconditions['created'] = $entrydate;
221 }
c484c852 222
e5137f24 223 //the post ID or false if post not found in DB
afce96f0 224 $postid = $DB->get_field('post', 'id', $existingpostconditions);
c484c852 225
afce96f0 226 $timestamp = null;
99cd408f 227 if (empty($entrydate)) {
afce96f0 228 $timestamp = time();
99cd408f 229 } else {
afce96f0 230 $timestamp = $entrydate;
99cd408f 231 }
c484c852 232
afce96f0 233 //only set created if its a new post so we retain the original creation timestamp if the post is edited
bb8a75e7 234 if ($postid === false) {
afce96f0 235 $newentry->created = $timestamp;
236 }
237 $newentry->lastmodified = $timestamp;
694fb770 238
bb8a75e7 239 if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
cc52e53d 240 //found an older post
241 $oldesttimestamp = $timestamp;
242 }
1c7b8b93 243
2f1e464a 244 if (core_text::strlen($newentry->uniquehash) > 255) {
3b59524d
SH
245 // The URL for this item is too long for the field. Rather than add
246 // the entry without the link we will skip straight over it.
247 // RSS spec says recommended length 500, we use 255.
248 debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
249 continue;
250 }
251
bb8a75e7 252 if ($postid === false) {
9829e3d8 253 $id = $DB->insert_record('post', $newentry);
1c7b8b93 254
9829e3d8 255 // Set tags
256 if ($tags = tag_get_tags_array('blog_external', $externalblog->id)) {
cc033d48 257 tag_set('post', $id, $tags, 'core', context_user::instance($externalblog->userid)->id);
9829e3d8 258 }
259 } else {
260 $newentry->id = $postid;
afce96f0 261 $DB->update_record('post', $newentry);
1c7b8b93 262 }
cae83708 263 }
c484c852 264
ed79b89b
DM
265 // Look at the posts we have in the database to check if any of them have been deleted from the feed.
266 // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
267 // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
268 $sql = "SELECT id, uniquehash
269 FROM {post}
270 WHERE module = 'blog_external'
271 AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
272 AND created > :ts";
42291c61
AD
273 $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
274
50ff50da 275 $todelete = array();
276 foreach($dbposts as $dbpost) {
29487578 277 if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
50ff50da 278 $todelete[] = $dbpost->id;
279 }
280 }
281 $DB->delete_records_list('post', 'id', $todelete);
c2ee4e87 282
e5137f24 283 $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
1c7b8b93
NC
284}
285
286/**
287 * Given an external blog object, deletes all related blog entries from the post table.
288 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
289 * @param object $externablog
290 */
291function blog_delete_external_entries($externalblog) {
292 global $DB;
41b38360 293 require_capability('moodle/blog:manageexternal', context_system::instance());
a742eb1f
EL
294 $DB->delete_records_select('post',
295 "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
296 array($externalblog->id));
cae83708 297}
d02240f3 298
27bad0a6 299/**
593270c6 300 * This function checks that blogs are enabled, and that the user can see blogs at all
27bad0a6
SH
301 * @return bool
302 */
303function blog_is_enabled_for_user() {
304 global $CFG;
850d2db8 305 return (!empty($CFG->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
27bad0a6
SH
306}
307
308/**
309 * This function gets all of the options available for the current user in respect
310 * to blogs.
897aa80c 311 *
27bad0a6
SH
312 * It loads the following if applicable:
313 * - Module options {@see blog_get_options_for_module}
314 * - Course options {@see blog_get_options_for_course}
315 * - User specific options {@see blog_get_options_for_user}
316 * - General options (BLOG_LEVEL_GLOBAL)
317 *
318 * @param moodle_page $page The page to load for (normally $PAGE)
319 * @param stdClass $userid Load for a specific user
320 * @return array An array of options organised by type.
321 */
322function blog_get_all_options(moodle_page $page, stdClass $userid = null) {
323 global $CFG, $DB, $USER;
324
325 $options = array();
326
327 // If blogs are enabled and the user is logged in and not a guest
328 if (blog_is_enabled_for_user()) {
329 // If the context is the user then assume we want to load for the users context
330 if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
331 $userid = $page->context->instanceid;
332 }
333 // Check the userid var
334 if (!is_null($userid) && $userid!==$USER->id) {
335 // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
336 $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
337 } else {
338 $user = null;
339 }
340
341 if ($CFG->useblogassociations && $page->cm !== null) {
342 // Load for the module associated with the page
343 $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
344 } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
345 // Load the options for the course associated with the page
346 $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
347 }
348
349 // Get the options for the user
5b183f51 350 if ($user !== null and !isguestuser($user)) {
27bad0a6
SH
351 // Load for the requested user
352 $options[CONTEXT_USER+1] = blog_get_options_for_user($user);
353 }
354 // Load for the current user
5b183f51
PS
355 if (isloggedin() and !isguestuser()) {
356 $options[CONTEXT_USER] = blog_get_options_for_user();
357 }
27bad0a6
SH
358 }
359
360 // If blog level is global then display a link to view all site entries
850d2db8 361 if (!empty($CFG->enableblogs) && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL && has_capability('moodle/blog:view', context_system::instance())) {
27bad0a6
SH
362 $options[CONTEXT_SYSTEM] = array('viewsite' => array(
363 'string' => get_string('viewsiteentries', 'blog'),
364 'link' => new moodle_url('/blog/index.php')
365 ));
366 }
367
368 // Return the options
369 return $options;
370}
371
372/**
373 * Get all of the blog options that relate to the passed user.
374 *
375 * If no user is passed the current user is assumed.
376 *
377 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
378 * @param stdClass $user
379 * @return array The array of options for the requested user
380 */
381function blog_get_options_for_user(stdClass $user=null) {
382 global $CFG, $USER;
383 // Cache
384 static $useroptions = array();
385
386 $options = array();
387 // Blogs must be enabled and the user must be logged in
388 if (!blog_is_enabled_for_user()) {
389 return $options;
390 }
391
392 // Sort out the user var
393 if ($user === null || $user->id == $USER->id) {
394 $user = $USER;
395 $iscurrentuser = true;
396 } else {
397 $iscurrentuser = false;
398 }
399
400 // If we've already generated serve from the cache
401 if (array_key_exists($user->id, $useroptions)) {
402 return $useroptions[$user->id];
403 }
404
41b38360 405 $sitecontext = context_system::instance();
27bad0a6
SH
406 $canview = has_capability('moodle/blog:view', $sitecontext);
407
408 if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
409 // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL
410 $options['userentries'] = array(
411 'string' => get_string('viewuserentries', 'blog', fullname($user)),
412 'link' => new moodle_url('/blog/index.php', array('userid'=>$user->id))
413 );
414 } else {
415 // It's the current user
416 if ($canview) {
417 // We can view our own blogs .... BIG surprise
418 $options['view'] = array(
419 'string' => get_string('viewallmyentries', 'blog'),
420 'link' => new moodle_url('/blog/index.php', array('userid'=>$USER->id))
421 );
422 }
423 if (has_capability('moodle/blog:create', $sitecontext)) {
424 // We can add to our own blog
425 $options['add'] = array(
426 'string' => get_string('addnewentry', 'blog'),
427 'link' => new moodle_url('/blog/edit.php', array('action'=>'add'))
428 );
429 }
430 }
0f4c6067 431 if ($canview && $CFG->enablerssfeeds) {
c000545d
JF
432 $options['rss'] = array(
433 'string' => get_string('rssfeed', 'blog'),
434 'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
435 );
436 }
437
27bad0a6
SH
438 // Cache the options
439 $useroptions[$user->id] = $options;
440 // Return the options
441 return $options;
442}
443
444/**
445 * Get the blog options that relate to the given course for the given user.
446 *
447 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
448 * @param stdClass $course The course to load options for
449 * @param stdClass $user The user to load options for null == current user
450 * @return array The array of options
451 */
452function blog_get_options_for_course(stdClass $course, stdClass $user=null) {
453 global $CFG, $USER;
454 // Cache
455 static $courseoptions = array();
897aa80c 456
27bad0a6
SH
457 $options = array();
458
459 // User must be logged in and blogs must be enabled
460 if (!blog_is_enabled_for_user()) {
461 return $options;
462 }
463
464 // Check that the user can associate with the course
41b38360 465 $sitecontext = context_system::instance();
27bad0a6
SH
466 // Generate the cache key
467 $key = $course->id.':';
468 if (!empty($user)) {
469 $key .= $user->id;
470 } else {
471 $key .= $USER->id;
472 }
473 // Serve from the cache if we've already generated for this course
474 if (array_key_exists($key, $courseoptions)) {
af8fe217 475 return $courseoptions[$key];
27bad0a6 476 }
897aa80c 477
ff53a58b 478
4ef08298 479 if (has_capability('moodle/blog:view', $sitecontext)) {
27bad0a6
SH
480 // We can view!
481 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
482 // View entries about this course
483 $options['courseview'] = array(
484 'string' => get_string('viewcourseblogs', 'blog'),
4ef08298 485 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id))
27bad0a6
SH
486 );
487 }
488 // View MY entries about this course
489 $options['courseviewmine'] = array(
490 'string' => get_string('viewmyentriesaboutcourse', 'blog'),
4ef08298 491 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $USER->id))
27bad0a6
SH
492 );
493 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
494 // View the provided users entries about this course
495 $options['courseviewuser'] = array(
496 'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
4ef08298 497 'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $user->id))
27bad0a6
SH
498 );
499 }
500 }
501
4ef08298 502 if (has_capability('moodle/blog:create', $sitecontext)) {
27bad0a6
SH
503 // We can blog about this course
504 $options['courseadd'] = array(
cfa11fd6 505 'string' => get_string('blogaboutthiscourse', 'blog'),
4ef08298 506 'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'courseid' => $course->id))
27bad0a6
SH
507 );
508 }
509
510
511 // Cache the options for this course
512 $courseoptions[$key] = $options;
513 // Return the options
514 return $options;
515}
516
517/**
518 * Get the blog options relating to the given module for the given user
519 *
520 * @staticvar array $moduleoptions Cache
78f0f64d 521 * @param stdClass|cm_info $module The module to get options for
27bad0a6
SH
522 * @param stdClass $user The user to get options for null == currentuser
523 * @return array
524 */
78f0f64d 525function blog_get_options_for_module($module, $user=null) {
27bad0a6
SH
526 global $CFG, $USER;
527 // Cache
528 static $moduleoptions = array();
529
530 $options = array();
531 // User must be logged in, blogs must be enabled
532 if (!blog_is_enabled_for_user()) {
533 return $options;
534 }
535
41b38360 536 $sitecontext = context_system::instance();
27bad0a6
SH
537
538 // Generate the cache key
539 $key = $module->id.':';
540 if (!empty($user)) {
541 $key .= $user->id;
542 } else {
543 $key .= $USER->id;
544 }
545 if (array_key_exists($key, $moduleoptions)) {
546 // Serve from the cache so we don't have to regenerate
46a710e9 547 return $moduleoptions[$key];
27bad0a6
SH
548 }
549
ff53a58b 550
4ef08298 551 if (has_capability('moodle/blog:view', $sitecontext)) {
dc9fa9cb
RT
552 // Save correct module name for later usage.
553 $modulename = get_string('modulename', $module->modname);
4eaf120a 554
27bad0a6
SH
555 // We can view!
556 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
557 // View all entries about this module
558 $a = new stdClass;
dc9fa9cb 559 $a->type = $modulename;
27bad0a6
SH
560 $options['moduleview'] = array(
561 'string' => get_string('viewallmodentries', 'blog', $a),
562 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id))
563 );
564 }
565 // View MY entries about this module
566 $options['moduleviewmine'] = array(
dc9fa9cb 567 'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
27bad0a6
SH
568 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$USER->id))
569 );
570 if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
571 // View the given users entries about this module
572 $a = new stdClass;
dc9fa9cb 573 $a->mod = $modulename;
27bad0a6
SH
574 $a->user = fullname($user);
575 $options['moduleviewuser'] = array(
576 'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
577 'link' => new moodle_url('/blog/index.php', array('modid'=>$module->id, 'userid'=>$user->id))
578 );
579 }
580 }
581
4ef08298 582 if (has_capability('moodle/blog:create', $sitecontext)) {
27bad0a6
SH
583 // The user can blog about this module
584 $options['moduleadd'] = array(
dc9fa9cb 585 'string' => get_string('blogaboutthismodule', 'blog', $modulename),
27bad0a6
SH
586 'link' => new moodle_url('/blog/edit.php', array('action'=>'add', 'modid'=>$module->id))
587 );
588 }
589 // Cache the options
590 $moduleoptions[$key] = $options;
591 // Return the options
592 return $options;
593}
594
cae83708 595/**
596 * This function encapsulates all the logic behind the complex
597 * navigation, titles and headings of the blog listing page, depending
1c7b8b93
NC
598 * on URL params. It looks at URL params and at the current context level.
599 * It builds and returns an array containing:
600 *
601 * 1. heading: The heading displayed above the blog entries
602 * 2. stradd: The text to be used as the "Add entry" link
603 * 3. strview: The text to be used as the "View entries" link
604 * 4. url: The moodle_url object used as the base for add and view links
605 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
cae83708 606 *
c5dc10ee 607 * All other variables are set directly in $PAGE
cae83708 608 *
609 * It uses the current URL to build these variables.
610 * A number of mutually exclusive use cases are used to structure this function.
611 *
612 * @return array
613 */
451f1e38 614function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null) {
cae83708 615 global $CFG, $PAGE, $DB, $USER;
616
9366362a 617 $id = optional_param('id', null, PARAM_INT);
cae83708 618 $tag = optional_param('tag', null, PARAM_NOTAGS);
451f1e38
AD
619 $tagid = optional_param('tagid', $tagid, PARAM_INT);
620 $userid = optional_param('userid', $userid, PARAM_INT);
cae83708 621 $modid = optional_param('modid', null, PARAM_INT);
622 $entryid = optional_param('entryid', null, PARAM_INT);
451f1e38
AD
623 $groupid = optional_param('groupid', $groupid, PARAM_INT);
624 $courseid = optional_param('courseid', $courseid, PARAM_INT);
cae83708 625 $search = optional_param('search', null, PARAM_RAW);
626 $action = optional_param('action', null, PARAM_ALPHA);
627 $confirm = optional_param('confirm', false, PARAM_BOOL);
628
1c7b8b93
NC
629 // Ignore userid when action == add
630 if ($action == 'add' && $userid) {
631 unset($userid);
632 $PAGE->url->remove_params(array('userid'));
633 } else if ($action == 'add' && $entryid) {
634 unset($entryid);
635 $PAGE->url->remove_params(array('entryid'));
636 }
637
638 $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
cae83708 639
a6855934 640 $blogurl = new moodle_url('/blog/index.php');
1c7b8b93 641
1c7b8b93
NC
642 $headers['stradd'] = get_string('addnewentry', 'blog');
643 $headers['strview'] = null;
cae83708 644
1c7b8b93 645 $site = $DB->get_record('course', array('id' => SITEID));
41b38360 646 $sitecontext = context_system::instance();
cae83708 647 // Common Lang strings
648 $strparticipants = get_string("participants");
649 $strblogentries = get_string("blogentries", 'blog');
650
651 // Prepare record objects as needed
652 if (!empty($courseid)) {
1c7b8b93 653 $headers['filters']['course'] = $courseid;
cae83708 654 $course = $DB->get_record('course', array('id' => $courseid));
655 }
e96f2a77 656
cae83708 657 if (!empty($userid)) {
1c7b8b93 658 $headers['filters']['user'] = $userid;
cae83708 659 $user = $DB->get_record('user', array('id' => $userid));
516194d0 660 }
bbbf2d40 661
cae83708 662 if (!empty($groupid)) { // groupid always overrides courseid
1c7b8b93 663 $headers['filters']['group'] = $groupid;
cae83708 664 $group = $DB->get_record('groups', array('id' => $groupid));
665 $course = $DB->get_record('course', array('id' => $group->courseid));
666 }
bbbf2d40 667
897aa80c 668 $PAGE->set_pagelayout('standard');
27bad0a6 669
1b30a9fa
DM
670 // modid always overrides courseid, so the $course object may be reset here
671 if (!empty($modid) && $CFG->useblogassociations) {
672
1c7b8b93 673 $headers['filters']['module'] = $modid;
cae83708 674 // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case
1c7b8b93
NC
675 $courseid = $DB->get_field('course_modules', 'course', array('id'=>$modid));
676 $course = $DB->get_record('course', array('id' => $courseid));
cae83708 677 $cm = $DB->get_record('course_modules', array('id' => $modid));
678 $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
679 $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
e463f508 680 $a = new stdClass();
1c7b8b93 681 $a->type = get_string('modulename', $cm->modname);
c5dc10ee 682 $PAGE->set_cm($cm, $course);
1c7b8b93
NC
683 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
684 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 685 }
b73d1ca4 686
1c7b8b93
NC
687 // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
688 // Note: if action is set to 'add' or 'edit', we do this at the end
689 if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
41b38360 690 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
1c7b8b93 691 $PAGE->navbar->add($strblogentries, $blogurl);
8ebbb06a
SH
692 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
693 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
694 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
1c7b8b93 695 // $headers['strview'] = get_string('viewsiteentries', 'blog');
4a8b890a 696 }
c2ee4e87 697
1c7b8b93 698 // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information
cae83708 699 if (!empty($entryid)) {
1c7b8b93
NC
700 $headers['filters']['entry'] = $entryid;
701 $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
cae83708 702 $user = $DB->get_record_sql($sql, array($entryid));
1c7b8b93 703 $entry = $DB->get_record('post', array('id' => $entryid));
c2ee4e87 704
1c7b8b93 705 $blogurl->param('userid', $user->id);
c2ee4e87 706
cae83708 707 if (!empty($course)) {
9366362a 708 $mycourseid = $course->id;
1c7b8b93 709 $blogurl->param('courseid', $mycourseid);
c2ee4e87 710 } else {
9366362a 711 $mycourseid = $site->id;
c2ee4e87 712 }
41b38360 713 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
e14de6f9 714
1c7b8b93
NC
715 $PAGE->navbar->add($strblogentries, $blogurl);
716
717 $blogurl->remove_params('userid');
718 $PAGE->navbar->add($entry->subject, $blogurl);
8ebbb06a
SH
719 $PAGE->set_title("$shortname: " . fullname($user) . ": $entry->subject");
720 $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
cae83708 721 $headers['heading'] = get_string('blogentrybyuser', 'blog', fullname($user));
722
723 // We ignore tag and search params
1c7b8b93
NC
724 if (empty($action) || !$CFG->useblogassociations) {
725 $headers['url'] = $blogurl;
9366362a 726 return $headers;
727 }
c2ee4e87 728 }
240075cd 729
1c7b8b93
NC
730 // Case 3: A user's blog entries
731 if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
41b38360 732 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
1c7b8b93 733 $blogurl->param('userid', $userid);
8ebbb06a
SH
734 $PAGE->set_title("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
735 $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
cae83708 736 $headers['heading'] = get_string('userblog', 'blog', fullname($user));
27bad0a6 737 $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
1c7b8b93
NC
738
739 } else
cae83708 740
1c7b8b93
NC
741 // Case 4: No blog associations, no userid
742 if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
41b38360 743 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
8ebbb06a
SH
744 $PAGE->set_title("$shortname: " . get_string('blog', 'blog'));
745 $PAGE->set_heading("$shortname: " . get_string('blog', 'blog'));
746 $headers['heading'] = get_string('siteblog', 'blog', $shortname);
cae83708 747 } else
748
1c7b8b93 749 // Case 5: Blog entries associated with an activity by a specific user (courseid ignored)
9366362a 750 if (!empty($userid) && !empty($modid) && empty($entryid)) {
41b38360 751 $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
1c7b8b93
NC
752 $blogurl->param('userid', $userid);
753 $blogurl->param('modid', $modid);
cae83708 754
755 // Course module navigation is handled by build_navigation as the second param
756 $headers['cm'] = $cm;
c5dc10ee 757 $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
1c7b8b93 758 $PAGE->navbar->add($strblogentries, $blogurl);
cae83708 759
8ebbb06a
SH
760 $PAGE->set_title("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
761 $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
cae83708 762
e463f508 763 $a = new stdClass();
cae83708 764 $a->user = fullname($user);
765 $a->mod = $cm->name;
1c7b8b93 766 $a->type = get_string('modulename', $cm->modname);
cae83708 767 $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
1c7b8b93
NC
768 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
769 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 770 } else
771
1c7b8b93 772 // Case 6: Blog entries associated with a course by a specific user
9366362a 773 if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
41b38360
AG
774 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
775 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1c7b8b93
NC
776 $blogurl->param('userid', $userid);
777 $blogurl->param('courseid', $courseid);
2c27b6ae 778
1c7b8b93 779 $PAGE->navbar->add($strblogentries, $blogurl);
cae83708 780
8ebbb06a
SH
781 $PAGE->set_title("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
782 $PAGE->set_heading("$siteshortname: $courseshortname: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
cae83708 783
e463f508 784 $a = new stdClass();
cae83708 785 $a->user = fullname($user);
41b38360 786 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1c7b8b93 787 $a->type = get_string('course');
cae83708 788 $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
1c7b8b93
NC
789 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
790 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
791
792 // Remove the userid from the URL to inform the blog_menu block correctly
793 $blogurl->remove_params(array('userid'));
cae83708 794 } else
795
1c7b8b93 796 // Case 7: Blog entries by members of a group, associated with that group's course
9366362a 797 if (!empty($groupid) && empty($modid) && empty($entryid)) {
41b38360
AG
798 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
799 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1c7b8b93 800 $blogurl->param('courseid', $course->id);
e14de6f9 801
1c7b8b93
NC
802 $PAGE->navbar->add($strblogentries, $blogurl);
803 $blogurl->remove_params(array('courseid'));
804 $blogurl->param('groupid', $groupid);
805 $PAGE->navbar->add($group->name, $blogurl);
cae83708 806
8ebbb06a
SH
807 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
808 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog') . ": $group->name");
cae83708 809
e463f508 810 $a = new stdClass();
cae83708 811 $a->group = $group->name;
41b38360 812 $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
1c7b8b93 813 $a->type = get_string('course');
cae83708 814 $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
1c7b8b93
NC
815 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
816 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
cae83708 817 } else
818
1c7b8b93 819 // Case 8: Blog entries by members of a group, associated with an activity in that course
9366362a 820 if (!empty($groupid) && !empty($modid) && empty($entryid)) {
41b38360
AG
821 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
822 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
cae83708 823 $headers['cm'] = $cm;
1c7b8b93
NC
824 $blogurl->param('modid', $modid);
825 $PAGE->navbar->add($strblogentries, $blogurl);
cae83708 826
1c7b8b93
NC
827 $blogurl->param('groupid', $groupid);
828 $PAGE->navbar->add($group->name, $blogurl);
cae83708 829
8ebbb06a
SH
830 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
831 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog') . ": $group->name");
cae83708 832
e463f508 833 $a = new stdClass();
cae83708 834 $a->group = $group->name;
835 $a->mod = $cm->name;
1c7b8b93 836 $a->type = get_string('modulename', $cm->modname);
cae83708 837 $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
1c7b8b93
NC
838 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
839 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 840
841 } else
842
1c7b8b93 843 // Case 9: All blog entries associated with an activity
9366362a 844 if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
41b38360
AG
845 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
846 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
c5dc10ee 847 $PAGE->set_cm($cm, $course);
1c7b8b93
NC
848 $blogurl->param('modid', $modid);
849 $PAGE->navbar->add($strblogentries, $blogurl);
8ebbb06a
SH
850 $PAGE->set_title("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
851 $PAGE->set_heading("$siteshortname: $courseshortname: $cm->name: " . get_string('blogentries', 'blog'));
cae83708 852 $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
e463f508 853 $a = new stdClass();
1c7b8b93
NC
854 $a->type = get_string('modulename', $cm->modname);
855 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
856 $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
cae83708 857 } else
858
1c7b8b93 859 // Case 10: All blog entries associated with a course
9366362a 860 if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
41b38360
AG
861 $siteshortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
862 $courseshortname = format_string($course->shortname, true, array('context' => context_course::instance($course->id)));
1c7b8b93
NC
863 $blogurl->param('courseid', $courseid);
864 $PAGE->navbar->add($strblogentries, $blogurl);
8ebbb06a
SH
865 $PAGE->set_title("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
866 $PAGE->set_heading("$siteshortname: $courseshortname: " . get_string('blogentries', 'blog'));
e463f508 867 $a = new stdClass();
1c7b8b93 868 $a->type = get_string('course');
41b38360 869 $headers['heading'] = get_string('blogentriesabout', 'blog', format_string($course->fullname, true, array('context' => context_course::instance($course->id))));
1c7b8b93
NC
870 $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
871 $headers['strview'] = get_string('viewblogentries', 'blog', $a);
872 $blogurl->remove_params(array('userid'));
873 }
874
875 if (!in_array($action, array('edit', 'add'))) {
876 // Append Tag info
877 if (!empty($tagid)) {
878 $headers['filters']['tag'] = $tagid;
879 $blogurl->param('tagid', $tagid);
880 $tagrec = $DB->get_record('tag', array('id'=>$tagid));
881 $PAGE->navbar->add($tagrec->name, $blogurl);
882 } elseif (!empty($tag)) {
1af9063e
AA
883 if ($tagrec = $DB->get_record('tag', array('name' => $tag))) {
884 $tagid = $tagrec->id;
885 $headers['filters']['tag'] = $tagid;
886 $blogurl->param('tag', $tag);
887 $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
888 }
1c7b8b93 889 }
240075cd 890
1c7b8b93
NC
891 // Append Search info
892 if (!empty($search)) {
893 $headers['filters']['search'] = $search;
894 $blogurl->param('search', $search);
895 $PAGE->navbar->add(get_string('searchterm', 'blog', $search), $blogurl->out());
896 }
ee00eb8c 897 }
898
cae83708 899 // Append edit mode info
900 if (!empty($action) && $action == 'add') {
f36b47ef 901
cae83708 902 } else if (!empty($action) && $action == 'edit') {
c5dc10ee 903 $PAGE->navbar->add(get_string('editentry', 'blog'));
240075cd 904 }
ee00eb8c 905
1c7b8b93
NC
906 if (empty($headers['url'])) {
907 $headers['url'] = $blogurl;
908 }
cae83708 909 return $headers;
910}
23677261 911
1c7b8b93
NC
912/**
913 * Shortcut function for getting a count of blog entries associated with a course or a module
914 * @param int $courseid The ID of the course
915 * @param int $cmid The ID of the course_modules
916 * @return string The number of associated entries
917 */
918function blog_get_associated_count($courseid, $cmid=null) {
919 global $DB;
41b38360 920 $context = context_course::instance($courseid);
1c7b8b93 921 if ($cmid) {
41b38360 922 $context = context_module::instance($cmid);
1c7b8b93
NC
923 }
924 return $DB->count_records('blog_association', array('contextid' => $context->id));
593270c6 925}
c1951ea9
DC
926
927/**
928 * Running addtional permission check on plugin, for example, plugins
929 * may have switch to turn on/off comments option, this callback will
930 * affect UI display, not like pluginname_comment_validate only throw
931 * exceptions.
9a909b1a
RT
932 * blog_comment_validate will be called before viewing/adding/deleting
933 * comment, so don't repeat checks.
c1951ea9
DC
934 * Capability check has been done in comment->check_permissions(), we
935 * don't need to do it again here.
936 *
35453657
DC
937 * @package core_blog
938 * @category comment
939 *
c1951ea9
DC
940 * @param stdClass $comment_param {
941 * context => context the context object
942 * courseid => int course id
943 * cm => stdClass course module object
944 * commentarea => string comment area
945 * itemid => int itemid
946 * }
947 * @return array
948 */
949function blog_comment_permissions($comment_param) {
9a909b1a
RT
950 global $DB;
951
952 // If blog is public and current user is guest, then don't let him post comments.
953 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), 'publishstate', MUST_EXIST);
954
955 if ($blogentry->publishstate != 'public') {
956 if (!isloggedin() || isguestuser()) {
957 return array('post' => false, 'view' => true);
958 }
959 }
960 return array('post' => true, 'view' => true);
c1951ea9
DC
961}
962
963/**
964 * Validate comment parameter before perform other comments actions
965 *
35453657
DC
966 * @package core_blog
967 * @category comment
968 *
c1951ea9
DC
969 * @param stdClass $comment {
970 * context => context the context object
971 * courseid => int course id
972 * cm => stdClass course module object
973 * commentarea => string comment area
974 * itemid => int itemid
975 * }
976 * @return boolean
977 */
978function blog_comment_validate($comment_param) {
9a909b1a
RT
979 global $CFG, $DB, $USER;
980
981 // Check if blogs are enabled user can comment.
982 if (empty($CFG->enableblogs) || empty($CFG->blogusecomments)) {
983 throw new comment_exception('nopermissiontocomment');
c1951ea9 984 }
9a909b1a 985
89f5e430 986 // Validate comment area.
c1951ea9
DC
987 if ($comment_param->commentarea != 'format_blog') {
988 throw new comment_exception('invalidcommentarea');
989 }
9a909b1a
RT
990
991 $blogentry = $DB->get_record('post', array('id' => $comment_param->itemid), '*', MUST_EXIST);
992
89f5e430 993 // Validation for comment deletion.
c1951ea9
DC
994 if (!empty($comment_param->commentid)) {
995 if ($record = $DB->get_record('comments', array('id'=>$comment_param->commentid))) {
996 if ($record->commentarea != 'format_blog') {
997 throw new comment_exception('invalidcommentarea');
998 }
999 if ($record->contextid != $comment_param->context->id) {
1000 throw new comment_exception('invalidcontext');
1001 }
1002 if ($record->itemid != $comment_param->itemid) {
1003 throw new comment_exception('invalidcommentitemid');
1004 }
1005 } else {
1006 throw new comment_exception('invalidcommentid');
1007 }
1008 }
9a909b1a
RT
1009
1010 // Validate if user has blog view permission.
1011 $sitecontext = context_system::instance();
1012 return has_capability('moodle/blog:view', $sitecontext) &&
1013 blog_user_can_view_user_entry($blogentry->userid, $blogentry);
c1951ea9 1014}
b1627a92
DC
1015
1016/**
1017 * Return a list of page types
1018 * @param string $pagetype current page type
1019 * @param stdClass $parentcontext Block's parent context
1020 * @param stdClass $currentcontext Current context of block
1021 */
b38e2e28 1022function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
b1627a92
DC
1023 return array(
1024 '*'=>get_string('page-x', 'pagetype'),
1025 'blog-*'=>get_string('page-blog-x', 'blog'),
1026 'blog-index'=>get_string('page-blog-index', 'blog'),
1027 'blog-edit'=>get_string('page-blog-edit', 'blog')
1028 );
1029}