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