PageRenderTime 54ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 0ms

/mod/web_services/lib/web_services.php

https://github.com/fragilbert/Elgg
PHP | 744 lines | 514 code | 69 blank | 161 comment | 60 complexity | 3e02ff7418e4db7d229cb3d0d6d63b2a MD5 | raw file
Possible License(s): MIT, BSD-3-Clause, LGPL-2.1, GPL-2.0
  1. <?php
  2. /**
  3. * Elgg web services API library
  4. * Functions and objects for exposing custom web services.
  5. *
  6. */
  7. /**
  8. * Check that the method call has the proper API and user authentication
  9. *
  10. * @param string $method The api name that was exposed
  11. *
  12. * @return true or throws an exception
  13. * @throws APIException
  14. * @since 1.7.0
  15. * @access private
  16. */
  17. function authenticate_method($method) {
  18. global $API_METHODS;
  19. // method must be exposed
  20. if (!isset($API_METHODS[$method])) {
  21. throw new APIException(elgg_echo('APIException:MethodCallNotImplemented', array($method)));
  22. }
  23. // check API authentication if required
  24. if ($API_METHODS[$method]["require_api_auth"] == true) {
  25. $api_pam = new ElggPAM('api');
  26. if ($api_pam->authenticate() !== true) {
  27. throw new APIException(elgg_echo('APIException:APIAuthenticationFailed'));
  28. }
  29. }
  30. $user_pam = new ElggPAM('user');
  31. $user_auth_result = $user_pam->authenticate(array());
  32. // check if user authentication is required
  33. if ($API_METHODS[$method]["require_user_auth"] == true) {
  34. if ($user_auth_result == false) {
  35. throw new APIException($user_pam->getFailureMessage(), ErrorResult::$RESULT_FAIL_AUTHTOKEN);
  36. }
  37. }
  38. return true;
  39. }
  40. /**
  41. * Executes a method.
  42. * A method is a function which you have previously exposed using expose_function.
  43. *
  44. * @param string $method Method, e.g. "foo.bar"
  45. *
  46. * @return GenericResult The result of the execution.
  47. * @throws APIException|CallException
  48. * @access private
  49. */
  50. function execute_method($method) {
  51. global $API_METHODS;
  52. // method must be exposed
  53. if (!isset($API_METHODS[$method])) {
  54. $msg = elgg_echo('APIException:MethodCallNotImplemented', array($method));
  55. throw new APIException($msg);
  56. }
  57. // function must be callable
  58. $function = null;
  59. if (isset($API_METHODS[$method]["function"])) {
  60. $function = $API_METHODS[$method]["function"];
  61. // allow array version of static callback
  62. if (is_array($function)
  63. && isset($function[0], $function[1])
  64. && is_string($function[0])
  65. && is_string($function[1])) {
  66. $function = "{$function[0]}::{$function[1]}";
  67. }
  68. }
  69. if (!is_string($function) || !is_callable($function)) {
  70. $msg = elgg_echo('APIException:FunctionDoesNotExist', array($method));
  71. throw new APIException($msg);
  72. }
  73. // check http call method
  74. if (strcmp(get_call_method(), $API_METHODS[$method]["call_method"]) != 0) {
  75. $msg = elgg_echo('CallException:InvalidCallMethod', array($method,
  76. $API_METHODS[$method]["call_method"]));
  77. throw new CallException($msg);
  78. }
  79. $parameters = get_parameters_for_method($method);
  80. // may throw exception, which is not caught here
  81. verify_parameters($method, $parameters);
  82. $serialised_parameters = serialise_parameters($method, $parameters);
  83. // Execute function: Construct function and calling parameters
  84. $serialised_parameters = trim($serialised_parameters, ", ");
  85. // @todo remove the need for eval()
  86. $result = eval("return $function($serialised_parameters);");
  87. // Sanity check result
  88. // If this function returns an api result itself, just return it
  89. if ($result instanceof GenericResult) {
  90. return $result;
  91. }
  92. if ($result === false) {
  93. $msg = elgg_echo('APIException:FunctionParseError', array($function, $serialised_parameters));
  94. throw new APIException($msg);
  95. }
  96. if ($result === NULL) {
  97. // If no value
  98. $msg = elgg_echo('APIException:FunctionNoReturn', array($function, $serialised_parameters));
  99. throw new APIException($msg);
  100. }
  101. // Otherwise assume that the call was successful and return it as a success object.
  102. return SuccessResult::getInstance($result);
  103. }
  104. /**
  105. * Get the request method.
  106. *
  107. * @return string HTTP request method
  108. * @access private
  109. */
  110. function get_call_method() {
  111. return $_SERVER['REQUEST_METHOD'];
  112. }
  113. /**
  114. * This function analyses all expected parameters for a given method
  115. *
  116. * This function sanitizes the input parameters and returns them in
  117. * an associated array.
  118. *
  119. * @param string $method The method
  120. *
  121. * @return array containing parameters as key => value
  122. * @access private
  123. */
  124. function get_parameters_for_method($method) {
  125. global $API_METHODS;
  126. $sanitised = array();
  127. // if there are parameters, sanitize them
  128. if (isset($API_METHODS[$method]['parameters'])) {
  129. foreach ($API_METHODS[$method]['parameters'] as $k => $v) {
  130. $param = get_input($k); // Make things go through the sanitiser
  131. if ($param !== '' && $param !== null) {
  132. $sanitised[$k] = $param;
  133. } else {
  134. // parameter wasn't passed so check for default
  135. if (isset($v['default'])) {
  136. $sanitised[$k] = $v['default'];
  137. }
  138. }
  139. }
  140. }
  141. return $sanitised;
  142. }
  143. /**
  144. * Get POST data
  145. * Since this is called through a handler, we need to manually get the post data
  146. *
  147. * @return POST data as string encoded as multipart/form-data
  148. * @access private
  149. */
  150. function get_post_data() {
  151. $postdata = file_get_contents('php://input');
  152. return $postdata;
  153. }
  154. /**
  155. * Verify that the required parameters are present
  156. *
  157. * @param string $method Method name
  158. * @param array $parameters List of expected parameters
  159. *
  160. * @return true on success or exception
  161. * @throws APIException
  162. * @since 1.7.0
  163. * @access private
  164. */
  165. function verify_parameters($method, $parameters) {
  166. global $API_METHODS;
  167. // are there any parameters for this method
  168. if (!(isset($API_METHODS[$method]["parameters"]))) {
  169. return true; // no so return
  170. }
  171. // check that the parameters were registered correctly and all required ones are there
  172. foreach ($API_METHODS[$method]['parameters'] as $key => $value) {
  173. // this tests the expose structure: must be array to describe parameter and type must be defined
  174. if (!is_array($value) || !isset($value['type'])) {
  175. $msg = elgg_echo('APIException:InvalidParameter', array($key, $method));
  176. throw new APIException($msg);
  177. }
  178. // Check that the variable is present in the request if required
  179. if ($value['required'] && !array_key_exists($key, $parameters)) {
  180. $msg = elgg_echo('APIException:MissingParameterInMethod', array($key, $method));
  181. throw new APIException($msg);
  182. }
  183. }
  184. return true;
  185. }
  186. /**
  187. * Serialize an array of parameters for an API method call
  188. *
  189. * @param string $method API method name
  190. * @param array $parameters Array of parameters
  191. *
  192. * @return string or exception
  193. * @throws APIException
  194. * @since 1.7.0
  195. * @access private
  196. */
  197. function serialise_parameters($method, $parameters) {
  198. global $API_METHODS;
  199. // are there any parameters for this method
  200. if (!(isset($API_METHODS[$method]["parameters"]))) {
  201. return ''; // if not, return
  202. }
  203. $serialised_parameters = "";
  204. foreach ($API_METHODS[$method]['parameters'] as $key => $value) {
  205. // avoid warning on parameters that are not required and not present
  206. if (!isset($parameters[$key])) {
  207. continue;
  208. }
  209. // Set variables casting to type.
  210. switch (strtolower($value['type']))
  211. {
  212. case 'int':
  213. case 'integer' :
  214. $serialised_parameters .= "," . (int)trim($parameters[$key]);
  215. break;
  216. case 'bool':
  217. case 'boolean':
  218. // change word false to boolean false
  219. if (strcasecmp(trim($parameters[$key]), "false") == 0) {
  220. $serialised_parameters .= ',false';
  221. } else if ($parameters[$key] == 0) {
  222. $serialised_parameters .= ',false';
  223. } else {
  224. $serialised_parameters .= ',true';
  225. }
  226. break;
  227. case 'string':
  228. $serialised_parameters .= ",'" . addcslashes(trim($parameters[$key]), "'") . "'";
  229. break;
  230. case 'float':
  231. $serialised_parameters .= "," . (float)trim($parameters[$key]);
  232. break;
  233. case 'array':
  234. // we can handle an array of strings, maybe ints, definitely not booleans or other arrays
  235. if (!is_array($parameters[$key])) {
  236. $msg = elgg_echo('APIException:ParameterNotArray', array($key));
  237. throw new APIException($msg);
  238. }
  239. $array = "array(";
  240. foreach ($parameters[$key] as $k => $v) {
  241. $k = sanitise_string($k);
  242. $v = sanitise_string($v);
  243. $array .= "'$k'=>'$v',";
  244. }
  245. $array = trim($array, ",");
  246. $array .= ")";
  247. $array = ",$array";
  248. $serialised_parameters .= $array;
  249. break;
  250. default:
  251. $msg = elgg_echo('APIException:UnrecognisedTypeCast', array($value['type'], $key, $method));
  252. throw new APIException($msg);
  253. }
  254. }
  255. return $serialised_parameters;
  256. }
  257. // API authorization handlers /////////////////////////////////////////////////////////////////////
  258. /**
  259. * PAM: Confirm that the call includes a valid API key
  260. *
  261. * @return true if good API key - otherwise throws exception
  262. *
  263. * @return mixed
  264. * @throws APIException
  265. * @since 1.7.0
  266. * @access private
  267. */
  268. function api_auth_key() {
  269. global $CONFIG;
  270. // check that an API key is present
  271. $api_key = get_input('api_key');
  272. if ($api_key == "") {
  273. throw new APIException(elgg_echo('APIException:MissingAPIKey'));
  274. }
  275. // check that it is active
  276. $api_user = get_api_user($CONFIG->site_id, $api_key);
  277. if (!$api_user) {
  278. // key is not active or does not exist
  279. throw new APIException(elgg_echo('APIException:BadAPIKey'));
  280. }
  281. // can be used for keeping stats
  282. // plugin can also return false to fail this authentication method
  283. return elgg_trigger_plugin_hook('api_key', 'use', $api_key, true);
  284. }
  285. /**
  286. * PAM: Confirm the HMAC signature
  287. *
  288. * @return true if success - otherwise throws exception
  289. *
  290. * @throws SecurityException
  291. * @since 1.7.0
  292. * @access private
  293. */
  294. function api_auth_hmac() {
  295. global $CONFIG;
  296. // Get api header
  297. $api_header = get_and_validate_api_headers();
  298. // Pull API user details
  299. $api_user = get_api_user($CONFIG->site_id, $api_header->api_key);
  300. if (!$api_user) {
  301. throw new SecurityException(elgg_echo('SecurityException:InvalidAPIKey'),
  302. ErrorResult::$RESULT_FAIL_APIKEY_INVALID);
  303. }
  304. // Get the secret key
  305. $secret_key = $api_user->secret;
  306. // get the query string
  307. $query = substr($_SERVER['REQUEST_URI'], strpos($_SERVER['REQUEST_URI'], '?') + 1);
  308. // calculate expected HMAC
  309. $hmac = calculate_hmac( $api_header->hmac_algo,
  310. $api_header->time,
  311. $api_header->nonce,
  312. $api_header->api_key,
  313. $secret_key,
  314. $query,
  315. $api_header->method == 'POST' ? $api_header->posthash : "");
  316. if ($api_header->hmac !== $hmac) {
  317. throw new SecurityException("HMAC is invalid. {$api_header->hmac} != [calc]$hmac");
  318. }
  319. // Now make sure this is not a replay
  320. if (cache_hmac_check_replay($hmac)) {
  321. throw new SecurityException(elgg_echo('SecurityException:DupePacket'));
  322. }
  323. // Validate post data
  324. if ($api_header->method == "POST") {
  325. $postdata = get_post_data();
  326. $calculated_posthash = calculate_posthash($postdata, $api_header->posthash_algo);
  327. if (strcmp($api_header->posthash, $calculated_posthash) != 0) {
  328. $msg = elgg_echo('SecurityException:InvalidPostHash',
  329. array($calculated_posthash, $api_header->posthash));
  330. throw new SecurityException($msg);
  331. }
  332. }
  333. return true;
  334. }
  335. // HMAC /////////////////////////////////////////////////////////////////////
  336. /**
  337. * This function looks at the super-global variable $_SERVER and extracts the various
  338. * header variables needed for the HMAC PAM
  339. *
  340. * @return stdClass Containing all the values.
  341. * @throws APIException Detailing any error.
  342. * @access private
  343. */
  344. function get_and_validate_api_headers() {
  345. $result = new stdClass;
  346. $result->method = get_call_method();
  347. // Only allow these methods
  348. if (($result->method != "GET") && ($result->method != "POST")) {
  349. throw new APIException(elgg_echo('APIException:NotGetOrPost'));
  350. }
  351. $result->api_key = $_SERVER['HTTP_X_ELGG_APIKEY'];
  352. if ($result->api_key == "") {
  353. throw new APIException(elgg_echo('APIException:MissingAPIKey'));
  354. }
  355. $result->hmac = $_SERVER['HTTP_X_ELGG_HMAC'];
  356. if ($result->hmac == "") {
  357. throw new APIException(elgg_echo('APIException:MissingHmac'));
  358. }
  359. $result->hmac_algo = $_SERVER['HTTP_X_ELGG_HMAC_ALGO'];
  360. if ($result->hmac_algo == "") {
  361. throw new APIException(elgg_echo('APIException:MissingHmacAlgo'));
  362. }
  363. $result->time = $_SERVER['HTTP_X_ELGG_TIME'];
  364. if ($result->time == "") {
  365. throw new APIException(elgg_echo('APIException:MissingTime'));
  366. }
  367. // Must have been sent within 25 hour period.
  368. // 25 hours is more than enough to handle server clock drift.
  369. // This values determines how long the HMAC cache needs to store previous
  370. // signatures. Heavy use of HMAC is better handled with a shorter sig lifetime.
  371. // See cache_hmac_check_replay()
  372. if (($result->time < (time() - 90000)) || ($result->time > (time() + 90000))) {
  373. throw new APIException(elgg_echo('APIException:TemporalDrift'));
  374. }
  375. $result->nonce = $_SERVER['HTTP_X_ELGG_NONCE'];
  376. if ($result->nonce == "") {
  377. throw new APIException(elgg_echo('APIException:MissingNonce'));
  378. }
  379. if ($result->method == "POST") {
  380. $result->posthash = $_SERVER['HTTP_X_ELGG_POSTHASH'];
  381. if ($result->posthash == "") {
  382. throw new APIException(elgg_echo('APIException:MissingPOSTHash'));
  383. }
  384. $result->posthash_algo = $_SERVER['HTTP_X_ELGG_POSTHASH_ALGO'];
  385. if ($result->posthash_algo == "") {
  386. throw new APIException(elgg_echo('APIException:MissingPOSTAlgo'));
  387. }
  388. $result->content_type = $_SERVER['CONTENT_TYPE'];
  389. if ($result->content_type == "") {
  390. throw new APIException(elgg_echo('APIException:MissingContentType'));
  391. }
  392. }
  393. return $result;
  394. }
  395. /**
  396. * Map various algorithms to their PHP equivs.
  397. * This also gives us an easy way to disable algorithms.
  398. *
  399. * @param string $algo The algorithm
  400. *
  401. * @return string The php algorithm
  402. * @throws APIException if an algorithm is not supported.
  403. * @access private
  404. */
  405. function map_api_hash($algo) {
  406. $algo = strtolower(sanitise_string($algo));
  407. $supported_algos = array(
  408. "md5" => "md5", // @todo Consider phasing this out
  409. "sha" => "sha1", // alias for sha1
  410. "sha1" => "sha1",
  411. "sha256" => "sha256"
  412. );
  413. if (array_key_exists($algo, $supported_algos)) {
  414. return $supported_algos[$algo];
  415. }
  416. throw new APIException(elgg_echo('APIException:AlgorithmNotSupported', array($algo)));
  417. }
  418. /**
  419. * Calculate the HMAC for the http request.
  420. * This function signs an api request using the information provided. The signature returned
  421. * has been base64 encoded and then url encoded.
  422. *
  423. * @param string $algo The HMAC algorithm used
  424. * @param string $time String representation of unix time
  425. * @param string $nonce Nonce
  426. * @param string $api_key Your api key
  427. * @param string $secret_key Your private key
  428. * @param string $get_variables URLEncoded string representation of the get variable parameters,
  429. * eg "method=user&guid=2"
  430. * @param string $post_hash Optional sha1 hash of the post data.
  431. *
  432. * @return string The HMAC signature
  433. * @access private
  434. */
  435. function calculate_hmac($algo, $time, $nonce, $api_key, $secret_key,
  436. $get_variables, $post_hash = "") {
  437. global $CONFIG;
  438. elgg_log("HMAC Parts: $algo, $time, $api_key, $secret_key, $get_variables, $post_hash");
  439. $ctx = hash_init(map_api_hash($algo), HASH_HMAC, $secret_key);
  440. hash_update($ctx, trim($time));
  441. hash_update($ctx, trim($nonce));
  442. hash_update($ctx, trim($api_key));
  443. hash_update($ctx, trim($get_variables));
  444. if (trim($post_hash) != "") {
  445. hash_update($ctx, trim($post_hash));
  446. }
  447. return urlencode(base64_encode(hash_final($ctx, true)));
  448. }
  449. /**
  450. * Calculate a hash for some post data.
  451. *
  452. * @todo Work out how to handle really large bits of data.
  453. *
  454. * @param string $postdata The post data.
  455. * @param string $algo The algorithm used.
  456. *
  457. * @return string The hash.
  458. * @access private
  459. */
  460. function calculate_posthash($postdata, $algo) {
  461. $ctx = hash_init(map_api_hash($algo));
  462. hash_update($ctx, $postdata);
  463. return hash_final($ctx);
  464. }
  465. /**
  466. * This function will do two things. Firstly it verifies that a HMAC signature
  467. * hasn't been seen before, and secondly it will add the given hmac to the cache.
  468. *
  469. * @param string $hmac The hmac string.
  470. *
  471. * @return bool True if replay detected, false if not.
  472. * @access private
  473. */
  474. function cache_hmac_check_replay($hmac) {
  475. // cache lifetime is 25 hours (this should be related to the time drift
  476. // allowed in get_and_validate_headers
  477. $cache = new ElggHMACCache(90000);
  478. if (!$cache->load($hmac)) {
  479. $cache->save($hmac, $hmac);
  480. return false;
  481. }
  482. return true;
  483. }
  484. /**
  485. * Check the user token
  486. * This examines whether an authentication token is present and returns true if
  487. * it is present and is valid. The user gets logged in so with the current
  488. * session code of Elgg, that user will be logged out of all other sessions.
  489. *
  490. * @return bool
  491. * @access private
  492. */
  493. function pam_auth_usertoken() {
  494. global $CONFIG;
  495. $token = get_input('auth_token');
  496. if (!$token) {
  497. return false;
  498. }
  499. $validated_userid = validate_user_token($token, $CONFIG->site_id);
  500. if ($validated_userid) {
  501. $u = get_entity($validated_userid);
  502. // Could we get the user?
  503. if (!$u) {
  504. return false;
  505. }
  506. // Not an elgg user
  507. if ((!$u instanceof ElggUser)) {
  508. return false;
  509. }
  510. // User is banned
  511. if ($u->isBanned()) {
  512. return false;
  513. }
  514. // Fail if we couldn't log the user in
  515. if (!login($u)) {
  516. return false;
  517. }
  518. return true;
  519. }
  520. return false;
  521. }
  522. /**
  523. * See if the user has a valid login sesson
  524. *
  525. * @return bool
  526. * @access private
  527. */
  528. function pam_auth_session() {
  529. return elgg_is_logged_in();
  530. }
  531. /**
  532. * API PHP Error handler function.
  533. * This function acts as a wrapper to catch and report PHP error messages.
  534. *
  535. * @see http://uk3.php.net/set-error-handler
  536. *
  537. * @param int $errno Error number
  538. * @param string $errmsg Human readable message
  539. * @param string $filename Filename
  540. * @param int $linenum Line number
  541. * @param array $vars Vars
  542. *
  543. * @return void
  544. * @access private
  545. *
  546. * @throws Exception
  547. */
  548. function _php_api_error_handler($errno, $errmsg, $filename, $linenum, $vars) {
  549. global $ERRORS;
  550. $error = date("Y-m-d H:i:s (T)") . ": \"" . $errmsg . "\" in file "
  551. . $filename . " (line " . $linenum . ")";
  552. switch ($errno) {
  553. case E_USER_ERROR:
  554. error_log("ERROR: " . $error);
  555. $ERRORS[] = "ERROR: " . $error;
  556. // Since this is a fatal error, we want to stop any further execution but do so gracefully.
  557. throw new Exception("ERROR: " . $error);
  558. break;
  559. case E_WARNING :
  560. case E_USER_WARNING :
  561. error_log("WARNING: " . $error);
  562. $ERRORS[] = "WARNING: " . $error;
  563. break;
  564. default:
  565. error_log("DEBUG: " . $error);
  566. $ERRORS[] = "DEBUG: " . $error;
  567. }
  568. }
  569. /**
  570. * API PHP Exception handler.
  571. * This is a generic exception handler for PHP exceptions. This will catch any
  572. * uncaught exception, end API execution and return the result to the requestor
  573. * as an ErrorResult in the requested format.
  574. *
  575. * @param Exception $exception Exception
  576. *
  577. * @return void
  578. * @access private
  579. */
  580. function _php_api_exception_handler($exception) {
  581. error_log("*** FATAL EXCEPTION (API) *** : " . $exception);
  582. $code = $exception->getCode() == 0 ? ErrorResult::$RESULT_FAIL : $exception->getCode();
  583. $result = new ErrorResult($exception->getMessage(), $code, NULL);
  584. echo elgg_view_page($exception->getMessage(), elgg_view("api/output", array("result" => $result)));
  585. }
  586. /**
  587. * Services handler - turns request over to the registered handler
  588. * If no handler is found, this returns a 404 error
  589. *
  590. * @param string $handler Handler name
  591. * @param array $request Request string
  592. *
  593. * @return void
  594. * @access private
  595. */
  596. function service_handler($handler, $request) {
  597. global $CONFIG;
  598. elgg_set_context('api');
  599. $request = explode('/', $request);
  600. // after the handler, the first identifier is response format
  601. // ex) http://example.org/services/api/rest/json/?method=test
  602. $response_format = array_shift($request);
  603. // Which view - xml, json, ...
  604. if ($response_format && elgg_is_registered_viewtype($response_format)) {
  605. elgg_set_viewtype($response_format);
  606. } else {
  607. // default to json
  608. elgg_set_viewtype("json");
  609. }
  610. if (!isset($CONFIG->servicehandler) || empty($handler)) {
  611. // no handlers set or bad url
  612. header("HTTP/1.0 404 Not Found");
  613. exit;
  614. } else if (isset($CONFIG->servicehandler[$handler]) && is_callable($CONFIG->servicehandler[$handler])) {
  615. $function = $CONFIG->servicehandler[$handler];
  616. call_user_func($function, $request, $handler);
  617. } else {
  618. // no handler for this web service
  619. header("HTTP/1.0 404 Not Found");
  620. exit;
  621. }
  622. }