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 * XMPP background connection manager for XMPP-using queue handlers,
24 * allowing them to send outgoing messages on the right connection.
26 * Input is handled during socket select loop, keepalive pings during idle.
27 * Any incoming messages will be forwarded to the main XmppDaemon process,
28 * which handles direct user interaction.
30 * In a multi-site queuedaemon.php run, one connection will be instantiated
31 * for each site being handled by the current process that has XMPP enabled.
34 class XmppManager extends IoManager
36 protected $site = null;
37 protected $pingid = 0;
38 protected $lastping = null;
40 static protected $singletons = array();
42 const PING_INTERVAL = 120;
45 * Fetch the singleton XmppManager for the current site.
46 * @return mixed XmppManager, or false if unneeded
48 public static function get()
50 if (common_config('xmpp', 'enabled')) {
51 $site = common_config('site', 'server');
52 if (empty(self::$singletons[$site])) {
53 self::$singletons[$site] = new XmppManager();
55 return self::$singletons[$site];
62 * Tell the i/o master we need one instance for each supporting site
63 * being handled in this process.
65 public static function multiSite()
67 return IoManager::INSTANCE_PER_SITE;
70 function __construct()
72 $this->site = common_config('site', 'server');
76 * Initialize connection to server.
77 * @return boolean true on success
79 public function start($master)
81 parent::start($master);
84 require_once "lib/jabber.php";
86 # Low priority; we don't want to receive messages
88 common_log(LOG_INFO, "INITIALIZE");
89 $this->conn = jabber_connect($this->resource());
91 if (empty($this->conn)) {
92 common_log(LOG_ERR, "Couldn't connect to server.");
96 $this->conn->addEventHandler('message', 'forward_message', $this);
97 $this->conn->addEventHandler('reconnect', 'handle_reconnect', $this);
98 $this->conn->setReconnectTimeout(600);
99 jabber_send_presence("Send me a message to post a notice", 'available', null, 'available', -1);
101 return !is_null($this->conn);
105 * Message pump is triggered on socket input, so we only need an idle()
106 * call often enough to trigger our outgoing pings.
110 return self::PING_INTERVAL;
114 * Lists the XMPP connection socket to allow i/o master to wake
115 * when input comes in here as well as from the queue source.
117 * @return array of resources
119 public function getSockets()
121 return array($this->conn->getSocket());
125 * Process XMPP events that have come in over the wire.
126 * Side effects: may switch site configuration
127 * @fixme may kill process on XMPP error
128 * @param resource $socket
130 public function handleInput($socket)
134 # Process the queue for as long as needed
137 assert($socket === $this->conn->getSocket());
139 common_log(LOG_DEBUG, "Servicing the XMPP queue.");
140 $this->stats('xmpp_process');
141 $this->conn->processTime(0);
143 } catch (XMPPHP_Exception $e) {
144 common_log(LOG_ERR, "Got an XMPPHP_Exception: " . $e->getMessage());
145 die($e->getMessage());
150 * Idle processing for io manager's execution loop.
151 * Send keepalive pings to server.
153 * Side effect: kills process on exception from XMPP library.
155 * @fixme non-dying error handling
157 public function idle($timeout=0)
161 if (empty($this->lastping) || $now - $this->lastping > self::PING_INTERVAL) {
165 $this->lastping = $now;
166 } catch (XMPPHP_Exception $e) {
167 common_log(LOG_ERR, "Got an XMPPHP_Exception: " . $e->getMessage());
168 die($e->getMessage());
175 * Send a keepalive ping to the XMPP server.
177 protected function sendPing()
179 $jid = jabber_daemon_address().'/'.$this->resource();
180 $server = common_config('xmpp', 'server');
182 if (!isset($this->pingid)) {
188 common_log(LOG_DEBUG, "Sending ping #{$this->pingid}");
190 $this->conn->send("<iq from='{$jid}' to='{$server}' id='ping_{$this->pingid}' type='get'><ping xmlns='urn:xmpp:ping'/></iq>");
194 * Callback for Jabber reconnect event
197 function handle_reconnect(&$pl)
199 common_log(LOG_NOTICE, 'XMPP reconnected');
201 $this->conn->processUntil('session_start');
202 $this->conn->presence(null, 'available', null, 'available', -1);
206 * Callback for Jabber message event.
208 * This connection handles output; if we get a message straight to us,
209 * forward it on to our XmppDaemon listener for processing.
213 function forward_message(&$pl)
215 if ($pl['type'] != 'chat') {
216 common_log(LOG_DEBUG, 'Ignoring message of type ' . $pl['type'] . ' from ' . $pl['from']);
219 $listener = $this->listener();
220 if (strtolower($listener) == strtolower($pl['from'])) {
221 common_log(LOG_WARNING, 'Ignoring loop message.');
224 common_log(LOG_INFO, 'Forwarding message from ' . $pl['from'] . ' to ' . $listener);
225 $this->conn->message($this->listener(), $pl['body'], 'chat', null, $this->ofrom($pl['from']));
229 * Build an <addresses> block with an ofrom entry for forwarded messages
231 * @param string $from Jabber ID of original sender
232 * @return string XML fragment
234 protected function ofrom($from)
236 $address = "<addresses xmlns='http://jabber.org/protocol/address'>\n";
237 $address .= "<address type='ofrom' jid='$from' />\n";
238 $address .= "</addresses>\n";
243 * Build the complete JID of the XmppDaemon process which
244 * handles primary XMPP input for this site.
246 * @return string Jabber ID
248 protected function listener()
250 if (common_config('xmpp', 'listener')) {
251 return common_config('xmpp', 'listener');
253 return jabber_daemon_address() . '/' . common_config('xmpp','resource') . 'daemon';
257 protected function resource()
259 return 'queue' . posix_getpid(); // @fixme PIDs won't be host-unique
263 * Make sure we're on the right site configuration
265 protected function switchSite()
267 if ($this->site != common_config('site', 'server')) {
268 common_log(LOG_DEBUG, __METHOD__ . ": switching to site $this->site");
269 $this->stats('switch');
270 StatusNet::init($this->site);