Merge branch 'MDL-63625-master' of git://github.com/marinaglancy/moodle
[moodle.git] / badges / criteria / award_criteria.php
blob0fb86e18e956ad2602c17d9a3d88e0229748e7a7
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.
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/>.
17 /**
18 * Badge award criteria
20 * @package core
21 * @subpackage badges
22 * @copyright 2012 onwards Totara Learning Solutions Ltd {@link http://www.totaralms.com/}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 * @author Yuliya Bozhko <yuliya.bozhko@totaralms.com>
27 defined('MOODLE_INTERNAL') || die();
30 * Role completion criteria type
31 * Criteria type constant, primarily for storing criteria type in the database.
33 define('BADGE_CRITERIA_TYPE_OVERALL', 0);
36 * Activity completion criteria type
37 * Criteria type constant, primarily for storing criteria type in the database.
39 define('BADGE_CRITERIA_TYPE_ACTIVITY', 1);
42 * Duration completion criteria type
43 * Criteria type constant, primarily for storing criteria type in the database.
45 define('BADGE_CRITERIA_TYPE_MANUAL', 2);
48 * Grade completion criteria type
49 * Criteria type constant, primarily for storing criteria type in the database.
51 define('BADGE_CRITERIA_TYPE_SOCIAL', 3);
54 * Course completion criteria type
55 * Criteria type constant, primarily for storing criteria type in the database.
57 define('BADGE_CRITERIA_TYPE_COURSE', 4);
60 * Courseset completion criteria type
61 * Criteria type constant, primarily for storing criteria type in the database.
63 define('BADGE_CRITERIA_TYPE_COURSESET', 5);
66 * Course completion criteria type
67 * Criteria type constant, primarily for storing criteria type in the database.
69 define('BADGE_CRITERIA_TYPE_PROFILE', 6);
72 * Badge completion criteria type
73 * Criteria type constant, primarily for storing criteria type in the database.
75 define('BADGE_CRITERIA_TYPE_BADGE', 7);
78 * Cohort criteria type
79 * Criteria type constant, primarily for storing criteria type in the database.
81 define('BADGE_CRITERIA_TYPE_COHORT', 8);
84 * Criteria type constant to class name mapping
86 global $BADGE_CRITERIA_TYPES;
87 $BADGE_CRITERIA_TYPES = array(
88 BADGE_CRITERIA_TYPE_OVERALL => 'overall',
89 BADGE_CRITERIA_TYPE_ACTIVITY => 'activity',
90 BADGE_CRITERIA_TYPE_MANUAL => 'manual',
91 BADGE_CRITERIA_TYPE_SOCIAL => 'social',
92 BADGE_CRITERIA_TYPE_COURSE => 'course',
93 BADGE_CRITERIA_TYPE_COURSESET => 'courseset',
94 BADGE_CRITERIA_TYPE_PROFILE => 'profile',
95 BADGE_CRITERIA_TYPE_BADGE => 'badge',
96 BADGE_CRITERIA_TYPE_COHORT => 'cohort',
99 /**
100 * Award criteria abstract definition
103 abstract class award_criteria {
106 * ID of the criterion.
107 * @var integer
109 public $id;
112 * Aggregation method [BADGE_CRITERIA_AGGREGATION_ANY, BADGE_CRITERIA_AGGREGATION_ALL].
113 * @var integer
115 public $method;
118 * ID of a badge this criterion belongs to.
119 * @var integer
121 public $badgeid;
124 * Criterion HTML/plain text description.
125 * @var string
127 public $description;
130 * Format of the criterion description.
131 * @var integer
133 public $descriptionformat;
136 * Any additional parameters.
137 * @var array
139 public $params = array();
142 * The base constructor
144 * @param array $params
146 public function __construct($params) {
147 $this->id = isset($params['id']) ? $params['id'] : 0;
148 $this->method = isset($params['method']) ? $params['method'] : BADGE_CRITERIA_AGGREGATION_ANY;
149 $this->badgeid = $params['badgeid'];
150 $this->description = isset($params['description']) ? $params['description'] : '';
151 $this->descriptionformat = isset($params['descriptionformat']) ? $params['descriptionformat'] : FORMAT_HTML;
152 if (isset($params['id'])) {
153 $this->params = $this->get_params($params['id']);
158 * Factory method for creating criteria class object
160 * @param array $params associative arrays varname => value
161 * @return award_criteria
163 public static function build($params) {
164 global $CFG, $BADGE_CRITERIA_TYPES;
166 if (!isset($params['criteriatype']) || !isset($BADGE_CRITERIA_TYPES[$params['criteriatype']])) {
167 print_error('error:invalidcriteriatype', 'badges');
170 $class = 'award_criteria_' . $BADGE_CRITERIA_TYPES[$params['criteriatype']];
171 require_once($CFG->dirroot . '/badges/criteria/' . $class . '.php');
173 return new $class($params);
177 * Return criteria title
179 * @return string
181 public function get_title() {
182 return get_string('criteria_' . $this->criteriatype, 'badges');
186 * Get criteria details for displaying to users
188 * @param string $short Print short version of criteria
189 * @return string
191 abstract public function get_details($short = '');
194 * Add appropriate criteria options to the form
197 abstract public function get_options(&$mform);
200 * Add appropriate parameter elements to the criteria form
203 public function config_options(&$mform, $param) {
204 global $OUTPUT;
205 $prefix = $this->required_param . '_';
207 if ($param['error']) {
208 $parameter[] =& $mform->createElement('advcheckbox', $prefix . $param['id'], '',
209 $OUTPUT->error_text($param['name']), null, array(0, $param['id']));
210 $mform->addGroup($parameter, 'param_' . $prefix . $param['id'], '', array(' '), false);
211 } else {
212 $parameter[] =& $mform->createElement('advcheckbox', $prefix . $param['id'], '', $param['name'], null, array(0, $param['id']));
213 $parameter[] =& $mform->createElement('static', 'break_start_' . $param['id'], null,
214 '<div class="ml-3 mt-1 w-100 align-items-center">');
216 if (in_array('grade', $this->optional_params)) {
217 $parameter[] =& $mform->createElement('static', 'mgrade_' . $param['id'], null, get_string('mingrade', 'badges'));
218 $parameter[] =& $mform->createElement('text', 'grade_' . $param['id'], '', array('size' => '5'));
219 $mform->setType('grade_' . $param['id'], PARAM_INT);
222 if (in_array('bydate', $this->optional_params)) {
223 $parameter[] =& $mform->createElement('static', 'complby_' . $param['id'], null, get_string('bydate', 'badges'));
224 $parameter[] =& $mform->createElement('date_selector', 'bydate_' . $param['id'], "", array('optional' => true));
227 $parameter[] =& $mform->createElement('static', 'break_end_' . $param['id'], null, '</div>');
228 $mform->addGroup($parameter, 'param_' . $prefix . $param['id'], '', array(' '), false);
229 if (in_array('grade', $this->optional_params)) {
230 $mform->addGroupRule('param_' . $prefix . $param['id'], array(
231 'grade_' . $param['id'] => array(array(get_string('err_numeric', 'form'), 'numeric', '', 'client'))));
233 $mform->disabledIf('bydate_' . $param['id'] . '[day]', 'bydate_' . $param['id'] . '[enabled]', 'notchecked');
234 $mform->disabledIf('bydate_' . $param['id'] . '[month]', 'bydate_' . $param['id'] . '[enabled]', 'notchecked');
235 $mform->disabledIf('bydate_' . $param['id'] . '[year]', 'bydate_' . $param['id'] . '[enabled]', 'notchecked');
236 $mform->disabledIf('param_' . $prefix . $param['id'], $prefix . $param['id'], 'notchecked');
239 // Set default values.
240 $mform->setDefault($prefix . $param['id'], $param['checked']);
241 if (isset($param['bydate'])) {
242 $mform->setDefault('bydate_' . $param['id'], $param['bydate']);
244 if (isset($param['grade'])) {
245 $mform->setDefault('grade_' . $param['id'], $param['grade']);
250 * Add appropriate criteria elements
252 * @param stdClass $data details of various criteria
254 public function config_form_criteria($data) {
255 global $OUTPUT;
256 $agg = $data->get_aggregation_methods();
258 $editurl = new moodle_url('/badges/criteria_settings.php',
259 array('badgeid' => $this->badgeid, 'edit' => true, 'type' => $this->criteriatype, 'crit' => $this->id));
260 $deleteurl = new moodle_url('/badges/criteria_action.php',
261 array('badgeid' => $this->badgeid, 'delete' => true, 'type' => $this->criteriatype));
262 $editaction = $OUTPUT->action_icon($editurl, new pix_icon('t/edit', get_string('edit')), null, array('class' => 'criteria-action'));
263 $deleteaction = $OUTPUT->action_icon($deleteurl, new pix_icon('t/delete', get_string('delete')), null, array('class' => 'criteria-action'));
265 echo $OUTPUT->box_start();
266 if (!$data->is_locked() && !$data->is_active()) {
267 echo $OUTPUT->box($deleteaction . $editaction, array('criteria-header'));
269 echo $OUTPUT->heading($this->get_title() . $OUTPUT->help_icon('criteria_' . $this->criteriatype, 'badges'), 3, 'main help');
271 if (!empty($this->description)) {
272 $badge = new badge($this->badgeid);
273 echo $OUTPUT->box(
274 format_text($this->description, $this->descriptionformat, array('context' => $badge->get_context())),
275 'criteria-description'
279 if (!empty($this->params)) {
280 if (count($this->params) > 1) {
281 echo $OUTPUT->box(get_string('criteria_descr_' . $this->criteriatype, 'badges',
282 core_text::strtoupper($agg[$data->get_aggregation_method($this->criteriatype)])), array('clearfix'));
283 } else {
284 echo $OUTPUT->box(get_string('criteria_descr_single_' . $this->criteriatype , 'badges'), array('clearfix'));
286 echo $OUTPUT->box($this->get_details(), array('clearfix'));
288 echo $OUTPUT->box_end();
292 * Review this criteria and decide if the user has completed
294 * @param int $userid User whose criteria completion needs to be reviewed.
295 * @param bool $filtered An additional parameter indicating that user list
296 * has been reduced and some expensive checks can be skipped.
298 * @return bool Whether criteria is complete
300 abstract public function review($userid, $filtered = false);
303 * Returns array with sql code and parameters returning all ids
304 * of users who meet this particular criterion.
306 * @return array list($join, $where, $params)
308 abstract public function get_completed_criteria_sql();
311 * Mark this criteria as complete for a user
313 * @param int $userid User whose criteria is completed.
315 public function mark_complete($userid) {
316 global $DB;
317 $obj = array();
318 $obj['critid'] = $this->id;
319 $obj['userid'] = $userid;
320 $obj['datemet'] = time();
321 if (!$DB->record_exists('badge_criteria_met', array('critid' => $this->id, 'userid' => $userid))) {
322 $DB->insert_record('badge_criteria_met', $obj);
327 * Return criteria parameters
329 * @param int $critid Criterion ID
330 * @return array
332 public function get_params($cid) {
333 global $DB;
334 $params = array();
336 $records = $DB->get_records('badge_criteria_param', array('critid' => $cid));
337 foreach ($records as $rec) {
338 $arr = explode('_', $rec->name);
339 $params[$arr[1]][$arr[0]] = $rec->value;
342 return $params;
346 * Delete this criterion
349 public function delete() {
350 global $DB, $PAGE;
352 // Remove any records if it has already been met.
353 $DB->delete_records('badge_criteria_met', array('critid' => $this->id));
355 // Remove all parameters records.
356 $DB->delete_records('badge_criteria_param', array('critid' => $this->id));
358 // Finally remove criterion itself.
359 $DB->delete_records('badge_criteria', array('id' => $this->id));
361 // Trigger event, badge criteria deleted.
362 $eventparams = array('objectid' => $this->id,
363 'context' => $PAGE->context,
364 'other' => array('badgeid' => $this->badgeid));
365 $event = \core\event\badge_criteria_deleted::create($eventparams);
366 $event->trigger();
370 * Saves intial criteria records with required parameters set up.
372 * @param array $params Values from the form or any other array.
374 public function save($params = array()) {
375 global $DB, $PAGE;
377 // Figure out criteria description.
378 // If it is coming from the form editor, it is an array(text, format).
379 $description = '';
380 $descriptionformat = FORMAT_HTML;
381 if (isset($params['description']['text'])) {
382 $description = $params['description']['text'];
383 $descriptionformat = $params['description']['format'];
384 } else if (isset($params['description'])) {
385 $description = $params['description'];
388 $fordb = new stdClass();
389 $fordb->criteriatype = $this->criteriatype;
390 $fordb->method = isset($params['agg']) ? $params['agg'] : BADGE_CRITERIA_AGGREGATION_ALL;
391 $fordb->badgeid = $this->badgeid;
392 $fordb->description = $description;
393 $fordb->descriptionformat = $descriptionformat;
394 $t = $DB->start_delegated_transaction();
396 // Pick only params that are required by this criterion.
397 // Filter out empty values first.
398 $params = array_filter($params);
399 // Find out which param matches optional and required ones.
400 $match = array_merge($this->optional_params, array($this->required_param));
401 $regex = implode('|', array_map(function($a) {
402 return $a . "_";
403 }, $match));
404 $requiredkeys = preg_grep('/^(' . $regex . ').*$/', array_keys($params));
406 if ($this->id !== 0) {
407 $cid = $this->id;
409 // Update criteria before doing anything with parameters.
410 $fordb->id = $cid;
411 $DB->update_record('badge_criteria', $fordb, true);
413 // Trigger event: badge_criteria_updated.
414 $eventparams = array('objectid' => $this->id,
415 'context' => $PAGE->context,
416 'other' => array('badgeid' => $this->badgeid));
417 $event = \core\event\badge_criteria_updated::create($eventparams);
418 $event->trigger();
420 $existing = $DB->get_fieldset_select('badge_criteria_param', 'name', 'critid = ?', array($cid));
421 $todelete = array_diff($existing, $requiredkeys);
423 if (!empty($todelete)) {
424 // A workaround to add some disabled elements that are still being submitted from the form.
425 foreach ($todelete as $del) {
426 $name = explode('_', $del);
427 if ($name[0] == $this->required_param) {
428 foreach ($this->optional_params as $opt) {
429 $todelete[] = $opt . '_' . $name[1];
433 $todelete = array_unique($todelete);
434 list($sql, $sqlparams) = $DB->get_in_or_equal($todelete, SQL_PARAMS_NAMED, 'd', true);
435 $sqlparams = array_merge(array('critid' => $cid), $sqlparams);
436 $DB->delete_records_select('badge_criteria_param', 'critid = :critid AND name ' . $sql, $sqlparams);
439 foreach ($requiredkeys as $key) {
440 if (in_array($key, $existing)) {
441 $updp = $DB->get_record('badge_criteria_param', array('name' => $key, 'critid' => $cid));
442 $updp->value = $params[$key];
443 $DB->update_record('badge_criteria_param', $updp, true);
444 } else {
445 $newp = new stdClass();
446 $newp->critid = $cid;
447 $newp->name = $key;
448 $newp->value = $params[$key];
449 $DB->insert_record('badge_criteria_param', $newp);
452 } else {
453 $cid = $DB->insert_record('badge_criteria', $fordb, true);
454 if ($cid) {
455 foreach ($requiredkeys as $key) {
456 $newp = new stdClass();
457 $newp->critid = $cid;
458 $newp->name = $key;
459 $newp->value = $params[$key];
460 $DB->insert_record('badge_criteria_param', $newp, false, true);
463 // Trigger event: badge_criteria_created.
464 $eventparams = array('objectid' => $this->id,
465 'context' => $PAGE->context,
466 'other' => array('badgeid' => $this->badgeid));
467 $event = \core\event\badge_criteria_created::create($eventparams);
468 $event->trigger();
470 $t->allow_commit();
474 * Saves intial criteria records with required parameters set up.
476 public function make_clone($newbadgeid) {
477 global $DB;
479 $fordb = new stdClass();
480 $fordb->criteriatype = $this->criteriatype;
481 $fordb->method = $this->method;
482 $fordb->badgeid = $newbadgeid;
483 $fordb->description = $this->description;
484 $fordb->descriptionformat = $this->descriptionformat;
485 if (($newcrit = $DB->insert_record('badge_criteria', $fordb, true)) && isset($this->params)) {
486 foreach ($this->params as $k => $param) {
487 foreach ($param as $key => $value) {
488 $paramdb = new stdClass();
489 $paramdb->critid = $newcrit;
490 $paramdb->name = $key . '_' . $k;
491 $paramdb->value = $value;
492 $DB->insert_record('badge_criteria_param', $paramdb);