phpBB
Statistics
| Revision:

root / trunk / phpBB / includes / functions_jabber.php

History | View | Annotate | Download (21.3 kB)

1
<?php
2
/**
3
*
4
* @package phpBB3
5
* @copyright (c) 2007 phpBB Group
6
* @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License v2
7
*
8
*/
9
10
/**
11
* @ignore
12
*/
13
if (!defined('IN_PHPBB'))
14
{
15
        exit;
16
}
17
18
/**
19
*
20
* Jabber class from Flyspray project
21
*
22
* @version class.jabber2.php 1595 2008-09-19 (0.9.9)
23
* @copyright 2006 Flyspray.org
24
* @author Florian Schmitz (floele)
25
*
26
* Only slightly modified by Acyd Burn
27
*
28
* @package phpBB3
29
*/
30
class jabber
31
{
32
        var $connection = null;
33
        var $session = array();
34
        var $timeout = 10;
35
36
        var $server;
37
        var $connect_server;
38
        var $port;
39
        var $username;
40
        var $password;
41
        var $use_ssl;
42
        var $resource = 'functions_jabber.phpbb.php';
43
44
        var $enable_logging;
45
        var $log_array;
46
47
        var $features = array();
48
49
        /**
50
        */
51
        function jabber($server, $port, $username, $password, $use_ssl = false)
52
        {
53
                $this->connect_server                = ($server) ? $server : 'localhost';
54
                $this->port                                        = ($port) ? $port : 5222;
55
56
                // Get the server and the username
57
                if (strpos($username, '@') === false)
58
                {
59
                        $this->server = $this->connect_server;
60
                        $this->username = $username;
61
                }
62
                else
63
                {
64
                        $jid = explode('@', $username, 2);
65
66
                        $this->username = $jid[0];
67
                        $this->server = $jid[1];
68
                }
69
70
                $this->password                                = $password;
71
                $this->use_ssl                                = ($use_ssl && $this->can_use_ssl()) ? true : false;
72
73
                // Change port if we use SSL
74
                if ($this->port == 5222 && $this->use_ssl)
75
                {
76
                        $this->port = 5223;
77
                }
78
79
                $this->enable_logging                = true;
80
                $this->log_array                        = array();
81
        }
82
83
        /**
84
        * Able to use the SSL functionality?
85
        */
86
        function can_use_ssl()
87
        {
88
                // Will not work with PHP >= 5.2.1 or < 5.2.3RC2 until timeout problem with ssl hasn't been fixed (http://bugs.php.net/41236)
89
                return ((version_compare(PHP_VERSION, '5.2.1', '<') || version_compare(PHP_VERSION, '5.2.3RC2', '>=')) && @extension_loaded('openssl')) ? true : false;
90
        }
91
92
        /**
93
        * Able to use TLS?
94
        */
95
        function can_use_tls()
96
        {
97
                if (!@extension_loaded('openssl') || !function_exists('stream_socket_enable_crypto') || !function_exists('stream_get_meta_data') || !function_exists('socket_set_blocking') || !function_exists('stream_get_wrappers'))
98
                {
99
                        return false;
100
                }
101
102
                /**
103
                * Make sure the encryption stream is supported
104
                * Also seem to work without the crypto stream if correctly compiled
105
106
                $streams = stream_get_wrappers();
107
108
                if (!in_array('streams.crypto', $streams))
109
                {
110
                        return false;
111
                }
112
                */
113
114
                return true;
115
        }
116
117
        /**
118
        * Sets the resource which is used. No validation is done here, only escaping.
119
        * @param string $name
120
        * @access public
121
        */
122
        function set_resource($name)
123
        {
124
                $this->resource = $name;
125
        }
126
127
        /**
128
        * Connect
129
        */
130
        function connect()
131
        {
132
/*                if (!$this->check_jid($this->username . '@' . $this->server))
133
                {
134
                        $this->add_to_log('Error: Jabber ID is not valid: ' . $this->username . '@' . $this->server);
135
                        return false;
136
                }*/
137
138
                $this->session['ssl'] = $this->use_ssl;
139
140
                if ($this->open_socket($this->connect_server, $this->port, $this->use_ssl))
141
                {
142
                        $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
143
                        $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
144
                }
145
                else
146
                {
147
                        $this->add_to_log('Error: connect() #2');
148
                        return false;
149
                }
150
151
                // Now we listen what the server has to say...and give appropriate responses
152
                $this->response($this->listen());
153
                return true;
154
        }
155
156
        /**
157
        * Disconnect
158
        */
159
        function disconnect()
160
        {
161
                if ($this->connected())
162
                {
163
                        // disconnect gracefully
164
                        if (isset($this->session['sent_presence']))
165
                        {
166
                                $this->send_presence('offline', '', true);
167
                        }
168
169
                        $this->send('</stream:stream>');
170
                        $this->session = array();
171
                        return fclose($this->connection);
172
                }
173
174
                return false;
175
        }
176
177
        /**
178
        * Connected?
179
        */
180
        function connected()
181
        {
182
                return (is_resource($this->connection) && !feof($this->connection)) ? true : false;
183
        }
184
185
186
        /**
187
        * Initiates login (using data from contructor, after calling connect())
188
        * @access public
189
        * @return bool
190
        */
191
        function login()
192
        {
193
                if (!sizeof($this->features))
194
                {
195
                        $this->add_to_log('Error: No feature information from server available.');
196
                        return false;
197
                }
198
199
                return $this->response($this->features);
200
        }
201
202
        /**
203
        * Send data to the Jabber server
204
        * @param string $xml
205
        * @access public
206
        * @return bool
207
        */
208
        function send($xml)
209
        {
210
                if ($this->connected())
211
                {
212
                        $xml = trim($xml);
213
                        $this->add_to_log('SEND: '. $xml);
214
                        return fwrite($this->connection, $xml);
215
                }
216
                else
217
                {
218
                        $this->add_to_log('Error: Could not send, connection lost (flood?).');
219
                        return false;
220
                }
221
        }
222
223
        /**
224
        * OpenSocket
225
        * @param string $server host to connect to
226
        * @param int $port port number
227
        * @param bool $use_ssl use ssl or not
228
        * @access public
229
        * @return bool
230
        */
231
        function open_socket($server, $port, $use_ssl = false)
232
        {
233
                if (@function_exists('dns_get_record'))
234
                {
235
                        $record = @dns_get_record("_xmpp-client._tcp.$server", DNS_SRV);
236
                        if (!empty($record) && !empty($record[0]['target']))
237
                        {
238
                                $server = $record[0]['target'];
239
                        }
240
                }
241
242
                $server = $use_ssl ? 'ssl://' . $server : $server;
243
244
                if ($this->connection = @fsockopen($server, $port, $errorno, $errorstr, $this->timeout))
245
                {
246
                        socket_set_blocking($this->connection, 0);
247
                        socket_set_timeout($this->connection, 60);
248
249
                        return true;
250
                }
251
252
                // Apparently an error occured...
253
                $this->add_to_log('Error: open_socket() - ' . $errorstr);
254
                return false;
255
        }
256
257
        /**
258
        * Return log
259
        */
260
        function get_log()
261
        {
262
                if ($this->enable_logging && sizeof($this->log_array))
263
                {
264
                        return implode("<br /><br />", $this->log_array);
265
                }
266
267
                return '';
268
        }
269
270
        /**
271
        * Add information to log
272
        */
273
        function add_to_log($string)
274
        {
275
                if ($this->enable_logging)
276
                {
277
                        $this->log_array[] = utf8_htmlspecialchars($string);
278
                }
279
        }
280
281
        /**
282
        * Listens to the connection until it gets data or the timeout is reached.
283
        * Thus, it should only be called if data is expected to be received.
284
        * @access public
285
        * @return mixed either false for timeout or an array with the received data
286
        */
287
        function listen($timeout = 10, $wait = false)
288
        {
289
                if (!$this->connected())
290
                {
291
                        return false;
292
                }
293
294
                // Wait for a response until timeout is reached
295
                $start = time();
296
                $data = '';
297
298
                do
299
                {
300
                        $read = trim(fread($this->connection, 4096));
301
                        $data .= $read;
302
                }
303
                while (time() <= $start + $timeout && !feof($this->connection) && ($wait || $data == '' || $read != '' || (substr(rtrim($data), -1) != '>')));
304
305
                if ($data != '')
306
                {
307
                        $this->add_to_log('RECV: '. $data);
308
                        return $this->xmlize($data);
309
                }
310
                else
311
                {
312
                        $this->add_to_log('Timeout, no response from server.');
313
                        return false;
314
                }
315
        }
316
317
        /**
318
        * Initiates account registration (based on data used for contructor)
319
        * @access public
320
        * @return bool
321
        */
322
        function register()
323
        {
324
                if (!isset($this->session['id']) || isset($this->session['jid']))
325
                {
326
                        $this->add_to_log('Error: Cannot initiate registration.');
327
                        return false;
328
                }
329
330
                $this->send("<iq type='get' id='reg_1'><query xmlns='jabber:iq:register'/></iq>");
331
                return $this->response($this->listen());
332
        }
333
334
        /**
335
        * Sets account presence. No additional info required (default is "online" status)
336
        * @param $message online, offline...
337
        * @param $type dnd, away, chat, xa or nothing
338
        * @param $unavailable set this to true if you want to become unavailable
339
        * @access public
340
        * @return bool
341
        */
342
        function send_presence($message = '', $type = '', $unavailable = false)
343
        {
344
                if (!isset($this->session['jid']))
345
                {
346
                        $this->add_to_log('ERROR: send_presence() - Cannot set presence at this point, no jid given.');
347
                        return false;
348
                }
349
350
                $type = strtolower($type);
351
                $type = (in_array($type, array('dnd', 'away', 'chat', 'xa'))) ? '<show>'. $type .'</show>' : '';
352
353
                $unavailable = ($unavailable) ? " type='unavailable'" : '';
354
                $message = ($message) ? '<status>' . utf8_htmlspecialchars($message) .'</status>' : '';
355
356
                $this->session['sent_presence'] = !$unavailable;
357
358
                return $this->send("<presence$unavailable>" . $type . $message . '</presence>');
359
        }
360
361
        /**
362
        * This handles all the different XML elements
363
        * @param array $xml
364
        * @access public
365
        * @return bool
366
        */
367
        function response($xml)
368
        {
369
                if (!is_array($xml) || !sizeof($xml))
370
                {
371
                        return false;
372
                }
373
374
                // did we get multiple elements? do one after another
375
                // array('message' => ..., 'presence' => ...)
376
                if (sizeof($xml) > 1)
377
                {
378
                        foreach ($xml as $key => $value)
379
                        {
380
                                $this->response(array($key => $value));
381
                        }
382
                        return;
383
                }
384
                else
385
                {
386
                        // or even multiple elements of the same type?
387
                        // array('message' => array(0 => ..., 1 => ...))
388
                        if (sizeof(reset($xml)) > 1)
389
                        {
390
                                foreach (reset($xml) as $value)
391
                                {
392
                                        $this->response(array(key($xml) => array(0 => $value)));
393
                                }
394
                                return;
395
                        }
396
                }
397
398
                switch (key($xml))
399
                {
400
                        case 'stream:stream':
401
                                // Connection initialised (or after authentication). Not much to do here...
402
403
                                if (isset($xml['stream:stream'][0]['#']['stream:features']))
404
                                {
405
                                        // we already got all info we need
406
                                        $this->features = $xml['stream:stream'][0]['#'];
407
                                }
408
                                else
409
                                {
410
                                        $this->features = $this->listen();
411
                                }
412
413
                                $second_time = isset($this->session['id']);
414
                                $this->session['id'] = $xml['stream:stream'][0]['@']['id'];
415
416
                                if ($second_time)
417
                                {
418
                                        // If we are here for the second time after TLS, we need to continue logging in
419
                                        return $this->login();
420
                                }
421
422
                                // go on with authentication?
423
                                if (isset($this->features['stream:features'][0]['#']['bind']) || !empty($this->session['tls']))
424
                                {
425
                                        return $this->response($this->features);
426
                                }
427
                        break;
428
429
                        case 'stream:features':
430
                                // Resource binding after successful authentication
431
                                if (isset($this->session['authenticated']))
432
                                {
433
                                        // session required?
434
                                        $this->session['sess_required'] = isset($xml['stream:features'][0]['#']['session']);
435
436
                                        $this->send("<iq type='set' id='bind_1'>
437
                                                <bind xmlns='urn:ietf:params:xml:ns:xmpp-bind'>
438
                                                        <resource>" . utf8_htmlspecialchars($this->resource) . '</resource>
439
                                                </bind>
440
                                        </iq>');
441
                                        return $this->response($this->listen());
442
                                }
443
444
                                // Let's use TLS if SSL is not enabled and we can actually use it
445
                                if (!$this->session['ssl'] && $this->can_use_tls() && $this->can_use_ssl() && isset($xml['stream:features'][0]['#']['starttls']))
446
                                {
447
                                        $this->add_to_log('Switching to TLS.');
448
                                        $this->send("<starttls xmlns='urn:ietf:params:xml:ns:xmpp-tls'/>\n");
449
                                        return $this->response($this->listen());
450
                                }
451
452
                                // Does the server support SASL authentication?
453
454
                                // I hope so, because we do (and no other method).
455
                                if (isset($xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns']) && $xml['stream:features'][0]['#']['mechanisms'][0]['@']['xmlns'] == 'urn:ietf:params:xml:ns:xmpp-sasl')
456
                                {
457
                                        // Now decide on method
458
                                        $methods = array();
459
460
                                        foreach ($xml['stream:features'][0]['#']['mechanisms'][0]['#']['mechanism'] as $value)
461
                                        {
462
                                                $methods[] = $value['#'];
463
                                        }
464
465
                                        // we prefer DIGEST-MD5
466
                                        // we don't want to use plain authentication (neither does the server usually) if no encryption is in place
467
468
                                        // http://www.xmpp.org/extensions/attic/jep-0078-1.7.html
469
                                        // The plaintext mechanism SHOULD NOT be used unless the underlying stream is encrypted (using SSL or TLS)
470
                                        // and the client has verified that the server certificate is signed by a trusted certificate authority.
471
472
                                        if (in_array('DIGEST-MD5', $methods))
473
                                        {
474
                                                $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='DIGEST-MD5'/>");
475
                                        }
476
                                        else if (in_array('PLAIN', $methods) && ($this->session['ssl'] || !empty($this->session['tls'])))
477
                                        {
478
                                                // http://www.ietf.org/rfc/rfc4616.txt (PLAIN SASL Mechanism)
479
                                                $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='PLAIN'>"
480
                                                        . base64_encode($this->username . '@' . $this->server . chr(0) . $this->username . chr(0) . $this->password) .
481
                                                        '</auth>');
482
                                        }
483
                                        else if (in_array('ANONYMOUS', $methods))
484
                                        {
485
                                                $this->send("<auth xmlns='urn:ietf:params:xml:ns:xmpp-sasl' mechanism='ANONYMOUS'/>");
486
                                        }
487
                                        else
488
                                        {
489
                                                // not good...
490
                                                $this->add_to_log('Error: No authentication method supported.');
491
                                                $this->disconnect();
492
                                                return false;
493
                                        }
494
495
                                        return $this->response($this->listen());
496
                                }
497
                                else
498
                                {
499
                                        // ok, this is it. bye.
500
                                        $this->add_to_log('Error: Server does not offer SASL authentication.');
501
                                        $this->disconnect();
502
                                        return false;
503
                                }
504
                        break;
505
506
                        case 'challenge':
507
                                // continue with authentication...a challenge literally -_-
508
                                $decoded = base64_decode($xml['challenge'][0]['#']);
509
                                $decoded = $this->parse_data($decoded);
510
511
                                if (!isset($decoded['digest-uri']))
512
                                {
513
                                        $decoded['digest-uri'] = 'xmpp/'. $this->server;
514
                                }
515
516
                                // better generate a cnonce, maybe it's needed
517
                                $decoded['cnonce'] = base64_encode(md5(uniqid(mt_rand(), true)));
518
519
                                // second challenge?
520
                                if (isset($decoded['rspauth']))
521
                                {
522
                                        $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'/>");
523
                                }
524
                                else
525
                                {
526
                                        // Make sure we only use 'auth' for qop (relevant for $this->encrypt_password())
527
                                        // If the <response> is choking up on the changed parameter we may need to adjust encrypt_password() directly
528
                                        if (isset($decoded['qop']) && $decoded['qop'] != 'auth' && strpos($decoded['qop'], 'auth') !== false)
529
                                        {
530
                                                $decoded['qop'] = 'auth';
531
                                        }
532
533
                                        $response = array(
534
                                                'username'        => $this->username,
535
                                                'response'        => $this->encrypt_password(array_merge($decoded, array('nc' => '00000001'))),
536
                                                'charset'        => 'utf-8',
537
                                                'nc'                => '00000001',
538
                                                'qop'                => 'auth',                        // only auth being supported
539
                                        );
540
541
                                        foreach (array('nonce', 'digest-uri', 'realm', 'cnonce') as $key)
542
                                        {
543
                                                if (isset($decoded[$key]))
544
                                                {
545
                                                        $response[$key] = $decoded[$key];
546
                                                }
547
                                        }
548
549
                                        $this->send("<response xmlns='urn:ietf:params:xml:ns:xmpp-sasl'>" . base64_encode($this->implode_data($response)) . '</response>');
550
                                }
551
552
                                return $this->response($this->listen());
553
                        break;
554
555
                        case 'failure':
556
                                $this->add_to_log('Error: Server sent "failure".');
557
                                $this->disconnect();
558
                                return false;
559
                        break;
560
561
                        case 'proceed':
562
                                // continue switching to TLS
563
                                $meta = stream_get_meta_data($this->connection);
564
                                socket_set_blocking($this->connection, 1);
565
566
                                if (!stream_socket_enable_crypto($this->connection, true, STREAM_CRYPTO_METHOD_TLS_CLIENT))
567
                                {
568
                                        $this->add_to_log('Error: TLS mode change failed.');
569
                                        return false;
570
                                }
571
572
                                socket_set_blocking($this->connection, $meta['blocked']);
573
                                $this->session['tls'] = true;
574
575
                                // new stream
576
                                $this->send("<?xml version='1.0' encoding='UTF-8' ?" . ">\n");
577
                                $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
578
579
                                return $this->response($this->listen());
580
                        break;
581
582
                        case 'success':
583
                                // Yay, authentication successful.
584
                                $this->send("<stream:stream to='{$this->server}' xmlns='jabber:client' xmlns:stream='http://etherx.jabber.org/streams' version='1.0'>\n");
585
                                $this->session['authenticated'] = true;
586
587
                                // we have to wait for another response
588
                                return $this->response($this->listen());
589
                        break;
590
591
                        case 'iq':
592
                                // we are not interested in IQs we did not expect
593
                                if (!isset($xml['iq'][0]['@']['id']))
594
                                {
595
                                        return false;
596
                                }
597
598
                                // multiple possibilities here
599
                                switch ($xml['iq'][0]['@']['id'])
600
                                {
601
                                        case 'bind_1':
602
                                                $this->session['jid'] = $xml['iq'][0]['#']['bind'][0]['#']['jid'][0]['#'];
603
604
                                                // and (maybe) yet another request to be able to send messages *finally*
605
                                                if ($this->session['sess_required'])
606
                                                {
607
                                                        $this->send("<iq to='{$this->server}' type='set' id='sess_1'>
608
                                                                <session xmlns='urn:ietf:params:xml:ns:xmpp-session'/>
609
                                                                </iq>");
610
                                                        return $this->response($this->listen());
611
                                                }
612
613
                                                return true;
614
                                        break;
615
616
                                        case 'sess_1':
617
                                                return true;
618
                                        break;
619
620
                                        case 'reg_1':
621
                                                $this->send("<iq type='set' id='reg_2'>
622
                                                                <query xmlns='jabber:iq:register'>
623
                                                                        <username>" . utf8_htmlspecialchars($this->username) . "</username>
624
                                                                        <password>" . utf8_htmlspecialchars($this->password) . "</password>
625
                                                                </query>
626
                                                        </iq>");
627
                                                return $this->response($this->listen());
628
                                        break;
629
630
                                        case 'reg_2':
631
                                                // registration end
632
                                                if (isset($xml['iq'][0]['#']['error']))
633
                                                {
634
                                                        $this->add_to_log('Warning: Registration failed.');
635
                                                        return false;
636
                                                }
637
                                                return true;
638
                                        break;
639
640
                                        case 'unreg_1':
641
                                                return true;
642
                                        break;
643
644
                                        default:
645
                                                $this->add_to_log('Notice: Received unexpected IQ.');
646
                                                return false;
647
                                        break;
648
                                }
649
                        break;
650
651
                        case 'message':
652
                                // we are only interested in content...
653
                                if (!isset($xml['message'][0]['#']['body']))
654
                                {
655
                                        return false;
656
                                }
657
658
                                $message['body'] = $xml['message'][0]['#']['body'][0]['#'];
659
                                $message['from'] = $xml['message'][0]['@']['from'];
660
661
                                if (isset($xml['message'][0]['#']['subject']))
662
                                {
663
                                        $message['subject'] = $xml['message'][0]['#']['subject'][0]['#'];
664
                                }
665
                                $this->session['messages'][] = $message;
666
                        break;
667
668
                        default:
669
                                // hm...don't know this response
670
                                $this->add_to_log('Notice: Unknown server response (' . key($xml) . ')');
671
                                return false;
672
                        break;
673
                }
674
        }
675
676
        function send_message($to, $text, $subject = '', $type = 'normal')
677
        {
678
                if (!isset($this->session['jid']))
679
                {
680
                        return false;
681
                }
682
683
                if (!in_array($type, array('chat', 'normal', 'error', 'groupchat', 'headline')))
684
                {
685
                        $type = 'normal';
686
                }
687
688
                return $this->send("<message from='" . utf8_htmlspecialchars($this->session['jid']) . "' to='" . utf8_htmlspecialchars($to) . "' type='$type' id='" . uniqid('msg') . "'>
689
                        <subject>" . utf8_htmlspecialchars($subject) . "</subject>
690
                        <body>" . utf8_htmlspecialchars($text) . "</body>
691
                        </message>"
692
                );
693
        }
694
695
        /**
696
        * Encrypts a password as in RFC 2831
697
        * @param array $data Needs data from the client-server connection
698
        * @access public
699
        * @return string
700
        */
701
        function encrypt_password($data)
702
        {
703
                // let's me think about <challenge> again...
704
                foreach (array('realm', 'cnonce', 'digest-uri') as $key)
705
                {
706
                        if (!isset($data[$key]))
707
                        {
708
                                $data[$key] = '';
709
                        }
710
                }
711
712
                $pack = md5($this->username . ':' . $data['realm'] . ':' . $this->password);
713
714
                if (isset($data['authzid']))
715
                {
716
                        $a1 = pack('H32', $pack)  . sprintf(':%s:%s:%s', $data['nonce'], $data['cnonce'], $data['authzid']);
717
                }
718
                else
719
                {
720
                        $a1 = pack('H32', $pack)  . sprintf(':%s:%s', $data['nonce'], $data['cnonce']);
721
                }
722
723
                // should be: qop = auth
724
                $a2 = 'AUTHENTICATE:'. $data['digest-uri'];
725
726
                return md5(sprintf('%s:%s:%s:%s:%s:%s', md5($a1), $data['nonce'], $data['nc'], $data['cnonce'], $data['qop'], md5($a2)));
727
        }
728
729
        /**
730
        * parse_data like a="b",c="d",... or like a="a, b", c, d="e", f=g,...
731
        * @param string $data
732
        * @access public
733
        * @return array a => b ...
734
        */
735
        function parse_data($data)
736
        {
737
                $data = explode(',', $data);
738
                $pairs = array();
739
                $key = false;
740
741
                foreach ($data as $pair)
742
                {
743
                        $dd = strpos($pair, '=');
744
745
                        if ($dd)
746
                        {
747
                                $key = trim(substr($pair, 0, $dd));
748
                                $pairs[$key] = trim(trim(substr($pair, $dd + 1)), '"');
749
                        }
750
                        else if (strpos(strrev(trim($pair)), '"') === 0 && $key)
751
                        {
752
                                // We are actually having something left from "a, b" values, add it to the last one we handled.
753
                                $pairs[$key] .= ',' . trim(trim($pair), '"');
754
                                continue;
755
                        }
756
                }
757
758
                return $pairs;
759
        }
760
761
        /**
762
        * opposite of jabber::parse_data()
763
        * @param array $data
764
        * @access public
765
        * @return string
766
        */
767
        function implode_data($data)
768
        {
769
                $return = array();
770
                foreach ($data as $key => $value)
771
                {
772
                        $return[] = $key . '="' . $value . '"';
773
                }
774
                return implode(',', $return);
775
        }
776
777
        /**
778
        * xmlize()
779
        * @author Hans Anderson
780
        * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
781
        */
782
        function xmlize($data, $skip_white = 1, $encoding = 'UTF-8')
783
        {
784
                $data = trim($data);
785
786
                if (substr($data, 0, 5) != '<?xml')
787
                {
788
                        // mod
789
                        $data = '<root>'. $data . '</root>';
790
                }
791
792
                $vals = $index = $array = array();
793
                $parser = xml_parser_create($encoding);
794
                xml_parser_set_option($parser, XML_OPTION_CASE_FOLDING, 0);
795
                xml_parser_set_option($parser, XML_OPTION_SKIP_WHITE, $skip_white);
796
                xml_parse_into_struct($parser, $data, $vals, $index);
797
                xml_parser_free($parser);
798
799
                $i = 0;
800
                $tagname = $vals[$i]['tag'];
801
802
                $array[$tagname][0]['@'] = (isset($vals[$i]['attributes'])) ? $vals[$i]['attributes'] : array();
803
                $array[$tagname][0]['#'] = $this->_xml_depth($vals, $i);
804
805
                if (substr($data, 0, 5) != '<?xml')
806
                {
807
                        $array = $array['root'][0]['#'];
808
                }
809
810
                return $array;
811
        }
812
813
        /**
814
        * _xml_depth()
815
        * @author Hans Anderson
816
        * @copyright Hans Anderson / http://www.hansanderson.com/php/xml/
817
        */
818
        function _xml_depth($vals, &$i)
819
        {
820
                $children = array();
821
822
                if (isset($vals[$i]['value']))
823
                {
824
                        array_push($children, $vals[$i]['value']);
825
                }
826
827
                while (++$i < sizeof($vals))
828
                {
829
                        switch ($vals[$i]['type'])
830
                        {
831
                                case 'open':
832
833
                                        $tagname = (isset($vals[$i]['tag'])) ? $vals[$i]['tag'] : '';
834
                                        $size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
835
836
                                        if (isset($vals[$i]['attributes']))
837
                                        {
838
                                                $children[$tagname][$size]['@'] = $vals[$i]['attributes'];
839
                                        }
840
841
                                        $children[$tagname][$size]['#'] = $this->_xml_depth($vals, $i);
842
843
                                break;
844
845
                                case 'cdata':
846
                                        array_push($children, $vals[$i]['value']);
847
                                break;
848
849
                                case 'complete':
850
851
                                        $tagname = $vals[$i]['tag'];
852
                                        $size = (isset($children[$tagname])) ? sizeof($children[$tagname]) : 0;
853
                                        $children[$tagname][$size]['#'] = (isset($vals[$i]['value'])) ? $vals[$i]['value'] : array();
854
855
                                        if (isset($vals[$i]['attributes']))
856
                                        {
857
                                                $children[$tagname][$size]['@'] = $vals[$i]['attributes'];
858
                                        }
859
860
                                break;
861
862
                                case 'close':
863
                                        return $children;
864
                                break;
865
                        }
866
                }
867
868
                return $children;
869
        }
870
}