Server.php 19 KB

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