]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Xmpp/XmppPlugin.php
OStatus and XMPP plugins now inform Nodeinfo plugins about their activity
[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 7
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     {
62         // TRANS: Plugin display name.
63         return _m('XMPP/Jabber');
64     }
65
66     function daemonScreenname()
67     {
68         $ret = $this->user . '@' . $this->server;
69         if ($this->resource) {
70             return $ret . '/' . $this->resource;
71         } else {
72             return $ret;
73         }
74     }
75
76     function validate($screenname)
77     {
78         return $this->validateBaseJid($screenname, common_config('email', 'check_domain'));
79     }
80
81     /**
82      * Checks whether a string is a syntactically valid base Jabber ID (JID).
83      * A base JID won't include a resource specifier on the end; since we
84      * take it off when reading input we can't really use them reliably
85      * to direct outgoing messages yet (sorry guys!)
86      *
87      * Note that a bare domain can be a valid JID.
88      *
89      * @param string $jid string to check
90      * @param bool $check_domain whether we should validate that domain...
91      *
92      * @return     boolean whether the string is a valid JID
93      */
94     protected function validateBaseJid($jid, $check_domain = false)
95     {
96         try {
97             $parts = $this->splitJid($jid);
98             if ($check_domain) {
99                 if (!$this->checkDomain($parts['domain'])) {
100                     return false;
101                 }
102             }
103             return ($parts['resource'] === null); // missing; empty ain't kosher
104         } catch (Exception $e) {
105             return false;
106         }
107     }
108
109     /**
110      * Splits a Jabber ID (JID) into node, domain, and resource portions.
111      *
112      * Based on validation routine submitted by:
113      * @param string $jid string to check
114      *
115      * @return array with "node", "domain", and "resource" indices
116      * @throws Exception if input is not valid
117      * @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact.
118      *
119      * @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
120      */
121     protected function splitJid($jid)
122     {
123         $chars = '';
124         /* the following definitions come from stringprep, Appendix C,
125            which is used in its entirety by nodeprop, Chapter 5, "Prohibited Output" */
126         /* C1.1 ASCII space characters */
127         $chars .= "\x{20}";
128         /* C1.2 Non-ASCII space characters */
129         $chars .= "\x{a0}\x{1680}\x{2000}-\x{200b}\x{202f}\x{205f}\x{3000a}";
130         /* C2.1 ASCII control characters */
131         $chars .= "\x{00}-\x{1f}\x{7f}";
132         /* C2.2 Non-ASCII control characters */
133         $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}";
134         /* C3 - Private Use */
135         $chars .= "\x{e000}-\x{f8ff}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}";
136         /* C4 - Non-character code points */
137         $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}";
138         /* C5 - Surrogate codes */
139         // We can't use preg_match to check this, fix below
140         // $chars .= "\x{d800}-\x{dfff}";
141         /* C6 - Inappropriate for plain text */
142         $chars .= "\x{fff9}-\x{fffd}";
143         /* C7 - Inappropriate for canonical representation */
144         $chars .= "\x{2ff0}-\x{2ffb}";
145         /* C8 - Change display properties or are deprecated */
146         $chars .= "\x{340}\x{341}\x{200e}\x{200f}\x{202a}-\x{202e}\x{206a}-\x{206f}";
147         /* C9 - Tagging characters */
148         $chars .= "\x{e0001}\x{e0020}-\x{e007f}";
149
150         /* Nodeprep forbids some more characters */
151         $nodeprepchars = $chars;
152         $nodeprepchars .= "\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}";
153
154         $parts = explode("/", $jid, 2);
155         if (count($parts) > 1) {
156             $resource = $parts[1];
157             // if ($resource == '') then
158             // Warning: empty resource isn't legit.
159             // But if we're normalizing, we may as well take it...
160         } else {
161             $resource = null;
162         }
163
164         $node = explode("@", $parts[0]);
165         if ((count($node) > 2) || (count($node) == 0)) {
166             // TRANS: Exception thrown when using too many @ signs in a Jabber ID.
167             throw new Exception(_m('Invalid JID: too many @s.'));
168         } else if (count($node) == 1) {
169             $domain = $node[0];
170             $node = null;
171         } else {
172             $domain = $node[1];
173             $node = $node[0];
174             if ($node == '') {
175                 // TRANS: Exception thrown when using @ sign not followed by a Jabber ID.
176                 throw new Exception(_m('Invalid JID: @ but no node'));
177             }
178         }
179
180         if ($node !== null) {
181             // Length limits per http://xmpp.org/rfcs/rfc3920.html#addressing
182             if (strlen($node) > 1023) {
183                 // TRANS: Exception thrown when using too long a Jabber ID (>1023).
184                 throw new Exception(_m('Invalid JID: node too long.'));
185             }
186             // C5 - Surrogate codes is ensured by encoding check
187             if (preg_match("/[" . $nodeprepchars . "]/u", $node) || mb_detect_encoding($node, 'UTF-8', true) != 'UTF-8') {
188                 // TRANS: Exception thrown when using an invalid Jabber ID.
189                 // TRANS: %s is the invalid Jabber ID.
190                 throw new Exception(sprintf(_m('Invalid JID node "%s".'), $node));
191             }
192         }
193
194         if (strlen($domain) > 1023) {
195             // TRANS: Exception thrown when using too long a Jabber domain (>1023).
196             throw new Exception(_m('Invalid JID: domain too long.'));
197         }
198         if (!common_valid_domain($domain)) {
199             // TRANS: Exception thrown when using an invalid Jabber domain name.
200             // TRANS: %s is the invalid domain name.
201             throw new Exception(sprintf(_m('Invalid JID domain name "%s".'), $domain));
202         }
203
204         if ($resource !== null) {
205             if (strlen($resource) > 1023) {
206                 // TRANS: Exception thrown when using too long a resource (>1023).
207                 throw new Exception("Invalid JID: resource too long.");
208             }
209             if (preg_match("/[" . $chars . "]/u", $resource)) {
210                 // TRANS: Exception thrown when using an invalid Jabber resource.
211                 // TRANS: %s is the invalid resource.
212                 throw new Exception(sprintf(_m('Invalid JID resource "%s".'), $resource));
213             }
214         }
215
216         return array('node' => is_null($node) ? null : mb_strtolower($node),
217             'domain' => is_null($domain) ? null : mb_strtolower($domain),
218             'resource' => $resource);
219     }
220
221     /**
222      * Check if this domain's got some legit DNS record
223      * @param $domain
224      * @return bool
225      */
226     protected function checkDomain($domain)
227     {
228         if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) {
229             return true;
230         }
231         if (checkdnsrr($domain, "ANY")) {
232             return true;
233         }
234         return false;
235     }
236
237     /**
238      * Load related modules when needed
239      *
240      * @param string $cls Name of the class to be loaded
241      *
242      * @return boolean hook value; true means continue processing, false means stop.
243      */
244
245     function onAutoload($cls)
246     {
247         switch ($cls) {
248             case 'XMPPHP_XMPP':
249                 require_once __DIR__ . '/extlib/XMPPHP/XMPP.php';
250                 return false;
251         }
252
253         return parent::onAutoload($cls);
254     }
255
256     function onStartImDaemonIoManagers(&$classes)
257     {
258         parent::onStartImDaemonIoManagers($classes);
259         $classes[] = new XmppManager($this); // handles pings/reconnects
260         return true;
261     }
262
263     function sendMessage($screenname, $body)
264     {
265         $this->queuedConnection()->message($screenname, $body, 'chat');
266     }
267
268     /**
269      * Build a queue-proxied XMPP interface object. Any outgoing messages
270      * will be run back through us for enqueing rather than sent directly.
271      *
272      * @return QueuedXMPP
273      * @throws Exception if server settings are invalid.
274      */
275     function queuedConnection()
276     {
277         if (!isset($this->server)) {
278             // TRANS: Exception thrown when the plugin configuration is incorrect.
279             throw new Exception(_m('You must specify a server in the configuration.'));
280         }
281         if (!isset($this->port)) {
282             // TRANS: Exception thrown when the plugin configuration is incorrect.
283             throw new Exception(_m('You must specify a port in the configuration.'));
284         }
285         if (!isset($this->user)) {
286             // TRANS: Exception thrown when the plugin configuration is incorrect.
287             throw new Exception(_m('You must specify a user in the configuration.'));
288         }
289         if (!isset($this->password)) {
290             // TRANS: Exception thrown when the plugin configuration is incorrect.
291             throw new Exception(_m('You must specify a password in the configuration.'));
292         }
293
294         return new QueuedXMPP($this, $this->host ?
295             $this->host :
296             $this->server,
297             $this->port,
298             $this->user,
299             $this->password,
300             $this->resource,
301             $this->server,
302             $this->debug ?
303                 true : false,
304             $this->debug ?
305                 \XMPPHP\Log::LEVEL_VERBOSE : null
306         );
307     }
308
309     function sendNotice($screenname, Notice $notice)
310     {
311         try {
312             $msg = $this->formatNotice($notice);
313             $entry = $this->format_entry($notice);
314         } catch (Exception $e) {
315             common_log(LOG_ERR, __METHOD__ . ": Discarding outgoing stanza because of exception: {$e->getMessage()}");
316             return false;   // return value of sendNotice is never actually used as of now
317         }
318         $this->queuedConnection()->message($screenname, $msg, 'chat', null, $entry);
319         return true;
320     }
321
322     /**
323      * extra information for XMPP messages, as defined by Twitter
324      *
325      * @param Notice $notice Notice being sent
326      *
327      * @return string Extra information (Atom, HTML, addresses) in string format
328      */
329     protected function format_entry(Notice $notice)
330     {
331         $profile = $notice->getProfile();
332
333         $entry = $notice->asAtomEntry(true, true);
334
335         $xs = new XMLStringer();
336         $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
337         $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
338         $xs->element('a', array('href' => $profile->profileurl), $profile->nickname);
339         try {
340             $parent = $notice->getParent();
341             $orig_profile = $parent->getProfile();
342             $orig_profurl = $orig_profile->getUrl();
343             $xs->text(" => ");
344             $xs->element('a', array('href' => $orig_profurl), $orig_profile->nickname);
345             $xs->text(": ");
346         } catch (NoParentNoticeException $e) {
347             $xs->text(": ");
348         }
349         // FIXME: Why do we replace \t with ''? is it just to make it pretty? shouldn't whitespace be handled well...?
350         $xs->raw(str_replace("\t", "", $notice->getRendered()));
351         $xs->text(" ");
352         $xs->element('a', array(
353             'href' => common_local_url('conversation',
354                     array('id' => $notice->conversation)) . '#notice-' . $notice->id),
355             // TRANS: Link description to notice in conversation.
356             // TRANS: %s is a notice ID.
357             sprintf(_m('[%u]'), $notice->id));
358         $xs->elementEnd('body');
359         $xs->elementEnd('html');
360
361         $html = $xs->getString();
362
363         return $html . ' ' . $entry;
364     }
365
366     function receiveRawMessage($pl)
367     {
368         $from = $this->normalize($pl['from']);
369
370         if ($pl['type'] != 'chat') {
371             $this->log(LOG_WARNING, "Ignoring message of type " . $pl['type'] . " from $from: " . $pl['xml']->toString());
372             return true;
373         }
374
375         if (mb_strlen($pl['body']) == 0) {
376             $this->log(LOG_WARNING, "Ignoring message with empty body from $from: " . $pl['xml']->toString());
377             return true;
378         }
379
380         $this->handleIncoming($from, $pl['body']);
381
382         return true;
383     }
384
385     /**
386      * Normalizes a Jabber ID for comparison, dropping the resource component if any.
387      *
388      * @param string $jid JID to check
389      * @return string an equivalent JID in normalized (lowercase) form
390      */
391     function normalize($jid)
392     {
393         try {
394             $parts = $this->splitJid($jid);
395             if ($parts['node'] !== null) {
396                 return $parts['node'] . '@' . $parts['domain'];
397             } else {
398                 return $parts['domain'];
399             }
400         } catch (Exception $e) {
401             return null;
402         }
403     }
404
405     /**
406      * Add XMPP plugin daemon to the list of daemon to start
407      *
408      * @param array $daemons the list of daemons to run
409      *
410      * @return boolean hook return
411      */
412     function onGetValidDaemons(&$daemons)
413     {
414         if (isset($this->server) &&
415             isset($this->port) &&
416             isset($this->user) &&
417             isset($this->password)) {
418
419             array_push(
420                 $daemons,
421                 INSTALLDIR
422                 . '/scripts/imdaemon.php'
423             );
424         }
425
426         return true;
427     }
428
429     /**
430      * Plugin Nodeinfo information
431      *
432      * @param array $protocols
433      * @return bool hook true
434      */
435     public function onNodeInfoProtocols(array &$protocols)
436     {
437         $protocols[] = "xmpp";
438         return true;
439     }
440
441     function onPluginVersion(array &$versions)
442     {
443         $versions[] = array('name' => 'XMPP',
444             'version' => GNUSOCIAL_VERSION,
445             'author' => 'Craig Andrews, Evan Prodromou',
446             'homepage' => 'https://git.gnu.io/gnu/gnu-social/tree/master/plugins/XMPP',
447             'rawdescription' =>
448             // TRANS: Plugin description.
449                 _m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.'));
450         return true;
451     }
452
453     /**
454      * Checks whether a string is a syntactically valid Jabber ID (JID),
455      * either with or without a resource.
456      *
457      * Note that a bare domain can be a valid JID.
458      *
459      * @param string $jid string to check
460      * @param bool $check_domain whether we should validate that domain...
461      *
462      * @return     boolean whether the string is a valid JID
463      */
464     protected function validateFullJid($jid, $check_domain = false)
465     {
466         try {
467             $parts = $this->splitJid($jid);
468             if ($check_domain) {
469                 if (!$this->checkDomain($parts['domain'])) {
470                     return false;
471                 }
472             }
473             return $parts['resource'] !== ''; // missing or present; empty ain't kosher
474         } catch (Exception $e) {
475             return false;
476         }
477     }
478 }
479