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