PageRenderTime 45ms CodeModel.GetById 15ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/zend/Zend/Rest/Server.php

https://bitbucket.org/kudutest1/moodlegit
PHP | 616 lines | 356 code | 67 blank | 193 comment | 64 complexity | 47c64ed0f77df61830d67e4e2698d13b MD5 | raw file
  1. <?php
  2. /**
  3. * Zend Framework
  4. *
  5. * LICENSE
  6. *
  7. * This source file is subject to the new BSD license that is bundled
  8. * with this package in the file LICENSE.txt.
  9. * It is also available through the world-wide-web at this URL:
  10. * http://framework.zend.com/license/new-bsd
  11. * If you did not receive a copy of the license and are unable to
  12. * obtain it through the world-wide-web, please send an email
  13. * to license@zend.com so we can send you a copy immediately.
  14. *
  15. * @category Zend
  16. * @package Zend_Rest
  17. * @subpackage Server
  18. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  19. * @license http://framework.zend.com/license/new-bsd New BSD License
  20. * @version $Id$
  21. */
  22. /**
  23. * @see Zend_Server_Interface
  24. */
  25. require_once 'Zend/Server/Interface.php';
  26. /**
  27. * @see Zend_Server_Reflection
  28. */
  29. require_once 'Zend/Server/Reflection.php';
  30. /**
  31. * @see Zend_Server_Abstract
  32. */
  33. require_once 'Zend/Server/Abstract.php';
  34. /**
  35. * @category Zend
  36. * @package Zend_Rest
  37. * @subpackage Server
  38. * @copyright Copyright (c) 2005-2010 Zend Technologies USA Inc. (http://www.zend.com)
  39. * @license http://framework.zend.com/license/new-bsd New BSD License
  40. */
  41. class Zend_Rest_Server implements Zend_Server_Interface
  42. {
  43. /**
  44. * Class Constructor Args
  45. * @var array
  46. */
  47. protected $_args = array();
  48. /**
  49. * @var string Encoding
  50. */
  51. protected $_encoding = 'UTF-8';
  52. /**
  53. * @var array An array of Zend_Server_Reflect_Method
  54. */
  55. protected $_functions = array();
  56. /**
  57. * @var array Array of headers to send
  58. */
  59. protected $_headers = array();
  60. /**
  61. * @var array PHP's Magic Methods, these are ignored
  62. */
  63. protected static $magicMethods = array(
  64. '__construct',
  65. '__destruct',
  66. '__get',
  67. '__set',
  68. '__call',
  69. '__sleep',
  70. '__wakeup',
  71. '__isset',
  72. '__unset',
  73. '__tostring',
  74. '__clone',
  75. '__set_state',
  76. );
  77. /**
  78. * @var string Current Method
  79. */
  80. protected $_method;
  81. /**
  82. * @var Zend_Server_Reflection
  83. */
  84. protected $_reflection = null;
  85. /**
  86. * Whether or not {@link handle()} should send output or return the response.
  87. * @var boolean Defaults to false
  88. */
  89. protected $_returnResponse = false;
  90. /**
  91. * Constructor
  92. */
  93. public function __construct()
  94. {
  95. set_exception_handler(array($this, "fault"));
  96. $this->_reflection = new Zend_Server_Reflection();
  97. }
  98. /**
  99. * Set XML encoding
  100. *
  101. * @param string $encoding
  102. * @return Zend_Rest_Server
  103. */
  104. public function setEncoding($encoding)
  105. {
  106. $this->_encoding = (string) $encoding;
  107. return $this;
  108. }
  109. /**
  110. * Get XML encoding
  111. *
  112. * @return string
  113. */
  114. public function getEncoding()
  115. {
  116. return $this->_encoding;
  117. }
  118. /**
  119. * Lowercase a string
  120. *
  121. * Lowercase's a string by reference
  122. *
  123. * @param string $value
  124. * @param string $key
  125. * @return string Lower cased string
  126. */
  127. public static function lowerCase(&$value, &$key)
  128. {
  129. return $value = strtolower($value);
  130. }
  131. /**
  132. * Whether or not to return a response
  133. *
  134. * If called without arguments, returns the value of the flag. If called
  135. * with an argument, sets the flag.
  136. *
  137. * When 'return response' is true, {@link handle()} will not send output,
  138. * but will instead return the response from the dispatched function/method.
  139. *
  140. * @param boolean $flag
  141. * @return boolean|Zend_Rest_Server Returns Zend_Rest_Server when used to set the flag; returns boolean flag value otherwise.
  142. */
  143. public function returnResponse($flag = null)
  144. {
  145. if (null === $flag) {
  146. return $this->_returnResponse;
  147. }
  148. $this->_returnResponse = ($flag) ? true : false;
  149. return $this;
  150. }
  151. /**
  152. * Implement Zend_Server_Interface::handle()
  153. *
  154. * @param array $request
  155. * @throws Zend_Rest_Server_Exception
  156. * @return string|void
  157. */
  158. public function handle($request = false)
  159. {
  160. $this->_headers = array('Content-Type: text/xml');
  161. if (!$request) {
  162. $request = $_REQUEST;
  163. }
  164. if (isset($request['method'])) {
  165. $this->_method = $request['method'];
  166. if (isset($this->_functions[$this->_method])) {
  167. if ($this->_functions[$this->_method] instanceof Zend_Server_Reflection_Function || $this->_functions[$this->_method] instanceof Zend_Server_Reflection_Method && $this->_functions[$this->_method]->isPublic()) {
  168. $request_keys = array_keys($request);
  169. array_walk($request_keys, array(__CLASS__, "lowerCase"));
  170. $request = array_combine($request_keys, $request);
  171. $func_args = $this->_functions[$this->_method]->getParameters();
  172. $calling_args = array();
  173. $missing_args = array();
  174. foreach ($func_args as $arg) {
  175. if (isset($request[strtolower($arg->getName())])) {
  176. $calling_args[] = $request[strtolower($arg->getName())];
  177. } elseif ($arg->isOptional()) {
  178. $calling_args[] = $arg->getDefaultValue();
  179. } else {
  180. $missing_args[] = $arg->getName();
  181. }
  182. }
  183. foreach ($request as $key => $value) {
  184. if (substr($key, 0, 3) == 'arg') {
  185. $key = str_replace('arg', '', $key);
  186. $calling_args[$key] = $value;
  187. if (($index = array_search($key, $missing_args)) !== false) {
  188. unset($missing_args[$index]);
  189. }
  190. }
  191. }
  192. // Sort arguments by key -- @see ZF-2279
  193. ksort($calling_args);
  194. $result = false;
  195. if (count($calling_args) < count($func_args)) {
  196. require_once 'Zend/Rest/Server/Exception.php';
  197. $result = $this->fault(new Zend_Rest_Server_Exception('Invalid Method Call to ' . $this->_method . '. Missing argument(s): ' . implode(', ', $missing_args) . '.'), 400);
  198. }
  199. if (!$result && $this->_functions[$this->_method] instanceof Zend_Server_Reflection_Method) {
  200. // Get class
  201. $class = $this->_functions[$this->_method]->getDeclaringClass()->getName();
  202. if ($this->_functions[$this->_method]->isStatic()) {
  203. // for some reason, invokeArgs() does not work the same as
  204. // invoke(), and expects the first argument to be an object.
  205. // So, using a callback if the method is static.
  206. $result = $this->_callStaticMethod($class, $calling_args);
  207. } else {
  208. // Object method
  209. $result = $this->_callObjectMethod($class, $calling_args);
  210. }
  211. } elseif (!$result) {
  212. try {
  213. $result = call_user_func_array($this->_functions[$this->_method]->getName(), $calling_args); //$this->_functions[$this->_method]->invokeArgs($calling_args);
  214. } catch (Exception $e) {
  215. $result = $this->fault($e);
  216. }
  217. }
  218. } else {
  219. require_once "Zend/Rest/Server/Exception.php";
  220. $result = $this->fault(
  221. new Zend_Rest_Server_Exception("Unknown Method '$this->_method'."),
  222. 404
  223. );
  224. }
  225. } else {
  226. require_once "Zend/Rest/Server/Exception.php";
  227. $result = $this->fault(
  228. new Zend_Rest_Server_Exception("Unknown Method '$this->_method'."),
  229. 404
  230. );
  231. }
  232. } else {
  233. require_once "Zend/Rest/Server/Exception.php";
  234. $result = $this->fault(
  235. new Zend_Rest_Server_Exception("No Method Specified."),
  236. 404
  237. );
  238. }
  239. if ($result instanceof SimpleXMLElement) {
  240. $response = $result->asXML();
  241. } elseif ($result instanceof DOMDocument) {
  242. $response = $result->saveXML();
  243. } elseif ($result instanceof DOMNode) {
  244. $response = $result->ownerDocument->saveXML($result);
  245. } elseif (is_array($result) || is_object($result)) {
  246. $response = $this->_handleStruct($result);
  247. } else {
  248. $response = $this->_handleScalar($result);
  249. }
  250. if (!$this->returnResponse()) {
  251. if (!headers_sent()) {
  252. foreach ($this->_headers as $header) {
  253. header($header);
  254. }
  255. }
  256. echo $response;
  257. return;
  258. }
  259. return $response;
  260. }
  261. /**
  262. * Implement Zend_Server_Interface::setClass()
  263. *
  264. * @param string $classname Class name
  265. * @param string $namespace Class namespace (unused)
  266. * @param array $argv An array of Constructor Arguments
  267. */
  268. public function setClass($classname, $namespace = '', $argv = array())
  269. {
  270. $this->_args = $argv;
  271. foreach ($this->_reflection->reflectClass($classname, $argv)->getMethods() as $method) {
  272. $this->_functions[$method->getName()] = $method;
  273. }
  274. }
  275. /**
  276. * Handle an array or object result
  277. *
  278. * @param array|object $struct Result Value
  279. * @return string XML Response
  280. */
  281. protected function _handleStruct($struct)
  282. {
  283. $function = $this->_functions[$this->_method];
  284. if ($function instanceof Zend_Server_Reflection_Method) {
  285. $class = $function->getDeclaringClass()->getName();
  286. } else {
  287. $class = false;
  288. }
  289. $method = $function->getName();
  290. $dom = new DOMDocument('1.0', $this->getEncoding());
  291. if ($class) {
  292. $root = $dom->createElement($class);
  293. $method = $dom->createElement($method);
  294. $root->appendChild($method);
  295. } else {
  296. $root = $dom->createElement($method);
  297. $method = $root;
  298. }
  299. $root->setAttribute('generator', 'zend');
  300. $root->setAttribute('version', '1.0');
  301. $dom->appendChild($root);
  302. $this->_structValue($struct, $dom, $method);
  303. $struct = (array) $struct;
  304. if (!isset($struct['status'])) {
  305. $status = $dom->createElement('status', 'success');
  306. $method->appendChild($status);
  307. }
  308. return $dom->saveXML();
  309. }
  310. /**
  311. * Recursively iterate through a struct
  312. *
  313. * Recursively iterates through an associative array or object's properties
  314. * to build XML response.
  315. *
  316. * @param mixed $struct
  317. * @param DOMDocument $dom
  318. * @param DOMElement $parent
  319. * @return void
  320. */
  321. protected function _structValue($struct, DOMDocument $dom, DOMElement $parent)
  322. {
  323. $struct = (array) $struct;
  324. foreach ($struct as $key => $value) {
  325. if ($value === false) {
  326. $value = 0;
  327. } elseif ($value === true) {
  328. $value = 1;
  329. }
  330. if (ctype_digit((string) $key)) {
  331. $key = 'key_' . $key;
  332. }
  333. if (is_array($value) || is_object($value)) {
  334. $element = $dom->createElement($key);
  335. $this->_structValue($value, $dom, $element);
  336. } else {
  337. $element = $dom->createElement($key);
  338. $element->appendChild($dom->createTextNode($value));
  339. }
  340. $parent->appendChild($element);
  341. }
  342. }
  343. /**
  344. * Handle a single value
  345. *
  346. * @param string|int|boolean $value Result value
  347. * @return string XML Response
  348. */
  349. protected function _handleScalar($value)
  350. {
  351. $function = $this->_functions[$this->_method];
  352. if ($function instanceof Zend_Server_Reflection_Method) {
  353. $class = $function->getDeclaringClass()->getName();
  354. } else {
  355. $class = false;
  356. }
  357. $method = $function->getName();
  358. $dom = new DOMDocument('1.0', $this->getEncoding());
  359. if ($class) {
  360. $xml = $dom->createElement($class);
  361. $methodNode = $dom->createElement($method);
  362. $xml->appendChild($methodNode);
  363. } else {
  364. $xml = $dom->createElement($method);
  365. $methodNode = $xml;
  366. }
  367. $xml->setAttribute('generator', 'zend');
  368. $xml->setAttribute('version', '1.0');
  369. $dom->appendChild($xml);
  370. if ($value === false) {
  371. $value = 0;
  372. } elseif ($value === true) {
  373. $value = 1;
  374. }
  375. if (isset($value)) {
  376. $element = $dom->createElement('response');
  377. $element->appendChild($dom->createTextNode($value));
  378. $methodNode->appendChild($element);
  379. } else {
  380. $methodNode->appendChild($dom->createElement('response'));
  381. }
  382. $methodNode->appendChild($dom->createElement('status', 'success'));
  383. return $dom->saveXML();
  384. }
  385. /**
  386. * Implement Zend_Server_Interface::fault()
  387. *
  388. * Creates XML error response, returning DOMDocument with response.
  389. *
  390. * @param string|Exception $fault Message
  391. * @param int $code Error Code
  392. * @return DOMDocument
  393. */
  394. public function fault($exception = null, $code = null)
  395. {
  396. if (isset($this->_functions[$this->_method])) {
  397. $function = $this->_functions[$this->_method];
  398. } elseif (isset($this->_method)) {
  399. $function = $this->_method;
  400. } else {
  401. $function = 'rest';
  402. }
  403. if ($function instanceof Zend_Server_Reflection_Method) {
  404. $class = $function->getDeclaringClass()->getName();
  405. } else {
  406. $class = false;
  407. }
  408. if ($function instanceof Zend_Server_Reflection_Function_Abstract) {
  409. $method = $function->getName();
  410. } else {
  411. $method = $function;
  412. }
  413. $dom = new DOMDocument('1.0', $this->getEncoding());
  414. if ($class) {
  415. $xml = $dom->createElement($class);
  416. $xmlMethod = $dom->createElement($method);
  417. $xml->appendChild($xmlMethod);
  418. } else {
  419. $xml = $dom->createElement($method);
  420. $xmlMethod = $xml;
  421. }
  422. $xml->setAttribute('generator', 'zend');
  423. $xml->setAttribute('version', '1.0');
  424. $dom->appendChild($xml);
  425. $xmlResponse = $dom->createElement('response');
  426. $xmlMethod->appendChild($xmlResponse);
  427. if ($exception instanceof Exception) {
  428. $element = $dom->createElement('message');
  429. $element->appendChild($dom->createTextNode($exception->getMessage()));
  430. $xmlResponse->appendChild($element);
  431. $code = $exception->getCode();
  432. } elseif (($exception !== null) || 'rest' == $function) {
  433. $xmlResponse->appendChild($dom->createElement('message', 'An unknown error occured. Please try again.'));
  434. } else {
  435. $xmlResponse->appendChild($dom->createElement('message', 'Call to ' . $method . ' failed.'));
  436. }
  437. $xmlMethod->appendChild($xmlResponse);
  438. $xmlMethod->appendChild($dom->createElement('status', 'failed'));
  439. // Headers to send
  440. if ($code === null || (404 != $code)) {
  441. $this->_headers[] = 'HTTP/1.0 400 Bad Request';
  442. } else {
  443. $this->_headers[] = 'HTTP/1.0 404 File Not Found';
  444. }
  445. return $dom;
  446. }
  447. /**
  448. * Retrieve any HTTP extra headers set by the server
  449. *
  450. * @return array
  451. */
  452. public function getHeaders()
  453. {
  454. return $this->_headers;
  455. }
  456. /**
  457. * Implement Zend_Server_Interface::addFunction()
  458. *
  459. * @param string $function Function Name
  460. * @param string $namespace Function namespace (unused)
  461. */
  462. public function addFunction($function, $namespace = '')
  463. {
  464. if (!is_array($function)) {
  465. $function = (array) $function;
  466. }
  467. foreach ($function as $func) {
  468. if (is_callable($func) && !in_array($func, self::$magicMethods)) {
  469. $this->_functions[$func] = $this->_reflection->reflectFunction($func);
  470. } else {
  471. require_once 'Zend/Rest/Server/Exception.php';
  472. throw new Zend_Rest_Server_Exception("Invalid Method Added to Service.");
  473. }
  474. }
  475. }
  476. /**
  477. * Implement Zend_Server_Interface::getFunctions()
  478. *
  479. * @return array An array of Zend_Server_Reflection_Method's
  480. */
  481. public function getFunctions()
  482. {
  483. return $this->_functions;
  484. }
  485. /**
  486. * Implement Zend_Server_Interface::loadFunctions()
  487. *
  488. * @todo Implement
  489. * @param array $functions
  490. */
  491. public function loadFunctions($functions)
  492. {
  493. }
  494. /**
  495. * Implement Zend_Server_Interface::setPersistence()
  496. *
  497. * @todo Implement
  498. * @param int $mode
  499. */
  500. public function setPersistence($mode)
  501. {
  502. }
  503. /**
  504. * Call a static class method and return the result
  505. *
  506. * @param string $class
  507. * @param array $args
  508. * @return mixed
  509. */
  510. protected function _callStaticMethod($class, array $args)
  511. {
  512. try {
  513. $result = call_user_func_array(array($class, $this->_functions[$this->_method]->getName()), $args);
  514. } catch (Exception $e) {
  515. $result = $this->fault($e);
  516. }
  517. return $result;
  518. }
  519. /**
  520. * Call an instance method of an object
  521. *
  522. * @param string $class
  523. * @param array $args
  524. * @return mixed
  525. * @throws Zend_Rest_Server_Exception For invalid class name
  526. */
  527. protected function _callObjectMethod($class, array $args)
  528. {
  529. try {
  530. if ($this->_functions[$this->_method]->getDeclaringClass()->getConstructor()) {
  531. $object = $this->_functions[$this->_method]->getDeclaringClass()->newInstanceArgs($this->_args);
  532. } else {
  533. $object = $this->_functions[$this->_method]->getDeclaringClass()->newInstance();
  534. }
  535. } catch (Exception $e) {
  536. require_once 'Zend/Rest/Server/Exception.php';
  537. throw new Zend_Rest_Server_Exception('Error instantiating class ' . $class .
  538. ' to invoke method ' . $this->_functions[$this->_method]->getName() .
  539. ' (' . $e->getMessage() . ') ',
  540. 500, $e);
  541. }
  542. try {
  543. $result = $this->_functions[$this->_method]->invokeArgs($object, $args);
  544. } catch (Exception $e) {
  545. $result = $this->fault($e);
  546. }
  547. return $result;
  548. }
  549. }