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
/**
18
 * Class registration
19
 *
20
 * @package    core
21
 * @copyright  2017 Marina Glancy
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
namespace core\hub;
26
defined('MOODLE_INTERNAL') || die();
27
 
28
use moodle_exception;
29
use moodle_url;
30
use context_system;
31
use stdClass;
32
use html_writer;
1441 ariadna 33
use core_plugin_manager;
1 efrain 34
 
35
/**
36
 * Methods to use when registering the site at the moodle sites directory.
37
 *
38
 * @package    core
39
 * @copyright  2017 Marina Glancy
40
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
41
 */
42
class registration {
43
 
44
    /** @var array Fields used in a site registration form.
45
     * IMPORTANT: any new fields with non-empty defaults have to be added to CONFIRM_NEW_FIELDS */
46
    const FORM_FIELDS = ['policyagreed', 'language', 'countrycode', 'privacy',
1441 ariadna 47
        'contactemail', 'emailalert', 'emailalertemail', 'commnews', 'commnewsemail',
48
        'contactname', 'name', 'description', 'imageurl', 'contactphone', 'regioncode',
49
        'geolocation', 'street', 'organisationtype'];
1 efrain 50
 
51
    /** @var array List of new FORM_FIELDS or siteinfo fields added indexed by the version when they were added.
52
     * If site was already registered, admin will be promted to confirm new registration data manually. Until registration is manually confirmed,
53
     * the scheduled task updating registration will be paused.
54
     * Keys of this array are not important as long as they increment, use current date to avoid confusions.
55
     */
56
    const CONFIRM_NEW_FIELDS = [
57
        2017092200 => [
58
            'commnews', // Receive communication news. This was added in 3.4 and is "On" by default. Admin must confirm or opt-out.
59
            'mobileservicesenabled', 'mobilenotificationsenabled', 'registereduserdevices', 'registeredactiveuserdevices' // Mobile stats added in 3.4.
60
        ],
61
        // Analytics stats added in Moodle 3.7.
62
        2019022200 => ['analyticsenabledmodels', 'analyticspredictions', 'analyticsactions', 'analyticsactionsnotuseful'],
63
        // Active users stats added in Moodle 3.9.
64
        2020022600 => ['activeusers', 'activeparticipantnumberaverage'],
65
        // Database type, course date info, site theme, primary auth type added in Moodle 4.2.
66
        2023021700 => ['dbtype', 'coursesnodates', 'sitetheme', 'primaryauthtype'],
1441 ariadna 67
        // Plugin usage added in Moodle 4.5.
68
        2023072300 => ['pluginusage'],
69
        // AI usage added in Moodle 4.5.
70
        2023081200 => ['aiusage'],
1 efrain 71
    ];
72
 
73
    /** @var string Site privacy: not displayed */
74
    const HUB_SITENOTPUBLISHED = 'notdisplayed';
75
 
76
    /** @var string Site privacy: public */
77
    const HUB_SITENAMEPUBLISHED = 'named';
78
 
79
    /** @var string Site privacy: public and global */
80
    const HUB_SITELINKPUBLISHED = 'linked';
81
 
82
    /** @var stdClass cached site registration information */
83
    protected static $registration = null;
84
 
85
    /**
86
     * Get site registration
87
     *
88
     * @param bool $confirmed
89
     * @return stdClass|null
90
     */
91
    protected static function get_registration($confirmed = true) {
92
        global $DB;
93
 
94
        if (self::$registration === null) {
95
            self::$registration = $DB->get_record('registration_hubs', ['huburl' => HUB_MOODLEORGHUBURL]) ?: null;
96
        }
97
 
98
        if (self::$registration && (bool)self::$registration->confirmed == (bool)$confirmed) {
99
            return self::$registration;
100
        }
101
 
102
        return null;
103
    }
104
 
105
    /**
106
     * Same as get_registration except it throws exception if site not registered
107
     *
108
     * @return stdClass
109
     * @throws \moodle_exception
110
     */
111
    public static function require_registration() {
112
        if ($registration = self::get_registration()) {
113
            return $registration;
114
        }
115
        if (has_capability('moodle/site:config', context_system::instance())) {
116
            throw new moodle_exception('registrationwarning', 'admin', new moodle_url('/admin/registration/index.php'));
117
        } else {
118
            throw new moodle_exception('registrationwarningcontactadmin', 'admin');
119
        }
120
    }
121
 
122
    /**
123
     * Checks if site is registered
124
     *
125
     * @return bool
126
     */
127
    public static function is_registered() {
128
        return self::get_registration() ? true : false;
129
    }
130
 
131
    /**
132
     * Returns registration token
133
     *
134
     * @param int $strictness if set to MUST_EXIST and site is not registered will throw an exception
135
     * @return null
136
     * @throws moodle_exception
137
     */
138
    public static function get_token($strictness = IGNORE_MISSING) {
139
        if ($strictness == MUST_EXIST) {
140
            $registration = self::require_registration();
141
        } else if (!$registration = self::get_registration()) {
142
            return null;
143
        }
144
        return $registration->token;
145
    }
146
 
147
    /**
1441 ariadna 148
     * Returns registration secret.
149
     *
150
     * @return string
151
     */
152
    public static function get_secret(): string {
153
        if ($registration = self::get_registration()) {
154
            return $registration->secret;
155
        }
156
        return '';
157
    }
158
 
159
    /**
1 efrain 160
     * When was the registration last updated
161
     *
162
     * @return int|null timestamp or null if site is not registered
163
     */
164
    public static function get_last_updated() {
165
        if ($registration = self::get_registration()) {
166
            return $registration->timemodified;
167
        }
168
        return null;
169
    }
170
 
171
    /**
172
     * Calculates and prepares site information to send to the sites directory as a part of registration.
173
     *
174
     * @param array $defaults default values for inputs in the registration form (if site was never registered before)
175
     * @return array site info
176
     */
177
    public static function get_site_info($defaults = []) {
178
        global $CFG, $DB;
179
        require_once($CFG->libdir . '/badgeslib.php');
180
        require_once($CFG->dirroot . "/course/lib.php");
181
 
182
        $siteinfo = array();
183
        foreach (self::FORM_FIELDS as $field) {
184
            $siteinfo[$field] = get_config('hub', 'site_'.$field);
185
            if ($siteinfo[$field] === false) {
186
                $siteinfo[$field] = array_key_exists($field, $defaults) ? $defaults[$field] : null;
187
            }
188
        }
189
 
190
        // Statistical data.
191
        $siteinfo['courses'] = $DB->count_records('course') - 1;
192
        $siteinfo['users'] = $DB->count_records('user', array('deleted' => 0));
193
        $siteinfo['activeusers'] = $DB->count_records_select('user', 'deleted = ? AND lastlogin > ?', [0, time() - DAYSECS * 30]);
194
        $siteinfo['enrolments'] = $DB->count_records('role_assignments');
195
        $siteinfo['posts'] = $DB->count_records('forum_posts');
196
        $siteinfo['questions'] = $DB->count_records('question');
197
        $siteinfo['resources'] = $DB->count_records('resource');
198
        $siteinfo['badges'] = $DB->count_records_select('badge', 'status <> ' . BADGE_STATUS_ARCHIVED);
199
        $siteinfo['issuedbadges'] = $DB->count_records('badge_issued');
200
        $siteinfo['participantnumberaverage'] = average_number_of_participants();
201
        $siteinfo['activeparticipantnumberaverage'] = average_number_of_participants(true, time() - DAYSECS * 30);
202
        $siteinfo['modulenumberaverage'] = average_number_of_courses_modules();
203
        $siteinfo['dbtype'] = $CFG->dbtype;
204
        $siteinfo['coursesnodates'] = $DB->count_records_select('course', 'enddate = ?', [0]) - 1;
205
        $siteinfo['sitetheme'] = get_config('core', 'theme');
1441 ariadna 206
        $siteinfo['pluginusage'] = json_encode(self::get_plugin_usage_data());
1 efrain 207
 
1441 ariadna 208
        // AI usage data.
209
        $aiusagedata = self::get_ai_usage_data();
210
        $siteinfo['aiusage'] = !empty($aiusagedata) ? json_encode($aiusagedata) : '';
211
 
1 efrain 212
        // Primary auth type.
213
        $primaryauthsql = 'SELECT auth, count(auth) as tc FROM {user} GROUP BY auth ORDER BY tc DESC';
214
        $siteinfo['primaryauthtype'] = $DB->get_field_sql($primaryauthsql, null, IGNORE_MULTIPLE);
215
 
216
        // Version and url.
217
        $siteinfo['moodlerelease'] = $CFG->release;
218
        $siteinfo['url'] = $CFG->wwwroot;
219
 
220
        // Mobile related information.
221
        $siteinfo['mobileservicesenabled'] = 0;
222
        $siteinfo['mobilenotificationsenabled'] = 0;
223
        $siteinfo['registereduserdevices'] = 0;
224
        $siteinfo['registeredactiveuserdevices'] = 0;
225
        if (!empty($CFG->enablewebservices) && !empty($CFG->enablemobilewebservice)) {
226
            $siteinfo['mobileservicesenabled'] = 1;
227
            $siteinfo['registereduserdevices'] = $DB->count_records('user_devices');
228
            $airnotifierextpath = $CFG->dirroot . '/message/output/airnotifier/externallib.php';
229
            if (file_exists($airnotifierextpath)) { // Maybe some one uninstalled the plugin.
230
                require_once($airnotifierextpath);
231
                $siteinfo['mobilenotificationsenabled'] = \message_airnotifier_external::is_system_configured();
232
                $siteinfo['registeredactiveuserdevices'] = $DB->count_records('message_airnotifier_devices', array('enable' => 1));
233
            }
234
        }
235
 
236
        // Analytics related data follow.
237
        $siteinfo['analyticsenabledmodels'] = \core_analytics\stats::enabled_models();
238
        $siteinfo['analyticspredictions'] = \core_analytics\stats::predictions();
239
        $siteinfo['analyticsactions'] = \core_analytics\stats::actions();
240
        $siteinfo['analyticsactionsnotuseful'] = \core_analytics\stats::actions_not_useful();
241
 
242
        // IMPORTANT: any new fields in siteinfo have to be added to the constant CONFIRM_NEW_FIELDS.
243
 
244
        return $siteinfo;
245
    }
246
 
247
    /**
248
     * Human-readable summary of data that will be sent to the sites directory.
249
     *
250
     * @param array $siteinfo result of get_site_info()
251
     * @return string
252
     */
253
    public static function get_stats_summary($siteinfo) {
1441 ariadna 254
        global $OUTPUT;
255
 
1 efrain 256
        $fieldsneedconfirm = self::get_new_registration_fields();
257
        $summary = html_writer::tag('p', get_string('sendfollowinginfo_help', 'hub')) .
258
            html_writer::start_tag('ul');
259
 
260
        $mobileservicesenabled = $siteinfo['mobileservicesenabled'] ? get_string('yes') : get_string('no');
261
        $mobilenotificationsenabled = $siteinfo['mobilenotificationsenabled'] ? get_string('yes') : get_string('no');
262
        $moodlerelease = $siteinfo['moodlerelease'];
263
        if (preg_match('/^(\d+\.\d.*?)[\. ]/', $moodlerelease, $matches)) {
264
            $moodlerelease = $matches[1];
265
        }
1441 ariadna 266
        $pluginusagelinks = [
267
            'overview' => new moodle_url('/admin/plugins.php'),
268
            'activities' => new moodle_url('/admin/modules.php'),
269
            'blocks' => new moodle_url('/admin/blocks.php'),
270
        ];
1 efrain 271
        $senddata = [
272
            'moodlerelease' => get_string('sitereleasenum', 'hub', $moodlerelease),
273
            'courses' => get_string('coursesnumber', 'hub', $siteinfo['courses']),
274
            'users' => get_string('usersnumber', 'hub', $siteinfo['users']),
275
            'activeusers' => get_string('activeusersnumber', 'hub', $siteinfo['activeusers']),
276
            'enrolments' => get_string('roleassignmentsnumber', 'hub', $siteinfo['enrolments']),
277
            'posts' => get_string('postsnumber', 'hub', $siteinfo['posts']),
278
            'questions' => get_string('questionsnumber', 'hub', $siteinfo['questions']),
279
            'resources' => get_string('resourcesnumber', 'hub', $siteinfo['resources']),
280
            'badges' => get_string('badgesnumber', 'hub', $siteinfo['badges']),
281
            'issuedbadges' => get_string('issuedbadgesnumber', 'hub', $siteinfo['issuedbadges']),
282
            'participantnumberaverage' => get_string('participantnumberaverage', 'hub',
283
                format_float($siteinfo['participantnumberaverage'], 2)),
284
            'activeparticipantnumberaverage' => get_string('activeparticipantnumberaverage', 'hub',
285
                format_float($siteinfo['activeparticipantnumberaverage'], 2)),
286
            'modulenumberaverage' => get_string('modulenumberaverage', 'hub',
287
                format_float($siteinfo['modulenumberaverage'], 2)),
288
            'mobileservicesenabled' => get_string('mobileservicesenabled', 'hub', $mobileservicesenabled),
289
            'mobilenotificationsenabled' => get_string('mobilenotificationsenabled', 'hub', $mobilenotificationsenabled),
290
            'registereduserdevices' => get_string('registereduserdevices', 'hub', $siteinfo['registereduserdevices']),
291
            'registeredactiveuserdevices' => get_string('registeredactiveuserdevices', 'hub', $siteinfo['registeredactiveuserdevices']),
292
            'analyticsenabledmodels' => get_string('analyticsenabledmodels', 'hub', $siteinfo['analyticsenabledmodels']),
293
            'analyticspredictions' => get_string('analyticspredictions', 'hub', $siteinfo['analyticspredictions']),
294
            'analyticsactions' => get_string('analyticsactions', 'hub', $siteinfo['analyticsactions']),
295
            'analyticsactionsnotuseful' => get_string('analyticsactionsnotuseful', 'hub', $siteinfo['analyticsactionsnotuseful']),
296
            'dbtype' => get_string('dbtype', 'hub', $siteinfo['dbtype']),
297
            'coursesnodates' => get_string('coursesnodates', 'hub', $siteinfo['coursesnodates']),
298
            'sitetheme' => get_string('sitetheme', 'hub', $siteinfo['sitetheme']),
299
            'primaryauthtype' => get_string('primaryauthtype', 'hub', $siteinfo['primaryauthtype']),
1441 ariadna 300
            'pluginusage' => get_string('pluginusagedata', 'hub', $pluginusagelinks),
301
            'aiusage' => $OUTPUT->render_from_template('core/ai_usage_data', ['aiusagedata' => self::show_ai_usage()]),
1 efrain 302
        ];
303
 
304
        foreach ($senddata as $key => $str) {
305
            $class = in_array($key, $fieldsneedconfirm) ? ' needsconfirmation mark' : '';
306
            $summary .= html_writer::tag('li', $str, ['class' => 'site' . $key . $class]);
307
        }
308
        $summary .= html_writer::end_tag('ul');
309
        return $summary;
310
    }
311
 
312
    /**
313
     * Save registration info locally so it can be retrieved when registration needs to be updated
314
     *
315
     * @param stdClass $formdata data from {@link site_registration_form}
316
     */
317
    public static function save_site_info($formdata) {
318
        foreach (self::FORM_FIELDS as $field) {
319
            set_config('site_' . $field, $formdata->$field, 'hub');
320
        }
321
        // Even if the connection with the sites directory fails, admin has manually submitted the form which means they don't need
322
        // to be redirected to the site registration page any more.
323
        set_config('site_regupdateversion', max(array_keys(self::CONFIRM_NEW_FIELDS)), 'hub');
324
    }
325
 
326
    /**
327
     * Updates site registration when "Update reigstration" button is clicked by admin
328
     */
329
    public static function update_manual() {
330
        global $DB;
331
 
332
        if (!$registration = self::get_registration()) {
333
            return false;
334
        }
335
 
336
        $siteinfo = self::get_site_info();
337
        try {
338
            api::update_registration($siteinfo);
339
        } catch (moodle_exception $e) {
340
            if (!self::is_registered()) {
341
                // Token was rejected during registration update and site and locally stored token was reset,
342
                // proceed to site registration. This method will redirect away.
343
                self::register('');
344
            }
345
            \core\notification::add(get_string('errorregistrationupdate', 'hub', $e->getMessage()),
346
                \core\output\notification::NOTIFY_ERROR);
347
            return false;
348
        }
349
        $DB->update_record('registration_hubs', ['id' => $registration->id, 'timemodified' => time()]);
350
        \core\notification::add(get_string('siteregistrationupdated', 'hub'),
351
            \core\output\notification::NOTIFY_SUCCESS);
352
        self::$registration = null;
353
        return true;
354
    }
355
 
356
    /**
357
     * Updates site registration via cron
358
     *
359
     * @throws moodle_exception
360
     */
361
    public static function update_cron() {
362
        global $DB;
363
 
364
        if (!$registration = self::get_registration()) {
365
            mtrace(get_string('registrationwarning', 'admin'));
366
            return;
367
        }
368
 
369
        if (self::get_new_registration_fields()) {
370
            mtrace(get_string('pleaserefreshregistrationnewdata', 'admin'));
371
            return;
372
        }
373
 
374
        $siteinfo = self::get_site_info();
375
        api::update_registration($siteinfo);
376
        $DB->update_record('registration_hubs', ['id' => $registration->id, 'timemodified' => time()]);
377
        mtrace(get_string('siteregistrationupdated', 'hub'));
378
        self::$registration = null;
379
    }
380
 
381
    /**
382
     * Confirms registration by the sites directory.
383
     *
384
     * @param string $token
385
     * @param string $newtoken
386
     * @param string $hubname
387
     * @throws moodle_exception
388
     */
389
    public static function confirm_registration($token, $newtoken, $hubname) {
390
        global $DB;
391
 
392
        $registration = self::get_registration(false);
393
        if (!$registration || $registration->token !== $token) {
394
            throw new moodle_exception('wrongtoken', 'hub', new moodle_url('/admin/registration/index.php'));
395
        }
1441 ariadna 396
 
397
        // Update hub information of the site.
1 efrain 398
        $record = ['id' => $registration->id];
399
        $record['token'] = $newtoken;
400
        $record['confirmed'] = 1;
401
        $record['hubname'] = $hubname;
402
        $record['timemodified'] = time();
403
        $DB->update_record('registration_hubs', $record);
404
        self::$registration = null;
405
 
406
        $siteinfo = self::get_site_info();
407
        if (strlen(http_build_query($siteinfo)) > 1800) {
408
            // Update registration again because the initial request was too long and could have been truncated.
409
            api::update_registration($siteinfo);
410
            self::$registration = null;
411
        }
412
 
413
        // Finally, allow other plugins to perform actions once a site is registered for first time.
414
        $pluginsfunction = get_plugins_with_function('post_site_registration_confirmed');
415
        foreach ($pluginsfunction as $plugins) {
416
            foreach ($plugins as $pluginfunction) {
417
                $pluginfunction($registration->id);
418
            }
419
        }
420
    }
421
 
422
    /**
423
     * Retrieve the options for site privacy form element to use in registration form
424
     * @return array
425
     */
426
    public static function site_privacy_options() {
427
        return [
428
            self::HUB_SITENOTPUBLISHED => get_string('siteprivacynotpublished', 'hub'),
429
            self::HUB_SITENAMEPUBLISHED => get_string('siteprivacypublished', 'hub'),
430
            self::HUB_SITELINKPUBLISHED => get_string('siteprivacylinked', 'hub')
431
        ];
432
    }
433
 
434
    /**
1441 ariadna 435
     * Get the options for organisation type form element to use in registration form.
436
     *
437
     * Indexes reference Moodle internal ids and should not be changed.
438
     *
439
     * @return array
440
     */
441
    public static function get_site_organisation_type_options(): array {
442
        return [
443
            1 => get_string('siteorganisationtype:wholeuniversity', 'hub'),
444
            2 => get_string('siteorganisationtype:universitydepartment', 'hub'),
445
            3 => get_string('siteorganisationtype:college', 'hub'),
446
            4 => get_string('siteorganisationtype:collegedepartment', 'hub'),
447
            5 => get_string('siteorganisationtype:highschool', 'hub'),
448
            6 => get_string('siteorganisationtype:highschooldepartment', 'hub'),
449
            7 => get_string('siteorganisationtype:primaryschool', 'hub'),
450
            8 => get_string('siteorganisationtype:independentteacher', 'hub'),
451
            9 => get_string('siteorganisationtype:companyinternal', 'hub'),
452
            10 => get_string('siteorganisationtype:companydepartment', 'hub'),
453
            11 => get_string('siteorganisationtype:commercialcourseprovider', 'hub'),
454
            12 => get_string('siteorganisationtype:other', 'hub'),
455
            13 => get_string('siteorganisationtype:highschooldistrict', 'hub'),
456
            14 => get_string('siteorganisationtype:government', 'hub'),
457
            16 => get_string('siteorganisationtype:charityornotforprofit', 'hub'),
458
            17 => get_string('siteorganisationtype:charterschool', 'hub'),
459
            18 => get_string('siteorganisationtype:schooldistrict', 'hub'),
460
            19 => get_string('siteorganisationtype:hospital', 'hub'),
461
        ];
462
    }
463
 
464
    /**
1 efrain 465
     * Registers a site
466
     *
467
     * This method will make sure that unconfirmed registration record is created and then redirect to
468
     * registration script on the sites directory.
469
     * The sites directory will check that the site is accessible, register it and redirect back
470
     * to /admin/registration/confirmregistration.php
471
     *
472
     * @param string $returnurl
473
     * @throws \coding_exception
474
     */
475
    public static function register($returnurl) {
476
        global $DB, $SESSION;
477
 
1441 ariadna 478
        // We should also check if the url is registered in the hub.
479
        if (self::is_registered() && api::is_site_registered_in_hub()) {
1 efrain 480
            // Caller of this method must make sure that site is not registered.
481
            throw new \coding_exception('Site already registered');
482
        }
483
 
1441 ariadna 484
        // Delete 'confirmed' registrations.
485
        $DB->delete_records('registration_hubs', ['confirmed' => 1]);
486
 
487
        // Get 'unconfirmed' registration.
1 efrain 488
        $hub = self::get_registration(false);
489
        if (empty($hub)) {
490
            // Create a new record in 'registration_hubs'.
491
            $hub = new stdClass();
1441 ariadna 492
            // Let's add date('Ymdhis') to make the token unique.
493
            $hub->token = get_site_identifier() . date('Ymdhis');
494
            // Secret is identical to token until registration confirmed (confirmregistration.php).
1 efrain 495
            $hub->secret = $hub->token;
496
            $hub->huburl = HUB_MOODLEORGHUBURL;
497
            $hub->hubname = 'moodle';
498
            $hub->confirmed = 0;
499
            $hub->timemodified = time();
500
            $hub->id = $DB->insert_record('registration_hubs', $hub);
501
            self::$registration = null;
502
        }
503
 
504
        $params = self::get_site_info();
505
 
506
        // The most conservative limit for the redirect URL length is 2000 characters. Only pass parameters before
507
        // we reach this limit. The next registration update will update all fields.
508
        // We will also update registration after we receive confirmation from moodle.net.
509
        $url = new moodle_url(HUB_MOODLEORGHUBURL . '/local/hub/siteregistration.php',
510
            ['token' => $hub->token, 'url' => $params['url']]);
511
        foreach ($params as $key => $value) {
512
            if (strlen($url->out(false, [$key => $value])) > 2000) {
513
                break;
514
            }
515
            $url->param($key, $value);
516
        }
517
 
518
        $SESSION->registrationredirect = $returnurl;
519
        redirect($url);
520
    }
521
 
522
    /**
523
     * Unregister site
524
     *
525
     * @param bool $unpublishalladvertisedcourses
526
     * @param bool $unpublishalluploadedcourses
527
     * @return bool
528
     */
529
    public static function unregister($unpublishalladvertisedcourses, $unpublishalluploadedcourses) {
530
        global $DB;
531
 
532
        if (!$hub = self::get_registration()) {
533
            return true;
534
        }
535
 
536
        // Course unpublish went ok, unregister the site now.
537
        try {
538
            api::unregister_site();
539
        } catch (moodle_exception $e) {
540
            \core\notification::add(get_string('unregistrationerror', 'hub', $e->getMessage()),
541
                \core\output\notification::NOTIFY_ERROR);
542
            return false;
543
        }
544
 
545
        $DB->delete_records('registration_hubs', array('id' => $hub->id));
546
        self::$registration = null;
547
        return true;
548
    }
549
 
550
    /**
551
     * Resets the registration token without changing site identifier so site can be re-registered
552
     *
553
     * @return bool
554
     */
555
    public static function reset_token() {
556
        global $DB;
557
        if (!$hub = self::get_registration()) {
558
            return true;
559
        }
560
        $DB->delete_records('registration_hubs', array('id' => $hub->id));
561
        self::$registration = null;
562
    }
563
 
564
    /**
565
     * Generate a new token for the site that is not registered
566
     *
567
     * @param string $token
568
     * @throws moodle_exception
569
     */
570
    public static function reset_site_identifier($token) {
571
        global $DB, $CFG;
572
 
573
        $registration = self::get_registration(false);
574
        if (!$registration || $registration->token != $token) {
575
            throw new moodle_exception('wrongtoken', 'hub',
576
               new moodle_url('/admin/registration/index.php'));
577
        }
578
 
579
        $DB->delete_records('registration_hubs', array('id' => $registration->id));
580
        self::$registration = null;
581
 
582
        $CFG->siteidentifier = null;
583
        get_site_identifier();
584
    }
585
 
586
    /**
587
     * Returns information about the sites directory.
588
     *
589
     * Example of the return array:
590
     * {
591
     *     "courses": 384,
592
     *     "description": "Official moodle sites directory",
593
     *     "downloadablecourses": 0,
594
     *     "enrollablecourses": 0,
595
     *     "hublogo": 1,
596
     *     "language": "en",
597
     *     "name": "moodle",
598
     *     "sites": 274175,
599
     *     "url": "https://stats.moodle.org",
600
     *     "imgurl": "https://stats.moodle.org/local/hub/webservice/download.php?filetype=hubscreenshot"
601
     * }
602
     *
603
     * @return array|null
604
     */
605
    public static function get_moodlenet_info() {
606
        try {
607
            return api::get_hub_info();
608
        } catch (moodle_exception $e) {
609
            // Ignore error, we only need it for displaying information about the sites directory.
610
            // If this request fails, it's not a big deal.
611
            return null;
612
        }
613
    }
614
 
615
    /**
616
     * Does admin need to be redirected to the registration page after install?
617
     *
618
     * @param bool|null $markasviewed if set to true will mark the registration form as viewed and admin will not be redirected
619
     *     to the registration form again (regardless of whether the site was registered or not).
620
     * @return bool
621
     */
622
    public static function show_after_install($markasviewed = null) {
623
        global $CFG;
624
        if (self::is_registered()) {
625
            $showregistration = false;
626
            $markasviewed = true;
627
        } else {
628
            $showregistration = !empty($CFG->registrationpending);
629
            if ($showregistration && !site_is_public()) {
630
                // If it's not a public site, don't redirect to registration, it won't work anyway.
631
                $showregistration = false;
632
                $markasviewed = true;
633
            }
634
        }
635
        if ($markasviewed !== null) {
636
            set_config('registrationpending', !$markasviewed);
637
        }
638
        return $showregistration;
639
    }
640
 
641
    /**
642
     * Returns the list of the fields in the registration form that were added since registration or last manual update
643
     *
644
     * If this list is not empty the scheduled task will be paused and admin will be reminded to update registration manually.
645
     *
646
     * @return array
647
     */
648
    public static function get_new_registration_fields() {
649
        $fieldsneedconfirm = [];
650
        if (!self::is_registered()) {
651
            // Nothing to update if site is not registered.
652
            return $fieldsneedconfirm;
653
        }
654
 
655
        $lastupdated = (int)get_config('hub', 'site_regupdateversion');
656
        foreach (self::CONFIRM_NEW_FIELDS as $version => $fields) {
657
            if ($version > $lastupdated) {
658
                $fieldsneedconfirm = array_merge($fieldsneedconfirm, $fields);
659
            }
660
        }
661
        return $fieldsneedconfirm;
662
    }
663
 
664
    /**
665
     * Redirect to the site registration form if it's a new install, upgrade or registration needs updating.
666
     *
667
     * @param string|moodle_url $url
668
     */
669
    public static function registration_reminder($url) {
670
        if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
671
            // No redirection during behat runs.
672
            return;
673
        }
674
        if (!has_capability('moodle/site:config', context_system::instance())) {
675
            return;
676
        }
1441 ariadna 677
        if (
678
            site_is_public() &&
679
            (self::show_after_install() || self::get_new_registration_fields())
680
        ) {
1 efrain 681
            $returnurl = new moodle_url($url);
682
            redirect(new moodle_url('/admin/registration/index.php', ['returnurl' => $returnurl->out_as_local_url(false)]));
683
        }
684
    }
1441 ariadna 685
 
686
    /**
687
     * Return a list of plugins.
688
     *
689
     * Only blocks and activities will include instance counts.
690
     *
691
     * @return array
692
     */
693
    public static function get_plugin_usage_data(): array {
694
        global $DB;
695
 
696
        $pluginman = core_plugin_manager::instance();
697
        $plugininfo = $pluginman->get_plugins();
698
        $data = [];
699
 
700
        foreach ($plugininfo as $plugins) {
701
            foreach ($plugins as $plugin) {
702
                // Plugins are considered enabled if $plugin->is_enabled() returns true or null.
703
                // Plugins that return null cannot be disabled.
704
                $enabled = ($plugin->is_enabled() || is_null($plugin->is_enabled()));
705
                $data[$plugin->type][$plugin->name]['enabled'] = $enabled ? 1 : 0;
706
 
707
                if ($plugin->type === 'mod') {
708
                    $mid = $DB->get_field('modules', 'id', ['name' => $plugin->name]);
709
                    $count = $DB->count_records('course_modules', ['module' => $mid]);
710
                    $data[$plugin->type][$plugin->name]['count'] = $count;
711
 
712
                } else if ($plugin->type === 'block') {
713
                    $count = $DB->count_records('block_instances', ['blockname' => $plugin->name]);
714
                    $data[$plugin->type][$plugin->name]['count'] = $count;
715
                }
716
            }
717
        }
718
 
719
        return $data;
720
    }
721
 
722
    /**
723
     * Get the time range to use in collected and reporting AI usage data.
724
     *
725
     * @param bool $format Use true to format timestamp.
726
     * @return array
727
     */
728
    private static function get_ai_usage_time_range(bool $format = false): array {
729
        global $DB;
730
 
731
        // We will try and use the last time this site was last registered for our 'from' time.
732
        // Otherwise, default to using one week's worth of data to roughly match the site rego scheduled task.
733
        $timenow = \core\di::get(\core\clock::class)->time();
734
        $defaultfrom = $timenow - WEEKSECS;
735
        $timeto = $timenow;
736
        $params = [
737
            'huburl' => HUB_MOODLEORGHUBURL,
738
            'confirmed' => 1,
739
        ];
740
        $lastregistered = $DB->get_field('registration_hubs', 'timemodified', $params);
741
        $timefrom = $lastregistered ? (int)$lastregistered : $defaultfrom;
742
 
743
        if ($format) {
744
            $timefrom = userdate($timefrom);
745
            $timeto = userdate($timeto);
746
        }
747
 
748
        return [
749
            'timefrom' => $timefrom,
750
            'timeto' => $timeto,
751
        ];
752
    }
753
 
754
    /**
755
     * Displays AI usage data for all providers.
756
     *
757
     * @return array Array containing usage data, grouped by provider
758
     */
759
    public static function show_ai_usage(): array {
760
        // Initialize aiusage collection.
761
        $aiusage = [];
762
 
763
        // Process each provider's data.
764
        foreach (self::get_ai_usage_data() as $provider => $actions) {
765
            if ($provider === 'time_range') {
766
                $aiusage['timerange'] = [
767
                    'label' => get_string($provider, 'hub'),
768
                    'values' => self::format_ai_usage_actions($actions),
769
                ];
770
            } else {
771
                // Initialize provider data structure.
772
                $aiusage['providers'][] = [
773
                    'providername' => get_string('pluginname', $provider),
774
                    'aiactions' => self::format_ai_usage_actions($actions),
775
                ];
776
            }
777
        }
778
 
779
        return $aiusage;
780
    }
781
 
782
    /**
783
     * Formats individual actions for a provider.
784
     *
785
     * @param array $actions Raw actions data
786
     * @return array Formatted action data
787
     */
788
    private static function format_ai_usage_actions(array $actions): array {
789
        $formattedactions = [];
790
 
791
        foreach ($actions as $action => $values) {
792
            if (in_array($action, ['timefrom', 'timeto'])) {
793
                $formattedactions[] = get_string($action, 'hub', userdate($values));
794
            } else {
795
                $formattedactions[] = [
796
                    'actionname' => get_string("action_$action", 'core_ai'),
797
                    'aiactionvalues' => self::format_ai_usage_action_values($values),
798
                ];
799
            }
800
        }
801
 
802
        return $formattedactions;
803
    }
804
 
805
    /**
806
     * Formats action values into formatted strings.
807
     *
808
     * @param array $values Action values to format
809
     * @return array Formatted action values
810
     */
811
    private static function format_ai_usage_action_values(array $values): array {
812
        $formattedvalues = [];
813
 
814
        foreach ($values as $key => $value) {
815
            if (get_string_manager()->string_exists($key, 'hub')) {
816
                if ($key === 'models') {
817
                    $formattedvalues[] = [
818
                        'label' => get_string($key, 'hub'),
819
                        'models' => self::format_ai_usage_model_values($value),
820
                    ];
821
                } else {
822
                    $formattedvalues[]['values'] = get_string($key, 'hub', $value);
823
                }
824
            }
825
        }
826
 
827
        return $formattedvalues;
828
    }
829
 
830
    /**
831
     * Formats model values with their counts.
832
     *
833
     * @param array $values Formatted model values
834
     */
835
    private static function format_ai_usage_model_values(array $values): array {
836
        $modelvalues = [];
837
 
838
        foreach ($values as $model => $count) {
839
            $modelvalues[] = "$model ($count[count])";
840
        }
841
 
842
        return $modelvalues;
843
    }
844
 
845
    /**
846
     * Get AI usage data.
847
     *
848
     * @return array
849
     */
850
    public static function get_ai_usage_data(): array {
851
        global $DB;
852
 
853
        $params = self::get_ai_usage_time_range();
854
 
855
        $sql = "SELECT aar.*
856
                  FROM {ai_action_register} aar
857
                 WHERE aar.timecompleted >= :timefrom
858
                   AND aar.timecompleted <= :timeto";
859
 
860
        $actions = $DB->get_records_sql($sql, $params);
861
 
862
        // Build data for site info reporting.
863
        $data = [];
864
 
865
        foreach ($actions as $action) {
866
            $provider = $action->provider;
867
            $actionname = $action->actionname;
868
 
869
            // Initialise data structure.
870
            if (!isset($data[$provider][$actionname])) {
871
                $data[$provider][$actionname] = [
872
                    'success_count' => 0,
873
                    'fail_count' => 0,
874
                    'times' => [],
875
                    'errors' => [],
876
                    'modelstemp' => [],
877
                ];
878
            }
879
 
880
            if ($action->success === '1') {
881
                $data[$provider][$actionname]['success_count'] += 1;
882
                // Collect AI processing times for averaging.
883
                $data[$provider][$actionname]['times'][] = (int)$action->timecompleted - (int)$action->timecreated;
884
 
885
            } else {
886
                $data[$provider][$actionname]['fail_count'] += 1;
887
                // Collect errors for determing the predominant one.
888
                $data[$provider][$actionname]['errors'][] = $action->errorcode;
889
            }
890
 
891
            // Collect models used and identify unknown ones.
892
            $model = $action->model ?? 'unknown';
893
            $data[$provider][$actionname]['modelstemp'][] = $model;
894
        }
895
 
896
        // Parse the errors, average the times, count the models and then add them to the data.
897
        foreach ($data as $p => $provider) {
898
            foreach ($provider as $a => $actionname) {
899
                if (isset($data[$p][$a]['errors'])) {
900
                    // Create an array with the error codes counted.
901
                    $errors = array_count_values($data[$p][$a]['errors']);
902
                    if (!empty($errors)) {
903
                        // Sort values descending and convert to an array of error codes (most predominant will be at start).
904
                        arsort($errors);
905
                        $errors = array_keys($errors);
906
                        $data[$p][$a]['predominant_error'] = $errors[0];
907
                    }
908
                    unset($data[$p][$a]['errors']);
909
                }
910
 
911
                if (isset($data[$p][$a]['times'])) {
912
                    $count = count($data[$p][$a]['times']);
913
                    if ($count > 0) {
914
                        // Average the time to perform the action (seconds).
915
                        $totaltime = array_sum($data[$p][$a]['times']);
916
                        $data[$p][$a]['average_time'] = round($totaltime / $count);
917
 
918
                    }
919
                }
920
                unset($data[$p][$a]['times']);
921
 
922
                if (isset($data[$p][$a]['modelstemp'])) {
923
                    // Create an array with the models counted.
924
                    $countedmodels = array_count_values($data[$p][$a]['modelstemp']);
925
                    foreach ($countedmodels as $model => $count) {
926
                        $data[$p][$a]['models'][$model]['count'] = $count;
927
                    }
928
                }
929
                unset($data[$p][$a]['modelstemp']);
930
            }
931
        }
932
 
933
        // Include the time range used to help interpret the data.
934
        if (!empty($data)) {
935
            $data['time_range'] = $params;
936
        }
937
 
938
        return $data;
939
    }
1 efrain 940
}