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
JL
154
155 if ($logourl = $OUTPUT->get_logo_url()) {
156 $settings['logourl'] = $logourl->out(false);
157 }
158 if ($compactlogourl = $OUTPUT->get_compact_logo_url()) {
159 $settings['compactlogourl'] = $compactlogourl->out(false);
160 }
161
a67e3bda
JL
162 // Identity providers.
163 $authsequence = get_enabled_auth_plugins(true);
164 $identityproviders = \auth_plugin_base::get_identity_providers($authsequence);
165 $identityprovidersdata = \auth_plugin_base::prepare_identity_providers_for_output($identityproviders, $OUTPUT);
166 if (!empty($identityprovidersdata)) {
167 $settings['identityproviders'] = $identityprovidersdata;
168 }
169
0002056f
JL
170 return $settings;
171 }
172
6b492628
JL
173 /**
174 * Returns a list of site configurations, filtering by section.
175 *
176 * @param string $section section name
177 * @return stdClass object containing the settings
178 */
179 public static function get_config($section) {
180 global $CFG, $SITE;
181
182 $settings = new \stdClass;
183 $context = context_system::instance();
184 $isadmin = has_capability('moodle/site:config', $context);
185
186 if (empty($section) or $section == 'frontpagesettings') {
187 require_once($CFG->dirroot . '/course/format/lib.php');
188 // First settings that anyone can deduce.
e2fe3bc0
JL
189 $settings->fullname = external_format_string($SITE->fullname, $context->id);
190 $settings->shortname = external_format_string($SITE->shortname, $context->id);
b14a04e0
DM
191
192 // Return to a var instead of directly to $settings object because of differences between
193 // list() in php5 and php7. {@link http://php.net/manual/en/function.list.php}
194 $formattedsummary = external_format_text($SITE->summary, $SITE->summaryformat,
e2fe3bc0 195 $context->id);
b14a04e0
DM
196 $settings->summary = $formattedsummary[0];
197 $settings->summaryformat = $formattedsummary[1];
6b492628
JL
198 $settings->frontpage = $CFG->frontpage;
199 $settings->frontpageloggedin = $CFG->frontpageloggedin;
200 $settings->maxcategorydepth = $CFG->maxcategorydepth;
201 $settings->frontpagecourselimit = $CFG->frontpagecourselimit;
89b909f6 202 $settings->numsections = course_get_format($SITE)->get_last_section_number();
6b492628
JL
203 $settings->newsitems = $SITE->newsitems;
204 $settings->commentsperpage = $CFG->commentsperpage;
205
206 // Now, admin settings.
207 if ($isadmin) {
208 $settings->defaultfrontpageroleid = $CFG->defaultfrontpageroleid;
209 }
210 }
211
212 if (empty($section) or $section == 'sitepolicies') {
213 $settings->disableuserimages = $CFG->disableuserimages;
214 }
215
216 if (empty($section) or $section == 'gradessettings') {
217 require_once($CFG->dirroot . '/user/lib.php');
218 $settings->mygradesurl = user_mygrades_url()->out(false);
219 }
220
7bdcf970
JL
221 if (empty($section) or $section == 'mobileapp') {
222 $settings->tool_mobile_forcelogout = get_config('tool_mobile', 'forcelogout');
af1b6043 223 $settings->tool_mobile_customlangstrings = get_config('tool_mobile', 'customlangstrings');
b2551b4c 224 $settings->tool_mobile_disabledfeatures = get_config('tool_mobile', 'disabledfeatures');
63d142e2 225 $settings->tool_mobile_custommenuitems = get_config('tool_mobile', 'custommenuitems');
7bdcf970
JL
226 }
227
6b492628
JL
228 return $settings;
229 }
230
961c9549
JL
231 /*
232 * Check if all the required conditions are met to allow the auto-login process continue.
233 *
234 * @param int $userid current user id
235 * @since Moodle 3.2
236 * @throws moodle_exception
237 */
238 public static function check_autologin_prerequisites($userid) {
239 global $CFG;
240
241 if (!$CFG->enablewebservices or !$CFG->enablemobilewebservice) {
242 throw new moodle_exception('enablewsdescription', 'webservice');
243 }
244
245 if (!is_https()) {
246 throw new moodle_exception('httpsrequired', 'tool_mobile');
247 }
248
249 if (has_capability('moodle/site:config', context_system::instance(), $userid) or is_siteadmin($userid)) {
250 throw new moodle_exception('autologinnotallowedtoadmins', 'tool_mobile');
251 }
252 }
253
254 /**
255 * Creates an auto-login key for the current user, this key is restricted by time and ip address.
256 *
257 * @return string the key
258 * @since Moodle 3.2
259 */
260 public static function get_autologin_key() {
261 global $USER;
262 // Delete previous keys.
263 delete_user_key('tool_mobile', $USER->id);
264
265 // Create a new key.
266 $iprestriction = getremoteaddr();
267 $validuntil = time() + self::LOGIN_KEY_TTL;
268 return create_user_key('tool_mobile', $USER->id, null, $iprestriction, $validuntil);
269 }
b2551b4c
JL
270
271 /**
272 * Get a list of the Mobile app features.
273 *
274 * @return array array with the features grouped by theirs ubication in the app.
275 * @since Moodle 3.3
276 */
277 public static function get_features_list() {
278 global $CFG;
279
280 $general = new lang_string('general');
281 $mainmenu = new lang_string('mainmenu', 'tool_mobile');
282 $course = new lang_string('course');
283 $modules = new lang_string('managemodules');
284 $user = new lang_string('user');
285 $files = new lang_string('files');
286 $remoteaddons = new lang_string('remoteaddons', 'tool_mobile');
287
288 $availablemods = core_plugin_manager::instance()->get_plugins_of_type('mod');
289 $coursemodules = array();
c3e745b7
JL
290 $appsupportedmodules = array('assign', 'book', 'chat', 'choice', 'data', 'feedback', 'folder', 'forum', 'glossary', 'imscp',
291 'label', 'lesson', 'lti', 'page', 'quiz', 'resource', 'scorm', 'survey', 'url', 'wiki');
b2551b4c
JL
292 foreach ($availablemods as $mod) {
293 if (in_array($mod->name, $appsupportedmodules)) {
294 $coursemodules['$mmCourseDelegate_mmaMod' . ucfirst($mod->name)] = $mod->displayname;
295 }
296 }
297
298 $remoteaddonslist = array();
299 $mobileplugins = self::get_plugins_supporting_mobile();
300 foreach ($mobileplugins as $plugin) {
301 $displayname = core_plugin_manager::instance()->plugin_name($plugin['component']) . " - " . $plugin['addon'];
302 $remoteaddonslist['remoteAddOn_' . $plugin['component'] . '_' . $plugin['addon']] = $displayname;
303
304 }
305
306 $features = array(
307 '$mmLoginEmailSignup' => new lang_string('startsignup'),
308 "$mainmenu" => array(
309 '$mmSideMenuDelegate_mmCourses' => new lang_string('mycourses'),
310 '$mmSideMenuDelegate_mmaFrontpage' => new lang_string('sitehome'),
311 '$mmSideMenuDelegate_mmaGrades' => new lang_string('grades', 'grades'),
312 '$mmSideMenuDelegate_mmaCompetency' => new lang_string('myplans', 'tool_lp'),
313 '$mmSideMenuDelegate_mmaNotifications' => new lang_string('notifications', 'message'),
314 '$mmSideMenuDelegate_mmaMessages' => new lang_string('messages', 'message'),
315 '$mmSideMenuDelegate_mmaCalendar' => new lang_string('calendar', 'calendar'),
316 '$mmSideMenuDelegate_mmaFiles' => new lang_string('files'),
317 '$mmSideMenuDelegate_website' => new lang_string('webpage'),
318 '$mmSideMenuDelegate_help' => new lang_string('help'),
319 ),
320 "$course" => array(
321 '$mmCoursesDelegate_search' => new lang_string('search'),
322 '$mmCoursesDelegate_mmaCompetency' => new lang_string('competencies', 'competency'),
323 '$mmCoursesDelegate_mmaParticipants' => new lang_string('participants'),
324 '$mmCoursesDelegate_mmaGrades' => new lang_string('grades', 'grades'),
325 '$mmCoursesDelegate_mmaCourseCompletion' => new lang_string('coursecompletion', 'completion'),
326 '$mmCoursesDelegate_mmaNotes' => new lang_string('notes', 'notes'),
327 ),
328 "$user" => array(
329 '$mmUserDelegate_mmaBadges' => new lang_string('badges', 'badges'),
330 '$mmUserDelegate_mmaCompetency:learningPlan' => new lang_string('competencies', 'competency'),
331 '$mmUserDelegate_mmaCourseCompletion:viewCompletion' => new lang_string('coursecompletion', 'completion'),
332 '$mmUserDelegate_mmaGrades:viewGrades' => new lang_string('grades', 'grades'),
333 '$mmUserDelegate_mmaMessages:sendMessage' => new lang_string('sendmessage', 'message'),
334 '$mmUserDelegate_mmaMessages:addContact' => new lang_string('addcontact', 'message'),
335 '$mmUserDelegate_mmaMessages:blockContact' => new lang_string('blockcontact', 'message'),
336 '$mmUserDelegate_mmaNotes:addNote' => new lang_string('addnewnote', 'notes'),
337 '$mmUserDelegate_picture' => new lang_string('userpic'),
338 ),
339 "$files" => array(
340 'files_privatefiles' => new lang_string('privatefiles'),
341 'files_sitefiles' => new lang_string('sitefiles'),
342 'files_upload' => new lang_string('upload'),
343 ),
344 "$modules" => $coursemodules,
345 );
346
347 if (!empty($remoteaddonslist)) {
348 $features["$remoteaddons"] = $remoteaddonslist;
349 }
350
351 return $features;
352 }
b2478ed0 353}