weekly release 3.4dev
[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;
b2478ed0
JL
33
34/**
b2551b4c 35 * API exposed by tool_mobile, to be used mostly by external functions and the plugin settings.
b2478ed0
JL
36 *
37 * @copyright 2016 Juan Leyva
38 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
39 * @since Moodle 3.1
40 */
41class api {
42
c951f1fe
JL
43 /** @var int to identify the login via app. */
44 const LOGIN_VIA_APP = 1;
45 /** @var int to identify the login via browser. */
46 const LOGIN_VIA_BROWSER = 2;
47 /** @var int to identify the login via an embedded browser. */
48 const LOGIN_VIA_EMBEDDED_BROWSER = 3;
961c9549
JL
49 /** @var int seconds an auto-login key will expire. */
50 const LOGIN_KEY_TTL = 60;
c951f1fe 51
b2478ed0
JL
52 /**
53 * Returns a list of Moodle plugins supporting the mobile app.
54 *
55 * @return array an array of objects containing the plugin information
56 */
57 public static function get_plugins_supporting_mobile() {
58 global $CFG;
59 require_once($CFG->libdir . '/adminlib.php');
60
30fccfcd
SK
61 // Check if we can return this from cache.
62 $cache = \cache::make('tool_mobile', 'plugininfo');
63 $pluginsinfo = $cache->get('mobileplugins');
64 if ($pluginsinfo !== false) {
65 return (array)$pluginsinfo;
66 }
67
b2478ed0
JL
68 $pluginsinfo = [];
69 $plugintypes = core_component::get_plugin_types();
70
71 foreach ($plugintypes as $plugintype => $unused) {
72 // We need to include files here.
73 $pluginswithfile = core_component::get_plugin_list_with_file($plugintype, 'db' . DIRECTORY_SEPARATOR . 'mobile.php');
74 foreach ($pluginswithfile as $plugin => $notused) {
75 $path = core_component::get_plugin_directory($plugintype, $plugin);
76 $component = $plugintype . '_' . $plugin;
77 $version = get_component_version($component);
78
30fccfcd 79 require("$path/db/mobile.php");
b2478ed0
JL
80 foreach ($addons as $addonname => $addoninfo) {
81 $plugininfo = array(
82 'component' => $component,
83 'version' => $version,
84 'addon' => $addonname,
b4baee42 85 'dependencies' => !empty($addoninfo['dependencies']) ? $addoninfo['dependencies'] : array(),
b2478ed0
JL
86 'fileurl' => '',
87 'filehash' => '',
88 'filesize' => 0
89 );
90
91 // All the mobile packages must be under the plugin mobile directory.
1c668c3c 92 $package = $path . '/mobile/' . $addonname . '.zip';
b2478ed0
JL
93 if (file_exists($package)) {
94 $plugininfo['fileurl'] = $CFG->wwwroot . '' . str_replace($CFG->dirroot, '', $package);
95 $plugininfo['filehash'] = sha1_file($package);
96 $plugininfo['filesize'] = filesize($package);
97 }
98 $pluginsinfo[] = $plugininfo;
99 }
100 }
101 }
30fccfcd
SK
102
103 $cache->set('mobileplugins', $pluginsinfo);
104
b2478ed0
JL
105 return $pluginsinfo;
106 }
107
0002056f
JL
108 /**
109 * Returns a list of the site public settings, those not requiring authentication.
110 *
111 * @return array with the settings and warnings
112 */
7c1cb3bf 113 public static function get_public_config() {
5d5e30c6 114 global $CFG, $SITE, $PAGE, $OUTPUT;
851b2919 115 require_once($CFG->libdir . '/authlib.php');
0002056f
JL
116
117 $context = context_system::instance();
118 // We need this to make work the format text functions.
119 $PAGE->set_context($context);
120
e2fe3bc0
JL
121 list($authinstructions, $notusedformat) = external_format_text($CFG->auth_instructions, FORMAT_MOODLE, $context->id);
122 list($maintenancemessage, $notusedformat) = external_format_text($CFG->maintenance_message, FORMAT_MOODLE, $context->id);
0002056f
JL
123 $settings = array(
124 'wwwroot' => $CFG->wwwroot,
125 'httpswwwroot' => $CFG->httpswwwroot,
126 'sitename' => external_format_string($SITE->fullname, $context->id, true),
127 'guestlogin' => $CFG->guestloginbutton,
128 'rememberusername' => $CFG->rememberusername,
129 'authloginviaemail' => $CFG->authloginviaemail,
130 'registerauth' => $CFG->registerauth,
131 'forgottenpasswordurl' => $CFG->forgottenpasswordurl,
e2fe3bc0 132 'authinstructions' => $authinstructions,
0002056f
JL
133 'authnoneenabled' => (int) is_enabled_auth('none'),
134 'enablewebservices' => $CFG->enablewebservices,
135 'enablemobilewebservice' => $CFG->enablemobilewebservice,
136 'maintenanceenabled' => $CFG->maintenance_enabled,
e2fe3bc0 137 'maintenancemessage' => $maintenancemessage,
91fff391 138 'mobilecssurl' => !empty($CFG->mobilecssurl) ? $CFG->mobilecssurl : '',
b2551b4c 139 'tool_mobile_disabledfeatures' => get_config('tool_mobile', 'disabledfeatures'),
0002056f 140 );
c951f1fe
JL
141
142 $typeoflogin = get_config('tool_mobile', 'typeoflogin');
143 // Not found, edge case.
144 if ($typeoflogin === false) {
145 $typeoflogin = self::LOGIN_VIA_APP; // Defaults to via app.
146 }
147 $settings['typeoflogin'] = $typeoflogin;
148
851b2919
JL
149 // Check if the user can sign-up to return the launch URL in that case.
150 $cansignup = signup_is_enabled();
151
b1037978
JL
152 $url = new moodle_url("/$CFG->admin/tool/mobile/launch.php");
153 $settings['launchurl'] = $url->out(false);
5d5e30c6 154
6703e031
JL
155 // Check that we are receiving a moodle_url object, themes can override get_logo_url and may return incorrect values.
156 if (($logourl = $OUTPUT->get_logo_url()) && $logourl instanceof moodle_url) {
5d5e30c6
JL
157 $settings['logourl'] = $logourl->out(false);
158 }
6703e031 159 if (($compactlogourl = $OUTPUT->get_compact_logo_url()) && $compactlogourl instanceof moodle_url) {
5d5e30c6
JL
160 $settings['compactlogourl'] = $compactlogourl->out(false);
161 }
162
a67e3bda
JL
163 // Identity providers.
164 $authsequence = get_enabled_auth_plugins(true);
165 $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
166 $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
167 if (!empty($identityprovidersdata)) {
168 $settings['identityproviders'] = $identityprovidersdata;
169 }
170
0002056f
JL
171 return $settings;
172 }
173
6b492628
JL
174 /**
175 * Returns a list of site configurations, filtering by section.
176 *
177 * @param string $section section name
178 * @return stdClass object containing the settings
179 */
180 public static function get_config($section) {
181 global $CFG, $SITE;
182
183 $settings = new \stdClass;
184 $context = context_system::instance();
185 $isadmin = has_capability('moodle/site:config', $context);
186
187 if (empty($section) or $section == 'frontpagesettings') {
188 require_once($CFG->dirroot . '/course/format/lib.php');
189 // First settings that anyone can deduce.
e2fe3bc0
JL
190 $settings->fullname = external_format_string($SITE->fullname, $context->id);
191 $settings->shortname = external_format_string($SITE->shortname, $context->id);
b14a04e0
DM
192
193 // Return to a var instead of directly to $settings object because of differences between
194 // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
195 $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
e2fe3bc0 196 $context->id);
b14a04e0
DM
197 $settings->summary = $formattedsummary[0];
198 $settings->summaryformat = $formattedsummary[1];
6b492628
JL
199 $settings->frontpage = $CFG->frontpage;
200 $settings->frontpageloggedin = $CFG->frontpageloggedin;
201 $settings->maxcategorydepth = $CFG->maxcategorydepth;
202 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
89b909f6 203 $settings->numsections = course_get_format($SITE)->get_last_section_number();
6b492628
JL
204 $settings->newsitems = $SITE->newsitems;
205 $settings->commentsperpage = $CFG->commentsperpage;
206
207 // Now, admin settings.
208 if ($isadmin) {
209 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
210 }
211 }
212
213 if (empty($section) or $section == 'sitepolicies') {
4fe55987 214 $settings->sitepolicy = $CFG->sitepolicy;
6b492628
JL
215 $settings->disableuserimages = $CFG->disableuserimages;
216 }
217
218 if (empty($section) or $section == 'gradessettings') {
219 require_once($CFG->dirroot . '/user/lib.php');
6703e031
JL
220 $settings->mygradesurl = user_mygrades_url();
221 // The previous function may return moodle_url instances or plain string URLs.
222 if ($settings->mygradesurl instanceof moodle_url) {
223 $settings->mygradesurl = $settings->mygradesurl->out(false);
224 }
6b492628
JL
225 }
226
7bdcf970
JL
227 if (empty($section) or $section == 'mobileapp') {
228 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
af1b6043 229 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
b2551b4c 230 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
63d142e2 231 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
7bdcf970
JL
232 }
233
6b492628
JL
234 return $settings;
235 }
236
961c9549
JL
237 /*
238 * Check if all the required conditions are met to allow the auto-login process continue.
239 *
240 * @param int $userid current user id
241 * @since Moodle 3.2
242 * @throws moodle_exception
243 */
244 public static function check_autologin_prerequisites($userid) {
245 global $CFG;
246
247 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
248 throw new moodle_exception('enablewsdescription', 'webservice');
249 }
250
251 if (!is_https()) {
252 throw new moodle_exception('httpsrequired', 'tool_mobile');
253 }
254
255 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
256 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
257 }
258 }
259
260 /**
261 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
262 *
263 * @return string the key
264 * @since Moodle 3.2
265 */
266 public static function get_autologin_key() {
267 global $USER;
268 // Delete previous keys.
269 delete_user_key('tool_mobile', $USER->id);
270
271 // Create a new key.
272 $iprestriction = getremoteaddr();
273 $validuntil = time() + self::LOGIN_KEY_TTL;
274 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
275 }
b2551b4c
JL
276
277 /**
278 * Get a list of the Mobile app features.
279 *
280 * @return array array with the features grouped by theirs ubication in the app.
281 * @since Moodle 3.3
282 */
283 public static function get_features_list() {
284 global $CFG;
285
286 $general = new lang_string('general');
287 $mainmenu = new lang_string('mainmenu', 'tool_mobile');
288 $course = new lang_string('course');
289 $modules = new lang_string('managemodules');
290 $user = new lang_string('user');
291 $files = new lang_string('files');
292 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
293
294 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
295 $coursemodules = array();
c3e745b7
JL
296 $appsupportedmodules = array('assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'imscp',
297 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki');
b2551b4c
JL
298 foreach ($availablemods as $mod) {
299 if (in_array($mod->name, $appsupportedmodules)) {
300 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
301 }
302 }
303
304 $remoteaddonslist = array();
305 $mobileplugins = self::get_plugins_supporting_mobile();
306 foreach ($mobileplugins as $plugin) {
307 $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
308 $remoteaddonslist['remoteAddOn_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
309
310 }
311
312 $features = array(
313 '$mmLoginEmailSignup' => new lang_string('startsignup'),
314 "$mainmenu" => array(
315 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
316 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
317 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
318 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
319 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
320 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
321 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
322 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
323 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
324 '$mmSideMenuDelegate_help' => new lang_string('help'),
325 ),
326 "$course" => array(
327 '$mmCoursesDelegate_search' => new lang_string('search'),
328 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
329 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
330 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
331 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
332 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
333 ),
334 "$user" => array(
335 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
336 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
337 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
338 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
339 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
340 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
341 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
342 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
343 '$mmUserDelegate_picture' => new lang_string('userpic'),
344 ),
345 "$files" => array(
346 'files_privatefiles' => new lang_string('privatefiles'),
347 'files_sitefiles' => new lang_string('sitefiles'),
348 'files_upload' => new lang_string('upload'),
349 ),
350 "$modules" => $coursemodules,
351 );
352
353 if (!empty($remoteaddonslist)) {
354 $features["$remoteaddons"] = $remoteaddonslist;
355 }
356
357 return $features;
358 }
b2478ed0 359}