Proyectos de Subversion Moodle

Rev

| Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 * Auth e-mail external API
19
 *
20
 * @package    auth_email
21
 * @category   external
22
 * @copyright  2016 Juan Leyva <juan@moodle.com>
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 * @since      Moodle 3.2
25
 */
26
 
27
use core_external\external_api;
28
use core_external\external_format_value;
29
use core_external\external_function_parameters;
30
use core_external\external_multiple_structure;
31
use core_external\external_single_structure;
32
use core_external\external_value;
33
use core_external\external_warnings;
34
 
35
defined('MOODLE_INTERNAL') || die;
36
 
37
require_once($CFG->libdir . '/authlib.php');
38
require_once($CFG->dirroot . '/user/editlib.php');
39
require_once($CFG->dirroot . '/user/profile/lib.php');
40
 
41
/**
42
 * Auth e-mail external functions
43
 *
44
 * @package    auth_email
45
 * @category   external
46
 * @copyright  2016 Juan Leyva <juan@moodle.com>
47
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
48
 * @since      Moodle 3.2
49
 */
50
class auth_email_external extends external_api {
51
 
52
    /**
53
     * Check if registration is enabled in this site.
54
     *
55
     * @throws moodle_exception
56
     * @since Moodle 3.2
57
     */
58
    protected static function check_signup_enabled() {
59
        global $CFG;
60
 
61
        if (empty($CFG->registerauth) or $CFG->registerauth != 'email') {
62
            throw new moodle_exception('registrationdisabled', 'error');
63
        }
64
    }
65
 
66
    /**
67
     * Describes the parameters for get_signup_settings.
68
     *
69
     * @return external_function_parameters
70
     * @since Moodle 3.2
71
     */
72
    public static function get_signup_settings_parameters() {
73
        return new external_function_parameters(array());
74
    }
75
 
76
    /**
77
     * Get the signup required settings and profile fields.
78
     *
79
     * @return array settings and possible warnings
80
     * @since Moodle 3.2
81
     * @throws moodle_exception
82
     */
83
    public static function get_signup_settings() {
84
        global $CFG, $PAGE;
85
 
86
        $context = context_system::instance();
87
        // We need this to make work the format text functions.
88
        $PAGE->set_context($context);
89
 
90
        self::check_signup_enabled();
91
 
92
        $result = array();
93
        $result['namefields'] = useredit_get_required_name_fields();
94
 
95
        if (!empty($CFG->passwordpolicy)) {
96
            $result['passwordpolicy'] = print_password_policy();
97
        }
98
        $manager = new \core_privacy\local\sitepolicy\manager();
99
        if ($sitepolicy = $manager->get_embed_url()) {
100
            $result['sitepolicy'] = $sitepolicy->out(false);
101
        }
102
        if (!empty($CFG->sitepolicyhandler)) {
103
            $result['sitepolicyhandler'] = $CFG->sitepolicyhandler;
104
        }
105
        if (!empty($CFG->defaultcity)) {
106
            $result['defaultcity'] = $CFG->defaultcity;
107
        }
108
        if (!empty($CFG->country)) {
109
            $result['country'] = $CFG->country;
110
        }
111
        $result['extendedusernamechars'] = !empty($CFG->extendedusernamechars);
112
 
113
        if ($fields = profile_get_signup_fields()) {
114
            $result['profilefields'] = array();
115
            foreach ($fields as $field) {
116
                $fielddata = $field->object->get_field_config_for_external();
117
                $fielddata['categoryname'] = \core_external\util::format_string($field->categoryname, $context->id);
118
                $fielddata['name'] = \core_external\util::format_string($fielddata['name'], $context->id);
119
                list($fielddata['defaultdata'], $fielddata['defaultdataformat']) =
120
                    \core_external\util::format_text($fielddata['defaultdata'], $fielddata['defaultdataformat'], $context->id);
121
 
122
                $result['profilefields'][] = $fielddata;
123
            }
124
        }
125
 
126
        if (signup_captcha_enabled()) {
127
            // With reCAPTCHA v2 the captcha will be rendered by the mobile client using just the publickey.
128
            $result['recaptchapublickey'] = $CFG->recaptchapublickey;
129
        }
130
 
131
        $result['warnings'] = array();
132
        return $result;
133
    }
134
 
135
    /**
136
     * Describes the get_signup_settings return value.
137
     *
138
     * @return external_single_structure
139
     * @since Moodle 3.2
140
     */
141
    public static function get_signup_settings_returns() {
142
 
143
        return new external_single_structure(
144
            [
145
                'namefields' => new external_multiple_structure(
146
                     new external_value(PARAM_NOTAGS, 'The order of the name fields')
147
                ),
148
                'passwordpolicy' => new external_value(PARAM_RAW, 'Password policy', VALUE_OPTIONAL),
149
                'sitepolicy' => new external_value(PARAM_RAW, 'Site policy', VALUE_OPTIONAL),
150
                'sitepolicyhandler' => new external_value(PARAM_PLUGIN, 'Site policy handler', VALUE_OPTIONAL),
151
                'defaultcity' => new external_value(PARAM_NOTAGS, 'Default city', VALUE_OPTIONAL),
152
                'country' => new external_value(PARAM_ALPHA, 'Default country', VALUE_OPTIONAL),
153
                'extendedusernamechars' => new external_value(
154
                    PARAM_BOOL, 'Extended characters in usernames or not', VALUE_OPTIONAL
155
                ),
156
                'profilefields' => new external_multiple_structure(
157
                    new external_single_structure(
158
                        [
159
                            'id' => new external_value(PARAM_INT, 'Profile field id', VALUE_OPTIONAL),
160
                            'shortname' => new external_value(PARAM_ALPHANUMEXT, 'Profile field shortname', VALUE_OPTIONAL),
161
                            'name' => new external_value(PARAM_RAW, 'Profield field name', VALUE_OPTIONAL),
162
                            'datatype' => new external_value(PARAM_ALPHANUMEXT, 'Profield field datatype', VALUE_OPTIONAL),
163
                            'description' => new external_value(PARAM_RAW, 'Profield field description', VALUE_OPTIONAL),
164
                            'descriptionformat' => new external_format_value('description'),
165
                            'categoryid' => new external_value(PARAM_INT, 'Profield field category id', VALUE_OPTIONAL),
166
                            'categoryname' => new external_value(PARAM_RAW, 'Profield field category name', VALUE_OPTIONAL),
167
                            'sortorder' => new external_value(PARAM_INT, 'Profield field sort order', VALUE_OPTIONAL),
168
                            'required' => new external_value(PARAM_INT, 'Profield field required', VALUE_OPTIONAL),
169
                            'locked' => new external_value(PARAM_INT, 'Profield field locked', VALUE_OPTIONAL),
170
                            'visible' => new external_value(PARAM_INT, 'Profield field visible', VALUE_OPTIONAL),
171
                            'forceunique' => new external_value(PARAM_INT, 'Profield field unique', VALUE_OPTIONAL),
172
                            'signup' => new external_value(PARAM_INT, 'Profield field in signup form', VALUE_OPTIONAL),
173
                            'defaultdata' => new external_value(PARAM_RAW, 'Profield field default data', VALUE_OPTIONAL),
174
                            'defaultdataformat' => new external_format_value('defaultdata'),
175
                            'param1' => new external_value(PARAM_RAW, 'Profield field settings', VALUE_OPTIONAL),
176
                            'param2' => new external_value(PARAM_RAW, 'Profield field settings', VALUE_OPTIONAL),
177
                            'param3' => new external_value(PARAM_RAW, 'Profield field settings', VALUE_OPTIONAL),
178
                            'param4' => new external_value(PARAM_RAW, 'Profield field settings', VALUE_OPTIONAL),
179
                            'param5' => new external_value(PARAM_RAW, 'Profield field settings', VALUE_OPTIONAL),
180
                        ]
181
                    ), 'Required profile fields', VALUE_OPTIONAL
182
                ),
183
                'recaptchapublickey' => new external_value(PARAM_RAW, 'Recaptcha public key', VALUE_OPTIONAL),
184
                'recaptchachallengehash' => new external_value(PARAM_RAW, 'Recaptcha challenge hash', VALUE_OPTIONAL),
185
                'recaptchachallengeimage' => new external_value(PARAM_URL, 'Recaptcha challenge noscript image', VALUE_OPTIONAL),
186
                'recaptchachallengejs' => new external_value(PARAM_URL, 'Recaptcha challenge js url', VALUE_OPTIONAL),
187
                'warnings'  => new external_warnings(),
188
            ]
189
        );
190
    }
191
 
192
    /**
193
     * Describes the parameters for signup_user.
194
     *
195
     * @return external_function_parameters
196
     * @since Moodle 3.2
197
     */
198
    public static function signup_user_parameters() {
199
        return new external_function_parameters(
200
            array(
201
                'username' => new external_value(core_user::get_property_type('username'), 'Username'),
202
                'password' => new external_value(core_user::get_property_type('password'), 'Plain text password'),
203
                'firstname' => new external_value(core_user::get_property_type('firstname'), 'The first name(s) of the user'),
204
                'lastname' => new external_value(core_user::get_property_type('lastname'), 'The family name of the user'),
205
                'email' => new external_value(core_user::get_property_type('email'), 'A valid and unique email address'),
206
                'city' => new external_value(core_user::get_property_type('city'), 'Home city of the user', VALUE_DEFAULT, ''),
207
                'country' => new external_value(core_user::get_property_type('country'), 'Home country code', VALUE_DEFAULT, ''),
208
                'recaptchachallengehash' => new external_value(PARAM_RAW, 'Recaptcha challenge hash', VALUE_DEFAULT, ''),
209
                'recaptcharesponse' => new external_value(PARAM_NOTAGS, 'Recaptcha response', VALUE_DEFAULT, ''),
210
                'customprofilefields' => new external_multiple_structure(
211
                    new external_single_structure(
212
                        array(
213
                            'type'  => new external_value(PARAM_ALPHANUMEXT, 'The type of the custom field'),
214
                            'name'  => new external_value(PARAM_ALPHANUMEXT, 'The name of the custom field'),
215
                            'value' => new external_value(PARAM_RAW, 'Custom field value, can be an encoded json if required')
216
                        )
217
                    ), 'User custom fields (also known as user profile fields)', VALUE_DEFAULT, array()
218
                ),
219
                'redirect' => new external_value(PARAM_LOCALURL, 'Redirect the user to this site url after confirmation.',
220
                                                    VALUE_DEFAULT, ''),
221
            )
222
        );
223
    }
224
 
225
    /**
226
     * Get the signup required settings and profile fields.
227
     *
228
     * @param  string $username               username
229
     * @param  string $password               plain text password
230
     * @param  string $firstname              the first name(s) of the user
231
     * @param  string $lastname               the family name of the user
232
     * @param  string $email                  a valid and unique email address
233
     * @param  string $city                   home city of the user
234
     * @param  string $country                home country code
235
     * @param  string $recaptchachallengehash recaptcha challenge hash
236
     * @param  string $recaptcharesponse      recaptcha response
237
     * @param  array  $customprofilefields    user custom fields (also known as user profile fields)
238
     * @param  string $redirect               Site url to redirect the user after confirmation
239
     * @return array settings and possible warnings
240
     * @since Moodle 3.2
241
     * @throws moodle_exception
242
     * @throws invalid_parameter_exception
243
     */
244
    public static function signup_user($username, $password, $firstname, $lastname, $email, $city = '', $country = '',
245
                                        $recaptchachallengehash = '', $recaptcharesponse = '', $customprofilefields = array(),
246
                                        $redirect = '') {
247
        global $CFG, $PAGE;
248
 
249
        $warnings = array();
250
        $params = self::validate_parameters(
251
            self::signup_user_parameters(),
252
            array(
253
                'username' => $username,
254
                'password' => $password,
255
                'firstname' => $firstname,
256
                'lastname' => $lastname,
257
                'email' => $email,
258
                'city' => $city,
259
                'country' => $country,
260
                'recaptchachallengehash' => $recaptchachallengehash,
261
                'recaptcharesponse' => $recaptcharesponse,
262
                'customprofilefields' => $customprofilefields,
263
                'redirect' => $redirect,
264
            )
265
        );
266
 
267
        // We need this to make work the format text functions.
268
        $context = context_system::instance();
269
        $PAGE->set_context($context);
270
 
271
        self::check_signup_enabled();
272
 
273
        // Validate profile fields param types.
274
        $allowedfields = profile_get_signup_fields();
275
        $fieldproperties = array();
276
        $fieldsrequired = array();
277
        foreach ($allowedfields as $field) {
278
            $fieldproperties[$field->object->inputname] = $field->object->get_field_properties();
279
            if ($field->object->is_required()) {
280
                $fieldsrequired[$field->object->inputname] = true;
281
            }
282
        }
283
 
284
        foreach ($params['customprofilefields'] as $profilefield) {
285
            if (!array_key_exists($profilefield['name'], $fieldproperties)) {
286
                throw new invalid_parameter_exception('Invalid field' . $profilefield['name']);
287
            }
288
            list($type, $allownull) = $fieldproperties[$profilefield['name']];
289
            validate_param($profilefield['value'], $type, $allownull);
290
            // Remove from the potential required list.
291
            if (isset($fieldsrequired[$profilefield['name']])) {
292
                unset($fieldsrequired[$profilefield['name']]);
293
            }
294
        }
295
        if (!empty($fieldsrequired)) {
296
            throw new invalid_parameter_exception('Missing required parameters: ' . implode(',', array_keys($fieldsrequired)));
297
        }
298
 
299
        // Validate the data sent.
300
        $data = $params;
301
        $data['email2'] = $data['email'];
302
        // Force policy agreed if a site policy is set. The client is responsible of implementing the interface check.
303
        $manager = new \core_privacy\local\sitepolicy\manager();
304
        if ($manager->is_defined()) {
305
            $data['policyagreed'] = 1;
306
        }
307
        unset($data['recaptcharesponse']);
308
        unset($data['customprofilefields']);
309
        // Add profile fields data.
310
        foreach ($params['customprofilefields'] as $profilefield) {
311
            // First, check if the value is a json (some profile fields like text area uses an array for sending data).
312
            $datadecoded = json_decode($profilefield['value'], true);
313
            if (is_array($datadecoded) && (json_last_error() == JSON_ERROR_NONE)) {
314
                $data[$profilefield['name']] = $datadecoded;
315
            } else {
316
                $data[$profilefield['name']] = $profilefield['value'];
317
            }
318
        }
319
 
320
        $errors = signup_validate_data($data, array());
321
 
322
        // Validate recaptcha.
323
        if (signup_captcha_enabled()) {
324
            require_once($CFG->libdir . '/recaptchalib_v2.php');
325
            $response = recaptcha_check_response(RECAPTCHA_VERIFY_URL, $CFG->recaptchaprivatekey,
326
                                                 getremoteaddr(), $params['recaptcharesponse']);
327
            if (!$response['isvalid']) {
328
                $errors['recaptcharesponse'] = $response['error'];
329
            }
330
        }
331
 
332
        if (!empty($errors)) {
333
            foreach ($errors as $itemname => $message) {
334
                $warnings[] = array(
335
                    'item' => $itemname,
336
                    'itemid' => 0,
337
                    'warningcode' => 'fielderror',
338
                    'message' => s($message)
339
                );
340
            }
341
            $result = array(
342
                'success' => false,
343
                'warnings' => $warnings,
344
            );
345
        } else {
346
            // Save the user.
347
            $user = signup_setup_new_user((object) $data);
348
 
349
            $authplugin = get_auth_plugin('email');
350
 
351
            // Check if we should redirect the user once the user is confirmed.
352
            $confirmationurl = null;
353
            if (!empty($params['redirect'])) {
354
                // Pass via moodle_url to fix thinks like admin links.
355
                $redirect = new moodle_url($params['redirect']);
356
 
357
                $confirmationurl = new moodle_url('/login/confirm.php', array('redirect' => $redirect->out()));
358
            }
359
            $authplugin->user_signup_with_confirmation($user, false, $confirmationurl);
360
 
361
            $result = array(
362
                'success' => true,
363
                'warnings' => array(),
364
            );
365
        }
366
        return $result;
367
    }
368
 
369
    /**
370
     * Describes the signup_user return value.
371
     *
372
     * @return external_single_structure
373
     * @since Moodle 3.2
374
     */
375
    public static function signup_user_returns() {
376
 
377
        return new external_single_structure(
378
            array(
379
                'success' => new external_value(PARAM_BOOL, 'True if the user was created false otherwise'),
380
                'warnings'  => new external_warnings(),
381
            )
382
        );
383
    }
384
}