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