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