lib.php 48.5 KB
Newer Older
1 2 3 4 5
<?php
/**
 *
 * @package    mahara
 * @subpackage artefact-blog
6
 * @author     Catalyst IT Ltd
7 8
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL version 3 or later
 * @copyright  For copyright information on Mahara, please see the README file distributed with this software.
9 10 11 12 13
 *
 */

defined('INTERNAL') || die();

14
/**
15 16 17 18 19 20 21 22 23 24
 * Users can create blogs and blog posts using this plugin.
 */
class PluginArtefactBlog extends PluginArtefact {

    public static function get_artefact_types() {
        return array(
            'blog',
            'blogpost',
        );
    }
25

26 27 28
    public static function get_block_types() {
        return array();
    }
29 30 31 32 33

    public static function get_plugin_name() {
        return 'blog';
    }

34 35 36 37
    public static function admin_menu_items() {
        $map['manageinstitutions/blogs'] = array(
            'path'   => 'manageinstitutions/blogs',
            'url'    => 'artefact/blog/index.php?institution=1',
38
            'title'  => get_string('Blogs', 'artefact.blog'),
39 40 41 42 43
            'weight' => 75,
        );
        $map['configsite/blogs'] = array(
            'path'   => 'configsite/blogs',
            'url'    => 'artefact/blog/index.php?institution=mahara',
44
            'title'  => get_string('Blogs', 'artefact.blog'),
45 46 47 48 49 50 51 52 53 54 55 56 57
            'weight' => 65,
        );

        if (defined('MENUITEM') && isset($map[MENUITEM])) {
            $map[MENUITEM]['selected'] = true;
        }
        return $map;
    }

    public static function institution_menu_items() {
        return self::admin_menu_items();
    }

58
    public static function set_blog_nav($institution = false, $institutionname = null, $groupid = null) {
59 60 61 62 63 64 65 66
        if ($institutionname == 'mahara') {
            define('ADMIN', 1);
            define('MENUITEM', 'configsite/blogs');
        }
        else if ($institution) {
            define('INSTITUTIONALADMIN', 1);
            define('MENUITEM', 'manageinstitutions/blogs');
        }
67 68 69 70
        else if ($groupid) {
            define('GROUP', $groupid);
            define('MENUITEM', 'groups/blogs');
        }
71 72 73 74 75
        else {
            define('MENUITEM', 'content/blogs');
        }
    }

76 77 78 79
    public static function is_active() {
        return get_field('artefact_installed', 'active', 'name', 'blog');
    }

80
    public static function menu_items() {
81
        global $USER;
82
        $tab = array(
83 84
            'path'   => 'content/blogs',
            'weight' => 40,
85
            'url'    => 'artefact/blog/index.php',
86
            'title'  => get_string('Blogs', 'artefact.blog'),
87
        );
88
        return array('content/blogs' => $tab);
89
    }
90

91
    public static function get_cron() {
92
        return array();
93 94
    }

95

96 97 98 99 100 101 102 103 104 105
    public static function get_event_subscriptions() {
        return array(
            (object)array(
                'plugin'       => 'blog',
                'event'        => 'createuser',
                'callfunction' => 'create_default_blog',
            ),
        );
    }

106
    public static function block_advanced_options_element($configdata, $artefacttype) {
107
        $strartefacttype = strtolower(get_string($artefacttype, 'artefact.blog'));
108 109 110 111 112 113 114 115 116 117

        $options = array('nocopy' => get_string('copynocopy', 'artefact.blog'));
        if ($artefacttype == 'taggedposts') {
            $options['tagsonly'] = get_string('copytagsonly', 'artefact.blog', $strartefacttype);
        }
        else {
            $options['reference'] = get_string('copyreference', 'artefact.blog', $strartefacttype);
            $options['full'] = get_string('copyfull', 'artefact.blog', $strartefacttype);
        }

118 119 120
        return array(
            'type' => 'fieldset',
            'name' => 'advanced',
121
            'class' => 'first last',
122 123
            'collapsible' => true,
            'collapsed' => false,
124
            'legend' => get_string('moreoptions', 'artefact.blog'),
125 126 127 128 129 130
            'elements' => array(
                'copytype' => array(
                    'type' => 'select',
                    'title' => get_string('blockcopypermission', 'view'),
                    'description' => get_string('blockcopypermissiondesc', 'view'),
                    'defaultvalue' => isset($configdata['copytype']) ? $configdata['copytype'] : 'nocopy',
131
                    'options' => $options,
132 133 134 135 136
                ),
            ),
        );
    }

137 138 139 140 141 142 143 144
    public static function create_default_blog($event, $user) {
        $name = display_name($user, null, true);
        $blog = new ArtefactTypeBlog(0, (object) array(
            'title'       => get_string('defaultblogtitle', 'artefact.blog', $name),
            'owner'       => $user['id'],
        ));
        $blog->commit();
    }
145 146 147 148 149 150

    public static function get_artefact_type_content_types() {
        return array(
            'blogpost' => array('text'),
        );
    }
151

152
    public static function progressbar_link($artefacttype) {
153 154
        return 'artefact/blog/view/index.php';
    }
155 156 157 158 159 160 161 162 163 164 165

    public static function group_tabs($groupid) {
        return array(
            'blogs' => array(
                'path' => 'groups/blogs',
                'url' => 'artefact/blog/index.php?group=' . $groupid,
                'title' => get_string('Blogs', 'artefact.blog'),
                'weight' => 65,
            ),
        );
    }
166 167 168 169 170 171 172
}

/**
 * A Blog artefact is a collection of BlogPost artefacts.
 */
class ArtefactTypeBlog extends ArtefactType {

Alastair Pharo's avatar
Alastair Pharo committed
173 174 175 176
    /**
     * This constant gives the per-page pagination for listing blogs.
     */
    const pagination = 10;
177 178


179 180 181 182 183 184 185 186
    /**
     * We override the constructor to fetch the extra data.
     *
     * @param integer
     * @param object
     */
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);
187 188 189 190 191 192

        if (empty($this->id)) {
            $this->container = 1;
        }
    }

193 194 195 196
    public static function is_allowed_in_progressbar() {
        return false;
    }

Alastair Pharo's avatar
Alastair Pharo committed
197
    /**
198 199 200
     * This function updates or inserts the artefact.  This involves putting
     * some data in the artefact table (handled by parent::commit()), and then
     * some data in the artefact_blog_blog table.
Alastair Pharo's avatar
Alastair Pharo committed
201
     */
202
    public function commit() {
203 204 205 206
        // Just forget the whole thing when we're clean.
        if (empty($this->dirty)) {
            return;
        }
207

208 209
        // We need to keep track of newness before and after.
        $new = empty($this->id);
210

211 212 213 214
        // Commit to the artefact table.
        parent::commit();

        $this->dirty = false;
215 216
    }

Alastair Pharo's avatar
Alastair Pharo committed
217
    /**
218 219
     * This function extends ArtefactType::delete() by deleting blog-specific
     * data.
Alastair Pharo's avatar
Alastair Pharo committed
220
     */
221
    public function delete() {
222 223 224 225
        if (empty($this->id)) {
            return;
        }

226 227 228 229
        db_begin();
        // Delete embedded images in the blog description
        require_once('embeddedimage.php');
        EmbeddedImage::delete_embedded_images('blog', $this->id);
230 231
        // Delete the artefact and all children.
        parent::delete();
232
        db_commit();
233 234
    }

235
    /**
236 237 238 239 240 241
     * Checks that the person viewing a personal blog is the owner.
     * Or the person is an institution admin for an institution blog.
     * Or a group member if viewing a group blog.
     * Or a group member with editing permissions if editing a blog.
     * If not, throws an AccessDeniedException.
     * Other people see blogs when they are placed in views.
242
     */
243
    public function check_permission($editing=false) {
244
        global $USER;
245

246 247 248 249 250 251 252 253
        if (!empty($this->institution)) {
            if ($this->institution == 'mahara' && !$USER->get('admin')) {
                throw new AccessDeniedException(get_string('youarenotasiteadmin', 'artefact.blog'));
            }
            else if (!$USER->get('admin') && !$USER->is_institutional_admin($this->institution)) {
                throw new AccessDeniedException(get_string('youarenotanadminof', 'artefact.blog', $this->institution));
            }
        }
254 255 256 257 258 259 260 261 262 263 264
        else if (!empty($this->group)) {
            $group = get_record('group', 'id', $this->group, 'deleted', 0);
            $USER->reset_grouproles();
            if (!isset($USER->grouproles[$this->group])) {
                throw new AccessDeniedException(get_string('youarenotamemberof', 'artefact.blog', $group->name));
            }
            require_once('group.php');
            if ($editing && !group_role_can_edit_views($this->group, $USER->grouproles[$this->group])) {
                throw new AccessDeniedException(get_string('youarenotaneditingmemberof', 'artefact.blog', $group->name));
            }
        }
265 266 267 268
        else {
            if ($USER->get('id') != $this->owner) {
                throw new AccessDeniedException(get_string('youarenottheownerofthisblog', 'artefact.blog'));
            }
269 270 271
        }
    }

272

273 274
    public function describe_size() {
        return $this->count_children() . ' ' . get_string('posts', 'artefact.blog');
275 276
    }

277
    /**
278
     * Renders a blog.
279 280 281 282 283
     *
     * @param  array  Options for rendering
     * @return array  A two key array, 'html' and 'javascript'.
     */
    public function render_self($options) {
284 285 286 287 288 289 290 291 292 293 294
        if (!isset($options['limit'])) {
            $limit = self::pagination;
        }
        else if ($options['limit'] === false) {
            $limit = null;
        }
        else {
            $limit = (int) $options['limit'];
        }
        $offset = isset($options['offset']) ? intval($options['offset']) : 0;

295 296 297 298 299
        if (!isset($options['countcomments'])) {
            // Count comments if this is a view
            $options['countcomments'] = (!empty($options['viewid']));
        }

300 301 302 303
        $posts = ArtefactTypeBlogpost::get_posts($this->id, $limit, $offset, $options);

        $template = 'artefact:blog:viewposts.tpl';

304
        $baseurl = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $this->id;
305 306 307
        if (!empty($options['viewid'])) {
            $baseurl .= '&view=' . $options['viewid'];
        }
308 309 310 311 312 313 314 315 316
        $pagination = array(
            'baseurl' => $baseurl,
            'id' => 'blogpost_pagination',
            'datatable' => 'postlist',
            'jsonscript' => 'artefact/blog/posts.json.php',
        );

        ArtefactTypeBlogpost::render_posts($posts, $template, $options, $pagination);

317 318
        $smarty = smarty_core();
        if (isset($options['viewid'])) {
319
            $smarty->assign('artefacttitle', '<a href="' . get_config('wwwroot') . 'artefact/artefact.php?artefact='
320
                                             . $this->get('id') . '&view=' . $options['viewid']
Richard Mansfield's avatar
Richard Mansfield committed
321
                                             . '">' . hsc($this->get('title')) . '</a>');
322 323
        }
        else {
Richard Mansfield's avatar
Richard Mansfield committed
324
            $smarty->assign('artefacttitle', hsc($this->get('title')));
325 326
        }

327 328 329 330 331 332 333
        if (!empty($options['details']) and get_config('licensemetadata')) {
            $smarty->assign('license', render_license($this));
        }
        else {
            $smarty->assign('license', false);
        }

334
        $options['hidetitle'] = true;
335
        $smarty->assign('options', $options);
336
        $smarty->assign('description', $this->get('description'));
337 338
        $smarty->assign('owner', $this->get('owner'));
        $smarty->assign('tags', $this->get('tags'));
339

340
        $smarty->assign('posts', $posts);
341

342
        return array('html' => $smarty->fetch('artefact:blog:blog.tpl'), 'javascript' => '');
343 344
    }

345

346
    public static function get_icon($options=null) {
347
        global $THEME;
348
        return false;
349 350
    }

351
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
352 353 354
        return false;
    }

Alastair Pharo's avatar
Alastair Pharo committed
355
    public static function collapse_config() {
356 357
    }

358 359 360 361
    public function can_have_attachments() {
        return true;
    }

Alastair Pharo's avatar
Alastair Pharo committed
362
    /**
363
     * This function returns a list of the given blogs.
Alastair Pharo's avatar
Alastair Pharo committed
364 365 366 367
     *
     * @param User
     * @return array (count: integer, data: array)
     */
368
    public static function get_blog_list($limit, $offset, $institution = null, $group = null) {
369
        global $USER;
370 371 372 373 374 375 376 377 378

        $sql = "SELECT b.id, b.title, b.description, b.locked, COUNT(p.id) AS postcount
                FROM {artefact} b LEFT JOIN {artefact} p ON (p.parent = b.id AND p.artefacttype = 'blogpost')
                WHERE b.artefacttype = 'blog'";
        if ($institution) {
            $sql .= ' AND b.institution = ?';
            $values = array($institution);
            $count = (int)get_field('artefact', 'COUNT(*)', 'institution', $institution, 'artefacttype', 'blog');
        }
379 380 381 382 383
        else if ($group) {
            $sql .= ' AND b.group = ?';
            $values = array($group);
            $count = (int)get_field('artefact', 'COUNT(*)', 'group', $group, 'artefacttype', 'blog');
        }
384 385 386 387 388 389 390
        else {
            $sql .= ' AND b.owner = ?';
            $values = array($USER->get('id'));
            $count = (int)get_field('artefact', 'COUNT(*)', 'owner', $USER->get('id'), 'artefacttype', 'blog');
        }
        $sql .= " GROUP BY b.id, b.title, b.description, b.locked ORDER BY b.title";
        ($result = get_records_sql_array($sql, $values, $offset, $limit))
Alastair Pharo's avatar
Alastair Pharo committed
391 392
            || ($result = array());

393 394
        foreach ($result as &$r) {
            if (!$r->locked) {
395
                $r->deleteform = ArtefactTypeBlog::delete_form($r->id, $r->title);
396 397 398
            }
        }

Alastair Pharo's avatar
Alastair Pharo committed
399 400 401
        return array($count, $result);
    }

402 403
    public static function build_blog_list_html(&$blogs) {
        $smarty = smarty_core();
404
        $smarty->assign('blogs', $blogs);
405 406
        $blogs->tablerows = $smarty->fetch('artefact:blog:bloglist.tpl');
        $pagination = build_pagination(array(
407 408 409
            'id' => 'bloglist_pagination',
            'class' => 'center',
            'url' => get_config('wwwroot') . 'artefact/blog/index.php',
410 411
            'jsonscript' => 'artefact/blog/index.json.php',
            'datatable' => 'bloglist',
412 413 414
            'count' => $blogs->count,
            'limit' => $blogs->limit,
            'offset' => $blogs->offset,
415
            'setlimit' => true,
416 417
            'jumplinks' => 6,
            'numbersincludeprevnext' => 2,
418 419 420
            'resultcounttextsingular' => get_string('blog', 'artefact.blog'),
            'resultcounttextplural' => get_string('blogs', 'artefact.blog'),
        ));
421 422
        $blogs->pagination = $pagination['html'];
        $blogs->pagination_js = $pagination['javascript'];
423 424
    }

Alastair Pharo's avatar
Alastair Pharo committed
425 426 427
    /**
     * This function creates a new blog.
     *
428
     * @param User or null
Alastair Pharo's avatar
Alastair Pharo committed
429 430
     * @param array
     */
431
    public static function new_blog($user, array $values) {
432 433
        require_once('embeddedimage.php');
        db_begin();
Alastair Pharo's avatar
Alastair Pharo committed
434 435 436
        $artefact = new ArtefactTypeBlog();
        $artefact->set('title', $values['title']);
        $artefact->set('description', $values['description']);
437 438 439
        if (!empty($values['institution'])) {
            $artefact->set('institution', $values['institution']);
        }
440 441 442
        else if (!empty($values['group'])) {
            $artefact->set('group', $values['group']);
        }
443 444 445
        else {
            $artefact->set('owner', $user->get('id'));
        }
446
        $artefact->set('tags', $values['tags']);
447 448 449 450 451
        if (get_config('licensemetadata')) {
            $artefact->set('license', $values['license']);
            $artefact->set('licensor', $values['licensor']);
            $artefact->set('licensorurl', $values['licensorurl']);
        }
Alastair Pharo's avatar
Alastair Pharo committed
452
        $artefact->commit();
453 454 455 456
        $blogid = $artefact->get('id');
        $newdescription = EmbeddedImage::prepare_embedded_images($artefact->get('description'), 'blog', $blogid);
        $artefact->set('description', $newdescription);
        db_commit();
457
    }
Alastair Pharo's avatar
Alastair Pharo committed
458 459 460 461 462 463 464 465

    /**
     * This function updates an existing blog.
     *
     * @param User
     * @param array
     */
    public static function edit_blog(User $user, array $values) {
466
        require_once('embeddedimage.php');
Alastair Pharo's avatar
Alastair Pharo committed
467 468 469 470 471
        if (empty($values['id']) || !is_numeric($values['id'])) {
            return;
        }

        $artefact = new ArtefactTypeBlog($values['id']);
472 473 474
        $institution = !empty($values['institution']) ? $values['institution'] : null;
        $group = !empty($values['group']) ? $values['group'] : null;
        if (!self::can_edit_blog($artefact, $institution, $group)) {
475 476
            return;
        }
Alastair Pharo's avatar
Alastair Pharo committed
477
        $artefact->set('title', $values['title']);
478 479
        $newdescription = EmbeddedImage::prepare_embedded_images($values['description'], 'blog', $values['id']);
        $artefact->set('description', $newdescription);
480
        $artefact->set('tags', $values['tags']);
481 482 483 484 485
        if (get_config('licensemetadata')) {
            $artefact->set('license', $values['license']);
            $artefact->set('licensor', $values['licensor']);
            $artefact->set('licensorurl', $values['licensorurl']);
        }
Alastair Pharo's avatar
Alastair Pharo committed
486 487
        $artefact->commit();
    }
488

Martyn Smith's avatar
Martyn Smith committed
489 490
    public static function get_links($id) {
        $wwwroot = get_config('wwwroot');
491

Martyn Smith's avatar
Martyn Smith committed
492
        return array(
493 494
            '_default'                                  => $wwwroot . 'artefact/blog/view/index.php?id=' . $id,
            get_string('blogsettings', 'artefact.blog') => $wwwroot . 'artefact/blog/settings/index.php?id=' . $id,
Martyn Smith's avatar
Martyn Smith committed
495 496
        );
    }
497 498 499 500 501

    public function copy_extra($new) {
        $new->set('title', get_string('Copyof', 'mahara', $this->get('title')));
    }

502 503 504
    /**
     * Returns the number of posts in this blog that have been published.
     *
505
     * The result of this function looked up from the database each time, so
506 507 508 509 510 511 512 513 514 515 516 517 518
     * cache it if you know it's safe to do so.
     *
     * @return int
     */
    public function count_published_posts() {
        return (int)get_field_sql("
            SELECT COUNT(*)
            FROM {artefact} a
            LEFT JOIN {artefact_blog_blogpost} bp ON a.id = bp.blogpost
            WHERE a.parent = ?
            AND bp.published = 1", array($this->get('id')));
    }

519
    public static function delete_form($id, $title = '') {
520
        global $THEME;
521 522

        $confirm = get_string('deleteblog?', 'artefact.blog');
523
        $title = hsc($title);
524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544
        // Check if this blog has posts.
        $postcnt = count_records_sql("
            SELECT COUNT(*)
            FROM {artefact} a
            INNER JOIN {artefact_blog_blogpost} bp ON a.id = bp.blogpost
            WHERE a.parent = ?
            ", array($id));
        if ($postcnt > 0) {
            $confirm = get_string('deletebloghaspost?', 'artefact.blog', $postcnt);

            // Check if this blog posts used in views.
            $viewscnt = count_records_sql("
                SELECT COUNT(DISTINCT(va.view))
                FROM {artefact} a
                INNER JOIN {view_artefact} va ON a.id = va.artefact
                WHERE a.parent = ? OR a.id = ?
                ", array($id, $id));
            if ($viewscnt > 0) {
                $confirm = get_string('deletebloghasview?', 'artefact.blog', $viewscnt);
            }
        }
545 546 547
        return pieform(array(
            'name' => 'delete_' . $id,
            'successcallback' => 'delete_blog_submit',
548 549
            'renderer' => 'div',
            'class' => 'form-as-button pull-left btn-group-item',
550 551
            'elements' => array(
                'submit' => array(
552 553
                    'type' => 'button',
                    'usebuttontag' => true,
554
                    'class' => 'btn-default btn-sm last',
555 556
                    'alt' => get_string('deletespecific', 'mahara', $title),
                    'elementtitle' => get_string('delete'),
557
                    'confirm' => $confirm,
558
                    'value' => '<span class="icon icon-trash icon-lg text-danger" role="presentation" aria-hidden="true"></span><span class="sr-only">' . get_string('delete') . '</span>',
559 560 561 562
                ),
                'delete' => array(
                    'type' => 'hidden',
                    'value' => $id,
563 564 565 566
                ),
            ),
        ));
    }
567

568 569 570 571 572 573 574 575 576
    public function update_artefact_references(&$view, &$template, &$artefactcopies, $oldid) {
        parent::update_artefact_references($view, $template, $artefactcopies, $oldid);
        // Update <img> tags in the blog description to refer to the new image artefacts.
        $regexp = array();
        $replacetext = array();
        if (isset($artefactcopies[$oldid]->oldembeds)) {
            foreach ($artefactcopies[$oldid]->oldembeds as $a) {
                if (isset($artefactcopies[$a])) {
                    // Change the old image id to the new one
577 578
                    $regexp[] = '#<img([^>]+)src="' . get_config('wwwroot') . 'artefact/file/download.php\?file=' . $a . '([^0-9])#';
                    $replacetext[] = '<img$1src="' . get_config('wwwroot') . 'artefact/file/download.php?file=' . $artefactcopies[$a]->newid . '$2';
579 580 581 582 583 584 585 586 587 588 589 590 591
                }
            }
            require_once('embeddedimage.php');
            $newdescription = EmbeddedImage::prepare_embedded_images(
                preg_replace($regexp, $replacetext, $this->get('description')),
                'blog',
                $this->get('id'),
                $view->get('group')
            );
            $this->set('description', $newdescription);
        }
    }

592 593 594 595 596 597 598 599 600
    /**
     * During the copying of a view, we might be allowed to copy
     * blogs. Users need to have multipleblogs enabled for these
     * to be visible.
     */
    public function default_parent_for_copy(&$view, &$template, $artefactstoignore) {
        global $USER, $SESSION;

        $viewid = $view->get('id');
601 602 603
        $groupid = $view->get('group');
        $institution = $view->get('institution');
        if ($groupid || $institution) {
604
            $SESSION->add_msg_once(get_string('copiedblogpoststonewjournal', 'collection'), 'ok', true, 'messages');
605
        }
606 607 608 609
        else {
            try {
                $user = get_user($view->get('owner'));
                set_account_preference($user->id, 'multipleblogs', 1);
610
                $SESSION->add_msg_once(get_string('copiedblogpoststonewjournal', 'collection'), 'ok', true, 'messages');
611 612 613 614
            }
            catch (Exception $e) {
                $SESSION->add_error_msg(get_string('unabletosetmultipleblogs', 'error', $user->username, $viewid, get_config('wwwroot') . 'account/index.php'), false);
            }
615

616 617 618 619 620 621
            try {
                $USER->accountprefs = load_account_preferences($user->id);
            }
            catch (Exception $e) {
                $SESSION->add_error_msg(get_string('pleaseloginforjournals', 'error'));
            }
622 623 624 625
        }

        return null;
    }
626 627 628 629 630 631 632 633 634

    /**
     * Check to see if the user has permissions to edit the blog
     *
     * @param object $blog         A blog artefact
     * @param string $institution  Institution name (optional)
     *
     * @return boolean
     */
635
    public static function can_edit_blog($blog, $institution = null, $group = null) {
636
        global $USER;
637 638
        require_once('group.php');
        $USER->reset_grouproles();
639 640 641
        if (
            ($institution == 'mahara' && $USER->get('admin'))
            || ($institution && $institution != 'mahara' && ($USER->get('admin') || $USER->is_institutional_admin($institution)))
642
            || ($group && !empty($USER->grouproles[$group]) && group_role_can_edit_views($group, $USER->grouproles[$group]))
643 644 645 646 647 648
            || ($USER->get('id') == $blog->get('owner'))
           ) {
            return true;
        }
        return false;
    }
649 650 651 652 653 654 655
}

/**
 * BlogPost artefacts occur within Blog artefacts
 */
class ArtefactTypeBlogPost extends ArtefactType {

656
    /**
Alastair Pharo's avatar
Alastair Pharo committed
657 658 659 660 661 662 663 664 665 666 667 668 669 670 671
     * This defines whether the blogpost is published or not.
     *
     * @var boolean
     */
    protected $published = false;

    /**
     * We override the constructor to fetch the extra data.
     *
     * @param integer
     * @param object
     */
    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

672 673 674 675 676
        if ($this->id) {
            if ($bpdata = get_record('artefact_blog_blogpost', 'blogpost', $this->id)) {
                foreach($bpdata as $name => $value) {
                    if (property_exists($this, $name)) {
                        $this->$name = $value;
677
                    }
Alastair Pharo's avatar
Alastair Pharo committed
678
                }
679 680 681 682
            }
            else {
                // This should never happen unless the user is playing around with blog post IDs in the location bar or similar
                throw new ArtefactNotFoundException(get_string('blogpostdoesnotexist', 'artefact.blog'));
683 684
            }
        }
685 686 687
        else {
            $this->allowcomments = 1; // Turn comments on for new posts
        }
Alastair Pharo's avatar
Alastair Pharo committed
688 689 690
    }

    /**
691
     * This method extends ArtefactType::commit() by adding additional data
Alastair Pharo's avatar
Alastair Pharo committed
692
     * into the artefact_blog_blogpost table.
693
     *
694
     * This method also works out what blockinstances this blogpost is in, and
695
     * informs them that they should re-check what artefacts they have in them.
696
     * The post content may now link to different artefacts. See {@link
697
     * PluginBlocktypeBlogPost::get_artefacts for more information}
698
     */
699
    protected function postcommit_hook($new) {
700 701
        require_once(get_config('docroot') . 'blocktype/lib.php');
        require_once(get_config('docroot') . 'artefact/blog/blocktype/taggedposts/lib.php');
Alastair Pharo's avatar
Alastair Pharo committed
702 703 704 705 706 707 708 709 710 711 712 713
        $data = (object)array(
            'blogpost'  => $this->get('id'),
            'published' => ($this->get('published') ? 1 : 0)
        );

        if ($new) {
            insert_record('artefact_blog_blogpost', $data);
        }
        else {
            update_record('artefact_blog_blogpost', $data, 'blogpost');
        }

714
        // We want to get all blockinstances that may contain this blog post. That is currently:
715 716
        // 1) All blogpost blocktypes with this post in it
        // 2) All blog blocktypes with this posts's blog in it
717 718
        // 3) All recentposts blocktypes with this post's blog in it
        // 4) All taggedposts blocktypes with this post's tags
719
        $blocks = (array)get_column_sql('SELECT block
720 721 722
            FROM {view_artefact}
            WHERE artefact = ?
            OR artefact = ?', array($this->get('id'), $this->get('parent')));
723 724 725 726 727 728 729 730 731 732
        if (!$blocks) {
            $blocks = array();
        }

        // Get all "tagged blog entries" blocks that may contain this block
        // (we'll just check for a single matching tag here, and let each block
        // instance further down decide whether or not it matches
        $tags = $this->get('tags');
        if ($tags) {
            $blocks = array_merge($blocks, PluginBlocktypeTaggedposts::find_matching_blocks($tags));
733 734 735 736
        }

        // Now rebuild the list of which artefacts these blocks contain
        // in the view_artefacts table. (This is used for watchlist notifications)
737 738
        if ($blocks) {
            foreach ($blocks as $id) {
739 740 741 742
                $instance = new BlockInstance($id);
                $instance->rebuild_artefact_list();
            }
        }
743 744
    }

745
    /**
Alastair Pharo's avatar
Alastair Pharo committed
746 747
     * This function extends ArtefactType::delete() by also deleting anything
     * that's in blogpost.
748
     */
749
    public function delete() {
Alastair Pharo's avatar
Alastair Pharo committed
750 751 752
        if (empty($this->id)) {
            return;
        }
753

754
        require_once('embeddedimage.php');
755
        db_begin();
756
        $this->detach(); // Detach all file attachments
Alastair Pharo's avatar
Alastair Pharo committed
757
        delete_records('artefact_blog_blogpost', 'blogpost', $this->id);
758
        EmbeddedImage::delete_embedded_images('blogpost', $this->id);
Alastair Pharo's avatar
Alastair Pharo committed
759
        parent::delete();
760
        db_commit();
Alastair Pharo's avatar
Alastair Pharo committed
761
    }
762

763
    public static function bulk_delete($artefactids, $log=false) {
764 765 766 767 768 769 770 771 772 773 774 775 776
        if (empty($artefactids)) {
            return;
        }

        $idstr = join(',', array_map('intval', $artefactids));

        db_begin();
        delete_records_select('artefact_blog_blogpost', 'blogpost IN (' . $idstr . ')');
        parent::bulk_delete($artefactids);
        db_commit();
    }


777
    /**
778 779 780 781 782 783
     * Checks that the person viewing a personal blog is the owner.
     * Or the person is an institution admin for an institution blog.
     * Or a group member if viewing a group blog.
     * Or a group member with editing permissions if editing a blog.
     * If not, throws an AccessDeniedException.
     * Other people see blogs when they are placed in views.
784
     */
785
    public function check_permission($editing=true) {
786
        global $USER;
787 788 789 790 791 792 793 794
        if (!empty($this->institution)) {
            if ($this->institution == 'mahara' && !$USER->get('admin')) {
                throw new AccessDeniedException(get_string('youarenotasiteadmin', 'artefact.blog'));
            }
            else if (!$USER->get('admin') && !$USER->is_institutional_admin($this->institution)) {
                throw new AccessDeniedException(get_string('youarenotanadminof', 'artefact.blog', $this->institution));
            }
        }
795 796 797 798 799 800 801 802 803 804 805
        else if (!empty($this->group)) {
            $group = get_record('group', 'id', $this->group, 'deleted', 0);
            $USER->reset_grouproles();
            if (!isset($USER->grouproles[$this->group])) {
                throw new AccessDeniedException(get_string('youarenotamemberof', 'artefact.blog', $group->name));
            }
            require_once('group.php');
            if ($editing && !group_role_can_edit_views($this->group, $USER->grouproles[$this->group])) {
                throw new AccessDeniedException(get_string('youarenotaneditingmemberof', 'artefact.blog', $group->name));
            }
        }
806 807 808 809
        else {
            if ($USER->get('id') != $this->owner) {
                throw new AccessDeniedException(get_string('youarenottheownerofthisblogpost', 'artefact.blog'));
            }
810 811
        }
    }
812

813 814
    public function describe_size() {
        return $this->count_attachments() . ' ' . get_string('attachments', 'artefact.blog');
815 816
    }

817
    public function render_self($options) {
818 819
        global $USER;

820
        $smarty = smarty_core();
821 822 823 824 825 826 827 828
        $smarty->assign('published', $this->get('published'));
        if (!$this->get('published')) {
            $notpublishedblogpoststr = get_string('notpublishedblogpost', 'artefact.blog');
            if ($this->get('owner') == $USER->get('id')) {
                $notpublishedblogpoststr .= ' <a href="' . get_config('wwwroot') . 'artefact/blog/post.php?id=' . $this->get('id') . '">' . get_string('publishit', 'artefact.blog') . '</a>';
            }
            $smarty->assign('notpublishedblogpost', $notpublishedblogpoststr);
        }
829
        $artefacturl = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $this->get('id');
830 831 832 833
        if (isset($options['viewid'])) {
            $artefacturl .= '&view=' . $options['viewid'];
        }
        $smarty->assign('artefacturl', $artefacturl);
834 835
        if (empty($options['hidetitle'])) {
            if (isset($options['viewid'])) {
836
                $smarty->assign('artefacttitle', '<a href="' . $artefacturl . '">' . hsc($this->get('title')) . '</a>');
837 838
            }
            else {
Richard Mansfield's avatar
Richard Mansfield committed
839
                $smarty->assign('artefacttitle', hsc($this->get('title')));
840 841 842 843
            }
        }

        // We need to make sure that the images in the post have the right viewid associated with them
844
        $postcontent = $this->get('description');
845
        if (isset($options['viewid'])) {
846 847
            safe_require('artefact', 'file');
            $postcontent = ArtefactTypeFolder::append_view_url($postcontent, $options['viewid']);
848 849
        }
        $smarty->assign('artefactdescription', $postcontent);
850 851
        $smarty->assign('artefacttags', $this->get('tags'));
        $smarty->assign('artefactowner', $this->get('owner'));
852 853 854 855 856 857 858
        if (!empty($options['details']) and get_config('licensemetadata')) {
            $smarty->assign('license', render_license($this));
        }
        else {
            $smarty->assign('license', false);
        }

859
        $attachments = $this->get_attachments();
860
        if ($attachments) {
861
            require_once(get_config('docroot') . 'artefact/lib.php');
862 863 864
            foreach ($attachments as &$attachment) {
                $f = artefact_instance_from_id($attachment->id);
                $attachment->size = $f->describe_size();
865
                $attachment->iconpath = $f->get_icon(array('id' => $attachment->id, 'viewid' => isset($options['viewid']) ? $options['viewid'] : 0));
866
                $attachment->viewpath = get_config('wwwroot') . 'artefact/artefact.php?artefact=' . $attachment->id . '&view=' . (isset($options['viewid']) ? $options['viewid'] : 0);
867 868
                $attachment->downloadpath = get_config('wwwroot') . 'artefact/file/download.php?file=' . $attachment->id;
                if (isset($options['viewid'])) {
869
                    $attachment->downloadpath .= '&view=' . $options['viewid'];
870 871 872
                }
            }
            $smarty->assign('attachments', $attachments);
873 874 875 876
            if (isset($options['blockid'])) {
                $smarty->assign('blockid', $options['blockid']);
            }
            $smarty->assign('postid', $this->get('id'));
877 878 879 880 881 882 883 884 885
        }
        $smarty->assign('postedbyon', get_string('postedbyon', 'artefact.blog',
                                                 display_name($this->owner),
                                                 format_date($this->ctime)));
        return array('html' => $smarty->fetch('artefact:blog:render/blogpost_renderfull.tpl'),
                     'javascript' => '');
    }


886 887
    public function can_have_attachments() {
        return true;
Richard Mansfield's avatar
Richard Mansfield committed
888 889 890
    }


891
    public static function get_icon($options=null) {
892
        global $THEME;
893
        return false;
894 895
    }

896
    public static function is_singular() {
Penny Leach's avatar
Penny Leach committed
897 898 899
        return false;
    }

Alastair Pharo's avatar
Alastair Pharo committed
900
    public static function collapse_config() {
901 902
    }

903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939
    /**
     * This function returns the blog id and offset for a given post.
     *
     * @param integer $postid The id of the required blog post
     * @return object An object containing the required data
     */
    public static function get_post_data($postid) {
        $post = new stdClass();

        $post->blogid = get_field('artefact', 'parent', 'id', $postid, 'artefacttype', 'blogpost');

        if (is_postgres()) {
            $rownum = get_field_sql("SELECT rownum
                                    FROM (SELECT id, ROW_NUMBER() OVER (ORDER BY id DESC) AS rownum
                                        FROM {artefact}
                                        WHERE parent = ?
                                        ORDER BY id DESC) AS posts
                                    WHERE id = ?",
                    array($post->blogid, $postid));
        }
        else if (is_mysql()) {
            $initvar = execute_sql("SET @row_num = 0");
            if ($initvar) {
                $rownum = get_field_sql("SELECT rownum
                                        FROM (SELECT id, @row_num := @row_num + 1 AS rownum
                                            FROM {artefact}
                                            WHERE parent = ?
                                            ORDER BY id DESC) AS posts
                                        WHERE id = ?",
                        array($post->blogid, $postid));
            }
        }
        $post->offset = $rownum - 1;

        return $post;
    }

Alastair Pharo's avatar
Alastair Pharo committed
940
    /**
941
     * This function returns a list of posts in a given blog.
Alastair Pharo's avatar
Alastair Pharo committed
942 943 944
     *
     * @param integer
     * @param integer
945
     * @param integer
946
     * @param array
Alastair Pharo's avatar
Alastair Pharo committed
947
     */
948
    public static function get_posts($id, $limit, $offset, $viewoptions=null) {
Alastair Pharo's avatar
Alastair Pharo committed
949

950 951 952 953
        $results = array(
            'limit'  => $limit,
            'offset' => $offset,
        );
954

955 956 957 958 959 960 961 962 963 964 965
        // If viewoptions is null, we're getting posts for the my blogs area,
        // and we should get all posts & show drafts first.  Otherwise it's a
        // blog in a view, and we should only get published posts.

        $from = "
            FROM {artefact} a LEFT JOIN {artefact_blog_blogpost} bp ON a.id = bp.blogpost
            WHERE a.artefacttype = 'blogpost' AND a.parent = ?";

        if (!is_null($viewoptions)) {
            if (isset($viewoptions['before'])) {
                $from .= " AND a.ctime < '{$viewoptions['before']}'";
966
            }
967
            $draftentries = count_records_sql('SELECT COUNT(*) ' . $from, array($id));
968 969
            $from .= ' AND bp.published = 1';
        }
970

971 972
        $results['count'] = count_records_sql('SELECT COUNT(*) ' . $from, array($id));

973 974 975 976 977
        //check if all posts are drafts
        if (isset($draftentries) && $draftentries > 0 && $results['count'] == 0) {
            $results['alldraftposts'] = true;
        }

978 979 980
        $data = get_records_sql_assoc('
            SELECT
                a.id, a.title, a.description, a.author, a.authorname, ' .
981 982
                db_format_tsfield('a.ctime', 'ctime') . ', ' . db_format_tsfield('a.mtime', 'mtime') . ',
                a.locked, bp.published, a.allowcomments ' . $from . '
983
            ORDER BY bp.published ASC, a.ctime DESC, a.id DESC',
984 985 986 987 988 989 990 991 992 993 994 995 996 997 998
            array($id),
            $offset, $limit
        );

        if (!$data) {
            $results['data'] = array();
            return $results;
        }

        // Get the attached files.
        $postids = array_map(create_function('$a', 'return $a->id;'), $data);
        $files = ArtefactType::attachments_from_id_list($postids);
        if ($files) {
            safe_require('artefact', 'file');
            foreach ($files as &$file) {
999 1000 1001 1002 1003
                $params = array('id' => $file->attachment);
                if (!empty($viewoptions['viewid'])) {
                    $params['viewid'] = $viewoptions['viewid'];
                }
                $file->icon = call_static_method(generate_artefact_class_name($file->artefacttype), 'get_icon', $params);
1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014
                $data[$file->artefact]->files[] = $file;
            }
        }

        if ($tags = ArtefactType::tags_from_id_list($postids)) {
            foreach($tags as &$at) {
                $data[$at->artefact]->tags[] = $at->tag;
            }
        }

        foreach ($data as &$post) {
1015
            // Format dates properly
1016
            if (is_null($viewoptions)) {
1017 1018
                // My Blogs area: create forms for changing post status & deleting posts.
                $post->changepoststatus = ArtefactTypeBlogpost::changepoststatus_form($post->id, $post->published);
1019
                $post->delete = ArtefactTypeBlogpost::delete_form($post->id, $post->title);
1020
            }
1021 1022 1023
            else {
                $by = $post->author ? display_default_name($post->author) : $post->authorname;
                $post->postedby = get_string('postedbyon', 'artefact.blog', $by, format_date($post->ctime));
1024 1025 1026 1027 1028 1029
                // Get comment counts
                if (!empty($viewoptions['countcomments'])) {
                    safe_require('artefact', 'comment');
                    require_once(get_config('docroot') . 'lib/view.php');
                    $view = new View($viewoptions['viewid']);
                    $artefact = artefact_instance_from_id($post->id);
1030 1031 1032
                    list($commentcount, $comments) = ArtefactTypeComment::get_artefact_comments_for_view($artefact, $view, null, false);
                    $post->commentcount = $commentcount;
                    $post->comments = $comments;
1033
                }
1034 1035 1036
            }
            $post->ctime = format_date($post->ctime, 'strftimedaydatetime');
            $post->mtime = format_date($post->mtime);
1037 1038 1039 1040 1041 1042

            // Ensure images in the post have the right viewid associated with them
            if (!empty($viewoptions['viewid'])) {
                safe_require('artefact', 'file');
                $post->description = ArtefactTypeFolder::append_view_url($post->description, $viewoptions['viewid']);
            }
1043
        }
Alastair Pharo's avatar
Alastair Pharo committed
1044

1045 1046 1047
        $results['data'] = array_values($data);

        return $results;
1048 1049
    }

1050 1051 1052 1053 1054 1055 1056 1057 1058
    /**
     * This function renders a list of posts as html
     *
     * @param array posts
     * @param string template
     * @param array options
     * @param array pagination
     */
    public function render_posts(&$posts, $template, $options, $pagination) {
1059
        $smarty = smarty_core();
1060
        $smarty->assign('options', $options);
1061 1062
        $smarty->assign('posts', $posts['data']);

1063 1064
        $posts['tablerows'] = $smarty->fetch($template);

1065 1066
        $setlimit = isset($pagination['setlimit']) ? $pagination['setlimit'] : false;

1067
        if ($posts['limit'] && $pagination) {
1068
            $pagination = build_pagination(array(
1069 1070 1071 1072 1073 1074 1075
                'id' => $pagination['id'],
                'class' => 'center',
                'datatable' => $pagination['datatable'],
                'url' => $pagination['baseurl'],
                'jsonscript' => $pagination['jsonscript'],
                'count' => $posts['count'],
                'limit' => $posts['limit'],
1076
                'setlimit' => $setlimit,
1077
                'offset' => $posts['offset'],
1078 1079
                'jumplinks' => 6,
                'numbersincludeprevnext' => 2,
1080 1081 1082 1083 1084
                'resultcounttextsingular' => get_string('post', 'artefact.blog'),
                'resultcounttextplural' => get_string('posts', 'artefact.blog'),
            ));
            $posts['pagination'] = $pagination['html'];
            $posts['pagination_js'] = $pagination['javascript'];
1085
        }
Alastair Pharo's avatar
Alastair Pharo committed
1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097
    }

    /**
     * This function creates a new blog post.
     *
     * @param User
     * @param array
     */
    public static function new_post(User $user, array $values) {
        $artefact = new ArtefactTypeBlogPost();
        $artefact->set('title', $values['title']);
        $artefact->set('description', $values['description']);
Alastair Pharo's avatar
Alastair Pharo committed
1098
        $artefact->set('published', $values['published']);
Alastair Pharo's avatar
Alastair Pharo committed
1099
        $artefact->set('owner', $user->get('id'));
1100
        $artefact->set('parent', $values['parent']);
Alastair Pharo's avatar
Alastair Pharo committed
1101
        $artefact->commit();
1102
        return true;
1103
    }
Alastair Pharo's avatar
Alastair Pharo committed
1104

1105
    /**
Alastair Pharo's avatar
Alastair Pharo committed
1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119
     * This function updates an existing blog post.
     *
     * @param User
     * @param array
     */
    public static function edit_post(User $user, array $values) {
        $artefact = new ArtefactTypeBlogPost($values['id']);
        if ($user->get('id') != $artefact->get('owner')) {
            return false;
        }

        $artefact->set('title', $values['title']);
        $artefact->set('description', $values['description']);
        $artefact->set('published', $values['published']);
1120
        $artefact->set('tags', $values['tags']);
1121 1122 1123 1124 1125
        if (get_config('licensemetadata')) {
            $artefact->set('license', $values['license']);
            $artefact->set('licensor', $values['licensor']);
            $artefact->set('licensorurl', $values['licensorurl']);
        }
Alastair Pharo's avatar
Alastair Pharo committed
1126 1127 1128 1129
        $artefact->commit();
        return true;
    }

1130 1131 1132 1133 1134 1135
    public static function changepoststatus_form($id, $published = null) {
        //Get current post status from database
        if ($published === null) {
            $post = new ArtefactTypeBlogPost($id);
            $published = $post->published;
        }
1136

1137
        if ($published) {
1138
            $strchangepoststatus = '<span class="icon icon-times icon-lg left text-danger" role="presentation" aria-hidden="true"></span> ' .get_string('unpublish', 'artefact.blog');
1139 1140
        }
        else {
1141
            $strchangepoststatus = '<span class="icon icon-check icon-lg left text-success" role="presentation" aria-hidden="true"></span> ' . get_string('publish', 'artefact.blog');
1142
        }
1143
        return pieform(array(
1144 1145 1146
            'name' => 'changepoststatus_' . $id,
            'jssuccesscallback' => 'changepoststatus_success',
            'successcallback' => 'changepoststatus_submit',
1147
            'jsform' => true,
1148
            'renderer' => 'div',
1149
            'elements' => array(
1150
                'changepoststatus' => array(
1151 1152 1153
                    'type' => 'hidden',
                    'value' => $id,
                ),
1154 1155 1156 1157
                'currentpoststatus' => array(
                    'type' => 'hidden',
                    'value' => $published,
                ),'submit' => array(
1158 1159
                    'type' => 'button',
                    'usebuttontag' => true,
1160
                    'class' => 'btn-default btn-sm publish',
1161
                    'value' => $strchangepoststatus,
1162 1163 1164 1165 1166
                ),
            ),
        ));
    }

1167
    public static function delete_form($id, $title = '') {
1168
        $title = hsc($title);
1169
        global $THEME;
1170 1171 1172 1173 1174
        return pieform(array(
            'name' => 'delete_' . $id,
            'successcallback' => 'delete_submit',
            'jsform' => true,
            'jssuccesscallback' => 'delete_success',
1175 1176
            'renderer' => 'div',
            'class' => 'form-as-button pull-left',
1177 1178 1179 1180 1181 1182 1183
            'elements' => array(
                'delete' => array(
                    'type' => 'hidden',
                    'value' => $id,
                    'help' => true,
                ),
                'submit' => array(
1184 1185
                    'type' => 'button',
                    'usebuttontag' => true,
1186
                    'class' => 'btn-default btn-sm',
1187
                    'elementtitle' => get_string('delete'),
1188
                    'confirm' => get_string('deleteblogpost?', 'artefact.blog'),