weekly release 3.5dev
[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'),
8d9dc60b
JL
152 'country' => clean_param($CFG->country, PARAM_NOTAGS),
153 'agedigitalconsentverification' => \core_auth\digital_consent::is_age_digital_consent_verification_enabled(),
0002056f 154 );
c951f1fe
JL
155
156 $typeoflogin = get_config('tool_mobile', 'typeoflogin');
157 // Not found, edge case.
158 if ($typeoflogin === false) {
159 $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
160 }
161 $settings['typeoflogin'] = $typeoflogin;
162
851b2919
JL
163 // Check if the user can sign-up to return the launch URL in that case.
164 $cansignup = signup_is_enabled();
165
b1037978
JL
166 $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
167 $settings['launchurl'] = $url->out(false);
5d5e30c6 168
6703e031
JL
169 // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
170 if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
5d5e30c6
JL
171 $settings['logourl'] = $logourl->out(false);
172 }
6703e031 173 if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
5d5e30c6
JL
174 $settings['compactlogourl'] = $compactlogourl->out(false);
175 }
176
a67e3bda
JL
177 // Identity providers.
178 $authsequence = get_enabled_auth_plugins(true);
179 $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
180 $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
181 if (!empty($identityprovidersdata)) {
182 $settings['identityproviders'] = $identityprovidersdata;
183 }
184
8d9dc60b
JL
185 // If age is verified, return also the admin contact details.
186 if ($settings['agedigitalconsentverification']) {
187 $settings['supportname'] = clean_param($CFG->supportname, PARAM_NOTAGS);
188 $settings['supportemail'] = clean_param($CFG->supportemail, PARAM_EMAIL);
189 }
190
0002056f
JL
191 return $settings;
192 }
193
6b492628
JL
194 /**
195 * Returns a list of site configurations, filtering by section.
196 *
197 * @param string $section section name
198 * @return stdClass object containing the settings
199 */
200 public static function get_config($section) {
201 global $CFG, $SITE;
202
203 $settings = new \stdClass;
204 $context = context_system::instance();
205 $isadmin = has_capability('moodle/site:config', $context);
206
207 if (empty($section) or $section == 'frontpagesettings') {
208 require_once($CFG->dirroot . '/course/format/lib.php');
209 // First settings that anyone can deduce.
e2fe3bc0
JL
210 $settings->fullname = external_format_string($SITE->fullname, $context->id);
211 $settings->shortname = external_format_string($SITE->shortname, $context->id);
b14a04e0
DM
212
213 // Return to a var instead of directly to $settings object because of differences between
214 // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
215 $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
e2fe3bc0 216 $context->id);
b14a04e0
DM
217 $settings->summary = $formattedsummary[0];
218 $settings->summaryformat = $formattedsummary[1];
6b492628
JL
219 $settings->frontpage = $CFG->frontpage;
220 $settings->frontpageloggedin = $CFG->frontpageloggedin;
221 $settings->maxcategorydepth = $CFG->maxcategorydepth;
222 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
89b909f6 223 $settings->numsections = course_get_format($SITE)->get_last_section_number();
6b492628
JL
224 $settings->newsitems = $SITE->newsitems;
225 $settings->commentsperpage = $CFG->commentsperpage;
226
227 // Now, admin settings.
228 if ($isadmin) {
229 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
230 }
231 }
232
233 if (empty($section) or $section == 'sitepolicies') {
1727c939
MG
234 $manager = new \core_privacy\local\sitepolicy\manager();
235 $settings->sitepolicy = ($sitepolicy = $manager->get_embed_url()) ? $sitepolicy->out(false) : '';
236 $settings->sitepolicyhandler = $CFG->sitepolicyhandler;
6b492628
JL
237 $settings->disableuserimages = $CFG->disableuserimages;
238 }
239
240 if (empty($section) or $section == 'gradessettings') {
241 require_once($CFG->dirroot . '/user/lib.php');
6703e031
JL
242 $settings->mygradesurl = user_mygrades_url();
243 // The previous function may return moodle_url instances or plain string URLs.
244 if ($settings->mygradesurl instanceof moodle_url) {
245 $settings->mygradesurl = $settings->mygradesurl->out(false);
246 }
6b492628
JL
247 }
248
7bdcf970
JL
249 if (empty($section) or $section == 'mobileapp') {
250 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
af1b6043 251 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
b2551b4c 252 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
63d142e2 253 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
7bdcf970
JL
254 }
255
6b492628
JL
256 return $settings;
257 }
258
961c9549
JL
259 /*
260 * Check if all the required conditions are met to allow the auto-login process continue.
261 *
262 * @param int $userid current user id
263 * @since Moodle 3.2
264 * @throws moodle_exception
265 */
266 public static function check_autologin_prerequisites($userid) {
267 global $CFG;
268
269 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
270 throw new moodle_exception('enablewsdescription', 'webservice');
271 }
272
273 if (!is_https()) {
274 throw new moodle_exception('httpsrequired', 'tool_mobile');
275 }
276
277 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
278 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
279 }
280 }
281
282 /**
283 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
284 *
285 * @return string the key
286 * @since Moodle 3.2
287 */
288 public static function get_autologin_key() {
289 global $USER;
290 // Delete previous keys.
291 delete_user_key('tool_mobile', $USER->id);
292
293 // Create a new key.
294 $iprestriction = getremoteaddr();
295 $validuntil = time() + self::LOGIN_KEY_TTL;
296 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
297 }
b2551b4c
JL
298
299 /**
300 * Get a list of the Mobile app features.
301 *
302 * @return array array with the features grouped by theirs ubication in the app.
303 * @since Moodle 3.3
304 */
305 public static function get_features_list() {
306 global $CFG;
307
308 $general = new lang_string('general');
309 $mainmenu = new lang_string('mainmenu', 'tool_mobile');
310 $course = new lang_string('course');
311 $modules = new lang_string('managemodules');
312 $user = new lang_string('user');
313 $files = new lang_string('files');
314 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
315
316 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
317 $coursemodules = array();
c3e745b7
JL
318 $appsupportedmodules = array('assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'imscp',
319 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki');
b2551b4c
JL
320 foreach ($availablemods as $mod) {
321 if (in_array($mod->name, $appsupportedmodules)) {
322 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
323 }
324 }
325
326 $remoteaddonslist = array();
327 $mobileplugins = self::get_plugins_supporting_mobile();
328 foreach ($mobileplugins as $plugin) {
329 $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
330 $remoteaddonslist['remoteAddOn_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
331
332 }
333
334 $features = array(
335 '$mmLoginEmailSignup' => new lang_string('startsignup'),
336 "$mainmenu" => array(
337 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
338 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
339 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
340 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
341 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
342 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
343 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
344 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
345 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
346 '$mmSideMenuDelegate_help' => new lang_string('help'),
347 ),
348 "$course" => array(
349 '$mmCoursesDelegate_search' => new lang_string('search'),
350 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
351 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
352 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
353 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
354 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
355 ),
356 "$user" => array(
357 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
358 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
359 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
360 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
361 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
362 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
363 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
364 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
365 '$mmUserDelegate_picture' => new lang_string('userpic'),
366 ),
367 "$files" => array(
368 'files_privatefiles' => new lang_string('privatefiles'),
369 'files_sitefiles' => new lang_string('sitefiles'),
370 'files_upload' => new lang_string('upload'),
371 ),
372 "$modules" => $coursemodules,
373 );
374
375 if (!empty($remoteaddonslist)) {
376 $features["$remoteaddons"] = $remoteaddonslist;
377 }
378
379 return $features;
380 }
66a159f8
JL
381
382 /**
383 * This function check the current site for potential configuration issues that may prevent the mobile app to work.
384 *
385 * @return array list of potential issues
386 * @since Moodle 3.4
387 */
388 public static function get_potential_config_issues() {
389 global $CFG;
390 require_once($CFG->dirroot . "/lib/filelib.php");
391 require_once($CFG->dirroot . '/message/lib.php');
392
393 $warnings = array();
394
395 $curl = new curl();
396 // Return certificate information and verify the certificate.
397 $curl->setopt(array('CURLOPT_CERTINFO' => 1, 'CURLOPT_SSL_VERIFYPEER' => true));
398 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot); // Force https url.
098b16fb
JL
399 // Check https using a page not redirecting or returning exceptions.
400 $curl->head($httpswwwroot . "/$CFG->admin/tool/mobile/mobile.webmanifest.php");
66a159f8
JL
401 $info = $curl->get_info();
402
403 // First of all, check the server certificate (if any).
404 if (empty($info['http_code']) or ($info['http_code'] >= 400)) {
405 $warnings[] = ['nohttpsformobilewarning', 'admin'];
406 } else {
407 // Check the certificate is not self-signed or has an untrusted-root.
408 // This may be weak in some scenarios (when the curl SSL verifier is outdated).
409 if (empty($info['certinfo'])) {
410 $warnings[] = ['selfsignedoruntrustedcertificatewarning', 'tool_mobile'];
411 } else {
412 $timenow = time();
413 $expectedissuer = null;
414 foreach ($info['certinfo'] as $cert) {
415 // Check if the signature algorithm is weak (Android won't work with SHA-1).
416 if ($cert['Signature Algorithm'] == 'sha1WithRSAEncryption' || $cert['Signature Algorithm'] == 'sha1WithRSA') {
417 $warnings[] = ['insecurealgorithmwarning', 'tool_mobile'];
418 }
419 // Check certificate start date.
420 if (strtotime($cert['Start date']) > $timenow) {
421 $warnings[] = ['invalidcertificatestartdatewarning', 'tool_mobile'];
422 }
423 // Check certificate end date.
424 if (strtotime($cert['Expire date']) < $timenow) {
425 $warnings[] = ['invalidcertificateexpiredatewarning', 'tool_mobile'];
426 }
427 // Check the chain.
428 if ($expectedissuer !== null) {
429 if ($expectedissuer !== $cert['Subject'] || $cert['Subject'] === $cert['Issuer']) {
430 $warnings[] = ['invalidcertificatechainwarning', 'tool_mobile'];
431 }
432 }
433 $expectedissuer = $cert['Issuer'];
434 }
435 }
436 }
437 // Now check typical configuration problems.
438 if ((int) $CFG->userquota === PHP_INT_MAX) {
439 // In old Moodle version was a text so was possible to have numeric values > PHP_INT_MAX.
440 $warnings[] = ['invaliduserquotawarning', 'tool_mobile'];
441 }
442 // Check ADOdb debug enabled.
443 if (get_config('auth_db', 'debugauthdb') || get_config('enrol_database', 'debugdb')) {
444 $warnings[] = ['adodbdebugwarning', 'tool_mobile'];
445 }
446 // Check display errors on.
447 if (!empty($CFG->debugdisplay)) {
448 $warnings[] = ['displayerrorswarning', 'tool_mobile'];
449 }
450 // Check mobile notifications.
451 $processors = get_message_processors();
452 $enabled = false;
453 foreach ($processors as $processor => $status) {
454 if ($processor == 'airnotifier' && $status->enabled) {
455 $enabled = true;
456 }
457 }
458 if (!$enabled) {
459 $warnings[] = ['mobilenotificationsdisabledwarning', 'tool_mobile'];
460 }
461
462 return $warnings;
463 }
b2478ed0 464}