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