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