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