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