3 * StatusNet, the distributed open-source microblogging tool
5 * utility functions for Jabber/GTalk/XMPP messages
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.
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.
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/>.
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/
30 if (!defined('STATUSNET') && !defined('LACONICA')) {
34 require_once 'XMPPHP/XMPP.php';
37 * Splits a Jabber ID (JID) into node, domain, and resource portions.
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.
43 * @param string $jid string to check
45 * @return array with "node", "domain", and "resource" indices
46 * @throws Exception if input is not valid
49 function jabber_split_jid($jid)
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 */
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}";
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}";
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...
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) {
102 throw new Exception("Invalid JID: @ but no node");
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.");
111 if (preg_match("/[".$nodeprepchars."]/u", $node)) {
112 throw new Exception("Invalid JID node '$node'");
116 if (strlen($domain) > 1023) {
117 throw new Exception("Invalid JID: domain too long.");
119 if (!common_valid_domain($domain)) {
120 throw new Exception("Invalid JID domain name '$domain'");
123 if ($resource !== null) {
124 if (strlen($resource) > 1023) {
125 throw new Exception("Invalid JID: resource too long.");
127 if (preg_match("/[".$chars."]/u", $resource)) {
128 throw new Exception("Invalid JID resource '$resource'");
132 return array('node' => is_null($node) ? null : mb_strtolower($node),
133 'domain' => is_null($domain) ? null : mb_strtolower($domain),
134 'resource' => $resource);
138 * Checks whether a string is a syntactically valid Jabber ID (JID),
139 * either with or without a resource.
141 * Note that a bare domain can be a valid JID.
143 * @param string $jid string to check
144 * @param bool $check_domain whether we should validate that domain...
146 * @return boolean whether the string is a valid JID
148 function jabber_valid_full_jid($jid, $check_domain=false)
151 $parts = jabber_split_jid($jid);
153 if (!jabber_check_domain($parts['domain'])) {
157 return $parts['resource'] !== ''; // missing or present; empty ain't kosher
158 } catch (Exception $e) {
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!)
169 * Note that a bare domain can be a valid JID.
171 * @param string $jid string to check
172 * @param bool $check_domain whether we should validate that domain...
174 * @return boolean whether the string is a valid JID
176 function jabber_valid_base_jid($jid, $check_domain=false)
179 $parts = jabber_split_jid($jid);
181 if (!jabber_check_domain($parts['domain'])) {
185 return ($parts['resource'] === null); // missing; empty ain't kosher
186 } catch (Exception $e) {
192 * Normalizes a Jabber ID for comparison, dropping the resource component if any.
194 * @param string $jid JID to check
195 * @param bool $check_domain if true, reject if the domain isn't findable
197 * @return string an equivalent JID in normalized (lowercase) form
200 function jabber_normalize_jid($jid)
203 $parts = jabber_split_jid($jid);
204 if ($parts['node'] !== null) {
205 return $parts['node'] . '@' . $parts['domain'];
207 return $parts['domain'];
209 } catch (Exception $e) {
215 * Check if this domain's got some legit DNS record
217 function jabber_check_domain($domain)
219 if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) {
222 if (checkdnsrr($domain, "ANY")) {
229 * the JID of the Jabber daemon for this StatusNet instance
231 * @return string JID of the Jabber daemon
234 function jabber_daemon_address()
236 return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server');
239 class Sharing_XMPP extends XMPPHP_XMPP
243 return $this->socket;
248 * Build an XMPP proxy connection that'll save outgoing messages
249 * to the 'xmppout' queue to be picked up by xmppdaemon later.
251 * If queueing is disabled, we'll grab a live connection.
255 function jabber_proxy()
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') ?
268 common_config('xmpp', 'debug') ?
269 XMPPHP_Log::LEVEL_VERBOSE : null);
272 return jabber_connect();
277 * Lazy-connect the configured Jabber account to the configured server;
278 * if already opened, the same connection will be returned.
280 * In a multi-site background process, each site configuration
281 * will get its own connection.
283 * @param string $resource Resource to connect (defaults to configured resource)
285 * @return XMPPHP connection to the configured server
288 function jabber_connect($resource=null)
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');
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'),
303 common_config('xmpp', 'server'),
304 common_config('xmpp', 'debug') ?
306 common_config('xmpp', 'debug') ?
307 XMPPHP_Log::LEVEL_VERBOSE : null
313 $connections[$site] = $conn;
315 $conn->autoSubscribe();
316 $conn->useEncryption(common_config('xmpp', 'encryption'));
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());
328 $conn->processUntil('session_start');
330 return $connections[$site];
334 * Queue send for a single notice to a given Jabber address
336 * @param string $to JID to send the notice to
337 * @param Notice $notice notice to send
339 * @return boolean success value
342 function jabber_send_notice($to, $notice)
344 $conn = jabber_proxy();
345 $profile = Profile::staticGet($notice->profile_id);
347 common_log(LOG_WARNING, 'Refusing to send notice with ' .
348 'unknown profile ' . common_log_objstring($notice),
352 $msg = jabber_format_notice($profile, $notice);
353 $entry = jabber_format_entry($profile, $notice);
354 $conn->message($to, $msg, 'chat', null, $entry);
360 * extra information for XMPP messages, as defined by Twitter
362 * @param Profile $profile Profile of the sending user
363 * @param Notice $notice Notice being sent
365 * @return string Extra information (Atom, HTML, addresses) in string format
368 function jabber_format_entry($profile, $notice)
370 $entry = $notice->asAtomEntry(true, true);
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),
378 if (!empty($notice->rendered)) {
379 $xs->raw($notice->rendered);
381 $xs->raw(common_render_content($notice->content, $notice));
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');
391 $html = $xs->getString();
393 return $html . ' ' . $entry;
397 * sends a single text message to a given JID
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
404 * @return boolean success flag
407 function jabber_send_message($to, $body, $type='chat', $subject=null)
409 $conn = jabber_proxy();
410 $conn->message($to, $body, $type, $subject);
415 * sends a presence stanza on the Jabber network
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
423 * @return boolean success value
426 function jabber_send_presence($status, $show='available', $to=null,
427 $type = 'available', $priority=null)
429 $conn = jabber_connect();
433 $conn->presence($status, $show, $to, $type, $priority);
438 * sends a confirmation request to a JID
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
444 * @return boolean success flag
447 function jabber_confirm_address($code, $nickname, $address)
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.';
457 return jabber_send_message($address, $body);
461 * sends a "special" presence stanza on the Jabber network
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
468 * @return boolean success flag
470 * @see jabber_send_presence()
473 function jabber_special_presence($type, $to=null, $show=null, $status=null)
475 // FIXME: why use this instead of jabber_send_presence()?
476 $conn = jabber_connect();
478 $to = htmlspecialchars($to);
479 $status = htmlspecialchars($status);
486 $out .= " type='$type'";
488 if ($show == 'available' and !$status) {
492 if ($show && ($show != 'available')) {
493 $out .= "<show>$show</show>";
496 $out .= "<status>$status</status>";
498 $out .= "</presence>";
504 * Queue broadcast of a notice to all subscribers and reply recipients
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.
512 * @param Notice $notice The notice to broadcast
514 * @return boolean success flag
517 function jabber_broadcast_notice($notice)
519 if (!common_config('xmpp', 'enabled')) {
522 $profile = Profile::staticGet($notice->profile_id);
525 common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
526 'unknown profile ' . common_log_objstring($notice),
528 return true; // not recoverable; discard.
531 $msg = jabber_format_notice($profile, $notice);
532 $entry = jabber_format_entry($profile, $notice);
539 $conn = jabber_proxy();
541 $ni = $notice->whoGets();
543 foreach ($ni as $user_id => $reason) {
544 $user = User::staticGet($user_id);
546 empty($user->jabber) ||
547 !$user->jabbernotify) {
548 // either not a local user, or just not found
552 case NOTICE_INBOX_SOURCE_REPLY:
553 if (!$user->jabberreplies) {
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) {
564 case NOTICE_INBOX_SOURCE_GROUP:
567 throw new Exception(sprintf(_("Unknown inbox source %d."), $reason));
571 'Sending notice ' . $notice->id . ' to ' . $user->jabber,
573 $conn->message($user->jabber, $msg, 'chat', null, $entry);
580 * Queue send of a notice to all public listeners
582 * For notices that are generated on the local system (by users), we can optionally
583 * forward them to remote listeners by XMPP.
585 * @param Notice $notice notice to broadcast
587 * @return boolean success flag
590 function jabber_public_notice($notice)
592 // Now, users who want everything
594 $public = common_config('xmpp', 'public');
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
600 if ($public && $notice->is_local == Notice::LOCAL_PUBLIC) {
601 $profile = Profile::staticGet($notice->profile_id);
604 common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
605 'unknown profile ' . common_log_objstring($notice),
607 return true; // not recoverable; discard.
610 $msg = jabber_format_notice($profile, $notice);
611 $entry = jabber_format_entry($profile, $notice);
613 $conn = jabber_proxy();
615 foreach ($public as $address) {
617 'Sending notice ' . $notice->id .
618 ' to public listener ' . $address,
620 $conn->message($address, $msg, 'chat', null, $entry);
629 * makes a plain-text formatted version of a notice, suitable for Jabber distribution
631 * @param Profile &$profile profile of the sending user
632 * @param Notice &$notice notice being sent
634 * @return string plain-text version of the notice, with user nickname prefixed
637 function jabber_format_notice(&$profile, &$notice)
639 return $profile->nickname . ': ' . $notice->content . ' [' . $notice->id . ']';