destinations.nodesquirrel.inc 38 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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. * Checks that a nodesquirel key is valid.
  9. */
  10. function backup_migrate_nodesquirrel_check_secret_key($secret_key) {
  11. if ($destination = backup_migrate_nodesquirrel_get_destination($secret_key)) {
  12. if ($destination->confirm_destination()) {
  13. return $destination;
  14. }
  15. }
  16. return FALSE;
  17. }
  18. /**
  19. * Gets the NS destination for the given key.
  20. */
  21. function backup_migrate_nodesquirrel_get_destination($secret_key) {
  22. if ($secret_key) {
  23. backup_migrate_include('destinations');
  24. $destination = backup_migrate_create_destination('nodesquirrel', array('machine_name' => 'nodesquirrel'));
  25. $destination->settings['secret_key'] = $secret_key;
  26. return $destination;
  27. }
  28. return NULL;
  29. }
  30. /**
  31. * Gets a helper link to activate a site and create a tree.
  32. */
  33. function backup_migrate_nodesquirrel_get_activate_help_text() {
  34. $activate_link = backup_migrate_nodesquirrel_get_activate_link();
  35. return array(
  36. '#type' => 'item',
  37. '#title' => t('Need a Secret Key?'),
  38. '#markup' => t('Visit !nodesquirrel.', array('!nodesquirrel' => $activate_link)),
  39. '#description' => t("Don't worry if you don't have an account yet. You can create one when you get there."),
  40. );
  41. }
  42. /**
  43. * Gets a helper link to activate a site and create a tree.
  44. */
  45. function backup_migrate_nodesquirrel_get_activate_link() {
  46. $activate_link = l('nodesquirrel.com/activate', variable_get('nodesquirrel_activate_url', 'https://manage.nodesquirrel.com/activate'), array(
  47. 'query' => array(
  48. 'url' => url('', array('absolute' => TRUE)),
  49. 'email' => variable_get('site_mail', ''),
  50. 'configure' => url($_GET['q'], array('absolute' => TRUE)),
  51. ),
  52. ));
  53. return $activate_link;
  54. }
  55. /**
  56. * Gets a helper link to activate a site and create a tree.
  57. */
  58. function backup_migrate_nodesquirrel_get_manage_link($destination) {
  59. $url = variable_get('nodesquirrel_manage_url', 'https://manage.nodesquirrel.com') . '/backups/' . $destination->_get_destination();
  60. return l($url, $url);
  61. }
  62. /**
  63. * Gets a helper link to activate a site and create a tree.
  64. */
  65. function backup_migrate_nodesquirrel_get_plan_link() {
  66. $url = variable_get('nodesquirrel_manage_url', 'https://manage.nodesquirrel.com') . '/plan';
  67. return l($url, $url);
  68. }
  69. /**
  70. * Gets the path to the nodesquirrel settings tab.
  71. */
  72. function backup_migrate_nodesquirrel_settings_path() {
  73. $path = BACKUP_MIGRATE_MENU_PATH . '/settings/destinations/nodesquirrel/edit';
  74. return $path;
  75. }
  76. /**
  77. * NodeSquirrel settings page callback.
  78. */
  79. function backup_migrate_nodesquirrel_settings() {
  80. return drupal_get_form('backup_migrate_nodesquirrel_settings_form');
  81. }
  82. /**
  83. * NodeSquirrel settings form.
  84. */
  85. function backup_migrate_nodesquirrel_credentials_settings_form($key = '', $status) {
  86. $collapse = !empty($status);
  87. $form['nodesquirrel_credentials'] = array(
  88. '#type' => 'fieldset',
  89. '#title' => t('NodeSquirrel Credentials'),
  90. '#collapsible' => $collapse,
  91. '#collapsed' => $collapse,
  92. );
  93. $form['nodesquirrel_credentials']['nodesquirrel_secret_key'] = array(
  94. '#type' => 'textfield',
  95. '#title' => t('Secret Key'),
  96. '#size' => 80,
  97. '#default_value' => $key,
  98. );
  99. if (empty($key)) {
  100. $form['nodesquirrel_credentials']['secret_key_help'] = backup_migrate_nodesquirrel_get_activate_help_text();
  101. }
  102. $form['nodesquirrel_credentials']['nodesquirrel_failover'] = array(
  103. '#type' => 'checkbox',
  104. '#title' => t('Connection failover by disabling SSL certification validation'),
  105. '#description' => t("If normal connections to NodeSquirrel fail due incompatibility between this server's PHP installation and the destination server, use this option to disable validating the destination's SSL certificate.<br />Note: <em>this has security implications</em> and should be the last option taken; it probably would be safer to update the server's PHP."),
  106. '#default_value' => variable_get('nodesquirrel_failover', FALSE),
  107. );
  108. return $form;
  109. }
  110. /**
  111. * Return a form element with some help text describing NodeSquirrel.
  112. */
  113. function backup_migrate_nodesquirrel_info_form() {
  114. $form = array();
  115. $form['nodesquirrel_info'] = array(
  116. '#type' => 'fieldset',
  117. '#title' => t('What is NodeSquirrel?'),
  118. );
  119. $form['nodesquirrel_info']['intro'] = array(
  120. '#type' => 'markup',
  121. '#markup' => t('<p>NodeSquirrel is the cloud backup service built by the maintainers of Backup and Migrate.</p></p>NodeSquirrel is now free for all Drupal sites, courtesy of Pantheon.</p><p>Create your free account at !signup</p>', array(
  122. '!nodesquirrel' => l('nodesquirrel.com', 'http://www.nodesquirrel.com'),
  123. '!signup' => backup_migrate_nodesquirrel_get_activate_link(),
  124. )),
  125. );
  126. return $form;
  127. }
  128. /**
  129. * Display the NodeSquirrel status on the configuration form.
  130. */
  131. function backup_migrate_nodesquirrel_status_form($key, $destination, $status) {
  132. $form = array();
  133. $form['nodesquirrel_status'] = array(
  134. '#type' => 'fieldset',
  135. '#title' => t('NodeSquirrel Status'),
  136. );
  137. $form['nodesquirrel_status']['status'] = array(
  138. '#type' => 'item',
  139. '#title' => t('NodeSquirrel Status'),
  140. '#markup' => t('Not Configured. Enter your Secret Key below to get started.'),
  141. );
  142. // Warn the user if the key they entered is invalid.
  143. if ($key && empty($status)) {
  144. $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' => backup_migrate_nodesquirrel_get_activate_link()));
  145. }
  146. elseif (!empty($destination) && is_array($status)) {
  147. if (!empty($status['lifetime_backups_used']) && !empty($status['lifetime_backups']) && $status['lifetime_backups_used'] >= $status['lifetime_backups']) {
  148. $form['nodesquirrel_status']['status']['#markup'] = t('Your !num backup trial has expired. Visit !link to continue backing up.', array('!num' => $status['lifetime_backups'], '!link' => backup_migrate_nodesquirrel_get_plan_link()));
  149. }
  150. else {
  151. $form['nodesquirrel_status']['status']['#markup'] = t('Ready to Backup');
  152. if (user_access('perform backup')) {
  153. $form['nodesquirrel_status']['status']['#markup'] .= ' ' . l('(' . t('backup now') . ')', BACKUP_MIGRATE_MENU_PATH);
  154. }
  155. }
  156. if (!empty($status['plan_name'])) {
  157. $form['nodesquirrel_status']['plan_name'] = array(
  158. '#type' => 'item',
  159. '#title' => t('Current Plan'),
  160. '#markup' => check_plain($status['plan_name']),
  161. );
  162. if (!empty($status['lifetime_backups']) && isset($status['lifetime_backups_used'])) {
  163. $remains = $status['lifetime_backups'] - $status['lifetime_backups_used'];
  164. $remains = $remains > 0 ? $remains : t('none');
  165. $form['nodesquirrel_status']['plan_name']['#markup'] .= ' ' . t('(@remains remaining of @backups backup trial)', array('@backups' => $status['lifetime_backups'], '@remains' => $remains));
  166. }
  167. if (!empty($status['lifespan']) && isset($status['age']) && $status['lifespan'] > 0) {
  168. $remains = ceil(($status['lifespan'] - $status['age']) / 86400);
  169. if ($remains <= 0) {
  170. $form['nodesquirrel_status']['plan_name']['#markup'] .= ' ' . t('(Your !span day trial has expired.)', array('!span' => ceil($status['lifespan'] / 86400)));
  171. }
  172. else {
  173. $form['nodesquirrel_status']['plan_name']['#markup'] .= ' ' . format_plural($remains, '(1 day remaining)', '(!span days remaining)', array('!span' => ceil($remains)));
  174. }
  175. }
  176. }
  177. if (isset($status['backups_used'])) {
  178. $form['nodesquirrel_status']['backups_used'] = array(
  179. '#type' => 'item',
  180. '#title' => t('Number of Stored Backups'),
  181. '#markup' => $status['backups_used'] == 0 ? t('None') : number_format($status['backups_used']),
  182. );
  183. }
  184. if (isset($status['last_backup'])) {
  185. $form['nodesquirrel_status']['last_backup'] = array(
  186. '#type' => 'item',
  187. '#title' => t('Last Backup'),
  188. '#markup' => empty($status['last_backup']) ? t('Never') : t('!date (!ago ago)', array(
  189. '!date' => format_date($status['last_backup'], 'small'),
  190. '!ago' => format_interval(time() - $status['last_backup'], 1),
  191. )),
  192. );
  193. }
  194. if ($status['bytes_per_locker']) {
  195. if (isset($status['bytes_used'])) {
  196. $form['nodesquirrel_status']['space'] = array(
  197. '#type' => 'item',
  198. '#title' => t('Storage Space'),
  199. '#markup' => t('!used used of !total (!remaining remaining)', array(
  200. '!used' => backup_migrate_format_size($status['bytes_used']),
  201. '!total' => backup_migrate_format_size($status['bytes_per_locker']),
  202. '!remaining' => backup_migrate_format_size(max(0, $status['bytes_per_locker'] - $status['bytes_used'])),
  203. )),
  204. );
  205. }
  206. else {
  207. $form['nodesquirrel_status']['space'] = array(
  208. '#type' => 'item',
  209. '#title' => t('Total Storage Space'),
  210. '#markup' => t('!total', array('!total' => backup_migrate_format_size($status['bytes_per_locker']))),
  211. );
  212. }
  213. }
  214. $form['nodesquirrel_status']['manage'] = array(
  215. '#type' => 'item',
  216. '#title' => t('Management Console'),
  217. '#markup' => backup_migrate_nodesquirrel_get_manage_link($destination),
  218. '#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.'),
  219. );
  220. }
  221. return $form;
  222. }
  223. function backup_migrate_nodesquirrel_schedule_settings_form($destination, $status) {
  224. backup_migrate_include('sources', 'schedules', 'profiles');
  225. // If the schedule has been overriden it must be edited in the schedule tab.
  226. $schedule = backup_migrate_crud_get_item('schedule', 'nodesquirrel');
  227. $default = 60 * 60 * 24;
  228. $form = array();
  229. $form['nodesquirrel_schedule'] = array(
  230. '#type' => 'fieldset',
  231. '#title' => t('Backup Schedule'),
  232. '#description' => t('Set up a schedule to back up your site to NodeSquirrel. You can customize this schedule or add additional schedules in the !schedule.', array(
  233. '!schedule' => l(t('Schedules tab'), BACKUP_MIGRATE_MENU_PATH . '/schedule'),
  234. '!cron' => l(t('cron'), 'http://drupal.org/cron'),
  235. )),
  236. );
  237. $key = 'nodesquirrel_schedule';
  238. $form['nodesquirrel_schedule'][$key] = array();
  239. $defaults = array(
  240. 'period' => empty($schedule) ? variable_get('nodesquirrel_schedule', 60 * 60 * 24) : $schedule->get('period'),
  241. 'enabled' => empty($schedule) ? variable_get('nodesquirrel_schedule_enabled', TRUE) : $schedule->get('enabled'),
  242. 'source_id' => empty($schedule) ? variable_get('nodesquirrel_schedule_source_id', 'db') : $schedule->get('source_id'),
  243. 'keep' => empty($schedule) ? variable_get('nodesquirrel_schedule_keep', BACKUP_MIGRATE_SMART_DELETE) : $schedule->get('keep'),
  244. );
  245. $form['nodesquirrel_schedule'][$key]['nodesquirrel_schedule_enabled'] = array(
  246. '#type' => 'checkbox',
  247. '#title' => t('Automatically backup to NodeSquirrel'),
  248. '#default_value' => $defaults['enabled'],
  249. );
  250. $form['nodesquirrel_schedule'][$key]['settings'] = array(
  251. '#type' => 'backup_migrate_dependent',
  252. '#dependencies' => array(
  253. 'nodesquirrel_schedule_enabled' => TRUE,
  254. ),
  255. );
  256. $form['nodesquirrel_schedule'][$key]['settings']['nodesquirrel_schedule_source_id'] = _backup_migrate_get_source_pulldown($defaults['source_id']);
  257. $options = array(
  258. (60 * 60) => t('Once an hour'),
  259. (60 * 60 * 24) => t('Once a day'),
  260. (60 * 60 * 24 * 7) => t('Once a week'),
  261. );
  262. $period = $defaults['period'];
  263. if (!isset($options[$period])) {
  264. $options[$period] = empty($schedule) ? t('Custom') : $schedule->get('frequency_description');
  265. }
  266. $form['nodesquirrel_schedule'][$key]['settings']['nodesquirrel_schedule'] = array(
  267. '#type' => 'select',
  268. '#title' => t('Schedule Frequency'),
  269. '#options' => $options,
  270. '#default_value' => $period,
  271. );
  272. $form['nodesquirrel_schedule'][$key]['settings']['nodesquirrel_schedule_keep'] = array(
  273. '#type' => 'checkbox',
  274. '#title' => t('Automatically delete old backups'),
  275. '#return_value' => $defaults['keep'] == BACKUP_MIGRATE_KEEP_ALL ? BACKUP_MIGRATE_SMART_DELETE : $defaults['keep'],
  276. '#default_value' => $defaults['keep'],
  277. );
  278. return $form;
  279. }
  280. /**
  281. * NodeSquirrel settings form.
  282. */
  283. function backup_migrate_nodesquirrel_settings_form($form_state) {
  284. _backup_migrate_message_callback('_backup_migrate_message_browser');
  285. $form = array();
  286. $key = variable_get('nodesquirrel_secret_key', '');
  287. $status = array();
  288. if ($destination = backup_migrate_nodesquirrel_get_destination($key)) {
  289. $status = $destination->check_limits();
  290. }
  291. $form += backup_migrate_nodesquirrel_info_form();
  292. $form += backup_migrate_nodesquirrel_status_form($key, $destination, $status);
  293. $form += backup_migrate_nodesquirrel_credentials_settings_form($key, $status);
  294. $form += backup_migrate_nodesquirrel_schedule_settings_form($destination, $status);
  295. return system_settings_form($form);
  296. }
  297. /**
  298. * A destination for sending database backups to the NodeSquirel backup service.
  299. *
  300. * @ingroup backup_migrate_destinations
  301. */
  302. class backup_migrate_destination_nodesquirrel extends backup_migrate_destination {
  303. public $supported_ops = array(
  304. 'scheduled backup',
  305. 'manual backup',
  306. 'remote backup',
  307. 'restore',
  308. 'list files',
  309. 'configure',
  310. 'delete',
  311. );
  312. public $cache_files = TRUE;
  313. /**
  314. * Don't generate a metadata file as NodeSquirrel can save metadata natively.
  315. */
  316. public $save_metadata = FALSE;
  317. public function __construct($params = array()) {
  318. parent::__construct($params + array('name' => t('NodeSquirrel')));
  319. }
  320. /**
  321. * Gets the menu items for manipulating this type.
  322. */
  323. public function get_menu_items() {
  324. $items = array();
  325. $path = BACKUP_MIGRATE_MENU_PATH . '/nodesquirrel';
  326. $items[$path] = array(
  327. 'title' => t('NodeSquirrel'),
  328. 'page callback' => 'backup_migrate_menu_callback',
  329. 'page arguments' => array('destinations.nodesquirrel', 'backup_migrate_nodesquirrel_settings'),
  330. 'access arguments' => array('administer backup and migrate'),
  331. 'weight' => 10,
  332. 'type' => MENU_LOCAL_TASK,
  333. );
  334. return $items;
  335. }
  336. /**
  337. * Declares any MySQL databases defined in the settings.php file as a possible destination.
  338. */
  339. public function destinations() {
  340. $out = array();
  341. $out['nodesquirrel'] = backup_migrate_create_destination('nodesquirrel', array('machine_name' => 'nodesquirrel'));
  342. if ($secret_key = variable_get('nodesquirrel_secret_key', '')) {
  343. $out['nodesquirrel']->settings['secret_key'] = $secret_key;
  344. }
  345. else {
  346. $out['nodesquirrel']->supported_ops = array('manual backup', 'remote backup');
  347. }
  348. return $out;
  349. }
  350. /**
  351. * Returns a form to be completed before saving to the destination can be complete.
  352. */
  353. public function before_backup_form($settings) {
  354. $form = array();
  355. $key = $this->settings('secret_key');
  356. if (empty($key)) {
  357. $form += backup_migrate_nodesquirrel_info_form();
  358. $form += backup_migrate_nodesquirrel_credentials_settings_form();
  359. }
  360. return $form;
  361. }
  362. /**
  363. * Validates the before_backup_form form.
  364. */
  365. public function before_backup_form_validate($settings, $form, $form_state) {
  366. if (isset($form_state['values']['nodesquirrel_secret_key'])) {
  367. $key = trim($form_state['values']['nodesquirrel_secret_key']);
  368. if ($error = $this->vaidate_key($key)) {
  369. form_set_error('secret_key', $error);
  370. }
  371. }
  372. }
  373. /**
  374. * Submits the before_backup_form form.
  375. */
  376. public function before_backup_form_submit($settings, $form, $form_state) {
  377. if (isset($form_state['values']['nodesquirrel_secret_key'])) {
  378. $this->settings['secret_key'] = $form_state['values']['nodesquirrel_secret_key'];
  379. variable_set('nodesquirrel_secret_key', $this->settings['secret_key']);
  380. }
  381. }
  382. /**
  383. * Saves to the NodeSquirrel destination.
  384. */
  385. public function save_file($file, $settings) {
  386. if ($destination = $this->_get_destination()) {
  387. srand((double) microtime() * 1000000);
  388. $filename = $file->filename();
  389. $filesize = filesize($file->filepath());
  390. $ticket = $this->_xmlrpc('backups.getUploadTicket', array(
  391. $destination,
  392. $filename,
  393. $filesize,
  394. $file->file_info,
  395. ));
  396. if ($ticket) {
  397. $url = $ticket['url'];
  398. // If the ticket requires authentication add our username/password to
  399. // the url.
  400. if (!empty($ticket['auth']) && $ticket['auth'] = 'basic') {
  401. $parts = parse_url($ticket['url']);
  402. list($parts['user'], $parts['pass']) = $this->get_user_pass();
  403. $url = $this->glue_url($parts, FALSE);
  404. }
  405. $out = $this->_post_file($url, 'POST', $ticket['params'], $file);
  406. if ($out->code == 200) {
  407. // Confirm the upload.
  408. $confirm = $this->_xmlrpc('backups.confirmUpload', array(
  409. $destination,
  410. $filename,
  411. $filesize,
  412. ));
  413. if ($confirm['success']) {
  414. // Set a message with a link to the manage console.
  415. _backup_migrate_message('Your backup has been saved to your NodeSquirrel account. View it at !account', array('!account' => backup_migrate_nodesquirrel_get_manage_link($this)));
  416. return $file;
  417. }
  418. else {
  419. _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');
  420. }
  421. }
  422. else {
  423. $error = !empty($out->headers['x-bams-error']) ? $out->headers['x-bams-error'] : $out->error;
  424. _backup_migrate_message('The NodeSquirrel server returned the following error: %err', array('%err' => $error), 'error');
  425. }
  426. }
  427. elseif ($err = xmlrpc_error()) {
  428. // XMLRPC errors are already handled by the server function below.
  429. }
  430. else {
  431. _backup_migrate_message('The NodeSquirrel server refused the backup but did not specify why. Maybe the server is down.');
  432. }
  433. }
  434. return NULL;
  435. }
  436. /**
  437. * Loads from the NodeSquirrel destination.
  438. */
  439. public function load_file($file_id) {
  440. if ($destination = $this->_get_destination()) {
  441. backup_migrate_include('files');
  442. $file = new backup_file(array('filename' => $file_id));
  443. $ticket = $this->_xmlrpc('backups.getDownloadTicket', array($destination, $file_id));
  444. if ($ticket && $url = $ticket['url']) {
  445. // If the ticket requires authentication add our username/password to
  446. // the url.
  447. if (!empty($ticket['auth']) && $ticket['auth'] = 'basic') {
  448. $parts = parse_url($ticket['url']);
  449. $parts['user'] = @$this->dest_url['user'];
  450. $parts['pass'] = @$this->dest_url['pass'];
  451. $url = $this->glue_url($parts, FALSE);
  452. }
  453. $out = drupal_http_request($url);
  454. if ($out->code == 200) {
  455. file_put_contents($file->filepath(), $out->data);
  456. return $file;
  457. }
  458. else {
  459. $error = !empty($out->headers['x-bams-error']) ? $out->headers['x-bams-error'] : $out->error;
  460. _backup_migrate_message('The server returned the following error: %err', array('%err' => $error), 'error');
  461. }
  462. }
  463. }
  464. return NULL;
  465. }
  466. /**
  467. * Deletes from the NodeSquirrel destination.
  468. */
  469. public function delete_file($file_id) {
  470. if ($destination = $this->_get_destination()) {
  471. $result = $this->_xmlrpc('backups.deleteFile', array($destination, $file_id));
  472. }
  473. }
  474. /**
  475. * Lists the files in the remote destination.
  476. */
  477. public function _list_files() {
  478. $files = array();
  479. backup_migrate_include('files');
  480. if ($destination = $this->_get_destination()) {
  481. $file_list = $this->_xmlrpc('backups.listFiles', array($destination));
  482. foreach ((array) $file_list as $file) {
  483. $files[$file['filename']] = new backup_file($file);
  484. }
  485. }
  486. return $files;
  487. }
  488. /**
  489. * Lists the files in the remote destination.
  490. */
  491. public function check_limits() {
  492. if (empty($this->limits)) {
  493. $this->limits = $this->_xmlrpc('backups.getLimits', array($this->_get_destination()));
  494. }
  495. return $this->limits;
  496. }
  497. /**
  498. * Checks that a destination is valid.
  499. */
  500. public function confirm_destination() {
  501. return $this->check_limits();
  502. }
  503. /**
  504. * Gets the form for the settings for this destination.
  505. */
  506. public function edit_form() {
  507. $form = parent::edit_form();
  508. // If this is a new destination but the default NS destination has not been
  509. // created yet, redirect to the NS config screen.
  510. if (!$this->get_id() && !variable_get('nodesquirrel_secret_key', '')) {
  511. drupal_goto(BACKUP_MIGRATE_MENU_PATH . '/nodesquirrel');
  512. }
  513. $form['settings'] = array('#tree' => TRUE);
  514. $activate_link = backup_migrate_nodesquirrel_get_activate_link();
  515. // Retrieve the key from the settings or get it from the get string if this
  516. // is an auto-config action.
  517. $key = $this->settings('secret_key');
  518. if (!empty($_GET['key']) && preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $_GET['key'])) {
  519. $key = $_GET['key'];
  520. }
  521. $form['settings']['secret_key'] = array(
  522. '#type' => 'textfield',
  523. '#title' => t('Secret Key'),
  524. '#default_value' => $key,
  525. );
  526. $form['settings']['location'] = array('#type' => 'value', '#value' => '');
  527. $form['settings']['secret_key_help'] = array(
  528. '#type' => 'item',
  529. '#title' => t('Need a Secret Key?'),
  530. '#markup' => t('Visit !nodesquirrel.', array('!nodesquirrel' => $activate_link)),
  531. );
  532. return $form;
  533. }
  534. /**
  535. * Submits the configuration form.
  536. *
  537. * Glue the url together and add the old password back if a new one was not
  538. * specified.
  539. */
  540. public function edit_form_validate($form, &$form_state) {
  541. $key = trim($form_state['values']['settings']['secret_key']);
  542. if ($error = $this->vaidate_key($key)) {
  543. form_set_error('secret_key', $error);
  544. }
  545. }
  546. /**
  547. * Validates a secret key.
  548. *
  549. * Returns error text if the key is invalid.
  550. */
  551. public function vaidate_key($key) {
  552. $error = FALSE;
  553. if ($key) {
  554. if (!preg_match(NODESQUIRREL_SECRET_KEY_PATTERN, $key)) {
  555. return 'The secret key you entered is not the right format. Please make sure you copy it exactly.';
  556. }
  557. $this->settings['secret_key'] = check_plain($key);
  558. $limits = $this->check_limits();
  559. if (!$limits) {
  560. $err = xmlrpc_error();
  561. if (!empty($err->code) && $err->code == '401') {
  562. return 'Could not log in to the NodeSquirrel server. Please check that your secret key is correct.';
  563. }
  564. else {
  565. return 'Your site could not be found on NodeSquirrel. Please check that your secret key is correct.';
  566. }
  567. }
  568. }
  569. else {
  570. return 'You must enter a NodeSquirrel secret key.';
  571. }
  572. return FALSE;
  573. }
  574. /**
  575. * Submits the configuration form.
  576. *
  577. * Glue the url together and add the old password back if a new one was not
  578. * specified.
  579. */
  580. public function edit_form_submit($form, &$form_state) {
  581. $form_state['values']['secret_key'] = check_plain($form_state['values']['settings']['secret_key']);
  582. parent::edit_form_submit($form, $form_state);
  583. }
  584. /**
  585. * Gets the destination id or warn the user that it has not been set.
  586. */
  587. public function _get_destination($warn = TRUE) {
  588. list($id, $key) = $this->get_user_pass();
  589. return $id;
  590. }
  591. /**
  592. * Gets the destination id or warn the user that it has not been set.
  593. */
  594. public function _get_private_key($warn = TRUE) {
  595. list($id, $key) = $this->get_user_pass();
  596. return $key;
  597. }
  598. /**
  599. * Breaks the secret key into the public/private key (user/pass).
  600. */
  601. public function get_user_pass() {
  602. $key = $this->settings('secret_key');
  603. // The username is the first 32 chars.
  604. $user = substr($key, 0, 32);
  605. // The pass is the last 32 chars. There may be a separating character.
  606. $pass = substr($key, strlen($key) - 32);
  607. return array($user, $pass);
  608. }
  609. public function get_display_location() {
  610. return t('NodeSquirrel.com');
  611. }
  612. public function add_scheme($url) {
  613. return 'https://' . $url;
  614. }
  615. /**
  616. * Gets the form for the settings for this destination.
  617. */
  618. public function _xmlrpc($method, $args = array()) {
  619. // Retrieve the severs or read them from a stored variable.
  620. $servers = $this->_get_endpoints();
  621. // Do the actual call.
  622. return $this->_xmlrpc_request($method, $args, $servers);
  623. }
  624. /**
  625. * Gets the form for the settings for this destination.
  626. */
  627. public function _xmlrpc_request($method, $args, $servers, $retry = 3) {
  628. if ($servers && --$retry > 0) {
  629. // Add the key authentication arguments if we can.
  630. if ($this->_sign_request($args)) {
  631. $url = reset($servers);
  632. // Try each available server in order.
  633. while ($url) {
  634. $url = $this->add_scheme($url);
  635. $options = array();
  636. // Optionally disable SSL certification validation. This may be
  637. // necessary if the server's SSL certificates are out of date because
  638. // and might be incompatible with PHP 5.6's OpenSSL implementation.
  639. // @see http://php.net/manual/en/migration56.openssl.php
  640. // @see http://php.net/manual/en/context.ssl.php#context.ssl.verify-peer
  641. if (variable_get('nodesquirrel_failover', FALSE)) {
  642. $opts = array(
  643. 'ssl' => array(
  644. 'verify_peer' => FALSE,
  645. ),
  646. );
  647. $options = array(
  648. 'context' => stream_context_create($opts),
  649. );
  650. }
  651. $out = xmlrpc($url, array($method => $args), $options);
  652. // Check for errors.
  653. $err = xmlrpc_error();
  654. if ($err && $err->is_error) {
  655. switch ($err->code) {
  656. case '500':
  657. case '503':
  658. case '404':
  659. // Some sort of server error. Try the next one.
  660. $url = next($servers);
  661. // If we're at the end of the line then try refetching the urls.
  662. if (!$url) {
  663. $servers = $this->_get_endpoints(TRUE, $retry);
  664. return $this->_xmlrpc_request($method, $args, $servers, $retry);
  665. }
  666. break;
  667. case '300':
  668. // 'Multiple Choices' means that the existing server list needs
  669. // to be refreshed.
  670. $servers = $this->_get_endpoints(TRUE, $retry);
  671. return $this->_xmlrpc_request($method, $args, $servers, $retry);
  672. case '401':
  673. case '403':
  674. // Authentication failed.
  675. _backup_migrate_message('Couldn\'t log in to NodeSquirrel. The server error was: %err', array('%err' => $err->message), 'error');
  676. return FALSE;
  677. default:
  678. // Some sort of client error. Don't try the next server because
  679. // it'll probably say the same thing.
  680. _backup_migrate_message('The NodeSquirrel server returned the following error: %err', array('%err' => $err->message), 'error');
  681. return FALSE;
  682. }
  683. }
  684. // No error, return the result.
  685. else {
  686. return $out;
  687. }
  688. }
  689. }
  690. }
  691. }
  692. /**
  693. * Genrates a hash with a given secret key, timestamp and random value.
  694. */
  695. public function _get_hash($time, $nonce) {
  696. if ($private_key = $this->_get_private_key()) {
  697. $message = $time . ':' . $nonce . ':' . $private_key;
  698. // Use HMAC-SHA1 to authenticate the call.
  699. $hash = base64_encode(
  700. pack('H*', sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x5c), 64))) .
  701. pack('H*', sha1((str_pad($private_key, 64, chr(0x00)) ^ (str_repeat(chr(0x36), 64))) .
  702. $message))))
  703. );
  704. return $hash;
  705. }
  706. _backup_migrate_message('You must enter a valid secret key to use NodeSquirrel.', array(), 'error');
  707. return FALSE;
  708. }
  709. /**
  710. * Genrates a hash with a given secret key, timestamp and random value.
  711. */
  712. public function _sign_request(&$args) {
  713. $nonce = md5(mt_rand());
  714. $time = time();
  715. $hash = $this->_get_hash($time, $nonce);
  716. if ($hash) {
  717. array_unshift($args, $nonce);
  718. array_unshift($args, $time);
  719. array_unshift($args, $hash);
  720. return TRUE;
  721. }
  722. else {
  723. return FALSE;
  724. }
  725. }
  726. /**
  727. * Retrieves the list of servers.
  728. */
  729. public function _get_endpoints($refresh = FALSE, $retry = 3) {
  730. $servers = (array) variable_get('nodesquirrel_endpoint_urls', array());
  731. // No servers saved or a force refreshr required.
  732. if ($refresh || empty($servers)) {
  733. $servers = array_unique(array_merge($servers, variable_get('nodesquirrel_default_endpoint_urls', array('api.nodesquirrel.com/services/xmlrpc'))));
  734. // Call the get endpoints method but use the default or previous servers
  735. // to avoid infinite loops.
  736. $new_servers = $this->_xmlrpc_request('backups.getEndpoints', array($this->_get_destination(), 'xmlrpc'), $servers, $retry);
  737. if ($new_servers) {
  738. variable_set('nodesquirrel_endpoint_urls', $new_servers);
  739. $servers = $new_servers;
  740. }
  741. }
  742. return $servers;
  743. }
  744. /**
  745. * Posts a file via HTTP.
  746. *
  747. * This looks a lot like a clone of drupal_http_request() but it can post a
  748. * large file without reading the whole file into memory.
  749. */
  750. public function _post_file($url, $method = 'GET', $params = array(), $file = NULL, $retry = 3) {
  751. global $db_prefix;
  752. $result = new stdClass();
  753. // Parse the URL and make sure we can handle the schema.
  754. $uri = parse_url($url);
  755. if ($uri == FALSE) {
  756. $result->error = 'unable to parse URL';
  757. $result->code = -1001;
  758. return $result;
  759. }
  760. if (!isset($uri['scheme'])) {
  761. $result->error = 'missing schema';
  762. $result->code = -1002;
  763. return $result;
  764. }
  765. // Avoid some "undefined variable" errors.
  766. $errno = $errstr = NULL;
  767. switch ($uri['scheme']) {
  768. case 'http':
  769. case 'feed':
  770. $port = isset($uri['port']) ? $uri['port'] : 80;
  771. $host = $uri['host'] . ($port != 80 ? ':' . $port : '');
  772. $fp = @fsockopen($uri['host'], $port, $errno, $errstr, 15);
  773. break;
  774. case 'https':
  775. // Note: Only works for PHP 4.3+ compiled with OpenSSL.
  776. $port = isset($uri['port']) ? $uri['port'] : 443;
  777. $host = $uri['host'] . ($port != 443 ? ':' . $port : '');
  778. $fp = @fsockopen('ssl://' . $uri['host'], $port, $errno, $errstr, 20);
  779. // If fsockopen() doesn't work, try again after disabling SSL.
  780. // Optionally disable SSL certification validation. This may be
  781. // necessary if the server's SSL certificates are out of date and/or
  782. // might be incompatible with PHP 5.6's OpenSSL implementation.
  783. // @see http://php.net/manual/en/migration56.openssl.php
  784. // @see http://php.net/manual/en/context.ssl.php#context.ssl.verify-peer
  785. if (!$fp && variable_get('nodesquirrel_failover', FALSE)) {
  786. $opts = array(
  787. 'ssl' => array(
  788. 'verify_peer' => FALSE,
  789. ),
  790. );
  791. $context = stream_context_create($opts);
  792. $fp = stream_socket_client('ssl://' . $uri['host'] . ':' . $port, $errno, $errstr, 20, STREAM_CLIENT_CONNECT, $context);
  793. }
  794. break;
  795. default:
  796. $result->error = 'invalid schema ' . $uri['scheme'];
  797. $result->code = -1003;
  798. return $result;
  799. }
  800. // Make sure the socket opened properly.
  801. if (!$fp) {
  802. // When a network error occurs, we use a negative number so it does not
  803. // clash with the HTTP status codes.
  804. $result->code = -$errno;
  805. $result->error = trim($errstr);
  806. // Mark that this request failed. This will trigger a check of the web
  807. // server's ability to make outgoing HTTP requests the next time that
  808. // requirements checking is performed.
  809. // @see system_requirements()
  810. variable_set('drupal_http_request_fails', TRUE);
  811. return $result;
  812. }
  813. // Construct the path to act on.
  814. $path = isset($uri['path']) ? $uri['path'] : '/';
  815. if (isset($uri['query'])) {
  816. $path .= '?' . $uri['query'];
  817. }
  818. // Prepare the data payload.
  819. $boundary = '---------------------------' . substr(md5(rand(0, 32000)), 0, 10);
  820. $data_footer = "\r\n--$boundary--\r\n";
  821. $data_header = '';
  822. foreach ($params as $key => $value) {
  823. $data_header .= "--$boundary\r\n";
  824. $data_header .= "Content-Disposition: form-data; name=\"" . $key . "\"\r\n";
  825. $data_header .= "\r\n" . $value . "\r\n";
  826. $data_header .= "--$boundary\r\n";
  827. }
  828. // Add the file header to the post payload.
  829. $data_header .= "--$boundary\r\n";
  830. $data_header .= "Content-Disposition: form-data; name=\"file\"; filename=\"" . $file->filename() . "\"\r\n";
  831. $data_header .= "Content-Type: application/octet-stream;\r\n";
  832. $data_header .= "\r\n";
  833. // Calculate the content length.
  834. $content_length = strlen($data_header . $data_footer) + filesize($file->filepath());
  835. // file_get_contents($file->filepath()));
  836. // Create HTTP request.
  837. $defaults = array(
  838. // RFC 2616: "non-standard ports MUST, default ports MAY be included".
  839. // We don't add the port to prevent from breaking rewrite rules checking
  840. // the host that do not take into account the port number.
  841. 'Host' => "Host: $host",
  842. 'Content-type' => "Content-type: multipart/form-data, boundary=$boundary",
  843. 'User-Agent' => 'User-Agent: NodeSquirrel Client/1.x (+http://www.nodesquirrel.com) (Drupal ' . VERSION . '; Backup and Migrate 2.x)',
  844. 'Content-Length' => 'Content-Length: ' . $content_length,
  845. );
  846. // If the server url has a user then attempt to use basic authentication.
  847. if (isset($uri['user'])) {
  848. $defaults['Authorization'] = 'Authorization: Basic ' . base64_encode($uri['user'] . (!empty($uri['pass']) ? ":" . $uri['pass'] : ''));
  849. }
  850. $request = $method . ' ' . $path . " HTTP/1.0\r\n";
  851. $request .= implode("\r\n", $defaults);
  852. $request .= "\r\n\r\n";
  853. $result->request = $request;
  854. $out = FALSE;
  855. // Write the headers and start of the headers
  856. if (($fp_in = fopen($file->filepath(), 'rb')) && fwrite($fp, $request) && fwrite($fp, $data_header)) {
  857. // Copy the file 1M at a time.
  858. do {
  859. $data = fread($fp_in, 1024 * 1024);
  860. $size = strlen($data);
  861. $sent = 0;
  862. while ($sent < $size && ($out = fwrite($fp, substr($data, $sent)))) {
  863. $sent += $out;
  864. }
  865. } while ($out && !feof($fp_in));
  866. // Finish the write.
  867. if ($out) {
  868. $out = fwrite($fp, $data_footer);
  869. }
  870. }
  871. @fclose($fp_in);
  872. // Check for errors.
  873. if (!$out) {
  874. watchdog('backup_migrate', 'NodeSquirrel: network write failed', NULL, WATCHDOG_ERROR);
  875. $result->code = -$errno;
  876. $result->error = trim($errstr);
  877. return $result;
  878. }
  879. // Fetch response.
  880. $response = '';
  881. while (!feof($fp) && $chunk = fread($fp, 1024)) {
  882. $response .= $chunk;
  883. }
  884. fclose($fp);
  885. if (variable_get('debug_http_request', FALSE)) {
  886. drupal_debug(date('r'));
  887. drupal_debug($request);
  888. drupal_debug($response);
  889. }
  890. // Parse response.
  891. list($split, $result->data) = explode("\r\n\r\n", $response, 2);
  892. $split = preg_split("/\r\n|\n|\r/", $split);
  893. list($protocol, $code, $status_message) = explode(' ', trim(array_shift($split)), 3);
  894. $result->protocol = $protocol;
  895. $result->status_message = $status_message;
  896. $result->headers = array();
  897. // Parse headers.
  898. while ($line = trim(array_shift($split))) {
  899. list($header, $value) = explode(':', $line, 2);
  900. if (isset($result->headers[$header]) && $header == 'Set-Cookie') {
  901. // RFC 2109: the Set-Cookie response header comprises the token Set-
  902. // Cookie:, followed by a comma-separated list of one or more cookies.
  903. $result->headers[$header] .= ',' . trim($value);
  904. }
  905. else {
  906. $result->headers[$header] = trim($value);
  907. }
  908. }
  909. $responses = array(
  910. 100 => 'Continue',
  911. 101 => 'Switching Protocols',
  912. 200 => 'OK',
  913. 201 => 'Created',
  914. 202 => 'Accepted',
  915. 203 => 'Non-Authoritative Information',
  916. 204 => 'No Content',
  917. 205 => 'Reset Content',
  918. 206 => 'Partial Content',
  919. 300 => 'Multiple Choices',
  920. 301 => 'Moved Permanently',
  921. 302 => 'Found',
  922. 303 => 'See Other',
  923. 304 => 'Not Modified',
  924. 305 => 'Use Proxy',
  925. 307 => 'Temporary Redirect',
  926. 400 => 'Bad Request',
  927. 401 => 'Unauthorized',
  928. 402 => 'Payment Required',
  929. 403 => 'Forbidden',
  930. 404 => 'Not Found',
  931. 405 => 'Method Not Allowed',
  932. 406 => 'Not Acceptable',
  933. 407 => 'Proxy Authentication Required',
  934. 408 => 'Request Time-out',
  935. 409 => 'Conflict',
  936. 410 => 'Gone',
  937. 411 => 'Length Required',
  938. 412 => 'Precondition Failed',
  939. 413 => 'Request Entity Too Large',
  940. 414 => 'Request-URI Too Large',
  941. 415 => 'Unsupported Media Type',
  942. 416 => 'Requested range not satisfiable',
  943. 417 => 'Expectation Failed',
  944. 500 => 'Internal Server Error',
  945. 501 => 'Not Implemented',
  946. 502 => 'Bad Gateway',
  947. 503 => 'Service Unavailable',
  948. 504 => 'Gateway Time-out',
  949. 505 => 'HTTP Version not supported',
  950. );
  951. // RFC 2616 states that all unknown HTTP codes must be treated the same as
  952. // the base code in their class.
  953. if (!isset($responses[$code])) {
  954. $code = floor($code / 100) * 100;
  955. }
  956. switch ($code) {
  957. case 200:
  958. // OK.
  959. case 304:
  960. // Not modified.
  961. break;
  962. case 301:
  963. // Moved permanently.
  964. case 302:
  965. // Moved temporarily.
  966. case 307:
  967. // Moved temporarily.
  968. $location = $result->headers['Location'];
  969. if ($retry) {
  970. $result = drupal_http_request($result->headers['Location'], $headers, $method, $data, --$retry);
  971. $result->redirect_code = $result->code;
  972. }
  973. $result->redirect_url = $location;
  974. break;
  975. default:
  976. $result->error = $status_message;
  977. }
  978. $result->code = $code;
  979. return $result;
  980. }
  981. }