Rackspace.php 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423
  1. <?php
  2. namespace MGModule\DNSManager2\mgLibs\custom\dns\submodules;
  3. use \MGModule\DNSManager2\mgLibs\custom\dns;
  4. use \MGModule\DNSManager2\mgLibs\custom\dns\exceptions;
  5. use \MGModule\DNSManager2\mgLibs\custom\dns\interfaces;
  6. use \MGModule\DNSManager2\mgLibs\custom\dns\utils\Patterns;
  7. class Rackspace extends dns\SubmoduleAbstract implements interfaces\SubmoduleImportInterface, interfaces\SubmoduleTTLInterface {
  8. public $configFields = array(
  9. 'username' => array(
  10. 'friendlyName' => 'Username',
  11. 'validators' => array(
  12. 'required' => 'required',
  13. )
  14. ),
  15. 'apikey' => array(
  16. 'friendlyName' => 'API Access Key',
  17. 'type' => 'password',
  18. 'validators' => array(
  19. 'required' => 'required',
  20. )
  21. ),
  22. 'account_id' => array(
  23. 'friendlyName' => 'Account ID',
  24. 'validators' => array(
  25. 'required' => 'required',
  26. )
  27. ),
  28. 'endpoint' => array(
  29. 'friendlyName' => 'Account Is',
  30. 'type' => 'select',
  31. 'options' => array('US' => 'US-Based', 'UK' => 'UK-Based')
  32. ),
  33. 'default_ip' => array(
  34. 'friendlyName' => 'Default IP',
  35. 'validators' => array(
  36. 'pattern' => Patterns::IP4_OR_IP6,
  37. )
  38. ),
  39. );
  40. private $account_id;
  41. private $auth_token;
  42. private $api_end_point;
  43. private $auth_end_point;
  44. public $error;
  45. private $timeout = 10;
  46. public $results = array();
  47. const API_VERSION = '1.0';
  48. const US_AUTHURL = 'https://auth.api.rackspacecloud.com';
  49. const UK_AUTHURL = 'https://lon.auth.api.rackspacecloud.com';
  50. const UK_DNS_ENDPOINT = 'https://lon.dns.api.rackspacecloud.com';
  51. const US_DNS_ENDPOINT = 'https://dns.api.rackspacecloud.com';
  52. /** available records types **/
  53. public $availableTypes = array('A', 'AAAA', 'NS', 'MX', 'CNAME', 'TXT', 'SRV');
  54. public function login() {
  55. $auth_options = array (
  56. 'X-Auth-User: '.$this->config['username'],
  57. 'X-Auth-Key: '.$this->config['apikey']
  58. );
  59. $ch = curl_init ();
  60. $url = $this->auth_end_point . '/' . rawurlencode ( "v" . self::API_VERSION );
  61. curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
  62. curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
  63. curl_setopt($ch, CURLOPT_MAXREDIRS, 4);
  64. curl_setopt($ch, CURLOPT_HTTPHEADER, $auth_options);
  65. curl_setopt($ch, CURLOPT_HEADER, true);
  66. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  67. curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
  68. curl_setopt($ch, CURLOPT_URL, $url);
  69. $response = curl_exec ($ch);
  70. curl_close ($ch);
  71. preg_match ("/^HTTP\/1\.[01] (\d{3}) (.*)/", $response, $matches);
  72. if(isset($matches[1])){
  73. if($matches[1] == "204") {
  74. preg_match ( "/X-Server-Management-Url: (.*)/", $response, $matches );
  75. //$account = explode('/', trim($matches[1]));
  76. //$this->account_id = array_pop($account);
  77. $this->account_id = $this->config['account_id'];
  78. preg_match ("/X-Auth-Token: (.*)/", $response, $matches);
  79. $this->auth_token = trim($matches[1]);
  80. return true;
  81. }
  82. }
  83. throw new exceptions\DNSSubmoduleException($this->getErrorCodeDescription($matches[1]), dns\SubmoduleExceptionCodes::CONNECTION_PROBLEM);
  84. }
  85. public function testConnection(){
  86. return $this->login();
  87. }
  88. private function get($ch, $url_add) {
  89. $url = $this->api_end_point . '/' . rawurlencode ( "v" . self::API_VERSION ) . '/' . $this->account_id . $url_add;
  90. curl_setopt($ch, CURLOPT_URL, $url);
  91. curl_setopt($ch, CURLOPT_HEADER, 0);
  92. curl_setopt($ch, CURLOPT_USERAGENT, 'Rackspace DNS PHP Binding');
  93. curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);
  94. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  95. $json_response = curl_exec($ch);
  96. if (curl_errno($ch)) {
  97. throw new exceptions\DNSSubmoduleException("cURL Error: " . curl_errno($ch) . " - " . curl_error($ch), dns\SubmoduleExceptionCodes::CONNECTION_PROBLEM);
  98. }
  99. curl_close($ch);
  100. $response = json_decode($json_response, true);
  101. if(!empty($response['overLimit'])){
  102. throw new exceptions\DNSSubmoduleException('Rackspace requests limit reached. Check your account limits.', dns\SubmoduleExceptionCodes::REQUEST_LIMIT);
  103. }
  104. return $response;
  105. }
  106. private function sendGETRequest($get_params) {
  107. if(!$this->login())
  108. return false;
  109. $parts = explode('?', $get_params);
  110. $url = $parts[0] . ".json";
  111. if(isset($parts[1]))
  112. $url .= '?' . $parts[1];
  113. //$json_url = $this->api_end_point . '/' . rawurlencode ( "v" . self::API_VERSION ) . '/' . $this->account_id . $url;
  114. $ch = curl_init();
  115. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'GET');
  116. curl_setopt($ch, CURLOPT_HTTPGET, true );
  117. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  118. 'Accept: application/json',
  119. 'X-Auth-Token: '.$this->auth_token
  120. ));
  121. return $this->get($ch, $url);
  122. }
  123. private function sendPOSTRequest($post_params, $json_params) {
  124. if(!$this->login())
  125. return false;
  126. //$json_url = $this->api_end_point . '/' . rawurlencode ( "v" . self::API_VERSION ) . '/' . $this->account_id . $post_params;
  127. $ch = curl_init();
  128. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
  129. curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($json_params));
  130. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  131. 'Content-Type: application/json',
  132. 'Accept: application/json',
  133. 'X-Auth-Token: '.$this->auth_token
  134. ));
  135. return $this->get($ch, $post_params);
  136. }
  137. private function sendPUTRequest($put_params, $json_params) {
  138. if(!$this->login())
  139. return false;
  140. //$json_url = $this->api_end_point . '/' . rawurlencode ( "v" . self::API_VERSION ) . '/' . $this->account_id . $put_params;
  141. $json_data = json_encode($json_params);
  142. $ch = curl_init();
  143. curl_setopt($this->ch, CURLOPT_POST, true );
  144. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'PUT');
  145. curl_setopt($ch, CURLOPT_POSTFIELDS, $json_data);
  146. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  147. 'Content-Length: '.strlen($json_data),
  148. 'Content-Type: application/json',
  149. 'Accept: application/json',
  150. 'X-Auth-Token: '.$this->auth_token
  151. ));
  152. return $this->get($ch, $put_params);
  153. }
  154. private function sendDELETERequest($delete_params) {
  155. if(!$this->login())
  156. return false;
  157. $parts = explode('?', $delete_params);
  158. $url = $parts[0] . ".json";
  159. if(isset($parts[1]))
  160. $url .= '?' . $parts[1];
  161. //$json_url = $this->api_end_point . '/' . rawurlencode ( "v" . self::API_VERSION ) . '/' . $this->account_id . $url;
  162. $ch = curl_init();
  163. curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'DELETE');
  164. curl_setopt($ch, CURLOPT_HTTPHEADER, array(
  165. 'Accept: application/json',
  166. 'X-Auth-Token: '.$this->auth_token
  167. ));
  168. return $this->get($ch, $url);
  169. }
  170. public function setConfiguration($config) {
  171. parent::setConfiguration($config);
  172. $this->auth_end_point = $config['endpoint'] == 'US' ? self::US_AUTHURL : self::UK_AUTHURL;
  173. $this->api_end_point = $config['endpoint'] == 'US' ? self::US_DNS_ENDPOINT : self::UK_DNS_ENDPOINT;
  174. }
  175. public function zoneExists() {
  176. // $this->getDomainID();
  177. try {
  178. $ret = $this->sendGETRequest('/domains?name=' . rawurlencode($this->domain));
  179. } catch (exceptions\DNSSubmoduleException $e) {
  180. if($e->getCode() == dns\SubmoduleExceptionCodes::COMMAND_ERROR) {
  181. return false;
  182. }
  183. throw $e;
  184. }
  185. if($ret['totalEntries'] == 0)
  186. return false;
  187. else
  188. return true;
  189. }
  190. private function getDomainID() {
  191. $ret = $this->sendGETRequest('/domains?name=' . rawurlencode($this->domain));
  192. $id = $ret['domains'][0]['id'];
  193. if(empty($id)) {
  194. throw new exceptions\DNSSubmoduleException('Zone does not exist', dns\SubmoduleExceptionCodes::INVALID_RESPONSE);
  195. }
  196. return $id;
  197. }
  198. public function getRecords($recordType = false) {
  199. $id = $this->getDomainID();
  200. $ret = $this->sendGETRequest('/domains/'.$id.'/records');
  201. $out = array();
  202. foreach($ret['records'] as $r) {
  203. $type = strtoupper((string)$r['type']);
  204. if(in_array($type, $recordType!==false ? array(strtoupper($recordType)) : $this->getAvailableRecordTypes())) {
  205. $record = new dns\record\Record();
  206. $record->line = (string)$r['id'];
  207. $record->name = (string)$r['name'];
  208. $record->ttl = $r['ttl'];
  209. $record->type = $type;
  210. $record->createRDATAObject($type);
  211. switch($type) {
  212. case 'SRV': case 'MX':
  213. $record->rdata->fromString($r['priority'] . ' ' . $r['data']);
  214. break;
  215. case 'TXT':
  216. $record->rdata->setFirstProperty(html_entity_decode($r['data']));
  217. break;
  218. default:
  219. $record->rdata->setFirstProperty($r['data']);
  220. break;
  221. }
  222. $out[] = $record;
  223. }
  224. }
  225. return $out;
  226. }
  227. public function addRecord(dns\record\Record $record) {
  228. $id = $this->getDomainID();
  229. $input = $this->recordToInputArray($record);
  230. $json_data = array('records' => array($input));
  231. $url = '/domains/'.$id.'/records';
  232. return $this->callbackLoop($this->sendPOSTRequest($url, $json_data));
  233. }
  234. private function recordToInputArray($record) {
  235. switch($record->type) {
  236. case 'MX':
  237. $data = $record->rdata->exchange;
  238. $priority = $record->rdata->preference;
  239. break;
  240. case 'SRV':
  241. $priority = $record->rdata->priority;
  242. $data = $record->rdata->toString(array('weight' => '', 'port' => '', 'target' => ''));
  243. break;
  244. case 'TXT':
  245. $data = $record->rdata->toString(); //trim( . '"');
  246. break;
  247. default:
  248. $data = $record->rdata->toString();
  249. break;
  250. }
  251. $input = array(
  252. 'name' => $record->nameToAbsolute($this->domain, false),
  253. 'type' => $record->type,
  254. 'ttl' => $record->ttl,
  255. 'data' => $data
  256. );
  257. if(isset($priority)) {
  258. $input['priority'] = $priority;
  259. }
  260. return $input;
  261. }
  262. private function callbackLoop($ret) {
  263. $this->checkErrors($ret);
  264. $timeout = time() + 20;
  265. while(isset($ret['callbackUrl']) && $timeout > time()) {
  266. $this->callbacks [] = $ret;
  267. usleep(500000);
  268. $url = explode('status', $ret['callbackUrl']);
  269. $ret = $this->sendGETRequest('/status' . array_pop($url).'?showDetails=true');
  270. if(isset($ret['error'])) {
  271. throw new exceptions\DNSSubmoduleException($ret['error']['details'], dns\SubmoduleExceptionCodes::COMMAND_ERROR);
  272. }
  273. if($ret['status'] == 'COMPLETED') {
  274. break;
  275. }
  276. }
  277. if($ret['status'] == 'COMPLETED') {
  278. return true;
  279. }
  280. throw new exceptions\DNSSubmoduleException("Unknown Error", dns\SubmoduleExceptionCodes::COMMAND_ERROR);
  281. }
  282. public function editRecord(dns\record\Record $record) {
  283. $id = $this->getDomainID();
  284. $input = $this->recordToInputArray($record);
  285. $input['id'] = $record->line;
  286. $json_data = array('records' => array($input));
  287. $url = '/domains/'.$id.'/records';
  288. return $this->callbackLoop($this->sendPUTRequest($url, $json_data));
  289. }
  290. public function deleteRecord(dns\record\Record $record) {
  291. $id = $this->getDomainID();
  292. return $this->callbackLoop($this->sendDELETERequest('/domains/'.$id.'/records/'.$record->line));
  293. }
  294. public function activateZone() {
  295. if($this->zoneExists()) {
  296. throw new exceptions\DNSSubmoduleException("Zone already exist", dns\SubmoduleExceptionCodes::COMMAND_ERROR);
  297. }
  298. $json_data = array(
  299. 'domains' => array(
  300. array(
  301. 'name' => $this->domain,
  302. 'emailAddress' => 'sample@rackspace.com',
  303. 'recordsList' => array('records' => array())
  304. )
  305. )
  306. );
  307. return $this->callbackLoop($this->sendPOSTRequest('/domains', $json_data));
  308. }
  309. public function terminateZone() {
  310. $id = $this->getDomainID();
  311. return $this->callbackLoop($this->sendDELETERequest('/domains/'.$id.'?deleteSubdomains=true'));
  312. }
  313. private function getErrorCodeDescription($error_code = "0") {
  314. $errors = array (
  315. "400" => "Bad request",
  316. "401" => "Bad username or password",
  317. "403" => "Resize not allowed",
  318. "404" => "Item not found",
  319. "409" => "Item already exists",
  320. "413" => "Over API limit (check limits())",
  321. "415" => "Bad media type",
  322. "500" => "Cloud server issue",
  323. "503" => "API service in unavailable, or capacity is not available",
  324. "0" => "UNKNOWN ERROR"
  325. );
  326. return $errors[$error_code];
  327. }
  328. private function checkErrors($ret) {
  329. if($ret['code'] > 203 && isset($ret['message'])) {
  330. throw new exceptions\DNSSubmoduleException($ret['message'] . (isset($ret['details'])?' Details: ' . $ret['details']:''), dns\SubmoduleExceptionCodes::COMMAND_ERROR);
  331. }
  332. if(isset($ret['validationErrors']['messages']) && count($ret['validationErrors']['messages'])) {
  333. throw new exceptions\DNSSubmoduleException(implode('; ', $ret['validationErrors']['messages']), dns\SubmoduleExceptionCodes::COMMAND_ERROR);
  334. }
  335. }
  336. public function getZones($params = false) {
  337. $params = $params ? $params : '/domains';
  338. $ret = $this->sendGETRequest($params);
  339. $out = array();
  340. foreach($ret['domains'] as $domain) {
  341. $out[$domain['name']] = '';
  342. }
  343. $nextStep = $ret['links'][0];
  344. if($nextStep['rel'] == 'next')
  345. {
  346. $fullUrl = $nextStep['href'];
  347. list($base, $url) = explode($this->account_id, $fullUrl);
  348. $out += $this->getZones($url);
  349. }
  350. return $out;
  351. }
  352. }