]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Xmpp/XmppPlugin.php
Merge remote-tracking branch 'upstream/master' into social-master
[quix0rs-gnu-social.git] / plugins / Xmpp / XmppPlugin.php
1 <?php
2 /**
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2009, StatusNet, Inc.
5  *
6  * Send and receive notices using the XMPP network
7  *
8  * PHP version 5
9  *
10  * This program is free software: you can redistribute it and/or modify
11  * it under the terms of the GNU Affero General Public License as published by
12  * the Free Software Foundation, either version 3 of the License, or
13  * (at your option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful,
16  * but WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18  * GNU Affero General Public License for more details.
19  *
20  * You should have received a copy of the GNU Affero General Public License
21  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  * @category  IM
24  * @package   StatusNet
25  * @author    Evan Prodromou <evan@status.net>
26  * @copyright 2009 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     // This check helps protect against security problems;
33     // your code file can't be executed directly from the web.
34     exit(1);
35 }
36
37 /**
38  * Plugin for XMPP
39  *
40  * @category  Plugin
41  * @package   StatusNet
42  * @author    Evan Prodromou <evan@status.net>
43  * @copyright 2009 StatusNet, Inc.
44  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
45  * @link      http://status.net/
46  */
47 class XmppPlugin extends ImPlugin
48 {
49     public $server = null;
50     public $port = 5222;
51     public $user =  'update';
52     public $resource = 'gnusocial';
53     public $encryption = true;
54     public $password = null;
55     public $host = null;  // only set if != server
56     public $debug = false; // print extra debug info
57
58     public $transport = 'xmpp';
59
60     function getDisplayName(){
61         // TRANS: Plugin display name.
62         return _m('XMPP/Jabber');
63     }
64
65     /**
66      * Splits a Jabber ID (JID) into node, domain, and resource portions.
67      *
68      * Based on validation routine submitted by:
69      * @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
70      * @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact.
71      *
72      * @param string $jid string to check
73      *
74      * @return array with "node", "domain", and "resource" indices
75      * @throws Exception if input is not valid
76      */
77     protected function splitJid($jid)
78     {
79         $chars = '';
80         /* the following definitions come from stringprep, Appendix C,
81            which is used in its entirety by nodeprop, Chapter 5, "Prohibited Output" */
82         /* C1.1 ASCII space characters */
83         $chars .= "\x{20}";
84         /* C1.2 Non-ASCII space characters */
85         $chars .= "\x{a0}\x{1680}\x{2000}-\x{200b}\x{202f}\x{205f}\x{3000a}";
86         /* C2.1 ASCII control characters */
87         $chars .= "\x{00}-\x{1f}\x{7f}";
88         /* C2.2 Non-ASCII control characters */
89         $chars .= "\x{80}-\x{9f}\x{6dd}\x{70f}\x{180e}\x{200c}\x{200d}\x{2028}\x{2029}\x{2060}-\x{2063}\x{206a}-\x{206f}\x{feff}\x{fff9}-\x{fffc}\x{1d173}-\x{1d17a}";
90         /* C3 - Private Use */
91         $chars .= "\x{e000}-\x{f8ff}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}";
92         /* C4 - Non-character code points */
93         $chars .= "\x{fdd0}-\x{fdef}\x{fffe}\x{ffff}\x{1fffe}\x{1ffff}\x{2fffe}\x{2ffff}\x{3fffe}\x{3ffff}\x{4fffe}\x{4ffff}\x{5fffe}\x{5ffff}\x{6fffe}\x{6ffff}\x{7fffe}\x{7ffff}\x{8fffe}\x{8ffff}\x{9fffe}\x{9ffff}\x{afffe}\x{affff}\x{bfffe}\x{bffff}\x{cfffe}\x{cffff}\x{dfffe}\x{dffff}\x{efffe}\x{effff}\x{ffffe}\x{fffff}\x{10fffe}\x{10ffff}";
94         /* C5 - Surrogate codes */
95         $chars .= "\x{d800}-\x{dfff}";
96         /* C6 - Inappropriate for plain text */
97         $chars .= "\x{fff9}-\x{fffd}";
98         /* C7 - Inappropriate for canonical representation */
99         $chars .= "\x{2ff0}-\x{2ffb}";
100         /* C8 - Change display properties or are deprecated */
101         $chars .= "\x{340}\x{341}\x{200e}\x{200f}\x{202a}-\x{202e}\x{206a}-\x{206f}";
102         /* C9 - Tagging characters */
103         $chars .= "\x{e0001}\x{e0020}-\x{e007f}";
104
105         /* Nodeprep forbids some more characters */
106         $nodeprepchars = $chars;
107         $nodeprepchars .= "\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}";
108
109         $parts = explode("/", $jid, 2);
110         if (count($parts) > 1) {
111             $resource = $parts[1];
112             if ($resource == '') {
113                 // Warning: empty resource isn't legit.
114                 // But if we're normalizing, we may as well take it...
115             }
116         } else {
117             $resource = null;
118         }
119
120         $node = explode("@", $parts[0]);
121         if ((count($node) > 2) || (count($node) == 0)) {
122             // TRANS: Exception thrown when using too many @ signs in a Jabber ID.
123             throw new Exception(_m('Invalid JID: too many @s.'));
124         } else if (count($node) == 1) {
125             $domain = $node[0];
126             $node = null;
127         } else {
128             $domain = $node[1];
129             $node = $node[0];
130             if ($node == '') {
131             // TRANS: Exception thrown when using @ sign not followed by a Jabber ID.
132                 throw new Exception(_m('Invalid JID: @ but no node'));
133             }
134         }
135
136         // Length limits per http://xmpp.org/rfcs/rfc3920.html#addressing
137         if ($node !== null) {
138             if (strlen($node) > 1023) {
139                 // TRANS: Exception thrown when using too long a Jabber ID (>1023).
140                 throw new Exception(_m('Invalid JID: node too long.'));
141             }
142             if (preg_match("/[".$nodeprepchars."]/u", $node)) {
143                 // TRANS: Exception thrown when using an invalid Jabber ID.
144                 // TRANS: %s is the invalid Jabber ID.
145                 throw new Exception(sprintf(_m('Invalid JID node "%s".'),$node));
146             }
147         }
148
149         if (strlen($domain) > 1023) {
150             // TRANS: Exception thrown when using too long a Jabber domain (>1023).
151             throw new Exception(_m('Invalid JID: domain too long.'));
152         }
153         if (!common_valid_domain($domain)) {
154             // TRANS: Exception thrown when using an invalid Jabber domain name.
155             // TRANS: %s is the invalid domain name.
156             throw new Exception(sprintf(_m('Invalid JID domain name "%s".'),$domain));
157         }
158
159         if ($resource !== null) {
160             if (strlen($resource) > 1023) {
161                 // TRANS: Exception thrown when using too long a resource (>1023).
162                 throw new Exception("Invalid JID: resource too long.");
163             }
164             if (preg_match("/[".$chars."]/u", $resource)) {
165                 // TRANS: Exception thrown when using an invalid Jabber resource.
166                 // TRANS: %s is the invalid resource.
167                 throw new Exception(sprintf(_m('Invalid JID resource "%s".'),$resource));
168             }
169         }
170
171         return array('node' => is_null($node) ? null : mb_strtolower($node),
172                      'domain' => is_null($domain) ? null : mb_strtolower($domain),
173                      'resource' => $resource);
174     }
175
176     /**
177      * Checks whether a string is a syntactically valid Jabber ID (JID),
178      * either with or without a resource.
179      *
180      * Note that a bare domain can be a valid JID.
181      *
182      * @param string $jid string to check
183      * @param bool $check_domain whether we should validate that domain...
184      *
185      * @return     boolean whether the string is a valid JID
186      */
187     protected function validateFullJid($jid, $check_domain=false)
188     {
189         try {
190             $parts = $this->splitJid($jid);
191             if ($check_domain) {
192                 if (!$this->checkDomain($parts['domain'])) {
193                     return false;
194                 }
195             }
196             return $parts['resource'] !== ''; // missing or present; empty ain't kosher
197         } catch (Exception $e) {
198             return false;
199         }
200     }
201
202     /**
203      * Checks whether a string is a syntactically valid base Jabber ID (JID).
204      * A base JID won't include a resource specifier on the end; since we
205      * take it off when reading input we can't really use them reliably
206      * to direct outgoing messages yet (sorry guys!)
207      *
208      * Note that a bare domain can be a valid JID.
209      *
210      * @param string $jid string to check
211      * @param bool $check_domain whether we should validate that domain...
212      *
213      * @return     boolean whether the string is a valid JID
214      */
215     protected function validateBaseJid($jid, $check_domain=false)
216     {
217         try {
218             $parts = $this->splitJid($jid);
219             if ($check_domain) {
220                 if (!$this->checkDomain($parts['domain'])) {
221                     return false;
222                 }
223             }
224             return ($parts['resource'] === null); // missing; empty ain't kosher
225         } catch (Exception $e) {
226             return false;
227         }
228     }
229
230     /**
231      * Normalizes a Jabber ID for comparison, dropping the resource component if any.
232      *
233      * @param string $jid JID to check
234      * @param bool $check_domain if true, reject if the domain isn't findable
235      *
236      * @return string an equivalent JID in normalized (lowercase) form
237      */
238     function normalize($jid)
239     {
240         try {
241             $parts = $this->splitJid($jid);
242             if ($parts['node'] !== null) {
243                 return $parts['node'] . '@' . $parts['domain'];
244             } else {
245                 return $parts['domain'];
246             }
247         } catch (Exception $e) {
248             return null;
249         }
250     }
251
252     /**
253      * Check if this domain's got some legit DNS record
254      */
255     protected function checkDomain($domain)
256     {
257         if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) {
258             return true;
259         }
260         if (checkdnsrr($domain, "ANY")) {
261             return true;
262         }
263         return false;
264     }
265
266     function daemonScreenname()
267     {
268         $ret = $this->user . '@' . $this->server;
269         if($this->resource)
270         {
271             return $ret . '/' . $this->resource;
272         }else{
273             return $ret;
274         }
275     }
276
277     function validate($screenname)
278     {
279         return $this->validateBaseJid($screenname, common_config('email', 'check_domain'));
280     }
281
282     /**
283      * Load related modules when needed
284      *
285      * @param string $cls Name of the class to be loaded
286      *
287      * @return boolean hook value; true means continue processing, false means stop.
288      */
289
290     function onAutoload($cls)
291     {
292         $dir = dirname(__FILE__);
293
294         switch ($cls)
295         {
296         case 'XMPPHP_XMPP':
297             require_once $dir . '/extlib/XMPPHP/XMPP.php';
298             return false;
299         }
300
301         return parent::onAutoload($cls);
302     }
303
304     function onStartImDaemonIoManagers(&$classes)
305     {
306         parent::onStartImDaemonIoManagers($classes);
307         $classes[] = new XmppManager($this); // handles pings/reconnects
308         return true;
309     }
310
311     function sendMessage($screenname, $body)
312     {
313         $this->queuedConnection()->message($screenname, $body, 'chat');
314     }
315
316     function sendNotice($screenname, Notice $notice)
317     {
318         $msg   = $this->formatNotice($notice);
319         $entry = $this->format_entry($notice);
320
321         $this->queuedConnection()->message($screenname, $msg, 'chat', null, $entry);
322         return true;
323     }
324
325     /**
326      * extra information for XMPP messages, as defined by Twitter
327      *
328      * @param Profile $profile Profile of the sending user
329      * @param Notice  $notice  Notice being sent
330      *
331      * @return string Extra information (Atom, HTML, addresses) in string format
332      */
333     protected function format_entry(Notice $notice)
334     {
335         $profile = $notice->getProfile();
336
337         $entry = $notice->asAtomEntry(true, true);
338
339         $xs = new XMLStringer();
340         $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
341         $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
342         $xs->element('a', array('href' => $profile->profileurl), $profile->nickname);
343         try {
344             $parent = $notice->getParent();
345             $orig_profile = $parent->getProfile();
346             $orig_profurl = $orig_profile->getUrl();
347             $xs->text(" => ");
348             $xs->element('a', array('href' => $orig_profurl), $orig_profile->nickname);
349             $xs->text(": ");
350         } catch (InvalidUrlException $e) {
351             $xs->text(sprintf(' => %s', $orig_profile->nickname));
352         } catch (NoParentNoticeException $e) {
353             $xs->text(": ");
354         } catch (NoResultException $e) {
355             // Parent notice was probably deleted.
356             $xs->text(": ");
357         }
358         // FIXME: Why do we replace \t with ''? is it just to make it pretty? shouldn't whitespace be handled well...?
359         $xs->raw(str_replace("\t", "", $notice->getRendered()));
360         $xs->text(" ");
361         $xs->element('a', array(
362             'href'=>common_local_url('conversation',
363                 array('id' => $notice->conversation)).'#notice-'.$notice->id),
364              // TRANS: Link description to notice in conversation.
365              // TRANS: %s is a notice ID.
366              sprintf(_m('[%u]'),$notice->id));
367         $xs->elementEnd('body');
368         $xs->elementEnd('html');
369
370         $html = $xs->getString();
371
372         return $html . ' ' . $entry;
373     }
374
375     function receiveRawMessage($pl)
376     {
377         $from = $this->normalize($pl['from']);
378
379         if ($pl['type'] != 'chat') {
380             $this->log(LOG_WARNING, "Ignoring message of type ".$pl['type']." from $from: " . $pl['xml']->toString());
381             return true;
382         }
383
384         if (mb_strlen($pl['body']) == 0) {
385             $this->log(LOG_WARNING, "Ignoring message with empty body from $from: "  . $pl['xml']->toString());
386             return true;
387         }
388
389         $this->handleIncoming($from, $pl['body']);
390
391         return true;
392     }
393
394     /**
395      * Build a queue-proxied XMPP interface object. Any outgoing messages
396      * will be run back through us for enqueing rather than sent directly.
397      *
398      * @return QueuedXMPP
399      * @throws Exception if server settings are invalid.
400      */
401     function queuedConnection(){
402         if(!isset($this->server)){
403             // TRANS: Exception thrown when the plugin configuration is incorrect.
404             throw new Exception(_m('You must specify a server in the configuration.'));
405         }
406         if(!isset($this->port)){
407             // TRANS: Exception thrown when the plugin configuration is incorrect.
408             throw new Exception(_m('You must specify a port in the configuration.'));
409         }
410         if(!isset($this->user)){
411             // TRANS: Exception thrown when the plugin configuration is incorrect.
412             throw new Exception(_m('You must specify a user in the configuration.'));
413         }
414         if(!isset($this->password)){
415             // TRANS: Exception thrown when the plugin configuration is incorrect.
416             throw new Exception(_m('You must specify a password in the configuration.'));
417         }
418
419         return new QueuedXMPP($this, $this->host ?
420                                     $this->host :
421                                     $this->server,
422                                     $this->port,
423                                     $this->user,
424                                     $this->password,
425                                     $this->resource,
426                                     $this->server,
427                                     $this->debug ?
428                                     true : false,
429                                     $this->debug ?
430                                     XMPPHP_Log::LEVEL_VERBOSE :  null
431                                     );
432     }
433
434     /**
435      * Add XMPP plugin daemon to the list of daemon to start
436      *
437      * @param array $daemons the list of daemons to run
438      *
439      * @return boolean hook return
440      */
441     function onGetValidDaemons(array &$daemons)
442     {
443         if( isset($this->server) &&
444             isset($this->port)   &&
445             isset($this->user)   &&
446             isset($this->password) ){
447
448             array_push(
449                 $daemons,
450                 INSTALLDIR
451                 . '/scripts/imdaemon.php'
452             );
453         }
454
455         return true;
456     }
457
458
459     function onPluginVersion(array &$versions)
460     {
461         $versions[] = array('name' => 'XMPP',
462                             'version' => GNUSOCIAL_VERSION,
463                             'author' => 'Craig Andrews, Evan Prodromou',
464                             'homepage' => 'http://status.net/wiki/Plugin:XMPP',
465                             'rawdescription' =>
466                             // TRANS: Plugin description.
467                             _m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.'));
468         return true;
469     }
470 }
471