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