PageRenderTime 52ms CodeModel.GetById 16ms RepoModel.GetById 1ms app.codeStats 0ms

/lib/externallib.php

http://github.com/moodle/moodle
PHP | 1556 lines | 858 code | 155 blank | 543 comment | 172 complexity | 72ddd8f6c51116a6a3bb8d886e964b83 MD5 | raw file
Possible License(s): MIT, AGPL-3.0, MPL-2.0-no-copyleft-exception, LGPL-3.0, GPL-3.0, Apache-2.0, LGPL-2.1, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. * Support for external API
  18. *
  19. * @package core_webservice
  20. * @copyright 2009 Petr Skodak
  21. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  22. */
  23. defined('MOODLE_INTERNAL') || die();
  24. /**
  25. * Exception indicating user is not allowed to use external function in the current context.
  26. *
  27. * @package core_webservice
  28. * @copyright 2009 Petr Skodak
  29. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  30. * @since Moodle 2.0
  31. */
  32. class restricted_context_exception extends moodle_exception {
  33. /**
  34. * Constructor
  35. *
  36. * @since Moodle 2.0
  37. */
  38. function __construct() {
  39. parent::__construct('restrictedcontextexception', 'error');
  40. }
  41. }
  42. /**
  43. * Base class for external api methods.
  44. *
  45. * @package core_webservice
  46. * @copyright 2009 Petr Skodak
  47. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  48. * @since Moodle 2.0
  49. */
  50. class external_api {
  51. /** @var stdClass context where the function calls will be restricted */
  52. private static $contextrestriction;
  53. /**
  54. * Returns detailed function information
  55. *
  56. * @param string|object $function name of external function or record from external_function
  57. * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
  58. * MUST_EXIST means throw exception if no record or multiple records found
  59. * @return stdClass description or false if not found or exception thrown
  60. * @since Moodle 2.0
  61. */
  62. public static function external_function_info($function, $strictness=MUST_EXIST) {
  63. global $DB, $CFG;
  64. if (!is_object($function)) {
  65. if (!$function = $DB->get_record('external_functions', array('name' => $function), '*', $strictness)) {
  66. return false;
  67. }
  68. }
  69. // First try class autoloading.
  70. if (!class_exists($function->classname)) {
  71. // Fallback to explicit include of externallib.php.
  72. if (empty($function->classpath)) {
  73. $function->classpath = core_component::get_component_directory($function->component).'/externallib.php';
  74. } else {
  75. $function->classpath = $CFG->dirroot.'/'.$function->classpath;
  76. }
  77. if (!file_exists($function->classpath)) {
  78. throw new coding_exception('Cannot find file with external function implementation');
  79. }
  80. require_once($function->classpath);
  81. if (!class_exists($function->classname)) {
  82. throw new coding_exception('Cannot find external class');
  83. }
  84. }
  85. $function->ajax_method = $function->methodname.'_is_allowed_from_ajax';
  86. $function->parameters_method = $function->methodname.'_parameters';
  87. $function->returns_method = $function->methodname.'_returns';
  88. $function->deprecated_method = $function->methodname.'_is_deprecated';
  89. // Make sure the implementaion class is ok.
  90. if (!method_exists($function->classname, $function->methodname)) {
  91. throw new coding_exception('Missing implementation method of '.$function->classname.'::'.$function->methodname);
  92. }
  93. if (!method_exists($function->classname, $function->parameters_method)) {
  94. throw new coding_exception('Missing parameters description');
  95. }
  96. if (!method_exists($function->classname, $function->returns_method)) {
  97. throw new coding_exception('Missing returned values description');
  98. }
  99. if (method_exists($function->classname, $function->deprecated_method)) {
  100. if (call_user_func(array($function->classname, $function->deprecated_method)) === true) {
  101. $function->deprecated = true;
  102. }
  103. }
  104. $function->allowed_from_ajax = false;
  105. // Fetch the parameters description.
  106. $function->parameters_desc = call_user_func(array($function->classname, $function->parameters_method));
  107. if (!($function->parameters_desc instanceof external_function_parameters)) {
  108. throw new coding_exception('Invalid parameters description');
  109. }
  110. // Fetch the return values description.
  111. $function->returns_desc = call_user_func(array($function->classname, $function->returns_method));
  112. // Null means void result or result is ignored.
  113. if (!is_null($function->returns_desc) and !($function->returns_desc instanceof external_description)) {
  114. throw new coding_exception('Invalid return description');
  115. }
  116. // Now get the function description.
  117. // TODO MDL-31115 use localised lang pack descriptions, it would be nice to have
  118. // easy to understand descriptions in admin UI,
  119. // on the other hand this is still a bit in a flux and we need to find some new naming
  120. // conventions for these descriptions in lang packs.
  121. $function->description = null;
  122. $servicesfile = core_component::get_component_directory($function->component).'/db/services.php';
  123. if (file_exists($servicesfile)) {
  124. $functions = null;
  125. include($servicesfile);
  126. if (isset($functions[$function->name]['description'])) {
  127. $function->description = $functions[$function->name]['description'];
  128. }
  129. if (isset($functions[$function->name]['testclientpath'])) {
  130. $function->testclientpath = $functions[$function->name]['testclientpath'];
  131. }
  132. if (isset($functions[$function->name]['type'])) {
  133. $function->type = $functions[$function->name]['type'];
  134. }
  135. if (isset($functions[$function->name]['ajax'])) {
  136. $function->allowed_from_ajax = $functions[$function->name]['ajax'];
  137. } else if (method_exists($function->classname, $function->ajax_method)) {
  138. if (call_user_func(array($function->classname, $function->ajax_method)) === true) {
  139. debugging('External function ' . $function->ajax_method . '() function is deprecated.' .
  140. 'Set ajax=>true in db/service.php instead.', DEBUG_DEVELOPER);
  141. $function->allowed_from_ajax = true;
  142. }
  143. }
  144. if (isset($functions[$function->name]['loginrequired'])) {
  145. $function->loginrequired = $functions[$function->name]['loginrequired'];
  146. } else {
  147. $function->loginrequired = true;
  148. }
  149. if (isset($functions[$function->name]['readonlysession'])) {
  150. $function->readonlysession = $functions[$function->name]['readonlysession'];
  151. } else {
  152. $function->readonlysession = false;
  153. }
  154. }
  155. return $function;
  156. }
  157. /**
  158. * Call an external function validating all params/returns correctly.
  159. *
  160. * Note that an external function may modify the state of the current page, so this wrapper
  161. * saves and restores tha PAGE and COURSE global variables before/after calling the external function.
  162. *
  163. * @param string $function A webservice function name.
  164. * @param array $args Params array (named params)
  165. * @param boolean $ajaxonly If true, an extra check will be peformed to see if ajax is required.
  166. * @return array containing keys for error (bool), exception and data.
  167. */
  168. public static function call_external_function($function, $args, $ajaxonly=false) {
  169. global $PAGE, $COURSE, $CFG, $SITE;
  170. require_once($CFG->libdir . "/pagelib.php");
  171. $externalfunctioninfo = static::external_function_info($function);
  172. // Eventually this should shift into the various handlers and not be handled via config.
  173. $readonlysession = $externalfunctioninfo->readonlysession ?? false;
  174. if (!$readonlysession || empty($CFG->enable_read_only_sessions)) {
  175. \core\session\manager::restart_with_write_lock();
  176. }
  177. $currentpage = $PAGE;
  178. $currentcourse = $COURSE;
  179. $response = array();
  180. try {
  181. // Taken straight from from setup.php.
  182. if (!empty($CFG->moodlepageclass)) {
  183. if (!empty($CFG->moodlepageclassfile)) {
  184. require_once($CFG->moodlepageclassfile);
  185. }
  186. $classname = $CFG->moodlepageclass;
  187. } else {
  188. $classname = 'moodle_page';
  189. }
  190. $PAGE = new $classname();
  191. $COURSE = clone($SITE);
  192. if ($ajaxonly && !$externalfunctioninfo->allowed_from_ajax) {
  193. throw new moodle_exception('servicenotavailable', 'webservice');
  194. }
  195. // Do not allow access to write or delete webservices as a public user.
  196. if ($externalfunctioninfo->loginrequired && !WS_SERVER) {
  197. if (defined('NO_MOODLE_COOKIES') && NO_MOODLE_COOKIES && !PHPUNIT_TEST) {
  198. throw new moodle_exception('servicerequireslogin', 'webservice');
  199. }
  200. if (!isloggedin()) {
  201. throw new moodle_exception('servicerequireslogin', 'webservice');
  202. } else {
  203. require_sesskey();
  204. }
  205. }
  206. // Validate params, this also sorts the params properly, we need the correct order in the next part.
  207. $callable = array($externalfunctioninfo->classname, 'validate_parameters');
  208. $params = call_user_func($callable,
  209. $externalfunctioninfo->parameters_desc,
  210. $args);
  211. $params = array_values($params);
  212. // Allow any Moodle plugin a chance to override this call. This is a convenient spot to
  213. // make arbitrary behaviour customisations. The overriding plugin could call the 'real'
  214. // function first and then modify the results, or it could do a completely separate
  215. // thing.
  216. $callbacks = get_plugins_with_function('override_webservice_execution');
  217. $result = false;
  218. foreach ($callbacks as $plugintype => $plugins) {
  219. foreach ($plugins as $plugin => $callback) {
  220. $result = $callback($externalfunctioninfo, $params);
  221. if ($result !== false) {
  222. break;
  223. }
  224. }
  225. }
  226. // If the function was not overridden, call the real one.
  227. if ($result === false) {
  228. $callable = array($externalfunctioninfo->classname, $externalfunctioninfo->methodname);
  229. $result = call_user_func_array($callable, $params);
  230. }
  231. // Validate the return parameters.
  232. if ($externalfunctioninfo->returns_desc !== null) {
  233. $callable = array($externalfunctioninfo->classname, 'clean_returnvalue');
  234. $result = call_user_func($callable, $externalfunctioninfo->returns_desc, $result);
  235. }
  236. $response['error'] = false;
  237. $response['data'] = $result;
  238. } catch (Throwable $e) {
  239. $exception = get_exception_info($e);
  240. unset($exception->a);
  241. $exception->backtrace = format_backtrace($exception->backtrace, true);
  242. if (!debugging('', DEBUG_DEVELOPER)) {
  243. unset($exception->debuginfo);
  244. unset($exception->backtrace);
  245. }
  246. $response['error'] = true;
  247. $response['exception'] = $exception;
  248. // Do not process the remaining requests.
  249. }
  250. $PAGE = $currentpage;
  251. $COURSE = $currentcourse;
  252. return $response;
  253. }
  254. /**
  255. * Set context restriction for all following subsequent function calls.
  256. *
  257. * @param stdClass $context the context restriction
  258. * @since Moodle 2.0
  259. */
  260. public static function set_context_restriction($context) {
  261. self::$contextrestriction = $context;
  262. }
  263. /**
  264. * This method has to be called before every operation
  265. * that takes a longer time to finish!
  266. *
  267. * @param int $seconds max expected time the next operation needs
  268. * @since Moodle 2.0
  269. */
  270. public static function set_timeout($seconds=360) {
  271. $seconds = ($seconds < 300) ? 300 : $seconds;
  272. core_php_time_limit::raise($seconds);
  273. }
  274. /**
  275. * Validates submitted function parameters, if anything is incorrect
  276. * invalid_parameter_exception is thrown.
  277. * This is a simple recursive method which is intended to be called from
  278. * each implementation method of external API.
  279. *
  280. * @param external_description $description description of parameters
  281. * @param mixed $params the actual parameters
  282. * @return mixed params with added defaults for optional items, invalid_parameters_exception thrown if any problem found
  283. * @since Moodle 2.0
  284. */
  285. public static function validate_parameters(external_description $description, $params) {
  286. if ($description instanceof external_value) {
  287. if (is_array($params) or is_object($params)) {
  288. throw new invalid_parameter_exception('Scalar type expected, array or object received.');
  289. }
  290. if ($description->type == PARAM_BOOL) {
  291. // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
  292. if (is_bool($params) or $params === 0 or $params === 1 or $params === '0' or $params === '1') {
  293. return (bool)$params;
  294. }
  295. }
  296. $debuginfo = 'Invalid external api parameter: the value is "' . $params .
  297. '", the server was expecting "' . $description->type . '" type';
  298. return validate_param($params, $description->type, $description->allownull, $debuginfo);
  299. } else if ($description instanceof external_single_structure) {
  300. if (!is_array($params)) {
  301. throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
  302. . print_r($params, true) . '\'');
  303. }
  304. $result = array();
  305. foreach ($description->keys as $key=>$subdesc) {
  306. if (!array_key_exists($key, $params)) {
  307. if ($subdesc->required == VALUE_REQUIRED) {
  308. throw new invalid_parameter_exception('Missing required key in single structure: '. $key);
  309. }
  310. if ($subdesc->required == VALUE_DEFAULT) {
  311. try {
  312. $result[$key] = static::validate_parameters($subdesc, $subdesc->default);
  313. } catch (invalid_parameter_exception $e) {
  314. //we are only interested by exceptions returned by validate_param() and validate_parameters()
  315. //(in order to build the path to the faulty attribut)
  316. throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
  317. }
  318. }
  319. } else {
  320. try {
  321. $result[$key] = static::validate_parameters($subdesc, $params[$key]);
  322. } catch (invalid_parameter_exception $e) {
  323. //we are only interested by exceptions returned by validate_param() and validate_parameters()
  324. //(in order to build the path to the faulty attribut)
  325. throw new invalid_parameter_exception($key." => ".$e->getMessage() . ': ' .$e->debuginfo);
  326. }
  327. }
  328. unset($params[$key]);
  329. }
  330. if (!empty($params)) {
  331. throw new invalid_parameter_exception('Unexpected keys (' . implode(', ', array_keys($params)) . ') detected in parameter array.');
  332. }
  333. return $result;
  334. } else if ($description instanceof external_multiple_structure) {
  335. if (!is_array($params)) {
  336. throw new invalid_parameter_exception('Only arrays accepted. The bad value is: \''
  337. . print_r($params, true) . '\'');
  338. }
  339. $result = array();
  340. foreach ($params as $param) {
  341. $result[] = static::validate_parameters($description->content, $param);
  342. }
  343. return $result;
  344. } else {
  345. throw new invalid_parameter_exception('Invalid external api description');
  346. }
  347. }
  348. /**
  349. * Clean response
  350. * If a response attribute is unknown from the description, we just ignore the attribute.
  351. * If a response attribute is incorrect, invalid_response_exception is thrown.
  352. * Note: this function is similar to validate parameters, however it is distinct because
  353. * parameters validation must be distinct from cleaning return values.
  354. *
  355. * @param external_description $description description of the return values
  356. * @param mixed $response the actual response
  357. * @return mixed response with added defaults for optional items, invalid_response_exception thrown if any problem found
  358. * @author 2010 Jerome Mouneyrac
  359. * @since Moodle 2.0
  360. */
  361. public static function clean_returnvalue(external_description $description, $response) {
  362. if ($description instanceof external_value) {
  363. if (is_array($response) or is_object($response)) {
  364. throw new invalid_response_exception('Scalar type expected, array or object received.');
  365. }
  366. if ($description->type == PARAM_BOOL) {
  367. // special case for PARAM_BOOL - we want true/false instead of the usual 1/0 - we can not be too strict here ;-)
  368. if (is_bool($response) or $response === 0 or $response === 1 or $response === '0' or $response === '1') {
  369. return (bool)$response;
  370. }
  371. }
  372. $responsetype = gettype($response);
  373. $debuginfo = 'Invalid external api response: the value is "' . $response .
  374. '" of PHP type "' . $responsetype . '", the server was expecting "' . $description->type . '" type';
  375. try {
  376. return validate_param($response, $description->type, $description->allownull, $debuginfo);
  377. } catch (invalid_parameter_exception $e) {
  378. //proper exception name, to be recursively catched to build the path to the faulty attribut
  379. throw new invalid_response_exception($e->debuginfo);
  380. }
  381. } else if ($description instanceof external_single_structure) {
  382. if (!is_array($response) && !is_object($response)) {
  383. throw new invalid_response_exception('Only arrays/objects accepted. The bad value is: \'' .
  384. print_r($response, true) . '\'');
  385. }
  386. // Cast objects into arrays.
  387. if (is_object($response)) {
  388. $response = (array) $response;
  389. }
  390. $result = array();
  391. foreach ($description->keys as $key=>$subdesc) {
  392. if (!array_key_exists($key, $response)) {
  393. if ($subdesc->required == VALUE_REQUIRED) {
  394. throw new invalid_response_exception('Error in response - Missing following required key in a single structure: ' . $key);
  395. }
  396. if ($subdesc instanceof external_value) {
  397. if ($subdesc->required == VALUE_DEFAULT) {
  398. try {
  399. $result[$key] = static::clean_returnvalue($subdesc, $subdesc->default);
  400. } catch (invalid_response_exception $e) {
  401. //build the path to the faulty attribut
  402. throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
  403. }
  404. }
  405. }
  406. } else {
  407. try {
  408. $result[$key] = static::clean_returnvalue($subdesc, $response[$key]);
  409. } catch (invalid_response_exception $e) {
  410. //build the path to the faulty attribut
  411. throw new invalid_response_exception($key." => ".$e->getMessage() . ': ' . $e->debuginfo);
  412. }
  413. }
  414. unset($response[$key]);
  415. }
  416. return $result;
  417. } else if ($description instanceof external_multiple_structure) {
  418. if (!is_array($response)) {
  419. throw new invalid_response_exception('Only arrays accepted. The bad value is: \'' .
  420. print_r($response, true) . '\'');
  421. }
  422. $result = array();
  423. foreach ($response as $param) {
  424. $result[] = static::clean_returnvalue($description->content, $param);
  425. }
  426. return $result;
  427. } else {
  428. throw new invalid_response_exception('Invalid external api response description');
  429. }
  430. }
  431. /**
  432. * Makes sure user may execute functions in this context.
  433. *
  434. * @param stdClass $context
  435. * @since Moodle 2.0
  436. */
  437. public static function validate_context($context) {
  438. global $CFG, $PAGE;
  439. if (empty($context)) {
  440. throw new invalid_parameter_exception('Context does not exist');
  441. }
  442. if (empty(self::$contextrestriction)) {
  443. self::$contextrestriction = context_system::instance();
  444. }
  445. $rcontext = self::$contextrestriction;
  446. if ($rcontext->contextlevel == $context->contextlevel) {
  447. if ($rcontext->id != $context->id) {
  448. throw new restricted_context_exception();
  449. }
  450. } else if ($rcontext->contextlevel > $context->contextlevel) {
  451. throw new restricted_context_exception();
  452. } else {
  453. $parents = $context->get_parent_context_ids();
  454. if (!in_array($rcontext->id, $parents)) {
  455. throw new restricted_context_exception();
  456. }
  457. }
  458. $PAGE->reset_theme_and_output();
  459. list($unused, $course, $cm) = get_context_info_array($context->id);
  460. require_login($course, false, $cm, false, true);
  461. $PAGE->set_context($context);
  462. }
  463. /**
  464. * Get context from passed parameters.
  465. * The passed array must either contain a contextid or a combination of context level and instance id to fetch the context.
  466. * For example, the context level can be "course" and instanceid can be courseid.
  467. *
  468. * See context_helper::get_all_levels() for a list of valid context levels.
  469. *
  470. * @param array $param
  471. * @since Moodle 2.6
  472. * @throws invalid_parameter_exception
  473. * @return context
  474. */
  475. protected static function get_context_from_params($param) {
  476. $levels = context_helper::get_all_levels();
  477. if (!empty($param['contextid'])) {
  478. return context::instance_by_id($param['contextid'], IGNORE_MISSING);
  479. } else if (!empty($param['contextlevel']) && isset($param['instanceid'])) {
  480. $contextlevel = "context_".$param['contextlevel'];
  481. if (!array_search($contextlevel, $levels)) {
  482. throw new invalid_parameter_exception('Invalid context level = '.$param['contextlevel']);
  483. }
  484. return $contextlevel::instance($param['instanceid'], IGNORE_MISSING);
  485. } else {
  486. // No valid context info was found.
  487. throw new invalid_parameter_exception('Missing parameters, please provide either context level with instance id or contextid');
  488. }
  489. }
  490. /**
  491. * Returns a prepared structure to use a context parameters.
  492. * @return external_single_structure
  493. */
  494. protected static function get_context_parameters() {
  495. $id = new external_value(
  496. PARAM_INT,
  497. 'Context ID. Either use this value, or level and instanceid.',
  498. VALUE_DEFAULT,
  499. 0
  500. );
  501. $level = new external_value(
  502. PARAM_ALPHA,
  503. 'Context level. To be used with instanceid.',
  504. VALUE_DEFAULT,
  505. ''
  506. );
  507. $instanceid = new external_value(
  508. PARAM_INT,
  509. 'Context instance ID. To be used with level',
  510. VALUE_DEFAULT,
  511. 0
  512. );
  513. return new external_single_structure(array(
  514. 'contextid' => $id,
  515. 'contextlevel' => $level,
  516. 'instanceid' => $instanceid,
  517. ));
  518. }
  519. }
  520. /**
  521. * Common ancestor of all parameter description classes
  522. *
  523. * @package core_webservice
  524. * @copyright 2009 Petr Skodak
  525. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  526. * @since Moodle 2.0
  527. */
  528. abstract class external_description {
  529. /** @var string Description of element */
  530. public $desc;
  531. /** @var bool Element value required, null not allowed */
  532. public $required;
  533. /** @var mixed Default value */
  534. public $default;
  535. /**
  536. * Contructor
  537. *
  538. * @param string $desc
  539. * @param bool $required
  540. * @param mixed $default
  541. * @since Moodle 2.0
  542. */
  543. public function __construct($desc, $required, $default) {
  544. $this->desc = $desc;
  545. $this->required = $required;
  546. $this->default = $default;
  547. }
  548. }
  549. /**
  550. * Scalar value description class
  551. *
  552. * @package core_webservice
  553. * @copyright 2009 Petr Skodak
  554. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  555. * @since Moodle 2.0
  556. */
  557. class external_value extends external_description {
  558. /** @var mixed Value type PARAM_XX */
  559. public $type;
  560. /** @var bool Allow null values */
  561. public $allownull;
  562. /**
  563. * Constructor
  564. *
  565. * @param mixed $type
  566. * @param string $desc
  567. * @param bool $required
  568. * @param mixed $default
  569. * @param bool $allownull
  570. * @since Moodle 2.0
  571. */
  572. public function __construct($type, $desc='', $required=VALUE_REQUIRED,
  573. $default=null, $allownull=NULL_ALLOWED) {
  574. parent::__construct($desc, $required, $default);
  575. $this->type = $type;
  576. $this->allownull = $allownull;
  577. }
  578. }
  579. /**
  580. * Associative array description class
  581. *
  582. * @package core_webservice
  583. * @copyright 2009 Petr Skodak
  584. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  585. * @since Moodle 2.0
  586. */
  587. class external_single_structure extends external_description {
  588. /** @var array Description of array keys key=>external_description */
  589. public $keys;
  590. /**
  591. * Constructor
  592. *
  593. * @param array $keys
  594. * @param string $desc
  595. * @param bool $required
  596. * @param array $default
  597. * @since Moodle 2.0
  598. */
  599. public function __construct(array $keys, $desc='',
  600. $required=VALUE_REQUIRED, $default=null) {
  601. parent::__construct($desc, $required, $default);
  602. $this->keys = $keys;
  603. }
  604. }
  605. /**
  606. * Bulk array description class.
  607. *
  608. * @package core_webservice
  609. * @copyright 2009 Petr Skodak
  610. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  611. * @since Moodle 2.0
  612. */
  613. class external_multiple_structure extends external_description {
  614. /** @var external_description content */
  615. public $content;
  616. /**
  617. * Constructor
  618. *
  619. * @param external_description $content
  620. * @param string $desc
  621. * @param bool $required
  622. * @param array $default
  623. * @since Moodle 2.0
  624. */
  625. public function __construct(external_description $content, $desc='',
  626. $required=VALUE_REQUIRED, $default=null) {
  627. parent::__construct($desc, $required, $default);
  628. $this->content = $content;
  629. }
  630. }
  631. /**
  632. * Description of top level - PHP function parameters.
  633. *
  634. * @package core_webservice
  635. * @copyright 2009 Petr Skodak
  636. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  637. * @since Moodle 2.0
  638. */
  639. class external_function_parameters extends external_single_structure {
  640. /**
  641. * Constructor - does extra checking to prevent top level optional parameters.
  642. *
  643. * @param array $keys
  644. * @param string $desc
  645. * @param bool $required
  646. * @param array $default
  647. */
  648. public function __construct(array $keys, $desc='', $required=VALUE_REQUIRED, $default=null) {
  649. global $CFG;
  650. if ($CFG->debugdeveloper) {
  651. foreach ($keys as $key => $value) {
  652. if ($value instanceof external_value) {
  653. if ($value->required == VALUE_OPTIONAL) {
  654. debugging('External function parameters: invalid OPTIONAL value specified.', DEBUG_DEVELOPER);
  655. break;
  656. }
  657. }
  658. }
  659. }
  660. parent::__construct($keys, $desc, $required, $default);
  661. }
  662. }
  663. /**
  664. * Generate a token
  665. *
  666. * @param string $tokentype EXTERNAL_TOKEN_EMBEDDED|EXTERNAL_TOKEN_PERMANENT
  667. * @param stdClass|int $serviceorid service linked to the token
  668. * @param int $userid user linked to the token
  669. * @param stdClass|int $contextorid
  670. * @param int $validuntil date when the token expired
  671. * @param string $iprestriction allowed ip - if 0 or empty then all ips are allowed
  672. * @return string generated token
  673. * @author 2010 Jamie Pratt
  674. * @since Moodle 2.0
  675. */
  676. function external_generate_token($tokentype, $serviceorid, $userid, $contextorid, $validuntil=0, $iprestriction=''){
  677. global $DB, $USER;
  678. // make sure the token doesn't exist (even if it should be almost impossible with the random generation)
  679. $numtries = 0;
  680. do {
  681. $numtries ++;
  682. $generatedtoken = md5(uniqid(rand(),1));
  683. if ($numtries > 5){
  684. throw new moodle_exception('tokengenerationfailed');
  685. }
  686. } while ($DB->record_exists('external_tokens', array('token'=>$generatedtoken)));
  687. $newtoken = new stdClass();
  688. $newtoken->token = $generatedtoken;
  689. if (!is_object($serviceorid)){
  690. $service = $DB->get_record('external_services', array('id' => $serviceorid));
  691. } else {
  692. $service = $serviceorid;
  693. }
  694. if (!is_object($contextorid)){
  695. $context = context::instance_by_id($contextorid, MUST_EXIST);
  696. } else {
  697. $context = $contextorid;
  698. }
  699. if (empty($service->requiredcapability) || has_capability($service->requiredcapability, $context, $userid)) {
  700. $newtoken->externalserviceid = $service->id;
  701. } else {
  702. throw new moodle_exception('nocapabilitytousethisservice');
  703. }
  704. $newtoken->tokentype = $tokentype;
  705. $newtoken->userid = $userid;
  706. if ($tokentype == EXTERNAL_TOKEN_EMBEDDED){
  707. $newtoken->sid = session_id();
  708. }
  709. $newtoken->contextid = $context->id;
  710. $newtoken->creatorid = $USER->id;
  711. $newtoken->timecreated = time();
  712. $newtoken->validuntil = $validuntil;
  713. if (!empty($iprestriction)) {
  714. $newtoken->iprestriction = $iprestriction;
  715. }
  716. // Generate the private token, it must be transmitted only via https.
  717. $newtoken->privatetoken = random_string(64);
  718. $DB->insert_record('external_tokens', $newtoken);
  719. return $newtoken->token;
  720. }
  721. /**
  722. * Create and return a session linked token. Token to be used for html embedded client apps that want to communicate
  723. * with the Moodle server through web services. The token is linked to the current session for the current page request.
  724. * It is expected this will be called in the script generating the html page that is embedding the client app and that the
  725. * returned token will be somehow passed into the client app being embedded in the page.
  726. *
  727. * @param string $servicename name of the web service. Service name as defined in db/services.php
  728. * @param int $context context within which the web service can operate.
  729. * @return int returns token id.
  730. * @since Moodle 2.0
  731. */
  732. function external_create_service_token($servicename, $context){
  733. global $USER, $DB;
  734. $service = $DB->get_record('external_services', array('name'=>$servicename), '*', MUST_EXIST);
  735. return external_generate_token(EXTERNAL_TOKEN_EMBEDDED, $service, $USER->id, $context, 0);
  736. }
  737. /**
  738. * Delete all pre-built services (+ related tokens) and external functions information defined in the specified component.
  739. *
  740. * @param string $component name of component (moodle, mod_assignment, etc.)
  741. */
  742. function external_delete_descriptions($component) {
  743. global $DB;
  744. $params = array($component);
  745. $DB->delete_records_select('external_tokens',
  746. "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
  747. $DB->delete_records_select('external_services_users',
  748. "externalserviceid IN (SELECT id FROM {external_services} WHERE component = ?)", $params);
  749. $DB->delete_records_select('external_services_functions',
  750. "functionname IN (SELECT name FROM {external_functions} WHERE component = ?)", $params);
  751. $DB->delete_records('external_services', array('component'=>$component));
  752. $DB->delete_records('external_functions', array('component'=>$component));
  753. }
  754. /**
  755. * Standard Moodle web service warnings
  756. *
  757. * @package core_webservice
  758. * @copyright 2012 Jerome Mouneyrac
  759. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  760. * @since Moodle 2.3
  761. */
  762. class external_warnings extends external_multiple_structure {
  763. /**
  764. * Constructor
  765. *
  766. * @since Moodle 2.3
  767. */
  768. public function __construct($itemdesc = 'item', $itemiddesc = 'item id',
  769. $warningcodedesc = 'the warning code can be used by the client app to implement specific behaviour') {
  770. parent::__construct(
  771. new external_single_structure(
  772. array(
  773. 'item' => new external_value(PARAM_TEXT, $itemdesc, VALUE_OPTIONAL),
  774. 'itemid' => new external_value(PARAM_INT, $itemiddesc, VALUE_OPTIONAL),
  775. 'warningcode' => new external_value(PARAM_ALPHANUM, $warningcodedesc),
  776. 'message' => new external_value(PARAM_TEXT,
  777. 'untranslated english message to explain the warning')
  778. ), 'warning'),
  779. 'list of warnings', VALUE_OPTIONAL);
  780. }
  781. }
  782. /**
  783. * A pre-filled external_value class for text format.
  784. *
  785. * Default is FORMAT_HTML
  786. * This should be used all the time in external xxx_params()/xxx_returns functions
  787. * as it is the standard way to implement text format param/return values.
  788. *
  789. * @package core_webservice
  790. * @copyright 2012 Jerome Mouneyrac
  791. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  792. * @since Moodle 2.3
  793. */
  794. class external_format_value extends external_value {
  795. /**
  796. * Constructor
  797. *
  798. * @param string $textfieldname Name of the text field
  799. * @param int $required if VALUE_REQUIRED then set standard default FORMAT_HTML
  800. * @param int $default Default value.
  801. * @since Moodle 2.3
  802. */
  803. public function __construct($textfieldname, $required = VALUE_REQUIRED, $default = null) {
  804. if ($default == null && $required == VALUE_DEFAULT) {
  805. $default = FORMAT_HTML;
  806. }
  807. $desc = $textfieldname . ' format (' . FORMAT_HTML . ' = HTML, '
  808. . FORMAT_MOODLE . ' = MOODLE, '
  809. . FORMAT_PLAIN . ' = PLAIN or '
  810. . FORMAT_MARKDOWN . ' = MARKDOWN)';
  811. parent::__construct(PARAM_INT, $desc, $required, $default);
  812. }
  813. }
  814. /**
  815. * Validate text field format against known FORMAT_XXX
  816. *
  817. * @param array $format the format to validate
  818. * @return the validated format
  819. * @throws coding_exception
  820. * @since Moodle 2.3
  821. */
  822. function external_validate_format($format) {
  823. $allowedformats = array(FORMAT_HTML, FORMAT_MOODLE, FORMAT_PLAIN, FORMAT_MARKDOWN);
  824. if (!in_array($format, $allowedformats)) {
  825. throw new moodle_exception('formatnotsupported', 'webservice', '' , null,
  826. 'The format with value=' . $format . ' is not supported by this Moodle site');
  827. }
  828. return $format;
  829. }
  830. /**
  831. * Format the string to be returned properly as requested by the either the web service server,
  832. * either by an internally call.
  833. * The caller can change the format (raw) with the external_settings singleton
  834. * All web service servers must set this singleton when parsing the $_GET and $_POST.
  835. *
  836. * <pre>
  837. * Options are the same that in {@link format_string()} with some changes:
  838. * filter : Can be set to false to force filters off, else observes {@link external_settings}.
  839. * </pre>
  840. *
  841. * @param string $str The string to be filtered. Should be plain text, expect
  842. * possibly for multilang tags.
  843. * @param boolean $striplinks To strip any link in the result text. Moodle 1.8 default changed from false to true! MDL-8713
  844. * @param context|int $contextorid The id of the context for the string or the context (affects filters).
  845. * @param array $options options array/object or courseid
  846. * @return string text
  847. * @since Moodle 3.0
  848. */
  849. function external_format_string($str, $contextorid, $striplinks = true, $options = array()) {
  850. // Get settings (singleton).
  851. $settings = external_settings::get_instance();
  852. if (empty($contextorid)) {
  853. throw new coding_exception('contextid is required');
  854. }
  855. if (!$settings->get_raw()) {
  856. if (is_object($contextorid) && is_a($contextorid, 'context')) {
  857. $context = $contextorid;
  858. } else {
  859. $context = context::instance_by_id($contextorid);
  860. }
  861. $options['context'] = $context;
  862. $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
  863. $str = format_string($str, $striplinks, $options);
  864. }
  865. return $str;
  866. }
  867. /**
  868. * Format the text to be returned properly as requested by the either the web service server,
  869. * either by an internally call.
  870. * The caller can change the format (raw, filter, file, fileurl) with the external_settings singleton
  871. * All web service servers must set this singleton when parsing the $_GET and $_POST.
  872. *
  873. * <pre>
  874. * Options are the same that in {@link format_text()} with some changes in defaults to provide backwards compatibility:
  875. * trusted : If true the string won't be cleaned. Default false.
  876. * noclean : If true the string won't be cleaned only if trusted is also true. Default false.
  877. * nocache : If true the string will not be cached and will be formatted every call. Default false.
  878. * filter : Can be set to false to force filters off, else observes {@link external_settings}.
  879. * para : If true then the returned string will be wrapped in div tags. Default (different from format_text) false.
  880. * Default changed because div tags are not commonly needed.
  881. * newlines : If true then lines newline breaks will be converted to HTML newline breaks. Default true.
  882. * context : Not used! Using contextid parameter instead.
  883. * overflowdiv : If set to true the formatted text will be encased in a div with the class no-overflow before being
  884. * returned. Default false.
  885. * allowid : If true then id attributes will not be removed, even when using htmlpurifier. Default (different from
  886. * format_text) true. Default changed id attributes are commonly needed.
  887. * blanktarget : If true all <a> tags will have target="_blank" added unless target is explicitly specified.
  888. * </pre>
  889. *
  890. * @param string $text The content that may contain ULRs in need of rewriting.
  891. * @param int $textformat The text format.
  892. * @param context|int $contextorid This parameter and the next two identify the file area to use.
  893. * @param string $component
  894. * @param string $filearea helps identify the file area.
  895. * @param int $itemid helps identify the file area.
  896. * @param object/array $options text formatting options
  897. * @return array text + textformat
  898. * @since Moodle 2.3
  899. * @since Moodle 3.2 component, filearea and itemid are optional parameters
  900. */
  901. function external_format_text($text, $textformat, $contextorid, $component = null, $filearea = null, $itemid = null,
  902. $options = null) {
  903. global $CFG;
  904. // Get settings (singleton).
  905. $settings = external_settings::get_instance();
  906. if (is_object($contextorid) && is_a($contextorid, 'context')) {
  907. $context = $contextorid;
  908. $contextid = $context->id;
  909. } else {
  910. $context = null;
  911. $contextid = $contextorid;
  912. }
  913. if ($component and $filearea and $settings->get_fileurl()) {
  914. require_once($CFG->libdir . "/filelib.php");
  915. $text = file_rewrite_pluginfile_urls($text, $settings->get_file(), $contextid, $component, $filearea, $itemid);
  916. }
  917. // Note that $CFG->forceclean does not apply here if the client requests for the raw database content.
  918. // This is consistent with web clients that are still able to load non-cleaned text into editors, too.
  919. if (!$settings->get_raw()) {
  920. $options = (array)$options;
  921. // If context is passed in options, check that is the same to show a debug message.
  922. if (isset($options['context'])) {
  923. if ((is_object($options['context']) && $options['context']->id != $contextid)
  924. || (!is_object($options['context']) && $options['context'] != $contextid)) {
  925. debugging('Different contexts found in external_format_text parameters. $options[\'context\'] not allowed.
  926. Using $contextid parameter...', DEBUG_DEVELOPER);
  927. }
  928. }
  929. $options['filter'] = isset($options['filter']) && !$options['filter'] ? false : $settings->get_filter();
  930. $options['para'] = isset($options['para']) ? $options['para'] : false;
  931. $options['context'] = !is_null($context) ? $context : context::instance_by_id($contextid);
  932. $options['allowid'] = isset($options['allowid']) ? $options['allowid'] : true;
  933. $text = format_text($text, $textformat, $options);
  934. $textformat = FORMAT_HTML; // Once converted to html (from markdown, plain... lets inform consumer this is already HTML).
  935. }
  936. return array($text, $textformat);
  937. }
  938. /**
  939. * Generate or return an existing token for the current authenticated user.
  940. * This function is used for creating a valid token for users authenticathing via login/token.php or admin/tool/mobile/launch.php.
  941. *
  942. * @param stdClass $service external service object
  943. * @return stdClass token object
  944. * @since Moodle 3.2
  945. * @throws moodle_exception
  946. */
  947. function external_generate_token_for_current_user($service) {
  948. global $DB, $USER, $CFG;
  949. core_user::require_active_user($USER, true, true);
  950. // Check if there is any required system capability.
  951. if ($service->requiredcapability and !has_capability($service->requiredcapability, context_system::instance())) {
  952. throw new moodle_exception('missingrequiredcapability', 'webservice', '', $service->requiredcapability);
  953. }
  954. // Specific checks related to user restricted service.
  955. if ($service->restrictedusers) {
  956. $authoriseduser = $DB->get_record('external_services_users',
  957. array('externalserviceid' => $service->id, 'userid' => $USER->id));
  958. if (empty($authoriseduser)) {
  959. throw new moodle_exception('usernotallowed', 'webservice', '', $service->shortname);
  960. }
  961. if (!empty($authoriseduser->validuntil) and $authoriseduser->validuntil < time()) {
  962. throw new moodle_exception('invalidtimedtoken', 'webservice');
  963. }
  964. if (!empty($authoriseduser->iprestriction) and !address_in_subnet(getremoteaddr(), $authoriseduser->iprestriction)) {
  965. throw new moodle_exception('invalidiptoken', 'webservice');
  966. }
  967. }
  968. // Check if a token has already been created for this user and this service.
  969. $conditions = array(
  970. 'userid' => $USER->id,
  971. 'externalserviceid' => $service->id,
  972. 'tokentype' => EXTERNAL_TOKEN_PERMANENT
  973. );
  974. $tokens = $DB->get_records('external_tokens', $conditions, 'timecreated ASC');
  975. // A bit of sanity checks.
  976. foreach ($tokens as $key => $token) {
  977. // Checks related to a specific token. (script execution continue).
  978. $unsettoken = false;
  979. // If sid is set then there must be a valid associated session no matter the token type.
  980. if (!empty($token->sid)) {
  981. if (!\core\session\manager::session_exists($token->sid)) {
  982. // This token will never be valid anymore, delete it.
  983. $DB->delete_records('external_tokens', array('sid' => $token->sid));
  984. $unsettoken = true;
  985. }
  986. }
  987. // Remove token is not valid anymore.
  988. if (!empty($token->validuntil) and $token->validuntil < time()) {
  989. $DB->delete_records('external_tokens', array('token' => $token->token, 'tokentype' => EXTERNAL_TOKEN_PERMANENT));
  990. $unsettoken = true;
  991. }
  992. // Remove token if its ip not in whitelist.
  993. if (isset($token->iprestriction) and !address_in_subnet(getremoteaddr(), $token->iprestriction)) {
  994. $unsettoken = true;
  995. }
  996. if ($unsettoken) {
  997. unset($tokens[$key]);
  998. }
  999. }
  1000. // If some valid tokens exist then use the most recent.
  1001. if (count($tokens) > 0) {
  1002. $token = array_pop($tokens);
  1003. } else {
  1004. $context = context_system::instance();
  1005. $isofficialservice = $service->shortname == MOODLE_OFFICIAL_MOBILE_SERVICE;
  1006. if (($isofficialservice and has_capability('moodle/webservice:createmobiletoken', $context)) or
  1007. (!is_siteadmin($USER) && has_capability('moodle/webservice:createtoken', $context))) {
  1008. // Create a new token.
  1009. $token = new stdClass;
  1010. $token->token = md5(uniqid(rand(), 1));
  1011. $token->userid = $USER->id;
  1012. $token->tokentype = EXTERNAL_TOKEN_PERMANENT;
  1013. $token->contextid = context_system::instance()->id;
  1014. $token->creatorid = $USER->id;
  1015. $token->timecreated = time();
  1016. $token->externalserviceid = $service->id;
  1017. // By default tokens are valid for 12 weeks.
  1018. $token->validuntil = $token->timecreated + $CFG->tokenduration;
  1019. $token->iprestriction = null;
  1020. $token->sid = null;
  1021. $token->lastaccess = null;
  1022. // Generate the private token, it must be transmitted only via https.
  1023. $token->privatetoken = random_string(64);
  1024. $token->id = $DB->insert_record('external_tokens', $token);
  1025. $eventtoken = clone $token;
  1026. $eventtoken->privatetoken = null;
  1027. $params = array(
  1028. 'objectid' => $eventtoken->id,
  1029. 'relateduserid' => $USER->id,
  1030. 'other' => array(
  1031. 'auto' => true
  1032. )
  1033. );
  1034. $event = \core\event\webservice_token_created::create($params);
  1035. $event->add_record_snapshot('external_tokens', $eventtoken);
  1036. $event->trigger();
  1037. } else {
  1038. throw new moodle_exception('cannotcreatetoken', 'webservice', '', $service->shortname);
  1039. }
  1040. }
  1041. return $token;
  1042. }
  1043. /**
  1044. * Set the last time a token was sent and trigger the \core\event\webservice_token_sent event.
  1045. *
  1046. * This function is used when a token is generated by the user via login/token.php or admin/tool/mobile/launch.php.
  1047. * In order to protect the privatetoken, we remove it from the event params.
  1048. *
  1049. * @param stdClass $token token object
  1050. * @since Moodle 3.2
  1051. */
  1052. function external_log_token_request($token) {
  1053. global $DB;
  1054. $token->privatetoken = null;
  1055. // Log token access.
  1056. $DB->set_field('external_tokens', 'lastaccess', time(), array('id' => $token->id));
  1057. $params = array(
  1058. 'objectid' => $token->id,
  1059. );
  1060. $event = \core\event\webservice_token_sent::create($params);
  1061. $event->add_record_snapshot('external_tokens', $token);
  1062. $event->trigger();
  1063. }
  1064. /**
  1065. * Singleton to handle the external settings.
  1066. *
  1067. * We use singleton to encapsulate the "logic"
  1068. *
  1069. * @package core_webservice
  1070. * @copyright 2012 Jerome Mouneyrac
  1071. * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  1072. * @since Moodle 2.3
  1073. */
  1074. class external_settings {
  1075. /** @var object the singleton instance */
  1076. public static $instance = null;
  1077. /** @var boolean Should the external function return raw text or formatted */
  1078. private $raw = false;
  1079. /** @var boolean Should the external function filter the text */
  1080. private $filter = false;
  1081. /** @var boolean Should the external function rewrite plugin file url */
  1082. private $fileurl = true;
  1083. /** @var string In which file should the urls be rewritten */
  1084. private $file = 'webservice/pluginfile.php';
  1085. /** @var string The session lang */
  1086. private $lang = '';
  1087. /**
  1088. * Constructor - protected - can not be instanciated
  1089. */
  1090. protected function __construct()

Large files files are truncated, but you can click here to view the full file