MDL-65175 analytics: Rm references to unexisting time-splittings
[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
DM
145 }
146 return $models;
147 }
148
149 /**
ed12ba6b 150 * Returns the provided predictions processor class.
369389c9 151 *
ed12ba6b 152 * @param false|string $predictionclass Returns the system default processor if false
369389c9
DM
153 * @param bool $checkisready
154 * @return \core_analytics\predictor
155 */
156 public static function get_predictions_processor($predictionclass = false, $checkisready = true) {
157
158 // We want 0 or 1 so we can use it as an array key for caching.
159 $checkisready = intval($checkisready);
160
ed12ba6b 161 if (!$predictionclass) {
369389c9
DM
162 $predictionclass = get_config('analytics', 'predictionsprocessor');
163 }
164
165 if (empty($predictionclass)) {
166 // Use the default one if nothing set.
ed12ba6b 167 $predictionclass = self::default_mlbackend();
369389c9
DM
168 }
169
170 if (!class_exists($predictionclass)) {
171 throw new \coding_exception('Invalid predictions processor ' . $predictionclass . '.');
172 }
173
174 $interfaces = class_implements($predictionclass);
175 if (empty($interfaces['core_analytics\predictor'])) {
176 throw new \coding_exception($predictionclass . ' should implement \core_analytics\predictor.');
177 }
178
179 // Return it from the cached list.
180 if (!isset(self::$predictionprocessors[$checkisready][$predictionclass])) {
181
182 $instance = new $predictionclass();
183 if ($checkisready) {
184 $isready = $instance->is_ready();
185 if ($isready !== true) {
186 throw new \moodle_exception('errorprocessornotready', 'analytics', '', $isready);
187 }
188 }
189 self::$predictionprocessors[$checkisready][$predictionclass] = $instance;
190 }
191
192 return self::$predictionprocessors[$checkisready][$predictionclass];
193 }
194
1611308b
DM
195 /**
196 * Return all system predictions processors.
197 *
08015e18 198 * @return \core_analytics\predictor[]
1611308b 199 */
369389c9
DM
200 public static function get_all_prediction_processors() {
201
202 $mlbackends = \core_component::get_plugin_list('mlbackend');
203
204 $predictionprocessors = array();
205 foreach ($mlbackends as $mlbackend => $unused) {
206d7aa9 206 $classfullpath = '\mlbackend_' . $mlbackend . '\processor';
369389c9
DM
207 $predictionprocessors[$classfullpath] = self::get_predictions_processor($classfullpath, false);
208 }
209 return $predictionprocessors;
210 }
211
ed12ba6b
DM
212 /**
213 * Returns the name of the provided predictions processor.
214 *
215 * @param \core_analytics\predictor $predictionsprocessor
216 * @return string
217 */
218 public static function get_predictions_processor_name(\core_analytics\predictor $predictionsprocessor) {
219 $component = substr(get_class($predictionsprocessor), 0, strpos(get_class($predictionsprocessor), '\\', 1));
220 return get_string('pluginname', $component);
221 }
222
223 /**
224 * Whether the provided plugin is used by any model.
225 *
226 * @param string $plugin
227 * @return bool
228 */
229 public static function is_mlbackend_used($plugin) {
230 $models = self::get_all_models();
231 foreach ($models as $model) {
232 $processor = $model->get_predictions_processor();
233 $noprefixnamespace = ltrim(get_class($processor), '\\');
234 $processorplugin = substr($noprefixnamespace, 0, strpos($noprefixnamespace, '\\'));
235 if ($processorplugin == $plugin) {
236 return true;
237 }
238 }
239
240 // Default predictions processor.
241 $defaultprocessorclass = get_config('analytics', 'predictionsprocessor');
242 $pluginclass = '\\' . $plugin . '\\processor';
243 if ($pluginclass === $defaultprocessorclass) {
244 return true;
245 }
246
247 return false;
248 }
249
369389c9
DM
250 /**
251 * Get all available time splitting methods.
252 *
1cc2b4ba 253 * @return \core_analytics\local\time_splitting\base[]
369389c9
DM
254 */
255 public static function get_all_time_splittings() {
256 if (self::$alltimesplittings !== null) {
257 return self::$alltimesplittings;
258 }
259
260 $classes = self::get_analytics_classes('time_splitting');
261
262 self::$alltimesplittings = [];
263 foreach ($classes as $fullclassname => $classpath) {
264 $instance = self::get_time_splitting($fullclassname);
265 // We need to check that it is a valid time splitting method, it may be an abstract class.
266 if ($instance) {
267 self::$alltimesplittings[$instance->get_id()] = $instance;
268 }
269 }
270
271 return self::$alltimesplittings;
272 }
273
274 /**
275 * Returns the enabled time splitting methods.
276 *
3576b66b
DM
277 * @deprecated since Moodle 3.7
278 * @todo MDL-65086 This will be deleted in Moodle 4.1
279 * @see \core_analytics\manager::get_time_splitting_methods_for_evaluation
369389c9
DM
280 * @return \core_analytics\local\time_splitting\base[]
281 */
282 public static function get_enabled_time_splitting_methods() {
3576b66b
DM
283 debugging('This function has been deprecated. You can use self::get_time_splitting_methods_for_evaluation if ' .
284 'you want to get the default time splitting methods for evaluation, or you can use self::get_all_time_splittings if ' .
285 'you want to get all the time splitting methods available on this site.');
286 return self::get_time_splitting_methods_for_evaluation();
287 }
288
289 /**
290 * Returns the default time splitting methods for model evaluation.
291 *
292 * @return \core_analytics\local\time_splitting\base[]
293 */
294 public static function get_time_splitting_methods_for_evaluation() {
369389c9 295
3576b66b 296 if ($enabledtimesplittings = get_config('analytics', 'defaulttimesplittingsevaluation')) {
369389c9
DM
297 $enabledtimesplittings = array_flip(explode(',', $enabledtimesplittings));
298 }
299
300 $timesplittings = self::get_all_time_splittings();
301 foreach ($timesplittings as $key => $timesplitting) {
302
303 // We remove the ones that are not enabled. This also respects the default value (all methods enabled).
304 if (!empty($enabledtimesplittings) && !isset($enabledtimesplittings[$key])) {
305 unset($timesplittings[$key]);
306 }
307 }
308 return $timesplittings;
309 }
310
311 /**
312 * Returns a time splitting method by its classname.
313 *
314 * @param string $fullclassname
315 * @return \core_analytics\local\time_splitting\base|false False if it is not valid.
316 */
317 public static function get_time_splitting($fullclassname) {
318 if (!self::is_valid($fullclassname, '\core_analytics\local\time_splitting\base')) {
319 return false;
320 }
321 return new $fullclassname();
322 }
323
e4453adc
DM
324 /**
325 * Return all targets in the system.
326 *
327 * @return \core_analytics\local\target\base[]
328 */
329 public static function get_all_targets() : array {
330 if (self::$alltargets !== null) {
331 return self::$alltargets;
332 }
333
334 $classes = self::get_analytics_classes('target');
335
336 self::$alltargets = [];
337 foreach ($classes as $fullclassname => $classpath) {
338 $instance = self::get_target($fullclassname);
339 if ($instance) {
340 self::$alltargets[$instance->get_id()] = $instance;
341 }
342 }
343
344 return self::$alltargets;
345 }
369389c9
DM
346 /**
347 * Return all system indicators.
348 *
349 * @return \core_analytics\local\indicator\base[]
350 */
351 public static function get_all_indicators() {
352 if (self::$allindicators !== null) {
353 return self::$allindicators;
354 }
355
356 $classes = self::get_analytics_classes('indicator');
357
358 self::$allindicators = [];
359 foreach ($classes as $fullclassname => $classpath) {
360 $instance = self::get_indicator($fullclassname);
361 if ($instance) {
b0c24929 362 self::$allindicators[$instance->get_id()] = $instance;
369389c9
DM
363 }
364 }
365
366 return self::$allindicators;
367 }
368
1611308b
DM
369 /**
370 * Returns the specified target
371 *
372 * @param mixed $fullclassname
373 * @return \core_analytics\local\target\base|false False if it is not valid
374 */
369389c9
DM
375 public static function get_target($fullclassname) {
376 if (!self::is_valid($fullclassname, 'core_analytics\local\target\base')) {
377 return false;
378 }
379 return new $fullclassname();
380 }
381
382 /**
383 * Returns an instance of the provided indicator.
384 *
385 * @param string $fullclassname
386 * @return \core_analytics\local\indicator\base|false False if it is not valid.
387 */
388 public static function get_indicator($fullclassname) {
389 if (!self::is_valid($fullclassname, 'core_analytics\local\indicator\base')) {
390 return false;
391 }
392 return new $fullclassname();
393 }
394
395 /**
396 * Returns whether a time splitting method is valid or not.
397 *
398 * @param string $fullclassname
1611308b 399 * @param string $baseclass
369389c9
DM
400 * @return bool
401 */
402 public static function is_valid($fullclassname, $baseclass) {
403 if (is_subclass_of($fullclassname, $baseclass)) {
404 if ((new \ReflectionClass($fullclassname))->isInstantiable()) {
405 return true;
406 }
407 }
408 return false;
409 }
410
f67f35f3 411 /**
1611308b 412 * Returns the logstore used for analytics.
f67f35f3 413 *
2db6e981 414 * @return \core\log\sql_reader|false False if no log stores are enabled.
f67f35f3
DM
415 */
416 public static function get_analytics_logstore() {
417 $readers = get_log_manager()->get_readers('core\log\sql_reader');
418 $analyticsstore = get_config('analytics', 'logstore');
85e50ba4
DM
419
420 if (!empty($analyticsstore) && !empty($readers[$analyticsstore])) {
f67f35f3 421 $logstore = $readers[$analyticsstore];
85e50ba4
DM
422 } else if (empty($analyticsstore) && !empty($readers)) {
423 // The first one, it is the same default than in settings.
424 $logstore = reset($readers);
2db6e981 425 } else if (!empty($readers)) {
f67f35f3
DM
426 $logstore = reset($readers);
427 debugging('The selected log store for analytics is not available anymore. Using "' .
428 $logstore->get_name() . '"', DEBUG_DEVELOPER);
429 }
430
2db6e981
DM
431 if (empty($logstore)) {
432 debugging('No system log stores available to use for analytics', DEBUG_DEVELOPER);
433 return false;
434 }
435
f67f35f3
DM
436 if (!$logstore->is_logging()) {
437 debugging('The selected log store for analytics "' . $logstore->get_name() .
438 '" is not logging activity logs', DEBUG_DEVELOPER);
439 }
440
441 return $logstore;
442 }
443
0690a271
DM
444 /**
445 * Returns this analysable calculations during the provided period.
446 *
447 * @param \core_analytics\analysable $analysable
448 * @param int $starttime
449 * @param int $endtime
450 * @param string $samplesorigin The samples origin as sampleid is not unique across models.
451 * @return array
452 */
453 public static function get_indicator_calculations($analysable, $starttime, $endtime, $samplesorigin) {
454 global $DB;
455
456 $params = array('starttime' => $starttime, 'endtime' => $endtime, 'contextid' => $analysable->get_context()->id,
457 'sampleorigin' => $samplesorigin);
458 $calculations = $DB->get_recordset('analytics_indicator_calc', $params, '', 'indicator, sampleid, value');
459
460 $existingcalculations = array();
461 foreach ($calculations as $calculation) {
462 if (empty($existingcalculations[$calculation->indicator])) {
463 $existingcalculations[$calculation->indicator] = array();
464 }
465 $existingcalculations[$calculation->indicator][$calculation->sampleid] = $calculation->value;
466 }
a938e409 467 $calculations->close();
0690a271
DM
468 return $existingcalculations;
469 }
470
1611308b
DM
471 /**
472 * Returns the models with insights at the provided context.
473 *
474 * @param \context $context
475 * @return \core_analytics\model[]
476 */
477 public static function get_models_with_insights(\context $context) {
478
479 self::check_can_list_insights($context);
480
413f19bc 481 $models = self::get_all_models(true, true, $context);
1611308b
DM
482 foreach ($models as $key => $model) {
483 // Check that it not only have predictions but also generates insights from them.
484 if (!$model->uses_insights()) {
485 unset($models[$key]);
486 }
487 }
488 return $models;
489 }
490
491 /**
492 * Returns a prediction
493 *
494 * @param int $predictionid
495 * @param bool $requirelogin
496 * @return array array($model, $prediction, $context)
497 */
498 public static function get_prediction($predictionid, $requirelogin = false) {
499 global $DB;
500
501 if (!$predictionobj = $DB->get_record('analytics_predictions', array('id' => $predictionid))) {
4a210b06
DM
502 throw new \moodle_exception('errorpredictionnotfound', 'analytics');
503 }
504
505 $context = \context::instance_by_id($predictionobj->contextid, IGNORE_MISSING);
506 if (!$context) {
507 throw new \moodle_exception('errorpredictioncontextnotavailable', 'analytics');
1611308b
DM
508 }
509
510 if ($requirelogin) {
511 list($context, $course, $cm) = get_context_info_array($predictionobj->contextid);
512 require_login($course, false, $cm);
1611308b
DM
513 }
514
413f19bc 515 self::check_can_list_insights($context);
1611308b
DM
516
517 $model = new \core_analytics\model($predictionobj->modelid);
518 $sampledata = $model->prediction_sample_data($predictionobj);
519 $prediction = new \core_analytics\prediction($predictionobj, $sampledata);
520
521 return array($model, $prediction, $context);
522 }
523
e709e544 524 /**
3b7c7918 525 * Used to be used to add models included with the Moodle core.
e709e544 526 *
3b7c7918
DM
527 * @deprecated Deprecated since Moodle 3.7 (MDL-61667) - Use lib/db/analytics.php instead.
528 * @todo Remove this method in Moodle 4.1 (MDL-65186).
e709e544
DM
529 * @return void
530 */
531 public static function add_builtin_models() {
532
3b7c7918
DM
533 debugging('core_analytics\manager::add_builtin_models() has been deprecated. Core models are now automatically '.
534 'updated according to their declaration in the lib/db/analytics.php file.', DEBUG_DEVELOPER);
e709e544
DM
535 }
536
f9222c49
DM
537 /**
538 * Cleans up analytics db tables that do not directly depend on analysables that may have been deleted.
539 */
540 public static function cleanup() {
541 global $DB;
542
543 // Clean up stuff that depends on contexts that do not exist anymore.
544 $sql = "SELECT DISTINCT ap.contextid FROM {analytics_predictions} ap
545 LEFT JOIN {context} ctx ON ap.contextid = ctx.id
546 WHERE ctx.id IS NULL";
547 $apcontexts = $DB->get_records_sql($sql);
548
549 $sql = "SELECT DISTINCT aic.contextid FROM {analytics_indicator_calc} aic
550 LEFT JOIN {context} ctx ON aic.contextid = ctx.id
551 WHERE ctx.id IS NULL";
552 $indcalccontexts = $DB->get_records_sql($sql);
553
554 $contexts = $apcontexts + $indcalccontexts;
555 if ($contexts) {
556 list($sql, $params) = $DB->get_in_or_equal(array_keys($contexts));
e08c74f5 557 $DB->execute("DELETE FROM {analytics_prediction_actions} WHERE predictionid IN
f9222c49
DM
558 (SELECT ap.id FROM {analytics_predictions} ap WHERE ap.contextid $sql)", $params);
559
560 $DB->delete_records_select('analytics_predictions', "contextid $sql", $params);
561 $DB->delete_records_select('analytics_indicator_calc', "contextid $sql", $params);
562 }
563
564 // Clean up stuff that depends on analysable ids that do not exist anymore.
565 $models = self::get_all_models();
566 foreach ($models as $model) {
567 $analyser = $model->get_analyser(array('notimesplitting' => true));
fccc728f
DM
568 $analysables = $analyser->get_analysables_iterator();
569
570 $analysableids = [];
571 foreach ($analysables as $analysable) {
572 if (!$analysable) {
573 continue;
574 }
575 $analysableids[] = $analysable->get_id();
576 }
577 if (empty($analysableids)) {
f9222c49
DM
578 continue;
579 }
580
f9222c49
DM
581 list($notinsql, $params) = $DB->get_in_or_equal($analysableids, SQL_PARAMS_NAMED, 'param', false);
582 $params['modelid'] = $model->get_id();
583
584 $DB->delete_records_select('analytics_predict_samples', "modelid = :modelid AND analysableid $notinsql", $params);
585 $DB->delete_records_select('analytics_train_samples', "modelid = :modelid AND analysableid $notinsql", $params);
586 }
587 }
588
ed12ba6b
DM
589 /**
590 * Default system backend.
591 *
592 * @return string
593 */
594 public static function default_mlbackend() {
595 return self::DEFAULT_MLBACKEND;
596 }
597
369389c9
DM
598 /**
599 * Returns the provided element classes in the site.
600 *
601 * @param string $element
602 * @return string[] Array keys are the FQCN and the values the class path.
603 */
604 private static function get_analytics_classes($element) {
605
606 // Just in case...
1611308b 607 $element = clean_param($element, PARAM_ALPHANUMEXT);
369389c9 608
206d7aa9
DM
609 // Core analytics classes (analytics subsystem should not contain uses of the analytics API).
610 $classes = \core_component::get_component_classes_in_namespace('core', 'analytics\\' . $element);
611
612 // Plugins.
369389c9
DM
613 foreach (\core_component::get_plugin_types() as $type => $unusedplugintypepath) {
614 foreach (\core_component::get_plugin_list($type) as $pluginname => $unusedpluginpath) {
615 $frankenstyle = $type . '_' . $pluginname;
616 $classes += \core_component::get_component_classes_in_namespace($frankenstyle, 'analytics\\' . $element);
617 }
618 }
1cc2b4ba 619
206d7aa9 620 // Core subsystems.
1cc2b4ba
DM
621 foreach (\core_component::get_core_subsystems() as $subsystemname => $unusedsubsystempath) {
622 $componentname = 'core_' . $subsystemname;
623 $classes += \core_component::get_component_classes_in_namespace($componentname, 'analytics\\' . $element);
624 }
625
369389c9
DM
626 return $classes;
627 }
f0584045 628
606c3be0
DM
629 /**
630 * Check that all the models declared by the component are up to date.
631 *
632 * This is intended to be called during the installation / upgrade to automatically create missing models.
633 *
634 * @param string $componentname The name of the component to load models for.
635 * @return array \core_analytics\model[] List of actually created models.
636 */
637 public static function update_default_models_for_component(string $componentname): array {
638
639 $result = [];
640
641 foreach (static::load_default_models_for_component($componentname) as $definition) {
642 if (!\core_analytics\model::exists(static::get_target($definition['target']))) {
643 $result[] = static::create_declared_model($definition);
644 }
645 }
646
647 return $result;
648 }
649
f0584045
DM
650 /**
651 * Return the list of models declared by the given component.
652 *
653 * @param string $componentname The name of the component to load models for.
654 * @throws \coding_exception Exception thrown in case of invalid syntax.
655 * @return array The $models description array.
656 */
657 public static function load_default_models_for_component(string $componentname): array {
658
659 $dir = \core_component::get_component_directory($componentname);
660
661 if (!$dir) {
662 // This is either an invalid component, or a core subsystem without its own root directory.
663 return [];
664 }
665
666 $file = $dir . '/' . self::ANALYTICS_FILENAME;
667
668 if (!is_readable($file)) {
669 return [];
670 }
671
672 $models = null;
673 include($file);
674
675 if (!isset($models) || !is_array($models) || empty($models)) {
676 return [];
677 }
678
679 foreach ($models as &$model) {
680 if (!isset($model['enabled'])) {
681 $model['enabled'] = false;
682 } else {
683 $model['enabled'] = clean_param($model['enabled'], PARAM_BOOL);
684 }
685 }
686
687 static::validate_models_declaration($models);
688
689 return $models;
690 }
691
692 /**
693 * Validate the declaration of prediction models according the syntax expected in the component's db folder.
694 *
695 * The expected structure looks like this:
696 *
697 * [
698 * [
699 * 'target' => '\fully\qualified\name\of\the\target\class',
700 * 'indicators' => [
701 * '\fully\qualified\name\of\the\first\indicator',
702 * '\fully\qualified\name\of\the\second\indicator',
703 * ],
704 * 'timesplitting' => '\optional\name\of\the\time_splitting\class',
705 * 'enabled' => true,
706 * ],
707 * ];
708 *
709 * @param array $models List of declared models.
710 * @throws \coding_exception Exception thrown in case of invalid syntax.
711 */
712 public static function validate_models_declaration(array $models) {
713
714 foreach ($models as $model) {
715 if (!isset($model['target'])) {
716 throw new \coding_exception('Missing target declaration');
717 }
718
719 if (!static::is_valid($model['target'], '\core_analytics\local\target\base')) {
720 throw new \coding_exception('Invalid target classname', $model['target']);
721 }
722
723 if (empty($model['indicators']) || !is_array($model['indicators'])) {
724 throw new \coding_exception('Missing indicators declaration');
725 }
726
727 foreach ($model['indicators'] as $indicator) {
728 if (!static::is_valid($indicator, '\core_analytics\local\indicator\base')) {
729 throw new \coding_exception('Invalid indicator classname', $indicator);
730 }
731 }
732
733 if (isset($model['timesplitting'])) {
734 if (substr($model['timesplitting'], 0, 1) !== '\\') {
735 throw new \coding_exception('Expecting fully qualified time splitting classname', $model['timesplitting']);
736 }
737 if (!static::is_valid($model['timesplitting'], '\core_analytics\local\time_splitting\base')) {
738 throw new \coding_exception('Invalid time splitting classname', $model['timesplitting']);
739 }
740 }
741
742 if (!empty($model['enabled']) && !isset($model['timesplitting'])) {
743 throw new \coding_exception('Cannot enable a model without time splitting method specified');
744 }
745 }
746 }
6187213f
DM
747
748 /**
749 * Create the defined model.
750 *
751 * @param array $definition See {@link self::validate_models_declaration()} for the syntax.
752 * @return \core_analytics\model
753 */
754 public static function create_declared_model(array $definition): \core_analytics\model {
755
756 $target = static::get_target($definition['target']);
757
758 $indicators = [];
759
760 foreach ($definition['indicators'] as $indicatorname) {
761 $indicator = static::get_indicator($indicatorname);
762 $indicators[$indicator->get_id()] = $indicator;
763 }
764
765 if (isset($definition['timesplitting'])) {
766 $timesplitting = $definition['timesplitting'];
767 } else {
768 $timesplitting = false;
769 }
770
771 $created = \core_analytics\model::create($target, $indicators, $timesplitting);
772
773 if (!empty($definition['enabled'])) {
774 $created->enable();
775 }
776
777 return $created;
778 }
369389c9 779}