]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - xmppdaemon.php
fixing IM message, AGAIN
[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 get_user($from) {
103                 $user = User::staticGet('jabber', jabber_normalize_jid($from));
104                 return $user;
105         }
106
107         function get_confirmation($from) {
108                 $confirm = new Confirm_address();
109                 $confirm->address = $from;
110                 $confirm->address_type = 'jabber';
111                 if ($confirm->find(TRUE)) {
112                         return $confirm;
113                 } else {
114                         return NULL;
115                 }
116         }
117
118         function handle_message(&$pl) {
119                 if ($pl['type'] != 'chat') {
120                         return;
121                 }
122                 if (strlen($pl['body']) == 0) {
123                         return;
124                 }
125
126                 $from = jabber_normalize_jid($pl['from']);
127                 $user = $this->get_user($from);
128
129                 if (!$user) {
130                         $this->from_site($from, 'Unknown user; go to ' .
131                                                          common_local_url('imsettings') .
132                                                          ' to add your address to your account');
133                         $this->log(LOG_WARNING, 'Message from unknown user ' . $from);
134                         return;
135                 }
136                 if ($this->handle_command($user, $pl['body'])) {
137                         return;
138                 } else if ($this->is_autoreply($pl['body'])) {
139                         $this->log(LOG_INFO, 'Ignoring auto reply from ' . $from);
140                         return;
141                 } else {
142                         $this->add_notice($user, $pl);
143                 }
144         }
145
146         function is_autoreply($txt) {
147                 if (preg_match('/[\[\(]?[Aa]uto-?[Rr]eply[\]\)]/', $txt)) {
148                         return true;
149                 } else {
150                         return false;
151                 }
152         }
153         
154         function from_site($address, $msg) {
155                 $text = '['.common_config('site', 'name') . '] ' . $msg;
156                 jabber_send_message($address, $text);
157         }
158
159         function handle_command($user, $body) {
160                 # XXX: localise
161                 switch(trim($body)) {
162                  case 'on':
163                         $this->set_notify($user, true);
164                         $this->from_site($user->jabber, 'notifications on');
165                         return true;
166                  case 'off':
167                         $this->set_notify($user, false);
168                         $this->from_site($user->jabber, 'notifications off');
169                         return true;
170                  default:
171                         return false;
172                 }
173         }
174
175         function set_notify(&$user, $notify) {
176                 $orig = clone($user);
177                 $user->jabbernotify = $notify;
178                 $result = $user->update($orig);
179                 if (!$id) {
180                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
181                         $this->log(LOG_ERROR,
182                                            'Could not set notify flag to ' . $notify .
183                                            ' for user ' . common_log_objstring($user) .
184                                            ': ' . $last_error->message);
185                 } else {
186                         $this->log(LOG_INFO,
187                                            'User ' . $user->nickname . ' set notify flag to ' . $notify);
188                 }
189         }
190
191         function add_notice(&$user, &$pl) {
192                 $notice = new Notice();
193                 $notice->profile_id = $user->id;
194                 $notice->content = trim(substr($pl['body'], 0, 140));
195                 $notice->rendered = common_render_content($notice->content, $notice);
196                 $notice->created = DB_DataObject_Cast::dateTime();
197                 $notice->query('BEGIN');
198                 $id = $notice->insert();
199                 if (!$id) {
200                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
201                         $this->log(LOG_ERROR,
202                                            'Could not insert ' . common_log_objstring($notice) .
203                                            ' for user ' . common_log_objstring($user) .
204                                            ': ' . $last_error->message);
205                         return;
206                 }
207                 $orig = clone($notice);
208                 $notice->uri = common_notice_uri($notice);
209                 $result = $notice->update($orig);
210                 if (!$result) {
211                         $last_error = &PEAR::getStaticProperty('DB_DataObject','lastError');
212                         $this->log(LOG_ERROR,
213                                            'Could not add URI to ' . common_log_objstring($notice) .
214                                            ' for user ' . common_log_objstring($user) .
215                                            ': ' . $last_error->message);
216                         return;
217                 }
218                 $notice->query('COMMIT');
219         common_save_replies($notice);   
220                 common_real_broadcast($notice);
221                 $this->log(LOG_INFO,
222                                    'Added notice ' . $notice->id . ' from user ' . $user->nickname);
223         }
224
225         function handle_presence(&$pl) {
226                 $from = jabber_normalize_jid($pl['from']);
227                 switch ($pl['type']) {
228                  case 'subscribe':
229                         # We let anyone subscribe
230                         $this->subscribed($from);
231                         $this->log(LOG_INFO,
232                                            'Accepted subscription from ' . $from);
233                         break;
234                  case 'subscribed':
235                  case 'unsubscribed':
236                  case 'unsubscribe':
237                         $this->log(LOG_INFO,
238                                            'Ignoring  "' . $pl['type'] . '" from ' . $from);
239                         break;
240                  default:
241                         if (!$pl['type']) {
242                                 $user = User::staticGet('jabber', $from);
243                                 if (!$user) {
244                                         $this->log(LOG_WARNING, 'Message from unknown user ' . $from);
245                                         return;
246                                 }
247                                 if ($user->updatefrompresence) {
248                                         $this->log(LOG_INFO, 'Updating ' . $user->nickname .
249                                                            ' status from presence.');
250                                         $this->add_notice($user, $pl);
251                                 }
252                         }
253                         break;
254                 }
255         }
256
257         function log($level, $msg) {
258                 common_log($level, 'XMPPDaemon('.$this->resource.'): '.$msg);
259         }
260
261         function subscribed($to) {
262                 jabber_special_presence('subscribed', $to);
263         }
264
265         function set_status($status) {
266                 $this->log(LOG_INFO, 'Setting status to "' . $status . '"');
267                 jabber_send_presence($status);
268         }
269
270         function top_queue_item() {
271
272                 $qi = new Queue_item();
273                 $qi->orderBy('created');
274                 $qi->whereAdd('claimed is NULL');
275
276                 $qi->limit(1);
277
278                 $cnt = $qi->find(TRUE);
279
280                 if ($cnt) {
281                         # XXX: potential race condition
282                         # can we force it to only update if claimed is still NULL
283                         # (or old)?
284                         $this->log(LOG_INFO, 'claiming queue item = ' . $qi->notice_id);
285                         $orig = clone($qi);
286                         $qi->claimed = DB_DataObject_Cast::dateTime();
287                         $result = $qi->update($orig);
288                         if ($result) {
289                                 $this->log(LOG_INFO, 'claim succeeded.');
290                                 return $qi;
291                         } else {
292                                 $this->log(LOG_INFO, 'claim failed.');
293                         }
294                 }
295                 $qi = NULL;
296                 return NULL;
297         }
298
299         function broadcast_queue() {
300                 $this->clear_old_claims();
301                 $this->log(LOG_INFO, 'checking for queued notices');
302                 do {
303                         $qi = $this->top_queue_item();
304                         if ($qi) {
305                                 $this->log(LOG_INFO, 'Got item enqueued '.common_exact_date($qi->created));
306                                 $notice = Notice::staticGet($qi->notice_id);
307                                 if ($notice) {
308                                         $this->log(LOG_INFO, 'broadcasting notice ID = ' . $notice->id);
309                                         # XXX: what to do if broadcast fails?
310                                         $result = common_real_broadcast($notice, $this->is_remote($notice));
311                                         if (!$result) {
312                                                 $this->log(LOG_WARNING, 'Failed broadcast for notice ID = ' . $notice->id);
313                                                 $orig = $qi;
314                                                 $qi->claimed = NULL;
315                                                 $qi->update($orig);
316                                                 $this->log(LOG_WARNING, 'Abandoned claim for notice ID = ' . $notice->id);
317                                                 continue;
318                                         }
319                                         $this->log(LOG_INFO, 'finished broadcasting notice ID = ' . $notice->id);
320                                         $notice = NULL;
321                                 } else {
322                                         $this->log(LOG_WARNING, 'queue item for notice that does not exist');
323                                 }
324                                 $qi->delete();
325                         }
326                 } while ($qi);
327         }
328
329         function clear_old_claims() {
330                 $qi = new Queue_item();
331                 $qi->claimed = NULL;
332                 $qi->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
333                 $qi->update(DB_DATAOBJECT_WHEREADD_ONLY);
334         }
335
336         function is_remote($notice) {
337                 $user = User::staticGet($notice->profile_id);
338                 return !$user;
339         }
340         
341         function confirmation_queue() {
342             # $this->clear_old_confirm_claims();
343                 $this->log(LOG_INFO, 'checking for queued confirmations');
344                 do {
345                         $confirm = $this->next_confirm();
346                         if ($confirm) {
347                                 $this->log(LOG_INFO, 'Sending confirmation for ' . $confirm->address);
348                                 $user = User::staticGet($confirm->user_id);
349                                 if (!$user) {
350                                         $this->log(LOG_WARNING, 'Confirmation for unknown user ' . $confirm->user_id);
351                                         continue;
352                                 }
353                                 $success = jabber_confirm_address($confirm->code,
354                                                                   $user->nickname,
355                                                                   $confirm->address);
356                                 if (!$success) {
357                                         $this->log(LOG_ERROR, 'Confirmation failed for ' . $confirm->address);
358                                         # Just let the claim age out; hopefully things work then
359                                         continue;
360                                 } else {
361                                         $this->log(LOG_INFO, 'Confirmation sent for ' . $confirm->address);
362                                         # Mark confirmation sent
363                                         $original = clone($confirm);
364                                         $confirm->sent = $confirm->claimed;
365                                         $result = $confirm->update($original);
366                                         if (!$result) {
367                                                 $this->log(LOG_ERROR, 'Cannot mark sent for ' . $confirm->address);
368                                                 # Just let the claim age out; hopefully things work then
369                                                 continue;
370                                         }
371                                 }
372                         }
373                 } while ($confirm);
374         }
375         
376         function next_confirm() {
377                 $confirm = new Confirm_address();
378                 $confirm->whereAdd('claimed IS NULL');
379                 $confirm->whereAdd('sent IS NULL');
380                 # XXX: eventually we could do other confirmations in the queue, too
381                 $confirm->address_type = 'jabber';
382                 $confirm->orderBy('modified DESC');
383                 $confirm->limit(1);
384                 if ($confirm->find(TRUE)) {
385                         $this->log(LOG_INFO, 'Claiming confirmation for ' . $confirm->address);
386                         # working around some weird DB_DataObject behaviour
387                         $confirm->whereAdd(''); # clears where stuff
388                         $original = clone($confirm);
389                         $confirm->claimed = DB_DataObject_Cast::dateTime();
390                         $result = $confirm->update($original);
391                         if ($result) {
392                                 $this->log(LOG_INFO, 'Succeeded in claim! '. $result);
393                                 return $confirm;
394                         } else {
395                                 $this->log(LOG_INFO, 'Failed in claim!');
396                                 return false;
397                         }
398                 }
399                 return NULL;
400         }
401         
402         function clear_old_confirm_claims() {
403                 $confirm = new Confirm();
404                 $confirm->claimed = NULL;
405                 $confirm->whereAdd('now() - claimed > '.CLAIM_TIMEOUT);
406                 $confirm->update(DB_DATAOBJECT_WHEREADD_ONLY);
407         }
408         
409 }
410
411 $resource = ($argc > 1) ? $argv[1] : NULL;
412
413 $daemon = new XMPPDaemon($resource);
414
415 if ($daemon->connect()) {
416         $daemon->set_status("Send me a message to post a notice");
417         $daemon->handle();
418 }
419
420 ?>