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
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
23 * Driver that uses the sockets wrapper of the streams extension for
24 * communicating with the server and handles formatting and parsing of
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
33 class Phergie_Driver_Streams extends Phergie_Driver_Abstract
40 protected $sockets = array();
43 * Reference to the currently active socket handler
50 * Amount of time in seconds to wait to receive an event each time the
55 protected $timeout = 0.1;
58 * Handles construction of command strings and their transmission to the
61 * @param string $command Command to send
62 * @param string|array $args Optional string or array of sequential
65 * @return string Command string that was sent
66 * @throws Phergie_Driver_Exception
68 protected function send($command, $args = '')
70 $connection = $this->getConnection();
71 $encoding = $connection->getEncoding();
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
82 $buffer = strtoupper($command);
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);
96 $buffer .= ' ' . $args;
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);
105 $written += (int) fwrite($this->socket, $temp);
106 if ($written < $length) {
107 $temp = substr($temp, $written);
109 if ($attempts == 3) {
110 throw new Phergie_Driver_Exception(
111 'Unable to write to socket',
112 Phergie_Driver_Exception::ERR_CONNECTION_WRITE_FAILED
120 // Return the command string that was transmitted
125 * Overrides the parent class to set the currently active socket handler
126 * when the active connection is changed.
128 * @param Phergie_Connection $connection Active connection
130 * @return Phergie_Driver_Streams Provides a fluent interface
132 public function setConnection(Phergie_Connection $connection)
134 // Set the active socket handler
135 $hostmask = (string) $connection->getHostmask();
136 if (!empty($this->sockets[$hostmask])) {
137 $this->socket = $this->sockets[$hostmask];
140 // Set the active connection
141 return parent::setConnection($connection);
145 * Returns a list of hostmasks corresponding to sockets with data to read.
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)
150 * @return array List of hostmasks or an empty array if none were found
151 * to have data to read
153 public function getActiveReadSockets($sec = 0, $usec = 200000)
155 $read = $this->sockets;
160 if (count($this->sockets) > 0) {
161 $number = stream_select($read, $write, $error, $sec, $usec);
163 foreach ($read as $item) {
164 $active[] = array_search($item, $this->sockets);
173 * Sets the amount of time to wait for a new event each time the socket
176 * @param float $timeout Amount of time in seconds
178 * @return Phergie_Driver_Streams Provides a fluent interface
180 public function setTimeout($timeout)
182 $timeout = (float) $timeout;
184 $this->timeout = $timeout;
190 * Returns the amount of time to wait for a new event each time the
193 * @return float Amount of time in seconds
195 public function getTimeout()
197 return $this->timeout;
201 * Supporting method to parse event argument strings where the last
202 * argument may contain a colon.
204 * @param string $args Argument string to parse
205 * @param int $count Optional maximum number of arguments
207 * @return array Array of argument values
209 protected function parseArguments($args, $count = -1)
211 return preg_split('/ :?/S', $args, $count);
215 * Listens for an event on the current connection.
217 * @return Phergie_Event_Interface|null Event instance if an event was
218 * received, NULL otherwise
220 public function getEvent()
222 // Check for a new event on the current connection
223 $buffer = fgets($this->socket, 512);
225 // If no new event was found, return NULL
226 if (empty($buffer)) {
230 // Strip the trailing newline from the buffer
231 $buffer = rtrim($buffer);
233 // If the event is from the server...
234 if (substr($buffer, 0, 1) != ':') {
236 // Parse the command and arguments
237 list($cmd, $args) = array_pad(explode(' ', $buffer, 2), 2, null);
240 // If the event could be from the server or a user...
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);
250 // Parse the event arguments depending on the event type
251 $cmd = strtolower($cmd);
259 $args = array(ltrim($args, ':'));
264 $ctcp = substr(strstr($args, ':'), 1);
265 if (substr($ctcp, 0, 1) === "\x01" && substr($ctcp, -1) === "\x01") {
266 $ctcp = substr($ctcp, 1, -1);
267 $reply = ($cmd == 'notice');
268 list($cmd, $args) = array_pad(explode(' ', $ctcp, 2), 2, null);
269 $cmd = strtolower($cmd);
286 $args = array($this->getConnection()->getNick(), $args);
294 $args = array($this->getConnection()->getNick(), $ctcp);
298 $args = $this->parseArguments($args, 2);
305 $args = $this->parseArguments($args);
311 $args = $this->parseArguments($args, 2);
315 $args = $this->parseArguments($args, 3);
318 // Remove the target from responses
320 $args = substr($args, strpos($args, ' ') + 1);
324 // Create, populate, and return an event object
325 if (ctype_digit($cmd)) {
326 $event = new Phergie_Event_Response;
329 ->setDescription($args);
331 $event = new Phergie_Event_Request;
334 ->setArguments($args);
335 if (isset($hostmask)) {
336 $event->setHostmask($hostmask);
339 $event->setRawData($buffer);
344 * Initiates a connection with the server.
348 public function doConnect()
350 // Listen for input indefinitely
353 // Get connection information
354 $connection = $this->getConnection();
355 $hostname = $connection->getHost();
356 $port = $connection->getPort();
357 $password = $connection->getPassword();
358 $username = $connection->getUsername();
359 $nick = $connection->getNick();
360 $realname = $connection->getRealname();
361 $transport = $connection->getTransport();
363 // Establish and configure the socket connection
364 $remote = $transport . '://' . $hostname . ':' . $port;
365 $this->socket = @stream_socket_client($remote, $errno, $errstr);
366 if (!$this->socket) {
367 throw new Phergie_Driver_Exception(
368 'Unable to connect: socket error ' . $errno . ' ' . $errstr,
369 Phergie_Driver_Exception::ERR_CONNECTION_ATTEMPT_FAILED
373 $seconds = (int) $this->timeout;
374 $microseconds = ($this->timeout - $seconds) * 1000000;
375 stream_set_timeout($this->socket, $seconds, $microseconds);
377 // Send the password if one is specified
378 if (!empty($password)) {
379 $this->send('PASS', $password);
382 // Send user information
393 $this->send('NICK', $nick);
395 // Add the socket handler to the internal array for socket handlers
396 $this->sockets[(string) $connection->getHostmask()] = $this->socket;
400 * Terminates the connection with the server.
402 * @param string $reason Reason for connection termination (optional)
406 public function doQuit($reason = null)
408 // Send a QUIT command to the server
409 $this->send('QUIT', $reason);
411 // Terminate the socket connection
412 fclose($this->socket);
414 // Remove the socket from the internal socket list
415 unset($this->sockets[(string) $this->getConnection()->getHostmask()]);
421 * @param string $channels Comma-delimited list of channels to join
422 * @param string $keys Optional comma-delimited list of channel keys
426 public function doJoin($channels, $keys = null)
428 $args = array($channels);
434 $this->send('JOIN', $args);
440 * @param string $channels Comma-delimited list of channels to leave
444 public function doPart($channels)
446 $this->send('PART', $channels);
450 * Invites a user to an invite-only channel.
452 * @param string $nick Nick of the user to invite
453 * @param string $channel Name of the channel
457 public function doInvite($nick, $channel)
459 $this->send('INVITE', array($nick, $channel));
463 * Obtains a list of nicks of usrs in currently joined channels.
465 * @param string $channels Comma-delimited list of one or more channels
469 public function doNames($channels)
471 $this->send('NAMES', $channels);
475 * Obtains a list of channel names and topics.
477 * @param string $channels Comma-delimited list of one or more channels
478 * to which the response should be restricted
483 public function doList($channels = null)
485 $this->send('LIST', $channels);
489 * Retrieves or changes a channel topic.
491 * @param string $channel Name of the channel
492 * @param string $topic New topic to assign (optional)
496 public function doTopic($channel, $topic = null)
498 $args = array($channel);
500 if (!empty($topic)) {
504 $this->send('TOPIC', $args);
508 * Retrieves or changes a channel or user mode.
510 * @param string $target Channel name or user nick
511 * @param string $mode New mode to assign (optional)
515 public function doMode($target, $mode = null)
517 $args = array($target);
523 $this->send('MODE', $args);
527 * Changes the client nick.
529 * @param string $nick New nick to assign
533 public function doNick($nick)
535 $this->send('NICK', $nick);
539 * Retrieves information about a nick.
541 * @param string $nick Nick
545 public function doWhois($nick)
547 $this->send('WHOIS', $nick);
551 * Sends a message to a nick or channel.
553 * @param string $target Channel name or user nick
554 * @param string $text Text of the message to send
558 public function doPrivmsg($target, $text)
560 $this->send('PRIVMSG', array($target, $text));
564 * Sends a notice to a nick or channel.
566 * @param string $target Channel name or user nick
567 * @param string $text Text of the notice to send
571 public function doNotice($target, $text)
573 $this->send('NOTICE', array($target, $text));
577 * Kicks a user from a channel.
579 * @param string $nick Nick of the user
580 * @param string $channel Channel name
581 * @param string $reason Reason for the kick (optional)
585 public function doKick($nick, $channel, $reason = null)
587 $args = array($nick, $channel);
589 if (!empty($reason)) {
593 $this->send('KICK', $args);
597 * Responds to a server test of client responsiveness.
599 * @param string $daemon Daemon from which the original request originates
603 public function doPong($daemon)
605 $this->send('PONG', $daemon);
609 * Sends a CTCP ACTION (/me) command to a nick or channel.
611 * @param string $target Channel name or user nick
612 * @param string $text Text of the action to perform
616 public function doAction($target, $text)
618 $buffer = rtrim('ACTION ' . $text);
620 $this->doPrivmsg($target, chr(1) . $buffer . chr(1));
624 * Sends a CTCP response to a user.
626 * @param string $nick User nick
627 * @param string $command Command to send
628 * @param string|array $args String or array of sequential arguments
633 protected function doCtcp($nick, $command, $args = null)
635 if (is_array($args)) {
636 $args = implode(' ', $args);
639 $buffer = rtrim(strtoupper($command) . ' ' . $args);
641 $this->doNotice($nick, chr(1) . $buffer . chr(1));
645 * Sends a CTCP PING request or response (they are identical) to a user.
647 * @param string $nick User nick
648 * @param string $hash Hash to use in the handshake
652 public function doPing($nick, $hash)
654 $this->doCtcp($nick, 'PING', $hash);
658 * Sends a CTCP VERSION request or response to a user.
660 * @param string $nick User nick
661 * @param string $version Version string to send for a response
665 public function doVersion($nick, $version = null)
668 $this->doCtcp($nick, 'VERSION', $version);
670 $this->doCtcp($nick, 'VERSION');
675 * Sends a CTCP TIME request to a user.
677 * @param string $nick User nick
678 * @param string $time Time string to send for a response
682 public function doTime($nick, $time = null)
685 $this->doCtcp($nick, 'TIME', $time);
687 $this->doCtcp($nick, 'TIME');
692 * Sends a CTCP FINGER request to a user.
694 * @param string $nick User nick
695 * @param string $finger Finger string to send for a response
699 public function doFinger($nick, $finger = null)
702 $this->doCtcp($nick, 'FINGER', $finger);
704 $this->doCtcp($nick, 'FINGER');
709 * Sends a raw command to the server.
711 * @param string $command Command string to send
715 public function doRaw($command)
717 $this->send('RAW', $command);