MDL-61622 auth: New WS is_age_digital_consent_verification_enabled
[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;
c951f1fe 52
b2478ed0
JL
53 /**
54 * Returns a list of Moodle plugins supporting the mobile app.
55 *
56 * @return array an array of objects containing the plugin information
57 */
58 public static function get_plugins_supporting_mobile() {
59 global $CFG;
60 require_once($CFG->libdir . '/adminlib.php');
61
7b1c55ea
JL
62 $cachekey = 'mobileplugins';
63 if (!isloggedin()) {
64 $cachekey = 'authmobileplugins'; // Use a different cache for not logged users.
65 }
66
30fccfcd
SK
67 // Check if we can return this from cache.
68 $cache = \cache::make('tool_mobile', 'plugininfo');
7b1c55ea 69 $pluginsinfo = $cache->get($cachekey);
30fccfcd
SK
70 if ($pluginsinfo !== false) {
71 return (array)$pluginsinfo;
72 }
73
b2478ed0 74 $pluginsinfo = [];
7b1c55ea
JL
75 // For not logged users return only auth plugins.
76 // This is to avoid anyone (not being a registered user) to obtain and download all the site remote add-ons.
77 if (!isloggedin()) {
78 $plugintypes = array('auth' => $CFG->dirroot.'/auth');
79 } else {
80 $plugintypes = core_component::get_plugin_types();
81 }
b2478ed0
JL
82
83 foreach ($plugintypes as $plugintype => $unused) {
84 // We need to include files here.
85 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
86 foreach ($pluginswithfile as $plugin => $notused) {
87 $path = core_component::get_plugin_directory($plugintype, $plugin);
88 $component = $plugintype . '_' . $plugin;
89 $version = get_component_version($component);
90
30fccfcd 91 require("$path/db/mobile.php");
b2478ed0
JL
92 foreach ($addons as $addonname => $addoninfo) {
93 $plugininfo = array(
94 'component' => $component,
95 'version' => $version,
96 'addon' => $addonname,
b4baee42 97 'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
b2478ed0
JL
98 'fileurl' => '',
99 'filehash' => '',
100 'filesize' => 0
101 );
102
103 // All the mobile packages must be under the plugin mobile directory.
1c668c3c 104 $package = $path . '/mobile/' . $addonname . '.zip';
b2478ed0
JL
105 if (file_exists($package)) {
106 $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
107 $plugininfo['filehash'] = sha1_file($package);
108 $plugininfo['filesize'] = filesize($package);
109 }
110 $pluginsinfo[] = $plugininfo;
111 }
112 }
113 }
30fccfcd 114
7b1c55ea 115 $cache->set($cachekey, $pluginsinfo);
30fccfcd 116
b2478ed0
JL
117 return $pluginsinfo;
118 }
119
0002056f
JL
120 /**
121 * Returns a list of the site public settings, those not requiring authentication.
122 *
123 * @return array with the settings and warnings
124 */
7c1cb3bf 125 public static function get_public_config() {
5d5e30c6 126 global $CFG, $SITE, $PAGE, $OUTPUT;
851b2919 127 require_once($CFG->libdir . '/authlib.php');
0002056f
JL
128
129 $context = context_system::instance();
130 // We need this to make work the format text functions.
131 $PAGE->set_context($context);
132
e2fe3bc0
JL
133 list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
134 list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
0002056f
JL
135 $settings = array(
136 'wwwroot' => $CFG->wwwroot,
672f4836 137 'httpswwwroot' => $CFG->wwwroot,
0002056f
JL
138 'sitename' => external_format_string($SITE->fullname, $context->id, true),
139 'guestlogin' => $CFG->guestloginbutton,
140 'rememberusername' => $CFG->rememberusername,
141 'authloginviaemail' => $CFG->authloginviaemail,
142 'registerauth' => $CFG->registerauth,
2479a7c4 143 'forgottenpasswordurl' => clean_param($CFG->forgottenpasswordurl, PARAM_URL), // We may expect a mailto: here.
e2fe3bc0 144 'authinstructions' => $authinstructions,
0002056f
JL
145 'authnoneenabled' => (int) is_enabled_auth('none'),
146 'enablewebservices' => $CFG->enablewebservices,
147 'enablemobilewebservice' => $CFG->enablemobilewebservice,
148 'maintenanceenabled' => $CFG->maintenance_enabled,
e2fe3bc0 149 'maintenancemessage' => $maintenancemessage,
91fff391 150 'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
b2551b4c 151 'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
0002056f 152 );
c951f1fe
JL
153
154 $typeoflogin = get_config('tool_mobile', 'typeoflogin');
155 // Not found, edge case.
156 if ($typeoflogin === false) {
157 $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
158 }
159 $settings['typeoflogin'] = $typeoflogin;
160
851b2919
JL
161 // Check if the user can sign-up to return the launch URL in that case.
162 $cansignup = signup_is_enabled();
163
b1037978
JL
164 $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
165 $settings['launchurl'] = $url->out(false);
5d5e30c6 166
6703e031
JL
167 // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
168 if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
5d5e30c6
JL
169 $settings['logourl'] = $logourl->out(false);
170 }
6703e031 171 if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
5d5e30c6
JL
172 $settings['compactlogourl'] = $compactlogourl->out(false);
173 }
174
a67e3bda
JL
175 // Identity providers.
176 $authsequence = get_enabled_auth_plugins(true);
177 $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
178 $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
179 if (!empty($identityprovidersdata)) {
180 $settings['identityproviders'] = $identityprovidersdata;
181 }
182
0002056f
JL
183 return $settings;
184 }
185
6b492628
JL
186 /**
187 * Returns a list of site configurations, filtering by section.
188 *
189 * @param string $section section name
190 * @return stdClass object containing the settings
191 */
192 public static function get_config($section) {
193 global $CFG, $SITE;
194
195 $settings = new \stdClass;
196 $context = context_system::instance();
197 $isadmin = has_capability('moodle/site:config', $context);
198
199 if (empty($section) or $section == 'frontpagesettings') {
200 require_once($CFG->dirroot . '/course/format/lib.php');
201 // First settings that anyone can deduce.
e2fe3bc0
JL
202 $settings->fullname = external_format_string($SITE->fullname, $context->id);
203 $settings->shortname = external_format_string($SITE->shortname, $context->id);
b14a04e0
DM
204
205 // Return to a var instead of directly to $settings object because of differences between
206 // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
207 $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
e2fe3bc0 208 $context->id);
b14a04e0
DM
209 $settings->summary = $formattedsummary[0];
210 $settings->summaryformat = $formattedsummary[1];
6b492628
JL
211 $settings->frontpage = $CFG->frontpage;
212 $settings->frontpageloggedin = $CFG->frontpageloggedin;
213 $settings->maxcategorydepth = $CFG->maxcategorydepth;
214 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
89b909f6 215 $settings->numsections = course_get_format($SITE)->get_last_section_number();
6b492628
JL
216 $settings->newsitems = $SITE->newsitems;
217 $settings->commentsperpage = $CFG->commentsperpage;
218
219 // Now, admin settings.
220 if ($isadmin) {
221 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
222 }
223 }
224
225 if (empty($section) or $section == 'sitepolicies') {
4fe55987 226 $settings->sitepolicy = $CFG->sitepolicy;
6b492628
JL
227 $settings->disableuserimages = $CFG->disableuserimages;
228 }
229
230 if (empty($section) or $section == 'gradessettings') {
231 require_once($CFG->dirroot . '/user/lib.php');
6703e031
JL
232 $settings->mygradesurl = user_mygrades_url();
233 // The previous function may return moodle_url instances or plain string URLs.
234 if ($settings->mygradesurl instanceof moodle_url) {
235 $settings->mygradesurl = $settings->mygradesurl->out(false);
236 }
6b492628
JL
237 }
238
7bdcf970
JL
239 if (empty($section) or $section == 'mobileapp') {
240 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
af1b6043 241 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
b2551b4c 242 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
63d142e2 243 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
7bdcf970
JL
244 }
245
6b492628
JL
246 return $settings;
247 }
248
961c9549
JL
249 /*
250 * Check if all the required conditions are met to allow the auto-login process continue.
251 *
252 * @param int $userid current user id
253 * @since Moodle 3.2
254 * @throws moodle_exception
255 */
256 public static function check_autologin_prerequisites($userid) {
257 global $CFG;
258
259 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
260 throw new moodle_exception('enablewsdescription', 'webservice');
261 }
262
263 if (!is_https()) {
264 throw new moodle_exception('httpsrequired', 'tool_mobile');
265 }
266
267 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
268 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
269 }
270 }
271
272 /**
273 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
274 *
275 * @return string the key
276 * @since Moodle 3.2
277 */
278 public static function get_autologin_key() {
279 global $USER;
280 // Delete previous keys.
281 delete_user_key('tool_mobile', $USER->id);
282
283 // Create a new key.
284 $iprestriction = getremoteaddr();
285 $validuntil = time() + self::LOGIN_KEY_TTL;
286 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
287 }
b2551b4c
JL
288
289 /**
290 * Get a list of the Mobile app features.
291 *
292 * @return array array with the features grouped by theirs ubication in the app.
293 * @since Moodle 3.3
294 */
295 public static function get_features_list() {
296 global $CFG;
297
298 $general = new lang_string('general');
299 $mainmenu = new lang_string('mainmenu', 'tool_mobile');
300 $course = new lang_string('course');
301 $modules = new lang_string('managemodules');
302 $user = new lang_string('user');
303 $files = new lang_string('files');
304 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
305
306 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
307 $coursemodules = array();
c3e745b7
JL
308 $appsupportedmodules = array('assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'imscp',
309 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki');
b2551b4c
JL
310 foreach ($availablemods as $mod) {
311 if (in_array($mod->name, $appsupportedmodules)) {
312 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
313 }
314 }
315
316 $remoteaddonslist = array();
317 $mobileplugins = self::get_plugins_supporting_mobile();
318 foreach ($mobileplugins as $plugin) {
319 $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
320 $remoteaddonslist['remoteAddOn_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
321
322 }
323
324 $features = array(
325 '$mmLoginEmailSignup' => new lang_string('startsignup'),
326 "$mainmenu" => array(
327 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
328 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
329 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
330 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
331 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
332 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
333 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
334 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
335 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
336 '$mmSideMenuDelegate_help' => new lang_string('help'),
337 ),
338 "$course" => array(
339 '$mmCoursesDelegate_search' => new lang_string('search'),
340 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
341 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
342 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
343 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
344 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
345 ),
346 "$user" => array(
347 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
348 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
349 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
350 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
351 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
352 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
353 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
354 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
355 '$mmUserDelegate_picture' => new lang_string('userpic'),
356 ),
357 "$files" => array(
358 'files_privatefiles' => new lang_string('privatefiles'),
359 'files_sitefiles' => new lang_string('sitefiles'),
360 'files_upload' => new lang_string('upload'),
361 ),
362 "$modules" => $coursemodules,
363 );
364
365 if (!empty($remoteaddonslist)) {
366 $features["$remoteaddons"] = $remoteaddonslist;
367 }
368
369 return $features;
370 }
66a159f8
JL
371
372 /**
373 * This function check the current site for potential configuration issues that may prevent the mobile app to work.
374 *
375 * @return array list of potential issues
376 * @since Moodle 3.4
377 */
378 public static function get_potential_config_issues() {
379 global $CFG;
380 require_once($CFG->dirroot . "/lib/filelib.php");
381 require_once($CFG->dirroot . '/message/lib.php');
382
383 $warnings = array();
384
385 $curl = new curl();
386 // Return certificate information and verify the certificate.
387 $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
388 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); // Force https url.
098b16fb
JL
389 // Check https using a page not redirecting or returning exceptions.
390 $curl->head($httpswwwroot . "/$CFG->admin/tool/mobile/mobile.webmanifest.php");
66a159f8
JL
391 $info = $curl->get_info();
392
393 // First of all, check the server certificate (if any).
394 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
395 $warnings[] = ['nohttpsformobilewarning', 'admin'];
396 } else {
397 // Check the certificate is not self-signed or has an untrusted-root.
398 // This may be weak in some scenarios (when the curl SSL verifier is outdated).
399 if (empty($info['certinfo'])) {
400 $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
401 } else {
402 $timenow = time();
403 $expectedissuer = null;
404 foreach ($info['certinfo'] as $cert) {
405 // Check if the signature algorithm is weak (Android won't work with SHA-1).
406 if ($cert['Signature Algorithm'] == 'sha1WithRSAEncryption' || $cert['Signature Algorithm'] == 'sha1WithRSA') {
407 $warnings[] = ['insecurealgorithmwarning', 'tool_mobile'];
408 }
409 // Check certificate start date.
410 if (strtotime($cert['Start date']) > $timenow) {
411 $warnings[] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
412 }
413 // Check certificate end date.
414 if (strtotime($cert['Expire date']) < $timenow) {
415 $warnings[] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
416 }
417 // Check the chain.
418 if ($expectedissuer !== null) {
419 if ($expectedissuer !== $cert['Subject'] || $cert['Subject'] === $cert['Issuer']) {
420 $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
421 }
422 }
423 $expectedissuer = $cert['Issuer'];
424 }
425 }
426 }
427 // Now check typical configuration problems.
428 if ((int) $CFG->userquota === PHP_INT_MAX) {
429 // In old Moodle version was a text so was possible to have numeric values > PHP_INT_MAX.
430 $warnings[] = ['invaliduserquotawarning', 'tool_mobile'];
431 }
432 // Check ADOdb debug enabled.
433 if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
434 $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
435 }
436 // Check display errors on.
437 if (!empty($CFG->debugdisplay)) {
438 $warnings[] = ['displayerrorswarning', 'tool_mobile'];
439 }
440 // Check mobile notifications.
441 $processors = get_message_processors();
442 $enabled = false;
443 foreach ($processors as $processor => $status) {
444 if ($processor == 'airnotifier' && $status->enabled) {
445 $enabled = true;
446 }
447 }
448 if (!$enabled) {
449 $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
450 }
451
452 return $warnings;
453 }
b2478ed0 454}