<?php
/*
 * Copyright (c) 2012, webvariants GbR, http://www.webvariants.de
 *
 * This file is released under the terms of the MIT license. You can find the
 * complete text in the attached LICENSE file or online at:
 *
 * http://www.opensource.org/licenses/mit-license.php
 */

abstract class _WV24_Mp_Extensions {
	public static function onResolveArticle(array $params) {
		if ($params['subject'] !== null) return $params['subject'];

		$host     = sly_Util_HTTP::getHost();
		$wwwAlt   = WV24_Util::getWwwAlternative($host);
		$cache    = sly_Core::cache();
		$ns       = 'realurl2.volatile.mp';
		$fallback = $cache->get($ns, $host, null);

		if ($fallback === null) {
			$sql      = WV_SQL::getInstance();
			$project  = $sql->fetch('id, clang', 'article', 'startpage = 1 AND (wv24_fragment LIKE ? OR wv24_fragment LIKE ?)', array("//$host%", "//$wwwAlt%"), '~');
			$fallback = false;

			if ($project !== false) {
				$artID   = $project['id'];
				$clang   = $project['clang'];

				// make datatypes happy (linklist will validate the articles before returning them)
				sly_Core::setCurrentClang($clang);

				$project  = sly_Util_Article::findById($artID);
				$articles = WV8_Settings::getValue('realurl2.mp', '404articles');

				foreach ($articles as $art) {
					$art = sly_Util_Article::findById($art);

					// if this 404art is inside the project category, use it.
					if ($art->inParentTree($project)) {
						$fallback = $art;
						break;
					}
				}
			}

			$cache->set($ns, $host, $fallback ? $fallback->getId() : false);
		}

		if ($fallback === false) {
			return null;
		}

		$controller = sly_Core::getCurrentController();

		if ($controller instanceof sly_Controller_Frontend_Article) {
			$controller->setIsNotFound(true);
		}

		if (!$fallback instanceof sly_Model_Article) {
			$fallback = sly_Util_Article::findById($fallback, sly_Core::getDefaultClangId());
		}

		return $fallback;
	}
}
