Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
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
 
17
/**
18
 * Core global functions for Blog.
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
 
26
defined('MOODLE_INTERNAL') || die();
27
 
28
/*
29
 * Library of functions and constants for blog
30
 */
31
require_once($CFG->dirroot .'/blog/rsslib.php');
32
 
33
/**
34
 * User can edit a blog entry if this is their own blog entry and they have
35
 * the capability moodle/blog:create, or if they have the capability
36
 * moodle/blog:manageentries.
37
 *
38
 * This also applies to deleting of entries.
39
 */
40
function blog_user_can_edit_entry($blogentry) {
41
    global $USER;
42
 
43
    $sitecontext = context_system::instance();
44
 
45
    if (has_capability('moodle/blog:manageentries', $sitecontext)) {
46
        return true; // Can edit any blog entry.
47
    }
48
 
49
    if ($blogentry->userid == $USER->id && has_capability('moodle/blog:create', $sitecontext)) {
50
        return true; // Can edit own when having blog:create capability.
51
    }
52
 
53
    return false;
54
}
55
 
56
 
57
/**
58
 * Checks to see if a user can view the blogs of another user.
59
 * Only blog level is checked here, the capabilities are enforced
60
 * in blog/index.php
61
 */
62
function blog_user_can_view_user_entry($targetuserid, $blogentry=null) {
63
    global $CFG, $USER, $DB;
64
 
65
    if (empty($CFG->enableblogs)) {
66
        return false; // Blog system disabled.
67
    }
68
 
69
    if (isloggedin() && $USER->id == $targetuserid) {
70
        return true; // Can view own entries in any case.
71
    }
72
 
73
    $sitecontext = context_system::instance();
74
    if (has_capability('moodle/blog:manageentries', $sitecontext)) {
75
        return true; // Can manage all entries.
76
    }
77
 
78
    // If blog is in draft state, then make sure user have proper capability.
79
    if ($blogentry && $blogentry->publishstate == 'draft' && !has_capability('moodle/blog:viewdrafts', $sitecontext)) {
80
        return false;  // Can not view draft of others.
81
    }
82
 
83
    // If blog entry is not public, make sure user is logged in.
84
    if ($blogentry && $blogentry->publishstate != 'public' && !isloggedin()) {
85
        return false;
86
    }
87
 
88
    // If blogentry is not passed or all above checks pass, then check capability based on system config.
89
    switch ($CFG->bloglevel) {
90
        case BLOG_GLOBAL_LEVEL:
91
            return true;
92
        break;
93
 
94
        case BLOG_SITE_LEVEL:
95
            if (isloggedin()) { // Not logged in viewers forbidden.
96
                return true;
97
            }
98
            return false;
99
        break;
100
 
101
        case BLOG_USER_LEVEL:
102
        default:
103
            // If user is viewing other user blog, then user should have user:readuserblogs capability.
104
            $personalcontext = context_user::instance($targetuserid);
105
            return has_capability('moodle/user:readuserblogs', $personalcontext);
106
        break;
107
 
108
    }
109
}
110
 
111
/**
112
 * remove all associations for the blog entries of a particular course
113
 * @param int courseid - id of user whose blog associations will be deleted
114
 */
115
function blog_remove_associations_for_course($courseid) {
116
    global $DB;
117
    $context = context_course::instance($courseid);
118
    $DB->delete_records('blog_association', array('contextid' => $context->id));
119
}
120
 
121
/**
122
 * Remove module associated blogs and blog tag instances.
123
 *
124
 * @param  int $modcontextid Module context ID.
125
 */
126
function blog_remove_associations_for_module($modcontextid) {
127
    global $DB;
128
 
129
    if (!empty($assocblogids = $DB->get_fieldset_select('blog_association', 'blogid',
130
        'contextid = :contextid', ['contextid' => $modcontextid]))) {
131
        list($sql, $params) = $DB->get_in_or_equal($assocblogids, SQL_PARAMS_NAMED);
132
 
133
        $DB->delete_records_select('tag_instance', "itemid $sql", $params);
134
        $DB->delete_records_select('post', "id $sql AND module = :module",
135
            array_merge($params, ['module' => 'blog']));
136
        $DB->delete_records('blog_association', ['contextid' => $modcontextid]);
137
    }
138
}
139
 
140
/**
141
 * Given a record in the {blog_external} table, checks the blog's URL
142
 * for new entries not yet copied into Moodle.
143
 * Also attempts to identify and remove deleted blog entries
144
 *
145
 * @param object $externalblog
146
 * @return boolean False if the Feed is invalid
147
 */
148
function blog_sync_external_entries($externalblog) {
149
    global $CFG, $DB;
150
    require_once($CFG->libdir . '/simplepie/moodle_simplepie.php');
151
 
152
    $rss = new moodle_simplepie();
153
    $rssfile = $rss->registry->create('File', array($externalblog->url));
154
    $filetest = $rss->registry->create('Locator', array($rssfile));
155
 
156
    if (!$filetest->is_feed($rssfile)) {
157
        $externalblog->failedlastsync = 1;
158
        $DB->update_record('blog_external', $externalblog);
159
        return false;
160
    } else if (!empty($externalblog->failedlastsync)) {
161
        $externalblog->failedlastsync = 0;
162
        $DB->update_record('blog_external', $externalblog);
163
    }
164
 
165
    $rss->set_feed_url($externalblog->url);
166
    $rss->init();
167
 
168
    if (empty($rss->data)) {
169
        return null;
170
    }
171
    // Used to identify blog posts that have been deleted from the source feed.
172
    $oldesttimestamp = null;
173
    $uniquehashes = array();
174
 
175
    foreach ($rss->get_items() as $entry) {
176
        // If filtertags are defined, use them to filter the entries by RSS category.
177
        if (!empty($externalblog->filtertags)) {
178
            $containsfiltertag = false;
179
            $categories = $entry->get_categories();
180
            $filtertags = explode(',', $externalblog->filtertags);
181
            $filtertags = array_map('trim', $filtertags);
182
            $filtertags = array_map('strtolower', $filtertags);
183
 
184
            if (!empty($categories)) {
185
                foreach ($categories as $category) {
186
                    if (in_array(trim(strtolower($category->term)), $filtertags)) {
187
                        $containsfiltertag = true;
188
                    }
189
                }
190
            }
191
 
192
            if (!$containsfiltertag) {
193
                continue;
194
            }
195
        }
196
 
197
        $uniquehashes[] = $entry->get_permalink();
198
 
199
        $newentry = new stdClass();
200
        $newentry->userid = $externalblog->userid;
201
        $newentry->module = 'blog_external';
202
        $newentry->content = $externalblog->id;
203
        $newentry->uniquehash = $entry->get_permalink();
204
        $newentry->publishstate = 'site';
205
        $newentry->format = FORMAT_HTML;
206
        // Clean subject of html, just in case.
207
        $newentry->subject = clean_param($entry->get_title(), PARAM_TEXT);
208
        // Observe 128 max chars in DB.
209
        // TODO: +1 to raise this to 255.
210
        if (core_text::strlen($newentry->subject) > 128) {
211
            $newentry->subject = core_text::substr($newentry->subject, 0, 125) . '...';
212
        }
213
        $newentry->summary = $entry->get_description();
214
 
215
        // Used to decide whether to insert or update.
216
        // Uses enty permalink plus creation date if available.
217
        $existingpostconditions = array('uniquehash' => $entry->get_permalink());
218
 
219
        // Our DB doesnt allow null creation or modified timestamps so check the external blog supplied one.
220
        $entrydate = $entry->get_date('U');
221
        if (!empty($entrydate)) {
222
            $existingpostconditions['created'] = $entrydate;
223
        }
224
 
225
        // The post ID or false if post not found in DB.
226
        $postid = $DB->get_field('post', 'id', $existingpostconditions);
227
 
228
        $timestamp = null;
229
        if (empty($entrydate)) {
230
            $timestamp = time();
231
        } else {
232
            $timestamp = $entrydate;
233
        }
234
 
235
        // Only set created if its a new post so we retain the original creation timestamp if the post is edited.
236
        if ($postid === false) {
237
            $newentry->created = $timestamp;
238
        }
239
        $newentry->lastmodified = $timestamp;
240
 
241
        if (empty($oldesttimestamp) || $timestamp < $oldesttimestamp) {
242
            // Found an older post.
243
            $oldesttimestamp = $timestamp;
244
        }
245
 
246
        if (core_text::strlen($newentry->uniquehash) > 255) {
247
            // The URL for this item is too long for the field. Rather than add
248
            // the entry without the link we will skip straight over it.
249
            // RSS spec says recommended length 500, we use 255.
250
            debugging('External blog entry skipped because of oversized URL', DEBUG_DEVELOPER);
251
            continue;
252
        }
253
 
254
        if ($postid === false) {
255
            $id = $DB->insert_record('post', $newentry);
256
 
257
            // Set tags.
258
            if ($tags = core_tag_tag::get_item_tags_array('core', 'blog_external', $externalblog->id)) {
259
                core_tag_tag::set_item_tags('core', 'post', $id, context_user::instance($externalblog->userid), $tags);
260
            }
261
        } else {
262
            $newentry->id = $postid;
263
            $DB->update_record('post', $newentry);
264
        }
265
    }
266
 
267
    // Look at the posts we have in the database to check if any of them have been deleted from the feed.
268
    // Only checking posts within the time frame returned by the rss feed. Older items may have been deleted or
269
    // may just not be returned anymore. We can't tell the difference so we leave older posts alone.
270
    $sql = "SELECT id, uniquehash
271
              FROM {post}
272
             WHERE module = 'blog_external'
273
                   AND " . $DB->sql_compare_text('content') . " = " . $DB->sql_compare_text(':blogid') . "
274
                   AND created > :ts";
275
    $dbposts = $DB->get_records_sql($sql, array('blogid' => $externalblog->id, 'ts' => $oldesttimestamp));
276
 
277
    $todelete = array();
278
    foreach ($dbposts as $dbpost) {
279
        if ( !in_array($dbpost->uniquehash, $uniquehashes) ) {
280
            $todelete[] = $dbpost->id;
281
        }
282
    }
283
    $DB->delete_records_list('post', 'id', $todelete);
284
 
285
    $DB->update_record('blog_external', array('id' => $externalblog->id, 'timefetched' => time()));
286
}
287
 
288
/**
289
 * Given an external blog object, deletes all related blog entries from the post table.
290
 * NOTE: The external blog's id is saved as post.content, a field that is not oterhwise used by blog entries.
291
 * @param object $externablog
292
 */
293
function blog_delete_external_entries($externalblog) {
294
    global $DB;
295
    require_capability('moodle/blog:manageexternal', context_system::instance());
296
    $DB->delete_records_select('post',
297
                               "module='blog_external' AND " . $DB->sql_compare_text('content') . " = ?",
298
                               array($externalblog->id));
299
}
300
 
301
/**
302
 * This function checks that blogs are enabled, and that the user can see blogs at all
303
 * @return bool
304
 */
305
function blog_is_enabled_for_user() {
306
    global $CFG;
307
    return (!empty($CFG->enableblogs) && (isloggedin() || ($CFG->bloglevel == BLOG_GLOBAL_LEVEL)));
308
}
309
 
310
/**
311
 * This function gets all of the options available for the current user in respect
312
 * to blogs.
313
 *
314
 * It loads the following if applicable:
315
 * -  Module options {@see blog_get_options_for_module}
316
 * -  Course options {@see blog_get_options_for_course}
317
 * -  User specific options {@see blog_get_options_for_user}
318
 * -  General options (BLOG_LEVEL_GLOBAL)
319
 *
320
 * @param moodle_page $page The page to load for (normally $PAGE)
321
 * @param stdClass $userid Load for a specific user
322
 * @return array An array of options organised by type.
323
 */
1441 ariadna 324
function blog_get_all_options(moodle_page $page, ?stdClass $userid = null) {
1 efrain 325
    global $CFG, $DB, $USER;
326
 
327
    $options = array();
328
 
329
    // If blogs are enabled and the user is logged in and not a guest.
330
    if (blog_is_enabled_for_user()) {
331
        // If the context is the user then assume we want to load for the users context.
332
        if (is_null($userid) && $page->context->contextlevel == CONTEXT_USER) {
333
            $userid = $page->context->instanceid;
334
        }
335
        // Check the userid var.
336
        if (!is_null($userid) && $userid !== $USER->id) {
337
            // Load the user from the userid... it MUST EXIST throw a wobbly if it doesn't!
338
            $user = $DB->get_record('user', array('id' => $userid), '*', MUST_EXIST);
339
        } else {
340
            $user = null;
341
        }
342
 
343
        if ($CFG->useblogassociations && $page->cm !== null) {
344
            // Load for the module associated with the page.
345
            $options[CONTEXT_MODULE] = blog_get_options_for_module($page->cm, $user);
346
        } else if ($CFG->useblogassociations && $page->course->id != SITEID) {
347
            // Load the options for the course associated with the page.
348
            $options[CONTEXT_COURSE] = blog_get_options_for_course($page->course, $user);
349
        }
350
 
351
        // Get the options for the user.
352
        if ($user !== null and !isguestuser($user)) {
353
            // Load for the requested user.
354
            $options[CONTEXT_USER + 1] = blog_get_options_for_user($user);
355
        }
356
        // Load for the current user.
357
        if (isloggedin() and !isguestuser()) {
358
            $options[CONTEXT_USER] = blog_get_options_for_user();
359
        }
360
    }
361
 
362
    // If blog level is global then display a link to view all site entries.
363
    if (!empty($CFG->enableblogs)
364
        && $CFG->bloglevel >= BLOG_GLOBAL_LEVEL
365
        && has_capability('moodle/blog:view', context_system::instance())) {
366
 
367
        $options[CONTEXT_SYSTEM] = array('viewsite' => array(
368
            'string' => get_string('viewsiteentries', 'blog'),
369
            'link' => new moodle_url('/blog/index.php')
370
        ));
371
    }
372
 
373
    // Return the options.
374
    return $options;
375
}
376
 
377
/**
378
 * Get all of the blog options that relate to the passed user.
379
 *
380
 * If no user is passed the current user is assumed.
381
 *
382
 * @staticvar array $useroptions Cache so we don't have to regenerate multiple times
383
 * @param stdClass $user
384
 * @return array The array of options for the requested user
385
 */
1441 ariadna 386
function blog_get_options_for_user(?stdClass $user=null) {
1 efrain 387
    global $CFG, $USER;
388
    // Cache.
389
    static $useroptions = array();
390
 
391
    $options = array();
392
    // Blogs must be enabled and the user must be logged in.
393
    if (!blog_is_enabled_for_user()) {
394
        return $options;
395
    }
396
 
397
    // Sort out the user var.
398
    if ($user === null || $user->id == $USER->id) {
399
        $user = $USER;
400
        $iscurrentuser = true;
401
    } else {
402
        $iscurrentuser = false;
403
    }
404
 
405
    // If we've already generated serve from the cache.
406
    if (array_key_exists($user->id, $useroptions)) {
407
        return $useroptions[$user->id];
408
    }
409
 
410
    $sitecontext = context_system::instance();
411
    $canview = has_capability('moodle/blog:view', $sitecontext);
412
 
413
    if (!$iscurrentuser && $canview && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
414
        // Not the current user, but we can view and its blogs are enabled for SITE or GLOBAL.
415
        $options['userentries'] = array(
416
            'string' => get_string('viewuserentries', 'blog', fullname($user)),
417
            'link' => new moodle_url('/blog/index.php', array('userid' => $user->id))
418
        );
419
    } else {
420
        // It's the current user.
421
        if ($canview) {
422
            // We can view our own blogs .... BIG surprise.
423
            $options['view'] = array(
424
                'string' => get_string('blogentries', 'blog'),
425
                'link' => new moodle_url('/blog/index.php', array('userid' => $USER->id))
426
            );
427
        }
428
        if (has_capability('moodle/blog:create', $sitecontext)) {
429
            // We can add to our own blog.
430
            $options['add'] = array(
431
                'string' => get_string('addnewentry', 'blog'),
432
                'link' => new moodle_url('/blog/edit.php', array('action' => 'add'))
433
            );
434
        }
435
    }
436
    if ($canview && $CFG->enablerssfeeds) {
437
        $options['rss'] = array(
438
            'string' => get_string('rssfeed', 'blog'),
439
            'link' => new moodle_url(rss_get_url($sitecontext->id, $USER->id, 'blog', 'user/'.$user->id))
440
        );
441
    }
442
 
443
    // Cache the options.
444
    $useroptions[$user->id] = $options;
445
    // Return the options.
446
    return $options;
447
}
448
 
449
/**
450
 * Get the blog options that relate to the given course for the given user.
451
 *
452
 * @staticvar array $courseoptions A cache so we can save regenerating multiple times
453
 * @param stdClass $course The course to load options for
454
 * @param stdClass $user The user to load options for null == current user
455
 * @return array The array of options
456
 */
1441 ariadna 457
function blog_get_options_for_course(stdClass $course, ?stdClass $user=null) {
1 efrain 458
    global $CFG, $USER;
459
    // Cache.
460
    static $courseoptions = array();
461
 
462
    $options = array();
463
 
464
    // User must be logged in and blogs must be enabled.
465
    if (!blog_is_enabled_for_user()) {
466
        return $options;
467
    }
468
 
469
    // Check that the user can associate with the course.
470
    $sitecontext = context_system::instance();
471
    // Generate the cache key.
472
    $key = $course->id.':';
473
    if (!empty($user)) {
474
        $key .= $user->id;
475
    } else {
476
        $key .= $USER->id;
477
    }
478
    // Serve from the cache if we've already generated for this course.
479
    if (array_key_exists($key, $courseoptions)) {
480
        return $courseoptions[$key];
481
    }
482
 
483
    if (has_capability('moodle/blog:view', $sitecontext)) {
484
        // We can view!
485
        if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
486
            // View entries about this course.
487
            $options['courseview'] = array(
488
                'string' => get_string('viewcourseblogs', 'blog'),
489
                'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id))
490
            );
491
        }
492
        // View MY entries about this course.
493
        $options['courseviewmine'] = array(
494
            'string' => get_string('viewmyentriesaboutcourse', 'blog'),
495
            'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $USER->id))
496
        );
497
        if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
498
            // View the provided users entries about this course.
499
            $options['courseviewuser'] = array(
500
                'string' => get_string('viewentriesbyuseraboutcourse', 'blog', fullname($user)),
501
                'link' => new moodle_url('/blog/index.php', array('courseid' => $course->id, 'userid' => $user->id))
502
            );
503
        }
504
    }
505
 
506
    if (has_capability('moodle/blog:create', $sitecontext)) {
507
        // We can blog about this course.
508
        $options['courseadd'] = array(
509
            'string' => get_string('blogaboutthiscourse', 'blog'),
510
            'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'courseid' => $course->id))
511
        );
512
    }
513
 
514
    // Cache the options for this course.
515
    $courseoptions[$key] = $options;
516
    // Return the options.
517
    return $options;
518
}
519
 
520
/**
521
 * Get the blog options relating to the given module for the given user
522
 *
523
 * @staticvar array $moduleoptions Cache
524
 * @param stdClass|cm_info $module The module to get options for
525
 * @param stdClass $user The user to get options for null == currentuser
526
 * @return array
527
 */
528
function blog_get_options_for_module($module, $user=null) {
529
    global $CFG, $USER;
530
    // Cache.
531
    static $moduleoptions = array();
532
 
533
    $options = array();
534
    // User must be logged in, blogs must be enabled.
535
    if (!blog_is_enabled_for_user()) {
536
        return $options;
537
    }
538
 
539
    $sitecontext = context_system::instance();
540
 
541
    // Generate the cache key.
542
    $key = $module->id.':';
543
    if (!empty($user)) {
544
        $key .= $user->id;
545
    } else {
546
        $key .= $USER->id;
547
    }
548
    if (array_key_exists($key, $moduleoptions)) {
549
        // Serve from the cache so we don't have to regenerate.
550
        return $moduleoptions[$key];
551
    }
552
 
553
    if (has_capability('moodle/blog:view', $sitecontext)) {
554
        // Save correct module name for later usage.
555
        $modulename = get_string('modulename', $module->modname);
556
 
557
        // We can view!
558
        if ($CFG->bloglevel >= BLOG_SITE_LEVEL) {
559
            // View all entries about this module.
560
            $a = new stdClass;
561
            $a->type = $modulename;
562
            $options['moduleview'] = array(
563
                'string' => get_string('viewallmodentries', 'blog', $a),
564
                'link' => new moodle_url('/blog/index.php', array('modid' => $module->id))
565
            );
566
        }
567
        // View MY entries about this module.
568
        $options['moduleviewmine'] = array(
569
            'string' => get_string('viewmyentriesaboutmodule', 'blog', $modulename),
570
            'link' => new moodle_url('/blog/index.php', array('modid' => $module->id, 'userid' => $USER->id))
571
        );
572
        if (!empty($user) && ($CFG->bloglevel >= BLOG_SITE_LEVEL)) {
573
            // View the given users entries about this module.
574
            $a = new stdClass;
575
            $a->mod = $modulename;
576
            $a->user = fullname($user);
577
            $options['moduleviewuser'] = array(
578
                'string' => get_string('blogentriesbyuseraboutmodule', 'blog', $a),
579
                'link' => new moodle_url('/blog/index.php', array('modid' => $module->id, 'userid' => $user->id))
580
            );
581
        }
582
    }
583
 
584
    if (has_capability('moodle/blog:create', $sitecontext)) {
585
        // The user can blog about this module.
586
        $options['moduleadd'] = array(
587
            'string' => get_string('blogaboutthismodule', 'blog', $modulename),
588
            'link' => new moodle_url('/blog/edit.php', array('action' => 'add', 'modid' => $module->id))
589
        );
590
    }
591
    // Cache the options.
592
    $moduleoptions[$key] = $options;
593
    // Return the options.
594
    return $options;
595
}
596
 
597
/**
598
 * This function encapsulates all the logic behind the complex
599
 * navigation, titles and headings of the blog listing page, depending
600
 * on URL params. It looks at URL params and at the current context level.
601
 * It builds and returns an array containing:
602
 *
603
 * 1. heading: The heading displayed above the blog entries
604
 * 2. stradd:  The text to be used as the "Add entry" link
605
 * 3. strview: The text to be used as the "View entries" link
606
 * 4. url:     The moodle_url object used as the base for add and view links
607
 * 5. filters: An array of parameters used to filter blog listings. Used by index.php and the Recent blogs block
608
 *
609
 * All other variables are set directly in $PAGE
610
 *
611
 * It uses the current URL to build these variables.
612
 * A number of mutually exclusive use cases are used to structure this function.
613
 *
614
 * @param  int $courseid   course id the the blog is associated to (can be null).
615
 * @param  int $groupid    group id to filter blogs I can see (can be null)
616
 * @param  int $userid     blog author id (can be null)
617
 * @param  int $tagid      tag id to filter (can be null)
618
 * @param  string $tag     tag name to filter (can be null)
619
 * @param  int $modid      module id the blog is associated to (can be null).
620
 * @param  int $entryid    blog entry id to filter(can be null)
621
 * @param  string $search  string to search (can be null)
622
 * @return array
623
 */
624
function blog_get_headers($courseid=null, $groupid=null, $userid=null, $tagid=null, $tag=null, $modid=null, $entryid=null,
625
        $search = null) {
626
    global $CFG, $PAGE, $DB, $USER;
627
 
628
    $id       = optional_param('id', null, PARAM_INT);
629
    $tag      = optional_param('tag', $tag, PARAM_NOTAGS);
630
    $tagid    = optional_param('tagid', $tagid, PARAM_INT);
631
    $userid   = optional_param('userid', $userid, PARAM_INT);
632
    $modid    = optional_param('modid', $modid, PARAM_INT);
633
    $entryid  = optional_param('entryid', $entryid, PARAM_INT);
634
    $groupid  = optional_param('groupid', $groupid, PARAM_INT);
635
    $courseid = optional_param('courseid', $courseid, PARAM_INT);
636
    $search   = optional_param('search', $search, PARAM_RAW);
637
    $action   = optional_param('action', null, PARAM_ALPHA);
638
    $confirm  = optional_param('confirm', false, PARAM_BOOL);
639
 
640
    // Ignore userid when action == add.
641
    if ($action == 'add' && $userid) {
642
        unset($userid);
643
        $PAGE->url->remove_params(array('userid'));
644
    } else if ($action == 'add' && $entryid) {
645
        unset($entryid);
646
        $PAGE->url->remove_params(array('entryid'));
647
    }
648
 
649
    $headers = array('title' => '', 'heading' => '', 'cm' => null, 'filters' => array());
650
 
651
    $blogurl = new moodle_url('/blog/index.php');
652
 
653
    $headers['stradd'] = get_string('addnewentry', 'blog');
654
    $headers['strview'] = null;
655
 
656
    $site = $DB->get_record('course', array('id' => SITEID));
657
    $sitecontext = context_system::instance();
658
    // Common Lang strings.
659
    $strparticipants = get_string("participants");
660
    $strblogentries  = get_string("blogentries", 'blog');
661
 
662
    // Prepare record objects as needed.
663
    if (!empty($courseid)) {
664
        $headers['filters']['course'] = $courseid;
665
        $course = $DB->get_record('course', array('id' => $courseid));
666
    }
667
 
668
    if (!empty($userid)) {
669
        $headers['filters']['user'] = $userid;
670
        $user = $DB->get_record('user', array('id' => $userid));
671
    }
672
 
673
    if (!empty($groupid)) { // The groupid always overrides courseid.
674
        $headers['filters']['group'] = $groupid;
675
        $group = $DB->get_record('groups', array('id' => $groupid));
676
        $course = $DB->get_record('course', array('id' => $group->courseid));
677
    }
678
 
679
    $PAGE->set_pagelayout('standard');
680
 
681
    // The modid always overrides courseid, so the $course object may be reset here.
682
    if (!empty($modid) && $CFG->useblogassociations) {
683
 
684
        $headers['filters']['module'] = $modid;
685
        // A groupid param may conflict with this coursemod's courseid. Ignore groupid in that case.
686
        $courseid = $DB->get_field('course_modules', 'course', array('id' => $modid));
687
        $course = $DB->get_record('course', array('id' => $courseid));
688
        $cm = $DB->get_record('course_modules', array('id' => $modid));
689
        $cm->modname = $DB->get_field('modules', 'name', array('id' => $cm->module));
690
        $cm->name = $DB->get_field($cm->modname, 'name', array('id' => $cm->instance));
691
        $a = new stdClass();
692
        $a->type = get_string('modulename', $cm->modname);
693
        $PAGE->set_cm($cm, $course);
694
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
695
        $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
696
    }
697
 
698
    // Case 1: No entry, mod, course or user params: all site entries to be shown (filtered by search and tag/tagid)
699
    // Note: if action is set to 'add' or 'edit', we do this at the end.
700
    if (empty($entryid) && empty($modid) && empty($courseid) && empty($userid) && !in_array($action, array('edit', 'add'))) {
701
        $PAGE->navbar->add($strblogentries, $blogurl);
702
        $strsiteblog = get_string('siteblogheading', 'blog');
703
        $PAGE->set_title($strsiteblog);
704
        $PAGE->set_heading($site->fullname);
705
        $headers['heading'] = $strsiteblog;
706
    }
707
 
708
    // Case 2: only entryid is requested, ignore all other filters. courseid is used to give more contextual information.
709
    if (!empty($entryid)) {
710
        $headers['filters']['entry'] = $entryid;
711
        $sql = 'SELECT u.* FROM {user} u, {post} p WHERE p.id = ? AND p.userid = u.id';
712
        $user = $DB->get_record_sql($sql, array($entryid));
713
        $entry = $DB->get_record('post', array('id' => $entryid));
714
 
715
        $blogurl->param('userid', $user->id);
716
 
717
        if (!empty($course)) {
718
            $mycourseid = $course->id;
719
            $blogurl->param('courseid', $mycourseid);
720
        } else {
721
            $mycourseid = $site->id;
722
        }
723
        $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
724
 
725
        $PAGE->navbar->add($strblogentries, $blogurl);
726
 
727
        $blogurl->remove_params('userid');
728
        $PAGE->navbar->add($entry->subject, $blogurl);
729
        $blogentryby = get_string('blogentrybyuser', 'blog', fullname($user));
730
        $PAGE->set_title($entry->subject . moodle_page::TITLE_SEPARATOR . $blogentryby);
731
        $PAGE->set_heading("$shortname: " . fullname($user) . ": $entry->subject");
732
        $headers['heading'] = $blogentryby;
733
 
734
        // We ignore tag and search params.
735
        if (empty($action) || !$CFG->useblogassociations) {
736
            $headers['url'] = $blogurl;
737
            return $headers;
738
        }
739
    }
740
 
741
    if (!empty($userid) && empty($entryid) && ((empty($courseid) && empty($modid)) || !$CFG->useblogassociations)) {
742
        // Case 3: A user's blog entries.
743
 
744
        $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
745
        $blogurl->param('userid', $userid);
746
        $PAGE->set_title(fullname($user) . ": " . get_string('blog', 'blog'));
747
        $PAGE->set_heading("$shortname: " . fullname($user) . ": " . get_string('blog', 'blog'));
748
        $headers['heading'] = get_string('userblog', 'blog', fullname($user));
749
        $headers['strview'] = get_string('viewuserentries', 'blog', fullname($user));
750
 
751
    } else if (!$CFG->useblogassociations && empty($userid) && !in_array($action, array('edit', 'add'))) {
752
        // Case 4: No blog associations, no userid.
753
 
754
        $strsiteblog = get_string('siteblogheading', 'blog');
755
        $PAGE->set_title($strsiteblog);
756
        $PAGE->set_heading($site->fullname);
757
        $headers['heading'] = $strsiteblog;
758
    } else if (!empty($userid) && !empty($modid) && empty($entryid)) {
759
        // Case 5: Blog entries associated with an activity by a specific user (courseid ignored).
760
 
761
        $shortname = format_string($site->shortname, true, array('context' => context_course::instance(SITEID)));
762
        $blogurl->param('userid', $userid);
763
        $blogurl->param('modid', $modid);
764
 
765
        // Course module navigation is handled by build_navigation as the second param.
766
        $headers['cm'] = $cm;
767
        $PAGE->navbar->add(fullname($user), "$CFG->wwwroot/user/view.php?id=$user->id");
768
        $PAGE->navbar->add($strblogentries, $blogurl);
769
 
770
        $PAGE->set_title(fullname($user) . ': ' . get_string('blogentries', 'blog') . moodle_page::TITLE_SEPARATOR . $cm->name);
771
        $PAGE->set_heading("$shortname: $cm->name: " . fullname($user) . ': ' . get_string('blogentries', 'blog'));
772
 
773
        $a = new stdClass();
774
        $a->user = fullname($user);
775
        $a->mod = $cm->name;
776
        $a->type = get_string('modulename', $cm->modname);
777
        $headers['heading'] = get_string('blogentriesbyuseraboutmodule', 'blog', $a);
778
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
779
        $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
780
    } else if (!empty($userid) && !empty($courseid) && empty($modid) && empty($entryid)) {
781
        // Case 6: Blog entries associated with a course by a specific user.
782
 
783
        $blogurl->param('userid', $userid);
784
        $blogurl->param('courseid', $courseid);
785
 
786
        $PAGE->set_title($course->fullname);
787
        $PAGE->set_heading($course->fullname);
788
 
789
        $a = new stdClass();
790
        $a->user = fullname($user);
791
        $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
792
        $a->type = get_string('course');
793
        $headers['heading'] = get_string('blogentriesbyuseraboutcourse', 'blog', $a);
794
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
795
        $headers['strview'] = get_string('viewblogentries', 'blog', $a);
796
 
797
        // Remove the userid from the URL to inform the blog_menu block correctly.
798
        $blogurl->remove_params(array('userid'));
799
    } else if (!empty($groupid) && empty($modid) && empty($entryid)) {
800
        // Case 7: Blog entries by members of a group, associated with that group's course.
801
 
802
        $blogurl->param('courseid', $course->id);
803
 
804
        $PAGE->navbar->add($strblogentries, $blogurl);
805
        $blogurl->remove_params(array('courseid'));
806
        $blogurl->param('groupid', $groupid);
807
        $PAGE->navbar->add($group->name, $blogurl);
808
 
809
        $PAGE->set_title($course->fullname);
810
        $PAGE->set_heading($course->fullname);
811
 
812
        $a = new stdClass();
813
        $a->group = $group->name;
814
        $a->course = format_string($course->fullname, true, array('context' => context_course::instance($course->id)));
815
        $a->type = get_string('course');
816
        $headers['heading'] = get_string('blogentriesbygroupaboutcourse', 'blog', $a);
817
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
818
        $headers['strview'] = get_string('viewblogentries', 'blog', $a);
819
    } else if (!empty($groupid) && !empty($modid) && empty($entryid)) {
820
        // Case 8: Blog entries by members of a group, associated with an activity in that course.
821
 
822
        $headers['cm'] = $cm;
823
        $blogurl->param('modid', $modid);
824
        $PAGE->navbar->add($strblogentries, $blogurl);
825
 
826
        $blogurl->param('groupid', $groupid);
827
        $PAGE->navbar->add($group->name, $blogurl);
828
 
829
        $PAGE->set_title($course->fullname);
830
        $PAGE->set_heading($course->fullname);
831
 
832
        $a = new stdClass();
833
        $a->group = $group->name;
834
        $a->mod = $cm->name;
835
        $a->type = get_string('modulename', $cm->modname);
836
        $headers['heading'] = get_string('blogentriesbygroupaboutmodule', 'blog', $a);
837
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
838
        $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
839
 
840
    } else if (!empty($modid) && empty($userid) && empty($groupid) && empty($entryid)) {
841
        // Case 9: All blog entries associated with an activity.
842
 
843
        $PAGE->set_cm($cm, $course);
844
        $blogurl->param('modid', $modid);
845
        $PAGE->navbar->add($strblogentries, $blogurl);
846
        $PAGE->set_title($course->fullname);
847
        $PAGE->set_heading($course->fullname);
848
        $headers['heading'] = get_string('blogentriesabout', 'blog', $cm->name);
849
        $a = new stdClass();
850
        $a->type = get_string('modulename', $cm->modname);
851
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
852
        $headers['strview'] = get_string('viewallmodentries', 'blog', $a);
853
    } else if (!empty($courseid) && empty($userid) && empty($groupid) && empty($modid) && empty($entryid)) {
854
        // Case 10: All blog entries associated with a course.
855
 
856
        $blogurl->param('courseid', $courseid);
857
        $PAGE->navbar->add($strblogentries, $blogurl);
858
        $PAGE->set_title($course->fullname);
859
        $PAGE->set_heading($course->fullname);
860
        $a = new stdClass();
861
        $a->type = get_string('course');
862
        $headers['heading'] = get_string('blogentriesabout',
863
                                         'blog',
864
                                         format_string($course->fullname,
865
                                                       true,
866
                                                       array('context' => context_course::instance($course->id))));
867
        $headers['stradd'] = get_string('blogaboutthis', 'blog', $a);
868
        $headers['strview'] = get_string('viewblogentries', 'blog', $a);
869
        $blogurl->remove_params(array('userid'));
870
    }
871
 
872
    if (!in_array($action, array('edit', 'add'))) {
873
        // Append Tag info.
874
        if (!empty($tagid)) {
875
            $headers['filters']['tag'] = $tagid;
876
            $blogurl->param('tagid', $tagid);
877
            $tagrec = $DB->get_record('tag', array('id' => $tagid));
878
            $PAGE->navbar->add($tagrec->name, $blogurl);
879
        } else if (!empty($tag)) {
880
            if ($tagrec = $DB->get_record('tag', array('name' => $tag))) {
881
                $tagid = $tagrec->id;
882
                $headers['filters']['tag'] = $tagid;
883
                $blogurl->param('tag', $tag);
884
                $PAGE->navbar->add(get_string('tagparam', 'blog', $tag), $blogurl);
885
            }
886
        }
887
 
888
        // Append Search info.
889
        if (!empty($search) && has_capability('moodle/blog:search', $sitecontext)) {
890
            $headers['filters']['search'] = $search;
891
            $blogurl->param('search', $search);
892
            $PAGE->navbar->add(get_string('searchterm', 'blog', s($search)), $blogurl->out());
893
        }
894
    }
895
 
896
    // Append edit mode info.
897
    if (!empty($action) && $action == 'add') {
898
 
899
    } else if (!empty($action) && $action == 'edit') {
900
        $PAGE->navbar->add(get_string('editentry', 'blog'));
901
    }
902
 
903
    if (empty($headers['url'])) {
904
        $headers['url'] = $blogurl;
905
    }
906
    return $headers;
907
}
908
 
909
/**
910
 * Shortcut function for getting a count of blog entries associated with a course or a module
911
 * @param int $courseid The ID of the course
912
 * @param int $cmid The ID of the course_modules
913
 * @return string The number of associated entries
914
 */
915
function blog_get_associated_count($courseid, $cmid=null) {
916
    global $DB;
917
    $context = context_course::instance($courseid);
918
    if ($cmid) {
919
        $context = context_module::instance($cmid);
920
    }
921
    return $DB->count_records('blog_association', array('contextid' => $context->id));
922
}
923
 
924
/**
925
 * Running addtional permission check on plugin, for example, plugins
926
 * may have switch to turn on/off comments option, this callback will
927
 * affect UI display, not like pluginname_comment_validate only throw
928
 * exceptions.
929
 * blog_comment_validate will be called before viewing/adding/deleting
930
 * comment, so don't repeat checks.
931
 * Capability check has been done in comment->check_permissions(), we
932
 * don't need to do it again here.
933
 *
934
 * @package  core_blog
935
 * @category comment
936
 *
937
 * @param stdClass $commentparam {
938
 *              context  => context the context object
939
 *              courseid => int course id
940
 *              cm       => stdClass course module object
941
 *              commentarea => string comment area
942
 *              itemid      => int itemid
943
 * }
944
 * @return array
945
 */
946
function blog_comment_permissions($commentparam) {
947
    global $DB;
948
 
949
    // If blog is public and current user is guest, then don't let him post comments.
950
    $blogentry = $DB->get_record('post', array('id' => $commentparam->itemid), 'publishstate', MUST_EXIST);
951
 
952
    if ($blogentry->publishstate != 'public') {
953
        if (!isloggedin() || isguestuser()) {
954
            return array('post' => false, 'view' => true);
955
        }
956
    }
957
    return array('post' => true, 'view' => true);
958
}
959
 
960
/**
961
 * Validate comment parameter before perform other comments actions
962
 *
963
 * @package  core_blog
964
 * @category comment
965
 *
966
 * @param stdClass $comment {
967
 *              context  => context the context object
968
 *              courseid => int course id
969
 *              cm       => stdClass course module object
970
 *              commentarea => string comment area
971
 *              itemid      => int itemid
972
 * }
973
 * @return boolean
974
 */
975
function blog_comment_validate($commentparam) {
976
    global $CFG, $DB, $USER;
977
 
978
    // Check if blogs are enabled user can comment.
979
    if (empty($CFG->enableblogs) || empty($CFG->blogusecomments)) {
980
        throw new comment_exception('nopermissiontocomment');
981
    }
982
 
983
    // Validate comment area.
984
    if ($commentparam->commentarea != 'format_blog') {
985
        throw new comment_exception('invalidcommentarea');
986
    }
987
 
988
    $blogentry = $DB->get_record('post', array('id' => $commentparam->itemid), '*', MUST_EXIST);
989
 
990
    // Validation for comment deletion.
991
    if (!empty($commentparam->commentid)) {
992
        if ($record = $DB->get_record('comments', array('id' => $commentparam->commentid))) {
993
            if ($record->commentarea != 'format_blog') {
994
                throw new comment_exception('invalidcommentarea');
995
            }
996
            if ($record->contextid != $commentparam->context->id) {
997
                throw new comment_exception('invalidcontext');
998
            }
999
            if ($record->itemid != $commentparam->itemid) {
1000
                throw new comment_exception('invalidcommentitemid');
1001
            }
1002
        } else {
1003
            throw new comment_exception('invalidcommentid');
1004
        }
1005
    }
1006
 
1007
    // Validate if user has blog view permission.
1008
    $sitecontext = context_system::instance();
1009
    return has_capability('moodle/blog:view', $sitecontext) &&
1010
            blog_user_can_view_user_entry($blogentry->userid, $blogentry);
1011
}
1012
 
1013
/**
1014
 * Return a list of page types
1015
 * @param string $pagetype current page type
1016
 * @param stdClass $parentcontext Block's parent context
1017
 * @param stdClass $currentcontext Current context of block
1018
 */
1019
function blog_page_type_list($pagetype, $parentcontext, $currentcontext) {
1020
    return array(
1021
        '*' => get_string('page-x', 'pagetype'),
1022
        'blog-*' => get_string('page-blog-x', 'blog'),
1023
        'blog-index' => get_string('page-blog-index', 'blog'),
1024
        'blog-edit' => get_string('page-blog-edit', 'blog')
1025
    );
1026
}
1027
 
1028
/**
1029
 * Add nodes to myprofile page.
1030
 *
1031
 * @param \core_user\output\myprofile\tree $tree Tree object
1032
 * @param stdClass $user user object
1033
 * @param bool $iscurrentuser
1034
 * @param stdClass $course Course object
1035
 *
1036
 * @return bool
1037
 */
1038
function core_blog_myprofile_navigation(core_user\output\myprofile\tree $tree, $user, $iscurrentuser, $course) {
1039
    global $CFG;
1040
    if (!blog_is_enabled_for_user() || isguestuser($user)) {
1041
        // The guest user cannot post, so it is not possible to view any posts.
1042
        // Also blogs might be disabled.
1043
        // May as well just bail aggressively here.
1044
        return true;
1045
    }
1046
    if (!blog_user_can_view_user_entry($user->id)) {
1047
        return true;
1048
    }
1049
    $url = new moodle_url("/blog/index.php", array('userid' => $user->id));
1050
    if (!empty($course)) {
1051
        $url->param('courseid', $course->id);
1052
    }
1053
    if ($iscurrentuser) {
1054
        $title = get_string('blogentries', 'core_blog');
1055
    } else {
1056
        $title = get_string('myprofileuserblogs', 'core_blog');
1057
    }
1058
    $blognode = new core_user\output\myprofile\node('miscellaneous', 'blogs', $title, null, $url);
1059
    $tree->add_node($blognode);
1060
    return true;
1061
}
1062
 
1063
/**
1064
 * Returns posts tagged with a specified tag.
1065
 *
1066
 * @param core_tag_tag $tag
1067
 * @param bool $exclusivemode if set to true it means that no other entities tagged with this tag
1068
 *             are displayed on the page and the per-page limit may be bigger
1069
 * @param int $fromctx context id where the link was displayed, may be used by callbacks
1070
 *            to display items in the same context first
1071
 * @param int $ctx context id where to search for records
1072
 * @param bool $rec search in subcontexts as well
1073
 * @param int $page 0-based number of page being displayed
1074
 * @return \core_tag\output\tagindex
1075
 */
1076
function blog_get_tagged_posts($tag, $exclusivemode = false, $fromctx = 0, $ctx = 0, $rec = true, $page = 0) {
1077
    global $CFG, $OUTPUT;
1078
    require_once($CFG->dirroot.'/user/lib.php');
1079
 
1080
    $systemcontext = context_system::instance();
1081
    $perpage = $exclusivemode ? 20 : 5;
1082
    $context = $ctx ? context::instance_by_id($ctx) : context_system::instance();
1083
 
1084
    $content = '';
1085
    if (empty($CFG->enableblogs) || !has_capability('moodle/blog:view', $systemcontext)) {
1086
        // Blogs are not enabled or are not visible to the current user.
1087
        $totalpages = 0;
1088
    } else if ($context->contextlevel != CONTEXT_SYSTEM && empty($CFG->useblogassociations)) {
1089
        // No blog entries can be associated to the non-system context.
1090
        $totalpages = 0;
1091
    } else if (!$rec && $context->contextlevel != CONTEXT_COURSE && $context->contextlevel != CONTEXT_MODULE) {
1092
        // No blog entries can be associated with category or block context.
1093
        $totalpages = 0;
1094
    } else {
1095
        require_once($CFG->dirroot.'/blog/locallib.php');
1096
 
1097
        $filters = array('tag' => $tag->id);
1098
        if ($rec) {
1099
            if ($context->contextlevel != CONTEXT_SYSTEM) {
1100
                $filters['context'] = $context->id;
1101
            }
1102
        } else if ($context->contextlevel == CONTEXT_COURSE) {
1103
            $filters['course'] = $context->instanceid;
1104
        } else if ($context->contextlevel == CONTEXT_MODULE) {
1105
            $filters['module'] = $context->instanceid;
1106
        }
1107
        $bloglisting = new blog_listing($filters);
1108
        $blogs = $bloglisting->get_entries($page * $perpage, $perpage);
1109
        $totalcount = $bloglisting->count_entries();
1110
        $totalpages = ceil($totalcount / $perpage);
1111
        if (!empty($blogs)) {
1112
            $tagfeed = new core_tag\output\tagfeed();
1113
            foreach ($blogs as $blog) {
1114
                $user = fullclone($blog);
1115
                $user->id = $blog->userid;
1116
                $user->deleted = 0;
1117
                $img = $OUTPUT->user_picture($user, array('size' => 35));
1118
                $subject = format_string($blog->subject);
1119
 
1120
                if ($blog->publishstate == 'draft') {
1121
                    $class = 'dimmed';
1122
                } else {
1123
                    $class = '';
1124
                }
1125
 
1126
                $url = new moodle_url('/blog/index.php', array('entryid' => $blog->id));
1127
                $subject = html_writer::link($url, $subject, array('class' => $class));
1128
 
1129
                $fullname = fullname($user);
1130
                if (user_can_view_profile($user)) {
1131
                    $profilelink = new moodle_url('/user/view.php', array('id' => $blog->userid));
1132
                    $fullname = html_writer::link($profilelink, $fullname);
1133
                }
1134
                $details = $fullname . ', ' . userdate($blog->created);
1135
 
1136
                $tagfeed->add($img, $subject, $details);
1137
            }
1138
 
1139
            $items = $tagfeed->export_for_template($OUTPUT);
1140
            $content = $OUTPUT->render_from_template('core_tag/tagfeed', $items);
1141
 
1142
            $urlparams = array('tagid' => $tag->id);
1143
            if ($context->contextlevel == CONTEXT_COURSE) {
1144
                $urlparams['courseid'] = $context->instanceid;
1145
            } else if ($context->contextlevel == CONTEXT_MODULE) {
1146
                $urlparams['modid'] = $context->instanceid;
1147
            }
1148
            $allblogsurl = new moodle_url('/blog/index.php', $urlparams);
1149
 
1150
            $rv = new core_tag\output\tagindex($tag, 'core', 'post',
1151
                    $content,
1152
                    $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1153
            $rv->exclusiveurl = $allblogsurl;
1154
            return $rv;
1155
        }
1156
    }
1157
 
1158
    $rv = new core_tag\output\tagindex($tag, 'core', 'post',
1159
            $content,
1160
            $exclusivemode, $fromctx, $ctx, $rec, $page, $totalpages);
1161
    $rv->exclusiveurl = null;
1162
    return $rv;
1163
}
1164
 
1165
/**
1166
 * Validate the access to a blog.
1167
 *
1168
 * @param  int $courseid course id the the blog is associated to (can be null).
1169
 * @param  int $modid    module id the blog is associated to (can be null).
1170
 * @param  int $groupid  group id to filter blogs I can see (can be null)
1171
 * @param  int $entryid  blog entry id (can be null)
1172
 * @param  int $userid   blog author id (can be null)
1173
 * @return array with the calculated course and id
1174
 * @since  Moodle 3.6
1175
 */
1176
function blog_validate_access($courseid, $modid, $groupid, $entryid, $userid) {
1177
    global $CFG, $DB, $USER, $COURSE;
1178
 
1179
    $sitecontext = context_system::instance();
1180
 
1181
    // Add courseid if modid or groupid is specified: This is used for navigation and title.
1182
    if (!empty($modid) && empty($courseid)) {
1183
        $courseid = $DB->get_field('course_modules', 'course', array('id' => $modid));
1184
    }
1185
 
1186
    if (!empty($groupid) && empty($courseid)) {
1187
        $courseid = $DB->get_field('groups', 'courseid', array('id' => $groupid));
1188
    }
1189
 
1190
    if (!$userid && has_capability('moodle/blog:view', $sitecontext) && $CFG->bloglevel > BLOG_USER_LEVEL) {
1191
        if ($entryid) {
1192
            if (!$entryobject = $DB->get_record('post', array('id' => $entryid))) {
1193
                throw new \moodle_exception('nosuchentry', 'blog');
1194
            }
1195
            $userid = $entryobject->userid;
1196
        }
1197
    } else if (!$userid) {
1198
        $userid = $USER->id;
1199
    }
1200
 
1201
    if (!empty($modid)) {
1202
        if ($CFG->bloglevel < BLOG_SITE_LEVEL) {
1203
            throw new \moodle_exception('courseblogdisable', 'blog');
1204
        }
1205
        if (!$mod = $DB->get_record('course_modules', array('id' => $modid))) {
1206
            throw new \moodle_exception('invalidmoduleid', 'error', '', $modid);
1207
        }
1208
        $courseid = $mod->course;
1209
    }
1210
 
1211
    if ((empty($courseid) ? true : $courseid == SITEID) && empty($userid)) {
1212
        if ($CFG->bloglevel < BLOG_SITE_LEVEL) {
1213
            throw new \moodle_exception('siteblogdisable', 'blog');
1214
        }
1215
        if (!has_capability('moodle/blog:view', $sitecontext)) {
1216
            throw new \moodle_exception('cannotviewsiteblog', 'blog');
1217
        }
1218
 
1219
        $COURSE = $DB->get_record('course', array('format' => 'site'));
1220
        $courseid = $COURSE->id;
1221
    }
1222
 
1223
    if (!empty($courseid)) {
1224
        if (!$course = $DB->get_record('course', array('id' => $courseid))) {
1225
            throw new \moodle_exception('invalidcourseid');
1226
        }
1227
 
1228
        $courseid = $course->id;
1229
 
1230
        if (!has_capability('moodle/blog:view', $sitecontext)) {
1231
            throw new \moodle_exception('cannotviewcourseblog', 'blog');
1232
        }
1233
    } else {
1234
        $coursecontext = context_course::instance(SITEID);
1235
    }
1236
 
1237
    if (!empty($groupid)) {
1238
        if ($CFG->bloglevel < BLOG_SITE_LEVEL) {
1239
            throw new \moodle_exception('groupblogdisable', 'blog');
1240
        }
1241
 
1242
        if (! $group = groups_get_group($groupid)) {
1243
            throw new \moodle_exception('invalidgroupid', 'blog');
1244
        }
1245
 
1246
        if (!$course = $DB->get_record('course', array('id' => $group->courseid))) {
1247
            throw new \moodle_exception('invalidcourseid');
1248
        }
1249
 
1250
        $coursecontext = context_course::instance($course->id);
1251
        $courseid = $course->id;
1252
 
1253
        if (!has_capability('moodle/blog:view', $sitecontext)) {
1254
            throw new \moodle_exception('cannotviewcourseorgroupblog', 'blog');
1255
        }
1256
 
1257
        if (groups_get_course_groupmode($course) == SEPARATEGROUPS &&
1258
                !has_capability('moodle/site:accessallgroups', $coursecontext)) {
1259
 
1260
            if (!groups_is_member($groupid)) {
1261
                throw new \moodle_exception('notmemberofgroup');
1262
            }
1263
        }
1264
    }
1265
 
1266
    if (!empty($userid)) {
1267
        if ($CFG->bloglevel < BLOG_USER_LEVEL) {
1268
            throw new \moodle_exception('blogdisable', 'blog');
1269
        }
1270
 
1271
        if (!$user = $DB->get_record('user', array('id' => $userid))) {
1272
            throw new \moodle_exception('invaliduserid');
1273
        }
1274
 
1275
        if ($user->deleted) {
1276
            throw new \moodle_exception('userdeleted');
1277
        }
1278
 
1279
        if ($USER->id == $userid) {
1280
            if (!has_capability('moodle/blog:create', $sitecontext)
1281
              && !has_capability('moodle/blog:view', $sitecontext)) {
1282
                throw new \moodle_exception('donothaveblog', 'blog');
1283
            }
1284
        } else {
1285
            if (!has_capability('moodle/blog:view', $sitecontext) || !blog_user_can_view_user_entry($userid)) {
1286
                throw new \moodle_exception('cannotviewcourseblog', 'blog');
1287
            }
1288
        }
1289
    }
1290
    return array($courseid, $userid);
1291
}
1292
 
1293
/**
1294
 * Get blog editor and attachment options for when creating or updating an entry
1295
 *
1296
 * @param mixed $entry The entry object (can be null)
1297
 * @return array editor and attachment options
1298
 */
1299
function blog_get_editor_options(mixed $entry = null): array {
1300
    global $CFG;
1301
 
1302
    if (is_null($entry)) {
1303
        $entry = new stdClass();
1304
        $entry->id = null;
1305
    }
1306
 
1307
    $sitecontext = context_system::instance();
1308
 
1309
    $summaryoptions = ['maxfiles' => 99, 'maxbytes' => $CFG->maxbytes, 'trusttext' => true, 'context' => $sitecontext,
1310
        'subdirs' => file_area_contains_subdirs($sitecontext, 'blog', 'post', $entry->id)];
1311
    $attachmentoptions = ['subdirs' => false, 'maxfiles' => 99, 'maxbytes' => $CFG->maxbytes];
1312
 
1313
    return [$summaryoptions, $attachmentoptions];
1314
}