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