<?php /*

 Composr
 Copyright (c) ocProducts, 2004-2016

 See text/EN/licence.txt for full licencing information.


 NOTE TO PROGRAMMERS:
   Do not edit this file. If you need to make changes, save your changed file to the appropriate *_custom folder
   **** If you ignore this advice, then your website upgrades (e.g. for bug fixes) will likely kill your changes ****

*/

/**
 * @license    http://opensource.org/licenses/cpal_1.0 Common Public Attribution License
 * @copyright  ocProducts Ltd
 * @package    backup
 */

/**
 * Hook class.
 */
class Hook_snippet_backup_size
{
    /**
     * Run function for snippet hooks. Generates XHTML to insert into a page using AJAX.
     *
     * @return Tempcode The snippet
     */
    public function run()
    {
        if (php_function_allowed('set_time_limit')) {
            @set_time_limit(0);
        }

        require_code('files');
        require_code('files2');
        require_code('backup');

        $directories_to_backup = array_flip(directories_to_backup());

        $size = 0;
        $max_size = get_param_integer('max_size') * 1024 * 1024;
        $files = get_directory_contents(get_custom_file_base());
        foreach ($files as $file) {
            $first_dir = preg_replace('#/.*#', '', $file);

            if (!isset($directories_to_backup[$first_dir])) {
                continue;
            }

            // Also see code in tar.php
            if ($GLOBALS['DEV_MODE']) {
                if (($first_dir == 'exports') && (preg_match('#^exports/(builds|addons)/#', $file) != 0)) {
                    continue;
                }
            }
            if (($first_dir == 'uploads') && (preg_match('#^uploads/(auto_thumbs|incoming)/#', $file) != 0)) {
                continue;
            }

            $file_size = filesize(get_custom_file_base() . '/' . $file);
            if ($file_size < $max_size) {
                $size += $file_size;
            }
        }

        return make_string_tempcode(clean_file_size($size));
    }
}
