Save to cache

@param Controller $controller
@param InlineAction $action
@param string $output
512185
public function saveToCache($controller, $action, $output){

		if(!$this->needCache()){

			$replaced = $this->makeReplace($output);

			return $replaced;
		}

		$name = $this->generateFileName($controller, $action);

		$path = Yii::getAlias('@webroot') . $this->getAssetsUrl() . DIRECTORY_SEPARATOR . $this->folder;
		$this->checkPermissionsOrCreate($path);

		$file = $path . DIRECTORY_SEPARATOR . $name;

		$fp = fopen($file, 'w');

		$replaced = $this->makeReplace($output);

		$output = str_replace(Yii::$app->request->getCsrfToken(), '{CSRF_TOKEN}', $output);


		if(!$fp){
			throw new Exception('Directory ' . $file . ' does not exists or does not have write permission');
		}

		fwrite($fp, $output);
		fclose($fp);

		Yii::$app->assetManager->publish(__DIR__ . DIRECTORY_SEPARATOR, true, 1);

		return $replaced;
	}
402506
protected function Cache($action, $filename, $data = '', $max_age = '')
    {
        if (!is_dir($this->cache_dir)) {
            return '';
        }

        // Set the full path
        $cache_file = $this->cache_dir . $filename;

        $cache = '';

        if ($action == 'get') {
            // Clear the file stats
            clearstatcache();

            if (is_file($cache_file) && $max_age != '') {
                // Make sure $max_age is negitive
                if (is_string($max_age) && substr($max_age, 0, 1) != '-') {
                    $max_age = '-' . $max_age;
                }

                // Make sure $max_age is an INT
                if (!is_int($max_age)) {
                    $max_age = strtotime($max_age);
                }

                // Test to see if the file is still fresh enough
                if (filemtime($cache_file) >= date($max_age)) {
                    $cache = file_get_contents($cache_file);
                }
            }
        } else {
            if (is_writable($this->cache_dir)) {
                // Serialize the Fields
                $store = serialize($data);

                //Open and Write the File
                $fp = fopen($cache_file, "w");
                fwrite($fp, $store);
                fclose($fp);
                chmod($cache_file, 0770);

                $cache = strlen($store);
            }
        }

        return $cache;
    }
575204
public function beforeRender(Controller $controller) {
		$configs = Cache::configured();
		$content = array();

		if (method_exists('Cache', 'getLogs')) {
			$content['stats'] = Cache::getLogs();
		}

		foreach($configs as $config)
		{
			$engine = Cache::settings($config);

			if (method_exists('Cache', 'getLogs')) {
				$logs = Cache::getLogs($config);
			} else {
				$logs['logs'] = array();
			}

			$content['cache'][$config] = array('settings' => $engine, 'logs' => $logs['logs']);
		}

		ksort($content['cache']);

		if ($this->priority > 0 && isset($content['stats'])) {
			if ($content['stats']['count'] === 0) {
				$this->title = __d('debug_kit_ex', '<b>0</b> cache');
			} else {
				$this->title = __d('debug_kit_ex', '<b>%dms / %d</b> cache', round($content['stats']['time']), $content['stats']['count']['total']);
			}
		}

		return $content;
	}
731647
public function patch(string $uri, string $controller, string $action)
    {
        $this->addRoute('PATCH', $uri, $controller, $action);
    }
1269116
private static function cached($actionContext) {
        $httpContext = $actionContext->getHttpContext();
        $request = $httpContext->getRequest();

        // TODO: support POST
        if ($request->isPost()) {
            return false;
        }

        $cacheSettings = InternalHelper::getStaticPropertyValue('\\PhpMvc\\OutputCache', 'settings');
        $actionName = $actionContext->getActionName();

        if (!isset($cacheSettings[$actionName])) {
            $cacheSettings[$actionName] = array();
        }

        if (!isset($cacheSettings['.'])) {
            $cacheSettings['.'] = array();
        }

        if (empty($cacheSettings[$actionName]) && empty($cacheSettings['.'])) {
            return false;
        }

        // location
        if (!empty($cacheSettings[$actionName]['location'])) {
            $location = intval($cacheSettings[$actionName]['location']);
        }
        elseif (!empty($cacheSettings['.']['location'])) {
            $location = intval($cacheSettings['.']['location']);
        }
        else {
            $location = OutputCacheLocation::ANY;
        }

        if (array_search($location, array(OutputCacheLocation::ANY, OutputCacheLocation::SERVER, OutputCacheLocation::SERVER_AND_CLIENT)) === false) {
            return false;
        }

        // vary by parameters
        $params = self::getCacheParams($actionContext, $cacheSettings, 'varyByParam', array_merge($request->get(), $actionContext->getArguments()));

        // vary by headers
        $headers = self::getCacheParams($actionContext, $cacheSettings, 'varyByHeader', $request->headers());

        // vary by custom handlers
        $custom = self::getCacheParams($actionContext, $cacheSettings, 'varyByCustom');

        // check cache
        $response = $httpContext->getResponse();
        $cache = $httpContext->getCache();

        $cacheKey = 'output_' . $request->path() . '_params=' . implode('&', $params) . '_http=' . implode('&', $headers) . '_custom=' . implode('&', $custom);

        if (($cachedResponse = $cache->get($cacheKey)) !== null) {
            $response->setHeaders($cachedResponse['headers']);
            $response->setCookies($cachedResponse['cookies']);
            $response->setStatusCode($cachedResponse['statusCode']);
            $response->setStatusDescription($cachedResponse['statusDescription']);
            $response->writeFile($cachedResponse['files']);
            $response->write($cachedResponse['output']);
            $response->end();
            return true;
        }

        InternalHelper::setPropertyValue($actionContext, 'cacheKey', $cacheKey);

        return false;
    }
456021
private function determineControllerAndAction(&$controller, &$actionName)
    {
        $request = $this->getRequest();
        $this->invokePluginsHook(
            'beforeControllerSelected',
            array($this, $request)
        );

        $controllerDiKey = $request->getController();
        try {
            $controller = $this->getServiceProvider()->getServiceInstance($controllerDiKey);
        } catch (Exception $e) {
            throw new ResourceNotFoundException(sprintf(
                'No such controller found "%s".',
                $this->getRequest()->getController()
            ));
        }
        $actionName = $request->getAction();
        if (!method_exists($controller, $actionName)) {
            throw new ResourceNotFoundException(sprintf(
                '%s does not have method %s',
                $controllerDiKey,
                $actionName
            ));
        }
        $this->invokePluginsHook(
            'afterControllerSelected',
            array($this, $request, $controller, $actionName)
        );
        $controller->initialize($request, $this);
    }
167291
public function dispatchAction($controller)
    {
        $action = $this->matchRoute[key($this->matchRoute)]['action'] . 'Action';

        $viewModel = $controller->$action();

        if ($viewModel instanceof ViewModel) {
            $this->view->setVariables($viewModel->getVariables());
        }
    }
400151
public function write($output)
    {
        //lets parse the file
        if ($this->_hasBeenModified($this->_file) || !file_exists($output)) {
            //get the data
            file_put_contents($output, $this->getData());
            //update the timestamp
            $this->_cache_data['timestamp'] = time();
            file_put_contents($this->_cache_file, serialize($this->_cache_data));
        }
    }
1130198
public function update(SiteInterface $site, OutputInterface $output = null, $clean = false)
    {
        $message = sprintf(
            ' > <info>Updating core routes for site</info> : <comment>%s - %s</comment>',
            $site->getName(),
            $site->getUrl()
        );

        $this->writeln($output, [
            str_repeat('=', \strlen($message)),
            '',
            $message,
            '',
            str_repeat('=', \strlen($message)),
        ]);

        $knowRoutes = [];

        $root = $this->pageManager->getPageByUrl($site, '/');

        // no root url for the given website, create one
        if (!$root) {
            $root = $this->createRootPage($site);
            $this->pageManager->save($root);
        }

        // Iterate over declared routes from the routing mechanism
        foreach ($this->router->getRouteCollection()->all() as $name => $route) {
            $name = trim($name);

            $knowRoutes[] = $name;

            $page = $this->pageManager->findOneBy([
                'routeName' => $name,
                'site' => $site->getId(),
            ]);

            $routeHostRegex = $route->compile()->getHostRegex();

            if (
                !$this->decoratorStrategy->isRouteNameDecorable($name)
                || !$this->decoratorStrategy->isRouteUriDecorable($route->getPath())
                || null !== $routeHostRegex
                && !preg_match($routeHostRegex, $site->getHost())
            ) {
                if ($page) {
                    $page->setEnabled(false);

                    $this->writeln($output, sprintf(
                        '  <error>DISABLE</error> <error>% -50s</error> %s',
                        $name,
                        $route->getPath()
                    ));
                } else {
                    continue;
                }
            }

            $update = true;

            if (!$page) {
                $update = false;

                $requirements = $route->getRequirements();

                $page = $this->pageManager->create([
                    'routeName' => $name,
                    'name' => $name,
                    'url' => $route->getPath(),
                    'site' => $site,
                    'requestMethod' => $requirements['_method'] ??
                        'GET|POST|HEAD|DELETE|PUT',
                ]);
            }

            if (!$page->getParent() && $page->getId() !== $root->getId()) {
                $page->setParent($root);
            }

            $page->setSlug($route->getPath());
            $page->setUrl($route->getPath());
            $page->setRequestMethod($requirements['_method'] ??
                'GET|POST|HEAD|DELETE|PUT');

            $this->pageManager->save($page);

            $this->writeln($output, sprintf(
                '  <info>%s</info> % -50s %s',
                $update ? 'UPDATE ' : 'CREATE ',
                $name,
                $route->getPath()
            ));
        }

        // Iterate over error pages
        foreach ($this->exceptionListener->getHttpErrorCodes() as $name) {
            $name = trim((string) $name);

            $knowRoutes[] = $name;

            $page = $this->pageManager->findOneBy([
                'routeName' => $name,
                'site' => $site->getId(),
            ]);

            if (!$page) {
                $params = [
                    'routeName' => $name,
                    'name' => $name,
                    'decorate' => false,
                    'site' => $site,
                ];

                $page = $this->pageManager->create($params);

                $this->writeln($output, sprintf('  <info>%s</info> % -50s %s', 'CREATE ', $name, ''));
            }

            // an internal page or an error page should not have any parent (no direct access)
            $page->setParent(null);
            $this->pageManager->save($page);
        }

        $has = false;

        foreach ($this->pageManager->getHybridPages($site) as $page) {
            if (!$page->isHybrid() || $page->isInternal()) {
                continue;
            }

            if (!\in_array($page->getRouteName(), $knowRoutes, true)) {
                if (!$has) {
                    $has = true;

                    $this->writeln($output, ['', 'Some hybrid pages does not exist anymore', str_repeat('-', 80)]);
                }

                if ($clean) {
                    $this->pageManager->delete($page);

                    $this->writeln($output, sprintf('  <error>REMOVED</error>   %s', $page->getRouteName()));
                } else {
                    $this->writeln($output, sprintf('  <error>ERROR</error>   %s', $page->getRouteName()));
                }
            }
        }

        if ($has && !$clean) {
            $this->writeln($output, <<<'MSG'
<error>
  *WARNING* : Pages has been updated however some pages do not exist anymore.
              You must remove them manually.
</error>
MSG
            );
        }
    }
576608
public function getActionLink($controller, $action = 'index', $remove = false)
    {
        $key = $this->_getKey($controller, $action);

        if ($this->offsetExists($key)) {

            $result = $this->toActionLink($key);

            if ($remove) {
                $this->offsetUnset($key);
            }

            return $result;
        }
    }
874781
public function writeSeedOut(OutputInterface $output, $force)
    {
        $class      = $this->getClass();
        $modelClass = $this->getModelClass();

        $fileName = $class . '.php';

        list($structure, $data, $count) = $this->renderData();

        if ($count > 0) {
            $this->writeToFileFromTemplate($this->path . '/' . $fileName, 'seeder', $output, [
                'use'       => $modelClass,
                'className' => $this->getClass(),
                'tableName' => snake_case($this->table->getTableName()),
                'model'     => class_basename($modelClass),
                'structure' => var_export($structure, true),
                'count'     => $count,
            ], $force);

            $this->writeToFileFromTemplate($this->path . '/data/' . snake_case($this->table->getTableName()) . '_table_data.php', 'seederData', $output, [
                'data' => $data,
            ], $force);
        }
    }
1265185
private function doDump(AssetInterface $asset, OutputInterface $stdout)
    {
        $combinations = VarUtils::getCombinations(
            $asset->getVars(),
            $this->getContainer()->getParameter('assetic.variables')
        );

        foreach ($combinations as $combination) {
            $asset->setValues($combination);

            // resolve the target path
            $target = rtrim($this->basePath, '/').'/'.$asset->getTargetPath();
            $target = str_replace('_controller/', '', $target);
            $target = VarUtils::resolve($target, $asset->getVars(), $asset->getValues());

            if (!is_dir($dir = dirname($target))) {
                $stdout->writeln(sprintf(
                    '<comment>%s</comment> <info>[dir+]</info> %s',
                    date('H:i:s'),
                    $dir
                ));

                if (false === @mkdir($dir, 0777, true)) {
                    throw new \RuntimeException('Unable to create directory '.$dir);
                }
            }

            $stdout->writeln(sprintf(
                '<comment>%s</comment> <info>[file+]</info> %s',
                date('H:i:s'),
                $target
            ));

            if (OutputInterface::VERBOSITY_VERBOSE <= $stdout->getVerbosity()) {
                if ($asset instanceof AssetCollectionInterface) {
                    foreach ($asset as $leaf) {
                        $root = $leaf->getSourceRoot();
                        $path = $leaf->getSourcePath();
                        $stdout->writeln(sprintf('        <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
                    }
                } else {
                    $root = $asset->getSourceRoot();
                    $path = $asset->getSourcePath();
                    $stdout->writeln(sprintf('        <comment>%s/%s</comment>', $root ?: '[unknown root]', $path ?: '[unknown path]'));
                }
            }

            if (false === @file_put_contents($target, $asset->dump())) {
                throw new \RuntimeException('Unable to write file '.$target);
            }
        }
    }
116170
private static function caching($actionContext) {
        $cacheKey = InternalHelper::getPropertyValue($actionContext, 'cacheKey');

        // no key, no cache
        if (empty($cacheKey)) {
            return;
        }

        $cacheSettings = InternalHelper::getStaticPropertyValue('\\PhpMvc\\OutputCache', 'settings');
        $actionName = $actionContext->getActionName();
        $httpContext = $actionContext->getHttpContext();
        $response = $httpContext->getResponse();
        $cache = $httpContext->getCache();

        // cache duration
        if (!empty($cacheSettings[$actionName]['duration'])) {
            $duration = intval($cacheSettings[$actionName]['duration']);
        }
        elseif (!empty($cacheSettings['.']['duration'])) {
            $duration = intval($cacheSettings['.']['duration']);
        }
        else {
            $duration = 0;
        }

        // TODO: regionName
        $regionName = null;

        $dataToCache = array();

        // add response to cache
        if (($cachePartSeq = $cache->get($cacheKey . '_part_seq')) === null) {
            $dataToCache['statusCode'] = $response->getStatusCode();
            $dataToCache['statusDescription'] = $response->getStatusDescription();
            $dataToCache['headers'] = $response->getHeaders();
            $dataToCache['cookies'] = $response->getCookies();
            $dataToCache['files'] = InternalHelper::getPropertyValue($response, 'files');
            $dataToCache['output'] = InternalHelper::getPropertyValue($response, 'output');
        }
        else {
            $dataToCache['statusCode'] = $response->getStatusCode();
            $dataToCache['statusDescription'] = $response->getStatusDescription();
            $dataToCache['headers'] = $response->getHeaders();
            $dataToCache['cookies'] = $response->getCookies();
            $dataToCache['files'] = array();
            $dataToCache['output'] = '';

            for ($i = 0; $i < $cachePartSeq; ++$i) {
                $part = $cache->get($cacheKey . '_part_' . $i);

                if ($part !== null) {
                    $dataToCache['output'] .= $part['output'];
                    $dataToCache['files'] = array_merge($dataToCache['files'], $part['files']);
                    $cache->remove($cacheKey . '_part_' . $i);
                }
            }

            $cache->remove($cacheKey . '_part_seq');
        }

        $cache->add($cacheKey, $dataToCache, $duration, $regionName);
    }
1165841
public static function setMCA(string $module, string $controller, string $action): void
    {
        self::$module = $module;
        self::$controller = $controller;
        self::$action = $action;
    }
516593
private static function execController($controller,$action,$args){
        $controller = new $controller();
        $controller->doAction($action,$args);
    }
864756
function performAction($controller,$action,$queryString = null,$render = 0) {
		$controllerFile = ROOT . '/application/controllers/' . $controller . "controller.php";
		//print "Trying to load $controllerFile<br>";
		if (file_exists($controllerFile)){
			//print "File exists<br>";
			include_once($controllerFile);
		} else {
			throw new Exception("Controller file: $controllerFile does not exists");
		}
		$controllerName = ucfirst($controller).'Controller';
		$actionName= $action . 'Action'; // This is done to avoid clash with reserved function names like list();
		if (class_exists($controllerName)){
			
		} else {
			throw new Exception("ControllerClass: $controllerName does not exists");
		}

		//print "Trying to load $controllerName<br>"; 
		$dispatch = new $controllerName($controller, $action);
		$dispatch->render = $render;
		$dispatch->$actionName($queryString);

		if ($dispatch->render >0) {
				$dispatch->display();
		}

	}
378484
public function post(string $uri, string $controller, string $action)
    {
        $this->addRoute('POST', $uri, $controller, $action);
    }