Backups.php 9.3 KB

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