]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - scripts/xmppdaemon.php
eef6f0d4bfe51be5cb7350277a7d8b46a8ecd203
[quix0rs-gnu-social.git] / scripts / 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 function xmppdaemon_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
22     switch ($errno) {
23      case E_USER_ERROR:
24                 echo "ERROR: [$errno] $errstr ($errfile:$errline)\n";
25                 echo "  Fatal error on line $errline in file $errfile";
26                 echo ", PHP " . PHP_VERSION . " (" . PHP_OS . ")\n";
27                 echo "Aborting...\n";
28                 exit(1);
29                 break;
30
31          case E_USER_WARNING:
32                 echo "WARNING [$errno] $errstr ($errfile:$errline)\n";
33                 break;
34
35      case E_USER_NOTICE:
36                 echo "NOTICE [$errno] $errstr ($errfile:$errline)\n";
37                 break;
38
39      default:
40                 echo "Unknown error type: [$errno] $errstr ($errfile:$errline)\n";
41                 break;
42     }
43
44     /* Don't execute PHP internal error handler */
45     return true;
46 }
47
48 set_error_handler('xmppdaemon_error_handler');
49
50 # Abort if called from a web server
51 if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
52         print "This script must be run from the command line\n";
53         exit();
54 }
55
56 define('INSTALLDIR', realpath(dirname(__FILE__) . '/..'));
57 define('LACONICA', true);
58 define('CLAIM_TIMEOUT', 100000);
59
60 require_once(INSTALLDIR . '/lib/common.php');
61 require_once(INSTALLDIR . '/lib/jabber.php');
62
63 # This is kind of clunky; we create a class to call the global functions
64 # in jabber.php, which create a new XMPP class. A more elegant (?) solution
65 # might be to use make this a subclass of XMPP.
66
67 class XMPPDaemon {
68
69         function XMPPDaemon($resource=NULL) {
70                 static $attrs = array('server', 'port', 'user', 'password', 'host');
71
72                 foreach ($attrs as $attr)
73                 {
74                         $this->$attr = common_config('xmpp', $attr);
75                 }
76
77                 if ($resource) {
78                         $this->resource = $resource;
79                 } else {
80                         $this->resource = common_config('xmpp', 'resource') . 'daemon';
81                 }
82
83                 $this->log(LOG_INFO, "{$this->user}@{$this->server}/{$this->resource}");
84         }
85
86         function connect() {
87
88                 $connect_to = ($this->host) ? $this->host : $this->server;
89
90                 $this->log(LOG_INFO, "Connecting to $connect_to on port $this->port");
91
92                 $this->conn = jabber_connect($this->resource);
93
94                 if (!$this->conn) {
95                         return false;
96                 }
97
98                 return !$this->conn->isDisconnected();
99         }
100
101         function handle() {
102
103                 static $parts = array('message', 'presence',
104                                                           'end_stream', 'session_start');
105
106                 while(!$this->conn->isDisconnected()) {
107
108                         $payloads = $this->conn->processUntil($parts, 10);
109
110                         if ($payloads) {
111                                 foreach($payloads as $event) {
112                                         $pl = $event[1];
113                                         switch($event[0]) {
114                                          case 'message':
115                                                 $this->handle_message($pl);
116                                                 break;
117                                          case 'presence':
118                                                 $this->handle_presence($pl);
119                                                 break;
120                                          case 'session_start':
121                                                 $this->handle_session($pl);
122                                                 break;
123                                         }
124                                 }
125                         }
126
127                         $this->broadcast_queue();
128                         $this->confirmation_queue();
129                 }
130         }
131
132         function handle_session($pl) {
133                 # XXX what to do here?
134                 return true;
135         }
136
137         function get_user($from) {
138                 $user = User::staticGet('jabber', jabber_normalize_jid($from));
139                 return $user;
140         }
141
142         function get_confirmation($from) {
143                 $confirm = new Confirm_address();
144                 $confirm->address = $from;
145                 $confirm->address_type = 'jabber';
146                 if ($confirm->find(TRUE)) {
147                         return $confirm;
148                 } else {
149                         return NULL;
150                 }
151         }
152
153         function handle_message(&$pl) {
154                 if ($pl['type'] != 'chat') {
155                         return;
156                 }
157                 if (mb_strlen($pl['body']) == 0) {
158                         return;
159                 }
160
161                 $from = jabber_normalize_jid($pl['from']);
162                 $user = $this->get_user($from);
163
164                 if (!$user) {
165                         $this->from_site($from, 'Unknown user; go to ' .
166                                                          common_local_url('imsettings') .
167                                                          ' to add your address to your account');
168                         $this->log(LOG_WARNING, 'Message from unknown user ' . $from);
169                         return;
170                 }
171                 if ($this->handle_command($user, $pl['body'])) {
172                         return;
173                 } else if ($this->is_autoreply($pl['body'])) {
174                         $this->log(LOG_INFO, 'Ignoring auto reply from ' . $from);
175                         return;
176                 } else if ($this->is_otr($pl['body'])) {
177                         $this->log(LOG_INFO, 'Ignoring OTR from ' . $from);
178                         return;
179                 } else {
180                         $len = mb_strlen($pl['body']);
181                         if($len > 140) {
182                                 $this->from_site($from, 'Message too long - maximum is 140 characters, you sent ' . $len);
183                                 return;
184                         }
185                         $this->add_notice($user, $pl);
186                 }
187         }
188
189         function is_autoreply($txt) {
190                 if (preg_match('/[\[\(]?[Aa]uto-?[Rr]eply[\]\)]/', $txt)) {
191                         return true;
192                 } else {
193                         return false;
194                 }
195         }
196
197         function is_otr($txt) {
198                 if (preg_match('/^\?OTR/', $txt)) {
199                         return true;
200                 } else {
201                         return false;
202                 }
203         }
204
205         function from_site($address, $msg) {
206                 $text = '['.common_config('site', 'name') . '] ' . $msg;
207                 jabber_send_message($address, $text);
208         }
209
210         function handle_command($user, $body) {
211                 # XXX: localise
212                 $p=explode(' ',$body);
213                 if(count($p)>2)
214                         return false;
215                 switch($p[0]) {
216                  case 'help':
217                         if(count($p)!=1)
218                                 return false;
219                         $this->from_site($user->jabber, "Commands:\n on     - turn on notifications\n off    - turn off notifications\n help   - show this help \n sub - subscribe to user\n unsub - unsubscribe from user");
220                         return true;
221                  case 'on':
222                         if(count($p)!=1)
223                                 return false;
224                         $this->set_notify($user, true);
225                         $this->from_site($user->jabber, 'notifications on');
226                         return true;
227                  case 'off':
228                         if(count($p)!=1)
229                                 return false;
230                         $this->set_notify($user, false);
231                         $this->from_site($user->jabber, 'notifications off');
232                         return true;
233                  case 'sub':
234                         if(count($p)==1) {
235                                 $this->from_site($user->jabber, 'Specify the name of the user to subscribe to');
236                                 return true;
237                         }
238                         $result=subs_subscribe_user($user, $p[1]);
239                         if($result=='true')
240                                 $this->from_site($user->jabber, 'Subscribed to ' . $p[1]);
241                         else
242                                 $this->from_site($user->jabber, $result);
243                         return true;
244                  case 'unsub':
245                         if(count($p)==1) {
246                                 $this->from_site($user->jabber, 'Specify the name of the user to unsubscribe from');
247                                 return true;
248                         }
249                         $result=subs_unsubscribe_user($user, $p[1]);
250                         if($result=='true')
251                                 $this->from_site($user->jabber, 'Unsubscribed from ' . $p[1]);
252                         else
253                                 $this->from_site($user->jabber, $result);
254                         return true;
255                  default:
256                         return false;
257                 }
258         }
259
260         function set_notify(&$user, $notify) {
261                 $orig = clone($user);
262                 $user->jabbernotify = $notify;
263                 $result = $user->update($orig);
264                 if (!$result) {
265                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
266                         $this->log(LOG_ERR,
267                                            'Could not set notify flag to ' . $notify .
268                                            ' for user ' . common_log_objstring($user) .
269                                            ': ' . $last_error->message);
270                 } else {
271                         $this->log(LOG_INFO,
272                                            'User ' . $user->nickname . ' set notify flag to ' . $notify);
273                 }
274         }
275
276         function add_notice(&$user, &$pl) {
277                 $notice = Notice::saveNew($user->id, trim(mb_substr($pl['body'], 0, 140)), 'xmpp');
278                 if (is_string($notice)) {
279                         $this->log(LOG_ERR, $notice);
280                         return;
281                 }
282                 common_real_broadcast($notice);
283                 $this->log(LOG_INFO,
284                                    'Added notice ' . $notice->id . ' from user ' . $user->nickname);
285         }
286
287         function handle_presence(&$pl) {
288                 $from = jabber_normalize_jid($pl['from']);
289                 switch ($pl['type']) {
290                  case 'subscribe':
291                         # We let anyone subscribe
292                         $this->subscribed($from);
293                         $this->log(LOG_INFO,
294                                            'Accepted subscription from ' . $from);
295                         break;
296                  case 'subscribed':
297                  case 'unsubscribed':
298                  case 'unsubscribe':
299                         $this->log(LOG_INFO,
300                                            'Ignoring  "' . $pl['type'] . '" from ' . $from);
301                         break;
302                  default:
303                         if (!$pl['type']) {
304                                 $user = User::staticGet('jabber', $from);
305                                 if (!$user) {
306                                         $this->log(LOG_WARNING, 'Presence from unknown user ' . $from);
307                                         return;
308                                 }
309                                 if ($user->updatefrompresence) {
310                                         $this->log(LOG_INFO, 'Updating ' . $user->nickname .
311                                                            ' status from presence.');
312                                         $this->add_notice($user, $pl);
313                                 }
314                         }
315                         break;
316                 }
317         }
318
319         function log($level, $msg) {
320                 common_log($level, 'XMPPDaemon('.$this->resource.'): '.$msg);
321         }
322
323         function subscribed($to) {
324                 jabber_special_presence('subscribed', $to);
325         }
326
327         function set_status($status) {
328                 $this->log(LOG_INFO, 'Setting status to "' . $status . '"');
329                 jabber_send_presence($status);
330         }
331
332         function top_queue_item() {
333
334                 $qi = new Queue_item();
335                 $qi->orderBy('created');
336                 $qi->whereAdd('claimed is NULL');
337
338                 $qi->limit(1);
339
340                 $cnt = $qi->find(TRUE);
341
342                 if ($cnt) {
343                         # XXX: potential race condition
344                         # can we force it to only update if claimed is still NULL
345                         # (or old)?
346                         $this->log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id);
347                         $orig = clone($qi);
348                         $qi->claimed = common_sql_now();
349                         $result = $qi->update($orig);
350                         if ($result) {
351                                 $this->log(LOG_INFO, 'claim succeeded.');
352                                 return $qi;
353                         } else {
354                                 $this->log(LOG_INFO, 'claim failed.');
355                         }
356                 }
357                 $qi = NULL;
358                 return NULL;
359         }
360
361         function broadcast_queue() {
362                 $this->clear_old_claims();
363                 $this->log(LOG_INFO, 'checking for queued notices');
364                 do {
365                         $qi = $this->top_queue_item();
366                         if ($qi) {
367                                 $this->log(LOG_INFO, 'Got item enqueued '.common_exact_date($qi->created));
368                                 $notice = Notice::staticGet($qi->notice_id);
369                                 if ($notice) {
370                                         $this->log(LOG_INFO, 'broadcasting notice ID = ' . $notice->id);
371                                         # XXX: what to do if broadcast fails?
372                                         $result = common_real_broadcast($notice, $this->is_remote($notice));
373                                         if (!$result) {
374                                                 $this->log(LOG_WARNING, 'Failed broadcast for notice ID = ' . $notice->id);
375                                                 $orig = $qi;
376                                                 $qi->claimed = NULL;
377                                                 $qi->update($orig);
378                                                 $this->log(LOG_WARNING, 'Abandoned claim for notice ID = ' . $notice->id);
379                                                 continue;
380                                         }
381                                         $this->log(LOG_INFO, 'finished broadcasting notice ID = ' . $notice->id);
382                                         $notice = NULL;
383                                 } else {
384                                         $this->log(LOG_WARNING, 'queue item for notice that does not exist');
385                                 }
386                                 $qi->delete();
387                         }
388                 } while ($qi);
389         }
390
391         function clear_old_claims() {
392                 $qi = new Queue_item();
393                 $qi->claimed = NULL;
394                 $qi->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
395                 $qi->update(DB_DATAOBJECT_WHEREADD_ONLY);
396         }
397
398         function is_remote($notice) {
399                 $user = User::staticGet($notice->profile_id);
400                 return !$user;
401         }
402
403         function confirmation_queue() {
404             # $this->clear_old_confirm_claims();
405                 $this->log(LOG_INFO, 'checking for queued confirmations');
406                 do {
407                         $confirm = $this->next_confirm();
408                         if ($confirm) {
409                                 $this->log(LOG_INFO, 'Sending confirmation for ' . $confirm->address);
410                                 $user = User::staticGet($confirm->user_id);
411                                 if (!$user) {
412                                         $this->log(LOG_WARNING, 'Confirmation for unknown user ' . $confirm->user_id);
413                                         continue;
414                                 }
415                                 $success = jabber_confirm_address($confirm->code,
416                                                                   $user->nickname,
417                                                                   $confirm->address);
418                                 if (!$success) {
419                                         $this->log(LOG_ERR, 'Confirmation failed for ' . $confirm->address);
420                                         # Just let the claim age out; hopefully things work then
421                                         continue;
422                                 } else {
423                                         $this->log(LOG_INFO, 'Confirmation sent for ' . $confirm->address);
424                                         # Mark confirmation sent
425                                         $original = clone($confirm);
426                                         $confirm->sent = $confirm->claimed;
427                                         $result = $confirm->update($original);
428                                         if (!$result) {
429                                                 $this->log(LOG_ERR, 'Cannot mark sent for ' . $confirm->address);
430                                                 # Just let the claim age out; hopefully things work then
431                                                 continue;
432                                         }
433                                 }
434                         }
435                 } while ($confirm);
436         }
437
438         function next_confirm() {
439                 $confirm = new Confirm_address();
440                 $confirm->whereAdd('claimed IS NULL');
441                 $confirm->whereAdd('sent IS NULL');
442                 # XXX: eventually we could do other confirmations in the queue, too
443                 $confirm->address_type = 'jabber';
444                 $confirm->orderBy('modified DESC');
445                 $confirm->limit(1);
446                 if ($confirm->find(TRUE)) {
447                         $this->log(LOG_INFO, 'Claiming confirmation for ' . $confirm->address);
448                         # working around some weird DB_DataObject behaviour
449                         $confirm->whereAdd(''); # clears where stuff
450                         $original = clone($confirm);
451                         $confirm->claimed = common_sql_now();
452                         $result = $confirm->update($original);
453                         if ($result) {
454                                 $this->log(LOG_INFO, 'Succeeded in claim! '. $result);
455                                 return $confirm;
456                         } else {
457                                 $this->log(LOG_INFO, 'Failed in claim!');
458                                 return false;
459                         }
460                 }
461                 return NULL;
462         }
463
464         function clear_old_confirm_claims() {
465                 $confirm = new Confirm();
466                 $confirm->claimed = NULL;
467                 $confirm->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
468                 $confirm->update(DB_DATAOBJECT_WHEREADD_ONLY);
469         }
470
471 }
472
473 mb_internal_encoding('UTF-8');
474
475 $resource = ($argc > 1) ? $argv[1] : NULL;
476
477 $daemon = new XMPPDaemon($resource);
478
479 if ($daemon->connect()) {
480         $daemon->set_status("Send me a message to post a notice");
481         $daemon->handle();
482 }
483
484 ?>