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