MollomPlugin.php 33 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Plugin to check submitted notices with Mollom
  18. *
  19. * Mollom is a bayesian spam checker, wrapped into a webservice
  20. * This plugin is based on the Drupal Mollom Plugin
  21. *
  22. * @category Plugin
  23. * @package GNUsocial
  24. * @author Brenda Wallace <brenda@cpan.org>
  25. * @copyright 2010 StatusNet, Inc.
  26. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  27. */
  28. defined('GNUsocial') || die();
  29. define('MOLLOMPLUGIN_VERSION', '0.1');
  30. define('MOLLOM_API_VERSION', '1.0');
  31. define('MOLLOM_ANALYSIS_UNKNOWN', 0);
  32. define('MOLLOM_ANALYSIS_HAM', 1);
  33. define('MOLLOM_ANALYSIS_SPAM', 2);
  34. define('MOLLOM_ANALYSIS_UNSURE', 3);
  35. define('MOLLOM_MODE_DISABLED', 0);
  36. define('MOLLOM_MODE_CAPTCHA', 1);
  37. define('MOLLOM_MODE_ANALYSIS', 2);
  38. define('MOLLOM_FALLBACK_BLOCK', 0);
  39. define('MOLLOM_FALLBACK_ACCEPT', 1);
  40. define('MOLLOM_ERROR', 1000);
  41. define('MOLLOM_REFRESH', 1100);
  42. define('MOLLOM_REDIRECT', 1200);
  43. /**
  44. * Plugin to check submitted notices with Mollom
  45. *
  46. * Mollom is a bayesian spam filter provided by webservice.
  47. *
  48. * @category Plugin
  49. * @package GNUsocial
  50. * @author Brenda Wallace <shiny@cpan.org>
  51. * @copyright 2010 StatusNet, Inc.
  52. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  53. *
  54. * @see Event
  55. */
  56. class MollomPlugin extends Plugin
  57. {
  58. public $public_key;
  59. public $private_key;
  60. public $servers = null;
  61. public function onStartNoticeSave($notice)
  62. {
  63. if ($this->public_key) {
  64. //Check spam
  65. $data = [
  66. 'post_body' => $notice->content,
  67. 'author_name' => $profile->nickname,
  68. 'author_url' => $profile->homepage,
  69. 'author_id' => $profile->id,
  70. 'author_ip' => $this->getClientIp(),
  71. ];
  72. $response = $this->mollom('mollom.checkContent', $data);
  73. switch ($response['spam']) {
  74. case MOLLOM_ANALYSIS_SPAM:
  75. // TRANS: Client exception thrown when notice content triggers the spam filter.
  76. throw new ClientException(_m('Spam Detected.'), 400);
  77. case MOLLOM_ANALYSIS_UNSURE:
  78. //if unsure, let through
  79. break;
  80. case MOLLOM_ANALYSIS_HAM:
  81. // all good! :-)
  82. break;
  83. }
  84. }
  85. return true;
  86. }
  87. public function getClientIP()
  88. {
  89. if (isset($_SERVER) && array_key_exists('REQUEST_METHOD', $_SERVER)) {
  90. // Note: order matters here; use proxy-forwarded stuff first
  91. foreach (array('HTTP_X_FORWARDED_FOR', 'CLIENT-IP', 'REMOTE_ADDR') as $k) {
  92. if (isset($_SERVER[$k])) {
  93. return $_SERVER[$k];
  94. }
  95. }
  96. }
  97. return '127.0.0.1';
  98. }
  99. /**
  100. * Call a remote procedure at the Mollom server. This function will
  101. * automatically add the information required to authenticate against
  102. * Mollom.
  103. */
  104. public function mollom($method, $data = [])
  105. {
  106. if (!extension_loaded('xmlrpc')) {
  107. if (!dl('xmlrpc.so')) {
  108. common_log(LOG_ERR, "Can't pingback; xmlrpc extension not available.");
  109. }
  110. }
  111. // Construct the server URL:
  112. $public_key = $this->public_key;
  113. // Retrieve the list of Mollom servers from the database:
  114. $servers = $this->servers;
  115. if (is_null($servers)) {
  116. // Retrieve a list of valid Mollom servers from mollom.com:
  117. $servers = $this->xmlrpc('http://xmlrpc.mollom.com/'. MOLLOM_API_VERSION, 'mollom.getServerList', $this->authentication());
  118. // Store the list of servers in the database:
  119. // @todo variable_set('mollom_servers', $servers);
  120. }
  121. if (is_array($servers)) {
  122. // Send the request to the first server, if that fails, try the other servers in the list:
  123. foreach ($servers as $server) {
  124. $auth = $this->authentication();
  125. $data = array_merge($data, $auth);
  126. $result = $this->xmlrpc(
  127. $server . '/' . MOLLOM_API_VERSION,
  128. $method,
  129. $data
  130. );
  131. // Debug output:
  132. if (array_key_exists('session_id', $data)) {
  133. common_debug(
  134. "called {$method} at server {$server} with session ID "
  135. . "'{$data['session_id']}'"
  136. );
  137. } else {
  138. common_debug(
  139. "called {$method} at server {$server} with no session ID"
  140. );
  141. }
  142. if (!empty($errno = $this->xmlrpc_errno())) {
  143. common_log(LOG_ERR, sprintf(
  144. 'Error @errno: %s - %s - %s - <pre>%s</pre>',
  145. $this->xmlrpc_errno(),
  146. $server,
  147. $this->xmlrpc_error_msg(),
  148. $method,
  149. print_r($data, true)
  150. ));
  151. if ($errno === MOLLOM_REFRESH) {
  152. // Retrieve a list of valid Mollom servers from mollom.com:
  153. $servers = $this->xmlrpc(
  154. 'http://xmlrpc.mollom.com/' . MOLLOM_API_VERSION,
  155. 'mollom.getServerList',
  156. $this->authentication()
  157. );
  158. // Store the updated list of servers in the database:
  159. // @todo variable_set('mollom_servers', $servers);
  160. } elseif ($errno === MOLLOM_ERROR) {
  161. return $result;
  162. } elseif ($errno === MOLLOM_REDIRECT) {
  163. // Do nothing, we select the next client automatically.
  164. }
  165. // Reset the XMLRPC error:
  166. $this->xmlrpc_error(0); // FIXME: this is crazy.
  167. } else {
  168. common_debug('Result = ' . print_r($result, true));
  169. return $result;
  170. }
  171. }
  172. }
  173. // If none of the servers worked, activate the fallback mechanism:
  174. common_debug('none of the servers worked');
  175. // _mollom_fallback();
  176. // If everything failed, we reset the server list to force Mollom to request a new list:
  177. //TODO variable_set('mollom_servers', array());
  178. }
  179. /**
  180. * This function generate an array with all the information required to
  181. * authenticate against Mollom. To prevent that requests are forged and
  182. * that you are impersonated, each request is signed with a hash computed
  183. * based on a private key and a timestamp.
  184. *
  185. * Both the client and the server share the secret key that is used to
  186. * create the authentication hash based on a timestamp. They both hash
  187. * the timestamp with the secret key, and if the hashes match, the
  188. * authenticity of the message has been validated.
  189. *
  190. * To avoid that someone can intercept a (hash, timestamp)-pair and
  191. * use that to impersonate a client, Mollom will reject the request
  192. * when the timestamp is more than 15 minutes off.
  193. *
  194. * Make sure your server's time is synchronized with the world clocks,
  195. * and that you don't share your private key with anyone else.
  196. */
  197. private function authentication()
  198. {
  199. $public_key = $this->public_key;
  200. $private_key = $this->private_key;
  201. $hash = hash_hmac('sha1', $private_key, $private_key, true);
  202. // Store everything in an array. Elsewhere in the code, we'll add the
  203. // acutal data before we pass it onto the XML-RPC library:
  204. $data['public_key'] = $public_key;
  205. $data['time'] = $time;
  206. $data['hash'] = $hash;
  207. return $data;
  208. }
  209. public function xmlrpc($url)
  210. {
  211. //require_once './includes/xmlrpc.inc';
  212. $args = func_get_args();
  213. return call_user_func_array(['MollomPlugin', '_xmlrpc'], $args);
  214. }
  215. /**
  216. * Recursively turn a data structure into objects with 'data' and 'type' attributes.
  217. *
  218. * @param $data
  219. * The data structure.
  220. * @param $type
  221. * Optional type assign to $data.
  222. * @return
  223. * Object.
  224. */
  225. public function xmlrpc_value($data, $type = false)
  226. {
  227. $xmlrpc_value = new stdClass();
  228. $xmlrpc_value->data = $data;
  229. if (!$type) {
  230. $type = $this->xmlrpc_value_calculate_type($xmlrpc_value);
  231. }
  232. $xmlrpc_value->type = $type;
  233. if ($type === 'struct') {
  234. // Turn all the values in the array into new xmlrpc_values
  235. foreach ($xmlrpc_value->data as $key => $value) {
  236. $xmlrpc_value->data[$key] = $this->xmlrpc_value($value);
  237. }
  238. }
  239. if ($type === 'array') {
  240. for ($i = 0, $j = count($xmlrpc_value->data); $i < $j; ++$i) {
  241. $xmlrpc_value->data[$i] = $this->xmlrpc_value($xmlrpc_value->data[$i]);
  242. }
  243. }
  244. return $xmlrpc_value;
  245. }
  246. /**
  247. * Map PHP type to XML-RPC type.
  248. *
  249. * @param $xmlrpc_value
  250. * Variable whose type should be mapped.
  251. * @return
  252. * XML-RPC type as string.
  253. * @see
  254. * http://www.xmlrpc.com/spec#scalars
  255. */
  256. public function xmlrpc_value_calculate_type(&$xmlrpc_value)
  257. {
  258. // http://www.php.net/gettype: Never use gettype() to test for a certain type [...] Instead, use the is_* functions.
  259. if (is_bool($xmlrpc_value->data)) {
  260. return 'boolean';
  261. } elseif (is_double($xmlrpc_value->data)) {
  262. return 'double';
  263. } elseif (is_int($xmlrpc_value->data)) {
  264. return 'int';
  265. } elseif (is_array($xmlrpc_value->data)) {
  266. // empty or integer-indexed arrays are 'array', string-indexed arrays 'struct'
  267. return empty($xmlrpc_value->data)
  268. || (range(0, count($xmlrpc_value->data) - 1) === array_keys($xmlrpc_value->data) ? 'array' : 'struct');
  269. }
  270. if (is_object($xmlrpc_value->data)) {
  271. if ($xmlrpc_value->data->is_date) {
  272. return 'date';
  273. } elseif ($xmlrpc_value->data->is_base64) {
  274. return 'base64';
  275. }
  276. $xmlrpc_value->data = get_object_vars($xmlrpc_value->data);
  277. return 'struct';
  278. }
  279. // default
  280. return 'string';
  281. }
  282. /**
  283. * Generate XML representing the given value.
  284. *
  285. * @param $xmlrpc_value
  286. * @return
  287. * XML representation of value.
  288. */
  289. public function xmlrpc_value_get_xml($xmlrpc_value)
  290. {
  291. switch ($xmlrpc_value->type) {
  292. case 'boolean':
  293. return '<boolean>'. (($xmlrpc_value->data) ? '1' : '0') .'</boolean>';
  294. break;
  295. case 'int':
  296. return '<int>'. $xmlrpc_value->data .'</int>';
  297. break;
  298. case 'double':
  299. return '<double>'. $xmlrpc_value->data .'</double>';
  300. break;
  301. case 'string':
  302. // Note: we don't escape apostrophes because of the many blogging clients
  303. // that don't support numerical entities (and XML in general) properly.
  304. return '<string>'. htmlspecialchars($xmlrpc_value->data) .'</string>';
  305. break;
  306. case 'array':
  307. $return = "<array><data>\n";
  308. foreach ($xmlrpc_value->data as $item) {
  309. $return .= ' <value>'. $this->xmlrpc_value_get_xml($item) ."</value>\n";
  310. }
  311. $return .= '</data></array>';
  312. return $return;
  313. break;
  314. case 'struct':
  315. $return = "<struct>\n";
  316. foreach ($xmlrpc_value->data as $name => $value) {
  317. $return .= ' <member><name>' . htmlentities($name) . '</name><value>';
  318. $return .= $this->xmlrpc_value_get_xml($value) . "</value></member>\n";
  319. }
  320. $return .= '</struct>';
  321. return $return;
  322. break;
  323. case 'date':
  324. return $this->xmlrpc_date_get_xml($xmlrpc_value->data);
  325. break;
  326. case 'base64':
  327. return $this->xmlrpc_base64_get_xml($xmlrpc_value->data);
  328. break;
  329. }
  330. return false;
  331. }
  332. /**
  333. * Perform an HTTP request.
  334. *
  335. * This is a flexible and powerful HTTP client implementation. Correctly handles
  336. * GET, POST, PUT or any other HTTP requests. Handles redirects.
  337. *
  338. * @param $url
  339. * A string containing a fully qualified URI.
  340. * @param $headers
  341. * An array containing an HTTP header => value pair.
  342. * @param $method
  343. * A string defining the HTTP request to use.
  344. * @param $data
  345. * A string containing data to include in the request.
  346. * @param $retry
  347. * An integer representing how many times to retry the request in case of a
  348. * redirect.
  349. * @return
  350. * An object containing the HTTP request headers, response code, headers,
  351. * data and redirect status.
  352. */
  353. public function http_request(
  354. $url,
  355. $headers = [],
  356. $method = 'GET',
  357. $data = null,
  358. $retry = 3
  359. ) {
  360. global $db_prefix;
  361. $result = new stdClass();
  362. // Parse the URL and make sure we can handle the schema.
  363. $uri = parse_url($url);
  364. if ($uri === false) {
  365. $result->error = 'unable to parse URL';
  366. return $result;
  367. }
  368. if (!array_key_exists('scheme', $uri)) {
  369. $result->error = 'missing schema';
  370. return $result;
  371. }
  372. switch ($uri['scheme']) {
  373. case 'http':
  374. $port = isset($uri['port']) ? $uri['port'] : 80;
  375. $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
  376. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
  377. break;
  378. case 'https':
  379. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  380. $port = isset($uri['port']) ? $uri['port'] : 443;
  381. $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
  382. $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
  383. break;
  384. default:
  385. $result->error = 'invalid schema '. $uri['scheme'];
  386. return $result;
  387. }
  388. // Make sure the socket opened properly.
  389. if ($fp === false) {
  390. // When a network error occurs, we use a negative number so it does not
  391. // clash with the HTTP status codes.
  392. $result->code = -$errno;
  393. $result->error = trim($errstr);
  394. // Mark that this request failed. This will trigger a check of the web
  395. // server's ability to make outgoing HTTP requests the next time that
  396. // requirements checking is performed.
  397. // @see system_requirements()
  398. // @todo variable_set('drupal_http_request_fails', TRUE);
  399. return $result;
  400. }
  401. // Construct the path to act on.
  402. $path = $uri['path'] ?? '/';
  403. if (array_key_exists('query', $uri)) {
  404. $path .= '?' . $uri['query'];
  405. }
  406. // Create HTTP request.
  407. $defaults = [
  408. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  409. // We don't add the port to prevent from breaking rewrite rules checking the
  410. // host that do not take into account the port number.
  411. 'Host' => "Host: {$host}",
  412. 'User-Agent' => 'User-Agent: Drupal (+http://drupal.org/)',
  413. 'Content-Length' => 'Content-Length: ' . strlen($data),
  414. ];
  415. // If the server url has a user then attempt to use basic authentication
  416. if (array_key_exists('user', $uri)) {
  417. $defaults['Authorization'] = 'Authorization: Basic '
  418. . base64_encode($uri['user']
  419. . (!empty($uri['pass']) ? ':' . $uri['pass'] : ''));
  420. }
  421. // If the database prefix is being used by SimpleTest to run the tests in a copied
  422. // database then set the user-agent header to the database prefix so that any
  423. // calls to other Drupal pages will run the SimpleTest prefixed database. The
  424. // user-agent is used to ensure that multiple testing sessions running at the
  425. // same time won't interfere with each other as they would if the database
  426. // prefix were stored statically in a file or database variable.
  427. if (
  428. is_string($db_prefix)
  429. && preg_match('/^simpletest\d+$/', $db_prefix, $matches)
  430. ) {
  431. $defaults['User-Agent'] = 'User-Agent: ' . $matches[0];
  432. }
  433. foreach ($headers as $header => $value) {
  434. $defaults[$header] = $header . ': ' . $value;
  435. }
  436. $request = $method . ' ' . $path . " HTTP/1.0\r\n";
  437. $request .= implode("\r\n", $defaults);
  438. $request .= "\r\n\r\n";
  439. $request .= $data;
  440. $result->request = $request;
  441. fwrite($fp, $request);
  442. // Fetch response.
  443. $response = '';
  444. while (!feof($fp) && ($chunk = fread($fp, 1024)) !== false) {
  445. $response .= $chunk;
  446. }
  447. fclose($fp);
  448. // Parse response.
  449. [$split, $result->data] = explode("\r\n\r\n", $response, 2);
  450. $split = preg_split("/\r\n|\n|\r/", $split);
  451. [$protocol, $code, $text] = explode(' ', trim(array_shift($split)), 3);
  452. $result->headers = [];
  453. // Parse headers.
  454. while (($line = trim(array_shift($split))) !== '') {
  455. [$header, $value] = explode(':', $line, 2);
  456. if (
  457. array_key_exists($header, $result->headers)
  458. && $header === 'Set-Cookie'
  459. ) {
  460. // RFC 2109: the Set-Cookie response header comprises the token Set-
  461. // Cookie:, followed by a comma-separated list of one or more cookies.
  462. $result->headers[$header] .= ',' . trim($value);
  463. } else {
  464. $result->headers[$header] = trim($value);
  465. }
  466. }
  467. $responses = [
  468. 100 => 'Continue', 101 => 'Switching Protocols',
  469. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  470. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  471. 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Time-out', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Large', 415 => 'Unsupported Media Type', 416 => 'Requested range not satisfiable', 417 => 'Expectation Failed',
  472. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported',
  473. ];
  474. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  475. // base code in their class.
  476. if (!array_key_exists($code, $responses)) {
  477. $code = floor($code / 100) * 100;
  478. }
  479. switch ($code) {
  480. case 200: // OK
  481. case 304: // Not modified
  482. break;
  483. case 301: // Moved permanently
  484. case 302: // Moved temporarily
  485. case 307: // Moved temporarily
  486. $location = $result->headers['Location'];
  487. if ($retry) {
  488. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  489. $result->redirect_code = $result->code;
  490. }
  491. $result->redirect_url = $location;
  492. break;
  493. default:
  494. $result->error = $text;
  495. }
  496. $result->code = $code;
  497. return $result;
  498. }
  499. /**
  500. * Construct an object representing an XML-RPC message.
  501. *
  502. * @param $message
  503. * String containing XML as defined at http://www.xmlrpc.com/spec
  504. * @return
  505. * Object
  506. */
  507. public function xmlrpc_message($message)
  508. {
  509. $xmlrpc_message = new stdClass();
  510. // The stack used to keep track of the current array/struct
  511. $xmlrpc_message->array_structs = [];
  512. // The stack used to keep track of if things are structs or array
  513. $xmlrpc_message->array_structs_types = [];
  514. // A stack as well
  515. $xmlrpc_message->current_struct_name = [];
  516. $xmlrpc_message->message = $message;
  517. return $xmlrpc_message;
  518. }
  519. /**
  520. * Parse an XML-RPC message. If parsing fails, the faultCode and faultString
  521. * will be added to the message object.
  522. *
  523. * @param $xmlrpc_message
  524. * Object generated by xmlrpc_message()
  525. * @return
  526. * TRUE if parsing succeeded; FALSE otherwise
  527. */
  528. public function xmlrpc_message_parse(&$xmlrpc_message)
  529. {
  530. // First remove the XML declaration
  531. $xmlrpc_message->message = preg_replace(
  532. '/<\?xml(.*)?\?'.'>/',
  533. '',
  534. $xmlrpc_message->message
  535. );
  536. if (trim($xmlrpc_message->message) === '') {
  537. return false;
  538. }
  539. $xmlrpc_message->_parser = xml_parser_create();
  540. // Set XML parser to take the case of tags into account.
  541. xml_parser_set_option(
  542. $xmlrpc_message->_parser,
  543. XML_OPTION_CASE_FOLDING,
  544. false
  545. );
  546. // Set XML parser callback functions
  547. xml_set_element_handler(
  548. $xmlrpc_message->_parser,
  549. ['MollomPlugin', 'xmlrpc_message_tag_open'],
  550. ['MollomPlugin', 'xmlrpc_message_tag_close']
  551. );
  552. xml_set_character_data_handler(
  553. $xmlrpc_message->_parser,
  554. ['MollomPlugin', 'xmlrpc_message_cdata']
  555. );
  556. $this->xmlrpc_message_set($xmlrpc_message);
  557. if (!xml_parse($xmlrpc_message->_parser, $xmlrpc_message->message)) {
  558. return false;
  559. }
  560. xml_parser_free($xmlrpc_message->_parser);
  561. // Grab the error messages, if any
  562. $xmlrpc_message = $this->xmlrpc_message_get();
  563. if ($xmlrpc_message->messagetype === 'fault') {
  564. $xmlrpc_message->fault_code = $xmlrpc_message->params[0]['faultCode'];
  565. $xmlrpc_message->fault_string = $xmlrpc_message->params[0]['faultString'];
  566. }
  567. return true;
  568. }
  569. /**
  570. * Store a copy of the $xmlrpc_message object temporarily.
  571. *
  572. * @param $value
  573. * Object
  574. * @return
  575. * The most recently stored $xmlrpc_message
  576. */
  577. public function xmlrpc_message_set($value = null)
  578. {
  579. static $xmlrpc_message;
  580. if ($value) {
  581. $xmlrpc_message = $value;
  582. }
  583. return $xmlrpc_message;
  584. }
  585. public function xmlrpc_message_get()
  586. {
  587. return $this->xmlrpc_message_set();
  588. }
  589. public function xmlrpc_message_tag_open($parser, $tag, $attr)
  590. {
  591. $xmlrpc_message = $this->xmlrpc_message_get();
  592. $xmlrpc_message->current_tag_contents = '';
  593. $xmlrpc_message->last_open = $tag;
  594. switch ($tag) {
  595. case 'methodCall':
  596. case 'methodResponse':
  597. case 'fault':
  598. $xmlrpc_message->messagetype = $tag;
  599. break;
  600. // Deal with stacks of arrays and structs
  601. case 'data':
  602. $xmlrpc_message->array_structs_types[] = 'array';
  603. $xmlrpc_message->array_structs[] = array();
  604. break;
  605. case 'struct':
  606. $xmlrpc_message->array_structs_types[] = 'struct';
  607. $xmlrpc_message->array_structs[] = array();
  608. break;
  609. }
  610. $this->xmlrpc_message_set($xmlrpc_message);
  611. }
  612. public function xmlrpc_message_cdata($parser, $cdata)
  613. {
  614. $xmlrpc_message = $this->xmlrpc_message_get();
  615. $xmlrpc_message->current_tag_contents .= $cdata;
  616. $this->xmlrpc_message_set($xmlrpc_message);
  617. }
  618. public function xmlrpc_message_tag_close($parser, $tag)
  619. {
  620. $xmlrpc_message = $this->xmlrpc_message_get();
  621. $value_flag = false;
  622. switch ($tag) {
  623. case 'int':
  624. case 'i4':
  625. $value = (int)trim($xmlrpc_message->current_tag_contents);
  626. $value_flag = true;
  627. break;
  628. case 'double':
  629. $value = (double)trim($xmlrpc_message->current_tag_contents);
  630. $value_flag = true;
  631. break;
  632. case 'string':
  633. $value = $xmlrpc_message->current_tag_contents;
  634. $value_flag = true;
  635. break;
  636. case 'dateTime.iso8601':
  637. $value = xmlrpc_date(trim($xmlrpc_message->current_tag_contents));
  638. // $value = $iso->getTimestamp();
  639. $value_flag = true;
  640. break;
  641. case 'value':
  642. // If no type is indicated, the type is string
  643. // We take special care for empty values
  644. if (trim($xmlrpc_message->current_tag_contents) != '' || (isset($xmlrpc_message->last_open) && ($xmlrpc_message->last_open == 'value'))) {
  645. $value = (string)$xmlrpc_message->current_tag_contents;
  646. $value_flag = true;
  647. }
  648. unset($xmlrpc_message->last_open);
  649. break;
  650. case 'boolean':
  651. $value = (boolean)trim($xmlrpc_message->current_tag_contents);
  652. $value_flag = true;
  653. break;
  654. case 'base64':
  655. $value = base64_decode(trim($xmlrpc_message->current_tag_contents));
  656. $value_flag = true;
  657. break;
  658. // Deal with stacks of arrays and structs
  659. case 'data':
  660. case 'struct':
  661. $value = array_pop($xmlrpc_message->array_structs);
  662. array_pop($xmlrpc_message->array_structs_types);
  663. $value_flag = true;
  664. break;
  665. case 'member':
  666. array_pop($xmlrpc_message->current_struct_name);
  667. break;
  668. case 'name':
  669. $xmlrpc_message->current_struct_name[] = trim($xmlrpc_message->current_tag_contents);
  670. break;
  671. case 'methodName':
  672. $xmlrpc_message->methodname = trim($xmlrpc_message->current_tag_contents);
  673. break;
  674. }
  675. if ($value_flag) {
  676. if (count($xmlrpc_message->array_structs) > 0) {
  677. // Add value to struct or array
  678. if ($xmlrpc_message->array_structs_types[count($xmlrpc_message->array_structs_types) - 1] === 'struct') {
  679. // Add to struct
  680. $xmlrpc_message->array_structs[count($xmlrpc_message->array_structs) - 1][$xmlrpc_message->current_struct_name[count($xmlrpc_message->current_struct_name) - 1]] = $value;
  681. } else {
  682. // Add to array
  683. $xmlrpc_message->array_structs[count($xmlrpc_message->array_structs) - 1][] = $value;
  684. }
  685. } else {
  686. // Just add as a parameter
  687. $xmlrpc_message->params[] = $value;
  688. }
  689. }
  690. if (!in_array($tag, ['data', 'struct', 'member'])) {
  691. $xmlrpc_message->current_tag_contents = '';
  692. }
  693. $this->xmlrpc_message_set($xmlrpc_message);
  694. }
  695. /**
  696. * Construct an object representing an XML-RPC request
  697. *
  698. * @param $method
  699. * The name of the method to be called
  700. * @param $args
  701. * An array of parameters to send with the method.
  702. * @return
  703. * Object
  704. */
  705. public function xmlrpc_request($method, $args)
  706. {
  707. $xmlrpc_request = new stdClass();
  708. $xmlrpc_request->method = $method;
  709. $xmlrpc_request->args = $args;
  710. $xmlrpc_request->xml = <<<EOD
  711. <?xml version="1.0"?>
  712. <methodCall>
  713. <methodName>{$xmlrpc_request->method}</methodName>
  714. <params>
  715. EOD;
  716. foreach ($xmlrpc_request->args as $arg) {
  717. $xmlrpc_request->xml .= '<param><value>';
  718. $v = $this->xmlrpc_value($arg);
  719. $xmlrpc_request->xml .= $this->xmlrpc_value_get_xml($v);
  720. $xmlrpc_request->xml .= "</value></param>\n";
  721. }
  722. $xmlrpc_request->xml .= '</params></methodCall>';
  723. return $xmlrpc_request;
  724. }
  725. public function xmlrpc_error($code = null, $message = null, $reset = false)
  726. {
  727. static $xmlrpc_error;
  728. if (!is_null($code)) {
  729. $xmlrpc_error = new stdClass();
  730. $xmlrpc_error->is_error = true;
  731. $xmlrpc_error->code = $code;
  732. $xmlrpc_error->message = $message;
  733. } elseif ($reset) {
  734. $xmlrpc_error = null;
  735. }
  736. return $xmlrpc_error;
  737. }
  738. public function xmlrpc_error_get_xml($xmlrpc_error)
  739. {
  740. return <<<EOD
  741. <methodResponse>
  742. <fault>
  743. <value>
  744. <struct>
  745. <member>
  746. <name>faultCode</name>
  747. <value><int>{$xmlrpc_error->code}</int></value>
  748. </member>
  749. <member>
  750. <name>faultString</name>
  751. <value><string>{$xmlrpc_error->message}</string></value>
  752. </member>
  753. </struct>
  754. </value>
  755. </fault>
  756. </methodResponse>
  757. EOD;
  758. }
  759. public function xmlrpc_date($time)
  760. {
  761. $xmlrpc_date = new stdClass();
  762. $xmlrpc_date->is_date = true;
  763. // $time can be a PHP timestamp or an ISO one
  764. if (is_numeric($time)) {
  765. $xmlrpc_date->year = gmdate('Y', $time);
  766. $xmlrpc_date->month = gmdate('m', $time);
  767. $xmlrpc_date->day = gmdate('d', $time);
  768. $xmlrpc_date->hour = gmdate('H', $time);
  769. $xmlrpc_date->minute = gmdate('i', $time);
  770. $xmlrpc_date->second = gmdate('s', $time);
  771. $xmlrpc_date->iso8601 = gmdate('Ymd\TH:i:s', $time);
  772. } else {
  773. $xmlrpc_date->iso8601 = $time;
  774. $time = str_replace(array('-', ':'), '', $time);
  775. $xmlrpc_date->year = substr($time, 0, 4);
  776. $xmlrpc_date->month = substr($time, 4, 2);
  777. $xmlrpc_date->day = substr($time, 6, 2);
  778. $xmlrpc_date->hour = substr($time, 9, 2);
  779. $xmlrpc_date->minute = substr($time, 11, 2);
  780. $xmlrpc_date->second = substr($time, 13, 2);
  781. }
  782. return $xmlrpc_date;
  783. }
  784. public function xmlrpc_date_get_xml($xmlrpc_date)
  785. {
  786. return '<dateTime.iso8601>'
  787. . $xmlrpc_date->year
  788. . $xmlrpc_date->month
  789. . $xmlrpc_date->day
  790. . 'T' . $xmlrpc_date->hour
  791. . ':'. $xmlrpc_date->minute
  792. . ':'. $xmlrpc_date->second
  793. . '</dateTime.iso8601>';
  794. }
  795. public function xmlrpc_base64($data)
  796. {
  797. $xmlrpc_base64 = new stdClass();
  798. $xmlrpc_base64->is_base64 = true;
  799. $xmlrpc_base64->data = $data;
  800. return $xmlrpc_base64;
  801. }
  802. public function xmlrpc_base64_get_xml($xmlrpc_base64)
  803. {
  804. return '<base64>'. base64_encode($xmlrpc_base64->data) .'</base64>';
  805. }
  806. /**
  807. * Execute an XML remote procedural call. This is private function; call xmlrpc()
  808. * in common.inc instead of this function.
  809. *
  810. * @return
  811. * A $xmlrpc_message object if the call succeeded; FALSE if the call failed
  812. */
  813. public function _xmlrpc()
  814. {
  815. $args = func_get_args();
  816. $url = array_shift($args);
  817. $this->xmlrpc_clear_error();
  818. if (is_array($args[0])) {
  819. $method = 'system.multicall';
  820. $multicall_args = [];
  821. foreach ($args[0] as $call) {
  822. $multicall_args[] = [
  823. 'methodName' => array_shift($call),
  824. 'params' => $call,
  825. ];
  826. }
  827. $args = [$multicall_args];
  828. } else {
  829. $method = array_shift($args);
  830. }
  831. $xmlrpc_request = $this->xmlrpc_request($method, $args);
  832. $result = $this->http_request($url, [
  833. 'Content-Type' => 'text/xml',
  834. ], 'POST', $xmlrpc_request->xml);
  835. if ($result->code !== 200) {
  836. $this->xmlrpc_error($result->code, $result->error);
  837. return false;
  838. }
  839. $message = $this->xmlrpc_message($result->data);
  840. // Now parse what we've got back
  841. if (!$this->xmlrpc_message_parse($message)) {
  842. // XML error
  843. $this->xmlrpc_error(-32700, t('Parse error. Not well formed'));
  844. return false;
  845. }
  846. // Is the message a fault?
  847. if ($message->messagetype === 'fault') {
  848. $this->xmlrpc_error($message->fault_code, $message->fault_string);
  849. return false;
  850. }
  851. // Message must be OK
  852. return $message->params[0];
  853. }
  854. /**
  855. * Returns the last XML-RPC client error number
  856. */
  857. public function xmlrpc_errno()
  858. {
  859. return $this->xmlrpc_error()->code ?? null;
  860. }
  861. /**
  862. * Returns the last XML-RPC client error message
  863. */
  864. public function xmlrpc_error_msg()
  865. {
  866. return xmlrpc_error()->message ?? null;
  867. }
  868. /**
  869. * Clears any previous error.
  870. */
  871. public function xmlrpc_clear_error()
  872. {
  873. $this->xmlrpc_error(null, null, true);
  874. }
  875. }