require('src/apache_conf_file') class Janitor attr_accessor :apache_vhosts_directory SECONDS_PER_MINUTE = 60 MINUTES_PER_HOUR = 60 HOURS_PER_DAY = 24 SECONDS_PER_DAY = SECONDS_PER_MINUTE * MINUTES_PER_HOUR * HOURS_PER_DAY def initialize() @apache_vhosts_directory = nil end protected; def seconds_to_whole_days(seconds) # Given some number of seconds, computer how many # entire days are contained in that number of seconds. # Fractions of days don't count! if (seconds < 0) raise(ArgumentException.new('Negative seconds?')) end return (seconds / SECONDS_PER_DAY).floor end public; # Get a list of all the temporary directories that # we'd like to clean out. def get_temporary_directories(remove_duplicates = true) temp_dirs = [] # Get the PHP temp dirs if we've been given a vhosts path if !@apache_vhosts_directory.nil? && File.directory?(@apache_vhosts_directory) Dir.glob(@apache_vhosts_directory + '/*.conf').each do |conf_file| acf = ApacheConfFile.new(conf_file) # Don't remove the duplicates here since we have # to do it afterwards anyway. temp_dirs += acf.get_php_temporary_directory_list(false) end end # We expect these to have been strip()ed already if remove_duplicates return temp_dirs.uniq else return temp_dirs end end def clean_directory(directory, max_age, file_pattern = '*') glob_pattern = File.join(directory, file_pattern) Dir.glob(glob_pattern).each do |f| # Obviously, we should bail if it's not a file. next if not File.file?(f) # Calculate how old it is days_old = seconds_to_whole_days(Time.now - File.mtime(f)) # And then delete the file (with a notice) if it's too old. if days_old > max_age puts "Deleting file: #{f} (#{days_old} days old)" File.delete(f) end end end end