destinations.nodesquirrel.inc 35 KB

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