destinations.nodesquirrel.inc 26 KB

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