]> 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 the socket is still active
223         if (feof($this->socket)) {
224             throw new Phergie_Driver_Exception(
225                 'EOF detected on socket',
226                 Phergie_Driver_Exception::ERR_CONNECTION_READ_FAILED
227             );
228         }
229
230         // Check for a new event on the current connection
231         $buffer = fgets($this->socket, 512);
232
233         // If no new event was found, return NULL
234         if (empty($buffer)) {
235             return null;
236         }
237
238         // Strip the trailing newline from the buffer
239         $buffer = rtrim($buffer);
240
241         // If the event is from the server...
242         if (substr($buffer, 0, 1) != ':') {
243
244             // Parse the command and arguments
245             list($cmd, $args) = array_pad(explode(' ', $buffer, 2), 2, null);
246             $hostmask = new Phergie_Hostmask(null, null, $this->connection->getHost());
247
248         } else {
249             // If the event could be from the server or a user...
250
251             // Parse the server hostname or user hostmask, command, and arguments
252             list($prefix, $cmd, $args)
253                 = array_pad(explode(' ', ltrim($buffer, ':'), 3), 3, null);
254             if (strpos($prefix, '@') !== false) {
255                 $hostmask = Phergie_Hostmask::fromString($prefix);
256             } else {
257                 $hostmask = new Phergie_Hostmask(null, null, $prefix);
258             }
259         }
260
261         // Parse the event arguments depending on the event type
262         $cmd = strtolower($cmd);
263         switch ($cmd) {
264         case 'names':
265         case 'nick':
266         case 'quit':
267         case 'ping':
268         case 'join':
269         case 'error':
270             $args = array(ltrim($args, ':'));
271             break;
272
273         case 'privmsg':
274         case 'notice':
275             $args = $this->parseArguments($args, 2);
276             list($source, $ctcp) = $args;
277             if (substr($ctcp, 0, 1) === "\001" && substr($ctcp, -1) === "\001") {
278                 $ctcp = substr($ctcp, 1, -1);
279                 $reply = ($cmd == 'notice');
280                 list($cmd, $args) = array_pad(explode(' ', $ctcp, 2), 2, null);
281                 $cmd = strtolower($cmd);
282                 switch ($cmd) {
283                 case 'version':
284                 case 'time':
285                 case 'finger':
286                     if ($reply) {
287                         $args = $ctcp;
288                     }
289                     break;
290                 case 'ping':
291                     if ($reply) {
292                         $cmd .= 'Response';
293                     } else {
294                         $cmd = 'ctcpPing';
295                     }
296                     break;
297                 case 'action':
298                     $args = array($source, $args);
299                     break;
300
301                 default:
302                     $cmd = 'ctcp';
303                     if ($reply) {
304                         $cmd .= 'Response';
305                     }
306                     $args = array($source, $args);
307                     break;
308                 }
309             }
310             break;
311
312         case 'oper':
313         case 'topic':
314         case 'mode':
315             $args = $this->parseArguments($args);
316             break;
317
318         case 'part':
319         case 'kill':
320         case 'invite':
321             $args = $this->parseArguments($args, 2);
322             break;
323
324         case 'kick':
325             $args = $this->parseArguments($args, 3);
326             break;
327
328         // Remove the target from responses
329         default:
330             $args = substr($args, strpos($args, ' ') + 1);
331             break;
332         }
333
334         // Create, populate, and return an event object
335         if (ctype_digit($cmd)) {
336             $event = new Phergie_Event_Response;
337             $event
338                 ->setCode($cmd)
339                 ->setDescription($args);
340         } else {
341             $event = new Phergie_Event_Request;
342             $event
343                 ->setType($cmd)
344                 ->setArguments($args);
345             if (isset($hostmask)) {
346                 $event->setHostmask($hostmask);
347             }
348         }
349         $event->setRawData($buffer);
350         return $event;
351     }
352
353     /**
354      * Initiates a connection with the server.
355      *
356      * @return void
357      */
358     public function doConnect()
359     {
360         // Listen for input indefinitely
361         set_time_limit(0);
362
363         // Get connection information
364         $connection = $this->getConnection();
365         $hostname = $connection->getHost();
366         $port = $connection->getPort();
367         $password = $connection->getPassword();
368         $username = $connection->getUsername();
369         $nick = $connection->getNick();
370         $realname = $connection->getRealname();
371         $transport = $connection->getTransport();
372
373         // Establish and configure the socket connection
374         $remote = $transport . '://' . $hostname . ':' . $port;
375         $this->socket = @stream_socket_client($remote, $errno, $errstr);
376         if (!$this->socket) {
377             throw new Phergie_Driver_Exception(
378                 'Unable to connect: socket error ' . $errno . ' ' . $errstr,
379                 Phergie_Driver_Exception::ERR_CONNECTION_ATTEMPT_FAILED
380             );
381         }
382
383         $seconds = (int) $this->timeout;
384         $microseconds = ($this->timeout - $seconds) * 1000000;
385         stream_set_timeout($this->socket, $seconds, $microseconds);
386
387         // Send the password if one is specified
388         if (!empty($password)) {
389             $this->send('PASS', $password);
390         }
391
392         // Send user information
393         $this->send(
394             'USER',
395             array(
396                 $username,
397                 $hostname,
398                 $hostname,
399                 $realname
400             )
401         );
402
403         $this->send('NICK', $nick);
404
405         // Add the socket handler to the internal array for socket handlers
406         $this->sockets[(string) $connection->getHostmask()] = $this->socket;
407     }
408
409     /**
410      * Terminates the connection with the server.
411      *
412      * @param string $reason Reason for connection termination (optional)
413      *
414      * @return void
415      */
416     public function doQuit($reason = null)
417     {
418         // Send a QUIT command to the server
419         $this->send('QUIT', $reason);
420
421         // Terminate the socket connection
422         fclose($this->socket);
423
424         // Remove the socket from the internal socket list
425         unset($this->sockets[(string) $this->getConnection()->getHostmask()]);
426     }
427
428     /**
429      * Joins a channel.
430      *
431      * @param string $channels Comma-delimited list of channels to join
432      * @param string $keys     Optional comma-delimited list of channel keys
433      *
434      * @return void
435      */
436     public function doJoin($channels, $keys = null)
437     {
438         $args = array($channels);
439
440         if (!empty($keys)) {
441             $args[] = $keys;
442         }
443
444         $this->send('JOIN', $args);
445     }
446
447     /**
448      * Leaves a channel.
449      *
450      * @param string $channels Comma-delimited list of channels to leave
451      *
452      * @return void
453      */
454     public function doPart($channels)
455     {
456         $this->send('PART', $channels);
457     }
458
459     /**
460      * Invites a user to an invite-only channel.
461      *
462      * @param string $nick    Nick of the user to invite
463      * @param string $channel Name of the channel
464      *
465      * @return void
466      */
467     public function doInvite($nick, $channel)
468     {
469         $this->send('INVITE', array($nick, $channel));
470     }
471
472     /**
473      * Obtains a list of nicks of usrs in currently joined channels.
474      *
475      * @param string $channels Comma-delimited list of one or more channels
476      *
477      * @return void
478      */
479     public function doNames($channels)
480     {
481         $this->send('NAMES', $channels);
482     }
483
484     /**
485      * Obtains a list of channel names and topics.
486      *
487      * @param string $channels Comma-delimited list of one or more channels
488      *                         to which the response should be restricted
489      *                         (optional)
490      *
491      * @return void
492      */
493     public function doList($channels = null)
494     {
495         $this->send('LIST', $channels);
496     }
497
498     /**
499      * Retrieves or changes a channel topic.
500      *
501      * @param string $channel Name of the channel
502      * @param string $topic   New topic to assign (optional)
503      *
504      * @return void
505      */
506     public function doTopic($channel, $topic = null)
507     {
508         $args = array($channel);
509
510         if (!empty($topic)) {
511             $args[] = $topic;
512         }
513
514         $this->send('TOPIC', $args);
515     }
516
517     /**
518      * Retrieves or changes a channel or user mode.
519      *
520      * @param string $target Channel name or user nick
521      * @param string $mode   New mode to assign (optional)
522      *
523      * @return void
524      */
525     public function doMode($target, $mode = null)
526     {
527         $args = array($target);
528
529         if (!empty($mode)) {
530             $args[] = $mode;
531         }
532
533         $this->send('MODE', $args);
534     }
535
536     /**
537      * Changes the client nick.
538      *
539      * @param string $nick New nick to assign
540      *
541      * @return void
542      */
543     public function doNick($nick)
544     {
545         $this->send('NICK', $nick);
546     }
547
548     /**
549      * Retrieves information about a nick.
550      *
551      * @param string $nick Nick
552      *
553      * @return void
554      */
555     public function doWhois($nick)
556     {
557         $this->send('WHOIS', $nick);
558     }
559
560     /**
561      * Sends a message to a nick or channel.
562      *
563      * @param string $target Channel name or user nick
564      * @param string $text   Text of the message to send
565      *
566      * @return void
567      */
568     public function doPrivmsg($target, $text)
569     {
570         $this->send('PRIVMSG', array($target, $text));
571     }
572
573     /**
574      * Sends a notice to a nick or channel.
575      *
576      * @param string $target Channel name or user nick
577      * @param string $text   Text of the notice to send
578      *
579      * @return void
580      */
581     public function doNotice($target, $text)
582     {
583         $this->send('NOTICE', array($target, $text));
584     }
585
586     /**
587      * Kicks a user from a channel.
588      *
589      * @param string $nick    Nick of the user
590      * @param string $channel Channel name
591      * @param string $reason  Reason for the kick (optional)
592      *
593      * @return void
594      */
595     public function doKick($nick, $channel, $reason = null)
596     {
597         $args = array($nick, $channel);
598
599         if (!empty($reason)) {
600             $args[] = $response;
601         }
602
603         $this->send('KICK', $args);
604     }
605
606     /**
607      * Responds to a server test of client responsiveness.
608      *
609      * @param string $daemon Daemon from which the original request originates
610      *
611      * @return void
612      */
613     public function doPong($daemon)
614     {
615         $this->send('PONG', $daemon);
616     }
617
618     /**
619      * Sends a CTCP ACTION (/me) command to a nick or channel.
620      *
621      * @param string $target Channel name or user nick
622      * @param string $text   Text of the action to perform
623      *
624      * @return void
625      */
626     public function doAction($target, $text)
627     {
628         $buffer = rtrim('ACTION ' . $text);
629
630         $this->doPrivmsg($target, chr(1) . $buffer . chr(1));
631     }
632
633     /**
634      * Sends a CTCP response to a user.
635      *
636      * @param string       $nick    User nick
637      * @param string       $command Command to send
638      * @param string|array $args    String or array of sequential arguments
639      *        (optional)
640      *
641      * @return void
642      */
643     protected function doCtcp($nick, $command, $args = null)
644     {
645         if (is_array($args)) {
646             $args = implode(' ', $args);
647         }
648
649         $buffer = rtrim(strtoupper($command) . ' ' . $args);
650
651         $this->doNotice($nick, chr(1) . $buffer . chr(1));
652     }
653
654     /**
655      * Sends a CTCP PING request or response (they are identical) to a user.
656      *
657      * @param string $nick User nick
658      * @param string $hash Hash to use in the handshake
659      *
660      * @return void
661      */
662     public function doPing($nick, $hash)
663     {
664         $this->doCtcp($nick, 'PING', $hash);
665     }
666
667     /**
668      * Sends a CTCP VERSION request or response to a user.
669      *
670      * @param string $nick    User nick
671      * @param string $version Version string to send for a response
672      *
673      * @return void
674      */
675     public function doVersion($nick, $version = null)
676     {
677         if ($version) {
678             $this->doCtcp($nick, 'VERSION', $version);
679         } else {
680             $this->doCtcp($nick, 'VERSION');
681         }
682     }
683
684     /**
685      * Sends a CTCP TIME request to a user.
686      *
687      * @param string $nick User nick
688      * @param string $time Time string to send for a response
689      *
690      * @return void
691      */
692     public function doTime($nick, $time = null)
693     {
694         if ($time) {
695             $this->doCtcp($nick, 'TIME', $time);
696         } else {
697             $this->doCtcp($nick, 'TIME');
698         }
699     }
700
701     /**
702      * Sends a CTCP FINGER request to a user.
703      *
704      * @param string $nick   User nick
705      * @param string $finger Finger string to send for a response
706      *
707      * @return void
708      */
709     public function doFinger($nick, $finger = null)
710     {
711         if ($finger) {
712             $this->doCtcp($nick, 'FINGER', $finger);
713         } else {
714             $this->doCtcp($nick, 'FINGER');
715         }
716     }
717
718     /**
719      * Sends a raw command to the server.
720      *
721      * @param string $command Command string to send
722      *
723      * @return void
724      */
725     public function doRaw($command)
726     {
727         $this->send('RAW', $command);
728     }
729 }