modrestclient.class.php 9.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304
  1. <?php
  2. /*
  3. * This file is part of MODX Revolution.
  4. *
  5. * Copyright (c) MODX, LLC. All Rights Reserved.
  6. *
  7. * For complete copyright and license information, see the COPYRIGHT and LICENSE
  8. * files found in the top-level directory of this distribution.
  9. */
  10. /**
  11. * The basic REST client for handling REST requests
  12. *
  13. * @deprecated To be removed in 2.3. See modRest instead.
  14. *
  15. * @package modx
  16. * @subpackage rest
  17. */
  18. class modRestClient {
  19. /**
  20. * @const The path of the request
  21. */
  22. const OPT_PATH = 'path';
  23. /**
  24. * @const The port of the request
  25. */
  26. const OPT_PORT = 'port';
  27. /**
  28. * @const The response class to use when generating the response object
  29. */
  30. const OPT_RESPONSE_CLASS = 'restResponse.class';
  31. /**
  32. * @const The number of seconds before the request times out
  33. */
  34. const OPT_TIMEOUT = 'timeout';
  35. /**
  36. * @const The user-agent sent in the request
  37. */
  38. const OPT_USERAGENT = 'userAgent';
  39. /**
  40. * @const The user password to send with the request
  41. */
  42. const OPT_USERPWD = 'userpwd';
  43. /**
  44. * @const The authentication type for the request
  45. */
  46. const OPT_AUTHTYPE = 'authtype';
  47. /**
  48. * @var modX $modx A reference to the modX instance.
  49. * @access public
  50. */
  51. public $modx = null;
  52. /**
  53. * @var array $config The configuration array.
  54. * @access public
  55. */
  56. public $config = array();
  57. /**
  58. * @var modRestClient $conn The client connection instance to use.
  59. * @access public
  60. */
  61. public $conn = null;
  62. /**
  63. * @var modRestResponse $response The response object after a request is
  64. * made.
  65. * @access public
  66. */
  67. public $response = null;
  68. /**
  69. * @access public
  70. * @var string The expected response type
  71. */
  72. public $responseType = 'xml';
  73. /**
  74. * The current host to connect to
  75. * @var string $host
  76. */
  77. public $host;
  78. /**
  79. * The constructor for the modRestClient class. Assigns a modX instance
  80. * reference and sets up the basic config array.
  81. *
  82. * @param modX &$modx A reference to the modX instance.
  83. * @param array $config An array of configuration options.
  84. * @return modRestClient
  85. */
  86. function __construct(modX &$modx,array $config = array()) {
  87. $this->modx =& $modx;
  88. $this->config = array_merge(array(
  89. modRestClient::OPT_PORT => 80,
  90. modRestClient::OPT_TIMEOUT => 30,
  91. modRestClient::OPT_PATH => '/',
  92. modRestClient::OPT_USERAGENT => "Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.1; .NET CLR 1.0.3705; .NET CLR 1.1.4322; Media Center PC 4.0)"
  93. ),$config);
  94. $this->modx->deprecated('2.3.0', 'Use the modRest classes instead.');
  95. }
  96. /**
  97. * Get the connection class for the client. Defaults to cURL, then
  98. * fsockopen. If neither exists, returns false.
  99. *
  100. * @access public
  101. * @return boolean True if a connection can be made.
  102. */
  103. public function getConnection() {
  104. $className = false;
  105. if (function_exists('curl_init')) {
  106. $className = $this->modx->loadClass('rest.modRestCurlClient','',false,true);
  107. } else if (function_exists('fsockopen')) {
  108. $className = $this->modx->loadClass('rest.modRestSockClient','',false,true);
  109. }
  110. if (!empty($className)) {
  111. $this->conn = new $className($this->modx,$this->config);
  112. }
  113. return is_object($this->conn);
  114. }
  115. /**
  116. * Send a REST request
  117. *
  118. * @access public
  119. * @param string $host The host of the REST server.
  120. * @param string $path The path to request to on the REST server.
  121. * @param string $method The HTTP method to use for the request. May be GET,
  122. * PUT or POST.
  123. * @param array $params An array of parameters to send with the request.
  124. * @param array $options An array of options to pass to the request.
  125. * @return modRestResponse The response object.
  126. */
  127. public function request($host,$path,$method = 'GET',array $params = array(),array $options = array()) {
  128. if (!is_object($this->conn)) {
  129. $loaded = $this->getConnection();
  130. if (!$loaded) return false;
  131. }
  132. $this->host = $host;
  133. $response = $this->conn->request($this->host,$path,$method,$params,$options);
  134. $responseClass = $this->modx->getOption(modRestClient::OPT_RESPONSE_CLASS,$this->config,'modRestResponse');
  135. $this->response = new $responseClass($this,$response,$this->responseType);
  136. return $this->response;
  137. }
  138. /**
  139. * Sets the response type
  140. *
  141. * @param string $type The type to set, either json or xml
  142. */
  143. public function setResponseType($type) {
  144. $this->responseType = $type;
  145. }
  146. /**
  147. * Translates a SimpleXMLElement object into an array.
  148. *
  149. * @access public
  150. * @param SimpleXMLElement $obj
  151. * @param array &$arr The reference array to store the results in.
  152. * @return boolean True if successful.
  153. */
  154. public function xml2array($obj, &$arr) {
  155. if (!($obj instanceof SimpleXMLElement)) return false;
  156. $children = $obj->children();
  157. foreach ($children as $elementName => $node)
  158. {
  159. $nextIdx = count($arr);
  160. $arr[$nextIdx] = array();
  161. $arr[$nextIdx]['name'] = strtolower((string)$elementName);
  162. $arr[$nextIdx]['attributes'] = array();
  163. $attributes = $node->attributes();
  164. foreach ($attributes as $attributeName => $attributeValue) {
  165. $attribName = strtolower(trim((string)$attributeName));
  166. $attribVal = trim((string)$attributeValue);
  167. $arr[$nextIdx]['attributes'][$attribName] = $attribVal;
  168. }
  169. $text = (string)$node;
  170. $text = trim($text);
  171. if (strlen($text) > 0) {
  172. $arr[$nextIdx]['text'] = $text;
  173. }
  174. $arr[$nextIdx]['children'] = array();
  175. $this->xml2array($node, $arr[$nextIdx]['children']);
  176. }
  177. return true;
  178. }
  179. }
  180. /**
  181. * A class for handling REST responses
  182. *
  183. * @package modx
  184. * @subpackage rest
  185. */
  186. class modRestResponse {
  187. /**
  188. * @var string The raw response.
  189. */
  190. public $response;
  191. /**
  192. * @var string The type of response format
  193. */
  194. public $responseType = 'xml';
  195. /** @var SimpleXMLElement $xml */
  196. public $xml = null;
  197. /** @var string $json */
  198. public $json = null;
  199. /**
  200. * The constructor for the modRestResponse class.
  201. *
  202. * @param modRestClient &$client A reference to the modRestClient instance.
  203. * @param string $response The response from the REST server.
  204. * @param string $responseType The type of response, either xml or json
  205. * @return modRestResponse
  206. */
  207. function __construct(modRestClient &$client, $response, $responseType = 'xml') {
  208. $this->client =& $client;
  209. $this->response = (string)$response;
  210. $this->responseType = $responseType;
  211. if ($responseType == 'xml') {
  212. $this->toXml();
  213. } elseif ($responseType == 'json') {
  214. $this->fromJSON();
  215. }
  216. }
  217. /**
  218. * Translates the current response object to a SimpleXMLElement instance
  219. *
  220. * @access public
  221. * @return SimpleXMLElement
  222. */
  223. public function toXml() {
  224. if (!empty($this->xml) && $this->xml instanceof SimpleXMLElement) return $this->xml;
  225. try {
  226. $this->xml = simplexml_load_string($this->response);
  227. } catch (Exception $e) {
  228. $this->client->modx->log(xPDO::LOG_LEVEL_ERROR,'Could not parse XML response from provider: '.$this->response);
  229. }
  230. if (!$this->xml) {
  231. $this->client->modx->log(xPDO::LOG_LEVEL_ERROR,'Could not connect to provider at: '.$this->client->host);
  232. $this->xml = new SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><error><message>'.$this->client->modx->lexicon('provider_err_blank_response').'</message></error>');
  233. return $this->xml;
  234. }
  235. return $this->xml;
  236. }
  237. /**
  238. * Translates current response from JSON to an array
  239. *
  240. * @access public
  241. * @return array
  242. */
  243. public function fromJSON() {
  244. if (!empty($this->json)) return $this->json;
  245. $this->json = $this->client->modx->fromJSON($this->response);
  246. return $this->json;
  247. }
  248. /**
  249. * Checks to see whether or not the response is an error response
  250. *
  251. * @access public
  252. * @return boolean True if the response is an error
  253. */
  254. public function isError() {
  255. if ($this->responseType == 'xml') {
  256. $this->toXml();
  257. $isError = $this->xml->getName() == 'error';
  258. } elseif ($this->responseType = 'json') {
  259. $this->fromJSON();
  260. $isError = !empty($this->json['error']) ? true : false;
  261. } else {
  262. $isError = !empty($this->response);
  263. }
  264. return $isError;
  265. }
  266. /**
  267. * Returns an error message, if any.
  268. *
  269. * @access public
  270. * @return string The error message
  271. */
  272. public function getError() {
  273. $message = '';
  274. if ($this->responseType == 'xml') {
  275. if (empty($this->xml) || !($this->xml instanceof SimpleXMLElement)) {
  276. $message = '';
  277. } else {
  278. $message = (string)$this->xml->message;
  279. }
  280. } elseif ($this->responseType == 'json') {
  281. $this->fromJSON();
  282. $message = !empty($this->json['error']) && !empty($this->json['message']) ? $this->json['message'] : '';
  283. }
  284. return $message;
  285. }
  286. }