Server.php 30 KB

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