Assembla home | Assembla project page
 

root/trunk/Phergie/Driver/Streams.php

Revision 292, 21.7 kB (checked in by tobias382, 4 weeks ago)

Fixed a bug with the previous commit caused beginning and ending CTCP characters to be stripped from outgoing commands

Line 
1 <?php
2 /**
3  * Provides a socket-based client driver.
4  */
5 class Phergie_Driver_Streams extends Phergie_Driver_Abstract
6 {
7     /**
8      * Names of commands that can be issued by callbacks ordered by
9      * priority of execution
10      *
11      * @var array
12      */
13     protected $priority = array(
14         'raw',
15         'pass',
16         'user',
17         'pong',
18         'notice',
19         'join',
20         'list',
21         'names',
22         'version',
23         'stats',
24         'links',
25         'time',
26         'trace',
27         'admin',
28         'info',
29         'who',
30         'whois',
31         'whowas',
32         'mode',
33         'privmsg',
34         'nick',
35         'topic',
36         'invite',
37         'kill',
38         'part'
39     );
40
41     /**
42      * Names of destructive commands that get queued up last
43      *
44      * @var array
45      */
46     protected $destuctive = array(
47         'nick',
48         'kill',
49         'part',
50         'quit'
51     );
52
53     /**
54      * Socket handler
55      *
56      * @var resource
57      */
58     protected $socket;
59
60     /**
61      * Flag to indicate whether or not the callbacks are currently being
62      * queued for execution rather than executed outright
63      *
64      * @var bool
65      */
66     protected $queueing;
67
68     /**
69      * Associative array mapping command names to queued sets of arguments
70      * from commands queued by callbacks
71      *
72      * @var array
73      */
74     protected $queue;
75
76     /**
77      * The time the bot started
78      *
79      * @var int
80      */
81     protected $startTime;
82
83     /**
84      * Constructor to initialize instance properties.
85      */
86     public function __construct()
87     {
88         $this->plugins = array();
89         $this->queueing = false;
90         $this->queue = array();
91     }
92
93     /**
94      * Returns the start time.
95      *
96      * @return int
97      */
98     public function getStartTime()
99     {
100         return $this->startTime;
101     }
102
103     /**
104      * Executes a continuous loop in which the client listens for events from
105      * the server and processes them until the connection is terminated.
106      *
107      * @return void
108      */
109     public function run()
110     {
111         $this->startTime = time();
112         $returnCode = $this->getIni('keepalive') ? self::RETURN_KEEPALIVE : self::RETURN_END;
113         $server = $this->getIni('server');
114         $port = $this->getIni('port');
115         if (!$port) {
116             $port = 6667;
117         }
118
119         $this->socket = @stream_socket_client('tcp://' . $server . ':' . $port, $errno, $errstr, 10);
120         if (!$this->socket) {
121             $this->debug(rtrim('Unable to connect to server: socket error ' . $errno . ' ' . $errstr));
122             return self::RETURN_END;
123         }
124         unset($port, $errno, $errstr);
125
126         stream_set_blocking($this->socket, false);
127
128         if ($this->getIni('timeout')) {
129             $timeout = $this->getIni('timeout') * 60;
130         } elseif ($this->getIni('keepalive')) {
131             $timeout = 600;
132         } else {
133             $timeout = false;
134         }
135         $lastPacket = time();
136
137         $password = $this->getIni('password');
138         if ($password) {
139             $this->send('PASS', array($password));
140         }
141         unset($password);
142
143         $params = array(
144             $this->getIni('username'),
145             $server,
146             $server,
147             $this->getIni('realname')
148         );
149
150         $this->send('USER', $params);
151         $this->doNick($this->getIni('nick'));
152         unset($server, $params);
153
154         if ($this->getIni('invisible')) {
155             $this->doMode($this->getIni('nick'), '+i');
156         }
157
158         // Run the onConnect handler since we successfully connected to the server
159         foreach($this->plugins as $plugin) {
160             $plugin->onConnect();
161         }
162
163         while (true) {
164             $this->queue = array();
165             $this->queueing = true;
166
167             // Clear the old event handler for every plugin
168             foreach($this->plugins as $plugin) {
169                 $plugin->setEvent(NULL);
170             }
171
172             $buffer = null;
173             while (empty($buffer)) {
174                 $buffer = fgets($this->socket, 512);
175
176                 // Check if we timed out
177                 if ($timeout !== false) {
178                     // Reset last packet timestamp if we received something
179                     if (!empty($buffer)) {
180                         $lastPacket = time();
181                     }
182                     // Timed out, exit
183                     if ($lastPacket < (time() - $timeout)) {
184                         $this->debug('Timed out');
185                         foreach($this->plugins as $plugin) {
186                             $plugin->onShutdown();
187                         }
188                         break 2;
189                     }
190                 }
191                 // onTick Handler
192                 if (empty($buffer)) {
193                     foreach($this->plugins as $plugin) {
194                         $plugin->onTick();
195                     }
196                     usleep(10000);
197                 }
198             }
199             if (!isset($buffer) || empty($buffer)) {
200                 continue;
201             }
202             $buffer = rtrim($buffer);
203             $this->debug('<- ' . $buffer);
204
205             if (substr($buffer, 0, 1) == ':') {
206                 list($prefix, $cmd, $args) = array_pad(explode(' ', substr($buffer, 1), 3), 3, null);
207                 $this->parseHostmask($prefix, $nick, $user, $host);
208             } else {
209                 list($cmd, $args) = array_pad(explode(' ', $buffer, 2), 2, null);
210             }
211
212             $cmd = strtolower($cmd);
213             switch ($cmd) {
214                 case 'names':
215                 case 'nick':
216                 case 'quit':
217                 case 'ping':
218                 case 'join':
219                 case 'error':
220                     $args = array(ltrim($args, ':'));
221                 break;
222
223                 case 'notice':
224                     $temp = preg_split('/ :?/', trim($args), 2);
225                     if (substr($temp[1], 0, 1) === chr(1) && substr($temp[1], -1) === chr(1)) {
226                         $ctcp = trim(substr($temp[1], 1, -1));
227                         list($cmd, $args) = array_pad(explode(' ', $ctcp, 2), 2, null);
228                         $cmd = strtolower($cmd);
229
230                         // Check for the type of Notice message and handle it accordingly
231                         if ($cmd == 'action') {
232                             // Return sender as source and the action as its first argument
233                             $args = array($nick, trim($args));
234                         } elseif ($cmd == 'ping' || $cmd == 'version' || $cmd == 'time') {
235                             // Return sender as source and the rest of the args as its first argument
236                             $cmd = $cmd . 'Reply';
237                             $args = array($nick, trim($args));
238                         } else {
239                             // Return sender as source and the ctcp as its first argument
240                             $cmd = 'ctcpReply';
241                             $args = array($nick, $ctcp);
242                         }
243                     } else {
244                         $args = preg_split('/ :?/', $args, 2);
245                     }
246                 break;
247
248                 case 'oper':
249                 case 'topic':
250                 case 'mode':
251                     $args = preg_split('/ :?/', $args);
252                 break;
253
254                 case 'part':
255                 case 'kill':
256                 case 'invite':
257                     $args = preg_split('/ :?/', $args, 2);
258                 break;
259
260                 case 'kick':
261                     $args = preg_split('/ :?/', $args, 3);
262                 break;
263
264                 case 'privmsg':
265                     $temp = preg_split('/ :?/', trim($args), 2);
266                     // Check to see if its a CTCP request, if so, handle it accordingly
267                     if (substr($temp[1], 0, 1) === chr(1) && substr($temp[1], -1) === chr(1)) {
268                         $ctcp = trim(substr($temp[1], 1, -1));
269                         list($cmd, $args) = array_pad(explode(' ', $ctcp, 2), 2, null);
270                         $cmd = strtolower($cmd);
271
272                         // Check for the type of CTCP message and handle it accordingly
273                         if ($cmd == 'action') {
274                             $botnick = $this->getIni('nick');
275                             // If sent within a channel, use the chanel as the source, else use the sender
276                             $source = (strtolower($temp[0]) == strtolower($botnick) ? $nick : $temp[0]);
277                             // Return channel/sender as source and the action as its first argument
278                             $args = array($source, trim($args));
279                         } elseif ($cmd == 'ping' && !empty($args)) {
280                             // Return nick of sender as source and the handshake as its first argument
281                             $args = array($nick, trim($args));
282                         } elseif (($cmd == 'version' || $cmd == 'time') && empty($args)) {
283                             // Return nick of sender as source and the ctcp as its first argument
284                             $args = array($nick, $ctcp);
285                         } else {
286                             // Return nick of sender as source and the ctcp as its first argument
287                             $cmd = 'ctcp';
288                             $args = array($nick, $ctcp);
289                         }
290                     } else {
291                         $args = preg_split('/ :?/', $args, 2);
292                     }
293                 break;
294             }
295
296             if (preg_match('/^[0-9]+$/', $cmd) > 0) {
297                 $event = new Phergie_Event_Response();
298                 $event->setCode($cmd);
299                 $event->setDescription($args);
300                 $event->setRawBuffer($buffer);
301             } else {
302                 $event = new Phergie_Event_Request();
303                 $event->setType($cmd);
304                 $event->setArguments($args);
305                 if (isset($user)) {
306                     $event->setHost($host);
307                     $event->setUsername($user);
308                     $event->setNick($nick);
309                 }
310                 $event->setRawBuffer($buffer);
311             }
312
313             $ignore = $this->hostmasksToRegex($this->getIni('ignore'));
314             $method = 'on' . ucfirst($cmd);
315             foreach($this->plugins as $plugin) {
316                 // Skip disabled plugins
317                 if (!$plugin->enabled) {
318                     continue;
319                 }
320                 $plugin->setEvent($event);
321                 // onRaw and onTick Handlers
322                 $plugin->onRaw();
323                 $plugin->onTick();
324                 if ($event instanceof Phergie_Event_Response) {
325                     $plugin->onResponse();
326                 // Skip events from ignored users and malformed packets
327                 } elseif (!empty($cmd) && method_exists($plugin, $method) &&
328                           !preg_match($ignore, $event->getHostmask())) {
329                     $plugin->{$method}();
330                 }
331             }
332
333             $this->queueing = false;
334             foreach($this->priority as $command) {
335                 if (isset($this->queue[$command])) {
336                     foreach($this->queue[$command] as $arguments) {
337                         $this->send($command, $arguments);
338                     }
339                 }
340             }
341             if (isset($this->queue['quit'])) {
342                 if (count($this->queue['quit'][0]) > 0) {
343                     $reason = $this->queue['quit'][0][0];
344                 } else {
345                     $reason = null;
346                 }
347                 foreach($this->plugins as $plugin) {
348                     $plugin->onShutdown();
349                 }
350                 if (isset($this->queue['quit'][0][1])) {
351                     $returnCode = ($this->queue['quit'][0][1] === true ? self::RETURN_RECONNECT : self::RETURN_END);
352                 }
353                 $this->doQuit($reason);
354                 break;
355             }
356
357             unset($this->queue, $event, $command, $arguments);
358         }
359
360         fclose($this->socket);
361
362         return $returnCode;
363     }
364
365     /**
366      * Sends a client command with accompanying arguments to the server.
367      *
368      * @param string $command Command to send
369      * @param array $arguments Ordered array of arguments to include
370      *                         (optional)
371      */
372     public function send($command, array $arguments = array(), $priority = false)
373     {
374         $command = strtolower($command);
375         if ($this->queueing && (in_array($command, $this->destuctive) xor $priority)) {
376             if (!isset($this->queue[$command])) {
377                 $this->queue[$command] = array();
378             }
379             $this->queue[$command][] = $arguments;
380         } else {
381             if ($command == Phergie_Event_Request::TYPE_RAW) {
382                 $buffer = (count($arguments) > 0 ? implode(' ', $arguments) : '');
383             } else {
384                 $buffer = strtoupper($command);
385                 if (count($arguments) > 0) {
386                     $end = count($arguments) - 1;
387                     $arguments[$end] = ':' . $arguments[$end];
388                     $buffer .= ' ' . implode(' ', $arguments);
389                 }
390             }
391             if (!empty($buffer)) {
392                 fwrite($this->socket, $this->filterCommand($buffer) . "\r\n");
393                 $this->debug('-> ' . $buffer);
394             }
395         }
396     }
397     
398     /**
399      * Filters the low-ASCII characters from the command
400      *
401      * @param string $buffer the buffer to filter
402      * @return string the filtered buffer
403      */
404     protected function filterCommand($buffer) {
405         static $search;
406         if (!$search) {
407             $search = range(chr(2), chr(31));
408             $search[] = chr(0);
409         }
410         return str_replace($search, '', $buffer);
411     }
412
413     /**
414      * Terminates the connection with the server.
415      *
416      * @param string $reason Reason for connection termination (optional)
417      * @param bool $reconnect if true, the bot will reconnect to the server
418      */
419     public function doQuit($reason = null, $reconnect = false, $priority = false)
420     {
421         if ($this->queueing) {
422             $this->send(Phergie_Event_Request::TYPE_QUIT, array($reason, $reconnect), $priority);
423         } else {
424             $this->send(Phergie_Event_Request::TYPE_QUIT, array($reason), $priority);
425         }
426     }
427
428     /**
429      * Joins a channel.
430      *
431      * @param string $channel Name of the channel to join
432      * @param string $keys Channel key if needed (optional)
433      */
434     public function doJoin($channel, $key = null, $priority = false)
435     {
436         $arguments = array($channel);
437
438         if ($key !== null) {
439             $arguments[] = $key;
440         }
441
442         $this->send(Phergie_Event_Request::TYPE_JOIN, $arguments, $priority);
443     }
444
445     /**
446      * Leaves a channel.
447      *
448      * @param string $channel Name of the channel to leave
449      */
450     public function doPart($channel, $reason = null, $priority = false)
451     {
452         $this->send(Phergie_Event_Request::TYPE_PART, array($channel, $reason), $priority);
453     }
454
455     /**
456      * Invites a user to an invite-only channel.
457      *
458      * @param string $nick Nick of the user to invite
459      * @param string $channel Name of the channel
460      */
461     public function doInvite($nick, $channel, $priority = false)
462     {
463         $this->send(Phergie_Event_Request::TYPE_INVITE, array($nick, $channel), $priority);
464     }
465
466     /**
467      * Obtains a list of nicks of usrs in currently joined channels.
468      *
469      * @param string $channels Comma-delimited list of one or more channels
470      */
471     public function doNa