on-demand release 3.9dev+
[moodle.git] / admin / tool / mobile / classes / api.php
CommitLineData
b2478ed0
JL
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 */
25namespace tool_mobile;
26
27use core_component;
28use core_plugin_manager;
0002056f 29use context_system;
c951f1fe 30use moodle_url;
961c9549 31use moodle_exception;
b2551b4c 32use lang_string;
66a159f8 33use curl;
9df51510
JL
34use core_qrcode;
35use stdClass;
b2478ed0
JL
36
37/**
b2551b4c 38 * API exposed by tool_mobile, to be used mostly by external functions and the plugin settings.
b2478ed0
JL
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 */
44class api {
45
c951f1fe
JL
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;
961c9549
JL
52 /** @var int seconds an auto-login key will expire. */
53 const LOGIN_KEY_TTL = 60;
e624a2c8
JL
54 /** @var string URL of the Moodle Apps Portal */
55 const MOODLE_APPS_PORTAL_URL = 'https://apps.moodle.com';
9df51510
JL
56 /** @var int seconds a QR login key will expire. */
57 const LOGIN_QR_KEY_TTL = 600;
af59fe58
JL
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;
c951f1fe 64
b2478ed0
JL
65 /**
66 * Returns a list of Moodle plugins supporting the mobile app.
67 *
68 * @return array an array of objects containing the plugin information
69 */
70 public static function get_plugins_supporting_mobile() {
71 global $CFG;
72 require_once($CFG->libdir . '/adminlib.php');
73
7b1c55ea
JL
74 $cachekey = 'mobileplugins';
75 if (!isloggedin()) {
76 $cachekey = 'authmobileplugins'; // Use a different cache for not logged users.
77 }
78
30fccfcd
SK
79 // Check if we can return this from cache.
80 $cache = \cache::make('tool_mobile', 'plugininfo');
7b1c55ea 81 $pluginsinfo = $cache->get($cachekey);
30fccfcd
SK
82 if ($pluginsinfo !== false) {
83 return (array)$pluginsinfo;
84 }
85
b2478ed0 86 $pluginsinfo = [];
7b1c55ea
JL
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.
89 if (!isloggedin()) {
90 $plugintypes = array('auth' => $CFG->dirroot.'/auth');
91 } else {
92 $plugintypes = core_component::get_plugin_types();
93 }
b2478ed0
JL
94
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);
102
30fccfcd 103 require("$path/db/mobile.php");
b2478ed0 104 foreach ($addons as $addonname => $addoninfo) {
73d85fee
JL
105
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.
109
110 // Now language strings used by the app.
111 $lang = array();
112 if (!empty($addoninfo['lang'])) {
113 $stringmanager = get_string_manager();
8c5850a5 114 $langs = $stringmanager->get_list_of_translations(true);
73d85fee
JL
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);
119 }
120 }
121 }
122 $lang = json_encode($lang);
123
b2478ed0
JL
124 $plugininfo = array(
125 'component' => $component,
126 'version' => $version,
127 'addon' => $addonname,
b4baee42 128 'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
b2478ed0
JL
129 'fileurl' => '',
130 'filehash' => '',
73d85fee
JL
131 'filesize' => 0,
132 'handlers' => $handlers,
133 'lang' => $lang,
b2478ed0
JL
134 );
135
136 // All the mobile packages must be under the plugin mobile directory.
1c668c3c 137 $package = $path . '/mobile/' . $addonname . '.zip';
b2478ed0
JL
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);
142 }
143 $pluginsinfo[] = $plugininfo;
144 }
145 }
146 }
30fccfcd 147
7b1c55ea 148 $cache->set($cachekey, $pluginsinfo);
30fccfcd 149
b2478ed0
JL
150 return $pluginsinfo;
151 }
152
0002056f
JL
153 /**
154 * Returns a list of the site public settings, those not requiring authentication.
155 *
156 * @return array with the settings and warnings
157 */
7c1cb3bf 158 public static function get_public_config() {
5d5e30c6 159 global $CFG, $SITE, $PAGE, $OUTPUT;
851b2919 160 require_once($CFG->libdir . '/authlib.php');
0002056f
JL
161
162 $context = context_system::instance();
163 // We need this to make work the format text functions.
164 $PAGE->set_context($context);
165
e2fe3bc0
JL
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);
0002056f
JL
168 $settings = array(
169 'wwwroot' => $CFG->wwwroot,
672f4836 170 'httpswwwroot' => $CFG->wwwroot,
0002056f
JL
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,
2479a7c4 176 'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
e2fe3bc0 177 'authinstructions' => $authinstructions,
0002056f
JL
178 'authnoneenabled' => (int) is_enabled_auth('none'),
179 'enablewebservices' => $CFG->enablewebservices,
180 'enablemobilewebservice' => $CFG->enablemobilewebservice,
181 'maintenanceenabled' => $CFG->maintenance_enabled,
e2fe3bc0 182 'maintenancemessage' => $maintenancemessage,
91fff391 183 'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
b2551b4c 184 'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
8d9dc60b
JL
185 'country' => clean_param($CFG->country, PARAM_NOTAGS),
186 'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
e236259d
JL
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,
4bf08f5b 192 'tool_mobile_minimumversion' => get_config('tool_mobile', 'minimumversion'),
12a289c7
JL
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),
0002056f 196 );
c951f1fe
JL
197
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.
202 }
203 $settings['typeoflogin'] = $typeoflogin;
204
851b2919
JL
205 // Check if the user can sign-up to return the launch URL in that case.
206 $cansignup = signup_is_enabled();
207
b1037978
JL
208 $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
209 $settings['launchurl'] = $url->out(false);
5d5e30c6 210
6703e031
JL
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) {
818d40a9 213 $settings['logourl'] = clean_param($logourl->out(false), PARAM_URL);
5d5e30c6 214 }
6703e031 215 if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
818d40a9 216 $settings['compactlogourl'] = clean_param($compactlogourl->out(false), PARAM_URL);
5d5e30c6
JL
217 }
218
a67e3bda
JL
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;
62a08b1d
JL
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) : '';
230 }
a67e3bda
JL
231 }
232
8d9dc60b
JL
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);
237 }
238
0002056f
JL
239 return $settings;
240 }
241
6b492628
JL
242 /**
243 * Returns a list of site configurations, filtering by section.
244 *
245 * @param string $section section name
246 * @return stdClass object containing the settings
247 */
248 public static function get_config($section) {
249 global $CFG, $SITE;
250
251 $settings = new \stdClass;
252 $context = context_system::instance();
253 $isadmin = has_capability('moodle/site:config', $context);
254
255 if (empty($section) or $section == 'frontpagesettings') {
256 require_once($CFG->dirroot . '/course/format/lib.php');
257 // First settings that anyone can deduce.
e2fe3bc0
JL
258 $settings->fullname = external_format_string($SITE->fullname, $context->id);
259 $settings->shortname = external_format_string($SITE->shortname, $context->id);
b14a04e0
DM
260
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,
e2fe3bc0 264 $context->id);
b14a04e0
DM
265 $settings->summary = $formattedsummary[0];
266 $settings->summaryformat = $formattedsummary[1];
6b492628
JL
267 $settings->frontpage = $CFG->frontpage;
268 $settings->frontpageloggedin = $CFG->frontpageloggedin;
269 $settings->maxcategorydepth = $CFG->maxcategorydepth;
270 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
89b909f6 271 $settings->numsections = course_get_format($SITE)->get_last_section_number();
6b492628
JL
272 $settings->newsitems = $SITE->newsitems;
273 $settings->commentsperpage = $CFG->commentsperpage;
274
275 // Now, admin settings.
276 if ($isadmin) {
277 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
278 }
279 }
280
281 if (empty($section) or $section == 'sitepolicies') {
1727c939
MG
282 $manager = new \core_privacy\local\sitepolicy\manager();
283 $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
284 $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
6b492628
JL
285 $settings->disableuserimages = $CFG->disableuserimages;
286 }
287
288 if (empty($section) or $section == 'gradessettings') {
289 require_once($CFG->dirroot . '/user/lib.php');
6703e031
JL
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);
294 }
6b492628
JL
295 }
296
7bdcf970
JL
297 if (empty($section) or $section == 'mobileapp') {
298 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
af1b6043 299 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
b2551b4c 300 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
63d142e2 301 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
04df75ce 302 $settings->tool_mobile_apppolicy = get_config('tool_mobile', 'apppolicy');
7bdcf970
JL
303 }
304
ab1b8238
JL
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;
312 }
313
666de979
JL
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);
318 }
319 }
320
6b492628
JL
321 return $settings;
322 }
323
961c9549
JL
324 /*
325 * Check if all the required conditions are met to allow the auto-login process continue.
326 *
327 * @param int $userid current user id
328 * @since Moodle 3.2
329 * @throws moodle_exception
330 */
331 public static function check_autologin_prerequisites($userid) {
332 global $CFG;
333
334 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
335 throw new moodle_exception('enablewsdescription', 'webservice');
336 }
337
338 if (!is_https()) {
339 throw new moodle_exception('httpsrequired', 'tool_mobile');
340 }
341
342 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
343 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
344 }
345 }
346
347 /**
348 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
9df51510 349 * This key is used for automatically login the user in the site when the Moodle app opens the site in a mobile browser.
961c9549
JL
350 *
351 * @return string the key
352 * @since Moodle 3.2
353 */
354 public static function get_autologin_key() {
355 global $USER;
356 // Delete previous keys.
357 delete_user_key('tool_mobile', $USER->id);
358
359 // Create a new key.
360 $iprestriction = getremoteaddr();
361 $validuntil = time() + self::LOGIN_KEY_TTL;
362 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
363 }
b2551b4c 364
9df51510
JL
365 /**
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.
368 *
369 * @return string the key
370 * @since Moodle 3.9
371 */
372 public static function get_qrlogin_key() {
373 global $USER;
374 // Delete previous keys.
375 delete_user_key('tool_mobile', $USER->id);
376
377 // Create a new key.
378 $iprestriction = getremoteaddr(null);
379 $validuntil = time() + self::LOGIN_QR_KEY_TTL;
380 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
381 }
382
b2551b4c
JL
383 /**
384 * Get a list of the Mobile app features.
385 *
386 * @return array array with the features grouped by theirs ubication in the app.
387 * @since Moodle 3.3
388 */
389 public static function get_features_list() {
390 global $CFG;
29aeab4e 391 require_once($CFG->libdir . '/authlib.php');
b2551b4c
JL
392
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');
c1720141 397 $blocks = new lang_string('blocks');
b2551b4c
JL
398 $user = new lang_string('user');
399 $files = new lang_string('files');
400 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
29aeab4e 401 $identityproviders = new lang_string('oauth2identityproviders', 'tool_mobile');
b2551b4c
JL
402
403 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
404 $coursemodules = array();
f724514e
JL
405 $appsupportedmodules = array(
406 'assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'h5pactivity', 'imscp',
d808c220
JL
407 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop');
408
b2551b4c
JL
409 foreach ($availablemods as $mod) {
410 if (in_array($mod->name, $appsupportedmodules)) {
411 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
412 }
413 }
bf258846 414 asort($coursemodules);
b2551b4c
JL
415
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'];
d6c06935 420 $remoteaddonslist['sitePlugin_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
b2551b4c
JL
421
422 }
423
c1720141
JL
424 // Display blocks.
425 $availableblocks = core_plugin_manager::instance()->get_plugins_of_type('block');
426 $courseblocks = array();
427 $appsupportedblocks = array(
428 'activity_modules' => 'CoreBlockDelegate_AddonBlockActivityModules',
f724514e 429 'activity_results' => 'CoreBlockDelegate_AddonBlockActivityResults',
c1720141
JL
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',
bf258846
JL
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',
c1720141
JL
452 );
453
454 foreach ($availableblocks as $block) {
455 if (isset($appsupportedblocks[$block->name])) {
456 $courseblocks[$appsupportedblocks[$block->name]] = $block->displayname;
457 }
458 }
bf258846 459 asort($courseblocks);
c1720141 460
b2551b4c 461 $features = array(
bf258846
JL
462 "$general" => array(
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'),
88932e49 469 'NoDelegate_ForgottenPassword' => new lang_string('forgotten'),
bf258846 470 'NoDelegate_ResponsiveMainMenuItems' => new lang_string('responsivemainmenuitems', 'tool_mobile'),
2ccdc21b 471 'NoDelegate_H5POffline' => new lang_string('h5poffline', 'tool_mobile'),
887f7a96 472 'NoDelegate_DarkMode' => new lang_string('darkmode', 'tool_mobile'),
f724514e 473 'CoreFilterDelegate' => new lang_string('type_filter_plural', 'plugin'),
bf258846 474 ),
b2551b4c 475 "$mainmenu" => array(
b2551b4c 476 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
bf258846
JL
477 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
478 'CoreMainMenuDelegate_CoreCoursesDashboard' => new lang_string('myhome'),
479 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
b2551b4c
JL
480 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
481 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
bf258846
JL
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'),
b2551b4c
JL
485 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
486 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
487 '$mmSideMenuDelegate_help' => new lang_string('help'),
488 ),
489 "$course" => array(
bf258846
JL
490 'NoDelegate_CourseBlocks' => new lang_string('blocks'),
491 'CoreCourseOptionsDelegate_AddonBlog' => new lang_string('blog', 'blog'),
b2551b4c
JL
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'),
3c8de97d
JL
498 'NoDelegate_CoreCourseDownload' => new lang_string('downloadcourse', 'tool_mobile'),
499 'NoDelegate_CoreCoursesDownload' => new lang_string('downloadcourses', 'tool_mobile'),
b2551b4c
JL
500 ),
501 "$user" => array(
f72a4828 502 'CoreUserDelegate_AddonBlog:blogs' => new lang_string('blog', 'blog'),
b2551b4c
JL
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'),
512 ),
513 "$files" => array(
514 'files_privatefiles' => new lang_string('privatefiles'),
515 'files_sitefiles' => new lang_string('sitefiles'),
516 'files_upload' => new lang_string('upload'),
517 ),
518 "$modules" => $coursemodules,
c1720141 519 "$blocks" => $courseblocks,
b2551b4c
JL
520 );
521
522 if (!empty($remoteaddonslist)) {
523 $features["$remoteaddons"] = $remoteaddonslist;
524 }
525
29aeab4e
DP
526 // Display OAuth 2 identity providers.
527 if (is_enabled_auth('oauth2')) {
528 $identityproviderslist = array();
529 $idps = \auth_plugin_base::get_identity_providers(['oauth2']);
530
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;
534 if ($id != null) {
535 $identityproviderslist['NoDelegate_IdentityProvider_' . $id] = $idp['name'];
536 }
537 }
538
539 if (!empty($identityproviderslist)) {
540 $features["$identityproviders"] = array();
541
542 if (count($identityproviderslist) > 1) {
543 // Include an option to disable them all.
544 $features["$identityproviders"]['NoDelegate_IdentityProviders'] = new lang_string('all');
545 }
546
547 $features["$identityproviders"] = array_merge($features["$identityproviders"], $identityproviderslist);
548 }
549 }
550
b2551b4c
JL
551 return $features;
552 }
66a159f8
JL
553
554 /**
555 * This function check the current site for potential configuration issues that may prevent the mobile app to work.
556 *
557 * @return array list of potential issues
558 * @since Moodle 3.4
559 */
560 public static function get_potential_config_issues() {
561 global $CFG;
562 require_once($CFG->dirroot . "/lib/filelib.php");
563 require_once($CFG->dirroot . '/message/lib.php');
564
565 $warnings = array();
566
567 $curl = new curl();
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.
098b16fb
JL
571 // Check https using a page not redirecting or returning exceptions.
572 $curl->head($httpswwwroot . "/$CFG->admin/tool/mobile/mobile.webmanifest.php");
66a159f8
JL
573 $info = $curl->get_info();
574
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'];
578 } else {
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'];
583 } else {
584 $timenow = time();
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'];
590 }
591 // Check certificate start date.
592 if (strtotime($cert['Start date']) > $timenow) {
593 $warnings[] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
594 }
595 // Check certificate end date.
596 if (strtotime($cert['Expire date']) < $timenow) {
597 $warnings[] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
598 }
599 // Check the chain.
600 if ($expectedissuer !== null) {
601 if ($expectedissuer !== $cert['Subject'] || $cert['Subject'] === $cert['Issuer']) {
602 $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
603 }
604 }
605 $expectedissuer = $cert['Issuer'];
606 }
607 }
608 }
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'];
613 }
614 // Check ADOdb debug enabled.
615 if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
616 $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
617 }
618 // Check display errors on.
619 if (!empty($CFG->debugdisplay)) {
620 $warnings[] = ['displayerrorswarning', 'tool_mobile'];
621 }
622 // Check mobile notifications.
623 $processors = get_message_processors();
624 $enabled = false;
625 foreach ($processors as $processor => $status) {
626 if ($processor == 'airnotifier' && $status->enabled) {
627 $enabled = true;
628 }
629 }
630 if (!$enabled) {
631 $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
632 }
633
634 return $warnings;
635 }
9df51510
JL
636
637 /**
af59fe58 638 * Generates a QR code with the site URL or for automatic login from the mobile app.
9df51510
JL
639 *
640 * @param stdClass $mobilesettings tool_mobile settings
af59fe58 641 * @return string base64 data image contents, null if qr disabled
9df51510
JL
642 */
643 public static function generate_login_qrcode(stdClass $mobilesettings) {
644 global $CFG, $USER;
645
af59fe58
JL
646 if ($mobilesettings->qrcodetype == static::QR_CODE_DISABLED) {
647 return null;
648 }
649
9df51510 650 $urlscheme = !empty($mobilesettings->forcedurlscheme) ? $mobilesettings->forcedurlscheme : 'moodlemobile';
af59fe58
JL
651 $data = $urlscheme . '://' . $CFG->wwwroot;
652
653 if ($mobilesettings->qrcodetype == static::QR_CODE_LOGIN) {
654 $qrloginkey = static::get_qrlogin_key();
655 $data .= '?qrlogin=' . $qrloginkey . '&userid=' . $USER->id;
656 }
9df51510
JL
657
658 $qrcode = new core_qrcode($data);
659 $imagedata = 'data:image/png;base64,' . base64_encode($qrcode->getBarcodePngData(5, 5));
660
661 return $imagedata;
662 }
b2478ed0 663}