4 * Laconica - a distributed open-source microblogging tool
5 * Copyright (C) 2008, Controlez-Vous, Inc.
7 * This program is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU Affero General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU Affero General Public License for more details.
17 * You should have received a copy of the GNU Affero General Public License
18 * along with this program. If not, see <http://www.gnu.org/licenses/>.
21 # Abort if called from a web server
22 if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
23 print "This script must be run from the command line\n";
27 define('INSTALLDIR', dirname(__FILE__));
28 define('LACONICA', true);
30 require_once(INSTALLDIR . '/lib/common.php');
31 require_once(INSTALLDIR . '/lib/jabber.php');
33 # This is kind of clunky; we create a class to call the global functions
34 # in jabber.php, which create a new XMPP class. A more elegant (?) solution
35 # might be to use make this a subclass of XMPP.
39 function XMPPDaemon($resource=NULL) {
40 static $attrs = array('server', 'port', 'user', 'password', 'host');
42 foreach ($attrs as $attr)
44 $this->$attr = common_config('xmpp', $attr);
48 $this->resource = $resource;
50 $this->resource = common_config('xmpp', 'resource') . 'daemon';
53 $this->log(LOG_INFO, "{$this->user}@{$this->server}/{$this->resource}");
58 $connect_to = ($this->host) ? $this->host : $this->server;
60 $this->log(LOG_INFO, "Connecting to $connect_to on port $this->port");
62 $this->conn = jabber_connect($this->resource);
68 return !$this->conn->isDisconnected();
73 static $parts = array('message', 'presence',
74 'end_stream', 'session_start');
76 while(!$this->conn->isDisconnected()) {
78 $payloads = $this->conn->processUntil($parts, 10);
81 foreach($payloads as $event) {
85 $this->handle_message($pl);
88 $this->handle_presence($pl);
91 $this->handle_session($pl);
97 $this->broadcast_queue();
98 $this->confirmation_queue();
102 function handle_session($pl) {
103 # XXX what to do here?
107 function get_user($from) {
108 $user = User::staticGet('jabber', jabber_normalize_jid($from));
112 function get_confirmation($from) {
113 $confirm = new Confirm_address();
114 $confirm->address = $from;
115 $confirm->address_type = 'jabber';
116 if ($confirm->find(TRUE)) {
123 function handle_message(&$pl) {
124 if ($pl['type'] != 'chat') {
127 if (strlen($pl['body']) == 0) {
131 $from = jabber_normalize_jid($pl['from']);
132 $user = $this->get_user($from);
135 $this->from_site($from, 'Unknown user; go to ' .
136 common_local_url('imsettings') .
137 ' to add your address to your account');
138 $this->log(LOG_WARNING, 'Message from unknown user ' . $from);
141 if ($this->handle_command($user, $pl['body'])) {
143 } else if ($this->is_autoreply($pl['body'])) {
144 $this->log(LOG_INFO, 'Ignoring auto reply from ' . $from);
147 $this->add_notice($user, $pl);
151 function is_autoreply($txt) {
152 if (preg_match('/[\[\(]?[Aa]uto-?[Rr]eply[\]\)]/', $txt)) {
159 function from_site($address, $msg) {
160 $text = '['.common_config('site', 'name') . '] ' . $msg;
161 jabber_send_message($address, $text);
164 function handle_command($user, $body) {
166 switch(trim($body)) {
168 $this->set_notify($user, true);
169 $this->from_site($user->jabber, 'notifications on');
172 $this->set_notify($user, false);
173 $this->from_site($user->jabber, 'notifications off');
180 function set_notify(&$user, $notify) {
181 $orig = clone($user);
182 $user->jabbernotify = $notify;
183 $result = $user->update($orig);
185 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
186 $this->log(LOG_ERROR,
187 'Could not set notify flag to ' . $notify .
188 ' for user ' . common_log_objstring($user) .
189 ': ' . $last_error->message);
192 'User ' . $user->nickname . ' set notify flag to ' . $notify);
196 function add_notice(&$user, &$pl) {
197 $notice = new Notice();
198 $notice->profile_id = $user->id;
199 $notice->content = trim(substr($pl['body'], 0, 140));
200 $notice->rendered = common_render_content($notice->content, $notice);
201 $notice->created = DB_DataObject_Cast::dateTime();
202 $notice->query('BEGIN');
203 $id = $notice->insert();
205 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
206 $this->log(LOG_ERROR,
207 'Could not insert ' . common_log_objstring($notice) .
208 ' for user ' . common_log_objstring($user) .
209 ': ' . $last_error->message);
212 $orig = clone($notice);
213 $notice->uri = common_notice_uri($notice);
214 $result = $notice->update($orig);
216 $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
217 $this->log(LOG_ERROR,
218 'Could not add URI to ' . common_log_objstring($notice) .
219 ' for user ' . common_log_objstring($user) .
220 ': ' . $last_error->message);
223 $notice->query('COMMIT');
224 common_save_replies($notice);
225 common_real_broadcast($notice);
227 'Added notice ' . $notice->id . ' from user ' . $user->nickname);
230 function handle_presence(&$pl) {
231 $from = jabber_normalize_jid($pl['from']);
232 switch ($pl['type']) {
234 # We let anyone subscribe
235 $this->subscribed($from);
237 'Accepted subscription from ' . $from);
243 'Ignoring "' . $pl['type'] . '" from ' . $from);
247 $user = User::staticGet('jabber', $from);
249 $this->log(LOG_WARNING, 'Message from unknown user ' . $from);
252 if ($user->updatefrompresence) {
253 $this->log(LOG_INFO, 'Updating ' . $user->nickname .
254 ' status from presence.');
255 $this->add_notice($user, $pl);
262 function log($level, $msg) {
263 common_log($level, 'XMPPDaemon('.$this->resource.'): '.$msg);
266 function subscribed($to) {
267 jabber_special_presence('subscribed', $to);
270 function set_status($status) {
271 $this->log(LOG_INFO, 'Setting status to "' . $status . '"');
272 jabber_send_presence($status);
275 function top_queue_item() {
277 $qi = new Queue_item();
278 $qi->orderBy('created');
279 $qi->whereAdd('claimed is NULL');
283 $cnt = $qi->find(TRUE);
286 # XXX: potential race condition
287 # can we force it to only update if claimed is still NULL
289 $this->log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id);
291 $qi->claimed = DB_DataObject_Cast::dateTime();
292 $result = $qi->update($orig);
294 $this->log(LOG_INFO, 'claim succeeded.');
297 $this->log(LOG_INFO, 'claim failed.');
304 function broadcast_queue() {
305 $this->clear_old_claims();
306 $this->log(LOG_INFO, 'checking for queued notices');
308 $qi = $this->top_queue_item();
310 $this->log(LOG_INFO, 'Got item enqueued '.common_exact_date($qi->created));
311 $notice = Notice::staticGet($qi->notice_id);
313 $this->log(LOG_INFO, 'broadcasting notice ID = ' . $notice->id);
314 # XXX: what to do if broadcast fails?
315 $result = common_real_broadcast($notice, $this->is_remote($notice));
317 $this->log(LOG_WARNING, 'Failed broadcast for notice ID = ' . $notice->id);
321 $this->log(LOG_WARNING, 'Abandoned claim for notice ID = ' . $notice->id);
324 $this->log(LOG_INFO, 'finished broadcasting notice ID = ' . $notice->id);
327 $this->log(LOG_WARNING, 'queue item for notice that does not exist');
334 function clear_old_claims() {
335 $qi = new Queue_item();
337 $qi->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
338 $qi->update(DB_DATAOBJECT_WHEREADD_ONLY);
341 function is_remote($notice) {
342 $user = User::staticGet($notice->profile_id);
346 function confirmation_queue() {
347 # $this->clear_old_confirm_claims();
348 $this->log(LOG_INFO, 'checking for queued confirmations');
350 $confirm = $this->next_confirm();
352 $this->log(LOG_INFO, 'Sending confirmation for ' . $confirm->address);
353 $user = User::staticGet($confirm->user_id);
355 $this->log(LOG_WARNING, 'Confirmation for unknown user ' . $confirm->user_id);
358 $success = jabber_confirm_address($confirm->code,
362 $this->log(LOG_ERROR, 'Confirmation failed for ' . $confirm->address);
363 # Just let the claim age out; hopefully things work then
366 $this->log(LOG_INFO, 'Confirmation sent for ' . $confirm->address);
367 # Mark confirmation sent
368 $original = clone($confirm);
369 $confirm->sent = $confirm->claimed;
370 $result = $confirm->update($original);
372 $this->log(LOG_ERROR, 'Cannot mark sent for ' . $confirm->address);
373 # Just let the claim age out; hopefully things work then
381 function next_confirm() {
382 $confirm = new Confirm_address();
383 $confirm->whereAdd('claimed IS NULL');
384 $confirm->whereAdd('sent IS NULL');
385 # XXX: eventually we could do other confirmations in the queue, too
386 $confirm->address_type = 'jabber';
387 $confirm->orderBy('modified DESC');
389 if ($confirm->find(TRUE)) {
390 $this->log(LOG_INFO, 'Claiming confirmation for ' . $confirm->address);
391 # working around some weird DB_DataObject behaviour
392 $confirm->whereAdd(''); # clears where stuff
393 $original = clone($confirm);
394 $confirm->claimed = DB_DataObject_Cast::dateTime();
395 $result = $confirm->update($original);
397 $this->log(LOG_INFO, 'Succeeded in claim! '. $result);
400 $this->log(LOG_INFO, 'Failed in claim!');
407 function clear_old_confirm_claims() {
408 $confirm = new Confirm();
409 $confirm->claimed = NULL;
410 $confirm->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
411 $confirm->update(DB_DATAOBJECT_WHEREADD_ONLY);
416 $resource = ($argc > 1) ? $argv[1] : NULL;
418 $daemon = new XMPPDaemon($resource);
420 if ($daemon->connect()) {
421 $daemon->set_status("Send me a message to post a notice");