Project

General

Profile

Download (58.7 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
            return PEAR::raiseError(get_class($this) . ': ' . $msg, $code);
563
        } else {
564
            return PEAR::raiseError('XML_RPC: ' . $msg, $code);
565
        }
566
    }
567

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

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

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

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

    
611
    /**
612
     * The protocol to use in contacting the remote server
613
     * @var string
614
     */
615
    var $protocol = 'http://';
616

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

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

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

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

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

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

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

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

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

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

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

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

    
699

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

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

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

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

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

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

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

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

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

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

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

    
912
        /*
913
         * If we're using a proxy open a socket to the proxy server
914
         * instead to the xml-rpc server
915
         */
916
        if ($this->proxy) {
917
            if ($this->proxy_protocol == 'http://') {
918
                $protocol = '';
919
            } else {
920
                $protocol = $this->proxy_protocol;
921
            }
922
            if ($timeout > 0) {
923
                $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port,
924
                                 $this->errno, $this->errstr, $timeout);
925
            } else {
926
                $fp = @fsockopen($protocol . $this->proxy, $this->proxy_port,
927
                                 $this->errno, $this->errstr);
928
            }
929
        } else {
930
            if ($this->protocol == 'http://') {
931
                $protocol = '';
932
            } else {
933
                $protocol = $this->protocol;
934
            }
935
            if ($timeout > 0) {
936
                $fp = @fsockopen($protocol . $server, $port,
937
                                 $this->errno, $this->errstr, $timeout);
938
            } else {
939
                $fp = @fsockopen($protocol . $server, $port,
940
                                 $this->errno, $this->errstr);
941
            }
942
        }
943

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

    
962
        if ($timeout) {
963
            /*
964
             * Using socket_set_timeout() because stream_set_timeout()
965
             * was introduced in 4.3.0, but we need to support 4.2.0.
966
             */
967
            socket_set_timeout($fp, $timeout);
968
        }
969

    
970
        if (!fputs($fp, $op, strlen($op))) {
971
            $this->errstr = 'Write error';
972
            return 0;
973
        }
974
        $resp = $msg->parseResponseFile($fp);
975

    
976
        $meta = socket_get_status($fp);
977
        if ($meta['timed_out']) {
978
            fclose($fp);
979
            $this->errstr = 'RPC server did not send response before timeout.';
980
            $this->raiseError($this->errstr, XML_RPC_ERROR_CONNECTION_FAILED);
981
            return 0;
982
        }
983

    
984
        fclose($fp);
985
        return $resp;
986
    }
987

    
988
    /**
989
     * Determines the HTTP headers and puts it in the $headers property
990
     *
991
     * @param object $msg       the XML_RPC_Message object
992
     *
993
     * @return boolean  TRUE if okay, FALSE if the message payload isn't set.
994
     *
995
     * @access protected
996
     */
997
    function createHeaders($msg)
998
    {
999
        if (empty($msg->payload)) {
1000
            return false;
1001
        }
1002
        if ($this->proxy) {
1003
            $this->headers = 'POST ' . $this->protocol . $this->server;
1004
            if ($this->proxy_port) {
1005
                $this->headers .= ':' . $this->port;
1006
            }
1007
        } else {
1008
           $this->headers = 'POST ';
1009
        }
1010
        $this->headers .= $this->path. " HTTP/1.0\r\n";
1011

    
1012
        $this->headers .= "User-Agent: PEAR XML_RPC\r\n";
1013
        $this->headers .= 'Host: ' . $this->server . "\r\n";
1014

    
1015
        if ($this->proxy && $this->proxy_user) {
1016
            $this->headers .= 'Proxy-Authorization: Basic '
1017
                     . base64_encode("$this->proxy_user:$this->proxy_pass")
1018
                     . "\r\n";
1019
        }
1020

    
1021
        // thanks to Grant Rauscher <grant7@firstworld.net> for this
1022
        if ($this->username) {
1023
            $this->headers .= 'Authorization: Basic '
1024
                     . base64_encode("$this->username:$this->password")
1025
                     . "\r\n";
1026
        }
1027

    
1028
        $this->headers .= "Content-Type: text/xml\r\n";
1029
        $this->headers .= 'Content-Length: ' . strlen($msg->payload);
1030
        return true;
1031
    }
1032
}
1033

    
1034
/**
1035
 * The methods and properties for interpreting responses to XML RPC requests
1036
 *
1037
 * @category   Web Services
1038
 * @package    XML_RPC
1039
 * @author     Edd Dumbill <edd@usefulinc.com>
1040
 * @author     Stig Bakken <stig@php.net>
1041
 * @author     Martin Jansen <mj@php.net>
1042
 * @author     Daniel Convissor <danielc@php.net>
1043
 * @copyright  1999-2001 Edd Dumbill, 2001-2010 The PHP Group
1044
 * @license    http://www.php.net/license/3_01.txt  PHP License
1045
 * @version    Release: @package_version@
1046
 * @link       http://pear.php.net/package/XML_RPC
1047
 */
1048
class XML_RPC_Response extends XML_RPC_Base
1049
{
1050
    var $xv;
1051
    var $fn;
1052
    var $fs;
1053
    var $hdrs;
1054

    
1055
    /**
1056
     * @return void
1057
     */
1058
    function XML_RPC_Response($val, $fcode = 0, $fstr = '')
1059
    {
1060
        if ($fcode != 0) {
1061
            $this->fn = $fcode;
1062
            $this->fs = htmlspecialchars($fstr);
1063
        } else {
1064
            $this->xv = $val;
1065
        }
1066
    }
1067

    
1068
    /**
1069
     * @return int  the error code
1070
     */
1071
    function faultCode()
1072
    {
1073
        if (isset($this->fn)) {
1074
            return $this->fn;
1075
        } else {
1076
            return 0;
1077
        }
1078
    }
1079

    
1080
    /**
1081
     * @return string  the error string
1082
     */
1083
    function faultString()
1084
    {
1085
        return $this->fs;
1086
    }
1087

    
1088
    /**
1089
     * @return mixed  the value
1090
     */
1091
    function value()
1092
    {
1093
        return $this->xv;
1094
    }
1095

    
1096
    /**
1097
     * @return string  the error message in XML format
1098
     */
1099
    function serialize()
1100
    {
1101
        $rs = "<methodResponse>\n";
1102
        if ($this->fn) {
1103
            $rs .= "<fault>
1104
  <value>
1105
    <struct>
1106
      <member>
1107
        <name>faultCode</name>
1108
        <value><int>" . $this->fn . "</int></value>
1109
      </member>
1110
      <member>
1111
        <name>faultString</name>
1112
        <value><string>" . $this->fs . "</string></value>
1113
      </member>
1114
    </struct>
1115
  </value>
1116
</fault>";
1117
        } else {
1118
            $rs .= "<params>\n<param>\n" . $this->xv->serialize() .
1119
        "</param>\n</params>";
1120
        }
1121
        $rs .= "\n</methodResponse>";
1122
        return $rs;
1123
    }
1124
}
1125

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

    
1151
    /**
1152
     * The current debug mode (1 = on, 0 = off)
1153
     * @var integer
1154
     */
1155
    var $debug = 0;
1156

    
1157
    /**
1158
     * The encoding to be used for outgoing messages
1159
     *
1160
     * Defaults to the value of <var>$GLOBALS['XML_RPC_defencoding']</var>
1161
     *
1162
     * @var string
1163
     * @see XML_RPC_Message::setSendEncoding(),
1164
     *      $GLOBALS['XML_RPC_defencoding'], XML_RPC_Message::xml_header()
1165
     */
1166
    var $send_encoding = '';
1167

    
1168
    /**
1169
     * The method presently being evaluated
1170
     * @var string
1171
     */
1172
    var $methodname = '';
1173

    
1174
    /**
1175
     * @var array
1176
     */
1177
    var $params = array();
1178

    
1179
    /**
1180
     * The XML message being generated
1181
     * @var string
1182
     */
1183
    var $payload = '';
1184

    
1185
    /**
1186
     * Should extra line breaks be removed from the payload?
1187
     * @since Property available since Release 1.4.6
1188
     * @var boolean
1189
     */
1190
    var $remove_extra_lines = true;
1191

    
1192
    /**
1193
     * The XML response from the remote server
1194
     * @since Property available since Release 1.4.6
1195
     * @var string
1196
     */
1197
    var $response_payload = '';
1198

    
1199

    
1200
    /**
1201
     * @return void
1202
     */
1203
    function XML_RPC_Message($meth, $pars = 0)
1204
    {
1205
        $this->methodname = $meth;
1206
        if (is_array($pars) && sizeof($pars) > 0) {
1207
            for ($i = 0; $i < sizeof($pars); $i++) {
1208
                $this->addParam($pars[$i]);
1209
            }
1210
        }
1211
    }
1212

    
1213
    /**
1214
     * Produces the XML declaration including the encoding attribute
1215
     *
1216
     * The encoding is determined by this class' <var>$send_encoding</var>
1217
     * property.  If the <var>$send_encoding</var> property is not set, use
1218
     * <var>$GLOBALS['XML_RPC_defencoding']</var>.
1219
     *
1220
     * @return string  the XML declaration and <methodCall> element
1221
     *
1222
     * @see XML_RPC_Message::setSendEncoding(),
1223
     *      XML_RPC_Message::$send_encoding, $GLOBALS['XML_RPC_defencoding']
1224
     */
1225
    function xml_header()
1226
    {
1227
        global $XML_RPC_defencoding;
1228

    
1229
        if (!$this->send_encoding) {
1230
            $this->send_encoding = $XML_RPC_defencoding;
1231
        }
1232
        return '<?xml version="1.0" encoding="' . $this->send_encoding . '"?>'
1233
               . "\n<methodCall>\n";
1234
    }
1235

    
1236
    /**
1237
     * @return string  the closing </methodCall> tag
1238
     */
1239
    function xml_footer()
1240
    {
1241
        return "</methodCall>\n";
1242
    }
1243

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

    
1283
    /**
1284
     * @return string  the name of the method
1285
     */
1286
    function method($meth = '')
1287
    {
1288
        if ($meth != '') {
1289
            $this->methodname = $meth;
1290
        }
1291
        return $this->methodname;
1292
    }
1293

    
1294
    /**
1295
     * @return string  the payload
1296
     */
1297
    function serialize()
1298
    {
1299
        $this->createPayload();
1300
        return $this->payload;
1301
    }
1302

    
1303
    /**
1304
     * @return void
1305
     */
1306
    function addParam($par)
1307
    {
1308
        $this->params[] = $par;
1309
    }
1310

    
1311
    /**
1312
     * Obtains an XML_RPC_Value object for the given parameter
1313
     *
1314
     * @param int $i  the index number of the parameter to obtain
1315
     *
1316
     * @return object  the XML_RPC_Value object.
1317
     *                  If the parameter doesn't exist, an XML_RPC_Response object.
1318
     *
1319
     * @since Returns XML_RPC_Response object on error since Release 1.3.0
1320
     */
1321
    function getParam($i)
1322
    {
1323
        global $XML_RPC_err, $XML_RPC_str;
1324

    
1325
        if (isset($this->params[$i])) {
1326
            return $this->params[$i];
1327
        } else {
1328
            $this->raiseError(gettext('The submitted request did not contain this parameter'),
1329
                              XML_RPC_ERROR_INCORRECT_PARAMS);
1330
            return new XML_RPC_Response(0, $XML_RPC_err['incorrect_params'],
1331
                                        $XML_RPC_str['incorrect_params']);
1332
        }
1333
    }
1334

    
1335
    /**
1336
     * @return int  the number of parameters
1337
     */
1338
    function getNumParams()
1339
    {
1340
        return sizeof($this->params);
1341
    }
1342

    
1343
    /**
1344
     * Sets whether the payload's content gets passed through
1345
     * mb_convert_encoding()
1346
     *
1347
     * Returns PEAR_ERROR object if mb_convert_encoding() isn't available.
1348
     *
1349
     * @param int $in  where 1 = on, 0 = off
1350
     *
1351
     * @return void
1352
     *
1353
     * @see XML_RPC_Message::setSendEncoding()
1354
     * @since Method available since Release 1.5.1
1355
     */
1356
    function setConvertPayloadEncoding($in)
1357
    {
1358
        if ($in && !function_exists('mb_convert_encoding')) {
1359
            return $this->raiseError(gettext('mb_convert_encoding() is not available'),
1360
                              XML_RPC_ERROR_PROGRAMMING);
1361
        }
1362
        $this->convert_payload_encoding = $in;
1363
    }
1364

    
1365
    /**
1366
     * Sets the XML declaration's encoding attribute
1367
     *
1368
     * @param string $type  the encoding type (ISO-8859-1, UTF-8 or US-ASCII)
1369
     *
1370
     * @return void
1371
     *
1372
     * @see XML_RPC_Message::setConvertPayloadEncoding(), XML_RPC_Message::xml_header()
1373
     * @since Method available since Release 1.2.0
1374
     */
1375
    function setSendEncoding($type)
1376
    {
1377
        $this->send_encoding = $type;
1378
    }
1379

    
1380
    /**
1381
     * Determine the XML's encoding via the encoding attribute
1382
     * in the XML declaration
1383
     *
1384
     * If the encoding parameter is not set or is not ISO-8859-1, UTF-8
1385
     * or US-ASCII, $XML_RPC_defencoding will be returned.
1386
     *
1387
     * @param string $data  the XML that will be parsed
1388
     *
1389
     * @return string  the encoding to be used
1390
     *
1391
     * @link   http://php.net/xml_parser_create
1392
     * @since  Method available since Release 1.2.0
1393
     */
1394
    function getEncoding($data)
1395
    {
1396
        global $XML_RPC_defencoding;
1397

    
1398
        if (preg_match('@<\?xml[^>]*\s*encoding\s*=\s*[\'"]([^"\']*)[\'"]@',
1399
                       $data, $match))
1400
        {
1401
            $match[1] = trim(strtoupper($match[1]));
1402
            switch ($match[1]) {
1403
                case 'ISO-8859-1':
1404
                case 'UTF-8':
1405
                case 'US-ASCII':
1406
                    return $match[1];
1407
                    break;
1408

    
1409
                default:
1410
                    return $XML_RPC_defencoding;
1411
            }
1412
        } else {
1413
            return $XML_RPC_defencoding;
1414
        }
1415
    }
1416

    
1417
    /**
1418
     * @return object  a new XML_RPC_Response object
1419
     */
1420
    function parseResponseFile($fp)
1421
    {
1422
        $ipd = '';
1423
        while ($data = @fread($fp, 8192)) {
1424
            $ipd .= $data;
1425
        }
1426
        return $this->parseResponse($ipd);
1427
    }
1428

    
1429
    /**
1430
     * @return object  a new XML_RPC_Response object
1431
     */
1432
    function parseResponse($data = '')
1433
    {
1434
        global $XML_RPC_xh, $XML_RPC_err, $XML_RPC_str, $XML_RPC_defencoding;
1435

    
1436
        $encoding = $this->getEncoding($data);
1437
        $parser_resource = xml_parser_create($encoding);
1438
        $parser = (int) $parser_resource;
1439

    
1440
        $XML_RPC_xh = array();
1441
        $XML_RPC_xh[$parser] = array();
1442

    
1443
        $XML_RPC_xh[$parser]['cm'] = 0;
1444
        $XML_RPC_xh[$parser]['isf'] = 0;
1445
        $XML_RPC_xh[$parser]['ac'] = '';
1446
        $XML_RPC_xh[$parser]['qt'] = '';
1447
        $XML_RPC_xh[$parser]['stack'] = array();
1448
        $XML_RPC_xh[$parser]['valuestack'] = array();
1449

    
1450
        xml_parser_set_option($parser_resource, XML_OPTION_CASE_FOLDING, true);
1451
        xml_set_element_handler($parser_resource, 'XML_RPC_se', 'XML_RPC_ee');
1452
        xml_set_character_data_handler($parser_resource, 'XML_RPC_cd');
1453

    
1454
        $hdrfnd = 0;
1455
        if ($this->debug) {
1456
            print "\n<pre>---GOT---\n";
1457
            print isset($_SERVER['SERVER_PROTOCOL']) ? htmlspecialchars($data) : $data;
1458
            print "\n---END---</pre>\n";
1459
        }
1460

    
1461
        // See if response is a 200 or a 100 then a 200, else raise error.
1462
        // But only do this if we're using the HTTP protocol.
1463
        if (preg_match('@^HTTP@', $data) &&
1464
            !preg_match('@^HTTP/[0-9\.]+ 200 @', $data) &&
1465
            !preg_match('@^HTTP/[0-9\.]+ 10[0-9]([A-Z ]+)?[\r\n]+HTTP/[0-9\.]+ 200@', $data))
1466
        {
1467
                $errstr = substr($data, 0, strpos($data, "\n") - 1);
1468
                error_log(sprintf(gettext("HTTP error, got response: %s"),$errstr));
1469
                $r = new XML_RPC_Response(0, $XML_RPC_err['http_error'],
1470
                                          $XML_RPC_str['http_error'] . ' (' .
1471
                                          $errstr . ')');
1472
                xml_parser_free($parser_resource);
1473
                return $r;
1474
        }
1475

    
1476
        // gotta get rid of headers here
1477
        if (!$hdrfnd && ($brpos = strpos($data,"\r\n\r\n"))) {
1478
            $XML_RPC_xh[$parser]['ha'] = substr($data, 0, $brpos);
1479
            $data = substr($data, $brpos + 4);
1480
            $hdrfnd = 1;
1481
        }
1482

    
1483
        /*
1484
         * be tolerant of junk after methodResponse
1485
         * (e.g. javascript automatically inserted by free hosts)
1486
         * thanks to Luca Mariano <luca.mariano@email.it>
1487
         */
1488
        $data = substr($data, 0, strpos($data, "</methodResponse>") + 17);
1489
        $this->response_payload = $data;
1490

    
1491
        if (!xml_parse($parser_resource, $data, sizeof($data))) {
1492
            // thanks to Peter Kocks <peter.kocks@baygate.com>
1493
            if (xml_get_current_line_number($parser_resource) == 1) {
1494
                $errstr = gettext("XML error at line 1, check URL");
1495
            } else {
1496
                $errstr = sprintf('XML error: %s at line %d',
1497
                                  xml_error_string(xml_get_error_code($parser_resource)),
1498
                                  xml_get_current_line_number($parser_resource));
1499
            }
1500
            error_log($errstr);
1501
            $r = new XML_RPC_Response(0, $XML_RPC_err['invalid_return'],
1502
                                      $XML_RPC_str['invalid_return']);
1503
            xml_parser_free($parser_resource);
1504
            return $r;
1505
        }
1506

    
1507
        xml_parser_free($parser_resource);
1508

    
1509
        if ($this->debug) {
1510
            print "\n<pre>---PARSED---\n";
1511
            var_dump($XML_RPC_xh[$parser]['value']);
1512
            print "---END---</pre>\n";
1513
        }
1514

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

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

    
1559
    /**
1560
     * @return void
1561
     */
1562
    function XML_RPC_Value($val = -1, $type = '')
1563
    {
1564
        $this->me = array();
1565
        $this->mytype = 0;
1566
        if ($val != -1 || $type != '') {
1567
            if ($type == '') {
1568
                $type = 'string';
1569
            }
1570
            if (!array_key_exists($type, $GLOBALS['XML_RPC_Types'])) {
1571
                // XXX
1572
                // need some way to report this error
1573
            } elseif ($GLOBALS['XML_RPC_Types'][$type] == 1) {
1574
                $this->addScalar($val, $type);
1575
            } elseif ($GLOBALS['XML_RPC_Types'][$type] == 2) {
1576
                $this->addArray($val);
1577
            } elseif ($GLOBALS['XML_RPC_Types'][$type] == 3) {
1578
                $this->addStruct($val);
1579
            }
1580
        }
1581
    }
1582

    
1583
    /**
1584
     * @return int  returns 1 if successful or 0 if there are problems
1585
     */
1586
    function addScalar($val, $type = 'string')
1587
    {
1588
        if ($this->mytype == 1) {
1589
            $this->raiseError(gettext('Scalar can have only one value'),
1590
                              XML_RPC_ERROR_INVALID_TYPE);
1591
            return 0;
1592
        }
1593
        $typeof = $GLOBALS['XML_RPC_Types'][$type];
1594
        if ($typeof != 1) {
1595
            $this->raiseError(
1596
                sprintf(gettext("Not a scalar type (%s)"), $typeof),
1597
                XML_RPC_ERROR_INVALID_TYPE);
1598
            return 0;
1599
        }
1600

    
1601
        if ($type == $GLOBALS['XML_RPC_Boolean']) {
1602
            if (strcasecmp($val, 'true') == 0
1603
                || $val == 1
1604
                || ($val == true && strcasecmp($val, 'false')))
1605
            {
1606
                $val = 1;
1607
            } else {
1608
                $val = 0;
1609
            }
1610
        }
1611

    
1612
        if ($this->mytype == 2) {
1613
            // we're adding to an array here
1614
            $ar = $this->me['array'];
1615
            $ar[] = new XML_RPC_Value($val, $type);
1616
            $this->me['array'] = $ar;
1617
        } else {
1618
            // a scalar, so set the value and remember we're scalar
1619
            $this->me[$type] = $val;
1620
            $this->mytype = $typeof;
1621
        }
1622
        return 1;
1623
    }
1624

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

    
1641
    /**
1642
     * @return int  returns 1 if successful or 0 if there are problems
1643
     */
1644
    function addStruct($vals)
1645
    {
1646
        if ($this->mytype != 0) {
1647
            $this->raiseError(
1648
                    sprintf(gettext('Already initialized as a [%s]'), $this->kindOf()),
1649
                    XML_RPC_ERROR_ALREADY_INITIALIZED);
1650
            return 0;
1651
        }
1652
        $this->mytype = $GLOBALS['XML_RPC_Types']['struct'];
1653
        $this->me['struct'] = $vals;
1654
        return 1;
1655
    }
1656

    
1657
    /**
1658
     * @return void
1659
     */
1660
    function dump($ar)
1661
    {
1662
        reset($ar);
1663
        foreach ($ar as $key => $val) {
1664
            echo "$key => $val<br />";
1665
            if ($key == 'array') {
1666
                foreach ($val as $key2 => $val2) {
1667
                    echo "-- $key2 => $val2<br />";
1668
                }
1669
            }
1670
        }
1671
    }
1672

    
1673
    /**
1674
     * @return string  the data type of the current value
1675
     */
1676
    function kindOf()
1677
    {
1678
        switch ($this->mytype) {
1679
        case 3:
1680
            return 'struct';
1681

    
1682
        case 2:
1683
            return 'array';
1684

    
1685
        case 1:
1686
            return 'scalar';
1687

    
1688
        default:
1689
            return 'undef';
1690
        }
1691
    }
1692

    
1693
    /**
1694
     * @return string  the data in XML format
1695
     */
1696
    function serializedata($typ, $val)
1697
    {
1698
        $rs = '';
1699
        if (!array_key_exists($typ, $GLOBALS['XML_RPC_Types'])) {
1700
            // XXX
1701
            // need some way to report this error
1702
            return;
1703
        }
1704
        switch ($GLOBALS['XML_RPC_Types'][$typ]) {
1705
        case 3:
1706
            // struct
1707
            $rs .= "<struct>\n";
1708
            reset($val);
1709
            foreach ($val as $key2 => $val2) {
1710
                $rs .= "<member><name>" . htmlspecialchars($key2) . "</name>\n";
1711
                $rs .= $this->serializeval($val2);
1712
                $rs .= "</member>\n";
1713
            }
1714
            $rs .= '</struct>';
1715
            break;
1716

    
1717
        case 2:
1718
            // array
1719
            $rs .= "<array>\n<data>\n";
1720
            foreach ($val as $value) {
1721
                $rs .= $this->serializeval($value);
1722
            }
1723
            $rs .= "</data>\n</array>";
1724
            break;
1725

    
1726
        case 1:
1727
            switch ($typ) {
1728
            case $GLOBALS['XML_RPC_Base64']:
1729
                $rs .= "<${typ}>" . base64_encode($val) . "</${typ}>";
1730
                break;
1731
            case $GLOBALS['XML_RPC_Boolean']:
1732
                $rs .= "<${typ}>" . ($val ? '1' : '0') . "</${typ}>";
1733
                break;
1734
            case $GLOBALS['XML_RPC_String']:
1735
                $rs .= "<${typ}>" . htmlspecialchars($val). "</${typ}>";
1736
                break;
1737
            default:
1738
                $rs .= "<${typ}>${val}</${typ}>";
1739
            }
1740
        }
1741
        return $rs;
1742
    }
1743

    
1744
    /**
1745
     * @return string  the data in XML format
1746
     */
1747
    function serialize()
1748
    {
1749
        return $this->serializeval($this);
1750
    }
1751

    
1752
    /**
1753
     * @return string  the data in XML format
1754
     */
1755
    function serializeval($o)
1756
    {
1757
        if (!is_object($o) || empty($o->me) || !is_array($o->me)) {
1758
            return '';
1759
        }
1760
        $ar = $o->me;
1761
        reset($ar);
1762
        list($typ, $val) = each($ar);
1763
        return '<value>' .  $this->serializedata($typ, $val) .  "</value>\n";
1764
    }
1765

    
1766
    /**
1767
     * @return mixed  the contents of the element requested
1768
     */
1769
    function structmem($m)
1770
    {
1771
        return $this->me['struct'][$m];
1772
    }
1773

    
1774
    /**
1775
     * @return void
1776
     */
1777
    function structreset()
1778
    {
1779
        reset($this->me['struct']);
1780
    }
1781

    
1782
    /**
1783
     * @return  the key/value pair of the struct's current element
1784
     */
1785
    function structeach()
1786
    {
1787
        return each($this->me['struct']);
1788
    }
1789

    
1790
    /**
1791
     * @return mixed  the current value
1792
     */
1793
    function getval()
1794
    {
1795
        // UNSTABLE
1796

    
1797
        reset($this->me);
1798
        $b = current($this->me);
1799

    
1800
        // contributed by I Sofer, 2001-03-24
1801
        // add support for nested arrays to scalarval
1802
        // i've created a new method here, so as to
1803
        // preserve back compatibility
1804

    
1805
        if (is_array($b)) {
1806
            foreach ($b as $id => $cont) {
1807
                $b[$id] = $cont->scalarval();
1808
            }
1809
        }
1810

    
1811
        // add support for structures directly encoding php objects
1812
        if (is_object($b)) {
1813
            $t = get_object_vars($b);
1814
            foreach ($t as $id => $cont) {
1815
                $t[$id] = $cont->scalarval();
1816
            }
1817
            foreach ($t as $id => $cont) {
1818
                $b->$id = $cont;
1819
            }
1820
        }
1821

    
1822
        // end contrib
1823
        return $b;
1824
    }
1825

    
1826
    /**
1827
     * @return mixed  the current element's scalar value.  If the value is
1828
     *                 not scalar, FALSE is returned.
1829
     */
1830
    function scalarval()
1831
    {
1832
        reset($this->me);
1833
        $v = current($this->me);
1834
        if (!is_scalar($v)) {
1835
            $v = false;
1836
        }
1837
        return $v;
1838
    }
1839

    
1840
    /**
1841
     * @return string
1842
     */
1843
    function scalartyp()
1844
    {
1845
        reset($this->me);
1846
        $a = key($this->me);
1847
        if ($a == $GLOBALS['XML_RPC_I4']) {
1848
            $a = $GLOBALS['XML_RPC_Int'];
1849
        }
1850
        return $a;
1851
    }
1852

    
1853
    /**
1854
     * @return mixed  the struct's current element
1855
     */
1856
    function arraymem($m)
1857
    {
1858
        return $this->me['array'][$m];
1859
    }
1860

    
1861
    /**
1862
     * @return int  the number of elements in the array
1863
     */
1864
    function arraysize()
1865
    {
1866
        reset($this->me);
1867
        list($a, $b) = each($this->me);
1868
        return sizeof($b);
1869
    }
1870

    
1871
    /**
1872
     * Determines if the item submitted is an XML_RPC_Value object
1873
     *
1874
     * @param mixed $val  the variable to be evaluated
1875
     *
1876
     * @return bool  TRUE if the item is an XML_RPC_Value object
1877
     *
1878
     * @static
1879
     * @since Method available since Release 1.3.0
1880
     */
1881
    function isValue($val)
1882
    {
1883
        return (strtolower(get_class($val)) == 'xml_rpc_value');
1884
    }
1885
}
1886

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

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

    
1942
/**
1943
 * Converts an XML_RPC_Value object into native PHP types
1944
 *
1945
 * @param object $XML_RPC_val  the XML_RPC_Value object to decode
1946
 *
1947
 * @return mixed  the PHP values
1948
 */
1949
function XML_RPC_decode($XML_RPC_val)
1950
{
1951
    $kind = $XML_RPC_val->kindOf();
1952

    
1953
    if ($kind == 'scalar') {
1954
        return $XML_RPC_val->scalarval();
1955

    
1956
    } elseif ($kind == 'array') {
1957
        $size = $XML_RPC_val->arraysize();
1958
        $arr = array();
1959
        for ($i = 0; $i < $size; $i++) {
1960
            $arr[] = XML_RPC_decode($XML_RPC_val->arraymem($i));
1961
        }
1962
        return $arr;
1963

    
1964
    } elseif ($kind == 'struct') {
1965
        $XML_RPC_val->structreset();
1966
        $arr = array();
1967
        while (list($key, $value) = $XML_RPC_val->structeach()) {
1968
            $arr[$key] = XML_RPC_decode($value);
1969
        }
1970
        return $arr;
1971
    }
1972
}
1973

    
1974
/**
1975
 * Converts native PHP types into an XML_RPC_Value object
1976
 *
1977
 * @param mixed $php_val  the PHP value or variable you want encoded
1978
 *
1979
 * @return object  the XML_RPC_Value object
1980
 */
1981
function XML_RPC_encode($php_val)
1982
{
1983
    $type = gettype($php_val);
1984
    $XML_RPC_val = new XML_RPC_Value;
1985

    
1986
    switch ($type) {
1987
    case 'array':
1988
        if (empty($php_val)) {
1989
            $XML_RPC_val->addArray($php_val);
1990
            break;
1991
        }
1992
        $tmp = array_diff(array_keys($php_val), range(0, count($php_val)-1));
1993
        if (empty($tmp)) {
1994
           $arr = array();
1995
           foreach ($php_val as $k => $v) {
1996
               $arr[$k] = XML_RPC_encode($v);
1997
           }
1998
           $XML_RPC_val->addArray($arr);
1999
           break;
2000
        }
2001
        // fall though if it's not an enumerated array
2002

    
2003
    case 'object':
2004
        $arr = array();
2005
        foreach ($php_val as $k => $v) {
2006
            $arr[$k] = XML_RPC_encode($v);
2007
        }
2008
        $XML_RPC_val->addStruct($arr);
2009
        break;
2010

    
2011
    case 'integer':
2012
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Int']);
2013
        break;
2014

    
2015
    case 'double':
2016
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Double']);
2017
        break;
2018

    
2019
    case 'string':
2020
    case 'NULL':
2021
        if (preg_match('@^[0-9]{8}\T{1}[0-9]{2}\:[0-9]{2}\:[0-9]{2}$@', $php_val)) {
2022
            $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_DateTime']);
2023
        } elseif ($GLOBALS['XML_RPC_auto_base64']
2024
                  && preg_match("@[^ -~\t\r\n]@", $php_val))
2025
        {
2026
            // Characters other than alpha-numeric, punctuation, SP, TAB,
2027
            // LF and CR break the XML parser, encode value via Base 64.
2028
            $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Base64']);
2029
        } else {
2030
            $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_String']);
2031
        }
2032
        break;
2033

    
2034
    case 'boolean':
2035
        // Add support for encoding/decoding of booleans, since they
2036
        // are supported in PHP
2037
        // by <G_Giunta_2001-02-29>
2038
        $XML_RPC_val->addScalar($php_val, $GLOBALS['XML_RPC_Boolean']);
2039
        break;
2040

    
2041
    case 'unknown type':
2042
    default:
2043
        $XML_RPC_val = false;
2044
    }
2045
    return $XML_RPC_val;
2046
}
2047

    
2048
/*
2049
 * Local variables:
2050
 * tab-width: 4
2051
 * c-basic-offset: 4
2052
 * c-hanging-comment-ender-p: nil
2053
 * End:
2054
 */
2055

    
2056
?>
(59-59/61)