external.php 17 KB

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