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