lib.php 88.4 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
<?php
/**
 *
 * @package    mahara
 * @subpackage artefact-annotation
 * @author     Catalyst IT Ltd
 * @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.
 *
 */
/**
 * Developement Notes:
 * We are creating this as an artefact to prepare for future changes:
 * 1. It can 'stand-alone' without a link to a view or an artefact.
 * 2. It can be linked to a particular artefact that is already on a view.
 * 3. It can be linked to an artefact that is not on a view (i.e. a file, a plan, etc.).
 *
 * Currently, an annotation can:
 * 1. Appear on a view multiple times.
 * 2. It is not linked to any particular artefact on the view.
 *    In the future, we will select an artefact on that view to link it to.
 * 3. It will be linked to the view it appears on (i.e. artefact.id = view_artefact.artefact)
 * 4. It does not have any attached files.
 * 5. It does not have any ratings.
 *
 * The database tables:
 * artefact_annotation - links an annotation to an artefact and/or view.
 * artefact_annotation_feedback - holds extra information about the annotationfeedback.
 * artefact_annotation_deletedby - holds static data
 */

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

require_once('activity.php');
require_once('license.php');

class PluginArtefactAnnotation extends PluginArtefact {

39
40
41
42
    public static function is_active() {
        return get_field('artefact_installed', 'active', 'name', 'annotation');
    }

43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
    public static function get_artefact_types() {
        return array(
            'annotation',
            'annotationfeedback',
        );
    }

    public static function get_block_types() {
        return array();
    }

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

    public static function menu_items() {
        return array();
    }

    public static function get_event_subscriptions() {
        return array();
    }

    public static function get_activity_types() {
        // These events are handled by this artefact.
        return array(
            (object)array(
                'name' => 'annotationfeedback',
                'admin' => 0,
                'delay' => 0,
                'allownonemethod' => 1,
                'defaultmethod' => 'email',
            )
        );
    }

    public static function can_be_disabled() {
        return false;
    }

    /**
     * Called post install and after every upgrade to the artefact.
     * @param string $prevversion the previously installed version of this artefact.
     */
    public static function postinst($prevversion) {
        if ($prevversion == 0) {
            // Since this is the first time, we need to
            // create the default settings and the static
            // table data for aretfact_annotation_deletedby.
            set_config_plugin('artefact', 'annotation', 'commenteditabletime', 10);
            foreach(ArtefactTypeAnnotationfeedback::deleted_by_types() as $index => $type) {
                insert_record('artefact_annotation_deletedby', (object)array('id' => ((int)$index + 1), 'name' => $type));
            }

            // If elasticsearch is installed, update the artefacttypesmap field to include
            // annotation and annotationfeedback.
            $sql = "SELECT value FROM {search_config} WHERE plugin='elasticsearch' AND field='artefacttypesmap'";
            if ($result = get_field_sql($sql, array())) {
                $elasticsearchartefacttypesmap = explode("\n", $result);
                // add annotation and annotationfeedback fields.
                $elasticsearchartefacttypesmap[] = "annotation|Annotation|Text";
                $elasticsearchartefacttypesmap[] = "annotationfeedback|Annotation|Text";
                // Now save the data including the new annotation fields.
                set_config_plugin('search', 'elasticsearch', 'artefacttypesmap', implode("\n", $elasticsearchartefacttypesmap));
            }

            // Now install the blocktype annotation only if Mahara was previously installed.
            // Otherwise, the Mahara installer will install everything.
            if (get_config('installed')) {
                if ($upgrade = check_upgrades('blocktype.annotation/annotation')) {
                    upgrade_plugin($upgrade);
                }
            }
        }
    }

    public static function view_export_extra_artefacts($viewids) {
        $artefacts = array();
        if (!$artefacts = get_column_sql("
            SELECT af.artefact
            FROM {artefact_annotation} an
            INNER JOIN {artefact_annotation_feedback} af ON an.annotation = af.onannotation
            WHERE af.deletedby IS NULL
            AND   an.view IN (" . join(',', array_map('intval', $viewids)) . ')', array())) {
            return array();
        }
        return $artefacts;
    }

    public static function artefact_export_extra_artefacts($artefactids) {
        if (!$artefacts = get_column_sql("
            SELECT af.artefact
            FROM {artefact_annotation} an
            INNER JOIN {artefact_annotation_feedback} af ON an.annotation = af.onannotation
            WHERE af.deletedby IS NULL
            AND   an.artefact IN (" . join(',', $artefactids) . ')', array())) {
            return array();
        }
        return $artefacts;
    }

    public static function get_cron() {
        return array(
            (object)array(
                'callfunction' => 'clean_annotationfeedback_notifications',
                'minute'       => '35',
                'hour'         => '22',
            ),
        );
    }

    public static function clean_annotationfeedback_notifications() {
        safe_require('notification', 'internal');
        PluginNotificationInternal::clean_notifications(array('annotationfeedback'));
    }

    public static function progressbar_link($artefacttype) {
        switch ($artefacttype) {
            case 'annotation':
162
163
164
                return 'view/index.php';
                break;
            case 'annotationfeedback':
165
166
167
168
169
170
171
172
173
                return 'view/sharedviews.php';
                break;
        }
    }

    public static function progressbar_additional_items() {
        return array(
            (object)array(
                'name' => 'annotation',
174
175
                'title' => get_string('placeannotation', 'artefact.annotation'),
                'plugin' => 'annotation',
176
                'active' => get_field('blocktype_installed', 'active', 'name', 'annotation', 'artefactplugin', 'annotation'),
177
178
179
180
181
                'iscountable' => true,
                'is_metaartefact' => true,
            ),
            (object)array(
                'name' => 'annotationfeedback',
182
183
                'title' => get_string('placeannotationfeedback', 'artefact.annotation'),
                'plugin' => 'annotation',
184
                'active' => get_field('blocktype_installed', 'active', 'name', 'annotation', 'artefactplugin', 'annotation'),
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
                'iscountable' => true,
                'is_metaartefact' => true,
            )
        );
    }

    public static function progressbar_metaartefact_count($name) {
        global $USER;
        $meta = new stdClass();
        $meta->artefacttype = $name;
        $meta->completed = 0;
        switch ($name) {
            case 'annotation':
                $sql = "SELECT COUNT(*) AS completed
                        FROM {artefact}
                        WHERE artefacttype='annotation'
201
202
203
204
205
206
207
                        AND owner = ?";
                $meta->completed = count_records_sql($sql, array($USER->get('id')));
                break;
            case 'annotationfeedback':
                $sql = "SELECT COUNT(*) AS completed
                        FROM {artefact}
                        WHERE artefacttype='annotationfeedback'
208
209
                        AND owner <> ?
                        AND author = ?";
210
                $meta->completed = count_records_sql($sql, array($USER->get('id'), $USER->get('id')));
211
212
213
214
215
216
217
218
219
220
221
222
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
253
254
255
256
257
                break;
            default:
                return false;
        }
        return $meta;
    }
}

class ArtefactTypeAnnotation extends ArtefactType {

    protected $annotation;  // artefactid of the annotation artefact.
    protected $artefact;    // artefactid of the artefact this annotation is linked to.
    protected $view;        // viewid of the view this annotation is linked to.

    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

        if ($this->id && ($extra = get_record('artefact_annotation', 'annotation', $this->id))) {
            foreach($extra as $name => $value) {
                if (property_exists($this, $name)) {
                    $this->{$name} = $value;
                }
            }
        }
    }

    /**
     * For annotations, the artefact.mtime property is displayed to users, as the "Update on" date,
     * if it is later than the artefact's creation time. The purpose of this is for transparency
     * in communication, so that people will know that a later comment may be in response to one
     * that no longer exists.
     *
     * @see ArtefactType::set()
     */
    public function set($field, $value) {
        if (($field == 'title' || $field == 'description') && $this->{$field} != $value) {
            $this->lastcontentupdate = $this->mtime;
        }
        return parent::set($field, $value);
    }

    public static function is_singular() {
        return false;
    }

    public static function get_icon($options=null) {
        global $THEME;
258
        return false;
259
260
261
    }

    public static function get_links($id) {
262
263
264
265
266
267
        $annotation = new ArtefactTypeAnnotation($id);
        require_once(get_config('libroot') . 'view.php');
        $v = new View($annotation->get('view'));
        return array(
            '_default' => $v->get_url(),
        );
268
269
270
271
272
273
274
275
276
277
278
279
280
    }

    public function get_view_url($viewid, $showcomment=true, $full=true) {
        $url = 'view/view.php?id=' . $viewid;
        if ($showcomment) {
            $url .= '&showcomment=' . $this->get('id');
        }
        if ($full) {
            $url = get_config('wwwroot') . $url;
        }
        return $url;
    }

281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
    public function update_artefact_references(&$view, &$template, &$artefactcopies, $oldid) {
        parent::update_artefact_references($view, $template, $artefactcopies, $oldid);
        // If we have some artefact mapping data
        if (isset($artefactcopies[$oldid]->newid)) {
            if ($viewid = get_field('view_artefact', 'view', 'artefact', $artefactcopies[$oldid]->newid, 'view', $view->get('id'))) {
                // And the mapping data relates to this particular view (useful if in collection)
                // Attach copies of the annotation artefact to correct view in artefact_annotation table.
                $data = (object)array(
                    'annotation'    => $artefactcopies[$oldid]->newid,
                    'view'          => $view->get('id'),
                    'artefact'      => $this->get('artefact'),
                );
                update_record('artefact_annotation', $data, 'annotation');
            }
        }
    }

298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
    public function commit() {
        if (empty($this->dirty)) {
            return;
        }

        $new = empty($this->id);

        db_begin();

        parent::commit();

        $data = (object)array(
            'annotation'    => $this->get('id'),
            'view'          => $this->get('view'),
            'artefact'      => $this->get('artefact'),
        );

        if ($new) {
            insert_record('artefact_annotation', $data);
        }
        else {
            update_record('artefact_annotation', $data, 'annotation');
        }

322
323
324
        if ($this->get('view')) {
            set_field('view', 'mtime', db_format_timestamp(time()), 'id', $this->get('view'));
        }
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
        db_commit();
        $this->dirty = false;
    }

    public function delete() {
        if (empty($this->id)) {
            return;
        }
        db_begin();
        $this->detach();

        // Delete all annotation feedback linked to this annotation.
        $sql = "SELECT af.id
                    FROM {artefact} a
                    INNER JOIN {artefact_annotation} an ON a.id = an.annotation
                    INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
                    INNER JOIN {artefact} af ON f.artefact = af.id
                    WHERE a.id = ?
                    ORDER BY af.id DESC";
        $annotationfeedbackids = get_column_sql($sql, array($this->id));
        foreach ($annotationfeedbackids as $id) {
            $feedback = new ArtefactTypeAnnotationfeedback($id);
            $feedback->delete();
        }

350
351
352
        // Remove any embedded images for this annotation.
        require_once('embeddedimage.php');
        EmbeddedImage::remove_embedded_images('annotation', $this->id);
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
        delete_records('artefact_annotation', 'annotation', $this->id);
        parent::delete();
        db_commit();
    }

}

class ArtefactTypeAnnotationfeedback extends ArtefactType {

    protected $artefact; // The artefact id for the annotationfeedback record.
    protected $onannotation;  // The artefact id of the annotation that this annotationfeedback relates to.
    protected $private;
    protected $deletedby;
    protected $requestpublic;
    protected $lastcontentupdate;

    public function __construct($id = 0, $data = null) {
        parent::__construct($id, $data);

        if ($this->id && ($extra = get_record('artefact_annotation_feedback', 'artefact', $this->id))) {
            foreach($extra as $name => $value) {
                if (property_exists($this, $name)) {
                    $this->{$name} = $value;
                }
            }
        }
    }

    public static function is_allowed_in_progressbar() {
        return false;
    }


    /**
     * For annotations, the artefact.mtime property is displayed to users, as the "Update on" date,
     * if it is later than the artefact's creation time. The purpose of this is for transparency
     * in communication, so that people will know that a later feedback may be in response to one
     * that no longer exists.
     *
     * @see ArtefactType::set()
     */
    public function set($field, $value) {
        if (($field == 'title' || $field == 'description') && $this->{$field} != $value) {
            $this->lastcontentupdate = $this->mtime;
        }
        return parent::set($field, $value);
    }

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

        $new = empty($this->id);

        db_begin();

        parent::commit();

        // Now fix up the text in case there were any embedded images.
        // Do this after saving because we may not have an artefactid yet.
        // This will add a record to the artefact_file_embedded table
        // for each file that is embedded in the feedback text.
        require_once('embeddedimage.php');
        $newtext = EmbeddedImage::prepare_embedded_images($this->get('description'), 'annotationfeedback', $this->id);
        if ($newtext !== false && $newtext !== $this->get('description')) {
            $updatedartefact = new stdClass();
            $updatedartefact->id = $this->get('id');
            $updatedartefact->description = $newtext;
            update_record('artefact', $updatedartefact, 'id');
        }

        $data = (object)array(
            'artefact'      => $this->get('id'),
            'onannotation'  => $this->get('onannotation'),
            'private'       => $this->get('private'),
            'deletedby'     => $this->get('deletedby'),
            'requestpublic' => $this->get('requestpublic'),
        );
        if ($this->get('lastcontentupdate')) {
            $data->lastcontentupdate = db_format_timestamp($this->get('lastcontentupdate'));
        }

        if ($new) {
            insert_record('artefact_annotation_feedback', $data);
        }
        else {
            update_record('artefact_annotation_feedback', $data, 'artefact');
        }

        // Get the block instance that contains this artefact
        // so we can add to the view any artefacts containted in the feedback text
        // as well as the feedback itself.
        $sql = "SELECT bi.*
                FROM {block_instance} bi
                INNER JOIN {view_artefact} va ON va.view = bi.view
                WHERE bi.blocktype = 'annotation'
                AND va.artefact = ?";
        if ($blocks = get_records_sql_array($sql, array($this->get('onannotation')))) {
            require_once(get_config('docroot') . 'blocktype/lib.php');
            foreach ($blocks as $bi) {
                $block = new BlockInstance($bi->id);
                $blockconfig = $block->get('configdata');
                if (isset($blockconfig['artefactid']) && $blockconfig['artefactid'] == $this->get('onannotation')) {
                    // Currently, all annotations can only exist on views.
                    // But, put the check anyway.
                    if ($block->get('view')) {
                        // We found the annotation we're inputting feedback for.
                        // Rebuild the block's list and break out of the loop.
462
                        set_field('view', 'mtime', db_format_timestamp(time()), 'id', $block->get('view'));
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
                        $block->rebuild_artefact_list();
                    }

                    break;
                }
            }
        }

        db_commit();
        $this->dirty = false;
    }

    public static function is_singular() {
        return false;
    }

    public static function get_icon($options=null) {
        global $THEME;
481
        return false;
482
483
484
485
486
487
488
489
490
491
492
493
    }

    public function delete() {
        if (empty($this->id)) {
            return;
        }
        db_begin();
        $this->detach();
        // Don't use EmbeddedImage::delete_embedded_images() - it deletes by
        // the fileid. We need to delete by the resourceid.
        delete_records('artefact_file_embedded', 'resourceid', $this->id);
        delete_records('artefact_annotation_feedback', 'artefact', $this->id);
494
        delete_records('framework_assessment_feedback', 'artefact', $this->id);
495
496
497
498
499
500
501
502
503
        parent::delete();
        db_commit();
    }

    /**
     * Delete annotationfeedback records in the artefact table and the artefat_annotation_feedback table.
     *
     * @param array $artefactids is a list of artefactids representing the annotationfeedback artefacts.
     */
504
    public static function bulk_delete($artefactids, $log=false) {
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
        if (empty($artefactids)) {
            return;
        }

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

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

    /**
     * Delete annotationfeedback records in the artefact table and the artefat_annotation_feedback table
     * that are on a particular view.
     *
     * @param array $viewid is the id of the view that the annotation is linked to.
     */
    public static function delete_annotation_feedback_onview($viewid) {
        // Get a list of the annotationfeedback ids that are on the viewid.
        $sql = "SELECT f.artefact
                FROM {artefact_annotation} a
                INNER JOIN {artefact_annotation_feedback} f on a.annotation = f.onannotation
                WHERE a.view = ?";

        $artefacts = get_records_sql_assoc($sql, array($viewid));
        $ids = array_keys($artefacts);
        self::bulk_delete($ids);
    }

    /**
     * Delete annotationfeedback records in the artefact table and the artefat_annotation_feedback table
     * that are on a particular artefact.
     *
     * @param array $artefactid is the id of the artefact that the annotation is linked to.
     */
    public static function delete_annotation_feedback_onartefact($artefactid) {
        // Get a list of the annotationfeedback ids that are on the artefactid.
        $sql = "SELECT f.artefact
                FROM {artefact_annotation} a
                INNER JOIN {artefact_annotation_feedback} f on a.annotation = f.onannotation
                WHERE a.artefact = ?";

        $artefacts = get_records_sql_assoc($sql, array($artefactid));
        $ids = array_keys($artefacts);
        self::bulk_delete($ids);
    }

    /**
     * Delete annotationfeedback records in the artefact table and the artefat_annotation_feedback table
     * that are for a particular annotation.
     *
     * @param array $artefactid is the id of the artefact that the annotation is linked to.
     */
    public static function delete_annotation_feedback_onannotation($artefactid) {
        $ids = get_column_sql("SELECT artefact FROM {artefact_annotation_feedback} WHERE onannotation IN ($artefactid)");
        self::bulk_delete($ids);
    }

    public static function get_links($id) {
        return array();
    }

    /**
     * Return an array of the user types that can delete a message.
     *
     * @return array
     */
    public static function deleted_by_types() {
        // An annotation can be deleted by these three types of users.
        return array('author', 'owner', 'admin');
    }

    /**
     * Return an array of the user types that can delete a message
     * with the corresponding string description.
     *
     * @return array
     */
    public static function deleted_by_types_description() {
        return array(
            'author' => 'commentremovedbyauthor',
            'owner'  => 'commentremovedbyowner',
            'admin'  => 'commentremovedbyadmin',
        );
    }

    /**
     * Generates default data object required for displaying annotations on the page.
     * The is called before populating with specific data to send to get_annotation_feedback() as
     * an easy way to add variables to get passed to get_annotation_feedback.
     *
     * int $limit              The number of comments to display (set to
     *                         0 for disabling pagination and showing all comments)
     * int $offset             The offset of comments used for pagination
     * int|string $showcomment Optionally show page with particular comment
     *                         on it or the last page. $offset will be ignored.
     *                         Specify either comment_id or 'last' respectively.
     *                         Set to null to use $offset for pagination.
     * int $annotation         The artefactid of the annotation.
     * int $view               Optional The view id that the annotation is linked to.
     * int $artefact           Optional artefact id that the annotation is linked to.
     * bool   $export          Determines if comments are fetched for html export purposes
     * bool   $onview          Optional - is viewing artefact annotations on view page so don't show edit buttons
     * string $sort            Optional - the sort order of the comments. Valid options are 'earliest' and 'latest'.
     * @return object $options Default annotations data object
     */
    public static function get_annotation_feedback_options() {
        $options = new stdClass();
614
        $options->limit = 0;
615
616
617
618
619
620
621
622
        $options->offset = 0;
        $options->showcomment = null;

        $options->annotation = '';      // artefactid for annotation.
        $options->artefact = '';        // artefactid that the annotation is linked to.
        $options->view = '';            // viewid that the annotation is linked to.
        $options->block = '';           // blockid that the annotation lives in.

623
        $options->export = 0;
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
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
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
        $sortorder = get_user_institution_comment_sort_order();
        $options->sort = (!empty($sortorder)) ? $sortorder : 'earliest';
        return $options;
    }

    /**
     * Generates the data object required for displaying annotations on the page.
     *
     * @param   object  $options  Object of annotation options
     *                            - defaults can be retrieved from get_annotation_feedback_options()
     * @return  object $result    Annotation data object
     */
    public static function get_annotation_feedback($options) {
        global $USER;
        // set the object's key/val pairs as variables
        foreach ($options as $key => $option) {
            $$key = $option;
        }
        $userid = $USER->get('id');

        $canedit = false;
        if (!empty($artefact)) {
            // This is the artefact that the annotation is linked to.
            $artefactobj = artefact_instance_from_id($artefact);
            $canedit = $USER->can_edit_artefact($artefactobj);
            $owner = $artefactobj->get('owner');
            $isowner = $userid && $userid == $owner;
            $view = null;
        }
        else if (!empty($view)) {
            // This is the view that the annotation is linked to.
            $viewobj = new View($view);
            $canedit = $USER->can_moderate_view($viewobj);
            $owner = $viewobj->get('owner');
            $isowner = $userid && $userid == $owner;
            $artefact = null;
        }

        $result = (object) array(
            'limit'      => $limit,
            'offset'     => $offset,
            'annotation' => $annotation,
            'view'       => $view,
            'artefact'   => $artefact,
            'block'      => $block,
            'canedit'    => $canedit,
            'owner'      => $owner,
            'isowner'    => $isowner,
            'export'     => $export,
            'sort'       => $sort,
            'data'       => array(),
        );

        $wherearray = array();
        $wherearray[] = 'a.id = ' . (int) $annotation;

        // if artefact and view are not set, this annotation is not linked to anything.
        if (!empty($artefact)) {
            $wherearray[] = 'an.artefact = ' . (int) $artefact;
        }
        else if (!empty($view)) {
            $wherearray[] = 'an.view = ' . (int) $view;
        }
        else {
            // Something is wrong.  Don't show anything.
            $wherearray[] = '1 = 2';
        }
        if (!$canedit) {
            $wherearray[] = '(f.private = 0 OR af.author = ' . (int) $userid . ')';
        }
        $where = implode(' AND ', $wherearray);

        $sql = 'SELECT COUNT(*)
                FROM {artefact} a
                INNER JOIN {artefact_annotation} an ON a.id = an.annotation
                INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
                INNER JOIN {artefact} af ON f.artefact = af.id
                INNER JOIN {usr} u ON a.author = u.id
                LEFT JOIN {usr} uf ON af.author = uf.id
                LEFT JOIN {usr_institution} uif ON uf.id = uif.usr
                WHERE ' . $where;
        $result->count = count_records_sql($sql);

        if ($result->count > 0) {
            // If pagination is in use, see if we want to get a page with particular comment
            if ($limit) {
                if ($showcomment == 'last') {
                    // If we have limit (pagination is used) ignore $offset and just get the last page of feedback.
                    $result->forceoffset = $offset = (ceil($result->count / $limit) - 1) * $limit;
                }
                else if (is_numeric($showcomment)) {
                    // Ignore $offset and get the page that has the comment
                    // with id $showcomment on it.
                    // Fetch everything up to $showcomment to get its rank
                    // This will get ugly if there are 1000s of feedback.
                    $ids = get_column_sql('
                        SELECT f.artefact
                        FROM {artefact} a
                        INNER JOIN {artefact_annotation} an ON a.id = an.annotation
                        INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
                        INNER JOIN {artefact} af ON f.artefact = af.id
                        INNER JOIN {usr} u ON a.author = u.id
                        LEFT JOIN {usr} uf ON af.author = uf.id
                        LEFT JOIN {usr_institution} uif ON uf.id = uif.usr
                        WHERE ' . $where . '
                        AND f.artefact <= ?
                        ORDER BY a.ctime', array($showcomment));
                    $last = end($ids);
                    if ($last == $showcomment) {
                        // Add 1 because array index starts from 0 and therefore key value is offset by 1.
                        $rank = key($ids) + 1;
                        $result->forceoffset = $offset = ((ceil($rank / $limit) - 1) * $limit);
                        $result->showcomment = $showcomment;
                    }
                }
            }

            $sortorder = (!empty($sort) && $sort == 'latest') ? 'af.ctime DESC' : 'af.ctime ASC';
            $sql = 'SELECT
                        af.id, af.author, af.authorname, af.ctime, af.mtime, af.description, af.group,
                        f.private, f.deletedby, f.requestpublic, f.lastcontentupdate,
                        uf.username, uf.firstname, uf.lastname, uf.preferredname, uf.email, uf.staff, uf.admin,
                        uf.deleted, uf.profileicon, uf.urlid,
                        uif.staff as feedbackinstitutionstaff, uif.admin as feedbackinstitutionadmin
                    FROM {artefact} a
                    INNER JOIN {artefact_annotation} an ON a.id = an.annotation
                    INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
                    INNER JOIN {artefact} af ON f.artefact = af.id
                    INNER JOIN {usr} u ON a.author = u.id
                    LEFT JOIN {usr} uf ON af.author = uf.id
                    LEFT JOIN {usr_institution} uif ON uf.id = uif.usr
                    WHERE ' . $where . '
                    ORDER BY ' . $sortorder;
            $annotationfeedback = get_records_sql_assoc($sql, array(), $offset, $limit);
            $result->data = array_values($annotationfeedback);
        }

        $result->position = 'blockinstance';

        self::build_html($result, $view);
        return $result;
    }

    public static function build_html(&$data, $onview) {
        global $USER, $THEME;

        $candelete = $data->canedit || $USER->get('admin');
        $deletedmessage = array();
        foreach (ArtefactTypeAnnotationfeedback::deleted_by_types_description() as $k => $v) {
            $deletedmessage[$k] = get_string($v, 'artefact.annotation');
        }
        $authors = array();
        $lastcomment = self::last_public_annotation_feedback($data->annotation, $data->view, $data->artefact);
        $editableafter = time() - 60 * get_config_plugin('artefact', 'annotation', 'commenteditabletime');
        foreach ($data->data as &$item) {
            $isadminfeedback = $item->admin == 1 || $item->staff == 1 || $item->feedbackinstitutionadmin == 1 || $item->feedbackinstitutionstaff == 1;
            $item->ts = strtotime($item->ctime);
            $item->date = format_date($item->ts, 'strftimedatetime');
            if ($item->ts < strtotime($item->lastcontentupdate)) {
                $item->updated = format_date(strtotime($item->lastcontentupdate), 'strftimedatetime');
            }
            $item->isauthor = $item->author && $item->author == $USER->get('id');
            if ($item->private) {
                $item->pubmessage = get_string('annotationfeedbackisprivate', 'artefact.annotation');
            }

            if (isset($data->showcomment) && $data->showcomment == $item->id) {
                $item->highlight = 1;
            }
793
            $is_export_preview = param_integer('export', $data->export);
794
795
796
797
798
799
800
801
802
803

            // Comment authors can edit recent comments if they're private or if no one has replied yet.
            if (!$item->deletedby && $item->isauthor && !$is_export_preview
                && ($item->private || $item->id == $lastcomment->id) && $item->ts > $editableafter) {
                $item->canedit = 1;
            }
            else {
                $item->canedit = 0;
            }

804
805
806
            if ($item->deletedby) {
                $item->deletedmessage = $deletedmessage[$item->deletedby];
            }
807
808
            else if (($candelete || $item->isauthor) && !$is_export_preview &&
                     (!$isadminfeedback || ($isadminfeedback && ($data->owner === $item->author)))) {
809
810
                // If the auther was admin/staff and not the owner of the annotation,
                // the feedback can't be deleted.
811
812
813
814
815
816
                $check = get_record_sql('SELECT v.* FROM {view} v WHERE v.id = ?', array($data->view), ERROR_MULTIPLE);
                if ($check->submittedstatus == View::UNSUBMITTED ||
                    ($item->canedit && $item->id == $lastcomment->id && $item->ts > $editableafter)
                   ) {
                    $item->deleteform = pieform(self::delete_annotation_feedback_form($data->annotation, $data->view, $data->artefact, $data->block, $item->id));
                }
817
818
819
820
821
822
823
824
825
826
827
828
            }

            // Form to make private comment public, or request that a
            // private comment be made public.
            if (!$item->deletedby && $item->private && $item->author && $data->owner
                && ($item->isauthor || $data->isowner)) {
                if ((empty($item->requestpublic) && $data->isowner)
                    || $item->isauthor && $item->requestpublic == 'owner'
                    || $data->isowner && $item->requestpublic == 'author') {
                    if (!$is_export_preview) {
                        $item->makepublicform = pieform(self::make_annotation_feedback_public_form($data->annotation, $data->view, $data->artefact, $data->block, $item->id));
                    }
829
830
831
                    else {
                        $item->highlight = 1;
                    }
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
                }
                else if ($item->isauthor && $item->requestpublic == 'author'
                         || $data->isowner && $item->requestpublic == 'owner') {
                    $item->makepublicrequested = 1;
                }
            }
            else if (!$item->deletedby && $item->private && !$item->author
                && $data->owner && $data->isowner && $item->requestpublic == 'author' && !$is_export_preview) {
                $item->makepublicform = pieform(self::make_annotation_feedback_public_form($data->annotation, $data->view, $data->artefact, $data->block, $item->id));
            }
            else if (!$item->deletedby && $item->private && !$data->owner
                && $item->group && $item->requestpublic == 'author') {
                // no owner as comment is on a group view / artefact
                if ($item->isauthor) {
                    $item->makepublicrequested = 1;
                }
                else {
                    if (($data->artefact && $data->canedit) || ($data->view && $data->canedit) && !$is_export_preview) {
                        $item->makepublicform = pieform(self::make_annotation_feedback_public_form($data->annotation, $data->view, $data->artefact, $data->block, $item->id));
                    }
                    else {
                        $item->makepublicrequested = 1;
                    }
                }
            }

            if ($item->author) {
                if (isset($authors[$item->author])) {
                    $item->author = $authors[$item->author];
                }
                else {
                    $item->author = $authors[$item->author] = (object) array(
                        'id'            => $item->author,
                        'username'      => $item->username,
                        'firstname'     => $item->firstname,
                        'lastname'      => $item->lastname,
                        'preferredname' => $item->preferredname,
                        'email'         => $item->email,
                        'staff'         => $item->staff,
                        'admin'         => $item->admin,
                        'deleted'       => $item->deleted,
                        'profileicon'   => $item->profileicon,
                        'profileurl'    => profile_url($item->author),
                    );
                }
            }
878
879
880
881
882
883
884
885
886
            if ($statechange = get_record('framework_assessment_feedback', 'artefact', $item->id)) {
                safe_require('module', 'framework');
                $state = Framework::get_state_array($statechange->newstatus, true);
                $states = Framework::get_evidence_statuses($statechange->framework);
                // We need to amend a bit of text to the feedback message
                $item->description .= '<div class="assessment text-small">' .
                    get_string('assessmentchangedto', 'artefact.annotation', $states[$statechange->newstatus]) .
                    ' <span class="assessmentfeedback ' . $state['classes'] . '"></span></div>';
            }
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
        }

        $extradata = array(
                'annotation' => $data->annotation,
                'view'       => $data->view,
                'artefact'   => (!empty($data->artefact) ? $data->artefact : ''),
                'blockid'    => $data->block,
            );
        $data->jsonscript = 'artefact/annotation/annotations.json.php';

        $data->baseurl = get_config('wwwroot') . 'artefact/artefact.php?' .
            'artefact=' . $data->annotation .
            '&view=' . $data->view .
            (isset($data->block) ? '&block=' . $data->block : '');

        $smarty = smarty_core();
903
        $smarty->assign('data', $data->data);
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
        $smarty->assign('canedit', $data->canedit);
        $smarty->assign('viewid', $data->view);
        $smarty->assign('position', $data->position);
        $smarty->assign('baseurl', $data->baseurl);
        $data->tablerows = $smarty->fetch('artefact:annotation:annotationlist.tpl');
        $pagination = build_pagination(array(
            'id' => 'annotationfeedback_pagination_' . $data->block,
            'class' => 'center',
            'url' => $data->baseurl,
            'jsonscript' => $data->jsonscript,
            'datatable' => 'annotationfeedbacktable_' . $data->block,
            'count' => $data->count,
            'limit' => $data->limit,
            'offset' => $data->offset,
            'forceoffset' => isset($data->forceoffset) ? $data->forceoffset : null,
919
920
            'resultcounttextsingular' => get_string('annotationfeedback', 'artefact.annotation'),
            'resultcounttextplural' => get_string('annotationfeedback', 'artefact.annotation'),
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
            'extradata' => $extradata,
        ));
        $data->pagination = $pagination['html'];
        $data->pagination_js = $pagination['javascript'];
    }

    public static function last_public_annotation_feedback($annotation, $onview=null, $onartefact=null) {
        if (!empty($onartefact)) {
            $where = 'an.artefact = ?';
            $values = array($onartefact);
        }
        else if (!empty($onview)) {
            $where = 'an.view = ?';
            $values = array($onview);
        }
        $newest = get_records_sql_array('
            SELECT af.id, af.ctime
            FROM {artefact} a
            INNER JOIN {artefact_annotation} an ON a.id = an.annotation
            INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
            INNER JOIN {artefact} af ON f.artefact = af.id
            WHERE f.private = 0
            AND   a.id = ' . (int) $annotation . '
            AND   ' . $where . '
            ORDER BY af.ctime DESC', $values, 0, 1
        );
        return $newest[0];
    }

950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
    /**
     * Fetching the annotations for an artefact to display on a matrix
     *
     * @param   object  $annotationartefact  The annotation artefact to display feedbacks for.
     * @param   object  $view     The view on which the annotation artefact is linked to.
     * @param   int     $blockid  The id of the block instance that connects the artefact to the view
     * @param   boolean $listonly Only return the list and not the form
     *
     */
    public function get_annotation_feedback_for_matrix($annotationartefact, $view, $blockid, $listonly = false) {
        $options = ArtefactTypeAnnotationfeedback::get_annotation_feedback_options();
        $options->limit = 0;
        $options->view = $view->get('id');
        $options->annotation = $annotationartefact->get('id');
        $options->block = $blockid;
        $options->export = 1;
966
        $options->sort = 'latest';
967
968
969
970
971
972
973
974
975
976
977
978
        $annotationfeedback = ArtefactTypeAnnotationfeedback::get_annotation_feedback($options);
        $annotationfeedbackcount = isset($annotationfeedback->count) ? $annotationfeedback->count : 0;

        if ($listonly) {
            return array($annotationfeedbackcount, $annotationfeedback);
        }

        $smarty = smarty_core();
        $smarty->assign('blockid', $blockid);
        $smarty->assign('annotationfeedbackcount', $annotationfeedbackcount);
        $smarty->assign('annotationfeedback', $annotationfeedback);

979
        if ($annotationartefact->get('allowcomments') && is_logged_in()) {
980
            $form = ArtefactTypeAnnotationfeedback::add_annotation_feedback_form($annotationartefact, $view, null, $blockid, false, $annotationartefact->get('approvecomments'));
981
982
983
984
985
986
987
            // Replace the submit/cancel with just a submit button
            $submit = array(
                'type'  => 'submit',
                'value' => get_string('placeannotationfeedback', 'artefact.annotation'),
                'class' => 'btn-default'
            );
            $form['elements']['submit'] = $submit;
988
989
            // Dont use the 'Processing...' bit on the submit button
            $form['presubmitcallback'] = '';
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
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
            // Remove the 'assessment' option as we want that independent of submitting feedback here
            unset($form['elements']['assessment']);
            $addannotationfeedbackform = pieform($form);
            $smarty->assign('addannotationfeedbackform', $addannotationfeedbackform);
        }
        else {
            // The user has switched off annotation feedback. Don't create the add annotation feedback form.
            $smarty->assign('addannotationfeedbackform', null);
        }
        $render = $smarty->fetch('artefact:annotation:annotationfeedbackmatrix.tpl');
        return array($annotationfeedbackcount, $render);
    }

    /**
     * Saving the annotation feedback via the matrix dock
     *
     * @param   object  $annotationartefact  The annotation artefact to add feedback to.
     * @param   object  $view      The view the annotation artefact is on
     * @param   int     $blockid   The id of the block instance that connects the artefact to the view
     * @param   string  $message   The feedback message
     * @param   boolean $ispublic  Whether it is a public message or not
     */
    public function save_matrix_feedback($annotationartefact, $view, $blockid, $message, $ispublic = true) {
        global $USER;
        if (!is_object($annotationartefact) || !is_object($view) || empty($message)) {
            throw new MaharaException(get_string('annotationinformationerror', 'artefact.annotation'));
        }

        $data = (object) array(
            'title'        => get_string('Annotation', 'artefact.annotation'),
            'description'  => $message,
            'onannotation' => $annotationartefact->get('id'),
        );

        $data->view        = $view->get('id');
        $data->owner       = $view->get('owner');
        $data->group       = $view->get('group');
        $data->institution = $view->get('institution');

        if ($author = $USER->get('id')) {
            $anonymous = false;
            $data->author = $author;
        }
        else {
            $anonymous = true;
            $data->authorname = $values['authorname'];
        }

        // @TODO deal with moderation
        // if (isset($values['moderate']) && $values['ispublic'] && !$USER->can_edit_view($view)) {
        //     $data->private = 1;
        //     $data->requestpublic = 'author';
        //     $moderated = true;
        // }
        // else {
            $data->private = (int) !$ispublic;
            $moderated = false;
        // }
        $private = $data->private;

        $annotationfeedback = new ArtefactTypeAnnotationfeedback(0, $data);

        db_begin();

        $annotationfeedback->commit();

1056
1057
        db_commit();

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
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
        if (isset($data->requestpublic) && $data->requestpublic === 'author' && $data->owner) {
            $arg = $author ? display_name($USER, null, true) : $data->authorname;
            $moderatemsg = (object) array(
                'subject'   => false,
                'message'   => false,
                'strings'   => (object) array(
                    'subject' => (object) array(
                        'key'     => 'makepublicrequestsubject',
                        'section' => 'artefact.annotation',
                        'args'    => array(),
                    ),
                    'message' => (object) array(
                        'key'     => 'makepublicrequestbyauthormessage',
                        'section' => 'artefact.annotation',
                        'args'    => array(hsc($arg)),
                    ),
                    'urltext' => (object) array(
                        'key'     => 'Annotation',
                        'section' => 'artefact.annotation',
                    ),
                ),
                'users'     => array($data->owner),
                'url'       => $url,
            );
        }

        require_once('activity.php');
        $data = (object) array(
            'annotationfeedbackid' => $annotationfeedback->get('id'),
            'annotationid'         => $annotationartefact->get('id'),
            'viewid'               => $view->get('id'),
        );
        activity_occurred('annotationfeedback', $data, 'artefact', 'annotation');

        if (isset($moderatemsg)) {
            activity_occurred('maharamessage', $moderatemsg);
        }

        list($count, $newlist) = self::get_annotation_feedback_for_matrix($annotationartefact, $view, $blockid, true);
        return $newlist->tablerows;
    }

1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
    /**
     * Fetching the annotations for an artefact to display on a view
     *
     * @param   object  $annotationartefact  The annotation artefact to display feedbacks for.
     * @param   object  $view     The view on which the annotation artefact is linked to.
     * @param   int     $blockid  The id of the block instance that connects the artefact to the view
     * @param   bool    $html     Whether to return the information rendered as html or not
     * @param   bool    $editing  Whether we are view edit mode or not
     */
    public function get_annotation_feedback_for_view($annotationartefact, $view, $blockid, $html = true, $editing = false) {
1110
        global $USER;
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
        if (!is_object($annotationartefact) || !is_object($view)) {
            throw new MaharaException(get_string('annotationinformationerror', 'artefact.annotation'));
        }

        // If there is annotation feedback, retrieve it so it can be displayed -
        // even if no annotation feedback is turned on.
        $options = ArtefactTypeAnnotationfeedback::get_annotation_feedback_options();
        // Don't paginate when the annotation is on a view.  It gets mixed up
        // with the pagination of feedback on a view.
        $options->limit = 0;
        $options->view = $view->get('id');
        $options->annotation = $annotationartefact->get('id');
        $options->block = $blockid;
        $annotationfeedback = ArtefactTypeAnnotationfeedback::get_annotation_feedback($options);
        $annotationfeedbackcount = isset($annotationfeedback->count) ? $annotationfeedback->count : 0;

        if ($html) {
            // Return the rendered form.
            $smarty = smarty_core();
            if ($annotationartefact->get('allowcomments') && !$editing) {
1131
                $addannotationfeedbackform = pieform(ArtefactTypeAnnotationfeedback::add_annotation_feedback_form($annotationartefact, $view, null, $blockid, false, $annotationartefact->get('approvecomments')));
1132
1133
1134
1135
1136
1137
                $smarty->assign('addannotationfeedbackform', $addannotationfeedbackform);
            }
            else {
                // The user has switched off annotation feedback. Don't create the add annotation feedback form.
                $smarty->assign('addannotationfeedbackform', null);
            }
1138
1139
1140
            safe_require('blocktype', 'annotation');
            $block = new BlockInstance($blockid);

1141
            $smarty->assign('blockid', $blockid);
1142
            $smarty->assign('annotationtitle', $block->get('title'));
1143
1144
1145
            $smarty->assign('annotationfeedbackcount', $annotationfeedbackcount);
            $smarty->assign('annotationfeedback', $annotationfeedback);
            $smarty->assign('editing', $editing);
1146
            $smarty->assign('allowfeedback', $USER->is_logged_in() && $annotationartefact->get('allowcomments'));
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
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
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
            $render = $smarty->fetch('artefact:annotation:annotationfeedbackview.tpl');
            return array($annotationfeedbackcount, $render);
        }
        else {
            // Return the array of raw data unrendered.
            return array($annotationfeedbackcount, $annotationfeedback);
        }
    }

    /**
     * Get the total number of annotation feedback inserted so far for a particular
     * annotation on a: view and/or on an artefact.
     * @param int $annotation
     * @param array $viewids list of viewids that the annotation lives on.
     * @param array $artefactids list of artefactids that the annotation is linked to.
     * @param boolean $bystafforadmin TRUE - retrieve the count of feedback input by users who are staff and/or admin.
     *                                FALSE - retrieve the count of feedback input by users who are NOT staff or admin.
     *                                NULL - retrieve the count of feedback input by users irrespecitve of the staff/admin flags.
     * @return array
     */
    public static function count_annotation_feedback($annotation, $viewids=null, $artefactids=null, $bystafforadmin = null) {
        $userwherearray = array();
        $instwherearray = array();
        $userwhere = '';
        $instwhere = '';
        if ($bystafforadmin === true) {
            $userwherearray[] = '(u.staff = 1 OR u.admin = 1)';
            $instwherearray[] = '(ui.staff = 1 OR ui.admin = 1)';
        }
        else if ($bystafforadmin === false) {
            $userwherearray[] = '(u.staff = 0 OR u.staff = 0)';
            $instwherearray[] = '(ui.staff = 0 OR ui.admin = 0)';
        }
        if (count($userwherearray) > 0) {
            $userwhere = ' AND ' . implode(' AND ', $userwherearray);
            $instwhere =  ' AND ' . implode(' AND ', $instwherearray);
        }
        if (!empty($viewids)) {
            // Get the count of feedback on a view for a particular annotation.
            $sql = 'SELECT an.view, COUNT(f.artefact) AS total
                    FROM {artefact} a
                    INNER JOIN {artefact_annotation} an ON a.id = an.annotation
                    INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
                    INNER JOIN {artefact} af ON af.id = f.artefact
                    INNER JOIN {usr} u ON af.author = u.id
                    LEFT JOIN {usr_institution} ui ON u.id = ui.usr
                        ' . $instwhere . '
                    WHERE an.annotation = ?
                    AND an.view IN (' . join(',', array_map('intval', $viewids)) . ')
                    AND f.deletedby IS NULL
                    ' . $userwhere . '
                    GROUP BY an.view';
            return get_records_sql_assoc($sql, array((int) $annotation));
        }
        if (!empty($artefactids)) {
            // Get the count of feedback on an artefact for a particular annotation.
            $sql = 'SELECT an.artefact, COUNT(c.artefact) AS total
                    FROM {artefact} a
                    INNER JOIN {artefact_annotation} an ON a.id = an.annotation
                    INNER JOIN {artefact_annotation_feedback} f ON an.annotation = f.onannotation
                    INNER JOIN {artefact} af ON af.id = f.artefact
                    INNER JOIN {usr} u ON af.author = u.id
                    LEFT JOIN {usr_institution} ui ON u.id = ui.usr
                        ' . $instwhere . '
                    WHERE an.annotation = ?
                    AND an.artefact IN (' . join(',', array_map('intval', $artefactids)) . ')
                    AND f.deletedby IS NULL
                    ' . $userwhere . '
                    GROUP BY an.artefact';
            return get_records_sql_assoc($sql, array((int) $annotation));
        }
    }

1220
    public function render_self($options) {
1221
1222
1223
1224
1225
1226
1227
1228
1229
        return clean_html($this->get('description'));
    }

    /**
     * Create a form so the user can enter feedback for an annotation that is linked to
     * a view or an artefact.
     * @param object $annotation the annotation artefact object.
     * @param object $view the view object that the annotation is linked to.
     * @param object $artefact the artefact object that the annotation is linked to.
1230
1231
1232
     * @param string $blockid the id of the block instance
     * @param boolean $defaultprivate set the private setting. Default is false.
     * @param boolean $moderate if moderating feedback. Default is false.
1233
1234
     * @return multitype:string multitype:NULL string
     */
1235
    public static function add_annotation_feedback_form($annotation, $view, $artefact, $blockid, $defaultprivate=false, $moderate=false) {
1236
1237
1238
1239
        global $USER;
        $form = array(
            'name'              => 'add_annotation_feedback_form_' . $blockid,
            'method'            => 'post',
1240
            'class'             => 'add_annotation_feedback_form form-condensed',
1241
1242
1243
1244
1245
1246
            'plugintype'        => 'artefact',
            'pluginname'        => 'annotation',
            'jsform'            => true,
            'autofocus'         => false,
            'elements'          => array(),
            'jssuccesscallback' => 'addAnnotationFeedbackSuccess',
1247
            'jserrorcallback'   => 'addAnnotationFeedbackError',
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
            'successcallback'   => 'add_annotation_feedback_form_submit',
            'validatecallback'  => 'add_annotation_feedback_form_validate',
        );
        if (!$USER->is_logged_in()) {
            $form['spam'] = array(
                'secret'       => get_config('formsecret'),
                'mintime'      => 1,
                'hash'         => array('authorname', 'message', 'ispublic', 'message', 'submit'),
            );
            $form['elements']['authorname'] = array(
                'type'  => 'text',
                'title' => get_string('name'),
                'rules' => array(
                    'required' => true,
                ),
            );
        }
        $form['elements']['message'] = array(
            'type'  => 'wysiwyg',
1267
            'class' => 'hide-label',
1268
1269
1270
1271
1272
            'title' => get_string('Annotationfeedback', 'artefact.annotation'),
            'rows'  => 5,
            'cols'  => 80,
            'rules' => array('maxlength' => 8192),
        );
1273
1274
1275
1276
1277
1278
1279
1280
1281

        $collection = $view->get('collection');
        if (is_object($collection) && $collection->has_framework()) {
            $view->get_artefact_instances(); // populate the artefact_metadata
            foreach ($view->get('artefact_metadata') as $metadata) {
                if ($metadata->id === $annotation->get('id')) {
                    safe_require('module', 'framework');

                    $evidence = get_record('framework_evidence', 'annotation', $metadata->block);
1282
1283
1284
1285
                    if (!empty($evidence)) {
                        // we are dealing with an annotation added since smartevidence was added
                        $defaultval = $evidence->state;

1286
                        if ($options = Framework::get_my_assessment_options_for_user($view, $evidence->framework)) {
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
                            if (!array_key_exists($defaultval, $options)) {
                                $defaultval = null;
                            }
                            $form['elements']['assessment'] = array(
                                'type' => 'select',
                                'title' => get_string('assessment', 'module.framework'),
                                'options' => $options,
                                'defaultvalue' => $defaultval,
                                'width' => '280px',
                            );

                            $form['elements']['evidence'] = array(
                                'type' => 'hidden',
                                'value' => $evidence->id,
                            );
1302
                        }
1303
1304
1305
1306
                    }
                }
            }
        }
1307

1308
        $form['elements']['ispublic'] = array(
1309
            'type'  => 'switchbox',
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
            'title' => get_string('makepublic', 'artefact.annotation'),
            'defaultvalue' => !$defaultprivate,
        );

        // What is this annotation feedback linked to? Store it in hidden fields.
        $form['elements']['viewid'] = array(
            'type'  => 'hidden',
            'value' => (isset($view) ? $view->get('id') : null),
        );
        $form['elements']['artefactid'] = array(
            'type'  => 'hidden',
            'value' => (isset($artefact) ? $artefact->get('id') : null),
        );
        // Save the artefactid of the annotation.
        $form['elements']['annotationid'] = array(
            'type'  => 'hidden',
            'value' => $annotation->get('id'),
        );
        $form['elements']['blockid'] = array(
            'type'  => 'hidden',
            'value' => $blockid,
        );

        if ($moderate) {
            $form['elements']['ispublic']['description'] = get_string('approvalrequired', 'artefact.annotation');
            $form['elements']['moderate'] = array(
                'type'  => 'hidden',
                'value' => true,
            );
        }
        $form['elements']['submit'] = array(
            'type'  => 'submitcancel',
1342
            'class' => 'btn-default',
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
            'value' => array(get_string('placeannotationfeedback', 'artefact.annotation'), get_string('cancel')),
            'goto' => '/' . $view->get_url(false),
        );
        return $form;
    }

    public static function make_annotation_feedback_public_form($annotationid, $viewid, $artefactid, $blockid, $id) {
        return array(
            'name'              => 'make_annotation_feedback_public_' . $id,
            'method'            => 'post',
            'autofocus'         => false,
1354
1355
            'renderer'          => 'div',
            'class'            => 'form-as-button',
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
            'plugintype'        => 'artefact',
            'pluginname'        => 'annotation',
            'jsform'            => true,
            'successcallback'   => 'make_annotation_feedback_public_submit',
            'validatecallback'  => 'make_annotation_feedback_public_validate',
            'jssuccesscallback' => 'modifyAnnotationFeedbackSuccess',
            'elements'        => array(
                'annotationfeedbackid' => array('type' => 'hidden', 'value' => $id),
                'annotationid' => array('type' => 'hidden', 'value' => $annotationid),
                'viewid' => array('type' => 'hidden', 'value' => $viewid),
                'artefactid' => array('type' => 'hidden', 'value' => $artefactid),
                'blockid' => array('type' => 'hidden', 'value' => $blockid),
                'submit'   => array(
1369
1370
                    'type'  => 'button',
                    'usebuttontag' => true,
1371
                    'class' => 'btn-link btn-xs quiet',
1372
                    'name'  => 'make_annotation_feedback_public_submit',
1373
                    'value' => '<span class="icon icon-lock text-default left" role="presentation" aria-hidden="true"></span>' . get_string('makepublic', 'artefact.annotation'),
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
                ),
            ),
        );
    }

    public static function delete_annotation_feedback_form($annotationid, $viewid, $artefactid, $blockid, $id) {
        global $THEME;
        return array(
            'name'              => 'delete_annotation_feedback_' . $id,
            'method'            => 'post',
            'autofocus'         => false,
            'renderer'          => 'oneline',
            'plugintype'        => 'artefact',
            'pluginname'        => 'annotation',
1388
            'class' => 'form-as-button pull-left delete-comment btn-group-item',
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
            'jsform'            => true,
            'successcallback'   => 'delete_annotation_feedback_submit',
            'jssuccesscallback' => 'modifyAnnotationFeedbackSuccess',
            'elements' => array(
                'annotationfeedbackid' => array('type' => 'hidden', 'value' => $id),
                'annotationid' => array('type' => 'hidden', 'value' => $annotationid),
                'viewid' => array('type' => 'hidden', 'value' => $viewid),
                'artefactid' => array('type' => 'hidden', 'value' => $artefactid),
                'blockid' => array('type' => 'hidden', 'value' => $blockid),
                'submit'  => array(
1399
1400
                    'type'  => 'button',
                    'usebuttontag' => true,
1401
                    'class' => 'btn-default btn-sm',
1402
                    'value' => '<span class="icon icon-trash text-danger" role="presentation" aria-hidden="true"></span><span class="sr-only">' . get_string('delete') . '</span>',
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
                    'elementtitle' => get_string('delete'),
                    'confirm' => get_string('reallydeletethisannotationfeedback', 'artefact.annotation'),
                    'name'  => 'delete_annotation_feedback_submit',
                ),
            ),
        );
    }

    public function exportable() {
        return empty($this->deletedby);
    }

    // Check whether the logged-in user can see a comment within the
    // context of a given view.  Does not check whether the user can
    // view the view.
    public function viewable_in($viewid) {
        global $USER;
        if ($this->get('deletedby')) {
            return false;
        }

        if ($USER->is_logged_in()) {
            if ($USER->can_view_artefact($this)) {
                return true;
            }
            if ($this->get('author') == $USER->get('id')) {
                return true;
            }
        }

        if ($this->get('private')) {
            return false;
        }

        if ($onview = $this->get('onview')) {
            return $onview == $viewid;
        }

        if ($onartefact = $this->get('onartefact')) {
            return artefact_in_view($onartefact, $viewid);
        }

        return false;
    }
}

/**
 * To make private annotations public, both the author and the owner must agree.
 * @param Pieform $form
 * @param array $values data entered on pieform.
 */
function make_annotation_feedback_public_validate(Pieform $form, $values) {
    global $USER;
    $annotationfeedback = new ArtefactTypeAnnotationFeedback((int) $values['annotationfeedbackid']);

    if (!empty($values['viewid']) && !can_view_view($values['viewid'])) {
        // The user does not access to this view.
        $form->set_error('annotationfeedbackid', get_string('noaccesstoview', 'view'));
    }

    $author    = $annotationfeedback->get('author');
    $owner     = $annotationfeedback->get('owner');
    $requester = $USER->get('id');
    $group     = $annotationfeedback->get('group');

    if (!$owner && !$group) {
        $form->set_error('annotationfeedbackid', get_string('makepublicnotallowed', 'artefact.annotation'));
    }
    else if (!$owner && $group) {
        if ($requester) {
            $allowed = false;
            // check to see if the requester is a group admin
            $group_admins = group_get_admin_ids($group);
            if (array_search($requester,$group_admins) === false) {
                $form->set_error('annotationfeedbackid', get_string('makepublicnotallowed', 'artefact.annotation'));
            }
        }
        else {
            $form->set_error('annotationfeedbackid', get_string('makepublicnotallowed', 'artefact.annotation'));
        }
    }
    else if (!$owner || !$requester || ($requester != $owner && $requester != $author)) {
        $form->set_error('annotationfeedbackid', get_string('makepublicnotallowed', 'artefact.annotation'));
    }
}

function make_annotation_feedback_public_submit(Pieform $form, $values) {
    global $USER;

    $annotationfeedback = new ArtefactTypeAnnotationFeedback((int) $values['annotationfeedbackid']);
    $annotationid = $annotationfeedback->get('onannotation');
    $annotation = new ArtefactTypeAnnotation((int) $annotationid);

    $viewid = $values['viewid'];
    $view = new View($viewid);

    $relativeurl = $annotation->get_view_url($viewid, true, false);
    $url = get_config('wwwroot') . $relativeurl;

    $author    = $annotationfeedback->get('author');
    $owner     = $annotationfeedback->get('owner');
    $groupid   = $annotationfeedback->get('group');
    $group_admins = array();
    if ($groupid) {
        $group_admins = group_get_admin_ids($groupid);
    }
    $requester = $USER->get('id');

    if (($author == $owner && $requester == $owner)
        || ($requester == $owner  && $annotationfeedback->get('requestpublic') == 'author')
        || (array_search($requester,$group_admins) !== false && $annotationfeedback->get('requestpublic') == 'author')
        || ($requester == $author && $annotationfeedback->get('requestpublic') == 'owner')) {
        $annotationfeedback->set('private', 0);
        $annotationfeedback->set('requestpublic', null);
        $annotationfeedback->commit();

        $form->reply(PIEFORM_OK, array(
            'message' => get_string('annotationfeedbackmadepublic', 'artefact.annotation'),
            'goto'    => $url,
        ));
    }

    $subject = 'makepublicrequestsubject';
    if ($requester == $owner) {
        $annotationfeedback->set('requestpublic', 'owner');
        $message = 'makepublicrequestbyownermessage';
        $arg = display_name($owner, $author);
        $userid = $author;
        $sessionmessage = get_string('makepublicrequestsent', 'artefact.annotation', display_name($author));
    }
    else if ($requester == $author) {
        $annotationfeedback->set('requestpublic', 'author');
        $message = 'makepublicrequestbyauthormessage';
        $arg = display_name($author, $owner);
        $userid = $owner;
        $sessionmessage = get_string('makepublicrequestsent', 'artefact.annotation', display_name($owner));
    }
    else if (array_search($requester,$group_admins) !== false) {
        $annotationfeedback->set('requestpublic', 'owner');
        $message = 'makepublicrequestbyownermessage';
        $arg = display_name($requester, $author);
        $userid = $author;
        $sessionmessage = get_string('makepublicrequestsent', 'artefact.annotation', display_name($author));
    }
    else {
        // Something is wrong. Go back to the view.
        redirect($url);
    }

    db_begin();
    $annotationfeedback->commit();

    $data = (object) array(
        'subject'   => false,
        'message'   => false,
        'strings'   => (object) array(
            'subject' => (object) array(
                'key'     => $subject,
                'section' => 'artefact.annotation',
                'args'    => array(),
            ),
            'message' => (object) array(
                'key'     => $message,
                'section' => 'artefact.annotation',
                'args'    => array(hsc($arg)),
            ),
            'urltext' => (object) array(
                'key'     => 'Annotation',
                'section' => 'artefact.annotation',
            ),
        ),
        'users'     => array($userid),
        'url'       => $relativeurl,
    );
    activity_occurred('maharamessage', $data);
    db_commit();

    $options = ArtefactTypeAnnotationfeedback::get_annotation_feedback_options();
    $options->showcomment = $annotationfeedback->get('id');
    $options->artefact = $values['artefactid'];
    $options->view = $viewid;
    $options->annotation = $annotationid;
    $options->block = $values['blockid'];
    $newlist = ArtefactTypeAnnotationfeedback::get_annotation_feedback($options);

    $form->reply(PIEFORM_OK, array(
        'message' => $sessionmessage,
        'goto'    => $url,
        'data'    => $newlist,
    ));

}

function delete_annotation_feedback_submit(Pieform $form, $values) {
    global $USER;

    $annotationfeedback = new ArtefactTypeAnnotationfeedback((int) $values['annotationfeedbackid']);
    $view = new View($values['viewid']);
    $annotationid = $annotationfeedback->get('onannotation');
    $annotation = new ArtefactTypeAnnotation((int) $annotationid);

    if ($USER->get('id') == $annotationfeedback->get('author')) {
        $deletedby = 'author';
    }
    else if ($USER->can_edit_view($view)) {
        $deletedby = 'owner';
    }
    else if ($USER->get('admin')) {
        $deletedby = 'admin';
    }

    $viewid = $view->get('id');
    if ($artefactid = $annotation->get('artefact')) {
        $url = 'artefact/artefact.php?view=' . $viewid . '&artefact=' . $artefactid;
    }
    else {
        $url = $view->get_url(false);
    }

1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
    // If this page is being marked, make annotation feedback un-deletable until released
    // unless it is the last fedback still with in the editable timeframe
    $editableafter = time() - 60 * get_config_plugin('artefact', 'annotation', 'commenteditabletime');
    $lastcomment = $annotationfeedback::last_public_annotation_feedback($annotationid, $viewid, null);
    if ($annotationfeedback->get('id') == $lastcomment->id && $annotationfeedback->get('mtime') > $editableafter) {
        $candelete = 1;
    }
    else {
        $candelete = 0;
    }
1632

1633
1634
    if ($view->get('submittedstatus') == View::UNSUBMITTED || $candelete) {
        db_begin();
1635

1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
        $annotationfeedback->set('deletedby', $deletedby);
        $annotationfeedback->commit();

        if ($deletedby != 'author') {
            // Notify author
            if ($artefactid) {
                $title = get_field('artefact', 'title', 'id', $artefactid);
            }
            else {
                $title = get_field('view', 'title', 'id', $viewid);
            }
            $title = hsc($title);
            $data = (object) array(
                'subject'   => false,
                'message'   => false,
                'strings'   => (object) array(
                    'subject' => (object) array(
                        'key'     => 'annotationfeedbackdeletednotificationsubject',
                        'section' => 'artefact.annotation',
                        'args'    => array($title),
                    ),
                    'message' => (object) array(
                        'key'     => 'annotationfeedbackdeletedauthornotification',
                        'section' => 'artefact.annotation',
                        'args'    => array($title, html2text($annotationfeedback->get('description'))),
                    ),
                    'urltext' => (object) array(
                        'key'     => $artefactid ? 'artefact' : 'view',
                    ),
1665
                ),
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
                'users'     => array($annotationfeedback->get('author')),
                'url'       => $url,
            );
            activity_occurred('maharamessage', $data);
        }
        if ($deletedby != 'owner' && $annotationfeedback->get('owner') != $USER->get('id')) {
            // Notify owner
            $data = (object) array(
                'annotationfeedbackid' => $annotationfeedback->get('id'),
                'annotationid'         => $annotationid,
                'viewid'               => $viewid,
                'artefactid'           => $artefactid,
            );
            activity_occurred('annotationfeedback', $data, 'artefact', 'annotation');
        }
1681

1682
1683
        db_commit();
    }
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748

    if (param_exists('offset')) {
        $options = ArtefactTypeAnnotationfeedback::get_annotation_feedback_options();
        $options->showcomment = $annotationfeedback->get('id');
        $options->artefact = $artefactid;
        $options->view = $viewid;
        $options->annotation = $annotationid;
        $options->block = $values['blockid'];
        $newlist = ArtefactTypeAnnotationfeedback::get_annotation_feedback($options);
    }
    else {
        $newlist = null;
    }

    $form->reply(PIEFORM_OK, array(
        'message' => get_string('annotationfeedbackremoved', 'artefact.annotation'),
        'goto'    => get_config('wwwroot') . $url,
        'data'    => $newlist,
    ));

}

function add_annotation_feedback_form_validate(Pieform $form, $values) {
    require_once(get_config('libroot') . 'antispam.php');

    if ($form->get_property('spam')) {
        $spamtrap = new_spam_trap(array(
            array(
                'type' => 'body',
                'value' => $values['message'],
            ),
        ));

        if ($form->spam_error() || $spamtrap->is_spam()) {
            $msg = get_string('formerror');
            $emailcontact = get_config('emailcontact');
            if (!empty($emailcontact)) {
                $msg .= ' ' . get_string('formerroremail', 'mahara', $emailcontact, $emailcontact);
            }
            $form->set_error('message', $msg);
        }
    }
    // Make sure that the user has not manipulated the ids.
    if (empty($values['artefactid']) && empty($values['viewid'])) {
        // One of them must have data.
        $form->set_error('message', get_string('invalidannotationfeedbacklinkerror', 'artefact.annotation'));
    }
    if (empty($values['annotationid'])) {
        $form->set_error('message', get_string('annotationinformationerror', 'artefact.annotation'));
    }
    if (!empty($values['viewid']) && !can_view_view($values['viewid'])) {
        // The user does not access to this view.
        $form->set_error('message', get_string('noaccesstoview', 'view'));
    }
    if (!empty($values['viewid']) &&
        !artefact_in_view($values['annotationid'], $values['viewid'])) {
        // The annotation is not on the view.
        $form->set_error('message', get_string('accessdenied', 'error'));
    }
    if (!empty($values['artefactid']) && !empty($values['viewid']) &&
        !artefact_in_view($values['artefactid'], $values['viewid'])) {
        // The artefact is not on the view.
        $form->set_error('message', get_string('accessdenied', 'error'));
    }

1749
1750
1751
1752
1753
1754
1755
1756
1757
    $elements = $form->get_property('elements');
    $assessmentchanged = false;
    if (isset($elements['assessment']) && isset($elements['assessment']['defaultvalue'])) {
        if ((int) $values['assessment'] !== (int) $elements['assessment']['defaultvalue']) {
            $assessmentchanged = true;
        }
    }
    // Only error on feedback if we are not changing assessment
    if (empty($values['message']) && !$assessmentchanged) {
1758
1759
1760
1761
1762
        $form->set_error('message', get_string('annotationfeedbackempty', 'artefact.annotation'));
    }

    $result = probation_validate_content($values['message']);
    if ($result !== true) {
1763
        $form->set_error('message', get_string('newuserscantpostlinksorimages1'));
1764
1765
1766
1767
    }
}

function add_annotation_feedback_form_submit(Pieform $form, $values) {
1768

1769
    global $USER;
1770

1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
    $data = (object) array(
        'title'        => get_string('Annotation', 'artefact.annotation'),
        'description'  => $values['message'],
        'onannotation' => $values['annotationid'],
    );

    // hidden fields.
    $artefactid = $values['artefactid'];
    $viewid = $values['viewid'];
    $blockid = $values['blockid'];

    if ($artefactid) {
        $artefact = artefact_instance_from_id($artefactid);
        $data->artefact    = $artefactid;
        $data->owner       = $artefact->get('owner');
        $data->group       = $artefact->get('group');
        $data->institution = $artefact->get('institution');
    }
    else if ($viewid) {
        $view = new View($viewid);
        $data->view        = $viewid;
        $data->owner       = $view->get('owner');
        $data->group       = $view->get('group');
        $data->institution = $view->get('institution');
    }

    if ($author = $USER->get('id')) {
        $anonymous = false;
        $data->author = $author;
    }
    else {
        $anonymous = true;
        $data->authorname = $values['authorname'];
    }

    if (isset($values['moderate']) && $values['ispublic'] && !$USER->can_edit_view($view)) {
        $data->private = 1;
        $data->requestpublic = 'author';
        $moderated = true;
    }
    else {
        $data->private = (int) !$values['ispublic'];
        $moderated = false;
    }
    $private = $data->private;

    $annotationfeedback = new ArtefactTypeAnnotationfeedback(0, $data);
    $annotation = new ArtefactTypeAnnotation($values['annotationid']);

    db_begin();

    $annotationfeedback->commit();
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
    if (!empty($values['evidence']) && !empty($values['assessment'])) {
        $reviewer = null;
        if ((int) $values['assessment'] === Framework::EVIDENCE_COMPLETED) {
            $reviewer = $USER->get('id');
        }
        $fordb = array('mtime' => db_format_timestamp(time()),
                       'state' => $values['assessment'],
                       'reviewer' => $reviewer,
        );
        // update row
        update_record('framework_evidence', (object) $fordb, (object) array('id' => $values['evidence']));
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
        $framework = get_field('framework_evidence', 'framework', 'id', $values['evidence']);
        // check if assessment status changed
        $elements = $form->get_property('elements');
        $assessmentchanged = false;
        if (isset($elements['assessment']) && isset($elements['assessment']['defaultvalue'])) {
            if ((int) $values['assessment'] !== (int) $elements['assessment']['defaultvalue']) {
                // We need to log this assessment change
                insert_record('framework_assessment_feedback', (object) array('framework' => $framework,
                                                                              'artefact' => $annotationfeedback->get('id'),
                                                                              'oldstatus' => $elements['assessment']['defaultvalue'],
                                                                              'newstatus' => $values['assessment'],
                                                                              'usr' => $USER->get('id')));
            }
        }
1848
    }
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020

    $url = $annotation->get_view_url($view->get('id'), true, false);
    $goto = get_config('wwwroot') . $url;

    if (isset($data->requestpublic) && $data->requestpublic === 'author' && $data->owner) {
        $arg = $author ? display_name($USER, null, true) : $data->authorname;
        $moderatemsg = (object) array(
            'subject'   => false,
            'message'   => false,
            'strings'   => (object) array(
                'subject' => (object) array(
                    'key'     => 'makepublicrequestsubject',
                    'section' => 'artefact.annotation',
                    'args'    => array(),
                ),
                'message' => (object) array(
                    'key'     => 'makepublicrequestbyauthormessage',
                    'section' => 'artefact.annotation',
                    'args'    => array(hsc($arg)),
                ),
                'urltext' => (object) array(
                    'key'     => 'Annotation',
                    'section' => 'artefact.annotation',
                ),
            ),
            'users'     => array($data->owner),
            'url'       => $url,
        );
    }

    require_once('activity.php');
    $data = (object) array(
        'annotationfeedbackid' => $annotationfeedback->get('id'),
        'annotationid'         => $values['annotationid'],
        'viewid'               => $viewid,
        'artefactid'           => $artefactid,
    );
    activity_occurred('annotationfeedback', $data, 'artefact', 'annotation');

    if (isset($moderatemsg)) {
        activity_occurred('maharamessage', $moderatemsg);
    }

    db_commit();

    if (param_exists('offset')) {
        $options = ArtefactTypeAnnotationfeedback::get_annotation_feedback_options();
        $options->showcomment = 'last';
        $options->artefact = $artefactid;
        $options->view = $viewid;
        $options->annotation = $values['annotationid'];
        $options->block = $blockid;
        $newlist = ArtefactTypeAnnotationfeedback::get_annotation_feedback($options);
    }
    else {
        $newlist = null;
    }

    // If you're anonymous and your message is moderated or private, then you won't
    // be able to tell what happened to it. So we'll provide some more explanation in
    // the feedback message.
    if ($anonymous && $moderated) {
        $message = get_string('annotationfeedbacksubmittedmoderatedanon', 'artefact.annotation');
    }
    else if ($anonymous && $private) {
        $message = get_string('annotationfeedbacksubmittedprivateanon', 'artefact.annotation');
    }
    else {
        $message = get_string('annotationfeedbacksubmitted', 'artefact.annotation');
    }

    $form->reply(PIEFORM_OK, array(
        'message' => $message,
        'goto'    => $goto,
        'data'    => $newlist,
    ));
}

/**
 * Class to handle the annotationfeedback event for annotations.
 *
 */
class ActivityTypeArtefactAnnotationAnnotationfeedback extends ActivityTypePlugin {

    protected $annotationfeedbackid;
    protected $annotationid;
    protected $viewid;
    protected $artefactid;

    /**
     * @param array $data Parameters:
     *                    - viewid (int)
     *                    - annotationid (int)
     */
    public function __construct($data, $cron=false) {
        parent::__construct($data, $cron);

        $annotation = new ArtefactTypeAnnotation($this->annotationid);
        $annotationfeedback = new ArtefactTypeAnnotationfeedback($this->annotationfeedbackid);

        $this->overridemessagecontents = true;

        if ($onartefact = $annotation->get('artefact')) {
            // Feedback on artefact.
            $userid = null;
            require_once(get_config('docroot') . 'artefact/lib.php');
            $artefactinstance = artefact_instance_from_id($onartefact);
            if ($artefactinstance->feedback_notify_owner()) {
                $userid = $artefactinstance->get('owner');
                $groupid = $artefactinstance->get('group');
                $institutionid = $artefactinstance->get('institution');
            }
            if (empty($this->url)) {
                $this->url = 'artefact/artefact.php?artefact=' . $onartefact . '&view=' . $this->viewid;
            }
        }
        else if ($onview = $annotation->get('view')) {
            // Feedback on view.
            if (!$viewrecord = get_record('view', 'id', $onview)) {
                throw new ViewNotFoundException(get_string('viewnotfound', 'error', $onview));
            }
            $userid = $viewrecord->owner;
            $groupid = $viewrecord->group;
            $institutionid =  $viewrecord->institution;
            if (empty($this->url)) {
                $this->url = 'view/view.php?id=' . $onview;
            }
        }
        else {
            // Something is wrong.
            throw new ViewNotFoundException(get_string('invalidannotationfeedbacklinkerror', 'artefact.annotation'));
        }

        // Now fetch the users that will need to get notified about this event
        // depending on whether the page has an owner, group, or institution id set.
        if (!empty($userid)) {
            $this->users = activity_get_users($this->get_id(), array($userid));
        }
        else if (!empty($groupid)) {
            require_once(get_config('docroot') . 'lib/group.php');
            $sql = "SELECT u.*
                    FROM {usr} u, {group_member} m, {group} g
                    WHERE g.id = m.group
                    AND m.member = u.id
                    AND m.group = ?
                    AND (g.feedbacknotify = " . GROUP_ROLES_ALL . "
                         OR (g.feedbacknotify = " . GROUP_ROLES_NONMEMBER . " AND (m.role = 'tutor' OR m.role = 'admin'))
                         OR (g.feedbacknotify = " . GROUP_ROLES_ADMIN . " AND m.role = 'admin')
                        )";
            $this->users = get_records_sql_array($sql, array($groupid));
        }
        else if (!empty($institutionid)) {
            require_once(get_config('libroot') .'institution.php');
            $institution = new Institution($institutionid);
            $admins = $institution->institution_and_site_admins();
            $this->users = get_records_sql_array("SELECT * FROM {usr} WHERE id IN (" . implode(',', $admins) . ")", array());
        }

        if (empty($this->users)) {
            // no one to notify - possibe if group 'feedbacknotify' is set to 0
            return;
        }

        $title = $onartefact ? $artefactinstance->get('title') : $viewrecord->title;
        $this->urltext = $title;
        $body = $annotationfeedback->get('description');
        $posttime = strftime(get_string('strftimedaydatetime'), $annotationfeedback->get('ctime'));

        // Internal
        $this->message = strip_tags(str_shorten_html($body, 200, true));
        // Seen as things like emaildigest base the message on $this->message
        // we need to set the language for the $removedbyline here based on first user.
2021
2022
        $firstuser = key($this->users);
        $user = $this->users[$firstuser];
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
        $lang = (empty($user->lang) || $user->lang == 'default') ? get_config('lang') : $user->lang;

        // Comment deleted notification
        if ($deletedby = $annotationfeedback->get('deletedby')) {
            $this->strings = (object) array(
                'subject' => (object) array(
                    'key'     => 'annotationfeedbackdeletednotificationsubject',
                    'section' => 'artefact.annotation',
                    'args'    => array($title),
                ),
            );
            $deletedmessage = ArtefactTypeAnnotationfeedback::deleted_by_types_description();
            $removedbyline = get_string_from_language($lang, $deletedmessage[$deletedby], 'artefact.annotation');
            $this->message = $removedbyline . ":\n" . $this->message;

            foreach ($this->users as $key => $user) {
                if (empty($user->lang) || $user->lang == 'default') {
                    // check to see if we need to show institution language
                    $instlang = get_user_institution_language($user->id);
                    $lang = (empty($instlang) || $instlang == 'default') ? get_config('lang') : $instlang;
                }
                else {
                    $lang = $user->lang;
                }
                // For email we can send the message in the user's preferred language
                $removedbyline = get_string_from_language($lang, $deletedmessage[$deletedby], 'artefact.annotation');
                $this->users[$key]->htmlmessage = get_string_from_language(
                    $lang, 'annotationfeedbackdeletedhtml', 'artefact.annotation',
                    hsc($title), $removedbyline, clean_html($body), get_config('wwwroot') . $this->url, hsc($title)
                );
                $this->users[$key]->emailmessage = get_string_from_language(
                    $lang, 'annotationfeedbackdeletedtext', 'artefact.annotation',
                    $title, $removedbyline, trim(html2text(htmlspecialchars($body))), $title, get_config('wwwroot') . $this->url
                );
            }
            return;
        }

        $this->strings = (object) array(
            'subject' => (object) array(
                'key'     => 'newannotationfeedbacknotificationsubject',
                'section' => 'artefact.annotation',
                'args'    => array($title),
            ),
        );

        $this->url .= '&showcomment=' . $annotationfeedback->get('id');

        // Email
        $author = $annotationfeedback->get('author');
        foreach ($this->users as $key => $user) {
            $authorname = empty($author) ? $annotationfeedback->get('authorname') : display_name($author, $user);
            if (empty($user->lang) || $user->lang == 'default') {
                // check to see if we need to show institution language
                $instlang = get_user_institution_language($user->id);
                $lang = (empty($instlang) || $instlang == 'default') ? get_config('lang') : $instlang;
            }
            else {
                $lang = $user->lang;
            }
            $this->users[$key]->htmlmessage = get_string_from_language(
                $lang, 'annotationfeedbacknotificationhtml', 'artefact.annotation',
                hsc($authorname), hsc($title), $posttime, clean_html($body), get_config('wwwroot') . $this->url
            );
            $this->users[$key]->emailmessage = get_string_from_language(
                $lang, 'annotationfeedbacknotificationtext', 'artefact.annotation',
                $authorname, $title, $posttime, trim(html2text(htmlspecialchars($body))), get_config('wwwroot') . $this->url
            );
        }
    }

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

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

    public function get_required_parameters() {
        return array('annotationfeedbackid', 'annotationid');
    }
}