Proyectos de Subversion Moodle

Rev

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

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