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 // Require an open socket connection to continue
71 if (empty($this->socket)) {
72 throw new Phergie_Driver_Exception(
73 'doConnect() must be called first',
74 Phergie_Driver_Exception::ERR_NO_INITIATED_CONNECTION
79 $buffer = strtoupper($command);
84 // Apply formatting if arguments are passed in as an array
85 if (is_array($args)) {
86 $end = count($args) - 1;
87 $args[$end] = ':' . $args[$end];
88 $args = implode(' ', $args);
91 $buffer .= ' ' . $args;
94 // Transmit the command over the socket connection
95 fwrite($this->socket, $buffer . "\r\n");
97 // Return the command string that was transmitted
102 * Overrides the parent class to set the currently active socket handler
103 * when the active connection is changed.
105 * @param Phergie_Connection $connection Active connection
107 * @return Phergie_Driver_Streams Provides a fluent interface
109 public function setConnection(Phergie_Connection $connection)
111 // Set the active socket handler
112 $hostmask = (string) $connection->getHostmask();
113 if (!empty($this->sockets[$hostmask])) {
114 $this->socket = $this->sockets[$hostmask];
117 // Set the active connection
118 return parent::setConnection($connection);
122 * Returns a list of hostmasks corresponding to sockets with data to read.
124 * @param int $sec Length of time to wait for new data (seconds)
125 * @param int $usec Length of time to wait for new data (microseconds)
127 * @return array List of hostmasks or an empty array if none were found
128 * to have data to read
130 public function getActiveReadSockets($sec = 0, $usec = 200000)
132 $read = $this->sockets;
137 if (count($this->sockets) > 0) {
138 $number = stream_select($read, $write, $error, $sec, $usec);
140 foreach ($read as $item) {
141 $active[] = array_search($item, $this->sockets);
150 * Sets the amount of time to wait for a new event each time the socket
153 * @param float $timeout Amount of time in seconds
155 * @return Phergie_Driver_Streams Provides a fluent interface
157 public function setTimeout($timeout)
159 $timeout = (float) $timeout;
161 $this->timeout = $timeout;
167 * Returns the amount of time to wait for a new event each time the
170 * @return float Amount of time in seconds
172 public function getTimeout()
174 return $this->timeout;
178 * Supporting method to parse event argument strings where the last
179 * argument may contain a colon.
181 * @param string $args Argument string to parse
182 * @param int $count Optional maximum number of arguments
184 * @return array Array of argument values
186 protected function parseArguments($args, $count = -1)
188 return preg_split('/ :?/S', $args, $count);
192 * Listens for an event on the current connection.
194 * @return Phergie_Event_Interface|null Event instance if an event was
195 * received, NULL otherwise
197 public function getEvent()
199 // Check for a new event on the current connection
200 $buffer = fgets($this->socket, 512);
202 // If no new event was found, return NULL
203 if (empty($buffer)) {
207 // Strip the trailing newline from the buffer
208 $buffer = rtrim($buffer);
210 // If the event is from the server...
211 if (substr($buffer, 0, 1) != ':') {
213 // Parse the command and arguments
214 list($cmd, $args) = array_pad(explode(' ', $buffer, 2), 2, null);
217 // If the event could be from the server or a user...
219 // Parse the server hostname or user hostmask, command, and arguments
220 list($prefix, $cmd, $args)
221 = array_pad(explode(' ', ltrim($buffer, ':'), 3), 3, null);
222 if (strpos($prefix, '@') !== false) {
223 $hostmask = Phergie_Hostmask::fromString($prefix);
227 // Parse the event arguments depending on the event type
228 $cmd = strtolower($cmd);
236 $args = array(ltrim($args, ':'));
241 $ctcp = substr(strstr($args, ':'), 1);
242 if (substr($ctcp, 0, 1) === "\x01" && substr($ctcp, -1) === "\x01") {
243 $ctcp = substr($ctcp, 1, -1);
244 $reply = ($cmd == 'notice');
245 list($cmd, $args) = array_pad(explode(' ', $ctcp, 2), 2, null);
246 $cmd = strtolower($cmd);
263 $args = array($this->getConnection()->getNick(), $args);
271 $args = array($this->getConnection()->getNick(), $ctcp);
275 $args = $this->parseArguments($args, 2);
282 $args = $this->parseArguments($args);
288 $args = $this->parseArguments($args, 2);
292 $args = $this->parseArguments($args, 3);
295 // Remove the target from responses
297 $args = substr($args, strpos($args, ' ') + 1);
301 // Create, populate, and return an event object
302 if (ctype_digit($cmd)) {
303 $event = new Phergie_Event_Response;
306 ->setDescription($args);
308 $event = new Phergie_Event_Request;
311 ->setArguments($args);
312 if (isset($hostmask)) {
313 $event->setHostmask($hostmask);
316 $event->setRawData($buffer);
321 * Initiates a connection with the server.
325 public function doConnect()
327 // Listen for input indefinitely
330 // Get connection information
331 $connection = $this->getConnection();
332 $hostname = $connection->getHost();
333 $port = $connection->getPort();
334 $password = $connection->getPassword();
335 $username = $connection->getUsername();
336 $nick = $connection->getNick();
337 $realname = $connection->getRealname();
338 $transport = $connection->getTransport();
340 // Establish and configure the socket connection
341 $remote = $transport . '://' . $hostname . ':' . $port;
342 $this->socket = @stream_socket_client($remote, $errno, $errstr);
343 if (!$this->socket) {
344 throw new Phergie_Driver_Exception(
345 'Unable to connect: socket error ' . $errno . ' ' . $errstr,
346 Phergie_Driver_Exception::ERR_CONNECTION_ATTEMPT_FAILED
350 $seconds = (int) $this->timeout;
351 $microseconds = ($this->timeout - $seconds) * 1000000;
352 stream_set_timeout($this->socket, $seconds, $microseconds);
354 // Send the password if one is specified
355 if (!empty($password)) {
356 $this->send('PASS', $password);
359 // Send user information
370 $this->send('NICK', $nick);
372 // Add the socket handler to the internal array for socket handlers
373 $this->sockets[(string) $connection->getHostmask()] = $this->socket;
377 * Terminates the connection with the server.
379 * @param string $reason Reason for connection termination (optional)
383 public function doQuit($reason = null)
385 // Send a QUIT command to the server
386 $this->send('QUIT', $reason);
388 // Terminate the socket connection
389 fclose($this->socket);
391 // Remove the socket from the internal socket list
392 unset($this->sockets[(string) $this->getConnection()->getHostmask()]);
398 * @param string $channels Comma-delimited list of channels to join
399 * @param string $keys Optional comma-delimited list of channel keys
403 public function doJoin($channels, $keys = null)
405 $args = array($channels);
411 $this->send('JOIN', $args);
417 * @param string $channels Comma-delimited list of channels to leave
421 public function doPart($channels)
423 $this->send('PART', $channels);
427 * Invites a user to an invite-only channel.
429 * @param string $nick Nick of the user to invite
430 * @param string $channel Name of the channel
434 public function doInvite($nick, $channel)
436 $this->send('INVITE', array($nick, $channel));
440 * Obtains a list of nicks of usrs in currently joined channels.
442 * @param string $channels Comma-delimited list of one or more channels
446 public function doNames($channels)
448 $this->send('NAMES', $channels);
452 * Obtains a list of channel names and topics.
454 * @param string $channels Comma-delimited list of one or more channels
455 * to which the response should be restricted
460 public function doList($channels = null)
462 $this->send('LIST', $channels);
466 * Retrieves or changes a channel topic.
468 * @param string $channel Name of the channel
469 * @param string $topic New topic to assign (optional)
473 public function doTopic($channel, $topic = null)
475 $args = array($channel);
477 if (!empty($topic)) {
481 $this->send('TOPIC', $args);
485 * Retrieves or changes a channel or user mode.
487 * @param string $target Channel name or user nick
488 * @param string $mode New mode to assign (optional)
492 public function doMode($target, $mode = null)
494 $args = array($target);
500 $this->send('MODE', $args);
504 * Changes the client nick.
506 * @param string $nick New nick to assign
510 public function doNick($nick)
512 $this->send('NICK', $nick);
516 * Retrieves information about a nick.
518 * @param string $nick Nick
522 public function doWhois($nick)
524 $this->send('WHOIS', $nick);
528 * Sends a message to a nick or channel.
530 * @param string $target Channel name or user nick
531 * @param string $text Text of the message to send
535 public function doPrivmsg($target, $text)
537 $this->send('PRIVMSG', array($target, $text));
541 * Sends a notice to a nick or channel.
543 * @param string $target Channel name or user nick
544 * @param string $text Text of the notice to send
548 public function doNotice($target, $text)
550 $this->send('NOTICE', array($target, $text));
554 * Kicks a user from a channel.
556 * @param string $nick Nick of the user
557 * @param string $channel Channel name
558 * @param string $reason Reason for the kick (optional)
562 public function doKick($nick, $channel, $reason = null)
564 $args = array($nick, $channel);
566 if (!empty($reason)) {
570 $this->send('KICK', $args);
574 * Responds to a server test of client responsiveness.
576 * @param string $daemon Daemon from which the original request originates
580 public function doPong($daemon)
582 $this->send('PONG', $daemon);
586 * Sends a CTCP ACTION (/me) command to a nick or channel.
588 * @param string $target Channel name or user nick
589 * @param string $text Text of the action to perform
593 public function doAction($target, $text)
595 $buffer = rtrim('ACTION ' . $text);
597 $this->doPrivmsg($target, chr(1) . $buffer . chr(1));
601 * Sends a CTCP response to a user.
603 * @param string $nick User nick
604 * @param string $command Command to send
605 * @param string|array $args String or array of sequential arguments
610 protected function doCtcp($nick, $command, $args = null)
612 if (is_array($args)) {
613 $args = implode(' ', $args);
616 $buffer = rtrim(strtoupper($command) . ' ' . $args);
618 $this->doNotice($nick, chr(1) . $buffer . chr(1));
622 * Sends a CTCP PING request or response (they are identical) to a user.
624 * @param string $nick User nick
625 * @param string $hash Hash to use in the handshake
629 public function doPing($nick, $hash)
631 $this->doCtcp($nick, 'PING', $hash);
635 * Sends a CTCP VERSION request or response to a user.
637 * @param string $nick User nick
638 * @param string $version Version string to send for a response
642 public function doVersion($nick, $version = null)
645 $this->doCtcp($nick, 'VERSION', $version);
647 $this->doCtcp($nick, 'VERSION');
652 * Sends a CTCP TIME request to a user.
654 * @param string $nick User nick
655 * @param string $time Time string to send for a response
659 public function doTime($nick, $time = null)
662 $this->doCtcp($nick, 'TIME', $time);
664 $this->doCtcp($nick, 'TIME');
669 * Sends a CTCP FINGER request to a user.
671 * @param string $nick User nick
672 * @param string $finger Finger string to send for a response
676 public function doFinger($nick, $finger = null)
679 $this->doCtcp($nick, 'FINGER', $finger);
681 $this->doCtcp($nick, 'FINGER');
686 * Sends a raw command to the server.
688 * @param string $command Command string to send
692 public function doRaw($command)
694 $this->send('RAW', $command);