2
0

Server.php 30 KB

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