MollomPlugin.php 31 KB

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