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.
32 class IrcManager extends ImManager {
33 protected $conn = null;
34 protected $lastPing = null;
35 protected $messageWaiting = true;
36 protected $lastMessage = null;
38 protected $regChecks = array();
39 protected $regChecksLookup = array();
41 protected $connected = false;
44 * Initialize connection to server.
46 * @return boolean true on success
48 public function start($master) {
49 if (parent::start($master)) {
58 * Return any open sockets that the run loop should listen
61 * @return array Array of socket resources
63 public function getSockets() {
66 return $this->conn->getSockets();
73 * Request a maximum timeout for listeners before the next idle period.
75 * @return integer Maximum timeout
77 public function timeout() {
78 if ($this->messageWaiting) {
81 return $this->plugin->pinginterval;
86 * Idle processing for io manager's execution loop.
90 public function idle() {
91 // Send a ping if necessary
92 if (empty($this->lastPing) || time() - $this->lastPing > $this->plugin->pinginterval) {
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();
101 $this->messageWaiting = false;
105 $data = unserialize($wm->data);
108 if ($this->send_raw_message($data)) {
111 if ($wm->attempts <= common_config('queue', 'max_retries')) {
112 // Try again next idle
115 // Exceeded the maximum number of retries
124 * Process IRC events that have come in over the wire.
126 * @param resource $socket Socket to handle input on
129 public function handleInput($socket) {
130 common_log(LOG_DEBUG, 'Servicing the IRC queue.');
131 $this->stats('irc_process');
134 $this->conn->handleEvents();
135 } catch (Phergie_Driver_Exception $e) {
136 $this->connected = false;
137 $this->conn->reconnect();
142 * Initiate connection
146 public function connect() {
148 $this->conn = new Phergie_StatusnetBot;
150 $config = new Phergie_Config;
153 'connections' => 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
166 'driver' => 'statusnet',
168 'processor' => 'async',
169 'processor.options' => array('sec' => 0, 'usec' => 0),
178 'plugins.autoload' => true,
180 // Uncomment to enable debugging output
181 //'ui.enabled' => true,
183 'nickserv.password' => $this->plugin->nickservpassword,
184 'nickserv.identify_message' => $this->plugin->nickservidentifyregexp,
186 'autojoin.channels' => $this->plugin->channels,
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
196 $this->conn->setConfig($config);
197 $this->conn->connect();
198 $this->lastPing = time();
199 $this->lastMessage = time();
205 * Called via a callback when a message is received
206 * Passes it back to the queuing system
208 * @param array $data Data
211 public function handle_irc_message($data) {
212 $this->plugin->enqueueIncomingRaw($data);
217 * Called via a callback when NickServ responds to
218 * the bots query asking if a nick is registered
220 * @param array $data Data
223 public function handle_reg_response($data) {
225 $screenname = $data['screenname'];
226 $nickdata = $this->regChecks[$screenname];
227 $usernick = $nickdata['user']->nickname;
229 if (isset($this->regChecksLookup[$usernick])) {
230 if ($data['registered']) {
232 $this->plugin->send_confirmation_code($screenname, $nickdata['code'], $nickdata['user'], true);
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 canceling IM address confirmation.
247 $this->serverError(_('Couldn\'t delete confirmation.'));
253 // Unset lookup value
254 unset($this->regChecksLookup[$usernick]);
257 unset($this->regChecks[$screename]);
262 * Called when the connection is established
266 public function handle_connected() {
267 $this->connected = true;
271 * Enters a message into the database for sending when ready
273 * @param string $command Command
274 * @param array $args Arguments
277 protected function enqueue_waiting_message($data) {
278 $wm = new Irc_waiting_message();
280 $wm->data = serialize($data);
281 $wm->prioritise = $data['prioritise'];
283 $wm->created = common_sql_now();
284 $result = $wm->insert();
287 common_log_db_error($wm, 'INSERT', __FILE__);
288 throw new ServerException('DB 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);