lib.php 51.7 KB
Newer Older
1
<?php
Nigel McNie's avatar
Nigel McNie committed
2
3
4
5
/**
 *
 * @package    mahara
 * @subpackage interaction-forum
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.
Nigel McNie's avatar
Nigel McNie committed
9
10
 *
 */
11

12
13
require_once('activity.php');

14
15
16
17
18
19
// Contstants for objectionable content reporting events.
define('REPORT_OBJECTIONABLE', 1);
define('MAKE_NOT_OBJECTIONABLE', 2);
define('DELETE_OBJECTIONABLE_POST', 3);
define('DELETE_OBJECTIONABLE_TOPIC', 4);

20
21
class PluginInteractionForum extends PluginInteraction {

22
23
    public static function instance_config_form($group, $instance=null) {
        if (isset($instance)) {
24
25
26
27
            $instanceconfig = get_records_assoc('interaction_forum_instance_config', 'forum', $instance->get('id'), '', 'field,value');
            $autosubscribe = isset($instanceconfig['autosubscribe']) ? $instanceconfig['autosubscribe']->value : false;
            $weight = isset($instanceconfig['weight']) ? $instanceconfig['weight']->value : null;
            $createtopicusers = isset($instanceconfig['createtopicusers']) ? $instanceconfig['createtopicusers']->value : null;
28
            $closetopics = !empty($instanceconfig['closetopics']);
29
30
            $indentmode = isset($instanceconfig['indentmode']) ? $instanceconfig['indentmode']->value : null;
            $maxindent = isset($instanceconfig['maxindent']) ? $instanceconfig['maxindent']->value : null;
31

32
            $moderators = get_forum_moderators($instance->get('id'));
33
34
        }

35
36
37
38
39
40
41
42
43
44
45
46
        if ($instance === null) {
            $exclude = '';
        }
        else {
            $exclude = 'AND i.id != ' . db_quote($instance->get('id'));
        }

        $existing = get_records_sql_array('
            SELECT i.id, i.title, c.value AS weight
            FROM {interaction_instance} i
            INNER JOIN {interaction_forum_instance_config} c ON (i.id = c.forum AND c.field = \'weight\')
            WHERE i.group = ?
Nigel McNie's avatar
Nigel McNie committed
47
            AND i.deleted != 1
48
            ' . $exclude . '
49
            ORDER BY CHAR_LENGTH(c.value), c.value',
50
51
52
53
54
55
56
57
58
59
            array($group->id));
        if ($existing) {
            foreach ($existing as &$item) {
                $item = (array)$item;
            }
        }
        else {
            $existing = array();
        }

60
        return array(
61
62
63
64
65
66
67
68
            'indentmode' => array(
                'type'         => 'select',
                'title'        => get_string('indentmode', 'interaction.forum'),
                'options'      => array('full_indent'  => get_string('indentfullindent', 'interaction.forum'),
                                        'max_indent'   => get_string('indentmaxindent', 'interaction.forum'),
                                        'no_indent'    => get_string('indentflatindent', 'interaction.forum') ),
                'description'  => get_string('indentmodedescription', 'interaction.forum'),
                'defaultvalue' => isset($indentmode) ? $indentmode : 'full_indent',
69
                'help' => true,
70
71
72
73
74
75
76
77
78
                'rules' => array(
                    'required' => true,
                ),
            ),
            'maxindent' => array(
                'type'         => 'text',
                'title'        => get_string('maxindent', 'interaction.forum'),
                'size'         => 2,
                'defaultvalue' => isset($maxindent) ? $maxindent : 10,
79
                'class'        => (isset($indentmode) && $indentmode == 'max_indent') ? '' : 'hidden',
80
81
82
83
84
85
                'rules' => array(
                    'integer' => true,
                    'minvalue' => 1,
                    'maxvalue' => 100,
                ),
            ),
86
87
            'fieldset' => array(
                'type' => 'fieldset',
88
                'class' => 'last',
89
                'collapsible' => true,
90
                'collapsed' => true,
91
                'legend' => get_string('forumsettings', 'interaction.forum'),
92
                'elements' => array(
93
                    'autosubscribe' => array(
94
                        'type'         => 'switchbox',
95
96
                        'title'        => get_string('autosubscribeusers', 'interaction.forum'),
                        'description'  => get_string('autosubscribeusersdescription', 'interaction.forum'),
97
                        'defaultvalue' => isset($autosubscribe) ? $autosubscribe : true,
98
99
                        'help'         => true,
                    ),
100
                    'weight' => array(
101
                        'type' => 'weight',
102
                        'title' => get_string('Order', 'interaction.forum'),
103
104
                        'description' => get_string('orderdescription', 'interaction.forum'),
                        'defaultvalue' => isset($weight) ? $weight : count($existing),
105
106
                        'rules' => array(
                            'required' => true,
107
108
109
                        ),
                        'existing' => $existing,
                        'ignore'   => (count($existing) == 0)
110
111
112
                    ),
                    'moderator' => array(
                        'type' => 'userlist',
113
                        'title' => get_string('Moderators', 'interaction.forum'),
114
115
116
                        'description' => get_string('moderatorsdescription', 'interaction.forum'),
                        'defaultvalue' => isset($moderators) ? $moderators : null,
                        'group' => $group->id,
117
                        'includeadmins' => false,
118
119
                        'lefttitle' => get_string('potentialmoderators', 'interaction.forum'),
                        'righttitle' => get_string('currentmoderators', 'interaction.forum')
120
121
122
123
124
125
126
127
128
129
130
131
                    ),
                    'createtopicusers' => array(
                        'type'         => 'select',
                        'title'        => get_string('whocancreatetopics', 'interaction.forum'),
                        'options'      => array('members'    => get_string('allgroupmembers', 'group'),
                                                'moderators' => get_string('moderatorsandgroupadminsonly', 'interaction.forum')),
                        'description'  => get_string('createtopicusersdescription', 'interaction.forum'),
                        'defaultvalue' => (isset($createtopicusers) && $createtopicusers == 'moderators') ? 'moderators' : 'members',
                        'rules' => array(
                            'required' => true,
                        ),
                    ),
132
                    'closetopics' => array(
133
                        'type'         => 'switchbox',
134
                        'title'        => get_string('closetopics', 'interaction.forum'),
135
                        'description'  => get_string('closetopicsdescription1', 'interaction.forum'),
136
137
                        'defaultvalue' => !empty($closetopics),
                    ),
138
139
140
141
142
                )
            )
        );
    }

143
144
    public static function instance_config_js() {
        return <<<EOF
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
jQuery(function($) {
    function update_maxindent() {
        var s = $('#edit_interaction_indentmode');
        var m = $('#edit_interaction_maxindent_container');
        var t = $('#edit_interaction_maxindent');
        if (!m) {
            return;
        }
        if (s.options[s.selectedIndex].val() == 'max_indent') {
            m.removeClass('hidden');
            t.removeClass('hidden');
        }
        else {
          m.addClass('hidden');
          t.addClass('hidden');
        }
161
    }
162
163

    $('#edit_interaction_indentmode').on('change', update_maxindent);
164
165
166
167
});
EOF;
    }

168
    public static function instance_config_save($instance, $values){
169
        db_begin();
170
171
172
173
174
175
176
177
178
179
180
181
182

        // Autosubscribe
        delete_records_sql(
            "DELETE FROM {interaction_forum_instance_config}
            WHERE field = 'autosubscribe' AND forum = ?",
            array($instance->get('id'))
        );
        insert_record('interaction_forum_instance_config', (object)array(
            'forum' => $instance->get('id'),
            'field' => 'autosubscribe',
            'value' => (bool)$values['autosubscribe'],
        ));

183
        if ($values['justcreated'] && $values['autosubscribe']) {
184
185
186
187
188
189
190
            // Subscribe all existing users in the group to the forums
            if ($userids = get_column('group_member', 'member', 'group', $instance->get('group'))) {
                foreach ($userids as $userid) {
                    insert_record(
                        'interaction_forum_subscription_forum',
                        (object)array(
                            'forum' => $instance->get('id'),
191
                            'user'  => $userid,
192
                            'key'   => PluginInteractionForum::generate_unsubscribe_key(),
193
194
195
196
197
198
199
                        )
                    );
                }
            }
        }

        // Moderators
200
201
202
203
        delete_records(
            'interaction_forum_moderator',
            'forum', $instance->get('id')
        );
204
205
206
207
208
209
210
211
212
213
        if (isset($values['moderator']) && is_array($values['moderator'])) {
            foreach ($values['moderator'] as $user) {
                insert_record(
                    'interaction_forum_moderator',
                    (object)array(
                        'user' => $user,
                        'forum' => $instance->get('id')
                    )
                );
            }
214
215
        }

216
        // Re-order the forums according to their new ordering
217
218
219
220
221
222
        delete_records_sql(
            'DELETE FROM {interaction_forum_instance_config}
            WHERE field = \'weight\' AND forum IN (
                SELECT id FROM {interaction_instance} WHERE "group" = ?
            )',
            array($instance->get('group'))
223
        );
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252

        if (isset($values['weight'])) {
            foreach ($values['weight'] as $weight => $id) {
                if ($id === null) {
                    // This is where the current forum is to be placed
                    $id = $instance->get('id');
                }

                insert_record(
                    'interaction_forum_instance_config',
                    (object)array(
                        'forum' => $id,
                        'field' => 'weight',
                        'value' => $weight,
                    )
                );
            }
        }
        else {
            // Element was ignored - because this is the first forum in a group
            insert_record(
                'interaction_forum_instance_config',
                (object)array(
                    'forum' => $instance->get('id'),
                    'field' => 'weight',
                    'value' => 0,
                )
            );
        }
253
254
255
256
257
258
259
260
261
262
263
264
265

        // Create topic users
        delete_records_sql(
            "DELETE FROM {interaction_forum_instance_config}
            WHERE field = 'createtopicusers' AND forum = ?",
            array($instance->get('id'))
        );
        insert_record('interaction_forum_instance_config', (object)array(
            'forum' => $instance->get('id'),
            'field' => 'createtopicusers',
            'value' => $values['createtopicusers'] == 'moderators' ? 'moderators' : 'members',
        ));

266
267
268
269
270
271
272
273
274
275
276
277
278
279
        // Close topics
        delete_records_sql(
            "DELETE FROM {interaction_forum_instance_config}
            WHERE field = 'closetopics' AND forum = ?",
            array($instance->get('id'))
        );
        if (!empty($values['closetopics'])) {
            insert_record('interaction_forum_instance_config', (object)array(
                'forum' => $instance->get('id'),
                'field' => 'closetopics',
                'value' => 1,
            ));
        }

280
281
282
283
284
285
        //Indent mode
        delete_records_sql(
            "DELETE FROM {interaction_forum_instance_config}
            WHERE field = 'indentmode' AND forum = ?",
            array($instance->get('id'))
        );
286
287
288
        if (!isset($values['indentmode'])) {
            $values['indentmode'] = 'full_indent';
        }
289
290
291
292
293
294
295
296
297
298
299
300
        insert_record('interaction_forum_instance_config', (object)array(
            'forum' => $instance->get('id'),
            'field' => 'indentmode',
            'value' => $values['indentmode'],
        ));

        //Max indent
        delete_records_sql(
            "DELETE FROM {interaction_forum_instance_config}
            WHERE field = 'maxindent' AND forum = ?",
            array($instance->get('id'))
        );
301
302
303
        if (!isset($values['maxindent'])) {
            $values['maxindent'] = 10;
        }
304
305
306
307
308
309
        insert_record('interaction_forum_instance_config', (object)array(
            'forum' => $instance->get('id'),
            'field' => 'maxindent',
            'value' => $values['maxindent'],
        ));

310

Nigel McNie's avatar
Nigel McNie committed
311
        db_commit();
312
    }
313

314
315
316
317
318
319
320
    public static function postinst($prevversion) {
        // On a new installation, set post delay to 30 minutes
        if ($prevversion == 0) {
            set_config_plugin('interaction', 'forum', 'postdelay', 30);
        }
    }

321
322
323
324
325
    public static function get_activity_types() {
        return array(
            (object)array(
                'name' => 'newpost',
                'admin' => 0,
326
327
328
                'delay' => 1,
                'allownonemethod' => 1,
                'defaultmethod' => 'email',
329
330
331
332
333
334
335
336
            ),
            (object)array(
                'name' => 'reportpost',
                'admin' => 1,
                'delay' => 0,
                'allownonemethod' => 1,
                'defaultmethod' => 'email',
            ),
337
        );
338
    }
339
340
341
342
343

    public static function get_cron() {
        return array(
            (object)array(
                'callfunction' => 'interaction_forum_new_post',
344
                'minute'       => '3-59/30',
345
            ),
346
347
348
349
350
            (object)array(
                'callfunction' => 'clean_forum_notifications',
                'minute'       => '30',
                'hour'         => '22',
            ),
351
352
353
        );
    }

354
355
356
357
358
    public static function clean_forum_notifications() {
        safe_require('notification', 'internal');
        PluginNotificationInternal::clean_notifications(array('newpost'));
    }

359
360
361
362
363
364
365
366
367
368
369
370
    /**
     * Subscribes the forum plugin to events
     *
     * @return array
     */
    public static function get_event_subscriptions() {
        return array(
            (object)array(
                'plugin'       => 'forum',
                'event'        => 'userjoinsgroup',
                'callfunction' => 'user_joined_group',
            ),
371
372
373
374
375
            (object)array(
                'plugin'       => 'forum',
                'event'        => 'creategroup',
                'callfunction' => 'create_default_forum',
            ),
376
377
378
        );
    }

Richard Mansfield's avatar
Richard Mansfield committed
379
380
    public static function menu_items() {
        return array(
381
            'groups/topics' => array(
Richard Mansfield's avatar
Richard Mansfield committed
382
383
384
                'path' => 'groups/topics',
                'url' => 'group/topics.php',
                'title' => get_string('Topics', 'interaction.forum'),
385
                'weight' => 70,
Richard Mansfield's avatar
Richard Mansfield committed
386
387
388
389
            ),
        );
    }

390
    public static function group_menu_items($group) {
391
        global $USER;
392
        $role = group_user_access($group->id);
393
394
395
396
397
398
399
400
401
402
403
404
        $hasobjectionable = false;
        if (!$role && $USER->get('admin')) {
            // No role, but site admin - see if there is objectionable content,
            // so that menu item should be displayed.
            foreach (self::get_instance_ids($group->id) as $instanceid) {
                $instance = new InteractionForumInstance($instanceid);
                if ($instance->has_objectionable()) {
                    $hasobjectionable = true;
                    break;
                }
            }
        }
405
        $menu = array();
406
        if ($group->public || $role || ($hasobjectionable && $USER->get('admin'))) {
407
408
409
410
411
412
413
414
415
416
            $menu['forums'] = array(// @todo: make forums an artefact plugin
                'path' => 'groups/forums',
                'url' => 'interaction/forum/index.php?group=' . $group->id,
                'title' => get_string('nameplural', 'interaction.forum'),
                'weight' => 40,
            );
        }
        return $menu;
    }

417
    /**
Aaron Wells's avatar
Aaron Wells committed
418
     * When a user joins a group, subscribe them automatically to all forums
419
420
421
422
423
424
425
426
427
428
     * that should be subscribable
     *
     * @param array $eventdata
     */
    public static function user_joined_group($event, $gm) {
        if ($forumids = get_column_sql("
            SELECT ii.id
            FROM {group} g
            LEFT JOIN {interaction_instance} ii ON g.id = ii.group
            LEFT JOIN {interaction_forum_instance_config} ific ON ific.forum = ii.id
429
            WHERE \"group\" = ? AND ific.field = 'autosubscribe' and ific.value = '1'",
430
431
432
433
434
435
436
            array($gm['group']))) {
            db_begin();
            foreach ($forumids as $forumid) {
                insert_record(
                    'interaction_forum_subscription_forum',
                    (object)array(
                        'forum' => $forumid,
437
                        'user'  => $gm['member'],
438
                        'key'   => PluginInteractionForum::generate_unsubscribe_key(),
439
440
441
442
443
444
445
                    )
                );
            }
            db_commit();
        }
    }

446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
    /**
     * When a group is created, create one forum automatically.
     *
     * @param array $eventdata
     */
    public static function create_default_forum($event, $eventdata) {
        global $USER;
        $creator = 0;
        if (isset($eventdata['members'][$USER->get('id')])) {
            $creator = $USER->get('id');
        }
        else {
            foreach($eventdata['members'] as $userid => $role) {
                if ($role == 'admin') {
                    $creator = $userid;
                    break;
                }
            }
        }
        db_begin();
        $forum = new InteractionForumInstance(0, (object) array(
            'group'       => $eventdata['id'],
            'creator'     => $creator,
            'title'       => get_string('defaultforumtitle', 'interaction.forum'),
            'description' => get_string('defaultforumdescription', 'interaction.forum', $eventdata['name']),
        ));
        $forum->commit();
        self::instance_config_save($forum, array(
            'createtopicusers' => 'members',
            'autosubscribe'    => 1,
            'justcreated'      => 1,
        ));
        db_commit();
    }

481
    /**
Aaron Wells's avatar
Aaron Wells committed
482
     * Optional method. Takes a list of forums and sorts them according to
483
484
485
486
487
488
489
490
491
492
493
494
     * their weights for the sideblock
     *
     * @param array $forums An array of hashes of forum data
     * @return array        The array, sorted appropriately
     */
    public static function sideblock_sort($forums) {
        if (!$forums) {
            return $forums;
        }

        $weights = get_records_assoc('interaction_forum_instance_config', 'field', 'weight', 'forum', 'forum, value');
        foreach ($forums as &$forum) {
Aaron Wells's avatar
Aaron Wells committed
495
496
497
498
            // Note: forums expect every forum to have a 'weight' record in the
            // forum instance config table, so we don't need to check that
            // there is a weight for the forum here - there should be,
            // otherwise someone has futz'd with the database or there's a bug
499
500
501
502
503
504
505
            // elsewhere that allowed this to happen
            $forum->weight = $weights[$forum->id]->value;
        }
        usort($forums, create_function('$a, $b', 'return $a->weight > $b->weight;'));
        return $forums;
    }

506
507
508
509

    /**
     * Process new forum posts.
     *
510
     * @param array $postnow An array of post ids to be sent immediately.  If null, send all posts older than postdelay.
511
512
513
514
     */
    public static function interaction_forum_new_post($postnow=null) {
        if (is_array($postnow) && !empty($postnow)) {
            $values = array();
515
            $postswhere = 'id IN (' . join(',', array_map('intval', $postnow)) . ')';
516
            $delay = false;
517
518
519
        }
        else {
            $currenttime = time();
520
            $minpostdelay = $currenttime - get_config_plugin('interaction', 'forum', 'postdelay') * 60;
521
522
            $values = array(db_format_timestamp($minpostdelay));
            $postswhere = 'ctime < ?';
523
            $delay = null;
524
        }
525
        $posts = get_column_sql('SELECT id FROM {interaction_forum_post} WHERE sent = 0 AND deleted = 0 AND ' . $postswhere, $values);
526
        if ($posts) {
527
528
            set_field_select('interaction_forum_post', 'sent', 1, 'deleted = 0 AND sent = 0 AND ' . $postswhere, $values);
            foreach ($posts as $postid) {
529
                activity_occurred('newpost', array('postid' => $postid), 'interaction', 'forum', $delay);
530
531
532
            }
        }
    }
533
534
535
536

    public static function can_be_disabled() {
        return false; //TODO until it either becomes an artefact plugin or stops being hardcoded everywhere
    }
537
538
539
540

    /**
     * Generates a random key to use for unsubscription requests.
     *
Aaron Wells's avatar
Aaron Wells committed
541
     * See the interaction_forum_subscription_* tables and related operations
542
543
544
545
546
547
548
     * on them for more information.
     *
     * @return string A random key
     */
    public static function generate_unsubscribe_key() {
        return dechex(mt_rand());
    }
549
550
551
552
553
554
555


    public static function has_config() {
        return true;
    }

    public static function get_config_options() {
556
        $postdelay = (int) get_config_plugin('interaction', 'forum', 'postdelay');
557
558
559
560
561
562
563

        return array(
            'elements' => array(
                'postdelay' => array(
                    'title'        => get_string('postdelay', 'interaction.forum'),
                    'description'  => get_string('postdelaydescription', 'interaction.forum'),
                    'type'         => 'text',
564
                    'class'      => '',
565
                    'rules'        => array('integer' => true, 'minvalue' => 0, 'maxvalue' => 10000000),
566
                    'defaultvalue' => $postdelay,
567
568
569
570
571
                ),
            ),
        );
    }

Son Nguyen's avatar
Son Nguyen committed
572
    public static function save_config_options(Pieform $form, $values) {
573
574
        set_config_plugin('interaction', 'forum', 'postdelay', $values['postdelay']);
    }
575

576
    public static function get_active_topics($limit, $offset, $category, $forumids = array()) {
577
578
        global $USER;

579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
        if (is_postgres()) {
            $lastposts = '
                    SELECT DISTINCT ON (topic) topic, id, poster, subject, body, ctime
                    FROM {interaction_forum_post} p
                    WHERE p.deleted = 0
                    ORDER BY topic, ctime DESC';
        }
        else if (is_mysql()) {
            $lastposts = '
                    SELECT topic, id, poster, subject, body, ctime
                    FROM (
                        SELECT topic, id, poster, subject, body, ctime
                        FROM {interaction_forum_post}
                        WHERE deleted = 0
                        ORDER BY ctime DESC
                    ) temp1
                    GROUP BY topic';
        }

598
        $values = array();
599
600
601
602
        $from = '
            FROM
                {interaction_forum_topic} t
                JOIN {interaction_instance} f ON t.forum = f.id
603
604
605
606
607
                JOIN {group} g ON f.group = g.id';

        // user is not anonymous
        if ($USER->get('id') > 0) {
            $from .= '
608
                JOIN {group_member} gm ON (gm.group = g.id AND gm.member = ?)
609
610
611
612
613
614
            ';

            $values[] = $USER->get('id');
        }

        $from .= '
615
                JOIN {interaction_forum_post} first ON (first.topic = t.id AND first.parent IS NULL)
616
                JOIN (' . $lastposts . '
617
618
619
620
621
                ) last ON last.topic = t.id';

        $where = '
            WHERE g.deleted = 0 AND f.deleted = 0 AND t.deleted = 0';

622
623
624
625
626
        if (!empty($category)) {
            $where .= ' AND g.category = ?';
            $values[] = (int) $category;
        }

627
        if (!empty($forumids)) {
628
629
            $where .= ' AND f.id IN (' . join(',', array_fill(0, count($forumids), '?')) . ')';
            $values = array_merge($values, $forumids);
630
631
        }

632
        $result = array(
633
            'count'  => count_records_sql('SELECT COUNT(*) ' . $from . $where, $values),
634
635
636
637
638
639
640
641
642
643
644
            'limit'  => $limit,
            'offset' => $offset,
            'data'   => array(),
        );

        if (!$result['count']) {
            return $result;
        }

        $select = '
            SELECT
645
                t.id, t.forum AS forumid, f.title AS forumname, g.id AS groupid, g.name AS groupname, g.urlid,
646
                first.subject AS topicname, first.poster AS firstpostby,
647
                last.id AS postid, last.poster, last.subject, last.body, last.ctime, edits.ctime as mtime,
648
                COUNT(posts.id) AS postcount';
649
650

        $from .= '
651
652
                LEFT JOIN {interaction_forum_post} posts ON posts.topic = t.id
                LEFT JOIN {interaction_forum_edit} edits ON edits.post = last.id';
653
654
655

        $sort = '
            GROUP BY
656
                t.id, t.forum, f.title, g.id, g.name, g.urlid,
657
                first.subject, first.poster,
658
                last.id, last.poster, last.subject, last.body, last.ctime, edits.ctime
659
660
            ORDER BY last.ctime DESC';

661
        $result['data'] = get_records_sql_array($select . $from . $where . $sort, $values, $offset, $limit);
662

663
664
665
666
        foreach($result['data'] as &$r) {
            $r->groupurl = group_homepage_url((object) array('id' => $r->groupid, 'urlid' => $r->urlid));
        }

667
668
        return $result;
    }
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753

    // Rewrite download links in the post body to add a post id parameter.
    // Used in download.php to determine permission to view the file.
    static $replacement_postid;

    public static function replace_download_link($matches) {
        parse_str(html_entity_decode($matches[1]), $params);
        if (empty($params['file'])) {
            return $matches[0];
        }
        $url = get_config('wwwroot') . 'artefact/file/download.php?file=' . (int) $params['file'];
        unset($params['post']);
        unset($params['file']);
        if (!empty($params)) {
            $url .= '&' . http_build_query($params);
        }
        return $url . '&post=' . (int) self::$replacement_postid;
    }

    public static function prepare_post_body($body, $postid) {
        self::$replacement_postid = $postid;
        return preg_replace_callback(
            '#(?<=[\'"])' . get_config('wwwroot') . 'artefact/file/download\.php\?(file=\d+(?:(?:&amp;|&)(?:[a-z]+=[x0-9]+)+)*)#',
            array('self', 'replace_download_link'),
            $body
        );
    }

    /**
     * Given a post id & the id of an image artefact, check that the logged-in user
     * has permission to see the image in the context of the post.
     */
    public static function can_see_attached_file($file, $postid) {
        global $USER;
        require_once('group.php');

        if (!$file instanceof ArtefactTypeImage) {
            return false;
        }

        $post = get_record_sql('
            SELECT
                p.body, p.poster, g.id AS groupid, g.public
            FROM {interaction_forum_post} p
            INNER JOIN {interaction_forum_topic} t ON (t.id = p.topic AND t.deleted = 0)
            INNER JOIN {interaction_forum_post} fp ON (fp.parent IS NULL AND fp.topic = t.id)
            INNER JOIN {interaction_instance} f ON (t.forum = f.id AND f.deleted = 0)
            INNER JOIN {group} g ON (f.group = g.id AND g.deleted = 0)
            WHERE p.id = ? AND p.deleted = 0',
            array($postid)
        );

        if (!$post) {
            return false;
        }

        if (!$post->public && !group_user_access($post->groupid, $USER->get('id'))) {
            return false;
        }

        // Check that the author of the post is allowed to publish the file
        $poster = new User();
        $poster->find_by_id($post->poster);
        if (!$poster->can_publish_artefact($file)) {
            return false;
        }

        // Load the post as an html fragment & make sure it has the image in it
        $page = new DOMDocument();
        libxml_use_internal_errors(true);
        $success = $page->loadHTML($post->body);
        libxml_use_internal_errors(false);
        if (!$success) {
            return false;
        }
        $xpath = new DOMXPath($page);
        $srcstart = get_config('wwwroot') . 'artefact/file/download.php?file=' . $file->get('id') . '&';
        $query = '//img[starts-with(@src,"' . $srcstart . '")]';
        $elements = $xpath->query($query);
        if ($elements->length < 1) {
            return false;
        }

        return true;
    }
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804

    /**
     * Return number of forums associated to a group
     *
     * @param  $groupid: the group ID number
     * @return the number of forums
     *     OR null if invalid $groupid
     */
    public static function count_group_forums($groupid) {
        if ($groupid && $groupid > 0) {
            return count_records_select('interaction_instance', '"group" = ? AND deleted != 1', array($groupid), 'COUNT(id)');
        }
        return null;
    }

    /**
     * Return number of topics associated to a group
     *
     * @param  $groupid: the group ID number
     * @return the number of topics
     *     OR null if invalid $groupid
     */
    public static function count_group_topics($groupid) {
        if ($groupid && $groupid > 0) {
            return count_records_sql('SELECT COUNT(t.id)
                    FROM {interaction_instance} f
                    JOIN {interaction_forum_topic} t ON t.forum = f.id AND t.deleted != 1
                    WHERE f.group = ?
                        AND f.deleted != 1', array($groupid));
        }
        return null;
    }

    /**
     * Return number of posts associated to a group
     *
     * @param  $groupid: the group ID number
     * @return the number of posts
     *     OR null if invalid $groupid
     */
    public static function count_group_posts($groupid) {
        if ($groupid && $groupid > 0) {
            return count_records_sql('SELECT COUNT(p.id)
                    FROM {interaction_instance} f
                    JOIN {interaction_forum_topic} t ON t.forum = f.id AND t.deleted != 1
                    JOIN {interaction_forum_post} p ON p.topic = t.id AND p.deleted != 1
                    WHERE f.group = ?
                    AND f.deleted != 1', array($groupid));
        }
        return null;
    }
805
806
807
808
809
810
811
812
813
814
815
816
817

    /**
     * Return IDs of plugin instances
     *
     * @param  int $groupid optional group ID number
     * @return array list of the instance IDs
     */
    public static function get_instance_ids($groupid = null) {
        if (isset($groupid) && $groupid > 0) {
            return get_column('interaction_instance', 'id', 'plugin', 'forum', 'group', $groupid, 'deleted', 0);
        }
        return get_column('interaction_instance', 'id', 'plugin', 'forum', 'deleted', 0);
    }
818
819
820
821
822
823
824
825
}

class InteractionForumInstance extends InteractionInstance {

    public static function get_plugin() {
        return 'forum';
    }

826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
    public function delete() {
        if (empty($this->id)) {
            $this->dirty = false;
            return;
        }

        db_begin();
        // Delete embedded images in the forum description
        require_once('embeddedimage.php');
        EmbeddedImage::delete_embedded_images('forum', $this->id);
        // Delete the interaction instance
        parent::delete();
        db_commit();
    }

    public function commit() {
        if (empty($this->dirty)) {
            return;
        }

        db_begin();
        parent::commit();
        // Update embedded images in the forum description
        require_once('embeddedimage.php');
        $newdescription = EmbeddedImage::prepare_embedded_images($this->description, 'forum', $this->id, $this->group);
        set_field('interaction_instance', 'description', $newdescription, 'id', $this->id);
        db_commit();
    }

855
856
    public function interaction_remove_user($userid) {
        delete_records('interaction_forum_moderator', 'forum', $this->id, 'user', $userid);
857
858
859
860
861
        delete_records('interaction_forum_subscription_forum', 'forum', $this->id, 'user', $userid);
        delete_records_select('interaction_forum_subscription_topic',
            'user = ? AND topic IN (SELECT id FROM {interaction_forum_topic} WHERE forum = ?)',
            array($userid, $this->id)
        );
862
863
    }

864
865
866
867
868
869
870
   /**
    * Check if forum instance contains reported content.
    *
    * @returns bool $reported whether forum contains reported content.
    */
   public function has_objectionable() {
       $reported = count_records_sql(
871
           "SELECT count(fp.id) FROM {interaction_forum_topic} ft
872
            JOIN {interaction_forum_post} fp ON (ft.id = fp.topic)
873
874
            JOIN {objectionable} o ON (o.objecttype = 'forum' AND o.objectid = fp.id)
            WHERE fp.deleted = 0 AND o.resolvedby IS NULL AND o.resolvedtime IS NULL AND ft.forum = ?", array($this->id)
875
876
877
       );
       return (bool) $reported;
   }
878
879
}

880
881
882
class ActivityTypeInteractionForumNewPost extends ActivityTypePlugin {

    protected $postid;
883
    protected $temp;
884

885
886
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);
887
        $this->overridemessagecontents = true;
888
889
890
891
892

        $post = get_record_sql('
            SELECT
                p.subject, p.body, p.poster, p.parent, ' . db_format_tsfield('p.ctime', 'ctime') . ',
                t.id AS topicid, fp.subject AS topicsubject, f.title AS forumtitle, g.name AS groupname, f.id AS forumid
893
            FROM {interaction_forum_post} p
894
895
896
897
898
            INNER JOIN {interaction_forum_topic} t ON (t.id = p.topic AND t.deleted = 0)
            INNER JOIN {interaction_forum_post} fp ON (fp.parent IS NULL AND fp.topic = t.id)
            INNER JOIN {interaction_instance} f ON (t.forum = f.id AND f.deleted = 0)
            INNER JOIN {group} g ON (f.group = g.id AND g.deleted = 0)
            WHERE p.id = ? AND p.deleted = 0',
899
900
            array($this->postid)
        );
901
902
903
904
905
906
907

        // The post may have been deleted during the activity delay
        if (!$post) {
            $this->users = array();
            return;
        }

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
940
        // A user may be subscribed via the forum or the specific topic. If they're subscribed to both, we want
        // to focus on the topic subscription because it's more specific.
        $sql = '
            SELECT
                subq2.subscriber,
                (CASE WHEN subq2.topickey IS NOT NULL THEN subq2.topickey ELSE subq2.forumkey END) AS "key",
                (CASE WHEN subq2.topickey IS NOT NULL THEN \'topic\' ELSE \'forum\' END) AS "type"
            FROM (
                SELECT subq1.subscriber, max(topickey) AS topickey, max(forumkey) AS forumkey
                FROM (
                    SELECT "user" AS subscriber, "key" AS topickey, NULL AS forumkey FROM {interaction_forum_subscription_topic} WHERE topic = ?
                    UNION ALL
                    SELECT "user" AS subscriber, NULL AS topickey, "key" AS forumkey FROM {interaction_forum_subscription_forum} WHERE forum = ?
                ) subq1
                GROUP BY subq1.subscriber
            ) subq2
            INNER JOIN {usr} u ON subq2.subscriber = u.id
            WHERE u.deleted = 0
        ';
        $params = array($post->topicid, $post->forumid);
        if ($cron) {
            $sql .= ' AND subq2.subscriber > ? ';
            $params[] = (int) $data->last_processed_userid;
            $limitfrom = 0;
            $limitnum = self::USERCHUNK_SIZE;
        }
        else {
            $limitfrom = '';
            $limitnum = '';
        }
        $sql .= ' ORDER BY subq2.subscriber';

        $subscribers = get_records_sql_assoc($sql, $params, $limitfrom, $limitnum);
941
942

        $this->users = $subscribers ? activity_get_users($this->get_id(), array_keys($subscribers)) : array();
943
        $this->fromuser = $post->poster;
944

945
946
947
        // When emailing forum posts, create Message-Id headers for threaded display by email clients
        $urlinfo = parse_url(get_config('wwwroot'));
        $hostname = $urlinfo['host'];
948
949
950
951
        $cleanforumname = clean_email_headers($post->forumtitle);
        $cleangroupname = clean_email_headers($post->groupname);
        $cleanforumname = str_replace('"', "'", strip_tags($cleanforumname));
        $cleangroupname = str_replace('"', "'", strip_tags($cleangroupname));
952
        $this->customheaders = array(
953
954
            'List-Id: "' . $cleanforumname . '" <forum' . $post->forumid . '@' . $hostname . '>',
            'List-Help: ' . get_config('wwwroot') . 'interaction/forum/view.php?id=' . $post->forumid,
955
            'Message-ID: <forumpost' . $this->postid . '@' . $hostname . '>',
956
957
            'X-Mahara-Group: ' . $cleangroupname,
            'X-Mahara-Forum: ' . $cleanforumname
958
        );
959
960
961
962
        if ($post->parent) {
            $this->customheaders[] = 'In-Reply-To: <forumpost' . $post->parent . '@' . $hostname . '>';
            $this->customheaders[] = 'References: <forumpost' . $post->parent . '@' . $hostname . '>';
        }
963

964
        $post->posttime = strftime(get_string('strftimedaydatetime'), $post->ctime);
965
966
967
        // Some messages are all html and when they're 'cleaned' with
        // strip_tags(str_shorten_html($post->body, 200, true)) for display,
        // they are left empty. Use html2text instead.
968
        $this->message = str_shorten_text(trim(html2text($post->body)), 200, true); // For internal notifications.
969

970
        $post->textbody = trim(html2text($post->body));
971
        $post->htmlbody = clean_html($post->body);
972
        $this->url = 'interaction/forum/topic.php?id=' . $post->topicid . '&post=' . $this->postid;
973

974
        $this->add_urltext(array(
975
            'key'     => 'Topic',
976
977
            'section' => 'interaction.forum'
        ));
978

979
        $this->strings->subject = (object) array(
980
            'key'     => 'newforumpostnotificationsubjectline',
981
            'section' => 'interaction.forum',
982
            'args'    => array($post->subject ? $post->subject : get_string('Re:', 'interaction.forum') . ($post->parent ? get_ancestorpostsubject($post->parent, true) : $post->topicsubject)),
983
        );
984

985
986
987
        foreach ($this->users as &$user) {
            $user->subscribetype = $subscribers[$user->id]->type;
            $user->unsubscribekey = $subscribers[$user->id]->key;
988
        }
989
990
991
992
993
994
995
996
997

        $this->temp = (object) array('post' => $post);
    }

    public function get_emailmessage($user) {
        $post = $this->temp->post;
        $unsubscribeid = $post->{$user->subscribetype . 'id'};
        $unsubscribelink = get_config('wwwroot') . 'interaction/forum/unsubscribe.php?' . $user->subscribetype . '=' . $unsubscribeid . '&key=' . $user->unsubscribekey;
        return get_string_from_language($user->lang, 'forumposttemplate', 'interaction.forum',
998
999
            $post->forumtitle,
            $post->groupname,
1000
            $post->textbody,
1001
            get_config('wwwroot') . $this->url,
1002
1003
1004
            $user->subscribetype,
            $unsubscribelink
        );
1005
1006
    }

1007
1008
1009
1010
1011
    public function get_htmlmessage($user) {
        $post = $this->temp->post;
        $unsubscribeid = $post->{$user->subscribetype . 'id'};
        $unsubscribelink = get_config('wwwroot') . 'interaction/forum/unsubscribe.php?' . $user->subscribetype . '=' . $unsubscribeid . '&key=' . $user->unsubscribekey;
        return get_string_from_language($user->lang, 'forumposthtmltemplate', 'interaction.forum',
1012
1013
            hsc($post->forumtitle),
            hsc($post->groupname),
1014
            $post->htmlbody,
1015
            get_config('wwwroot') . $this->url,
1016
1017
1018
            $unsubscribelink,
            $user->subscribetype
        );
1019
1020
    }

1021
1022
1023
1024
1025
1026
1027
    public function get_plugintype(){
        return 'interaction';
    }

    public function get_pluginname(){
        return 'forum';
    }
1028
1029

    public function get_required_parameters() {
1030
        return array('postid');
1031
    }
1032
1033
}

1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
class ActivityTypeInteractionForumReportPost extends ActivityTypePlugin {

    protected $postid;
    protected $message;
    protected $reporter;
    protected $ctime;
    protected $event;
    protected $temp;

    public function __construct($data, $cron = false) {
        parent::__construct($data, $cron);

        $post = get_record_sql('
            SELECT
                p.subject, p.body, p.poster, p.parent, ' . db_format_tsfield('p.ctime', 'ctime') . ',
                t.id AS topicid, fp.subject AS topicsubject, f.title AS forumtitle, g.id AS groupid, g.name AS groupname, f.id AS forumid
            FROM {interaction_forum_post} p
            INNER JOIN {interaction_forum_topic} t ON (t.id = p.topic AND t.deleted = 0)
            INNER JOIN {interaction_forum_post} fp ON (fp.parent IS NULL AND fp.topic = t.id)
            INNER JOIN {interaction_instance} f ON (t.forum = f.id AND f.deleted = 0)
            INNER JOIN {group} g ON (f.group = g.id AND g.deleted = 0)
            WHERE p.id = ? AND p.deleted = 0',
            array($this->postid)
        );

        // The post may have been deleted during the activity delay
        if (!$post) {
            $this->users = array();
            return;
        }

        // Set notification to site admins.
        $siteadmins = activity_get_users($this->get_id(), null, null, true);
        // Get forum moderators and admins.
        $forumadminsandmoderators = activity_get_users(
            $this->get_id(),
            array_merge(get_forum_moderators($post->forumid),
            group_get_admin_ids($post->groupid)));
        // Populate users to notify list and get rid of duplicates.
        foreach (array_merge($siteadmins, $forumadminsandmoderators) as $user) {
            if (!isset($this->users[$user->id])) {
                $this->users[$user->id] = $user;
            }
        }

        // Record who reported it.
        $this->fromuser = $this->reporter;

        $post->posttime = strftime(get_string('strftimedaydatetime'), $post->ctime);
        $post->textbody = trim(html2text($post->body));
        $post->htmlbody = clean_html($post->body);
1085
        $this->url = 'interaction/forum/topic.php?id=' . $post->topicid . '&post=' . $this->postid . '&objection=1';
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156

        $this->add_urltext(array(
            'key'     => 'Topic',
            'section' => 'interaction.forum'
        ));

        if ($this->event === REPORT_OBJECTIONABLE) {
            $this->overridemessagecontents = true;
            $this->strings->subject = (object) array(
                'key'     => 'objectionablecontentpost',
                'section' => 'interaction.forum',
                'args'    => array($post->topicsubject, display_default_name($this->reporter)),
            );
        }
        else if ($this->event === MAKE_NOT_OBJECTIONABLE) {
            $this->strings = (object) array(
                'subject' => (object) array(
                    'key' => 'postnotobjectionablesubject',
                    'section' => 'interaction.forum',
                    'args' => array($post->topicsubject, display_default_name($this->reporter)),
                ),
                'message' => (object) array(
                    'key' => 'postnotobjectionablebody',
                    'section' => 'interaction.forum',
                    'args' => array(display_default_name($this->reporter), display_default_name($post->poster)),
                ),
            );
        }
        else if ($this->event === DELETE_OBJECTIONABLE_POST) {
            $this->url = '';
            $this->strings = (object) array(
                'subject' => (object) array(
                    'key' => 'objectionablepostdeletedsubject',
                    'section' => 'interaction.forum',
                    'args' => array($post->topicsubject, display_default_name($this->reporter)),
                ),
                'message' => (object) array(
                    'key' => 'objectionablepostdeletedbody',
                    'section' => 'interaction.forum',
                    'args' => array(display_default_name($this->reporter), display_default_name($post->poster), $post->textbody),
                ),
            );
        }
        else if ($this->event === DELETE_OBJECTIONABLE_TOPIC) {
            $this->url = '';
            $this->strings = (object) array(
                'subject' => (object) array(
                    'key' => 'objectionabletopicdeletedsubject',
                    'section' => 'interaction.forum',
                    'args' => array($post->topicsubject, display_default_name($this->reporter)),
                ),
                'message' => (object) array(
                    'key' => 'objectionabletopicdeletedbody',
                    'section' => 'interaction.forum',
                    'args' => array(display_default_name($this->reporter), display_default_name($post->poster), $post->textbody),
                ),
            );

        }
        else {
            throw new SystemException();
        }

        $this->temp = (object) array('post' => $post);
    }

    public function get_emailmessage($user) {
        $post = $this->temp->post;
        $reporterurl = profile_url($this->reporter);
        $ctime = strftime(get_string_from_language($user->lang, 'strftimedaydatetime'), $this->ctime);
        return get_string_from_language(
Aaron Wells's avatar
Aaron Wells committed
1157
            $user->lang, 'objectionablecontentposttext', 'interaction.forum',
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
            $post->topicsubject, display_default_name($this->reporter), $ctime,
            $this->message, $post->posttime, $post->textbody, get_config('wwwroot') . $this->url, $reporterurl
        );
    }

    public function get_htmlmessage($user) {
        $post = $this->temp->post;
        $reportername = hsc(display_default_name($this->reporter));
        $reporterurl = profile_url($this->reporter);
        $ctime = strftime(get_string_from_language($user->lang, 'strftimedaydatetime'), $this->ctime);
        return get_string_from_language(
            $user->lang, 'objectionablecontentposthtml', 'interaction.forum',
            hsc($post->topicsubject), $reportername, $ctime,
            $this->message, $post->posttime, $post->htmlbody, get_config('wwwroot') . $this->url, hsc($post->topicsubject),
            $reporterurl, $reportername
        );
    }

    public function get_plugintype(){
        return 'interaction';
    }

    public function get_pluginname(){
        return 'forum';
    }

    public function get_required_parameters() {
        return array('postid', 'message', 'reporter', 'ctime', 'event');
    }
}

1189
1190
1191
1192
1193
// constants for forum membership types
define('INTERACTION_FORUM_ADMIN', 1);
define('INTERACTION_FORUM_MOD', 2);
define('INTERACTION_FORUM_MEMBER', 4);

1194
/**
1195
 * Can a user access a given forum?
Clare Lenihan's avatar
Clare Lenihan committed
1196
 *
1197
1198
1199
 * @param int $forumid id of forum
 * @param int $userid optional id of user, defaults to logged in user
 *
1200
 * @returns constant access level or false
1201
 */
1202
function user_can_access_forum($forumid, $userid=null) {
1203
1204
1205
1206
1207
    global $USER;
    $forumuser = $USER;
    if (!empty($userid)) {
        $forumuser = new User;
        $forumuser->find_by_id($userid);
1208
1209
    }
    if (!is_int($forumid)) {
1210
1211
1212
1213
1214
        throw new InvalidArgumentException("non integer forum id given to user_can_access_forum: $forumid");
    }

    $membership = 0;

1215
1216
1217
1218
1219
1220
    // Allow site admins accessing the forum directly if it has objectionable content.
    $instance = new InteractionForumInstance($forumid);
    if ($instance->has_objectionable() && $forumuser->get('admin')) {
        return $membership | INTERACTION_FORUM_ADMIN | INTERACTION_FORUM_MOD;
    }

1221
    $groupid = get_field('interaction_instance', '"group"', 'id', $forumid);
1222
    $groupmembership = group_user_access((int)$groupid, $forumuser->get('id'));
1223
1224
1225
1226
1227

    if (!$groupmembership) {
        return $membership;
    }
    $membership = $membership | INTERACTION_FORUM_MEMBER;
1228
    if ($groupmembership == 'admin') {
1229
1230
        $membership = $membership | INTERACTION_FORUM_ADMIN | INTERACTION_FORUM_MOD;
    }
1231
    if (record_exists('interaction_forum_moderator', 'forum', $forumid, 'user', $forumuser->get('id'))) {
1232
        $membership = $membership | INTERACTION_FORUM_MOD;
1233
    }
1234
    return $membership;
1235
1236
}

1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
/**
 * Get list of moderators for a given forum.
 *
 * @param int $forumid id of forum
 *
 * @returns array $moderators list of forum moderators.
 */
function get_forum_moderators($forumid) {
    $moderators = get_column_sql(
        'SELECT fm.user FROM {interaction_forum_moderator} fm
         JOIN {usr} u ON (fm.user = u.id AND u.deleted = 0)
         WHERE fm.forum = ?', array($forumid)
    );
    return (array) $moderators;
}

1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
/**
 * Is a user allowed to edit a post
 *
 * @param boolean $moderator
 * @param int $poster the the id of the user who created the post
 * @param int $posttime the time the post was made
 * @param int $userid optional id of user, defaults to logged in user
 *
 * @returns boolean
 */
1263
function user_can_edit_post($poster, $posttime, $userid=null, $verifydelay=true) {
1264
    if (empty($userid)) {
1265
1266
1267
        global $USER;
        $userid = $USER->get('id');
    }
1268
1269
1270
1271
1272
    $permitted = true;
    if ($verifydelay) {
        $permitted = $posttime > (time() - get_config_plugin('interaction', 'forum', 'postdelay') * 60);
    }
    return $poster == $userid && $permitted;
1273
1274
}

1275
1276
1277
1278
1279
1280
1281
1282
/**
 * Generates a relative date containing yesterday/today when appropriate
 *
 * @param string $relative the format (for strftime) for a relative date (with %v where yesterday/today should be)
 * @param string $absolute the format (for strftime) for an absolute date
 * @param int $time1 the time to display
 * @param int $time2 optional the time $time1 is relative to, defaults to current time
 */
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
function relative_date($relative, $absolute, $time1, $time2=null) {
    if ($time2==null) {
        $time2 = time();
    }

    $date = getdate($time1);

    $yesterday = getdate(strtotime('-1 day', $time2));
    $tomorrow = getdate(strtotime('+1 day', $time2));
    $today = getdate($time2);

    if ($date['year'] == $yesterday['year'] && $date['yday'] == $yesterday['yday']) {
        return str_replace('%v', get_string('yesterday', 'interaction.forum'), strftime($relative, $time1));
    }
    else if ($date['year'] == $today['year'] && $date['yday'] == $today['yday']) {
        return str_replace('%v', get_string('today', 'interaction.forum'), strftime($relative, $time1));
    }
1300
    return strftime(get_string('strftimedatetime'), $time1);
1301
1302
1303

}

1304
1305
1306
1307
1308
1309
function subscribe_forum_validate(Pieform $form, $values) {
    if (!is_logged_in()) {
        throw new AccessDeniedException();
    }
}

1310
1311
function subscribe_forum_submit(Pieform $form, $values) {
    global $USER, $SESSION;
1312
1313
    if ($values['type'] == 'subscribe') {
        db_begin();
1314
1315
1316
1317
        insert_record(
            'interaction_forum_subscription_forum',
            (object)array(
                'forum' => $values['forum'],
1318
                'user'  => $USER->get('id'),
1319
                'key'   => PluginInteractionForum::generate_unsubscribe_key(),
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
            )
        );
        delete_records_sql(
            'DELETE FROM {interaction_forum_subscription_topic}
            WHERE topic IN (
                SELECT id
                FROM {interaction_forum_topic}
                WHERE forum = ?
                AND "user" = ?
            )',
            array($values['forum'], $USER->get('id'))
        );
1332
        db_commit();
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
        $SESSION->add_ok_msg(get_string('forumsuccessfulsubscribe', 'interaction.forum'));
    }
    else {
        delete_records(
            'interaction_forum_subscription_forum',
            'forum', $values['forum'],
            'user', $USER->get('id')
        );
        $SESSION->add_ok_msg(get_string('forumsuccessfulunsubscribe', 'interaction.forum'));
    }
1343
1344
1345
1346
1347
1348
    if ($values['redirect'] == 'index') {
        redirect('/interaction/forum/index.php?group=' . $values['group']);
    }
    else {
        redirect('/interaction/forum/view.php?id=' . $values['forum'] . '&offset=' . $values['offset']);
    }
1349
}
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380

/*
 * Return the subject for the topic
 *
 * @param int $postid the ID of the post
 *
 * @return string the subject
 */

function get_ancestorpostsubject($postid, $isparent = false) {
    if ($isparent) {
        $record = get_record_sql(
           'SELECT p.subject
            FROM {interaction_forum_post} p
            WHERE p.id = ?', array($postid));
        if ($record && !empty($record->subject)) {
            return $record->subject;
        }
    }
    while ($ppost = get_record_sql(
           'SELECT p1.id, p1.subject
            FROM {interaction_forum_post} p1
            INNER JOIN {interaction_forum_post} p2 ON (p1.id = p2.parent)
            WHERE p2.id = ?', array($postid))) {
        if (!empty ($ppost->subject)) {
            return $ppost->subject;
        }
        $postid = $ppost->id;
    }
    return null;
}