]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Irc/ircmanager.php
Merge branch '1.0.x' into schema-x
[quix0rs-gnu-social.git] / plugins / Irc / 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
32 class IrcManager extends ImManager {
33     protected $conn = null;
34     protected $lastPing = null;
35     protected $messageWaiting = true;
36     protected $lastMessage = null;
37
38     protected $regChecks = array();
39     protected $regChecksLookup = array();
40
41     protected $connected = false;
42
43     /**
44      * Initialize connection to server.
45      *
46      * @return boolean true on success
47      */
48     public function start($master) {
49         if (parent::start($master)) {
50             $this->connect();
51             return true;
52         } else {
53             return false;
54         }
55     }
56
57     /**
58     * Return any open sockets that the run loop should listen
59     * for input on.
60     *
61     * @return array Array of socket resources
62     */
63     public function getSockets() {
64         $this->connect();
65         if ($this->conn) {
66             return $this->conn->getSockets();
67         } else {
68             return array();
69         }
70     }
71
72     /**
73      * Request a maximum timeout for listeners before the next idle period.
74      *
75      * @return integer Maximum timeout
76      */
77     public function timeout() {
78         if ($this->messageWaiting) {
79             return 1;
80         } else {
81             return $this->plugin->pinginterval;
82         }
83     }
84
85     /**
86      * Idle processing for io manager's execution loop.
87      *
88      * @return void
89      */
90     public function idle() {
91         // Send a ping if necessary
92         if (empty($this->lastPing) || time() - $this->lastPing > $this->plugin->pinginterval) {
93             $this->sendPing();
94         }
95
96         if ($this->connected) {
97             // Send a waiting message if appropriate
98             if ($this->messageWaiting && time() - $this->lastMessage > 1) {
99                 $wm = Irc_waiting_message::top();
100                 if ($wm === NULL) {
101                     $this->messageWaiting = false;
102                     return;
103                 }
104
105                 $data = unserialize($wm->data);
106                 $wm->incAttempts();
107
108                 if ($this->send_raw_message($data)) {
109                     $wm->delete();
110                 } else {
111                     if ($wm->attempts <= common_config('queue', 'max_retries')) {
112                         // Try again next idle
113                         $wm->releaseClaim();
114                     } else {
115                         // Exceeded the maximum number of retries
116                         $wm->delete();
117                     }
118                 }
119             }
120         }
121     }
122
123     /**
124      * Process IRC events that have come in over the wire.
125      *
126      * @param resource $socket Socket to handle input on
127      * @return void
128      */
129     public function handleInput($socket) {
130         common_log(LOG_DEBUG, 'Servicing the IRC queue.');
131         $this->stats('irc_process');
132
133         try {
134             $this->conn->handleEvents();
135         } catch (Phergie_Driver_Exception $e) {
136             $this->connected = false;
137             $this->conn->reconnect();
138         }
139     }
140
141     /**
142     * Initiate connection
143     *
144     * @return void
145     */
146     public function connect() {
147         if (!$this->conn) {
148             $this->conn = new Phergie_StatusnetBot;
149
150             $config = new Phergie_Config;
151             $config->readArray(
152                 array(
153                     'connections' => array(
154                         array(
155                             'host' => $this->plugin->host,
156                             'port' => $this->plugin->port,
157                             'username' => $this->plugin->username,
158                             'realname' => $this->plugin->realname,
159                             'nick' => $this->plugin->nick,
160                             'password' => $this->plugin->password,
161                             'transport' => $this->plugin->transporttype,
162                             'encoding' => $this->plugin->encoding
163                         )
164                     ),
165
166                     'driver' => 'statusnet',
167
168                     'processor' => 'async',
169                     'processor.options' => array('sec' => 0, 'usec' => 0),
170
171                     'plugins' => array(
172                         'Pong',
173                         'NickServ',
174                         'AutoJoin',
175                         'Statusnet',
176                     ),
177
178                     'plugins.autoload' => true,
179
180                     // Uncomment to enable debugging output
181                     //'ui.enabled' => true,
182
183                     'nickserv.password' => $this->plugin->nickservpassword,
184                     'nickserv.identify_message' => $this->plugin->nickservidentifyregexp,
185
186                     'autojoin.channels' => $this->plugin->channels,
187
188                     'statusnet.messagecallback' => array($this, 'handle_irc_message'),
189                     'statusnet.regcallback' => array($this, 'handle_reg_response'),
190                     'statusnet.connectedcallback' => array($this, 'handle_connected'),
191                     'statusnet.unregregexp' => $this->plugin->unregregexp,
192                     'statusnet.regregexp' => $this->plugin->regregexp
193                 )
194             );
195
196             $this->conn->setConfig($config);
197             $this->conn->connect();
198             $this->lastPing = time();
199             $this->lastMessage = time();
200         }
201         return $this->conn;
202     }
203
204     /**
205     * Called via a callback when a message is received
206     * Passes it back to the queuing system
207     *
208     * @param array $data Data
209     * @return boolean
210     */
211     public function handle_irc_message($data) {
212         $this->plugin->enqueueIncomingRaw($data);
213         return true;
214     }
215
216     /**
217     * Called via a callback when NickServ responds to
218     * the bots query asking if a nick is registered
219     *
220     * @param array $data Data
221     * @return void
222     */
223     public function handle_reg_response($data) {
224         // Retrieve data
225         $screenname = $data['screenname'];
226         $nickdata = $this->regChecks[$screenname];
227         $usernick = $nickdata['user']->nickname;
228
229         if (isset($this->regChecksLookup[$usernick])) {
230             if ($data['registered']) {
231                 // Send message
232                 $this->plugin->sendConfirmationCode($screenname, $nickdata['code'], $nickdata['user'], true);
233             } else {
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 canceling IM address confirmation.
247                         $this->serverError(_('Couldn\'t delete confirmation.'));
248                         return;
249                     }
250                 }
251             }
252
253             // Unset lookup value
254             unset($this->regChecksLookup[$usernick]);
255
256             // Unset data
257             unset($this->regChecks[$screename]);
258         }
259     }
260
261     /**
262     * Called when the connection is established
263     *
264     * @return void
265     */
266     public function handle_connected() {
267         $this->connected = true;
268     }
269
270     /**
271     * Enters a message into the database for sending when ready
272     *
273     * @param string $command Command
274     * @param array $args Arguments
275     * @return boolean
276     */
277     protected function enqueue_waiting_message($data) {
278         $wm = new Irc_waiting_message();
279
280         $wm->data       = serialize($data);
281         $wm->prioritise = $data['prioritise'];
282         $wm->attempts   = 0;
283         $wm->created    = common_sql_now();
284         $result         = $wm->insert();
285
286         if (!$result) {
287             common_log_db_error($wm, 'INSERT', __FILE__);
288             throw new ServerException('DB 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 }