2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * Badge award criteria
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 * Criteria type constant to class name mapping
74 global $BADGE_CRITERIA_TYPES;
75 $BADGE_CRITERIA_TYPES = array(
76 BADGE_CRITERIA_TYPE_OVERALL
=> 'overall',
77 BADGE_CRITERIA_TYPE_ACTIVITY
=> 'activity',
78 BADGE_CRITERIA_TYPE_MANUAL
=> 'manual',
79 BADGE_CRITERIA_TYPE_SOCIAL
=> 'social',
80 BADGE_CRITERIA_TYPE_COURSE
=> 'course',
81 BADGE_CRITERIA_TYPE_COURSESET
=> 'courseset',
82 BADGE_CRITERIA_TYPE_PROFILE
=> 'profile'
86 * Award criteria abstract definition
89 abstract class award_criteria
{
92 * ID of the criterion.
98 * Aggregation method [BADGE_CRITERIA_AGGREGATION_ANY, BADGE_CRITERIA_AGGREGATION_ALL].
104 * ID of a badge this criterion belongs to.
110 * Criterion HTML/plain text description.
116 * Format of the criterion description.
119 public $descriptionformat;
122 * Any additional parameters.
125 public $params = array();
128 * The base constructor
130 * @param array $params
132 public function __construct($params) {
133 $this->id
= isset($params['id']) ?
$params['id'] : 0;
134 $this->method
= isset($params['method']) ?
$params['method'] : BADGE_CRITERIA_AGGREGATION_ANY
;
135 $this->badgeid
= $params['badgeid'];
136 $this->description
= isset($params['description']) ?
$params['description'] : '';
137 $this->descriptionformat
= isset($params['descriptionformat']) ?
$params['descriptionformat'] : FORMAT_HTML
;
138 if (isset($params['id'])) {
139 $this->params
= $this->get_params($params['id']);
144 * Factory method for creating criteria class object
146 * @param array $params associative arrays varname => value
147 * @return award_criteria
149 public static function build($params) {
150 global $CFG, $BADGE_CRITERIA_TYPES;
152 if (!isset($params['criteriatype']) ||
!isset($BADGE_CRITERIA_TYPES[$params['criteriatype']])) {
153 print_error('error:invalidcriteriatype', 'badges');
156 $class = 'award_criteria_' . $BADGE_CRITERIA_TYPES[$params['criteriatype']];
157 require_once($CFG->dirroot
. '/badges/criteria/' . $class . '.php');
159 return new $class($params);
163 * Return criteria title
167 public function get_title() {
168 return get_string('criteria_' . $this->criteriatype
, 'badges');
172 * Get criteria details for displaying to users
174 * @param string $short Print short version of criteria
177 abstract public function get_details($short = '');
180 * Add appropriate criteria options to the form
183 abstract public function get_options(&$mform);
186 * Add appropriate parameter elements to the criteria form
189 public function config_options(&$mform, $param) {
191 $prefix = $this->required_param
. '_';
193 if ($param['error']) {
194 $parameter[] =& $mform->createElement('advcheckbox', $prefix . $param['id'], '',
195 $OUTPUT->error_text($param['name']), null, array(0, $param['id']));
196 $mform->addGroup($parameter, 'param_' . $prefix . $param['id'], '', array(' '), false);
198 $parameter[] =& $mform->createElement('advcheckbox', $prefix . $param['id'], '', $param['name'], null, array(0, $param['id']));
199 $parameter[] =& $mform->createElement('static', 'break_start_' . $param['id'], null, '<div style="margin-left: 3em;">');
201 if (in_array('grade', $this->optional_params
)) {
202 $parameter[] =& $mform->createElement('static', 'mgrade_' . $param['id'], null, get_string('mingrade', 'badges'));
203 $parameter[] =& $mform->createElement('text', 'grade_' . $param['id'], '', array('size' => '5'));
204 $mform->setType('grade_' . $param['id'], PARAM_INT
);
207 if (in_array('bydate', $this->optional_params
)) {
208 $parameter[] =& $mform->createElement('static', 'complby_' . $param['id'], null, get_string('bydate', 'badges'));
209 $parameter[] =& $mform->createElement('date_selector', 'bydate_' . $param['id'], "", array('optional' => true));
212 $parameter[] =& $mform->createElement('static', 'break_end_' . $param['id'], null, '</div>');
213 $mform->addGroup($parameter, 'param_' . $prefix . $param['id'], '', array(' '), false);
214 if (in_array('grade', $this->optional_params
)) {
215 $mform->addGroupRule('param_' . $prefix . $param['id'], array(
216 'grade_' . $param['id'] => array(array(get_string('err_numeric', 'form'), 'numeric', '', 'client'))));
218 $mform->disabledIf('bydate_' . $param['id'] . '[day]', 'bydate_' . $param['id'] . '[enabled]', 'notchecked');
219 $mform->disabledIf('bydate_' . $param['id'] . '[month]', 'bydate_' . $param['id'] . '[enabled]', 'notchecked');
220 $mform->disabledIf('bydate_' . $param['id'] . '[year]', 'bydate_' . $param['id'] . '[enabled]', 'notchecked');
221 $mform->disabledIf('param_' . $prefix . $param['id'], $prefix . $param['id'], 'notchecked');
224 // Set default values.
225 $mform->setDefault($prefix . $param['id'], $param['checked']);
226 if (isset($param['bydate'])) {
227 $mform->setDefault('bydate_' . $param['id'], $param['bydate']);
229 if (isset($param['grade'])) {
230 $mform->setDefault('grade_' . $param['id'], $param['grade']);
235 * Add appropriate criteria elements
237 * @param stdClass $data details of various criteria
239 public function config_form_criteria($data) {
241 $agg = $data->get_aggregation_methods();
243 $editurl = new moodle_url('/badges/criteria_settings.php',
244 array('badgeid' => $this->badgeid
, 'edit' => true, 'type' => $this->criteriatype
, 'crit' => $this->id
));
245 $deleteurl = new moodle_url('/badges/criteria_action.php',
246 array('badgeid' => $this->badgeid
, 'delete' => true, 'type' => $this->criteriatype
));
247 $editaction = $OUTPUT->action_icon($editurl, new pix_icon('t/edit', get_string('edit')), null, array('class' => 'criteria-action'));
248 $deleteaction = $OUTPUT->action_icon($deleteurl, new pix_icon('t/delete', get_string('delete')), null, array('class' => 'criteria-action'));
250 echo $OUTPUT->box_start();
251 if (!$data->is_locked() && !$data->is_active()) {
252 echo $OUTPUT->box($deleteaction . $editaction, array('criteria-header'));
254 echo $OUTPUT->heading($this->get_title() . $OUTPUT->help_icon('criteria_' . $this->criteriatype
, 'badges'), 3, 'main help');
256 if (!empty($this->description
)) {
257 $badge = new badge($this->badgeid
);
259 format_text($this->description
, $this->descriptionformat
, array('context' => $badge->get_context())),
260 'criteria-description'
264 if (!empty($this->params
)) {
265 if (count($this->params
) > 1) {
266 echo $OUTPUT->box(get_string('criteria_descr_' . $this->criteriatype
, 'badges',
267 core_text
::strtoupper($agg[$data->get_aggregation_method($this->criteriatype
)])), array('clearfix'));
269 echo $OUTPUT->box(get_string('criteria_descr_single_' . $this->criteriatype
, 'badges'), array('clearfix'));
271 echo $OUTPUT->box($this->get_details(), array('clearfix'));
273 echo $OUTPUT->box_end();
277 * Review this criteria and decide if the user has completed
279 * @param int $userid User whose criteria completion needs to be reviewed.
280 * @param bool $filtered An additional parameter indicating that user list
281 * has been reduced and some expensive checks can be skipped.
283 * @return bool Whether criteria is complete
285 abstract public function review($userid, $filtered = false);
288 * Returns array with sql code and parameters returning all ids
289 * of users who meet this particular criterion.
291 * @return array list($join, $where, $params)
293 abstract public function get_completed_criteria_sql();
296 * Mark this criteria as complete for a user
298 * @param int $userid User whose criteria is completed.
300 public function mark_complete($userid) {
303 $obj['critid'] = $this->id
;
304 $obj['userid'] = $userid;
305 $obj['datemet'] = time();
306 if (!$DB->record_exists('badge_criteria_met', array('critid' => $this->id
, 'userid' => $userid))) {
307 $DB->insert_record('badge_criteria_met', $obj);
312 * Return criteria parameters
314 * @param int $critid Criterion ID
317 public function get_params($cid) {
321 $records = $DB->get_records('badge_criteria_param', array('critid' => $cid));
322 foreach ($records as $rec) {
323 $arr = explode('_', $rec->name
);
324 $params[$arr[1]][$arr[0]] = $rec->value
;
331 * Delete this criterion
334 public function delete() {
337 // Remove any records if it has already been met.
338 $DB->delete_records('badge_criteria_met', array('critid' => $this->id
));
340 // Remove all parameters records.
341 $DB->delete_records('badge_criteria_param', array('critid' => $this->id
));
343 // Finally remove criterion itself.
344 $DB->delete_records('badge_criteria', array('id' => $this->id
));
348 * Saves intial criteria records with required parameters set up.
350 * @param array $params Values from the form or any other array.
352 public function save($params = array()) {
355 // Figure out criteria description.
356 // If it is coming from the form editor, it is an array(text, format).
358 $descriptionformat = FORMAT_HTML
;
359 if (isset($params['description']['text'])) {
360 $description = $params['description']['text'];
361 $descriptionformat = $params['description']['format'];
362 } else if (isset($params['description'])) {
363 $description = $params['description'];
366 $fordb = new stdClass();
367 $fordb->criteriatype
= $this->criteriatype
;
368 $fordb->method
= isset($params['agg']) ?
$params['agg'] : BADGE_CRITERIA_AGGREGATION_ALL
;
369 $fordb->badgeid
= $this->badgeid
;
370 $fordb->description
= $description;
371 $fordb->descriptionformat
= $descriptionformat;
372 $t = $DB->start_delegated_transaction();
374 // Pick only params that are required by this criterion.
375 // Filter out empty values first.
376 $params = array_filter($params);
377 // Find out which param matches optional and required ones.
378 $match = array_merge($this->optional_params
, array($this->required_param
));
379 $regex = implode('|', array_map(create_function('$a', 'return $a . "_";'), $match));
380 $requiredkeys = preg_grep('/^(' . $regex . ').*$/', array_keys($params));
382 if ($this->id
!== 0) {
385 // Update criteria before doing anything with parameters.
387 $DB->update_record('badge_criteria', $fordb, true);
389 $existing = $DB->get_fieldset_select('badge_criteria_param', 'name', 'critid = ?', array($cid));
390 $todelete = array_diff($existing, $requiredkeys);
392 if (!empty($todelete)) {
393 // A workaround to add some disabled elements that are still being submitted from the form.
394 foreach ($todelete as $del) {
395 $name = explode('_', $del);
396 if ($name[0] == $this->required_param
) {
397 foreach ($this->optional_params
as $opt) {
398 $todelete[] = $opt . '_' . $name[1];
402 $todelete = array_unique($todelete);
403 list($sql, $sqlparams) = $DB->get_in_or_equal($todelete, SQL_PARAMS_NAMED
, 'd', true);
404 $sqlparams = array_merge(array('critid' => $cid), $sqlparams);
405 $DB->delete_records_select('badge_criteria_param', 'critid = :critid AND name ' . $sql, $sqlparams);
408 foreach ($requiredkeys as $key) {
409 if (in_array($key, $existing)) {
410 $updp = $DB->get_record('badge_criteria_param', array('name' => $key, 'critid' => $cid));
411 $updp->value
= $params[$key];
412 $DB->update_record('badge_criteria_param', $updp, true);
414 $newp = new stdClass();
415 $newp->critid
= $cid;
417 $newp->value
= $params[$key];
418 $DB->insert_record('badge_criteria_param', $newp);
422 $cid = $DB->insert_record('badge_criteria', $fordb, true);
424 foreach ($requiredkeys as $key) {
425 $newp = new stdClass();
426 $newp->critid
= $cid;
428 $newp->value
= $params[$key];
429 $DB->insert_record('badge_criteria_param', $newp, false, true);
437 * Saves intial criteria records with required parameters set up.
439 public function make_clone($newbadgeid) {
442 $fordb = new stdClass();
443 $fordb->criteriatype
= $this->criteriatype
;
444 $fordb->method
= $this->method
;
445 $fordb->badgeid
= $newbadgeid;
446 $fordb->description
= $this->description
;
447 $fordb->descriptionformat
= $this->descriptionformat
;
448 if (($newcrit = $DB->insert_record('badge_criteria', $fordb, true)) && isset($this->params
)) {
449 foreach ($this->params
as $k => $param) {
450 foreach ($param as $key => $value) {
451 $paramdb = new stdClass();
452 $paramdb->critid
= $newcrit;
453 $paramdb->name
= $key . '_' . $k;
454 $paramdb->value
= $value;
455 $DB->insert_record('badge_criteria_param', $paramdb);