2 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
18 * Class for Moodle Mobile tools.
20 * @package tool_mobile
21 * @copyright 2016 Juan Leyva
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25 namespace tool_mobile;
28 use core_plugin_manager;
38 * API exposed by tool_mobile, to be used mostly by external functions and the plugin settings.
40 * @copyright 2016 Juan Leyva
41 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
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 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;
66 * Returns a list of Moodle plugins supporting the mobile app.
68 * @return array an array of objects containing the plugin information
70 public static function get_plugins_supporting_mobile() {
72 require_once($CFG->libdir . '/adminlib.php');
74 $cachekey = 'mobileplugins';
76 $cachekey = 'authmobileplugins'; // Use a different cache for not logged users.
79 // Check if we can return this from cache.
80 $cache = \cache::make('tool_mobile', 'plugininfo');
81 $pluginsinfo = $cache->get($cachekey);
82 if ($pluginsinfo !== false) {
83 return (array)$pluginsinfo;
87 // For not logged users return only auth plugins.
88 // This is to avoid anyone (not being a registered user) to obtain and download all the site remote add-ons.
90 $plugintypes = array('auth' => $CFG->dirroot.'/auth');
92 $plugintypes = core_component::get_plugin_types();
95 foreach ($plugintypes as $plugintype => $unused) {
96 // We need to include files here.
97 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
98 foreach ($pluginswithfile as $plugin => $notused) {
99 $path = core_component::get_plugin_directory($plugintype, $plugin);
100 $component = $plugintype . '_' . $plugin;
101 $version = get_component_version($component);
103 require("$path/db/mobile.php");
104 foreach ($addons as $addonname => $addoninfo) {
106 // Add handlers (for site add-ons).
107 $handlers = !empty($addoninfo['handlers']) ? $addoninfo['handlers'] : array();
108 $handlers = json_encode($handlers); // JSON formatted, since it is a complex structure that may vary over time.
110 // Now language strings used by the app.
112 if (!empty($addoninfo['lang'])) {
113 $stringmanager = get_string_manager();
114 $langs = $stringmanager->get_list_of_translations(true);
115 foreach ($langs as $langid => $langname) {
116 foreach ($addoninfo['lang'] as $stringinfo) {
117 $lang[$langid][$stringinfo[0]] =
118 $stringmanager->get_string($stringinfo[0], $stringinfo[1], null, $langid);
122 $lang = json_encode($lang);
125 'component' => $component,
126 'version' => $version,
127 'addon' => $addonname,
128 'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
132 'handlers' => $handlers,
136 // All the mobile packages must be under the plugin mobile directory.
137 $package = $path . '/mobile/' . $addonname . '.zip';
138 if (file_exists($package)) {
139 $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
140 $plugininfo['filehash'] = sha1_file($package);
141 $plugininfo['filesize'] = filesize($package);
143 $pluginsinfo[] = $plugininfo;
148 $cache->set($cachekey, $pluginsinfo);
154 * Returns a list of the site public settings, those not requiring authentication.
156 * @return array with the settings and warnings
158 public static function get_public_config() {
159 global $CFG, $SITE, $PAGE, $OUTPUT;
160 require_once($CFG->libdir . '/authlib.php');
162 $context = context_system::instance();
163 // We need this to make work the format text functions.
164 $PAGE->set_context($context);
166 list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
167 list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
169 'wwwroot' => $CFG->wwwroot,
170 'httpswwwroot' => $CFG->wwwroot,
171 'sitename' => external_format_string($SITE->fullname, $context->id, true),
172 'guestlogin' => $CFG->guestloginbutton,
173 'rememberusername' => $CFG->rememberusername,
174 'authloginviaemail' => $CFG->authloginviaemail,
175 'registerauth' => $CFG->registerauth,
176 'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
177 'authinstructions' => $authinstructions,
178 'authnoneenabled' => (int) is_enabled_auth('none'),
179 'enablewebservices' => $CFG->enablewebservices,
180 'enablemobilewebservice' => $CFG->enablemobilewebservice,
181 'maintenanceenabled' => $CFG->maintenance_enabled,
182 'maintenancemessage' => $maintenancemessage,
183 'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
184 'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
185 'country' => clean_param($CFG->country, PARAM_NOTAGS),
186 'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
187 'autolang' => $CFG->autolang,
188 'lang' => clean_param($CFG->lang, PARAM_LANG), // Avoid breaking WS because of incorrect package langs.
189 'langmenu' => $CFG->langmenu,
190 'langlist' => $CFG->langlist,
191 'locale' => $CFG->locale,
192 'tool_mobile_minimumversion' => get_config('tool_mobile', 'minimumversion'),
193 'tool_mobile_iosappid' => get_config('tool_mobile', 'iosappid'),
194 'tool_mobile_androidappid' => get_config('tool_mobile', 'androidappid'),
195 'tool_mobile_setuplink' => clean_param(get_config('tool_mobile', 'setuplink'), PARAM_URL),
198 $typeoflogin = get_config('tool_mobile', 'typeoflogin');
199 // Not found, edge case.
200 if ($typeoflogin === false) {
201 $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
203 $settings['typeoflogin'] = $typeoflogin;
205 // Check if the user can sign-up to return the launch URL in that case.
206 $cansignup = signup_is_enabled();
208 $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
209 $settings['launchurl'] = $url->out(false);
211 // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
212 if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
213 $settings['logourl'] = clean_param($logourl->out(false), PARAM_URL);
215 if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
216 $settings['compactlogourl'] = clean_param($compactlogourl->out(false), PARAM_URL);
219 // Identity providers.
220 $authsequence = get_enabled_auth_plugins(true);
221 $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
222 $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
223 if (!empty($identityprovidersdata)) {
224 $settings['identityproviders'] = $identityprovidersdata;
225 // Clean URLs to avoid breaking Web Services.
226 // We can't do it in prepare_identity_providers_for_output() because it may break the web output.
227 foreach ($settings['identityproviders'] as &$ip) {
228 $ip['url'] = (!empty($ip['url'])) ? clean_param($ip['url'], PARAM_URL) : '';
229 $ip['iconurl'] = (!empty($ip['iconurl'])) ? clean_param($ip['iconurl'], PARAM_URL) : '';
233 // If age is verified, return also the admin contact details.
234 if ($settings['agedigitalconsentverification']) {
235 $settings['supportname'] = clean_param($CFG->supportname, PARAM_NOTAGS);
236 $settings['supportemail'] = clean_param($CFG->supportemail, PARAM_EMAIL);
243 * Returns a list of site configurations, filtering by section.
245 * @param string $section section name
246 * @return stdClass object containing the settings
248 public static function get_config($section) {
251 $settings = new \stdClass;
252 $context = context_system::instance();
253 $isadmin = has_capability('moodle/site:config', $context);
255 if (empty($section) or $section == 'frontpagesettings') {
256 require_once($CFG->dirroot . '/course/format/lib.php');
257 // First settings that anyone can deduce.
258 $settings->fullname = external_format_string($SITE->fullname, $context->id);
259 $settings->shortname = external_format_string($SITE->shortname, $context->id);
261 // Return to a var instead of directly to $settings object because of differences between
262 // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
263 $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
265 $settings->summary = $formattedsummary[0];
266 $settings->summaryformat = $formattedsummary[1];
267 $settings->frontpage = $CFG->frontpage;
268 $settings->frontpageloggedin = $CFG->frontpageloggedin;
269 $settings->maxcategorydepth = $CFG->maxcategorydepth;
270 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
271 $settings->numsections = course_get_format($SITE)->get_last_section_number();
272 $settings->newsitems = $SITE->newsitems;
273 $settings->commentsperpage = $CFG->commentsperpage;
275 // Now, admin settings.
277 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
281 if (empty($section) or $section == 'sitepolicies') {
282 $manager = new \core_privacy\local\sitepolicy\manager();
283 $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
284 $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
285 $settings->disableuserimages = $CFG->disableuserimages;
288 if (empty($section) or $section == 'gradessettings') {
289 require_once($CFG->dirroot . '/user/lib.php');
290 $settings->mygradesurl = user_mygrades_url();
291 // The previous function may return moodle_url instances or plain string URLs.
292 if ($settings->mygradesurl instanceof moodle_url) {
293 $settings->mygradesurl = $settings->mygradesurl->out(false);
297 if (empty($section) or $section == 'mobileapp') {
298 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
299 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
300 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
301 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
302 $settings->tool_mobile_apppolicy = get_config('tool_mobile', 'apppolicy');
305 if (empty($section) or $section == 'calendar') {
306 $settings->calendartype = $CFG->calendartype;
307 $settings->calendar_site_timeformat = $CFG->calendar_site_timeformat;
308 $settings->calendar_startwday = $CFG->calendar_startwday;
309 $settings->calendar_adminseesall = $CFG->calendar_adminseesall;
310 $settings->calendar_lookahead = $CFG->calendar_lookahead;
311 $settings->calendar_maxevents = $CFG->calendar_maxevents;
314 if (empty($section) or $section == 'coursecolors') {
315 $colornumbers = range(1, 10);
316 foreach ($colornumbers as $number) {
317 $settings->{'core_admin_coursecolor' . $number} = get_config('core_admin', 'coursecolor' . $number);
325 * Check if all the required conditions are met to allow the auto-login process continue.
327 * @param int $userid current user id
329 * @throws moodle_exception
331 public static function check_autologin_prerequisites($userid) {
334 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
335 throw new moodle_exception('enablewsdescription', 'webservice');
339 throw new moodle_exception('httpsrequired', 'tool_mobile');
342 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
343 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
348 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
349 * This key is used for automatically login the user in the site when the Moodle app opens the site in a mobile browser.
351 * @return string the key
354 public static function get_autologin_key() {
356 // Delete previous keys.
357 delete_user_key('tool_mobile', $USER->id);
360 $iprestriction = getremoteaddr();
361 $validuntil = time() + self::LOGIN_KEY_TTL;
362 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
366 * Creates a QR login key for the current user, this key is restricted by time and ip address.
367 * This key is used for automatically login the user in the site when the user scans a QR code in the Moodle app.
369 * @return string the key
372 public static function get_qrlogin_key() {
374 // Delete previous keys.
375 delete_user_key('tool_mobile', $USER->id);
378 $iprestriction = getremoteaddr(null);
379 $validuntil = time() + self::LOGIN_QR_KEY_TTL;
380 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
384 * Get a list of the Mobile app features.
386 * @return array array with the features grouped by theirs ubication in the app.
389 public static function get_features_list() {
391 require_once($CFG->libdir . '/authlib.php');
393 $general = new lang_string('general');
394 $mainmenu = new lang_string('mainmenu', 'tool_mobile');
395 $course = new lang_string('course');
396 $modules = new lang_string('managemodules');
397 $blocks = new lang_string('blocks');
398 $user = new lang_string('user');
399 $files = new lang_string('files');
400 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
401 $identityproviders = new lang_string('oauth2identityproviders', 'tool_mobile');
403 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
404 $coursemodules = array();
405 $appsupportedmodules = array(
406 'assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'h5pactivity', 'imscp',
407 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop');
409 foreach ($availablemods as $mod) {
410 if (in_array($mod->name, $appsupportedmodules)) {
411 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
414 asort($coursemodules);
416 $remoteaddonslist = array();
417 $mobileplugins = self::get_plugins_supporting_mobile();
418 foreach ($mobileplugins as $plugin) {
419 $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
420 $remoteaddonslist['sitePlugin_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
425 $availableblocks = core_plugin_manager::instance()->get_plugins_of_type('block');
426 $courseblocks = array();
427 $appsupportedblocks = array(
428 'activity_modules' => 'CoreBlockDelegate_AddonBlockActivityModules',
429 'activity_results' => 'CoreBlockDelegate_AddonBlockActivityResults',
430 'site_main_menu' => 'CoreBlockDelegate_AddonBlockSiteMainMenu',
431 'myoverview' => 'CoreBlockDelegate_AddonBlockMyOverview',
432 'timeline' => 'CoreBlockDelegate_AddonBlockTimeline',
433 'recentlyaccessedcourses' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedCourses',
434 'starredcourses' => 'CoreBlockDelegate_AddonBlockStarredCourses',
435 'recentlyaccesseditems' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedItems',
436 'badges' => 'CoreBlockDelegate_AddonBlockBadges',
437 'blog_menu' => 'CoreBlockDelegate_AddonBlockBlogMenu',
438 'blog_recent' => 'CoreBlockDelegate_AddonBlockBlogRecent',
439 'blog_tags' => 'CoreBlockDelegate_AddonBlockBlogTags',
440 'calendar_month' => 'CoreBlockDelegate_AddonBlockCalendarMonth',
441 'calendar_upcoming' => 'CoreBlockDelegate_AddonBlockCalendarUpcoming',
442 'comments' => 'CoreBlockDelegate_AddonBlockComments',
443 'completionstatus' => 'CoreBlockDelegate_AddonBlockCompletionStatus',
444 'feedback' => 'CoreBlockDelegate_AddonBlockFeedback',
445 'glossary_random' => 'CoreBlockDelegate_AddonBlockGlossaryRandom',
446 'html' => 'CoreBlockDelegate_AddonBlockHtml',
447 'lp' => 'CoreBlockDelegate_AddonBlockLp',
448 'news_items' => 'CoreBlockDelegate_AddonBlockNewsItems',
449 'online_users' => 'CoreBlockDelegate_AddonBlockOnlineUsers',
450 'selfcompletion' => 'CoreBlockDelegate_AddonBlockSelfCompletion',
451 'tags' => 'CoreBlockDelegate_AddonBlockTags',
454 foreach ($availableblocks as $block) {
455 if (isset($appsupportedblocks[$block->name])) {
456 $courseblocks[$appsupportedblocks[$block->name]] = $block->displayname;
459 asort($courseblocks);
463 'NoDelegate_CoreOffline' => new lang_string('offlineuse', 'tool_mobile'),
464 'NoDelegate_SiteBlocks' => new lang_string('blocks'),
465 'NoDelegate_CoreComments' => new lang_string('comments'),
466 'NoDelegate_CoreRating' => new lang_string('ratings', 'rating'),
467 'NoDelegate_CoreTag' => new lang_string('tags'),
468 '$mmLoginEmailSignup' => new lang_string('startsignup'),
469 'NoDelegate_ForgottenPassword' => new lang_string('forgotten'),
470 'NoDelegate_ResponsiveMainMenuItems' => new lang_string('responsivemainmenuitems', 'tool_mobile'),
471 'NoDelegate_H5POffline' => new lang_string('h5poffline', 'tool_mobile'),
472 'NoDelegate_DarkMode' => new lang_string('darkmode', 'tool_mobile'),
473 'CoreFilterDelegate' => new lang_string('type_filter_plural', 'plugin'),
475 "$mainmenu" => array(
476 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
477 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
478 'CoreMainMenuDelegate_CoreCoursesDashboard' => new lang_string('myhome'),
479 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
480 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
481 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
482 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
483 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
484 'CoreMainMenuDelegate_AddonBlog' => new lang_string('blog', 'blog'),
485 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
486 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
487 '$mmSideMenuDelegate_help' => new lang_string('help'),
490 'NoDelegate_CourseBlocks' => new lang_string('blocks'),
491 'CoreCourseOptionsDelegate_AddonBlog' => new lang_string('blog', 'blog'),
492 '$mmCoursesDelegate_search' => new lang_string('search'),
493 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
494 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
495 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
496 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
497 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
498 'NoDelegate_CoreCourseDownload' => new lang_string('downloadcourse', 'tool_mobile'),
499 'NoDelegate_CoreCoursesDownload' => new lang_string('downloadcourses', 'tool_mobile'),
502 'CoreUserDelegate_AddonBlog:blogs' => new lang_string('blog', 'blog'),
503 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
504 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
505 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
506 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
507 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
508 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
509 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
510 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
511 '$mmUserDelegate_picture' => new lang_string('userpic'),
514 'files_privatefiles' => new lang_string('privatefiles'),
515 'files_sitefiles' => new lang_string('sitefiles'),
516 'files_upload' => new lang_string('upload'),
518 "$modules" => $coursemodules,
519 "$blocks" => $courseblocks,
522 if (!empty($remoteaddonslist)) {
523 $features["$remoteaddons"] = $remoteaddonslist;
526 // Display OAuth 2 identity providers.
527 if (is_enabled_auth('oauth2')) {
528 $identityproviderslist = array();
529 $idps = \auth_plugin_base::get_identity_providers(['oauth2']);
531 foreach ($idps as $idp) {
532 // Only add identity providers that have an ID.
533 $id = isset($idp['url']) ? $idp['url']->get_param('id') : null;
535 $identityproviderslist['NoDelegate_IdentityProvider_' . $id] = $idp['name'];
539 if (!empty($identityproviderslist)) {
540 $features["$identityproviders"] = array();
542 if (count($identityproviderslist) > 1) {
543 // Include an option to disable them all.
544 $features["$identityproviders"]['NoDelegate_IdentityProviders'] = new lang_string('all');
547 $features["$identityproviders"] = array_merge($features["$identityproviders"], $identityproviderslist);
555 * This function check the current site for potential configuration issues that may prevent the mobile app to work.
557 * @return array list of potential issues
560 public static function get_potential_config_issues() {
562 require_once($CFG->dirroot . "/lib/filelib.php");
563 require_once($CFG->dirroot . '/message/lib.php');
568 // Return certificate information and verify the certificate.
569 $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
570 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); // Force https url.
571 // Check https using a page not redirecting or returning exceptions.
572 $curl->head($httpswwwroot . "/$CFG->admin/tool/mobile/mobile.webmanifest.php");
573 $info = $curl->get_info();
575 // First of all, check the server certificate (if any).
576 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
577 $warnings[] = ['nohttpsformobilewarning', 'admin'];
579 // Check the certificate is not self-signed or has an untrusted-root.
580 // This may be weak in some scenarios (when the curl SSL verifier is outdated).
581 if (empty($info['certinfo'])) {
582 $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
585 $expectedissuer = null;
586 foreach ($info['certinfo'] as $cert) {
587 // Check if the signature algorithm is weak (Android won't work with SHA-1).
588 if ($cert['Signature Algorithm'] == 'sha1WithRSAEncryption' || $cert['Signature Algorithm'] == 'sha1WithRSA') {
589 $warnings[] = ['insecurealgorithmwarning', 'tool_mobile'];
591 // Check certificate start date.
592 if (strtotime($cert['Start date']) > $timenow) {
593 $warnings[] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
595 // Check certificate end date.
596 if (strtotime($cert['Expire date']) < $timenow) {
597 $warnings[] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
600 if ($expectedissuer !== null) {
601 if ($expectedissuer !== $cert['Subject'] || $cert['Subject'] === $cert['Issuer']) {
602 $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
605 $expectedissuer = $cert['Issuer'];
609 // Now check typical configuration problems.
610 if ((int) $CFG->userquota === PHP_INT_MAX) {
611 // In old Moodle version was a text so was possible to have numeric values > PHP_INT_MAX.
612 $warnings[] = ['invaliduserquotawarning', 'tool_mobile'];
614 // Check ADOdb debug enabled.
615 if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
616 $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
618 // Check display errors on.
619 if (!empty($CFG->debugdisplay)) {
620 $warnings[] = ['displayerrorswarning', 'tool_mobile'];
622 // Check mobile notifications.
623 $processors = get_message_processors();
625 foreach ($processors as $processor => $status) {
626 if ($processor == 'airnotifier' && $status->enabled) {
631 $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
638 * Generates a QR code with the site URL or for automatic login from the mobile app.
640 * @param stdClass $mobilesettings tool_mobile settings
641 * @return string base64 data image contents, null if qr disabled
643 public static function generate_login_qrcode(stdClass $mobilesettings) {
646 if ($mobilesettings->qrcodetype == static::QR_CODE_DISABLED) {
650 $urlscheme = !empty($mobilesettings->forcedurlscheme) ? $mobilesettings->forcedurlscheme : 'moodlemobile';
651 $data = $urlscheme . '://' . $CFG->wwwroot;
653 if ($mobilesettings->qrcodetype == static::QR_CODE_LOGIN) {
654 $qrloginkey = static::get_qrlogin_key();
655 $data .= '?qrlogin=' . $qrloginkey . '&userid=' . $USER->id;
658 $qrcode = new core_qrcode($data);
659 $imagedata = 'data:image/png;base64,' . base64_encode($qrcode->getBarcodePngData(5, 5));