Stomp.php 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614
  1. <?php
  2. /**
  3. *
  4. * Copyright 2005-2006 The Apache Software Foundation
  5. *
  6. * Licensed under the Apache License, Version 2.0 (the "License");
  7. * you may not use this file except in compliance with the License.
  8. * You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. */
  18. /* vim: set expandtab tabstop=3 shiftwidth=3: */
  19. require_once 'Stomp/Frame.php';
  20. /**
  21. * A Stomp Connection
  22. *
  23. *
  24. * @package Stomp
  25. * @author Hiram Chirino <hiram@hiramchirino.com>
  26. * @author Dejan Bosanac <dejan@nighttale.net>
  27. * @author Michael Caplan <mcaplan@labnet.net>
  28. * @version $Revision: 43 $
  29. */
  30. class Stomp
  31. {
  32. /**
  33. * Perform request synchronously
  34. *
  35. * @var boolean
  36. */
  37. public $sync = false;
  38. /**
  39. * Default prefetch size
  40. *
  41. * @var int
  42. */
  43. public $prefetchSize = 1;
  44. /**
  45. * Client id used for durable subscriptions
  46. *
  47. * @var string
  48. */
  49. public $clientId = null;
  50. protected $_brokerUri = null;
  51. protected $_socket = null;
  52. protected $_hosts = array();
  53. protected $_params = array();
  54. protected $_subscriptions = array();
  55. protected $_defaultPort = 61613;
  56. protected $_currentHost = - 1;
  57. protected $_attempts = 10;
  58. protected $_username = '';
  59. protected $_password = '';
  60. protected $_sessionId;
  61. protected $_read_timeout_seconds = 60;
  62. protected $_read_timeout_milliseconds = 0;
  63. protected $_connect_timeout_seconds = 60;
  64. /**
  65. * Constructor
  66. *
  67. * @param string $brokerUri Broker URL
  68. * @throws StompException
  69. */
  70. public function __construct ($brokerUri)
  71. {
  72. $this->_brokerUri = $brokerUri;
  73. $this->_init();
  74. }
  75. /**
  76. * Initialize connection
  77. *
  78. * @throws StompException
  79. */
  80. protected function _init ()
  81. {
  82. $pattern = "|^(([a-zA-Z]+)://)+\(*([a-zA-Z0-9\.:/i,-]+)\)*\??([a-zA-Z0-9=]*)$|i";
  83. if (preg_match($pattern, $this->_brokerUri, $regs)) {
  84. $scheme = $regs[2];
  85. $hosts = $regs[3];
  86. $params = $regs[4];
  87. if ($scheme != "failover") {
  88. $this->_processUrl($this->_brokerUri);
  89. } else {
  90. $urls = explode(",", $hosts);
  91. foreach ($urls as $url) {
  92. $this->_processUrl($url);
  93. }
  94. }
  95. if ($params != null) {
  96. parse_str($params, $this->_params);
  97. }
  98. } else {
  99. require_once 'Stomp/Exception.php';
  100. throw new StompException("Bad Broker URL {$this->_brokerUri}");
  101. }
  102. }
  103. /**
  104. * Process broker URL
  105. *
  106. * @param string $url Broker URL
  107. * @throws StompException
  108. * @return boolean
  109. */
  110. protected function _processUrl ($url)
  111. {
  112. $parsed = parse_url($url);
  113. if ($parsed) {
  114. array_push($this->_hosts, array($parsed['host'] , $parsed['port'] , $parsed['scheme']));
  115. } else {
  116. require_once 'Stomp/Exception.php';
  117. throw new StompException("Bad Broker URL $url");
  118. }
  119. }
  120. /**
  121. * Make socket connection to the server
  122. *
  123. * @throws StompException
  124. */
  125. protected function _makeConnection ()
  126. {
  127. if (count($this->_hosts) == 0) {
  128. require_once 'Stomp/Exception.php';
  129. throw new StompException("No broker defined");
  130. }
  131. // force disconnect, if previous established connection exists
  132. $this->disconnect();
  133. $i = $this->_currentHost;
  134. $att = 0;
  135. $connected = false;
  136. $connect_errno = null;
  137. $connect_errstr = null;
  138. while (! $connected && $att ++ < $this->_attempts) {
  139. if (isset($this->_params['randomize']) && $this->_params['randomize'] == 'true') {
  140. $i = rand(0, count($this->_hosts) - 1);
  141. } else {
  142. $i = ($i + 1) % count($this->_hosts);
  143. }
  144. $broker = $this->_hosts[$i];
  145. $host = $broker[0];
  146. $port = $broker[1];
  147. $scheme = $broker[2];
  148. if ($port == null) {
  149. $port = $this->_defaultPort;
  150. }
  151. if ($this->_socket != null) {
  152. fclose($this->_socket);
  153. $this->_socket = null;
  154. }
  155. $this->_socket = @fsockopen($scheme . '://' . $host, $port, $connect_errno, $connect_errstr, $this->_connect_timeout_seconds);
  156. if (!is_resource($this->_socket) && $att >= $this->_attempts && !array_key_exists($i + 1, $this->_hosts)) {
  157. require_once 'Stomp/Exception.php';
  158. throw new StompException("Could not connect to $host:$port ($att/{$this->_attempts})");
  159. } else if (is_resource($this->_socket)) {
  160. $connected = true;
  161. $this->_currentHost = $i;
  162. break;
  163. }
  164. }
  165. if (! $connected) {
  166. require_once 'Stomp/Exception.php';
  167. throw new StompException("Could not connect to a broker");
  168. }
  169. }
  170. /**
  171. * Connect to server
  172. *
  173. * @param string $username
  174. * @param string $password
  175. * @return boolean
  176. * @throws StompException
  177. */
  178. public function connect ($username = '', $password = '')
  179. {
  180. $this->_makeConnection();
  181. if ($username != '') {
  182. $this->_username = $username;
  183. }
  184. if ($password != '') {
  185. $this->_password = $password;
  186. }
  187. $headers = array('login' => $this->_username , 'passcode' => $this->_password);
  188. if ($this->clientId != null) {
  189. $headers["client-id"] = $this->clientId;
  190. }
  191. $frame = new StompFrame("CONNECT", $headers);
  192. $this->_writeFrame($frame);
  193. $frame = $this->readFrame();
  194. if ($frame instanceof StompFrame && $frame->command == 'CONNECTED') {
  195. $this->_sessionId = $frame->headers["session"];
  196. return true;
  197. } else {
  198. require_once 'Stomp/Exception.php';
  199. if ($frame instanceof StompFrame) {
  200. throw new StompException("Unexpected command: {$frame->command}", 0, $frame->body);
  201. } else {
  202. throw new StompException("Connection not acknowledged");
  203. }
  204. }
  205. }
  206. /**
  207. * Check if client session has ben established
  208. *
  209. * @return boolean
  210. */
  211. public function isConnected ()
  212. {
  213. return !empty($this->_sessionId) && is_resource($this->_socket);
  214. }
  215. /**
  216. * Current stomp session ID
  217. *
  218. * @return string
  219. */
  220. public function getSessionId()
  221. {
  222. return $this->_sessionId;
  223. }
  224. /**
  225. * Send a message to a destination in the messaging system
  226. *
  227. * @param string $destination Destination queue
  228. * @param string|StompFrame $msg Message
  229. * @param array $properties
  230. * @param boolean $sync Perform request synchronously
  231. * @return boolean
  232. */
  233. public function send ($destination, $msg, $properties = array(), $sync = null)
  234. {
  235. if ($msg instanceof StompFrame) {
  236. $msg->headers['destination'] = $destination;
  237. if (is_array($properties)) $msg->headers = array_merge($msg->headers, $properties);
  238. $frame = $msg;
  239. } else {
  240. $headers = $properties;
  241. $headers['destination'] = $destination;
  242. $frame = new StompFrame('SEND', $headers, $msg);
  243. }
  244. $this->_prepareReceipt($frame, $sync);
  245. $this->_writeFrame($frame);
  246. return $this->_waitForReceipt($frame, $sync);
  247. }
  248. /**
  249. * Prepair frame receipt
  250. *
  251. * @param StompFrame $frame
  252. * @param boolean $sync
  253. */
  254. protected function _prepareReceipt (StompFrame $frame, $sync)
  255. {
  256. $receive = $this->sync;
  257. if ($sync !== null) {
  258. $receive = $sync;
  259. }
  260. if ($receive == true) {
  261. $frame->headers['receipt'] = md5(microtime());
  262. }
  263. }
  264. /**
  265. * Wait for receipt
  266. *
  267. * @param StompFrame $frame
  268. * @param boolean $sync
  269. * @return boolean
  270. * @throws StompException
  271. */
  272. protected function _waitForReceipt (StompFrame $frame, $sync)
  273. {
  274. $receive = $this->sync;
  275. if ($sync !== null) {
  276. $receive = $sync;
  277. }
  278. if ($receive == true) {
  279. $id = (isset($frame->headers['receipt'])) ? $frame->headers['receipt'] : null;
  280. if ($id == null) {
  281. return true;
  282. }
  283. $frame = $this->readFrame();
  284. if ($frame instanceof StompFrame && $frame->command == 'RECEIPT') {
  285. if ($frame->headers['receipt-id'] == $id) {
  286. return true;
  287. } else {
  288. require_once 'Stomp/Exception.php';
  289. throw new StompException("Unexpected receipt id {$frame->headers['receipt-id']}", 0, $frame->body);
  290. }
  291. } else {
  292. require_once 'Stomp/Exception.php';
  293. if ($frame instanceof StompFrame) {
  294. throw new StompException("Unexpected command {$frame->command}", 0, $frame->body);
  295. } else {
  296. throw new StompException("Receipt not received");
  297. }
  298. }
  299. }
  300. return true;
  301. }
  302. /**
  303. * Register to listen to a given destination
  304. *
  305. * @param string $destination Destination queue
  306. * @param array $properties
  307. * @param boolean $sync Perform request synchronously
  308. * @return boolean
  309. * @throws StompException
  310. */
  311. public function subscribe ($destination, $properties = null, $sync = null)
  312. {
  313. $headers = array('ack' => 'client');
  314. $headers['activemq.prefetchSize'] = $this->prefetchSize;
  315. if ($this->clientId != null) {
  316. $headers["activemq.subcriptionName"] = $this->clientId;
  317. }
  318. if (isset($properties)) {
  319. foreach ($properties as $name => $value) {
  320. $headers[$name] = $value;
  321. }
  322. }
  323. $headers['destination'] = $destination;
  324. $frame = new StompFrame('SUBSCRIBE', $headers);
  325. $this->_prepareReceipt($frame, $sync);
  326. $this->_writeFrame($frame);
  327. if ($this->_waitForReceipt($frame, $sync) == true) {
  328. $this->_subscriptions[$destination] = $properties;
  329. return true;
  330. } else {
  331. return false;
  332. }
  333. }
  334. /**
  335. * Remove an existing subscription
  336. *
  337. * @param string $destination
  338. * @param array $properties
  339. * @param boolean $sync Perform request synchronously
  340. * @return boolean
  341. * @throws StompException
  342. */
  343. public function unsubscribe ($destination, $properties = null, $sync = null)
  344. {
  345. $headers = array();
  346. if (isset($properties)) {
  347. foreach ($properties as $name => $value) {
  348. $headers[$name] = $value;
  349. }
  350. }
  351. $headers['destination'] = $destination;
  352. $frame = new StompFrame('UNSUBSCRIBE', $headers);
  353. $this->_prepareReceipt($frame, $sync);
  354. $this->_writeFrame($frame);
  355. if ($this->_waitForReceipt($frame, $sync) == true) {
  356. unset($this->_subscriptions[$destination]);
  357. return true;
  358. } else {
  359. return false;
  360. }
  361. }
  362. /**
  363. * Start a transaction
  364. *
  365. * @param string $transactionId
  366. * @param boolean $sync Perform request synchronously
  367. * @return boolean
  368. * @throws StompException
  369. */
  370. public function begin ($transactionId = null, $sync = null)
  371. {
  372. $headers = array();
  373. if (isset($transactionId)) {
  374. $headers['transaction'] = $transactionId;
  375. }
  376. $frame = new StompFrame('BEGIN', $headers);
  377. $this->_prepareReceipt($frame, $sync);
  378. $this->_writeFrame($frame);
  379. return $this->_waitForReceipt($frame, $sync);
  380. }
  381. /**
  382. * Commit a transaction in progress
  383. *
  384. * @param string $transactionId
  385. * @param boolean $sync Perform request synchronously
  386. * @return boolean
  387. * @throws StompException
  388. */
  389. public function commit ($transactionId = null, $sync = null)
  390. {
  391. $headers = array();
  392. if (isset($transactionId)) {
  393. $headers['transaction'] = $transactionId;
  394. }
  395. $frame = new StompFrame('COMMIT', $headers);
  396. $this->_prepareReceipt($frame, $sync);
  397. $this->_writeFrame($frame);
  398. return $this->_waitForReceipt($frame, $sync);
  399. }
  400. /**
  401. * Roll back a transaction in progress
  402. *
  403. * @param string $transactionId
  404. * @param boolean $sync Perform request synchronously
  405. */
  406. public function abort ($transactionId = null, $sync = null)
  407. {
  408. $headers = array();
  409. if (isset($transactionId)) {
  410. $headers['transaction'] = $transactionId;
  411. }
  412. $frame = new StompFrame('ABORT', $headers);
  413. $this->_prepareReceipt($frame, $sync);
  414. $this->_writeFrame($frame);
  415. return $this->_waitForReceipt($frame, $sync);
  416. }
  417. /**
  418. * Acknowledge consumption of a message from a subscription
  419. * Note: This operation is always asynchronous
  420. *
  421. * @param string|StompFrame $messageMessage ID
  422. * @param string $transactionId
  423. * @return boolean
  424. * @throws StompException
  425. */
  426. public function ack ($message, $transactionId = null)
  427. {
  428. if ($message instanceof StompFrame) {
  429. $headers = $message->headers;
  430. if (isset($transactionId)) {
  431. $headers['transaction'] = $transactionId;
  432. }
  433. $frame = new StompFrame('ACK', $headers);
  434. $this->_writeFrame($frame);
  435. return true;
  436. } else {
  437. $headers = array();
  438. if (isset($transactionId)) {
  439. $headers['transaction'] = $transactionId;
  440. }
  441. $headers['message-id'] = $message;
  442. $frame = new StompFrame('ACK', $headers);
  443. $this->_writeFrame($frame);
  444. return true;
  445. }
  446. }
  447. /**
  448. * Graceful disconnect from the server
  449. *
  450. */
  451. public function disconnect ()
  452. {
  453. $headers = array();
  454. if ($this->clientId != null) {
  455. $headers["client-id"] = $this->clientId;
  456. }
  457. if (is_resource($this->_socket)) {
  458. $this->_writeFrame(new StompFrame('DISCONNECT', $headers));
  459. fclose($this->_socket);
  460. }
  461. $this->_socket = null;
  462. $this->_sessionId = null;
  463. $this->_currentHost = -1;
  464. $this->_subscriptions = array();
  465. $this->_username = '';
  466. $this->_password = '';
  467. }
  468. /**
  469. * Write frame to server
  470. *
  471. * @param StompFrame $stompFrame
  472. */
  473. protected function _writeFrame (StompFrame $stompFrame)
  474. {
  475. if (!is_resource($this->_socket)) {
  476. require_once 'Stomp/Exception.php';
  477. throw new StompException('Socket connection hasn\'t been established');
  478. }
  479. $data = $stompFrame->__toString();
  480. $r = fwrite($this->_socket, $data, strlen($data));
  481. if ($r === false || $r == 0) {
  482. $this->_reconnect();
  483. $this->_writeFrame($stompFrame);
  484. }
  485. }
  486. /**
  487. * Set timeout to wait for content to read
  488. *
  489. * @param int $seconds_to_wait Seconds to wait for a frame
  490. * @param int $milliseconds Milliseconds to wait for a frame
  491. */
  492. public function setReadTimeout($seconds, $milliseconds = 0)
  493. {
  494. $this->_read_timeout_seconds = $seconds;
  495. $this->_read_timeout_milliseconds = $milliseconds;
  496. }
  497. /**
  498. * Read response frame from server
  499. *
  500. * @return StompFrame False when no frame to read
  501. */
  502. public function readFrame ()
  503. {
  504. if (!$this->hasFrameToRead()) {
  505. return false;
  506. }
  507. $rb = 1024;
  508. $data = '';
  509. $end = false;
  510. do {
  511. $read = fread($this->_socket, $rb);
  512. if ($read === false) {
  513. $this->_reconnect();
  514. return $this->readFrame();
  515. }
  516. $data .= $read;
  517. if (strpos($data, "\x00") !== false) {
  518. $end = true;
  519. $data = rtrim($data, "\n");
  520. }
  521. $len = strlen($data);
  522. } while ($len < 2 || $end == false);
  523. list ($header, $body) = explode("\n\n", $data, 2);
  524. $header = explode("\n", $header);
  525. $headers = array();
  526. $command = null;
  527. foreach ($header as $v) {
  528. if (isset($command)) {
  529. list ($name, $value) = explode(':', $v, 2);
  530. $headers[$name] = $value;
  531. } else {
  532. $command = $v;
  533. }
  534. }
  535. $frame = new StompFrame($command, $headers, trim($body));
  536. if (isset($frame->headers['transformation']) && $frame->headers['transformation'] == 'jms-map-json') {
  537. require_once 'Stomp/Message/Map.php';
  538. return new StompMessageMap($frame);
  539. } else {
  540. return $frame;
  541. }
  542. return $frame;
  543. }
  544. /**
  545. * Check if there is a frame to read
  546. *
  547. * @return boolean
  548. */
  549. public function hasFrameToRead()
  550. {
  551. $read = array($this->_socket);
  552. $write = null;
  553. $except = null;
  554. $has_frame_to_read = @stream_select($read, $write, $except, $this->_read_timeout_seconds, $this->_read_timeout_milliseconds);
  555. if ($has_frame_to_read !== false)
  556. $has_frame_to_read = count($read);
  557. if ($has_frame_to_read === false) {
  558. throw new StompException('Check failed to determine if the socket is readable');
  559. } else if ($has_frame_to_read > 0) {
  560. return true;
  561. } else {
  562. return false;
  563. }
  564. }
  565. /**
  566. * Reconnects and renews subscriptions (if there were any)
  567. * Call this method when you detect connection problems
  568. */
  569. protected function _reconnect ()
  570. {
  571. $subscriptions = $this->_subscriptions;
  572. $this->connect($this->_username, $this->_password);
  573. foreach ($subscriptions as $dest => $properties) {
  574. $this->subscribe($dest, $properties);
  575. }
  576. }
  577. /**
  578. * Graceful object desruction
  579. *
  580. */
  581. public function __destruct()
  582. {
  583. $this->disconnect();
  584. }
  585. }
  586. ?>