]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Irc/extlib/phergie/Phergie/Driver/Streams.php
Merged in Phergie changes
[quix0rs-gnu-social.git] / plugins / Irc / extlib / phergie / Phergie / Driver / Streams.php
1 <?php
2 /**
3  * Phergie
4  *
5  * PHP version 5
6  *
7  * LICENSE
8  *
9  * This source file is subject to the new BSD license that is bundled
10  * with this package in the file LICENSE.
11  * It is also available through the world-wide-web at this URL:
12  * http://phergie.org/license
13  *
14  * @category  Phergie
15  * @package   Phergie
16  * @author    Phergie Development Team <team@phergie.org>
17  * @copyright 2008-2010 Phergie Development Team (http://phergie.org)
18  * @license   http://phergie.org/license New BSD License
19  * @link      http://pear.phergie.org/package/Phergie
20  */
21
22 /**
23  * Driver that uses the sockets wrapper of the streams extension for
24  * communicating with the server and handles formatting and parsing of
25  * events using PHP.
26  *
27  * @category Phergie
28  * @package  Phergie
29  * @author   Phergie Development Team <team@phergie.org>
30  * @license  http://phergie.org/license New BSD License
31  * @link     http://pear.phergie.org/package/Phergie
32  */
33 class Phergie_Driver_Streams extends Phergie_Driver_Abstract
34 {
35     /**
36      * Socket handlers
37      *
38      * @var array
39      */
40     protected $sockets = array();
41
42     /**
43      * Reference to the currently active socket handler
44      *
45      * @var resource
46      */
47     protected $socket;
48
49     /**
50      * Amount of time in seconds to wait to receive an event each time the
51      * socket is polled
52      *
53      * @var float
54      */
55     protected $timeout = 0.1;
56
57     /**
58      * Handles construction of command strings and their transmission to the
59      * server.
60      *
61      * @param string       $command Command to send
62      * @param string|array $args    Optional string or array of sequential
63      *        arguments
64      *
65      * @return string Command string that was sent
66      * @throws Phergie_Driver_Exception
67      */
68     protected function send($command, $args = '')
69     {
70         $connection = $this->getConnection();
71         $encoding = $connection->getEncoding();
72
73         // Require an open socket connection to continue
74         if (empty($this->socket)) {
75             throw new Phergie_Driver_Exception(
76                 'doConnect() must be called first',
77                 Phergie_Driver_Exception::ERR_NO_INITIATED_CONNECTION
78             );
79         }
80
81         // Add the command
82         $buffer = strtoupper($command);
83
84         // Add arguments
85         if (!empty($args)) {
86
87             // Apply formatting if arguments are passed in as an array
88             if (is_array($args)) {
89                 $end = count($args) - 1;
90                 $args[$end] = ':' . $args[$end];
91                 $args = implode(' ', $args);
92             } else {
93                 $args = ':' . $args;
94             }
95
96             $buffer .= ' ' . $args;
97         }
98
99         // Transmit the command over the socket connection
100         $attempts = $written = 0;
101         $temp = $buffer . "\r\n";
102         $is_multibyte = !substr($encoding, 0, 8) === 'ISO-8859' && $encoding !== 'ASCII' && $encoding !== 'CP1252';
103         $length = ($is_multibyte) ? mb_strlen($buffer, '8bit') : strlen($buffer);
104         while (true) {
105             $written += (int) fwrite($this->socket, $temp);
106             if ($written < $length) {
107                 $temp = substr($temp, $written);
108                 $attempts++;
109                 if ($attempts == 3) {
110                     throw new Phergie_Driver_Exception(
111                         'Unable to write to socket',
112                         Phergie_Driver_Exception::ERR_CONNECTION_WRITE_FAILED
113                     );
114                 }
115             } else {
116                 break;
117             }
118         }
119
120         // Return the command string that was transmitted
121         return $buffer;
122     }
123
124     /**
125      * Overrides the parent class to set the currently active socket handler
126      * when the active connection is changed.
127      *
128      * @param Phergie_Connection $connection Active connection
129      *
130      * @return Phergie_Driver_Streams Provides a fluent interface
131      */
132     public function setConnection(Phergie_Connection $connection)
133     {
134         // Set the active socket handler
135         $hostmask = (string) $connection->getHostmask();
136         if (!empty($this->sockets[$hostmask])) {
137             $this->socket = $this->sockets[$hostmask];
138         }
139
140         // Set the active connection
141         return parent::setConnection($connection);
142     }
143
144     /**
145      * Returns a list of hostmasks corresponding to sockets with data to read.
146      *
147      * @param int $sec  Length of time to wait for new data (seconds)
148      * @param int $usec Length of time to wait for new data (microseconds)
149      *
150      * @return array List of hostmasks or an empty array if none were found
151      *         to have data to read
152      */
153     public function getActiveReadSockets($sec = 0, $usec = 200000)
154     {
155         $read = $this->sockets;
156         $write = null;
157         $error = null;
158         $active = array();
159
160         if (count($this->sockets) > 0) {
161             $number = stream_select($read, $write, $error, $sec, $usec);
162             if ($number > 0) {
163                 foreach ($read as $item) {
164                     $active[] = array_search($item, $this->sockets);
165                 }
166             }
167         }
168
169         return $active;
170     }
171
172     /**
173      * Sets the amount of time to wait for a new event each time the socket
174      * is polled.
175      *
176      * @param float $timeout Amount of time in seconds
177      *
178      * @return Phergie_Driver_Streams Provides a fluent interface
179      */
180     public function setTimeout($timeout)
181     {
182         $timeout = (float) $timeout;
183         if ($timeout) {
184             $this->timeout = $timeout;
185         }
186         return $this;
187     }
188
189     /**
190      * Returns the amount of time to wait for a new event each time the
191      * socket is polled.
192      *
193      * @return float Amount of time in seconds
194      */
195     public function getTimeout()
196     {
197         return $this->timeout;
198     }
199
200     /**
201      * Supporting method to parse event argument strings where the last
202      * argument may contain a colon.
203      *
204      * @param string $args  Argument string to parse
205      * @param int    $count Optional maximum number of arguments
206      *
207      * @return array Array of argument values
208      */
209     protected function parseArguments($args, $count = -1)
210     {
211         return preg_split('/ :?/S', $args, $count);
212     }
213
214     /**
215      * Listens for an event on the current connection.
216      *
217      * @return Phergie_Event_Interface|null Event instance if an event was
218      *         received, NULL otherwise
219      */
220     public function getEvent()
221     {
222         // Check for a new event on the current connection
223         $buffer = fgets($this->socket, 512);
224         if ($buffer === false) {
225             throw new Phergie_Driver_Exception(
226                 'Unable to read from socket',
227                 Phergie_Driver_Exception::ERR_CONNECTION_READ_FAILED
228             );
229         }
230
231         // If no new event was found, return NULL
232         if (empty($buffer)) {
233             return null;
234         }
235
236         // Strip the trailing newline from the buffer
237         $buffer = rtrim($buffer);
238
239         // If the event is from the server...
240         if (substr($buffer, 0, 1) != ':') {
241
242             // Parse the command and arguments
243             list($cmd, $args) = array_pad(explode(' ', $buffer, 2), 2, null);
244
245         } else {
246             // If the event could be from the server or a user...
247
248             // Parse the server hostname or user hostmask, command, and arguments
249             list($prefix, $cmd, $args)
250                 = array_pad(explode(' ', ltrim($buffer, ':'), 3), 3, null);
251             if (strpos($prefix, '@') !== false) {
252                 $hostmask = Phergie_Hostmask::fromString($prefix);
253             } else {
254                 $hostmask = new Phergie_Hostmask(null, null, $prefix);
255             }
256         }
257
258         // Parse the event arguments depending on the event type
259         $cmd = strtolower($cmd);
260         switch ($cmd) {
261         case 'names':
262         case 'nick':
263         case 'quit':
264         case 'ping':
265         case 'join':
266         case 'error':
267             $args = array(ltrim($args, ':'));
268             break;
269
270         case 'privmsg':
271         case 'notice':
272             $args = $this->parseArguments($args, 2);
273             list($source, $ctcp) = $args;
274             if (substr($ctcp, 0, 1) === "\001" && substr($ctcp, -1) === "\001") {
275                 $ctcp = substr($ctcp, 1, -1);
276                 $reply = ($cmd == 'notice');
277                 list($cmd, $args) = array_pad(explode(' ', $ctcp, 2), 2, null);
278                 $cmd = strtolower($cmd);
279                 switch ($cmd) {
280                 case 'version':
281                 case 'time':
282                 case 'finger':
283                     if ($reply) {
284                         $args = $ctcp;
285                     }
286                     break;
287                 case 'ping':
288                     if ($reply) {
289                         $cmd .= 'Response';
290                     } else {
291                         $cmd = 'ctcpPing';
292                     }
293                     break;
294                 case 'action':
295                     $args = array($source, $args);
296                     break;
297
298                 default:
299                     $cmd = 'ctcp';
300                     if ($reply) {
301                         $cmd .= 'Response';
302                     }
303                     $args = array($source, $args);
304                     break;
305                 }
306             }
307             break;
308
309         case 'oper':
310         case 'topic':
311         case 'mode':
312             $args = $this->parseArguments($args);
313             break;
314
315         case 'part':
316         case 'kill':
317         case 'invite':
318             $args = $this->parseArguments($args, 2);
319             break;
320
321         case 'kick':
322             $args = $this->parseArguments($args, 3);
323             break;
324
325         // Remove the target from responses
326         default:
327             $args = substr($args, strpos($args, ' ') + 1);
328             break;
329         }
330
331         // Create, populate, and return an event object
332         if (ctype_digit($cmd)) {
333             $event = new Phergie_Event_Response;
334             $event
335                 ->setCode($cmd)
336                 ->setDescription($args);
337         } else {
338             $event = new Phergie_Event_Request;
339             $event
340                 ->setType($cmd)
341                 ->setArguments($args);
342             if (isset($hostmask)) {
343                 $event->setHostmask($hostmask);
344             }
345         }
346         $event->setRawData($buffer);
347         return $event;
348     }
349
350     /**
351      * Initiates a connection with the server.
352      *
353      * @return void
354      */
355     public function doConnect()
356     {
357         // Listen for input indefinitely
358         set_time_limit(0);
359
360         // Get connection information
361         $connection = $this->getConnection();
362         $hostname = $connection->getHost();
363         $port = $connection->getPort();
364         $password = $connection->getPassword();
365         $username = $connection->getUsername();
366         $nick = $connection->getNick();
367         $realname = $connection->getRealname();
368         $transport = $connection->getTransport();
369
370         // Establish and configure the socket connection
371         $remote = $transport . '://' . $hostname . ':' . $port;
372         $this->socket = @stream_socket_client($remote, $errno, $errstr);
373         if (!$this->socket) {
374             throw new Phergie_Driver_Exception(
375                 'Unable to connect: socket error ' . $errno . ' ' . $errstr,
376                 Phergie_Driver_Exception::ERR_CONNECTION_ATTEMPT_FAILED
377             );
378         }
379
380         $seconds = (int) $this->timeout;
381         $microseconds = ($this->timeout - $seconds) * 1000000;
382         stream_set_timeout($this->socket, $seconds, $microseconds);
383
384         // Send the password if one is specified
385         if (!empty($password)) {
386             $this->send('PASS', $password);
387         }
388
389         // Send user information
390         $this->send(
391             'USER',
392             array(
393                 $username,
394                 $hostname,
395                 $hostname,
396                 $realname
397             )
398         );
399
400         $this->send('NICK', $nick);
401
402         // Add the socket handler to the internal array for socket handlers
403         $this->sockets[(string) $connection->getHostmask()] = $this->socket;
404     }
405
406     /**
407      * Terminates the connection with the server.
408      *
409      * @param string $reason Reason for connection termination (optional)
410      *
411      * @return void
412      */
413     public function doQuit($reason = null)
414     {
415         // Send a QUIT command to the server
416         $this->send('QUIT', $reason);
417
418         // Terminate the socket connection
419         fclose($this->socket);
420
421         // Remove the socket from the internal socket list
422         unset($this->sockets[(string) $this->getConnection()->getHostmask()]);
423     }
424
425     /**
426      * Joins a channel.
427      *
428      * @param string $channels Comma-delimited list of channels to join
429      * @param string $keys     Optional comma-delimited list of channel keys
430      *
431      * @return void
432      */
433     public function doJoin($channels, $keys = null)
434     {
435         $args = array($channels);
436
437         if (!empty($keys)) {
438             $args[] = $keys;
439         }
440
441         $this->send('JOIN', $args);
442     }
443
444     /**
445      * Leaves a channel.
446      *
447      * @param string $channels Comma-delimited list of channels to leave
448      *
449      * @return void
450      */
451     public function doPart($channels)
452     {
453         $this->send('PART', $channels);
454     }
455
456     /**
457      * Invites a user to an invite-only channel.
458      *
459      * @param string $nick    Nick of the user to invite
460      * @param string $channel Name of the channel
461      *
462      * @return void
463      */
464     public function doInvite($nick, $channel)
465     {
466         $this->send('INVITE', array($nick, $channel));
467     }
468
469     /**
470      * Obtains a list of nicks of usrs in currently joined channels.
471      *
472      * @param string $channels Comma-delimited list of one or more channels
473      *
474      * @return void
475      */
476     public function doNames($channels)
477     {
478         $this->send('NAMES', $channels);
479     }
480
481     /**
482      * Obtains a list of channel names and topics.
483      *
484      * @param string $channels Comma-delimited list of one or more channels
485      *                         to which the response should be restricted
486      *                         (optional)
487      *
488      * @return void
489      */
490     public function doList($channels = null)
491     {
492         $this->send('LIST', $channels);
493     }
494
495     /**
496      * Retrieves or changes a channel topic.
497      *
498      * @param string $channel Name of the channel
499      * @param string $topic   New topic to assign (optional)
500      *
501      * @return void
502      */
503     public function doTopic($channel, $topic = null)
504     {
505         $args = array($channel);
506
507         if (!empty($topic)) {
508             $args[] = $topic;
509         }
510
511         $this->send('TOPIC', $args);
512     }
513
514     /**
515      * Retrieves or changes a channel or user mode.
516      *
517      * @param string $target Channel name or user nick
518      * @param string $mode   New mode to assign (optional)
519      *
520      * @return void
521      */
522     public function doMode($target, $mode = null)
523     {
524         $args = array($target);
525
526         if (!empty($mode)) {
527             $args[] = $mode;
528         }
529
530         $this->send('MODE', $args);
531     }
532
533     /**
534      * Changes the client nick.
535      *
536      * @param string $nick New nick to assign
537      *
538      * @return void
539      */
540     public function doNick($nick)
541     {
542         $this->send('NICK', $nick);
543     }
544
545     /**
546      * Retrieves information about a nick.
547      *
548      * @param string $nick Nick
549      *
550      * @return void
551      */
552     public function doWhois($nick)
553     {
554         $this->send('WHOIS', $nick);
555     }
556
557     /**
558      * Sends a message to a nick or channel.
559      *
560      * @param string $target Channel name or user nick
561      * @param string $text   Text of the message to send
562      *
563      * @return void
564      */
565     public function doPrivmsg($target, $text)
566     {
567         $this->send('PRIVMSG', array($target, $text));
568     }
569
570     /**
571      * Sends a notice to a nick or channel.
572      *
573      * @param string $target Channel name or user nick
574      * @param string $text   Text of the notice to send
575      *
576      * @return void
577      */
578     public function doNotice($target, $text)
579     {
580         $this->send('NOTICE', array($target, $text));
581     }
582
583     /**
584      * Kicks a user from a channel.
585      *
586      * @param string $nick    Nick of the user
587      * @param string $channel Channel name
588      * @param string $reason  Reason for the kick (optional)
589      *
590      * @return void
591      */
592     public function doKick($nick, $channel, $reason = null)
593     {
594         $args = array($nick, $channel);
595
596         if (!empty($reason)) {
597             $args[] = $response;
598         }
599
600         $this->send('KICK', $args);
601     }
602
603     /**
604      * Responds to a server test of client responsiveness.
605      *
606      * @param string $daemon Daemon from which the original request originates
607      *
608      * @return void
609      */
610     public function doPong($daemon)
611     {
612         $this->send('PONG', $daemon);
613     }
614
615     /**
616      * Sends a CTCP ACTION (/me) command to a nick or channel.
617      *
618      * @param string $target Channel name or user nick
619      * @param string $text   Text of the action to perform
620      *
621      * @return void
622      */
623     public function doAction($target, $text)
624     {
625         $buffer = rtrim('ACTION ' . $text);
626
627         $this->doPrivmsg($target, chr(1) . $buffer . chr(1));
628     }
629
630     /**
631      * Sends a CTCP response to a user.
632      *
633      * @param string       $nick    User nick
634      * @param string       $command Command to send
635      * @param string|array $args    String or array of sequential arguments
636      *        (optional)
637      *
638      * @return void
639      */
640     protected function doCtcp($nick, $command, $args = null)
641     {
642         if (is_array($args)) {
643             $args = implode(' ', $args);
644         }
645
646         $buffer = rtrim(strtoupper($command) . ' ' . $args);
647
648         $this->doNotice($nick, chr(1) . $buffer . chr(1));
649     }
650
651     /**
652      * Sends a CTCP PING request or response (they are identical) to a user.
653      *
654      * @param string $nick User nick
655      * @param string $hash Hash to use in the handshake
656      *
657      * @return void
658      */
659     public function doPing($nick, $hash)
660     {
661         $this->doCtcp($nick, 'PING', $hash);
662     }
663
664     /**
665      * Sends a CTCP VERSION request or response to a user.
666      *
667      * @param string $nick    User nick
668      * @param string $version Version string to send for a response
669      *
670      * @return void
671      */
672     public function doVersion($nick, $version = null)
673     {
674         if ($version) {
675             $this->doCtcp($nick, 'VERSION', $version);
676         } else {
677             $this->doCtcp($nick, 'VERSION');
678         }
679     }
680
681     /**
682      * Sends a CTCP TIME request to a user.
683      *
684      * @param string $nick User nick
685      * @param string $time Time string to send for a response
686      *
687      * @return void
688      */
689     public function doTime($nick, $time = null)
690     {
691         if ($time) {
692             $this->doCtcp($nick, 'TIME', $time);
693         } else {
694             $this->doCtcp($nick, 'TIME');
695         }
696     }
697
698     /**
699      * Sends a CTCP FINGER request to a user.
700      *
701      * @param string $nick   User nick
702      * @param string $finger Finger string to send for a response
703      *
704      * @return void
705      */
706     public function doFinger($nick, $finger = null)
707     {
708         if ($finger) {
709             $this->doCtcp($nick, 'FINGER', $finger);
710         } else {
711             $this->doCtcp($nick, 'FINGER');
712         }
713     }
714
715     /**
716      * Sends a raw command to the server.
717      *
718      * @param string $command Command string to send
719      *
720      * @return void
721      */
722     public function doRaw($command)
723     {
724         $this->send('RAW', $command);
725     }
726 }