MDL-46218 reshuffled access checks in blog and notes
[moodle.git] / blog / locallib.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 * Classes for Blogs.
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 27defined('MOODLE_INTERNAL') || die();
cae83708 28
99d19c13
PS
29require_once($CFG->libdir . '/filelib.php');
30
cae83708 31/**
32 * Blog_entry class. Represents an entry in a user's blog. Contains all methods for managing this entry.
33 * This class does not contain any HTML-generating code. See blog_listing sub-classes for such code.
34 * This class follows the Object Relational Mapping technique, its member variables being mapped to
1c7b8b93 35 * the fields of the post table.
cae83708 36 *
37 * @package moodlecore
38 * @subpackage blog
39 * @copyright 2009 Nicolas Connault
40 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41 */
2591c7ae 42class blog_entry implements renderable {
cae83708 43 // Public Database fields
44 public $id;
45 public $userid;
46 public $subject;
47 public $summary;
1c7b8b93
NC
48 public $rating = 0;
49 public $attachment;
cae83708 50 public $publishstate;
51
52 // Locked Database fields (Don't touch these)
1c7b8b93
NC
53 public $courseid = 0;
54 public $groupid = 0;
55 public $module = 'blog';
56 public $moduleid = 0;
57 public $coursemoduleid = 0;
cae83708 58 public $content;
59 public $format = 1;
1c7b8b93 60 public $uniquehash = '';
cae83708 61 public $lastmodified;
62 public $created;
63 public $usermodified;
64
65 // Other class variables
66 public $form;
67 public $tags = array();
68
f8133217 69 /** @var StdClass Data needed to render the entry */
2591c7ae
DM
70 public $renderable;
71
cae83708 72 // Methods
73 /**
74 * Constructor. If given an id, will fetch the corresponding record from the DB.
75 *
b73d1ca4 76 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
cae83708 77 */
1c7b8b93 78 public function __construct($id=null, $params=null, $form=null) {
af7e05d6 79 global $DB, $PAGE, $CFG;
cae83708 80
1c7b8b93
NC
81 if (!empty($id)) {
82 $object = $DB->get_record('post', array('id' => $id));
cae83708 83 foreach ($object as $var => $val) {
84 $this->$var = $val;
85 }
1c7b8b93
NC
86 } else if (!empty($params) && (is_array($params) || is_object($params))) {
87 foreach ($params as $var => $val) {
cae83708 88 $this->$var = $val;
89 }
90 }
91
af7e05d6
EL
92 if (!empty($CFG->useblogassociations)) {
93 $associations = $DB->get_records('blog_association', array('blogid' => $this->id));
94 foreach ($associations as $association) {
95 $context = context::instance_by_id($association->contextid);
96 if ($context->contextlevel == CONTEXT_COURSE) {
97 $this->courseassoc = $association->contextid;
98 } else if ($context->contextlevel == CONTEXT_MODULE) {
99 $this->modassoc = $association->contextid;
100 }
101 }
102 }
103
cae83708 104 $this->form = $form;
105 }
106
2591c7ae 107
cae83708 108 /**
2591c7ae 109 * Gets the required data to print the entry
cae83708 110 */
2591c7ae 111 public function prepare_render() {
cae83708 112
2591c7ae 113 global $DB, $CFG, $PAGE;
b73d1ca4 114
2591c7ae 115 $this->renderable = new StdClass();
cae83708 116
2591c7ae 117 $this->renderable->user = $DB->get_record('user', array('id'=>$this->userid));
cae83708 118
af7e05d6
EL
119 // Entry comments.
120 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
2591c7ae 121 require_once($CFG->dirroot . '/comment/lib.php');
af7e05d6
EL
122
123 $cmt = new stdClass();
124 $cmt->context = context_user::instance($this->userid);
125 $cmt->courseid = $PAGE->course->id;
126 $cmt->area = 'format_blog';
127 $cmt->itemid = $this->id;
128 $cmt->showcount = $CFG->blogshowcommentscount;
129 $cmt->component = 'blog';
130 $this->renderable->comment = new comment($cmt);
cae83708 131 }
2591c7ae 132
af7e05d6
EL
133 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
134
135 // External blog link.
136 if ($this->uniquehash && $this->content) {
137 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
138 $urlparts = parse_url($externalblog->url);
f8133217 139 $this->renderable->externalblogtext = get_string('retrievedfrom', 'blog') . get_string('labelsep', 'langconfig');
af7e05d6
EL
140 $this->renderable->externalblogtext .= html_writer::link($urlparts['scheme'] . '://'.$urlparts['host'], $externalblog->name);
141 }
cae83708 142 }
f8133217
DM
143
144 // Retrieve associations
145 $this->renderable->unassociatedentry = false;
146 if (!empty($CFG->useblogassociations)) {
af7e05d6 147
f8133217
DM
148 // Adding the entry associations data.
149 if ($associations = $associations = $DB->get_records('blog_association', array('blogid' => $this->id))) {
af7e05d6
EL
150
151 // Check to see if the entry is unassociated with group/course level access.
152 if ($this->publishstate == 'group' || $this->publishstate == 'course') {
153 $this->renderable->unassociatedentry = true;
f8133217 154 }
af7e05d6
EL
155
156 foreach ($associations as $key => $assocrec) {
1c7b8b93 157
f8133217
DM
158 if (!$context = context::instance_by_id($assocrec->contextid, IGNORE_MISSING)) {
159 unset($associations[$key]);
160 continue;
161 }
2591c7ae 162
f8133217
DM
163 // The renderer will need the contextlevel of the association.
164 $associations[$key]->contextlevel = $context->contextlevel;
af7e05d6
EL
165
166 // Course associations.
2591c7ae
DM
167 if ($context->contextlevel == CONTEXT_COURSE) {
168 $instancename = $DB->get_field('course', 'shortname', array('id' => $context->instanceid)); //TODO: performance!!!!
f8133217 169
2591c7ae
DM
170 $associations[$key]->url = $assocurl = new moodle_url('/course/view.php', array('id' => $context->instanceid));
171 $associations[$key]->text = $instancename;
af7e05d6 172 $associations[$key]->icon = new pix_icon('i/course', $associations[$key]->text);
5f4d4d80 173 }
174
f8133217 175 // Mod associations.
2591c7ae 176 if ($context->contextlevel == CONTEXT_MODULE) {
cae83708 177
f8133217
DM
178 // Getting the activity type and the activity instance id
179 $sql = 'SELECT cm.instance, m.name FROM {course_modules} cm
180 JOIN {modules} m ON m.id = cm.module
181 WHERE cm.id = :cmid';
182 $modinfo = $DB->get_record_sql($sql, array('cmid' => $context->instanceid));
183 $instancename = $DB->get_field($modinfo->name, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
cae83708 184
f8133217
DM
185 $associations[$key]->type = get_string('modulename', $modinfo->name);
186 $associations[$key]->url = new moodle_url('/mod/' . $modinfo->name . '/view.php', array('id' => $context->instanceid));
2591c7ae 187 $associations[$key]->text = $instancename;
f8133217 188 $associations[$key]->icon = new pix_icon('icon', $associations[$key]->text, $modinfo->name);
af7e05d6 189 }
cae83708 190 }
191 }
af7e05d6
EL
192 $this->renderable->blogassociations = $associations;
193 }
cae83708 194
f8133217 195 // Entry attachments.
2591c7ae 196 $this->renderable->attachments = $this->get_attachments();
cae83708 197
2591c7ae
DM
198 $this->renderable->usercanedit = blog_user_can_edit_entry($this);
199 }
cae83708 200
cae83708 201
2591c7ae
DM
202 /**
203 * Gets the entry attachments list
204 * @return array List of blog_entry_attachment instances
205 */
206 function get_attachments() {
207
af7e05d6
EL
208 global $CFG;
209
210 require_once($CFG->libdir.'/filelib.php');
211
f8133217 212 $syscontext = context_system::instance();
af7e05d6 213
2591c7ae 214 $fs = get_file_storage();
af7e05d6 215 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
cae83708 216
f8133217 217 // Adding a blog_entry_attachment for each non-directory file.
af7e05d6
EL
218 $attachments = array();
219 foreach ($files as $file) {
220 if ($file->is_directory()) {
221 continue;
4def8463 222 }
af7e05d6
EL
223 $attachments[] = new blog_entry_attachment($file, $this->id);
224 }
cae83708 225
2591c7ae 226 return $attachments;
cae83708 227 }
228
229 /**
230 * Inserts this entry in the database. Access control checks must be done by calling code.
231 *
232 * @param mform $form Used for attachments
233 * @return void
234 */
235 public function process_attachment($form) {
236 $this->form = $form;
237 }
238
239 /**
240 * Inserts this entry in the database. Access control checks must be done by calling code.
241 * TODO Set the publishstate correctly
cae83708 242 * @return void
243 */
244 public function add() {
245 global $CFG, $USER, $DB;
246
247 unset($this->id);
248 $this->module = 'blog';
249 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
250 $this->lastmodified = time();
251 $this->created = time();
252
253 // Insert the new blog entry.
9d97f08e 254 $this->id = $DB->insert_record('post', $this);
cae83708 255
9d97f08e
PS
256 // Update tags.
257 $this->add_tags_info();
cae83708 258
9d97f08e
PS
259 if (!empty($CFG->useblogassociations)) {
260 $this->add_associations();
cae83708 261 }
9d97f08e 262
cc033d48 263 tag_set('post', $this->id, $this->tags, 'core', context_user::instance($this->userid)->id);
3049780a
AA
264
265 // Trigger an event for the new entry.
77037e27
AA
266 $event = \core\event\blog_entry_created::create(array(
267 'objectid' => $this->id,
aa139299 268 'relateduserid' => $this->userid
77037e27 269 ));
24c32bdf 270 $event->set_blog_entry($this);
3049780a 271 $event->trigger();
cae83708 272 }
273
274 /**
275 * Updates this entry in the database. Access control checks must be done by calling code.
276 *
32dea439
AA
277 * @param array $params Entry parameters.
278 * @param moodleform $form Used for attachments.
279 * @param array $summaryoptions Summary options.
280 * @param array $attachmentoptions Attachment options.
281 *
cae83708 282 * @return void
283 */
1c7b8b93 284 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
32dea439 285 global $CFG, $DB;
cae83708 286
41b38360 287 $sitecontext = context_system::instance();
1c7b8b93
NC
288 $entry = $this;
289
cae83708 290 $this->form = $form;
291 foreach ($params as $var => $val) {
1c7b8b93 292 $entry->$var = $val;
cae83708 293 }
294
64f93798
PS
295 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
296 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
b73d1ca4 297
5f4d4d80 298 if (!empty($CFG->useblogassociations)) {
1c7b8b93 299 $entry->add_associations();
cae83708 300 }
301
1c7b8b93
NC
302 $entry->lastmodified = time();
303
32dea439 304 // Update record.
1c7b8b93 305 $DB->update_record('post', $entry);
cc033d48 306 tag_set('post', $entry->id, $entry->tags, 'core', context_user::instance($this->userid)->id);
cae83708 307
32dea439
AA
308 $event = \core\event\blog_entry_updated::create(array(
309 'objectid' => $entry->id,
aa139299 310 'relateduserid' => $entry->userid
32dea439 311 ));
24c32bdf 312 $event->set_blog_entry($entry);
32dea439 313 $event->trigger();
cae83708 314 }
315
316 /**
317 * Deletes this entry from the database. Access control checks must be done by calling code.
318 *
319 * @return void
320 */
321 public function delete() {
ac31c38e 322 global $DB;
cae83708 323
cae83708 324 $this->delete_attachments();
ac31c38e 325 $this->remove_associations();
cae83708 326
6c66b7f3
AA
327 // Get record to pass onto the event.
328 $record = $DB->get_record('post', array('id' => $this->id));
1c7b8b93 329 $DB->delete_records('post', array('id' => $this->id));
cc033d48 330 tag_set('post', $this->id, array(), 'core', context_user::instance($this->userid)->id);
cae83708 331
77037e27
AA
332 $event = \core\event\blog_entry_deleted::create(array(
333 'objectid' => $this->id,
aa139299
RT
334 'relateduserid' => $this->userid
335 ));
6c66b7f3 336 $event->add_record_snapshot("post", $record);
24c32bdf 337 $event->set_blog_entry($this);
6c66b7f3 338 $event->trigger();
cae83708 339 }
340
341 /**
6b364115
AA
342 * Function to add all context associations to an entry.
343 * TODO : Remove $action in 2.9 (MDL-41330)
344 *
345 * @param string $action - This does nothing, do not use it. This is present only for Backward compatibility.
cae83708 346 */
6b364115
AA
347 public function add_associations($action = null) {
348
349 if (!empty($action)) {
350 debugging('blog_entry->add_associations() does not accept any argument', DEBUG_DEVELOPER);
351 }
cae83708 352
cae83708 353 $this->remove_associations();
354
355 if (!empty($this->courseassoc)) {
6b364115 356 $this->add_association($this->courseassoc);
cae83708 357 }
358
359 if (!empty($this->modassoc)) {
6b364115 360 $this->add_association($this->modassoc);
cae83708 361 }
362 }
363
364 /**
6b364115
AA
365 * Add a single association for a blog entry
366 * TODO : Remove $action in 2.9 (MDL-41330)
367 *
368 * @param int $contextid - id of context to associate with the blog entry.
369 * @param string $action - This does nothing, do not use it. This is present only for Backward compatibility.
cae83708 370 */
6b364115
AA
371 public function add_association($contextid, $action = null) {
372 global $DB;
373
374 if (!empty($action)) {
375 debugging('blog_entry->add_association() accepts only one argument', DEBUG_DEVELOPER);
376 }
cae83708 377
1c7b8b93
NC
378 $assocobject = new StdClass;
379 $assocobject->contextid = $contextid;
380 $assocobject->blogid = $this->id;
6b364115 381 $id = $DB->insert_record('blog_association', $assocobject);
1c7b8b93 382
6b364115 383 // Trigger an association created event.
41b38360 384 $context = context::instance_by_id($contextid);
6b364115
AA
385 $eventparam = array(
386 'objectid' => $id,
387 'other' => array('associateid' => $context->instanceid, 'subject' => $this->subject, 'blogid' => $this->id),
388 'relateduserid' => $this->userid
389 );
1c7b8b93 390 if ($context->contextlevel == CONTEXT_COURSE) {
6b364115
AA
391 $eventparam['other']['associatetype'] = 'course';
392
1c7b8b93 393 } else if ($context->contextlevel == CONTEXT_MODULE) {
6b364115 394 $eventparam['other']['associatetype'] = 'coursemodule';
1c7b8b93 395 }
6b364115
AA
396 $event = \core\event\blog_association_created::create($eventparam);
397 $event->trigger();
cae83708 398 }
399
400 /**
401 * remove all associations for a blog entry
402 * @return voic
403 */
404 public function remove_associations() {
405 global $DB;
406 $DB->delete_records('blog_association', array('blogid' => $this->id));
407 }
408
409 /**
410 * Deletes all the user files in the attachments area for an entry
411 *
412 * @return void
413 */
414 public function delete_attachments() {
415 $fs = get_file_storage();
64f93798
PS
416 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
417 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
cae83708 418 }
419
cae83708 420 /**
421 * function to attach tags into an entry
422 * @return void
423 */
424 public function add_tags_info() {
425
426 $tags = array();
427
428 if ($otags = optional_param('otags', '', PARAM_INT)) {
429 foreach ($otags as $tagid) {
430 // TODO : make this use the tag name in the form
431 if ($tag = tag_get('id', $tagid)) {
432 $tags[] = $tag->name;
433 }
434 }
435 }
436
cc033d48 437 tag_set('post', $this->id, $tags, 'core', context_user::instance($this->userid)->id);
cae83708 438 }
439
440 /**
441 * User can edit a blog entry if this is their own blog entry and they have
442 * the capability moodle/blog:create, or if they have the capability
443 * moodle/blog:manageentries.
444 * This also applies to deleting of entries.
445 *
446 * @param int $userid Optional. If not given, $USER is used
447 * @return boolean
448 */
449 public function can_user_edit($userid=null) {
450 global $CFG, $USER;
451
452 if (empty($userid)) {
453 $userid = $USER->id;
454 }
455
41b38360 456 $sitecontext = context_system::instance();
cae83708 457
458 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
459 return true; // can edit any blog entry
460 }
461
462 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
463 return true; // can edit own when having blog:create capability
464 }
465
466 return false;
467 }
468
469 /**
470 * Checks to see if a user can view the blogs of another user.
471 * Only blog level is checked here, the capabilities are enforced
472 * in blog/index.php
473 *
474 * @param int $targetuserid ID of the user we are checking
475 *
476 * @return bool
477 */
478 public function can_user_view($targetuserid) {
479 global $CFG, $USER, $DB;
41b38360 480 $sitecontext = context_system::instance();
cae83708 481
850d2db8 482 if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) {
1c7b8b93 483 return false; // blog system disabled or user has no blog view capability
cae83708 484 }
485
4f0c2d00 486 if (isloggedin() && $USER->id == $targetuserid) {
cae83708 487 return true; // can view own entries in any case
488 }
489
cae83708 490 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
491 return true; // can manage all entries
492 }
493
494 // coming for 1 entry, make sure it's not a draft
1c7b8b93 495 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
cae83708 496 return false; // can not view draft of others
497 }
498
499 // coming for 1 entry, make sure user is logged in, if not a public blog
1c7b8b93 500 if ($this->publishstate != 'public' && !isloggedin()) {
cae83708 501 return false;
502 }
503
504 switch ($CFG->bloglevel) {
505 case BLOG_GLOBAL_LEVEL:
506 return true;
507 break;
508
509 case BLOG_SITE_LEVEL:
4f0c2d00 510 if (isloggedin()) { // not logged in viewers forbidden
cae83708 511 return true;
512 }
513 return false;
514 break;
515
516 case BLOG_USER_LEVEL:
517 default:
41b38360 518 $personalcontext = context_user::instance($targetuserid);
cae83708 519 return has_capability('moodle/user:readuserblogs', $personalcontext);
520 break;
521 }
522 }
523
524 /**
525 * Use this function to retrieve a list of publish states available for
526 * the currently logged in user.
527 *
528 * @return array This function returns an array ideal for sending to moodles'
529 * choose_from_menu function.
530 */
531
532 public static function get_applicable_publish_states() {
533 global $CFG;
534 $options = array();
535
536 // everyone gets draft access
537 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
1c7b8b93 538 $options['draft'] = get_string('publishtonoone', 'blog');
cae83708 539 }
540
541 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
1c7b8b93 542 $options['site'] = get_string('publishtosite', 'blog');
cae83708 543 }
544
545 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
1c7b8b93 546 $options['public'] = get_string('publishtoworld', 'blog');
cae83708 547 }
548
549 return $options;
550 }
551}
552
553/**
554 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
555 *
556 * @package moodlecore
557 * @subpackage blog
558 * @copyright 2009 Nicolas Connault
559 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
560 */
561class blog_listing {
562 /**
563 * Array of blog_entry objects.
564 * @var array $entries
565 */
566 public $entries = array();
567
568 /**
569 * An array of blog_filter_* objects
570 * @var array $filters
571 */
572 public $filters = array();
573
574 /**
575 * Constructor
576 *
577 * @param array $filters An associative array of filtername => filterid
578 */
579 public function __construct($filters=array()) {
580 // Unset filters overridden by more specific filters
581 foreach ($filters as $type => $id) {
582 if (!empty($type) && !empty($id)) {
583 $this->filters[$type] = blog_filter::get_instance($id, $type);
584 }
585 }
586
587 foreach ($this->filters as $type => $filter) {
588 foreach ($filter->overrides as $override) {
589 if (array_key_exists($override, $this->filters)) {
590 unset($this->filters[$override]);
591 }
592 }
593 }
594 }
595
596 /**
597 * Fetches the array of blog entries.
598 *
599 * @return array
600 */
601 public function get_entries($start=0, $limit=10) {
602 global $DB;
603
604 if (empty($this->entries)) {
899d5e2d 605 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
af3158d8 606 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
cae83708 607 } else {
608 return false;
609 }
610 }
611
612 return $this->entries;
613 }
614
615 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
616 global $DB, $USER, $CFG;
617
618 if(!$userid) {
619 $userid = $USER->id;
620 }
621
506c8d59 622 $allnamefields = get_all_user_name_fields(true, 'u');
cae83708 623 // The query used to locate blog entries is complicated. It will be built from the following components:
506c8d59 624 $requiredfields = "p.*, $allnamefields, u.email"; // the SELECT clause
1c7b8b93
NC
625 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
626 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
cae83708 627
628 // build up a clause for permission constraints
629
630 $params = array();
631
632 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
633 // admins can see all blogs regardless of publish states, as described on the help page
41b38360 634 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
cae83708 635 // don't add permission constraints
636
637 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
41b38360 638 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
cae83708 639 // don't add permission constraints
640
641 } else {
4f0c2d00 642 if (isloggedin() and !isguestuser()) {
cae83708 643 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
644
645 //begin permission sql clause
1c7b8b93 646 $permissionsql = '(p.userid = ? ';
cae83708 647 $params[] = $userid;
648
649 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
1c7b8b93 650 $permissionsql .= " OR p.publishstate = 'site' ";
cae83708 651 }
652
653 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
1c7b8b93 654 $permissionsql .= " OR p.publishstate = 'public' ";
cae83708 655 }
656
657 $permissionsql .= ') '; //close permissions sql clause
658 } else { // default is access to public entries
1c7b8b93 659 $permissionsql = "p.publishstate = 'public'";
cae83708 660 }
661 $conditions[] = $permissionsql; //add permission constraints
662 }
663
1c7b8b93
NC
664 foreach ($this->filters as $type => $blogfilter) {
665 $conditions = array_merge($conditions, $blogfilter->conditions);
666 $params = array_merge($params, $blogfilter->params);
667 $tables = array_merge($tables, $blogfilter->tables);
cae83708 668 }
669
670 $tablessql = ''; // build up the FROM clause
671 foreach ($tables as $tablename => $table) {
672 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
673 }
674
675 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
676 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
527761e0 677 $sql .= ($count) ? '' : " ORDER BY $sort";
cae83708 678
679 return array('sql' => $sql, 'params' => $params);
680 }
681
682 /**
683 * Outputs all the blog entries aggregated by this blog listing.
684 *
685 * @return void
686 */
687 public function print_entries() {
2591c7ae 688 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
41b38360 689 $sitecontext = context_system::instance();
cae83708 690
af7e05d6 691 // Blog renderer
2591c7ae
DM
692 $output = $PAGE->get_renderer('blog');
693
cae83708 694 $page = optional_param('blogpage', 0, PARAM_INT);
695 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
696 $start = $page * $limit;
697
698 $morelink = '<br />&nbsp;&nbsp;';
699
1c7b8b93
NC
700 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
701 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
cae83708 702 } else {
703 $totalentries = 0;
704 }
705
706 $entries = $this->get_entries($start, $limit);
929d7a83 707 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
cae83708 708 $pagingbar->pagevar = 'blogpage';
1c7b8b93 709 $blogheaders = blog_get_headers();
cae83708 710
929d7a83 711 echo $OUTPUT->render($pagingbar);
cae83708 712
cae83708 713 if (has_capability('moodle/blog:create', $sitecontext)) {
714 //the user's blog is enabled and they are viewing their own blog
715 $userid = optional_param('userid', null, PARAM_INT);
716
717 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
4219ffab 718
207b6fc5 719 $courseid = optional_param('courseid', null, PARAM_INT);
4ef08298
AA
720 $modid = optional_param('modid', null, PARAM_INT);
721
722 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
723 $urlparams = array('action' => 'add',
724 'userid' => $userid,
725 'courseid' => $courseid,
726 'groupid' => optional_param('groupid', null, PARAM_INT),
727 'modid' => $modid,
728 'tagid' => optional_param('tagid', null, PARAM_INT),
729 'tag' => optional_param('tag', null, PARAM_INT),
730 'search' => optional_param('search', null, PARAM_INT));
731
732 $urlparams = array_filter($urlparams);
733 $addurl->params($urlparams);
734
735 $addlink = '<div class="addbloglink">';
736 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
737 $addlink .= '</div>';
738 echo $addlink;
cae83708 739 }
740 }
741
742 if ($entries) {
743 $count = 0;
cae83708 744 foreach ($entries as $entry) {
1c7b8b93 745 $blogentry = new blog_entry(null, $entry);
2591c7ae
DM
746
747 // Get the required blog entry data to render it
748 $blogentry->prepare_render();
749 echo $output->render($blogentry);
750
cae83708 751 $count++;
752 }
753
929d7a83 754 echo $OUTPUT->render($pagingbar);
cae83708 755
756 if (!$count) {
757 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
758 }
759
760 print $morelink.'<br />'."\n";
761 return;
762 }
763 }
764
765 /// Find the base url from $_GET variables, for print_paging_bar
766 public function get_baseurl() {
767 $getcopy = $_GET;
768
769 unset($getcopy['blogpage']);
770
771 if (!empty($getcopy)) {
772 $first = false;
773 $querystring = '';
774
775 foreach ($getcopy as $var => $val) {
776 if (!$first) {
777 $first = true;
778 $querystring .= "?$var=$val";
779 } else {
780 $querystring .= '&amp;'.$var.'='.$val;
781 $hasparam = true;
782 }
783 }
784 } else {
785 $querystring = '?';
786 }
787
788 return strip_querystring(qualified_me()) . $querystring;
789
790 }
791}
792
793/**
794 * Abstract class for blog_filter objects.
795 * A set of core filters are implemented here. To write new filters, you need to subclass
796 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
797 * The blog_filter abstract class will automatically use it when the filter is added to the
798 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
799 * or have any other meaning you wish it to have. The second parameter is called $type and is
800 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
801 */
802abstract class blog_filter {
803 /**
804 * An array of strings representing the available filter types for each blog_filter.
1c7b8b93 805 * @var array $availabletypes
cae83708 806 */
1c7b8b93 807 public $availabletypes = array();
cae83708 808
809 /**
810 * The type of filter (for example, types of blog_filter_context are site, course and module)
811 * @var string $type
812 */
813 public $type;
814
815 /**
816 * The unique ID for a filter's associated record
817 * @var int $id
818 */
819 public $id;
820
821 /**
822 * An array of table aliases that are used in the WHERE conditions
823 * @var array $tables
824 */
825 public $tables = array();
826
827 /**
828 * An array of WHERE conditions
829 * @var array $conditions
830 */
831 public $conditions = array();
832
833 /**
834 * An array of SQL params
835 * @var array $params
836 */
837 public $params = array();
838
839 /**
840 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
841 */
842 public $overrides = array();
843
844 public function __construct($id, $type=null) {
845 $this->id = $id;
846 $this->type = $type;
847 }
848
849 /**
850 * TODO This is poor design. A parent class should not know anything about its children.
851 * The default case helps to resolve this design issue
852 */
853 public static function get_instance($id, $type) {
854
855 switch ($type) {
856 case 'site':
857 case 'course':
858 case 'module':
859 return new blog_filter_context($id, $type);
860 break;
861
862 case 'group':
863 case 'user':
864 return new blog_filter_user($id, $type);
865 break;
866
867 case 'tag':
868 return new blog_filter_tag($id);
869 break;
870
871 default:
1c7b8b93
NC
872 $classname = "blog_filter_$type";
873 if (class_exists($classname)) {
874 return new $classname($id, $type);
cae83708 875 }
876 }
877 }
878}
879
880/**
881 * This filter defines the context level of the blog entries being searched: site, course, module
882 */
883class blog_filter_context extends blog_filter {
884 /**
885 * Constructor
886 *
887 * @param string $type
888 * @param int $id
889 */
890 public function __construct($id=null, $type='site') {
891 global $SITE, $CFG, $DB;
892
893 if (empty($id)) {
894 $this->type = 'site';
895 } else {
896 $this->id = $id;
897 $this->type = $type;
898 }
899
8eaf1ba1 900 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
cae83708 901
902 switch ($this->type) {
903 case 'course': // Careful of site course!
904 // Ignore course filter if blog associations are not enabled
905 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
906 $this->overrides = array('site');
41b38360 907 $context = context_course::instance($this->id);
cae83708 908 $this->tables['ba'] = 'blog_association';
1c7b8b93 909 $this->conditions[] = 'p.id = ba.blogid';
cae83708 910 $this->conditions[] = 'ba.contextid = '.$context->id;
911 break;
912 } else {
913 // We are dealing with the site course, do not break from the current case
914 }
915
916 case 'site':
917 // No special constraints
918 break;
919 case 'module':
920 if (!empty($CFG->useblogassociations)) {
921 $this->overrides = array('course', 'site');
922
41b38360 923 $context = context_module::instance($this->id);
cae83708 924 $this->tables['ba'] = 'blog_association';
1c7b8b93
NC
925 $this->tables['p'] = 'post';
926 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
cae83708 927 $this->params = array($context->id);
928 }
929 break;
930 }
931 }
932}
933
934/**
935 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
936 * It can be combined with a context filter in order to refine the search.
937 */
938class blog_filter_user extends blog_filter {
939 public $tables = array('u' => 'user');
940
941 /**
942 * Constructor
943 *
944 * @param string $type
945 * @param int $id
946 */
947 public function __construct($id=null, $type='user') {
320ae23a 948 global $CFG, $DB, $USER;
1c7b8b93 949 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
cae83708 950
951 if (empty($id)) {
952 $this->id = $USER->id;
953 $this->type = 'user';
954 } else {
955 $this->id = $id;
956 $this->type = $type;
957 }
958
959 if ($this->type == 'user') {
960 $this->conditions = array('u.id = ?');
961 $this->params = array($this->id);
962 $this->overrides = array('group');
963
964 } elseif ($this->type == 'group') {
965 $this->overrides = array('course', 'site');
966
967 $this->tables['gm'] = 'groups_members';
1c7b8b93 968 $this->conditions[] = 'p.userid = gm.userid';
cae83708 969 $this->conditions[] = 'gm.groupid = ?';
970 $this->params[] = $this->id;
971
972 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
41b38360 973 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
cae83708 974 $this->tables['ba'] = 'blog_association';
975 $this->conditions[] = 'gm.groupid = ?';
976 $this->conditions[] = 'ba.contextid = ?';
1c7b8b93 977 $this->conditions[] = 'ba.blogid = p.id';
cae83708 978 $this->params[] = $this->id;
1c7b8b93 979 $this->params[] = $coursecontext->id;
cae83708 980 }
981 }
b73d1ca4 982
cae83708 983 }
984}
985
986/**
987 * This filter defines a tag by which blog entries should be searched.
988 */
989class blog_filter_tag extends blog_filter {
1c7b8b93 990 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
cae83708 991
992 /**
993 * Constructor
994 *
995 * @return void
996 */
997 public function __construct($id) {
998 global $DB;
999 $this->id = $id;
1000
1001 $this->conditions = array('ti.tagid = t.id',
1c7b8b93
NC
1002 "ti.itemtype = 'post'",
1003 'ti.itemid = p.id',
cae83708 1004 't.id = ?');
1005 $this->params = array($this->id);
1006 }
1007}
1008
1009/**
1010 * This filter defines a specific blog entry id.
1011 */
1012class blog_filter_entry extends blog_filter {
1013 public $conditions = array('p.id = ?');
1014 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1015
1016 public function __construct($id) {
1017 $this->id = $id;
1018 $this->params[] = $this->id;
1019 }
1020}
1021
1c7b8b93 1022/**
caee6e6c 1023 * This filter restricts the results to a time interval in seconds up to time()
1c7b8b93
NC
1024 */
1025class blog_filter_since extends blog_filter {
1026 public function __construct($interval) {
1027 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
caee6e6c
PS
1028 $this->params[] = time() - $interval;
1029 $this->params[] = time();
1c7b8b93
NC
1030 }
1031}
1032
cae83708 1033/**
1034 * Filter used to perform full-text search on an entry's subject, summary and content
1035 */
1036class blog_filter_search extends blog_filter {
1037
1c7b8b93 1038 public function __construct($searchterm) {
cae83708 1039 global $DB;
c014d57c
PS
1040 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1041 ".$DB->sql_like('p.content', '?', false)." OR
1042 ".$DB->sql_like('p.subject', '?', false).")");
1c7b8b93
NC
1043 $this->params[] = "%$searchterm%";
1044 $this->params[] = "%$searchterm%";
1045 $this->params[] = "%$searchterm%";
cae83708 1046 }
1047}
2591c7ae
DM
1048
1049
1050/**
1051 * Renderable class to represent an entry attachment
1052 */
1053class blog_entry_attachment implements renderable {
1054
1055 public $filename;
1056 public $url;
1057 public $file;
1058
1059 /**
f8133217
DM
1060 * Gets the file data
1061 *
2591c7ae
DM
1062 * @param stored_file $file
1063 * @param int $entryid Attachment entry id
1064 */
1065 public function __construct($file, $entryid) {
1066
f8133217 1067 global $CFG;
2591c7ae
DM
1068
1069 $this->file = $file;
af7e05d6
EL
1070 $this->filename = $file->get_filename();
1071 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);
2591c7ae
DM
1072 }
1073
1074}