Project

General

Profile

Download (58.4 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2

    
3
/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */
4

    
5
/**
6
 * PHP implementation of the XML-RPC protocol
7
 *
8
 * This is a PEAR-ified version of Useful inc's XML-RPC for PHP.
9
 * It has support for HTTP transport, proxies and authentication.
10
 *
11
 * PHP versions 4 and 5
12
 *
13
 * @category   Web Services
14
 * @package    XML_RPC
15
 * @author     Edd Dumbill <edd@usefulinc.com>
16
 * @author     Stig Bakken <stig@php.net>
17
 * @author     Martin Jansen <mj@php.net>
18
 * @author     Daniel Convissor <danielc@php.net>
19
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
20
 * @license    http://www.php.net/license/3_01.txt  PHP License
21
 * @version    SVN: $Id: RPC.php 300961 2010-07-03 02:17:34Z danielc $
22
 * @link       http://pear.php.net/package/XML_RPC
23
 */
24

    
25

    
26
if (!function_exists('xml_parser_create')) {
27
    include_once 'PEAR.inc';
28
    PEAR::loadExtension('xml');
29
}
30

    
31
/**#@+
32
 * Error constants
33
 */
34
/**
35
 * Parameter values don't match parameter types
36
 */
37
define('XML_RPC_ERROR_INVALID_TYPE', 101);
38
/**
39
 * Parameter declared to be numeric but the values are not
40
 */
41
define('XML_RPC_ERROR_NON_NUMERIC_FOUND', 102);
42
/**
43
 * Communication error
44
 */
45
define('XML_RPC_ERROR_CONNECTION_FAILED', 103);
46
/**
47
 * The array or struct has already been started
48
 */
49
define('XML_RPC_ERROR_ALREADY_INITIALIZED', 104);
50
/**
51
 * Incorrect parameters submitted
52
 */
53
define('XML_RPC_ERROR_INCORRECT_PARAMS', 105);
54
/**
55
 * Programming error by developer
56
 */
57
define('XML_RPC_ERROR_PROGRAMMING', 106);
58
/**#@-*/
59

    
60

    
61
/**
62
 * Data types
63
 * @global string $GLOBALS['XML_RPC_I4']
64
 */
65
$GLOBALS['XML_RPC_I4'] = 'i4';
66

    
67
/**
68
 * Data types
69
 * @global string $GLOBALS['XML_RPC_Int']
70
 */
71
$GLOBALS['XML_RPC_Int'] = 'int';
72

    
73
/**
74
 * Data types
75
 * @global string $GLOBALS['XML_RPC_Boolean']
76
 */
77
$GLOBALS['XML_RPC_Boolean'] = 'boolean';
78

    
79
/**
80
 * Data types
81
 * @global string $GLOBALS['XML_RPC_Double']
82
 */
83
$GLOBALS['XML_RPC_Double'] = 'double';
84

    
85
/**
86
 * Data types
87
 * @global string $GLOBALS['XML_RPC_String']
88
 */
89
$GLOBALS['XML_RPC_String'] = 'string';
90

    
91
/**
92
 * Data types
93
 * @global string $GLOBALS['XML_RPC_DateTime']
94
 */
95
$GLOBALS['XML_RPC_DateTime'] = 'dateTime.iso8601';
96

    
97
/**
98
 * Data types
99
 * @global string $GLOBALS['XML_RPC_Base64']
100
 */
101
$GLOBALS['XML_RPC_Base64'] = 'base64';
102

    
103
/**
104
 * Data types
105
 * @global string $GLOBALS['XML_RPC_Array']
106
 */
107
$GLOBALS['XML_RPC_Array'] = 'array';
108

    
109
/**
110
 * Data types
111
 * @global string $GLOBALS['XML_RPC_Struct']
112
 */
113
$GLOBALS['XML_RPC_Struct'] = 'struct';
114

    
115

    
116
/**
117
 * Data type meta-types
118
 * @global array $GLOBALS['XML_RPC_Types']
119
 */
120
$GLOBALS['XML_RPC_Types'] = array(
121
    $GLOBALS['XML_RPC_I4']       => 1,
122
    $GLOBALS['XML_RPC_Int']      => 1,
123
    $GLOBALS['XML_RPC_Boolean']  => 1,
124
    $GLOBALS['XML_RPC_String']   => 1,
125
    $GLOBALS['XML_RPC_Double']   => 1,
126
    $GLOBALS['XML_RPC_DateTime'] => 1,
127
    $GLOBALS['XML_RPC_Base64']   => 1,
128
    $GLOBALS['XML_RPC_Array']    => 2,
129
    $GLOBALS['XML_RPC_Struct']   => 3,
130
);
131

    
132

    
133
/**
134
 * Error message numbers
135
 * @global array $GLOBALS['XML_RPC_err']
136
 */
137
$GLOBALS['XML_RPC_err'] = array(
138
    'unknown_method'      => 1,
139
    'invalid_return'      => 2,
140
    'incorrect_params'    => 3,
141
    'introspect_unknown'  => 4,
142
    'http_error'          => 5,
143
    'not_response_object' => 6,
144
    'invalid_request'     => 7,
145
);
146

    
147
/**
148
 * Error message strings
149
 * @global array $GLOBALS['XML_RPC_str']
150
 */
151
$GLOBALS['XML_RPC_str'] = array(
152
    'unknown_method'      => gettext("Unknown method"),
153
    'invalid_return'      => gettext("Invalid return payload: enable debugging to examine incoming payload"),
154
    'incorrect_params'    => gettext("Incorrect parameters passed to method"),
155
    'introspect_unknown'  => gettext("Can't introspect: method unknown"),
156
    'http_error'          => gettext("Didn't receive 200 OK from remote server."),
157
    'not_response_object' => gettext("The requested method didn't return an XML_RPC_Response object."),
158
    'invalid_request'     => gettext("Invalid request payload"),
159
);
160

    
161

    
162
/**
163
 * Default XML encoding (ISO-8859-1, UTF-8 or US-ASCII)
164
 * @global string $GLOBALS['XML_RPC_defencoding']
165
 */
166
$GLOBALS['XML_RPC_defencoding'] = 'UTF-8';
167

    
168
/**
169
 * User error codes start at 800
170
 * @global int $GLOBALS['XML_RPC_erruser']
171
 */
172
$GLOBALS['XML_RPC_erruser'] = 800;
173

    
174
/**
175
 * XML parse error codes start at 100
176
 * @global int $GLOBALS['XML_RPC_errxml']
177
 */
178
$GLOBALS['XML_RPC_errxml'] = 100;
179

    
180

    
181
/**
182
 * Compose backslashes for escaping regexp
183
 * @global string $GLOBALS['XML_RPC_backslash']
184
 */
185
$GLOBALS['XML_RPC_backslash'] = chr(92) . chr(92);
186

    
187

    
188
/**
189
 * Should we automatically base64 encode strings that contain characters
190
 * which can cause PHP's SAX-based XML parser to break?
191
 * @global boolean $GLOBALS['XML_RPC_auto_base64']
192
 */
193
$GLOBALS['XML_RPC_auto_base64'] = true;
194

    
195

    
196
/**
197
 * Valid parents of XML elements
198
 * @global array $GLOBALS['XML_RPC_valid_parents']
199
 */
200
$GLOBALS['XML_RPC_valid_parents'] = array(
201
    'BOOLEAN' => array('VALUE'),
202
    'I4' => array('VALUE'),
203
    'INT' => array('VALUE'),
204
    'STRING' => array('VALUE'),
205
    'DOUBLE' => array('VALUE'),
206
    'DATETIME.ISO8601' => array('VALUE'),
207
    'BASE64' => array('VALUE'),
208
    'ARRAY' => array('VALUE'),
209
    'STRUCT' => array('VALUE'),
210
    'PARAM' => array('PARAMS'),
211
    'METHODNAME' => array('METHODCALL'),
212
    'PARAMS' => array('METHODCALL', 'METHODRESPONSE'),
213
    'MEMBER' => array('STRUCT'),
214
    'NAME' => array('MEMBER'),
215
    'DATA' => array('ARRAY'),
216
    'FAULT' => array('METHODRESPONSE'),
217
    'VALUE' => array('MEMBER', 'DATA', 'PARAM', 'FAULT'),
218
);
219

    
220

    
221
/**
222
 * Stores state during parsing
223
 *
224
 * quick explanation of components:
225
 *   + ac     = accumulates values
226
 *   + qt     = decides if quotes are needed for evaluation
227
 *   + cm     = denotes struct or array (comma needed)
228
 *   + isf    = indicates a fault
229
 *   + lv     = indicates "looking for a value": implements the logic
230
 *               to allow values with no types to be strings
231
 *   + params = stores parameters in method calls
232
 *   + method = stores method name
233
 *
234
 * @global array $GLOBALS['XML_RPC_xh']
235
 */
236
$GLOBALS['XML_RPC_xh'] = array();
237

    
238

    
239
/**
240
 * Start element handler for the XML parser
241
 *
242
 * @return void
243
 */
244
function XML_RPC_se($parser_resource, $name, $attrs)
245
{
246
    global $XML_RPC_xh, $XML_RPC_valid_parents;
247

    
248
    $parser = (int) $parser_resource;
249

    
250
    // if invalid xmlrpc already detected, skip all processing
251
    if ($XML_RPC_xh[$parser]['isf'] >= 2) {
252
        return;
253
    }
254

    
255
    // check for correct element nesting
256
    // top level element can only be of 2 types
257
    if (count($XML_RPC_xh[$parser]['stack']) == 0) {
258
        if ($name != 'METHODRESPONSE' && $name != 'METHODCALL') {
259
            $XML_RPC_xh[$parser]['isf'] = 2;
260
            $XML_RPC_xh[$parser]['isf_reason'] = gettext('missing top level xmlrpc element');
261
            return;
262
        }
263
    } else {
264
        // not top level element: see if parent is OK
265
        if (!in_array($XML_RPC_xh[$parser]['stack'][0], $XML_RPC_valid_parents[$name])) {
266
            $name = preg_replace('@[^a-zA-Z0-9._-]@', '', $name);
267
            $XML_RPC_xh[$parser]['isf'] = 2;
268
            $XML_RPC_xh[$parser]['isf_reason'] = sprintf(gettext('xmlrpc element %1$s cannot be child of %2$s'), $name, $XML_RPC_xh[$parser]['stack'][0]);
269
            return;
270
        }
271
    }
272

    
273
    switch ($name) {
274
    case 'STRUCT':
275
        $XML_RPC_xh[$parser]['cm']++;
276

    
277
        // turn quoting off
278
        $XML_RPC_xh[$parser]['qt'] = 0;
279

    
280
        $cur_val = array();
281
        $cur_val['value'] = array();
282
        $cur_val['members'] = 1;
283
        array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
284
        break;
285

    
286
    case 'ARRAY':
287
        $XML_RPC_xh[$parser]['cm']++;
288

    
289
        // turn quoting off
290
        $XML_RPC_xh[$parser]['qt'] = 0;
291

    
292
        $cur_val = array();
293
        $cur_val['value'] = array();
294
        $cur_val['members'] = 0;
295
        array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
296
        break;
297

    
298
    case 'NAME':
299
        $XML_RPC_xh[$parser]['ac'] = '';
300
        break;
301

    
302
    case 'FAULT':
303
        $XML_RPC_xh[$parser]['isf'] = 1;
304
        break;
305

    
306
    case 'PARAM':
307
        $XML_RPC_xh[$parser]['valuestack'] = array();
308
        break;
309

    
310
    case 'VALUE':
311
        $XML_RPC_xh[$parser]['lv'] = 1;
312
        $XML_RPC_xh[$parser]['vt'] = $GLOBALS['XML_RPC_String'];
313
        $XML_RPC_xh[$parser]['ac'] = '';
314
        $XML_RPC_xh[$parser]['qt'] = 0;
315
        // look for a value: if this is still 1 by the
316
        // time we reach the first data segment then the type is string
317
        // by implication and we need to add in a quote
318
        break;
319

    
320
    case 'I4':
321
    case 'INT':
322
    case 'STRING':
323
    case 'BOOLEAN':
324
    case 'DOUBLE':
325
    case 'DATETIME.ISO8601':
326
    case 'BASE64':
327
        $XML_RPC_xh[$parser]['ac'] = ''; // reset the accumulator
328

    
329
        if ($name == 'DATETIME.ISO8601' || $name == 'STRING') {
330
            $XML_RPC_xh[$parser]['qt'] = 1;
331

    
332
            if ($name == 'DATETIME.ISO8601') {
333
                $XML_RPC_xh[$parser]['vt'] = $GLOBALS['XML_RPC_DateTime'];
334
            }
335

    
336
        } elseif ($name == 'BASE64') {
337
            $XML_RPC_xh[$parser]['qt'] = 2;
338
        } else {
339
            // No quoting is required here -- but
340
            // at the end of the element we must check
341
            // for data format errors.
342
            $XML_RPC_xh[$parser]['qt'] = 0;
343
        }
344
        break;
345

    
346
    case 'MEMBER':
347
        $XML_RPC_xh[$parser]['ac'] = '';
348
        break;
349

    
350
    case 'DATA':
351
    case 'METHODCALL':
352
    case 'METHODNAME':
353
    case 'METHODRESPONSE':
354
    case 'PARAMS':
355
        // valid elements that add little to processing
356
        break;
357
    }
358

    
359

    
360
    // Save current element to stack
361
    array_unshift($XML_RPC_xh[$parser]['stack'], $name);
362

    
363
    if ($name != 'VALUE') {
364
        $XML_RPC_xh[$parser]['lv'] = 0;
365
    }
366
}
367

    
368
/**
369
 * End element handler for the XML parser
370
 *
371
 * @return void
372
 */
373
function XML_RPC_ee($parser_resource, $name)
374
{
375
    global $XML_RPC_xh;
376

    
377
    $parser = (int) $parser_resource;
378

    
379
    if ($XML_RPC_xh[$parser]['isf'] >= 2) {
380
        return;
381
    }
382

    
383
    // push this element from stack
384
    // NB: if XML validates, correct opening/closing is guaranteed and
385
    // we do not have to check for $name == $curr_elem.
386
    // we also checked for proper nesting at start of elements...
387
    $curr_elem = array_shift($XML_RPC_xh[$parser]['stack']);
388

    
389
    switch ($name) {
390
    case 'STRUCT':
391
    case 'ARRAY':
392
    $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
393
    $XML_RPC_xh[$parser]['value'] = $cur_val['value'];
394
        $XML_RPC_xh[$parser]['vt'] = strtolower($name);
395
        $XML_RPC_xh[$parser]['cm']--;
396
        break;
397

    
398
    case 'NAME':
399
    $XML_RPC_xh[$parser]['valuestack'][0]['name'] = $XML_RPC_xh[$parser]['ac'];
400
        break;
401

    
402
    case 'BOOLEAN':
403
        // special case here: we translate boolean 1 or 0 into PHP
404
        // constants true or false
405
        if ($XML_RPC_xh[$parser]['ac'] == '1') {
406
            $XML_RPC_xh[$parser]['ac'] = 'true';
407
        } else {
408
            $XML_RPC_xh[$parser]['ac'] = 'false';
409
        }
410

    
411
        $XML_RPC_xh[$parser]['vt'] = strtolower($name);
412
        // Drop through intentionally.
413

    
414
    case 'I4':
415
    case 'INT':
416
    case 'STRING':
417
    case 'DOUBLE':
418
    case 'DATETIME.ISO8601':
419
    case 'BASE64':
420
        if ($XML_RPC_xh[$parser]['qt'] == 1) {
421
            // we use double quotes rather than single so backslashification works OK
422
            $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
423
        } elseif ($XML_RPC_xh[$parser]['qt'] == 2) {
424
            $XML_RPC_xh[$parser]['value'] = base64_decode($XML_RPC_xh[$parser]['ac']);
425
        } elseif ($name == 'BOOLEAN') {
426
            $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
427
        } else {
428
            // we have an I4, INT or a DOUBLE
429
            // we must check that only 0123456789-.<space> are characters here
430
            if (!preg_match("@^[+-]?[0123456789 \t\.]+$@", $XML_RPC_xh[$parser]['ac'])) {
431
                XML_RPC_Base::raiseError(gettext('Non-numeric value received in INT or DOUBLE'),
432
                                         XML_RPC_ERROR_NON_NUMERIC_FOUND);
433
                $XML_RPC_xh[$parser]['value'] = XML_RPC_ERROR_NON_NUMERIC_FOUND;
434
            } else {
435
                // it's ok, add it on
436
                $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
437
            }
438
        }
439

    
440
        $XML_RPC_xh[$parser]['ac'] = '';
441
        $XML_RPC_xh[$parser]['qt'] = 0;
442
        $XML_RPC_xh[$parser]['lv'] = 3; // indicate we've found a value
443
        break;
444

    
445
    case 'VALUE':
446
        if ($XML_RPC_xh[$parser]['vt'] == $GLOBALS['XML_RPC_String']) {
447
            if (strlen($XML_RPC_xh[$parser]['ac']) > 0) {
448
                $XML_RPC_xh[$parser]['value'] = $XML_RPC_xh[$parser]['ac'];
449
            } elseif ($XML_RPC_xh[$parser]['lv'] == 1) {
450
                // The <value> element was empty.
451
                $XML_RPC_xh[$parser]['value'] = '';
452
            }
453
        }
454

    
455
        $temp = new XML_RPC_Value($XML_RPC_xh[$parser]['value'], $XML_RPC_xh[$parser]['vt']);
456

    
457
        $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
458
        if (is_array($cur_val)) {
459
            if ($cur_val['members']==0) {
460
                $cur_val['value'][] = $temp;
461
            } else {
462
                $XML_RPC_xh[$parser]['value'] = $temp;
463
            }
464
            array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
465
        } else {
466
            $XML_RPC_xh[$parser]['value'] = $temp;
467
        }
468
        break;
469

    
470
    case 'MEMBER':
471
        $XML_RPC_xh[$parser]['ac'] = '';
472
        $XML_RPC_xh[$parser]['qt'] = 0;
473

    
474
        $cur_val = array_shift($XML_RPC_xh[$parser]['valuestack']);
475
        if (is_array($cur_val)) {
476
            if ($cur_val['members']==1) {
477
                $cur_val['value'][$cur_val['name']] = $XML_RPC_xh[$parser]['value'];
478
            }
479
            array_unshift($XML_RPC_xh[$parser]['valuestack'], $cur_val);
480
        }
481
        break;
482

    
483
    case 'DATA':
484
        $XML_RPC_xh[$parser]['ac'] = '';
485
        $XML_RPC_xh[$parser]['qt'] = 0;
486
        break;
487

    
488
    case 'PARAM':
489
        $XML_RPC_xh[$parser]['params'][] = $XML_RPC_xh[$parser]['value'];
490
        break;
491

    
492
    case 'METHODNAME':
493
    case 'RPCMETHODNAME':
494
        $XML_RPC_xh[$parser]['method'] = preg_replace("@^[\n\r\t ]+@", '',
495
                                                      $XML_RPC_xh[$parser]['ac']);
496
        break;
497
    }
498

    
499
    // if it's a valid type name, set the type
500
    if (isset($GLOBALS['XML_RPC_Types'][strtolower($name)])) {
501
        $XML_RPC_xh[$parser]['vt'] = strtolower($name);
502
    }
503
}
504

    
505
/**
506
 * Character data handler for the XML parser
507
 *
508
 * @return void
509
 */
510
function XML_RPC_cd($parser_resource, $data)
511
{
512
    global $XML_RPC_xh, $XML_RPC_backslash;
513

    
514
    $parser = (int) $parser_resource;
515

    
516
    if ($XML_RPC_xh[$parser]['lv'] != 3) {
517
        // "lookforvalue==3" means that we've found an entire value
518
        // and should discard any further character data
519

    
520
        if ($XML_RPC_xh[$parser]['lv'] == 1) {
521
            // if we've found text and we're just in a <value> then
522
            // turn quoting on, as this will be a string
523
            $XML_RPC_xh[$parser]['qt'] = 1;
524
            // and say we've found a value
525
            $XML_RPC_xh[$parser]['lv'] = 2;
526
        }
527

    
528
        // replace characters that eval would
529
        // do special things with
530
        if (!isset($XML_RPC_xh[$parser]['ac'])) {
531
            $XML_RPC_xh[$parser]['ac'] = '';
532
        }
533
        $XML_RPC_xh[$parser]['ac'] .= $data;
534
    }
535
}
536

    
537
/**
538
 * The common methods and properties for all of the XML_RPC classes
539
 *
540
 * @category   Web Services
541
 * @package    XML_RPC
542
 * @author     Edd Dumbill <edd@usefulinc.com>
543
 * @author     Stig Bakken <stig@php.net>
544
 * @author     Martin Jansen <mj@php.net>
545
 * @author     Daniel Convissor <danielc@php.net>
546
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
547
 * @license    http://www.php.net/license/3_01.txt  PHP License
548
 * @version    Release: @package_version@
549
 * @link       http://pear.php.net/package/XML_RPC
550
 */
551
class XML_RPC_Base {
552

    
553
    /**
554
     * PEAR Error handling
555
     *
556
     * @return object  PEAR_Error object
557
     */
558
    function raiseError($msg, $code)
559
    {
560
        include_once 'PEAR.inc';
561
        if (is_object(@$this)) {
562
	    log_error(get_class($this) . ': ' . $msg . " {$code}");
563
            return PEAR::raiseError(get_class($this) . ': ' . $msg, $code);
564
        } else {
565
	    log_error("XML_RPC: " . ': ' . $msg . " {$code}");
566
            return PEAR::raiseError('XML_RPC: ' . $msg, $code);
567
        }
568
    }
569

    
570
    /**
571
     * Tell whether something is a PEAR_Error object
572
     *
573
     * @param mixed $value  the item to check
574
     *
575
     * @return bool  whether $value is a PEAR_Error object or not
576
     *
577
     * @access public
578
     */
579
    function isError($value)
580
    {
581
        return is_a($value, 'PEAR_Error');
582
    }
583
}
584

    
585
/**
586
 * The methods and properties for submitting XML RPC requests
587
 *
588
 * @category   Web Services
589
 * @package    XML_RPC
590
 * @author     Edd Dumbill <edd@usefulinc.com>
591
 * @author     Stig Bakken <stig@php.net>
592
 * @author     Martin Jansen <mj@php.net>
593
 * @author     Daniel Convissor <danielc@php.net>
594
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
595
 * @license    http://www.php.net/license/3_01.txt  PHP License
596
 * @version    Release: @package_version@
597
 * @link       http://pear.php.net/package/XML_RPC
598
 */
599
class XML_RPC_Client extends XML_RPC_Base {
600

    
601
    /**
602
     * The path and name of the RPC server script you want the request to go to
603
     * @var string
604
     */
605
    var $path = '';
606

    
607
    /**
608
     * The name of the remote server to connect to
609
     * @var string
610
     */
611
    var $server = '';
612

    
613
    /**
614
     * The protocol to use in contacting the remote server
615
     * @var string
616
     */
617
    var $protocol = 'tcp://';
618

    
619
    /**
620
     * The port for connecting to the remote server
621
     *
622
     * The default is 80 for http:// connections
623
     * and 443 for https:// and ssl:// connections.
624
     *
625
     * @var integer
626
     */
627
    var $port = 80;
628

    
629
    /**
630
     * A user name for accessing the RPC server
631
     * @var string
632
     * @see XML_RPC_Client::setCredentials()
633
     */
634
    var $username = '';
635

    
636
    /**
637
     * A password for accessing the RPC server
638
     * @var string
639
     * @see XML_RPC_Client::setCredentials()
640
     */
641
    var $password = '';
642

    
643
    /**
644
     * The name of the proxy server to use, if any
645
     * @var string
646
     */
647
    var $proxy = '';
648

    
649
    /**
650
     * The protocol to use in contacting the proxy server, if any
651
     * @var string
652
     */
653
    var $proxy_protocol = 'tcp://';
654

    
655
    /**
656
     * The port for connecting to the proxy server
657
     *
658
     * The default is 8080 for http:// connections
659
     * and 443 for https:// and ssl:// connections.
660
     *
661
     * @var integer
662
     */
663
    var $proxy_port = 8080;
664

    
665
    /**
666
     * A user name for accessing the proxy server
667
     * @var string
668
     */
669
    var $proxy_user = '';
670

    
671
    /**
672
     * A password for accessing the proxy server
673
     * @var string
674
     */
675
    var $proxy_pass = '';
676

    
677
    /**
678
     * The error number, if any
679
     * @var integer
680
     */
681
    var $errno = 0;
682

    
683
    /**
684
     * The error message, if any
685
     * @var string
686
     */
687
    var $errstr = '';
688

    
689
    /**
690
     * The current debug mode (1 = on, 0 = off)
691
     * @var integer
692
     */
693
    var $debug = 0;
694

    
695
    /**
696
     * The HTTP headers for the current request.
697
     * @var string
698
     */
699
    var $headers = '';
700

    
701

    
702
    /**
703
     * Sets the object's properties
704
     *
705
     * @param string  $path        the path and name of the RPC server script
706
     *                              you want the request to go to
707
     * @param string  $server      the URL of the remote server to connect to.
708
     *                              If this parameter doesn't specify a
709
     *                              protocol and $port is 443, ssl:// is
710
     *                              assumed.
711
     * @param integer $port        a port for connecting to the remote server.
712
     *                              Defaults to 80 for http:// connections and
713
     *                              443 for https:// and ssl:// connections.
714
     * @param string  $proxy       the URL of the proxy server to use, if any.
715
     *                              If this parameter doesn't specify a
716
     *                              protocol and $port is 443, ssl:// is
717
     *                              assumed.
718
     * @param integer $proxy_port  a port for connecting to the remote server.
719
     *                              Defaults to 8080 for http:// connections and
720
     *                              443 for https:// and ssl:// connections.
721
     * @param string  $proxy_user  a user name for accessing the proxy server
722
     * @param string  $proxy_pass  a password for accessing the proxy server
723
     *
724
     * @return void
725
     */
726
    function XML_RPC_Client($path, $server, $port = 0,
727
                            $proxy = '', $proxy_port = 0,
728
                            $proxy_user = '', $proxy_pass = '')
729
    {
730
        $this->path       = $path;
731
        $this->proxy_user = $proxy_user;
732
        $this->proxy_pass = $proxy_pass;
733

    
734
        preg_match('@^(http://|https://|ssl://)?(.*)$@', $server, $match);
735
        if ($match[1] == '') {
736
            if ($port == 443) {
737
                $this->server   = $match[2];
738
                $this->protocol = 'ssl://';
739
                $this->port     = 443;
740
            } else {
741
                $this->server = $match[2];
742
                $this->protocol = 'tcp://';
743
                if ($port) {
744
                    $this->port = $port;
745
                }
746
            }
747
        } elseif ($match[1] == 'http://') {
748
            $this->server = $match[2];
749
            $this->protocol = 'tcp://';
750
            if ($port) {
751
                $this->port = $port;
752
            }
753
        } else {
754
            $this->server   = $match[2];
755
            $this->protocol = 'ssl://';
756
            if ($port) {
757
                $this->port = $port;
758
            } else {
759
                $this->port = 443;
760
            }
761
        }
762

    
763
        if ($proxy) {
764
            preg_match('@^(http://|https://|ssl://)?(.*)$@', $proxy, $match);
765
            if ($match[1] == '') {
766
                if ($proxy_port == 443) {
767
                    $this->proxy          = $match[2];
768
                    $this->proxy_protocol = 'ssl://';
769
                    $this->proxy_port     = 443;
770
                } else {
771
                    $this->proxy = $match[2];
772
                    $this->proxy_protocol = 'tcp://';
773
                    if ($proxy_port) {
774
                        $this->proxy_port = $proxy_port;
775
                    }
776
                }
777
            } elseif ($match[1] == 'http://') {
778
                $this->proxy = $match[2];
779
                $this->proxy_protocol = 'tcp://';
780
                if ($proxy_port) {
781
                    $this->proxy_port = $proxy_port;
782
                }
783
            } else {
784
                $this->proxy          = $match[2];
785
                $this->proxy_protocol = 'ssl://';
786
                if ($proxy_port) {
787
                    $this->proxy_port = $proxy_port;
788
                } else {
789
                    $this->proxy_port = 443;
790
                }
791
            }
792
        }
793
    }
794

    
795
    /**
796
     * Change the current debug mode
797
     *
798
     * @param int $in  where 1 = on, 0 = off
799
     *
800
     * @return void
801
     */
802
    function setDebug($in)
803
    {
804
        if ($in) {
805
            $this->debug = 1;
806
        } else {
807
            $this->debug = 0;
808
        }
809
    }
810

    
811
    /**
812
     * Sets whether strings that contain characters which may cause PHP's
813
     * SAX-based XML parser to break should be automatically base64 encoded
814
     *
815
     * This is is a workaround for systems that don't have PHP's mbstring
816
     * extension available.
817
     *
818
     * @param int $in  where 1 = on, 0 = off
819
     *
820
     * @return void
821
     */
822
    function setAutoBase64($in)
823
    {
824
        if ($in) {
825
            $GLOBALS['XML_RPC_auto_base64'] = true;
826
        } else {
827
            $GLOBALS['XML_RPC_auto_base64'] = false;
828
        }
829
    }
830

    
831
    /**
832
     * Set username and password properties for connecting to the RPC server
833
     *
834
     * @param string $u  the user name
835
     * @param string $p  the password
836
     *
837
     * @return void
838
     *
839
     * @see XML_RPC_Client::$username, XML_RPC_Client::$password
840
     */
841
    function setCredentials($u, $p)
842
    {
843
        $this->username = $u;
844
        $this->password = $p;
845
    }
846

    
847
    /**
848
     * Transmit the RPC request via HTTP 1.0 protocol
849
     *
850
     * @param object $msg       the XML_RPC_Message object
851
     * @param int    $timeout   how many seconds to wait for the request
852
     *
853
     * @return object  an XML_RPC_Response object.  0 is returned if any
854
     *                  problems happen.
855
     *
856
     * @see XML_RPC_Message, XML_RPC_Client::XML_RPC_Client(),
857
     *      XML_RPC_Client::setCredentials()
858
     */
859
    function send($msg, $timeout = 0)
860
    {
861
        if (!is_a($msg, 'XML_RPC_Message')) {
862
            $this->errstr = sprintf(
863
                gettext(
864
                    "send()'s %s parameter must be an XML_RPC_Message object."
865
                ), $msg);
866
            $this->raiseError($this->errstr, XML_RPC_ERROR_PROGRAMMING);
867
            return 0;
868
        }
869
        $msg->debug = $this->debug;
870
        return $this->sendPayloadHTTP10($msg, $this->server, $this->port,
871
                                        $timeout, $this->username,
872
                                        $this->password);
873
    }
874

    
875
    /**
876
     * Transmit the RPC request via HTTP 1.0 protocol
877
     *
878
     * Requests should be sent using XML_RPC_Client send() rather than
879
     * calling this method directly.
880
     *
881
     * @param object $msg       the XML_RPC_Message object
882
     * @param string $server    the server to send the request to
883
     * @param int    $port      the server port send the request to
884
     * @param int    $timeout   how many seconds to wait for the request
885
     *                           before giving up
886
     * @param string $username  a user name for accessing the RPC server
887
     * @param string $password  a password for accessing the RPC server
888
     *
889
     * @return object  an XML_RPC_Response object.  0 is returned if any
890
     *                  problems happen.
891
     *
892
     * @access protected
893
     * @see XML_RPC_Client::send()
894
     */
895
    function sendPayloadHTTP10($msg, $server, $port, $timeout = 0,
896
                               $username = '', $password = '')
897
    {
898
        // Pre-emptive BC hacks for fools calling sendPayloadHTTP10() directly
899
        if ($username != $this->username) {
900
            $this->setCredentials($username, $password);
901
        }
902

    
903
        // Only create the payload if it was not created previously
904
        if (empty($msg->payload)) {
905
            $msg->createPayload();
906
        }
907
        $this->createHeaders($msg);
908

    
909
        $op  = $this->headers . "\r\n\r\n";
910
        $op .= $msg->payload;
911

    
912
        if ($this->debug) {
913
            print "\n<pre>---SENT---\n";
914
            print $op;
915
            print "\n---END---</pre>\n";
916
        }
917

    
918
        $ctx_options = array();
919

    
920
        /* Add proxy to context when it's set */
921
        if ($this->proxy) {
922
            $ctx_options['http'] = array(
923
                'proxy' => "{$this->proxy_protocol}{$this->proxy}:{$this->proxy_port}"
924
            );
925
        }
926

    
927
        /* Disable SSL certificate check since it's used only by HA nowadays */
928
        $ctx_options['ssl'] = array(
929
            'verify_peer' => false,
930
            'verify_peer_name' => false
931
        );
932

    
933
        $ctx = stream_context_create($ctx_options);
934

    
935
        $fp = @stream_socket_client("{$this->protocol}{$server}:{$port}",
936
            $this->errno, $this->errstr,
937
            ($timeout > 0 ? $timeout : ini_get("default_socket_timeout")),
938
            STREAM_CLIENT_CONNECT, $ctx);
939

    
940
        /*
941
         * Just raising the error without returning it is strange,
942
         * but keep it here for backwards compatibility.
943
         */
944
        if (!$fp && $this->proxy) {
945
            $this->raiseError(sprintf(gettext('Connection to proxy server 
946
                              %1$s:%2$s failed. %3$s')
947
                              ,$this->proxy,$this->proxy_port,$this->errstr),
948
                              XML_RPC_ERROR_CONNECTION_FAILED);
949
            return 0;
950
        } elseif (!$fp) {
951
            $this->raiseError(sprintf(gettext('Connection to RPC server 
952
                              %1$s:%2$s failed. %3$s')
953
                              ,$server,$port,$this->errstr),
954
                              XML_RPC_ERROR_CONNECTION_FAILED);
955
            return 0;
956
        }
957

    
958
        if (!fputs($fp, $op, strlen($op))) {
959
            $this->errstr = 'Write error';
960
            return 0;
961
        }
962
        $resp = $msg->parseResponseFile($fp);
963

    
964
        $meta = socket_get_status($fp);
965
        if ($meta['timed_out']) {
966
            fclose($fp);
967
            $this->errstr = 'RPC server did not send response before timeout.';
968
            $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED);
969
            return 0;
970
        }
971

    
972
        fclose($fp);
973
        return $resp;
974
    }
975

    
976
    /**
977
     * Determines the HTTP headers and puts it in the $headers property
978
     *
979
     * @param object $msg       the XML_RPC_Message object
980
     *
981
     * @return boolean  TRUE if okay, FALSE if the message payload isn't set.
982
     *
983
     * @access protected
984
     */
985
    function createHeaders($msg)
986
    {
987
        if (empty($msg->payload)) {
988
            return false;
989
        }
990
        if ($this->proxy) {
991
            $this->headers = 'POST ' . ($this->protocol=='ssl://'?'https://':$this->protocol). $this->server;
992
            if ($this->proxy_port) {
993
                $this->headers .= ':' . $this->port;
994
            }
995
        } else {
996
           $this->headers = 'POST ';
997
        }
998
        $this->headers .= $this->path. " HTTP/1.0\r\n";
999

    
1000
        $this->headers .= "User-Agent: PEAR XML_RPC\r\n";
1001
        $this->headers .= 'Host: ' . $this->server . "\r\n";
1002

    
1003
        if ($this->proxy && $this->proxy_user) {
1004
            $this->headers .= 'Proxy-Authorization: Basic '
1005
                     . base64_encode("$this->proxy_user:$this->proxy_pass")
1006
                     . "\r\n";
1007
        }
1008

    
1009
        // thanks to Grant Rauscher <grant7@firstworld.net> for this
1010
        if ($this->username) {
1011
            $this->headers .= 'Authorization: Basic '
1012
                     . base64_encode("$this->username:$this->password")
1013
                     . "\r\n";
1014
        }
1015

    
1016
        $this->headers .= "Content-Type: text/xml\r\n";
1017
        $this->headers .= 'Content-Length: ' . strlen($msg->payload);
1018
        return true;
1019
    }
1020
}
1021

    
1022
/**
1023
 * The methods and properties for interpreting responses to XML RPC requests
1024
 *
1025
 * @category   Web Services
1026
 * @package    XML_RPC
1027
 * @author     Edd Dumbill <edd@usefulinc.com>
1028
 * @author     Stig Bakken <stig@php.net>
1029
 * @author     Martin Jansen <mj@php.net>
1030
 * @author     Daniel Convissor <danielc@php.net>
1031
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
1032
 * @license    http://www.php.net/license/3_01.txt  PHP License
1033
 * @version    Release: @package_version@
1034
 * @link       http://pear.php.net/package/XML_RPC
1035
 */
1036
class XML_RPC_Response extends XML_RPC_Base
1037
{
1038
    var $xv;
1039
    var $fn;
1040
    var $fs;
1041
    var $hdrs;
1042

    
1043
    /**
1044
     * @return void
1045
     */
1046
    function XML_RPC_Response($val, $fcode = 0, $fstr = '')
1047
    {
1048
        if ($fcode != 0) {
1049
            $this->fn = $fcode;
1050
            $this->fs = htmlspecialchars($fstr);
1051
        } else {
1052
            $this->xv = $val;
1053
        }
1054
    }
1055

    
1056
    /**
1057
     * @return int  the error code
1058
     */
1059
    function faultCode()
1060
    {
1061
        if (isset($this->fn)) {
1062
            return $this->fn;
1063
        } else {
1064
            return 0;
1065
        }
1066
    }
1067

    
1068
    /**
1069
     * @return string  the error string
1070
     */
1071
    function faultString()
1072
    {
1073
        return $this->fs;
1074
    }
1075

    
1076
    /**
1077
     * @return mixed  the value
1078
     */
1079
    function value()
1080
    {
1081
        return $this->xv;
1082
    }
1083

    
1084
    /**
1085
     * @return string  the error message in XML format
1086
     */
1087
    function serialize()
1088
    {
1089
        $rs = "<methodResponse>\n";
1090
        if ($this->fn) {
1091
            $rs .= "<fault>
1092
  <value>
1093
    <struct>
1094
      <member>
1095
        <name>faultCode</name>
1096
        <value><int>" . $this->fn . "</int></value>
1097
      </member>
1098
      <member>
1099
        <name>faultString</name>
1100
        <value><string>" . $this->fs . "</string></value>
1101
      </member>
1102
    </struct>
1103
  </value>
1104
</fault>";
1105
        } else {
1106
            $rs .= "<params>\n<param>\n" . $this->xv->serialize() .
1107
        "</param>\n</params>";
1108
        }
1109
        $rs .= "\n</methodResponse>";
1110
        return $rs;
1111
    }
1112
}
1113

    
1114
/**
1115
 * The methods and properties for composing XML RPC messages
1116
 *
1117
 * @category   Web Services
1118
 * @package    XML_RPC
1119
 * @author     Edd Dumbill <edd@usefulinc.com>
1120
 * @author     Stig Bakken <stig@php.net>
1121
 * @author     Martin Jansen <mj@php.net>
1122
 * @author     Daniel Convissor <danielc@php.net>
1123
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
1124
 * @license    http://www.php.net/license/3_01.txt  PHP License
1125
 * @version    Release: @package_version@
1126
 * @link       http://pear.php.net/package/XML_RPC
1127
 */
1128
class XML_RPC_Message extends XML_RPC_Base
1129
{
1130
    /**
1131
     * Should the payload's content be passed through mb_convert_encoding()?
1132
     *
1133
     * @see XML_RPC_Message::setConvertPayloadEncoding()
1134
     * @since Property available since Release 1.5.1
1135
     * @var boolean
1136
     */
1137
    var $convert_payload_encoding = false;
1138

    
1139
    /**
1140
     * The current debug mode (1 = on, 0 = off)
1141
     * @var integer
1142
     */
1143
    var $debug = 0;
1144

    
1145
    /**
1146
     * The encoding to be used for outgoing messages
1147
     *
1148
     * Defaults to the value of <var>$GLOBALS['XML_RPC_defencoding']</var>
1149
     *
1150
     * @var string
1151
     * @see XML_RPC_Message::setSendEncoding(),
1152
     *      $GLOBALS['XML_RPC_defencoding'], XML_RPC_Message::xml_header()
1153
     */
1154
    var $send_encoding = '';
1155

    
1156
    /**
1157
     * The method presently being evaluated
1158
     * @var string
1159
     */
1160
    var $methodname = '';
1161

    
1162
    /**
1163
     * @var array
1164
     */
1165
    var $params = array();
1166

    
1167
    /**
1168
     * The XML message being generated
1169
     * @var string
1170
     */
1171
    var $payload = '';
1172

    
1173
    /**
1174
     * Should extra line breaks be removed from the payload?
1175
     * @since Property available since Release 1.4.6
1176
     * @var boolean
1177
     */
1178
    var $remove_extra_lines = true;
1179

    
1180
    /**
1181
     * The XML response from the remote server
1182
     * @since Property available since Release 1.4.6
1183
     * @var string
1184
     */
1185
    var $response_payload = '';
1186

    
1187

    
1188
    /**
1189
     * @return void
1190
     */
1191
    function XML_RPC_Message($meth, $pars = 0)
1192
    {
1193
        $this->methodname = $meth;
1194
        if (is_array($pars) && sizeof($pars) > 0) {
1195
            for ($i = 0; $i < sizeof($pars); $i++) {
1196
                $this->addParam($pars[$i]);
1197
            }
1198
        }
1199
    }
1200

    
1201
    /**
1202
     * Produces the XML declaration including the encoding attribute
1203
     *
1204
     * The encoding is determined by this class' <var>$send_encoding</var>
1205
     * property.  If the <var>$send_encoding</var> property is not set, use
1206
     * <var>$GLOBALS['XML_RPC_defencoding']</var>.
1207
     *
1208
     * @return string  the XML declaration and <methodCall> element
1209
     *
1210
     * @see XML_RPC_Message::setSendEncoding(),
1211
     *      XML_RPC_Message::$send_encoding, $GLOBALS['XML_RPC_defencoding']
1212
     */
1213
    function xml_header()
1214
    {
1215
        global $XML_RPC_defencoding;
1216

    
1217
        if (!$this->send_encoding) {
1218
            $this->send_encoding = $XML_RPC_defencoding;
1219
        }
1220
        return '<?xml version="1.0" encoding="' . $this->send_encoding . '"?>'
1221
               . "\n<methodCall>\n";
1222
    }
1223

    
1224
    /**
1225
     * @return string  the closing </methodCall> tag
1226
     */
1227
    function xml_footer()
1228
    {
1229
        return "</methodCall>\n";
1230
    }
1231

    
1232
    /**
1233
     * Fills the XML_RPC_Message::$payload property
1234
     *
1235
     * Part of the process makes sure all line endings are in DOS format
1236
     * (CRLF), which is probably required by specifications.
1237
     *
1238
     * If XML_RPC_Message::setConvertPayloadEncoding() was set to true,
1239
     * the payload gets passed through mb_convert_encoding()
1240
     * to ensure the payload matches the encoding set in the
1241
     * XML declaration.  The encoding type can be manually set via
1242
     * XML_RPC_Message::setSendEncoding().
1243
     *
1244
     * @return void
1245
     *
1246
     * @uses XML_RPC_Message::xml_header(), XML_RPC_Message::xml_footer()
1247
     * @see XML_RPC_Message::setSendEncoding(), $GLOBALS['XML_RPC_defencoding'],
1248
     *      XML_RPC_Message::setConvertPayloadEncoding()
1249
     */
1250
    function createPayload()
1251
    {
1252
        $this->payload = $this->xml_header();
1253
        $this->payload .= '<methodName>' . $this->methodname . "</methodName>\n";
1254
        $this->payload .= "<params>\n";
1255
        for ($i = 0; $i < sizeof($this->params); $i++) {
1256
            $p = $this->params[$i];
1257
            $this->payload .= "<param>\n" . $p->serialize() . "</param>\n";
1258
        }
1259
        $this->payload .= "</params>\n";
1260
        $this->payload .= $this->xml_footer();
1261
        if ($this->remove_extra_lines) {
1262
            $this->payload = preg_replace("@[\r\n]+@", "\r\n", $this->payload);
1263
        } else {
1264
            $this->payload = preg_replace("@\r\n|\n|\r|\n\r@", "\r\n", $this->payload);
1265
        }
1266
        if ($this->convert_payload_encoding) {
1267
            $this->payload = mb_convert_encoding($this->payload, $this->send_encoding);
1268
        }
1269
    }
1270

    
1271
    /**
1272
     * @return string  the name of the method
1273
     */
1274
    function method($meth = '')
1275
    {
1276
        if ($meth != '') {
1277
            $this->methodname = $meth;
1278
        }
1279
        return $this->methodname;
1280
    }
1281

    
1282
    /**
1283
     * @return string  the payload
1284
     */
1285
    function serialize()
1286
    {
1287
        $this->createPayload();
1288
        return $this->payload;
1289
    }
1290

    
1291
    /**
1292
     * @return void
1293
     */
1294
    function addParam($par)
1295
    {
1296
        $this->params[] = $par;
1297
    }
1298

    
1299
    /**
1300
     * Obtains an XML_RPC_Value object for the given parameter
1301
     *
1302
     * @param int $i  the index number of the parameter to obtain
1303
     *
1304
     * @return object  the XML_RPC_Value object.
1305
     *                  If the parameter doesn't exist, an XML_RPC_Response object.
1306
     *
1307
     * @since Returns XML_RPC_Response object on error since Release 1.3.0
1308
     */
1309
    function getParam($i)
1310
    {
1311
        global $XML_RPC_err, $XML_RPC_str;
1312

    
1313
        if (isset($this->params[$i])) {
1314
            return $this->params[$i];
1315
        } else {
1316
            $this->raiseError(gettext('The submitted request did not contain this parameter'),
1317
                              XML_RPC_ERROR_INCORRECT_PARAMS);
1318
            return new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
1319
                                        $XML_RPC_str['incorrect_params']);
1320
        }
1321
    }
1322

    
1323
    /**
1324
     * @return int  the number of parameters
1325
     */
1326
    function getNumParams()
1327
    {
1328
        return sizeof($this->params);
1329
    }
1330

    
1331
    /**
1332
     * Sets whether the payload's content gets passed through
1333
     * mb_convert_encoding()
1334
     *
1335
     * Returns PEAR_ERROR object if mb_convert_encoding() isn't available.
1336
     *
1337
     * @param int $in  where 1 = on, 0 = off
1338
     *
1339
     * @return void
1340
     *
1341
     * @see XML_RPC_Message::setSendEncoding()
1342
     * @since Method available since Release 1.5.1
1343
     */
1344
    function setConvertPayloadEncoding($in)
1345
    {
1346
        if ($in && !function_exists('mb_convert_encoding')) {
1347
            return $this->raiseError(gettext('mb_convert_encoding() is not available'),
1348
                              XML_RPC_ERROR_PROGRAMMING);
1349
        }
1350
        $this->convert_payload_encoding = $in;
1351
    }
1352

    
1353
    /**
1354
     * Sets the XML declaration's encoding attribute
1355
     *
1356
     * @param string $type  the encoding type (ISO-8859-1, UTF-8 or US-ASCII)
1357
     *
1358
     * @return void
1359
     *
1360
     * @see XML_RPC_Message::setConvertPayloadEncoding(), XML_RPC_Message::xml_header()
1361
     * @since Method available since Release 1.2.0
1362
     */
1363
    function setSendEncoding($type)
1364
    {
1365
        $this->send_encoding = $type;
1366
    }
1367

    
1368
    /**
1369
     * Determine the XML's encoding via the encoding attribute
1370
     * in the XML declaration
1371
     *
1372
     * If the encoding parameter is not set or is not ISO-8859-1, UTF-8
1373
     * or US-ASCII, $XML_RPC_defencoding will be returned.
1374
     *
1375
     * @param string $data  the XML that will be parsed
1376
     *
1377
     * @return string  the encoding to be used
1378
     *
1379
     * @link   http://php.net/xml_parser_create
1380
     * @since  Method available since Release 1.2.0
1381
     */
1382
    function getEncoding($data)
1383
    {
1384
        global $XML_RPC_defencoding;
1385

    
1386
        if (preg_match('@<\?xml[^>]*\s*encoding\s*=\s*[\'"]([^"\']*)[\'"]@',
1387
                       $data, $match))
1388
        {
1389
            $match[1] = trim(strtoupper($match[1]));
1390
            switch ($match[1]) {
1391
                case 'ISO-8859-1':
1392
                case 'UTF-8':
1393
                case 'US-ASCII':
1394
                    return $match[1];
1395
                    break;
1396

    
1397
                default:
1398
                    return $XML_RPC_defencoding;
1399
            }
1400
        } else {
1401
            return $XML_RPC_defencoding;
1402
        }
1403
    }
1404

    
1405
    /**
1406
     * @return object  a new XML_RPC_Response object
1407
     */
1408
    function parseResponseFile($fp)
1409
    {
1410
        $ipd = '';
1411
        while ($data = @fread($fp, 8192)) {
1412
            $ipd .= $data;
1413
        }
1414
        return $this->parseResponse($ipd);
1415
    }
1416

    
1417
    /**
1418
     * @return object  a new XML_RPC_Response object
1419
     */
1420
    function parseResponse($data = '')
1421
    {
1422
        global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding;
1423

    
1424
        $encoding = $this->getEncoding($data);
1425
        $parser_resource = xml_parser_create($encoding);
1426
        $parser = (int) $parser_resource;
1427

    
1428
        $XML_RPC_xh = array();
1429
        $XML_RPC_xh[$parser] = array();
1430

    
1431
        $XML_RPC_xh[$parser]['cm'] = 0;
1432
        $XML_RPC_xh[$parser]['isf'] = 0;
1433
        $XML_RPC_xh[$parser]['ac'] = '';
1434
        $XML_RPC_xh[$parser]['qt'] = '';
1435
        $XML_RPC_xh[$parser]['stack'] = array();
1436
        $XML_RPC_xh[$parser]['valuestack'] = array();
1437

    
1438
        xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
1439
        xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
1440
        xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
1441

    
1442
        $hdrfnd = 0;
1443
        if ($this->debug) {
1444
            print "\n<pre>---GOT---\n";
1445
            print isset($_SERVER['SERVER_PROTOCOL']) ? htmlspecialchars($data) : $data;
1446
            print "\n---END---</pre>\n";
1447
        }
1448

    
1449
        // See if response is a 200 or a 100 then a 200, else raise error.
1450
        // But only do this if we're using the HTTP protocol.
1451
        if (preg_match('@^HTTP@', $data) &&
1452
            !preg_match('@^HTTP/[0-9\.]+ 200 @', $data) &&
1453
            !preg_match('@^HTTP/[0-9\.]+ 10[0-9]([A-Z ]+)?[\r\n]+HTTP/[0-9\.]+ 200@', $data))
1454
        {
1455
                $errstr = substr($data, 0, strpos($data, "\n") - 1);
1456
                error_log(sprintf(gettext("HTTP error, got response: %s"),$errstr));
1457
                $r = new XML_RPC_Response(0, $XML_RPC_err['http_error'],
1458
                                          $XML_RPC_str['http_error'] . ' (' .
1459
                                          $errstr . ')');
1460
                xml_parser_free($parser_resource);
1461
                return $r;
1462
        }
1463

    
1464
        // gotta get rid of headers here
1465
        if (!$hdrfnd && ($brpos = strpos($data,"\r\n\r\n"))) {
1466
            $XML_RPC_xh[$parser]['ha'] = substr($data, 0, $brpos);
1467
            $data = substr($data, $brpos + 4);
1468
            $hdrfnd = 1;
1469
        }
1470

    
1471
        /*
1472
         * be tolerant of junk after methodResponse
1473
         * (e.g. javascript automatically inserted by free hosts)
1474
         * thanks to Luca Mariano <luca.mariano@email.it>
1475
         */
1476
        $data = substr($data, 0, strpos($data, "</methodResponse>") + 17);
1477
        $this->response_payload = $data;
1478

    
1479
        if (!xml_parse($parser_resource, $data, sizeof($data))) {
1480
            // thanks to Peter Kocks <peter.kocks@baygate.com>
1481
            if (xml_get_current_line_number($parser_resource) == 1) {
1482
		/* We already error on this in the GUI, no need to log it and cause a PHP error. */
1483
		//$errstr = gettext("XML error at line 1, check URL");
1484
            } else {
1485
                $errstr = sprintf('XML error: %s at line %d',
1486
                                  xml_error_string(xml_get_error_code($parser_resource)),
1487
                                  xml_get_current_line_number($parser_resource));
1488
            }
1489
		if (!empty($errstr))
1490
			error_log($errstr);
1491
            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
1492
                                      $XML_RPC_str['invalid_return']);
1493
            xml_parser_free($parser_resource);
1494
            return $r;
1495
        }
1496

    
1497
        xml_parser_free($parser_resource);
1498

    
1499
        if ($this->debug) {
1500
            print "\n<pre>---PARSED---\n";
1501
            var_dump($XML_RPC_xh[$parser]['value']);
1502
            print "---END---</pre>\n";
1503
        }
1504

    
1505
        if ($XML_RPC_xh[$parser]['isf'] > 1) {
1506
            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
1507
                                      $XML_RPC_str['invalid_return'].' '.$XML_RPC_xh[$parser]['isf_reason']);
1508
        } elseif (!is_object($XML_RPC_xh[$parser]['value'])) {
1509
            // then something odd has happened
1510
            // and it's time to generate a client side error
1511
            // indicating something odd went on
1512
            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
1513
                                      $XML_RPC_str['invalid_return']);
1514
        } else {
1515
            $v = $XML_RPC_xh[$parser]['value'];
1516
            if ($XML_RPC_xh[$parser]['isf']) {
1517
                $f = $v->structmem('faultCode');
1518
                $fs = $v->structmem('faultString');
1519
                $r = new XML_RPC_Response($v, $f->scalarval(),
1520
                                          $fs->scalarval());
1521
            } else {
1522
                $r = new XML_RPC_Response($v);
1523
            }
1524
        }
1525
        $r->hdrs = preg_split("@\r?\n@", $XML_RPC_xh[$parser]['ha'][1]);
1526
        return $r;
1527
    }
1528
}
1529

    
1530
/**
1531
 * The methods and properties that represent data in XML RPC format
1532
 *
1533
 * @category   Web Services
1534
 * @package    XML_RPC
1535
 * @author     Edd Dumbill <edd@usefulinc.com>
1536
 * @author     Stig Bakken <stig@php.net>
1537
 * @author     Martin Jansen <mj@php.net>
1538
 * @author     Daniel Convissor <danielc@php.net>
1539
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
1540
 * @license    http://www.php.net/license/3_01.txt  PHP License
1541
 * @version    Release: @package_version@
1542
 * @link       http://pear.php.net/package/XML_RPC
1543
 */
1544
class XML_RPC_Value extends XML_RPC_Base
1545
{
1546
    var $me = array();
1547
    var $mytype = 0;
1548

    
1549
    /**
1550
     * @return void
1551
     */
1552
    function XML_RPC_Value($val = -1, $type = '')
1553
    {
1554
        $this->me = array();
1555
        $this->mytype = 0;
1556
        if ($val != -1 || $type != '') {
1557
            if ($type == '') {
1558
                $type = 'string';
1559
            }
1560
            if (!array_key_exists($type, $GLOBALS['XML_RPC_Types'])) {
1561
                // XXX
1562
                // need some way to report this error
1563
            } elseif ($GLOBALS['XML_RPC_Types'][$type] == 1) {
1564
                $this->addScalar($val, $type);
1565
            } elseif ($GLOBALS['XML_RPC_Types'][$type] == 2) {
1566
                $this->addArray($val);
1567
            } elseif ($GLOBALS['XML_RPC_Types'][$type] == 3) {
1568
                $this->addStruct($val);
1569
            }
1570
        }
1571
    }
1572

    
1573
    /**
1574
     * @return int  returns 1 if successful or 0 if there are problems
1575
     */
1576
    function addScalar($val, $type = 'string')
1577
    {
1578
        if ($this->mytype == 1) {
1579
            $this->raiseError(gettext('Scalar can have only one value'),
1580
                              XML_RPC_ERROR_INVALID_TYPE);
1581
            return 0;
1582
        }
1583
        $typeof = $GLOBALS['XML_RPC_Types'][$type];
1584
        if ($typeof != 1) {
1585
            $this->raiseError(
1586
                sprintf(gettext("Not a scalar type (%s)"), $typeof),
1587
                XML_RPC_ERROR_INVALID_TYPE);
1588
            return 0;
1589
        }
1590

    
1591
        if ($type == $GLOBALS['XML_RPC_Boolean']) {
1592
            if (strcasecmp($val, 'true') == 0
1593
                || $val == 1
1594
                || ($val == true && strcasecmp($val, 'false')))
1595
            {
1596
                $val = 1;
1597
            } else {
1598
                $val = 0;
1599
            }
1600
        }
1601

    
1602
        if ($this->mytype == 2) {
1603
            // we're adding to an array here
1604
            $ar = $this->me['array'];
1605
            $ar[] = new XML_RPC_Value($val, $type);
1606
            $this->me['array'] = $ar;
1607
        } else {
1608
            // a scalar, so set the value and remember we're scalar
1609
            $this->me[$type] = $val;
1610
            $this->mytype = $typeof;
1611
        }
1612
        return 1;
1613
    }
1614

    
1615
    /**
1616
     * @return int  returns 1 if successful or 0 if there are problems
1617
     */
1618
    function addArray($vals)
1619
    {
1620
        if ($this->mytype != 0) {
1621
            $this->raiseError(
1622
                    sprintf(gettext('Already initialized as a [%s]'), $this->kindOf()),
1623
                    XML_RPC_ERROR_ALREADY_INITIALIZED);
1624
            return 0;
1625
        }
1626
        $this->mytype = $GLOBALS['XML_RPC_Types']['array'];
1627
        $this->me['array'] = $vals;
1628
        return 1;
1629
    }
1630

    
1631
    /**
1632
     * @return int  returns 1 if successful or 0 if there are problems
1633
     */
1634
    function addStruct($vals)
1635
    {
1636
        if ($this->mytype != 0) {
1637
            $this->raiseError(
1638
                    sprintf(gettext('Already initialized as a [%s]'), $this->kindOf()),
1639
                    XML_RPC_ERROR_ALREADY_INITIALIZED);
1640
            return 0;
1641
        }
1642
        $this->mytype = $GLOBALS['XML_RPC_Types']['struct'];
1643
        $this->me['struct'] = $vals;
1644
        return 1;
1645
    }
1646

    
1647
    /**
1648
     * @return void
1649
     */
1650
    function dump($ar)
1651
    {
1652
        reset($ar);
1653
        foreach ($ar as $key => $val) {
1654
            echo "$key => $val<br />";
1655
            if ($key == 'array') {
1656
                foreach ($val as $key2 => $val2) {
1657
                    echo "-- $key2 => $val2<br />";
1658
                }
1659
            }
1660
        }
1661
    }
1662

    
1663
    /**
1664
     * @return string  the data type of the current value
1665
     */
1666
    function kindOf()
1667
    {
1668
        switch ($this->mytype) {
1669
        case 3:
1670
            return 'struct';
1671

    
1672
        case 2:
1673
            return 'array';
1674

    
1675
        case 1:
1676
            return 'scalar';
1677

    
1678
        default:
1679
            return 'undef';
1680
        }
1681
    }
1682

    
1683
    /**
1684
     * @return string  the data in XML format
1685
     */
1686
    function serializedata($typ, $val)
1687
    {
1688
        $rs = '';
1689
        if (!array_key_exists($typ, $GLOBALS['XML_RPC_Types'])) {
1690
            // XXX
1691
            // need some way to report this error
1692
            return;
1693
        }
1694
        switch ($GLOBALS['XML_RPC_Types'][$typ]) {
1695
        case 3:
1696
            // struct
1697
            $rs .= "<struct>\n";
1698
            reset($val);
1699
            foreach ($val as $key2 => $val2) {
1700
                $rs .= "<member><name>" . htmlspecialchars($key2) . "</name>\n";
1701
                $rs .= $this->serializeval($val2);
1702
                $rs .= "</member>\n";
1703
            }
1704
            $rs .= '</struct>';
1705
            break;
1706

    
1707
        case 2:
1708
            // array
1709
            $rs .= "<array>\n<data>\n";
1710
            foreach ($val as $value) {
1711
                $rs .= $this->serializeval($value);
1712
            }
1713
            $rs .= "</data>\n</array>";
1714
            break;
1715

    
1716
        case 1:
1717
            switch ($typ) {
1718
            case $GLOBALS['XML_RPC_Base64']:
1719
                $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
1720
                break;
1721
            case $GLOBALS['XML_RPC_Boolean']:
1722
                $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
1723
                break;
1724
            case $GLOBALS['XML_RPC_String']:
1725
                $rs .= "<${typ}>" . htmlspecialchars($val). "</${typ}>";
1726
                break;
1727
            default:
1728
                $rs .= "<${typ}>${val}</${typ}>";
1729
            }
1730
        }
1731
        return $rs;
1732
    }
1733

    
1734
    /**
1735
     * @return string  the data in XML format
1736
     */
1737
    function serialize()
1738
    {
1739
        return $this->serializeval($this);
1740
    }
1741

    
1742
    /**
1743
     * @return string  the data in XML format
1744
     */
1745
    function serializeval($o)
1746
    {
1747
        if (!is_object($o) || empty($o->me) || !is_array($o->me)) {
1748
            return '';
1749
        }
1750
        $ar = $o->me;
1751
        reset($ar);
1752
        list($typ, $val) = each($ar);
1753
        return '<value>' .  $this->serializedata($typ, $val) .  "</value>\n";
1754
    }
1755

    
1756
    /**
1757
     * @return mixed  the contents of the element requested
1758
     */
1759
    function structmem($m)
1760
    {
1761
        return $this->me['struct'][$m];
1762
    }
1763

    
1764
    /**
1765
     * @return void
1766
     */
1767
    function structreset()
1768
    {
1769
        reset($this->me['struct']);
1770
    }
1771

    
1772
    /**
1773
     * @return  the key/value pair of the struct's current element
1774
     */
1775
    function structeach()
1776
    {
1777
        return each($this->me['struct']);
1778
    }
1779

    
1780
    /**
1781
     * @return mixed  the current value
1782
     */
1783
    function getval()
1784
    {
1785
        // UNSTABLE
1786

    
1787
        reset($this->me);
1788
        $b = current($this->me);
1789

    
1790
        // contributed by I Sofer, 2001-03-24
1791
        // add support for nested arrays to scalarval
1792
        // i've created a new method here, so as to
1793
        // preserve back compatibility
1794

    
1795
        if (is_array($b)) {
1796
            foreach ($b as $id => $cont) {
1797
                $b[$id] = $cont->scalarval();
1798
            }
1799
        }
1800

    
1801
        // add support for structures directly encoding php objects
1802
        if (is_object($b)) {
1803
            $t = get_object_vars($b);
1804
            foreach ($t as $id => $cont) {
1805
                $t[$id] = $cont->scalarval();
1806
            }
1807
            foreach ($t as $id => $cont) {
1808
                $b->$id = $cont;
1809
            }
1810
        }
1811

    
1812
        // end contrib
1813
        return $b;
1814
    }
1815

    
1816
    /**
1817
     * @return mixed  the current element's scalar value.  If the value is
1818
     *                 not scalar, FALSE is returned.
1819
     */
1820
    function scalarval()
1821
    {
1822
        reset($this->me);
1823
        $v = current($this->me);
1824
        if (!is_scalar($v)) {
1825
            $v = false;
1826
        }
1827
        return $v;
1828
    }
1829

    
1830
    /**
1831
     * @return string
1832
     */
1833
    function scalartyp()
1834
    {
1835
        reset($this->me);
1836
        $a = key($this->me);
1837
        if ($a == $GLOBALS['XML_RPC_I4']) {
1838
            $a = $GLOBALS['XML_RPC_Int'];
1839
        }
1840
        return $a;
1841
    }
1842

    
1843
    /**
1844
     * @return mixed  the struct's current element
1845
     */
1846
    function arraymem($m)
1847
    {
1848
        return $this->me['array'][$m];
1849
    }
1850

    
1851
    /**
1852
     * @return int  the number of elements in the array
1853
     */
1854
    function arraysize()
1855
    {
1856
        reset($this->me);
1857
        list($a, $b) = each($this->me);
1858
        return sizeof($b);
1859
    }
1860

    
1861
    /**
1862
     * Determines if the item submitted is an XML_RPC_Value object
1863
     *
1864
     * @param mixed $val  the variable to be evaluated
1865
     *
1866
     * @return bool  TRUE if the item is an XML_RPC_Value object
1867
     *
1868
     * @static
1869
     * @since Method available since Release 1.3.0
1870
     */
1871
    function isValue($val)
1872
    {
1873
        return (strtolower(get_class($val)) == 'xml_rpc_value');
1874
    }
1875
}
1876

    
1877
/**
1878
 * Return an ISO8601 encoded string
1879
 *
1880
 * While timezones ought to be supported, the XML-RPC spec says:
1881
 *
1882
 * "Don't assume a timezone. It should be specified by the server in its
1883
 * documentation what assumptions it makes about timezones."
1884
 *
1885
 * This routine always assumes localtime unless $utc is set to 1, in which
1886
 * case UTC is assumed and an adjustment for locale is made when encoding.
1887
 *
1888
 * @return string  the formatted date
1889
 */
1890
function XML_RPC_iso8601_encode($timet, $utc = 0)
1891
{
1892
    if (!$utc) {
1893
        $t = strftime('%Y%m%dT%H:%M:%S', $timet);
1894
    } else {
1895
        if (function_exists('gmstrftime')) {
1896
            // gmstrftime doesn't exist in some versions
1897
            // of PHP
1898
            $t = gmstrftime('%Y%m%dT%H:%M:%S', $timet);
1899
        } else {
1900
            $t = strftime('%Y%m%dT%H:%M:%S', $timet - date('Z'));
1901
        }
1902
    }
1903
    return $t;
1904
}
1905

    
1906
/**
1907
 * Convert a datetime string into a Unix timestamp
1908
 *
1909
 * While timezones ought to be supported, the XML-RPC spec says:
1910
 *
1911
 * "Don't assume a timezone. It should be specified by the server in its
1912
 * documentation what assumptions it makes about timezones."
1913
 *
1914
 * This routine always assumes localtime unless $utc is set to 1, in which
1915
 * case UTC is assumed and an adjustment for locale is made when encoding.
1916
 *
1917
 * @return int  the unix timestamp of the date submitted
1918
 */
1919
function XML_RPC_iso8601_decode($idate, $utc = 0)
1920
{
1921
    $t = 0;
1922
    if (preg_match('@([0-9]{4})([0-9]{2})([0-9]{2})T([0-9]{2}):([0-9]{2}):([0-9]{2})@', $idate, $regs)) {
1923
        if ($utc) {
1924
            $t = gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
1925
        } else {
1926
            $t = mktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
1927
        }
1928
    }
1929
    return $t;
1930
}
1931

    
1932
/**
1933
 * Converts an XML_RPC_Value object into native PHP types
1934
 *
1935
 * @param object $XML_RPC_val  the XML_RPC_Value object to decode
1936
 *
1937
 * @return mixed  the PHP values
1938
 */
1939
function XML_RPC_decode($XML_RPC_val)
1940
{
1941
    $kind = $XML_RPC_val->kindOf();
1942

    
1943
    if ($kind == 'scalar') {
1944
        return $XML_RPC_val->scalarval();
1945

    
1946
    } elseif ($kind == 'array') {
1947
        $size = $XML_RPC_val->arraysize();
1948
        $arr = array();
1949
        for ($i = 0; $i < $size; $i++) {
1950
            $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i));
1951
        }
1952
        return $arr;
1953

    
1954
    } elseif ($kind == 'struct') {
1955
        $XML_RPC_val->structreset();
1956
        $arr = array();
1957
        while (list($key, $value) = $XML_RPC_val->structeach()) {
1958
            $arr[$key] = XML_RPC_decode($value);
1959
        }
1960
        return $arr;
1961
    }
1962
}
1963

    
1964
/**
1965
 * Converts native PHP types into an XML_RPC_Value object
1966
 *
1967
 * @param mixed $php_val  the PHP value or variable you want encoded
1968
 *
1969
 * @return object  the XML_RPC_Value object
1970
 */
1971
function XML_RPC_encode($php_val)
1972
{
1973
    $type = gettype($php_val);
1974
    $XML_RPC_val = new XML_RPC_Value;
1975

    
1976
    switch ($type) {
1977
    case 'array':
1978
        if (empty($php_val)) {
1979
            $XML_RPC_val->addArray($php_val);
1980
            break;
1981
        }
1982
        $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
1983
        if (empty($tmp)) {
1984
           $arr = array();
1985
           foreach ($php_val as $k => $v) {
1986
               $arr[$k] = XML_RPC_encode($v);
1987
           }
1988
           $XML_RPC_val->addArray($arr);
1989
           break;
1990
        }
1991
        // fall though if it's not an enumerated array
1992

    
1993
    case 'object':
1994
        $arr = array();
1995
        foreach ($php_val as $k => $v) {
1996
            $arr[$k] = XML_RPC_encode($v);
1997
        }
1998
        $XML_RPC_val->addStruct($arr);
1999
        break;
2000

    
2001
    case 'integer':
2002
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Int']);
2003
        break;
2004

    
2005
    case 'double':
2006
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Double']);
2007
        break;
2008

    
2009
    case 'string':
2010
    case 'NULL':
2011
        if (preg_match('@^[0-9]{8}\T{1}[0-9]{2}\:[0-9]{2}\:[0-9]{2}$@', $php_val)) {
2012
            $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_DateTime']);
2013
        } elseif ($GLOBALS['XML_RPC_auto_base64']
2014
                  && preg_match("@[^ -~\t\r\n]@", $php_val))
2015
        {
2016
            // Characters other than alpha-numeric, punctuation, SP, TAB,
2017
            // LF and CR break the XML parser, encode value via Base 64.
2018
            $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Base64']);
2019
        } else {
2020
            $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_String']);
2021
        }
2022
        break;
2023

    
2024
    case 'boolean':
2025
        // Add support for encoding/decoding of booleans, since they
2026
        // are supported in PHP
2027
        // by <G_Giunta_2001-02-29>
2028
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Boolean']);
2029
        break;
2030

    
2031
    case 'unknown type':
2032
    default:
2033
        $XML_RPC_val = false;
2034
    }
2035
    return $XML_RPC_val;
2036
}
2037

    
2038
/*
2039
 * Local variables:
2040
 * tab-width: 4
2041
 * c-basic-offset: 4
2042
 * c-hanging-comment-ender-p: nil
2043
 * End:
2044
 */
2045

    
2046
?>
(64-64/65)