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 for Moodle Mobile tools.
19
 *
20
 * @package    tool_mobile
21
 * @copyright  2016 Juan Leyva
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 * @since      Moodle 3.1
24
 */
25
namespace tool_mobile;
26
 
27
use core_component;
28
use core_plugin_manager;
29
use context_system;
30
use moodle_url;
31
use moodle_exception;
32
use lang_string;
33
use curl;
34
use core_qrcode;
35
use stdClass;
36
 
37
/**
38
 * API exposed by tool_mobile, to be used mostly by external functions and the plugin settings.
39
 *
40
 * @copyright  2016 Juan Leyva
41
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 * @since      Moodle 3.1
43
 */
44
class api {
45
 
46
    /** @var int to identify the login via app. */
47
    const LOGIN_VIA_APP = 1;
48
    /** @var int to identify the login via browser. */
49
    const LOGIN_VIA_BROWSER = 2;
50
    /** @var int to identify the login via an embedded browser. */
51
    const LOGIN_VIA_EMBEDDED_BROWSER = 3;
52
    /** @var int seconds an auto-login key will expire. */
53
    const LOGIN_KEY_TTL = 60;
54
    /** @var string URL of the Moodle Apps Portal */
55
    const MOODLE_APPS_PORTAL_URL = 'https://apps.moodle.com';
56
    /** @var int default value in seconds a QR login key will expire. */
57
    const LOGIN_QR_KEY_TTL = 600;
58
    /** @var int QR code disabled value */
59
    const QR_CODE_DISABLED = 0;
60
    /** @var int QR code type URL value */
61
    const QR_CODE_URL = 1;
62
    /** @var int QR code type login value */
63
    const QR_CODE_LOGIN = 2;
64
    /** @var string Default Android app id */
65
    const DEFAULT_ANDROID_APP_ID = 'com.moodle.moodlemobile';
66
    /** @var string Default iOS app id */
67
    const DEFAULT_IOS_APP_ID = '633359593';
68
    /** @var int AUTOLOGOUT disabled value */
69
    const AUTOLOGOUT_DISABLED = 0;
70
    /** @var int AUTOLOGOUT type inmediate value */
71
    const AUTOLOGOUT_INMEDIATE = 1;
72
    /** @var int AUTOLOGOUT type custom value */
73
    const AUTOLOGOUT_CUSTOM = 2;
74
 
75
    /**
76
     * Returns a list of Moodle plugins supporting the mobile app.
77
     *
78
     * @return array an array of objects containing the plugin information
79
     */
80
    public static function get_plugins_supporting_mobile() {
81
        global $CFG;
82
        require_once($CFG->libdir . '/adminlib.php');
83
 
84
        $cachekey = 'mobileplugins';
85
        if (!isloggedin()) {
86
            $cachekey = 'authmobileplugins';    // Use a different cache for not logged users.
87
        }
88
 
89
        // Check if we can return this from cache.
90
        $cache = \cache::make('tool_mobile', 'plugininfo');
91
        $pluginsinfo = $cache->get($cachekey);
92
        if ($pluginsinfo !== false) {
93
            return (array)$pluginsinfo;
94
        }
95
 
96
        $pluginsinfo = [];
97
        // For not logged users return only auth plugins.
98
        // This is to avoid anyone (not being a registered user) to obtain and download all the site remote add-ons.
99
        if (!isloggedin()) {
100
            $plugintypes = array('auth' => $CFG->dirroot.'/auth');
101
        } else {
102
            $plugintypes = core_component::get_plugin_types();
103
        }
104
 
105
        foreach ($plugintypes as $plugintype => $unused) {
106
            // We need to include files here.
107
            $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
108
            foreach ($pluginswithfile as $plugin => $notused) {
109
                $path = core_component::get_plugin_directory($plugintype, $plugin);
110
                $component = $plugintype . '_' . $plugin;
111
                $version = get_component_version($component);
112
 
113
                require("$path/db/mobile.php");
114
                foreach ($addons as $addonname => $addoninfo) {
115
 
116
                    // Add handlers (for site add-ons).
117
                    $handlers = !empty($addoninfo['handlers']) ? $addoninfo['handlers'] : array();
118
                    $handlers = json_encode($handlers); // JSON formatted, since it is a complex structure that may vary over time.
119
 
120
                    // Now language strings used by the app.
121
                    $lang = array();
122
                    if (!empty($addoninfo['lang'])) {
123
                        $stringmanager = get_string_manager();
124
                        $langs = $stringmanager->get_list_of_translations(true);
125
                        foreach ($langs as $langid => $langname) {
126
                            foreach ($addoninfo['lang'] as $stringinfo) {
127
                                $lang[$langid][$stringinfo[0]] = $stringmanager->get_string(
128
                                    $stringinfo[0],
129
                                    $stringinfo[1] ?? '',
130
                                    null,
131
                                    $langid,
132
                                );
133
                            }
134
                        }
135
                    }
136
                    $lang = json_encode($lang);
137
 
138
                    $plugininfo = array(
139
                        'component' => $component,
140
                        'version' => $version,
141
                        'addon' => $addonname,
142
                        'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
143
                        'fileurl' => '',
144
                        'filehash' => '',
145
                        'filesize' => 0,
146
                        'handlers' => $handlers,
147
                        'lang' => $lang,
148
                    );
149
 
150
                    // All the mobile packages must be under the plugin mobile directory.
151
                    $package = $path . '/mobile/' . $addonname . '.zip';
152
                    if (file_exists($package)) {
153
                        $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
154
                        $plugininfo['filehash'] = sha1_file($package);
155
                        $plugininfo['filesize'] = filesize($package);
156
                    }
157
                    $pluginsinfo[] = $plugininfo;
158
                }
159
            }
160
        }
161
 
162
        $cache->set($cachekey, $pluginsinfo);
163
 
164
        return $pluginsinfo;
165
    }
166
 
167
    /**
168
     * Returns a list of the site public settings, those not requiring authentication.
169
     *
170
     * @return array with the settings and warnings
171
     */
172
    public static function get_public_config() {
173
        global $CFG, $SITE, $PAGE, $OUTPUT;
174
        require_once($CFG->libdir . '/authlib.php');
175
 
176
        $context = context_system::instance();
177
        // We need this to make work the format text functions.
178
        $PAGE->set_context($context);
179
 
180
        // Check if contacting site support is available to all visitors.
181
        $sitesupportavailable = (isset($CFG->supportavailability) && $CFG->supportavailability == CONTACT_SUPPORT_ANYONE);
182
 
183
        [$authinstructions] = \core_external\util::format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
184
        [$maintenancemessage] = \core_external\util::format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
185
        $settings = array(
186
            'wwwroot' => $CFG->wwwroot,
187
            'httpswwwroot' => $CFG->wwwroot,
188
            'sitename' => \core_external\util::format_string($SITE->fullname, $context->id, true),
189
            'guestlogin' => $CFG->guestloginbutton,
190
            'rememberusername' => $CFG->rememberusername,
191
            'authloginviaemail' => $CFG->authloginviaemail,
192
            'registerauth' => $CFG->registerauth,
193
            'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
194
            'authinstructions' => $authinstructions,
195
            'authnoneenabled' => (int) is_enabled_auth('none'),
196
            'enablewebservices' => $CFG->enablewebservices,
197
            'enablemobilewebservice' => $CFG->enablemobilewebservice,
198
            'maintenanceenabled' => $CFG->maintenance_enabled,
199
            'maintenancemessage' => $maintenancemessage,
200
            'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
201
            'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
202
            'country' => clean_param($CFG->country, PARAM_NOTAGS),
203
            'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
204
            'autolang' => $CFG->autolang,
205
            'lang' => clean_param($CFG->lang, PARAM_LANG),  // Avoid breaking WS because of incorrect package langs.
206
            'langmenu' => $CFG->langmenu,
207
            'langlist' => $CFG->langlist,
208
            'locale' => $CFG->locale,
209
            'tool_mobile_minimumversion' => get_config('tool_mobile', 'minimumversion'),
210
            'tool_mobile_iosappid' => get_config('tool_mobile', 'iosappid'),
211
            'tool_mobile_androidappid' => get_config('tool_mobile', 'androidappid'),
212
            'tool_mobile_setuplink' => clean_param(get_config('tool_mobile', 'setuplink'), PARAM_URL),
213
            'tool_mobile_qrcodetype' => clean_param(get_config('tool_mobile', 'qrcodetype'), PARAM_INT),
214
            'supportpage' => $sitesupportavailable ? clean_param($CFG->supportpage, PARAM_URL) : '',
215
            'supportavailability' => clean_param($CFG->supportavailability, PARAM_INT),
1441 ariadna 216
            'showloginform' => (int) get_config('core', 'showloginform'),
1 efrain 217
        );
218
 
219
        $typeoflogin = get_config('tool_mobile', 'typeoflogin');
220
        // Not found, edge case.
221
        if ($typeoflogin === false) {
222
            $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
223
        }
224
        $settings['typeoflogin'] = $typeoflogin;
225
 
226
        // Check if the user can sign-up to return the launch URL in that case.
227
        $cansignup = signup_is_enabled();
228
 
229
        $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
230
        $settings['launchurl'] = $url->out(false);
231
 
232
        // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
233
        if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
234
            $settings['logourl'] = clean_param($logourl->out(false), PARAM_URL);
235
        }
236
        if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
237
            $settings['compactlogourl'] = clean_param($compactlogourl->out(false), PARAM_URL);
238
        }
239
 
240
        // Identity providers.
241
        $authsequence = get_enabled_auth_plugins();
242
        $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
243
        $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
244
        if (!empty($identityprovidersdata)) {
245
            $settings['identityproviders'] = $identityprovidersdata;
246
            // Clean URLs to avoid breaking Web Services.
247
            // We can't do it in prepare_identity_providers_for_output() because it may break the web output.
248
            foreach ($settings['identityproviders'] as &$ip) {
249
                $ip['url'] = (!empty($ip['url'])) ? clean_param($ip['url'], PARAM_URL) : '';
250
                $ip['iconurl'] = (!empty($ip['iconurl'])) ? clean_param($ip['iconurl'], PARAM_URL) : '';
251
            }
252
        }
253
 
254
        // If age is verified or support is available to all visitors, also return the admin contact details.
255
        if ($settings['agedigitalconsentverification'] || $sitesupportavailable) {
256
            $settings['supportname'] = clean_param($CFG->supportname, PARAM_NOTAGS);
257
            $settings['supportemail'] = clean_param($CFG->supportemail, PARAM_EMAIL);
258
        }
259
 
260
        return $settings;
261
    }
262
 
263
    /**
264
     * Returns a list of site configurations, filtering by section.
265
     *
266
     * @param  string $section section name
267
     * @return stdClass object containing the settings
268
     */
269
    public static function get_config($section) {
270
        global $CFG, $SITE;
271
 
272
        $settings = new \stdClass;
273
        $context = context_system::instance();
274
        $isadmin = has_capability('moodle/site:config', $context);
275
 
276
        if (empty($section) or $section == 'frontpagesettings') {
277
            require_once($CFG->dirroot . '/course/format/lib.php');
278
            // First settings that anyone can deduce.
279
            $settings->fullname = \core_external\util::format_string($SITE->fullname, $context->id);
280
            $settings->shortname = \core_external\util::format_string($SITE->shortname, $context->id);
281
 
282
            // Return to a var instead of directly to $settings object because of differences between
283
            // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
284
            $formattedsummary = \core_external\util::format_text($SITE->summary, $SITE->summaryformat,
285
                                                                                        $context->id);
286
            $settings->summary = $formattedsummary[0];
287
            $settings->summaryformat = $formattedsummary[1];
288
            $settings->frontpage = $CFG->frontpage;
289
            $settings->frontpageloggedin = $CFG->frontpageloggedin;
290
            $settings->maxcategorydepth = $CFG->maxcategorydepth;
291
            $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
292
            $settings->numsections = course_get_format($SITE)->get_last_section_number();
293
            $settings->newsitems = $SITE->newsitems;
294
            $settings->commentsperpage = $CFG->commentsperpage;
295
 
296
            // Now, admin settings.
297
            if ($isadmin) {
298
                $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
299
            }
300
        }
301
 
302
        if (empty($section) or $section == 'sitepolicies') {
303
            $manager = new \core_privacy\local\sitepolicy\manager();
304
            $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
305
            $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
306
            $settings->disableuserimages = $CFG->disableuserimages;
307
        }
308
 
309
        if (empty($section) or $section == 'gradessettings') {
310
            require_once($CFG->dirroot . '/user/lib.php');
311
            $settings->mygradesurl = user_mygrades_url();
312
            // The previous function may return moodle_url instances or plain string URLs.
313
            if ($settings->mygradesurl instanceof moodle_url) {
314
                $settings->mygradesurl = $settings->mygradesurl->out(false);
315
            }
316
        }
317
 
318
        if (empty($section) or $section == 'mobileapp') {
319
            $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
320
            $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
321
            $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
322
            $settings->tool_mobile_filetypeexclusionlist = get_config('tool_mobile', 'filetypeexclusionlist');
1441 ariadna 323
            $custommenuitems = get_config('tool_mobile', 'custommenuitems');
324
            // If filtering of the primary custom menu is enabled, apply only the string filters.
325
            if (!empty($CFG->navfilter && !empty($CFG->stringfilters))) {
326
                // Apply filters that are enabled for Content and Headings.
327
                $filtermanager = \filter_manager::instance();
328
                $custommenuitems = $filtermanager->filter_string($custommenuitems, \context_system::instance());
329
            }
330
            $settings->tool_mobile_custommenuitems = $custommenuitems;
1 efrain 331
            $settings->tool_mobile_apppolicy = get_config('tool_mobile', 'apppolicy');
332
            // This setting could be not set in some edge cases such as bad upgrade.
333
            $mintimereq = get_config('tool_mobile', 'autologinmintimebetweenreq');
334
            $mintimereq = empty($mintimereq) ? 6 * MINSECS : $mintimereq;
335
            $settings->tool_mobile_autologinmintimebetweenreq = $mintimereq;
336
            $settings->tool_mobile_autologout = get_config('tool_mobile', 'autologout');
337
            $settings->tool_mobile_autologouttime = get_config('tool_mobile', 'autologouttime');
338
        }
339
 
340
        if (empty($section) or $section == 'calendar') {
341
            $settings->calendartype = $CFG->calendartype;
342
            $settings->calendar_site_timeformat = $CFG->calendar_site_timeformat;
343
            $settings->calendar_startwday = $CFG->calendar_startwday;
344
            $settings->calendar_adminseesall = $CFG->calendar_adminseesall;
345
            $settings->calendar_lookahead = $CFG->calendar_lookahead;
346
            $settings->calendar_maxevents = $CFG->calendar_maxevents;
347
        }
348
 
349
        if (empty($section) or $section == 'coursecolors') {
350
            $colornumbers = range(1, 10);
351
            foreach ($colornumbers as $number) {
352
                $settings->{'core_admin_coursecolor' . $number} = get_config('core_admin', 'coursecolor' . $number);
353
            }
354
        }
355
 
356
        if (empty($section) or $section == 'supportcontact') {
357
            $settings->supportavailability = $CFG->supportavailability;
358
 
359
            if ($CFG->supportavailability == CONTACT_SUPPORT_DISABLED) {
360
                $settings->supportname = null;
361
                $settings->supportemail = null;
362
                $settings->supportpage = null;
363
            } else {
364
                $settings->supportname = $CFG->supportname;
365
                $settings->supportemail = $CFG->supportemail ?? null;
366
                $settings->supportpage = $CFG->supportpage;
367
            }
368
        }
369
 
370
        if (empty($section) || $section === 'graceperiodsettings') {
371
            $settings->coursegraceperiodafter = $CFG->coursegraceperiodafter;
372
            $settings->coursegraceperiodbefore = $CFG->coursegraceperiodbefore;
373
        }
374
 
375
        if (empty($section) || $section === 'navigation') {
376
            $settings->enabledashboard = $CFG->enabledashboard;
377
        }
378
 
379
        if (empty($section) || ($section === 'themesettings' || $section === 'themesettingsadvanced')) {
380
            $settings->customusermenuitems = $CFG->customusermenuitems;
381
        }
382
 
383
        if (empty($section) || $section === 'locationsettings') {
384
            $settings->timezone = $CFG->timezone;
385
            $settings->forcetimezone = $CFG->forcetimezone;
386
        }
387
 
388
        if (empty($section) || $section === 'manageglobalsearch') {
389
            $settings->searchengine = $CFG->searchengine;
390
            $settings->searchenablecategories = $CFG->searchenablecategories;
391
            $settings->searchdefaultcategory = $CFG->searchdefaultcategory;
392
            $settings->searchhideallcategory = $CFG->searchhideallcategory;
393
            $settings->searchmaxtopresults = $CFG->searchmaxtopresults;
394
            $settings->searchbannerenable = $CFG->searchbannerenable;
395
            $settings->searchbanner = \core_external\util::format_text(
396
                $CFG->searchbanner, FORMAT_HTML, $context)[0];
397
        }
398
 
399
        if (empty($section) || $section === 'privacysettings') {
400
            $settings->tool_dataprivacy_contactdataprotectionofficer = get_config('tool_dataprivacy', 'contactdataprotectionofficer');
401
            $settings->tool_dataprivacy_showdataretentionsummary = get_config('tool_dataprivacy', 'showdataretentionsummary');
402
        }
403
 
404
        if (empty($section) || $section === 'blog') {
405
            $settings->useblogassociations = $CFG->useblogassociations;
406
            $settings->bloglevel = $CFG->bloglevel;
407
            $settings->blogusecomments = $CFG->blogusecomments;
408
        }
409
 
410
        if (empty($section) || $section === 'h5psettings') {
411
            \core_h5p\local\library\autoloader::register();
412
            $customcss = \core_h5p\file_storage::get_custom_styles();
413
            if (!empty($customcss)) {
414
                $settings->h5pcustomcssurl = $customcss['cssurl']->out() . '?ver=' . $customcss['cssversion'];
415
            }
416
        }
417
 
418
        return $settings;
419
    }
420
 
421
    /*
422
     * Check if all the required conditions are met to allow the auto-login process continue.
423
     *
424
     * @param  int $userid  current user id
425
     * @since Moodle 3.2
426
     * @throws moodle_exception
427
     */
428
    public static function check_autologin_prerequisites($userid) {
429
        global $CFG;
430
 
431
        if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
432
            throw new moodle_exception('enablewsdescription', 'webservice');
433
        }
434
 
435
        if (!is_https()) {
436
            throw new moodle_exception('httpsrequired', 'tool_mobile');
437
        }
438
 
439
        if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
440
            throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
441
        }
442
    }
443
 
444
    /**
445
     * Creates an auto-login key for the current user, this key is restricted by time and ip address.
446
     * This key is used for automatically login the user in the site when the Moodle app opens the site in a mobile browser.
447
     *
448
     * @return string the key
449
     * @since Moodle 3.2
450
     */
451
    public static function get_autologin_key() {
452
        global $USER;
453
        // Delete previous keys.
454
        delete_user_key('tool_mobile', $USER->id);
455
 
456
        // Create a new key.
457
        $iprestriction = getremoteaddr();
458
        $validuntil = time() + self::LOGIN_KEY_TTL;
459
        return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
460
    }
461
 
462
    /**
463
     * Creates a QR login key for the current user, this key is restricted by time and ip address.
464
     * This key is used for automatically login the user in the site when the user scans a QR code in the Moodle app.
465
     *
466
     * @param  stdClass $mobilesettings  mobile app plugin settings
467
     * @return string the key
468
     * @since Moodle 3.9
469
     */
470
    public static function get_qrlogin_key(stdClass $mobilesettings) {
471
        global $USER;
472
        // Delete previous keys.
473
        delete_user_key('tool_mobile/qrlogin', $USER->id);
474
 
475
        // Create a new key.
476
        $iprestriction = !empty($mobilesettings->qrsameipcheck) ? getremoteaddr(null) : null;
477
        $qrkeyttl = !empty($mobilesettings->qrkeyttl) ? $mobilesettings->qrkeyttl : self::LOGIN_QR_KEY_TTL;
478
        $validuntil = time() + $qrkeyttl;
479
        return create_user_key('tool_mobile/qrlogin', $USER->id, null, $iprestriction, $validuntil);
480
    }
481
 
482
    /**
483
     * Get a list of the Mobile app features.
484
     *
485
     * @return array array with the features grouped by theirs ubication in the app.
486
     * @since Moodle 3.3
487
     */
488
    public static function get_features_list() {
489
        global $CFG;
490
        require_once($CFG->libdir . '/authlib.php');
491
 
492
        $general = new lang_string('general');
493
        $mainmenu = new lang_string('mainmenu', 'tool_mobile');
494
        $course = new lang_string('course');
495
        $modules = new lang_string('managemodules');
496
        $blocks = new lang_string('blocks');
497
        $useraccount = new lang_string('useraccount');
498
        $participants = new lang_string('participants');
499
        $files = new lang_string('files');
500
        $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
501
        $identityproviders = new lang_string('oauth2identityproviders', 'tool_mobile');
502
 
503
        $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
504
        $coursemodules = array();
505
        $appsupportedmodules = array(
1441 ariadna 506
            'assign', 'bigbluebuttonbn', 'book', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'h5pactivity',
507
            'imscp', 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'url', 'wiki', 'workshop');
1 efrain 508
 
509
        foreach ($availablemods as $mod) {
510
            if (in_array($mod->name, $appsupportedmodules)) {
511
                $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
512
            }
513
        }
514
        asort($coursemodules);
515
 
516
        $remoteaddonslist = array();
517
        $mobileplugins = self::get_plugins_supporting_mobile();
518
        foreach ($mobileplugins as $plugin) {
519
            $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
520
            $remoteaddonslist['sitePlugin_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
521
 
522
        }
523
 
524
        // Display blocks.
525
        $availableblocks = core_plugin_manager::instance()->get_plugins_of_type('block');
526
        $courseblocks = array();
527
        $appsupportedblocks = array(
528
            'activity_modules' => 'CoreBlockDelegate_AddonBlockActivityModules',
529
            'activity_results' => 'CoreBlockDelegate_AddonBlockActivityResults',
530
            'site_main_menu' => 'CoreBlockDelegate_AddonBlockSiteMainMenu',
531
            'myoverview' => 'CoreBlockDelegate_AddonBlockMyOverview',
532
            'course_list' => 'CoreBlockDelegate_AddonBlockCourseList',
533
            'timeline' => 'CoreBlockDelegate_AddonBlockTimeline',
534
            'recentlyaccessedcourses' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedCourses',
535
            'starredcourses' => 'CoreBlockDelegate_AddonBlockStarredCourses',
536
            'recentlyaccesseditems' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedItems',
537
            'badges' => 'CoreBlockDelegate_AddonBlockBadges',
538
            'blog_menu' => 'CoreBlockDelegate_AddonBlockBlogMenu',
539
            'blog_recent' => 'CoreBlockDelegate_AddonBlockBlogRecent',
540
            'blog_tags' => 'CoreBlockDelegate_AddonBlockBlogTags',
541
            'calendar_month' => 'CoreBlockDelegate_AddonBlockCalendarMonth',
542
            'calendar_upcoming' => 'CoreBlockDelegate_AddonBlockCalendarUpcoming',
543
            'comments' => 'CoreBlockDelegate_AddonBlockComments',
544
            'completionstatus' => 'CoreBlockDelegate_AddonBlockCompletionStatus',
545
            'feedback' => 'CoreBlockDelegate_AddonBlockFeedback',
546
            'globalsearch' => 'CoreBlockDelegate_AddonBlockGlobalSearch',
547
            'glossary_random' => 'CoreBlockDelegate_AddonBlockGlossaryRandom',
548
            'html' => 'CoreBlockDelegate_AddonBlockHtml',
549
            'lp' => 'CoreBlockDelegate_AddonBlockLp',
550
            'news_items' => 'CoreBlockDelegate_AddonBlockNewsItems',
551
            'online_users' => 'CoreBlockDelegate_AddonBlockOnlineUsers',
552
            'private_files' => 'CoreBlockDelegate_AddonBlockPrivateFiles',
553
            'recent_activity' => 'CoreBlockDelegate_AddonBlockRecentActivity',
554
            'rss_client' => 'CoreBlockDelegate_AddonBlockRssClient',
555
            'search_forums' => 'CoreBlockDelegate_AddonBlockSearchForums',
556
            'selfcompletion' => 'CoreBlockDelegate_AddonBlockSelfCompletion',
557
            'tags' => 'CoreBlockDelegate_AddonBlockTags',
558
        );
559
 
560
        foreach ($availableblocks as $block) {
561
            if (isset($appsupportedblocks[$block->name])) {
562
                $courseblocks[$appsupportedblocks[$block->name]] = $block->displayname;
563
            }
564
        }
565
        asort($courseblocks);
566
 
567
        $features = array(
568
            "$general" => array(
569
                'NoDelegate_CoreOffline' => new lang_string('offlineuse', 'tool_mobile'),
570
                'NoDelegate_SiteBlocks' => new lang_string('blocks'),
571
                'NoDelegate_CoreComments' => new lang_string('comments'),
572
                'NoDelegate_CoreRating' => new lang_string('ratings', 'rating'),
573
                'NoDelegate_CoreTag' => new lang_string('tags'),
574
                '$mmLoginEmailSignup' => new lang_string('startsignup'),
575
                'NoDelegate_ForgottenPassword' => new lang_string('forgotten'),
576
                'NoDelegate_ResponsiveMainMenuItems' => new lang_string('responsivemainmenuitems', 'tool_mobile'),
577
                'NoDelegate_H5POffline' => new lang_string('h5poffline', 'tool_mobile'),
578
                'NoDelegate_DarkMode' => new lang_string('darkmode', 'tool_mobile'),
579
                'CoreFilterDelegate' => new lang_string('type_filter_plural', 'plugin'),
580
                'CoreReportBuilderDelegate' => new lang_string('reportbuilder', 'core_reportbuilder'),
581
                'NoDelegate_CoreUserSupport' => new lang_string('contactsitesupport', 'admin'),
582
                'NoDelegate_GlobalSearch' => new lang_string('globalsearch', 'search'),
583
            ),
584
            "$mainmenu" => array(
585
                '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
586
                'CoreMainMenuDelegate_CoreCoursesDashboard' => new lang_string('myhome'),
587
                '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
588
                '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
589
                '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
590
                '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
591
                'CoreMainMenuDelegate_AddonBlog' => new lang_string('blog', 'blog'),
592
                'CoreMainMenuDelegate_CoreTag' => new lang_string('tags'),
593
                'CoreMainMenuDelegate_QrReader' => new lang_string('scanqrcode', 'tool_mobile'),
594
            ),
595
            "$useraccount" => array(
596
                '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
597
                '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
598
                'CoreUserDelegate_AddonBadges:account' => new lang_string('badges', 'badges'),
599
                'CoreUserDelegate_AddonBlog:account' => new lang_string('blog', 'blog'),
600
                '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
601
                'CoreUserDelegate_CorePolicy' => new lang_string('policiesagreements', 'tool_policy'),
602
                'CoreUserDelegate_CoreDataPrivacy' => new lang_string('pluginname', 'tool_dataprivacy'),
603
                'NoDelegate_SwitchAccount' => new lang_string('switchaccount', 'tool_mobile'),
604
            ),
605
            "$course" => array(
606
                '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
607
                '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
608
                '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
609
                '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
610
                '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
611
                'NoDelegate_CourseBlocks' => new lang_string('blocks'),
612
                'CoreCourseOptionsDelegate_AddonBlog' => new lang_string('blog', 'blog'),
613
                '$mmCoursesDelegate_search' => new lang_string('search'),
614
                'NoDelegate_CoreCourseDownload' => new lang_string('downloadcourse', 'tool_mobile'),
615
                'NoDelegate_CoreCoursesDownload' => new lang_string('downloadcourses', 'tool_mobile'),
616
            ),
617
            "$participants" => array(
618
                '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
619
                '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
620
                '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
621
                '$mmUserDelegate_mmaNotes:addNote' => new lang_string('notes', 'notes'),
622
                'CoreUserDelegate_AddonBlog:blogs' => new lang_string('blog', 'blog'),
623
                '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
624
                '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
625
                '$mmUserDelegate_picture' => new lang_string('userpic'),
626
            ),
627
            "$files" => array(
628
                'files_privatefiles' => new lang_string('privatefiles'),
629
                'files_sitefiles' => new lang_string('sitefiles'),
630
                'files_upload' => new lang_string('upload'),
631
            ),
632
            "$modules" => $coursemodules,
633
            "$blocks" => $courseblocks,
634
        );
635
 
636
        if (!empty($remoteaddonslist)) {
637
            $features["$remoteaddons"] = $remoteaddonslist;
638
        }
639
 
640
        if (!empty($availablemods['lti'])) {
641
            $ltidisplayname = $availablemods['lti']->displayname;
642
            $features["$ltidisplayname"]['CoreCourseModuleDelegate_AddonModLti:launchViaSite'] =
643
                new lang_string('launchviasiteinbrowser', 'tool_mobile');
644
        }
645
 
646
        // Display OAuth 2 identity providers.
647
        if (is_enabled_auth('oauth2')) {
648
            $identityproviderslist = array();
649
            $idps = \auth_plugin_base::get_identity_providers(['oauth2']);
650
 
651
            foreach ($idps as $idp) {
652
                // Only add identity providers that have an ID.
653
                $id = isset($idp['url']) ? $idp['url']->get_param('id') : null;
654
                if ($id != null) {
655
                    $identityproviderslist['NoDelegate_IdentityProvider_' . $id] = $idp['name'];
656
                }
657
            }
658
 
659
            if (!empty($identityproviderslist)) {
660
                $features["$identityproviders"] = array();
661
 
662
                if (count($identityproviderslist) > 1) {
663
                    // Include an option to disable them all.
664
                    $features["$identityproviders"]['NoDelegate_IdentityProviders'] = new lang_string('all');
665
                }
666
 
667
                $features["$identityproviders"] = array_merge($features["$identityproviders"], $identityproviderslist);
668
            }
669
        }
670
 
671
        return $features;
672
    }
673
 
674
    /**
675
     * This function check the current site for potential configuration issues that may prevent the mobile app to work.
676
     *
677
     * @return array list of potential issues
678
     * @since  Moodle 3.4
679
     */
680
    public static function get_potential_config_issues() {
681
        global $CFG;
682
        require_once($CFG->dirroot . "/lib/filelib.php");
683
        require_once($CFG->dirroot . '/message/lib.php');
684
 
685
        $warnings = array();
686
 
687
        if (is_https()) {
688
            $curl = new curl();
689
            // Return certificate information and verify the certificate.
690
            $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
691
            // Check https using a page not redirecting or returning exceptions.
692
            $curl->head("$CFG->wwwroot/$CFG->admin/tool/mobile/mobile.webmanifest.php");
693
            $info = $curl->get_info();
694
 
695
            // Check the certificate is not self-signed or has an untrusted-root.
696
            // This may be weak in some scenarios (when the curl SSL verifier is outdated).
697
            if (empty($info['http_code']) || empty($info['certinfo'])) {
698
                $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
699
            } else {
700
                $timenow = time();
701
                $infokeys = array_keys($info['certinfo']);
702
                $lastkey = end($infokeys);
703
 
704
                if (count($info['certinfo']) == 1) {
705
                    // This will work in a normal browser because it will complete the chain, but not in a mobile app.
706
                    $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
707
                }
708
 
709
                foreach ($info['certinfo'] as $key => $cert) {
710
                    // Convert to lower case the keys, some OS/curl implementations differ.
711
                    $cert = array_change_key_case($cert, CASE_LOWER);
712
 
713
                    // Due to a bug in certain curl/openssl versions the signature algorithm isn't always correctly parsed.
714
                    // See https://github.com/curl/curl/issues/3706 for reference.
715
                    if (!array_key_exists('signature algorithm', $cert)) {
716
                        // The malformed field that does contain the algorithm we're looking for looks like the following:
717
                        // <WHITESPACE>Signature Algorithm: <ALGORITHM><CRLF><ALGORITHM>.
718
                        preg_match('/\s+Signature Algorithm: (?<algorithm>[^\s]+)/', $cert['public key algorithm'], $matches);
719
 
720
                        $signaturealgorithm = $matches['algorithm'] ?? '';
721
                    } else {
722
                        $signaturealgorithm = $cert['signature algorithm'];
723
                    }
724
 
725
                    // Check if the signature algorithm is weak (Android won't work with SHA-1).
726
                    if ($key != $lastkey &&
727
                            ($signaturealgorithm == 'sha1WithRSAEncryption' || $signaturealgorithm == 'sha1WithRSA')) {
728
                        $warnings['insecurealgorithmwarning'] = ['insecurealgorithmwarning', 'tool_mobile'];
729
                    }
730
                    // Check certificate start date.
731
                    if (strtotime($cert['start date']) > $timenow) {
732
                        $warnings['invalidcertificatestartdatewarning'] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
733
                    }
734
                    // Check certificate end date.
735
                    if (strtotime($cert['expire date']) < $timenow) {
736
                        $warnings['invalidcertificateexpiredatewarning'] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
737
                    }
738
                }
739
            }
740
        } else {
741
            // Warning for non https sites.
742
            $warnings[] = ['nohttpsformobilewarning', 'admin'];
743
        }
744
 
745
        // Check ADOdb debug enabled.
746
        if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
747
            $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
748
        }
749
        // Check display errors on.
750
        if (!empty($CFG->debugdisplay)) {
751
            $warnings[] = ['displayerrorswarning', 'tool_mobile'];
752
        }
753
        // Check mobile notifications.
754
        $processors = get_message_processors();
755
        $enabled = false;
756
        foreach ($processors as $processor => $status) {
757
            if ($processor == 'airnotifier' && $status->enabled) {
758
                $enabled = true;
759
            }
760
        }
761
        if (!$enabled) {
762
            $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
763
        }
764
 
765
        return $warnings;
766
    }
767
 
768
    /**
769
     * Generates a QR code with the site URL or for automatic login from the mobile app.
770
     *
771
     * @param  stdClass $mobilesettings tool_mobile settings
772
     * @return string base64 data image contents, null if qr disabled
773
     */
774
    public static function generate_login_qrcode(stdClass $mobilesettings) {
775
        global $CFG, $USER;
776
 
777
        if ($mobilesettings->qrcodetype == static::QR_CODE_DISABLED) {
778
            return null;
779
        }
780
 
781
        $urlscheme = !empty($mobilesettings->forcedurlscheme) ? $mobilesettings->forcedurlscheme : 'moodlemobile';
782
        $data = $urlscheme . '://' . $CFG->wwwroot;
783
 
784
        if ($mobilesettings->qrcodetype == static::QR_CODE_LOGIN) {
785
            $qrloginkey = static::get_qrlogin_key($mobilesettings);
786
            $data .= '?qrlogin=' . $qrloginkey . '&userid=' . $USER->id;
787
        }
788
 
789
        $qrcode = new core_qrcode($data);
790
        $imagedata = 'data:image/png;base64,' . base64_encode($qrcode->getBarcodePngData(5, 5));
791
 
792
        return $imagedata;
793
    }
794
 
795
    /**
796
     * Gets Moodle app plan subscription information for the current site as it is returned by the Apps Portal.
797
     *
798
     * @return array Subscription information
799
     */
800
    public static function get_subscription_information(): ?array {
801
        global $CFG;
802
 
803
        // Use session cache to prevent multiple requests.
804
        $cache = \cache::make('tool_mobile', 'subscriptiondata');
805
        $subscriptiondata = $cache->get(0);
806
        if ($subscriptiondata !== false) {
807
            return $subscriptiondata;
808
        }
809
 
810
        $mobilesettings = get_config('tool_mobile');
811
 
812
        // To validate that the requests come from this site we need to send some private information that only is known by the
813
        // Moodle Apps portal or the Sites registration database.
814
        $credentials = [];
815
 
816
        if (!empty($CFG->airnotifieraccesskey)) {
817
            $credentials[] = ['type' => 'airnotifieraccesskey', 'value' => $CFG->airnotifieraccesskey];
818
        }
819
        if (\core\hub\registration::is_registered()) {
820
            $credentials[] = ['type' => 'siteid', 'value' => $CFG->siteidentifier];
821
        }
822
        // Generate a hash key for validating that the request is coming from this site via WS.
823
        $key = complex_random_string(32);
824
        $sitesubscriptionkey = json_encode(['validuntil' => time() + 10 * MINSECS, 'key' => $key]);
825
        set_config('sitesubscriptionkey', $sitesubscriptionkey, 'tool_mobile');
826
        $credentials[] = ['type' => 'sitesubscriptionkey', 'value' => $key];
827
 
828
        // Parameters for the WebService returning site information.
829
        $androidappid = empty($mobilesettings->androidappid) ? static::DEFAULT_ANDROID_APP_ID : $mobilesettings->androidappid;
830
        $iosappid = empty($mobilesettings->iosappid) ? static::DEFAULT_IOS_APP_ID : $mobilesettings->iosappid;
831
        $fnparams = (object) [
832
            'siteurl' => $CFG->wwwroot,
833
            'appids' => [$androidappid, $iosappid],
834
            'credentials' => $credentials,
835
        ];
836
        // Prepare the arguments for a request to the AJAX nologin endpoint.
837
        $args = [
838
            (object) [
839
                'index' => 0,
840
                'methodname' => 'local_apps_get_site_info',
841
                'args' => $fnparams,
842
            ]
843
        ];
844
 
845
        // Ask the Moodle Apps Portal for the subscription information.
846
        $curl = new curl();
847
        $curl->setopt(array('CURLOPT_TIMEOUT' => 10, 'CURLOPT_CONNECTTIMEOUT' => 10));
848
 
849
        $serverurl = static::MOODLE_APPS_PORTAL_URL . "/lib/ajax/service-nologin.php";
850
        $query = 'args=' . urlencode(json_encode($args));
851
        $wsresponse = @json_decode($curl->post($serverurl, $query), true);
852
 
853
        $info = $curl->get_info();
854
        if ($curlerrno = $curl->get_errno()) {
855
            // CURL connection error.
856
            debugging("Unexpected response from the Moodle Apps Portal server, CURL error number: $curlerrno");
857
            return null;
858
        } else if ($info['http_code'] != 200) {
859
            // Unexpected error from server.
860
            debugging('Unexpected response from the Moodle Apps Portal server, HTTP code:' . $info['httpcode']);
861
            return null;
862
        } else if (!empty($wsresponse[0]['error'])) {
863
            // Unexpected error from Moodle Apps Portal.
864
            debugging('Unexpected response from the Moodle Apps Portal server:' . json_encode($wsresponse[0]));
865
            return null;
866
        } else if (empty($wsresponse[0]['data'])) {
867
            debugging('Unexpected response from the Moodle Apps Portal server:' . json_encode($wsresponse));
868
            return null;
869
        }
870
 
871
        $cache->set(0, $wsresponse[0]['data']);
872
 
873
        return $wsresponse[0]['data'];
874
    }
875
}