xmlrpc.inc 17.3 KB
Newer Older
1
<?php
2

3 4
/**
 * @file
5 6 7
 * Drupal XML-RPC library.
 *
 * Based on the IXR - The Incutio XML-RPC Library - (c) Incutio Ltd 2002-2005
8 9 10 11
 * Version 1.7 (beta) - Simon Willison, 23rd May 2005
 * Site:   http://scripts.incutio.com/xmlrpc/
 * Manual: http://scripts.incutio.com/xmlrpc/manual.php
 * This version is made available under the GNU GPL License
12
 */
13

14
use GuzzleHttp\Exception\RequestException;
15

16
/**
17
 * Turns a data structure into objects with 'data' and 'type' attributes.
18 19 20
 *
 * @param $data
 *   The data structure.
21
 * @param $type
22 23 24 25
 *   Optional type to assign to $data.
 *
 * @return object
 *   An XML-RPC data object containing the input $data.
26
 */
27 28 29 30 31 32 33 34
function xmlrpc_value($data, $type = FALSE) {
  $xmlrpc_value = new stdClass();
  $xmlrpc_value->data = $data;
  if (!$type) {
    $type = xmlrpc_value_calculate_type($xmlrpc_value);
  }
  $xmlrpc_value->type = $type;
  if ($type == 'struct') {
35
    // Turn all the values in the array into new xmlrpc_values
36 37
    foreach ($xmlrpc_value->data as $key => $value) {
      $xmlrpc_value->data[$key] = xmlrpc_value($value);
38 39
    }
  }
40 41 42 43 44 45
  if ($type == 'array') {
    for ($i = 0, $j = count($xmlrpc_value->data); $i < $j; $i++) {
      $xmlrpc_value->data[$i] = xmlrpc_value($xmlrpc_value->data[$i]);
    }
  }
  return $xmlrpc_value;
46 47
}

Dries's avatar
Dries committed
48
/**
49
 * Maps a PHP type to an XML-RPC type.
Dries's avatar
Dries committed
50 51 52
 *
 * @param $xmlrpc_value
 *   Variable whose type should be mapped.
53 54 55 56
 *
 * @return string
 *   The corresponding XML-RPC type.
 *
57
 * @see http://www.xmlrpc.com/spec#scalars
Dries's avatar
Dries committed
58
 */
59
function xmlrpc_value_calculate_type($xmlrpc_value) {
60 61
  // http://www.php.net/gettype: Never use gettype() to test for a certain type
  // [...] Instead, use the is_* functions.
Dries's avatar
Dries committed
62 63 64 65 66 67 68
  if (is_bool($xmlrpc_value->data)) {
    return 'boolean';
  }
  if (is_double($xmlrpc_value->data)) {
    return 'double';
  }
  if (is_int($xmlrpc_value->data)) {
69
    return 'int';
70
  }
Dries's avatar
Dries committed
71 72 73 74 75
  if (is_array($xmlrpc_value->data)) {
    // empty or integer-indexed arrays are 'array', string-indexed arrays 'struct'
    return empty($xmlrpc_value->data) || range(0, count($xmlrpc_value->data) - 1) === array_keys($xmlrpc_value->data) ? 'array' : 'struct';
  }
  if (is_object($xmlrpc_value->data)) {
76
    if (isset($xmlrpc_value->data->is_date)) {
Dries's avatar
Dries committed
77 78
      return 'date';
    }
79
    if (isset($xmlrpc_value->data->is_base64)) {
Dries's avatar
Dries committed
80 81 82 83 84 85 86
      return 'base64';
    }
    $xmlrpc_value->data = get_object_vars($xmlrpc_value->data);
    return 'struct';
  }
  // default
  return 'string';
87 88
}

89
/**
90
 * Generates XML representing the given value.
91 92
 *
 * @param $xmlrpc_value
93
 *   A value to be represented in XML.
94
 *
95
 * @return
96
 *   XML representation of $xmlrpc_value.
97
 */
98 99 100
function xmlrpc_value_get_xml($xmlrpc_value) {
  switch ($xmlrpc_value->type) {
    case 'boolean':
101
      return '<boolean>' . (($xmlrpc_value->data) ? '1' : '0') . '</boolean>';
102

103
    case 'int':
104
      return '<int>' . $xmlrpc_value->data . '</int>';
105

106
    case 'double':
107
      return '<double>' . $xmlrpc_value->data . '</double>';
108

109
    case 'string':
110 111
      // Note: we don't escape apostrophes because of the many blogging clients
      // that don't support numerical entities (and XML in general) properly.
112
      return '<string>' . htmlspecialchars($xmlrpc_value->data) . '</string>';
113

114
    case 'array':
115
      $return = '<array><data>' . "\n";
116
      foreach ($xmlrpc_value->data as $item) {
117
        $return .= '  <value>' . xmlrpc_value_get_xml($item) . "</value>\n";
118 119 120
      }
      $return .= '</data></array>';
      return $return;
121

122
    case 'struct':
123
      $return = '<struct>' . "\n";
124
      foreach ($xmlrpc_value->data as $name => $value) {
125 126
        $return .= "  <member><name>" . check_plain($name) . "</name><value>";
        $return .= xmlrpc_value_get_xml($value) . "</value></member>\n";
127 128 129
      }
      $return .= '</struct>';
      return $return;
130

131 132
    case 'date':
      return xmlrpc_date_get_xml($xmlrpc_value->data);
133

134 135
    case 'base64':
      return xmlrpc_base64_get_xml($xmlrpc_value->data);
136
  }
137
  return FALSE;
138 139
}

140
/**
141
 * Constructs an object representing an XML-RPC message.
142 143
 *
 * @param $message
144 145 146 147 148 149
 *   A string containing an XML message.
 *
 * @return object
 *   An XML-RPC object containing the message.
 *
 * @see http://www.xmlrpc.com/spec
150
 */
151 152
function xmlrpc_message($message) {
  $xmlrpc_message = new stdClass();
153 154 155 156 157 158
  // The stack used to keep track of the current array/struct
  $xmlrpc_message->array_structs = array();
  // The stack used to keep track of if things are structs or array
  $xmlrpc_message->array_structs_types = array();
  // A stack as well
  $xmlrpc_message->current_struct_name = array();
159 160
  $xmlrpc_message->message = $message;
  return $xmlrpc_message;
161 162
}

163
/**
164
 * Parses an XML-RPC message.
165 166 167
 *
 * If parsing fails, the faultCode and faultString will be added to the message
 * object.
168 169
 *
 * @param $xmlrpc_message
170 171
 *   An object generated by xmlrpc_message().
 *
172
 * @return
173
 *   TRUE if parsing succeeded; FALSE otherwise.
174
 */
175
function xmlrpc_message_parse($xmlrpc_message) {
176
  $xmlrpc_message->_parser = xml_parser_create();
177
  // Set XML parser to take the case of tags into account.
178 179 180 181 182 183 184 185 186
  xml_parser_set_option($xmlrpc_message->_parser, XML_OPTION_CASE_FOLDING, FALSE);
  // Set XML parser callback functions
  xml_set_element_handler($xmlrpc_message->_parser, 'xmlrpc_message_tag_open', 'xmlrpc_message_tag_close');
  xml_set_character_data_handler($xmlrpc_message->_parser, 'xmlrpc_message_cdata');
  xmlrpc_message_set($xmlrpc_message);
  if (!xml_parse($xmlrpc_message->_parser, $xmlrpc_message->message)) {
    return FALSE;
  }
  xml_parser_free($xmlrpc_message->_parser);
187 188

  // Grab the error messages, if any.
189
  $xmlrpc_message = xmlrpc_message_get();
190 191 192 193
  if (!isset($xmlrpc_message->messagetype)) {
    return FALSE;
  }
  elseif ($xmlrpc_message->messagetype == 'fault') {
194 195 196 197
    $xmlrpc_message->fault_code = $xmlrpc_message->params[0]['faultCode'];
    $xmlrpc_message->fault_string = $xmlrpc_message->params[0]['faultString'];
  }
  return TRUE;
198 199
}

200
/**
201
 * Stores a copy of the most recent XML-RPC message object temporarily.
202 203
 *
 * @param $value
204 205 206 207 208 209
 *   An XML-RPC message to store, or NULL to keep the last message.
 *
 * @return object
 *   The most recently stored message.
 *
 * @see xmlrpc_message_get()
210
 */
211 212 213 214
function xmlrpc_message_set($value = NULL) {
  static $xmlrpc_message;
  if ($value) {
    $xmlrpc_message = $value;
215
  }
216
  return $xmlrpc_message;
217 218
}

219 220 221 222 223 224 225 226
/**
 * Returns the most recently stored XML-RPC message object.
 *
 * @return object
 *   The most recently stored message.
 *
 * @see xmlrpc_message_set()
 */
227 228 229
function xmlrpc_message_get() {
  return xmlrpc_message_set();
}
230

231 232 233
/**
 * Handles opening tags for XML parsing in xmlrpc_message_parse().
 */
234 235 236
function xmlrpc_message_tag_open($parser, $tag, $attr) {
  $xmlrpc_message = xmlrpc_message_get();
  $xmlrpc_message->current_tag_contents = '';
237
  $xmlrpc_message->last_open = $tag;
238
  switch ($tag) {
239 240 241 242 243
    case 'methodCall':
    case 'methodResponse':
    case 'fault':
      $xmlrpc_message->messagetype = $tag;
      break;
244

245
    // Deal with stacks of arrays and structs
246 247 248 249
    case 'data':
      $xmlrpc_message->array_structs_types[] = 'array';
      $xmlrpc_message->array_structs[] = array();
      break;
250

251 252 253 254
    case 'struct':
      $xmlrpc_message->array_structs_types[] = 'struct';
      $xmlrpc_message->array_structs[] = array();
      break;
255
  }
256
  xmlrpc_message_set($xmlrpc_message);
257 258
}

259 260 261
/**
 * Handles character data for XML parsing in xmlrpc_message_parse().
 */
262 263 264 265 266
function xmlrpc_message_cdata($parser, $cdata) {
  $xmlrpc_message = xmlrpc_message_get();
  $xmlrpc_message->current_tag_contents .= $cdata;
  xmlrpc_message_set($xmlrpc_message);
}
267

268 269 270
/**
 * Handles closing tags for XML parsing in xmlrpc_message_parse().
 */
271 272 273
function xmlrpc_message_tag_close($parser, $tag) {
  $xmlrpc_message = xmlrpc_message_get();
  $value_flag = FALSE;
274
  switch ($tag) {
275 276 277 278 279
    case 'int':
    case 'i4':
      $value = (int)trim($xmlrpc_message->current_tag_contents);
      $value_flag = TRUE;
      break;
280

281 282 283 284
    case 'double':
      $value = (double)trim($xmlrpc_message->current_tag_contents);
      $value_flag = TRUE;
      break;
285

286 287 288 289
    case 'string':
      $value = $xmlrpc_message->current_tag_contents;
      $value_flag = TRUE;
      break;
290

291 292 293 294 295
    case 'dateTime.iso8601':
      $value = xmlrpc_date(trim($xmlrpc_message->current_tag_contents));
      // $value = $iso->getTimestamp();
      $value_flag = TRUE;
      break;
296

297
    case 'value':
298
      // If no type is indicated, the type is string
299
      // We take special care for empty values
300
      if (trim($xmlrpc_message->current_tag_contents) != '' || (isset($xmlrpc_message->last_open) && ($xmlrpc_message->last_open == 'value'))) {
301
        $value = (string) $xmlrpc_message->current_tag_contents;
302 303 304
        $value_flag = TRUE;
      }
      unset($xmlrpc_message->last_open);
305
      break;
306

307 308 309 310
    case 'boolean':
      $value = (boolean)trim($xmlrpc_message->current_tag_contents);
      $value_flag = TRUE;
      break;
311

312 313 314 315
    case 'base64':
      $value = base64_decode(trim($xmlrpc_message->current_tag_contents));
      $value_flag = TRUE;
      break;
316

317
    // Deal with stacks of arrays and structs
318 319
    case 'data':
    case 'struct':
320
      $value = array_pop($xmlrpc_message->array_structs);
321 322 323
      array_pop($xmlrpc_message->array_structs_types);
      $value_flag = TRUE;
      break;
324

325 326 327
    case 'member':
      array_pop($xmlrpc_message->current_struct_name);
      break;
328

329 330 331
    case 'name':
      $xmlrpc_message->current_struct_name[] = trim($xmlrpc_message->current_tag_contents);
      break;
332

333 334 335
    case 'methodName':
      $xmlrpc_message->methodname = trim($xmlrpc_message->current_tag_contents);
      break;
336
  }
337
  if ($value_flag) {
338
    if (count($xmlrpc_message->array_structs) > 0) {
339
      // Add value to struct or array
340
      if ($xmlrpc_message->array_structs_types[count($xmlrpc_message->array_structs_types) - 1] == 'struct') {
341
        // Add to struct
342
        $xmlrpc_message->array_structs[count($xmlrpc_message->array_structs) - 1][$xmlrpc_message->current_struct_name[count($xmlrpc_message->current_struct_name) - 1]] = $value;
343 344
      }
      else {
345
        // Add to array
346
        $xmlrpc_message->array_structs[count($xmlrpc_message->array_structs) - 1][] = $value;
347
      }
348 349
    }
    else {
350
      // Just add as a parameter
351
      $xmlrpc_message->params[] = $value;
352 353
    }
  }
354 355
  if (!in_array($tag, array("data", "struct", "member"))) {
    $xmlrpc_message->current_tag_contents = '';
356
  }
357 358
  xmlrpc_message_set($xmlrpc_message);
}
359

360
/**
361
 * Constructs an object representing an XML-RPC request.
362 363
 *
 * @param $method
364
 *   The name of the method to be called.
365 366
 * @param $args
 *   An array of parameters to send with the method.
367 368 369
 *
 * @return object
 *   An XML-RPC object representing the request.
370
 */
371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390
function xmlrpc_request($method, $args) {
  $xmlrpc_request = new stdClass();
  $xmlrpc_request->method = $method;
  $xmlrpc_request->args = $args;
  $xmlrpc_request->xml = <<<EOD
<?xml version="1.0"?>
<methodCall>
<methodName>{$xmlrpc_request->method}</methodName>
<params>

EOD;
  foreach ($xmlrpc_request->args as $arg) {
    $xmlrpc_request->xml .= '<param><value>';
    $v = xmlrpc_value($arg);
    $xmlrpc_request->xml .= xmlrpc_value_get_xml($v);
    $xmlrpc_request->xml .= "</value></param>\n";
  }
  $xmlrpc_request->xml .= '</params></methodCall>';
  return $xmlrpc_request;
}
391

392 393 394 395 396 397 398 399 400 401 402 403 404 405
/**
 * Generates, temporarily saves, and returns an XML-RPC error object.
 *
 * @param $code
 *   The error code.
 * @param $message
 *   The error message.
 * @param $reset
 *   TRUE to empty the temporary error storage. Ignored if $code is supplied.
 *
 * @return object
 *   An XML-RPC error object representing $code and $message, or the most
 *   recently stored error object if omitted.
 */
406
function xmlrpc_error($code = NULL, $message = NULL, $reset = FALSE) {
407
  static $xmlrpc_error;
408
  if (isset($code)) {
409 410 411 412
    $xmlrpc_error = new stdClass();
    $xmlrpc_error->is_error = TRUE;
    $xmlrpc_error->code = $code;
    $xmlrpc_error->message = $message;
413
  }
414 415 416
  elseif ($reset) {
    $xmlrpc_error = NULL;
  }
417
  return $xmlrpc_error;
418 419
}

420 421 422 423 424 425 426 427 428
/**
 * Converts an XML-RPC error object into XML.
 *
 * @param $xmlrpc_error
 *   The XML-RPC error object.
 *
 * @return string
 *   An XML representation of the error as an XML methodResponse.
 */
429
function xmlrpc_error_get_xml($xmlrpc_error) {
430
  return <<<EOD
431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448
<methodResponse>
  <fault>
  <value>
    <struct>
    <member>
      <name>faultCode</name>
      <value><int>{$xmlrpc_error->code}</int></value>
    </member>
    <member>
      <name>faultString</name>
      <value><string>{$xmlrpc_error->message}</string></value>
    </member>
    </struct>
  </value>
  </fault>
</methodResponse>

EOD;
449 450
}

451 452 453 454 455 456 457 458 459
/**
 * Converts a PHP or ISO date/time to an XML-RPC object.
 *
 * @param $time
 *   A PHP timestamp or an ISO date-time string.
 *
 * @return object
 *   An XML-RPC time/date object.
 */
460 461 462 463 464
function xmlrpc_date($time) {
  $xmlrpc_date = new stdClass();
  $xmlrpc_date->is_date = TRUE;
  // $time can be a PHP timestamp or an ISO one
  if (is_numeric($time)) {
465 466 467 468 469 470 471
    $xmlrpc_date->year = gmdate('Y', $time);
    $xmlrpc_date->month = gmdate('m', $time);
    $xmlrpc_date->day = gmdate('d', $time);
    $xmlrpc_date->hour = gmdate('H', $time);
    $xmlrpc_date->minute = gmdate('i', $time);
    $xmlrpc_date->second = gmdate('s', $time);
    $xmlrpc_date->iso8601 = gmdate('Ymd\TH:i:s', $time);
472 473
  }
  else {
474
    $xmlrpc_date->iso8601 = $time;
475
    $time = str_replace(array('-', ':'), '', $time);
476 477 478 479
    $xmlrpc_date->year = substr($time, 0, 4);
    $xmlrpc_date->month = substr($time, 4, 2);
    $xmlrpc_date->day = substr($time, 6, 2);
    $xmlrpc_date->hour = substr($time, 9, 2);
480
    $xmlrpc_date->minute = substr($time, 11, 2);
481
    $xmlrpc_date->second = substr($time, 13, 2);
482 483
  }
  return $xmlrpc_date;
484 485
}

486 487 488 489 490 491 492 493 494
/**
 * Converts an XML-RPC date-time object into XML.
 *
 * @param $xmlrpc_date
 *   The XML-RPC date-time object.
 *
 * @return string
 *   An XML representation of the date/time as XML.
 */
495
function xmlrpc_date_get_xml($xmlrpc_date) {
496
  return '<dateTime.iso8601>' . $xmlrpc_date->year . $xmlrpc_date->month . $xmlrpc_date->day . 'T' . $xmlrpc_date->hour . ':' . $xmlrpc_date->minute . ':' . $xmlrpc_date->second . '</dateTime.iso8601>';
497
}
498

499 500 501 502 503 504 505 506 507
/**
 * Returns an XML-RPC base 64 object.
 *
 * @param $data
 *   Base 64 data to store in returned object.
 *
 * @return object
 *   An XML-RPC base 64 object.
 */
508 509 510 511 512 513
function xmlrpc_base64($data) {
  $xmlrpc_base64 = new stdClass();
  $xmlrpc_base64->is_base64 = TRUE;
  $xmlrpc_base64->data = $data;
  return $xmlrpc_base64;
}
514

515 516 517 518 519 520 521 522 523
/**
 * Converts an XML-RPC base 64 object into XML.
 *
 * @param $xmlrpc_base64
 *   The XML-RPC base 64 object.
 *
 * @return string
 *   An XML representation of the base 64 data as XML.
 */
524
function xmlrpc_base64_get_xml($xmlrpc_base64) {
525
  return '<base64>' . base64_encode($xmlrpc_base64->data) . '</base64>';
526 527
}

528
/**
529
 * Performs one or more XML-RPC requests.
530
 *
531
 * @param string $url
532 533
 *   An absolute URL of the XML-RPC endpoint, e.g.,
 *   http://example.com/xmlrpc.php
534
 * @param array $args
535 536 537
 *   An associative array whose keys are the methods to call and whose values
 *   are the arguments to pass to the respective method. If multiple methods
 *   are specified, a system.multicall is performed.
538 539
 * @param array $headers
 *   (optional) An array of HTTP headers to pass along.
540
 *
541 542 543 544 545 546
 * @return
 *   A single response (single request) or an array of responses (multicall
 *   request). Each response is the return value of the method, just as if it
 *   has been a local function call, on success, or FALSE on failure. If FALSE
 *   is returned, see xmlrpc_errno() and xmlrpc_error_msg() to get more
 *   information.
547
 */
548
function _xmlrpc($url, array $args, array $headers = array()) {
549
  xmlrpc_clear_error();
550
  if (count($args) > 1) {
551
    $multicall_args = array();
552 553
    foreach ($args as $method => $call) {
      $multicall_args[] = array('methodName' => $method, 'params' => $call);
554
    }
555
    $method = 'system.multicall';
556 557 558
    $args = array($multicall_args);
  }
  else {
559 560
    $method = key($args);
    $args = $args[$method];
561
  }
562
  $xmlrpc_request = xmlrpc_request($method, $args);
563 564 565

  $headers['Content-Type'] = 'text/xml';

566
  try {
567
    $response = \Drupal::httpClient()->post($url, array('headers' => $headers, 'body' => $xmlrpc_request->xml));
568 569 570
  }
  catch (RequestException $exception) {
    xmlrpc_error(NULL, $exception->getMethod());
571 572
    return FALSE;
  }
573
  $message = xmlrpc_message($response->getBody(TRUE));
574 575 576
  // Now parse what we've got back
  if (!xmlrpc_message_parse($message)) {
    // XML error
577
    xmlrpc_error(-32700, t('Parse error. Not well formed'));
578 579 580 581
    return FALSE;
  }
  // Is the message a fault?
  if ($message->messagetype == 'fault') {
582
    xmlrpc_error($message->fault_code, $message->fault_string);
583 584
    return FALSE;
  }
585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601
  // We now know that the message is well-formed and a non-fault result.
  if ($method == 'system.multicall') {
    // Return per-method results or error objects.
    $return = array();
    foreach ($message->params[0] as $result) {
      if (array_keys($result) == array(0)) {
        $return[] = $result[0];
      }
      else {
        $return[] = xmlrpc_error($result['faultCode'], $result['faultString']);
      }
    }
  }
  else {
    $return = $message->params[0];
  }
  return $return;
602
}
603

604
/**
605
 * Returns the last XML-RPC client error number.
606 607 608
 */
function xmlrpc_errno() {
  $error = xmlrpc_error();
609
  return ($error != NULL ? $error->code : NULL);
610 611
}

612
/**
613
 * Returns the last XML-RPC client error message.
614 615 616
 */
function xmlrpc_error_msg() {
  $error = xmlrpc_error();
617
  return ($error != NULL ? $error->message : NULL);
618
}
619 620

/**
621 622 623
 * Clears any previously-saved errors.
 *
 * @see xmlrpc_error()
624 625 626 627
 */
function xmlrpc_clear_error() {
  xmlrpc_error(NULL, NULL, TRUE);
}