MDL-35117 librairies: File Packer can only extract a specific list a files
[moodle.git] / backup / util / helper / backup_cron_helper.class.php
CommitLineData
bac233d3
SH
1<?php
2
3// This file is part of Moodle - http://moodle.org/
4//
5// Moodle is free software: you can redistribute it and/or modify
6// it under the terms of the GNU General Public License as published by
7// the Free Software Foundation, either version 3 of the License, or
8// (at your option) any later version.
9//
10// Moodle is distributed in the hope that it will be useful,
11// but WITHOUT ANY WARRANTY; without even the implied warranty of
12// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13// GNU General Public License for more details.
14//
15// You should have received a copy of the GNU General Public License
16// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17
18
19/**
20 * Utility helper for automated backups run through cron.
21 *
22 * @package core
23 * @subpackage backup
24 * @copyright 2010 Sam Hemelryk
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 */
27
28/**
29 * This class is an abstract class with methods that can be called to aid the
30 * running of automated backups over cron.
31 */
32abstract class backup_cron_automated_helper {
33
34 /** automated backups are active and ready to run */
35 const STATE_OK = 0;
36 /** automated backups are disabled and will not be run */
37 const STATE_DISABLED = 1;
38 /** automated backups are all ready running! */
39 const STATE_RUNNING = 2;
40
41 /** Course automated backup completed successfully */
42 const BACKUP_STATUS_OK = 1;
43 /** Course automated backup errored */
44 const BACKUP_STATUS_ERROR = 0;
45 /** Course automated backup never finished */
46 const BACKUP_STATUS_UNFINISHED = 2;
47 /** Course automated backup was skipped */
48 const BACKUP_STATUS_SKIPPED = 3;
05e521c9
FM
49 /** Course automated backup had warnings */
50 const BACKUP_STATUS_WARNING = 4;
bac233d3 51
081c914b
SH
52 /** Run if required by the schedule set in config. Default. **/
53 const RUN_ON_SCHEDULE = 0;
743fff98
PS
54 /** Run immediately. **/
55 const RUN_IMMEDIATELY = 1;
081c914b
SH
56
57 const AUTO_BACKUP_DISABLED = 0;
58 const AUTO_BACKUP_ENABLED = 1;
59 const AUTO_BACKUP_MANUAL = 2;
bac233d3
SH
60
61 /**
62 * Runs the automated backups if required
63 *
64 * @global moodle_database $DB
65 */
081c914b 66 public static function run_automated_backup($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
67 global $CFG, $DB;
68
69 $status = true;
70 $emailpending = false;
71 $now = time();
72
73 mtrace("Checking automated backup status",'...');
081c914b 74 $state = backup_cron_automated_helper::get_automated_backup_state($rundirective);
bac233d3
SH
75 if ($state === backup_cron_automated_helper::STATE_DISABLED) {
76 mtrace('INACTIVE');
081c914b 77 return $state;
bac233d3
SH
78 } else if ($state === backup_cron_automated_helper::STATE_RUNNING) {
79 mtrace('RUNNING');
743fff98 80 if ($rundirective == self::RUN_IMMEDIATELY) {
beae4a66 81 mtrace('Automated backups are already running. If this script is being run by cron this constitues an error. You will need to increase the time between executions within cron.');
081c914b
SH
82 } else {
83 mtrace("automated backup are already running. Execution delayed");
84 }
85 return $state;
bac233d3
SH
86 } else {
87 mtrace('OK');
88 }
89 backup_cron_automated_helper::set_state_running();
90
91 mtrace("Getting admin info");
92 $admin = get_admin();
93 if (!$admin) {
94 mtrace("Error: No admin account was found");
95 $state = false;
96 }
97
98 if ($status) {
99 mtrace("Checking courses");
100 mtrace("Skipping deleted courses", '...');
101 mtrace(sprintf("%d courses", backup_cron_automated_helper::remove_deleted_courses_from_schedule()));
102 }
103
104 if ($status) {
105
106 mtrace('Running required automated backups...');
107
108 // This could take a while!
109 @set_time_limit(0);
110 raise_memory_limit(MEMORY_EXTRA);
111
112 $nextstarttime = backup_cron_automated_helper::calculate_next_automated_backup($admin->timezone, $now);
113 $showtime = "undefined";
114 if ($nextstarttime > 0) {
4d91f735 115 $showtime = date('r', $nextstarttime);
bac233d3
SH
116 }
117
118 $rs = $DB->get_recordset('course');
119 foreach ($rs as $course) {
120 $backupcourse = $DB->get_record('backup_courses', array('courseid'=>$course->id));
121 if (!$backupcourse) {
122 $backupcourse = new stdClass;
123 $backupcourse->courseid = $course->id;
124 $DB->insert_record('backup_courses',$backupcourse);
125 $backupcourse = $DB->get_record('backup_courses', array('courseid'=>$course->id));
126 }
127
e2558cd3 128 // Skip courses that do not yet need backup
4d91f735
FM
129 $skipped = !(($backupcourse->nextstarttime > 0 && $backupcourse->nextstarttime < $now) || $rundirective == self::RUN_IMMEDIATELY);
130 if ($skipped && $backupcourse->nextstarttime != $nextstarttime) {
131 $backupcourse->nextstarttime = $nextstarttime;
132 $backupcourse->laststatus = backup_cron_automated_helper::BACKUP_STATUS_SKIPPED;
133 $DB->update_record('backup_courses', $backupcourse);
134 mtrace('Backup of \'' . $course->fullname . '\' is scheduled on ' . $showtime);
135 }
136
bac233d3 137 // Skip backup of unavailable courses that have remained unmodified in a month
e2558cd3
MG
138 if (!$skipped && empty($course->visible) && ($now - $course->timemodified) > 31*24*60*60) { //Hidden + settings were unmodified last month
139 //Check log if there were any modifications to the course content
a6c124f5 140 $sqlwhere = "course=:courseid AND time>:time AND ". $DB->sql_like('action', ':action', false, true, true);
e2558cd3 141 $params = array('courseid' => $course->id, 'time' => $now-31*24*60*60, 'action' => '%view%');
a6c124f5
MG
142 $logexists = $DB->record_exists_select('log', $sqlwhere, $params);
143 if (!$logexists) {
05e521c9 144 $backupcourse->laststatus = self::BACKUP_STATUS_SKIPPED;
e2558cd3
MG
145 $backupcourse->nextstarttime = $nextstarttime;
146 $DB->update_record('backup_courses', $backupcourse);
147 mtrace('Skipping unchanged course '.$course->fullname);
148 $skipped = true;
149 }
150 }
4d91f735 151
e2558cd3
MG
152 //Now we backup every non-skipped course
153 if (!$skipped) {
4d91f735 154 mtrace('Backing up '.$course->fullname.'...');
bac233d3
SH
155
156 //We have to send a email because we have included at least one backup
157 $emailpending = true;
743fff98 158
bac233d3
SH
159 //Only make the backup if laststatus isn't 2-UNFINISHED (uncontrolled error)
160 if ($backupcourse->laststatus != 2) {
161 //Set laststarttime
162 $starttime = time();
163
164 $backupcourse->laststarttime = time();
05e521c9 165 $backupcourse->laststatus = self::BACKUP_STATUS_UNFINISHED;
bac233d3
SH
166 $DB->update_record('backup_courses', $backupcourse);
167
168 $backupcourse->laststatus = backup_cron_automated_helper::launch_automated_backup($course, $backupcourse->laststarttime, $admin->id);
169 $backupcourse->lastendtime = time();
170 $backupcourse->nextstarttime = $nextstarttime;
171
172 $DB->update_record('backup_courses', $backupcourse);
173
05e521c9 174 if ($backupcourse->laststatus === self::BACKUP_STATUS_OK) {
bac233d3
SH
175 // Clean up any excess course backups now that we have
176 // taken a successful backup.
177 $removedcount = backup_cron_automated_helper::remove_excess_backups($course);
178 }
179 }
180
181 mtrace("complete - next execution: $showtime");
182 }
183 }
184 $rs->close();
185 }
186
187 //Send email to admin if necessary
188 if ($emailpending) {
189 mtrace("Sending email to admin");
190 $message = "";
191
192 $count = backup_cron_automated_helper::get_backup_status_array();
05e521c9 193 $haserrors = ($count[self::BACKUP_STATUS_ERROR] != 0 || $count[self::BACKUP_STATUS_UNFINISHED] != 0);
bac233d3
SH
194
195 //Build the message text
196 //Summary
197 $message .= get_string('summary')."\n";
198 $message .= "==================================================\n";
199 $message .= " ".get_string('courses').": ".array_sum($count)."\n";
05e521c9
FM
200 $message .= " ".get_string('ok').": ".$count[self::BACKUP_STATUS_OK]."\n";
201 $message .= " ".get_string('skipped').": ".$count[self::BACKUP_STATUS_SKIPPED]."\n";
202 $message .= " ".get_string('error').": ".$count[self::BACKUP_STATUS_ERROR]."\n";
203 $message .= " ".get_string('unfinished').": ".$count[self::BACKUP_STATUS_UNFINISHED]."\n";
204 $message .= " ".get_string('warning').": ".$count[self::BACKUP_STATUS_WARNING]."\n\n";
bac233d3
SH
205
206 //Reference
207 if ($haserrors) {
208 $message .= " ".get_string('backupfailed')."\n\n";
daca599f 209 $dest_url = "$CFG->wwwroot/report/backups/index.php";
bac233d3
SH
210 $message .= " ".get_string('backuptakealook','',$dest_url)."\n\n";
211 //Set message priority
212 $admin->priority = 1;
213 //Reset unfinished to error
214 $DB->set_field('backup_courses','laststatus','0', array('laststatus'=>'2'));
215 } else {
216 $message .= " ".get_string('backupfinished')."\n";
217 }
218
219 //Build the message subject
220 $site = get_site();
a689cd1d 221 $prefix = format_string($site->shortname, true, array('context' => context_course::instance(SITEID))).": ";
bac233d3
SH
222 if ($haserrors) {
223 $prefix .= "[".strtoupper(get_string('error'))."] ";
224 }
225 $subject = $prefix.get_string('automatedbackupstatus', 'backup');
226
227 //Send the message
228 $eventdata = new stdClass();
229 $eventdata->modulename = 'moodle';
230 $eventdata->userfrom = $admin;
231 $eventdata->userto = $admin;
232 $eventdata->subject = $subject;
233 $eventdata->fullmessage = $message;
234 $eventdata->fullmessageformat = FORMAT_PLAIN;
235 $eventdata->fullmessagehtml = '';
236 $eventdata->smallmessage = '';
237
238 $eventdata->component = 'moodle';
239 $eventdata->name = 'backup';
240
241 message_send($eventdata);
242 }
243
244 //Everything is finished stop backup_auto_running
245 backup_cron_automated_helper::set_state_running(false);
246
247 mtrace('Automated backups complete.');
248
249 return $status;
250 }
251
252 /**
253 * Gets the results from the last automated backup that was run based upon
254 * the statuses of the courses that were looked at.
255 *
256 * @global moodle_database $DB
257 * @return array
258 */
259 public static function get_backup_status_array() {
260 global $DB;
261
262 $result = array(
263 self::BACKUP_STATUS_ERROR => 0,
264 self::BACKUP_STATUS_OK => 0,
265 self::BACKUP_STATUS_UNFINISHED => 0,
266 self::BACKUP_STATUS_SKIPPED => 0,
05e521c9 267 self::BACKUP_STATUS_WARNING => 0
bac233d3
SH
268 );
269
4cb18cb0 270 $statuses = $DB->get_records_sql('SELECT DISTINCT bc.laststatus, COUNT(bc.courseid) AS statuscount FROM {backup_courses} bc GROUP BY bc.laststatus');
bac233d3
SH
271
272 foreach ($statuses as $status) {
273 if (empty($status->statuscount)) {
274 $status->statuscount = 0;
275 }
276 $result[(int)$status->laststatus] += $status->statuscount;
277 }
278
279 return $result;
280 }
281
282 /**
283 * Works out the next time the automated backup should be run.
284 *
4d91f735
FM
285 * @param mixed $timezone user timezone
286 * @param int $now timestamp, should not be in the past, most likely time()
287 * @return int timestamp of the next execution at server time
bac233d3
SH
288 */
289 public static function calculate_next_automated_backup($timezone, $now) {
290
4d91f735 291 $result = 0;
bac233d3 292 $config = get_config('backup');
4d91f735
FM
293 $autohour = $config->backup_auto_hour;
294 $automin = $config->backup_auto_minute;
295
296 // Gets the user time relatively to the server time.
bac233d3 297 $date = usergetdate($now, $timezone);
4d91f735
FM
298 $usertime = mktime($date['hours'], $date['minutes'], $date['seconds'], $date['mon'], $date['mday'], $date['year']);
299 $diff = $now - $usertime;
743fff98 300
4d91f735 301 // Get number of days (from user's today) to execute backups.
d4a49ba2 302 $automateddays = substr($config->backup_auto_weekdays, $date['wday']) . $config->backup_auto_weekdays;
4d91f735 303 $daysfromnow = strpos($automateddays, "1");
d4a49ba2 304
4d91f735
FM
305 // Error, there are no days to schedule the backup for.
306 if ($daysfromnow === false) {
307 return 0;
bac233d3
SH
308 }
309
4d91f735
FM
310 // Checks if the date would happen in the future (of the user).
311 $userresult = mktime($autohour, $automin, 0, $date['mon'], $date['mday'] + $daysfromnow, $date['year']);
312 if ($userresult <= $usertime) {
313 // If not, we skip the first scheduled day, that should fix it.
314 $daysfromnow = strpos($automateddays, "1", 1);
315 $userresult = mktime($autohour, $automin, 0, $date['mon'], $date['mday'] + $daysfromnow, $date['year']);
bac233d3
SH
316 }
317
4d91f735
FM
318 // Now we generate the time relative to the server.
319 $result = $userresult + $diff;
320
321 // If that time is past, call the function recursively to obtain the next valid day.
322 if ($result <= $now) {
323 // Checking time() in here works, but makes PHPUnit Tests extremely hard to predict.
324 // $now should never be earlier than time() anyway...
325 $result = self::calculate_next_automated_backup($timezone, $now + DAYSECS);
bac233d3
SH
326 }
327
328 return $result;
329 }
330
331 /**
332 * Launches a automated backup routine for the given course
333 *
334 * @param stdClass $course
335 * @param int $starttime
336 * @param int $userid
337 * @return bool
338 */
339 public static function launch_automated_backup($course, $starttime, $userid) {
340
05e521c9 341 $outcome = self::BACKUP_STATUS_OK;
bac233d3
SH
342 $config = get_config('backup');
343 $bc = new backup_controller(backup::TYPE_1COURSE, $course->id, backup::FORMAT_MOODLE, backup::INTERACTIVE_NO, backup::MODE_AUTOMATED, $userid);
344
345 try {
346
347 $settings = array(
348 'users' => 'backup_auto_users',
0d5e5644 349 'role_assignments' => 'backup_auto_role_assignments',
bac233d3
SH
350 'activities' => 'backup_auto_activities',
351 'blocks' => 'backup_auto_blocks',
352 'filters' => 'backup_auto_filters',
353 'comments' => 'backup_auto_comments',
354 'completion_information' => 'backup_auto_userscompletion',
355 'logs' => 'backup_auto_logs',
356 'histories' => 'backup_auto_histories'
357 );
358 foreach ($settings as $setting => $configsetting) {
359 if ($bc->get_plan()->setting_exists($setting)) {
360 $bc->get_plan()->get_setting($setting)->set_value($config->{$configsetting});
361 }
362 }
363
364 // Set the default filename
365 $format = $bc->get_format();
366 $type = $bc->get_type();
367 $id = $bc->get_id();
368 $users = $bc->get_plan()->get_setting('users')->get_value();
369 $anonymised = $bc->get_plan()->get_setting('anonymize')->get_value();
370 $bc->get_plan()->get_setting('filename')->set_value(backup_plan_dbops::get_default_backup_filename($format, $type, $id, $users, $anonymised));
743fff98 371
bac233d3
SH
372 $bc->set_status(backup::STATUS_AWAITING);
373
fde4c609 374 $bc->execute_plan();
bac233d3 375 $results = $bc->get_results();
05e521c9 376 $outcome = self::outcome_from_results($results);
096702f6 377 $file = $results['backup_destination']; // may be empty if file already moved to target location
bac233d3
SH
378 $dir = $config->backup_auto_destination;
379 $storage = (int)$config->backup_auto_storage;
380 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
381 $dir = null;
382 }
096702f6 383 if ($file && !empty($dir) && $storage !== 0) {
66150286 384 $filename = backup_plan_dbops::get_default_backup_filename($format, $type, $course->id, $users, $anonymised, !$config->backup_shortname);
05e521c9
FM
385 if (!$file->copy_content_to($dir.'/'.$filename)) {
386 $outcome = self::BACKUP_STATUS_ERROR;
387 }
388 if ($outcome != self::BACKUP_STATUS_ERROR && $storage === 1) {
bac233d3
SH
389 $file->delete();
390 }
391 }
392
fde4c609
EL
393 } catch (moodle_exception $e) {
394 $bc->log('backup_auto_failed_on_course', backup::LOG_ERROR, $course->shortname); // Log error header.
395 $bc->log('Exception: ' . $e->errorcode, backup::LOG_ERROR, $e->a, 1); // Log original exception problem.
396 $bc->log('Debug: ' . $e->debuginfo, backup::LOG_DEBUG, null, 1); // Log original debug information.
05e521c9 397 $outcome = self::BACKUP_STATUS_ERROR;
bac233d3
SH
398 }
399
ca1292e0
SH
400 $bc->destroy();
401 unset($bc);
402
fde4c609 403 return $outcome;
bac233d3
SH
404 }
405
05e521c9
FM
406 /**
407 * Returns the backup outcome by analysing its results.
408 *
409 * @param array $results returned by a backup
410 * @return int {@link self::BACKUP_STATUS_OK} and other constants
411 */
412 public static function outcome_from_results($results) {
413 $outcome = self::BACKUP_STATUS_OK;
414 foreach ($results as $code => $value) {
415 // Each possible error and warning code has to be specified in this switch
416 // which basically analyses the results to return the correct backup status.
417 switch ($code) {
418 case 'missing_files_in_pool':
419 $outcome = self::BACKUP_STATUS_WARNING;
420 break;
421 }
422 // If we found the highest error level, we exit the loop.
423 if ($outcome == self::BACKUP_STATUS_ERROR) {
424 break;
425 }
426 }
427 return $outcome;
428 }
429
bac233d3
SH
430 /**
431 * Removes deleted courses fromn the backup_courses table so that we don't
432 * waste time backing them up.
433 *
434 * @global moodle_database $DB
435 * @return int
436 */
437 public static function remove_deleted_courses_from_schedule() {
438 global $DB;
439 $skipped = 0;
440 $sql = "SELECT bc.courseid FROM {backup_courses} bc WHERE bc.courseid NOT IN (SELECT c.id FROM {course} c)";
441 $rs = $DB->get_recordset_sql($sql);
442 foreach ($rs as $deletedcourse) {
443 //Doesn't exist, so delete from backup tables
444 $DB->delete_records('backup_courses', array('courseid'=>$deletedcourse->courseid));
445 $skipped++;
446 }
447 $rs->close();
448 return $skipped;
449 }
450
451 /**
452 * Gets the state of the automated backup system.
453 *
454 * @global moodle_database $DB
455 * @return int One of self::STATE_*
456 */
081c914b 457 public static function get_automated_backup_state($rundirective = self::RUN_ON_SCHEDULE) {
bac233d3
SH
458 global $DB;
459
460 $config = get_config('backup');
081c914b 461 $active = (int)$config->backup_auto_active;
4d91f735
FM
462 $weekdays = (string)$config->backup_auto_weekdays;
463
464 // In case of automated backup also check that it is scheduled for at least one weekday.
465 if ($active === self::AUTO_BACKUP_DISABLED ||
466 ($rundirective == self::RUN_ON_SCHEDULE && $active === self::AUTO_BACKUP_MANUAL) ||
467 ($rundirective == self::RUN_ON_SCHEDULE && strpos($weekdays, '1') === false)) {
bac233d3
SH
468 return self::STATE_DISABLED;
469 } else if (!empty($config->backup_auto_running)) {
beae4a66
EL
470 // Detect if the backup_auto_running semaphore is a valid one
471 // by looking for recent activity in the backup_controllers table
472 // for backups of type backup::MODE_AUTOMATED
473 $timetosee = 60 * 90; // Time to consider in order to clean the semaphore
474 $params = array( 'purpose' => backup::MODE_AUTOMATED, 'timetolook' => (time() - $timetosee));
475 if ($DB->record_exists_select('backup_controllers',
476 "operation = 'backup' AND type = 'course' AND purpose = :purpose AND timemodified > :timetolook", $params)) {
477 return self::STATE_RUNNING; // Recent activity found, still running
478 } else {
479 // No recent activity found, let's clean the semaphore
480 mtrace('Automated backups activity not found in last ' . (int)$timetosee/60 . ' minutes. Cleaning running status');
481 backup_cron_automated_helper::set_state_running(false);
482 }
bac233d3
SH
483 }
484 return self::STATE_OK;
485 }
486
487 /**
488 * Sets the state of the automated backup system.
489 *
490 * @param bool $running
491 * @return bool
492 */
493 public static function set_state_running($running = true) {
494 if ($running === true) {
495 if (self::get_automated_backup_state() === self::STATE_RUNNING) {
496 throw new backup_exception('backup_automated_already_running');
497 }
498 set_config('backup_auto_running', '1', 'backup');
499 } else {
500 unset_config('backup_auto_running', 'backup');
501 }
502 return true;
503 }
504
505 /**
506 * Removes excess backups from the external system and the local file system.
507 *
508 * The number of backups keep comes from $config->backup_auto_keep
509 *
510 * @param stdClass $course
511 * @return bool
512 */
513 public static function remove_excess_backups($course) {
514 $config = get_config('backup');
515 $keep = (int)$config->backup_auto_keep;
516 $storage = $config->backup_auto_storage;
517 $dir = $config->backup_auto_destination;
518
dbf7784e
PS
519 if ($keep == 0) {
520 // means keep all backup files
521 return true;
522 }
523
6f3451e5 524 $backupword = str_replace(' ', '_', textlib::strtolower(get_string('backupfilename')));
bac233d3
SH
525 $backupword = trim(clean_filename($backupword), '_');
526
527 if (!file_exists($dir) || !is_dir($dir) || !is_writable($dir)) {
528 $dir = null;
529 }
530
531 // Clean up excess backups in the course backup filearea
532 if ($storage == 0 || $storage == 2) {
533 $fs = get_file_storage();
a689cd1d 534 $context = context_course::instance($course->id);
bac233d3
SH
535 $component = 'backup';
536 $filearea = 'automated';
537 $itemid = 0;
538 $files = array();
8afbe44f 539 // Store all the matching files into timemodified => stored_file array
bac233d3
SH
540 foreach ($fs->get_area_files($context->id, $component, $filearea, $itemid) as $file) {
541 if (strpos($file->get_filename(), $backupword) !== 0) {
542 continue;
543 }
544 $files[$file->get_timemodified()] = $file;
545 }
8afbe44f
EL
546 if (count($files) <= $keep) {
547 // There are less matching files than the desired number to keep
548 // do there is nothing to clean up.
549 return 0;
550 }
551 // Sort by keys descending (newer to older filemodified)
552 krsort($files);
bac233d3
SH
553 $remove = array_splice($files, $keep);
554 foreach ($remove as $file) {
555 $file->delete();
556 }
8afbe44f 557 //mtrace('Removed '.count($remove).' old backup file(s) from the automated filearea');
bac233d3
SH
558 }
559
560 // Clean up excess backups in the specified external directory
561 if (!empty($dir) && ($storage == 1 || $storage == 2)) {
8afbe44f
EL
562 // Calculate backup filename regex, ignoring the date/time/info parts that can be
563 // variable, depending of languages, formats and automated backup settings
14ecc5a8 564 $filename = $backupword . '-' . backup::FORMAT_MOODLE . '-' . backup::TYPE_1COURSE . '-' .$course->id . '-';
8afbe44f 565 $regex = '#^'.preg_quote($filename, '#').'.*\.mbz$#';
bac233d3 566
8afbe44f 567 // Store all the matching files into fullpath => timemodified array
bac233d3
SH
568 $files = array();
569 foreach (scandir($dir) as $file) {
570 if (preg_match($regex, $file, $matches)) {
8afbe44f 571 $files[$file] = filemtime($dir . '/' . $file);
bac233d3
SH
572 }
573 }
574 if (count($files) <= $keep) {
575 // There are less matching files than the desired number to keep
576 // do there is nothing to clean up.
577 return 0;
578 }
8afbe44f 579 // Sort by values descending (newer to older filemodified)
bac233d3
SH
580 arsort($files);
581 $remove = array_splice($files, $keep);
582 foreach (array_keys($remove) as $file) {
8afbe44f 583 unlink($dir . '/' . $file);
bac233d3
SH
584 }
585 //mtrace('Removed '.count($remove).' old backup file(s) from external directory');
586 }
587
588 return true;
589 }
02cf6919 590}