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