Server.php 20 KB

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