Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
namespace tool_brickfield;
18
 
19
/**
20
 * Class manager
21
 * @package tool_brickfield
22
 * @copyright  2021 Brickfield Education Labs https://www.brickfield.ie
23
 * @license https://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
class manager {
26
 
27
    /**
28
     * Defines the waiting for analysis status.
29
     */
30
    const STATUS_WAITING = 0;
31
 
32
    /**
33
     * Defined the analysis in progress status.
34
     */
35
    const STATUS_INPROGRESS = -1;
36
 
37
    /**
38
     * Defines the analysis has completed status.
39
     */
40
    const STATUS_CHECKED = 1;
41
 
42
    /**
43
     * Defines summary error value.
44
     */
45
    const SUMMARY_ERROR = 0;
46
 
47
    /**
48
     * Defines summary failed value.
49
     */
50
    const SUMMARY_FAILED = 1;
51
 
52
    /**
53
     * Defines summary percent value.
54
     */
55
    const SUMMARY_PERCENT = 2;
56
 
57
    /**
58
     * Default bulk record limit.
59
     */
60
    const BULKRECORDLIMIT = 1000;
61
 
62
    /**
63
     * Name of this plugin.
64
     */
65
    const PLUGINNAME = 'tool_brickfield';
66
 
67
    /**
68
     * Areas table name.
69
     */
70
    const DB_AREAS = self::PLUGINNAME . '_areas';
71
 
72
    /**
73
     * Cacheacts table name.
74
     */
75
    const DB_CACHEACTS = self::PLUGINNAME . '_cache_acts';
76
 
77
    /**
78
     * Cachecheck table name.
79
     */
80
    const DB_CACHECHECK = self::PLUGINNAME . '_cache_check';
81
 
82
    /**
83
     * Checks table name.
84
     */
85
    const DB_CHECKS = self::PLUGINNAME . '_checks';
86
 
87
    /**
88
     * Content table name.
89
     */
90
    const DB_CONTENT = self::PLUGINNAME . '_content';
91
 
92
    /**
93
     * Errors table name.
94
     */
95
    const DB_ERRORS = self::PLUGINNAME . '_errors';
96
 
97
    /**
98
     * Process table name.
99
     */
100
    const DB_PROCESS = self::PLUGINNAME . '_process';
101
 
102
    /**
103
     * Results table name.
104
     */
105
    const DB_RESULTS = self::PLUGINNAME . '_results';
106
 
107
    /**
108
     * Schedule table name.
109
     */
110
    const DB_SCHEDULE = self::PLUGINNAME . '_schedule';
111
 
112
    /**
113
     * Summary table name.
114
     */
115
    const DB_SUMMARY = self::PLUGINNAME . '_summary';
116
 
117
    /** @var string The URL to find help at. */
118
    private static $helpurl = 'https://www.brickfield.ie/moodle-help-311';
119
 
120
 
121
    /** @var  array Statically stores the database checks records. */
122
    static protected $checks;
123
 
124
    /**
125
     * Returns the URL used for registration.
126
     *
127
     * @return \moodle_url
128
     */
129
    public static function registration_url(): \moodle_url {
130
        return accessibility::get_plugin_url('registration.php');
131
    }
132
 
133
    /**
134
     * Returns an appropriate message about the current registration state.
135
     *
136
     * @return string
137
     * @throws \coding_exception
138
     * @throws \dml_exception
139
     * @throws \moodle_exception
140
     */
141
    public static function registration_message(): string {
142
        $firstline = get_string('notregistered', self::PLUGINNAME);
143
        if (has_capability('moodle/site:config', \context_system::instance())) {
144
            $secondline = \html_writer::link(self::registration_url(), get_string('registernow', self::PLUGINNAME));
145
        } else {
146
            $secondline = get_string('contactadmin', self::PLUGINNAME);
147
        }
148
        return $firstline . '<br />' . $secondline;
149
    }
150
 
151
    /**
152
     * Get the help page URL.
153
     * @return string
154
     * @throws dml_exception
155
     */
156
    public static function get_helpurl(): string {
157
        return self::$helpurl;
158
    }
159
 
160
    /**
161
     * Return an array of system checks available, and store them statically.
162
     *
163
     * @return array
164
     * @throws \dml_exception
165
     */
166
    public static function get_checks(): array {
167
        global $DB;
168
        if (self::$checks === null) {
169
            self::$checks = $DB->get_records(self::DB_CHECKS, [] , 'id');
170
        }
171
        return self::$checks;
172
    }
173
 
174
    /**
175
     * Find all available areas.
176
     *
177
     * @return area_base[]
178
     * @throws \ReflectionException
179
     */
180
    public static function get_all_areas(): array {
181
        return array_filter(
182
            array_map(
183
                function($classname) {
184
                    $reflectionclass = new \ReflectionClass($classname);
185
                    if ($reflectionclass->isAbstract()) {
186
                        return false;
187
                    }
188
                    $instance = new $classname();
189
 
190
                    if ($instance->is_available()) {
191
                        return $instance;
192
                    } else {
193
                        return null;
194
                    }
195
                },
196
                array_keys(\core_component::get_component_classes_in_namespace('tool_brickfield', 'local\areas'))
197
            )
198
        );
199
    }
200
 
201
    /**
202
     * Calculate contenthash of a given content string
203
     *
204
     * @param string|null $content
205
     * @return string
206
     */
207
    public static function get_contenthash(?string $content = null): string {
208
        return sha1($content ?? '');
209
    }
210
 
211
    /**
212
     * Does the current area content need to be scheduled for check?
213
     *
214
     * It does not need to be scheduled if:
215
     * - it is the current content
216
     * OR
217
     * - there is already schedule
218
     *
219
     * @param int $areaid
220
     * @param string $contenthash
221
     * @return bool
222
     * @throws \dml_exception
223
     */
224
    protected static function content_needs_scheduling(int $areaid, string $contenthash): bool {
225
        global $DB;
226
        return ! $DB->get_field_sql('SELECT 1 FROM {' . self::DB_CONTENT . '} '.
227
            'WHERE areaid = ?
228
            AND (status = 0 OR (iscurrent = 1 AND contenthash = ?))',
229
            [$areaid, $contenthash], IGNORE_MULTIPLE);
230
    }
231
 
232
    /**
233
     * Schedule an area for analysis if there has been changes.
234
     *
235
     * @param \stdClass $arearecord record with the fields from the {tool_brickfield_areas} table
236
     *    as returned by area_base::find_relevant_areas().
237
     *    It also contains the 'content' property with the current area content
238
     * @throws \dml_exception
239
     */
240
    protected static function schedule_area_if_necessary(\stdClass $arearecord) {
241
        global $DB;
242
 
243
        $contenthash = static::get_contenthash($arearecord->content);
244
        $searchparams = array_diff_key((array)$arearecord, ['content' => 1, 'reftable' => 1, 'refid' => 1]);
245
        if ($dbrecord = $DB->get_record(self::DB_AREAS, $searchparams)) {
246
            if ( ! static::content_needs_scheduling($dbrecord->id, $contenthash)) {
247
                // This is already the latest content record or there is already scheduled record, nothing to do.
248
                return;
249
            }
250
        } else {
251
            $dbrecord = (object)array_diff_key((array)$arearecord, ['content' => 1]);
252
            $dbrecord->id = $DB->insert_record(self::DB_AREAS, $dbrecord);
253
        }
254
        // Schedule the area for the check. Note that we do not record the contenthash, we will calculate it again
255
        // during the actual check.
256
        $DB->insert_record(self::DB_CONTENT,
257
            (object)['areaid' => $dbrecord->id, 'contenthash' => '', 'timecreated' => time(),
258
                'status' => self::STATUS_WAITING]);
259
    }
260
 
261
    /**
262
     * Asks all area providers if they have any areas that might have changed as a result of an event and schedules them
263
     *
264
     * @param \core\event\base $event
265
     * @throws \ReflectionException
266
     * @throws \dml_exception
267
     */
268
    public static function find_new_or_updated_areas(\core\event\base $event) {
269
        foreach (static::get_all_areas() as $area) {
270
            if ($records = $area->find_relevant_areas($event)) {
271
                foreach ($records as $record) {
272
                    static::schedule_area_if_necessary($record);
273
                }
274
                $records->close();
275
            }
276
        }
277
    }
278
 
279
    /**
280
     * Returns the current content of the area.
281
     *
282
     * @param \stdClass $arearecord record from the tool_brickfield_areas table
283
     * @return array|null array where the first element is the value of the field and the second element
284
     *    is the 'format' for this field if it is present. If the record was not found null is returned.
285
     * @throws \ddl_exception
286
     * @throws \ddl_table_missing_exception
287
     * @throws \dml_exception
288
     */
289
    protected static function get_area_content(\stdClass $arearecord): array {
290
        global $DB;
291
        if ($arearecord->type == area_base::TYPE_FIELD) {
292
            $tablename = $arearecord->tablename;
293
            $fieldname = $arearecord->fieldorarea;
294
            $itemid = $arearecord->itemid;
295
 
296
            if (!$DB->get_manager()->table_exists($tablename)) {
297
                return [];
298
            }
299
            if (!$DB->get_manager()->field_exists($tablename, $fieldname)) {
300
                return [];
301
            }
302
            $fields = $fieldname;
303
            if ($DB->get_manager()->field_exists($tablename, $fieldname . 'format')) {
304
                $fields .= ',' . $fieldname . 'format';
305
            }
306
            if ($record = $DB->get_record($tablename, ['id' => $itemid], $fields)) {
307
                return array_values((array)$record);
308
            }
309
        }
310
        return [];
311
    }
312
 
313
    /**
314
     * Asks all area providers if they have any areas that might have changed per courseid and schedules them.
315
     *
316
     * @param int $courseid
317
     * @throws \ReflectionException
318
     * @throws \coding_exception
319
     * @throws \ddl_exception
320
     * @throws \ddl_table_missing_exception
321
     * @throws \dml_exception
322
     */
323
    public static function find_new_or_updated_areas_per_course(int $courseid) {
324
        $totalcount = 0;
325
        foreach (static::get_all_areas() as $area) {
326
            if ($records = $area->find_course_areas($courseid)) {
327
                foreach ($records as $record) {
328
                    $totalcount++;
329
                    static::schedule_area_if_necessary($record);
330
                }
331
                $records->close();
332
            }
333
            // For a site course request, also process the site level areas.
334
            if (($courseid == SITEID) && ($records = $area->find_system_areas())) {
335
                foreach ($records as $record) {
336
                    $totalcount++;
337
                    // Currently, the courseid in the area table is null if there is a category id.
338
                    if (!empty($record->categoryid)) {
339
                        $record->courseid = null;
340
                    }
341
                    static::schedule_area_if_necessary($record);
342
                }
343
                $records->close();
344
            }
345
        }
346
        // Need to run for total count of areas.
347
        static::check_scheduled_areas($totalcount);
348
    }
349
 
350
    /**
351
     * Finds all areas that are waiting to be checked, performs checks. Returns true if there were records processed, false if not.
352
     * To be called from scheduled task
353
     *
354
     * @param int $batch
355
     * @return bool
356
     * @throws \coding_exception
357
     * @throws \ddl_exception
358
     * @throws \ddl_table_missing_exception
359
     * @throws \dml_exception
360
     */
361
    public static function check_scheduled_areas(int $batch = 0): bool {
362
        global $DB;
363
 
364
        $processingtime = 0;
365
        $resultstime = 0;
366
 
367
        $config = get_config(self::PLUGINNAME);
368
        if ($batch == 0) {
369
            $batch = $config->batch;
370
        }
371
        // Creating insert array for courseid cache reruns.
372
        $recordsfound = false;
373
        $batchinserts = [];
374
        echo("Batch amount is ".$batch.", starttime ".time()."\n");
375
        $rs = $DB->get_recordset_sql('SELECT a.*, ch.id AS contentid
376
            FROM {' . self::DB_AREAS. '} a
377
            JOIN {' . self::DB_CONTENT . '} ch ON ch.areaid = a.id
378
            WHERE ch.status = ?
379
            ORDER BY a.id, ch.timecreated, ch.id',
380
            [self::STATUS_WAITING], 0, $batch);
381
 
382
        foreach ($rs as $arearecord) {
383
            $recordsfound = true;
384
            $DB->set_field(self::DB_CONTENT, 'status', self::STATUS_INPROGRESS, ['id' => $arearecord->contentid]);
385
            $content = static::get_area_content($arearecord);
386
            if ($content[0] == null) {
387
                $content[0] = '';
388
            }
389
            accessibility::run_check($content[0], $arearecord->contentid, $processingtime, $resultstime);
390
 
391
            // Set all content 'iscurrent' fields for this areaid to 0.
392
            $DB->set_field(self::DB_CONTENT, 'iscurrent', 0, ['areaid' => $arearecord->id]);
393
            // Update this content record to be the current record.
394
            $DB->update_record(self::DB_CONTENT,
395
                (object)['id' => $arearecord->contentid, 'status' => self::STATUS_CHECKED, 'timechecked' => time(),
396
                    'contenthash' => static::get_contenthash($content[0]), 'iscurrent' => 1]);
397
 
398
            // If full caching has been run, then queue, if not in queue already.
399
            if (($arearecord->courseid != null) && static::is_okay_to_cache() &&
400
                !isset($batchinserts[$arearecord->courseid])) {
401
                $batchinserts[$arearecord->courseid] = ['courseid' => $arearecord->courseid, 'item' => 'cache'];
402
            }
403
        }
404
 
1441 ariadna 405
        $rs->close();
406
 
1 efrain 407
        if (count($batchinserts) > 0) {
408
            $DB->insert_records(self::DB_PROCESS, $batchinserts);
409
        }
410
 
411
        mtrace('Total time in htmlchecker: ' . $processingtime . ' secs.');
412
        mtrace('Total time in results: ' . $resultstime . ' secs.');
413
        return $recordsfound;
414
    }
415
 
416
    /**
417
     * Return true if analysis hasn't been disabled.
418
     * @return bool
419
     * @throws \dml_exception
420
     */
421
    public static function is_okay_to_cache(): bool {
422
        return (analysis::type_is_byrequest());
423
    }
424
 
425
    /**
426
     * Finds all areas that are waiting to be deleted, performs deletions.
427
     *
428
     * @param int $batch limit, can be called from runcli.php
429
     * To be called from scheduled task
430
     * @throws \coding_exception
431
     * @throws \dml_exception
432
     */
433
    public static function check_scheduled_deletions(int $batch = 0) {
434
        global $DB;
435
 
436
        $config = get_config(self::PLUGINNAME);
437
        if ($batch == 0) {
438
            $batch = $config->batch;
439
        }
440
 
441
        // Creating insert array for courseid cache reruns.
442
        $batchinserts = [];
443
 
444
        $rs = $DB->get_recordset(self::DB_PROCESS, ['contextid' => -1, 'timecompleted' => 0], '', '*', 0, $batch);
445
 
446
        foreach ($rs as $record) {
447
 
448
            if ($record->item == "core_course") {
449
                $tidyparams = ['courseid' => $record->courseid];
450
                static::delete_summary_data($record->courseid); // Delete cache too.
451
            } else if ($record->item == "course_categories") {
452
                $tidyparams = ['component' => 'core_course', 'categoryid' => $record->innercontextid];
453
            } else if ($record->item == "course_sections") {
454
                // Locate course sections, using innercontextid, contextid set to -1 for delete.
455
                $tidyparams = ['courseid' => $record->courseid, 'component' => 'core_course',
456
                    'tablename' => $record->item, 'itemid' => $record->innercontextid];
457
            } else if ($record->item == "lesson_pages") {
458
                // Locate lesson pages, using innercontextid, contextid set to -1 for delete.
459
                $tidyparams = ['courseid' => $record->courseid, 'component' => 'mod_lesson',
460
                    'tablename' => $record->item, 'itemid' => $record->innercontextid];
461
            } else if ($record->item == "book_chapters") {
462
                // Locate book chapters, using innercontextid, contextid set to -1 for delete.
463
                $tidyparams = ['courseid' => $record->courseid, 'component' => 'mod_book',
464
                    'tablename' => $record->item, 'itemid' => $record->innercontextid];
465
            } else if ($record->item == "question") {
466
                // Locate question areas, using innercontextid, contextid set to -1 for delete.
467
                $tidyparams = [
468
                    'courseid' => $record->courseid, 'component' => 'core_question',
469
                    'tablename' => $record->item, 'itemid' => $record->innercontextid
470
                ];
471
            } else {
472
                // Locate specific module instance, using innercontextid, contextid set to -1 for delete.
473
                $tidyparams = ['courseid' => $record->courseid, 'component' => $record->item,
474
                    'itemid' => $record->innercontextid];
475
            }
476
 
477
            $areas = $DB->get_records(self::DB_AREAS, $tidyparams);
478
            foreach ($areas as $area) {
479
                static::delete_area_tree($area);
480
            }
481
 
482
            $DB->delete_records(self::DB_PROCESS, ['id' => $record->id]);
483
 
484
            // If full caching has been run, then queue, if not in queue already.
485
            if ($record->courseid != null && static::is_okay_to_cache() && !isset($batchinserts[$record->courseid])) {
486
                $batchinserts[$record->courseid] = ['courseid' => $record->courseid, 'item' => 'cache'];
487
            }
488
        }
489
        $rs->close();
490
 
491
        if (count($batchinserts) > 0) {
492
            $DB->insert_records(self::DB_PROCESS, $batchinserts);
493
        }
494
    }
495
 
496
    /**
497
     * Checks all queued course updates, and finds all relevant areas.
498
     *
499
     * @param int $batch limit
500
     * To be called from scheduled task
501
     * @throws \ReflectionException
502
     * @throws \dml_exception
503
     */
504
    public static function check_course_updates(int $batch = 0) {
505
        global $DB;
506
 
507
        if ($batch == 0) {
508
            $config = get_config(self::PLUGINNAME);
509
            $batch = $config->batch;
510
        }
511
 
512
        $recs = $DB->get_records(self::DB_PROCESS, ['item' => 'coursererun'], '', 'DISTINCT courseid', 0, $batch);
513
 
514
        foreach ($recs as $record) {
515
            static::find_new_or_updated_areas_per_course($record->courseid);
516
            $DB->delete_records(self::DB_PROCESS, ['courseid' => $record->courseid, 'item' => 'coursererun']);
517
            static::store_result_summary($record->courseid);
518
        }
519
    }
520
 
521
    /**
522
     * Finds all records for a given content area and performs deletions.
523
     *
524
     * To be called from scheduled task
525
     * @param \stdClass $area
526
     * @throws \dml_exception
527
     */
528
    public static function delete_area_tree(\stdClass $area) {
529
        global $DB;
530
 
531
        $contents = $DB->get_records(self::DB_CONTENT, ['areaid' => $area->id]);
532
        foreach ($contents as $content) {
533
            $results = $DB->get_records(self::DB_RESULTS, ['contentid' => $content->id]);
534
            foreach ($results as $result) {
535
                $DB->delete_records(self::DB_ERRORS, ['resultid' => $result->id]);
536
            }
537
            $DB->delete_records(self::DB_RESULTS, ['contentid' => $content->id]);
538
        }
539
 
540
        // Also, delete all child areas, if existing.
541
        $childparams = ['type' => $area->type, 'reftable' => $area->tablename,
542
            'refid' => $area->itemid];
543
        $childareas = $DB->get_records(self::DB_AREAS, $childparams);
544
        foreach ($childareas as $childarea) {
545
            static::delete_area_tree($childarea);
546
        }
547
 
548
        $DB->delete_records(self::DB_CONTENT, ['areaid' => $area->id]);
549
        $DB->delete_records(self::DB_AREAS, ['id' => $area->id]);
550
    }
551
 
552
    /**
553
     * Finds all records which are no longer current and performs deletions.
554
     *
555
     * To be called from scheduled task.
556
     */
557
    public static function delete_historical_data() {
558
        global $DB;
559
 
560
        $config = get_config(self::PLUGINNAME);
561
 
562
        if ($config->deletehistoricaldata) {
563
            $contents = $DB->get_records(self::DB_CONTENT, ['iscurrent' => 0, 'status' => self::STATUS_CHECKED]);
564
            foreach ($contents as $content) {
565
                $results = $DB->get_records(self::DB_RESULTS, ['contentid' => $content->id]);
566
                foreach ($results as $result) {
567
                    $DB->delete_records(self::DB_ERRORS, ['resultid' => $result->id]);
568
                }
569
                $DB->delete_records(self::DB_RESULTS, ['contentid' => $content->id]);
570
                $DB->delete_records(self::DB_CONTENT, ['id' => $content->id]);
571
            }
572
        }
573
    }
574
 
575
    /**
576
     * Finds all summary cache records for a given courseid and performs deletions.
577
     * To be called from scheduled task.
578
     *
579
     * @param int $courseid
580
     * @throws \dml_exception
581
     */
582
    public static function delete_summary_data(int $courseid) {
583
        global $DB;
584
 
585
        if ($courseid == null) {
586
            mtrace('Attempting to run delete_summary_data with no courseid, returning');
587
            return;
588
        }
589
 
590
        $DB->delete_records(self::DB_SUMMARY, ['courseid' => $courseid]);
591
        $DB->delete_records(self::DB_CACHECHECK, ['courseid' => $courseid]);
592
        $DB->delete_records(self::DB_CACHEACTS, ['courseid' => $courseid]);
593
    }
594
 
595
    /**
596
     * Finds all results required to display accessibility report and stores them in the database.
597
     *
598
     * To be called from scheduled task.
599
     * @param int|null $courseid
600
     * @throws \coding_exception
601
     * @throws \dml_exception
602
     */
1441 ariadna 603
    public static function store_result_summary(?int $courseid = null) {
1 efrain 604
        global $DB;
605
 
606
        if (static::is_okay_to_cache() && ($courseid == null)) {
607
            mtrace('Attempting to run update cache with no courseid, returning');
608
            return;
609
        }
610
 
611
        $extrasql = !$courseid ? "" : "AND courseid = ?";
612
        $coursesqlval = !$courseid ? [] : [$courseid];
613
 
614
        // Count of failed activities and count of errors by check.
615
        $errorsql = "SELECT areas.courseid, chx.checkgroup,
616
                COUNT(DISTINCT (".$DB->sql_concat('areas.contextid', 'areas.component').")) AS failed,
617
                SUM(res.errorcount) AS errors
618
                FROM {" . self::DB_AREAS . "} areas
619
                INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = areas.id
620
                INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id
621
                INNER JOIN {" . self::DB_CHECKS . "} chx ON chx.id = res.checkid
622
                WHERE res.errorcount > ? AND ch.iscurrent = ? ". $extrasql ." GROUP BY courseid, chx.checkgroup";
623
 
624
        $recordserrored = $DB->get_recordset_sql($errorsql,  array_merge([0, 1], $coursesqlval));
625
 
626
        // Count of failed activities by course.
627
        $failsql = "SELECT areas.courseid,
628
                COUNT(DISTINCT (".$DB->sql_concat('areas.contextid', 'areas.component').")) AS failed,
629
                SUM(res.errorcount) AS errors
630
                FROM {" . self::DB_AREAS . "} areas
631
                INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = areas.id
632
                INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id
633
                WHERE res.errorcount > ? AND ch.iscurrent = ? ". $extrasql ." GROUP BY courseid";
634
 
635
        $recordsfailed = $DB->get_recordset_sql($failsql, array_merge([0, 1], $coursesqlval));
636
 
637
        $extrasql = !$courseid ? "" : "WHERE courseid = ?";
638
        // Count of activities per course.
639
        $countsql = "SELECT courseid, COUNT(DISTINCT (".$DB->sql_concat('areas.contextid', 'areas.component').")) AS activities
640
                FROM {" . self::DB_AREAS . "} areas ". $extrasql ." GROUP BY areas.courseid";
641
 
642
        $recordscount = $DB->get_records_sql($countsql, $coursesqlval);
643
 
644
        $final = [];
645
        $values = [];
646
 
647
        foreach ($recordscount as $countrecord) {
648
            $final[$countrecord->courseid] = array_pad(array(), 8,
649
                    [self::SUMMARY_ERROR => 0, self::SUMMARY_FAILED => 0, self::SUMMARY_PERCENT => 100]
650
                ) + [
651
                    "activitiespassed" => $countrecord->activities,
652
                    "activitiesfailed" => 0,
653
                    "activities" => $countrecord->activities
654
                ];
655
        }
656
 
657
        foreach ($recordsfailed as $failedrecord) {
658
            $final[$failedrecord->courseid]["activitiespassed"] -= $failedrecord->failed;
659
            $final[$failedrecord->courseid]["activitiesfailed"] += $failedrecord->failed;
660
        }
661
 
662
        foreach ($recordserrored as $errorrecord) {
663
            $final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_ERROR] = $errorrecord->errors;
664
            $final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_FAILED] = $errorrecord->failed;
665
            $final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_PERCENT] = round(100 * (1 -
666
                    ($final[$errorrecord->courseid][$errorrecord->checkgroup][self::SUMMARY_FAILED]
667
                        / $final[$errorrecord->courseid]["activities"])));
668
        }
669
 
670
        foreach ($recordscount as $course) {
671
            if (!$course->courseid) {
672
                continue;
673
            }
674
            $element = [
675
                'courseid' => $course->courseid,
676
                'status' => self::STATUS_CHECKED,
677
                'activities' => $final[$course->courseid]["activities"],
678
                'activitiespassed' => $final[$course->courseid]["activitiespassed"],
679
                'activitiesfailed' => $final[$course->courseid]["activitiesfailed"],
680
                'errorschecktype1' => $final[$course->courseid][area_base::CHECKGROUP_FORM][self::SUMMARY_ERROR],
681
                'errorschecktype2' => $final[$course->courseid][area_base::CHECKGROUP_IMAGE][self::SUMMARY_ERROR],
682
                'errorschecktype3' => $final[$course->courseid][area_base::CHECKGROUP_LAYOUT][self::SUMMARY_ERROR],
683
                'errorschecktype4' => $final[$course->courseid][area_base::CHECKGROUP_LINK][self::SUMMARY_ERROR],
684
                'errorschecktype5' => $final[$course->courseid][area_base::CHECKGROUP_MEDIA][self::SUMMARY_ERROR],
685
                'errorschecktype6' => $final[$course->courseid][area_base::CHECKGROUP_TABLE][self::SUMMARY_ERROR],
686
                'errorschecktype7' => $final[$course->courseid][area_base::CHECKGROUP_TEXT][self::SUMMARY_ERROR],
687
                'failedchecktype1' => $final[$course->courseid][area_base::CHECKGROUP_FORM][self::SUMMARY_FAILED],
688
                'failedchecktype2' => $final[$course->courseid][area_base::CHECKGROUP_IMAGE][self::SUMMARY_FAILED],
689
                'failedchecktype3' => $final[$course->courseid][area_base::CHECKGROUP_LAYOUT][self::SUMMARY_FAILED],
690
                'failedchecktype4' => $final[$course->courseid][area_base::CHECKGROUP_LINK][self::SUMMARY_FAILED],
691
                'failedchecktype5' => $final[$course->courseid][area_base::CHECKGROUP_MEDIA][self::SUMMARY_FAILED],
692
                'failedchecktype6' => $final[$course->courseid][area_base::CHECKGROUP_TABLE][self::SUMMARY_FAILED],
693
                'failedchecktype7' => $final[$course->courseid][area_base::CHECKGROUP_TEXT][self::SUMMARY_FAILED],
694
                'percentchecktype1' => $final[$course->courseid][area_base::CHECKGROUP_FORM][self::SUMMARY_PERCENT],
695
                'percentchecktype2' => $final[$course->courseid][area_base::CHECKGROUP_IMAGE][self::SUMMARY_PERCENT],
696
                'percentchecktype3' => $final[$course->courseid][area_base::CHECKGROUP_LAYOUT][self::SUMMARY_PERCENT],
697
                'percentchecktype4' => $final[$course->courseid][area_base::CHECKGROUP_LINK][self::SUMMARY_PERCENT],
698
                'percentchecktype5' => $final[$course->courseid][area_base::CHECKGROUP_MEDIA][self::SUMMARY_PERCENT],
699
                'percentchecktype6' => $final[$course->courseid][area_base::CHECKGROUP_TABLE][self::SUMMARY_PERCENT],
700
                'percentchecktype7' => $final[$course->courseid][area_base::CHECKGROUP_TEXT][self::SUMMARY_PERCENT]
701
            ];
702
            $resultid = $DB->get_field(self::DB_SUMMARY, 'id', ['courseid' => $course->courseid]);
703
            if ($resultid) {
704
                $element['id'] = $resultid;
705
                $DB->update_record(self::DB_SUMMARY, (object)$element);
706
                continue;
707
            }
708
            array_push($values, $element);
709
        }
710
 
711
        $DB->insert_records(self::DB_SUMMARY, $values);
712
 
713
        $extrasql = !$courseid ? "WHERE courseid != ?" : "WHERE courseid = ?";
714
        $coursesqlval = !$courseid ? [0] : [$courseid];
715
        // Count of failed errors per check.
716
        $checkssql = "SELECT area.courseid, ".self::STATUS_CHECKED." AS status, res.checkid,
717
                COUNT(res.errorcount) as checkcount, SUM(res.errorcount) AS errorcount
718
                FROM {" . self::DB_AREAS . "} area
719
                INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1
720
                INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id
721
                ".$extrasql." GROUP BY area.courseid, res.checkid";
722
 
723
        $checksresult = $DB->get_recordset_sql($checkssql, $coursesqlval);
724
 
725
        $checkvalues = [];
726
        foreach ($checksresult as $check) {
727
            if ($result = $DB->get_record(self::DB_CACHECHECK, ['courseid' => $check->courseid, 'checkid' => $check->checkid])) {
728
                $check->id = $result->id;
729
                $DB->update_record(self::DB_CACHECHECK, $check);
730
            } else {
731
                array_push($checkvalues, (array)$check);
732
            }
733
        }
734
        $DB->insert_records(self::DB_CACHECHECK, $checkvalues);
735
 
736
        // Count of failed or passed rate per activity.
737
        $activitysql = "SELECT courseid, ".self::STATUS_CHECKED." AS status, area.component,
738
                COUNT(DISTINCT area.contextid) AS totalactivities, 0 AS failedactivities,
739
                COUNT(DISTINCT area.contextid) AS passedactivities, 0 AS errorcount
740
                FROM {" . self::DB_AREAS . "} area
741
                ".$extrasql."
742
                GROUP BY area.courseid, area.component";
743
 
744
        $activityresults = $DB->get_recordset_sql($activitysql, $coursesqlval);
745
 
746
        $activityvalues = [];
747
 
748
        // Count of failed errors per courseid per activity.
749
        $activityfailedsql = "SELECT area.courseid, area.component, area.contextid, SUM(res.errorcount) AS errorcount
750
                FROM {" . self::DB_AREAS . "} area
751
                INNER JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1
752
                INNER JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id
753
                ".$extrasql." AND res.errorcount != 0
754
                GROUP BY area.courseid, area.component, area.contextid";
755
 
756
        $activityfailedresults = $DB->get_recordset_sql($activityfailedsql, $coursesqlval);
757
 
758
        foreach ($activityresults as $activity) {
759
            $tmpkey = $activity->courseid.$activity->component;
760
            $activityvalues[$tmpkey] = $activity;
761
        }
762
 
763
        foreach ($activityfailedresults as $failed) {
764
            $tmpkey = $failed->courseid.$failed->component;
765
            $activityvalues[$tmpkey]->failedactivities ++;
766
            $activityvalues[$tmpkey]->passedactivities --;
767
            $activityvalues[$tmpkey]->errorcount += $failed->errorcount;
768
        }
769
 
770
        $activityvaluespush = [];
771
        foreach ($activityvalues as $value) {
772
            if ($result = $DB->get_record(self::DB_CACHEACTS, ['courseid' => $value->courseid, 'component' => $value->component])) {
773
                $value->id = $result->id;
774
                $DB->update_record(self::DB_CACHEACTS, $value);
775
            } else {
776
                array_push($activityvaluespush, (array)$value);
777
            }
778
        }
779
 
780
        $DB->insert_records(self::DB_CACHEACTS, $activityvaluespush);
781
 
782
        $recordserrored->close();
783
        $recordsfailed->close();
784
        $checksresult->close();
785
        $activityresults->close();
786
        $activityfailedresults->close();
787
    }
788
 
789
    /**
790
     * Get course module summary information for a course.
791
     *
792
     * @param   int $courseid
793
     * @return  \stdClass[]
794
     */
795
    public static function get_cm_summary_for_course(int $courseid): array {
796
        global $DB;
797
 
798
        $sql = "
799
        SELECT
800
            area.cmid,
801
            sum(errorcount) as numerrors,
802
            count(errorcount) as numchecks
803
         FROM {" . self::DB_AREAS . "} area
804
         JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1
805
         JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id
806
        WHERE area.courseid = :courseid AND component != :component
807
     GROUP BY cmid";
808
 
809
        $params = [
810
            'courseid' => $courseid,
811
            'component' => 'core_course',
812
        ];
813
 
814
        return $DB->get_records_sql($sql, $params);
815
    }
816
 
817
    /**
818
     * Get section summary information for a course.
819
     *
820
     * @param   int $courseid
821
     * @return  stdClass[]
822
     */
823
    public static function get_section_summary_for_course(int $courseid): array {
824
        global $DB;
825
 
826
        $sql = "
827
        SELECT
828
            sec.section,
829
            sum(errorcount) AS numerrors,
830
            count(errorcount) as numchecks
831
         FROM {" . self::DB_AREAS . "} area
832
         JOIN {" . self::DB_CONTENT . "} ch ON ch.areaid = area.id AND ch.iscurrent = 1
833
         JOIN {" . self::DB_RESULTS . "} res ON res.contentid = ch.id
834
         JOIN {course_sections} sec ON area.itemid = sec.id
835
        WHERE area.tablename = :tablename AND area.courseid = :courseid
836
     GROUP BY sec.section";
837
 
838
        $params = [
839
            'courseid' => $courseid,
840
            'tablename' => 'course_sections'
841
        ];
842
 
843
        return $DB->get_records_sql($sql, $params);
844
    }
845
}