]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Irc/lib/ircmanager.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / plugins / Irc / lib / ircmanager.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 /**
23  * IRC background connection manager for IRC-using queue handlers,
24  * allowing them to send outgoing messages on the right connection.
25  *
26  * Input is handled during socket select loop, Any incoming messages will be handled.
27  *
28  * In a multi-site queuedaemon.php run, one connection will be instantiated
29  * for each site being handled by the current process that has IRC enabled.
30  */
31 class IrcManager extends ImManager {
32     protected $conn = null;
33     protected $lastPing = null;
34     protected $messageWaiting = true;
35     protected $lastMessage = null;
36
37     protected $regChecks = array();
38     protected $regChecksLookup = array();
39
40     protected $connected = false;
41
42     /**
43      * Initialize connection to server.
44      *
45      * @return boolean true on success
46      */
47     public function start($master) {
48         if (parent::start($master)) {
49             $this->connect();
50             return true;
51         } else {
52             return false;
53         }
54     }
55
56     /**
57     * Return any open sockets that the run loop should listen
58     * for input on.
59     *
60     * @return array Array of socket resources
61     */
62     public function getSockets() {
63         $this->connect();
64         if ($this->conn) {
65             return $this->conn->getSockets();
66         } else {
67             return array();
68         }
69     }
70
71     /**
72      * Request a maximum timeout for listeners before the next idle period.
73      *
74      * @return integer Maximum timeout
75      */
76     public function timeout() {
77         if ($this->messageWaiting) {
78             return 1;
79         } else {
80             return $this->plugin->pinginterval;
81         }
82     }
83
84     /**
85      * Idle processing for io manager's execution loop.
86      *
87      * @return void
88      */
89     public function idle() {
90         // Send a ping if necessary
91         if (empty($this->lastPing) || time() - $this->lastPing > $this->plugin->pinginterval) {
92             $this->sendPing();
93         }
94
95         if ($this->connected) {
96             // Send a waiting message if appropriate
97             if ($this->messageWaiting && time() - $this->lastMessage > 1) {
98                 $wm = Irc_waiting_message::top();
99                 if ($wm === NULL) {
100                     $this->messageWaiting = false;
101                     return;
102                 }
103
104                 $data = unserialize($wm->data);
105                 $wm->incAttempts();
106
107                 if ($this->send_raw_message($data)) {
108                     $wm->delete();
109                 } else {
110                     if ($wm->attempts <= common_config('queue', 'max_retries')) {
111                         // Try again next idle
112                         $wm->releaseClaim();
113                     } else {
114                         // Exceeded the maximum number of retries
115                         $wm->delete();
116                     }
117                 }
118             }
119         }
120     }
121
122     /**
123      * Process IRC events that have come in over the wire.
124      *
125      * @param resource $socket Socket to handle input on
126      * @return void
127      */
128     public function handleInput($socket) {
129         common_debug('Servicing the IRC queue.');
130         $this->stats('irc_process');
131
132         try {
133             $this->conn->handleEvents();
134         } catch (Phergie_Driver_Exception $e) {
135             $this->connected = false;
136             $this->conn->reconnect();
137         }
138     }
139
140     /**
141     * Initiate connection
142     *
143     * @return void
144     */
145     public function connect() {
146         if (!$this->conn) {
147             $this->conn = new Phergie_StatusnetBot;
148
149             $config = new Phergie_Config;
150             $config->readArray(
151                 array(
152                     'connections' => array(
153                         array(
154                             'host' => $this->plugin->host,
155                             'port' => $this->plugin->port,
156                             'username' => $this->plugin->username,
157                             'realname' => $this->plugin->realname,
158                             'nick' => $this->plugin->nick,
159                             'password' => $this->plugin->password,
160                             'transport' => $this->plugin->transporttype,
161                             'encoding' => $this->plugin->encoding
162                         )
163                     ),
164
165                     'driver' => 'statusnet',
166
167                     'processor' => 'async',
168                     'processor.options' => array('sec' => 0, 'usec' => 0),
169
170                     'plugins' => array(
171                         'Pong',
172                         'NickServ',
173                         'AutoJoin',
174                         'Statusnet',
175                     ),
176
177                     'plugins.autoload' => true,
178
179                     // Uncomment to enable debugging output
180                     //'ui.enabled' => true,
181
182                     'nickserv.password' => $this->plugin->nickservpassword,
183                     'nickserv.identify_message' => $this->plugin->nickservidentifyregexp,
184
185                     'autojoin.channels' => $this->plugin->channels,
186
187                     'statusnet.messagecallback' => array($this, 'handle_irc_message'),
188                     'statusnet.regcallback' => array($this, 'handle_reg_response'),
189                     'statusnet.connectedcallback' => array($this, 'handle_connected'),
190                     'statusnet.unregregexp' => $this->plugin->unregregexp,
191                     'statusnet.regregexp' => $this->plugin->regregexp
192                 )
193             );
194
195             $this->conn->setConfig($config);
196             $this->conn->connect();
197             $this->lastPing = time();
198             $this->lastMessage = time();
199         }
200         return $this->conn;
201     }
202
203     /**
204     * Called via a callback when a message is received
205     * Passes it back to the queuing system
206     *
207     * @param array $data Data
208     * @return boolean
209     */
210     public function handle_irc_message($data) {
211         $this->plugin->enqueueIncomingRaw($data);
212         return true;
213     }
214
215     /**
216     * Called via a callback when NickServ responds to
217     * the bots query asking if a nick is registered
218     *
219     * @param array $data Data
220     * @return void
221     */
222     public function handle_reg_response($data) {
223         // Retrieve data
224         $screenname = $data['screenname'];
225         $nickdata = $this->regChecks[$screenname];
226         $usernick = $nickdata['user']->nickname;
227
228         if (isset($this->regChecksLookup[$usernick])) {
229             if ($data['registered']) {
230                 // Send message
231                 $this->plugin->sendConfirmationCode($screenname, $nickdata['code'], $nickdata['user'], true);
232             } else {
233                 // TRANS: Message given when using an unregistered IRC nickname.
234                 $this->plugin->sendMessage($screenname, _m('Your nickname is not registered so IRC connectivity cannot be enabled.'));
235
236                 $confirm = new Confirm_address();
237
238                 $confirm->user_id      = $user->id;
239                 $confirm->address_type = $this->plugin->transport;
240
241                 if ($confirm->find(true)) {
242                     $result = $confirm->delete();
243
244                     if (!$result) {
245                         common_log_db_error($confirm, 'DELETE', __FILE__);
246                         // TRANS: Server error thrown on database error when deleting IRC nickname confirmation.
247                         throw new ServerException(_m('Could not delete confirmation.'));
248                     }
249                 }
250             }
251
252             // Unset lookup value
253             unset($this->regChecksLookup[$usernick]);
254
255             // Unset data
256             unset($this->regChecks[$screename]);
257         }
258     }
259
260     /**
261     * Called when the connection is established
262     *
263     * @return void
264     */
265     public function handle_connected() {
266         $this->connected = true;
267     }
268
269     /**
270     * Enters a message into the database for sending when ready
271     *
272     * @param string $command Command
273     * @param array $args Arguments
274     * @return boolean
275     */
276     protected function enqueue_waiting_message($data) {
277         $wm = new Irc_waiting_message();
278
279         $wm->data       = serialize($data);
280         $wm->prioritise = $data['prioritise'];
281         $wm->attempts   = 0;
282         $wm->created    = common_sql_now();
283         $result         = $wm->insert();
284
285         if (!$result) {
286             common_log_db_error($wm, 'INSERT', __FILE__);
287             // TRANS: Server exception thrown when an IRC waiting queue item could not be added to the database.
288             throw new ServerException(_m('Database error inserting IRC waiting queue item.'));
289         }
290
291         return true;
292     }
293
294     /**
295      * Send a message using the daemon
296      *
297      * @param $data Message data
298      * @return boolean true on success
299      */
300     public function send_raw_message($data) {
301         $this->connect();
302         if (!$this->conn) {
303             return false;
304         }
305
306         if ($data['type'] != 'delayedmessage') {
307             if ($data['type'] != 'message') {
308                 // Nick checking
309                 $nickdata = $data['nickdata'];
310                 $usernick = $nickdata['user']->nickname;
311                 $screenname = $nickdata['screenname'];
312
313                 // Cancel any existing checks for this user
314                 if (isset($this->regChecksLookup[$usernick])) {
315                     unset($this->regChecks[$this->regChecksLookup[$usernick]]);
316                 }
317
318                 $this->regChecks[$screenname] = $nickdata;
319                 $this->regChecksLookup[$usernick] = $screenname;
320             }
321
322             // If there is a backlog or we need to wait, queue the message
323             if ($this->messageWaiting || time() - $this->lastMessage < 1) {
324                 $this->enqueue_waiting_message(
325                     array(
326                         'type' => 'delayedmessage',
327                         'prioritise' => $data['prioritise'],
328                         'data' => $data['data']
329                     )
330                 );
331                 $this->messageWaiting = true;
332                 return true;
333             }
334         }
335
336         try {
337             $this->conn->send($data['data']['command'], $data['data']['args']);
338         } catch (Phergie_Driver_Exception $e) {
339             $this->connected = false;
340             $this->conn->reconnect();
341             return false;
342         }
343
344         $this->lastMessage = time();
345         return true;
346     }
347
348     /**
349     * Sends a ping
350     *
351     * @return void
352     */
353     protected function sendPing() {
354         $this->lastPing = time();
355         $this->conn->send('PING', $this->lastPing);
356     }
357 }