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 the customcert module for 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
 * This file contains the customcert element date's core interaction API.
19
 *
20
 * @package    customcertelement_date
21
 * @copyright  2013 Mark Nelson <markn@moodle.com>
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace customcertelement_date;
26
 
27
defined('MOODLE_INTERNAL') || die();
28
 
29
/**
30
 * Date - Course grade date
31
 */
32
define('CUSTOMCERT_DATE_COURSE_GRADE', '0');
33
 
34
/**
35
 * Date - Issue
36
 */
37
define('CUSTOMCERT_DATE_ISSUE', '-1');
38
 
39
/**
40
 * Date - Completion
41
 */
42
define('CUSTOMCERT_DATE_COMPLETION', '-2');
43
 
44
/**
45
 * Date - Course start
46
 */
47
define('CUSTOMCERT_DATE_COURSE_START', '-3');
48
 
49
/**
50
 * Date - Course end
51
 */
52
define('CUSTOMCERT_DATE_COURSE_END', '-4');
53
 
54
/**
55
 * Date - Current date
56
 */
57
define('CUSTOMCERT_DATE_CURRENT_DATE', '-5');
58
 
59
/**
60
 * Date - Enrollment start
61
 */
62
define('CUSTOMCERT_DATE_ENROLMENT_START', '-6');
63
 
64
/**
65
 * Date - Entrollment end
66
 */
67
define('CUSTOMCERT_DATE_ENROLMENT_END', '-7');
68
 
69
/**
70
 * Date - Relative expiry date of 1 year
71
 */
72
define('CUSTOMCERT_DATE_EXPIRY_ONE', '-8');
73
 
74
/**
75
 * Date - Relative expiry date of 2 year
76
 */
77
define('CUSTOMCERT_DATE_EXPIRY_TWO', '-9');
78
 
79
/**
80
 * Date - Relative expiry date of 3 year
81
 */
82
define('CUSTOMCERT_DATE_EXPIRY_THREE', '-10');
83
 
84
/**
85
 * Date - Relative expiry date of 4 year
86
 */
87
define('CUSTOMCERT_DATE_EXPIRY_FOUR', '-11');
88
 
89
/**
90
 * Date - Relative expiry date of 5 year
91
 */
92
define('CUSTOMCERT_DATE_EXPIRY_FIVE', '-12');
93
 
94
require_once($CFG->dirroot . '/lib/grade/constants.php');
95
 
96
/**
97
 * The customcert element date's core interaction API.
98
 *
99
 * @package    customcertelement_date
100
 * @copyright  2013 Mark Nelson <markn@moodle.com>
101
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
102
 */
103
class element extends \mod_customcert\element {
104
 
105
    /**
106
     * This function renders the form elements when adding a customcert element.
107
     *
108
     * @param \MoodleQuickForm $mform the edit_form instance
109
     */
110
    public function render_form_elements($mform) {
111
        global $CFG, $COURSE;
112
 
113
        // Get the possible date options.
114
        $dateoptions = [];
115
        $dateoptions[CUSTOMCERT_DATE_ISSUE] = get_string('issueddate', 'customcertelement_date');
116
        $dateoptions[CUSTOMCERT_DATE_CURRENT_DATE] = get_string('currentdate', 'customcertelement_date');
117
        $completionenabled = $CFG->enablecompletion && ($COURSE->id == SITEID || $COURSE->enablecompletion);
118
        if ($completionenabled) {
119
            $dateoptions[CUSTOMCERT_DATE_COMPLETION] = get_string('completiondate', 'customcertelement_date');
120
        }
121
        $dateoptions[CUSTOMCERT_DATE_ENROLMENT_START] = get_string('enrolmentstartdate', 'customcertelement_date');
122
        $dateoptions[CUSTOMCERT_DATE_ENROLMENT_END] = get_string('enrolmentenddate', 'customcertelement_date');
123
        $dateoptions[CUSTOMCERT_DATE_EXPIRY_ONE] = get_string('expirydateone', 'customcertelement_date');
124
        $dateoptions[CUSTOMCERT_DATE_EXPIRY_TWO] = get_string('expirydatetwo', 'customcertelement_date');
125
        $dateoptions[CUSTOMCERT_DATE_EXPIRY_THREE] = get_string('expirydatethree', 'customcertelement_date');
126
        $dateoptions[CUSTOMCERT_DATE_EXPIRY_FOUR] = get_string('expirydatefour', 'customcertelement_date');
127
        $dateoptions[CUSTOMCERT_DATE_EXPIRY_FIVE] = get_string('expirydatefive', 'customcertelement_date');
128
        $dateoptions[CUSTOMCERT_DATE_COURSE_START] = get_string('coursestartdate', 'customcertelement_date');
129
        $dateoptions[CUSTOMCERT_DATE_COURSE_END] = get_string('courseenddate', 'customcertelement_date');
130
        $dateoptions[CUSTOMCERT_DATE_COURSE_GRADE] = get_string('coursegradedate', 'customcertelement_date');
131
        $dateoptions = $dateoptions + \mod_customcert\element_helper::get_grade_items($COURSE);
132
 
133
        $mform->addElement('select', 'dateitem', get_string('dateitem', 'customcertelement_date'), $dateoptions);
134
        $mform->addHelpButton('dateitem', 'dateitem', 'customcertelement_date');
135
 
136
        $mform->addElement('select', 'dateformat', get_string('dateformat', 'customcertelement_date'), self::get_date_formats());
137
        $mform->addHelpButton('dateformat', 'dateformat', 'customcertelement_date');
138
 
139
        parent::render_form_elements($mform);
140
    }
141
 
142
    /**
143
     * This will handle how form data will be saved into the data column in the
144
     * customcert_elements table.
145
     *
146
     * @param \stdClass $data the form data
147
     * @return string the json encoded array
148
     */
149
    public function save_unique_data($data) {
150
        // Array of data we will be storing in the database.
151
        $arrtostore = [
152
            'dateitem' => $data->dateitem,
153
            'dateformat' => $data->dateformat,
154
        ];
155
 
156
        // Encode these variables before saving into the DB.
157
        return json_encode($arrtostore);
158
    }
159
 
160
    /**
161
     * Handles rendering the element on the pdf.
162
     *
163
     * @param \pdf $pdf the pdf object
164
     * @param bool $preview true if it is a preview, false otherwise
165
     * @param \stdClass $user the user we are rendering this for
166
     */
167
    public function render($pdf, $preview, $user) {
168
        global $DB;
169
 
170
        // If there is no element data, we have nothing to display.
171
        if (empty($this->get_data())) {
172
            return;
173
        }
174
 
175
        $courseid = \mod_customcert\element_helper::get_courseid($this->id);
176
 
177
        // Decode the information stored in the database.
178
        $dateinfo = json_decode($this->get_data());
179
        $dateitem = $dateinfo->dateitem;
180
        $dateformat = $dateinfo->dateformat;
181
 
182
        // If we are previewing this certificate then just show a demonstration date.
183
        if ($preview) {
184
            $date = time();
185
        } else {
186
            // Get the page.
187
            $page = $DB->get_record('customcert_pages', ['id' => $this->get_pageid()], '*', MUST_EXIST);
188
            // Get the customcert this page belongs to.
189
            $customcert = $DB->get_record('customcert', ['templateid' => $page->templateid], '*', MUST_EXIST);
190
            // Now we can get the issue for this user.
191
            $issue = $DB->get_record('customcert_issues', ['userid' => $user->id, 'customcertid' => $customcert->id],
192
                '*', IGNORE_MULTIPLE);
193
 
194
            if ($dateitem == CUSTOMCERT_DATE_ISSUE) {
195
                $date = $issue->timecreated;
196
            } else if ($dateitem == CUSTOMCERT_DATE_EXPIRY_ONE) {
197
                $date = strtotime('+1 years', $issue->timecreated);
198
            } else if ($dateitem == CUSTOMCERT_DATE_EXPIRY_TWO) {
199
                $date = strtotime('+2 years', $issue->timecreated);
200
            } else if ($dateitem == CUSTOMCERT_DATE_EXPIRY_THREE) {
201
                $date = strtotime('+3 years', $issue->timecreated);
202
            } else if ($dateitem == CUSTOMCERT_DATE_EXPIRY_FOUR) {
203
                $date = strtotime('+4 years', $issue->timecreated);
204
            } else if ($dateitem == CUSTOMCERT_DATE_EXPIRY_FIVE) {
205
                $date = strtotime('+5 years', $issue->timecreated);
206
            } else if ($dateitem == CUSTOMCERT_DATE_CURRENT_DATE) {
207
                $date = time();
208
            } else if ($dateitem == CUSTOMCERT_DATE_COMPLETION) {
209
                // Get the last completion date.
210
                $sql = "SELECT MAX(c.timecompleted) as timecompleted
211
                          FROM {course_completions} c
212
                         WHERE c.userid = :userid
213
                           AND c.course = :courseid";
214
                if ($timecompleted = $DB->get_record_sql($sql, ['userid' => $issue->userid, 'courseid' => $courseid])) {
215
                    if (!empty($timecompleted->timecompleted)) {
216
                        $date = $timecompleted->timecompleted;
217
                    }
218
                }
219
            } else if ($dateitem == CUSTOMCERT_DATE_ENROLMENT_START) {
220
                // Get the enrolment start date.
221
                $sql = "SELECT ue.timestart FROM {enrol} e JOIN {user_enrolments} ue ON ue.enrolid = e.id
222
                         WHERE e.courseid = :courseid
223
                           AND ue.userid = :userid";
224
                if ($timestart = $DB->get_record_sql($sql, ['userid' => $issue->userid, 'courseid' => $courseid])) {
225
                    if (!empty($timestart->timestart)) {
226
                        $date = $timestart->timestart;
227
                    }
228
                }
229
            } else if ($dateitem == CUSTOMCERT_DATE_ENROLMENT_END) {
230
                // Get the enrolment end date.
231
                $sql = "SELECT ue.timeend FROM {enrol} e JOIN {user_enrolments} ue ON ue.enrolid = e.id
232
                         WHERE e.courseid = :courseid
233
                           AND ue.userid = :userid";
234
                if ($timeend = $DB->get_record_sql($sql, ['userid' => $issue->userid, 'courseid' => $courseid])) {
235
                    if (!empty($timeend->timeend)) {
236
                        $date = $timeend->timeend;
237
                    }
238
                }
239
            } else if ($dateitem == CUSTOMCERT_DATE_COURSE_START) {
240
                $date = $DB->get_field('course', 'startdate', ['id' => $courseid]);
241
            } else if ($dateitem == CUSTOMCERT_DATE_COURSE_END) {
242
                $date = $DB->get_field('course', 'enddate', ['id' => $courseid]);
243
            } else {
244
                if ($dateitem == CUSTOMCERT_DATE_COURSE_GRADE) {
245
                    $grade = \mod_customcert\element_helper::get_course_grade_info(
246
                        $courseid,
247
                        GRADE_DISPLAY_TYPE_DEFAULT,
248
                        $user->id
249
                    );
250
                } else if (strpos($dateitem, 'gradeitem:') === 0) {
251
                    $gradeitemid = substr($dateitem, 10);
252
                    $grade = \mod_customcert\element_helper::get_grade_item_info(
253
                        $gradeitemid,
254
                        $dateitem,
255
                        $user->id
256
                    );
257
                } else {
258
                    $grade = \mod_customcert\element_helper::get_mod_grade_info(
259
                        $dateitem,
260
                        GRADE_DISPLAY_TYPE_DEFAULT,
261
                        $user->id
262
                    );
263
                }
264
 
265
                if ($grade && !empty($grade->get_dategraded())) {
266
                    $date = $grade->get_dategraded();
267
                }
268
            }
269
        }
270
 
271
        // Ensure that a date has been set.
272
        if (!empty($date)) {
273
            \mod_customcert\element_helper::render_content($pdf, $this, $this->get_date_format_string($date, $dateformat));
274
        }
275
    }
276
 
277
    /**
278
     * Render the element in html.
279
     *
280
     * This function is used to render the element when we are using the
281
     * drag and drop interface to position it.
282
     *
283
     * @return string the html
284
     */
285
    public function render_html() {
286
        // If there is no element data, we have nothing to display.
287
        if (empty($this->get_data())) {
288
            return;
289
        }
290
 
291
        // Decode the information stored in the database.
292
        $dateinfo = json_decode($this->get_data());
293
        $dateformat = $dateinfo->dateformat;
294
 
295
        return \mod_customcert\element_helper::render_html_content($this, $this->get_date_format_string(time(), $dateformat));
296
    }
297
 
298
    /**
299
     * Sets the data on the form when editing an element.
300
     *
301
     * @param \MoodleQuickForm $mform the edit_form instance
302
     */
303
    public function definition_after_data($mform) {
304
        // Set the item and format for this element.
305
        if (!empty($this->get_data())) {
306
            $dateinfo = json_decode($this->get_data());
307
 
308
            $element = $mform->getElement('dateitem');
309
            $element->setValue($dateinfo->dateitem);
310
 
311
            $element = $mform->getElement('dateformat');
312
            $element->setValue($dateinfo->dateformat);
313
        }
314
 
315
        parent::definition_after_data($mform);
316
    }
317
 
318
    /**
319
     * This function is responsible for handling the restoration process of the element.
320
     *
321
     * We will want to update the course module the date element is pointing to as it will
322
     * have changed in the course restore.
323
     *
324
     * @param \restore_customcert_activity_task $restore
325
     */
326
    public function after_restore($restore) {
327
        global $DB;
328
 
329
        $dateinfo = json_decode($this->get_data());
330
 
331
        $isgradeitem = false;
332
        $oldid = $dateinfo->dateitem;
333
        if (str_starts_with($dateinfo->dateitem, 'gradeitem:')) {
334
            $isgradeitem = true;
335
            $oldid = str_replace('gradeitem:', '', $dateinfo->dateitem);
336
        }
337
 
338
        $itemname = $isgradeitem ? 'grade_item' : 'course_module';
339
        if ($newitem = \restore_dbops::get_backup_ids_record($restore->get_restoreid(), $itemname, $oldid)) {
340
            $dateinfo->dateitem = '';
341
            if ($isgradeitem) {
342
                $dateinfo->dateitem = 'gradeitem:';
343
            }
344
            $dateinfo->dateitem = $dateinfo->dateitem . $newitem->newitemid;
345
            $DB->set_field('customcert_elements', 'data', $this->save_unique_data($dateinfo), ['id' => $this->get_id()]);
346
        }
347
    }
348
 
349
    /**
350
     * Helper function to return all the date formats.
351
     *
352
     * @return array the list of date formats
353
     */
354
    public static function get_date_formats() {
355
        // Hard-code date so users can see the difference between short dates with and without the leading zero.
356
        // Eg. 06/07/18 vs 6/07/18.
357
        $date = 1530849658;
358
 
359
        $suffix = self::get_ordinal_number_suffix(userdate($date, '%d'));
360
 
361
        $dateformats = [
362
            1 => userdate($date, '%B %d, %Y'),
363
            2 => userdate($date, '%B %d' . $suffix . ', %Y'),
364
        ];
365
 
366
        $strdateformats = [
367
            'strftimedate',
368
            'strftimedatefullshort',
369
            'strftimedatefullshortwleadingzero',
370
            'strftimedateshort',
371
            'strftimedatetime',
372
            'strftimedatetimeshort',
373
            'strftimedatetimeshortwleadingzero',
374
            'strftimedaydate',
375
            'strftimedaydatetime',
376
            'strftimedayshort',
377
            'strftimedaytime',
378
            'strftimemonthyear',
379
            'strftimerecent',
380
            'strftimerecentfull',
381
            'strftimetime',
382
        ];
383
 
384
        foreach ($strdateformats as $strdateformat) {
385
            if ($strdateformat == 'strftimedatefullshortwleadingzero') {
386
                $dateformats[$strdateformat] = userdate($date, get_string('strftimedatefullshort', 'langconfig'), 99, false);
387
            } else if ($strdateformat == 'strftimedatetimeshortwleadingzero') {
388
                $dateformats[$strdateformat] = userdate($date, get_string('strftimedatetimeshort', 'langconfig'), 99, false);
389
            } else {
390
                $dateformats[$strdateformat] = userdate($date, get_string($strdateformat, 'langconfig'));
391
            }
392
        }
393
 
394
        return $dateformats;
395
    }
396
 
397
    /**
398
     * Returns the date in a readable format.
399
     *
400
     * @param int $date
401
     * @param string $dateformat
402
     * @return string
403
     */
404
    protected function get_date_format_string($date, $dateformat) {
405
        // Keeping for backwards compatibility.
406
        if (is_number($dateformat)) {
407
            switch ($dateformat) {
408
                case 1:
409
                    $certificatedate = userdate($date, '%B %d, %Y');
410
                    break;
411
                case 2:
412
                    $suffix = self::get_ordinal_number_suffix(userdate($date, '%d'));
413
                    $certificatedate = userdate($date, '%B %d' . $suffix . ', %Y');
414
                    break;
415
                case 3:
416
                    $certificatedate = userdate($date, '%d %B %Y');
417
                    break;
418
                case 4:
419
                    $certificatedate = userdate($date, '%B %Y');
420
                    break;
421
                default:
422
                    $certificatedate = userdate($date, get_string('strftimedate', 'langconfig'));
423
            }
424
        }
425
 
426
        // Ok, so we must have been passed the actual format in the lang file.
427
        if (!isset($certificatedate)) {
428
            if ($dateformat == 'strftimedatefullshortwleadingzero') {
429
                $certificatedate = userdate($date, get_string('strftimedatefullshort', 'langconfig'), 99, false);
430
            } else if ($dateformat == 'strftimedatetimeshortwleadingzero') {
431
                $certificatedate = userdate($date, get_string('strftimedatetimeshort', 'langconfig'), 99, false);
432
            } else {
433
                $certificatedate = userdate($date, get_string($dateformat, 'langconfig'));
434
            }
435
        }
436
 
437
        return $certificatedate;
438
    }
439
 
440
    /**
441
     * Helper function to return the suffix of the day of
442
     * the month, eg 'st' if it is the 1st of the month.
443
     *
444
     * @param int $day the day of the month
445
     * @return string the suffix.
446
     */
447
    protected static function get_ordinal_number_suffix($day) {
448
        if (!in_array(($day % 100), [11, 12, 13])) {
449
            switch ($day % 10) {
450
                // Handle 1st, 2nd, 3rd.
451
                case 1:
452
                    return get_string('numbersuffix_st_as_in_first', 'customcertelement_date');
453
                case 2:
454
                    return get_string('numbersuffix_nd_as_in_second', 'customcertelement_date');
455
                case 3:
456
                    return get_string('numbersuffix_rd_as_in_third', 'customcertelement_date');
457
            }
458
        }
459
        return 'th';
460
    }
461
}