MDL-40040 events: Add unit tests for blog events
[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
PS
262
263 tag_set('post', $this->id, $this->tags);
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 ));
3049780a
AA
270 $event->set_custom_data($this);
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
NC
305 $DB->update_record('post', $entry);
306 tag_set('post', $entry->id, $entry->tags);
cae83708 307
32dea439
AA
308 $event = \core\event\blog_entry_updated::create(array(
309 'objectid' => $entry->id,
aa139299 310 'relateduserid' => $entry->userid
32dea439
AA
311 ));
312 $event->set_custom_data($entry);
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
NC
329 $DB->delete_records('post', array('id' => $this->id));
330 tag_set('post', $this->id, array());
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
AA
336 $event->add_record_snapshot("post", $record);
337 $event->set_custom_data($this);
338 $event->trigger();
cae83708 339 }
340
341 /**
342 * function to add all context associations to an entry
343 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
344 */
1c7b8b93 345 public function add_associations($action='add') {
cae83708 346 global $DB, $USER;
347
cae83708 348 $this->remove_associations();
349
350 if (!empty($this->courseassoc)) {
1c7b8b93 351 $this->add_association($this->courseassoc, $action);
cae83708 352 }
353
354 if (!empty($this->modassoc)) {
1c7b8b93 355 $this->add_association($this->modassoc, $action);
cae83708 356 }
357 }
358
359 /**
360 * add a single association for a blog entry
361 * @param int contextid - id of context to associate with the blog entry
362 */
1c7b8b93
NC
363 public function add_association($contextid, $action='add') {
364 global $DB, $USER;
cae83708 365
1c7b8b93
NC
366 $assocobject = new StdClass;
367 $assocobject->contextid = $contextid;
368 $assocobject->blogid = $this->id;
369 $DB->insert_record('blog_association', $assocobject);
370
41b38360 371 $context = context::instance_by_id($contextid);
1c7b8b93
NC
372 $courseid = null;
373
374 if ($context->contextlevel == CONTEXT_COURSE) {
375 $courseid = $context->instanceid;
376 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
377 } else if ($context->contextlevel == CONTEXT_MODULE) {
378 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
379 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
380 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
381 }
cae83708 382 }
383
384 /**
385 * remove all associations for a blog entry
386 * @return voic
387 */
388 public function remove_associations() {
389 global $DB;
390 $DB->delete_records('blog_association', array('blogid' => $this->id));
391 }
392
393 /**
394 * Deletes all the user files in the attachments area for an entry
395 *
396 * @return void
397 */
398 public function delete_attachments() {
399 $fs = get_file_storage();
64f93798
PS
400 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
401 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
cae83708 402 }
403
cae83708 404 /**
405 * function to attach tags into an entry
406 * @return void
407 */
408 public function add_tags_info() {
409
410 $tags = array();
411
412 if ($otags = optional_param('otags', '', PARAM_INT)) {
413 foreach ($otags as $tagid) {
414 // TODO : make this use the tag name in the form
415 if ($tag = tag_get('id', $tagid)) {
416 $tags[] = $tag->name;
417 }
418 }
419 }
420
1c7b8b93 421 tag_set('post', $this->id, $tags);
cae83708 422 }
423
424 /**
425 * User can edit a blog entry if this is their own blog entry and they have
426 * the capability moodle/blog:create, or if they have the capability
427 * moodle/blog:manageentries.
428 * This also applies to deleting of entries.
429 *
430 * @param int $userid Optional. If not given, $USER is used
431 * @return boolean
432 */
433 public function can_user_edit($userid=null) {
434 global $CFG, $USER;
435
436 if (empty($userid)) {
437 $userid = $USER->id;
438 }
439
41b38360 440 $sitecontext = context_system::instance();
cae83708 441
442 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
443 return true; // can edit any blog entry
444 }
445
446 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
447 return true; // can edit own when having blog:create capability
448 }
449
450 return false;
451 }
452
453 /**
454 * Checks to see if a user can view the blogs of another user.
455 * Only blog level is checked here, the capabilities are enforced
456 * in blog/index.php
457 *
458 * @param int $targetuserid ID of the user we are checking
459 *
460 * @return bool
461 */
462 public function can_user_view($targetuserid) {
463 global $CFG, $USER, $DB;
41b38360 464 $sitecontext = context_system::instance();
cae83708 465
850d2db8 466 if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $sitecontext)) {
1c7b8b93 467 return false; // blog system disabled or user has no blog view capability
cae83708 468 }
469
4f0c2d00 470 if (isloggedin() && $USER->id == $targetuserid) {
cae83708 471 return true; // can view own entries in any case
472 }
473
cae83708 474 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
475 return true; // can manage all entries
476 }
477
478 // coming for 1 entry, make sure it's not a draft
1c7b8b93 479 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
cae83708 480 return false; // can not view draft of others
481 }
482
483 // coming for 1 entry, make sure user is logged in, if not a public blog
1c7b8b93 484 if ($this->publishstate != 'public' && !isloggedin()) {
cae83708 485 return false;
486 }
487
488 switch ($CFG->bloglevel) {
489 case BLOG_GLOBAL_LEVEL:
490 return true;
491 break;
492
493 case BLOG_SITE_LEVEL:
4f0c2d00 494 if (isloggedin()) { // not logged in viewers forbidden
cae83708 495 return true;
496 }
497 return false;
498 break;
499
500 case BLOG_USER_LEVEL:
501 default:
41b38360 502 $personalcontext = context_user::instance($targetuserid);
cae83708 503 return has_capability('moodle/user:readuserblogs', $personalcontext);
504 break;
505 }
506 }
507
508 /**
509 * Use this function to retrieve a list of publish states available for
510 * the currently logged in user.
511 *
512 * @return array This function returns an array ideal for sending to moodles'
513 * choose_from_menu function.
514 */
515
516 public static function get_applicable_publish_states() {
517 global $CFG;
518 $options = array();
519
520 // everyone gets draft access
521 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
1c7b8b93 522 $options['draft'] = get_string('publishtonoone', 'blog');
cae83708 523 }
524
525 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
1c7b8b93 526 $options['site'] = get_string('publishtosite', 'blog');
cae83708 527 }
528
529 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
1c7b8b93 530 $options['public'] = get_string('publishtoworld', 'blog');
cae83708 531 }
532
533 return $options;
534 }
535}
536
537/**
538 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
539 *
540 * @package moodlecore
541 * @subpackage blog
542 * @copyright 2009 Nicolas Connault
543 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
544 */
545class blog_listing {
546 /**
547 * Array of blog_entry objects.
548 * @var array $entries
549 */
550 public $entries = array();
551
552 /**
553 * An array of blog_filter_* objects
554 * @var array $filters
555 */
556 public $filters = array();
557
558 /**
559 * Constructor
560 *
561 * @param array $filters An associative array of filtername => filterid
562 */
563 public function __construct($filters=array()) {
564 // Unset filters overridden by more specific filters
565 foreach ($filters as $type => $id) {
566 if (!empty($type) && !empty($id)) {
567 $this->filters[$type] = blog_filter::get_instance($id, $type);
568 }
569 }
570
571 foreach ($this->filters as $type => $filter) {
572 foreach ($filter->overrides as $override) {
573 if (array_key_exists($override, $this->filters)) {
574 unset($this->filters[$override]);
575 }
576 }
577 }
578 }
579
580 /**
581 * Fetches the array of blog entries.
582 *
583 * @return array
584 */
585 public function get_entries($start=0, $limit=10) {
586 global $DB;
587
588 if (empty($this->entries)) {
899d5e2d 589 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
af3158d8 590 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
cae83708 591 } else {
592 return false;
593 }
594 }
595
596 return $this->entries;
597 }
598
599 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
600 global $DB, $USER, $CFG;
601
602 if(!$userid) {
603 $userid = $USER->id;
604 }
605
506c8d59 606 $allnamefields = get_all_user_name_fields(true, 'u');
cae83708 607 // The query used to locate blog entries is complicated. It will be built from the following components:
506c8d59 608 $requiredfields = "p.*, $allnamefields, u.email"; // the SELECT clause
1c7b8b93
NC
609 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
610 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
cae83708 611
612 // build up a clause for permission constraints
613
614 $params = array();
615
616 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
617 // admins can see all blogs regardless of publish states, as described on the help page
41b38360 618 if (has_capability('moodle/user:readuserblogs', context_system::instance())) {
cae83708 619 // don't add permission constraints
620
621 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
41b38360 622 context_user::instance((empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
cae83708 623 // don't add permission constraints
624
625 } else {
4f0c2d00 626 if (isloggedin() and !isguestuser()) {
cae83708 627 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
628
629 //begin permission sql clause
1c7b8b93 630 $permissionsql = '(p.userid = ? ';
cae83708 631 $params[] = $userid;
632
633 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
1c7b8b93 634 $permissionsql .= " OR p.publishstate = 'site' ";
cae83708 635 }
636
637 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
1c7b8b93 638 $permissionsql .= " OR p.publishstate = 'public' ";
cae83708 639 }
640
641 $permissionsql .= ') '; //close permissions sql clause
642 } else { // default is access to public entries
1c7b8b93 643 $permissionsql = "p.publishstate = 'public'";
cae83708 644 }
645 $conditions[] = $permissionsql; //add permission constraints
646 }
647
1c7b8b93
NC
648 foreach ($this->filters as $type => $blogfilter) {
649 $conditions = array_merge($conditions, $blogfilter->conditions);
650 $params = array_merge($params, $blogfilter->params);
651 $tables = array_merge($tables, $blogfilter->tables);
cae83708 652 }
653
654 $tablessql = ''; // build up the FROM clause
655 foreach ($tables as $tablename => $table) {
656 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
657 }
658
659 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
660 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
527761e0 661 $sql .= ($count) ? '' : " ORDER BY $sort";
cae83708 662
663 return array('sql' => $sql, 'params' => $params);
664 }
665
666 /**
667 * Outputs all the blog entries aggregated by this blog listing.
668 *
669 * @return void
670 */
671 public function print_entries() {
2591c7ae 672 global $CFG, $USER, $DB, $OUTPUT, $PAGE;
41b38360 673 $sitecontext = context_system::instance();
cae83708 674
af7e05d6 675 // Blog renderer
2591c7ae
DM
676 $output = $PAGE->get_renderer('blog');
677
cae83708 678 $page = optional_param('blogpage', 0, PARAM_INT);
679 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
680 $start = $page * $limit;
681
682 $morelink = '<br />&nbsp;&nbsp;';
683
1c7b8b93
NC
684 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
685 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
cae83708 686 } else {
687 $totalentries = 0;
688 }
689
690 $entries = $this->get_entries($start, $limit);
929d7a83 691 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
cae83708 692 $pagingbar->pagevar = 'blogpage';
1c7b8b93 693 $blogheaders = blog_get_headers();
cae83708 694
929d7a83 695 echo $OUTPUT->render($pagingbar);
cae83708 696
cae83708 697 if (has_capability('moodle/blog:create', $sitecontext)) {
698 //the user's blog is enabled and they are viewing their own blog
699 $userid = optional_param('userid', null, PARAM_INT);
700
701 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
4219ffab 702
207b6fc5 703 $courseid = optional_param('courseid', null, PARAM_INT);
4ef08298
AA
704 $modid = optional_param('modid', null, PARAM_INT);
705
706 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
707 $urlparams = array('action' => 'add',
708 'userid' => $userid,
709 'courseid' => $courseid,
710 'groupid' => optional_param('groupid', null, PARAM_INT),
711 'modid' => $modid,
712 'tagid' => optional_param('tagid', null, PARAM_INT),
713 'tag' => optional_param('tag', null, PARAM_INT),
714 'search' => optional_param('search', null, PARAM_INT));
715
716 $urlparams = array_filter($urlparams);
717 $addurl->params($urlparams);
718
719 $addlink = '<div class="addbloglink">';
720 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
721 $addlink .= '</div>';
722 echo $addlink;
cae83708 723 }
724 }
725
726 if ($entries) {
727 $count = 0;
cae83708 728 foreach ($entries as $entry) {
1c7b8b93 729 $blogentry = new blog_entry(null, $entry);
2591c7ae
DM
730
731 // Get the required blog entry data to render it
732 $blogentry->prepare_render();
733 echo $output->render($blogentry);
734
cae83708 735 $count++;
736 }
737
929d7a83 738 echo $OUTPUT->render($pagingbar);
cae83708 739
740 if (!$count) {
741 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
742 }
743
744 print $morelink.'<br />'."\n";
745 return;
746 }
747 }
748
749 /// Find the base url from $_GET variables, for print_paging_bar
750 public function get_baseurl() {
751 $getcopy = $_GET;
752
753 unset($getcopy['blogpage']);
754
755 if (!empty($getcopy)) {
756 $first = false;
757 $querystring = '';
758
759 foreach ($getcopy as $var => $val) {
760 if (!$first) {
761 $first = true;
762 $querystring .= "?$var=$val";
763 } else {
764 $querystring .= '&amp;'.$var.'='.$val;
765 $hasparam = true;
766 }
767 }
768 } else {
769 $querystring = '?';
770 }
771
772 return strip_querystring(qualified_me()) . $querystring;
773
774 }
775}
776
777/**
778 * Abstract class for blog_filter objects.
779 * A set of core filters are implemented here. To write new filters, you need to subclass
780 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
781 * The blog_filter abstract class will automatically use it when the filter is added to the
782 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
783 * or have any other meaning you wish it to have. The second parameter is called $type and is
784 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
785 */
786abstract class blog_filter {
787 /**
788 * An array of strings representing the available filter types for each blog_filter.
1c7b8b93 789 * @var array $availabletypes
cae83708 790 */
1c7b8b93 791 public $availabletypes = array();
cae83708 792
793 /**
794 * The type of filter (for example, types of blog_filter_context are site, course and module)
795 * @var string $type
796 */
797 public $type;
798
799 /**
800 * The unique ID for a filter's associated record
801 * @var int $id
802 */
803 public $id;
804
805 /**
806 * An array of table aliases that are used in the WHERE conditions
807 * @var array $tables
808 */
809 public $tables = array();
810
811 /**
812 * An array of WHERE conditions
813 * @var array $conditions
814 */
815 public $conditions = array();
816
817 /**
818 * An array of SQL params
819 * @var array $params
820 */
821 public $params = array();
822
823 /**
824 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
825 */
826 public $overrides = array();
827
828 public function __construct($id, $type=null) {
829 $this->id = $id;
830 $this->type = $type;
831 }
832
833 /**
834 * TODO This is poor design. A parent class should not know anything about its children.
835 * The default case helps to resolve this design issue
836 */
837 public static function get_instance($id, $type) {
838
839 switch ($type) {
840 case 'site':
841 case 'course':
842 case 'module':
843 return new blog_filter_context($id, $type);
844 break;
845
846 case 'group':
847 case 'user':
848 return new blog_filter_user($id, $type);
849 break;
850
851 case 'tag':
852 return new blog_filter_tag($id);
853 break;
854
855 default:
1c7b8b93
NC
856 $classname = "blog_filter_$type";
857 if (class_exists($classname)) {
858 return new $classname($id, $type);
cae83708 859 }
860 }
861 }
862}
863
864/**
865 * This filter defines the context level of the blog entries being searched: site, course, module
866 */
867class blog_filter_context extends blog_filter {
868 /**
869 * Constructor
870 *
871 * @param string $type
872 * @param int $id
873 */
874 public function __construct($id=null, $type='site') {
875 global $SITE, $CFG, $DB;
876
877 if (empty($id)) {
878 $this->type = 'site';
879 } else {
880 $this->id = $id;
881 $this->type = $type;
882 }
883
8eaf1ba1 884 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
cae83708 885
886 switch ($this->type) {
887 case 'course': // Careful of site course!
888 // Ignore course filter if blog associations are not enabled
889 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
890 $this->overrides = array('site');
41b38360 891 $context = context_course::instance($this->id);
cae83708 892 $this->tables['ba'] = 'blog_association';
1c7b8b93 893 $this->conditions[] = 'p.id = ba.blogid';
cae83708 894 $this->conditions[] = 'ba.contextid = '.$context->id;
895 break;
896 } else {
897 // We are dealing with the site course, do not break from the current case
898 }
899
900 case 'site':
901 // No special constraints
902 break;
903 case 'module':
904 if (!empty($CFG->useblogassociations)) {
905 $this->overrides = array('course', 'site');
906
41b38360 907 $context = context_module::instance($this->id);
cae83708 908 $this->tables['ba'] = 'blog_association';
1c7b8b93
NC
909 $this->tables['p'] = 'post';
910 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
cae83708 911 $this->params = array($context->id);
912 }
913 break;
914 }
915 }
916}
917
918/**
919 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
920 * It can be combined with a context filter in order to refine the search.
921 */
922class blog_filter_user extends blog_filter {
923 public $tables = array('u' => 'user');
924
925 /**
926 * Constructor
927 *
928 * @param string $type
929 * @param int $id
930 */
931 public function __construct($id=null, $type='user') {
320ae23a 932 global $CFG, $DB, $USER;
1c7b8b93 933 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
cae83708 934
935 if (empty($id)) {
936 $this->id = $USER->id;
937 $this->type = 'user';
938 } else {
939 $this->id = $id;
940 $this->type = $type;
941 }
942
943 if ($this->type == 'user') {
944 $this->conditions = array('u.id = ?');
945 $this->params = array($this->id);
946 $this->overrides = array('group');
947
948 } elseif ($this->type == 'group') {
949 $this->overrides = array('course', 'site');
950
951 $this->tables['gm'] = 'groups_members';
1c7b8b93 952 $this->conditions[] = 'p.userid = gm.userid';
cae83708 953 $this->conditions[] = 'gm.groupid = ?';
954 $this->params[] = $this->id;
955
956 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
41b38360 957 $coursecontext = context_course::instance($DB->get_field('groups', 'courseid', array('id' => $this->id)));
cae83708 958 $this->tables['ba'] = 'blog_association';
959 $this->conditions[] = 'gm.groupid = ?';
960 $this->conditions[] = 'ba.contextid = ?';
1c7b8b93 961 $this->conditions[] = 'ba.blogid = p.id';
cae83708 962 $this->params[] = $this->id;
1c7b8b93 963 $this->params[] = $coursecontext->id;
cae83708 964 }
965 }
b73d1ca4 966
cae83708 967 }
968}
969
970/**
971 * This filter defines a tag by which blog entries should be searched.
972 */
973class blog_filter_tag extends blog_filter {
1c7b8b93 974 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
cae83708 975
976 /**
977 * Constructor
978 *
979 * @return void
980 */
981 public function __construct($id) {
982 global $DB;
983 $this->id = $id;
984
985 $this->conditions = array('ti.tagid = t.id',
1c7b8b93
NC
986 "ti.itemtype = 'post'",
987 'ti.itemid = p.id',
cae83708 988 't.id = ?');
989 $this->params = array($this->id);
990 }
991}
992
993/**
994 * This filter defines a specific blog entry id.
995 */
996class blog_filter_entry extends blog_filter {
997 public $conditions = array('p.id = ?');
998 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
999
1000 public function __construct($id) {
1001 $this->id = $id;
1002 $this->params[] = $this->id;
1003 }
1004}
1005
1c7b8b93 1006/**
caee6e6c 1007 * This filter restricts the results to a time interval in seconds up to time()
1c7b8b93
NC
1008 */
1009class blog_filter_since extends blog_filter {
1010 public function __construct($interval) {
1011 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
caee6e6c
PS
1012 $this->params[] = time() - $interval;
1013 $this->params[] = time();
1c7b8b93
NC
1014 }
1015}
1016
cae83708 1017/**
1018 * Filter used to perform full-text search on an entry's subject, summary and content
1019 */
1020class blog_filter_search extends blog_filter {
1021
1c7b8b93 1022 public function __construct($searchterm) {
cae83708 1023 global $DB;
c014d57c
PS
1024 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1025 ".$DB->sql_like('p.content', '?', false)." OR
1026 ".$DB->sql_like('p.subject', '?', false).")");
1c7b8b93
NC
1027 $this->params[] = "%$searchterm%";
1028 $this->params[] = "%$searchterm%";
1029 $this->params[] = "%$searchterm%";
cae83708 1030 }
1031}
2591c7ae
DM
1032
1033
1034/**
1035 * Renderable class to represent an entry attachment
1036 */
1037class blog_entry_attachment implements renderable {
1038
1039 public $filename;
1040 public $url;
1041 public $file;
1042
1043 /**
f8133217
DM
1044 * Gets the file data
1045 *
2591c7ae
DM
1046 * @param stored_file $file
1047 * @param int $entryid Attachment entry id
1048 */
1049 public function __construct($file, $entryid) {
1050
f8133217 1051 global $CFG;
2591c7ae
DM
1052
1053 $this->file = $file;
af7e05d6
EL
1054 $this->filename = $file->get_filename();
1055 $this->url = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$entryid.'/'.$this->filename);
2591c7ae
DM
1056 }
1057
1058}