Server.php 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  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-2009 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. * Zend_Server_Interface
  24. */
  25. require_once 'Zend/Server/Interface.php';
  26. /**
  27. * Zend_Server_Reflection
  28. */
  29. require_once 'Zend/Server/Reflection.php';
  30. /**
  31. * 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-2009 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. foreach ($func_args as $arg) {
  174. if (isset($request[strtolower($arg->getName())])) {
  175. $calling_args[] = $request[strtolower($arg->getName())];
  176. } elseif ($arg->isOptional()) {
  177. $calling_args[] = $arg->getDefaultValue();
  178. }
  179. }
  180. foreach ($request as $key => $value) {
  181. if (substr($key, 0, 3) == 'arg') {
  182. $key = str_replace('arg', '', $key);
  183. $calling_args[$key] = $value;
  184. }
  185. }
  186. // Sort arguments by key -- @see ZF-2279
  187. ksort($calling_args);
  188. $result = false;
  189. if (count($calling_args) < count($func_args)) {
  190. require_once 'Zend/Rest/Server/Exception.php';
  191. $result = $this->fault(new Zend_Rest_Server_Exception('Invalid Method Call to ' . $this->_method . '. Requires ' . count($func_args) . ', ' . count($calling_args) . ' given.'), 400);
  192. }
  193. if (!$result && $this->_functions[$this->_method] instanceof Zend_Server_Reflection_Method) {
  194. // Get class
  195. $class = $this->_functions[$this->_method]->getDeclaringClass()->getName();
  196. if ($this->_functions[$this->_method]->isStatic()) {
  197. // for some reason, invokeArgs() does not work the same as
  198. // invoke(), and expects the first argument to be an object.
  199. // So, using a callback if the method is static.
  200. $result = $this->_callStaticMethod($class, $calling_args);
  201. } else {
  202. // Object method
  203. $result = $this->_callObjectMethod($class, $calling_args);
  204. }
  205. } elseif (!$result) {
  206. try {
  207. $result = call_user_func_array($this->_functions[$this->_method]->getName(), $calling_args); //$this->_functions[$this->_method]->invokeArgs($calling_args);
  208. } catch (Exception $e) {
  209. $result = $this->fault($e);
  210. }
  211. }
  212. } else {
  213. require_once "Zend/Rest/Server/Exception.php";
  214. $result = $this->fault(
  215. new Zend_Rest_Server_Exception("Unknown Method '$this->_method'."),
  216. 404
  217. );
  218. }
  219. } else {
  220. require_once "Zend/Rest/Server/Exception.php";
  221. $result = $this->fault(
  222. new Zend_Rest_Server_Exception("Unknown Method '$this->_method'."),
  223. 404
  224. );
  225. }
  226. } else {
  227. require_once "Zend/Rest/Server/Exception.php";
  228. $result = $this->fault(
  229. new Zend_Rest_Server_Exception("No Method Specified."),
  230. 404
  231. );
  232. }
  233. if ($result instanceof SimpleXMLElement) {
  234. $response = $result->asXML();
  235. } elseif ($result instanceof DOMDocument) {
  236. $response = $result->saveXML();
  237. } elseif ($result instanceof DOMNode) {
  238. $response = $result->ownerDocument->saveXML($result);
  239. } elseif (is_array($result) || is_object($result)) {
  240. $response = $this->_handleStruct($result);
  241. } else {
  242. $response = $this->_handleScalar($result);
  243. }
  244. if (!$this->returnResponse()) {
  245. if (!headers_sent()) {
  246. foreach ($this->_headers as $header) {
  247. header($header);
  248. }
  249. }
  250. echo $response;
  251. return;
  252. }
  253. return $response;
  254. }
  255. /**
  256. * Implement Zend_Server_Interface::setClass()
  257. *
  258. * @param string $classname Class name
  259. * @param string $namespace Class namespace (unused)
  260. * @param array $argv An array of Constructor Arguments
  261. */
  262. public function setClass($classname, $namespace = '', $argv = array())
  263. {
  264. $this->_args = $argv;
  265. foreach ($this->_reflection->reflectClass($classname, $argv)->getMethods() as $method) {
  266. $this->_functions[$method->getName()] = $method;
  267. }
  268. }
  269. /**
  270. * Handle an array or object result
  271. *
  272. * @param array|object $struct Result Value
  273. * @return string XML Response
  274. */
  275. protected function _handleStruct($struct)
  276. {
  277. $function = $this->_functions[$this->_method];
  278. if ($function instanceof Zend_Server_Reflection_Method) {
  279. $class = $function->getDeclaringClass()->getName();
  280. } else {
  281. $class = false;
  282. }
  283. $method = $function->getName();
  284. $dom = new DOMDocument('1.0', $this->getEncoding());
  285. if ($class) {
  286. $root = $dom->createElement($class);
  287. $method = $dom->createElement($method);
  288. $root->appendChild($method);
  289. } else {
  290. $root = $dom->createElement($method);
  291. $method = $root;
  292. }
  293. $root->setAttribute('generator', 'zend');
  294. $root->setAttribute('version', '1.0');
  295. $dom->appendChild($root);
  296. $this->_structValue($struct, $dom, $method);
  297. $struct = (array) $struct;
  298. if (!isset($struct['status'])) {
  299. $status = $dom->createElement('status', 'success');
  300. $method->appendChild($status);
  301. }
  302. return $dom->saveXML();
  303. }
  304. /**
  305. * Recursively iterate through a struct
  306. *
  307. * Recursively iterates through an associative array or object's properties
  308. * to build XML response.
  309. *
  310. * @param mixed $struct
  311. * @param DOMDocument $dom
  312. * @param DOMElement $parent
  313. * @return void
  314. */
  315. protected function _structValue($struct, DOMDocument $dom, DOMElement $parent)
  316. {
  317. $struct = (array) $struct;
  318. foreach ($struct as $key => $value) {
  319. if ($value === false) {
  320. $value = 0;
  321. } elseif ($value === true) {
  322. $value = 1;
  323. }
  324. if (ctype_digit((string) $key)) {
  325. $key = 'key_' . $key;
  326. }
  327. if (is_array($value) || is_object($value)) {
  328. $element = $dom->createElement($key);
  329. $this->_structValue($value, $dom, $element);
  330. } else {
  331. $element = $dom->createElement($key);
  332. $element->appendChild($dom->createTextNode($value));
  333. }
  334. $parent->appendChild($element);
  335. }
  336. }
  337. /**
  338. * Handle a single value
  339. *
  340. * @param string|int|boolean $value Result value
  341. * @return string XML Response
  342. */
  343. protected function _handleScalar($value)
  344. {
  345. $function = $this->_functions[$this->_method];
  346. if ($function instanceof Zend_Server_Reflection_Method) {
  347. $class = $function->getDeclaringClass()->getName();
  348. } else {
  349. $class = false;
  350. }
  351. $method = $function->getName();
  352. $dom = new DOMDocument('1.0', $this->getEncoding());
  353. if ($class) {
  354. $xml = $dom->createElement($class);
  355. $methodNode = $dom->createElement($method);
  356. $xml->appendChild($methodNode);
  357. } else {
  358. $xml = $dom->createElement($method);
  359. $methodNode = $xml;
  360. }
  361. $xml->setAttribute('generator', 'zend');
  362. $xml->setAttribute('version', '1.0');
  363. $dom->appendChild($xml);
  364. if ($value === false) {
  365. $value = 0;
  366. } elseif ($value === true) {
  367. $value = 1;
  368. }
  369. if (isset($value)) {
  370. $element = $dom->createElement('response');
  371. $element->appendChild($dom->createTextNode($value));
  372. $methodNode->appendChild($element);
  373. } else {
  374. $methodNode->appendChild($dom->createElement('response'));
  375. }
  376. $methodNode->appendChild($dom->createElement('status', 'success'));
  377. return $dom->saveXML();
  378. }
  379. /**
  380. * Implement Zend_Server_Interface::fault()
  381. *
  382. * Creates XML error response, returning DOMDocument with response.
  383. *
  384. * @param string|Exception $fault Message
  385. * @param int $code Error Code
  386. * @return DOMDocument
  387. */
  388. public function fault($exception = null, $code = null)
  389. {
  390. if (isset($this->_functions[$this->_method])) {
  391. $function = $this->_functions[$this->_method];
  392. } elseif (isset($this->_method)) {
  393. $function = $this->_method;
  394. } else {
  395. $function = 'rest';
  396. }
  397. if ($function instanceof Zend_Server_Reflection_Method) {
  398. $class = $function->getDeclaringClass()->getName();
  399. } else {
  400. $class = false;
  401. }
  402. if ($function instanceof Zend_Server_Reflection_Function_Abstract) {
  403. $method = $function->getName();
  404. } else {
  405. $method = $function;
  406. }
  407. $dom = new DOMDocument('1.0', $this->getEncoding());
  408. if ($class) {
  409. $xml = $dom->createElement($class);
  410. $xmlMethod = $dom->createElement($method);
  411. $xml->appendChild($xmlMethod);
  412. } else {
  413. $xml = $dom->createElement($method);
  414. $xmlMethod = $xml;
  415. }
  416. $xml->setAttribute('generator', 'zend');
  417. $xml->setAttribute('version', '1.0');
  418. $dom->appendChild($xml);
  419. $xmlResponse = $dom->createElement('response');
  420. $xmlMethod->appendChild($xmlResponse);
  421. if ($exception instanceof Exception) {
  422. $element = $dom->createElement('message');
  423. $element->appendChild($dom->createTextNode($exception->getMessage()));
  424. $xmlResponse->appendChild($element);
  425. $code = $exception->getCode();
  426. } elseif (($exception !== null) || 'rest' == $function) {
  427. $xmlResponse->appendChild($dom->createElement('message', 'An unknown error occured. Please try again.'));
  428. } else {
  429. $xmlResponse->appendChild($dom->createElement('message', 'Call to ' . $method . ' failed.'));
  430. }
  431. $xmlMethod->appendChild($xmlResponse);
  432. $xmlMethod->appendChild($dom->createElement('status', 'failed'));
  433. // Headers to send
  434. if ($code === null || (404 != $code)) {
  435. $this->_headers[] = 'HTTP/1.0 400 Bad Request';
  436. } else {
  437. $this->_headers[] = 'HTTP/1.0 404 File Not Found';
  438. }
  439. return $dom;
  440. }
  441. /**
  442. * Retrieve any HTTP extra headers set by the server
  443. *
  444. * @return array
  445. */
  446. public function getHeaders()
  447. {
  448. return $this->_headers;
  449. }
  450. /**
  451. * Implement Zend_Server_Interface::addFunction()
  452. *
  453. * @param string $function Function Name
  454. * @param string $namespace Function namespace (unused)
  455. */
  456. public function addFunction($function, $namespace = '')
  457. {
  458. if (!is_array($function)) {
  459. $function = (array) $function;
  460. }
  461. foreach ($function as $func) {
  462. if (is_callable($func) && !in_array($func, self::$magicMethods)) {
  463. $this->_functions[$func] = $this->_reflection->reflectFunction($func);
  464. } else {
  465. require_once 'Zend/Rest/Server/Exception.php';
  466. throw new Zend_Rest_Server_Exception("Invalid Method Added to Service.");
  467. }
  468. }
  469. }
  470. /**
  471. * Implement Zend_Server_Interface::getFunctions()
  472. *
  473. * @return array An array of Zend_Server_Reflection_Method's
  474. */
  475. public function getFunctions()
  476. {
  477. return $this->_functions;
  478. }
  479. /**
  480. * Implement Zend_Server_Interface::loadFunctions()
  481. *
  482. * @todo Implement
  483. * @param array $functions
  484. */
  485. public function loadFunctions($functions)
  486. {
  487. }
  488. /**
  489. * Implement Zend_Server_Interface::setPersistence()
  490. *
  491. * @todo Implement
  492. * @param int $mode
  493. */
  494. public function setPersistence($mode)
  495. {
  496. }
  497. /**
  498. * Call a static class method and return the result
  499. *
  500. * @param string $class
  501. * @param array $args
  502. * @return mixed
  503. */
  504. protected function _callStaticMethod($class, array $args)
  505. {
  506. try {
  507. $result = call_user_func_array(array($class, $this->_functions[$this->_method]->getName()), $args);
  508. } catch (Exception $e) {
  509. $result = $this->fault($e);
  510. }
  511. return $result;
  512. }
  513. /**
  514. * Call an instance method of an object
  515. *
  516. * @param string $class
  517. * @param array $args
  518. * @return mixed
  519. * @throws Zend_Rest_Server_Exception For invalid class name
  520. */
  521. protected function _callObjectMethod($class, array $args)
  522. {
  523. try {
  524. if ($this->_functions[$this->_method]->getDeclaringClass()->getConstructor()) {
  525. $object = $this->_functions[$this->_method]->getDeclaringClass()->newInstanceArgs($this->_args);
  526. } else {
  527. $object = $this->_functions[$this->_method]->getDeclaringClass()->newInstance();
  528. }
  529. } catch (Exception $e) {
  530. echo $e->getMessage();
  531. require_once 'Zend/Rest/Server/Exception.php';
  532. throw new Zend_Rest_Server_Exception('Error instantiating class ' . $class . ' to invoke method ' . $this->_functions[$this->_method]->getName(), 500);
  533. }
  534. try {
  535. $result = $this->_functions[$this->_method]->invokeArgs($object, $args);
  536. } catch (Exception $e) {
  537. $result = $this->fault($e);
  538. }
  539. return $result;
  540. }
  541. }