MDL-52919 tool_lp: Show the path when listing competencies
[moodle.git] / admin / tool / lp / classes / competency.php
blob59297929407fff7ea16ba971cbf65def6ca336ff
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 * Class for loading/storing competencies from the DB.
20 * @package tool_lp
21 * @copyright 2015 Damyon Wiese
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 namespace tool_lp;
25 defined('MOODLE_INTERNAL') || die();
27 use coding_exception;
28 use context_system;
29 use lang_string;
30 use stdClass;
32 require_once($CFG->libdir . '/grade/grade_scale.php');
34 /**
35 * Class for loading/storing competencies from the DB.
37 * @copyright 2015 Damyon Wiese
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40 class competency extends persistent {
42 const TABLE = 'tool_lp_competency';
44 /** Outcome none. */
45 const OUTCOME_NONE = 0;
46 /** Outcome evidence. */
47 const OUTCOME_EVIDENCE = 1;
48 /** Outcome complete. */
49 const OUTCOME_COMPLETE = 2;
50 /** Outcome recommend. */
51 const OUTCOME_RECOMMEND = 3;
53 /** @var competency Object before update. */
54 protected $beforeupdate = null;
56 /**
57 * Return the definition of the properties of this model.
59 * @return array
61 protected static function define_properties() {
62 return array(
63 'shortname' => array(
64 'type' => PARAM_TEXT
66 'idnumber' => array(
67 'type' => PARAM_TEXT
69 'description' => array(
70 'default' => '',
71 'type' => PARAM_RAW
73 'descriptionformat' => array(
74 'choices' => array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN),
75 'type' => PARAM_INT,
76 'default' => FORMAT_HTML
78 'sortorder' => array(
79 'default' => null,
80 'type' => PARAM_INT
82 'parentid' => array(
83 'default' => 0,
84 'type' => PARAM_INT
86 'path' => array(
87 'default' => '/0/',
88 'type' => PARAM_RAW
90 'ruleoutcome' => array(
91 'choices' => array(self::OUTCOME_NONE, self::OUTCOME_EVIDENCE, self::OUTCOME_COMPLETE, self::OUTCOME_RECOMMEND),
92 'default' => self::OUTCOME_NONE,
93 'type' => PARAM_INT
95 'ruletype' => array(
96 'type' => PARAM_RAW,
97 'default' => null,
98 'null' => NULL_ALLOWED
100 'ruleconfig' => array(
101 'default' => null,
102 'type' => PARAM_RAW,
103 'null' => NULL_ALLOWED
105 'scaleid' => array(
106 'default' => null,
107 'type' => PARAM_INT,
108 'null' => NULL_ALLOWED
110 'scaleconfiguration' => array(
111 'default' => null,
112 'type' => PARAM_RAW,
113 'null' => NULL_ALLOWED
115 'competencyframeworkid' => array(
116 'default' => 0,
117 'type' => PARAM_INT
123 * Hook to execute before validate.
125 * @return void
127 protected function before_validate() {
128 $this->beforeupdate = null;
129 $this->newparent = null;
131 // During update.
132 if ($this->get_id()) {
133 $this->beforeupdate = new competency($this->get_id());
135 // The parent ID has changed.
136 if ($this->beforeupdate->get_parentid() != $this->get_parentid()) {
137 $this->newparent = $this->get_parent();
139 // Update path and sortorder.
140 $this->set_new_path($this->newparent);
141 $this->set_new_sortorder();
144 // During create.
145 } else {
147 $this->set_new_path();
148 // Always generate new sortorder when we create new competency.
149 $this->set_new_sortorder();
155 * Hook to execute after an update.
157 * @param bool $result Whether or not the update was successful.
158 * @return void
160 protected function after_update($result) {
161 global $DB;
163 if (!$result) {
164 $this->beforeupdate = null;
165 return;
168 // The parent ID has changed, we need to fix all the paths of the children.
169 if ($this->beforeupdate->get_parentid() != $this->get_parentid()) {
170 $beforepath = $this->beforeupdate->get_path() . $this->get_id() . '/';
172 $like = $DB->sql_like('path', '?');
173 $likesearch = $DB->sql_like_escape($beforepath) . '%';
175 $table = '{' . self::TABLE . '}';
176 $sql = "UPDATE $table SET path = REPLACE(path, ?, ?) WHERE " . $like;
177 $DB->execute($sql, array(
178 $beforepath,
179 $this->get_path() . $this->get_id() . '/',
180 $likesearch
183 // Resolving sortorder holes left after changing parent.
184 $table = '{' . self::TABLE . '}';
185 $sql = "UPDATE $table SET sortorder = sortorder -1 "
186 . " WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?";
187 $DB->execute($sql, array($this->get_competencyframeworkid(),
188 $this->beforeupdate->get_parentid(),
189 $this->beforeupdate->get_sortorder()
193 $this->beforeupdate = null;
198 * Hook to execute after a delete.
200 * @param bool $result Whether or not the delete was successful.
201 * @return void
203 protected function after_delete($result) {
204 global $DB;
205 if (!$result) {
206 return;
209 // Resolving sortorder holes left after delete.
210 $table = '{' . self::TABLE . '}';
211 $sql = "UPDATE $table SET sortorder = sortorder -1 WHERE competencyframeworkid = ? AND parentid = ? AND sortorder > ?";
212 $DB->execute($sql, array($this->get_competencyframeworkid(), $this->get_parentid(), $this->get_sortorder()));
216 * Extracts the default grade from the scale configuration.
218 * Returns an array where the first element is the grade, and the second
219 * is a boolean representing whether or not this grade is considered 'proficient'.
221 * @return array(int grade, bool proficient)
223 public function get_default_grade() {
224 $scaleid = $this->get_scaleid();
225 $scaleconfig = $this->get_scaleconfiguration();
226 if ($scaleid === null) {
227 $scaleconfig = $this->get_framework()->get_scaleconfiguration();
229 return competency_framework::get_default_grade_from_scale_configuration($scaleconfig);
233 * Get the competency framework.
235 * @return competency_framework
237 public function get_framework() {
238 return new competency_framework($this->get_competencyframeworkid());
242 * Get the competency level.
244 * @return int
246 public function get_level() {
247 $path = $this->get_path();
248 $path = trim($path, '/');
249 return substr_count($path, '/') + 1;
253 * Return the parent competency.
255 * @return null|competency
257 public function get_parent() {
258 $parentid = $this->get_parentid();
259 if (!$parentid) {
260 return null;
262 return new competency($parentid);
266 * Extracts the proficiency of a grade from the scale configuration.
268 * @param int $grade The grade (scale item ID).
269 * @return array(int grade, bool proficient)
271 public function get_proficiency_of_grade($grade) {
272 $scaleid = $this->get_scaleid();
273 $scaleconfig = $this->get_scaleconfiguration();
274 if ($scaleid === null) {
275 $scaleconfig = $this->get_framework()->get_scaleconfiguration();
277 return competency_framework::get_proficiency_of_grade_from_scale_configuration($scaleconfig, $grade);
281 * Return the related competencies.
283 * @return competency[]
285 public function get_related_competencies() {
286 return related_competency::get_related_competencies($this->get_id());
290 * Get the rule object.
292 * @return null|competency_rule
294 public function get_rule_object() {
295 $rule = $this->get_ruletype();
297 if (!$rule || !is_subclass_of($rule, 'tool_lp\\competency_rule')) {
298 // Double check that the rule is extending the right class to avoid bad surprises.
299 return null;
302 return new $rule($this);
306 * Return the scale.
308 * @return \grade_scale
310 public function get_scale() {
311 $scaleid = $this->get_scaleid();
312 if ($scaleid === null) {
313 return $this->get_framework()->get_scale();
315 $scale = \grade_scale::fetch(array('id' => $scaleid));
316 $scale->load_items();
317 return $scale;
321 * Returns true when the competency has user competencies.
323 * This is useful to determine if the competency, or part of it, should be locked down.
325 * @return boolean
327 public function has_user_competencies() {
328 return user_competency::has_records_for_competency($this->get_id()) ||
329 user_competency_plan::has_records_for_competency($this->get_id());
333 * Check if the competency is the parent of passed competencies.
335 * @param array $ids IDs of supposedly direct children.
336 * @return boolean
338 public function is_parent_of(array $ids) {
339 global $DB;
341 list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
342 $params['parentid'] = $this->get_id();
344 return $DB->count_records_select(self::TABLE, "id $insql AND parentid = :parentid", $params) == count($ids);
348 * Reset the rule.
350 * @return void
352 public function reset_rule() {
353 $this->set_ruleoutcome(static::OUTCOME_NONE);
354 $this->set_ruletype(null);
355 $this->set_ruleconfig(null);
359 * Helper method to set the path.
361 * @param competency $parent The parent competency object.
362 * @return void
364 protected function set_new_path(competency $parent = null) {
365 $path = '/0/';
366 if ($this->get_parentid()) {
367 $parent = $parent !== null ? $parent : $this->get_parent();
368 $path = $parent->get_path() . $this->get_parentid() . '/';
370 $this->set('path', $path);
374 * Helper method to set the sortorder.
376 * @return void
378 protected function set_new_sortorder() {
379 $search = array('parentid' => $this->get_parentid(), 'competencyframeworkid' => $this->get_competencyframeworkid());
380 $this->set('sortorder', $this->count_records($search));
384 * This does a specialised search that finds all nodes in the tree with matching text on any text like field,
385 * and returns this node and all its parents in a displayable sort order.
387 * @param string $searchtext The text to search for.
388 * @param int $competencyframeworkid The competency framework to limit the search.
389 * @return persistent[]
391 public static function search($searchtext, $competencyframeworkid) {
392 global $DB;
394 $like1 = $DB->sql_like('shortname', ':like1', false);
395 $like2 = $DB->sql_like('idnumber', ':like2', false);
396 $like3 = $DB->sql_like('description', ':like3', false);
398 $params = array(
399 'like1' => '%' . $DB->sql_like_escape($searchtext) . '%',
400 'like2' => '%' . $DB->sql_like_escape($searchtext) . '%',
401 'like3' => '%' . $DB->sql_like_escape($searchtext) . '%',
402 'frameworkid' => $competencyframeworkid
405 $sql = 'competencyframeworkid = :frameworkid AND ((' . $like1 . ') OR (' . $like2 . ') OR (' . $like3 . '))';
406 $records = $DB->get_records_select(self::TABLE, $sql, $params, 'path, sortorder ASC', '*');
408 // Now get all the parents.
409 $parents = array();
410 foreach ($records as $record) {
411 $split = explode('/', trim($record->path, '/'));
412 foreach ($split as $parent) {
413 $parents[intval($parent)] = true;
416 $parents = array_keys($parents);
418 // Skip ones we already fetched.
419 foreach ($parents as $idx => $parent) {
420 if ($parent == 0 || isset($records[$parent])) {
421 unset($parents[$idx]);
425 if (count($parents)) {
426 list($parentsql, $parentparams) = $DB->get_in_or_equal($parents, SQL_PARAMS_NAMED);
428 $parentrecords = $DB->get_records_select(self::TABLE, 'id ' . $parentsql,
429 $parentparams, 'path, sortorder ASC', '*');
431 foreach ($parentrecords as $id => $record) {
432 $records[$id] = $record;
436 $instances = array();
437 // Convert to instances of this class.
438 foreach ($records as $record) {
439 $newrecord = new static(0, $record);
440 $instances[$newrecord->get_id()] = $newrecord;
442 return $instances;
446 * Validate the competency framework ID.
448 * @param int $value The framework ID.
449 * @return true|lang_string
451 protected function validate_competencyframeworkid($value) {
453 // During update.
454 if ($this->get_id()) {
456 // Ensure that we are not trying to move the competency across frameworks.
457 if ($this->beforeupdate->get_competencyframeworkid() != $value) {
458 return new lang_string('invaliddata', 'error');
461 // During create.
462 } else {
464 // Check that the framework exists.
465 if (!competency_framework::record_exists($value)) {
466 return new lang_string('invaliddata', 'error');
470 return true;
474 * Validate the ID number.
476 * @param string $value The ID number.
477 * @return true|lang_string
479 protected function validate_idnumber($value) {
480 global $DB;
481 $sql = 'idnumber = :idnumber AND competencyframeworkid = :competencyframeworkid AND id <> :id';
482 $params = array(
483 'id' => $this->get_id(),
484 'idnumber' => $value,
485 'competencyframeworkid' => $this->get_competencyframeworkid()
487 if ($DB->record_exists_select(self::TABLE, $sql, $params)) {
488 return new lang_string('idnumbertaken', 'error');
490 return true;
494 * Validate the path.
496 * @param string $value The path.
497 * @return true|lang_string
499 protected function validate_path($value) {
501 // The last item should be the parent ID.
502 $id = $this->get_parentid();
503 if (substr($value, -(strlen($id) + 2)) != '/' . $id . '/') {
504 return new lang_string('invaliddata', 'error');
506 // The format of the path should be as follows.
507 } else if (!preg_match('@/([0-9]+/)+@', $value)) {
508 return new lang_string('invaliddata', 'error');
510 // Validate the depth of the path.
511 } else if ((substr_count($value, '/') - 1) > competency_framework::get_taxonomies_max_level()) {
512 return new lang_string('invaliddata', 'error');
515 return true;
519 * Validate the parent ID.
521 * @param string $value The ID.
522 * @return true|lang_string
524 protected function validate_parentid($value) {
526 // Check that the parent exists. But only if we don't have it already, and we actually have a parent.
527 if (!empty($value) && !$this->newparent && !self::record_exists($value)) {
528 return new lang_string('invaliddata', 'error');
531 // During update.
532 if ($this->get_id()) {
534 // If there is a new parent.
535 if ($this->beforeupdate->get_parentid() != $value && $this->newparent) {
537 // Check that the new parent belongs to the same framework.
538 if ($this->newparent->get_competencyframeworkid() != $this->get_competencyframeworkid()) {
539 return new lang_string('invaliddata', 'error');
544 return true;
548 * Validate the rule.
550 * @param string $value The ID.
551 * @return true|lang_string
553 protected function validate_ruletype($value) {
554 if ($value === null) {
555 return true;
558 if (!class_exists($value) || !is_subclass_of($value, '\tool_lp\competency_rule')) {
559 return new lang_string('invaliddata', 'error');
562 return true;
566 * Validate the rule config.
568 * @param string $value The ID.
569 * @return true|lang_string
571 protected function validate_ruleconfig($value) {
572 $rule = $this->get_rule_object();
574 // We don't have a rule.
575 if (empty($rule)) {
576 if ($value === null) {
577 // No config, perfect.
578 return true;
580 // Config but no rules, whoops!
581 return new lang_string('invaliddata', 'error');
584 $valid = $rule->validate_config($value);
585 if ($valid !== true) {
586 // Whoops!
587 return new lang_string('invaliddata', 'error');
590 return true;
594 * Validate the scale ID.
596 * Note that the value for a scale can never be 0, null has to be used when
597 * the framework's scale has to be used.
599 * @param int $value
600 * @return true|lang_string
602 protected function validate_scaleid($value) {
603 global $DB;
605 if ($value === null) {
606 return true;
609 // Always validate that the scale exists.
610 if (!$DB->record_exists_select('scale', 'id = :id', array('id' => $value))) {
611 return new lang_string('invalidscaleid', 'error');
614 // During update.
615 if ($this->get_id()) {
617 // Validate that we can only change the scale when it is not used yet.
618 if ($this->beforeupdate->get_scaleid() != $value) {
619 if ($this->has_user_competencies()) {
620 return new lang_string('errorscalealreadyused', 'tool_lp');
626 return true;
630 * Validate the scale configuration.
632 * This logic is adapted from {@link \tool_lp\competency_framework::validate_scaleconfiguration()}.
634 * @param string $value The scale configuration.
635 * @return bool|lang_string
637 protected function validate_scaleconfiguration($value) {
638 $scaleid = $this->get('scaleid');
639 if ($scaleid === null && $value === null) {
640 return true;
643 $scaledefaultselected = false;
644 $proficientselected = false;
645 $scaleconfigurations = json_decode($value);
647 if (is_array($scaleconfigurations)) {
649 // The first element of the array contains the scale ID.
650 $scaleinfo = array_shift($scaleconfigurations);
651 if (empty($scaleinfo) || !isset($scaleinfo->scaleid) || $scaleinfo->scaleid != $scaleid) {
652 // This should never happen.
653 return new lang_string('errorscaleconfiguration', 'tool_lp');
656 // Walk through the array to find proficient and default values.
657 foreach ($scaleconfigurations as $scaleconfiguration) {
658 if (isset($scaleconfiguration->scaledefault) && $scaleconfiguration->scaledefault) {
659 $scaledefaultselected = true;
661 if (isset($scaleconfiguration->proficient) && $scaleconfiguration->proficient) {
662 $proficientselected = true;
667 if (!$scaledefaultselected || !$proficientselected) {
668 return new lang_string('errorscaleconfiguration', 'tool_lp');
671 return true;
675 * Return whether or not the competency IDs share the same framework.
677 * @param array $ids Competency IDs
678 * @return bool
680 public static function share_same_framework(array $ids) {
681 global $DB;
682 list($insql, $params) = $DB->get_in_or_equal($ids);
683 return $DB->count_records_select(self::TABLE, "id $insql", $params, "COUNT(DISTINCT(competencyframeworkid))") == 1;
687 * Get the available rules.
689 * @return array Keys are the class names, values is an object containing name and amd.
691 public static function get_available_rules() {
692 // Fully qualified class names without leading slashes because get_class() does not add them either.
693 $rules = array(
694 'tool_lp\\competency_rule_all' => (object) array(),
695 'tool_lp\\competency_rule_points' => (object) array(),
697 foreach ($rules as $class => $rule) {
698 $rule->name = $class::get_name();
699 $rule->amd = $class::get_amd_module();
701 return $rules;
705 * Build a framework tree with competency nodes.
707 * @param int $frameworkid the framework id
708 * @return node[] tree of framework competency nodes
710 public static function get_framework_tree($frameworkid) {
711 $competencies = self::search('', $frameworkid);
712 return self::build_tree($competencies, 0);
716 * Get the context from the framework.
718 * @return context
720 public function get_context() {
721 return $this->get_framework()->get_context();
725 * Recursively build up the tree of nodes.
727 * @param array $all - List of all competency classes.
728 * @param int $parentid - The current parent ID. Pass 0 to build the tree from the top.
729 * @return node[] $tree tree of nodes
731 protected static function build_tree($all, $parentid) {
732 $tree = array();
733 foreach ($all as $one) {
734 if ($one->get_parentid() == $parentid) {
735 $node = new stdClass();
736 $node->competency = $one;
737 $node->children = self::build_tree($all, $one->get_id());
738 $tree[] = $node;
741 return $tree;
745 * Check if we can delete competencies safely.
747 * This moethod does not check any capablities.
748 * Check if competency is used in a plan and user competency.
749 * Check if competency is used in a template.
750 * Check if competency is linked to a course.
752 * @param array $ids Array of competencies ids.
753 * @return bool True if we can delete the competencies.
755 public static function can_all_be_deleted($ids) {
756 if (empty($ids)) {
757 return true;
759 // Check if competency is used in template.
760 if (template_competency::has_records_for_competencies($ids)) {
761 return false;
763 // Check if competency is used in plan.
764 if (plan_competency::has_records_for_competencies($ids)) {
765 return false;
767 // Check if competency is used in course.
768 if (course_competency::has_records_for_competencies($ids)) {
769 return false;
771 // Check if competency is used in user_competency.
772 if (user_competency::has_records_for_competencies($ids)) {
773 return false;
775 // Check if competency is used in user_competency_plan.
776 if (user_competency_plan::has_records_for_competencies($ids)) {
777 return false;
779 return true;
783 * Delete the competencies.
785 * This method is reserved to core usage.
786 * This method does not trigger the after_delete event.
787 * This method does not delete related objects such as related competencies and evidences.
789 * @param array $ids The competencies ids.
790 * @return bool True if the competencies were deleted successfully.
792 public static function delete_multiple($ids) {
793 global $DB;
794 list($insql, $params) = $DB->get_in_or_equal($ids, SQL_PARAMS_NAMED);
795 return $DB->delete_records_select(self::TABLE, "id $insql", $params);
799 * Get descendant ids.
801 * @param competency $competency The competency.
802 * @return array Array of competencies ids.
804 public static function get_descendants_ids($competency) {
805 global $DB;
807 $path = $DB->sql_like_escape($competency->get_path() . $competency->get_id() . '/') . '%';
808 $like = $DB->sql_like('path', ':likepath');
809 return $DB->get_fieldset_select(self::TABLE, 'id', $like, array('likepath' => $path));
813 * Get competencyids by frameworkid.
815 * @param int $frameworkid The competency framework ID.
816 * @return array Array of competency ids.
818 public static function get_ids_by_frameworkid($frameworkid) {
819 global $DB;
821 return $DB->get_fieldset_select(self::TABLE, 'id', 'competencyframeworkid = :frmid', array('frmid' => $frameworkid));
825 * Delete competencies by framework ID.
827 * This method is reserved to core usage.
828 * This method does not trigger the after_delete event.
829 * This method does not delete related objects such as related competencies and evidences.
831 * @param int $id the framework ID
832 * @return bool Return true if delete was successful.
834 public static function delete_by_frameworkid($id) {
835 global $DB;
836 return $DB->delete_records(self::TABLE, array('competencyframeworkid' => $id));
840 * Get competency ancestors.
842 * @return competency[] Return array of ancestors.
844 public function get_ancestors() {
845 global $DB;
846 $ancestors = array();
847 $ancestorsids = explode('/', trim($this->get_path(), '/'));
848 // Drop the root item from the array /0/.
849 array_shift($ancestorsids);
850 if (!empty($ancestorsids)) {
851 list($insql, $params) = $DB->get_in_or_equal($ancestorsids, SQL_PARAMS_NAMED);
852 $ancestors = self::get_records_select("id $insql", $params);
854 return $ancestors;