]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/jabber.php
Merge branch 'testing' of git@gitorious.org:statusnet/mainline into 0.9.x
[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  * checks whether a string is a syntactically valid Jabber ID (JID)
38  *
39  * @param string $jid string to check
40  *
41  * @return     boolean whether the string is a valid JID
42  */
43
44 function jabber_valid_base_jid($jid)
45 {
46     // Cheap but effective
47     return Validate::email($jid);
48 }
49
50 /**
51  * normalizes a Jabber ID for comparison
52  *
53  * @param string $jid JID to check
54  *
55  * @return string an equivalent JID in normalized (lowercase) form
56  */
57
58 function jabber_normalize_jid($jid)
59 {
60     if (preg_match("/(?:([^\@]+)\@)?([^\/]+)(?:\/(.*))?$/", $jid, $matches)) {
61         $node   = $matches[1];
62         $server = $matches[2];
63         return strtolower($node.'@'.$server);
64     } else {
65         return null;
66     }
67 }
68
69 /**
70  * the JID of the Jabber daemon for this StatusNet instance
71  *
72  * @return string JID of the Jabber daemon
73  */
74
75 function jabber_daemon_address()
76 {
77     return common_config('xmpp', 'user') . '@' . common_config('xmpp', 'server');
78 }
79
80 class Sharing_XMPP extends XMPPHP_XMPP
81 {
82     function getSocket()
83     {
84         return $this->socket;
85     }
86 }
87
88 /**
89  * Build an XMPP proxy connection that'll save outgoing messages
90  * to the 'xmppout' queue to be picked up by xmppdaemon later.
91  */
92 function jabber_proxy()
93 {
94         $proxy = new Queued_XMPP(common_config('xmpp', 'host') ?
95                              common_config('xmpp', 'host') :
96                              common_config('xmpp', 'server'),
97                              common_config('xmpp', 'port'),
98                              common_config('xmpp', 'user'),
99                              common_config('xmpp', 'password'),
100                              common_config('xmpp', 'resource') . 'daemon',
101                              common_config('xmpp', 'server'),
102                              common_config('xmpp', 'debug') ?
103                              true : false,
104                              common_config('xmpp', 'debug') ?
105                              XMPPHP_Log::LEVEL_VERBOSE :  null);
106     return $proxy;
107 }
108
109 /**
110  * Lazy-connect the configured Jabber account to the configured server;
111  * if already opened, the same connection will be returned.
112  *
113  * In a multi-site background process, each site configuration
114  * will get its own connection.
115  *
116  * @param string $resource Resource to connect (defaults to configured resource)
117  *
118  * @return XMPPHP connection to the configured server
119  */
120
121 function jabber_connect($resource=null)
122 {
123     static $connections = array();
124     $site = common_config('site', 'server');
125     if (empty($connections[$site])) {
126         if (empty($resource)) {
127             $resource = common_config('xmpp', 'resource');
128         }
129         $conn = new Sharing_XMPP(common_config('xmpp', 'host') ?
130                                 common_config('xmpp', 'host') :
131                                 common_config('xmpp', 'server'),
132                                 common_config('xmpp', 'port'),
133                                 common_config('xmpp', 'user'),
134                                 common_config('xmpp', 'password'),
135                                 $resource,
136                                 common_config('xmpp', 'server'),
137                                 common_config('xmpp', 'debug') ?
138                                 true : false,
139                                 common_config('xmpp', 'debug') ?
140                                 XMPPHP_Log::LEVEL_VERBOSE :  null
141                                 );
142
143         if (!$conn) {
144             return false;
145         }
146         $connections[$site] = $conn;
147
148         $conn->autoSubscribe();
149         $conn->useEncryption(common_config('xmpp', 'encryption'));
150
151         try {
152             common_log(LOG_INFO, __METHOD__ . ": connecting " .
153                 common_config('xmpp', 'user') . '/' . $resource);
154             //$conn->connect(true); // true = persistent connection
155             $conn->connect(); // persistent connections break multisite
156         } catch (XMPPHP_Exception $e) {
157             common_log(LOG_ERR, $e->getMessage());
158             return false;
159         }
160
161         $conn->processUntil('session_start');
162     }
163     return $connections[$site];
164 }
165
166 /**
167  * Queue send for a single notice to a given Jabber address
168  *
169  * @param string $to     JID to send the notice to
170  * @param Notice $notice notice to send
171  *
172  * @return boolean success value
173  */
174
175 function jabber_send_notice($to, $notice)
176 {
177     $conn = jabber_proxy();
178     $profile = Profile::staticGet($notice->profile_id);
179     if (!$profile) {
180         common_log(LOG_WARNING, 'Refusing to send notice with ' .
181                    'unknown profile ' . common_log_objstring($notice),
182                    __FILE__);
183         return false;
184     }
185     $msg   = jabber_format_notice($profile, $notice);
186     $entry = jabber_format_entry($profile, $notice);
187     $conn->message($to, $msg, 'chat', null, $entry);
188     $profile->free();
189     return true;
190 }
191
192 /**
193  * extra information for XMPP messages, as defined by Twitter
194  *
195  * @param Profile $profile Profile of the sending user
196  * @param Notice  $notice  Notice being sent
197  *
198  * @return string Extra information (Atom, HTML, addresses) in string format
199  */
200
201 function jabber_format_entry($profile, $notice)
202 {
203     $entry = $notice->asAtomEntry(true, true);
204
205     $xs = new XMLStringer();
206     $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
207     $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
208     $xs->element('a', array('href' => $profile->profileurl),
209                  $profile->nickname);
210     $xs->text(": ");
211     if (!empty($notice->rendered)) {
212         $xs->raw($notice->rendered);
213     } else {
214         $xs->raw(common_render_content($notice->content, $notice));
215     }
216     $xs->text(" ");
217     $xs->element('a', array(
218         'href'=>common_local_url('conversation',
219             array('id' => $notice->conversation)).'#notice-'.$notice->id
220          ),sprintf(_('[%s]'),$notice->id));
221     $xs->elementEnd('body');
222     $xs->elementEnd('html');
223
224     $html = $xs->getString();
225
226     return $html . ' ' . $entry;
227 }
228
229 /**
230  * sends a single text message to a given JID
231  *
232  * @param string $to      JID to send the message to
233  * @param string $body    body of the message
234  * @param string $type    type of the message
235  * @param string $subject subject of the message
236  *
237  * @return boolean success flag
238  */
239
240 function jabber_send_message($to, $body, $type='chat', $subject=null)
241 {
242     $conn = jabber_proxy();
243     $conn->message($to, $body, $type, $subject);
244     return true;
245 }
246
247 /**
248  * sends a presence stanza on the Jabber network
249  *
250  * @param string $status   current status, free-form string
251  * @param string $show     structured status value
252  * @param string $to       recipient of presence, null for general
253  * @param string $type     type of status message, related to $show
254  * @param int    $priority priority of the presence
255  *
256  * @return boolean success value
257  */
258
259 function jabber_send_presence($status, $show='available', $to=null,
260                               $type = 'available', $priority=null)
261 {
262     $conn = jabber_connect();
263     if (!$conn) {
264         return false;
265     }
266     $conn->presence($status, $show, $to, $type, $priority);
267     return true;
268 }
269
270 /**
271  * sends a confirmation request to a JID
272  *
273  * @param string $code     confirmation code for confirmation URL
274  * @param string $nickname nickname of confirming user
275  * @param string $address  JID to send confirmation to
276  *
277  * @return boolean success flag
278  */
279
280 function jabber_confirm_address($code, $nickname, $address)
281 {
282     $body = 'User "' . $nickname . '" on ' . common_config('site', 'name') . ' ' .
283       'has said that your Jabber ID belongs to them. ' .
284       'If that\'s true, you can confirm by clicking on this URL: ' .
285       common_local_url('confirmaddress', array('code' => $code)) .
286       ' . (If you cannot click it, copy-and-paste it into the ' .
287       'address bar of your browser). If that user isn\'t you, ' .
288       'or if you didn\'t request this confirmation, just ignore this message.';
289
290     return jabber_send_message($address, $body);
291 }
292
293 /**
294  * sends a "special" presence stanza on the Jabber network
295  *
296  * @param string $type   Type of presence
297  * @param string $to     JID to send presence to
298  * @param string $show   show value for presence
299  * @param string $status status value for presence
300  *
301  * @return boolean success flag
302  *
303  * @see jabber_send_presence()
304  */
305
306 function jabber_special_presence($type, $to=null, $show=null, $status=null)
307 {
308     // FIXME: why use this instead of jabber_send_presence()?
309     $conn = jabber_connect();
310
311     $to     = htmlspecialchars($to);
312     $status = htmlspecialchars($status);
313
314     $out = "<presence";
315     if ($to) {
316         $out .= " to='$to'";
317     }
318     if ($type) {
319         $out .= " type='$type'";
320     }
321     if ($show == 'available' and !$status) {
322         $out .= "/>";
323     } else {
324         $out .= ">";
325         if ($show && ($show != 'available')) {
326             $out .= "<show>$show</show>";
327         }
328         if ($status) {
329             $out .= "<status>$status</status>";
330         }
331         $out .= "</presence>";
332     }
333     $conn->send($out);
334 }
335
336 /**
337  * Queue broadcast of a notice to all subscribers and reply recipients
338  *
339  * This function will send a notice to all subscribers on the local server
340  * who have Jabber addresses, and have Jabber notification enabled, and
341  * have this subscription enabled for Jabber. It also sends the notice to
342  * all recipients of @-replies who have Jabber addresses and Jabber notification
343  * enabled. This is really the heart of Jabber distribution in StatusNet.
344  *
345  * @param Notice $notice The notice to broadcast
346  *
347  * @return boolean success flag
348  */
349
350 function jabber_broadcast_notice($notice)
351 {
352     if (!common_config('xmpp', 'enabled')) {
353         return true;
354     }
355     $profile = Profile::staticGet($notice->profile_id);
356
357     if (!$profile) {
358         common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
359                    'unknown profile ' . common_log_objstring($notice),
360                    __FILE__);
361         return true; // not recoverable; discard.
362     }
363
364     $msg   = jabber_format_notice($profile, $notice);
365     $entry = jabber_format_entry($profile, $notice);
366
367     $profile->free();
368     unset($profile);
369
370     $sent_to = array();
371
372     $conn = jabber_proxy();
373
374     $ni = $notice->whoGets();
375
376     foreach ($ni as $user_id => $reason) {
377         $user = User::staticGet($user_id);
378         if (empty($user) ||
379             empty($user->jabber) ||
380             !$user->jabbernotify) {
381             // either not a local user, or just not found
382             continue;
383         }
384         switch ($reason) {
385         case NOTICE_INBOX_SOURCE_REPLY:
386             if (!$user->jabberreplies) {
387                 continue 2;
388             }
389             break;
390         case NOTICE_INBOX_SOURCE_SUB:
391             $sub = Subscription::pkeyGet(array('subscriber' => $user->id,
392                                                'subscribed' => $notice->profile_id));
393             if (empty($sub) || !$sub->jabber) {
394                 continue 2;
395             }
396             break;
397         case NOTICE_INBOX_SOURCE_GROUP:
398             break;
399         default:
400             throw new Exception(sprintf(_("Unknown inbox source %d."), $reason));
401         }
402
403         common_log(LOG_INFO,
404                    'Sending notice ' . $notice->id . ' to ' . $user->jabber,
405                    __FILE__);
406         $conn->message($user->jabber, $msg, 'chat', null, $entry);
407     }
408
409     return true;
410 }
411
412 /**
413  * Queue send of a notice to all public listeners
414  *
415  * For notices that are generated on the local system (by users), we can optionally
416  * forward them to remote listeners by XMPP.
417  *
418  * @param Notice $notice notice to broadcast
419  *
420  * @return boolean success flag
421  */
422
423 function jabber_public_notice($notice)
424 {
425     // Now, users who want everything
426
427     $public = common_config('xmpp', 'public');
428
429     // FIXME PRIV don't send out private messages here
430     // XXX: should we send out non-local messages if public,localonly
431     // = false? I think not
432
433     if ($public && $notice->is_local == Notice::LOCAL_PUBLIC) {
434         $profile = Profile::staticGet($notice->profile_id);
435
436         if (!$profile) {
437             common_log(LOG_WARNING, 'Refusing to broadcast notice with ' .
438                        'unknown profile ' . common_log_objstring($notice),
439                        __FILE__);
440             return true; // not recoverable; discard.
441         }
442
443         $msg   = jabber_format_notice($profile, $notice);
444         $entry = jabber_format_entry($profile, $notice);
445
446         $conn = jabber_proxy();
447
448         foreach ($public as $address) {
449             common_log(LOG_INFO,
450                        'Sending notice ' . $notice->id .
451                        ' to public listener ' . $address,
452                        __FILE__);
453             $conn->message($address, $msg, 'chat', null, $entry);
454         }
455         $profile->free();
456     }
457
458     return true;
459 }
460
461 /**
462  * makes a plain-text formatted version of a notice, suitable for Jabber distribution
463  *
464  * @param Profile &$profile profile of the sending user
465  * @param Notice  &$notice  notice being sent
466  *
467  * @return string plain-text version of the notice, with user nickname prefixed
468  */
469
470 function jabber_format_notice(&$profile, &$notice)
471 {
472     return $profile->nickname . ': ' . $notice->content . ' [' . $notice->id . ']';
473 }