<?php /*

 Composr
 Copyright (c) Christopher Graham, 2004-2024

 See docs/LICENSE.md for full licensing 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  Christopher Graham
 * @package    core_cleanup_tools
 */

/**
 * Hook class.
 */
class Hook_task_find_broken_urls
{
    /**
     * Run the task hook.
     *
     * @param  ID_TEXT $urls_identifier The cache identifier which holds the URLs we are scanning
     * @param  boolean $show_passes Whether to show passes
     * @return ?array A tuple of at least 2: Return mime-type, content (either Tempcode, or a string, or a filename and file-path pair to a temporary file), map of HTTP headers if transferring immediately, map of ini_set commands if transferring immediately (null: show standard success message)
     */
    public function run(string $urls_identifier, bool $show_passes) : ?array
    {
        require_lang('cleanup');
        require_code('broken_urls');
        require_code('caches');

        $_urls = get_cache_entry('broken_urls_choose', serialize([$urls_identifier]));
        if ($_urls === null) {
            warn_exit(do_lang_tempcode('INTERNAL_ERROR'));
        }
        $urls = unserialize($_urls);

        $url_scanner = new BrokenURLScanner();

        $i = 0;
        foreach ($urls as $url => &$url_bits) {
            task_log($this, 'Checking URL', $i, count($urls));

            $message = '';
            $passed = $url_scanner->check_url($url, $message);

            if ((!$show_passes) && ($passed)) {
                unset($urls[$url]);
                continue;
            }

            $url_bits['STATUS'] = $passed;
            $url_bits['MESSAGE'] = $message;

            $i++;
        }

        $ret = do_template('BROKEN_URLS', ['_GUID' => '840e203e9f2643ffd806ad3849597c3b', 'URLS' => $urls, 'DONE' => true]);

        return ['text/html', $ret];
    }
}
