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