]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - xmppdaemon.php
unique key on a boolean value is not scalable
[quix0rs-gnu-social.git] / xmppdaemon.php
1 #!/usr/bin/env php
2 <?php
3 /*
4  * Laconica - a distributed open-source microblogging tool
5  * Copyright (C) 2008, Controlez-Vous, Inc.
6  *
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.
11  *
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.
16  *
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/>.
19  */
20
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";
24         exit();
25 }
26
27 define('INSTALLDIR', dirname(__FILE__));
28 define('LACONICA', true);
29
30 require_once(INSTALLDIR . '/lib/common.php');
31 require_once(INSTALLDIR . '/lib/jabber.php');
32
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.
36
37 class XMPPDaemon {
38
39         function XMPPDaemon($resource=NULL) {
40                 static $attrs = array('server', 'port', 'user', 'password', 'host');
41
42                 foreach ($attrs as $attr)
43                 {
44                         $this->$attr = common_config('xmpp', $attr);
45                 }
46
47                 if ($resource) {
48                         $this->resource = $resource;
49                 } else {
50                         $this->resource = common_config('xmpp', 'resource') . 'daemon';
51                 }
52
53                 $this->log(LOG_INFO, "{$this->user}@{$this->server}/{$this->resource}");
54         }
55
56         function connect() {
57
58                 $connect_to = ($this->host) ? $this->host : $this->server;
59
60                 $this->log(LOG_INFO, "Connecting to $connect_to on port $this->port");
61
62                 $this->conn = jabber_connect($this->resource);
63
64                 if (!$this->conn) {
65                         return false;
66                 }
67             
68                 return !$this->conn->isDisconnected();
69         }
70
71         function handle() {
72
73                 static $parts = array('message', 'presence',
74                                                           'end_stream', 'session_start');
75
76                 while(!$this->conn->isDisconnected()) {
77
78                         $payloads = $this->conn->processUntil($parts, 10);
79
80                         if ($payloads) {
81                                 foreach($payloads as $event) {
82                                         $pl = $event[1];
83                                         switch($event[0]) {
84                                          case 'message':
85                                                 $this->handle_message($pl);
86                                                 break;
87                                          case 'presence':
88                                                 $this->handle_presence($pl);
89                                                 break;
90                                          case 'session_start':
91                                                 $this->handle_session($pl);
92                                                 break;
93                                         }
94                                 }
95                         }
96
97                         $this->broadcast_queue();
98                         $this->confirmation_queue();
99                 }
100         }
101         
102         function handle_session($pl) {
103                 # XXX what to do here?
104                 return true;
105         }
106         
107         function get_user($from) {
108                 $user = User::staticGet('jabber', jabber_normalize_jid($from));
109                 return $user;
110         }
111
112         function get_confirmation($from) {
113                 $confirm = new Confirm_address();
114                 $confirm->address = $from;
115                 $confirm->address_type = 'jabber';
116                 if ($confirm->find(TRUE)) {
117                         return $confirm;
118                 } else {
119                         return NULL;
120                 }
121         }
122
123         function handle_message(&$pl) {
124                 if ($pl['type'] != 'chat') {
125                         return;
126                 }
127                 if (strlen($pl['body']) == 0) {
128                         return;
129                 }
130
131                 $from = jabber_normalize_jid($pl['from']);
132                 $user = $this->get_user($from);
133
134                 if (!$user) {
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);
139                         return;
140                 }
141                 if ($this->handle_command($user, $pl['body'])) {
142                         return;
143                 } else if ($this->is_autoreply($pl['body'])) {
144                         $this->log(LOG_INFO, 'Ignoring auto reply from ' . $from);
145                         return;
146                 } else {
147                         $this->add_notice($user, $pl);
148                 }
149         }
150
151         function is_autoreply($txt) {
152                 if (preg_match('/[\[\(]?[Aa]uto-?[Rr]eply[\]\)]/', $txt)) {
153                         return true;
154                 } else {
155                         return false;
156                 }
157         }
158         
159         function from_site($address, $msg) {
160                 $text = '['.common_config('site', 'name') . '] ' . $msg;
161                 jabber_send_message($address, $text);
162         }
163
164         function handle_command($user, $body) {
165                 # XXX: localise
166                 switch(trim($body)) {
167                  case 'on':
168                         $this->set_notify($user, true);
169                         $this->from_site($user->jabber, 'notifications on');
170                         return true;
171                  case 'off':
172                         $this->set_notify($user, false);
173                         $this->from_site($user->jabber, 'notifications off');
174                         return true;
175                  default:
176                         return false;
177                 }
178         }
179
180         function set_notify(&$user, $notify) {
181                 $orig = clone($user);
182                 $user->jabbernotify = $notify;
183                 $result = $user->update($orig);
184                 if (!$id) {
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);
190                 } else {
191                         $this->log(LOG_INFO,
192                                            'User ' . $user->nickname . ' set notify flag to ' . $notify);
193                 }
194         }
195
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();
204                 if (!$id) {
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);
210                         return;
211                 }
212                 $orig = clone($notice);
213                 $notice->uri = common_notice_uri($notice);
214                 $result = $notice->update($orig);
215                 if (!$result) {
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);
221                         return;
222                 }
223                 $notice->query('COMMIT');
224         common_save_replies($notice);   
225                 common_real_broadcast($notice);
226                 $this->log(LOG_INFO,
227                                    'Added notice ' . $notice->id . ' from user ' . $user->nickname);
228         }
229
230         function handle_presence(&$pl) {
231                 $from = jabber_normalize_jid($pl['from']);
232                 switch ($pl['type']) {
233                  case 'subscribe':
234                         # We let anyone subscribe
235                         $this->subscribed($from);
236                         $this->log(LOG_INFO,
237                                            'Accepted subscription from ' . $from);
238                         break;
239                  case 'subscribed':
240                  case 'unsubscribed':
241                  case 'unsubscribe':
242                         $this->log(LOG_INFO,
243                                            'Ignoring  "' . $pl['type'] . '" from ' . $from);
244                         break;
245                  default:
246                         if (!$pl['type']) {
247                                 $user = User::staticGet('jabber', $from);
248                                 if (!$user) {
249                                         $this->log(LOG_WARNING, 'Message from unknown user ' . $from);
250                                         return;
251                                 }
252                                 if ($user->updatefrompresence) {
253                                         $this->log(LOG_INFO, 'Updating ' . $user->nickname .
254                                                            ' status from presence.');
255                                         $this->add_notice($user, $pl);
256                                 }
257                         }
258                         break;
259                 }
260         }
261
262         function log($level, $msg) {
263                 common_log($level, 'XMPPDaemon('.$this->resource.'): '.$msg);
264         }
265
266         function subscribed($to) {
267                 jabber_special_presence('subscribed', $to);
268         }
269
270         function set_status($status) {
271                 $this->log(LOG_INFO, 'Setting status to "' . $status . '"');
272                 jabber_send_presence($status);
273         }
274
275         function top_queue_item() {
276
277                 $qi = new Queue_item();
278                 $qi->orderBy('created');
279                 $qi->whereAdd('claimed is NULL');
280
281                 $qi->limit(1);
282
283                 $cnt = $qi->find(TRUE);
284
285                 if ($cnt) {
286                         # XXX: potential race condition
287                         # can we force it to only update if claimed is still NULL
288                         # (or old)?
289                         $this->log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id);
290                         $orig = clone($qi);
291                         $qi->claimed = DB_DataObject_Cast::dateTime();
292                         $result = $qi->update($orig);
293                         if ($result) {
294                                 $this->log(LOG_INFO, 'claim succeeded.');
295                                 return $qi;
296                         } else {
297                                 $this->log(LOG_INFO, 'claim failed.');
298                         }
299                 }
300                 $qi = NULL;
301                 return NULL;
302         }
303
304         function broadcast_queue() {
305                 $this->clear_old_claims();
306                 $this->log(LOG_INFO, 'checking for queued notices');
307                 do {
308                         $qi = $this->top_queue_item();
309                         if ($qi) {
310                                 $this->log(LOG_INFO, 'Got item enqueued '.common_exact_date($qi->created));
311                                 $notice = Notice::staticGet($qi->notice_id);
312                                 if ($notice) {
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));
316                                         if (!$result) {
317                                                 $this->log(LOG_WARNING, 'Failed broadcast for notice ID = ' . $notice->id);
318                                                 $orig = $qi;
319                                                 $qi->claimed = NULL;
320                                                 $qi->update($orig);
321                                                 $this->log(LOG_WARNING, 'Abandoned claim for notice ID = ' . $notice->id);
322                                                 continue;
323                                         }
324                                         $this->log(LOG_INFO, 'finished broadcasting notice ID = ' . $notice->id);
325                                         $notice = NULL;
326                                 } else {
327                                         $this->log(LOG_WARNING, 'queue item for notice that does not exist');
328                                 }
329                                 $qi->delete();
330                         }
331                 } while ($qi);
332         }
333
334         function clear_old_claims() {
335                 $qi = new Queue_item();
336                 $qi->claimed = NULL;
337                 $qi->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
338                 $qi->update(DB_DATAOBJECT_WHEREADD_ONLY);
339         }
340
341         function is_remote($notice) {
342                 $user = User::staticGet($notice->profile_id);
343                 return !$user;
344         }
345         
346         function confirmation_queue() {
347             # $this->clear_old_confirm_claims();
348                 $this->log(LOG_INFO, 'checking for queued confirmations');
349                 do {
350                         $confirm = $this->next_confirm();
351                         if ($confirm) {
352                                 $this->log(LOG_INFO, 'Sending confirmation for ' . $confirm->address);
353                                 $user = User::staticGet($confirm->user_id);
354                                 if (!$user) {
355                                         $this->log(LOG_WARNING, 'Confirmation for unknown user ' . $confirm->user_id);
356                                         continue;
357                                 }
358                                 $success = jabber_confirm_address($confirm->code,
359                                                                   $user->nickname,
360                                                                   $confirm->address);
361                                 if (!$success) {
362                                         $this->log(LOG_ERROR, 'Confirmation failed for ' . $confirm->address);
363                                         # Just let the claim age out; hopefully things work then
364                                         continue;
365                                 } else {
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);
371                                         if (!$result) {
372                                                 $this->log(LOG_ERROR, 'Cannot mark sent for ' . $confirm->address);
373                                                 # Just let the claim age out; hopefully things work then
374                                                 continue;
375                                         }
376                                 }
377                         }
378                 } while ($confirm);
379         }
380         
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');
388                 $confirm->limit(1);
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);
396                         if ($result) {
397                                 $this->log(LOG_INFO, 'Succeeded in claim! '. $result);
398                                 return $confirm;
399                         } else {
400                                 $this->log(LOG_INFO, 'Failed in claim!');
401                                 return false;
402                         }
403                 }
404                 return NULL;
405         }
406         
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);
412         }
413         
414 }
415
416 $resource = ($argc > 1) ? $argv[1] : NULL;
417
418 $daemon = new XMPPDaemon($resource);
419
420 if ($daemon->connect()) {
421         $daemon->set_status("Send me a message to post a notice");
422         $daemon->handle();
423 }
424
425 ?>