MDL-69031 tool_mobile: Add missing features that can be disabled in 3.9
[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;
509a4c58
JL
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';
c951f1fe 68
b2478ed0
JL
69 /**
70 * Returns a list of Moodle plugins supporting the mobile app.
71 *
72 * @return array an array of objects containing the plugin information
73 */
74 public static function get_plugins_supporting_mobile() {
75 global $CFG;
76 require_once($CFG->libdir . '/adminlib.php');
77
7b1c55ea
JL
78 $cachekey = 'mobileplugins';
79 if (!isloggedin()) {
80 $cachekey = 'authmobileplugins'; // Use a different cache for not logged users.
81 }
82
30fccfcd
SK
83 // Check if we can return this from cache.
84 $cache = \cache::make('tool_mobile', 'plugininfo');
7b1c55ea 85 $pluginsinfo = $cache->get($cachekey);
30fccfcd
SK
86 if ($pluginsinfo !== false) {
87 return (array)$pluginsinfo;
88 }
89
b2478ed0 90 $pluginsinfo = [];
7b1c55ea
JL
91 // For not logged users return only auth plugins.
92 // This is to avoid anyone (not being a registered user) to obtain and download all the site remote add-ons.
93 if (!isloggedin()) {
94 $plugintypes = array('auth' => $CFG->dirroot.'/auth');
95 } else {
96 $plugintypes = core_component::get_plugin_types();
97 }
b2478ed0
JL
98
99 foreach ($plugintypes as $plugintype => $unused) {
100 // We need to include files here.
101 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
102 foreach ($pluginswithfile as $plugin => $notused) {
103 $path = core_component::get_plugin_directory($plugintype, $plugin);
104 $component = $plugintype . '_' . $plugin;
105 $version = get_component_version($component);
106
30fccfcd 107 require("$path/db/mobile.php");
b2478ed0 108 foreach ($addons as $addonname => $addoninfo) {
73d85fee
JL
109
110 // Add handlers (for site add-ons).
111 $handlers = !empty($addoninfo['handlers']) ? $addoninfo['handlers'] : array();
112 $handlers = json_encode($handlers); // JSON formatted, since it is a complex structure that may vary over time.
113
114 // Now language strings used by the app.
115 $lang = array();
116 if (!empty($addoninfo['lang'])) {
117 $stringmanager = get_string_manager();
8c5850a5 118 $langs = $stringmanager->get_list_of_translations(true);
73d85fee
JL
119 foreach ($langs as $langid => $langname) {
120 foreach ($addoninfo['lang'] as $stringinfo) {
121 $lang[$langid][$stringinfo[0]] =
122 $stringmanager->get_string($stringinfo[0], $stringinfo[1], null, $langid);
123 }
124 }
125 }
126 $lang = json_encode($lang);
127
b2478ed0
JL
128 $plugininfo = array(
129 'component' => $component,
130 'version' => $version,
131 'addon' => $addonname,
b4baee42 132 'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
b2478ed0
JL
133 'fileurl' => '',
134 'filehash' => '',
73d85fee
JL
135 'filesize' => 0,
136 'handlers' => $handlers,
137 'lang' => $lang,
b2478ed0
JL
138 );
139
140 // All the mobile packages must be under the plugin mobile directory.
1c668c3c 141 $package = $path . '/mobile/' . $addonname . '.zip';
b2478ed0
JL
142 if (file_exists($package)) {
143 $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
144 $plugininfo['filehash'] = sha1_file($package);
145 $plugininfo['filesize'] = filesize($package);
146 }
147 $pluginsinfo[] = $plugininfo;
148 }
149 }
150 }
30fccfcd 151
7b1c55ea 152 $cache->set($cachekey, $pluginsinfo);
30fccfcd 153
b2478ed0
JL
154 return $pluginsinfo;
155 }
156
0002056f
JL
157 /**
158 * Returns a list of the site public settings, those not requiring authentication.
159 *
160 * @return array with the settings and warnings
161 */
7c1cb3bf 162 public static function get_public_config() {
5d5e30c6 163 global $CFG, $SITE, $PAGE, $OUTPUT;
851b2919 164 require_once($CFG->libdir . '/authlib.php');
0002056f
JL
165
166 $context = context_system::instance();
167 // We need this to make work the format text functions.
168 $PAGE->set_context($context);
169
e2fe3bc0
JL
170 list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
171 list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
0002056f
JL
172 $settings = array(
173 'wwwroot' => $CFG->wwwroot,
672f4836 174 'httpswwwroot' => $CFG->wwwroot,
0002056f
JL
175 'sitename' => external_format_string($SITE->fullname, $context->id, true),
176 'guestlogin' => $CFG->guestloginbutton,
177 'rememberusername' => $CFG->rememberusername,
178 'authloginviaemail' => $CFG->authloginviaemail,
179 'registerauth' => $CFG->registerauth,
2479a7c4 180 'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
e2fe3bc0 181 'authinstructions' => $authinstructions,
0002056f
JL
182 'authnoneenabled' => (int) is_enabled_auth('none'),
183 'enablewebservices' => $CFG->enablewebservices,
184 'enablemobilewebservice' => $CFG->enablemobilewebservice,
185 'maintenanceenabled' => $CFG->maintenance_enabled,
e2fe3bc0 186 'maintenancemessage' => $maintenancemessage,
91fff391 187 'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
b2551b4c 188 'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
8d9dc60b
JL
189 'country' => clean_param($CFG->country, PARAM_NOTAGS),
190 'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
e236259d
JL
191 'autolang' => $CFG->autolang,
192 'lang' => clean_param($CFG->lang, PARAM_LANG), // Avoid breaking WS because of incorrect package langs.
193 'langmenu' => $CFG->langmenu,
194 'langlist' => $CFG->langlist,
195 'locale' => $CFG->locale,
4bf08f5b 196 'tool_mobile_minimumversion' => get_config('tool_mobile', 'minimumversion'),
12a289c7
JL
197 'tool_mobile_iosappid' => get_config('tool_mobile', 'iosappid'),
198 'tool_mobile_androidappid' => get_config('tool_mobile', 'androidappid'),
199 'tool_mobile_setuplink' => clean_param(get_config('tool_mobile', 'setuplink'), PARAM_URL),
0002056f 200 );
c951f1fe
JL
201
202 $typeoflogin = get_config('tool_mobile', 'typeoflogin');
203 // Not found, edge case.
204 if ($typeoflogin === false) {
205 $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
206 }
207 $settings['typeoflogin'] = $typeoflogin;
208
851b2919
JL
209 // Check if the user can sign-up to return the launch URL in that case.
210 $cansignup = signup_is_enabled();
211
b1037978
JL
212 $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
213 $settings['launchurl'] = $url->out(false);
5d5e30c6 214
6703e031
JL
215 // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
216 if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
818d40a9 217 $settings['logourl'] = clean_param($logourl->out(false), PARAM_URL);
5d5e30c6 218 }
6703e031 219 if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
818d40a9 220 $settings['compactlogourl'] = clean_param($compactlogourl->out(false), PARAM_URL);
5d5e30c6
JL
221 }
222
a67e3bda
JL
223 // Identity providers.
224 $authsequence = get_enabled_auth_plugins(true);
225 $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
226 $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
227 if (!empty($identityprovidersdata)) {
228 $settings['identityproviders'] = $identityprovidersdata;
62a08b1d
JL
229 // Clean URLs to avoid breaking Web Services.
230 // We can't do it in prepare_identity_providers_for_output() because it may break the web output.
231 foreach ($settings['identityproviders'] as &$ip) {
232 $ip['url'] = (!empty($ip['url'])) ? clean_param($ip['url'], PARAM_URL) : '';
233 $ip['iconurl'] = (!empty($ip['iconurl'])) ? clean_param($ip['iconurl'], PARAM_URL) : '';
234 }
a67e3bda
JL
235 }
236
8d9dc60b
JL
237 // If age is verified, return also the admin contact details.
238 if ($settings['agedigitalconsentverification']) {
239 $settings['supportname'] = clean_param($CFG->supportname, PARAM_NOTAGS);
240 $settings['supportemail'] = clean_param($CFG->supportemail, PARAM_EMAIL);
241 }
242
0002056f
JL
243 return $settings;
244 }
245
6b492628
JL
246 /**
247 * Returns a list of site configurations, filtering by section.
248 *
249 * @param string $section section name
250 * @return stdClass object containing the settings
251 */
252 public static function get_config($section) {
253 global $CFG, $SITE;
254
255 $settings = new \stdClass;
256 $context = context_system::instance();
257 $isadmin = has_capability('moodle/site:config', $context);
258
259 if (empty($section) or $section == 'frontpagesettings') {
260 require_once($CFG->dirroot . '/course/format/lib.php');
261 // First settings that anyone can deduce.
e2fe3bc0
JL
262 $settings->fullname = external_format_string($SITE->fullname, $context->id);
263 $settings->shortname = external_format_string($SITE->shortname, $context->id);
b14a04e0
DM
264
265 // Return to a var instead of directly to $settings object because of differences between
266 // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
267 $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
e2fe3bc0 268 $context->id);
b14a04e0
DM
269 $settings->summary = $formattedsummary[0];
270 $settings->summaryformat = $formattedsummary[1];
6b492628
JL
271 $settings->frontpage = $CFG->frontpage;
272 $settings->frontpageloggedin = $CFG->frontpageloggedin;
273 $settings->maxcategorydepth = $CFG->maxcategorydepth;
274 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
89b909f6 275 $settings->numsections = course_get_format($SITE)->get_last_section_number();
6b492628
JL
276 $settings->newsitems = $SITE->newsitems;
277 $settings->commentsperpage = $CFG->commentsperpage;
278
279 // Now, admin settings.
280 if ($isadmin) {
281 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
282 }
283 }
284
285 if (empty($section) or $section == 'sitepolicies') {
1727c939
MG
286 $manager = new \core_privacy\local\sitepolicy\manager();
287 $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
288 $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
6b492628
JL
289 $settings->disableuserimages = $CFG->disableuserimages;
290 }
291
292 if (empty($section) or $section == 'gradessettings') {
293 require_once($CFG->dirroot . '/user/lib.php');
6703e031
JL
294 $settings->mygradesurl = user_mygrades_url();
295 // The previous function may return moodle_url instances or plain string URLs.
296 if ($settings->mygradesurl instanceof moodle_url) {
297 $settings->mygradesurl = $settings->mygradesurl->out(false);
298 }
6b492628
JL
299 }
300
7bdcf970
JL
301 if (empty($section) or $section == 'mobileapp') {
302 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
af1b6043 303 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
b2551b4c 304 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
63d142e2 305 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
04df75ce 306 $settings->tool_mobile_apppolicy = get_config('tool_mobile', 'apppolicy');
7bdcf970
JL
307 }
308
ab1b8238
JL
309 if (empty($section) or $section == 'calendar') {
310 $settings->calendartype = $CFG->calendartype;
311 $settings->calendar_site_timeformat = $CFG->calendar_site_timeformat;
312 $settings->calendar_startwday = $CFG->calendar_startwday;
313 $settings->calendar_adminseesall = $CFG->calendar_adminseesall;
314 $settings->calendar_lookahead = $CFG->calendar_lookahead;
315 $settings->calendar_maxevents = $CFG->calendar_maxevents;
316 }
317
666de979
JL
318 if (empty($section) or $section == 'coursecolors') {
319 $colornumbers = range(1, 10);
320 foreach ($colornumbers as $number) {
321 $settings->{'core_admin_coursecolor' . $number} = get_config('core_admin', 'coursecolor' . $number);
322 }
323 }
324
6b492628
JL
325 return $settings;
326 }
327
961c9549
JL
328 /*
329 * Check if all the required conditions are met to allow the auto-login process continue.
330 *
331 * @param int $userid current user id
332 * @since Moodle 3.2
333 * @throws moodle_exception
334 */
335 public static function check_autologin_prerequisites($userid) {
336 global $CFG;
337
338 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
339 throw new moodle_exception('enablewsdescription', 'webservice');
340 }
341
342 if (!is_https()) {
343 throw new moodle_exception('httpsrequired', 'tool_mobile');
344 }
345
346 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
347 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
348 }
349 }
350
351 /**
352 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
9df51510 353 * 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
354 *
355 * @return string the key
356 * @since Moodle 3.2
357 */
358 public static function get_autologin_key() {
359 global $USER;
360 // Delete previous keys.
361 delete_user_key('tool_mobile', $USER->id);
362
363 // Create a new key.
364 $iprestriction = getremoteaddr();
365 $validuntil = time() + self::LOGIN_KEY_TTL;
366 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
367 }
b2551b4c 368
9df51510
JL
369 /**
370 * Creates a QR login key for the current user, this key is restricted by time and ip address.
371 * This key is used for automatically login the user in the site when the user scans a QR code in the Moodle app.
372 *
373 * @return string the key
374 * @since Moodle 3.9
375 */
376 public static function get_qrlogin_key() {
377 global $USER;
378 // Delete previous keys.
379 delete_user_key('tool_mobile', $USER->id);
380
381 // Create a new key.
382 $iprestriction = getremoteaddr(null);
383 $validuntil = time() + self::LOGIN_QR_KEY_TTL;
384 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
385 }
386
b2551b4c
JL
387 /**
388 * Get a list of the Mobile app features.
389 *
390 * @return array array with the features grouped by theirs ubication in the app.
391 * @since Moodle 3.3
392 */
393 public static function get_features_list() {
394 global $CFG;
29aeab4e 395 require_once($CFG->libdir . '/authlib.php');
b2551b4c
JL
396
397 $general = new lang_string('general');
398 $mainmenu = new lang_string('mainmenu', 'tool_mobile');
399 $course = new lang_string('course');
400 $modules = new lang_string('managemodules');
c1720141 401 $blocks = new lang_string('blocks');
b2551b4c
JL
402 $user = new lang_string('user');
403 $files = new lang_string('files');
404 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
29aeab4e 405 $identityproviders = new lang_string('oauth2identityproviders', 'tool_mobile');
b2551b4c
JL
406
407 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
408 $coursemodules = array();
f724514e
JL
409 $appsupportedmodules = array(
410 'assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'h5pactivity', 'imscp',
d808c220
JL
411 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki', 'workshop');
412
b2551b4c
JL
413 foreach ($availablemods as $mod) {
414 if (in_array($mod->name, $appsupportedmodules)) {
415 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
416 }
417 }
bf258846 418 asort($coursemodules);
b2551b4c
JL
419
420 $remoteaddonslist = array();
421 $mobileplugins = self::get_plugins_supporting_mobile();
422 foreach ($mobileplugins as $plugin) {
423 $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
d6c06935 424 $remoteaddonslist['sitePlugin_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
b2551b4c
JL
425
426 }
427
c1720141
JL
428 // Display blocks.
429 $availableblocks = core_plugin_manager::instance()->get_plugins_of_type('block');
430 $courseblocks = array();
431 $appsupportedblocks = array(
432 'activity_modules' => 'CoreBlockDelegate_AddonBlockActivityModules',
f724514e 433 'activity_results' => 'CoreBlockDelegate_AddonBlockActivityResults',
c1720141
JL
434 'site_main_menu' => 'CoreBlockDelegate_AddonBlockSiteMainMenu',
435 'myoverview' => 'CoreBlockDelegate_AddonBlockMyOverview',
436 'timeline' => 'CoreBlockDelegate_AddonBlockTimeline',
437 'recentlyaccessedcourses' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedCourses',
438 'starredcourses' => 'CoreBlockDelegate_AddonBlockStarredCourses',
439 'recentlyaccesseditems' => 'CoreBlockDelegate_AddonBlockRecentlyAccessedItems',
bf258846
JL
440 'badges' => 'CoreBlockDelegate_AddonBlockBadges',
441 'blog_menu' => 'CoreBlockDelegate_AddonBlockBlogMenu',
442 'blog_recent' => 'CoreBlockDelegate_AddonBlockBlogRecent',
443 'blog_tags' => 'CoreBlockDelegate_AddonBlockBlogTags',
444 'calendar_month' => 'CoreBlockDelegate_AddonBlockCalendarMonth',
445 'calendar_upcoming' => 'CoreBlockDelegate_AddonBlockCalendarUpcoming',
446 'comments' => 'CoreBlockDelegate_AddonBlockComments',
447 'completionstatus' => 'CoreBlockDelegate_AddonBlockCompletionStatus',
448 'feedback' => 'CoreBlockDelegate_AddonBlockFeedback',
449 'glossary_random' => 'CoreBlockDelegate_AddonBlockGlossaryRandom',
450 'html' => 'CoreBlockDelegate_AddonBlockHtml',
451 'lp' => 'CoreBlockDelegate_AddonBlockLp',
452 'news_items' => 'CoreBlockDelegate_AddonBlockNewsItems',
453 'online_users' => 'CoreBlockDelegate_AddonBlockOnlineUsers',
454 'selfcompletion' => 'CoreBlockDelegate_AddonBlockSelfCompletion',
455 'tags' => 'CoreBlockDelegate_AddonBlockTags',
c1720141
JL
456 );
457
458 foreach ($availableblocks as $block) {
459 if (isset($appsupportedblocks[$block->name])) {
460 $courseblocks[$appsupportedblocks[$block->name]] = $block->displayname;
461 }
462 }
bf258846 463 asort($courseblocks);
c1720141 464
b2551b4c 465 $features = array(
bf258846
JL
466 "$general" => array(
467 'NoDelegate_CoreOffline' => new lang_string('offlineuse', 'tool_mobile'),
468 'NoDelegate_SiteBlocks' => new lang_string('blocks'),
469 'NoDelegate_CoreComments' => new lang_string('comments'),
470 'NoDelegate_CoreRating' => new lang_string('ratings', 'rating'),
471 'NoDelegate_CoreTag' => new lang_string('tags'),
472 '$mmLoginEmailSignup' => new lang_string('startsignup'),
88932e49 473 'NoDelegate_ForgottenPassword' => new lang_string('forgotten'),
bf258846 474 'NoDelegate_ResponsiveMainMenuItems' => new lang_string('responsivemainmenuitems', 'tool_mobile'),
2ccdc21b 475 'NoDelegate_H5POffline' => new lang_string('h5poffline', 'tool_mobile'),
887f7a96 476 'NoDelegate_DarkMode' => new lang_string('darkmode', 'tool_mobile'),
f724514e 477 'CoreFilterDelegate' => new lang_string('type_filter_plural', 'plugin'),
bf258846 478 ),
b2551b4c 479 "$mainmenu" => array(
b2551b4c 480 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
bf258846
JL
481 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
482 'CoreMainMenuDelegate_CoreCoursesDashboard' => new lang_string('myhome'),
483 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
b2551b4c
JL
484 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
485 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
bf258846
JL
486 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
487 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
488 'CoreMainMenuDelegate_AddonBlog' => new lang_string('blog', 'blog'),
b2551b4c
JL
489 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
490 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
491 '$mmSideMenuDelegate_help' => new lang_string('help'),
01ec0ee8 492 'CoreMainMenuDelegate_QrReader' => new lang_string('scanqrcode', 'tool_mobile'),
b2551b4c
JL
493 ),
494 "$course" => array(
bf258846
JL
495 'NoDelegate_CourseBlocks' => new lang_string('blocks'),
496 'CoreCourseOptionsDelegate_AddonBlog' => new lang_string('blog', 'blog'),
b2551b4c
JL
497 '$mmCoursesDelegate_search' => new lang_string('search'),
498 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
499 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
500 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
501 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
502 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
3c8de97d
JL
503 'NoDelegate_CoreCourseDownload' => new lang_string('downloadcourse', 'tool_mobile'),
504 'NoDelegate_CoreCoursesDownload' => new lang_string('downloadcourses', 'tool_mobile'),
b2551b4c
JL
505 ),
506 "$user" => array(
f72a4828 507 'CoreUserDelegate_AddonBlog:blogs' => new lang_string('blog', 'blog'),
b2551b4c
JL
508 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
509 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
510 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
511 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
512 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
513 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
514 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
515 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
516 '$mmUserDelegate_picture' => new lang_string('userpic'),
517 ),
518 "$files" => array(
519 'files_privatefiles' => new lang_string('privatefiles'),
520 'files_sitefiles' => new lang_string('sitefiles'),
521 'files_upload' => new lang_string('upload'),
522 ),
523 "$modules" => $coursemodules,
c1720141 524 "$blocks" => $courseblocks,
b2551b4c
JL
525 );
526
527 if (!empty($remoteaddonslist)) {
528 $features["$remoteaddons"] = $remoteaddonslist;
529 }
530
01ec0ee8
JL
531 if (!empty($availablemods['lti'])) {
532 $ltidisplayname = $availablemods['lti']->displayname;
533 $features["$ltidisplayname"]['CoreCourseModuleDelegate_AddonModLti:openInAppBrowser'] =
534 new lang_string('openusingembeddedbrowser', 'tool_mobile');
535 }
536
29aeab4e
DP
537 // Display OAuth 2 identity providers.
538 if (is_enabled_auth('oauth2')) {
539 $identityproviderslist = array();
540 $idps = \auth_plugin_base::get_identity_providers(['oauth2']);
541
542 foreach ($idps as $idp) {
543 // Only add identity providers that have an ID.
544 $id = isset($idp['url']) ? $idp['url']->get_param('id') : null;
545 if ($id != null) {
546 $identityproviderslist['NoDelegate_IdentityProvider_' . $id] = $idp['name'];
547 }
548 }
549
550 if (!empty($identityproviderslist)) {
551 $features["$identityproviders"] = array();
552
553 if (count($identityproviderslist) > 1) {
554 // Include an option to disable them all.
555 $features["$identityproviders"]['NoDelegate_IdentityProviders'] = new lang_string('all');
556 }
557
558 $features["$identityproviders"] = array_merge($features["$identityproviders"], $identityproviderslist);
559 }
560 }
561
b2551b4c
JL
562 return $features;
563 }
66a159f8
JL
564
565 /**
566 * This function check the current site for potential configuration issues that may prevent the mobile app to work.
567 *
568 * @return array list of potential issues
569 * @since Moodle 3.4
570 */
571 public static function get_potential_config_issues() {
572 global $CFG;
573 require_once($CFG->dirroot . "/lib/filelib.php");
574 require_once($CFG->dirroot . '/message/lib.php');
575
576 $warnings = array();
577
578 $curl = new curl();
579 // Return certificate information and verify the certificate.
580 $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
581 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); // Force https url.
098b16fb
JL
582 // Check https using a page not redirecting or returning exceptions.
583 $curl->head($httpswwwroot . "/$CFG->admin/tool/mobile/mobile.webmanifest.php");
66a159f8
JL
584 $info = $curl->get_info();
585
586 // First of all, check the server certificate (if any).
587 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
588 $warnings[] = ['nohttpsformobilewarning', 'admin'];
589 } else {
590 // Check the certificate is not self-signed or has an untrusted-root.
591 // This may be weak in some scenarios (when the curl SSL verifier is outdated).
592 if (empty($info['certinfo'])) {
593 $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
594 } else {
595 $timenow = time();
596 $expectedissuer = null;
597 foreach ($info['certinfo'] as $cert) {
598 // Check if the signature algorithm is weak (Android won't work with SHA-1).
599 if ($cert['Signature Algorithm'] == 'sha1WithRSAEncryption' || $cert['Signature Algorithm'] == 'sha1WithRSA') {
600 $warnings[] = ['insecurealgorithmwarning', 'tool_mobile'];
601 }
602 // Check certificate start date.
603 if (strtotime($cert['Start date']) > $timenow) {
604 $warnings[] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
605 }
606 // Check certificate end date.
607 if (strtotime($cert['Expire date']) < $timenow) {
608 $warnings[] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
609 }
610 // Check the chain.
611 if ($expectedissuer !== null) {
612 if ($expectedissuer !== $cert['Subject'] || $cert['Subject'] === $cert['Issuer']) {
613 $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
614 }
615 }
616 $expectedissuer = $cert['Issuer'];
617 }
618 }
619 }
620 // Now check typical configuration problems.
621 if ((int) $CFG->userquota === PHP_INT_MAX) {
622 // In old Moodle version was a text so was possible to have numeric values > PHP_INT_MAX.
623 $warnings[] = ['invaliduserquotawarning', 'tool_mobile'];
624 }
625 // Check ADOdb debug enabled.
626 if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
627 $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
628 }
629 // Check display errors on.
630 if (!empty($CFG->debugdisplay)) {
631 $warnings[] = ['displayerrorswarning', 'tool_mobile'];
632 }
633 // Check mobile notifications.
634 $processors = get_message_processors();
635 $enabled = false;
636 foreach ($processors as $processor => $status) {
637 if ($processor == 'airnotifier' && $status->enabled) {
638 $enabled = true;
639 }
640 }
641 if (!$enabled) {
642 $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
643 }
644
645 return $warnings;
646 }
9df51510
JL
647
648 /**
af59fe58 649 * Generates a QR code with the site URL or for automatic login from the mobile app.
9df51510
JL
650 *
651 * @param stdClass $mobilesettings tool_mobile settings
af59fe58 652 * @return string base64 data image contents, null if qr disabled
9df51510
JL
653 */
654 public static function generate_login_qrcode(stdClass $mobilesettings) {
655 global $CFG, $USER;
656
af59fe58
JL
657 if ($mobilesettings->qrcodetype == static::QR_CODE_DISABLED) {
658 return null;
659 }
660
9df51510 661 $urlscheme = !empty($mobilesettings->forcedurlscheme) ? $mobilesettings->forcedurlscheme : 'moodlemobile';
af59fe58
JL
662 $data = $urlscheme . '://' . $CFG->wwwroot;
663
664 if ($mobilesettings->qrcodetype == static::QR_CODE_LOGIN) {
665 $qrloginkey = static::get_qrlogin_key();
666 $data .= '?qrlogin=' . $qrloginkey . '&userid=' . $USER->id;
667 }
9df51510
JL
668
669 $qrcode = new core_qrcode($data);
670 $imagedata = 'data:image/png;base64,' . base64_encode($qrcode->getBarcodePngData(5, 5));
671
672 return $imagedata;
673 }
33dbc582
JL
674
675 /**
676 * Gets Moodle app plan subscription information for the current site as it is returned by the Apps Portal.
677 *
678 * @return array Subscription information
679 */
680 public static function get_subscription_information() : ?array {
681 global $CFG;
682
683 // Use session cache to prevent multiple requests.
684 $cache = \cache::make('tool_mobile', 'subscriptiondata');
685 $subscriptiondata = $cache->get(0);
686 if ($subscriptiondata !== false) {
687 return $subscriptiondata;
688 }
689
690 $mobilesettings = get_config('tool_mobile');
691
692 // To validate that the requests come from this site we need to send some private information that only is known by the
693 // Moodle Apps portal or the Sites registration database.
694 $credentials = [];
695
696 if (!empty($CFG->airnotifieraccesskey)) {
697 $credentials[] = ['type' => 'airnotifieraccesskey', 'value' => $CFG->airnotifieraccesskey];
698 }
699 if (\core\hub\registration::is_registered()) {
700 $credentials[] = ['type' => 'siteid', 'value' => $CFG->siteidentifier];
701 }
df2aa348 702 // Generate a hash key for validating that the request is coming from this site via WS.
509a4c58
JL
703 $key = complex_random_string(32);
704 $sitesubscriptionkey = json_encode(['validuntil' => time() + 10 * MINSECS, 'key' => $key]);
df2aa348 705 set_config('sitesubscriptionkey', $sitesubscriptionkey, 'tool_mobile');
509a4c58 706 $credentials[] = ['type' => 'sitesubscriptionkey', 'value' => $key];
33dbc582
JL
707
708 // Parameters for the WebService returning site information.
509a4c58
JL
709 $androidappid = empty($mobilesettings->androidappid) ? static::DEFAULT_ANDROID_APP_ID : $mobilesettings->androidappid;
710 $iosappid = empty($mobilesettings->iosappid) ? static::DEFAULT_IOS_APP_ID : $mobilesettings->iosappid;
33dbc582
JL
711 $fnparams = (object) [
712 'siteurl' => $CFG->wwwroot,
509a4c58 713 'appids' => [$androidappid, $iosappid],
33dbc582
JL
714 'credentials' => $credentials,
715 ];
716 // Prepare the arguments for a request to the AJAX nologin endpoint.
717 $args = [
718 (object) [
719 'index' => 0,
720 'methodname' => 'local_apps_get_site_info',
721 'args' => $fnparams,
722 ]
723 ];
724
725 // Ask the Moodle Apps Portal for the subscription information.
726 $curl = new curl();
727 $curl->setopt(array('CURLOPT_TIMEOUT' => 10, 'CURLOPT_CONNECTTIMEOUT' => 10));
728
729 $serverurl = static::MOODLE_APPS_PORTAL_URL . "/lib/ajax/service-nologin.php";
730 $query = 'args=' . urlencode(json_encode($args));
731 $wsresponse = @json_decode($curl->post($serverurl, $query), true);
732
733 $info = $curl->get_info();
734 if ($curlerrno = $curl->get_errno()) {
735 // CURL connection error.
736 debugging("Unexpected response from the Moodle Apps Portal server, CURL error number: $curlerrno");
737 return null;
738 } else if ($info['http_code'] != 200) {
739 // Unexpected error from server.
740 debugging('Unexpected response from the Moodle Apps Portal server, HTTP code:' . $info['httpcode']);
741 return null;
742 } else if (!empty($wsresponse[0]['error'])) {
743 // Unexpected error from Moodle Apps Portal.
744 debugging('Unexpected response from the Moodle Apps Portal server:' . json_encode($wsresponse[0]));
745 return null;
746 } else if (empty($wsresponse[0]['data'])) {
747 debugging('Unexpected response from the Moodle Apps Portal server:' . json_encode($wsresponse));
748 return null;
749 }
750
751 $cache->set(0, $wsresponse[0]['data']);
752
753 return $wsresponse[0]['data'];
754 }
b2478ed0 755}