Server.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918
  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_Amf
  17. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  18. * @license http://framework.zend.com/license/new-bsd New BSD License
  19. */
  20. /** Zend_Server_Interface */
  21. require_once 'Zend/Server/Interface.php';
  22. /** Zend_Server_Reflection */
  23. require_once 'Zend/Server/Reflection.php';
  24. /** Zend_Amf_Constants */
  25. require_once 'Zend/Amf/Constants.php';
  26. /** Zend_Amf_Value_MessageBody */
  27. require_once 'Zend/Amf/Value/MessageBody.php';
  28. /** Zend_Amf_Value_MessageHeader */
  29. require_once 'Zend/Amf/Value/MessageHeader.php';
  30. /** Zend_Amf_Value_Messaging_CommandMessage */
  31. require_once 'Zend/Amf/Value/Messaging/CommandMessage.php';
  32. /** Zend_Loader_PluginLoader */
  33. require_once 'Zend/Loader/PluginLoader.php';
  34. /** Zend_Amf_Parse_TypeLoader */
  35. require_once 'Zend/Amf/Parse/TypeLoader.php';
  36. /** Zend_Auth */
  37. require_once 'Zend/Auth.php';
  38. /**
  39. * An AMF gateway server implementation to allow the connection of the Adobe Flash Player to
  40. * Zend Framework
  41. *
  42. * @todo Make the relection methods cache and autoload.
  43. * @package Zend_Amf
  44. * @subpackage Server
  45. * @copyright Copyright (c) 2005-2009 Zend Technologies USA Inc. (http://www.zend.com)
  46. * @license http://framework.zend.com/license/new-bsd New BSD License
  47. */
  48. class Zend_Amf_Server implements Zend_Server_Interface
  49. {
  50. /**
  51. * Array of dispatchables
  52. * @var array
  53. */
  54. protected $_methods = array();
  55. /**
  56. * Loader for classes in added directories
  57. * @var Zend_Loader_PluginLoader
  58. */
  59. protected $_loader;
  60. /**
  61. * @var bool Production flag; whether or not to return exception messages
  62. */
  63. protected $_production = true;
  64. /**
  65. * Request processed
  66. * @var null|Zend_Amf_Request
  67. */
  68. protected $_request = null;
  69. /**
  70. * Class to use for responses
  71. * @var null|Zend_Amf_Response
  72. */
  73. protected $_response;
  74. /**
  75. * Dispatch table of name => method pairs
  76. * @var array
  77. */
  78. protected $_table = array();
  79. /**
  80. *
  81. * @var bool session flag; whether or not to add a session to each response.
  82. */
  83. protected $_session = false;
  84. /**
  85. * Namespace allows all AMF calls to not clobber other php session variables
  86. * @var Zend_Session_NameSpace default session namespace zend_amf
  87. */
  88. protected $_sesionNamespace = 'zend_amf';
  89. /**
  90. * Set the default session.name if php_
  91. * @var string
  92. */
  93. protected $_sessionName = 'PHPSESSID';
  94. /**
  95. * Authentication handler object
  96. *
  97. * @var Zend_Amf_Auth_Abstract
  98. */
  99. protected $_auth;
  100. /**
  101. * ACL handler object
  102. *
  103. * @var Zend_Acl
  104. */
  105. protected $_acl;
  106. /**
  107. * The server constructor
  108. */
  109. public function __construct()
  110. {
  111. Zend_Amf_Parse_TypeLoader::setResourceLoader(new Zend_Loader_PluginLoader(array("Zend_Amf_Parse_Resource" => "Zend/Amf/Parse/Resource")));
  112. }
  113. /**
  114. * Set authentication adapter
  115. *
  116. * @param Zend_Amf_Auth_Abstract $auth
  117. * @return Zend_Amf_Server
  118. */
  119. public function setAuth(Zend_Amf_Auth_Abstract $auth)
  120. {
  121. $this->_auth = $auth;
  122. return $this;
  123. }
  124. /**
  125. * Get authentication adapter
  126. *
  127. * @return Zend_Amf_Auth_Abstract
  128. */
  129. public function getAuth()
  130. {
  131. return $this->_auth;
  132. }
  133. /**
  134. * Set ACL adapter
  135. *
  136. * @param Zend_Acl $acl
  137. * @return Zend_Amf_Server
  138. */
  139. public function setAcl(Zend_Acl $acl)
  140. {
  141. $this->_acl = $acl;
  142. return $this;
  143. }
  144. /**
  145. * Get ACL adapter
  146. *
  147. * @return Zend_Acl
  148. */
  149. public function getAcl()
  150. {
  151. return $this->_acl;
  152. }
  153. /**
  154. * Set production flag
  155. *
  156. * @param bool $flag
  157. * @return Zend_Amf_Server
  158. */
  159. public function setProduction($flag)
  160. {
  161. $this->_production = (bool) $flag;
  162. return $this;
  163. }
  164. /**
  165. * Whether or not the server is in production
  166. *
  167. * @return bool
  168. */
  169. public function isProduction()
  170. {
  171. return $this->_production;
  172. }
  173. /**
  174. * @param namespace of all incoming sessions defaults to Zend_Amf
  175. * @return Zend_Amf_Server
  176. */
  177. public function setSession($namespace = 'Zend_Amf')
  178. {
  179. require_once 'Zend/Session.php';
  180. $this->_session = true;
  181. $this->_sesionNamespace = new Zend_Session_Namespace($namespace);
  182. return $this;
  183. }
  184. /**
  185. * Whether of not the server is using sessions
  186. * @return bool
  187. */
  188. public function isSession()
  189. {
  190. return $this->_session;
  191. }
  192. /**
  193. * Check if the ACL allows accessing the function or method
  194. *
  195. * @param string|object $object Object or class being accessed
  196. * @param string $function Function or method being acessed
  197. * @return unknown_type
  198. */
  199. protected function _checkAcl($object, $function)
  200. {
  201. if(!$this->_acl) {
  202. return true;
  203. }
  204. if($object) {
  205. $class = is_object($object)?get_class($object):$object;
  206. if(!$this->_acl->has($class)) {
  207. require_once 'Zend/Acl/Resource.php';
  208. $this->_acl->add(new Zend_Acl_Resource($class));
  209. }
  210. $call = array($object, "initAcl");
  211. if(is_callable($call) && !call_user_func($call, $this->_acl)) {
  212. // if initAcl returns false, no ACL check
  213. return true;
  214. }
  215. } else {
  216. $class = null;
  217. }
  218. $auth = Zend_Auth::getInstance();
  219. if($auth->hasIdentity()) {
  220. $role = $auth->getIdentity()->role;
  221. } else {
  222. if($this->_acl->hasRole(Zend_Amf_Constants::GUEST_ROLE)) {
  223. $role = Zend_Amf_Constants::GUEST_ROLE;
  224. } else {
  225. require_once 'Zend/Amf/Server/Exception.php';
  226. throw new Zend_Amf_Server_Exception("Unauthenticated access not allowed");
  227. }
  228. }
  229. if($this->_acl->isAllowed($role, $class, $function)) {
  230. return true;
  231. } else {
  232. require_once 'Zend/Amf/Server/Exception.php';
  233. throw new Zend_Amf_Server_Exception("Access not allowed");
  234. }
  235. }
  236. /**
  237. * Get PluginLoader for the Server
  238. *
  239. * @return Zend_Loader_PluginLoader
  240. */
  241. protected function getLoader()
  242. {
  243. if(empty($this->_loader)) {
  244. require_once 'Zend/Loader/PluginLoader.php';
  245. $this->_loader = new Zend_Loader_PluginLoader();
  246. }
  247. return $this->_loader;
  248. }
  249. /**
  250. * Loads a remote class or method and executes the function and returns
  251. * the result
  252. *
  253. * @param string $method Is the method to execute
  254. * @param mixed $param values for the method
  255. * @return mixed $response the result of executing the method
  256. * @throws Zend_Amf_Server_Exception
  257. */
  258. protected function _dispatch($method, $params = null, $source = null)
  259. {
  260. if($source) {
  261. if(($mapped = Zend_Amf_Parse_TypeLoader::getMappedClassName($source)) !== false) {
  262. $source = $mapped;
  263. }
  264. }
  265. $qualifiedName = empty($source) ? $method : $source.".".$method;
  266. if (!isset($this->_table[$qualifiedName])) {
  267. // if source is null a method that was not defined was called.
  268. if ($source) {
  269. $className = str_replace(".", "_", $source);
  270. try {
  271. $this->getLoader()->load($className);
  272. } catch (Exception $e) {
  273. require_once 'Zend/Amf/Server/Exception.php';
  274. throw new Zend_Amf_Server_Exception('Class "' . $className . '" does not exist');
  275. }
  276. // Add the new loaded class to the server.
  277. $this->setClass($className, $source);
  278. } else {
  279. require_once 'Zend/Amf/Server/Exception.php';
  280. throw new Zend_Amf_Server_Exception('Method "' . $method . '" does not exist');
  281. }
  282. }
  283. $info = $this->_table[$qualifiedName];
  284. $argv = $info->getInvokeArguments();
  285. if (0 < count($argv)) {
  286. $params = array_merge($params, $argv);
  287. }
  288. if ($info instanceof Zend_Server_Reflection_Function) {
  289. $func = $info->getName();
  290. $this->_checkAcl(null, $func);
  291. $return = call_user_func_array($func, $params);
  292. } elseif ($info instanceof Zend_Server_Reflection_Method) {
  293. // Get class
  294. $class = $info->getDeclaringClass()->getName();
  295. if ('static' == $info->isStatic()) {
  296. // for some reason, invokeArgs() does not work the same as
  297. // invoke(), and expects the first argument to be an object.
  298. // So, using a callback if the method is static.
  299. $this->_checkAcl($class, $info->getName());
  300. $return = call_user_func_array(array($class, $info->getName()), $params);
  301. } else {
  302. // Object methods
  303. try {
  304. $object = $info->getDeclaringClass()->newInstance();
  305. } catch (Exception $e) {
  306. require_once 'Zend/Amf/Server/Exception.php';
  307. throw new Zend_Amf_Server_Exception('Error instantiating class ' . $class . ' to invoke method ' . $info->getName(), 621);
  308. }
  309. $this->_checkAcl($object, $info->getName());
  310. $return = $info->invokeArgs($object, $params);
  311. }
  312. } else {
  313. require_once 'Zend/Amf/Server/Exception.php';
  314. throw new Zend_Amf_Server_Exception('Method missing implementation ' . get_class($info));
  315. }
  316. return $return;
  317. }
  318. /**
  319. * Handles each of the 11 different command message types.
  320. *
  321. * A command message is a flex.messaging.messages.CommandMessage
  322. *
  323. * @see Zend_Amf_Value_Messaging_CommandMessage
  324. * @param Zend_Amf_Value_Messaging_CommandMessage $message
  325. * @return Zend_Amf_Value_Messaging_AcknowledgeMessage
  326. */
  327. protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message)
  328. {
  329. require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
  330. switch($message->operation) {
  331. case Zend_Amf_Value_Messaging_CommandMessage::DISCONNECT_OPERATION :
  332. case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION :
  333. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  334. break;
  335. case Zend_Amf_Value_Messaging_CommandMessage::LOGIN_OPERATION :
  336. $data = explode(':', base64_decode($message->body));
  337. $userid = $data[0];
  338. $password = isset($data[1])?$data[1]:"";
  339. if(empty($userid)) {
  340. require_once 'Zend/Amf/Server/Exception.php';
  341. throw new Zend_Amf_Server_Exception('Login failed: username not supplied');
  342. }
  343. if(!$this->_handleAuth($userid, $password)) {
  344. require_once 'Zend/Amf/Server/Exception.php';
  345. throw new Zend_Amf_Server_Exception('Authentication failed');
  346. }
  347. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  348. break;
  349. case Zend_Amf_Value_Messaging_CommandMessage::LOGOUT_OPERATION :
  350. if($this->_auth) {
  351. Zend_Auth::getInstance()->clearIdentity();
  352. }
  353. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  354. break;
  355. default :
  356. require_once 'Zend/Amf/Server/Exception.php';
  357. throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented');
  358. break;
  359. }
  360. return $return;
  361. }
  362. /**
  363. * Create appropriate error message
  364. *
  365. * @param int $objectEncoding Current AMF encoding
  366. * @param string $message Message that was being processed when error happened
  367. * @param string $description Error description
  368. * @param mixed $detail Detailed data about the error
  369. * @param int $code Error code
  370. * @param int $line Error line
  371. * @return Zend_Amf_Value_Messaging_ErrorMessage|array
  372. */
  373. protected function _errorMessage($objectEncoding, $message, $description, $detail, $code, $line)
  374. {
  375. $return = null;
  376. switch ($objectEncoding) {
  377. case Zend_Amf_Constants::AMF0_OBJECT_ENCODING :
  378. return array (
  379. 'description' => ($this->isProduction ()) ? '' : $description,
  380. 'detail' => ($this->isProduction ()) ? '' : $detail,
  381. 'line' => ($this->isProduction ()) ? 0 : $line,
  382. 'code' => $code
  383. );
  384. case Zend_Amf_Constants::AMF3_OBJECT_ENCODING :
  385. require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
  386. $return = new Zend_Amf_Value_Messaging_ErrorMessage ( $message );
  387. $return->faultString = $this->isProduction () ? '' : $description;
  388. $return->faultCode = $code;
  389. $return->faultDetail = $this->isProduction () ? '' : $detail;
  390. break;
  391. }
  392. return $return;
  393. }
  394. /**
  395. * Handle AMF authenticaton
  396. *
  397. * @param string $userid
  398. * @param string $password
  399. * @return boolean
  400. */
  401. protected function _handleAuth( $userid, $password)
  402. {
  403. if (!$this->_auth) {
  404. return true;
  405. }
  406. $this->_auth->setCredentials($userid, $password);
  407. $auth = Zend_Auth::getInstance();
  408. $result = $auth->authenticate($this->_auth);
  409. if ($result->isValid()) {
  410. if (!$this->isSession()) {
  411. $this->setSession();
  412. }
  413. return true;
  414. } else {
  415. // authentication failed, good bye
  416. require_once 'Zend/Amf/Server/Exception.php';
  417. throw new Zend_Amf_Server_Exception(
  418. "Authentication failed: " . join("\n",
  419. $result->getMessages()), $result->getCode());
  420. }
  421. }
  422. /**
  423. * Takes the deserialized AMF request and performs any operations.
  424. *
  425. * @todo should implement and SPL observer pattern for custom AMF headers
  426. * @todo DescribeService support
  427. * @param Zend_Amf_Request $request
  428. * @return Zend_Amf_Response
  429. * @throws Zend_Amf_server_Exception|Exception
  430. */
  431. protected function _handle(Zend_Amf_Request $request)
  432. {
  433. // Get the object encoding of the request.
  434. $objectEncoding = $request->getObjectEncoding();
  435. // create a response object to place the output from the services.
  436. $response = $this->getResponse();
  437. // set reponse encoding
  438. $response->setObjectEncoding($objectEncoding);
  439. $responseBody = $request->getAmfBodies();
  440. $handleAuth = false;
  441. if ($this->_auth) {
  442. $headers = $request->getAmfHeaders();
  443. if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]) &&
  444. isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid)) {
  445. $handleAuth = true;
  446. }
  447. }
  448. // Iterate through each of the service calls in the AMF request
  449. foreach($responseBody as $body)
  450. {
  451. try {
  452. if ($handleAuth) {
  453. if ($this->_handleAuth(
  454. $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid,
  455. $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password)) {
  456. // use RequestPersistentHeader to clear credentials
  457. $response->addAmfHeader(
  458. new Zend_Amf_Value_MessageHeader(
  459. Zend_Amf_Constants::PERSISTENT_HEADER,
  460. false,
  461. new Zend_Amf_Value_MessageHeader(
  462. Zend_Amf_Constants::CREDENTIALS_HEADER,
  463. false, null)));
  464. $handleAuth = false;
  465. }
  466. }
  467. if ($objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) {
  468. // AMF0 Object Encoding
  469. $targetURI = $body->getTargetURI();
  470. $message = '';
  471. // Split the target string into its values.
  472. $source = substr($targetURI, 0, strrpos($targetURI, '.'));
  473. if ($source) {
  474. // Break off method name from namespace into source
  475. $method = substr(strrchr($targetURI, '.'), 1);
  476. $return = $this->_dispatch($method, $body->getData(), $source);
  477. } else {
  478. // Just have a method name.
  479. $return = $this->_dispatch($targetURI, $body->getData());
  480. }
  481. } else {
  482. // AMF3 read message type
  483. $message = $body->getData();
  484. if ($message instanceof Zend_Amf_Value_Messaging_CommandMessage) {
  485. // async call with command message
  486. $return = $this->_loadCommandMessage($message);
  487. } elseif ($message instanceof Zend_Amf_Value_Messaging_RemotingMessage) {
  488. require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
  489. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  490. $return->body = $this->_dispatch($message->operation, $message->body, $message->source);
  491. } else {
  492. // Amf3 message sent with netConnection
  493. $targetURI = $body->getTargetURI();
  494. // Split the target string into its values.
  495. $source = substr($targetURI, 0, strrpos($targetURI, '.'));
  496. if ($source) {
  497. // Break off method name from namespace into source
  498. $method = substr(strrchr($targetURI, '.'), 1);
  499. $return = $this->_dispatch($method, $body->getData(), $source);
  500. } else {
  501. // Just have a method name.
  502. $return = $this->_dispatch($targetURI, $body->getData());
  503. }
  504. }
  505. }
  506. $responseType = Zend_AMF_Constants::RESULT_METHOD;
  507. } catch (Exception $e) {
  508. $return = $this->_errorMessage($objectEncoding, $message,
  509. $e->getMessage(), $e->getTraceAsString(),$e->getCode(), $e->getLine());
  510. $responseType = Zend_AMF_Constants::STATUS_METHOD;
  511. }
  512. $responseURI = $body->getResponseURI() . $responseType;
  513. $newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $return);
  514. $response->addAmfBody($newBody);
  515. }
  516. // Add a session header to the body if session is requested.
  517. if($this->isSession()) {
  518. $currentID = session_id();
  519. $joint = "?";
  520. if(isset($_SERVER['QUERY_STRING'])) {
  521. if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) {
  522. if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) {
  523. $joint = "&";
  524. }
  525. }
  526. }
  527. // create a new AMF message header with the session id as a variable.
  528. $sessionValue = $joint . $this->_sessionName . "=" . $currentID;
  529. $sessionHeader = new Zend_Amf_Value_MessageHeader(Zend_Amf_Constants::URL_APPEND_HEADER, false, $sessionValue);
  530. $response->addAmfHeader($sessionHeader);
  531. }
  532. // serialize the response and return serialized body.
  533. $response->finalize();
  534. }
  535. /**
  536. * Handle an AMF call from the gateway.
  537. *
  538. * @param null|Zend_Amf_Request $request Optional
  539. * @return Zend_Amf_Response
  540. */
  541. public function handle($request = null)
  542. {
  543. // Check if request was passed otherwise get it from the server
  544. if (is_null($request) || !$request instanceof Zend_Amf_Request) {
  545. $request = $this->getRequest();
  546. } else {
  547. $this->setRequest($request);
  548. }
  549. if ($this->isSession()) {
  550. // Check if a session is being sent from the amf call
  551. if (isset($_COOKIE[$this->_sessionName])) {
  552. session_id($_COOKIE[$this->_sessionName]);
  553. }
  554. }
  555. // Check for errors that may have happend in deserialization of Request.
  556. try {
  557. // Take converted PHP objects and handle service call.
  558. // Serialize to Zend_Amf_response for output stream
  559. $this->_handle($request);
  560. $response = $this->getResponse();
  561. } catch (Exception $e) {
  562. // Handle any errors in the serialization and service calls.
  563. require_once 'Zend/Amf/Server/Exception.php';
  564. throw new Zend_Amf_Server_Exception('Handle error: ' . $e->getMessage() . ' ' . $e->getLine());
  565. }
  566. // Return the Amf serialized output string
  567. return $response;
  568. }
  569. /**
  570. * Set request object
  571. *
  572. * @param string|Zend_Amf_Request $request
  573. * @return Zend_Amf_Server
  574. */
  575. public function setRequest($request)
  576. {
  577. if (is_string($request) && class_exists($request)) {
  578. $request = new $request();
  579. if (!$request instanceof Zend_Amf_Request) {
  580. require_once 'Zend/Amf/Server/Exception.php';
  581. throw new Zend_Amf_Server_Exception('Invalid request class');
  582. }
  583. } elseif (!$request instanceof Zend_Amf_Request) {
  584. require_once 'Zend/Amf/Server/Exception.php';
  585. throw new Zend_Amf_Server_Exception('Invalid request object');
  586. }
  587. $this->_request = $request;
  588. return $this;
  589. }
  590. /**
  591. * Return currently registered request object
  592. *
  593. * @return null|Zend_Amf_Request
  594. */
  595. public function getRequest()
  596. {
  597. if (null === $this->_request) {
  598. require_once 'Zend/Amf/Request/Http.php';
  599. $this->setRequest(new Zend_Amf_Request_Http());
  600. }
  601. return $this->_request;
  602. }
  603. /**
  604. * Public access method to private Zend_Amf_Server_Response refrence
  605. *
  606. * @param string|Zend_Amf_Server_Response $response
  607. * @return Zend_Amf_Server
  608. */
  609. public function setResponse($response)
  610. {
  611. if (is_string($response) && class_exists($response)) {
  612. $response = new $response();
  613. if (!$response instanceof Zend_Amf_Response) {
  614. require_once 'Zend/Amf/Server/Exception.php';
  615. throw new Zend_Amf_Server_Exception('Invalid response class');
  616. }
  617. } elseif (!$response instanceof Zend_Amf_Response) {
  618. require_once 'Zend/Amf/Server/Exception.php';
  619. throw new Zend_Amf_Server_Exception('Invalid response object');
  620. }
  621. $this->_response = $response;
  622. return $this;
  623. }
  624. /**
  625. * get a refrence to the Zend_Amf_response instance
  626. *
  627. * @return Zend_Amf_Server_Response
  628. */
  629. public function getResponse()
  630. {
  631. if (null === ($response = $this->_response)) {
  632. require_once 'Zend/Amf/Response/Http.php';
  633. $this->setResponse(new Zend_Amf_Response_Http());
  634. }
  635. return $this->_response;
  636. }
  637. /**
  638. * Attach a class or object to the server
  639. *
  640. * Class may be either a class name or an instantiated object. Reflection
  641. * is done on the class or object to determine the available public
  642. * methods, and each is attached to the server as and available method. If
  643. * a $namespace has been provided, that namespace is used to prefix
  644. * AMF service call.
  645. *
  646. * @param string|object $class
  647. * @param string $namespace Optional
  648. * @param mixed $arg Optional arguments to pass to a method
  649. * @return Zend_Amf_Server
  650. * @throws Zend_Amf_Server_Exception on invalid input
  651. */
  652. public function setClass($class, $namespace = '', $argv = null)
  653. {
  654. if (is_string($class) && !class_exists($class)){
  655. require_once 'Zend/Amf/Server/Exception.php';
  656. throw new Zend_Amf_Server_Exception('Invalid method or class');
  657. } elseif (!is_string($class) && !is_object($class)) {
  658. require_once 'Zend/Amf/Server/Exception.php';
  659. throw new Zend_Amf_Server_Exception('Invalid method or class; must be a classname or object');
  660. }
  661. $argv = null;
  662. if (2 < func_num_args()) {
  663. $argv = array_slice(func_get_args(), 2);
  664. }
  665. // Use the class name as the name space by default.
  666. if ($namespace == '') {
  667. $namespace = is_object($class) ? get_class($class) : $class;
  668. }
  669. $this->_methods[] = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
  670. $this->_buildDispatchTable();
  671. return $this;
  672. }
  673. /**
  674. * Attach a function to the server
  675. *
  676. * Additional arguments to pass to the function at dispatch may be passed;
  677. * any arguments following the namespace will be aggregated and passed at
  678. * dispatch time.
  679. *
  680. * @param string|array $function Valid callback
  681. * @param string $namespace Optional namespace prefix
  682. * @return Zend_Amf_Server
  683. * @throws Zend_Amf_Server_Exception
  684. */
  685. public function addFunction($function, $namespace = '')
  686. {
  687. if (!is_string($function) && !is_array($function)) {
  688. require_once 'Zend/Amf/Server/Exception.php';
  689. throw new Zend_Amf_Server_Exception('Unable to attach function');
  690. }
  691. $argv = null;
  692. if (2 < func_num_args()) {
  693. $argv = array_slice(func_get_args(), 2);
  694. }
  695. $function = (array) $function;
  696. foreach ($function as $func) {
  697. if (!is_string($func) || !function_exists($func)) {
  698. require_once 'Zend/Amf/Server/Exception.php';
  699. throw new Zend_Amf_Server_Exception('Unable to attach function');
  700. }
  701. $this->_methods[] = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace);
  702. }
  703. $this->_buildDispatchTable();
  704. return $this;
  705. }
  706. /**
  707. * Creates an array of directories in which services can reside.
  708. * TODO: add support for prefixes?
  709. *
  710. * @param string $dir
  711. */
  712. public function addDirectory($dir)
  713. {
  714. $this->getLoader()->addPrefixPath("", $dir);
  715. }
  716. /**
  717. * Returns an array of directories that can hold services.
  718. *
  719. * @return array
  720. */
  721. public function getDirectory()
  722. {
  723. return $this->getLoader()->getPaths("");
  724. }
  725. /**
  726. * (Re)Build the dispatch table
  727. *
  728. * The dispatch table consists of a an array of method name =>
  729. * Zend_Server_Reflection_Function_Abstract pairs
  730. *
  731. * @return void
  732. */
  733. protected function _buildDispatchTable()
  734. {
  735. $table = array();
  736. foreach ($this->_methods as $key => $dispatchable) {
  737. if ($dispatchable instanceof Zend_Server_Reflection_Function_Abstract) {
  738. $ns = $dispatchable->getNamespace();
  739. $name = $dispatchable->getName();
  740. $name = empty($ns) ? $name : $ns . '.' . $name;
  741. if (isset($table[$name])) {
  742. require_once 'Zend/Amf/Server/Exception.php';
  743. throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
  744. }
  745. $table[$name] = $dispatchable;
  746. continue;
  747. }
  748. if ($dispatchable instanceof Zend_Server_Reflection_Class) {
  749. foreach ($dispatchable->getMethods() as $method) {
  750. $ns = $method->getNamespace();
  751. $name = $method->getName();
  752. $name = empty($ns) ? $name : $ns . '.' . $name;
  753. if (isset($table[$name])) {
  754. require_once 'Zend/Amf/Server/Exception.php';
  755. throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
  756. }
  757. $table[$name] = $method;
  758. continue;
  759. }
  760. }
  761. }
  762. $this->_table = $table;
  763. }
  764. /**
  765. * Raise a server fault
  766. *
  767. * Unimplemented
  768. *
  769. * @param string|Exception $fault
  770. * @return void
  771. */
  772. public function fault($fault = null, $code = 404)
  773. {
  774. }
  775. /**
  776. * Returns a list of registered methods
  777. *
  778. * Returns an array of dispatchables (Zend_Server_Reflection_Function,
  779. * _Method, and _Class items).
  780. *
  781. * @return array
  782. */
  783. public function getFunctions()
  784. {
  785. return $this->_table;
  786. }
  787. /**
  788. * Set server persistence
  789. *
  790. * Unimplemented
  791. *
  792. * @param mixed $mode
  793. * @return void
  794. */
  795. public function setPersistence($mode)
  796. {
  797. }
  798. /**
  799. * Load server definition
  800. *
  801. * Unimplemented
  802. *
  803. * @param array $definition
  804. * @return void
  805. */
  806. public function loadFunctions($definition)
  807. {
  808. }
  809. /**
  810. * Map ActionScript classes to PHP classes
  811. *
  812. * @param string $asClass
  813. * @param string $phpClass
  814. * @return Zend_Amf_Server
  815. */
  816. public function setClassMap($asClass, $phpClass)
  817. {
  818. require_once 'Zend/Amf/Parse/TypeLoader.php';
  819. Zend_Amf_Parse_TypeLoader::setMapping($asClass, $phpClass);
  820. return $this;
  821. }
  822. /**
  823. * List all available methods
  824. *
  825. * Returns an array of method names.
  826. *
  827. * @return array
  828. */
  829. public function listMethods()
  830. {
  831. return array_keys($this->_table);
  832. }
  833. }