Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library of functions and constants for module feedback
19
 * includes the main-part of feedback-functions
20
 *
21
 * @package mod_feedback
22
 * @copyright Andreas Grabs
23
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
defined('MOODLE_INTERNAL') || die();
27
 
28
// Include forms lib.
29
require_once($CFG->libdir.'/formslib.php');
30
 
31
define('FEEDBACK_ANONYMOUS_YES', 1);
32
define('FEEDBACK_ANONYMOUS_NO', 2);
33
define('FEEDBACK_MIN_ANONYMOUS_COUNT_IN_GROUP', 2);
34
define('FEEDBACK_DECIMAL', '.');
35
define('FEEDBACK_THOUSAND', ',');
36
define('FEEDBACK_RESETFORM_RESET', 'feedback_reset_data_');
37
define('FEEDBACK_RESETFORM_DROP', 'feedback_drop_feedback_');
38
define('FEEDBACK_MAX_PIX_LENGTH', '400'); //max. Breite des grafischen Balkens in der Auswertung
39
define('FEEDBACK_DEFAULT_PAGE_COUNT', 20);
40
 
41
// Event types.
42
define('FEEDBACK_EVENT_TYPE_OPEN', 'open');
43
define('FEEDBACK_EVENT_TYPE_CLOSE', 'close');
44
 
45
require_once(__DIR__ . '/deprecatedlib.php');
46
 
47
/**
48
 * @uses FEATURE_GROUPS
49
 * @uses FEATURE_GROUPINGS
50
 * @uses FEATURE_MOD_INTRO
51
 * @uses FEATURE_COMPLETION_TRACKS_VIEWS
52
 * @uses FEATURE_GRADE_HAS_GRADE
53
 * @uses FEATURE_GRADE_OUTCOMES
54
 * @param string $feature FEATURE_xx constant for requested feature
55
 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
56
 */
57
function feedback_supports($feature) {
58
    switch($feature) {
59
        case FEATURE_GROUPS:                  return true;
60
        case FEATURE_GROUPINGS:               return true;
61
        case FEATURE_MOD_INTRO:               return true;
62
        case FEATURE_COMPLETION_TRACKS_VIEWS: return true;
63
        case FEATURE_COMPLETION_HAS_RULES:    return true;
64
        case FEATURE_GRADE_HAS_GRADE:         return false;
65
        case FEATURE_GRADE_OUTCOMES:          return false;
66
        case FEATURE_BACKUP_MOODLE2:          return true;
67
        case FEATURE_SHOW_DESCRIPTION:        return true;
68
        case FEATURE_MOD_PURPOSE:             return MOD_PURPOSE_COMMUNICATION;
69
 
70
        default: return null;
71
    }
72
}
73
 
74
/**
75
 * this will create a new instance and return the id number
76
 * of the new instance.
77
 *
78
 * @global object
79
 * @param object $feedback the object given by mod_feedback_mod_form
80
 * @return int
81
 */
82
function feedback_add_instance($feedback) {
83
    global $DB;
84
 
85
    $feedback->timemodified = time();
86
    $feedback->id = '';
87
 
88
    if (empty($feedback->site_after_submit)) {
89
        $feedback->site_after_submit = '';
90
    }
91
 
92
    //saving the feedback in db
93
    $feedbackid = $DB->insert_record("feedback", $feedback);
94
 
95
    $feedback->id = $feedbackid;
96
 
97
    feedback_set_events($feedback);
98
 
99
    if (!isset($feedback->coursemodule)) {
100
        $cm = get_coursemodule_from_id('feedback', $feedback->id);
101
        $feedback->coursemodule = $cm->id;
102
    }
103
    $context = context_module::instance($feedback->coursemodule);
104
 
105
    if (!empty($feedback->completionexpected)) {
106
        \core_completion\api::update_completion_date_event($feedback->coursemodule, 'feedback', $feedback->id,
107
                $feedback->completionexpected);
108
    }
109
 
110
    $editoroptions = feedback_get_editor_options();
111
 
112
    // process the custom wysiwyg editor in page_after_submit
113
    if ($draftitemid = $feedback->page_after_submit_editor['itemid']) {
114
        $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id,
115
                                                    'mod_feedback', 'page_after_submit',
116
                                                    0, $editoroptions,
117
                                                    $feedback->page_after_submit_editor['text']);
118
 
119
        $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format'];
120
    }
121
    $DB->update_record('feedback', $feedback);
122
 
123
    return $feedbackid;
124
}
125
 
126
/**
127
 * this will update a given instance
128
 *
129
 * @global object
130
 * @param object $feedback the object given by mod_feedback_mod_form
131
 * @return boolean
132
 */
133
function feedback_update_instance($feedback) {
134
    global $DB;
135
 
136
    $feedback->timemodified = time();
137
    $feedback->id = $feedback->instance;
138
 
139
    if (empty($feedback->site_after_submit)) {
140
        $feedback->site_after_submit = '';
141
    }
142
 
143
    //save the feedback into the db
144
    $DB->update_record("feedback", $feedback);
145
 
146
    //create or update the new events
147
    feedback_set_events($feedback);
148
    $completionexpected = (!empty($feedback->completionexpected)) ? $feedback->completionexpected : null;
149
    \core_completion\api::update_completion_date_event($feedback->coursemodule, 'feedback', $feedback->id, $completionexpected);
150
 
151
    $context = context_module::instance($feedback->coursemodule);
152
 
153
    $editoroptions = feedback_get_editor_options();
154
 
155
    // process the custom wysiwyg editor in page_after_submit
156
    if ($draftitemid = $feedback->page_after_submit_editor['itemid']) {
157
        $feedback->page_after_submit = file_save_draft_area_files($draftitemid, $context->id,
158
                                                    'mod_feedback', 'page_after_submit',
159
                                                    0, $editoroptions,
160
                                                    $feedback->page_after_submit_editor['text']);
161
 
162
        $feedback->page_after_submitformat = $feedback->page_after_submit_editor['format'];
163
    }
164
    $DB->update_record('feedback', $feedback);
165
 
166
    return true;
167
}
168
 
169
/**
170
 * Serves the files included in feedback items like label. Implements needed access control ;-)
171
 *
172
 * There are two situations in general where the files will be sent.
173
 * 1) filearea = item, 2) filearea = template
174
 *
175
 * @package  mod_feedback
176
 * @category files
177
 * @param stdClass $course course object
178
 * @param stdClass $cm course module object
179
 * @param stdClass $context context object
180
 * @param string $filearea file area
181
 * @param array $args extra arguments
182
 * @param bool $forcedownload whether or not force download
183
 * @param array $options additional options affecting the file serving
184
 * @return bool false if file not found, does not return if found - justsend the file
185
 */
186
function feedback_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, array $options=array()) {
187
    global $CFG, $DB;
188
 
189
    if ($filearea === 'item' or $filearea === 'template') {
190
        $itemid = (int)array_shift($args);
191
        //get the item what includes the file
192
        if (!$item = $DB->get_record('feedback_item', array('id'=>$itemid))) {
193
            return false;
194
        }
195
        $feedbackid = $item->feedback;
196
        $templateid = $item->template;
197
    }
198
 
199
    if ($filearea === 'page_after_submit' or $filearea === 'item') {
200
        if (! $feedback = $DB->get_record("feedback", array("id"=>$cm->instance))) {
201
            return false;
202
        }
203
 
204
        $feedbackid = $feedback->id;
205
 
206
        //if the filearea is "item" so we check the permissions like view/complete the feedback
207
        $canload = false;
208
        //first check whether the user has the complete capability
209
        if (has_capability('mod/feedback:complete', $context)) {
210
            $canload = true;
211
        }
212
 
213
        //now we check whether the user has the view capability
214
        if (has_capability('mod/feedback:view', $context)) {
215
            $canload = true;
216
        }
217
 
218
        //if the feedback is on frontpage and anonymous and the fullanonymous is allowed
219
        //so the file can be loaded too.
220
        if (isset($CFG->feedback_allowfullanonymous)
221
                    AND $CFG->feedback_allowfullanonymous
222
                    AND $course->id == SITEID
223
                    AND $feedback->anonymous == FEEDBACK_ANONYMOUS_YES ) {
224
            $canload = true;
225
        }
226
 
227
        if (!$canload) {
228
            return false;
229
        }
230
    } else if ($filearea === 'template') { //now we check files in templates
231
        if (!$template = $DB->get_record('feedback_template', array('id'=>$templateid))) {
232
            return false;
233
        }
234
 
235
        //if the file is not public so the capability edititems has to be there
236
        if (!$template->ispublic) {
237
            if (!has_capability('mod/feedback:edititems', $context)) {
238
                return false;
239
            }
240
        } else { //on public templates, at least the user has to be logged in
241
            if (!isloggedin()) {
242
                return false;
243
            }
244
        }
245
    } else {
246
        return false;
247
    }
248
 
249
    if ($context->contextlevel == CONTEXT_MODULE) {
250
        if ($filearea !== 'item' and $filearea !== 'page_after_submit') {
251
            return false;
252
        }
253
    }
254
 
255
    if ($context->contextlevel == CONTEXT_COURSE || $context->contextlevel == CONTEXT_SYSTEM) {
256
        if ($filearea !== 'template') {
257
            return false;
258
        }
259
    }
260
 
261
    $relativepath = implode('/', $args);
262
    if ($filearea === 'page_after_submit') {
263
        $fullpath = "/{$context->id}/mod_feedback/$filearea/$relativepath";
264
    } else {
265
        $fullpath = "/{$context->id}/mod_feedback/$filearea/{$item->id}/$relativepath";
266
    }
267
 
268
    $fs = get_file_storage();
269
 
270
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
271
        return false;
272
    }
273
 
274
    // finally send the file
275
    send_stored_file($file, 0, 0, true, $options); // download MUST be forced - security!
276
 
277
    return false;
278
}
279
 
280
/**
281
 * this will delete a given instance.
282
 * all referenced data also will be deleted
283
 *
284
 * @global object
285
 * @param int $id the instanceid of feedback
286
 * @return boolean
287
 */
288
function feedback_delete_instance($id) {
289
    global $DB;
290
 
291
    //get all referenced items
292
    $feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$id));
293
 
294
    //deleting all referenced items and values
295
    if (is_array($feedbackitems)) {
296
        foreach ($feedbackitems as $feedbackitem) {
297
            $DB->delete_records("feedback_value", array("item"=>$feedbackitem->id));
298
            $DB->delete_records("feedback_valuetmp", array("item"=>$feedbackitem->id));
299
        }
300
        if ($delitems = $DB->get_records("feedback_item", array("feedback"=>$id))) {
301
            foreach ($delitems as $delitem) {
302
                feedback_delete_item($delitem->id, false);
303
            }
304
        }
305
    }
306
 
307
    //deleting the completeds
308
    $DB->delete_records("feedback_completed", array("feedback"=>$id));
309
 
310
    //deleting the unfinished completeds
311
    $DB->delete_records("feedback_completedtmp", array("feedback"=>$id));
312
 
313
    //deleting old events
314
    $DB->delete_records('event', array('modulename'=>'feedback', 'instance'=>$id));
315
    return $DB->delete_records("feedback", array("id"=>$id));
316
}
317
 
318
/**
319
 * Return a small object with summary information about what a
320
 * user has done with a given particular instance of this module
321
 * Used for user activity reports.
322
 * $return->time = the time they did it
323
 * $return->info = a short text description
324
 *
325
 * @param stdClass $course
326
 * @param stdClass $user
327
 * @param cm_info|stdClass $mod
328
 * @param stdClass $feedback
329
 * @return stdClass
330
 */
331
function feedback_user_outline($course, $user, $mod, $feedback) {
332
    global $DB;
333
    $outline = (object)['info' => '', 'time' => 0];
334
    if ($feedback->anonymous != FEEDBACK_ANONYMOUS_NO) {
335
        // Do not disclose any user info if feedback is anonymous.
336
        return $outline;
337
    }
338
    $params = array('userid' => $user->id, 'feedback' => $feedback->id,
339
        'anonymous_response' => FEEDBACK_ANONYMOUS_NO);
340
    $status = null;
341
    $context = context_module::instance($mod->id);
342
    if ($completed = $DB->get_record('feedback_completed', $params)) {
343
        // User has completed feedback.
344
        $outline->info = get_string('completed', 'feedback');
345
        $outline->time = $completed->timemodified;
346
    } else if ($completedtmp = $DB->get_record('feedback_completedtmp', $params)) {
347
        // User has started but not completed feedback.
348
        $outline->info = get_string('started', 'feedback');
349
        $outline->time = $completedtmp->timemodified;
350
    } else if (has_capability('mod/feedback:complete', $context, $user)) {
351
        // User has not started feedback but has capability to do so.
352
        $outline->info = get_string('not_started', 'feedback');
353
    }
354
 
355
    return $outline;
356
}
357
 
358
/**
359
 * Returns all users who has completed a specified feedback since a given time
360
 * many thanks to Manolescu Dorel, who contributed these two functions
361
 *
362
 * @global object
363
 * @global object
364
 * @global object
365
 * @global object
366
 * @uses CONTEXT_MODULE
367
 * @param array $activities Passed by reference
368
 * @param int $index Passed by reference
369
 * @param int $timemodified Timestamp
370
 * @param int $courseid
371
 * @param int $cmid
372
 * @param int $userid
373
 * @param int $groupid
374
 * @return void
375
 */
376
function feedback_get_recent_mod_activity(&$activities, &$index,
377
                                          $timemodified, $courseid,
378
                                          $cmid, $userid="", $groupid="") {
379
 
380
    global $CFG, $COURSE, $USER, $DB;
381
 
382
    if ($COURSE->id == $courseid) {
383
        $course = $COURSE;
384
    } else {
385
        $course = $DB->get_record('course', array('id'=>$courseid));
386
    }
387
 
388
    $modinfo = get_fast_modinfo($course);
389
 
390
    $cm = $modinfo->cms[$cmid];
391
 
392
    $sqlargs = array();
393
 
394
    $userfieldsapi = \core_user\fields::for_userpic();
395
    $userfields = $userfieldsapi->get_sql('u', false, '', 'useridagain', false)->selects;
396
    $sql = " SELECT fk . * , fc . * , $userfields
397
                FROM {feedback_completed} fc
398
                    JOIN {feedback} fk ON fk.id = fc.feedback
399
                    JOIN {user} u ON u.id = fc.userid ";
400
 
401
    if ($groupid) {
402
        $sql .= " JOIN {groups_members} gm ON  gm.userid=u.id ";
403
    }
404
 
405
    $sql .= " WHERE fc.timemodified > ?
406
                AND fk.id = ?
407
                AND fc.anonymous_response = ?";
408
    $sqlargs[] = $timemodified;
409
    $sqlargs[] = $cm->instance;
410
    $sqlargs[] = FEEDBACK_ANONYMOUS_NO;
411
 
412
    if ($userid) {
413
        $sql .= " AND u.id = ? ";
414
        $sqlargs[] = $userid;
415
    }
416
 
417
    if ($groupid) {
418
        $sql .= " AND gm.groupid = ? ";
419
        $sqlargs[] = $groupid;
420
    }
421
 
422
    if (!$feedbackitems = $DB->get_records_sql($sql, $sqlargs)) {
423
        return;
424
    }
425
 
426
    $cm_context = context_module::instance($cm->id);
427
 
428
    if (!has_capability('mod/feedback:view', $cm_context)) {
429
        return;
430
    }
431
 
432
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
433
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $cm_context);
434
    $groupmode       = groups_get_activity_groupmode($cm, $course);
435
 
436
    $aname = format_string($cm->name, true);
437
    foreach ($feedbackitems as $feedbackitem) {
438
        if ($feedbackitem->userid != $USER->id) {
439
 
440
            if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
441
                $usersgroups = groups_get_all_groups($course->id,
442
                                                     $feedbackitem->userid,
443
                                                     $cm->groupingid);
444
                if (!is_array($usersgroups)) {
445
                    continue;
446
                }
447
                $usersgroups = array_keys($usersgroups);
448
                $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
449
                if (empty($intersect)) {
450
                    continue;
451
                }
452
            }
453
        }
454
 
455
        $tmpactivity = new stdClass();
456
 
457
        $tmpactivity->type      = 'feedback';
458
        $tmpactivity->cmid      = $cm->id;
459
        $tmpactivity->name      = $aname;
460
        $tmpactivity->sectionnum= $cm->sectionnum;
461
        $tmpactivity->timestamp = $feedbackitem->timemodified;
462
 
463
        $tmpactivity->content = new stdClass();
464
        $tmpactivity->content->feedbackid = $feedbackitem->id;
465
        $tmpactivity->content->feedbackuserid = $feedbackitem->userid;
466
 
467
        $tmpactivity->user = user_picture::unalias($feedbackitem, null, 'useridagain');
468
        $tmpactivity->user->fullname = fullname($feedbackitem, $viewfullnames);
469
 
470
        $activities[$index++] = $tmpactivity;
471
    }
472
 
473
    return;
474
}
475
 
476
/**
477
 * Prints all users who has completed a specified feedback since a given time
478
 * many thanks to Manolescu Dorel, who contributed these two functions
479
 *
480
 * @global object
481
 * @param object $activity
482
 * @param int $courseid
483
 * @param string $detail
484
 * @param array $modnames
485
 * @return void Output is echo'd
486
 */
487
function feedback_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
488
    global $CFG, $OUTPUT;
489
 
490
    echo '<table border="0" cellpadding="3" cellspacing="0" class="forum-recent">';
491
 
492
    echo "<tr><td class=\"userpicture align-top\">";
493
    echo $OUTPUT->user_picture($activity->user, array('courseid'=>$courseid));
494
    echo "</td><td>";
495
 
496
    if ($detail) {
497
        $modname = $modnames[$activity->type];
498
        echo '<div class="title">';
499
        echo $OUTPUT->image_icon('monologo', $modname, $activity->type);
500
        echo "<a href=\"$CFG->wwwroot/mod/feedback/view.php?id={$activity->cmid}\">{$activity->name}</a>";
501
        echo '</div>';
502
    }
503
 
504
    echo '<div class="title">';
505
    echo '</div>';
506
 
507
    echo '<div class="user">';
508
    echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">"
509
         ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
510
    echo '</div>';
511
 
512
    echo "</td></tr></table>";
513
 
514
    return;
515
}
516
 
517
/**
518
 * Print a detailed representation of what a  user has done with
519
 * a given particular instance of this module, for user activity reports.
520
 *
521
 * @param stdClass $course
522
 * @param stdClass $user
523
 * @param cm_info|stdClass $mod
524
 * @param stdClass $feedback
525
 */
526
function feedback_user_complete($course, $user, $mod, $feedback) {
527
    global $DB;
528
    if ($feedback->anonymous != FEEDBACK_ANONYMOUS_NO) {
529
        // Do not disclose any user info if feedback is anonymous.
530
        return;
531
    }
532
    $params = array('userid' => $user->id, 'feedback' => $feedback->id,
533
        'anonymous_response' => FEEDBACK_ANONYMOUS_NO);
534
    $url = $status = null;
535
    $context = context_module::instance($mod->id);
536
    if ($completed = $DB->get_record('feedback_completed', $params)) {
537
        // User has completed feedback.
538
        if (has_capability('mod/feedback:viewreports', $context)) {
539
            $url = new moodle_url('/mod/feedback/show_entries.php',
540
                ['id' => $mod->id, 'userid' => $user->id,
541
                    'showcompleted' => $completed->id]);
542
        }
543
        $status = get_string('completedon', 'feedback', userdate($completed->timemodified));
544
    } else if ($completedtmp = $DB->get_record('feedback_completedtmp', $params)) {
545
        // User has started but not completed feedback.
546
        $status = get_string('startedon', 'feedback', userdate($completedtmp->timemodified));
547
    } else if (has_capability('mod/feedback:complete', $context, $user)) {
548
        // User has not started feedback but has capability to do so.
549
        $status = get_string('not_started', 'feedback');
550
    }
551
 
552
    if ($url && $status) {
553
        echo html_writer::link($url, $status);
554
    } else if ($status) {
555
        echo html_writer::div($status);
556
    }
557
}
558
 
559
/**
560
 * @return bool true
561
 */
562
function feedback_cron () {
563
    return true;
564
}
565
 
566
/**
567
 * @deprecated since Moodle 3.8
568
 */
569
function feedback_scale_used() {
570
    throw new coding_exception('feedback_scale_used() can not be used anymore. Plugins can implement ' .
571
        '<modname>_scale_used_anywhere, all implementations of <modname>_scale_used are now ignored');
572
}
573
 
574
/**
575
 * Checks if scale is being used by any instance of feedback
576
 *
577
 * This is used to find out if scale used anywhere
578
 * @param $scaleid int
579
 * @return boolean True if the scale is used by any assignment
580
 */
581
function feedback_scale_used_anywhere($scaleid) {
582
    return false;
583
}
584
 
585
/**
586
 * List the actions that correspond to a view of this module.
587
 * This is used by the participation report.
588
 *
589
 * Note: This is not used by new logging system. Event with
590
 *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
591
 *       be considered as view action.
592
 *
593
 * @return array
594
 */
595
function feedback_get_view_actions() {
596
    return array('view', 'view all');
597
}
598
 
599
/**
600
 * List the actions that correspond to a post of this module.
601
 * This is used by the participation report.
602
 *
603
 * Note: This is not used by new logging system. Event with
604
 *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
605
 *       will be considered as post action.
606
 *
607
 * @return array
608
 */
609
function feedback_get_post_actions() {
610
    return array('submit');
611
}
612
 
613
/**
614
 * This function is used by the reset_course_userdata function in moodlelib.
615
 * This function will remove all responses from the specified feedback
616
 * and clean up any related data.
617
 *
618
 * @global object
619
 * @global object
620
 * @uses FEEDBACK_RESETFORM_RESET
621
 * @uses FEEDBACK_RESETFORM_DROP
622
 * @param object $data the data submitted from the reset course.
623
 * @return array status array
624
 */
625
function feedback_reset_userdata($data) {
626
    global $CFG, $DB;
627
 
628
    $resetfeedbacks = array();
629
    $dropfeedbacks = array();
630
    $status = array();
631
    $componentstr = get_string('modulenameplural', 'feedback');
632
 
633
    //get the relevant entries from $data
634
    foreach ($data as $key => $value) {
635
        switch(true) {
636
            case substr($key, 0, strlen(FEEDBACK_RESETFORM_RESET)) == FEEDBACK_RESETFORM_RESET:
637
                if ($value == 1) {
638
                    $templist = explode('_', $key);
639
                    if (isset($templist[3])) {
640
                        $resetfeedbacks[] = intval($templist[3]);
641
                    }
642
                }
643
            break;
644
            case substr($key, 0, strlen(FEEDBACK_RESETFORM_DROP)) == FEEDBACK_RESETFORM_DROP:
645
                if ($value == 1) {
646
                    $templist = explode('_', $key);
647
                    if (isset($templist[3])) {
648
                        $dropfeedbacks[] = intval($templist[3]);
649
                    }
650
                }
651
            break;
652
        }
653
    }
654
 
655
    //reset the selected feedbacks
656
    foreach ($resetfeedbacks as $id) {
657
        $feedback = $DB->get_record('feedback', array('id'=>$id));
658
        feedback_delete_all_completeds($feedback);
659
        $status[] = array('component'=>$componentstr.':'.$feedback->name,
660
                        'item'=>get_string('resetting_data', 'feedback'),
661
                        'error'=>false);
662
    }
663
 
664
    // Updating dates - shift may be negative too.
665
    if ($data->timeshift) {
666
        // Any changes to the list of dates that needs to be rolled should be same during course restore and course reset.
667
        // See MDL-9367.
668
        $shifterror = !shift_course_mod_dates('feedback', array('timeopen', 'timeclose'), $data->timeshift, $data->courseid);
669
        $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => $shifterror);
670
    }
671
 
672
    return $status;
673
}
674
 
675
/**
676
 * Called by course/reset.php
677
 *
678
 * @global object
679
 * @uses FEEDBACK_RESETFORM_RESET
680
 * @param MoodleQuickForm $mform form passed by reference
681
 */
682
function feedback_reset_course_form_definition(&$mform) {
683
    global $COURSE, $DB;
684
 
685
    $mform->addElement('header', 'feedbackheader', get_string('modulenameplural', 'feedback'));
686
 
687
    if (!$feedbacks = $DB->get_records('feedback', array('course'=>$COURSE->id), 'name')) {
688
        return;
689
    }
690
 
691
    $mform->addElement('static', 'hint', get_string('resetting_data', 'feedback'));
692
    foreach ($feedbacks as $feedback) {
693
        $mform->addElement('checkbox', FEEDBACK_RESETFORM_RESET.$feedback->id, $feedback->name);
694
    }
695
}
696
 
697
/**
698
 * Course reset form defaults.
699
 *
700
 * @global object
701
 * @uses FEEDBACK_RESETFORM_RESET
702
 * @param object $course
703
 */
704
function feedback_reset_course_form_defaults($course) {
705
    global $DB;
706
 
707
    $return = array();
708
    if (!$feedbacks = $DB->get_records('feedback', array('course'=>$course->id), 'name')) {
709
        return;
710
    }
711
    foreach ($feedbacks as $feedback) {
712
        $return[FEEDBACK_RESETFORM_RESET.$feedback->id] = true;
713
    }
714
    return $return;
715
}
716
 
717
/**
718
 * Called by course/reset.php and shows the formdata by coursereset.
719
 * it prints checkboxes for each feedback available at the given course
720
 * there are two checkboxes:
721
 * 1) delete userdata and keep the feedback
722
 * 2) delete userdata and drop the feedback
723
 *
724
 * @global object
725
 * @uses FEEDBACK_RESETFORM_RESET
726
 * @uses FEEDBACK_RESETFORM_DROP
727
 * @param object $course
728
 * @return void
729
 */
730
function feedback_reset_course_form($course) {
731
    global $DB, $OUTPUT;
732
 
733
    echo get_string('resetting_feedbacks', 'feedback'); echo ':<br />';
734
    if (!$feedbacks = $DB->get_records('feedback', array('course'=>$course->id), 'name')) {
735
        return;
736
    }
737
 
738
    foreach ($feedbacks as $feedback) {
739
        echo '<p>';
740
        echo get_string('name', 'feedback').': '.$feedback->name.'<br />';
741
        echo html_writer::checkbox(FEEDBACK_RESETFORM_RESET.$feedback->id,
742
                                1, true,
743
                                get_string('resetting_data', 'feedback'));
744
        echo '<br />';
745
        echo html_writer::checkbox(FEEDBACK_RESETFORM_DROP.$feedback->id,
746
                                1, false,
747
                                get_string('drop_feedback', 'feedback'));
748
        echo '</p>';
749
    }
750
}
751
 
752
/**
753
 * This gets an array with default options for the editor
754
 *
755
 * @return array the options
756
 */
757
function feedback_get_editor_options() {
758
    return array('maxfiles' => EDITOR_UNLIMITED_FILES,
759
                'trusttext'=>true);
760
}
761
 
762
/**
763
 * This creates new events given as timeopen and closeopen by $feedback.
764
 *
765
 * @global object
766
 * @param object $feedback
767
 * @return void
768
 */
769
function feedback_set_events($feedback) {
770
    global $DB, $CFG;
771
 
772
    // Include calendar/lib.php.
773
    require_once($CFG->dirroot.'/calendar/lib.php');
774
 
775
    // Get CMID if not sent as part of $feedback.
776
    if (!isset($feedback->coursemodule)) {
777
        $cm = get_coursemodule_from_instance('feedback', $feedback->id, $feedback->course);
778
        $feedback->coursemodule = $cm->id;
779
    }
780
 
781
    // Feedback start calendar events.
782
    $eventid = $DB->get_field('event', 'id',
783
            array('modulename' => 'feedback', 'instance' => $feedback->id, 'eventtype' => FEEDBACK_EVENT_TYPE_OPEN));
784
 
785
    if (isset($feedback->timeopen) && $feedback->timeopen > 0) {
786
        $event = new stdClass();
787
        $event->eventtype    = FEEDBACK_EVENT_TYPE_OPEN;
788
        $event->type         = empty($feedback->timeclose) ? CALENDAR_EVENT_TYPE_ACTION : CALENDAR_EVENT_TYPE_STANDARD;
789
        $event->name         = get_string('calendarstart', 'feedback', $feedback->name);
790
        $event->description  = format_module_intro('feedback', $feedback, $feedback->coursemodule, false);
791
        $event->format       = FORMAT_HTML;
792
        $event->timestart    = $feedback->timeopen;
793
        $event->timesort     = $feedback->timeopen;
794
        $event->visible      = instance_is_visible('feedback', $feedback);
795
        $event->timeduration = 0;
796
        if ($eventid) {
797
            // Calendar event exists so update it.
798
            $event->id = $eventid;
799
            $calendarevent = calendar_event::load($event->id);
800
            $calendarevent->update($event, false);
801
        } else {
802
            // Event doesn't exist so create one.
803
            $event->courseid     = $feedback->course;
804
            $event->groupid      = 0;
805
            $event->userid       = 0;
806
            $event->modulename   = 'feedback';
807
            $event->instance     = $feedback->id;
808
            $event->eventtype    = FEEDBACK_EVENT_TYPE_OPEN;
809
            calendar_event::create($event, false);
810
        }
811
    } else if ($eventid) {
812
        // Calendar event is on longer needed.
813
        $calendarevent = calendar_event::load($eventid);
814
        $calendarevent->delete();
815
    }
816
 
817
    // Feedback close calendar events.
818
    $eventid = $DB->get_field('event', 'id',
819
            array('modulename' => 'feedback', 'instance' => $feedback->id, 'eventtype' => FEEDBACK_EVENT_TYPE_CLOSE));
820
 
821
    if (isset($feedback->timeclose) && $feedback->timeclose > 0) {
822
        $event = new stdClass();
823
        $event->type         = CALENDAR_EVENT_TYPE_ACTION;
824
        $event->eventtype    = FEEDBACK_EVENT_TYPE_CLOSE;
825
        $event->name         = get_string('calendarend', 'feedback', $feedback->name);
826
        $event->description  = format_module_intro('feedback', $feedback, $feedback->coursemodule, false);
827
        $event->format       = FORMAT_HTML;
828
        $event->timestart    = $feedback->timeclose;
829
        $event->timesort     = $feedback->timeclose;
830
        $event->visible      = instance_is_visible('feedback', $feedback);
831
        $event->timeduration = 0;
832
        if ($eventid) {
833
            // Calendar event exists so update it.
834
            $event->id = $eventid;
835
            $calendarevent = calendar_event::load($event->id);
836
            $calendarevent->update($event, false);
837
        } else {
838
            // Event doesn't exist so create one.
839
            $event->courseid     = $feedback->course;
840
            $event->groupid      = 0;
841
            $event->userid       = 0;
842
            $event->modulename   = 'feedback';
843
            $event->instance     = $feedback->id;
844
            calendar_event::create($event, false);
845
        }
846
    } else if ($eventid) {
847
        // Calendar event is on longer needed.
848
        $calendarevent = calendar_event::load($eventid);
849
        $calendarevent->delete();
850
    }
851
}
852
 
853
/**
854
 * This standard function will check all instances of this module
855
 * and make sure there are up-to-date events created for each of them.
856
 * If courseid = 0, then every feedback event in the site is checked, else
857
 * only feedback events belonging to the course specified are checked.
858
 * This function is used, in its new format, by restore_refresh_events()
859
 *
860
 * @param int $courseid
861
 * @param int|stdClass $instance Feedback module instance or ID.
862
 * @param int|stdClass $cm Course module object or ID (not used in this module).
863
 * @return bool
864
 */
865
function feedback_refresh_events($courseid = 0, $instance = null, $cm = null) {
866
    global $DB;
867
 
868
    // If we have instance information then we can just update the one event instead of updating all events.
869
    if (isset($instance)) {
870
        if (!is_object($instance)) {
871
            $instance = $DB->get_record('feedback', array('id' => $instance), '*', MUST_EXIST);
872
        }
873
        feedback_set_events($instance);
874
        return true;
875
    }
876
 
877
    if ($courseid) {
878
        if (! $feedbacks = $DB->get_records("feedback", array("course" => $courseid))) {
879
            return true;
880
        }
881
    } else {
882
        if (! $feedbacks = $DB->get_records("feedback")) {
883
            return true;
884
        }
885
    }
886
 
887
    foreach ($feedbacks as $feedback) {
888
        feedback_set_events($feedback);
889
    }
890
    return true;
891
}
892
 
893
/**
894
 * this function is called by {@link feedback_delete_userdata()}
895
 * it drops the feedback-instance from the course_module table
896
 *
897
 * @global object
898
 * @param int $id the id from the coursemodule
899
 * @return boolean
900
 */
901
function feedback_delete_course_module($id) {
902
    global $DB;
903
 
904
    if (!$cm = $DB->get_record('course_modules', array('id'=>$id))) {
905
        return true;
906
    }
907
    return $DB->delete_records('course_modules', array('id'=>$cm->id));
908
}
909
 
910
 
911
 
912
////////////////////////////////////////////////
913
//functions to handle capabilities
914
////////////////////////////////////////////////
915
 
916
/**
917
 * @deprecated since 3.1
918
 */
919
function feedback_get_context() {
920
    throw new coding_exception('feedback_get_context() can not be used anymore.');
921
}
922
 
923
/**
924
 *  returns true if the current role is faked by switching role feature
925
 *
926
 * @global object
927
 * @return boolean
928
 */
929
function feedback_check_is_switchrole() {
930
    global $USER;
931
    if (isset($USER->switchrole) AND
932
            is_array($USER->switchrole) AND
933
            count($USER->switchrole) > 0) {
934
 
935
        return true;
936
    }
937
    return false;
938
}
939
 
940
/**
941
 * count users which have not completed the feedback
942
 *
943
 * @global object
944
 * @uses CONTEXT_MODULE
945
 * @param cm_info $cm Course-module object
946
 * @param int $group single groupid
947
 * @param string $sort
948
 * @param int $startpage
949
 * @param int $pagecount
950
 * @param bool $includestatus to return if the user started or not the feedback among the complete user record
951
 * @return array array of user ids or user objects when $includestatus set to true
952
 */
953
function feedback_get_incomplete_users(cm_info $cm,
954
                                       $group = false,
955
                                       $sort = '',
956
                                       $startpage = false,
957
                                       $pagecount = false,
958
                                       $includestatus = false) {
959
 
960
    global $DB;
961
 
962
    $context = context_module::instance($cm->id);
963
 
964
    //first get all user who can complete this feedback
965
    $cap = 'mod/feedback:complete';
966
    $userfieldsapi = \core_user\fields::for_name();
967
    $allnames = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
968
    $fields = 'u.id, ' . $allnames . ', u.picture, u.email, u.imagealt';
969
    if (!$allusers = get_users_by_capability($context,
970
                                            $cap,
971
                                            $fields,
972
                                            $sort,
973
                                            '',
974
                                            '',
975
                                            $group,
976
                                            '',
977
                                            true)) {
978
        return false;
979
    }
980
    // Filter users that are not in the correct group/grouping.
981
    $info = new \core_availability\info_module($cm);
982
    $allusersrecords = $info->filter_user_list($allusers);
983
 
984
    $allusers = array_keys($allusersrecords);
985
 
986
    //now get all completeds
987
    $params = array('feedback'=>$cm->instance);
988
    if ($completedusers = $DB->get_records_menu('feedback_completed', $params, '', 'id, userid')) {
989
        // Now strike all completedusers from allusers.
990
        $allusers = array_diff($allusers, $completedusers);
991
    }
992
 
993
    //for paging I use array_slice()
994
    if ($startpage !== false AND $pagecount !== false) {
995
        $allusers = array_slice($allusers, $startpage, $pagecount);
996
    }
997
 
998
    // Check if we should return the full users objects.
999
    if ($includestatus) {
1000
        $userrecords = [];
1001
        $startedusers = $DB->get_records_menu('feedback_completedtmp', ['feedback' => $cm->instance], '', 'id, userid');
1002
        $startedusers = array_flip($startedusers);
1003
        foreach ($allusers as $userid) {
1004
            $allusersrecords[$userid]->feedbackstarted = isset($startedusers[$userid]);
1005
            $userrecords[] = $allusersrecords[$userid];
1006
        }
1007
        return $userrecords;
1008
    } else {    // Return just user ids.
1009
        return $allusers;
1010
    }
1011
}
1012
 
1013
/**
1014
 * count users which have not completed the feedback
1015
 *
1016
 * @global object
1017
 * @param object $cm
1018
 * @param int $group single groupid
1019
 * @return int count of userrecords
1020
 */
1021
function feedback_count_incomplete_users($cm, $group = false) {
1022
    if ($allusers = feedback_get_incomplete_users($cm, $group)) {
1023
        return count($allusers);
1024
    }
1025
    return 0;
1026
}
1027
 
1028
/**
1029
 * count users which have completed a feedback
1030
 *
1031
 * @global object
1032
 * @uses FEEDBACK_ANONYMOUS_NO
1033
 * @param object $cm
1034
 * @param int $group single groupid
1035
 * @return int count of userrecords
1036
 */
1037
function feedback_count_complete_users($cm, $group = false) {
1038
    global $DB;
1039
 
1040
    $params = array(FEEDBACK_ANONYMOUS_NO, $cm->instance);
1041
 
1042
    $fromgroup = '';
1043
    $wheregroup = '';
1044
    if ($group) {
1045
        $fromgroup = ', {groups_members} g';
1046
        $wheregroup = ' AND g.groupid = ? AND g.userid = c.userid';
1047
        $params[] = $group;
1048
    }
1049
 
1050
    $sql = 'SELECT COUNT(u.id) FROM {user} u, {feedback_completed} c'.$fromgroup.'
1051
              WHERE anonymous_response = ? AND u.id = c.userid AND c.feedback = ?
1052
              '.$wheregroup;
1053
 
1054
    return $DB->count_records_sql($sql, $params);
1055
 
1056
}
1057
 
1058
/**
1059
 * get users which have completed a feedback
1060
 *
1061
 * @global object
1062
 * @uses CONTEXT_MODULE
1063
 * @uses FEEDBACK_ANONYMOUS_NO
1064
 * @param object $cm
1065
 * @param int $group single groupid
1066
 * @param string $where a sql where condition (must end with " AND ")
1067
 * @param array parameters used in $where
1068
 * @param string $sort a table field
1069
 * @param int $startpage
1070
 * @param int $pagecount
1071
 * @return object the userrecords
1072
 */
1073
function feedback_get_complete_users($cm,
1074
                                     $group = false,
1075
                                     $where = '',
1076
                                     array $params = null,
1077
                                     $sort = '',
1078
                                     $startpage = false,
1079
                                     $pagecount = false) {
1080
 
1081
    global $DB;
1082
 
1083
    $context = context_module::instance($cm->id);
1084
 
1085
    $params = (array)$params;
1086
 
1087
    $params['anon'] = FEEDBACK_ANONYMOUS_NO;
1088
    $params['instance'] = $cm->instance;
1089
 
1090
    $fromgroup = '';
1091
    $wheregroup = '';
1092
    if ($group) {
1093
        $fromgroup = ', {groups_members} g';
1094
        $wheregroup = ' AND g.groupid = :group AND g.userid = c.userid';
1095
        $params['group'] = $group;
1096
    }
1097
 
1098
    if ($sort) {
1099
        $sortsql = ' ORDER BY '.$sort;
1100
    } else {
1101
        $sortsql = '';
1102
    }
1103
 
1104
    $userfieldsapi = \core_user\fields::for_userpic();
1105
    $ufields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1106
    $sql = 'SELECT DISTINCT '.$ufields.', c.timemodified as completed_timemodified
1107
            FROM {user} u, {feedback_completed} c '.$fromgroup.'
1108
            WHERE '.$where.' anonymous_response = :anon
1109
                AND u.id = c.userid
1110
                AND c.feedback = :instance
1111
              '.$wheregroup.$sortsql;
1112
 
1113
    if ($startpage === false OR $pagecount === false) {
1114
        $startpage = false;
1115
        $pagecount = false;
1116
    }
1117
    return $DB->get_records_sql($sql, $params, $startpage, $pagecount);
1118
}
1119
 
1120
/**
1121
 * get users which have the viewreports-capability
1122
 *
1123
 * @uses CONTEXT_MODULE
1124
 * @param int $cmid
1125
 * @param mixed $groups single groupid or array of groupids - group(s) user is in
1126
 * @return object the userrecords
1127
 */
1128
function feedback_get_viewreports_users($cmid, $groups = false) {
1129
 
1130
    $context = context_module::instance($cmid);
1131
 
1132
    //description of the call below:
1133
    //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
1134
    //                          $limitnum='', $groups='', $exceptions='', $doanything=true)
1135
    return get_users_by_capability($context,
1136
                            'mod/feedback:viewreports',
1137
                            '',
1138
                            'lastname',
1139
                            '',
1140
                            '',
1141
                            $groups,
1142
                            '',
1143
                            false);
1144
}
1145
 
1146
/**
1147
 * get users which have the receivemail-capability
1148
 *
1149
 * @uses CONTEXT_MODULE
1150
 * @param int $cmid
1151
 * @param mixed $groups single groupid or array of groupids - group(s) user is in
1152
 * @return object the userrecords
1153
 */
1154
function feedback_get_receivemail_users($cmid, $groups = false) {
1155
 
1156
    $context = context_module::instance($cmid);
1157
 
1158
    //description of the call below:
1159
    //get_users_by_capability($context, $capability, $fields='', $sort='', $limitfrom='',
1160
    //                          $limitnum='', $groups='', $exceptions='', $doanything=true)
1161
    return get_users_by_capability($context,
1162
                            'mod/feedback:receivemail',
1163
                            '',
1164
                            'lastname',
1165
                            '',
1166
                            '',
1167
                            $groups,
1168
                            '',
1169
                            false);
1170
}
1171
 
1172
////////////////////////////////////////////////
1173
//functions to handle the templates
1174
////////////////////////////////////////////////
1175
////////////////////////////////////////////////
1176
 
1177
/**
1178
 * creates a new template-record.
1179
 *
1180
 * @global object
1181
 * @param int $courseid
1182
 * @param string $name the name of template shown in the templatelist
1183
 * @param int $ispublic 0:privat 1:public
1184
 * @return stdClass the new template
1185
 */
1186
function feedback_create_template($courseid, $name, $ispublic = 0) {
1187
    global $DB;
1188
 
1189
    $templ = new stdClass();
1190
    $templ->course   = ($ispublic ? 0 : $courseid);
1191
    $templ->name     = $name;
1192
    $templ->ispublic = $ispublic;
1193
 
1194
    $templid = $DB->insert_record('feedback_template', $templ);
1195
    return $DB->get_record('feedback_template', array('id'=>$templid));
1196
}
1197
 
1198
/**
1199
 * creates new template items.
1200
 * all items will be copied and the attribute feedback will be set to 0
1201
 * and the attribute template will be set to the new templateid
1202
 *
1203
 * @global object
1204
 * @uses CONTEXT_MODULE
1205
 * @uses CONTEXT_COURSE
1206
 * @param object $feedback
1207
 * @param string $name the name of template shown in the templatelist
1208
 * @param int $ispublic 0:privat 1:public
1209
 * @return boolean
1210
 */
1211
function feedback_save_as_template($feedback, $name, $ispublic = 0) {
1212
    global $DB;
1213
    $fs = get_file_storage();
1214
 
1215
    if (!$feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$feedback->id))) {
1216
        return false;
1217
    }
1218
 
1219
    if (!$newtempl = feedback_create_template($feedback->course, $name, $ispublic)) {
1220
        return false;
1221
    }
1222
 
1223
    //files in the template_item are in the context of the current course or
1224
    //if the template is public the files are in the system context
1225
    //files in the feedback_item are in the feedback_context of the feedback
1226
    if ($ispublic) {
1227
        $s_context = context_system::instance();
1228
    } else {
1229
        $s_context = context_course::instance($newtempl->course);
1230
    }
1231
    $cm = get_coursemodule_from_instance('feedback', $feedback->id);
1232
    $f_context = context_module::instance($cm->id);
1233
 
1234
    //create items of this new template
1235
    //depend items we are storing temporary in an mapping list array(new id => dependitem)
1236
    //we also store a mapping of all items array(oldid => newid)
1237
    $dependitemsmap = array();
1238
    $itembackup = array();
1239
    foreach ($feedbackitems as $item) {
1240
 
1241
        $t_item = clone($item);
1242
 
1243
        unset($t_item->id);
1244
        $t_item->feedback = 0;
1245
        $t_item->template     = $newtempl->id;
1246
        $t_item->id = $DB->insert_record('feedback_item', $t_item);
1247
        //copy all included files to the feedback_template filearea
1248
        $itemfiles = $fs->get_area_files($f_context->id,
1249
                                    'mod_feedback',
1250
                                    'item',
1251
                                    $item->id,
1252
                                    "id",
1253
                                    false);
1254
        if ($itemfiles) {
1255
            foreach ($itemfiles as $ifile) {
1256
                $file_record = new stdClass();
1257
                $file_record->contextid = $s_context->id;
1258
                $file_record->component = 'mod_feedback';
1259
                $file_record->filearea = 'template';
1260
                $file_record->itemid = $t_item->id;
1261
                $fs->create_file_from_storedfile($file_record, $ifile);
1262
            }
1263
        }
1264
 
1265
        $itembackup[$item->id] = $t_item->id;
1266
        if ($t_item->dependitem) {
1267
            $dependitemsmap[$t_item->id] = $t_item->dependitem;
1268
        }
1269
 
1270
    }
1271
 
1272
    //remapping the dependency
1273
    foreach ($dependitemsmap as $key => $dependitem) {
1274
        $newitem = $DB->get_record('feedback_item', array('id'=>$key));
1275
        $newitem->dependitem = $itembackup[$newitem->dependitem];
1276
        $DB->update_record('feedback_item', $newitem);
1277
    }
1278
 
1279
    return true;
1280
}
1281
 
1282
/**
1283
 * deletes all feedback_items related to the given template id
1284
 *
1285
 * @global object
1286
 * @uses CONTEXT_COURSE
1287
 * @param object $template the template
1288
 * @return void
1289
 */
1290
function feedback_delete_template($template) {
1291
    global $DB;
1292
 
1293
    //deleting the files from the item is done by feedback_delete_item
1294
    if ($t_items = $DB->get_records("feedback_item", array("template"=>$template->id))) {
1295
        foreach ($t_items as $t_item) {
1296
            feedback_delete_item($t_item->id, false, $template);
1297
        }
1298
    }
1299
    $DB->delete_records("feedback_template", array("id"=>$template->id));
1300
}
1301
 
1302
/**
1303
 * creates new feedback_item-records from template.
1304
 * if $deleteold is set true so the existing items of the given feedback will be deleted
1305
 * if $deleteold is set false so the new items will be appanded to the old items
1306
 *
1307
 * @global object
1308
 * @uses CONTEXT_COURSE
1309
 * @uses CONTEXT_MODULE
1310
 * @param object $feedback
1311
 * @param int $templateid
1312
 * @param boolean $deleteold
1313
 */
1314
function feedback_items_from_template($feedback, $templateid, $deleteold = false) {
1315
    global $DB, $CFG;
1316
 
1317
    require_once($CFG->libdir.'/completionlib.php');
1318
 
1319
    $fs = get_file_storage();
1320
 
1321
    if (!$template = $DB->get_record('feedback_template', array('id'=>$templateid))) {
1322
        return false;
1323
    }
1324
    //get all templateitems
1325
    if (!$templitems = $DB->get_records('feedback_item', array('template'=>$templateid))) {
1326
        return false;
1327
    }
1328
 
1329
    //files in the template_item are in the context of the current course
1330
    //files in the feedback_item are in the feedback_context of the feedback
1331
    if ($template->ispublic) {
1332
        $s_context = context_system::instance();
1333
    } else {
1334
        $s_context = context_course::instance($feedback->course);
1335
    }
1336
    $course = $DB->get_record('course', array('id'=>$feedback->course));
1337
    $cm = get_coursemodule_from_instance('feedback', $feedback->id);
1338
    $f_context = context_module::instance($cm->id);
1339
 
1340
    //if deleteold then delete all old items before
1341
    //get all items
1342
    if ($deleteold) {
1343
        if ($feedbackitems = $DB->get_records('feedback_item', array('feedback'=>$feedback->id))) {
1344
            //delete all items of this feedback
1345
            foreach ($feedbackitems as $item) {
1346
                feedback_delete_item($item->id, false);
1347
            }
1348
 
1349
            $params = array('feedback'=>$feedback->id);
1350
            if ($completeds = $DB->get_records('feedback_completed', $params)) {
1351
                $completion = new completion_info($course);
1352
                foreach ($completeds as $completed) {
1353
                    $DB->delete_records('feedback_completed', array('id' => $completed->id));
1354
                    // Update completion state
1355
                    if ($completion->is_enabled($cm) && $cm->completion == COMPLETION_TRACKING_AUTOMATIC &&
1356
                            $feedback->completionsubmit) {
1357
                        $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
1358
                    }
1359
                }
1360
            }
1361
            $DB->delete_records('feedback_completedtmp', array('feedback'=>$feedback->id));
1362
        }
1363
        $positionoffset = 0;
1364
    } else {
1365
        //if the old items are kept the new items will be appended
1366
        //therefor the new position has an offset
1367
        $positionoffset = $DB->count_records('feedback_item', array('feedback'=>$feedback->id));
1368
    }
1369
 
1370
    //create items of this new template
1371
    //depend items we are storing temporary in an mapping list array(new id => dependitem)
1372
    //we also store a mapping of all items array(oldid => newid)
1373
    $dependitemsmap = array();
1374
    $itembackup = array();
1375
    foreach ($templitems as $t_item) {
1376
        $item = clone($t_item);
1377
        unset($item->id);
1378
        $item->feedback = $feedback->id;
1379
        $item->template = 0;
1380
        $item->position = $item->position + $positionoffset;
1381
 
1382
        $item->id = $DB->insert_record('feedback_item', $item);
1383
 
1384
        //moving the files to the new item
1385
        $templatefiles = $fs->get_area_files($s_context->id,
1386
                                        'mod_feedback',
1387
                                        'template',
1388
                                        $t_item->id,
1389
                                        "id",
1390
                                        false);
1391
        if ($templatefiles) {
1392
            foreach ($templatefiles as $tfile) {
1393
                $file_record = new stdClass();
1394
                $file_record->contextid = $f_context->id;
1395
                $file_record->component = 'mod_feedback';
1396
                $file_record->filearea = 'item';
1397
                $file_record->itemid = $item->id;
1398
                $fs->create_file_from_storedfile($file_record, $tfile);
1399
            }
1400
        }
1401
 
1402
        $itembackup[$t_item->id] = $item->id;
1403
        if ($item->dependitem) {
1404
            $dependitemsmap[$item->id] = $item->dependitem;
1405
        }
1406
    }
1407
 
1408
    //remapping the dependency
1409
    foreach ($dependitemsmap as $key => $dependitem) {
1410
        $newitem = $DB->get_record('feedback_item', array('id'=>$key));
1411
        $newitem->dependitem = $itembackup[$newitem->dependitem];
1412
        $DB->update_record('feedback_item', $newitem);
1413
    }
1414
}
1415
 
1416
/**
1417
 * get the list of available templates.
1418
 * if the $onlyown param is set true so only templates from own course will be served
1419
 * this is important for droping templates
1420
 *
1421
 * @global object
1422
 * @param object $course
1423
 * @param string $onlyownorpublic
1424
 * @return array the template recordsets
1425
 */
1426
function feedback_get_template_list($course, $onlyownorpublic = '') {
1427
    global $DB, $CFG;
1428
 
1429
    switch($onlyownorpublic) {
1430
        case '':
1431
            $templates = $DB->get_records_select('feedback_template',
1432
                                                 'course = ? OR ispublic = 1',
1433
                                                 array($course->id),
1434
                                                 'name');
1435
            break;
1436
        case 'own':
1437
            $templates = $DB->get_records('feedback_template',
1438
                                          array('course'=>$course->id),
1439
                                          'name');
1440
            break;
1441
        case 'public':
1442
            $templates = $DB->get_records('feedback_template', array('ispublic'=>1), 'name');
1443
            break;
1444
    }
1445
    return $templates;
1446
}
1447
 
1448
////////////////////////////////////////////////
1449
//Handling der Items
1450
////////////////////////////////////////////////
1451
////////////////////////////////////////////////
1452
 
1453
/**
1454
 * load the lib.php from item-plugin-dir and returns the instance of the itemclass
1455
 *
1456
 * @param string $typ
1457
 * @return feedback_item_base the instance of itemclass
1458
 * @throws moodle_exception For invalid type
1459
 */
1460
function feedback_get_item_class($typ) {
1461
    global $CFG;
1462
 
1463
    require_once($CFG->dirroot.'/mod/feedback/item/feedback_item_class.php');
1464
 
1465
    //get the class of item-typ
1466
    $typeclean = clean_param($typ, PARAM_ALPHA);
1467
 
1468
    $itemclass = "feedback_item_{$typeclean}";
1469
    $itemclasspath = "{$CFG->dirroot}/mod/feedback/item/{$typeclean}/lib.php";
1470
 
1471
    //get the instance of item-class
1472
    if (!class_exists($itemclass) && file_exists($itemclasspath)) {
1473
        require_once($itemclasspath);
1474
    }
1475
 
1476
    if (!class_exists($itemclass)) {
1477
        throw new moodle_exception('typemissing', 'feedback');
1478
    }
1479
 
1480
    return new $itemclass();
1481
}
1482
 
1483
/**
1484
 * load the available item plugins from given subdirectory of $CFG->dirroot
1485
 * the default is "mod/feedback/item"
1486
 *
1487
 * @global object
1488
 * @param string $dir the subdir
1489
 * @return array pluginnames as string
1490
 */
1491
function feedback_load_feedback_items($dir = 'mod/feedback/item') {
1492
    global $CFG;
1493
    $names = get_list_of_plugins($dir);
1494
    $ret_names = array();
1495
 
1496
    foreach ($names as $name) {
1497
        require_once($CFG->dirroot.'/'.$dir.'/'.$name.'/lib.php');
1498
        if (class_exists('feedback_item_'.$name)) {
1499
            $ret_names[] = $name;
1500
        }
1501
    }
1502
    return $ret_names;
1503
}
1504
 
1505
/**
1506
 * load the available item plugins to use as dropdown-options
1507
 *
1508
 * @global object
1509
 * @return array pluginnames as string
1510
 */
1511
function feedback_load_feedback_items_options() {
1512
    global $CFG;
1513
 
1514
    $feedback_options = array("pagebreak" => get_string('add_pagebreak', 'feedback'));
1515
 
1516
    if (!$feedback_names = feedback_load_feedback_items('mod/feedback/item')) {
1517
        return array();
1518
    }
1519
 
1520
    foreach ($feedback_names as $fn) {
1521
        $feedback_options[$fn] = get_string($fn, 'feedback');
1522
    }
1523
    asort($feedback_options);
1524
    return $feedback_options;
1525
}
1526
 
1527
/**
1528
 * load the available items for the depend item dropdown list shown in the edit_item form
1529
 *
1530
 * @global object
1531
 * @param object $feedback
1532
 * @param object $item the item of the edit_item form
1533
 * @return array all items except the item $item, labels and pagebreaks
1534
 */
1535
function feedback_get_depend_candidates_for_item($feedback, $item) {
1536
    global $DB;
1537
    //all items for dependitem
1538
    $where = "feedback = ? AND typ != 'pagebreak' AND hasvalue = 1";
1539
    $params = array($feedback->id);
1540
    if (isset($item->id) AND $item->id) {
1541
        $where .= ' AND id != ?';
1542
        $params[] = $item->id;
1543
    }
1544
    $dependitems = array(0 => get_string('choose'));
1545
    $feedbackitems = $DB->get_records_select_menu('feedback_item',
1546
                                                  $where,
1547
                                                  $params,
1548
                                                  'position',
1549
                                                  'id, label');
1550
 
1551
    if (!$feedbackitems) {
1552
        return $dependitems;
1553
    }
1554
    //adding the choose-option
1555
    foreach ($feedbackitems as $key => $val) {
1556
        if (trim(strval($val)) !== '') {
1557
            $dependitems[$key] = format_string($val);
1558
        }
1559
    }
1560
    return $dependitems;
1561
}
1562
 
1563
/**
1564
 * @deprecated since 3.1
1565
 */
1566
function feedback_create_item() {
1567
    throw new coding_exception('feedback_create_item() can not be used anymore.');
1568
}
1569
 
1570
/**
1571
 * save the changes of a given item.
1572
 *
1573
 * @global object
1574
 * @param object $item
1575
 * @return boolean
1576
 */
1577
function feedback_update_item($item) {
1578
    global $DB;
1579
    return $DB->update_record("feedback_item", $item);
1580
}
1581
 
1582
/**
1583
 * deletes an item and also deletes all related values
1584
 *
1585
 * @global object
1586
 * @uses CONTEXT_MODULE
1587
 * @param int $itemid
1588
 * @param boolean $renumber should the kept items renumbered Yes/No
1589
 * @param object $template if the template is given so the items are bound to it
1590
 * @return void
1591
 */
1592
function feedback_delete_item($itemid, $renumber = true, $template = false) {
1593
    global $DB;
1594
 
1595
    $item = $DB->get_record('feedback_item', array('id'=>$itemid));
1596
 
1597
    //deleting the files from the item
1598
    $fs = get_file_storage();
1599
 
1600
    if ($template) {
1601
        if ($template->ispublic) {
1602
            $context = context_system::instance();
1603
        } else {
1604
            $context = context_course::instance($template->course);
1605
        }
1606
        $templatefiles = $fs->get_area_files($context->id,
1607
                                    'mod_feedback',
1608
                                    'template',
1609
                                    $item->id,
1610
                                    "id",
1611
                                    false);
1612
 
1613
        if ($templatefiles) {
1614
            $fs->delete_area_files($context->id, 'mod_feedback', 'template', $item->id);
1615
        }
1616
    } else {
1617
        if (!$cm = get_coursemodule_from_instance('feedback', $item->feedback)) {
1618
            return false;
1619
        }
1620
        $context = context_module::instance($cm->id);
1621
 
1622
        $itemfiles = $fs->get_area_files($context->id,
1623
                                    'mod_feedback',
1624
                                    'item',
1625
                                    $item->id,
1626
                                    "id", false);
1627
 
1628
        if ($itemfiles) {
1629
            $fs->delete_area_files($context->id, 'mod_feedback', 'item', $item->id);
1630
        }
1631
    }
1632
 
1633
    $DB->delete_records("feedback_value", array("item"=>$itemid));
1634
    $DB->delete_records("feedback_valuetmp", array("item"=>$itemid));
1635
 
1636
    //remove all depends
1637
    $DB->set_field('feedback_item', 'dependvalue', '', array('dependitem'=>$itemid));
1638
    $DB->set_field('feedback_item', 'dependitem', 0, array('dependitem'=>$itemid));
1639
 
1640
    $DB->delete_records("feedback_item", array("id"=>$itemid));
1641
    if ($renumber) {
1642
        feedback_renumber_items($item->feedback);
1643
    }
1644
}
1645
 
1646
/**
1647
 * deletes all items of the given feedbackid
1648
 *
1649
 * @global object
1650
 * @param int $feedbackid
1651
 * @return void
1652
 */
1653
function feedback_delete_all_items($feedbackid) {
1654
    global $DB, $CFG;
1655
    require_once($CFG->libdir.'/completionlib.php');
1656
 
1657
    if (!$feedback = $DB->get_record('feedback', array('id'=>$feedbackid))) {
1658
        return false;
1659
    }
1660
 
1661
    if (!$cm = get_coursemodule_from_instance('feedback', $feedback->id)) {
1662
        return false;
1663
    }
1664
 
1665
    if (!$course = $DB->get_record('course', array('id'=>$feedback->course))) {
1666
        return false;
1667
    }
1668
 
1669
    if (!$items = $DB->get_records('feedback_item', array('feedback'=>$feedbackid))) {
1670
        return;
1671
    }
1672
    foreach ($items as $item) {
1673
        feedback_delete_item($item->id, false);
1674
    }
1675
    if ($completeds = $DB->get_records('feedback_completed', array('feedback'=>$feedback->id))) {
1676
        $completion = new completion_info($course);
1677
        foreach ($completeds as $completed) {
1678
            $DB->delete_records('feedback_completed', array('id' => $completed->id));
1679
            // Update completion state
1680
            if ($completion->is_enabled($cm) && $cm->completion == COMPLETION_TRACKING_AUTOMATIC &&
1681
                    $feedback->completionsubmit) {
1682
                $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
1683
            }
1684
        }
1685
    }
1686
 
1687
    $DB->delete_records('feedback_completedtmp', array('feedback'=>$feedbackid));
1688
 
1689
}
1690
 
1691
/**
1692
 * this function toggled the item-attribute required (yes/no)
1693
 *
1694
 * @global object
1695
 * @param object $item
1696
 * @return boolean
1697
 */
1698
function feedback_switch_item_required($item) {
1699
    global $DB, $CFG;
1700
 
1701
    $itemobj = feedback_get_item_class($item->typ);
1702
 
1703
    if ($itemobj->can_switch_require()) {
1704
        $new_require_val = (int)!(bool)$item->required;
1705
        $params = array('id'=>$item->id);
1706
        $DB->set_field('feedback_item', 'required', $new_require_val, $params);
1707
    }
1708
    return true;
1709
}
1710
 
1711
/**
1712
 * renumbers all items of the given feedbackid
1713
 *
1714
 * @global object
1715
 * @param int $feedbackid
1716
 * @return void
1717
 */
1718
function feedback_renumber_items($feedbackid) {
1719
    global $DB;
1720
 
1721
    $items = $DB->get_records('feedback_item', array('feedback'=>$feedbackid), 'position');
1722
    $pos = 1;
1723
    if ($items) {
1724
        foreach ($items as $item) {
1725
            $DB->set_field('feedback_item', 'position', $pos, array('id'=>$item->id));
1726
            $pos++;
1727
        }
1728
    }
1729
}
1730
 
1731
/**
1732
 * this decreases the position of the given item
1733
 *
1734
 * @global object
1735
 * @param object $item
1736
 * @return bool
1737
 */
1738
function feedback_moveup_item($item) {
1739
    global $DB;
1740
 
1741
    if ($item->position == 1) {
1742
        return true;
1743
    }
1744
 
1745
    $params = array('feedback'=>$item->feedback);
1746
    if (!$items = $DB->get_records('feedback_item', $params, 'position')) {
1747
        return false;
1748
    }
1749
 
1750
    $itembefore = null;
1751
    foreach ($items as $i) {
1752
        if ($i->id == $item->id) {
1753
            if (is_null($itembefore)) {
1754
                return true;
1755
            }
1756
            $itembefore->position = $item->position;
1757
            $item->position--;
1758
            feedback_update_item($itembefore);
1759
            feedback_update_item($item);
1760
            feedback_renumber_items($item->feedback);
1761
            return true;
1762
        }
1763
        $itembefore = $i;
1764
    }
1765
    return false;
1766
}
1767
 
1768
/**
1769
 * this increased the position of the given item
1770
 *
1771
 * @global object
1772
 * @param object $item
1773
 * @return bool
1774
 */
1775
function feedback_movedown_item($item) {
1776
    global $DB;
1777
 
1778
    $params = array('feedback'=>$item->feedback);
1779
    if (!$items = $DB->get_records('feedback_item', $params, 'position')) {
1780
        return false;
1781
    }
1782
 
1783
    $movedownitem = null;
1784
    foreach ($items as $i) {
1785
        if (!is_null($movedownitem) AND $movedownitem->id == $item->id) {
1786
            $movedownitem->position = $i->position;
1787
            $i->position--;
1788
            feedback_update_item($movedownitem);
1789
            feedback_update_item($i);
1790
            feedback_renumber_items($item->feedback);
1791
            return true;
1792
        }
1793
        $movedownitem = $i;
1794
    }
1795
    return false;
1796
}
1797
 
1798
/**
1799
 * here the position of the given item will be set to the value in $pos
1800
 *
1801
 * @global object
1802
 * @param object $moveitem
1803
 * @param int $pos
1804
 * @return boolean
1805
 */
1806
function feedback_move_item($moveitem, $pos) {
1807
    global $DB;
1808
 
1809
    $params = array('feedback'=>$moveitem->feedback);
1810
    if (!$allitems = $DB->get_records('feedback_item', $params, 'position')) {
1811
        return false;
1812
    }
1813
    if (is_array($allitems)) {
1814
        $index = 1;
1815
        foreach ($allitems as $item) {
1816
            if ($index == $pos) {
1817
                $index++;
1818
            }
1819
            if ($item->id == $moveitem->id) {
1820
                $moveitem->position = $pos;
1821
                feedback_update_item($moveitem);
1822
                continue;
1823
            }
1824
            $item->position = $index;
1825
            feedback_update_item($item);
1826
            $index++;
1827
        }
1828
        return true;
1829
    }
1830
    return false;
1831
}
1832
 
1833
/**
1834
 * @deprecated since Moodle 3.1
1835
 */
1836
function feedback_print_item_preview() {
1837
    throw new coding_exception('feedback_print_item_preview() can not be used anymore. '
1838
            . 'Items must implement complete_form_element().');
1839
}
1840
 
1841
/**
1842
 * @deprecated since Moodle 3.1
1843
 */
1844
function feedback_print_item_complete() {
1845
    throw new coding_exception('feedback_print_item_complete() can not be used anymore. '
1846
        . 'Items must implement complete_form_element().');
1847
}
1848
 
1849
/**
1850
 * @deprecated since Moodle 3.1
1851
 */
1852
function feedback_print_item_show_value() {
1853
    throw new coding_exception('feedback_print_item_show_value() can not be used anymore. '
1854
        . 'Items must implement complete_form_element().');
1855
}
1856
 
1857
/**
1858
 * if the user completes a feedback and there is a pagebreak so the values are saved temporary.
1859
 * the values are not saved permanently until the user click on save button
1860
 *
1861
 * @global object
1862
 * @param object $feedbackcompleted
1863
 * @return object temporary saved completed-record
1864
 */
1865
function feedback_set_tmp_values($feedbackcompleted) {
1866
    global $DB;
1867
 
1868
    //first we create a completedtmp
1869
    $tmpcpl = new stdClass();
1870
    foreach ($feedbackcompleted as $key => $value) {
1871
        $tmpcpl->{$key} = $value;
1872
    }
1873
    unset($tmpcpl->id);
1874
    $tmpcpl->timemodified = time();
1875
    $tmpcpl->id = $DB->insert_record('feedback_completedtmp', $tmpcpl);
1876
    //get all values of original-completed
1877
    if (!$values = $DB->get_records('feedback_value', array('completed'=>$feedbackcompleted->id))) {
1878
        return;
1879
    }
1880
    foreach ($values as $value) {
1881
        unset($value->id);
1882
        $value->completed = $tmpcpl->id;
1883
        $DB->insert_record('feedback_valuetmp', $value);
1884
    }
1885
    return $tmpcpl;
1886
}
1887
 
1888
/**
1889
 * this saves the temporary saved values permanently
1890
 *
1891
 * @global object
1892
 * @param object $feedbackcompletedtmp the temporary completed
1893
 * @param stdClass|null $feedbackcompleted the target completed
1894
 * @return int the id of the completed
1895
 */
1896
function feedback_save_tmp_values($feedbackcompletedtmp, ?stdClass $feedbackcompleted = null) {
1897
    global $DB;
1898
 
1899
    $tmpcplid = $feedbackcompletedtmp->id;
1900
    if ($feedbackcompleted) {
1901
        //first drop all existing values
1902
        $DB->delete_records('feedback_value', array('completed'=>$feedbackcompleted->id));
1903
        //update the current completed
1904
        $feedbackcompleted->timemodified = time();
1905
        $DB->update_record('feedback_completed', $feedbackcompleted);
1906
    } else {
1907
        $feedbackcompleted = clone($feedbackcompletedtmp);
1908
        $feedbackcompleted->id = '';
1909
        $feedbackcompleted->timemodified = time();
1910
        $feedbackcompleted->id = $DB->insert_record('feedback_completed', $feedbackcompleted);
1911
    }
1912
 
1913
    $allitems = $DB->get_records('feedback_item', array('feedback' => $feedbackcompleted->feedback));
1914
 
1915
    //save all the new values from feedback_valuetmp
1916
    //get all values of tmp-completed
1917
    $params = array('completed'=>$feedbackcompletedtmp->id);
1918
    $values = $DB->get_records('feedback_valuetmp', $params);
1919
    foreach ($values as $value) {
1920
        //check if there are depend items
1921
        $item = $DB->get_record('feedback_item', array('id'=>$value->item));
1922
        if ($item->dependitem > 0 && isset($allitems[$item->dependitem])) {
1923
            $ditem = $allitems[$item->dependitem];
1924
            while ($ditem !== null) {
1925
                $check = feedback_compare_item_value($tmpcplid,
1926
                                            $ditem,
1927
                                            $item->dependvalue,
1928
                                            true);
1929
                if (!$check) {
1930
                    break;
1931
                }
1932
                if ($ditem->dependitem > 0 && isset($allitems[$ditem->dependitem])) {
1933
                    $item = $ditem;
1934
                    $ditem = $allitems[$ditem->dependitem];
1935
                } else {
1936
                    $ditem = null;
1937
                }
1938
            }
1939
 
1940
        } else {
1941
            $check = true;
1942
        }
1943
        if ($check) {
1944
            unset($value->id);
1945
            $value->completed = $feedbackcompleted->id;
1946
            $DB->insert_record('feedback_value', $value);
1947
        }
1948
    }
1949
    //drop all the tmpvalues
1950
    $DB->delete_records('feedback_valuetmp', array('completed'=>$tmpcplid));
1951
    $DB->delete_records('feedback_completedtmp', array('id'=>$tmpcplid));
1952
 
1953
    // Trigger event for the delete action we performed.
1954
    $cm = get_coursemodule_from_instance('feedback', $feedbackcompleted->feedback);
1955
    $event = \mod_feedback\event\response_submitted::create_from_record($feedbackcompleted, $cm);
1956
    $event->trigger();
1957
    return $feedbackcompleted->id;
1958
 
1959
}
1960
 
1961
/**
1962
 * @deprecated since Moodle 3.1
1963
 */
1964
function feedback_delete_completedtmp() {
1965
    throw new coding_exception('feedback_delete_completedtmp() can not be used anymore.');
1966
 
1967
}
1968
 
1969
////////////////////////////////////////////////
1970
////////////////////////////////////////////////
1971
////////////////////////////////////////////////
1972
//functions to handle the pagebreaks
1973
////////////////////////////////////////////////
1974
 
1975
/**
1976
 * this creates a pagebreak.
1977
 * a pagebreak is a special kind of item
1978
 *
1979
 * @global object
1980
 * @param int $feedbackid
1981
 * @return int|false false if there already is a pagebreak on last position or the id of the pagebreak-item
1982
 */
1983
function feedback_create_pagebreak($feedbackid) {
1984
    global $DB;
1985
 
1986
    //check if there already is a pagebreak on the last position
1987
    $lastposition = $DB->count_records('feedback_item', array('feedback'=>$feedbackid));
1988
    if ($lastposition == feedback_get_last_break_position($feedbackid)) {
1989
        return false;
1990
    }
1991
 
1992
    $item = new stdClass();
1993
    $item->feedback = $feedbackid;
1994
 
1995
    $item->template=0;
1996
 
1997
    $item->name = '';
1998
 
1999
    $item->presentation = '';
2000
    $item->hasvalue = 0;
2001
 
2002
    $item->typ = 'pagebreak';
2003
    $item->position = $lastposition + 1;
2004
 
2005
    $item->required=0;
2006
 
2007
    return $DB->insert_record('feedback_item', $item);
2008
}
2009
 
2010
/**
2011
 * get all positions of pagebreaks in the given feedback
2012
 *
2013
 * @global object
2014
 * @param int $feedbackid
2015
 * @return array all ordered pagebreak positions
2016
 */
2017
function feedback_get_all_break_positions($feedbackid) {
2018
    global $DB;
2019
 
2020
    $params = array('typ'=>'pagebreak', 'feedback'=>$feedbackid);
2021
    $allbreaks = $DB->get_records_menu('feedback_item', $params, 'position', 'id, position');
2022
    if (!$allbreaks) {
2023
        return false;
2024
    }
2025
    return array_values($allbreaks);
2026
}
2027
 
2028
/**
2029
 * get the position of the last pagebreak
2030
 *
2031
 * @param int $feedbackid
2032
 * @return int the position of the last pagebreak
2033
 */
2034
function feedback_get_last_break_position($feedbackid) {
2035
    if (!$allbreaks = feedback_get_all_break_positions($feedbackid)) {
2036
        return false;
2037
    }
2038
    return $allbreaks[count($allbreaks) - 1];
2039
}
2040
 
2041
/**
2042
 * @deprecated since Moodle 3.1
2043
 */
2044
function feedback_get_page_to_continue() {
2045
    throw new coding_exception('feedback_get_page_to_continue() can not be used anymore.');
2046
}
2047
 
2048
////////////////////////////////////////////////
2049
////////////////////////////////////////////////
2050
////////////////////////////////////////////////
2051
//functions to handle the values
2052
////////////////////////////////////////////////
2053
 
2054
/**
2055
 * @deprecated since Moodle 3.1
2056
 */
2057
function feedback_clean_input_value() {
2058
    throw new coding_exception('feedback_clean_input_value() can not be used anymore. '
2059
        . 'Items must implement complete_form_element().');
2060
 
2061
}
2062
 
2063
/**
2064
 * @deprecated since Moodle 3.1
2065
 */
2066
function feedback_save_values() {
2067
    throw new coding_exception('feedback_save_values() can not be used anymore.');
2068
}
2069
 
2070
/**
2071
 * @deprecated since Moodle 3.1
2072
 */
2073
function feedback_save_guest_values() {
2074
    throw new coding_exception('feedback_save_guest_values() can not be used anymore.');
2075
}
2076
 
2077
/**
2078
 * get the value from the given item related to the given completed.
2079
 * the value can come as temporary or as permanently value. the deciding is done by $tmp
2080
 *
2081
 * @global object
2082
 * @param int $completeid
2083
 * @param int $itemid
2084
 * @param boolean $tmp
2085
 * @return mixed the value, the type depends on plugin-definition
2086
 */
2087
function feedback_get_item_value($completedid, $itemid, $tmp = false) {
2088
    global $DB;
2089
 
2090
    $tmpstr = $tmp ? 'tmp' : '';
2091
    $params = array('completed'=>$completedid, 'item'=>$itemid);
2092
    return $DB->get_field('feedback_value'.$tmpstr, 'value', $params);
2093
}
2094
 
2095
/**
2096
 * compares the value of the itemid related to the completedid with the dependvalue.
2097
 * this is used if a depend item is set.
2098
 * the value can come as temporary or as permanently value. the deciding is done by $tmp.
2099
 *
2100
 * @param int $completedid
2101
 * @param stdClass|int $item
2102
 * @param mixed $dependvalue
2103
 * @param bool $tmp
2104
 * @return bool
2105
 */
2106
function feedback_compare_item_value($completedid, $item, $dependvalue, $tmp = false) {
2107
    global $DB;
2108
 
2109
    if (is_int($item)) {
2110
        $item = $DB->get_record('feedback_item', array('id' => $item));
2111
    }
2112
 
2113
    $dbvalue = feedback_get_item_value($completedid, $item->id, $tmp);
2114
 
2115
    $itemobj = feedback_get_item_class($item->typ);
2116
    return $itemobj->compare_value($item, $dbvalue, $dependvalue); //true or false
2117
}
2118
 
2119
/**
2120
 * @deprecated since Moodle 3.1
2121
 */
2122
function feedback_check_values() {
2123
    throw new coding_exception('feedback_check_values() can not be used anymore. '
2124
        . 'Items must implement complete_form_element().');
2125
}
2126
 
2127
/**
2128
 * @deprecated since Moodle 3.1
2129
 */
2130
function feedback_create_values() {
2131
    throw new coding_exception('feedback_create_values() can not be used anymore.');
2132
}
2133
 
2134
/**
2135
 * @deprecated since Moodle 3.1
2136
 */
2137
function feedback_update_values() {
2138
    throw new coding_exception('feedback_update_values() can not be used anymore.');
2139
}
2140
 
2141
/**
2142
 * get the values of an item depending on the given groupid.
2143
 * if the feedback is anonymous so the values are shuffled
2144
 *
2145
 * @global object
2146
 * @global object
2147
 * @param object $item
2148
 * @param int $groupid
2149
 * @param int $courseid
2150
 * @param bool $ignore_empty if this is set true so empty values are not delivered
2151
 * @return array the value-records
2152
 */
2153
function feedback_get_group_values($item,
2154
                                   $groupid = false,
2155
                                   $courseid = false,
2156
                                   $ignore_empty = false) {
2157
 
2158
    global $CFG, $DB;
2159
 
2160
    //if the groupid is given?
2161
    if (intval($groupid) > 0) {
2162
        $params = array();
2163
        if ($ignore_empty) {
2164
            $value = $DB->sql_compare_text('fbv.value');
2165
            $ignore_empty_select = "AND $value != :emptyvalue AND $value != :zerovalue";
2166
            $params += array('emptyvalue' => '', 'zerovalue' => '0');
2167
        } else {
2168
            $ignore_empty_select = "";
2169
        }
2170
 
2171
        $query = 'SELECT fbv .  *
2172
                    FROM {feedback_value} fbv, {feedback_completed} fbc, {groups_members} gm
2173
                   WHERE fbv.item = :itemid
2174
                         AND fbv.completed = fbc.id
2175
                         AND fbc.userid = gm.userid
2176
                         '.$ignore_empty_select.'
2177
                         AND gm.groupid = :groupid
2178
                ORDER BY fbc.timemodified';
2179
        $params += array('itemid' => $item->id, 'groupid' => $groupid);
2180
        $values = $DB->get_records_sql($query, $params);
2181
 
2182
    } else {
2183
        $params = array();
2184
        if ($ignore_empty) {
2185
            $value = $DB->sql_compare_text('value');
2186
            $ignore_empty_select = "AND $value != :emptyvalue AND $value != :zerovalue";
2187
            $params += array('emptyvalue' => '', 'zerovalue' => '0');
2188
        } else {
2189
            $ignore_empty_select = "";
2190
        }
2191
 
2192
        if ($courseid) {
2193
            $select = "item = :itemid AND course_id = :courseid ".$ignore_empty_select;
2194
            $params += array('itemid' => $item->id, 'courseid' => $courseid);
2195
            $values = $DB->get_records_select('feedback_value', $select, $params);
2196
        } else {
2197
            $select = "item = :itemid ".$ignore_empty_select;
2198
            $params += array('itemid' => $item->id);
2199
            $values = $DB->get_records_select('feedback_value', $select, $params);
2200
        }
2201
    }
2202
    $params = array('id'=>$item->feedback);
2203
    if ($DB->get_field('feedback', 'anonymous', $params) == FEEDBACK_ANONYMOUS_YES) {
2204
        if (is_array($values)) {
2205
            shuffle($values);
2206
        }
2207
    }
2208
    return $values;
2209
}
2210
 
2211
/**
2212
 * check for multiple_submit = false.
2213
 * if the feedback is global so the courseid must be given
2214
 *
2215
 * @global object
2216
 * @global object
2217
 * @param int $feedbackid
2218
 * @param int $courseid
2219
 * @return boolean true if the feedback already is submitted otherwise false
2220
 */
2221
function feedback_is_already_submitted($feedbackid, $courseid = false) {
2222
    global $USER, $DB;
2223
 
2224
    if (!isloggedin() || isguestuser()) {
2225
        return false;
2226
    }
2227
 
2228
    $params = array('userid' => $USER->id, 'feedback' => $feedbackid);
2229
    if ($courseid) {
2230
        $params['courseid'] = $courseid;
2231
    }
2232
    return $DB->record_exists('feedback_completed', $params);
2233
}
2234
 
2235
/**
2236
 * @deprecated since Moodle 3.1. Use feedback_get_current_completed_tmp() or feedback_get_last_completed.
2237
 */
2238
function feedback_get_current_completed() {
2239
    throw new coding_exception('feedback_get_current_completed() can not be used anymore. Please ' .
2240
            'use either feedback_get_current_completed_tmp() or feedback_get_last_completed()');
2241
}
2242
 
2243
/**
2244
 * get the completeds depending on the given groupid.
2245
 *
2246
 * @global object
2247
 * @global object
2248
 * @param object $feedback
2249
 * @param int $groupid
2250
 * @param int $courseid
2251
 * @return mixed array of found completeds otherwise false
2252
 */
2253
function feedback_get_completeds_group($feedback, $groupid = false, $courseid = false) {
2254
    global $CFG, $DB;
2255
 
2256
    if (intval($groupid) > 0) {
2257
        $query = "SELECT fbc.*
2258
                    FROM {feedback_completed} fbc, {groups_members} gm
2259
                   WHERE fbc.feedback = ?
2260
                         AND gm.groupid = ?
2261
                         AND fbc.userid = gm.userid";
2262
        if ($values = $DB->get_records_sql($query, array($feedback->id, $groupid))) {
2263
            return $values;
2264
        } else {
2265
            return false;
2266
        }
2267
    } else {
2268
        if ($courseid) {
2269
            $query = "SELECT DISTINCT fbc.*
2270
                        FROM {feedback_completed} fbc, {feedback_value} fbv
2271
                        WHERE fbc.id = fbv.completed
2272
                            AND fbc.feedback = ?
2273
                            AND fbv.course_id = ?
2274
                        ORDER BY random_response";
2275
            if ($values = $DB->get_records_sql($query, array($feedback->id, $courseid))) {
2276
                return $values;
2277
            } else {
2278
                return false;
2279
            }
2280
        } else {
2281
            if ($values = $DB->get_records('feedback_completed', array('feedback'=>$feedback->id))) {
2282
                return $values;
2283
            } else {
2284
                return false;
2285
            }
2286
        }
2287
    }
2288
}
2289
 
2290
/**
2291
 * get the count of completeds depending on the given groupid.
2292
 *
2293
 * @global object
2294
 * @global object
2295
 * @param object $feedback
2296
 * @param int $groupid
2297
 * @param int $courseid
2298
 * @return mixed count of completeds or false
2299
 */
2300
function feedback_get_completeds_group_count($feedback, $groupid = false, $courseid = false) {
2301
    global $CFG, $DB;
2302
 
2303
    if ($courseid > 0 AND !$groupid <= 0) {
2304
        $sql = "SELECT id, COUNT(item) AS ci
2305
                  FROM {feedback_value}
2306
                 WHERE course_id  = ?
2307
              GROUP BY item ORDER BY ci DESC";
2308
        if ($foundrecs = $DB->get_records_sql($sql, array($courseid))) {
2309
            $foundrecs = array_values($foundrecs);
2310
            return $foundrecs[0]->ci;
2311
        }
2312
        return false;
2313
    }
2314
    if ($values = feedback_get_completeds_group($feedback, $groupid)) {
2315
        return count($values);
2316
    } else {
2317
        return false;
2318
    }
2319
}
2320
 
2321
/**
2322
 * deletes all completed-recordsets from a feedback.
2323
 * all related data such as values also will be deleted
2324
 *
2325
 * @param stdClass|int $feedback
2326
 * @param stdClass|cm_info $cm
2327
 * @param stdClass $course
2328
 * @return void
2329
 */
2330
function feedback_delete_all_completeds($feedback, $cm = null, $course = null) {
2331
    global $DB;
2332
 
2333
    if (is_int($feedback)) {
2334
        $feedback = $DB->get_record('feedback', array('id' => $feedback));
2335
    }
2336
 
2337
    if (!$completeds = $DB->get_records('feedback_completed', array('feedback' => $feedback->id))) {
2338
        return;
2339
    }
2340
 
2341
    if (!$course && !($course = $DB->get_record('course', array('id' => $feedback->course)))) {
2342
        return false;
2343
    }
2344
 
2345
    if (!$cm && !($cm = get_coursemodule_from_instance('feedback', $feedback->id))) {
2346
        return false;
2347
    }
2348
 
2349
    foreach ($completeds as $completed) {
2350
        feedback_delete_completed($completed, $feedback, $cm, $course);
2351
    }
2352
}
2353
 
2354
/**
2355
 * deletes a completed given by completedid.
2356
 * all related data such values or tracking data also will be deleted
2357
 *
2358
 * @param int|stdClass $completed
2359
 * @param stdClass $feedback
2360
 * @param stdClass|cm_info $cm
2361
 * @param stdClass $course
2362
 * @return boolean
2363
 */
2364
function feedback_delete_completed($completed, $feedback = null, $cm = null, $course = null) {
2365
    global $DB, $CFG;
2366
    require_once($CFG->libdir.'/completionlib.php');
2367
 
2368
    if (!isset($completed->id)) {
2369
        if (!$completed = $DB->get_record('feedback_completed', array('id' => $completed))) {
2370
            return false;
2371
        }
2372
    }
2373
 
2374
    if (!$feedback && !($feedback = $DB->get_record('feedback', array('id' => $completed->feedback)))) {
2375
        return false;
2376
    }
2377
 
2378
    if (!$course && !($course = $DB->get_record('course', array('id' => $feedback->course)))) {
2379
        return false;
2380
    }
2381
 
2382
    if (!$cm && !($cm = get_coursemodule_from_instance('feedback', $feedback->id))) {
2383
        return false;
2384
    }
2385
 
2386
    //first we delete all related values
2387
    $DB->delete_records('feedback_value', array('completed' => $completed->id));
2388
 
2389
    // Delete the completed record.
2390
    $return = $DB->delete_records('feedback_completed', array('id' => $completed->id));
2391
 
2392
    // Update completion state
2393
    $completion = new completion_info($course);
2394
    if ($completion->is_enabled($cm) && $cm->completion == COMPLETION_TRACKING_AUTOMATIC && $feedback->completionsubmit) {
2395
        $completion->update_state($cm, COMPLETION_INCOMPLETE, $completed->userid);
2396
    }
2397
    // Trigger event for the delete action we performed.
2398
    $event = \mod_feedback\event\response_deleted::create_from_record($completed, $cm, $feedback);
2399
    $event->trigger();
2400
 
2401
    return $return;
2402
}
2403
 
2404
////////////////////////////////////////////////
2405
////////////////////////////////////////////////
2406
////////////////////////////////////////////////
2407
//functions to handle sitecourse mapping
2408
////////////////////////////////////////////////
2409
 
2410
/**
2411
 * @deprecated since 3.1
2412
 */
2413
function feedback_is_course_in_sitecourse_map() {
2414
    throw new coding_exception('feedback_is_course_in_sitecourse_map() can not be used anymore.');
2415
}
2416
 
2417
/**
2418
 * @deprecated since 3.1
2419
 */
2420
function feedback_is_feedback_in_sitecourse_map() {
2421
    throw new coding_exception('feedback_is_feedback_in_sitecourse_map() can not be used anymore.');
2422
}
2423
 
2424
/**
2425
 * gets the feedbacks from table feedback_sitecourse_map.
2426
 * this is used to show the global feedbacks on the feedback block
2427
 * all feedbacks with the following criteria will be selected:<br />
2428
 *
2429
 * 1) all feedbacks which id are listed together with the courseid in sitecoursemap and<br />
2430
 * 2) all feedbacks which not are listed in sitecoursemap
2431
 *
2432
 * @global object
2433
 * @param int $courseid
2434
 * @return array the feedback-records
2435
 */
2436
function feedback_get_feedbacks_from_sitecourse_map($courseid) {
2437
    global $DB;
2438
 
2439
    //first get all feedbacks listed in sitecourse_map with named courseid
2440
    $sql = "SELECT f.id AS id,
2441
                   cm.id AS cmid,
2442
                   f.name AS name,
2443
                   f.timeopen AS timeopen,
2444
                   f.timeclose AS timeclose
2445
            FROM {feedback} f, {course_modules} cm, {feedback_sitecourse_map} sm, {modules} m
2446
            WHERE f.id = cm.instance
2447
                   AND f.course = '".SITEID."'
2448
                   AND m.id = cm.module
2449
                   AND m.name = 'feedback'
2450
                   AND sm.courseid = ?
2451
                   AND sm.feedbackid = f.id";
2452
 
2453
    if (!$feedbacks1 = $DB->get_records_sql($sql, array($courseid))) {
2454
        $feedbacks1 = array();
2455
    }
2456
 
2457
    //second get all feedbacks not listed in sitecourse_map
2458
    $feedbacks2 = array();
2459
    $sql = "SELECT f.id AS id,
2460
                   cm.id AS cmid,
2461
                   f.name AS name,
2462
                   f.timeopen AS timeopen,
2463
                   f.timeclose AS timeclose
2464
            FROM {feedback} f, {course_modules} cm, {modules} m
2465
            WHERE f.id = cm.instance
2466
                   AND f.course = '".SITEID."'
2467
                   AND m.id = cm.module
2468
                   AND m.name = 'feedback'";
2469
    if (!$allfeedbacks = $DB->get_records_sql($sql)) {
2470
        $allfeedbacks = array();
2471
    }
2472
    foreach ($allfeedbacks as $a) {
2473
        if (!$DB->record_exists('feedback_sitecourse_map', array('feedbackid'=>$a->id))) {
2474
            $feedbacks2[] = $a;
2475
        }
2476
    }
2477
 
2478
    $feedbacks = array_merge($feedbacks1, $feedbacks2);
2479
    $modinfo = get_fast_modinfo(SITEID);
2480
    return array_filter($feedbacks, function($f) use ($modinfo) {
2481
        return ($cm = $modinfo->get_cm($f->cmid)) && $cm->uservisible;
2482
    });
2483
 
2484
}
2485
 
2486
/**
2487
 * Gets the courses from table feedback_sitecourse_map
2488
 *
2489
 * @param int $feedbackid
2490
 * @return array the course-records
2491
 */
2492
function feedback_get_courses_from_sitecourse_map($feedbackid) {
2493
    global $DB;
2494
 
2495
    $sql = "SELECT c.id, c.fullname, c.shortname
2496
              FROM {feedback_sitecourse_map} f, {course} c
2497
             WHERE c.id = f.courseid
2498
                   AND f.feedbackid = ?
2499
          ORDER BY c.fullname";
2500
 
2501
    return $DB->get_records_sql($sql, array($feedbackid));
2502
 
2503
}
2504
 
2505
/**
2506
 * Updates the course mapping for the feedback
2507
 *
2508
 * @param stdClass $feedback
2509
 * @param array $courses array of course ids
2510
 */
2511
function feedback_update_sitecourse_map($feedback, $courses) {
2512
    global $DB;
2513
    if (empty($courses)) {
2514
        $courses = array();
2515
    }
2516
    $currentmapping = $DB->get_fieldset_select('feedback_sitecourse_map', 'courseid', 'feedbackid=?', array($feedback->id));
2517
    foreach (array_diff($courses, $currentmapping) as $courseid) {
2518
        $DB->insert_record('feedback_sitecourse_map', array('feedbackid' => $feedback->id, 'courseid' => $courseid));
2519
    }
2520
    foreach (array_diff($currentmapping, $courses) as $courseid) {
2521
        $DB->delete_records('feedback_sitecourse_map', array('feedbackid' => $feedback->id, 'courseid' => $courseid));
2522
    }
2523
    // TODO MDL-53574 add events.
2524
}
2525
 
2526
/**
2527
 * @deprecated since 3.1
2528
 */
2529
function feedback_clean_up_sitecourse_map() {
2530
    throw new coding_exception('feedback_clean_up_sitecourse_map() can not be used anymore.');
2531
}
2532
 
2533
////////////////////////////////////////////////
2534
////////////////////////////////////////////////
2535
////////////////////////////////////////////////
2536
//not relatable functions
2537
////////////////////////////////////////////////
2538
 
2539
/**
2540
 * @deprecated since 3.1
2541
 */
2542
function feedback_print_numeric_option_list() {
2543
    throw new coding_exception('feedback_print_numeric_option_list() can not be used anymore.');
2544
}
2545
 
2546
/**
2547
 * sends an email to the teachers of the course where the given feedback is placed.
2548
 *
2549
 * @global object
2550
 * @global object
2551
 * @uses FEEDBACK_ANONYMOUS_NO
2552
 * @uses FORMAT_PLAIN
2553
 * @param object $cm the coursemodule-record
2554
 * @param object $feedback
2555
 * @param object $course
2556
 * @param stdClass|int $user
2557
 * @param stdClass $completed record from feedback_completed if known
2558
 * @return void
2559
 */
2560
function feedback_send_email($cm, $feedback, $course, $user, $completed = null) {
2561
    global $CFG, $DB, $PAGE;
2562
 
2563
    if ($feedback->email_notification == 0) {  // No need to do anything
2564
        return;
2565
    }
2566
 
2567
    if (!is_object($user)) {
2568
        $user = $DB->get_record('user', array('id' => $user));
2569
    }
2570
 
2571
    if (isset($cm->groupmode) && empty($course->groupmodeforce)) {
2572
        $groupmode =  $cm->groupmode;
2573
    } else {
2574
        $groupmode = $course->groupmode;
2575
    }
2576
 
2577
    if ($groupmode == SEPARATEGROUPS) {
2578
        $groups = $DB->get_records_sql_menu("SELECT g.name, g.id
2579
                                               FROM {groups} g, {groups_members} m
2580
                                              WHERE g.courseid = ?
2581
                                                    AND g.id = m.groupid
2582
                                                    AND m.userid = ?
2583
                                           ORDER BY name ASC", array($course->id, $user->id));
2584
        $groups = array_values($groups);
2585
 
2586
        $teachers = feedback_get_receivemail_users($cm->id, $groups);
2587
    } else {
2588
        $teachers = feedback_get_receivemail_users($cm->id);
2589
    }
2590
 
2591
    if ($teachers) {
2592
 
2593
        $strfeedbacks = get_string('modulenameplural', 'feedback');
2594
        $strfeedback  = get_string('modulename', 'feedback');
2595
 
2596
        if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
2597
            $printusername = fullname($user);
2598
        } else {
2599
            $printusername = get_string('anonymous_user', 'feedback');
2600
        }
2601
 
2602
        foreach ($teachers as $teacher) {
2603
            $info = new stdClass();
2604
            $info->username = $printusername;
2605
            $info->feedback = format_string($feedback->name, true);
2606
            $info->url = $CFG->wwwroot.'/mod/feedback/show_entries.php?'.
2607
                            'id='.$cm->id.'&'.
2608
                            'userid=' . $user->id;
2609
            if ($completed) {
2610
                $info->url .= '&showcompleted=' . $completed->id;
2611
                if ($feedback->course == SITEID) {
2612
                    // Course where feedback was completed (for site feedbacks only).
2613
                    $info->url .= '&courseid=' . $completed->courseid;
2614
                }
2615
            }
2616
 
2617
            $a = array('username' => $info->username, 'feedbackname' => $feedback->name);
2618
 
2619
            $postsubject = get_string('feedbackcompleted', 'feedback', $a);
2620
            $posttext = feedback_send_email_text($info, $course);
2621
 
2622
            if ($teacher->mailformat == 1) {
2623
                $posthtml = feedback_send_email_html($info, $course, $cm);
2624
            } else {
2625
                $posthtml = '';
2626
            }
2627
 
2628
            $customdata = [
2629
                'cmid' => $cm->id,
2630
                'instance' => $feedback->id,
2631
            ];
2632
            if ($feedback->anonymous == FEEDBACK_ANONYMOUS_NO) {
2633
                $eventdata = new \core\message\message();
2634
                $eventdata->anonymous        = false;
2635
                $eventdata->courseid         = $course->id;
2636
                $eventdata->name             = 'submission';
2637
                $eventdata->component        = 'mod_feedback';
2638
                $eventdata->userfrom         = $user;
2639
                $eventdata->userto           = $teacher;
2640
                $eventdata->subject          = $postsubject;
2641
                $eventdata->fullmessage      = $posttext;
2642
                $eventdata->fullmessageformat = FORMAT_PLAIN;
2643
                $eventdata->fullmessagehtml  = $posthtml;
2644
                $eventdata->smallmessage     = '';
2645
                $eventdata->courseid         = $course->id;
2646
                $eventdata->contexturl       = $info->url;
2647
                $eventdata->contexturlname   = $info->feedback;
2648
                // User image.
2649
                $userpicture = new user_picture($user);
2650
                $userpicture->size = 1; // Use f1 size.
2651
                $userpicture->includetoken = $teacher->id; // Generate an out-of-session token for the user receiving the message.
2652
                $customdata['notificationiconurl'] = $userpicture->get_url($PAGE)->out(false);
2653
                $eventdata->customdata = $customdata;
2654
                message_send($eventdata);
2655
            } else {
2656
                $eventdata = new \core\message\message();
2657
                $eventdata->anonymous        = true;
2658
                $eventdata->courseid         = $course->id;
2659
                $eventdata->name             = 'submission';
2660
                $eventdata->component        = 'mod_feedback';
2661
                $eventdata->userfrom         = $teacher;
2662
                $eventdata->userto           = $teacher;
2663
                $eventdata->subject          = $postsubject;
2664
                $eventdata->fullmessage      = $posttext;
2665
                $eventdata->fullmessageformat = FORMAT_PLAIN;
2666
                $eventdata->fullmessagehtml  = $posthtml;
2667
                $eventdata->smallmessage     = '';
2668
                $eventdata->courseid         = $course->id;
2669
                $eventdata->contexturl       = $info->url;
2670
                $eventdata->contexturlname   = $info->feedback;
2671
                // Feedback icon if can be easily reachable.
2672
                $customdata['notificationiconurl'] = ($cm instanceof cm_info) ? $cm->get_icon_url()->out() : '';
2673
                $eventdata->customdata = $customdata;
2674
                message_send($eventdata);
2675
            }
2676
        }
2677
    }
2678
}
2679
 
2680
/**
2681
 * sends an email to the teachers of the course where the given feedback is placed.
2682
 *
2683
 * @global object
2684
 * @uses FORMAT_PLAIN
2685
 * @param object $cm the coursemodule-record
2686
 * @param object $feedback
2687
 * @param object $course
2688
 * @return void
2689
 */
2690
function feedback_send_email_anonym($cm, $feedback, $course) {
2691
    global $CFG;
2692
 
2693
    if ($feedback->email_notification == 0) { // No need to do anything
2694
        return;
2695
    }
2696
 
2697
    $teachers = feedback_get_receivemail_users($cm->id);
2698
 
2699
    if ($teachers) {
2700
 
2701
        $strfeedbacks = get_string('modulenameplural', 'feedback');
2702
        $strfeedback  = get_string('modulename', 'feedback');
2703
        $printusername = get_string('anonymous_user', 'feedback');
2704
 
2705
        foreach ($teachers as $teacher) {
2706
            $info = new stdClass();
2707
            $info->username = $printusername;
2708
            $info->feedback = format_string($feedback->name, true);
2709
            $info->url = $CFG->wwwroot.'/mod/feedback/show_entries.php?id=' . $cm->id;
2710
 
2711
            $a = array('username' => $info->username, 'feedbackname' => $feedback->name);
2712
 
2713
            $postsubject = get_string('feedbackcompleted', 'feedback', $a);
2714
            $posttext = feedback_send_email_text($info, $course);
2715
 
2716
            if ($teacher->mailformat == 1) {
2717
                $posthtml = feedback_send_email_html($info, $course, $cm);
2718
            } else {
2719
                $posthtml = '';
2720
            }
2721
 
2722
            $eventdata = new \core\message\message();
2723
            $eventdata->anonymous        = true;
2724
            $eventdata->courseid         = $course->id;
2725
            $eventdata->name             = 'submission';
2726
            $eventdata->component        = 'mod_feedback';
2727
            $eventdata->userfrom         = $teacher;
2728
            $eventdata->userto           = $teacher;
2729
            $eventdata->subject          = $postsubject;
2730
            $eventdata->fullmessage      = $posttext;
2731
            $eventdata->fullmessageformat = FORMAT_PLAIN;
2732
            $eventdata->fullmessagehtml  = $posthtml;
2733
            $eventdata->smallmessage     = '';
2734
            $eventdata->courseid         = $course->id;
2735
            $eventdata->contexturl       = $info->url;
2736
            $eventdata->contexturlname   = $info->feedback;
2737
            $eventdata->customdata       = [
2738
                'cmid' => $cm->id,
2739
                'instance' => $feedback->id,
2740
                'notificationiconurl' => ($cm instanceof cm_info) ? $cm->get_icon_url()->out() : '',  // Performance wise.
2741
            ];
2742
 
2743
            message_send($eventdata);
2744
        }
2745
    }
2746
}
2747
 
2748
/**
2749
 * send the text-part of the email
2750
 *
2751
 * @param object $info includes some infos about the feedback you want to send
2752
 * @param object $course
2753
 * @return string the text you want to post
2754
 */
2755
function feedback_send_email_text($info, $course) {
2756
    $coursecontext = context_course::instance($course->id);
2757
    $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2758
    $posttext  = $courseshortname.' -> '.get_string('modulenameplural', 'feedback').' -> '.
2759
                    $info->feedback."\n";
2760
    $posttext .= '---------------------------------------------------------------------'."\n";
2761
    $posttext .= get_string("emailteachermail", "feedback", $info)."\n";
2762
    $posttext .= '---------------------------------------------------------------------'."\n";
2763
    return $posttext;
2764
}
2765
 
2766
 
2767
/**
2768
 * send the html-part of the email
2769
 *
2770
 * @global object
2771
 * @param object $info includes some infos about the feedback you want to send
2772
 * @param object $course
2773
 * @return string the text you want to post
2774
 */
2775
function feedback_send_email_html($info, $course, $cm) {
2776
    global $CFG;
2777
    $coursecontext = context_course::instance($course->id);
2778
    $courseshortname = format_string($course->shortname, true, array('context' => $coursecontext));
2779
    $course_url = $CFG->wwwroot.'/course/view.php?id='.$course->id;
2780
    $feedback_all_url = $CFG->wwwroot.'/mod/feedback/index.php?id='.$course->id;
2781
    $feedback_url = $CFG->wwwroot.'/mod/feedback/view.php?id='.$cm->id;
2782
 
2783
    $posthtml = '<p><font face="sans-serif">'.
2784
            '<a href="'.$course_url.'">'.$courseshortname.'</a> ->'.
2785
            '<a href="'.$feedback_all_url.'">'.get_string('modulenameplural', 'feedback').'</a> ->'.
2786
            '<a href="'.$feedback_url.'">'.$info->feedback.'</a></font></p>';
2787
    $posthtml .= '<hr /><font face="sans-serif">';
2788
    $posthtml .= '<p>'.get_string('emailteachermailhtml', 'feedback', $info).'</p>';
2789
    $posthtml .= '</font><hr />';
2790
    return $posthtml;
2791
}
2792
 
2793
/**
2794
 * @param string $url
2795
 * @return string
2796
 */
2797
function feedback_encode_target_url($url) {
2798
    if (strpos($url, '?')) {
2799
        list($part1, $part2) = explode('?', $url, 2); //maximal 2 parts
2800
        return $part1 . '?' . htmlentities($part2, ENT_COMPAT);
2801
    } else {
2802
        return $url;
2803
    }
2804
}
2805
 
2806
/**
2807
 * Adds module specific settings to the settings block
2808
 *
2809
 * @param settings_navigation $settings The settings navigation object
2810
 * @param navigation_node $feedbacknode The node to add module settings to
2811
 */
2812
function feedback_extend_settings_navigation(settings_navigation $settings, navigation_node $feedbacknode) {
2813
    $hassecondary = $settings->get_page()->has_secondary_navigation();
2814
    if (!$context = context_module::instance($settings->get_page()->cm->id, IGNORE_MISSING)) {
2815
        throw new \moodle_exception('badcontext');
2816
    }
2817
 
2818
    if (has_capability('mod/feedback:edititems', $context)) {
2819
        $questionnode = $feedbacknode->add(get_string('questions', 'feedback'), null,
2820
            navigation_node::TYPE_CUSTOM, null, 'questionnode');
2821
        $questionnode->add(get_string('edit_items', 'feedback'),
2822
            new moodle_url('/mod/feedback/edit.php', ['id' => $settings->get_page()->cm->id]));
2823
 
2824
        $questionnode->add(get_string('export_questions', 'feedback'),
2825
            new moodle_url('/mod/feedback/export.php', ['id' => $settings->get_page()->cm->id, 'action' => 'exportfile']));
2826
 
2827
        $questionnode->add(get_string('import_questions', 'feedback'),
2828
            new moodle_url('/mod/feedback/import.php', ['id' => $settings->get_page()->cm->id]));
2829
 
2830
        $feedbacknode->add(get_string('templates', 'feedback'),
2831
            new moodle_url('/mod/feedback/manage_templates.php', ['id' => $settings->get_page()->cm->id, 'mode' => 'manage']),
2832
            navigation_node::TYPE_CUSTOM, null, 'templatenode');
2833
    }
2834
 
2835
    if (has_capability('mod/feedback:mapcourse', $context) && $settings->get_page()->course->id == SITEID) {
2836
        $feedbacknode->add(get_string('mappedcourses', 'feedback'),
2837
            new moodle_url('/mod/feedback/mapcourse.php', ['id' => $settings->get_page()->cm->id]),
2838
            navigation_node::TYPE_CUSTOM, null, 'mapcourse');
2839
    }
2840
 
2841
    $feedback = $settings->get_page()->activityrecord;
2842
    if ($feedback->course == SITEID) {
2843
        $analysisnode = navigation_node::create(get_string('analysis', 'feedback'),
2844
            new moodle_url('/mod/feedback/analysis_course.php', ['id' => $settings->get_page()->cm->id]),
2845
            navigation_node::TYPE_CUSTOM, null, 'feedbackanalysis');
2846
    } else {
2847
        $analysisnode = navigation_node::create(get_string('analysis', 'feedback'),
2848
            new moodle_url('/mod/feedback/analysis.php', ['id' => $settings->get_page()->cm->id]),
2849
            navigation_node::TYPE_CUSTOM, null, 'feedbackanalysis');
2850
    }
2851
 
2852
    if (has_capability('mod/feedback:viewreports', $context)) {
2853
        $feedbacknode->add_node($analysisnode);
2854
        $feedbacknode->add(get_string(($hassecondary ? 'responses' : 'show_entries'), 'feedback'),
2855
            new moodle_url('/mod/feedback/show_entries.php', ['id' => $settings->get_page()->cm->id]),
2856
            navigation_node::TYPE_CUSTOM, null, 'responses');
2857
    } else {
2858
        $feedbackcompletion = new mod_feedback_completion($feedback, $context, $settings->get_page()->course->id);
2859
        if ($feedbackcompletion->can_view_analysis()) {
2860
            $feedbacknode->add_node($analysisnode);
2861
        }
2862
    }
2863
}
2864
 
2865
function feedback_init_feedback_session() {
2866
    //initialize the feedback-Session - not nice at all!!
2867
    global $SESSION;
2868
    if (!empty($SESSION)) {
2869
        if (!isset($SESSION->feedback) OR !is_object($SESSION->feedback)) {
2870
            $SESSION->feedback = new stdClass();
2871
        }
2872
    }
2873
}
2874
 
2875
/**
2876
 * Return a list of page types
2877
 * @param string $pagetype current page type
2878
 * @param stdClass $parentcontext Block's parent context
2879
 * @param stdClass $currentcontext Current context of block
2880
 */
2881
function feedback_page_type_list($pagetype, $parentcontext, $currentcontext) {
2882
    $module_pagetype = array('mod-feedback-*'=>get_string('page-mod-feedback-x', 'feedback'));
2883
    return $module_pagetype;
2884
}
2885
 
2886
/**
2887
 * Move save the items of the given $feedback in the order of $itemlist.
2888
 * @param string $itemlist a comma separated list with item ids
2889
 * @param stdClass $feedback
2890
 * @return bool true if success
2891
 */
2892
function feedback_ajax_saveitemorder($itemlist, $feedback) {
2893
    global $DB;
2894
 
2895
    $result = true;
2896
    $position = 0;
2897
    foreach ($itemlist as $itemid) {
2898
        $position++;
2899
        $result = $result && $DB->set_field('feedback_item',
2900
                                            'position',
2901
                                            $position,
2902
                                            array('id'=>$itemid, 'feedback'=>$feedback->id));
2903
    }
2904
    return $result;
2905
}
2906
 
2907
/**
2908
 * Checks if current user is able to view feedback on this course.
2909
 *
2910
 * @param stdClass $feedback
2911
 * @param context_module $context
2912
 * @param int $courseid
2913
 * @return bool
2914
 */
2915
function feedback_can_view_analysis($feedback, $context, $courseid = false) {
2916
    if (has_capability('mod/feedback:viewreports', $context)) {
2917
        return true;
2918
    }
2919
 
2920
    if (intval($feedback->publish_stats) != 1 ||
2921
            !has_capability('mod/feedback:viewanalysepage', $context)) {
2922
        return false;
2923
    }
2924
 
2925
    if (!isloggedin() || isguestuser()) {
2926
        // There is no tracking for the guests, assume that they can view analysis if condition above is satisfied.
2927
        return $feedback->course == SITEID;
2928
    }
2929
 
2930
    return feedback_is_already_submitted($feedback->id, $courseid);
2931
}
2932
 
2933
/**
2934
 * Get icon mapping for font-awesome.
2935
 */
2936
function mod_feedback_get_fontawesome_icon_map() {
2937
    return [
2938
        'mod_feedback:required' => 'fa-exclamation-circle',
2939
        'mod_feedback:notrequired' => 'fa-question-circle-o',
2940
    ];
2941
}
2942
 
2943
/**
2944
 * Check if the module has any update that affects the current user since a given time.
2945
 *
2946
 * @param  cm_info $cm course module data
2947
 * @param  int $from the time to check updates from
2948
 * @param  array $filter if we need to check only specific updates
2949
 * @return stdClass an object with the different type of areas indicating if they were updated or not
2950
 * @since Moodle 3.3
2951
 */
2952
function feedback_check_updates_since(cm_info $cm, $from, $filter = array()) {
2953
    global $DB, $USER, $CFG;
2954
 
2955
    $updates = course_check_module_updates_since($cm, $from, array(), $filter);
2956
 
2957
    // Check for new attempts.
2958
    $updates->attemptsfinished = (object) array('updated' => false);
2959
    $updates->attemptsunfinished = (object) array('updated' => false);
2960
    $select = 'feedback = ? AND userid = ? AND timemodified > ?';
2961
    $params = array($cm->instance, $USER->id, $from);
2962
 
2963
    $attemptsfinished = $DB->get_records_select('feedback_completed', $select, $params, '', 'id');
2964
    if (!empty($attemptsfinished)) {
2965
        $updates->attemptsfinished->updated = true;
2966
        $updates->attemptsfinished->itemids = array_keys($attemptsfinished);
2967
    }
2968
    $attemptsunfinished = $DB->get_records_select('feedback_completedtmp', $select, $params, '', 'id');
2969
    if (!empty($attemptsunfinished)) {
2970
        $updates->attemptsunfinished->updated = true;
2971
        $updates->attemptsunfinished->itemids = array_keys($attemptsunfinished);
2972
    }
2973
 
2974
    // Now, teachers should see other students updates.
2975
    if (has_capability('mod/feedback:viewreports', $cm->context)) {
2976
        $select = 'feedback = ? AND timemodified > ?';
2977
        $params = array($cm->instance, $from);
2978
 
2979
        if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
2980
            $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
2981
            if (empty($groupusers)) {
2982
                return $updates;
2983
            }
2984
            list($insql, $inparams) = $DB->get_in_or_equal($groupusers);
2985
            $select .= ' AND userid ' . $insql;
2986
            $params = array_merge($params, $inparams);
2987
        }
2988
 
2989
        $updates->userattemptsfinished = (object) array('updated' => false);
2990
        $attemptsfinished = $DB->get_records_select('feedback_completed', $select, $params, '', 'id');
2991
        if (!empty($attemptsfinished)) {
2992
            $updates->userattemptsfinished->updated = true;
2993
            $updates->userattemptsfinished->itemids = array_keys($attemptsfinished);
2994
        }
2995
 
2996
        $updates->userattemptsunfinished = (object) array('updated' => false);
2997
        $attemptsunfinished = $DB->get_records_select('feedback_completedtmp', $select, $params, '', 'id');
2998
        if (!empty($attemptsunfinished)) {
2999
            $updates->userattemptsunfinished->updated = true;
3000
            $updates->userattemptsunfinished->itemids = array_keys($attemptsunfinished);
3001
        }
3002
    }
3003
 
3004
    return $updates;
3005
}
3006
 
3007
/**
3008
 * This function receives a calendar event and returns the action associated with it, or null if there is none.
3009
 *
3010
 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
3011
 * is not displayed on the block.
3012
 *
3013
 * @param calendar_event $event
3014
 * @param \core_calendar\action_factory $factory
3015
 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
3016
 * @return \core_calendar\local\event\entities\action_interface|null
3017
 */
3018
function mod_feedback_core_calendar_provide_event_action(calendar_event $event,
3019
                                                         \core_calendar\action_factory $factory,
3020
                                                         int $userid = 0) {
3021
 
3022
    global $USER;
3023
 
3024
    if (empty($userid)) {
3025
        $userid = $USER->id;
3026
    }
3027
 
3028
    $cm = get_fast_modinfo($event->courseid, $userid)->instances['feedback'][$event->instance];
3029
 
3030
    if (!$cm->uservisible) {
3031
        // The module is not visible to the user for any reason.
3032
        return null;
3033
    }
3034
 
3035
    $completion = new \completion_info($cm->get_course());
3036
 
3037
    $completiondata = $completion->get_data($cm, false, $userid);
3038
 
3039
    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
3040
        return null;
3041
    }
3042
 
3043
    $feedbackcompletion = new mod_feedback_completion(null, $cm, 0, false, null, null, $userid);
3044
 
3045
    if (!empty($cm->customdata['timeclose']) && $cm->customdata['timeclose'] < time()) {
3046
        // Feedback is already closed, do not display it even if it was never submitted.
3047
        return null;
3048
    }
3049
 
3050
    if (!$feedbackcompletion->can_complete()) {
3051
        // The user can't complete the feedback so there is no action for them.
3052
        return null;
3053
    }
3054
 
3055
    // The feedback is actionable if it does not have timeopen or timeopen is in the past.
3056
    $actionable = $feedbackcompletion->is_open();
3057
 
3058
    if ($actionable && $feedbackcompletion->is_already_submitted(false)) {
3059
        // There is no need to display anything if the user has already submitted the feedback.
3060
        return null;
3061
    }
3062
 
3063
    return $factory->create_instance(
3064
        get_string('answerquestions', 'feedback'),
3065
        new \moodle_url('/mod/feedback/view.php', ['id' => $cm->id]),
3066
        1,
3067
        $actionable
3068
    );
3069
}
3070
 
3071
/**
3072
 * Add a get_coursemodule_info function in case any feedback type wants to add 'extra' information
3073
 * for the course (see resource).
3074
 *
3075
 * Given a course_module object, this function returns any "extra" information that may be needed
3076
 * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
3077
 *
3078
 * @param stdClass $coursemodule The coursemodule object (record).
3079
 * @return cached_cm_info An object on information that the courses
3080
 *                        will know about (most noticeably, an icon).
3081
 */
3082
function feedback_get_coursemodule_info($coursemodule) {
3083
    global $DB;
3084
 
3085
    $dbparams = ['id' => $coursemodule->instance];
3086
    $fields = 'id, name, intro, introformat, completionsubmit, timeopen, timeclose, anonymous';
3087
    if (!$feedback = $DB->get_record('feedback', $dbparams, $fields)) {
3088
        return false;
3089
    }
3090
 
3091
    $result = new cached_cm_info();
3092
    $result->name = $feedback->name;
3093
 
3094
    if ($coursemodule->showdescription) {
3095
        // Convert intro to html. Do not filter cached version, filters run at display time.
3096
        $result->content = format_module_intro('feedback', $feedback, $coursemodule->id, false);
3097
    }
3098
 
3099
    // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
3100
    if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
3101
        $result->customdata['customcompletionrules']['completionsubmit'] = $feedback->completionsubmit;
3102
    }
3103
    // Populate some other values that can be used in calendar or on dashboard.
3104
    if ($feedback->timeopen) {
3105
        $result->customdata['timeopen'] = $feedback->timeopen;
3106
    }
3107
    if ($feedback->timeclose) {
3108
        $result->customdata['timeclose'] = $feedback->timeclose;
3109
    }
3110
    if ($feedback->anonymous) {
3111
        $result->customdata['anonymous'] = $feedback->anonymous;
3112
    }
3113
 
3114
    return $result;
3115
}
3116
 
3117
/**
3118
 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
3119
 *
3120
 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
3121
 * @return array $descriptions the array of descriptions for the custom rules.
3122
 */
3123
function mod_feedback_get_completion_active_rule_descriptions($cm) {
3124
    // Values will be present in cm_info, and we assume these are up to date.
3125
    if (empty($cm->customdata['customcompletionrules'])
3126
        || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
3127
        return [];
3128
    }
3129
 
3130
    $descriptions = [];
3131
    foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
3132
        switch ($key) {
3133
            case 'completionsubmit':
3134
                if (!empty($val)) {
3135
                    $descriptions[] = get_string('completionsubmit', 'feedback');
3136
                }
3137
                break;
3138
            default:
3139
                break;
3140
        }
3141
    }
3142
    return $descriptions;
3143
}
3144
 
3145
/**
3146
 * This function calculates the minimum and maximum cutoff values for the timestart of
3147
 * the given event.
3148
 *
3149
 * It will return an array with two values, the first being the minimum cutoff value and
3150
 * the second being the maximum cutoff value. Either or both values can be null, which
3151
 * indicates there is no minimum or maximum, respectively.
3152
 *
3153
 * If a cutoff is required then the function must return an array containing the cutoff
3154
 * timestamp and error string to display to the user if the cutoff value is violated.
3155
 *
3156
 * A minimum and maximum cutoff return value will look like:
3157
 * [
3158
 *     [1505704373, 'The due date must be after the sbumission start date'],
3159
 *     [1506741172, 'The due date must be before the cutoff date']
3160
 * ]
3161
 *
3162
 * @param calendar_event $event The calendar event to get the time range for
3163
 * @param stdClass $instance The module instance to get the range from
3164
 * @return array
3165
 */
3166
function mod_feedback_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
3167
    $mindate = null;
3168
    $maxdate = null;
3169
 
3170
    if ($event->eventtype == FEEDBACK_EVENT_TYPE_OPEN) {
3171
        // The start time of the open event can't be equal to or after the
3172
        // close time of the choice activity.
3173
        if (!empty($instance->timeclose)) {
3174
            $maxdate = [
3175
                $instance->timeclose,
3176
                get_string('openafterclose', 'feedback')
3177
            ];
3178
        }
3179
    } else if ($event->eventtype == FEEDBACK_EVENT_TYPE_CLOSE) {
3180
        // The start time of the close event can't be equal to or earlier than the
3181
        // open time of the choice activity.
3182
        if (!empty($instance->timeopen)) {
3183
            $mindate = [
3184
                $instance->timeopen,
3185
                get_string('closebeforeopen', 'feedback')
3186
            ];
3187
        }
3188
    }
3189
 
3190
    return [$mindate, $maxdate];
3191
}
3192
 
3193
/**
3194
 * This function will update the feedback module according to the
3195
 * event that has been modified.
3196
 *
3197
 * It will set the timeopen or timeclose value of the feedback instance
3198
 * according to the type of event provided.
3199
 *
3200
 * @throws \moodle_exception
3201
 * @param \calendar_event $event
3202
 * @param stdClass $feedback The module instance to get the range from
3203
 */
3204
function mod_feedback_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $feedback) {
3205
    global $CFG, $DB;
3206
 
3207
    if (empty($event->instance) || $event->modulename != 'feedback') {
3208
        return;
3209
    }
3210
 
3211
    if ($event->instance != $feedback->id) {
3212
        return;
3213
    }
3214
 
3215
    if (!in_array($event->eventtype, [FEEDBACK_EVENT_TYPE_OPEN, FEEDBACK_EVENT_TYPE_CLOSE])) {
3216
        return;
3217
    }
3218
 
3219
    $courseid = $event->courseid;
3220
    $modulename = $event->modulename;
3221
    $instanceid = $event->instance;
3222
    $modified = false;
3223
 
3224
    $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
3225
    $context = context_module::instance($coursemodule->id);
3226
 
3227
    // The user does not have the capability to modify this activity.
3228
    if (!has_capability('moodle/course:manageactivities', $context)) {
3229
        return;
3230
    }
3231
 
3232
    if ($event->eventtype == FEEDBACK_EVENT_TYPE_OPEN) {
3233
        // If the event is for the feedback activity opening then we should
3234
        // set the start time of the feedback activity to be the new start
3235
        // time of the event.
3236
        if ($feedback->timeopen != $event->timestart) {
3237
            $feedback->timeopen = $event->timestart;
3238
            $feedback->timemodified = time();
3239
            $modified = true;
3240
        }
3241
    } else if ($event->eventtype == FEEDBACK_EVENT_TYPE_CLOSE) {
3242
        // If the event is for the feedback activity closing then we should
3243
        // set the end time of the feedback activity to be the new start
3244
        // time of the event.
3245
        if ($feedback->timeclose != $event->timestart) {
3246
            $feedback->timeclose = $event->timestart;
3247
            $modified = true;
3248
        }
3249
    }
3250
 
3251
    if ($modified) {
3252
        $feedback->timemodified = time();
3253
        $DB->update_record('feedback', $feedback);
3254
        $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
3255
        $event->trigger();
3256
    }
3257
}
3258
 
3259
/**
3260
 * Callback to fetch the activity event type lang string.
3261
 *
3262
 * @param string $eventtype The event type.
3263
 * @return lang_string The event type lang string.
3264
 */
3265
function mod_feedback_core_calendar_get_event_action_string(string $eventtype): string {
3266
    $modulename = get_string('modulename', 'feedback');
3267
 
3268
    switch ($eventtype) {
3269
        case FEEDBACK_EVENT_TYPE_OPEN:
3270
            $identifier = 'calendarstart';
3271
            break;
3272
        case FEEDBACK_EVENT_TYPE_CLOSE:
3273
            $identifier = 'calendarend';
3274
            break;
3275
        default:
3276
            return get_string('requiresaction', 'calendar', $modulename);
3277
    }
3278
 
3279
    return get_string($identifier, 'feedback', $modulename);
3280
}