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