75de14bdb7e40e8a33c86d2d3ca953e0a3c1cc1f
[moodle.git] / admin / tool / mobile / classes / api.php
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/>.
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;
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;
35 /**
36  * API exposed by tool_mobile, to be used mostly by external functions and the plugin settings.
37  *
38  * @copyright  2016 Juan Leyva
39  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
40  * @since      Moodle 3.1
41  */
42 class api {
44     /** @var int to identify the login via app. */
45     const LOGIN_VIA_APP = 1;
46     /** @var int to identify the login via browser. */
47     const LOGIN_VIA_BROWSER = 2;
48     /** @var int to identify the login via an embedded browser. */
49     const LOGIN_VIA_EMBEDDED_BROWSER = 3;
50     /** @var int seconds an auto-login key will expire. */
51     const LOGIN_KEY_TTL = 60;
53     /**
54      * Returns a list of Moodle plugins supporting the mobile app.
55      *
56      * @return array an array of objects containing the plugin information
57      */
58     public static function get_plugins_supporting_mobile() {
59         global $CFG;
60         require_once($CFG->libdir . '/adminlib.php');
62         $cachekey = 'mobileplugins';
63         if (!isloggedin()) {
64             $cachekey = 'authmobileplugins';    // Use a different cache for not logged users.
65         }
67         // Check if we can return this from cache.
68         $cache = \cache::make('tool_mobile', 'plugininfo');
69         $pluginsinfo = $cache->get($cachekey);
70         if ($pluginsinfo !== false) {
71             return (array)$pluginsinfo;
72         }
74         $pluginsinfo = [];
75         // For not logged users return only auth plugins.
76         // This is to avoid anyone (not being a registered user) to obtain and download all the site remote add-ons.
77         if (!isloggedin()) {
78             $plugintypes = array('auth' => $CFG->dirroot.'/auth');
79         } else {
80             $plugintypes = core_component::get_plugin_types();
81         }
83         foreach ($plugintypes as $plugintype => $unused) {
84             // We need to include files here.
85             $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
86             foreach ($pluginswithfile as $plugin => $notused) {
87                 $path = core_component::get_plugin_directory($plugintype, $plugin);
88                 $component = $plugintype . '_' . $plugin;
89                 $version = get_component_version($component);
91                 require("$path/db/mobile.php");
92                 foreach ($addons as $addonname => $addoninfo) {
94                     // Add handlers (for site add-ons).
95                     $handlers = !empty($addoninfo['handlers']) ? $addoninfo['handlers'] : array();
96                     $handlers = json_encode($handlers); // JSON formatted, since it is a complex structure that may vary over time.
98                     // Now language strings used by the app.
99                     $lang = array();
100                     if (!empty($addoninfo['lang'])) {
101                         $stringmanager = get_string_manager();
102                         $langs = $stringmanager->get_list_of_translations(true);
103                         foreach ($langs as $langid => $langname) {
104                             foreach ($addoninfo['lang'] as $stringinfo) {
105                                 $lang[$langid][$stringinfo[0]] =
106                                     $stringmanager->get_string($stringinfo[0], $stringinfo[1], null, $langid);
107                             }
108                         }
109                     }
110                     $lang = json_encode($lang);
112                     $plugininfo = array(
113                         'component' => $component,
114                         'version' => $version,
115                         'addon' => $addonname,
116                         'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
117                         'fileurl' => '',
118                         'filehash' => '',
119                         'filesize' => 0,
120                         'handlers' => $handlers,
121                         'lang' => $lang,
122                     );
124                     // All the mobile packages must be under the plugin mobile directory.
125                     $package = $path . '/mobile/' . $addonname . '.zip';
126                     if (file_exists($package)) {
127                         $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
128                         $plugininfo['filehash'] = sha1_file($package);
129                         $plugininfo['filesize'] = filesize($package);
130                     }
131                     $pluginsinfo[] = $plugininfo;
132                 }
133             }
134         }
136         $cache->set($cachekey, $pluginsinfo);
138         return $pluginsinfo;
139     }
141     /**
142      * Returns a list of the site public settings, those not requiring authentication.
143      *
144      * @return array with the settings and warnings
145      */
146     public static function get_public_config() {
147         global $CFG, $SITE, $PAGE, $OUTPUT;
148         require_once($CFG->libdir . '/authlib.php');
150         $context = context_system::instance();
151         // We need this to make work the format text functions.
152         $PAGE->set_context($context);
154         list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
155         list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
156         $settings = array(
157             'wwwroot' => $CFG->wwwroot,
158             'httpswwwroot' => $CFG->wwwroot,
159             'sitename' => external_format_string($SITE->fullname, $context->id, true),
160             'guestlogin' => $CFG->guestloginbutton,
161             'rememberusername' => $CFG->rememberusername,
162             'authloginviaemail' => $CFG->authloginviaemail,
163             'registerauth' => $CFG->registerauth,
164             'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
165             'authinstructions' => $authinstructions,
166             'authnoneenabled' => (int) is_enabled_auth('none'),
167             'enablewebservices' => $CFG->enablewebservices,
168             'enablemobilewebservice' => $CFG->enablemobilewebservice,
169             'maintenanceenabled' => $CFG->maintenance_enabled,
170             'maintenancemessage' => $maintenancemessage,
171             'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
172             'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
173             'country' => clean_param($CFG->country, PARAM_NOTAGS),
174             'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
175             'autolang' => $CFG->autolang,
176             'lang' => clean_param($CFG->lang, PARAM_LANG),  // Avoid breaking WS because of incorrect package langs.
177             'langmenu' => $CFG->langmenu,
178             'langlist' => $CFG->langlist,
179             'locale' => $CFG->locale,
180             'tool_mobile_minimumversion' => get_config('tool_mobile', 'minimumversion'),
181             'tool_mobile_iosappid' => get_config('tool_mobile', 'iosappid'),
182             'tool_mobile_androidappid' => get_config('tool_mobile', 'androidappid'),
183             'tool_mobile_setuplink' => clean_param(get_config('tool_mobile', 'setuplink'), PARAM_URL),
184         );
186         $typeoflogin = get_config('tool_mobile', 'typeoflogin');
187         // Not found, edge case.
188         if ($typeoflogin === false) {
189             $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
190         }
191         $settings['typeoflogin'] = $typeoflogin;
193         // Check if the user can sign-up to return the launch URL in that case.
194         $cansignup = signup_is_enabled();
196         $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
197         $settings['launchurl'] = $url->out(false);
199         // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
200         if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
201             $settings['logourl'] = clean_param($logourl->out(false), PARAM_URL);
202         }
203         if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
204             $settings['compactlogourl'] = clean_param($compactlogourl->out(false), PARAM_URL);
205         }
207         // Identity providers.
208         $authsequence = get_enabled_auth_plugins(true);
209         $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
210         $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
211         if (!empty($identityprovidersdata)) {
212             $settings['identityproviders'] = $identityprovidersdata;
213             // Clean URLs to avoid breaking Web Services.
214             // We can't do it in prepare_identity_providers_for_output() because it may break the web output.
215             foreach ($settings['identityproviders'] as &$ip) {
216                 $ip['url'] = (!empty($ip['url'])) ? clean_param($ip['url'], PARAM_URL) : '';
217                 $ip['iconurl'] = (!empty($ip['iconurl'])) ? clean_param($ip['iconurl'], PARAM_URL) : '';
218             }
219         }
221         // If age is verified, return also the admin contact details.
222         if ($settings['agedigitalconsentverification']) {
223             $settings['supportname'] = clean_param($CFG->supportname, PARAM_NOTAGS);
224             $settings['supportemail'] = clean_param($CFG->supportemail, PARAM_EMAIL);
225         }
227         return $settings;
228     }
230     /**
231      * Returns a list of site configurations, filtering by section.
232      *
233      * @param  string $section section name
234      * @return stdClass object containing the settings
235      */
236     public static function get_config($section) {
237         global $CFG, $SITE;
239         $settings = new \stdClass;
240         $context = context_system::instance();
241         $isadmin = has_capability('moodle/site:config', $context);
243         if (empty($section) or $section == 'frontpagesettings') {
244             require_once($CFG->dirroot . '/course/format/lib.php');
245             // First settings that anyone can deduce.
246             $settings->fullname = external_format_string($SITE->fullname, $context->id);
247             $settings->shortname = external_format_string($SITE->shortname, $context->id);
249             // Return to a var instead of directly to $settings object because of differences between
250             // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
251             $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
252                                                                                         $context->id);
253             $settings->summary = $formattedsummary[0];
254             $settings->summaryformat = $formattedsummary[1];
255             $settings->frontpage = $CFG->frontpage;
256             $settings->frontpageloggedin = $CFG->frontpageloggedin;
257             $settings->maxcategorydepth = $CFG->maxcategorydepth;
258             $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
259             $settings->numsections = course_get_format($SITE)->get_last_section_number();
260             $settings->newsitems = $SITE->newsitems;
261             $settings->commentsperpage = $CFG->commentsperpage;
263             // Now, admin settings.
264             if ($isadmin) {
265                 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
266             }
267         }
269         if (empty($section) or $section == 'sitepolicies') {
270             $manager = new \core_privacy\local\sitepolicy\manager();
271             $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
272             $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
273             $settings->disableuserimages = $CFG->disableuserimages;
274         }
276         if (empty($section) or $section == 'gradessettings') {
277             require_once($CFG->dirroot . '/user/lib.php');
278             $settings->mygradesurl = user_mygrades_url();
279             // The previous function may return moodle_url instances or plain string URLs.
280             if ($settings->mygradesurl instanceof moodle_url) {
281                 $settings->mygradesurl = $settings->mygradesurl->out(false);
282             }
283         }
285         if (empty($section) or $section == 'mobileapp') {
286             $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
287             $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
288             $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
289             $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
290             $settings->tool_mobile_apppolicy = get_config('tool_mobile', 'apppolicy');
291         }
293         if (empty($section) or $section == 'calendar') {
294             $settings->calendartype = $CFG->calendartype;
295             $settings->calendar_site_timeformat = $CFG->calendar_site_timeformat;
296             $settings->calendar_startwday = $CFG->calendar_startwday;
297             $settings->calendar_adminseesall = $CFG->calendar_adminseesall;
298             $settings->calendar_lookahead = $CFG->calendar_lookahead;
299             $settings->calendar_maxevents = $CFG->calendar_maxevents;
300         }
302         if (empty($section) or $section == 'coursecolors') {
303             $colornumbers = range(1, 10);
304             foreach ($colornumbers as $number) {
305                 $settings->{'core_admin_coursecolor' . $number} = get_config('core_admin', 'coursecolor' . $number);
306             }
307         }
309         return $settings;
310     }
312     /*
313      * Check if all the required conditions are met to allow the auto-login process continue.
314      *
315      * @param  int $userid  current user id
316      * @since Moodle 3.2
317      * @throws moodle_exception
318      */
319     public static function check_autologin_prerequisites($userid) {
320         global $CFG;
322         if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
323             throw new moodle_exception('enablewsdescription', 'webservice');
324         }
326         if (!is_https()) {
327             throw new moodle_exception('httpsrequired', 'tool_mobile');
328         }
330         if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
331             throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
332         }
333     }
335     /**
336      * Creates an auto-login key for the current user, this key is restricted by time and ip address.
337      *
338      * @return string the key
339      * @since Moodle 3.2
340      */
341     public static function get_autologin_key() {
342         global $USER;
343         // Delete previous keys.
344         delete_user_key('tool_mobile', $USER->id);
346         // Create a new key.
347         $iprestriction = getremoteaddr();
348         $validuntil = time() + self::LOGIN_KEY_TTL;
349         return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
350     }
352     /**
353      * Get a list of the Mobile app features.
354      *
355      * @return array array with the features grouped by theirs ubication in the app.
356      * @since Moodle 3.3
357      */
358     public static function get_features_list() {
359         global $CFG;
361         $general = new lang_string('general');
362         $mainmenu = new lang_string('mainmenu', 'tool_mobile');
363         $course = new lang_string('course');
364         $modules = new lang_string('managemodules');
365         $blocks = new lang_string('blocks');
366         $user = new lang_string('user');
367         $files = new lang_string('files');
368         $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
370         $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
371         $coursemodules = array();
372         $appsupportedmodules = array('assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'imscp',
373             'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop');
375         foreach ($availablemods as $mod) {
376             if (in_array($mod->name, $appsupportedmodules)) {
377                 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
378             }
379         }
380         asort($coursemodules);
382         $remoteaddonslist = array();
383         $mobileplugins = self::get_plugins_supporting_mobile();
384         foreach ($mobileplugins as $plugin) {
385             $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
386             $remoteaddonslist['sitePlugin_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
388         }
390         // Display blocks.
391         $availableblocks = core_plugin_manager::instance()->get_plugins_of_type('block');
392         $courseblocks = array();
393         $appsupportedblocks = array(
394             'activity_modules' => 'CoreBlockDelegate_AddonBlockActivityModules',
395             'site_main_menu' => 'CoreBlockDelegate_AddonBlockSiteMainMenu',
396             'myoverview' => 'CoreBlockDelegate_AddonBlockMyOverview',
397             'timeline' => 'CoreBlockDelegate_AddonBlockTimeline',
398             'recentlyaccessedcourses' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedCourses',
399             'starredcourses' => 'CoreBlockDelegate_AddonBlockStarredCourses',
400             'recentlyaccesseditems' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedItems',
401             'badges' => 'CoreBlockDelegate_AddonBlockBadges',
402             'blog_menu' => 'CoreBlockDelegate_AddonBlockBlogMenu',
403             'blog_recent' => 'CoreBlockDelegate_AddonBlockBlogRecent',
404             'blog_tags' => 'CoreBlockDelegate_AddonBlockBlogTags',
405             'calendar_month' => 'CoreBlockDelegate_AddonBlockCalendarMonth',
406             'calendar_upcoming' => 'CoreBlockDelegate_AddonBlockCalendarUpcoming',
407             'comments' => 'CoreBlockDelegate_AddonBlockComments',
408             'completionstatus' => 'CoreBlockDelegate_AddonBlockCompletionStatus',
409             'feedback' => 'CoreBlockDelegate_AddonBlockFeedback',
410             'glossary_random' => 'CoreBlockDelegate_AddonBlockGlossaryRandom',
411             'html' => 'CoreBlockDelegate_AddonBlockHtml',
412             'lp' => 'CoreBlockDelegate_AddonBlockLp',
413             'news_items' => 'CoreBlockDelegate_AddonBlockNewsItems',
414             'online_users' => 'CoreBlockDelegate_AddonBlockOnlineUsers',
415             'selfcompletion' => 'CoreBlockDelegate_AddonBlockSelfCompletion',
416             'tags' => 'CoreBlockDelegate_AddonBlockTags',
417         );
419         foreach ($availableblocks as $block) {
420             if (isset($appsupportedblocks[$block->name])) {
421                 $courseblocks[$appsupportedblocks[$block->name]] = $block->displayname;
422             }
423         }
424         asort($courseblocks);
426         $features = array(
427             "$general" => array(
428                 'NoDelegate_CoreOffline' => new lang_string('offlineuse', 'tool_mobile'),
429                 'NoDelegate_SiteBlocks' => new lang_string('blocks'),
430                 'NoDelegate_CoreComments' => new lang_string('comments'),
431                 'NoDelegate_CoreRating' => new lang_string('ratings', 'rating'),
432                 'NoDelegate_CoreTag' => new lang_string('tags'),
433                 '$mmLoginEmailSignup' => new lang_string('startsignup'),
434                 'NoDelegate_ForgottenPassword' => new lang_string('forgotten'),
435                 'NoDelegate_ResponsiveMainMenuItems' => new lang_string('responsivemainmenuitems', 'tool_mobile'),
436                 'NoDelegate_H5POffline' => new lang_string('h5poffline', 'tool_mobile'),
437                 'NoDelegate_DarkMode' => new lang_string('darkmode', 'tool_mobile'),
438             ),
439             "$mainmenu" => array(
440                 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
441                 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
442                 'CoreMainMenuDelegate_CoreCoursesDashboard' => new lang_string('myhome'),
443                 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
444                 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
445                 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
446                 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
447                 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
448                 'CoreMainMenuDelegate_AddonBlog' => new lang_string('blog', 'blog'),
449                 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
450                 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
451                 '$mmSideMenuDelegate_help' => new lang_string('help'),
452             ),
453             "$course" => array(
454                 'NoDelegate_CourseBlocks' => new lang_string('blocks'),
455                 'CoreCourseOptionsDelegate_AddonBlog' => new lang_string('blog', 'blog'),
456                 '$mmCoursesDelegate_search' => new lang_string('search'),
457                 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
458                 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
459                 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
460                 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
461                 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
462                 'NoDelegate_CoreCourseDownload' => new lang_string('downloadcourse', 'tool_mobile'),
463                 'NoDelegate_CoreCoursesDownload' => new lang_string('downloadcourses', 'tool_mobile'),
464             ),
465             "$user" => array(
466                 'CoreUserDelegate_AddonBlog:blogs' => new lang_string('blog', 'blog'),
467                 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
468                 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
469                 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
470                 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
471                 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
472                 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
473                 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
474                 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
475                 '$mmUserDelegate_picture' => new lang_string('userpic'),
476             ),
477             "$files" => array(
478                 'files_privatefiles' => new lang_string('privatefiles'),
479                 'files_sitefiles' => new lang_string('sitefiles'),
480                 'files_upload' => new lang_string('upload'),
481             ),
482             "$modules" => $coursemodules,
483             "$blocks" => $courseblocks,
484         );
486         if (!empty($remoteaddonslist)) {
487             $features["$remoteaddons"] = $remoteaddonslist;
488         }
490         return $features;
491     }
493     /**
494      * This function check the current site for potential configuration issues that may prevent the mobile app to work.
495      *
496      * @return array list of potential issues
497      * @since  Moodle 3.4
498      */
499     public static function get_potential_config_issues() {
500         global $CFG;
501         require_once($CFG->dirroot . "/lib/filelib.php");
502         require_once($CFG->dirroot . '/message/lib.php');
504         $warnings = array();
506         $curl = new curl();
507         // Return certificate information and verify the certificate.
508         $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
509         $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); // Force https url.
510         // Check https using a page not redirecting or returning exceptions.
511         $curl->head($httpswwwroot . "/$CFG->admin/tool/mobile/mobile.webmanifest.php");
512         $info = $curl->get_info();
514         // First of all, check the server certificate (if any).
515         if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
516             $warnings[] = ['nohttpsformobilewarning', 'admin'];
517         } else {
518             // Check the certificate is not self-signed or has an untrusted-root.
519             // This may be weak in some scenarios (when the curl SSL verifier is outdated).
520             if (empty($info['certinfo'])) {
521                 $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
522             } else {
523                 $timenow = time();
524                 $expectedissuer = null;
525                 foreach ($info['certinfo'] as $cert) {
526                     // Check if the signature algorithm is weak (Android won't work with SHA-1).
527                     if ($cert['Signature Algorithm'] == 'sha1WithRSAEncryption' || $cert['Signature Algorithm'] == 'sha1WithRSA') {
528                         $warnings[] = ['insecurealgorithmwarning', 'tool_mobile'];
529                     }
530                     // Check certificate start date.
531                     if (strtotime($cert['Start date']) > $timenow) {
532                         $warnings[] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
533                     }
534                     // Check certificate end date.
535                     if (strtotime($cert['Expire date']) < $timenow) {
536                         $warnings[] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
537                     }
538                     // Check the chain.
539                     if ($expectedissuer !== null) {
540                         if ($expectedissuer !== $cert['Subject'] || $cert['Subject'] === $cert['Issuer']) {
541                             $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
542                         }
543                     }
544                     $expectedissuer = $cert['Issuer'];
545                 }
546             }
547         }
548         // Now check typical configuration problems.
549         if ((int) $CFG->userquota === PHP_INT_MAX) {
550             // In old Moodle version was a text so was possible to have numeric values > PHP_INT_MAX.
551             $warnings[] = ['invaliduserquotawarning', 'tool_mobile'];
552         }
553         // Check ADOdb debug enabled.
554         if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
555             $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
556         }
557         // Check display errors on.
558         if (!empty($CFG->debugdisplay)) {
559             $warnings[] = ['displayerrorswarning', 'tool_mobile'];
560         }
561         // Check mobile notifications.
562         $processors = get_message_processors();
563         $enabled = false;
564         foreach ($processors as $processor => $status) {
565             if ($processor == 'airnotifier' && $status->enabled) {
566                 $enabled = true;
567             }
568         }
569         if (!$enabled) {
570             $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
571         }
573         return $warnings;
574     }