MDL-25840 blog - fixed broken image file image attachment display
[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 */
42class blog_entry {
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
69 // Methods
70 /**
71 * Constructor. If given an id, will fetch the corresponding record from the DB.
72 *
b73d1ca4 73 * @param mixed $idorparams A blog entry id if INT, or data for a new entry if array
cae83708 74 */
1c7b8b93 75 public function __construct($id=null, $params=null, $form=null) {
b73d1ca4 76 global $DB, $PAGE;
cae83708 77
1c7b8b93
NC
78 if (!empty($id)) {
79 $object = $DB->get_record('post', array('id' => $id));
cae83708 80 foreach ($object as $var => $val) {
81 $this->$var = $val;
82 }
1c7b8b93
NC
83 } else if (!empty($params) && (is_array($params) || is_object($params))) {
84 foreach ($params as $var => $val) {
cae83708 85 $this->$var = $val;
86 }
87 }
88
89 $this->form = $form;
90 }
91
92 /**
93 * Prints or returns the HTML for this blog entry.
94 *
95 * @param bool $return
96 * @return string
97 */
98 public function print_html($return=false) {
99
b73d1ca4 100 global $USER, $CFG, $COURSE, $DB, $OUTPUT, $PAGE;
101
cae83708 102 $user = $DB->get_record('user', array('id'=>$this->userid));
35716b86
PS
103 $cmttext = '';
104 if (!empty($CFG->usecomments) and $CFG->blogusecomments) {
105 require_once($CFG->dirroot . '/comment/lib.php');
db954aba
DC
106 // Comments
107 $cmt = new stdClass();
108 $cmt->context = get_context_instance(CONTEXT_USER, $user->id);
109 $cmt->courseid = $PAGE->course->id;
110 $cmt->area = 'format_blog';
db954aba
DC
111 $cmt->itemid = $this->id;
112 $cmt->showcount = $CFG->blogshowcommentscount;
d846488e 113 $cmt->component = 'blog';
35716b86
PS
114 $comment = new comment($cmt);
115 $cmttext = $comment->output(true);
db954aba 116 }
64f93798 117 $this->summary = file_rewrite_pluginfile_urls($this->summary, 'pluginfile.php', SYSCONTEXTID, 'blog', 'post', $this->id);
cae83708 118
367a75fa
SH
119 $options = array('overflowdiv'=>true);
120 $template['body'] = format_text($this->summary, $this->summaryformat, $options).$cmttext;
8397492b 121 $template['title'] = format_string($this->subject);
cae83708 122 $template['userid'] = $user->id;
123 $template['author'] = fullname($user);
124 $template['created'] = userdate($this->created);
125
8397492b 126 if ($this->created != $this->lastmodified) {
cae83708 127 $template['lastmod'] = userdate($this->lastmodified);
128 }
129
130 $template['publishstate'] = $this->publishstate;
131
132 $stredit = get_string('edit');
133 $strdelete = get_string('delete');
134
1c7b8b93 135 // Check to see if the entry is unassociated with group/course level access
cae83708 136 $unassociatedentry = false;
137 if (!empty($CFG->useblogassociations) && ($this->publishstate == 'group' || $this->publishstate == 'course')) {
138 if (!$DB->record_exists('blog_association', array('blogid' => $this->id))) {
139 $unassociatedentry = true;
140 }
141 }
142
1c7b8b93 143 // Start printing of the blog
cae83708 144 $table = new html_table();
145 $table->cellspacing = 0;
16be8974 146 $table->attributes['class'] = 'forumpost blog_entry blog'. ($unassociatedentry ? 'draft' : $template['publishstate']);
8397492b 147 $table->attributes['id'] = 'b'.$this->id;
cae83708 148 $table->width = '100%';
149
150 $picturecell = new html_table_cell();
16be8974 151 $picturecell->attributes['class'] = 'picture left';
812dbaf7 152 $picturecell->text = $OUTPUT->user_picture($user);
cae83708 153
154 $table->head[] = $picturecell;
155
156 $topiccell = new html_table_cell();
16be8974 157 $topiccell->attributes['class'] = 'topic starter';
8397492b
MD
158 $titlelink = html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), $template['title']);
159 $topiccell->text = $OUTPUT->container($titlelink, 'subject');
cae83708 160 $topiccell->text .= $OUTPUT->container_start('author');
161
513a73df 162 $fullname = fullname($user, has_capability('moodle/site:viewfullnames', get_context_instance(CONTEXT_COURSE, $PAGE->course->id)));
e463f508 163 $by = new stdClass();
513a73df 164 $by->name = html_writer::link(new moodle_url('/user/view.php', array('id' => $user->id, 'course' => $PAGE->course->id)), $fullname);
cae83708 165 $by->date = $template['created'];
166
167 $topiccell->text .= get_string('bynameondate', 'forum', $by);
168 $topiccell->text .= $OUTPUT->container_end();
1c7b8b93
NC
169
170 if ($this->uniquehash && $this->content) {
171 if ($externalblog = $DB->get_record('blog_external', array('id' => $this->content))) {
172 $urlparts = parse_url($externalblog->url);
995f2d51 173 $topiccell->text .= $OUTPUT->container(get_string('retrievedfrom', 'blog').get_string('labelsep', 'langconfig').html_writer::link($urlparts['scheme'].'://'.$urlparts['host'], $externalblog->name), 'externalblog');
1c7b8b93
NC
174 }
175 }
176
cae83708 177 $topiccell->header = false;
178 $table->head[] = $topiccell;
179
1c7b8b93 180 // Actual content
cae83708 181 $mainrow = new html_table_row();
182
183 $leftsidecell = new html_table_cell();
16be8974 184 $leftsidecell->attributes['class'] = 'left side';
cae83708 185 $mainrow->cells[] = $leftsidecell;
186
187 $contentcell = new html_table_cell();
16be8974 188 $contentcell->attributes['class'] = 'content';
cae83708 189
90156096 190 $attachedimages = $OUTPUT->container($this->print_attachments(), 'attachments');
cae83708 191
1c7b8b93 192 // retrieve associations in case they're needed early
5f4d4d80 193 $blogassociations = $DB->get_records('blog_association', array('blogid' => $this->id));
1c7b8b93
NC
194
195 // determine text for publish state
cae83708 196 switch ($template['publishstate']) {
1c7b8b93 197 case 'draft':
cae83708 198 $blogtype = get_string('publishtonoone', 'blog');
199 break;
1c7b8b93 200 case 'site':
cae83708 201 $blogtype = get_string('publishtosite', 'blog');
202 break;
1c7b8b93 203 case 'public':
cae83708 204 $blogtype = get_string('publishtoworld', 'blog');
205 break;
206 default:
207 $blogtype = '';
208 break;
209
210 }
211
212 $contentcell->text .= $OUTPUT->container($blogtype, 'audience');
213
214 $contentcell->text .= $template['body'];
215 $contentcell->text .= $attachedimages;
216
1c7b8b93
NC
217 // Uniquehash is used as a link to an external blog
218 if (!empty($this->uniquehash)) {
cae83708 219 $contentcell->text .= $OUTPUT->container_start('externalblog');
0f4c64b7 220 $contentcell->text .= html_writer::link($this->uniquehash, get_string('linktooriginalentry', 'blog'));
cae83708 221 $contentcell->text .= $OUTPUT->container_end();
222 }
223
224 // Links to tags
1c7b8b93
NC
225 $officialtags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'official');
226 $defaulttags = tag_get_tags_csv('post', $this->id, TAG_RETURN_HTML, 'default');
cae83708 227
1c7b8b93 228 if (!empty($CFG->usetags) && ($officialtags || $defaulttags) ) {
cae83708 229 $contentcell->text .= $OUTPUT->container_start('tags');
230
1c7b8b93
NC
231 if ($officialtags) {
232 $contentcell->text .= get_string('tags', 'tag') .': '. $OUTPUT->container($officialtags, 'officialblogtags');
233 if ($defaulttags) {
234 $contentcell->text .= ', ';
235 }
cae83708 236 }
1c7b8b93 237 $contentcell->text .= $defaulttags;
cae83708 238 $contentcell->text .= $OUTPUT->container_end();
239 }
240
1c7b8b93 241 // Add associations
5f4d4d80 242 if (!empty($CFG->useblogassociations) && $blogassociations) {
cae83708 243 $contentcell->text .= $OUTPUT->container_start('tags');
5f4d4d80 244 $assocstr = '';
245 $hascourseassocs = false;
1c7b8b93 246 $assoctype = '';
cae83708 247
1c7b8b93
NC
248 // First find and show the associated course
249 foreach ($blogassociations as $assocrec) {
250 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid));
251 if ($contextrec->contextlevel == CONTEXT_COURSE) {
a1dc03b5 252 $assocurl = new moodle_url('/course/view.php', array('id' => $contextrec->instanceid));
8ae8bf8a 253 $text = $DB->get_field('course', 'shortname', array('id' => $contextrec->instanceid)); //TODO: performance!!!!
a1dc03b5 254 $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('i/course', $text), null, array(), true);
5f4d4d80 255 $hascourseassocs = true;
1c7b8b93 256 $assoctype = get_string('course');
cae83708 257 }
258 }
259
1c7b8b93
NC
260 // Now show mod association
261 foreach ($blogassociations as $assocrec) {
262 $contextrec = $DB->get_record('context', array('id' => $assocrec->contextid));
cae83708 263
1c7b8b93 264 if ($contextrec->contextlevel == CONTEXT_MODULE) {
5f4d4d80 265 if ($hascourseassocs) {
266 $assocstr .= ', ';
267 $hascourseassocs = false;
268 }
269
1c7b8b93 270 $modinfo = $DB->get_record('course_modules', array('id' => $contextrec->instanceid));
cae83708 271 $modname = $DB->get_field('modules', 'name', array('id' => $modinfo->module));
272
a1dc03b5 273 $assocurl = new moodle_url('/mod/'.$modname.'/view.php', array('id' => $modinfo->id));
8ae8bf8a 274 $text = $DB->get_field($modname, 'name', array('id' => $modinfo->instance)); //TODO: performance!!!!
a1dc03b5 275 $assocstr .= $OUTPUT->action_icon($assocurl, new pix_icon('icon', $text, $modname), null, array(), true);
5f4d4d80 276 $assocstr .= ', ';
1c7b8b93 277 $assoctype = get_string('modulename', $modname);
cae83708 278
cae83708 279 }
280 }
5f4d4d80 281 $assocstr = substr($assocstr, 0, -2);
1c7b8b93 282 $contentcell->text .= get_string('associated', 'blog', $assoctype) . ': '. $assocstr;
cae83708 283
284 $contentcell->text .= $OUTPUT->container_end();
285 }
286
287 if ($unassociatedentry) {
288 $contentcell->text .= $OUTPUT->container(get_string('associationunviewable', 'blog'), 'noticebox');
289 }
290
291 /// Commands
292
293 $contentcell->text .= $OUTPUT->container_start('commands');
294
1c7b8b93 295 if (blog_user_can_edit_entry($this) && empty($this->uniquehash)) {
a6855934
PS
296 $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'edit', 'entryid' => $this->id)), $stredit) . ' | ';
297 $contentcell->text .= html_writer::link(new moodle_url('/blog/edit.php', array('action' => 'delete', 'entryid' => $this->id)), $strdelete) . ' | ';
cae83708 298 }
299
a6855934 300 $contentcell->text .= html_writer::link(new moodle_url('/blog/index.php', array('entryid' => $this->id)), get_string('permalink', 'blog'));
cae83708 301
302 $contentcell->text .= $OUTPUT->container_end();
303
304 if (isset($template['lastmod']) ){
305 $contentcell->text .= '<div style="font-size: 55%;">';
306 $contentcell->text .= ' [ '.get_string('modified').': '.$template['lastmod'].' ]';
307 $contentcell->text .= '</div>';
308 }
309
310 $mainrow->cells[] = $contentcell;
311 $table->data = array($mainrow);
312
313 if ($return) {
16be8974 314 return html_writer::table($table);
cae83708 315 } else {
16be8974 316 echo html_writer::table($table);
cae83708 317 }
318 }
319
320 /**
321 * Inserts this entry in the database. Access control checks must be done by calling code.
322 *
323 * @param mform $form Used for attachments
324 * @return void
325 */
326 public function process_attachment($form) {
327 $this->form = $form;
328 }
329
330 /**
331 * Inserts this entry in the database. Access control checks must be done by calling code.
332 * TODO Set the publishstate correctly
333 * @param mform $form Used for attachments
334 * @return void
335 */
336 public function add() {
337 global $CFG, $USER, $DB;
338
339 unset($this->id);
340 $this->module = 'blog';
341 $this->userid = (empty($this->userid)) ? $USER->id : $this->userid;
342 $this->lastmodified = time();
343 $this->created = time();
344
345 // Insert the new blog entry.
9d97f08e 346 $this->id = $DB->insert_record('post', $this);
cae83708 347
9d97f08e
PS
348 // Update tags.
349 $this->add_tags_info();
cae83708 350
9d97f08e
PS
351 if (!empty($CFG->useblogassociations)) {
352 $this->add_associations();
353 add_to_log(SITEID, 'blog', 'add', 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
cae83708 354 }
9d97f08e
PS
355
356 tag_set('post', $this->id, $this->tags);
cae83708 357 }
358
359 /**
360 * Updates this entry in the database. Access control checks must be done by calling code.
361 *
362 * @param mform $form Used for attachments
363 * @return void
364 */
1c7b8b93 365 public function edit($params=array(), $form=null, $summaryoptions=array(), $attachmentoptions=array()) {
b73d1ca4 366 global $CFG, $USER, $DB, $PAGE;
cae83708 367
1c7b8b93
NC
368 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
369 $entry = $this;
370
cae83708 371 $this->form = $form;
372 foreach ($params as $var => $val) {
1c7b8b93 373 $entry->$var = $val;
cae83708 374 }
375
64f93798
PS
376 $entry = file_postupdate_standard_editor($entry, 'summary', $summaryoptions, $sitecontext, 'blog', 'post', $entry->id);
377 $entry = file_postupdate_standard_filemanager($entry, 'attachment', $attachmentoptions, $sitecontext, 'blog', 'attachment', $entry->id);
b73d1ca4 378
5f4d4d80 379 if (!empty($CFG->useblogassociations)) {
1c7b8b93 380 $entry->add_associations();
cae83708 381 }
382
1c7b8b93
NC
383 $entry->lastmodified = time();
384
cae83708 385 // Update record
1c7b8b93
NC
386 $DB->update_record('post', $entry);
387 tag_set('post', $entry->id, $entry->tags);
cae83708 388
1c7b8b93 389 add_to_log(SITEID, 'blog', 'update', 'index.php?userid='.$USER->id.'&entryid='.$entry->id, $entry->subject);
cae83708 390 }
391
392 /**
393 * Deletes this entry from the database. Access control checks must be done by calling code.
394 *
395 * @return void
396 */
397 public function delete() {
398 global $DB, $USER;
399
400 $returnurl = '';
401
cae83708 402 $this->delete_attachments();
403
1c7b8b93
NC
404 $DB->delete_records('post', array('id' => $this->id));
405 tag_set('post', $this->id, array());
cae83708 406
407 add_to_log(SITEID, 'blog', 'delete', 'index.php?userid='. $this->userid, 'deleted blog entry with entry id# '. $this->id);
408 }
409
410 /**
411 * function to add all context associations to an entry
412 * @param int entry - data object processed to include all 'entry' fields and extra data from the edit_form object
413 */
1c7b8b93 414 public function add_associations($action='add') {
cae83708 415 global $DB, $USER;
416
cae83708 417 $this->remove_associations();
418
419 if (!empty($this->courseassoc)) {
1c7b8b93 420 $this->add_association($this->courseassoc, $action);
cae83708 421 }
422
423 if (!empty($this->modassoc)) {
1c7b8b93 424 $this->add_association($this->modassoc, $action);
cae83708 425 }
426 }
427
428 /**
429 * add a single association for a blog entry
430 * @param int contextid - id of context to associate with the blog entry
431 */
1c7b8b93
NC
432 public function add_association($contextid, $action='add') {
433 global $DB, $USER;
cae83708 434
1c7b8b93
NC
435 $assocobject = new StdClass;
436 $assocobject->contextid = $contextid;
437 $assocobject->blogid = $this->id;
438 $DB->insert_record('blog_association', $assocobject);
439
440 $context = get_context_instance_by_id($contextid);
441 $courseid = null;
442
443 if ($context->contextlevel == CONTEXT_COURSE) {
444 $courseid = $context->instanceid;
445 add_to_log($courseid, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject);
446 } else if ($context->contextlevel == CONTEXT_MODULE) {
447 $cm = $DB->get_record('course_modules', array('id' => $context->instanceid));
448 $modulename = $DB->get_field('modules', 'name', array('id' => $cm->module));
449 add_to_log($cm->course, 'blog', $action, 'index.php?userid='.$this->userid.'&entryid='.$this->id, $this->subject, $cm->id, $this->userid);
450 }
cae83708 451 }
452
453 /**
454 * remove all associations for a blog entry
455 * @return voic
456 */
457 public function remove_associations() {
458 global $DB;
459 $DB->delete_records('blog_association', array('blogid' => $this->id));
460 }
461
462 /**
463 * Deletes all the user files in the attachments area for an entry
464 *
465 * @return void
466 */
467 public function delete_attachments() {
468 $fs = get_file_storage();
64f93798
PS
469 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'attachment', $this->id);
470 $fs->delete_area_files(SYSCONTEXTID, 'blog', 'post', $this->id);
cae83708 471 }
472
473 /**
474 * if return=html, then return a html string.
475 * if return=text, then return a text-only string.
476 * otherwise, print HTML for non-images, and return image HTML
477 *
478 * @param bool $return Whether to return or print the generated code
479 * @return void
480 */
481 public function print_attachments($return=false) {
1c7b8b93 482 global $CFG, $OUTPUT;
cae83708 483
484 require_once($CFG->libdir.'/filelib.php');
485
486 $fs = get_file_storage();
cae83708 487
35716b86
PS
488 $syscontext = get_context_instance(CONTEXT_SYSTEM);
489
490 $files = $fs->get_area_files($syscontext->id, 'blog', 'attachment', $this->id);
cae83708 491
492 $imagereturn = "";
493 $output = "";
494
495 $strattachment = get_string("attachment", "forum");
496
497 foreach ($files as $file) {
498 if ($file->is_directory()) {
499 continue;
500 }
501
502 $filename = $file->get_filename();
64f93798 503 $ffurl = file_encode_url($CFG->wwwroot.'/pluginfile.php', '/'.SYSCONTEXTID.'/blog/attachment/'.$this->id.'/'.$filename);
1c7b8b93 504 $mimetype = $file->get_mimetype();
cae83708 505
ede72522 506 $icon = mimeinfo_from_type("icon", $mimetype);
1c7b8b93
NC
507 $type = mimeinfo_from_type("type", $mimetype);
508
ede72522 509 $image = $OUTPUT->pix_icon("f/$icon", $filename, 'moodle', array('class'=>'icon'));
cae83708 510
511 if ($return == "html") {
000c278c 512 $output .= html_writer::link($ffurl, $image);
0f4c64b7 513 $output .= html_writer::link($ffurl, $filename);
cae83708 514
515 } else if ($return == "text") {
516 $output .= "$strattachment $filename:\n$ffurl\n";
517
518 } else {
519 if (in_array($type, array('image/gif', 'image/jpeg', 'image/png'))) { // Image attachments don't get printed as links
20b50384 520 $imagereturn .= '<br /><img src="'.$ffurl.'" alt="" />';
cae83708 521 } else {
0f4c64b7 522 $imagereturn .= html_writer::link($ffurl, $image);
35716b86 523 $imagereturn .= format_text(html_writer::link($ffurl, $filename), FORMAT_HTML, array('context'=>$syscontext));
cae83708 524 }
525 }
526 }
527
528 if ($return) {
529 return $output;
530 }
531
532 return $imagereturn;
533
534 }
535
536 /**
537 * function to attach tags into an entry
538 * @return void
539 */
540 public function add_tags_info() {
541
542 $tags = array();
543
544 if ($otags = optional_param('otags', '', PARAM_INT)) {
545 foreach ($otags as $tagid) {
546 // TODO : make this use the tag name in the form
547 if ($tag = tag_get('id', $tagid)) {
548 $tags[] = $tag->name;
549 }
550 }
551 }
552
1c7b8b93 553 tag_set('post', $this->id, $tags);
cae83708 554 }
555
556 /**
557 * User can edit a blog entry if this is their own blog entry and they have
558 * the capability moodle/blog:create, or if they have the capability
559 * moodle/blog:manageentries.
560 * This also applies to deleting of entries.
561 *
562 * @param int $userid Optional. If not given, $USER is used
563 * @return boolean
564 */
565 public function can_user_edit($userid=null) {
566 global $CFG, $USER;
567
568 if (empty($userid)) {
569 $userid = $USER->id;
570 }
571
572 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
573
574 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
575 return true; // can edit any blog entry
576 }
577
578 if ($this->userid == $userid && has_capability('moodle/blog:create', $sitecontext)) {
579 return true; // can edit own when having blog:create capability
580 }
581
582 return false;
583 }
584
585 /**
586 * Checks to see if a user can view the blogs of another user.
587 * Only blog level is checked here, the capabilities are enforced
588 * in blog/index.php
589 *
590 * @param int $targetuserid ID of the user we are checking
591 *
592 * @return bool
593 */
594 public function can_user_view($targetuserid) {
595 global $CFG, $USER, $DB;
1c7b8b93 596 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
cae83708 597
1c7b8b93
NC
598 if (empty($CFG->bloglevel) || !has_capability('moodle/blog:view', $sitecontext)) {
599 return false; // blog system disabled or user has no blog view capability
cae83708 600 }
601
4f0c2d00 602 if (isloggedin() && $USER->id == $targetuserid) {
cae83708 603 return true; // can view own entries in any case
604 }
605
cae83708 606 if (has_capability('moodle/blog:manageentries', $sitecontext)) {
607 return true; // can manage all entries
608 }
609
610 // coming for 1 entry, make sure it's not a draft
1c7b8b93 611 if ($this->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
cae83708 612 return false; // can not view draft of others
613 }
614
615 // coming for 1 entry, make sure user is logged in, if not a public blog
1c7b8b93 616 if ($this->publishstate != 'public' && !isloggedin()) {
cae83708 617 return false;
618 }
619
620 switch ($CFG->bloglevel) {
621 case BLOG_GLOBAL_LEVEL:
622 return true;
623 break;
624
625 case BLOG_SITE_LEVEL:
4f0c2d00 626 if (isloggedin()) { // not logged in viewers forbidden
cae83708 627 return true;
628 }
629 return false;
630 break;
631
632 case BLOG_USER_LEVEL:
633 default:
634 $personalcontext = get_context_instance(CONTEXT_USER, $targetuserid);
635 return has_capability('moodle/user:readuserblogs', $personalcontext);
636 break;
637 }
638 }
639
640 /**
641 * Use this function to retrieve a list of publish states available for
642 * the currently logged in user.
643 *
644 * @return array This function returns an array ideal for sending to moodles'
645 * choose_from_menu function.
646 */
647
648 public static function get_applicable_publish_states() {
649 global $CFG;
650 $options = array();
651
652 // everyone gets draft access
653 if ($CFG->bloglevel >= BLOG_USER_LEVEL) {
1c7b8b93 654 $options['draft'] = get_string('publishtonoone', 'blog');
cae83708 655 }
656
657 if ($CFG->bloglevel > BLOG_USER_LEVEL) {
1c7b8b93 658 $options['site'] = get_string('publishtosite', 'blog');
cae83708 659 }
660
661 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) {
1c7b8b93 662 $options['public'] = get_string('publishtoworld', 'blog');
cae83708 663 }
664
665 return $options;
666 }
667}
668
669/**
670 * Abstract Blog_Listing class: used to gather blog entries and output them as listings. One of the subclasses must be used.
671 *
672 * @package moodlecore
673 * @subpackage blog
674 * @copyright 2009 Nicolas Connault
675 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
676 */
677class blog_listing {
678 /**
679 * Array of blog_entry objects.
680 * @var array $entries
681 */
682 public $entries = array();
683
684 /**
685 * An array of blog_filter_* objects
686 * @var array $filters
687 */
688 public $filters = array();
689
690 /**
691 * Constructor
692 *
693 * @param array $filters An associative array of filtername => filterid
694 */
695 public function __construct($filters=array()) {
696 // Unset filters overridden by more specific filters
697 foreach ($filters as $type => $id) {
698 if (!empty($type) && !empty($id)) {
699 $this->filters[$type] = blog_filter::get_instance($id, $type);
700 }
701 }
702
703 foreach ($this->filters as $type => $filter) {
704 foreach ($filter->overrides as $override) {
705 if (array_key_exists($override, $this->filters)) {
706 unset($this->filters[$override]);
707 }
708 }
709 }
710 }
711
712 /**
713 * Fetches the array of blog entries.
714 *
715 * @return array
716 */
717 public function get_entries($start=0, $limit=10) {
718 global $DB;
719
720 if (empty($this->entries)) {
899d5e2d 721 if ($sqlarray = $this->get_entry_fetch_sql(false, 'created DESC')) {
af3158d8 722 $this->entries = $DB->get_records_sql($sqlarray['sql'], $sqlarray['params'], $start, $limit);
cae83708 723 } else {
724 return false;
725 }
726 }
727
728 return $this->entries;
729 }
730
731 public function get_entry_fetch_sql($count=false, $sort='lastmodified DESC', $userid = false) {
732 global $DB, $USER, $CFG;
733
734 if(!$userid) {
735 $userid = $USER->id;
736 }
737
738 // The query used to locate blog entries is complicated. It will be built from the following components:
1c7b8b93
NC
739 $requiredfields = "p.*, u.firstname, u.lastname, u.email"; // the SELECT clause
740 $tables = array('p' => 'post', 'u' => 'user'); // components of the FROM clause (table_id => table_name)
741 $conditions = array('u.deleted = 0', 'p.userid = u.id', '(p.module = \'blog\' OR p.module = \'blog_external\')'); // components of the WHERE clause (conjunction)
cae83708 742
743 // build up a clause for permission constraints
744
745 $params = array();
746
747 // fix for MDL-9165, use with readuserblogs capability in a user context can read that user's private blogs
748 // admins can see all blogs regardless of publish states, as described on the help page
749 if (has_capability('moodle/user:readuserblogs', get_context_instance(CONTEXT_SYSTEM))) {
750 // don't add permission constraints
751
752 } else if(!empty($this->filters['user']) && has_capability('moodle/user:readuserblogs',
753 get_context_instance(CONTEXT_USER, (empty($this->filters['user']->id) ? 0 : $this->filters['user']->id)))) {
754 // don't add permission constraints
755
756 } else {
4f0c2d00 757 if (isloggedin() and !isguestuser()) {
cae83708 758 $assocexists = $DB->record_exists('blog_association', array()); //dont check association records if there aren't any
759
760 //begin permission sql clause
1c7b8b93 761 $permissionsql = '(p.userid = ? ';
cae83708 762 $params[] = $userid;
763
764 if ($CFG->bloglevel >= BLOG_SITE_LEVEL) { // add permission to view site-level entries
1c7b8b93 765 $permissionsql .= " OR p.publishstate = 'site' ";
cae83708 766 }
767
768 if ($CFG->bloglevel >= BLOG_GLOBAL_LEVEL) { // add permission to view global entries
1c7b8b93 769 $permissionsql .= " OR p.publishstate = 'public' ";
cae83708 770 }
771
772 $permissionsql .= ') '; //close permissions sql clause
773 } else { // default is access to public entries
1c7b8b93 774 $permissionsql = "p.publishstate = 'public'";
cae83708 775 }
776 $conditions[] = $permissionsql; //add permission constraints
777 }
778
1c7b8b93
NC
779 foreach ($this->filters as $type => $blogfilter) {
780 $conditions = array_merge($conditions, $blogfilter->conditions);
781 $params = array_merge($params, $blogfilter->params);
782 $tables = array_merge($tables, $blogfilter->tables);
cae83708 783 }
784
785 $tablessql = ''; // build up the FROM clause
786 foreach ($tables as $tablename => $table) {
787 $tablessql .= ($tablessql ? ', ' : '').'{'.$table.'} '.$tablename;
788 }
789
790 $sql = ($count) ? 'SELECT COUNT(*)' : 'SELECT ' . $requiredfields;
791 $sql .= " FROM $tablessql WHERE " . implode(' AND ', $conditions);
527761e0 792 $sql .= ($count) ? '' : " ORDER BY $sort";
cae83708 793
794 return array('sql' => $sql, 'params' => $params);
795 }
796
797 /**
798 * Outputs all the blog entries aggregated by this blog listing.
799 *
800 * @return void
801 */
802 public function print_entries() {
803 global $CFG, $USER, $DB, $OUTPUT;
804 $sitecontext = get_context_instance(CONTEXT_SYSTEM);
805
806 $page = optional_param('blogpage', 0, PARAM_INT);
807 $limit = optional_param('limit', get_user_preferences('blogpagesize', 10), PARAM_INT);
808 $start = $page * $limit;
809
810 $morelink = '<br />&nbsp;&nbsp;';
811
1c7b8b93
NC
812 if ($sqlarray = $this->get_entry_fetch_sql(true)) {
813 $totalentries = $DB->count_records_sql($sqlarray['sql'], $sqlarray['params']);
cae83708 814 } else {
815 $totalentries = 0;
816 }
817
818 $entries = $this->get_entries($start, $limit);
929d7a83 819 $pagingbar = new paging_bar($totalentries, $page, $limit, $this->get_baseurl());
cae83708 820 $pagingbar->pagevar = 'blogpage';
1c7b8b93 821 $blogheaders = blog_get_headers();
cae83708 822
929d7a83 823 echo $OUTPUT->render($pagingbar);
cae83708 824
cae83708 825 if (has_capability('moodle/blog:create', $sitecontext)) {
826 //the user's blog is enabled and they are viewing their own blog
827 $userid = optional_param('userid', null, PARAM_INT);
828
829 if (empty($userid) || (!empty($userid) && $userid == $USER->id)) {
1c7b8b93
NC
830 $addurl = new moodle_url("$CFG->wwwroot/blog/edit.php");
831 $urlparams = array('action' => 'add',
832 'userid' => $userid,
833 'courseid' => optional_param('courseid', null, PARAM_INT),
834 'groupid' => optional_param('groupid', null, PARAM_INT),
835 'modid' => optional_param('modid', null, PARAM_INT),
836 'tagid' => optional_param('tagid', null, PARAM_INT),
837 'tag' => optional_param('tag', null, PARAM_INT),
838 'search' => optional_param('search', null, PARAM_INT));
839
840 foreach ($urlparams as $var => $val) {
cae83708 841 if (empty($val)) {
1c7b8b93 842 unset($urlparams[$var]);
cae83708 843 }
844 }
1c7b8b93 845 $addurl->params($urlparams);
cae83708 846
847 $addlink = '<div class="addbloglink">';
1c7b8b93 848 $addlink .= '<a href="'.$addurl->out().'">'. $blogheaders['stradd'].'</a>';
cae83708 849 $addlink .= '</div>';
850 echo $addlink;
851 }
852 }
853
854 if ($entries) {
855 $count = 0;
856
857 foreach ($entries as $entry) {
1c7b8b93
NC
858 $blogentry = new blog_entry(null, $entry);
859 $blogentry->print_html();
cae83708 860 $count++;
861 }
862
929d7a83 863 echo $OUTPUT->render($pagingbar);
cae83708 864
865 if (!$count) {
866 print '<br /><div style="text-align:center">'. get_string('noentriesyet', 'blog') .'</div><br />';
867 }
868
869 print $morelink.'<br />'."\n";
870 return;
871 }
872 }
873
874 /// Find the base url from $_GET variables, for print_paging_bar
875 public function get_baseurl() {
876 $getcopy = $_GET;
877
878 unset($getcopy['blogpage']);
879
880 if (!empty($getcopy)) {
881 $first = false;
882 $querystring = '';
883
884 foreach ($getcopy as $var => $val) {
885 if (!$first) {
886 $first = true;
887 $querystring .= "?$var=$val";
888 } else {
889 $querystring .= '&amp;'.$var.'='.$val;
890 $hasparam = true;
891 }
892 }
893 } else {
894 $querystring = '?';
895 }
896
897 return strip_querystring(qualified_me()) . $querystring;
898
899 }
900}
901
902/**
903 * Abstract class for blog_filter objects.
904 * A set of core filters are implemented here. To write new filters, you need to subclass
905 * blog_filter and give it the name of the type you want (for example, blog_filter_entry).
906 * The blog_filter abstract class will automatically use it when the filter is added to the
907 * URL. The first parameter of the constructor is the ID of your filter, but it can be a string
908 * or have any other meaning you wish it to have. The second parameter is called $type and is
909 * used as a sub-type for filters that have a very similar implementation (see blog_filter_context for an example)
910 */
911abstract class blog_filter {
912 /**
913 * An array of strings representing the available filter types for each blog_filter.
1c7b8b93 914 * @var array $availabletypes
cae83708 915 */
1c7b8b93 916 public $availabletypes = array();
cae83708 917
918 /**
919 * The type of filter (for example, types of blog_filter_context are site, course and module)
920 * @var string $type
921 */
922 public $type;
923
924 /**
925 * The unique ID for a filter's associated record
926 * @var int $id
927 */
928 public $id;
929
930 /**
931 * An array of table aliases that are used in the WHERE conditions
932 * @var array $tables
933 */
934 public $tables = array();
935
936 /**
937 * An array of WHERE conditions
938 * @var array $conditions
939 */
940 public $conditions = array();
941
942 /**
943 * An array of SQL params
944 * @var array $params
945 */
946 public $params = array();
947
948 /**
949 * An array of filter types which this particular filter type overrides: their conditions will not be evaluated
950 */
951 public $overrides = array();
952
953 public function __construct($id, $type=null) {
954 $this->id = $id;
955 $this->type = $type;
956 }
957
958 /**
959 * TODO This is poor design. A parent class should not know anything about its children.
960 * The default case helps to resolve this design issue
961 */
962 public static function get_instance($id, $type) {
963
964 switch ($type) {
965 case 'site':
966 case 'course':
967 case 'module':
968 return new blog_filter_context($id, $type);
969 break;
970
971 case 'group':
972 case 'user':
973 return new blog_filter_user($id, $type);
974 break;
975
976 case 'tag':
977 return new blog_filter_tag($id);
978 break;
979
980 default:
1c7b8b93
NC
981 $classname = "blog_filter_$type";
982 if (class_exists($classname)) {
983 return new $classname($id, $type);
cae83708 984 }
985 }
986 }
987}
988
989/**
990 * This filter defines the context level of the blog entries being searched: site, course, module
991 */
992class blog_filter_context extends blog_filter {
993 /**
994 * Constructor
995 *
996 * @param string $type
997 * @param int $id
998 */
999 public function __construct($id=null, $type='site') {
1000 global $SITE, $CFG, $DB;
1001
1002 if (empty($id)) {
1003 $this->type = 'site';
1004 } else {
1005 $this->id = $id;
1006 $this->type = $type;
1007 }
1008
8eaf1ba1 1009 $this->availabletypes = array('site' => get_string('site'), 'course' => get_string('course'), 'module' => get_string('activity'));
cae83708 1010
1011 switch ($this->type) {
1012 case 'course': // Careful of site course!
1013 // Ignore course filter if blog associations are not enabled
1014 if ($this->id != $SITE->id && !empty($CFG->useblogassociations)) {
1015 $this->overrides = array('site');
1016 $context = get_context_instance(CONTEXT_COURSE, $this->id);
1017 $this->tables['ba'] = 'blog_association';
1c7b8b93 1018 $this->conditions[] = 'p.id = ba.blogid';
cae83708 1019 $this->conditions[] = 'ba.contextid = '.$context->id;
1020 break;
1021 } else {
1022 // We are dealing with the site course, do not break from the current case
1023 }
1024
1025 case 'site':
1026 // No special constraints
1027 break;
1028 case 'module':
1029 if (!empty($CFG->useblogassociations)) {
1030 $this->overrides = array('course', 'site');
1031
1032 $context = get_context_instance(CONTEXT_MODULE, $this->id);
1033 $this->tables['ba'] = 'blog_association';
1c7b8b93
NC
1034 $this->tables['p'] = 'post';
1035 $this->conditions = array('p.id = ba.blogid', 'ba.contextid = ?');
cae83708 1036 $this->params = array($context->id);
1037 }
1038 break;
1039 }
1040 }
1041}
1042
1043/**
1044 * This filter defines the user level of the blog entries being searched: a userid or a groupid.
1045 * It can be combined with a context filter in order to refine the search.
1046 */
1047class blog_filter_user extends blog_filter {
1048 public $tables = array('u' => 'user');
1049
1050 /**
1051 * Constructor
1052 *
1053 * @param string $type
1054 * @param int $id
1055 */
1056 public function __construct($id=null, $type='user') {
320ae23a 1057 global $CFG, $DB, $USER;
1c7b8b93 1058 $this->availabletypes = array('user' => get_string('user'), 'group' => get_string('group'));
cae83708 1059
1060 if (empty($id)) {
1061 $this->id = $USER->id;
1062 $this->type = 'user';
1063 } else {
1064 $this->id = $id;
1065 $this->type = $type;
1066 }
1067
1068 if ($this->type == 'user') {
1069 $this->conditions = array('u.id = ?');
1070 $this->params = array($this->id);
1071 $this->overrides = array('group');
1072
1073 } elseif ($this->type == 'group') {
1074 $this->overrides = array('course', 'site');
1075
1076 $this->tables['gm'] = 'groups_members';
1c7b8b93 1077 $this->conditions[] = 'p.userid = gm.userid';
cae83708 1078 $this->conditions[] = 'gm.groupid = ?';
1079 $this->params[] = $this->id;
1080
1081 if (!empty($CFG->useblogassociations)) { // only show blog entries associated with this course
1c7b8b93 1082 $coursecontext = get_context_instance(CONTEXT_COURSE, $DB->get_field('groups', 'courseid', array('id' => $this->id)));
cae83708 1083 $this->tables['ba'] = 'blog_association';
1084 $this->conditions[] = 'gm.groupid = ?';
1085 $this->conditions[] = 'ba.contextid = ?';
1c7b8b93 1086 $this->conditions[] = 'ba.blogid = p.id';
cae83708 1087 $this->params[] = $this->id;
1c7b8b93 1088 $this->params[] = $coursecontext->id;
cae83708 1089 }
1090 }
b73d1ca4 1091
cae83708 1092 }
1093}
1094
1095/**
1096 * This filter defines a tag by which blog entries should be searched.
1097 */
1098class blog_filter_tag extends blog_filter {
1c7b8b93 1099 public $tables = array('t' => 'tag', 'ti' => 'tag_instance', 'p' => 'post');
cae83708 1100
1101 /**
1102 * Constructor
1103 *
1104 * @return void
1105 */
1106 public function __construct($id) {
1107 global $DB;
1108 $this->id = $id;
1109
1110 $this->conditions = array('ti.tagid = t.id',
1c7b8b93
NC
1111 "ti.itemtype = 'post'",
1112 'ti.itemid = p.id',
cae83708 1113 't.id = ?');
1114 $this->params = array($this->id);
1115 }
1116}
1117
1118/**
1119 * This filter defines a specific blog entry id.
1120 */
1121class blog_filter_entry extends blog_filter {
1122 public $conditions = array('p.id = ?');
1123 public $overrides = array('site', 'course', 'module', 'group', 'user', 'tag');
1124
1125 public function __construct($id) {
1126 $this->id = $id;
1127 $this->params[] = $this->id;
1128 }
1129}
1130
1c7b8b93
NC
1131/**
1132 * This filter restricts the results to a time interval in seconds up to mktime()
1133 */
1134class blog_filter_since extends blog_filter {
1135 public function __construct($interval) {
1136 $this->conditions[] = 'p.lastmodified >= ? AND p.lastmodified <= ?';
1137 $this->params[] = mktime() - $interval;
1138 $this->params[] = mktime();
1139 }
1140}
1141
cae83708 1142/**
1143 * Filter used to perform full-text search on an entry's subject, summary and content
1144 */
1145class blog_filter_search extends blog_filter {
1146
1c7b8b93 1147 public function __construct($searchterm) {
cae83708 1148 global $DB;
c014d57c
PS
1149 $this->conditions = array("(".$DB->sql_like('p.summary', '?', false)." OR
1150 ".$DB->sql_like('p.content', '?', false)." OR
1151 ".$DB->sql_like('p.subject', '?', false).")");
1c7b8b93
NC
1152 $this->params[] = "%$searchterm%";
1153 $this->params[] = "%$searchterm%";
1154 $this->params[] = "%$searchterm%";
cae83708 1155 }
1156}