destinations.nodesquirrel.inc

Functions to handle the NodeSquirrel backup destination.

Functions

Namesort descending Description
nodesquirrel_check_secret_key Check that a nodesquirel key is valid.
nodesquirrel_get_activate_help_text Get a helper link to activate a site and create a tree.
nodesquirrel_get_activate_link Get a helper link to activate a site and create a tree.
nodesquirrel_get_destination Get the NS destination for the given key.
nodesquirrel_get_manage_link Get a helper link to activate a site and create a tree.
nodesquirrel_settings NodeSquirrel settings form.
nodesquirrel_settings_page The NodeSquirrel settings form page.

Constants

Classes

Namesort descending Description
backup_migrate_destination_nodesquirrel A destination for sending database backups to the NodeSquirel backup service.

File

modules/contrib/backup_migrate/includes/destinations.nodesquirrel.inc
View source
  1. <?php
  2. /**
  3. * @file
  4. * Functions to handle the NodeSquirrel backup destination.
  5. */
  6. define('NODESQUIRREL_SECRET_KEY_PATTERN', '/^[0-9a-f]{32}\:?[0-9a-f]{32}$/');
  7. /**
  8. * The NodeSquirrel settings form page.
  9. */
  10. function nodesquirrel_settings_page() {
  11. return drupal_get_form('nodesquirrel_settings');
  12. }
  13. /**
  14. * Check that a nodesquirel key is valid.
  15. */
  16. function nodesquirrel_check_secret_key($secret_key) {
  17. if ($destination = nodesquirrel_get_destination($secret_key)) {
  18. if ($destination->confirm_destination()) {
  19. return $destination;
  20. }
  21. }
  22. return FALSE;
  23. }
  24. /**
  25. * Get the NS destination for the given key.
  26. */
  27. function nodesquirrel_get_destination($secret_key) {
  28. if ($secret_key) {
  29. backup_migrate_include('destinations');
  30. $destination = backup_migrate_create_destination('nodesquirrel', array('destination_id' => 'nodesquirrel'));
  31. $destination->settings['secret_key'] = $secret_key;
  32. return $destination;
  33. }
  34. return NULL;
  35. }
  36. /**
  37. * Get a helper link to activate a site and create a tree.
  38. */
  39. function nodesquirrel_get_activate_help_text() {
  40. $activate_link = nodesquirrel_get_activate_link();
  41. return array(
  42. '#type' => 'item',
  43. '#title' => t('Need a Secret Key?'),
  44. '#markup' => t('Visit !nodesquirrel.', array('!nodesquirrel' => $activate_link)),
  45. '#description' => t('Don\'t worry if you don\'t have an account yet. You can create one when you get there.'),
  46. );
  47. }
  48. /**
  49. * Get a helper link to activate a site and create a tree.
  50. */
  51. function nodesquirrel_get_activate_link() {
  52. $activate_link = l('nodesquirrel.com/activate', variable_get('nodesquirrel_activate_url', 'http://manage.nodesquirrel.com/activate'), array('query' => array('url' => url('', array('absolute' => TRUE)), 'email' => variable_get('site_mail', ''), 'configure' => url($_GET['q'], array('absolute' => TRUE)))));
  53. return $activate_link;
  54. }
  55. /**
  56. * Get a helper link to activate a site and create a tree.
  57. */
  58. function nodesquirrel_get_manage_link($destination) {
  59. $url = variable_get('nodesquirrel_manage_url', 'http://manage.nodesquirrel.com') . '/backups/' . $destination->_get_destination();
  60. return l($url, $url);
  61. }
  62. /**
  63. * NodeSquirrel settings form.
  64. */
  65. function nodesquirrel_settings($form_state) {
  66. _backup_migrate_message_callback('_backup_migrate_message_browser');
  67. $form = array();
  68. $key = variable_get('nodesquirrel_secret_key', '');
  69. $destination = nodesquirrel_check_secret_key($key);
  70. $form['intro'] = array(
  71. '#type' => 'markup',
  72. '#markup' => t('<p>For better protection, back your site up regularly to a location not on your web server. !nodesquirrel is the cloud backup service built by the maintainers of Backup and Migrate. You can also !add such as FTP or Amazon S3. Additional 3rd party options are available and many are listed on the !bam.', array('!nodesquirrel' => l(t('NodeSquirrel'), 'http://nodesquirrel.com'), '!add' => l(t('add other offsite destinations'), BACKUP_MIGRATE_MENU_PATH . '/destination/list/add'), '!bam' => l(t('Backup and Migrate project page'), 'http://drupal.org/project/backup_migrate'))),
  73. );
  74. $form['nodesquirrel_status'] = array(
  75. '#type' => 'fieldset',
  76. '#title' => t('NodeSquirrel Status'),
  77. );
  78. $form['nodesquirrel_status']['status'] = array(
  79. '#type' => 'item',
  80. '#title' => t('NodeSquirrel Status'),
  81. '#markup' => t('Not Configured'),
  82. );
  83. // Warn the user if the key they entered is invalid.
  84. if ($key && empty($destination)) {
  85. $form['nodesquirrel_status']['status']['#value'] = t('Your secret key does not seem to be valid. Please check that you entered it correctly or visit !ns to generate a new key.', array('!ns' => nodesquirrel_get_activate_link()));
  86. }
  87. else if (!empty($destination)) {
  88. $form['nodesquirrel_status']['manage'] = array(
  89. '#type' => 'item',
  90. '#title' => t('Management Console'),
  91. '#markup' => nodesquirrel_get_manage_link($destination),
  92. '#description' => t('You can use the NodeSquirrel management console to add and edit your sites, reset your secret key, download and delete backups, and modify your NodeSquirrel account.'),
  93. );
  94. $form['nodesquirrel_status']['status']['#markup'] = t('Ready to Backup');
  95. if (user_access('perform backup')) {
  96. $form['nodesquirrel_status']['status']['#markup'] .= ' ' . l('(' . t('backup now') . ')', BACKUP_MIGRATE_MENU_PATH);
  97. }
  98. }
  99. $form['nodesquirrel_credentials'] = array(
  100. '#type' => 'fieldset',
  101. '#title' => t('NodeSquirrel Credentials'),
  102. );
  103. $form['nodesquirrel_credentials']['nodesquirrel_secret_key'] = array(
  104. '#type' => 'textfield',
  105. '#title' => t('Secret Key'),
  106. '#size' => 80,
  107. '#default_value' => variable_get('nodesquirrel_secret_key', ''),
  108. );
  109. if (empty($destination)) {
  110. $form['nodesquirrel_credentials']['secret_key_help'] = nodesquirrel_get_activate_help_text();
  111. }
  112. // If the schedule has been overriden it must be edited in the schedule tab.
  113. backup_migrate_include('crud');
  114. $item = backup_migrate_crud_get_item('schedule', 'nodesquirrel');
  115. if ($item && $item->storage == BACKUP_MIGRATE_STORAGE_OVERRIDEN) {
  116. $form['nodesquirrel_schedule']['#options'] = array('' => t('- Overriden -'));
  117. $form['nodesquirrel_schedule']['#disabled'] = TRUE;
  118. $form['nodesquirrel_schedule']['#description'] = t('Your NodeSquirrel schedule has been overriden and must be edited in the !schedule.', array('!schedule' => l(t('Schedules tab'), BACKUP_MIGRATE_MENU_PATH . '/schedule/list/edit/nodesquirrel')));
  119. }
  120. return system_settings_form($form);
  121. }
  122. /**
  123. * A destination for sending database backups to the NodeSquirel backup service.
  124. *
  125. * @ingroup backup_migrate_destinations
  126. */
  127. class backup_migrate_destination_nodesquirrel extends backup_migrate_destination {
  128. var $supported_ops = array('scheduled backup', 'manual backup', 'restore', 'list files', 'configure', 'delete');
  129. var $cache_files = TRUE;
  130. // Don't generate a metadata file as NodeSquirrel can save metadata natively.
  131. var $save_metadata = FALSE;
  132. /**
  133. * Get the destination name. Provide a default.
  134. */
  135. function get_name() {
  136. if (empty($this->name)) {
  137. return t('NodeSquirrel');
  138. }
  139. return $this->name;
  140. }
  141. /**
  142. * Save to the NodeSquirrel destination.
  143. */
  144. function save_file($file, $settings) {
  145. if ($destination = $this->_get_destination()) {
  146. srand((double)microtime()*1000000);
  147. $filename = $file->filename();
  148. $filesize = filesize($file->filepath());
  149. $ticket = $this->_xmlrpc('backups.getUploadTicket', array($destination, $filename, $filesize, $file->file_info));
  150. if ($ticket) {
  151. $url = $ticket['url'];
  152. // If the ticket requires authentication add our username/password to the url.
  153. if (!empty($ticket['auth']) && $ticket['auth'] = 'basic') {
  154. $parts = parse_url($ticket['url']);
  155. list($parts['user'], $parts['pass']) = $this->get_user_pass();
  156. $url = $this->glue_url($parts, FALSE);
  157. }
  158. $out = $this->_post_file($url, 'POST', $ticket['params'], $file);
  159. if ($out->code == 200) {
  160. // Confirm the upload.
  161. $confirm = $this->_xmlrpc('backups.confirmUpload', array($destination, $filename, $filesize));
  162. if ($confirm['success']) {
  163. // Set a message with a link to the manage console.
  164. $url = variable_get('nodesquirrel_manage_url', 'http://manage.nodesquirrel.com') . '/backups/' . $this->_get_destination();
  165. _backup_migrate_message('Your backup has been saved to your NodeSquirrel account. View it at !account', array('!account' => l($url, $url)));
  166. return $file;
  167. }
  168. else {
  169. _backup_migrate_message('The backup file never made it to the NodeSquirrel backup server. There may have been a network problem. Please try again later');
  170. }
  171. }
  172. else {
  173. $error = !empty($out->headers['x-bams-error']) ? $out->headers['x-bams-error'] : $out->error;
  174. _backup_migrate_message('The NodeSquirrel server returned the following error: %err', array('%err' => $error), 'error');
  175. }
  176. }
  177. else if ($err = xmlrpc_error()) {
  178. // XMLRPC errors are already handled by the server function below.
  179. }
  180. else {
  181. _backup_migrate_message('The NodeSquirrel server refused the backup but did not specify why. Maybe the server is down.');
  182. }
  183. }
  184. return NULL;
  185. }
  186. /**
  187. * Load from the NodeSquirrel destination.
  188. */
  189. function load_file($file_id) {
  190. if ($destination = $this->_get_destination()) {
  191. backup_migrate_include('files');
  192. $file = new backup_file(array('filename' => $file_id));
  193. $ticket = $this->_xmlrpc('backups.getDownloadTicket', array($destination, $file_id));
  194. if ($ticket && $url = $ticket['url']) {
  195. // If the ticket requires authentication add our username/password to the url.
  196. if (!empty($ticket['auth']) && $ticket['auth'] = 'basic') {
  197. $parts = parse_url($ticket['url']);
  198. $parts['user'] = @$this->dest_url['user'];
  199. $parts['pass'] = @$this->dest_url['pass'];
  200. $url = $this->glue_url($parts, FALSE);
  201. }
  202. $out = drupal_http_request($url);
  203. if ($out->code == 200) {
  204. file_put_contents($file->filepath(), $out->data);
  205. return $file;
  206. }
  207. else {
  208. $error = !empty($out->headers['x-bams-error']) ? $out->headers['x-bams-error'] : $out->error;
  209. _backup_migrate_message('The server returned the following error: %err', array('%err' => $error), 'error');
  210. }
  211. }
  212. }
  213. return NULL;
  214. }
  215. /**
  216. * Delete from the NodeSquirrel destination.
  217. */
  218. function delete_file($file_id) {
  219. if ($destination = $this->_get_destination()) {
  220. $result = $this->_xmlrpc('backups.deleteFile', array($destination, $file_id));
  221. }
  222. }
  223. /**
  224. * List the files in the remote destination.
  225. */
  226. function _list_files() {
  227. $files = array();
  228. backup_migrate_include('files');
  229. if ($destination = $this->_get_destination()) {
  230. $file_list = $this->_xmlrpc('backups.listFiles', array($destination));
  231. foreach ((array)$file_list as $file) {
  232. $files[$file['filename']] = new backup_file($file);
  233. }
  234. }
  235. return $files;
  236. }
  237. /**
  238. * List the files in the remote destination.
  239. */
  240. function check_limits() {
  241. if (empty($this->limits)) {
  242. $this->limits = $this->_xmlrpc('backups.getLimits', array($this->_get_destination()));
  243. }
  244. return $this->limits;
  245. }
  246. /**
  247. * Check that a destination is valid.
  248. */
  249. function confirm_destination() {
  250. return $this->check_limits();
  251. }
  252. /**
  253. * Get the form for the settings for this destination.
  254. */
  255. function edit_form() {
  256. $form = parent::edit_form();
  257. $form['settings'] = array('#tree' => TRUE);
  258. $activate_link = l('nodesquirrel.com/activate', variable_get('nodesquirrel_activate_url', 'http://manage.nodesquirrel.com/activate'), array('query' => array('url' => url('', array('absolute' => TRUE)), 'email' => variable_get('site_mail', ''), 'configure' => url($_GET['q'], array('absolute' => TRUE)))));
  259. // Retrieve the key from the settings or get it from the get string if this is an auto-config action.
  260. $key = $this->settings('secret_key');
  261. if (!empty($_GET['key']) && preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $_GET['key'])) {
  262. $key = $_GET['key'];
  263. }
  264. $form['settings']['secret_key'] = array(
  265. '#type' => 'textfield',
  266. '#title' => t('Secret Key'),
  267. '#default_value' => $key,
  268. );
  269. $form['settings']['location'] = array('#type' => 'value', '#value' => '');
  270. $form['settings']['secret_key_help'] = array(
  271. '#type' => 'item',
  272. '#title' => t('Need a Secret Key?'),
  273. '#markup' => t('Visit !nodesquirrel.', array('!nodesquirrel' => $activate_link)),
  274. );
  275. return $form;
  276. }
  277. /**
  278. * Submit the configuration form. Glue the url together and add the old password back if a new one was not specified.
  279. */
  280. function edit_form_validate($form, &$form_state) {
  281. $key = trim($form_state['values']['settings']['secret_key']);
  282. if ($key) {
  283. if (!preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $key)) {
  284. form_set_error('secret_key', 'The secret key you entered is not the right format. Please make sure you copy it exactly.');
  285. return;
  286. }
  287. $this->settings['secret_key'] = check_plain($key);
  288. $limits = $this->check_limits();
  289. if (!$limits) {
  290. $err = xmlrpc_error();
  291. if (!empty($err->code) && $err->code == '401') {
  292. form_set_error('user', 'Could not login to server. Please check that your secret key is correct.');
  293. }
  294. else {
  295. form_set_error('', 'There was an error retrieving the specified site. Please check that your secret key is correct.');
  296. }
  297. }
  298. }
  299. }
  300. /**
  301. * Submit the configuration form. Glue the url together and add the old password back if a new one was not specified.
  302. */
  303. function edit_form_submit($form, &$form_state) {
  304. $form_state['values']['secret_key'] = check_plain($form_state['values']['settings']['secret_key']);
  305. parent::edit_form_submit($form, $form_state);
  306. }
  307. /**
  308. * Get the destination id or warn the user that it has not been set.
  309. */
  310. function _get_destination($warn = TRUE) {
  311. list($id, $key) = $this->get_user_pass();
  312. return $id;
  313. }
  314. /**
  315. * Get the destination id or warn the user that it has not been set.
  316. */
  317. function _get_private_key($warn = TRUE) {
  318. list($id, $key) = $this->get_user_pass();
  319. return $key;
  320. }
  321. /**
  322. * Break the secret key into the public/private key (user/pass).
  323. */
  324. function get_user_pass() {
  325. $key = $this->settings('secret_key');
  326. // The username is the first 32 chars.
  327. $user = substr($key, 0, 32);
  328. // The pass is the last 32 chars. There may be a separating character.
  329. $pass = substr($key, strlen($key) - 32);
  330. return array($user, $pass);
  331. }
  332. function get_display_location() {
  333. return t('NodeSquirrel.com');
  334. }
  335. function add_scheme($url) {
  336. return 'http://' . $url;
  337. }
  338. /**
  339. * Get the form for the settings for this destination.
  340. */
  341. function _xmlrpc($method, $args = array()) {
  342. // Retrieve the severs or read them from a stored variable.
  343. $servers = $this->_get_endpoints();
  344. // Do the actual call.
  345. return $this->__xmlrpc($method, $args, $servers);
  346. }
  347. /**
  348. * Get the form for the settings for this destination.
  349. */
  350. function __xmlrpc($method, $args, $servers, $retry = 3) {
  351. if ($servers && --$retry > 0) {
  352. // Add the key authentication arguments if we can.
  353. if ($this->_sign_request($args)) {
  354. $url = reset($servers);
  355. // Try each available server in order.
  356. while ($url) {
  357. $url = $this->add_scheme($url);
  358. $out = xmlrpc($url, array($method => $args));
  359. // Check for errors.
  360. $err = xmlrpc_error();
  361. if ($err && $err->is_error) {
  362. switch ($err->code) {
  363. case '500':
  364. case '503':
  365. case '404':
  366. // Some sort of server error. Try the next one.
  367. $url = next($servers);
  368. // If we're at the end of the line then try refetching the urls
  369. if (!$url) {
  370. $servers = $this->_get_endpoints(TRUE, $retry);
  371. return $this->__xmlrpc($method, $args, $servers, $retry);
  372. }
  373. break;
  374. case '300':
  375. // 'Multiple Choices' means that the existing server list needs to be refreshed.
  376. $servers = $this->_get_endpoints(TRUE, $retry);
  377. return $this->__xmlrpc($method, $args, $servers, $retry);
  378. break;
  379. case '401':
  380. case '403':
  381. // Authentication failed.
  382. _backup_migrate_message('Couldn\'t log in to NodeSquirrel. The server error was: %err', array('%err' => $err->message), 'error');
  383. return FALSE;
  384. break;
  385. default:
  386. // Some sort of client error. Don't try the next server because it'll probably say the same thing.
  387. _backup_migrate_message('The NodeSquirrel server returned the following error: %err', array('%err' => $err->message), 'error');
  388. return FALSE;
  389. break;
  390. }
  391. }
  392. // No error, return the result.
  393. else {
  394. return $out;
  395. }
  396. }
  397. }
  398. }
  399. }
  400. /**
  401. * Genrate a hash with a given secret key, timestamp and random value.
  402. */
  403. function _get_hash($time, $nonce) {
  404. if ($private_key = $this->_get_private_key()) {
  405. $message = $time . ':' . $nonce . ':' . $private_key;
  406. // Use HMAC-SHA1 to authenticate the call.
  407. $hash = base64_encode(
  408. pack('H*', sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
  409. pack('H*', sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x36), 64))) .
  410. $message))))
  411. );
  412. return $hash;
  413. }
  414. _backup_migrate_message('You must enter a valid private key to use NodeSquirrel.', array(), 'error');
  415. return FALSE;
  416. }
  417. /**
  418. * Genrate a hash with a given secret key, timestamp and random value.
  419. */
  420. function _sign_request(&$args) {
  421. $nonce = md5(mt_rand());
  422. $time = time();
  423. $hash = $this->_get_hash($time, $nonce);
  424. if ($hash) {
  425. array_unshift($args, $nonce);
  426. array_unshift($args, $time);
  427. array_unshift($args, $hash);
  428. return TRUE;
  429. }
  430. else {
  431. return FALSE;
  432. }
  433. }
  434. /**
  435. * Retrieve the list of servers.
  436. */
  437. function _get_endpoints($refresh = FALSE, $retry = 3) {
  438. $servers = (array)variable_get('nodesquirrel_endpoint_urls', array());
  439. // No servers saved or a force refreshr required.
  440. if ($refresh || empty($servers)) {
  441. $servers = array_unique(array_merge($servers, variable_get('nodesquirrel_default_endpoint_urls', array('api.nodesquirrel.com/services/xmlrpc'))));
  442. // Call the get endpoints method but use the default or previous servers to avoid infinite loops.
  443. $new_servers = $this->__xmlrpc('backups.getEndpoints', array($this->_get_destination(), 'xmlrpc'), $servers, $retry);
  444. if ($new_servers) {
  445. variable_set('nodesquirrel_endpoint_urls', $new_servers);
  446. $servers = $new_servers;
  447. }
  448. }
  449. return $servers;
  450. }
  451. /**
  452. * Post a file via http.
  453. *
  454. * This looks a lot like a clone of drupal_http_request but it can post a large
  455. * file without reading the whole file into memory.
  456. */
  457. function _post_file($url, $method = 'GET', $params = array(), $file = NULL, $retry = 3) {
  458. global $db_prefix;
  459. $result = new stdClass();
  460. // Parse the URL and make sure we can handle the schema.
  461. $uri = parse_url($url);
  462. if ($uri == FALSE) {
  463. $result->error = 'unable to parse URL';
  464. $result->code = -1001;
  465. return $result;
  466. }
  467. if (!isset($uri['scheme'])) {
  468. $result->error = 'missing schema';
  469. $result->code = -1002;
  470. return $result;
  471. }
  472. switch ($uri['scheme']) {
  473. case 'http':
  474. case 'feed':
  475. $port = isset($uri['port']) ? $uri['port'] : 80;
  476. $host = $uri['host'] . ($port != 80 ? ':'. $port : '');
  477. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
  478. break;
  479. case 'https':
  480. // Note: Only works for PHP 4.3 compiled with OpenSSL.
  481. $port = isset($uri['port']) ? $uri['port'] : 443;
  482. $host = $uri['host'] . ($port != 443 ? ':'. $port : '');
  483. $fp = @fsockopen('ssl://'. $uri['host'], $port, $errno, $errstr, 20);
  484. break;
  485. default:
  486. $result->error = 'invalid schema '. $uri['scheme'];
  487. $result->code = -1003;
  488. return $result;
  489. }
  490. // Make sure the socket opened properly.
  491. if (!$fp) {
  492. // When a network error occurs, we use a negative number so it does not
  493. // clash with the HTTP status codes.
  494. $result->code = -$errno;
  495. $result->error = trim($errstr);
  496. // Mark that this request failed. This will trigger a check of the web
  497. // server's ability to make outgoing HTTP requests the next time that
  498. // requirements checking is performed.
  499. // @see system_requirements()
  500. variable_set('drupal_http_request_fails', TRUE);
  501. return $result;
  502. }
  503. // Construct the path to act on.
  504. $path = isset($uri['path']) ? $uri['path'] : '/';
  505. if (isset($uri['query'])) {
  506. $path .= '?'. $uri['query'];
  507. }
  508. // Prepare the data payload.
  509. $boundary = '---------------------------'. substr(md5(rand(0,32000)),0,10);
  510. $data_footer = "\r\n--$boundary--\r\n";
  511. $data_header = '';
  512. foreach ($params as $key => $value) {
  513. $data_header .="--$boundary\r\n";
  514. $data_header .= "Content-Disposition: form-data; name=\"".$key."\"\r\n";
  515. $data_header .= "\r\n".$value."\r\n";
  516. $data_header .="--$boundary\r\n";
  517. }
  518. // Add the file header to the post payload.
  519. $data_header .="--$boundary\r\n";
  520. $data_header .= "Content-Disposition: form-data; name=\"file\"; filename=\"". $file->filename() ."\"\r\n";
  521. $data_header .= "Content-Type: application/octet-stream;\r\n";
  522. $data_header .= "\r\n";
  523. // Calculate the content length.
  524. $content_length = strlen($data_header . $data_footer) + filesize($file->filepath());
  525. //file_get_contents($file->filepath()));
  526. // Create HTTP request.
  527. $defaults = array(
  528. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  529. // We don't add the port to prevent from breaking rewrite rules checking the
  530. // host that do not take into account the port number.
  531. 'Host' => "Host: $host",
  532. 'Content-type' => "Content-type: multipart/form-data, boundary=$boundary",
  533. 'User-Agent' => 'User-Agent: NodeSquirrel Client/1.x (+http://www.nodesquirrel.com) (Drupal '. VERSION .'; Backup and Migrate 2.x)',
  534. 'Content-Length' => 'Content-Length: '. $content_length
  535. );
  536. // If the server url has a user then attempt to use basic authentication
  537. if (isset($uri['user'])) {
  538. $defaults['Authorization'] = 'Authorization: Basic '. base64_encode($uri['user'] . (!empty($uri['pass']) ? ":". $uri['pass'] : ''));
  539. }
  540. $request = $method .' '. $path ." HTTP/1.0\r\n";
  541. $request .= implode("\r\n", $defaults);
  542. $request .= "\r\n\r\n";
  543. $result->request = $request;
  544. // Write the headers and start of the headers
  545. fwrite($fp, $request);
  546. fwrite($fp, $data_header);
  547. // Copy the file 512k at a time to prevent memory issues.
  548. if ($fp_in = fopen($file->filepath(), 'rb')) {
  549. while (!feof($fp_in)) {
  550. fwrite($fp, fread($fp_in, 1024 * 512));
  551. }
  552. $success = TRUE;
  553. }
  554. @fclose($fp_in);
  555. // Finish the write.
  556. fwrite($fp, $data_footer);
  557. // Fetch response.
  558. $response = '';
  559. while (!feof($fp) && $chunk = fread($fp, 1024)) {
  560. $response .= $chunk;
  561. }
  562. fclose($fp);
  563. // Parse response.
  564. list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  565. $split = preg_split("/\r\n|\n|\r/", $split);
  566. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  567. $result->protocol = $protocol;
  568. $result->status_message = $status_message;
  569. $result->headers = array();
  570. // Parse headers.
  571. while ($line = trim(array_shift($split))) {
  572. list($header, $value) = explode(':', $line, 2);
  573. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  574. // RFC 2109: the Set-Cookie response header comprises the token Set-
  575. // Cookie:, followed by a comma-separated list of one or more cookies.
  576. $result->headers[$header] .= ','. trim($value);
  577. }
  578. else {
  579. $result->headers[$header] = trim($value);
  580. }
  581. }
  582. $responses = array(
  583. 100 => 'Continue', 101 => 'Switching Protocols',
  584. 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content',
  585. 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 307 => 'Temporary Redirect',
  586. 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',
  587. 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Time-out', 505 => 'HTTP Version not supported'
  588. );
  589. // RFC 2616 states that all unknown HTTP codes must be treated the same as the
  590. // base code in their class.
  591. if (!isset($responses[$code])) {
  592. $code = floor($code / 100) * 100;
  593. }
  594. switch ($code) {
  595. case 200: // OK
  596. case 304: // Not modified
  597. break;
  598. case 301: // Moved permanently
  599. case 302: // Moved temporarily
  600. case 307: // Moved temporarily
  601. $location = $result->headers['Location'];
  602. if ($retry) {
  603. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  604. $result->redirect_code = $result->code;
  605. }
  606. $result->redirect_url = $location;
  607. break;
  608. default:
  609. $result->error = $status_message;
  610. }
  611. $result->code = $code;
  612. return $result;
  613. }
  614. }