Backups.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261
  1. <?php
  2. /**
  3. * @package Grav\Common\Backup
  4. *
  5. * @copyright Copyright (C) 2015 - 2019 Trilby Media, LLC. All rights reserved.
  6. * @license MIT License; see LICENSE file for details.
  7. */
  8. namespace Grav\Common\Backup;
  9. use Grav\Common\Filesystem\Archiver;
  10. use Grav\Common\Filesystem\Folder;
  11. use Grav\Common\Inflector;
  12. use Grav\Common\Scheduler\Job;
  13. use Grav\Common\Scheduler\Scheduler;
  14. use Grav\Common\Utils;
  15. use Grav\Common\Grav;
  16. use RocketTheme\Toolbox\Event\Event;
  17. use RocketTheme\Toolbox\Event\EventDispatcher;
  18. use RocketTheme\Toolbox\File\JsonFile;
  19. use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
  20. class Backups
  21. {
  22. protected const BACKUP_FILENAME_REGEXZ = "#(.*)--(\d*).zip#";
  23. protected const BACKUP_DATE_FORMAT = 'YmdHis';
  24. protected static $backup_dir;
  25. protected static $backups = null;
  26. public function init()
  27. {
  28. /** @var EventDispatcher $dispatcher */
  29. $dispatcher = Grav::instance()['events'];
  30. $dispatcher->addListener('onSchedulerInitialized', [$this, 'onSchedulerInitialized']);
  31. Grav::instance()->fireEvent('onBackupsInitialized', new Event(['backups' => $this]));
  32. }
  33. public function setup()
  34. {
  35. if (null === static::$backup_dir) {
  36. static::$backup_dir = Grav::instance()['locator']->findResource('backup://', true, true);
  37. Folder::create(static::$backup_dir);
  38. }
  39. }
  40. public function onSchedulerInitialized(Event $event)
  41. {
  42. /** @var Scheduler $scheduler */
  43. $scheduler = $event['scheduler'];
  44. /** @var Inflector $inflector */
  45. $inflector = Grav::instance()['inflector'];
  46. foreach (static::getBackupProfiles() as $id => $profile) {
  47. $at = $profile['schedule_at'];
  48. $name = $inflector::hyphenize($profile['name']);
  49. $logs = 'logs/backup-' . $name . '.out';
  50. /** @var Job $job */
  51. $job = $scheduler->addFunction('Grav\Common\Backup\Backups::backup', [$id], $name );
  52. $job->at($at);
  53. $job->output($logs);
  54. $job->backlink('/tools/backups');
  55. }
  56. }
  57. public function getBackupDownloadUrl($backup, $base_url)
  58. {
  59. $param_sep = $param_sep = Grav::instance()['config']->get('system.param_sep', ':');
  60. $download = urlencode(base64_encode($backup));
  61. $url = rtrim(Grav::instance()['uri']->rootUrl(true), '/') . '/' . trim($base_url,
  62. '/') . '/task' . $param_sep . 'backup/download' . $param_sep . $download . '/admin-nonce' . $param_sep . Utils::getNonce('admin-form');
  63. return $url;
  64. }
  65. public static function getBackupProfiles()
  66. {
  67. return Grav::instance()['config']->get('backups.profiles');
  68. }
  69. public static function getPurgeConfig()
  70. {
  71. return Grav::instance()['config']->get('backups.purge');
  72. }
  73. public function getBackupNames()
  74. {
  75. return array_column(static::getBackupProfiles(), 'name');
  76. }
  77. public static function getTotalBackupsSize()
  78. {
  79. $backups = static::getAvailableBackups();
  80. $size = array_sum(array_column($backups, 'size'));
  81. return $size ?? 0;
  82. }
  83. public static function getAvailableBackups($force = false)
  84. {
  85. if ($force || null === static::$backups) {
  86. static::$backups = [];
  87. $backups_itr = new \GlobIterator(static::$backup_dir . '/*.zip', \FilesystemIterator::KEY_AS_FILENAME);
  88. $inflector = Grav::instance()['inflector'];
  89. $long_date_format = DATE_RFC2822;
  90. /**
  91. * @var string $name
  92. * @var \SplFileInfo $file
  93. */
  94. foreach ($backups_itr as $name => $file) {
  95. if (preg_match(static::BACKUP_FILENAME_REGEXZ, $name, $matches)) {
  96. $date = \DateTime::createFromFormat(static::BACKUP_DATE_FORMAT, $matches[2]);
  97. $timestamp = $date->getTimestamp();
  98. $backup = new \stdClass();
  99. $backup->title = $inflector->titleize($matches[1]);
  100. $backup->time = $date;
  101. $backup->date = $date->format($long_date_format);
  102. $backup->filename = $name;
  103. $backup->path = $file->getPathname();
  104. $backup->size = $file->getSize();
  105. static::$backups[$timestamp] = $backup;
  106. }
  107. }
  108. // Reverse Key Sort to get in reverse date order
  109. krsort(static::$backups);
  110. }
  111. return static::$backups;
  112. }
  113. /**
  114. * Backup
  115. *
  116. * @param int $id
  117. * @param callable|null $status
  118. *
  119. * @return null|string
  120. */
  121. public static function backup($id = 0, callable $status = null)
  122. {
  123. $profiles = static::getBackupProfiles();
  124. /** @var UniformResourceLocator $locator */
  125. $locator = Grav::instance()['locator'];
  126. if (isset($profiles[$id])) {
  127. $backup = (object) $profiles[$id];
  128. } else {
  129. throw new \RuntimeException('No backups defined...');
  130. }
  131. $name = Grav::instance()['inflector']->underscorize($backup->name);
  132. $date = date(static::BACKUP_DATE_FORMAT, time());
  133. $filename = trim($name, '_') . '--' . $date . '.zip';
  134. $destination = static::$backup_dir . DS . $filename;
  135. $max_execution_time = ini_set('max_execution_time', 600);
  136. $backup_root = $backup->root;
  137. if ($locator->isStream($backup_root)) {
  138. $backup_root = $locator->findResource($backup_root);
  139. } else {
  140. $backup_root = rtrim(GRAV_ROOT . $backup_root, '/');
  141. }
  142. if (!file_exists($backup_root)) {
  143. throw new \RuntimeException("Backup location: {$backup_root} does not exist...");
  144. }
  145. $options = [
  146. 'exclude_files' => static::convertExclude($backup->exclude_files ?? ''),
  147. 'exclude_paths' => static::convertExclude($backup->exclude_paths ?? ''),
  148. ];
  149. /** @var Archiver $archiver */
  150. $archiver = Archiver::create('zip');
  151. $archiver->setArchive($destination)->setOptions($options)->compress($backup_root, $status)->addEmptyFolders($options['exclude_paths'], $status);
  152. $status && $status([
  153. 'type' => 'message',
  154. 'message' => 'Done...',
  155. ]);
  156. $status && $status([
  157. 'type' => 'progress',
  158. 'complete' => true
  159. ]);
  160. if ($max_execution_time !== false) {
  161. ini_set('max_execution_time', $max_execution_time);
  162. }
  163. // Log the backup
  164. Grav::instance()['log']->notice('Backup Created: ' . $destination);
  165. // Fire Finished event
  166. Grav::instance()->fireEvent('onBackupFinished', new Event(['backup' => $destination]));
  167. // Purge anything required
  168. static::purge();
  169. // Log
  170. $log = JsonFile::instance(Grav::instance()['locator']->findResource("log://backup.log", true, true));
  171. $log->content([
  172. 'time' => time(),
  173. 'location' => $destination
  174. ]);
  175. $log->save();
  176. return $destination;
  177. }
  178. public static function purge()
  179. {
  180. $purge_config = static::getPurgeConfig();
  181. $trigger = $purge_config['trigger'];
  182. $backups = static::getAvailableBackups(true);
  183. switch ($trigger)
  184. {
  185. case 'number':
  186. $backups_count = count($backups);
  187. if ($backups_count > $purge_config['max_backups_count']) {
  188. $last = end($backups);
  189. unlink ($last->path);
  190. static::purge();
  191. }
  192. break;
  193. case 'time':
  194. $last = end($backups);
  195. $now = new \DateTime();
  196. $interval = $now->diff($last->time);
  197. if ($interval->days > $purge_config['max_backups_time']) {
  198. unlink($last->path);
  199. static::purge();
  200. }
  201. break;
  202. default:
  203. $used_space = static::getTotalBackupsSize();
  204. $max_space = $purge_config['max_backups_space'] * 1024 * 1024 * 1024;
  205. if ($used_space > $max_space) {
  206. $last = end($backups);
  207. unlink($last->path);
  208. static::purge();
  209. }
  210. break;
  211. }
  212. }
  213. protected static function convertExclude($exclude)
  214. {
  215. $lines = preg_split("/[\s,]+/", $exclude);
  216. return array_map('trim', $lines, array_fill(0, \count($lines), '/'));
  217. }
  218. }