MDL-66498 analytics: SQL IN in chunks
[moodle.git] / analytics / classes / manager.php
CommitLineData
369389c9
DM
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.
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/**
b94dbb55 18 * Analytics basic actions manager.
369389c9
DM
19 *
20 * @package core_analytics
21 * @copyright 2017 David Monllao {@link http://www.davidmonllao.com}
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25namespace core_analytics;
26
27defined('MOODLE_INTERNAL') || die();
28
29/**
b94dbb55 30 * Analytics basic actions manager.
369389c9
DM
31 *
32 * @package core_analytics
33 * @copyright 2017 David Monllao {@link http://www.davidmonllao.com}
34 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
35 */
36class manager {
37
ed12ba6b
DM
38 /**
39 * Default mlbackend
40 */
41 const DEFAULT_MLBACKEND = '\mlbackend_php\processor';
42
f0584045
DM
43 /**
44 * Name of the file where components declare their models.
45 */
46 const ANALYTICS_FILENAME = 'db/analytics.php';
47
369389c9
DM
48 /**
49 * @var \core_analytics\predictor[]
50 */
51 protected static $predictionprocessors = null;
52
e4453adc
DM
53 /**
54 * @var \core_analytics\local\target\base[]
55 */
56 protected static $alltargets = null;
57
369389c9
DM
58 /**
59 * @var \core_analytics\local\indicator\base[]
60 */
61 protected static $allindicators = null;
62
63 /**
64 * @var \core_analytics\local\time_splitting\base[]
65 */
66 protected static $alltimesplittings = null;
67
1611308b
DM
68 /**
69 * Checks that the user can manage models
70 *
71 * @throws \required_capability_exception
72 * @return void
73 */
74 public static function check_can_manage_models() {
75 require_capability('moodle/analytics:managemodels', \context_system::instance());
76 }
77
78 /**
79 * Checks that the user can list that context insights
80 *
81 * @throws \required_capability_exception
82 * @param \context $context
50935afb 83 * @param bool $return The method returns a bool if true.
1611308b
DM
84 * @return void
85 */
50935afb
DM
86 public static function check_can_list_insights(\context $context, bool $return = false) {
87 global $USER;
88
89 if ($context->contextlevel === CONTEXT_USER && $context->instanceid == $USER->id) {
90 $capability = 'moodle/analytics:listowninsights';
91 } else {
92 $capability = 'moodle/analytics:listinsights';
93 }
94
95 if ($return) {
96 return has_capability($capability, $context);
97 } else {
98 require_capability($capability, $context);
99 }
1611308b
DM
100 }
101
584ffa4f
DM
102 /**
103 * Returns all system models that match the provided filters.
104 *
105 * @param bool $enabled
106 * @param bool $trained
08015e18 107 * @param \context|false $predictioncontext
584ffa4f
DM
108 * @return \core_analytics\model[]
109 */
369389c9
DM
110 public static function get_all_models($enabled = false, $trained = false, $predictioncontext = false) {
111 global $DB;
112
1611308b
DM
113 $params = array();
114
88777c57 115 $sql = "SELECT am.* FROM {analytics_models} am";
1611308b 116
88777c57 117 if ($enabled || $trained || $predictioncontext) {
1611308b
DM
118 $conditions = [];
119 if ($enabled) {
120 $conditions[] = 'am.enabled = :enabled';
121 $params['enabled'] = 1;
122 }
123 if ($trained) {
124 $conditions[] = 'am.trained = :trained';
125 $params['trained'] = 1;
126 }
88777c57 127 if ($predictioncontext) {
d887b0c7
DM
128 $conditions[] = "EXISTS (SELECT 'x'
129 FROM {analytics_predictions} ap
130 WHERE ap.modelid = am.id AND ap.contextid = :contextid)";
88777c57
DM
131 $params['contextid'] = $predictioncontext->id;
132 }
e10b29ed 133 $sql .= ' WHERE ' . implode(' AND ', $conditions);
369389c9 134 }
e10b29ed
DM
135 $sql .= ' ORDER BY am.enabled DESC, am.timemodified DESC';
136
1611308b 137 $modelobjs = $DB->get_records_sql($sql, $params);
369389c9
DM
138
139 $models = array();
140 foreach ($modelobjs as $modelobj) {
3a396286
DM
141 $model = new \core_analytics\model($modelobj);
142 if ($model->is_available()) {
143 $models[$modelobj->id] = $model;
144 }
369389c9 145 }
35b10d09
DM
146
147 // Sort the models by the model name using the current session language.
148 \core_collator::asort_objects_by_method($models, 'get_name');
149
369389c9
DM
150 return $models;
151 }
152
153 /**
ed12ba6b 154 * Returns the provided predictions processor class.
369389c9 155 *
ed12ba6b 156 * @param false|string $predictionclass Returns the system default processor if false
369389c9
DM
157 * @param bool $checkisready
158 * @return \core_analytics\predictor
159 */
160 public static function get_predictions_processor($predictionclass = false, $checkisready = true) {
161
162 // We want 0 or 1 so we can use it as an array key for caching.
163 $checkisready = intval($checkisready);
164
ed12ba6b 165 if (!$predictionclass) {
369389c9
DM
166 $predictionclass = get_config('analytics', 'predictionsprocessor');
167 }
168
169 if (empty($predictionclass)) {
170 // Use the default one if nothing set.
ed12ba6b 171 $predictionclass = self::default_mlbackend();
369389c9
DM
172 }
173
174 if (!class_exists($predictionclass)) {
175 throw new \coding_exception('Invalid predictions processor ' . $predictionclass . '.');
176 }
177
178 $interfaces = class_implements($predictionclass);
179 if (empty($interfaces['core_analytics\predictor'])) {
180 throw new \coding_exception($predictionclass . ' should implement \core_analytics\predictor.');
181 }
182
183 // Return it from the cached list.
184 if (!isset(self::$predictionprocessors[$checkisready][$predictionclass])) {
185
186 $instance = new $predictionclass();
187 if ($checkisready) {
188 $isready = $instance->is_ready();
189 if ($isready !== true) {
190 throw new \moodle_exception('errorprocessornotready', 'analytics', '', $isready);
191 }
192 }
193 self::$predictionprocessors[$checkisready][$predictionclass] = $instance;
194 }
195
196 return self::$predictionprocessors[$checkisready][$predictionclass];
197 }
198
1611308b
DM
199 /**
200 * Return all system predictions processors.
201 *
08015e18 202 * @return \core_analytics\predictor[]
1611308b 203 */
369389c9
DM
204 public static function get_all_prediction_processors() {
205
206 $mlbackends = \core_component::get_plugin_list('mlbackend');
207
208 $predictionprocessors = array();
209 foreach ($mlbackends as $mlbackend => $unused) {
206d7aa9 210 $classfullpath = '\mlbackend_' . $mlbackend . '\processor';
369389c9
DM
211 $predictionprocessors[$classfullpath] = self::get_predictions_processor($classfullpath, false);
212 }
213 return $predictionprocessors;
214 }
215
ed12ba6b
DM
216 /**
217 * Returns the name of the provided predictions processor.
218 *
219 * @param \core_analytics\predictor $predictionsprocessor
220 * @return string
221 */
222 public static function get_predictions_processor_name(\core_analytics\predictor $predictionsprocessor) {
223 $component = substr(get_class($predictionsprocessor), 0, strpos(get_class($predictionsprocessor), '\\', 1));
224 return get_string('pluginname', $component);
225 }
226
227 /**
228 * Whether the provided plugin is used by any model.
229 *
230 * @param string $plugin
231 * @return bool
232 */
233 public static function is_mlbackend_used($plugin) {
234 $models = self::get_all_models();
235 foreach ($models as $model) {
236 $processor = $model->get_predictions_processor();
237 $noprefixnamespace = ltrim(get_class($processor), '\\');
238 $processorplugin = substr($noprefixnamespace, 0, strpos($noprefixnamespace, '\\'));
239 if ($processorplugin == $plugin) {
240 return true;
241 }
242 }
243
244 // Default predictions processor.
245 $defaultprocessorclass = get_config('analytics', 'predictionsprocessor');
246 $pluginclass = '\\' . $plugin . '\\processor';
247 if ($pluginclass === $defaultprocessorclass) {
248 return true;
249 }
250
251 return false;
252 }
253
369389c9
DM
254 /**
255 * Get all available time splitting methods.
256 *
1cc2b4ba 257 * @return \core_analytics\local\time_splitting\base[]
369389c9
DM
258 */
259 public static function get_all_time_splittings() {
260 if (self::$alltimesplittings !== null) {
261 return self::$alltimesplittings;
262 }
263
264 $classes = self::get_analytics_classes('time_splitting');
265
266 self::$alltimesplittings = [];
267 foreach ($classes as $fullclassname => $classpath) {
268 $instance = self::get_time_splitting($fullclassname);
269 // We need to check that it is a valid time splitting method, it may be an abstract class.
270 if ($instance) {
271 self::$alltimesplittings[$instance->get_id()] = $instance;
272 }
273 }
274
275 return self::$alltimesplittings;
276 }
277
278 /**
279 * Returns the enabled time splitting methods.
280 *
3576b66b
DM
281 * @deprecated since Moodle 3.7
282 * @todo MDL-65086 This will be deleted in Moodle 4.1
283 * @see \core_analytics\manager::get_time_splitting_methods_for_evaluation
369389c9
DM
284 * @return \core_analytics\local\time_splitting\base[]
285 */
286 public static function get_enabled_time_splitting_methods() {
3576b66b
DM
287 debugging('This function has been deprecated. You can use self::get_time_splitting_methods_for_evaluation if ' .
288 'you want to get the default time splitting methods for evaluation, or you can use self::get_all_time_splittings if ' .
289 'you want to get all the time splitting methods available on this site.');
290 return self::get_time_splitting_methods_for_evaluation();
291 }
292
293 /**
5f1f0ee6 294 * Returns the time-splitting methods for model evaluation.
3576b66b 295 *
5f1f0ee6 296 * @param bool $all Return all the time-splitting methods that can potentially be used for evaluation or the default ones.
3576b66b
DM
297 * @return \core_analytics\local\time_splitting\base[]
298 */
5f1f0ee6 299 public static function get_time_splitting_methods_for_evaluation(bool $all = false) {
369389c9 300
5f1f0ee6
DM
301 if ($all === false) {
302 if ($enabledtimesplittings = get_config('analytics', 'defaulttimesplittingsevaluation')) {
303 $enabledtimesplittings = array_flip(explode(',', $enabledtimesplittings));
304 }
369389c9
DM
305 }
306
307 $timesplittings = self::get_all_time_splittings();
308 foreach ($timesplittings as $key => $timesplitting) {
309
5f1f0ee6 310 if (!$timesplitting->valid_for_evaluation()) {
369389c9
DM
311 unset($timesplittings[$key]);
312 }
5f1f0ee6
DM
313
314 if ($all === false) {
315 // We remove the ones that are not enabled. This also respects the default value (all methods enabled).
316 if (!empty($enabledtimesplittings) && !isset($enabledtimesplittings[$key])) {
317 unset($timesplittings[$key]);
318 }
319 }
369389c9
DM
320 }
321 return $timesplittings;
322 }
323
324 /**
325 * Returns a time splitting method by its classname.
326 *
327 * @param string $fullclassname
328 * @return \core_analytics\local\time_splitting\base|false False if it is not valid.
329 */
330 public static function get_time_splitting($fullclassname) {
331 if (!self::is_valid($fullclassname, '\core_analytics\local\time_splitting\base')) {
332 return false;
333 }
334 return new $fullclassname();
335 }
336
e4453adc
DM
337 /**
338 * Return all targets in the system.
339 *
340 * @return \core_analytics\local\target\base[]
341 */
342 public static function get_all_targets() : array {
343 if (self::$alltargets !== null) {
344 return self::$alltargets;
345 }
346
347 $classes = self::get_analytics_classes('target');
348
349 self::$alltargets = [];
350 foreach ($classes as $fullclassname => $classpath) {
351 $instance = self::get_target($fullclassname);
352 if ($instance) {
353 self::$alltargets[$instance->get_id()] = $instance;
354 }
355 }
356
357 return self::$alltargets;
358 }
369389c9
DM
359 /**
360 * Return all system indicators.
361 *
362 * @return \core_analytics\local\indicator\base[]
363 */
364 public static function get_all_indicators() {
365 if (self::$allindicators !== null) {
366 return self::$allindicators;
367 }
368
369 $classes = self::get_analytics_classes('indicator');
370
371 self::$allindicators = [];
372 foreach ($classes as $fullclassname => $classpath) {
373 $instance = self::get_indicator($fullclassname);
374 if ($instance) {
b0c24929 375 self::$allindicators[$instance->get_id()] = $instance;
369389c9
DM
376 }
377 }
378
379 return self::$allindicators;
380 }
381
1611308b
DM
382 /**
383 * Returns the specified target
384 *
385 * @param mixed $fullclassname
386 * @return \core_analytics\local\target\base|false False if it is not valid
387 */
369389c9
DM
388 public static function get_target($fullclassname) {
389 if (!self::is_valid($fullclassname, 'core_analytics\local\target\base')) {
390 return false;
391 }
392 return new $fullclassname();
393 }
394
395 /**
396 * Returns an instance of the provided indicator.
397 *
398 * @param string $fullclassname
399 * @return \core_analytics\local\indicator\base|false False if it is not valid.
400 */
401 public static function get_indicator($fullclassname) {
402 if (!self::is_valid($fullclassname, 'core_analytics\local\indicator\base')) {
403 return false;
404 }
405 return new $fullclassname();
406 }
407
408 /**
409 * Returns whether a time splitting method is valid or not.
410 *
411 * @param string $fullclassname
1611308b 412 * @param string $baseclass
369389c9
DM
413 * @return bool
414 */
415 public static function is_valid($fullclassname, $baseclass) {
416 if (is_subclass_of($fullclassname, $baseclass)) {
417 if ((new \ReflectionClass($fullclassname))->isInstantiable()) {
418 return true;
419 }
420 }
421 return false;
422 }
423
f67f35f3 424 /**
1611308b 425 * Returns the logstore used for analytics.
f67f35f3 426 *
2db6e981 427 * @return \core\log\sql_reader|false False if no log stores are enabled.
f67f35f3
DM
428 */
429 public static function get_analytics_logstore() {
430 $readers = get_log_manager()->get_readers('core\log\sql_reader');
431 $analyticsstore = get_config('analytics', 'logstore');
85e50ba4
DM
432
433 if (!empty($analyticsstore) && !empty($readers[$analyticsstore])) {
f67f35f3 434 $logstore = $readers[$analyticsstore];
85e50ba4
DM
435 } else if (empty($analyticsstore) && !empty($readers)) {
436 // The first one, it is the same default than in settings.
437 $logstore = reset($readers);
2db6e981 438 } else if (!empty($readers)) {
f67f35f3
DM
439 $logstore = reset($readers);
440 debugging('The selected log store for analytics is not available anymore. Using "' .
441 $logstore->get_name() . '"', DEBUG_DEVELOPER);
442 }
443
2db6e981
DM
444 if (empty($logstore)) {
445 debugging('No system log stores available to use for analytics', DEBUG_DEVELOPER);
446 return false;
447 }
448
f67f35f3
DM
449 if (!$logstore->is_logging()) {
450 debugging('The selected log store for analytics "' . $logstore->get_name() .
451 '" is not logging activity logs', DEBUG_DEVELOPER);
452 }
453
454 return $logstore;
455 }
456
0690a271
DM
457 /**
458 * Returns this analysable calculations during the provided period.
459 *
460 * @param \core_analytics\analysable $analysable
461 * @param int $starttime
462 * @param int $endtime
463 * @param string $samplesorigin The samples origin as sampleid is not unique across models.
464 * @return array
465 */
466 public static function get_indicator_calculations($analysable, $starttime, $endtime, $samplesorigin) {
467 global $DB;
468
469 $params = array('starttime' => $starttime, 'endtime' => $endtime, 'contextid' => $analysable->get_context()->id,
470 'sampleorigin' => $samplesorigin);
471 $calculations = $DB->get_recordset('analytics_indicator_calc', $params, '', 'indicator, sampleid, value');
472
473 $existingcalculations = array();
474 foreach ($calculations as $calculation) {
475 if (empty($existingcalculations[$calculation->indicator])) {
476 $existingcalculations[$calculation->indicator] = array();
477 }
478 $existingcalculations[$calculation->indicator][$calculation->sampleid] = $calculation->value;
479 }
a938e409 480 $calculations->close();
0690a271
DM
481 return $existingcalculations;
482 }
483
1611308b
DM
484 /**
485 * Returns the models with insights at the provided context.
486 *
487 * @param \context $context
488 * @return \core_analytics\model[]
489 */
490 public static function get_models_with_insights(\context $context) {
491
492 self::check_can_list_insights($context);
493
413f19bc 494 $models = self::get_all_models(true, true, $context);
1611308b
DM
495 foreach ($models as $key => $model) {
496 // Check that it not only have predictions but also generates insights from them.
497 if (!$model->uses_insights()) {
498 unset($models[$key]);
499 }
500 }
501 return $models;
502 }
503
504 /**
505 * Returns a prediction
506 *
507 * @param int $predictionid
508 * @param bool $requirelogin
509 * @return array array($model, $prediction, $context)
510 */
511 public static function get_prediction($predictionid, $requirelogin = false) {
512 global $DB;
513
514 if (!$predictionobj = $DB->get_record('analytics_predictions', array('id' => $predictionid))) {
4a210b06
DM
515 throw new \moodle_exception('errorpredictionnotfound', 'analytics');
516 }
517
518 $context = \context::instance_by_id($predictionobj->contextid, IGNORE_MISSING);
519 if (!$context) {
520 throw new \moodle_exception('errorpredictioncontextnotavailable', 'analytics');
1611308b
DM
521 }
522
523 if ($requirelogin) {
524 list($context, $course, $cm) = get_context_info_array($predictionobj->contextid);
525 require_login($course, false, $cm);
1611308b
DM
526 }
527
413f19bc 528 self::check_can_list_insights($context);
1611308b
DM
529
530 $model = new \core_analytics\model($predictionobj->modelid);
531 $sampledata = $model->prediction_sample_data($predictionobj);
532 $prediction = new \core_analytics\prediction($predictionobj, $sampledata);
533
534 return array($model, $prediction, $context);
535 }
536
e709e544 537 /**
3b7c7918 538 * Used to be used to add models included with the Moodle core.
e709e544 539 *
3b7c7918
DM
540 * @deprecated Deprecated since Moodle 3.7 (MDL-61667) - Use lib/db/analytics.php instead.
541 * @todo Remove this method in Moodle 4.1 (MDL-65186).
e709e544
DM
542 * @return void
543 */
544 public static function add_builtin_models() {
545
3b7c7918
DM
546 debugging('core_analytics\manager::add_builtin_models() has been deprecated. Core models are now automatically '.
547 'updated according to their declaration in the lib/db/analytics.php file.', DEBUG_DEVELOPER);
e709e544
DM
548 }
549
f9222c49
DM
550 /**
551 * Cleans up analytics db tables that do not directly depend on analysables that may have been deleted.
552 */
553 public static function cleanup() {
554 global $DB;
555
556 // Clean up stuff that depends on contexts that do not exist anymore.
557 $sql = "SELECT DISTINCT ap.contextid FROM {analytics_predictions} ap
558 LEFT JOIN {context} ctx ON ap.contextid = ctx.id
559 WHERE ctx.id IS NULL";
560 $apcontexts = $DB->get_records_sql($sql);
561
562 $sql = "SELECT DISTINCT aic.contextid FROM {analytics_indicator_calc} aic
563 LEFT JOIN {context} ctx ON aic.contextid = ctx.id
564 WHERE ctx.id IS NULL";
565 $indcalccontexts = $DB->get_records_sql($sql);
566
567 $contexts = $apcontexts + $indcalccontexts;
568 if ($contexts) {
569 list($sql, $params) = $DB->get_in_or_equal(array_keys($contexts));
e08c74f5 570 $DB->execute("DELETE FROM {analytics_prediction_actions} WHERE predictionid IN
f9222c49
DM
571 (SELECT ap.id FROM {analytics_predictions} ap WHERE ap.contextid $sql)", $params);
572
573 $DB->delete_records_select('analytics_predictions', "contextid $sql", $params);
574 $DB->delete_records_select('analytics_indicator_calc', "contextid $sql", $params);
575 }
576
577 // Clean up stuff that depends on analysable ids that do not exist anymore.
500111c5 578
f9222c49
DM
579 $models = self::get_all_models();
580 foreach ($models as $model) {
500111c5
DM
581
582 // We first dump into memory the list of analysables we have in the database (we could probably do this with 1 single
583 // query for the 3 tables, but it may be safer to do it separately).
584 $predictsamplesanalysableids = $DB->get_fieldset_select('analytics_predict_samples', 'DISTINCT analysableid',
585 'modelid = :modelid', ['modelid' => $model->get_id()]);
586 $predictsamplesanalysableids = array_flip($predictsamplesanalysableids);
587 $trainsamplesanalysableids = $DB->get_fieldset_select('analytics_train_samples', 'DISTINCT analysableid',
588 'modelid = :modelid', ['modelid' => $model->get_id()]);
589 $trainsamplesanalysableids = array_flip($trainsamplesanalysableids);
590 $usedanalysablesanalysableids = $DB->get_fieldset_select('analytics_used_analysables', 'DISTINCT analysableid',
591 'modelid = :modelid', ['modelid' => $model->get_id()]);
592 $usedanalysablesanalysableids = array_flip($usedanalysablesanalysableids);
593
f9222c49 594 $analyser = $model->get_analyser(array('notimesplitting' => true));
fccc728f
DM
595 $analysables = $analyser->get_analysables_iterator();
596
597 $analysableids = [];
598 foreach ($analysables as $analysable) {
599 if (!$analysable) {
600 continue;
601 }
500111c5
DM
602 unset($predictsamplesanalysableids[$analysable->get_id()]);
603 unset($trainsamplesanalysableids[$analysable->get_id()]);
604 unset($usedanalysablesanalysableids[$analysable->get_id()]);
f9222c49
DM
605 }
606
500111c5 607 $param = ['modelid' => $model->get_id()];
f9222c49 608
500111c5
DM
609 if ($predictsamplesanalysableids) {
610 $chunks = array_chunk(array_flip($predictsamplesanalysableids), 1000);
611 foreach ($chunks as $chunk) {
612 list($idssql, $idsparams) = $DB->get_in_or_equal($chunk, SQL_PARAMS_NAMED);
613 $DB->delete_records_select('analytics_predict_samples', "modelid = :modelid AND analysableid $idssql",
614 $param + $idsparams);
615 }
616 }
617 if ($trainsamplesanalysableids) {
618 $chunks = array_chunk(array_flip($trainsamplesanalysableids), 1000);
619 foreach ($chunks as $chunk) {
620 list($idssql, $idsparams) = $DB->get_in_or_equal($chunk, SQL_PARAMS_NAMED);
621 $DB->delete_records_select('analytics_train_samples', "modelid = :modelid AND analysableid $idssql",
622 $param + $idsparams);
623 }
624 }
625 if ($usedanalysablesanalysableids) {
626 $chunks = array_chunk(array_flip($usedanalysablesanalysableids), 1000);
627 foreach ($chunks as $chunk) {
628 list($idssql, $idsparams) = $DB->get_in_or_equal($chunk, SQL_PARAMS_NAMED);
629 $DB->delete_records_select('analytics_used_analysables', "modelid = :modelid AND analysableid $idssql",
630 $param + $idsparams);
631 }
632 }
f9222c49
DM
633 }
634 }
635
ed12ba6b
DM
636 /**
637 * Default system backend.
638 *
639 * @return string
640 */
641 public static function default_mlbackend() {
642 return self::DEFAULT_MLBACKEND;
643 }
644
369389c9
DM
645 /**
646 * Returns the provided element classes in the site.
647 *
648 * @param string $element
649 * @return string[] Array keys are the FQCN and the values the class path.
650 */
651 private static function get_analytics_classes($element) {
652
653 // Just in case...
1611308b 654 $element = clean_param($element, PARAM_ALPHANUMEXT);
369389c9 655
0d6a45d2 656 $classes = \core_component::get_component_classes_in_namespace(null, 'analytics\\' . $element);
1cc2b4ba 657
369389c9
DM
658 return $classes;
659 }
f0584045 660
606c3be0
DM
661 /**
662 * Check that all the models declared by the component are up to date.
663 *
664 * This is intended to be called during the installation / upgrade to automatically create missing models.
665 *
666 * @param string $componentname The name of the component to load models for.
667 * @return array \core_analytics\model[] List of actually created models.
668 */
669 public static function update_default_models_for_component(string $componentname): array {
670
671 $result = [];
672
673 foreach (static::load_default_models_for_component($componentname) as $definition) {
674 if (!\core_analytics\model::exists(static::get_target($definition['target']))) {
675 $result[] = static::create_declared_model($definition);
676 }
677 }
678
679 return $result;
680 }
681
f0584045
DM
682 /**
683 * Return the list of models declared by the given component.
684 *
685 * @param string $componentname The name of the component to load models for.
686 * @throws \coding_exception Exception thrown in case of invalid syntax.
687 * @return array The $models description array.
688 */
689 public static function load_default_models_for_component(string $componentname): array {
690
691 $dir = \core_component::get_component_directory($componentname);
692
693 if (!$dir) {
694 // This is either an invalid component, or a core subsystem without its own root directory.
695 return [];
696 }
697
698 $file = $dir . '/' . self::ANALYTICS_FILENAME;
699
700 if (!is_readable($file)) {
701 return [];
702 }
703
704 $models = null;
705 include($file);
706
707 if (!isset($models) || !is_array($models) || empty($models)) {
708 return [];
709 }
710
711 foreach ($models as &$model) {
712 if (!isset($model['enabled'])) {
713 $model['enabled'] = false;
714 } else {
715 $model['enabled'] = clean_param($model['enabled'], PARAM_BOOL);
716 }
717 }
718
719 static::validate_models_declaration($models);
720
721 return $models;
722 }
723
1297fa41
DM
724 /**
725 * Return the list of all the models declared anywhere in this Moodle installation.
726 *
727 * Models defined by the core and core subsystems come first, followed by those provided by plugins.
728 *
729 * @return array indexed by the frankenstyle component
730 */
731 public static function load_default_models_for_all_components(): array {
732
733 $tmp = [];
734
735 foreach (\core_component::get_component_list() as $type => $components) {
736 foreach (array_keys($components) as $component) {
737 if ($loaded = static::load_default_models_for_component($component)) {
738 $tmp[$type][$component] = $loaded;
739 }
740 }
741 }
742
743 $result = [];
744
745 if ($loaded = static::load_default_models_for_component('core')) {
746 $result['core'] = $loaded;
747 }
748
749 if (!empty($tmp['core'])) {
750 $result += $tmp['core'];
751 unset($tmp['core']);
752 }
753
754 foreach ($tmp as $components) {
755 $result += $components;
756 }
757
758 return $result;
759 }
760
f0584045
DM
761 /**
762 * Validate the declaration of prediction models according the syntax expected in the component's db folder.
763 *
764 * The expected structure looks like this:
765 *
766 * [
767 * [
768 * 'target' => '\fully\qualified\name\of\the\target\class',
769 * 'indicators' => [
770 * '\fully\qualified\name\of\the\first\indicator',
771 * '\fully\qualified\name\of\the\second\indicator',
772 * ],
773 * 'timesplitting' => '\optional\name\of\the\time_splitting\class',
774 * 'enabled' => true,
775 * ],
776 * ];
777 *
778 * @param array $models List of declared models.
779 * @throws \coding_exception Exception thrown in case of invalid syntax.
780 */
781 public static function validate_models_declaration(array $models) {
782
783 foreach ($models as $model) {
784 if (!isset($model['target'])) {
785 throw new \coding_exception('Missing target declaration');
786 }
787
788 if (!static::is_valid($model['target'], '\core_analytics\local\target\base')) {
789 throw new \coding_exception('Invalid target classname', $model['target']);
790 }
791
792 if (empty($model['indicators']) || !is_array($model['indicators'])) {
793 throw new \coding_exception('Missing indicators declaration');
794 }
795
796 foreach ($model['indicators'] as $indicator) {
797 if (!static::is_valid($indicator, '\core_analytics\local\indicator\base')) {
798 throw new \coding_exception('Invalid indicator classname', $indicator);
799 }
800 }
801
802 if (isset($model['timesplitting'])) {
803 if (substr($model['timesplitting'], 0, 1) !== '\\') {
804 throw new \coding_exception('Expecting fully qualified time splitting classname', $model['timesplitting']);
805 }
806 if (!static::is_valid($model['timesplitting'], '\core_analytics\local\time_splitting\base')) {
807 throw new \coding_exception('Invalid time splitting classname', $model['timesplitting']);
808 }
809 }
810
811 if (!empty($model['enabled']) && !isset($model['timesplitting'])) {
812 throw new \coding_exception('Cannot enable a model without time splitting method specified');
813 }
814 }
815 }
6187213f
DM
816
817 /**
818 * Create the defined model.
819 *
820 * @param array $definition See {@link self::validate_models_declaration()} for the syntax.
821 * @return \core_analytics\model
822 */
823 public static function create_declared_model(array $definition): \core_analytics\model {
824
7dba0c27 825 list($target, $indicators) = static::get_declared_target_and_indicators_instances($definition);
6187213f
DM
826
827 if (isset($definition['timesplitting'])) {
828 $timesplitting = $definition['timesplitting'];
829 } else {
830 $timesplitting = false;
831 }
832
833 $created = \core_analytics\model::create($target, $indicators, $timesplitting);
834
835 if (!empty($definition['enabled'])) {
836 $created->enable();
837 }
838
839 return $created;
840 }
01d620ee
DM
841
842 /**
843 * Returns a string uniquely representing the given model declaration.
844 *
845 * @param array $model Model declaration
846 * @return string complying with PARAM_ALPHANUM rules and starting with an 'id' prefix
847 */
848 public static function model_declaration_identifier(array $model) : string {
849 return 'id'.sha1(serialize($model));
850 }
7dba0c27
DM
851
852 /**
853 * Given a model definition, return actual target and indicators instances.
854 *
855 * @param array $definition See {@link self::validate_models_declaration()} for the syntax.
856 * @return array [0] => target instance, [1] => array of indicators instances
857 */
858 public static function get_declared_target_and_indicators_instances(array $definition): array {
859
860 $target = static::get_target($definition['target']);
861
862 $indicators = [];
863
864 foreach ($definition['indicators'] as $indicatorname) {
865 $indicator = static::get_indicator($indicatorname);
866 $indicators[$indicator->get_id()] = $indicator;
867 }
868
869 return [$target, $indicators];
870 }
369389c9 871}