]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Xmpp/XmppPlugin.php
IM cleanup on 1.0.x branch:
[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 set_include_path(get_include_path() . PATH_SEPARATOR . INSTALLDIR . '/extlib/XMPPHP');
38
39 /**
40  * Plugin for XMPP
41  *
42  * @category  Plugin
43  * @package   StatusNet
44  * @author    Evan Prodromou <evan@status.net>
45  * @copyright 2009 StatusNet, Inc.
46  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
47  * @link      http://status.net/
48  */
49
50 class XmppPlugin extends ImPlugin
51 {
52     public $server = null;
53     public $port = 5222;
54     public $user =  'update';
55     public $resource = null;
56     public $encryption = true;
57     public $password = null;
58     public $host = null;  // only set if != server
59     public $debug = false; // print extra debug info
60
61     public $transport = 'xmpp';
62
63     function getDisplayName(){
64         return _m('XMPP/Jabber/GTalk');
65     }
66
67     /**
68      * Splits a Jabber ID (JID) into node, domain, and resource portions.
69      * 
70      * Based on validation routine submitted by:
71      * @copyright 2009 Patrick Georgi <patrick@georgi-clan.de>
72      * @license Licensed under ISC-L, which is compatible with everything else that keeps the copyright notice intact. 
73      *
74      * @param string $jid string to check
75      *
76      * @return array with "node", "domain", and "resource" indices
77      * @throws Exception if input is not valid
78      */
79
80     protected function splitJid($jid)
81     {
82         $chars = '';
83         /* the following definitions come from stringprep, Appendix C,
84            which is used in its entirety by nodeprop, Chapter 5, "Prohibited Output" */
85         /* C1.1 ASCII space characters */
86         $chars .= "\x{20}";
87         /* C1.2 Non-ASCII space characters */
88         $chars .= "\x{a0}\x{1680}\x{2000}-\x{200b}\x{202f}\x{205f}\x{3000a}";
89         /* C2.1 ASCII control characters */
90         $chars .= "\x{00}-\x{1f}\x{7f}";
91         /* C2.2 Non-ASCII control characters */
92         $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}";
93         /* C3 - Private Use */
94         $chars .= "\x{e000}-\x{f8ff}\x{f0000}-\x{ffffd}\x{100000}-\x{10fffd}";
95         /* C4 - Non-character code points */
96         $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}";
97         /* C5 - Surrogate codes */
98         $chars .= "\x{d800}-\x{dfff}";
99         /* C6 - Inappropriate for plain text */
100         $chars .= "\x{fff9}-\x{fffd}";
101         /* C7 - Inappropriate for canonical representation */
102         $chars .= "\x{2ff0}-\x{2ffb}";
103         /* C8 - Change display properties or are deprecated */
104         $chars .= "\x{340}\x{341}\x{200e}\x{200f}\x{202a}-\x{202e}\x{206a}-\x{206f}";
105         /* C9 - Tagging characters */
106         $chars .= "\x{e0001}\x{e0020}-\x{e007f}";
107     
108         /* Nodeprep forbids some more characters */
109         $nodeprepchars = $chars;
110         $nodeprepchars .= "\x{22}\x{26}\x{27}\x{2f}\x{3a}\x{3c}\x{3e}\x{40}";
111     
112         $parts = explode("/", $jid, 2);
113         if (count($parts) > 1) {
114             $resource = $parts[1];
115             if ($resource == '') {
116                 // Warning: empty resource isn't legit.
117                 // But if we're normalizing, we may as well take it...
118             }
119         } else {
120             $resource = null;
121         }
122     
123         $node = explode("@", $parts[0]);
124         if ((count($node) > 2) || (count($node) == 0)) {
125             throw new Exception("Invalid JID: too many @s");
126         } else if (count($node) == 1) {
127             $domain = $node[0];
128             $node = null;
129         } else {
130             $domain = $node[1];
131             $node = $node[0];
132             if ($node == '') {
133                 throw new Exception("Invalid JID: @ but no node");
134             }
135         }
136     
137         // Length limits per http://xmpp.org/rfcs/rfc3920.html#addressing
138         if ($node !== null) {
139             if (strlen($node) > 1023) {
140                 throw new Exception("Invalid JID: node too long.");
141             }
142             if (preg_match("/[".$nodeprepchars."]/u", $node)) {
143                 throw new Exception("Invalid JID node '$node'");
144             }
145         }
146     
147         if (strlen($domain) > 1023) {
148             throw new Exception("Invalid JID: domain too long.");
149         }
150         if (!common_valid_domain($domain)) {
151             throw new Exception("Invalid JID domain name '$domain'");
152         }
153     
154         if ($resource !== null) {
155             if (strlen($resource) > 1023) {
156                 throw new Exception("Invalid JID: resource too long.");
157             }
158             if (preg_match("/[".$chars."]/u", $resource)) {
159                 throw new Exception("Invalid JID resource '$resource'");
160             }
161         }
162     
163         return array('node' => is_null($node) ? null : mb_strtolower($node),
164                      'domain' => is_null($domain) ? null : mb_strtolower($domain),
165                      'resource' => $resource);
166     }
167     
168     /**
169      * Checks whether a string is a syntactically valid Jabber ID (JID),
170      * either with or without a resource.
171      * 
172      * Note that a bare domain can be a valid JID.
173      * 
174      * @param string $jid string to check
175      * @param bool $check_domain whether we should validate that domain...
176      *
177      * @return     boolean whether the string is a valid JID
178      */
179     protected function validateFullJid($jid, $check_domain=false)
180     {
181         try {
182             $parts = $this->splitJid($jid);
183             if ($check_domain) {
184                 if (!$this->checkDomain($parts['domain'])) {
185                     return false;
186                 }
187             }
188             return $parts['resource'] !== ''; // missing or present; empty ain't kosher
189         } catch (Exception $e) {
190             return false;
191         }
192     }
193     
194     /**
195      * Checks whether a string is a syntactically valid base Jabber ID (JID).
196      * A base JID won't include a resource specifier on the end; since we
197      * take it off when reading input we can't really use them reliably
198      * to direct outgoing messages yet (sorry guys!)
199      * 
200      * Note that a bare domain can be a valid JID.
201      * 
202      * @param string $jid string to check
203      * @param bool $check_domain whether we should validate that domain...
204      *
205      * @return     boolean whether the string is a valid JID
206      */
207     protected function validateBaseJid($jid, $check_domain=false)
208     {
209         try {
210             $parts = $this->splitJid($jid);
211             if ($check_domain) {
212                 if (!$this->checkDomain($parts['domain'])) {
213                     return false;
214                 }
215             }
216             return ($parts['resource'] === null); // missing; empty ain't kosher
217         } catch (Exception $e) {
218             return false;
219         }
220     }
221
222     /**
223      * Normalizes a Jabber ID for comparison, dropping the resource component if any.
224      *
225      * @param string $jid JID to check
226      * @param bool $check_domain if true, reject if the domain isn't findable
227      *
228      * @return string an equivalent JID in normalized (lowercase) form
229      */
230
231     function normalize($jid)
232     {
233         try {
234             $parts = $this->splitJid($jid);
235             if ($parts['node'] !== null) {
236                 return $parts['node'] . '@' . $parts['domain'];
237             } else {
238                 return $parts['domain'];
239             }
240         } catch (Exception $e) {
241             return null;
242         }
243     }
244
245     /**
246      * Check if this domain's got some legit DNS record
247      */
248     protected function checkDomain($domain)
249     {
250         if (checkdnsrr("_xmpp-server._tcp." . $domain, "SRV")) {
251             return true;
252         }
253         if (checkdnsrr($domain, "ANY")) {
254             return true;
255         }
256         return false;
257     }
258
259     function daemon_screenname()
260     {
261         $ret = $this->user . '@' . $this->server;
262         if($this->resource)
263         {
264             return $ret . '/' . $this->resource;
265         }else{
266             return $ret;
267         }
268     }
269
270     function validate($screenname)
271     {
272         return $this->validateBaseJid($screenname, common_config('email', 'check_domain'));
273     }
274
275     /**
276      * Load related modules when needed
277      *
278      * @param string $cls Name of the class to be loaded
279      *
280      * @return boolean hook value; true means continue processing, false means stop.
281      */
282
283     function onAutoload($cls)
284     {
285         $dir = dirname(__FILE__);
286
287         switch ($cls)
288         {
289         case 'XMPPHP_XMPP':
290             require_once 'XMPP.php';
291             return false;
292         case 'Sharing_XMPP':
293         case 'Queued_XMPP':
294             require_once $dir . '/'.$cls.'.php';
295             return false;
296         case 'XmppManager':
297             require_once $dir . '/'.strtolower($cls).'.php';
298             return false;
299         default:
300             return true;
301         }
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 microiduri($screenname)
312     {
313         return 'xmpp:' . $screenname;    
314     }
315
316     function send_message($screenname, $body)
317     {
318         $this->queuedConnection()->message($screenname, $body, 'chat');
319     }
320
321     function send_notice($screenname, $notice)
322     {
323         $msg   = $this->format_notice($notice);
324         $entry = $this->format_entry($notice);
325         
326         $this->queuedConnection()->message($screenname, $msg, 'chat', null, $entry);
327         return true;
328     }
329
330     /**
331      * extra information for XMPP messages, as defined by Twitter
332      *
333      * @param Profile $profile Profile of the sending user
334      * @param Notice  $notice  Notice being sent
335      *
336      * @return string Extra information (Atom, HTML, addresses) in string format
337      */
338
339     function format_entry($notice)
340     {
341         $profile = $notice->getProfile();
342
343         $entry = $notice->asAtomEntry(true, true);
344
345         $xs = new XMLStringer();
346         $xs->elementStart('html', array('xmlns' => 'http://jabber.org/protocol/xhtml-im'));
347         $xs->elementStart('body', array('xmlns' => 'http://www.w3.org/1999/xhtml'));
348         $xs->element('a', array('href' => $profile->profileurl),
349                      $profile->nickname);
350         $xs->text(": ");
351         if (!empty($notice->rendered)) {
352             $xs->raw($notice->rendered);
353         } else {
354             $xs->raw(common_render_content($notice->content, $notice));
355         }
356         $xs->text(" ");
357         $xs->element('a', array(
358             'href'=>common_local_url('conversation',
359                 array('id' => $notice->conversation)).'#notice-'.$notice->id
360              ),sprintf(_('[%s]'),$notice->id));
361         $xs->elementEnd('body');
362         $xs->elementEnd('html');
363
364         $html = $xs->getString();
365
366         return $html . ' ' . $entry;
367     }
368
369     function receive_raw_message($pl)
370     {
371         $from = $this->normalize($pl['from']);
372
373         if ($pl['type'] != 'chat') {
374             common_log(LOG_WARNING, "Ignoring message of type ".$pl['type']." from $from.");
375             return true;
376         }
377
378         if (mb_strlen($pl['body']) == 0) {
379             common_log(LOG_WARNING, "Ignoring message with empty body from $from.");
380             return true;
381         }
382
383         $this->handle_incoming($from, $pl['body']);
384         
385         return true;
386     }
387
388     /**
389      * Build a queue-proxied XMPP interface object. Any outgoing messages
390      * will be run back through us for enqueing rather than sent directly.
391      * 
392      * @return Queued_XMPP
393      * @throws Exception if server settings are invalid.
394      */
395     function queuedConnection(){
396         if(!isset($this->server)){
397             throw new Exception("must specify a server");
398         }
399         if(!isset($this->port)){
400             throw new Exception("must specify a port");
401         }
402         if(!isset($this->user)){
403             throw new Exception("must specify a user");
404         }
405         if(!isset($this->password)){
406             throw new Exception("must specify a password");
407         }
408
409         return new Queued_XMPP($this, $this->host ?
410                                     $this->host :
411                                     $this->server,
412                                     $this->port,
413                                     $this->user,
414                                     $this->password,
415                                     $this->resource,
416                                     $this->server,
417                                     $this->debug ?
418                                     true : false,
419                                     $this->debug ?
420                                     XMPPHP_Log::LEVEL_VERBOSE :  null
421                                     );
422     }
423
424     function onPluginVersion(&$versions)
425     {
426         $versions[] = array('name' => 'XMPP',
427                             'version' => STATUSNET_VERSION,
428                             'author' => 'Craig Andrews, Evan Prodromou',
429                             'homepage' => 'http://status.net/wiki/Plugin:XMPP',
430                             'rawdescription' =>
431                             _m('The XMPP plugin allows users to send and receive notices over the XMPP/Jabber network.'));
432         return true;
433     }
434 }
435