<?php
header('Content-Type:text/plain');
define('_JEXEC', 1);
define('JPATH_BASE', realpath('../../'));
define('JPATH_ROOT', realpath('../../'));

require_once JPATH_BASE . '/includes/defines.php';
require_once JPATH_BASE . '/includes/framework.php';

$container = \Joomla\CMS\Factory::getContainer();
$container->alias('session.web', 'session.web.site')
    ->alias('session', 'session.web.site')
    ->alias('JSession', 'session.web.site')
    ->alias(\Joomla\CMS\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\Session::class, 'session.web.site')
    ->alias(\Joomla\Session\SessionInterface::class, 'session.web.site');
$app = $container->get(\Joomla\CMS\Application\SiteApplication::class);
\Joomla\CMS\Factory::$application = $app;

// Create the Application
$globalParams = JComponentHelper::getParams('com_pixelcms_articles');

if (!isset($_REQUEST['api_key']) || ($_REQUEST['api_key'] !== $globalParams->get('pixel_cms_token'))) {
	header('HTTP/1.0 401 Unauthorized');
	die('Keine Berechtigung zum Aufruf des Cache Cleaners');
}

function rrmdir($src) {
    $dir = opendir($src);
    while(false !== ( $file = readdir($dir)) ) {
        if (( $file != '.' ) && ( $file != '..' )) {
            $full = $src . '/' . $file;
            if ( is_dir($full) ) {
                rrmdir($full);
            }
            else {
                unlink($full);
            }
        }
    }
    closedir($dir);
    return rmdir($src);
}

function clearCache($cache = null) {
	$basepath = realpath(JPATH_ROOT.'/cache').'/';
	if ($cache) {
		$clean = glob(JPATH_ROOT."/cache/$cache");
	} else {
		$clean = glob(JPATH_ROOT."/cache/*", GLOB_ONLYDIR);
	}
	$clean = array_map(function($src) use ($basepath) {
		if (!substr_count(realpath($src), $basepath)) return "$src: skipped!";
		if (is_dir($src)) {
			$success = rrmdir($src);
		} else {
			$success = unlink($src);
		}
		return "$src: ".(($success) ? 'deleted' : 'failed');
	}, $clean);
	return $clean;
}

if (isset($_REQUEST['clear'])) {
	$clear = $_REQUEST['clear'];
	$clear = is_array($clear) ? $clear : explode(',', $clear);

	$cleaned = [];
	foreach ($clear as $key => $cache) {
		$cleaned = array_merge($cleaned, clearCache($cache));
	}
} else {
	$cleaned = clearCache();
}
foreach ($cleaned as $key => $value) {
	echo "$value\n";
}
