Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - https://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 <https://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library of interface functions and constants.
19
 *
20
 * @package     mod_stickynotes
21
 * @copyright   2021 Olivier VALENTIN
22
 * @license     https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
require_once(dirname(__FILE__) . '/../../config.php');
28
require_once("$CFG->libdir/formslib.php");
29
require_once("{$CFG->dirroot}/lib/navigationlib.php");
30
global $COURSE, $OUTPUT, $PAGE, $CFG;;
31
 
32
 
33
/**
34
 * Return if the plugin supports $feature.
35
 *
36
 * @param string $feature Constant representing the feature.
37
 * @return true | null True if the feature is supported, null otherwise.
38
 */
39
function stickynotes_supports($feature) {
40
    switch ($feature) {
41
        case FEATURE_MOD_INTRO:
42
            return true;
43
        case FEATURE_COMPLETION_TRACKS_VIEWS:
44
            return true;
45
        case FEATURE_COMPLETION_HAS_RULES:
46
            return true;
47
        case FEATURE_BACKUP_MOODLE2:
48
            return true;
49
        case FEATURE_SHOW_DESCRIPTION:
50
            return true;
51
        case FEATURE_MOD_PURPOSE:
52
            return MOD_PURPOSE_COLLABORATION;
53
        default:
54
            return null;
55
    }
56
}
57
 
58
/**
59
 * Saves a new instance of the mod_stickynotes into the database.
60
 *
61
 * Given an object containing all the necessary data, (defined by the form
62
 * in mod_form.php) this function will create a new instance and return the id
63
 * number of the instance.
64
 *
65
 * @param object $moduleinstance An object from the form.
66
 * @param mod_stickynotes_mod_form $mform The form.
67
 * @return int The id of the newly inserted record.
68
 */
69
function stickynotes_add_instance($moduleinstance, $mform = null) {
70
    global $DB;
71
 
72
    $moduleinstance->timecreated = time();
73
 
74
    $id = $DB->insert_record('stickynotes', $moduleinstance);
75
 
76
    $col = new stdClass();
77
    $col->stickyid = $id;
78
    $col->title = get_string('new_column_title', 'stickynotes');
79
 
80
    $defaultcolumn = $DB->insert_record('stickynotes_column', $col);
81
 
82
    return $id;
83
}
84
 
85
/**
86
 * Updates an instance of the mod_stickynotes in the database.
87
 *
88
 * Given an object containing all the necessary data (defined in mod_form.php),
89
 * this function will update an existing instance with new data.
90
 *
91
 * @param object $moduleinstance An object from the form in mod_form.php.
92
 * @param mod_stickynotes_mod_form $mform The form.
93
 * @return bool True if successful, false otherwise.
94
 */
95
function stickynotes_update_instance($moduleinstance, $mform = null) {
96
    global $DB;
97
 
98
    $moduleinstance->timemodified = time();
99
    $moduleinstance->id = $moduleinstance->instance;
100
 
101
    return $DB->update_record('stickynotes', $moduleinstance);
102
}
103
 
104
/**
105
 * Removes an instance of the mod_stickynotes from the database.
106
 *
107
 * @param int $id Id of the module instance.
108
 * @return bool True if successful, false on failure.
109
 */
110
function stickynotes_delete_instance($id) {
111
    global $DB;
112
 
113
    $exists = $DB->get_record('stickynotes', array('id' => $id));
114
    if (!$exists) {
115
        return false;
116
    }
117
 
118
    $DB->delete_records('stickynotes', array('id' => $id));
119
    $DB->delete_records('stickynotes_column', array('stickyid' => $id));
120
    $DB->delete_records('stickynotes_note', array('stickyid' => $id));
121
    $DB->delete_records('stickynotes_vote', array('stickyid' => $id));
122
 
123
    return true;
124
}
125
 
126
/**
127
 * Returns the lists of all browsable file areas within the given module context.
128
 *
129
 * The file area 'intro' for the activity introduction field is added automatically
130
 * by {@see file_browser::get_file_info_context_module()}.
131
 *
132
 * @package     mod_stickynotes
133
 * @category    files
134
 *
135
 * @param stdClass $course
136
 * @param stdClass $cm
137
 * @param stdClass $context
138
 * @return string[].
139
 */
140
function stickynotes_get_file_areas($course, $cm, $context) {
141
    return array();
142
}
143
 
144
/**
145
 * File browsing support for mod_stickynotes file areas.
146
 *
147
 * @package     mod_stickynotes
148
 * @category    files
149
 *
150
 * @param file_browser $browser
151
 * @param array $areas
152
 * @param stdClass $course
153
 * @param stdClass $cm
154
 * @param stdClass $context
155
 * @param string $filearea
156
 * @param int $itemid
157
 * @param string $filepath
158
 * @param string $filename
159
 * @return file_info Instance or null if not found.
160
 */
161
function stickynotes_get_file_info($browser, $areas, $course, $cm, $context, $filearea, $itemid, $filepath, $filename) {
162
    return null;
163
}
164
 
165
/**
166
 * Serves the files from the mod_stickynotes file areas.
167
 *
168
 * @package     mod_stickynotes
169
 * @category    files
170
 *
171
 * @param stdClass $course The course object.
172
 * @param stdClass $cm The course module object.
173
 * @param stdClass $context The mod_stickynotes's context.
174
 * @param string $filearea The name of the file area.
175
 * @param array $args Extra arguments (itemid, path).
176
 * @param bool $forcedownload Whether or not force download.
177
 * @param array $options Additional options affecting the file serving.
178
 */
179
function stickynotes_pluginfile($course, $cm, $context, $filearea, $args, $forcedownload, $options = array()) {
180
    global $DB, $CFG;
181
 
182
    if ($context->contextlevel != CONTEXT_MODULE) {
183
        send_file_not_found();
184
    }
185
 
186
    require_login($course, true, $cm);
187
    send_file_not_found();
188
}
189
 
190
/**
191
 * Extends the global navigation tree by adding mod_stickynotes nodes if there is a relevant content.
192
 *
193
 * This can be called by an AJAX request so do not rely on $PAGE as it might not be set up properly.
194
 *
195
 * @param navigation_node $stickynotesnode An object representing the navigation tree node.
196
 * @param stdClass $course
197
 * @param stdClass $module
198
 * @param cm_info $cm
199
 */
200
function stickynotes_extend_navigation($stickynotesnode, $course, $module, $cm) {
201
}
202
 
203
/**
204
 * Extend navigation.
205
 * @param object $settings
206
 * @param object $stickynotesnode
207
 */
208
function stickynotes_extend_settings_navigation($settings, $stickynotesnode) {
209
    global $PAGE;
210
 
211
    if (has_capability('mod/stickynotes:export', $PAGE->cm->context)) {
212
        $node = navigation_node::create(get_string('export', 'stickynotes'),
213
                new moodle_url('/mod/stickynotes/export_csv.php', array('id' => $PAGE->cm->id)),
214
                navigation_node::TYPE_SETTING,
215
                new pix_icon('i/export', ''));
216
        $stickynotesnode->add_node($node);
217
    }
218
}
219
 
220
/**
221
 * Generates form to create or update a note.
222
 */
223
class form_note extends moodleform {
224
 
225
     /**
226
      * Form definition for notes.
227
      *
228
      * @return void
229
      */
230
    public function definition() {
231
        global $CFG, $USER, $DB;
232
        $mform = $this->_form;
233
        $stickyid     = $this->_customdata['post'];
234
 
235
        if (isset($stickyid->create)) {
236
            $stickyid->color = 'color1';
237
        }
238
 
239
        $mform->addElement('text', 'message', get_string('message', 'stickynotes'), 'maxlength="100" size="48"');
240
        $mform->setType('message', PARAM_TEXT);
241
        $mform->addRule('message', get_string('maximumchars', '', 100), 'maxlength', 100, 'client');
242
 
243
        // If color choice is enabled.
244
        if ($stickyid->choose_color == 1) {
245
 
246
            // First, array the 6 colors defined for this activity.
247
            $configcolor = array (
248
                'color1',
249
                'color2',
250
                'color3',
251
                'color4',
252
                'color5',
253
                'color6'
254
            );
255
            // Second, retrieve colors settings for this instance.
256
            $retrievecolors = $DB->get_record('stickynotes', array('id' => $stickyid->stickyid), '*', MUST_EXIST);
257
 
258
            $colorarray = array();
259
            foreach ($configcolor as $color) {
260
                if ($retrievecolors->$color == 1) {
261
                    // If a color is used in instance, design a colored square and add meaning if define.
262
                    $thiscolor = "<div style=\"width:50px;background-color:".get_config('mod_stickynotes', $color)
263
                    ."\">&nbsp;</div>&nbsp;";
264
                    $thiscolor .= $DB->get_field('stickynotes', $color.'_meaning', array('id' => $stickyid->stickyid));
265
                    $thiscolor .= "\n";
266
                    // Create a radio button to choose color.
267
                    $colorarray[] = $mform->createElement('radio', 'color', '', $thiscolor, $color);
268
                }
269
            }
270
            $mform->setDefault('color', $stickyid->color);
271
            $mform->addGroup($colorarray, 'colorarr', get_string('choosecolorbuttons', 'stickynotes'), array('<br />'), false);
272
        } else {
273
            // Else, default color for note is always color 1.
274
            $mform->addElement('hidden', 'color');
275
            $mform->setType('color', PARAM_TEXT);
276
            $mform->setDefault('color',  'color1');
277
        }
278
 
279
        if (isset($stickyid->edit)) {
280
            // If editing note, display menu to change column.
281
 
282
            // Does the note stays at its place ?
283
            $mform->addElement('advcheckbox', 'nomove', get_string('nomove', 'stickynotes'));
284
            $mform->addHelpButton('nomove', 'nomove', 'stickynotes');
285
            $mform->setDefault('nomove',  '0');
286
 
287
            $req = $DB->get_records('stickynotes_column', array('stickyid' => $stickyid->stickyid), 'id', 'id,title');
288
            $options = [];
289
 
290
            foreach ($req as $new) {
291
                $options[$new->id] = $new->title;
292
            }
293
 
294
            $mform->disabledIf('stickycolid', 'nomove', '1');
295
            $mform->addElement('select', 'stickycolid', get_string('changecolumn', 'stickynotes'), $options);
296
            $mform->setType('stickycolid', PARAM_INT);
297
 
298
            $optionsorder = [];
299
            $mform->disabledIf('selectorder', 'nomove', '1');
300
            $mform->addElement('select', 'selectorder', get_string('selectorder', 'stickynotes'), $optionsorder);
301
            $mform->setType('selectorder', PARAM_INT);
302
            $mform->setDefault('selectorder', 0);
303
 
304
            $mform->addElement('hidden', 'ordernote');
305
            $mform->setType('ordernote', PARAM_INT);
306
 
307
            $mform->addElement('hidden', 'oldrank');
308
            $mform->setType('oldrank', PARAM_INT);
309
            $mform->setDefault('oldrank', $stickyid->oldrank);
310
 
311
            $mform->addElement('hidden', 'oldcolumn');
312
            $mform->setType('oldcolumn', PARAM_INT);
313
            $mform->setDefault('oldcolumn', $stickyid->oldcolumn);
314
        } else {
315
            // Else, hide column select and create ordernote select.
316
            $sql = 'SELECT ordernote, message FROM {stickynotes_note} WHERE stickycolid = ? ORDER BY ordernote';
317
            $paramsdb = array($stickyid->stickycolid);
318
            $dbresult = $DB->get_records_sql($sql, $paramsdb);
319
 
320
            $createorder[0] = get_string('lastplace', 'stickynotes');
321
            $createorder[1] = get_string('firstplace', 'stickynotes');
322
 
323
            foreach ($dbresult as $move) {
324
                $neworder = $move->ordernote + 1;
325
                $createorder[$neworder] = get_string('after', 'stickynotes')." '".$move->message."'";
326
            }
327
 
328
            $mform->addElement('select', 'ordernote', get_string('selectorder', 'stickynotes'), $createorder);
329
            $mform->setType('ordernote', PARAM_INT);
330
            $mform->setDefault('ordernote', 1000);
331
 
332
            $mform->addElement('hidden', 'stickycolid');
333
            $mform->setType('stickycolid', PARAM_INT);
334
        }
335
 
336
        $mform->addElement('hidden', 'id');
337
        $mform->setType('id', PARAM_INT);
338
 
339
        $mform->addElement('hidden', 'userid');
340
        $mform->setType('userid', PARAM_INT);
341
 
342
        $mform->addElement('hidden', 'oldrank');
343
        $mform->setType('oldrank', PARAM_INT);
344
 
345
        $mform->addElement('hidden', 'oldcolumn');
346
        $mform->setType('oldcolumn', PARAM_INT);
347
 
348
        // Are we creating a note?
349
        $mform->addElement('hidden', 'create');
350
        $mform->setType('create', PARAM_INT);
351
 
352
        // Are we editing a note?
353
        $mform->addElement('hidden', 'edit');
354
        $mform->setType('edit', PARAM_INT);
355
 
356
        // Instance id.
357
        $mform->addElement('hidden', 'stickyid');
358
        $mform->setType('stickyid', PARAM_INT);
359
 
360
        // Stickynote id.
361
        $mform->addElement('hidden', 'note');
362
        $mform->setType('note', PARAM_INT);
363
 
364
        $this->add_action_buttons(true, get_string('validate', 'stickynotes'));
365
    }
366
 
367
    /**
368
     * Form validation.
369
     *
370
     * @param array $data  data from the form.
371
     * @param array $files files uplaoded.
372
     *
373
     * @return array of errors.
374
     */
375
    public function validation($data, $files) {
376
        $errors = parent::validation($data, $files);
377
        if (empty($data['message'])) {
378
            $errors['message'] = get_string('erroremptymessage', 'stickynotes');
379
        }
380
        return $errors;
381
    }
382
}
383
/**
384
 * Generates form to create or update column.
385
 */
386
class form_column extends moodleform {
387
 
388
    /**
389
     * Form definition for columns.
390
     *
391
     * @return void
392
     */
393
    public function definition() {
394
        global $CFG, $USER;
395
        $mform = $this->_form;
396
 
397
        $mform->addElement('text', 'title', get_string('title', 'stickynotes'), 'size="48"');
398
        $mform->setType('title', PARAM_TEXT);
399
        $mform->addRule('title', get_string('maximumchars', '', 20), 'maxlength', 20, 'client');
400
 
401
        $mform->addElement('hidden', 'id');
402
        $mform->setType('id', PARAM_INT);
403
 
404
        $mform->addElement('hidden', 'userid');
405
        $mform->setType('userid', PARAM_INT);
406
 
407
        // Are we creating a column?
408
        $mform->addElement('hidden', 'create');
409
        $mform->setType('create', PARAM_INT);
410
 
411
        // Are we editing a column?
412
        $mform->addElement('hidden', 'edit');
413
        $mform->setType('edit', PARAM_INT);
414
 
415
        // Instance id.
416
        $mform->addElement('hidden', 'stickyid');
417
        $mform->setType('stickyid', PARAM_INT);
418
 
419
        // Column id.
420
        $mform->addElement('hidden', 'col');
421
        $mform->setType('col', PARAM_INT);
422
 
423
        $this->add_action_buttons(true, get_string('validate', 'stickynotes'));
424
    }
425
 
426
    /**
427
     * Form validation.
428
     *
429
     * @param array $data  data from the form.
430
     * @param array $files files uplaoded.
431
     *
432
     * @return array of errors.
433
     */
434
    public function validation($data, $files) {
435
        $errors = parent::validation($data, $files);
436
        if (empty($data['title'])) {
437
            $errors['title'] = get_string('erroremptytitle', 'stickynotes');
438
        }
439
 
440
        return $errors;
441
    }
442
}
443
 /**
444
  * Creates a new note.
445
  * @param stdClass $data  Datas from the form.
446
  *
447
  * @return bool True if successful, false otherwise.
448
  */
449
function insert_stickynote($data, $moduleinstance, $course, $cm) {
450
    global $DB, $USER;
451
    $id = required_param('id', PARAM_INT);
452
    $data = (object)$data;
453
    $data->timecreated = time();
454
 
455
     // Check ordernote.
456
    if ($data->ordernote == 0) {
457
        // If ordernote is zero, user creates note at the end of the column.
458
        // Calculate order : order of last note + 1.
459
        $sql = 'SELECT ordernote FROM {stickynotes_note} WHERE stickycolid = ? ORDER BY ordernote DESC LIMIT 1';
460
        $paramsdb = array($data->stickycolid);
461
        $dbresult = $DB->get_field_sql($sql, $paramsdb);
462
        $data->ordernote = $dbresult + 1;
463
    } else {
464
        // User creates a note at a specific place.
465
        // First, all notes following are moved of one place BEFORE creating new note.
466
        $sql = 'SELECT id, ordernote FROM {stickynotes_note} WHERE stickycolid = ? AND ordernote >= ? ORDER BY ordernote';
467
        $paramsdb = array($data->stickycolid, $data->ordernote);
468
        $dbresult = $DB->get_records_sql($sql, $paramsdb);
469
        foreach ($dbresult as $note) {
470
            $updatenotes = (object)$note;
471
            $updatenotes->ordernote = $note->ordernote + 1;
472
            $resnotes = $DB->update_record('stickynotes_note', $updatenotes);
473
        }
474
    }
475
    // Finally, create the new note.
476
    $res = $DB->insert_record('stickynotes_note', $data);
477
 
478
    // Activates completion checking.
479
    $completion = new \completion_info($course);
480
    if ($completion->is_enabled($cm) && $moduleinstance->completionstickynotes) {
481
        $completion->update_state($cm);
482
    }
483
 
484
    return $res;
485
}
486
 /**
487
  * Updates a note
488
  * @param object $data  Datas from the form
489
  *
490
  * @return $post The id of the activity.
491
  */
492
function update_stickynote($data) {
493
    global $DB, $USER;
494
    $data = (object)$data;
495
    $data->timemodified = time();
496
 
497
    // First, retrieve all notes following the moved note BEFORE updating !
498
    $sql = 'SELECT id, ordernote FROM {stickynotes_note} WHERE stickycolid = ? AND ordernote >= ? AND id != ? ORDER BY ordernote';
499
    $paramsdb = array($data->stickycolid, $data->ordernote, $data->note);
500
    $dbresult = $DB->get_records_sql($sql, $paramsdb);
501
 
502
    // Now we can update the note at its new place.
503
    $res = $DB->update_record('stickynotes_note', $data);
504
 
505
    // Finally, all notes following are moved of one place.
506
    foreach ($dbresult as $note) {
507
        $updatenotes = (object)$note;
508
        $updatenotes->ordernote = $note->ordernote + 1;
509
        $resnotes = $DB->update_record('stickynotes_note', $updatenotes);
510
    }
511
 
512
    $post = new StdClass;
513
    $post->id = $data->instance;
514
 
515
    return $post;
516
}
517
 /**
518
  * Creates a new column.
519
  * @param object $data  Datas from the form
520
  * @return bool True if successful, false otherwise.
521
  */
522
function insert_column($data) {
523
    global $DB, $USER;
524
    $id = required_param('id', PARAM_INT);
525
 
526
    $data = (object)$data;
527
 
528
    // Count numbers of column for this activity.
529
    $options = array('stickyid' => $data->stickyid);
530
    $count = $DB->count_records('stickynotes_column', $options);
531
 
532
    $last = $count + 1;
533
    $data->column_order    = $last;
534
 
535
    $DB->insert_record('stickynotes_column', $data);
536
 
537
    return true;
538
}
539
 /**
540
  * Updates a column.
541
  * @param object $data  Datas from the form
542
  * @return post The id of the activity.
543
  */
544
function update_column($data) {
545
    global $DB, $USER;
546
    $data = (object)$data;
547
    $data->id = $data->col;
548
 
549
    $res = $DB->update_record('stickynotes_column', $data);
550
 
551
    return true;
552
}
553
 /**
554
  * Deletes a column.
555
  * @param int $col  Column id
556
  * @param int $modulecontext  Activity id
557
  * @return bool True if successful, false otherwise.
558
  */
559
function delete_column($col, $modulecontext) {
560
    global $DB;
561
    if (!$DB->delete_records('stickynotes_column', array('id' => $col))) {
562
        $result = false;
563
    }
564
}
565
 /**
566
  * Deletes a note.
567
  * @param int $note  Note id
568
  * @param int $modulecontext  Activity id
569
  * @return bool True if successful, false otherwise.
570
  */
571
function delete_stickynote($note, $modulecontext, $moduleinstance, $course, $cm,$user) {
572
    global $DB;
573
    if (!$DB->delete_records('stickynotes_note', array('id' => $note))) {
574
        $result = false;
575
    }
576
 
577
    // Activates completion checking.
578
    $completion = new \completion_info($course);
579
    if ($completion->is_enabled($cm) == COMPLETION_TRACKING_AUTOMATIC && $moduleinstance->completionstickynotes) {
580
        $completion->update_state($cm, COMPLETION_INCOMPLETE, $user);
581
    }
582
}
583
 /**
584
  * Count number of notes created by a given user in activity.
585
  * @param int $userid  user id.
586
  * @param int $modulecontext activity id.
587
  * @return int Number of notes created by user.
588
  */
589
function stickynote_count_notes($userid, $modulecontext) {
590
    global $DB;
591
    $count = $DB->count_records('stickynotes_note', array ('userid' => $userid, 'stickyid' => $modulecontext));
592
    return $count;
593
}
594
 /**
595
  * Count number of votes created for a given note.
596
  * @param int $note  sticky note id.
597
  * @return int Number of votes of user in given activity.
598
  */
599
function stickynote_count_votes($note) {
600
    global $DB;
601
    $count = $DB->count_records('stickynotes_vote', array ('stickynoteid' => $note));
602
     return $count;
603
}
604
 /**
605
  * Search column title.
606
  * @param int $col  Column id.
607
  * @return array
608
  */
609
function get_column_title($col) {
610
    global $DB;
611
    $record = $DB->get_record('stickynotes_column', array('id' => $col));
612
    if (!$record) {
613
        return;
614
    } else {
615
        $column['title'] = $record->title;
616
    }
617
    return $column;
618
}
619
 /**
620
  * Defines icon to display for a note for a "Like" vote type.
621
  *
622
  * This function is related to the "Like" vote.
623
  * Checks if user has alreadey voted or not, and if he hasn't voted,
624
  * defines if he has reached or not the max votes limit.
625
  *
626
  * @param int $userid user id.
627
  * @param int $note sticky note id
628
  * @param int $limit activity setting (vote limit is enabled if 1)
629
  * @param int $max activity setting (max number of votes per user)
630
  * @param int $instance activity ID
631
  * @return int myvote  return if user has voted or not.
632
  * @return int limitedvote  return if user has reached limit.
633
  * @return int action  return action to trigger if user clicks on heart.
634
  */
635
function stickynote_get_vote_like($userid, $note, $limit, $max, $instance) {
636
    global $DB, $USER;
637
 
638
    $post = $DB->get_record('stickynotes_vote', array('userid' => $userid, 'stickynoteid' => $note));
639
    // If User has already voted for this note, display full icon to unvote.
640
    if ($post) {
641
        $params['myvote'] = 1;
642
        $params['limitedvote'] = 0;
643
        // Action : delete vote.
644
        $params['action'] = 'del';
645
    } else {
646
        // If no votes detected.
647
        if ($limit == 1) {
648
            // If vote has max limit, count votes for this user.
649
            $check = $DB->count_records('stickynotes_vote', array ('userid' => $userid, 'stickyid' => $instance));
650
            if ($check >= $max) {
651
                // If user has reached max votes, icon is grey.
652
                $params['myvote'] = 0;
653
                $params['limitedvote'] = 1;
654
                $params['action'] = 'n';
655
            } else {
656
                // If limit is note reached, user can vote for this note.
657
                $params['myvote'] = 0;
658
                $params['limitedvote'] = 0;
659
                $params['action'] = 'add';
660
            }
661
        } else {
662
            // Else, user can vote.
663
            $params['myvote'] = 0;
664
            $params['limitedvote'] = 0;
665
            $params['action'] = 'add';
666
        }
667
    }
668
    return $params;
669
}
670
/**
671
 * Defines action to trigger for a "Like" vote type.
672
 *
673
 * This function is related to "Like" vote.
674
 * Triggers action if user is voting or retiring his vote.
675
 *
676
 * @param int $userid user id.
677
 * @param int $note sticky note id
678
 * @param int $action definess if user adds or delete vote
679
 * @param int $instance  activity id
680
 * @return bool True if successful, false otherwise.
681
 */
682
function stickynote_do_vote_like($userid, $note, $action, $instance) {
683
    global $DB, $USER;
684
 
685
    $data = new StdClass;
686
 
687
    if ($action == "add") {
688
        $data->userid = $userid;
689
        $data->vote = 1;
690
        $data->stickynoteid = $note;
691
        $data->stickyid = $instance;
692
        $data->timecreated = time();
693
 
694
        if (!$DB->insert_record('stickynotes_vote', $data)) {
695
            $result = false;
696
        }
697
    } else if ($action == "del") {
698
        $data->userid = $userid;
699
        $data->stickynoteid = $note;
700
 
701
        if (!$DB->delete_records('stickynotes_vote', array('userid' => $data->userid, 'stickynoteid' => $data->stickynoteid))) {
702
            $result = false;
703
        }
704
    }
705
 
706
    return true;
707
}
708
 
709
/**
710
 * Implementation of the function for printing the form elements that control
711
 * whether the course reset functionality affects the Sticky Notes activity.
712
 *
713
 * @param $mform the course reset form that is being built.
714
 */
715
function stickynotes_reset_course_form_definition($mform) {
716
    $mform->addElement('header', 'stickynotesheader', get_string('modulenameplural', 'stickynotes'));
717
 
718
    $mform->addElement('advcheckbox', 'reset_stickynotes_all',
719
            get_string('resetstickynotesall', 'stickynotes'));
720
 
721
    $mform->addElement('advcheckbox', 'reset_stickynotes_notes',
722
            get_string('resetstickynotesnotes', 'stickynotes'));
723
    $mform->disabledIf('reset_stickynotes_notes', 'reset_stickynotes_all', 'checked');
724
 
725
    $mform->addElement('advcheckbox', 'reset_stickynotes_votes',
726
            get_string('resetstickynotesvotes', 'stickynotes'));
727
    $mform->disabledIf('reset_stickynotes_votes', 'reset_stickynotes_all', 'checked');
728
    $mform->disabledIf('reset_stickynotes_votes', 'reset_stickynotes_notes', 'checked');
729
}
730
 
731
/**
732
 * Course reset form defaults.
733
 * @return array the defaults.
734
 */
735
function stickynotes_reset_course_form_defaults($course) {
736
    return array('reset_stickynotes_all' => 1,
737
                 'reset_stickynotes_notes' => 1,
738
                 'reset_stickynotes_votes' => 1);
739
}
740
 
741
/**
742
 * Actual implementation of the reset course functionality, delete all contents,
743
 * or only notes, or only votes.
744
 *
745
 * If delete all is selected, a start column will be created.
746
 *
747
 * @param object $data the data submitted from the reset course.
748
 * @return array status array
749
 */
750
function stickynotes_reset_userdata($data) {
751
    global $CFG, $DB;
752
 
753
    $componentstr = get_string('modulenameplural', 'stickynotes');
754
    $status = array();
755
 
756
    $sql = "SELECT sn.id FROM {stickynotes} sn WHERE sn.course=".$data->courseid."";
757
 
758
    // Remove all contents - columns, notes and votes.
759
    if (!empty($data->reset_stickynotes_all)) {
760
        // Delete all columns, notes and votes queries.
761
        $res_columns = $DB->delete_records_select('stickynotes_column', "stickyid IN ($sql)");
762
        $res_notes = $DB->delete_records_select('stickynotes_note', "stickyid IN ($sql)");
763
        $res_votes = $DB->delete_records_select('stickynotes_vote', "stickyid IN ($sql)");
764
 
765
        // Now columns are deleted, create a new default column for each activity.
766
        $res_activities = $DB->get_records_sql($sql);
767
        foreach ($res_activities as $recreate_column) {
768
            $new = new stdClass();
769
            $new->stickyid = $recreate_column->id;
770
            $new->title = get_string('new_column_title', 'stickynotes');
771
            insert_column($new);
772
        }
773
 
774
        $status[] = array('component'=>$componentstr, 'item'=>get_string('removeallresponse', 'stickynotes'), 'error'=>false);
775
    }
776
 
777
    // Remove notes and votes. Columns stay.
778
    if (!empty($data->reset_stickynotes_notes)) {
779
        $res_notes = $DB->delete_records_select('stickynotes_note', "stickyid IN ($sql)");
780
        $res_votes = $DB->delete_records_select('stickynotes_vote', "stickyid IN ($sql)");
781
        $status[] = array('component'=>$componentstr, 'item'=>get_string('removenotesandvotesresponse', 'stickynotes'), 'error'=>false);
782
    }
783
 
784
    // Remove votes only
785
    if (!empty($data->reset_stickynotes_votes)) {
786
        $res_votes = $DB->delete_records_select('stickynotes_vote', "stickyid IN ($sql)");
787
        $status[] = array('component'=>$componentstr, 'item'=>get_string('removevotesresponse', 'stickynotes'), 'error'=>false);
788
    }
789
 
790
    return $status;
791
}
792
 
793
/**
794
 * Add a get_coursemodule_info function in case any stickynotes type wants to add 'extra' information
795
 * for the course (see resource).
796
 *
797
 * Given a course_module object, this function returns any "extra" information that may be needed
798
 * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
799
 *
800
 * @param stdClass $coursemodule The coursemodule object (record).
801
 * @return cached_cm_info An object on information that the courses
802
 *                        will know about (most noticeably, an icon).
803
 */
804
function stickynotes_get_coursemodule_info($coursemodule) {
805
    global $DB;
806
 
807
    $dbparams = ['id' => $coursemodule->instance];
808
    $fields = 'id, name, intro, introformat, completionstickynotes';
809
    if (!$stickynotes = $DB->get_record('stickynotes', $dbparams, $fields)) {
810
        return false;
811
    }
812
 
813
    $result = new cached_cm_info();
814
    $result->name = $stickynotes->name;
815
 
816
    if ($coursemodule->showdescription) {
817
        // Convert intro to html. Do not filter cached version, filters run at display time.
818
        $result->content = format_module_intro('stickynotes', $stickynotes, $coursemodule->id, false);
819
    }
820
 
821
    // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
822
    if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
823
        $result->customdata['customcompletionrules']['completionstickynotes'] = $stickynotes->completionstickynotes;
824
    }
825
 
826
    return $result;
827
}
828
 
829
/**
830
 * Obtains the automatic completion state for this stickynotes on any conditions
831
 * in stickynotes settings
832
 *
833
 * @param object $course Course
834
 * @param object $cm Course-module
835
 * @param int $userid User ID
836
 * @param bool $type Type of comparison (or/and; can be used as return value if no conditions)
837
 * @return bool True if completed, false if not. (If no conditions, then return
838
 *   value depends on comparison type)
839
 */
840
function stickynotes_get_completion_state($course, $cm, $userid, $type) {
841
    global $DB;
842
 
843
    $stickynotesid = $cm->instance;
844
 
845
    if (!$stickynotes = $DB->get_record('stickynotes', ['id' => $stickynotesid])) {
846
        throw new \moodle_exception('Unable to find stickynotes activity with id ' . $stickynotesid);
847
    }
848
 
849
    $params = ['userid' => $userid, 'stickyid' => $stickynotesid];
850
    $sql = "SELECT COUNT(*)
851
                FROM {stickynotes_note} sn
852
                JOIN {stickynotes_column} sc ON sn.stickycolid = sc.id
853
                WHERE sn.userid = :userid
854
                AND sc.stickyid = :stickyid";
855
 
856
    if ($stickynotes->completionstickynotes) {
857
        $stickynotes = $DB->get_field_sql($sql, $params);
858
        if ($stickynotes) {
859
            return ($stickynotes >= $stickynotes->completionstickynotes) ? COMPLETION_COMPLETE : COMPLETION_INCOMPLETE;
860
        } else {
861
            return COMPLETION_INCOMPLETE;
862
        }
863
    }
864
    return $type;
865
}
866
 
867
/**
868
 * Callback which returns human-readable strings describing the active completion custom rules for the stickynotes module instance.
869
 *
870
 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
871
 * @return array $descriptions the array of descriptions for the custom rules.
872
 */
873
function mod_stickynotes_get_completion_active_rule_descriptions($cm) {
874
    // Values will be present in cm_info, and we assume these are up to date.
875
    if (empty($cm->customdata['customcompletionrules'])
876
        || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
877
        return [];
878
    }
879
 
880
    $descriptions = [];
881
    foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
882
        switch ($key) {
883
            case 'completionstickynotes':
884
                if (!empty($val)) {
885
                    $descriptions[] = get_string('completionstickynotesdesc', 'mod_stickynotes', $val);
886
                }
887
                break;
888
            default:
889
                break;
890
        }
891
    }
892
    return $descriptions;
893
}
894
 
895
 /**
896
  * Updates locks parameters.
897
  * @param object $data  Datas from the form
898
  * @return post The id of the activity.
899
  */
900
  function update_lock($instance, $lock, $lockvalue) {
901
    global $DB;
902
    $data = (object)$data;
903
    $data->id = $instance;
904
    $data->$lock = $lockvalue;
905
 
906
    $res = $DB->update_record('stickynotes', $data);
907
 
908
    return true;
909
}
910
 
911
 /**
912
  * Decides if text color is black or white depending on
913
  * the note background color.
914
  * Author : Elmer Wilson
915
  * @param object $data  Hexadecimal background color.
916
  * @return post Text color (black or white) in hex.
917
  */
918
 
919
function getcontrastcolor($hexcolor)
920
{
921
        // hexColor RGB
922
        $R1 = hexdec(substr($hexcolor, 1, 2));
923
        $G1 = hexdec(substr($hexcolor, 3, 2));
924
        $B1 = hexdec(substr($hexcolor, 5, 2));
925
        // Black RGB
926
        $blackColor = "#000000";
927
        $R2BlackColor = hexdec(substr($blackColor, 1, 2));
928
        $G2BlackColor = hexdec(substr($blackColor, 3, 2));
929
        $B2BlackColor = hexdec(substr($blackColor, 5, 2));
930
         // Calc contrast ratio
931
         $L1 = 0.2126 * pow($R1 / 255, 2.2) +
932
               0.7152 * pow($G1 / 255, 2.2) +
933
               0.0722 * pow($B1 / 255, 2.2);
934
        $L2 = 0.2126 * pow($R2BlackColor / 255, 2.2) +
935
              0.7152 * pow($G2BlackColor / 255, 2.2) +
936
              0.0722 * pow($B2BlackColor / 255, 2.2);
937
        $contrastRatio = 0;
938
        if ($L1 > $L2) {
939
            $contrastRatio = (int)(($L1 + 0.05) / ($L2 + 0.05));
940
        } else {
941
            $contrastRatio = (int)(($L2 + 0.05) / ($L1 + 0.05));
942
        }
943
        // If contrast is more than 5, return black color
944
        if ($contrastRatio > 5) {
945
            return '#000000';
946
        } else {
947
            // if not, return white color.
948
            return '#FFFFFF';
949
        }
950
}