<?php
/*****************************************************************************
 * Router.php
 * Contains key class Router.
 *
 * Kabuki CMS (C) 2013-2015, Aaron van Geffen
 *****************************************************************************/

class Router
{
	public static function route()
	{
		$possibleActions = [
			'accountsettings' => 'AccountSettings',
			'addalbum' => 'EditAlbum',
			'albums' => 'ViewPhotoAlbums',
			'editalbum' => 'EditAlbum',
			'editasset' => 'EditAsset',
			'edittag' => 'EditTag',
			'edituser' => 'EditUser',
			'login' => 'Login',
			'logout' => 'Logout',
			'managealbums' => 'ManageAlbums',
			'manageassets' => 'ManageAssets',
			'manageerrors' => 'ManageErrors',
			'managetags' => 'ManageTags',
			'manageusers' => 'ManageUsers',
			'people' => 'ViewPeople',
			'resetpassword' => 'ResetPassword',
			'suggest' => 'ProvideAutoSuggest',
			'timeline' => 'ViewTimeline',
			'uploadmedia' => 'UploadMedia',
			'download' => 'Download',
		];

		// Work around PHP's FPM not always providing PATH_INFO.
		if (empty($_SERVER['PATH_INFO']) && isset($_SERVER['REQUEST_URI']))
		{
			if (strpos($_SERVER['REQUEST_URI'], '?') === false)
				$_SERVER['PATH_INFO'] = $_SERVER['REQUEST_URI'];
			else
				$_SERVER['PATH_INFO'] = substr($_SERVER['REQUEST_URI'], 0, strpos($_SERVER['REQUEST_URI'], '?'));
		}

		// Just showing the album index?
		if (empty($_SERVER['PATH_INFO']) || $_SERVER['PATH_INFO'] == '/')
		{
			return new ViewPhotoAlbum();
		}
		// Asynchronously generating thumbnails?
		elseif (preg_match('~^/thumbnail/(?<id>\d+)/(?<width>\d+)x(?<height>\d+)(?:_(?<mode>c(t|b|s|)))?/?~', $_SERVER['PATH_INFO'], $path))
		{
			$_GET = array_merge($_GET, $path);
			return new GenerateThumbnail();
		}
		// Look for particular actions...
		elseif (preg_match('~^/(?<action>[a-z]+)(?:/page/(?<page>\d+))?/?~', $_SERVER['PATH_INFO'], $path) && isset($possibleActions[$path['action']]))
		{
			$_GET = array_merge($_GET, $path);
			return new $possibleActions[$path['action']]();
		}
		// An album, person, or any other tag?
		elseif (preg_match('~^/(?<tag>.+?)(?:/page/(?<page>\d+))?/?$~', $_SERVER['PATH_INFO'], $path) && Tag::matchSlug($path['tag']))
		{
			$_GET = array_merge($_GET, $path);
			return new ViewPhotoAlbum();
		}
		// A photo for sure, then, right?
		elseif (preg_match('~^/(?<slug>.+?)/?$~', $_SERVER['PATH_INFO'], $path))
		{
			$_GET = array_merge($_GET, $path);
			return new ViewPhoto();
		}
		// No idea, then?
		else
			throw new NotFoundException();
	}
}