]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/jabber.php
Localisation updates from http://translatewiki.net
[quix0rs-gnu-social.git] / lib / jabber.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * utility functions for Jabber/GTalk/XMPP messages
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Network
23  * @package   StatusNet
24  * @author    Evan Prodromou <evan@status.net>
25  * @copyright 2008 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
31     exit(1);
32 }
33
34 require_once 'XMPPHP/XMPP.php';
35
36 /**
37  * Splits a Jabber ID (JID) into node, domain, and resource portions.
38  * 
39  * Based on validation routine submitted by:
40  * @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
41  * @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact. 
42  *
43  * @param string $jid string to check
44  *
45  * @return array with "node", "domain", and "resource" indices
46  * @throws Exception if input is not valid
47  */
48
49 function jabber_split_jid($jid)
50 {
51     $chars = '';
52     /* the following definitions come from stringprep, Appendix C,
53        which is used in its entirety by nodeprop, Chapter 5, "Prohibited Output" */
54     /* C1.1 ASCII space characters */
55     $chars .= "\x{20}";
56     /* C1.2 Non-ASCII space characters */
57     $chars .= "\x{a0}\x{1680}\x{2000}-\x{200b}\x{202f}\x{205f}\x{3000a}";
58     /* C2.1 ASCII control characters */
59     $chars .= "\x{00}-\x{1f}\x{7f}";
60     /* C2.2 Non-ASCII control characters */
61     $chars .= "\x{80}-\x{9f}\x{6dd}\x{70f}\x{180e}\x{200c}\x{200d}\x{2028}\x{2029}\x{2060}-\x{2063}\x{206a}-\x{206f}\x{feff}\x{fff9}-\x{fffc}\x{1d173}-\x{1d17a}";
62     /* C3 - Private Use */
63     $chars .= "\x{e000}-\x{f8ff}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}";
64     /* C4 - Non-character code points */
65     $chars .= "\x{fdd0}-\x{fdef}\x{fffe}\x{ffff}\x{1fffe}\x{1ffff}\x{2fffe}\x{2ffff}\x{3fffe}\x{3ffff}\x{4fffe}\x{4ffff}\x{5fffe}\x{5ffff}\x{6fffe}\x{6ffff}\x{7fffe}\x{7ffff}\x{8fffe}\x{8ffff}\x{9fffe}\x{9ffff}\x{afffe}\x{affff}\x{bfffe}\x{bffff}\x{cfffe}\x{cffff}\x{dfffe}\x{dffff}\x{efffe}\x{effff}\x{ffffe}\x{fffff}\x{10fffe}\x{10ffff}";
66     /* C5 - Surrogate codes */
67     $chars .= "\x{d800}-\x{dfff}";
68     /* C6 - Inappropriate for plain text */
69     $chars .= "\x{fff9}-\x{fffd}";
70     /* C7 - Inappropriate for canonical representation */
71     $chars .= "\x{2ff0}-\x{2ffb}";
72     /* C8 - Change display properties or are deprecated */
73     $chars .= "\x{340}\x{341}\x{200e}\x{200f}\x{202a}-\x{202e}\x{206a}-\x{206f}";
74     /* C9 - Tagging characters */
75     $chars .= "\x{e0001}\x{e0020}-\x{e007f}";
76
77     /* Nodeprep forbids some more characters */
78     $nodeprepchars = $chars;
79     $nodeprepchars .= "\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}";
80
81     $parts = explode("/", $jid, 2);
82     if (count($parts) > 1) {
83         $resource = $parts[1];
84         if ($resource == '') {
85             // Warning: empty resource isn't legit.
86             // But if we're normalizing, we may as well take it...
87         }
88     } else {
89         $resource = null;
90     }
91
92     $node = explode("@", $parts[0]);
93     if ((count($node) > 2) || (count($node) == 0)) {
94         throw new Exception("Invalid JID: too many @s");
95     } else if (count($node) == 1) {
96         $domain = $node[0];
97         $node = null;
98     } else {
99         $domain = $node[1];
100         $node = $node[0];
101         if ($node == '') {
102             throw new Exception("Invalid JID: @ but no node");
103         }
104     }
105
106     // Length limits per http://xmpp.org/rfcs/rfc3920.html#addressing
107     if ($node !== null) {
108         if (strlen($node) > 1023) {
109             throw new Exception("Invalid JID: node too long.");
110         }
111         if (preg_match("/[".$nodeprepchars."]/u", $node)) {
112             throw new Exception("Invalid JID node '$node'");
113         }
114     }
115
116     if (strlen($domain) > 1023) {
117         throw new Exception("Invalid JID: domain too long.");
118     }
119     if (!common_valid_domain($domain)) {
120         throw new Exception("Invalid JID domain name '$domain'");
121     }
122
123     if ($resource !== null) {
124         if (strlen($resource) > 1023) {
125             throw new Exception("Invalid JID: resource too long.");
126         }
127         if (preg_match("/[".$chars."]/u", $resource)) {
128             throw new Exception("Invalid JID resource '$resource'");
129         }
130     }
131
132     return array('node' => is_null($node) ? null : mb_strtolower($node),
133                  'domain' => is_null($domain) ? null : mb_strtolower($domain),
134                  'resource' => $resource);
135 }
136
137 /**
138  * Checks whether a string is a syntactically valid Jabber ID (JID),
139  * either with or without a resource.
140  * 
141  * Note that a bare domain can be a valid JID.
142  * 
143  * @param string $jid string to check
144  * @param bool $check_domain whether we should validate that domain...
145  *
146  * @return     boolean whether the string is a valid JID
147  */
148 function jabber_valid_full_jid($jid, $check_domain=false)
149 {
150     try {
151         $parts = jabber_split_jid($jid);
152         if ($check_domain) {
153             if (!jabber_check_domain($parts['domain'])) {
154                 return false;
155             }
156         }
157         return $parts['resource'] !== ''; // missing or present; empty ain't kosher
158     } catch (Exception $e) {
159         return false;
160     }
161 }
162
163 /**
164  * Checks whether a string is a syntactically valid base Jabber ID (JID).
165  * A base JID won't include a resource specifier on the end; since we
166  * take it off when reading input we can't really use them reliably
167  * to direct outgoing messages yet (sorry guys!)
168  * 
169  * Note that a bare domain can be a valid JID.
170  * 
171  * @param string $jid string to check
172  * @param bool $check_domain whether we should validate that domain...
173  *
174  * @return     boolean whether the string is a valid JID
175  */
176 function jabber_valid_base_jid($jid, $check_domain=false)
177 {
178     try {
179         $parts = jabber_split_jid($jid);
180         if ($check_domain) {
181             if (!jabber_check_domain($parts['domain'])) {
182                 return false;
183             }
184         }
185         return ($parts['resource'] === null); // missing; empty ain't kosher
186     } catch (Exception $e) {
187         return false;
188     }
189 }
190
191 /**
192  * Normalizes a Jabber ID for comparison, dropping the resource component if any.
193  *
194  * @param string $jid JID to check
195  * @param bool $check_domain if true, reject if the domain isn't findable
196  *
197  * @return string an equivalent JID in normalized (lowercase) form
198  */
199
200 function jabber_normalize_jid($jid)
201 {
202     try {
203         $parts = jabber_split_jid($jid);
204         if ($parts['node'] !== null) {
205             return $parts['node'] . '@' . $parts['domain'];
206         } else {
207             return $parts['domain'];
208         }
209     } catch (Exception $e) {
210         return null;
211     }
212 }
213
214 /**
215  * Check if this domain's got some legit DNS record
216  */
217 function jabber_check_domain($domain)
218 {
219     if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) {
220         return true;
221     }
222     if (checkdnsrr($domain, "ANY")) {
223         return true;
224     }
225     return false;
226 }
227
228 /**
229  * the JID of the Jabber daemon for this StatusNet instance
230  *
231  * @return string JID of the Jabber daemon
232  */
233
234 function jabber_daemon_address()
235 {
236     return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server');
237 }
238
239 class Sharing_XMPP extends XMPPHP_XMPP
240 {
241     function getSocket()
242     {
243         return $this->socket;
244     }
245 }
246
247 /**
248  * Build an XMPP proxy connection that'll save outgoing messages
249  * to the 'xmppout' queue to be picked up by xmppdaemon later.
250  *
251  * If queueing is disabled, we'll grab a live connection.
252  *
253  * @return XMPPHP
254  */
255 function jabber_proxy()
256 {
257     if (common_config('queue', 'enabled')) {
258             $proxy = new Queued_XMPP(common_config('xmpp', 'host') ?
259                                  common_config('xmpp', 'host') :
260                                  common_config('xmpp', 'server'),
261                                  common_config('xmpp', 'port'),
262                                  common_config('xmpp', 'user'),
263                                  common_config('xmpp', 'password'),
264                                  common_config('xmpp', 'resource') . 'daemon',
265                                  common_config('xmpp', 'server'),
266                                  common_config('xmpp', 'debug') ?
267                                  true : false,
268                                  common_config('xmpp', 'debug') ?
269                                  XMPPHP_Log::LEVEL_VERBOSE :  null);
270         return $proxy;
271     } else {
272         return jabber_connect();
273     }
274 }
275
276 /**
277  * Lazy-connect the configured Jabber account to the configured server;
278  * if already opened, the same connection will be returned.
279  *
280  * In a multi-site background process, each site configuration
281  * will get its own connection.
282  *
283  * @param string $resource Resource to connect (defaults to configured resource)
284  *
285  * @return XMPPHP connection to the configured server
286  */
287
288 function jabber_connect($resource=null)
289 {
290     static $connections = array();
291     $site = common_config('site', 'server');
292     if (empty($connections[$site])) {
293         if (empty($resource)) {
294             $resource = common_config('xmpp', 'resource');
295         }
296         $conn = new Sharing_XMPP(common_config('xmpp', 'host') ?
297                                 common_config('xmpp', 'host') :
298                                 common_config('xmpp', 'server'),
299                                 common_config('xmpp', 'port'),
300                                 common_config('xmpp', 'user'),
301                                 common_config('xmpp', 'password'),
302                                 $resource,
303                                 common_config('xmpp', 'server'),
304                                 common_config('xmpp', 'debug') ?
305                                 true : false,
306                                 common_config('xmpp', 'debug') ?
307                                 XMPPHP_Log::LEVEL_VERBOSE :  null
308                                 );
309
310         if (!$conn) {
311             return false;
312         }
313         $connections[$site] = $conn;
314
315         $conn->autoSubscribe();
316         $conn->useEncryption(common_config('xmpp', 'encryption'));
317
318         try {
319             common_log(LOG_INFO, __METHOD__ . ": connecting " .
320                 common_config('xmpp', 'user') . '/' . $resource);
321             //$conn->connect(true); // true = persistent connection
322             $conn->connect(); // persistent connections break multisite
323         } catch (XMPPHP_Exception $e) {
324             common_log(LOG_ERR, $e->getMessage());
325             return false;
326         }
327
328         $conn->processUntil('session_start');
329     }
330     return $connections[$site];
331 }
332
333 /**
334  * Queue send for a single notice to a given Jabber address
335  *
336  * @param string $to     JID to send the notice to
337  * @param Notice $notice notice to send
338  *
339  * @return boolean success value
340  */
341
342 function jabber_send_notice($to, $notice)
343 {
344     $conn = jabber_proxy();
345     $profile = Profile::staticGet($notice->profile_id);
346     if (!$profile) {
347         common_log(LOG_WARNING, 'Refusing to send notice with ' .
348                    'unknown profile ' . common_log_objstring($notice),
349                    __FILE__);
350         return false;
351     }
352     $msg   = jabber_format_notice($profile, $notice);
353     $entry = jabber_format_entry($profile, $notice);
354     $conn->message($to, $msg, 'chat', null, $entry);
355     $profile->free();
356     return true;
357 }
358
359 /**
360  * extra information for XMPP messages, as defined by Twitter
361  *
362  * @param Profile $profile Profile of the sending user
363  * @param Notice  $notice  Notice being sent
364  *
365  * @return string Extra information (Atom, HTML, addresses) in string format
366  */
367
368 function jabber_format_entry($profile, $notice)
369 {
370     $entry = $notice->asAtomEntry(true, true);
371
372     $xs = new XMLStringer();
373     $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
374     $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
375     $xs->element('a', array('href' => $profile->profileurl),
376                  $profile->nickname);
377     $xs->text(": ");
378     if (!empty($notice->rendered)) {
379         $xs->raw($notice->rendered);
380     } else {
381         $xs->raw(common_render_content($notice->content, $notice));
382     }
383     $xs->text(" ");
384     $xs->element('a', array(
385         'href'=>common_local_url('conversation',
386             array('id' => $notice->conversation)).'#notice-'.$notice->id
387          ),sprintf(_('[%s]'),$notice->id));
388     $xs->elementEnd('body');
389     $xs->elementEnd('html');
390
391     $html = $xs->getString();
392
393     return $html . ' ' . $entry;
394 }
395
396 /**
397  * sends a single text message to a given JID
398  *
399  * @param string $to      JID to send the message to
400  * @param string $body    body of the message
401  * @param string $type    type of the message
402  * @param string $subject subject of the message
403  *
404  * @return boolean success flag
405  */
406
407 function jabber_send_message($to, $body, $type='chat', $subject=null)
408 {
409     $conn = jabber_proxy();
410     $conn->message($to, $body, $type, $subject);
411     return true;
412 }
413
414 /**
415  * sends a presence stanza on the Jabber network
416  *
417  * @param string $status   current status, free-form string
418  * @param string $show     structured status value
419  * @param string $to       recipient of presence, null for general
420  * @param string $type     type of status message, related to $show
421  * @param int    $priority priority of the presence
422  *
423  * @return boolean success value
424  */
425
426 function jabber_send_presence($status, $show='available', $to=null,
427                               $type = 'available', $priority=null)
428 {
429     $conn = jabber_connect();
430     if (!$conn) {
431         return false;
432     }
433     $conn->presence($status, $show, $to, $type, $priority);
434     return true;
435 }
436
437 /**
438  * sends a confirmation request to a JID
439  *
440  * @param string $code     confirmation code for confirmation URL
441  * @param string $nickname nickname of confirming user
442  * @param string $address  JID to send confirmation to
443  *
444  * @return boolean success flag
445  */
446
447 function jabber_confirm_address($code, $nickname, $address)
448 {
449     $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' .
450       'has said that your Jabber ID belongs to them. ' .
451       'If that\'s true, you can confirm by clicking on this URL: ' .
452       common_local_url('confirmaddress', array('code' => $code)) .
453       ' . (If you cannot click it, copy-and-paste it into the ' .
454       'address bar of your browser). If that user isn\'t you, ' .
455       'or if you didn\'t request this confirmation, just ignore this message.';
456
457     return jabber_send_message($address, $body);
458 }
459
460 /**
461  * sends a "special" presence stanza on the Jabber network
462  *
463  * @param string $type   Type of presence
464  * @param string $to     JID to send presence to
465  * @param string $show   show value for presence
466  * @param string $status status value for presence
467  *
468  * @return boolean success flag
469  *
470  * @see jabber_send_presence()
471  */
472
473 function jabber_special_presence($type, $to=null, $show=null, $status=null)
474 {
475     // FIXME: why use this instead of jabber_send_presence()?
476     $conn = jabber_connect();
477
478     $to     = htmlspecialchars($to);
479     $status = htmlspecialchars($status);
480
481     $out = "<presence";
482     if ($to) {
483         $out .= " to='$to'";
484     }
485     if ($type) {
486         $out .= " type='$type'";
487     }
488     if ($show == 'available' and !$status) {
489         $out .= "/>";
490     } else {
491         $out .= ">";
492         if ($show && ($show != 'available')) {
493             $out .= "<show>$show</show>";
494         }
495         if ($status) {
496             $out .= "<status>$status</status>";
497         }
498         $out .= "</presence>";
499     }
500     $conn->send($out);
501 }
502
503 /**
504  * Queue broadcast of a notice to all subscribers and reply recipients
505  *
506  * This function will send a notice to all subscribers on the local server
507  * who have Jabber addresses, and have Jabber notification enabled, and
508  * have this subscription enabled for Jabber. It also sends the notice to
509  * all recipients of @-replies who have Jabber addresses and Jabber notification
510  * enabled. This is really the heart of Jabber distribution in StatusNet.
511  *
512  * @param Notice $notice The notice to broadcast
513  *
514  * @return boolean success flag
515  */
516
517 function jabber_broadcast_notice($notice)
518 {
519     if (!common_config('xmpp', 'enabled')) {
520         return true;
521     }
522     $profile = Profile::staticGet($notice->profile_id);
523
524     if (!$profile) {
525         common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
526                    'unknown profile ' . common_log_objstring($notice),
527                    __FILE__);
528         return true; // not recoverable; discard.
529     }
530
531     $msg   = jabber_format_notice($profile, $notice);
532     $entry = jabber_format_entry($profile, $notice);
533
534     $profile->free();
535     unset($profile);
536
537     $sent_to = array();
538
539     $conn = jabber_proxy();
540
541     $ni = $notice->whoGets();
542
543     foreach ($ni as $user_id => $reason) {
544         $user = User::staticGet($user_id);
545         if (empty($user) ||
546             empty($user->jabber) ||
547             !$user->jabbernotify) {
548             // either not a local user, or just not found
549             continue;
550         }
551         switch ($reason) {
552         case NOTICE_INBOX_SOURCE_REPLY:
553             if (!$user->jabberreplies) {
554                 continue 2;
555             }
556             break;
557         case NOTICE_INBOX_SOURCE_SUB:
558             $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
559                                                'subscribed' => $notice->profile_id));
560             if (empty($sub) || !$sub->jabber) {
561                 continue 2;
562             }
563             break;
564         case NOTICE_INBOX_SOURCE_GROUP:
565             break;
566         default:
567             throw new Exception(sprintf(_("Unknown inbox source %d."), $reason));
568         }
569
570         common_log(LOG_INFO,
571                    'Sending notice ' . $notice->id . ' to ' . $user->jabber,
572                    __FILE__);
573         $conn->message($user->jabber, $msg, 'chat', null, $entry);
574     }
575
576     return true;
577 }
578
579 /**
580  * Queue send of a notice to all public listeners
581  *
582  * For notices that are generated on the local system (by users), we can optionally
583  * forward them to remote listeners by XMPP.
584  *
585  * @param Notice $notice notice to broadcast
586  *
587  * @return boolean success flag
588  */
589
590 function jabber_public_notice($notice)
591 {
592     // Now, users who want everything
593
594     $public = common_config('xmpp', 'public');
595
596     // FIXME PRIV don't send out private messages here
597     // XXX: should we send out non-local messages if public,localonly
598     // = false? I think not
599
600     if ($public && $notice->is_local == Notice::LOCAL_PUBLIC) {
601         $profile = Profile::staticGet($notice->profile_id);
602
603         if (!$profile) {
604             common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
605                        'unknown profile ' . common_log_objstring($notice),
606                        __FILE__);
607             return true; // not recoverable; discard.
608         }
609
610         $msg   = jabber_format_notice($profile, $notice);
611         $entry = jabber_format_entry($profile, $notice);
612
613         $conn = jabber_proxy();
614
615         foreach ($public as $address) {
616             common_log(LOG_INFO,
617                        'Sending notice ' . $notice->id .
618                        ' to public listener ' . $address,
619                        __FILE__);
620             $conn->message($address, $msg, 'chat', null, $entry);
621         }
622         $profile->free();
623     }
624
625     return true;
626 }
627
628 /**
629  * makes a plain-text formatted version of a notice, suitable for Jabber distribution
630  *
631  * @param Profile &$profile profile of the sending user
632  * @param Notice  &$notice  notice being sent
633  *
634  * @return string plain-text version of the notice, with user nickname prefixed
635  */
636
637 function jabber_format_notice(&$profile, &$notice)
638 {
639     return $profile->nickname . ': ' . $notice->content . ' [' . $notice->id . ']';
640 }