Project

General

Profile

Download (58.2 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 = 'http://';
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 = 'http://';
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
                if ($port) {
743
                    $this->port = $port;
744
                }
745
            }
746
        } elseif ($match[1] == 'http://') {
747
            $this->server = $match[2];
748
            if ($port) {
749
                $this->port = $port;
750
            }
751
        } else {
752
            $this->server   = $match[2];
753
            $this->protocol = 'ssl://';
754
            if ($port) {
755
                $this->port = $port;
756
            } else {
757
                $this->port = 443;
758
            }
759
        }
760

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

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

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

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

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

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

    
899
        // Only create the payload if it was not created previously
900
        if (empty($msg->payload)) {
901
            $msg->createPayload();
902
        }
903
        $this->createHeaders($msg);
904

    
905
        $op  = $this->headers . "\r\n\r\n";
906
        $op .= $msg->payload;
907

    
908
        if ($this->debug) {
909
            print "\n<pre>---SENT---\n";
910
            print $op;
911
            print "\n---END---</pre>\n";
912
        }
913

    
914
        $ctx_options = array();
915

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

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

    
929
        $ctx = stream_context_create($ctx_options);
930

    
931
        $fp = stream_socket_client("{$this->protocol}{$server}:{$port}",
932
            $this->errno, $this->errstr,
933
            ($timeout > 0 ? $timeout : ini_get("default_socket_timeout")),
934
            STREAM_CLIENT_CONNECT, $ctx);
935

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

    
954
        if (!fputs($fp, $op, strlen($op))) {
955
            $this->errstr = 'Write error';
956
            return 0;
957
        }
958
        $resp = $msg->parseResponseFile($fp);
959

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

    
968
        fclose($fp);
969
        return $resp;
970
    }
971

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

    
996
        $this->headers .= "User-Agent: PEAR XML_RPC\r\n";
997
        $this->headers .= 'Host: ' . $this->server . "\r\n";
998

    
999
        if ($this->proxy && $this->proxy_user) {
1000
            $this->headers .= 'Proxy-Authorization: Basic '
1001
                     . base64_encode("$this->proxy_user:$this->proxy_pass")
1002
                     . "\r\n";
1003
        }
1004

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

    
1012
        $this->headers .= "Content-Type: text/xml\r\n";
1013
        $this->headers .= 'Content-Length: ' . strlen($msg->payload);
1014
        return true;
1015
    }
1016
}
1017

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

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

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

    
1064
    /**
1065
     * @return string  the error string
1066
     */
1067
    function faultString()
1068
    {
1069
        return $this->fs;
1070
    }
1071

    
1072
    /**
1073
     * @return mixed  the value
1074
     */
1075
    function value()
1076
    {
1077
        return $this->xv;
1078
    }
1079

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

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

    
1135
    /**
1136
     * The current debug mode (1 = on, 0 = off)
1137
     * @var integer
1138
     */
1139
    var $debug = 0;
1140

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

    
1152
    /**
1153
     * The method presently being evaluated
1154
     * @var string
1155
     */
1156
    var $methodname = '';
1157

    
1158
    /**
1159
     * @var array
1160
     */
1161
    var $params = array();
1162

    
1163
    /**
1164
     * The XML message being generated
1165
     * @var string
1166
     */
1167
    var $payload = '';
1168

    
1169
    /**
1170
     * Should extra line breaks be removed from the payload?
1171
     * @since Property available since Release 1.4.6
1172
     * @var boolean
1173
     */
1174
    var $remove_extra_lines = true;
1175

    
1176
    /**
1177
     * The XML response from the remote server
1178
     * @since Property available since Release 1.4.6
1179
     * @var string
1180
     */
1181
    var $response_payload = '';
1182

    
1183

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

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

    
1213
        if (!$this->send_encoding) {
1214
            $this->send_encoding = $XML_RPC_defencoding;
1215
        }
1216
        return '<?xml version="1.0" encoding="' . $this->send_encoding . '"?>'
1217
               . "\n<methodCall>\n";
1218
    }
1219

    
1220
    /**
1221
     * @return string  the closing </methodCall> tag
1222
     */
1223
    function xml_footer()
1224
    {
1225
        return "</methodCall>\n";
1226
    }
1227

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

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

    
1278
    /**
1279
     * @return string  the payload
1280
     */
1281
    function serialize()
1282
    {
1283
        $this->createPayload();
1284
        return $this->payload;
1285
    }
1286

    
1287
    /**
1288
     * @return void
1289
     */
1290
    function addParam($par)
1291
    {
1292
        $this->params[] = $par;
1293
    }
1294

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

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

    
1319
    /**
1320
     * @return int  the number of parameters
1321
     */
1322
    function getNumParams()
1323
    {
1324
        return sizeof($this->params);
1325
    }
1326

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

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

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

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

    
1393
                default:
1394
                    return $XML_RPC_defencoding;
1395
            }
1396
        } else {
1397
            return $XML_RPC_defencoding;
1398
        }
1399
    }
1400

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

    
1413
    /**
1414
     * @return object  a new XML_RPC_Response object
1415
     */
1416
    function parseResponse($data = '')
1417
    {
1418
        global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding;
1419

    
1420
        $encoding = $this->getEncoding($data);
1421
        $parser_resource = xml_parser_create($encoding);
1422
        $parser = (int) $parser_resource;
1423

    
1424
        $XML_RPC_xh = array();
1425
        $XML_RPC_xh[$parser] = array();
1426

    
1427
        $XML_RPC_xh[$parser]['cm'] = 0;
1428
        $XML_RPC_xh[$parser]['isf'] = 0;
1429
        $XML_RPC_xh[$parser]['ac'] = '';
1430
        $XML_RPC_xh[$parser]['qt'] = '';
1431
        $XML_RPC_xh[$parser]['stack'] = array();
1432
        $XML_RPC_xh[$parser]['valuestack'] = array();
1433

    
1434
        xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
1435
        xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
1436
        xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
1437

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

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

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

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

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

    
1493
        xml_parser_free($parser_resource);
1494

    
1495
        if ($this->debug) {
1496
            print "\n<pre>---PARSED---\n";
1497
            var_dump($XML_RPC_xh[$parser]['value']);
1498
            print "---END---</pre>\n";
1499
        }
1500

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

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

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

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

    
1587
        if ($type == $GLOBALS['XML_RPC_Boolean']) {
1588
            if (strcasecmp($val, 'true') == 0
1589
                || $val == 1
1590
                || ($val == true && strcasecmp($val, 'false')))
1591
            {
1592
                $val = 1;
1593
            } else {
1594
                $val = 0;
1595
            }
1596
        }
1597

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

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

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

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

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

    
1668
        case 2:
1669
            return 'array';
1670

    
1671
        case 1:
1672
            return 'scalar';
1673

    
1674
        default:
1675
            return 'undef';
1676
        }
1677
    }
1678

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

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

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

    
1730
    /**
1731
     * @return string  the data in XML format
1732
     */
1733
    function serialize()
1734
    {
1735
        return $this->serializeval($this);
1736
    }
1737

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

    
1752
    /**
1753
     * @return mixed  the contents of the element requested
1754
     */
1755
    function structmem($m)
1756
    {
1757
        return $this->me['struct'][$m];
1758
    }
1759

    
1760
    /**
1761
     * @return void
1762
     */
1763
    function structreset()
1764
    {
1765
        reset($this->me['struct']);
1766
    }
1767

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

    
1776
    /**
1777
     * @return mixed  the current value
1778
     */
1779
    function getval()
1780
    {
1781
        // UNSTABLE
1782

    
1783
        reset($this->me);
1784
        $b = current($this->me);
1785

    
1786
        // contributed by I Sofer, 2001-03-24
1787
        // add support for nested arrays to scalarval
1788
        // i've created a new method here, so as to
1789
        // preserve back compatibility
1790

    
1791
        if (is_array($b)) {
1792
            foreach ($b as $id => $cont) {
1793
                $b[$id] = $cont->scalarval();
1794
            }
1795
        }
1796

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

    
1808
        // end contrib
1809
        return $b;
1810
    }
1811

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

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

    
1839
    /**
1840
     * @return mixed  the struct's current element
1841
     */
1842
    function arraymem($m)
1843
    {
1844
        return $this->me['array'][$m];
1845
    }
1846

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

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

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

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

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

    
1939
    if ($kind == 'scalar') {
1940
        return $XML_RPC_val->scalarval();
1941

    
1942
    } elseif ($kind == 'array') {
1943
        $size = $XML_RPC_val->arraysize();
1944
        $arr = array();
1945
        for ($i = 0; $i < $size; $i++) {
1946
            $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i));
1947
        }
1948
        return $arr;
1949

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

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

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

    
1989
    case 'object':
1990
        $arr = array();
1991
        foreach ($php_val as $k => $v) {
1992
            $arr[$k] = XML_RPC_encode($v);
1993
        }
1994
        $XML_RPC_val->addStruct($arr);
1995
        break;
1996

    
1997
    case 'integer':
1998
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Int']);
1999
        break;
2000

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

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

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

    
2027
    case 'unknown type':
2028
    default:
2029
        $XML_RPC_val = false;
2030
    }
2031
    return $XML_RPC_val;
2032
}
2033

    
2034
/*
2035
 * Local variables:
2036
 * tab-width: 4
2037
 * c-basic-offset: 4
2038
 * c-hanging-comment-ender-p: nil
2039
 * End:
2040
 */
2041

    
2042
?>
(64-64/65)