3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
23 * IRC background connection manager for IRC-using queue handlers,
24 * allowing them to send outgoing messages on the right connection.
26 * Input is handled during socket select loop, Any incoming messages will be handled.
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.
31 class IrcManager extends ImManager {
32 protected $conn = null;
33 protected $lastPing = null;
34 protected $messageWaiting = true;
35 protected $lastMessage = null;
37 protected $regChecks = array();
38 protected $regChecksLookup = array();
40 protected $connected = false;
43 * Initialize connection to server.
45 * @return boolean true on success
47 public function start($master) {
48 if (parent::start($master)) {
57 * Return any open sockets that the run loop should listen
60 * @return array Array of socket resources
62 public function getSockets() {
65 return $this->conn->getSockets();
72 * Request a maximum timeout for listeners before the next idle period.
74 * @return integer Maximum timeout
76 public function timeout() {
77 if ($this->messageWaiting) {
80 return $this->plugin->pinginterval;
85 * Idle processing for io manager's execution loop.
89 public function idle() {
90 // Send a ping if necessary
91 if (empty($this->lastPing) || time() - $this->lastPing > $this->plugin->pinginterval) {
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();
100 $this->messageWaiting = false;
104 $data = unserialize($wm->data);
107 if ($this->send_raw_message($data)) {
110 if ($wm->attempts <= common_config('queue', 'max_retries')) {
111 // Try again next idle
114 // Exceeded the maximum number of retries
123 * Process IRC events that have come in over the wire.
125 * @param resource $socket Socket to handle input on
128 public function handleInput($socket) {
129 common_debug('Servicing the IRC queue.');
130 $this->stats('irc_process');
133 $this->conn->handleEvents();
134 } catch (Phergie_Driver_Exception $e) {
135 $this->connected = false;
136 $this->conn->reconnect();
141 * Initiate connection
145 public function connect() {
147 $this->conn = new Phergie_StatusnetBot;
149 $config = new Phergie_Config;
152 'connections' => 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
165 'driver' => 'statusnet',
167 'processor' => 'async',
168 'processor.options' => array('sec' => 0, 'usec' => 0),
177 'plugins.autoload' => true,
179 // Uncomment to enable debugging output
180 //'ui.enabled' => true,
182 'nickserv.password' => $this->plugin->nickservpassword,
183 'nickserv.identify_message' => $this->plugin->nickservidentifyregexp,
185 'autojoin.channels' => $this->plugin->channels,
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
195 $this->conn->setConfig($config);
196 $this->conn->connect();
197 $this->lastPing = time();
198 $this->lastMessage = time();
204 * Called via a callback when a message is received
205 * Passes it back to the queuing system
207 * @param array $data Data
210 public function handle_irc_message($data) {
211 $this->plugin->enqueueIncomingRaw($data);
216 * Called via a callback when NickServ responds to
217 * the bots query asking if a nick is registered
219 * @param array $data Data
222 public function handle_reg_response($data) {
224 $screenname = $data['screenname'];
225 $nickdata = $this->regChecks[$screenname];
226 $usernick = $nickdata['user']->nickname;
228 if (isset($this->regChecksLookup[$usernick])) {
229 if ($data['registered']) {
231 $this->plugin->sendConfirmationCode($screenname, $nickdata['code'], $nickdata['user'], true);
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.'));
236 $confirm = new Confirm_address();
238 $confirm->user_id = $user->id;
239 $confirm->address_type = $this->plugin->transport;
241 if ($confirm->find(true)) {
242 $result = $confirm->delete();
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.'));
252 // Unset lookup value
253 unset($this->regChecksLookup[$usernick]);
256 unset($this->regChecks[$screename]);
261 * Called when the connection is established
265 public function handle_connected() {
266 $this->connected = true;
270 * Enters a message into the database for sending when ready
272 * @param string $command Command
273 * @param array $args Arguments
276 protected function enqueue_waiting_message($data) {
277 $wm = new Irc_waiting_message();
279 $wm->data = serialize($data);
280 $wm->prioritise = $data['prioritise'];
282 $wm->created = common_sql_now();
283 $result = $wm->insert();
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.'));
295 * Send a message using the daemon
297 * @param $data Message data
298 * @return boolean true on success
300 public function send_raw_message($data) {
306 if ($data['type'] != 'delayedmessage') {
307 if ($data['type'] != 'message') {
309 $nickdata = $data['nickdata'];
310 $usernick = $nickdata['user']->nickname;
311 $screenname = $nickdata['screenname'];
313 // Cancel any existing checks for this user
314 if (isset($this->regChecksLookup[$usernick])) {
315 unset($this->regChecks[$this->regChecksLookup[$usernick]]);
318 $this->regChecks[$screenname] = $nickdata;
319 $this->regChecksLookup[$usernick] = $screenname;
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(
326 'type' => 'delayedmessage',
327 'prioritise' => $data['prioritise'],
328 'data' => $data['data']
331 $this->messageWaiting = true;
337 $this->conn->send($data['data']['command'], $data['data']['args']);
338 } catch (Phergie_Driver_Exception $e) {
339 $this->connected = false;
340 $this->conn->reconnect();
344 $this->lastMessage = time();
353 protected function sendPing() {
354 $this->lastPing = time();
355 $this->conn->send('PING', $this->lastPing);