Server.php 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923
  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. * 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. if(class_exists($className, false) && !isset($this->_classAllowed[$className])) {
  271. require_once 'Zend/Amf/Server/Exception.php';
  272. throw new Zend_Amf_Server_Exception('Can not call "' . $className . '" - use setClass()');
  273. }
  274. try {
  275. $this->getLoader()->load($className);
  276. } catch (Exception $e) {
  277. require_once 'Zend/Amf/Server/Exception.php';
  278. throw new Zend_Amf_Server_Exception('Class "' . $className . '" does not exist');
  279. }
  280. // Add the new loaded class to the server.
  281. $this->setClass($className, $source);
  282. } else {
  283. require_once 'Zend/Amf/Server/Exception.php';
  284. throw new Zend_Amf_Server_Exception('Method "' . $method . '" does not exist');
  285. }
  286. }
  287. $info = $this->_table[$qualifiedName];
  288. $argv = $info->getInvokeArguments();
  289. if (0 < count($argv)) {
  290. $params = array_merge($params, $argv);
  291. }
  292. if ($info instanceof Zend_Server_Reflection_Function) {
  293. $func = $info->getName();
  294. $this->_checkAcl(null, $func);
  295. $return = call_user_func_array($func, $params);
  296. } elseif ($info instanceof Zend_Server_Reflection_Method) {
  297. // Get class
  298. $class = $info->getDeclaringClass()->getName();
  299. if ('static' == $info->isStatic()) {
  300. // for some reason, invokeArgs() does not work the same as
  301. // invoke(), and expects the first argument to be an object.
  302. // So, using a callback if the method is static.
  303. $this->_checkAcl($class, $info->getName());
  304. $return = call_user_func_array(array($class, $info->getName()), $params);
  305. } else {
  306. // Object methods
  307. try {
  308. $object = $info->getDeclaringClass()->newInstance();
  309. } catch (Exception $e) {
  310. require_once 'Zend/Amf/Server/Exception.php';
  311. throw new Zend_Amf_Server_Exception('Error instantiating class ' . $class . ' to invoke method ' . $info->getName(), 621);
  312. }
  313. $this->_checkAcl($object, $info->getName());
  314. $return = $info->invokeArgs($object, $params);
  315. }
  316. } else {
  317. require_once 'Zend/Amf/Server/Exception.php';
  318. throw new Zend_Amf_Server_Exception('Method missing implementation ' . get_class($info));
  319. }
  320. return $return;
  321. }
  322. /**
  323. * Handles each of the 11 different command message types.
  324. *
  325. * A command message is a flex.messaging.messages.CommandMessage
  326. *
  327. * @see Zend_Amf_Value_Messaging_CommandMessage
  328. * @param Zend_Amf_Value_Messaging_CommandMessage $message
  329. * @return Zend_Amf_Value_Messaging_AcknowledgeMessage
  330. */
  331. protected function _loadCommandMessage(Zend_Amf_Value_Messaging_CommandMessage $message)
  332. {
  333. require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
  334. switch($message->operation) {
  335. case Zend_Amf_Value_Messaging_CommandMessage::DISCONNECT_OPERATION :
  336. case Zend_Amf_Value_Messaging_CommandMessage::CLIENT_PING_OPERATION :
  337. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  338. break;
  339. case Zend_Amf_Value_Messaging_CommandMessage::LOGIN_OPERATION :
  340. $data = explode(':', base64_decode($message->body));
  341. $userid = $data[0];
  342. $password = isset($data[1])?$data[1]:"";
  343. if(empty($userid)) {
  344. require_once 'Zend/Amf/Server/Exception.php';
  345. throw new Zend_Amf_Server_Exception('Login failed: username not supplied');
  346. }
  347. if(!$this->_handleAuth($userid, $password)) {
  348. require_once 'Zend/Amf/Server/Exception.php';
  349. throw new Zend_Amf_Server_Exception('Authentication failed');
  350. }
  351. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  352. break;
  353. case Zend_Amf_Value_Messaging_CommandMessage::LOGOUT_OPERATION :
  354. if($this->_auth) {
  355. Zend_Auth::getInstance()->clearIdentity();
  356. }
  357. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  358. break;
  359. default :
  360. require_once 'Zend/Amf/Server/Exception.php';
  361. throw new Zend_Amf_Server_Exception('CommandMessage::' . $message->operation . ' not implemented');
  362. break;
  363. }
  364. return $return;
  365. }
  366. /**
  367. * Create appropriate error message
  368. *
  369. * @param int $objectEncoding Current AMF encoding
  370. * @param string $message Message that was being processed when error happened
  371. * @param string $description Error description
  372. * @param mixed $detail Detailed data about the error
  373. * @param int $code Error code
  374. * @param int $line Error line
  375. * @return Zend_Amf_Value_Messaging_ErrorMessage|array
  376. */
  377. protected function _errorMessage($objectEncoding, $message, $description, $detail, $code, $line)
  378. {
  379. $return = null;
  380. switch ($objectEncoding) {
  381. case Zend_Amf_Constants::AMF0_OBJECT_ENCODING :
  382. return array (
  383. 'description' => ($this->isProduction ()) ? '' : $description,
  384. 'detail' => ($this->isProduction ()) ? '' : $detail,
  385. 'line' => ($this->isProduction ()) ? 0 : $line,
  386. 'code' => $code
  387. );
  388. case Zend_Amf_Constants::AMF3_OBJECT_ENCODING :
  389. require_once 'Zend/Amf/Value/Messaging/ErrorMessage.php';
  390. $return = new Zend_Amf_Value_Messaging_ErrorMessage ( $message );
  391. $return->faultString = $this->isProduction () ? '' : $description;
  392. $return->faultCode = $code;
  393. $return->faultDetail = $this->isProduction () ? '' : $detail;
  394. break;
  395. }
  396. return $return;
  397. }
  398. /**
  399. * Handle AMF authenticaton
  400. *
  401. * @param string $userid
  402. * @param string $password
  403. * @return boolean
  404. */
  405. protected function _handleAuth( $userid, $password)
  406. {
  407. if (!$this->_auth) {
  408. return true;
  409. }
  410. $this->_auth->setCredentials($userid, $password);
  411. $auth = Zend_Auth::getInstance();
  412. $result = $auth->authenticate($this->_auth);
  413. if ($result->isValid()) {
  414. if (!$this->isSession()) {
  415. $this->setSession();
  416. }
  417. return true;
  418. } else {
  419. // authentication failed, good bye
  420. require_once 'Zend/Amf/Server/Exception.php';
  421. throw new Zend_Amf_Server_Exception(
  422. "Authentication failed: " . join("\n",
  423. $result->getMessages()), $result->getCode());
  424. }
  425. }
  426. /**
  427. * Takes the deserialized AMF request and performs any operations.
  428. *
  429. * @todo should implement and SPL observer pattern for custom AMF headers
  430. * @todo DescribeService support
  431. * @param Zend_Amf_Request $request
  432. * @return Zend_Amf_Response
  433. * @throws Zend_Amf_server_Exception|Exception
  434. */
  435. protected function _handle(Zend_Amf_Request $request)
  436. {
  437. // Get the object encoding of the request.
  438. $objectEncoding = $request->getObjectEncoding();
  439. // create a response object to place the output from the services.
  440. $response = $this->getResponse();
  441. // set reponse encoding
  442. $response->setObjectEncoding($objectEncoding);
  443. $responseBody = $request->getAmfBodies();
  444. $handleAuth = false;
  445. if ($this->_auth) {
  446. $headers = $request->getAmfHeaders();
  447. if (isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]) &&
  448. isset($headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid)) {
  449. $handleAuth = true;
  450. }
  451. }
  452. // Iterate through each of the service calls in the AMF request
  453. foreach($responseBody as $body)
  454. {
  455. try {
  456. if ($handleAuth) {
  457. if ($this->_handleAuth(
  458. $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->userid,
  459. $headers[Zend_Amf_Constants::CREDENTIALS_HEADER]->password)) {
  460. // use RequestPersistentHeader to clear credentials
  461. $response->addAmfHeader(
  462. new Zend_Amf_Value_MessageHeader(
  463. Zend_Amf_Constants::PERSISTENT_HEADER,
  464. false,
  465. new Zend_Amf_Value_MessageHeader(
  466. Zend_Amf_Constants::CREDENTIALS_HEADER,
  467. false, null)));
  468. $handleAuth = false;
  469. }
  470. }
  471. if ($objectEncoding == Zend_Amf_Constants::AMF0_OBJECT_ENCODING) {
  472. // AMF0 Object Encoding
  473. $targetURI = $body->getTargetURI();
  474. $message = '';
  475. // Split the target string into its values.
  476. $source = substr($targetURI, 0, strrpos($targetURI, '.'));
  477. if ($source) {
  478. // Break off method name from namespace into source
  479. $method = substr(strrchr($targetURI, '.'), 1);
  480. $return = $this->_dispatch($method, $body->getData(), $source);
  481. } else {
  482. // Just have a method name.
  483. $return = $this->_dispatch($targetURI, $body->getData());
  484. }
  485. } else {
  486. // AMF3 read message type
  487. $message = $body->getData();
  488. if ($message instanceof Zend_Amf_Value_Messaging_CommandMessage) {
  489. // async call with command message
  490. $return = $this->_loadCommandMessage($message);
  491. } elseif ($message instanceof Zend_Amf_Value_Messaging_RemotingMessage) {
  492. require_once 'Zend/Amf/Value/Messaging/AcknowledgeMessage.php';
  493. $return = new Zend_Amf_Value_Messaging_AcknowledgeMessage($message);
  494. $return->body = $this->_dispatch($message->operation, $message->body, $message->source);
  495. } else {
  496. // Amf3 message sent with netConnection
  497. $targetURI = $body->getTargetURI();
  498. // Split the target string into its values.
  499. $source = substr($targetURI, 0, strrpos($targetURI, '.'));
  500. if ($source) {
  501. // Break off method name from namespace into source
  502. $method = substr(strrchr($targetURI, '.'), 1);
  503. $return = $this->_dispatch($method, $body->getData(), $source);
  504. } else {
  505. // Just have a method name.
  506. $return = $this->_dispatch($targetURI, $body->getData());
  507. }
  508. }
  509. }
  510. $responseType = Zend_AMF_Constants::RESULT_METHOD;
  511. } catch (Exception $e) {
  512. $return = $this->_errorMessage($objectEncoding, $message,
  513. $e->getMessage(), $e->getTraceAsString(),$e->getCode(), $e->getLine());
  514. $responseType = Zend_AMF_Constants::STATUS_METHOD;
  515. }
  516. $responseURI = $body->getResponseURI() . $responseType;
  517. $newBody = new Zend_Amf_Value_MessageBody($responseURI, null, $return);
  518. $response->addAmfBody($newBody);
  519. }
  520. // Add a session header to the body if session is requested.
  521. if($this->isSession()) {
  522. $currentID = session_id();
  523. $joint = "?";
  524. if(isset($_SERVER['QUERY_STRING'])) {
  525. if(!strpos($_SERVER['QUERY_STRING'], $currentID) !== FALSE) {
  526. if(strrpos($_SERVER['QUERY_STRING'], "?") !== FALSE) {
  527. $joint = "&";
  528. }
  529. }
  530. }
  531. // create a new AMF message header with the session id as a variable.
  532. $sessionValue = $joint . $this->_sessionName . "=" . $currentID;
  533. $sessionHeader = new Zend_Amf_Value_MessageHeader(Zend_Amf_Constants::URL_APPEND_HEADER, false, $sessionValue);
  534. $response->addAmfHeader($sessionHeader);
  535. }
  536. // serialize the response and return serialized body.
  537. $response->finalize();
  538. }
  539. /**
  540. * Handle an AMF call from the gateway.
  541. *
  542. * @param null|Zend_Amf_Request $request Optional
  543. * @return Zend_Amf_Response
  544. */
  545. public function handle($request = null)
  546. {
  547. // Check if request was passed otherwise get it from the server
  548. if (is_null($request) || !$request instanceof Zend_Amf_Request) {
  549. $request = $this->getRequest();
  550. } else {
  551. $this->setRequest($request);
  552. }
  553. if ($this->isSession()) {
  554. // Check if a session is being sent from the amf call
  555. if (isset($_COOKIE[$this->_sessionName])) {
  556. session_id($_COOKIE[$this->_sessionName]);
  557. }
  558. }
  559. // Check for errors that may have happend in deserialization of Request.
  560. try {
  561. // Take converted PHP objects and handle service call.
  562. // Serialize to Zend_Amf_response for output stream
  563. $this->_handle($request);
  564. $response = $this->getResponse();
  565. } catch (Exception $e) {
  566. // Handle any errors in the serialization and service calls.
  567. require_once 'Zend/Amf/Server/Exception.php';
  568. throw new Zend_Amf_Server_Exception('Handle error: ' . $e->getMessage() . ' ' . $e->getLine());
  569. }
  570. // Return the Amf serialized output string
  571. return $response;
  572. }
  573. /**
  574. * Set request object
  575. *
  576. * @param string|Zend_Amf_Request $request
  577. * @return Zend_Amf_Server
  578. */
  579. public function setRequest($request)
  580. {
  581. if (is_string($request) && class_exists($request)) {
  582. $request = new $request();
  583. if (!$request instanceof Zend_Amf_Request) {
  584. require_once 'Zend/Amf/Server/Exception.php';
  585. throw new Zend_Amf_Server_Exception('Invalid request class');
  586. }
  587. } elseif (!$request instanceof Zend_Amf_Request) {
  588. require_once 'Zend/Amf/Server/Exception.php';
  589. throw new Zend_Amf_Server_Exception('Invalid request object');
  590. }
  591. $this->_request = $request;
  592. return $this;
  593. }
  594. /**
  595. * Return currently registered request object
  596. *
  597. * @return null|Zend_Amf_Request
  598. */
  599. public function getRequest()
  600. {
  601. if (null === $this->_request) {
  602. require_once 'Zend/Amf/Request/Http.php';
  603. $this->setRequest(new Zend_Amf_Request_Http());
  604. }
  605. return $this->_request;
  606. }
  607. /**
  608. * Public access method to private Zend_Amf_Server_Response refrence
  609. *
  610. * @param string|Zend_Amf_Server_Response $response
  611. * @return Zend_Amf_Server
  612. */
  613. public function setResponse($response)
  614. {
  615. if (is_string($response) && class_exists($response)) {
  616. $response = new $response();
  617. if (!$response instanceof Zend_Amf_Response) {
  618. require_once 'Zend/Amf/Server/Exception.php';
  619. throw new Zend_Amf_Server_Exception('Invalid response class');
  620. }
  621. } elseif (!$response instanceof Zend_Amf_Response) {
  622. require_once 'Zend/Amf/Server/Exception.php';
  623. throw new Zend_Amf_Server_Exception('Invalid response object');
  624. }
  625. $this->_response = $response;
  626. return $this;
  627. }
  628. /**
  629. * get a refrence to the Zend_Amf_response instance
  630. *
  631. * @return Zend_Amf_Server_Response
  632. */
  633. public function getResponse()
  634. {
  635. if (null === ($response = $this->_response)) {
  636. require_once 'Zend/Amf/Response/Http.php';
  637. $this->setResponse(new Zend_Amf_Response_Http());
  638. }
  639. return $this->_response;
  640. }
  641. /**
  642. * Attach a class or object to the server
  643. *
  644. * Class may be either a class name or an instantiated object. Reflection
  645. * is done on the class or object to determine the available public
  646. * methods, and each is attached to the server as and available method. If
  647. * a $namespace has been provided, that namespace is used to prefix
  648. * AMF service call.
  649. *
  650. * @param string|object $class
  651. * @param string $namespace Optional
  652. * @param mixed $arg Optional arguments to pass to a method
  653. * @return Zend_Amf_Server
  654. * @throws Zend_Amf_Server_Exception on invalid input
  655. */
  656. public function setClass($class, $namespace = '', $argv = null)
  657. {
  658. if (is_string($class) && !class_exists($class)){
  659. require_once 'Zend/Amf/Server/Exception.php';
  660. throw new Zend_Amf_Server_Exception('Invalid method or class');
  661. } elseif (!is_string($class) && !is_object($class)) {
  662. require_once 'Zend/Amf/Server/Exception.php';
  663. throw new Zend_Amf_Server_Exception('Invalid method or class; must be a classname or object');
  664. }
  665. $argv = null;
  666. if (2 < func_num_args()) {
  667. $argv = array_slice(func_get_args(), 2);
  668. }
  669. // Use the class name as the name space by default.
  670. if ($namespace == '') {
  671. $namespace = is_object($class) ? get_class($class) : $class;
  672. }
  673. $this->_classAllowed[is_object($class) ? get_class($class) : $class] = true;
  674. $this->_methods[] = Zend_Server_Reflection::reflectClass($class, $argv, $namespace);
  675. $this->_buildDispatchTable();
  676. return $this;
  677. }
  678. /**
  679. * Attach a function to the server
  680. *
  681. * Additional arguments to pass to the function at dispatch may be passed;
  682. * any arguments following the namespace will be aggregated and passed at
  683. * dispatch time.
  684. *
  685. * @param string|array $function Valid callback
  686. * @param string $namespace Optional namespace prefix
  687. * @return Zend_Amf_Server
  688. * @throws Zend_Amf_Server_Exception
  689. */
  690. public function addFunction($function, $namespace = '')
  691. {
  692. if (!is_string($function) && !is_array($function)) {
  693. require_once 'Zend/Amf/Server/Exception.php';
  694. throw new Zend_Amf_Server_Exception('Unable to attach function');
  695. }
  696. $argv = null;
  697. if (2 < func_num_args()) {
  698. $argv = array_slice(func_get_args(), 2);
  699. }
  700. $function = (array) $function;
  701. foreach ($function as $func) {
  702. if (!is_string($func) || !function_exists($func)) {
  703. require_once 'Zend/Amf/Server/Exception.php';
  704. throw new Zend_Amf_Server_Exception('Unable to attach function');
  705. }
  706. $this->_methods[] = Zend_Server_Reflection::reflectFunction($func, $argv, $namespace);
  707. }
  708. $this->_buildDispatchTable();
  709. return $this;
  710. }
  711. /**
  712. * Creates an array of directories in which services can reside.
  713. * TODO: add support for prefixes?
  714. *
  715. * @param string $dir
  716. */
  717. public function addDirectory($dir)
  718. {
  719. $this->getLoader()->addPrefixPath("", $dir);
  720. }
  721. /**
  722. * Returns an array of directories that can hold services.
  723. *
  724. * @return array
  725. */
  726. public function getDirectory()
  727. {
  728. return $this->getLoader()->getPaths("");
  729. }
  730. /**
  731. * (Re)Build the dispatch table
  732. *
  733. * The dispatch table consists of a an array of method name =>
  734. * Zend_Server_Reflection_Function_Abstract pairs
  735. *
  736. * @return void
  737. */
  738. protected function _buildDispatchTable()
  739. {
  740. $table = array();
  741. foreach ($this->_methods as $key => $dispatchable) {
  742. if ($dispatchable instanceof Zend_Server_Reflection_Function_Abstract) {
  743. $ns = $dispatchable->getNamespace();
  744. $name = $dispatchable->getName();
  745. $name = empty($ns) ? $name : $ns . '.' . $name;
  746. if (isset($table[$name])) {
  747. require_once 'Zend/Amf/Server/Exception.php';
  748. throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
  749. }
  750. $table[$name] = $dispatchable;
  751. continue;
  752. }
  753. if ($dispatchable instanceof Zend_Server_Reflection_Class) {
  754. foreach ($dispatchable->getMethods() as $method) {
  755. $ns = $method->getNamespace();
  756. $name = $method->getName();
  757. $name = empty($ns) ? $name : $ns . '.' . $name;
  758. if (isset($table[$name])) {
  759. require_once 'Zend/Amf/Server/Exception.php';
  760. throw new Zend_Amf_Server_Exception('Duplicate method registered: ' . $name);
  761. }
  762. $table[$name] = $method;
  763. continue;
  764. }
  765. }
  766. }
  767. $this->_table = $table;
  768. }
  769. /**
  770. * Raise a server fault
  771. *
  772. * Unimplemented
  773. *
  774. * @param string|Exception $fault
  775. * @return void
  776. */
  777. public function fault($fault = null, $code = 404)
  778. {
  779. }
  780. /**
  781. * Returns a list of registered methods
  782. *
  783. * Returns an array of dispatchables (Zend_Server_Reflection_Function,
  784. * _Method, and _Class items).
  785. *
  786. * @return array
  787. */
  788. public function getFunctions()
  789. {
  790. return $this->_table;
  791. }
  792. /**
  793. * Set server persistence
  794. *
  795. * Unimplemented
  796. *
  797. * @param mixed $mode
  798. * @return void
  799. */
  800. public function setPersistence($mode)
  801. {
  802. }
  803. /**
  804. * Load server definition
  805. *
  806. * Unimplemented
  807. *
  808. * @param array $definition
  809. * @return void
  810. */
  811. public function loadFunctions($definition)
  812. {
  813. }
  814. /**
  815. * Map ActionScript classes to PHP classes
  816. *
  817. * @param string $asClass
  818. * @param string $phpClass
  819. * @return Zend_Amf_Server
  820. */
  821. public function setClassMap($asClass, $phpClass)
  822. {
  823. require_once 'Zend/Amf/Parse/TypeLoader.php';
  824. Zend_Amf_Parse_TypeLoader::setMapping($asClass, $phpClass);
  825. return $this;
  826. }
  827. /**
  828. * List all available methods
  829. *
  830. * Returns an array of method names.
  831. *
  832. * @return array
  833. */
  834. public function listMethods()
  835. {
  836. return array_keys($this->_table);
  837. }
  838. }