<?php
/**
*    Отображение ошибок
*/
error_reporting(0);
/**
*    Подключаю библиотеки
*/
include 'includes/flight/Flight.php';
include 'includes/helpers.php';
include 'includes/templater.php';
include 'includes/idiorm.php';
include 'includes/UTF8.php';
include 'includes/URLify.php';
include 'includes/Http.php';
include 'includes/nokogiri.php';
include 'includes/cleaner.php';

/**
*    Подключаю переменные в систему
*/
Flight::set('base_url','http://' . $_SERVER['HTTP_HOST'] . rtrim(dirname($_SERVER['SCRIPT_NAME']), '/.\\') . '/');
Flight::set('docs_root', realpath(dirname(__FILE__)) . DIRECTORY_SEPARATOR);
Flight::set('templates_root', realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR.'templates') . DIRECTORY_SEPARATOR);
Flight::set('plugins_root', realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR.'plugins') . DIRECTORY_SEPARATOR);
Flight::set('data_root', realpath(dirname(__FILE__) . DIRECTORY_SEPARATOR.'data') . DIRECTORY_SEPARATOR);
Flight::set('flight.views.path', Flight::get('docs_root').'/includes/views');

/*
*	Подключаю файл с конфигурацией	
*/
$config = file_exists('config.php')?include('config.php'):die('Нет файла конфигурации');

/**
*    Подключаю плагины в систему
*/
foreach (glob(Flight::get('plugins_root')."*.php") as $filename)
{
    include $filename;
}

/**
*   Регистрирую доп класы в систему
*/
Flight::register('template', 'Templater');

/**
*    Настраиваю соединение с БД
*/
ORM::configure($config['database']);
ORM::configure('id_column_overrides', array(
    'article' => 'id',
    'category' => 'category_id',
    'keyword' => 'keyword_id'
));

/**
*   Для сохранения массивов как конфиг файлов
*/
Flight::map('save', function($path, $array) {
		$content = '<?php' . PHP_EOL . 'return ' . var_export($array, true) . ';';
    	return is_numeric(file_put_contents($path, $content));
});

/**
*    Установка скрипта
*/
Flight::map('install', function() use ($config) {
	$db = ORM::get_db();
	$db->exec("PRAGMA synchronous = OFF;");
	$db->exec("
			CREATE TABLE IF NOT EXISTS article (
				id INTEGER PRIMARY KEY,
				keyword TEXT,
				meta_title TEXT,
				meta_description TEXT,
				meta_keywords TEXT,
				h_title TEXT,
				url TEXT,
				short_story TEXT,
				full_story TEXT,				
				category_id INTEGER,
                created_at DATETIME DEFAULT CURRENT_TIMESTAMP
			);"
		);
	$db->exec("
			CREATE TABLE IF NOT EXISTS category (
				category_id INTEGER PRIMARY KEY,
				category_name TEXT,
				category_url TEXT
			);"
		);
	$db->exec("
			CREATE TABLE IF NOT EXISTS keyword (
				keyword_id INTEGER PRIMARY KEY,
				keyword_name TEXT,
				keyword_current INTEGER
			);"
		);
    /**
    *    Наполняю базу категориями
    */    
    foreach($config['categories'] as $value)
    {
        $category = ORM::for_table('category')->create();
        $category->category_name = $value;
        $category->category_url = URLify::filter ($value);
        $category->save();
    }
    /**
    *	Регистрирую все файлы с ключами
    */
    foreach (glob(Flight::get('data_root')."*.txt") as $filename)
	{
	    $keyword = ORM::for_table('keyword')->create();
        $keyword->keyword_name = $filename;
        $keyword->keyword_current = 0;
        $keyword->save();
	}
    
    /**
        Наполняю фейком статьи
    
    $categories = ORM::for_table('category')->select('category_id')->find_array();
    $demo_key = 'мама мыла раму';
    
    for($i=0;$i<32;$i++)
    {
        $rand_id = array_rand($categories);

        $article = ORM::for_table('article')->create();
        $article->keyword = $demo_key.$i;
        $article->meta_title = UTF8::utf8_ucfirst($demo_key).$i;
        $article->meta_description = UTF8::utf8_ucfirst($demo_key).$i;
        $article->meta_keywords = UTF8::utf8_ucfirst($demo_key).$i;
        $article->h_title = UTF8::utf8_ucfirst($demo_key).$i;
        $article->url = URLify::filter ( $demo_key.$i);
        $article->short_story = $demo_key.$i;
        $article->full_story = $demo_key.$i;
        $article->category_id = $categories[$rand_id]['category_id'];
        $article->created_at = time();
        $article->save();
    }
    */
    
});

/**
*    Проверяю окружение и установку
*/
Flight::map('check', function() {
	if (version_compare(phpversion(), "5.3.0", "=<")) { 
	  	die('Версия PHP должна быть новее 5.3.0.');
	}
    if (!extension_loaded('mbstring')) 
    {
		die('mbstring.so не установлен.');
	}
    if (!extension_loaded('iconv')) 
    {
		die('iconv.so не установлен.');
	}
	if (!extension_loaded('pdo'))
    {
		die('pdo.so не установлен.');
	}
	if (!extension_loaded('pdo_sqlite'))
    {
		die('pdo_sqlite.so не установлен.');
	}
	
    /**
    *    Проверяю существуют ли нужные таблици
    */
    try {
        ORM::for_table('category')->count();
    } catch (Exception $e) {
        Flight::install();
    }   

});

/**
*    Проверка Окружения
*/
Flight::check();

/**
*    ХУКИ
*/

/**
*    Вывод Аутов(слива) в шаблон 
*/
Flight::map('render_site_outs',function($outs) {
    foreach( $outs as $snippet => $out) {
		Flight::template()->set($snippet, $out);	
	}
});

/**
*	Генерация страниц из файла. Метод.
*/
Flight::map('generate_by', function() use ($config) {	
	$type_template = '';
	switch ($config['site']['generate_by']) {
		case 'ajax':
			$type_template ='<script>
								  	$(document).ready(function() {
										$.get( "'.Flight::get('base_url').'find/", function( data ) {});
									});
							</script>';
		break;

		case 'iframe':
			$type_template ='<iframe src="'.Flight::get('base_url').'find/" width="0" height="0"></iframe>';
		break;

		case 'php':
			$type_template = eval('echo $content = @file_get_contents("'.Flight::get('base_url').'find/");');
		break;

		case 'none':
			$type_template = '';
		break;

		default:
		  	$type_template = '';
	}
	return $type_template;
});

/**
*    Вывод Шапки шаблона
*/
Flight::map('render_theme_header', function() use ($config) {

    Flight::template()->dir = Flight::get('templates_root').$config['site']['current_template'];
    Flight::template()->load_template('main.tpl');    
    Flight::template()->set('{THEME}', Flight::get('base_url').'templates/'.$config['site']['current_template']);
	Flight::template()->set('{login}', '');
	Flight::template()->set('{info}', '');
	Flight::template()->set('{sort}', '');
	Flight::template()->set('{speedbar}', '');
	Flight::template()->set('{vote}', '');
	Flight::template()->set('{changeskin}', '');
    Flight::template()->set('/index.php?do=feedback', '');
	Flight::template()->set('/index.php?do=rules', '');
	Flight::template()->set('/index.php?do=lastnews', '');
	Flight::template()->set('/index.php?action=mobile', '');
	Flight::template()->set('/index.php?do=search&mode=advanced', '');
	Flight::template()->set('/index.php', Flight::get('base_url'));
    Flight::template()->set('{AJAX}', Flight::generate_by());
	Flight::template()->set_block ("#\\[not-group=(.+?)\\](.*?)\\[/not-group\\]#is", '' );
	Flight::template()->set_block ("#\\[group=(.+?)\\](.*?)\\[/group\\]#is", '' );
	Flight::template()->set_block ("#\\[sort](.*?)\\[/sort\\]#is", '' );
	Flight::template()->set_block ("#\\[edit](.*?)\\[/edit\\]#is", '' );
	Flight::template()->set_block ("#\\[aviable=(.+?)\\](.*?)\\[/aviable\\]#is", '' );
	Flight::template()->set_block ("#\\[not-aviable=(.+?)\\](.*?)\\[/not-aviable\\]#is", '' );
	Flight::template()->set_block ("#\\[page-count=(.+?)\\](.*?)\\[/page-count\\]#is", '' );
	Flight::template()->set_block ("#\\[not-page-count=(.+?)\\](.*?)\\[/not-page-count\\]#is", '' );
	Flight::template()->set_block ("#\\{custom(.+?)}#is", '');
    
    /**
	*	Загружаю ауты в шаблон
	*/
    $outs = array();
    $outs = $config['out'];
    Flight::render_site_outs($outs);
});

/**
*    Вывод Подвалa шаблона
*/
Flight::map('render_theme_footer', function() {
    Flight::template()->compile('main');
	eval (' ?' . '>' . Flight::template()->result['main'] . '<' . '?php '); 
	Flight::template()->global_clear(); 
});


/**
*    Вывод МЕТА Главной
*/
Flight::map('render_home_meta', function($data) {
    
    $headers = array();
    
    $headers[] = '<title>'.$data['title'].'</title>';
    $headers[] = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';                    
	$headers[] = '<meta name="robots" content="'.$data['robots'].'" />';
	$headers[] = '<meta name="generator" content="'.$data['generator'].'" />';   
	$headers[] = '<meta name="keywords" content="'.$data['keywords'].'" />';	
	$headers[] = '<meta name="description" content="'.$data['description'].'" />';

	$headers[] = '<link rel="sitemap" type="application/xml" title="Sitemap" href="'.Flight::get('base_url').'sitemap.xml" />';
	$headers[] = '<link rel="alternate" type="application/rss+xml" title="RSS" href="'.Flight::get('base_url').'rss.xml" />';
	$headers[] = '<link type="text/plain" rel="author" href="'.Flight::get('base_url').'humans.txt" />';

	$headers[] = '<script language="javascript" type="text/javascript" src="'.Flight::get('base_url').'includes/views/assets/js/jquery-2.1.4.min.js"></script>';	
	$headers[] = '<script src="//unslider.com/unslider.min.js"></script>';
	$headers[] = '<script>$(function() {$(\'.banner\').unslider({dots: true});});</script>';
	$headers[]= '<style>.banner { position: relative; overflow: auto; }.banner li { list-style: none; }.banner ul li { float: left; }</style>';
    
	return implode(PHP_EOL, $headers);
});

/**
*    Вывод МЕТА Категории
*/
Flight::map('render_category_meta', function($category_id, $data) {
    
    $headers = array();
    
	$headers[] = '<title>'.$data['title'].'</title>';
    $headers[] = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';
	$headers[] = '<meta name="robots" content="'.$data['robots'].'" />';
	$headers[] = '<meta name="generator" content="'.$data['generator'].'" />';   
	$headers[] = '<meta name="keywords" content="'.$data['keywords'].'" />';	
	$headers[] = '<meta name="description" content="'.$data['description'].'" />';

	$headers[] = '<link rel="sitemap" type="application/xml" title="Sitemap" href="'.Flight::get('base_url').'sitemap.xml" />';
	$headers[] = '<link rel="alternate" type="application/rss+xml" title="RSS" href="'.Flight::get('base_url').'rss.xml" />';
	$headers[] = '<link type="text/plain" rel="author" href="'.Flight::get('base_url').'humans.txt" />';

	$headers[] = '<script language="javascript" type="text/javascript" src="'.Flight::get('base_url').'includes/views/assets/js/jquery-2.1.4.min.js"></script>';	
	$headers[] = '<script src="//unslider.com/unslider.min.js"></script>';
	$headers[] = '<script>$(function() {$(\'.banner\').unslider({dots: true});});</script>';
	$headers[]= '<style>.banner { position: relative; overflow: auto; }.banner li { list-style: none; }.banner ul li { float: left; }</style>';
	return implode(PHP_EOL, $headers);
});

/**
*    Вывод МЕТА Статьи
*/
Flight::map('render_article_meta', function($post) use ($config) { 
    
	$headers = array();
    
	$headers[] = '<title>'.$post['meta_title'].'</title>';
    $headers[] = '<meta http-equiv="content-type" content="text/html; charset=utf-8" />';     
	$headers[] = '<meta name="robots" content="'.$config['site']['meta_name_robots'].'" />';
	$headers[] = '<meta name="generator" content="'.$config['site']['meta_name_generator'].'" />';
	$headers[] = '<meta name="keywords" content="'.$post['meta_keywords'].'" />';	
	$headers[] = '<meta name="description" content="'.$post['meta_description'].'" />';

    $headers[] = '<link rel="sitemap" type="application/xml" title="Sitemap" href="'.Flight::get('base_url').'sitemap.xml" />';
    $headers[] = '<link rel="alternate" type="application/rss+xml" title="RSS" href="'.Flight::get('base_url').'rss.xml" />';
    $headers[] = '<link type="text/plain" rel="author" href="'.Flight::get('base_url').'humans.txt" />';

    $headers[] = '<script language="javascript" type="text/javascript" src="'.Flight::get('base_url').'includes/views/assets/js/jquery-2.1.4.min.js"></script>';	
	$headers[] = '<script src="//unslider.com/unslider.min.js"></script>';
	$headers[] = '<script>$(function() {$(\'.banner\').unslider({dots: true});});</script>';
	$headers[]= '<style>.banner { position: relative; overflow: auto; }.banner li { list-style: none; }.banner ul li { float: left; }</style>';
	return implode(PHP_EOL, $headers);
    
});

/**
*    Получение статей для главной
*/
Flight::map('get_home_content',function($data) {
    return ORM::for_table('article')->join('category', array('article.category_id', '=', 'category.category_id'))->limit($data['limit'])->offset($data['offset'])->order_by_desc('created_at')->find_array();
});

/**
*    Получение статей для категории
*/
Flight::map('get_category_content',function($data) {
    return ORM::for_table('article')->where('article.category_id', $data['category_id'])->join('category', array('article.category_id', '=', 'category.category_id'))->limit($data['limit'])->offset($data['offset'])->order_by_desc('created_at')->find_array();
});

/**
*    Получение статьи
*/
Flight::map('get_article_content',function($data) {
    return ORM::for_table('article')->join('category', array('article.category_id', '=', 'category.category_id'))->find_one($data['article_id'])->as_array();
});

/**
*    Добавление статьи в БД 
*/
Flight::map('add_article_content',function($term, $category_id, $data) {
    $article = ORM::for_table('article')->create();
    
    $article->keyword = $data['keyword'];
    $article->meta_title = $data['meta_title'];
    $article->meta_description = $data['meta_description'];
    $article->meta_keywords = $data['meta_keywords'];
    $article->h_title = $data['h_title'];
    $article->url = $data['url'];
    $article->short_story = $data['short_story'];
    $article->full_story = $data['full_story'];
    $article->category_id = $data['category_id'];
    $article->created_at = time();
    $article->save();
    
    return $article->as_array();   
    
});

/**
*    Добавление категории в БД 
*/
Flight::map('add_category_content',function($data) {    
    $category = ORM::for_table('category')->create();
    
    $category->category_name = $data['category_name'];
    $category->category_url = $data['category_url'];
    $category->save();
    
    return $category->as_array();   
    
});

/**
*    Добавление Пункта в Меню Админку 
*/
Flight::map('add_menu_item',function($menu, $item) {        
    return array_merge ($menu, $item);
});

/**
*   СЕССИИ
*/

/**
*    Старт
*/
Flight::map('session_start', function($login) {
    session_start();
    $_SESSION['login'] = $login;    
});

/**
*    Проверка
*/
Flight::map('session_check', function() {
    session_start();
    return isset($_SESSION['login']);
    
});

/**
*    Стоп
*/
Flight::map('session_stop', function() {
    session_start();
    unset($_SESSION['login']); 
    session_destroy();
    Flight::redirect('/admin/login/');    
});

/**
*   РОУТИНГ
*/

/**
*    Главная
*/
Flight::route('(/page(/@id:[1-9]+))', function($id) use ($config) {

    Flight::render_theme_header();
    
    $data = array();
    
    $data['current_page'] = is_numeric($id)?$id:1;
	$data['limit'] = (int)$config['site']['articles_per_page'];
	$data['offset'] = ($data['current_page']-1)*$data['limit'];
        
    /**
    *    Получаю статьи для главной
    */    
	$posts = Flight::get_home_content($data);

	$posts_count = count($posts);
	$shortstory_tpl  = Flight::template()->sub_load_template('shortstory.tpl');
		
	if($posts_count>0) {
		for($i=0;$i<$posts_count;$i++) {
			$chank[$i]=str_replace('{title}', '<a href="'.Flight::get('base_url').'article/'.$posts[$i]['id'].'-'.$posts[$i]['url'].'">'.$posts[$i]['h_title'].'</a>', $shortstory_tpl);
			$chank[$i]=str_replace('{short-story}', $posts[$i]['short_story'], $chank[$i]);
			$chank[$i]=str_replace('{link-category}', '<a href="'.Flight::get('base_url').'category/'.$posts[$i]['category_id'].'-'.$posts[$i]['category_url'].'">'.$posts[$i]['category_name'].'</a>', $chank[$i]);
			$chank[$i]=str_replace('{category}', $posts[$i]['category_name'], $chank[$i]);
			$chank[$i]=str_replace('{THEME}', Flight::get('base_url').'templates/'.$config['site']['current_template'], $chank[$i]);
			$chank[$i]=str_replace('{author}', $config['site']['author'], $chank[$i]);
			$chank[$i]=str_replace('{date}', date('j-m-y',$posts[$i]['created_at']), $chank[$i]);
			$chank[$i]=str_replace('{views}', rand(1000,5000), $chank[$i]);
			$chank[$i]=str_replace('{rating}', rand(1000,5000), $chank[$i]);
			$chank[$i]=str_replace('{comments-num}', rand(100,300), $chank[$i]);
			$chank[$i]=str_replace('{favorites}', '', $chank[$i]);
			$chank[$i]=str_replace('[full-link]', '<a href="'.Flight::get('base_url').'article/'.$posts[$i]['id'].'-'.$posts[$i]['url'].'">', $chank[$i]);
			$chank[$i]=str_replace('[/full-link]', '</a>', $chank[$i]);
			$chank[$i]=str_replace('{full-link}', '', $chank[$i]);

			$chank[$i]=str_replace('[com-link]', "", $chank[$i]);
			$chank[$i]=str_replace('[/com-link]', "", $chank[$i]);
			$chank[$i]=str_replace('[day-news]', "", $chank[$i]);
			$chank[$i]=str_replace('[/day-news]', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[rating](.*?)\\[/rating\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[edit-date](.*?)\\[/edit-date\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[edit](.*?)\\[/edit\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[complaint](.*?)\\[/complaint\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[tags](.*?)\\[/tags\\]#is', "", $chank[$i]);	
		}			
		$content  = implode('',$chank);		
	}else{
		$content='';
	}		
			
	$navigation_tpl = Flight::template()->sub_load_template('navigation.tpl');
	$content = $content.$navigation_tpl;
		
	if($data['current_page']>1)
    {
		$prev_link = Flight::get('base_url').'page/'.($data['current_page']-1);
		$content=str_replace('[prev-link]', '<a href="'.$prev_link.'">', $content);
		$content=str_replace('[/prev-link]', "</a>", $content);	
	}else{
		$content=str_replace('[prev-link]', '', $content);
		$content=str_replace('[/prev-link]', '', $content);	
	}		
		
	if($posts_count==$data['limit']) {
		$next_link = Flight::get('base_url').'page/'.($data['current_page']+1);
		$content=str_replace('[next-link]', '<a href="'.$next_link.'">', $content);
		$content=str_replace('[/next-link]', "</a>", $content);
	}else{
		$content=str_replace('[next-link]', '', $content);
		$content=str_replace('[/next-link]', '', $content);
	}
		
	$content=str_replace('{pages}', '', $content);

    /**
    *    Формирую массив с данными, с помощью плагинов переопределю, потом 
    */
    $data = array
    (
        'title'=>$config['site']['meta_name_title_index'],
        'description'=>$config['site']['meta_name_description_index'],
        'keywords'=>$config['site']['meta_name_keywords_index'],        
        'robots'=>$config['site']['meta_name_robots'],
        'generator'=>$config['site']['meta_name_generator']
  
    );
    /**
    *    Добавляю в шаблон мета теги для главной
    */
	$headers = Flight::render_home_meta($data);
    
	Flight::template()->set('{headers}', $headers);
	Flight::template()->set('{content}', $content);	    
    Flight::render_theme_footer();
});

/**
*    Категория сайта
*/
Flight::route('/category(/@name(/page(/@id:[1-9]+)))', function($name, $id) use ($config) {

    Flight::render_theme_header();
    
    if($name==NULL)
    {
        Flight::notFound();
    }    
    
    $data = array();
    
    $data['current_page'] = is_numeric($id)?$id:1;
	$data['limit'] = (int)$config['site']['articles_per_page'];
	$data['offset'] = ($data['current_page']-1)*$data['limit'];
    
    $pieces = explode('-', $name);
	$data['category_id'] = (int)$pieces[0];
        
	$posts = Flight::get_category_content($data);
    
    $category = array
    (
        'category_id' =>$posts[0]['category_id'],
        'category_name' => $posts[0]['category_name'],
        'category_url' => $posts[0]['category_url']      
    );    
    
	$posts_count = count($posts);
	$shortstory_tpl  = Flight::template()->sub_load_template('shortstory.tpl');
		
	if($posts_count>0) {
		for($i=0;$i<$posts_count;$i++) {
			$chank[$i]=str_replace('{title}', '<a href="'.Flight::get('base_url').'article/'.$posts[$i]['id'].'-'.$posts[$i]['url'].'">'.$posts[$i]['h_title'].'</a>', $shortstory_tpl);
			$chank[$i]=str_replace('{short-story}', $posts[$i]['short_story'], $chank[$i]);
			$chank[$i]=str_replace('{link-category}', '<a href="'.Flight::get('base_url').'category/'.$posts[$i]['category_id'].'-'.$posts[$i]['category_url'].'">'.$posts[$i]['category_name'].'</a>', $chank[$i]);
			$chank[$i]=str_replace('{category}', $posts[$i]['category_name'], $chank[$i]);
			$chank[$i]=str_replace('{THEME}', Flight::get('base_url').'templates/'.$config['site']['current_template'], $chank[$i]);
			$chank[$i]=str_replace('{author}', $config['site']['author'], $chank[$i]);
			$chank[$i]=str_replace('{date}', date('j-m-y',$posts[$i]['created_at']), $chank[$i]);
			$chank[$i]=str_replace('{views}', rand(1000,5000), $chank[$i]);
			$chank[$i]=str_replace('{rating}', rand(1000,5000), $chank[$i]);
			$chank[$i]=str_replace('{comments-num}', rand(100,300), $chank[$i]);
			$chank[$i]=str_replace('{favorites}', '', $chank[$i]);
			$chank[$i]=str_replace('[full-link]', '<a href="'.Flight::get('base_url').'article/'.$posts[$i]['url'].'">', $chank[$i]);
			$chank[$i]=str_replace('[/full-link]', '</a>', $chank[$i]);
			$chank[$i]=str_replace('{full-link}', '', $chank[$i]);

			$chank[$i]=str_replace('[com-link]', "", $chank[$i]);
			$chank[$i]=str_replace('[/com-link]', "", $chank[$i]);
			$chank[$i]=str_replace('[day-news]', "", $chank[$i]);
			$chank[$i]=str_replace('[/day-news]', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[rating](.*?)\\[/rating\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[edit-date](.*?)\\[/edit-date\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[edit](.*?)\\[/edit\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[complaint](.*?)\\[/complaint\\]#is', "", $chank[$i]);
			$chank[$i]=preg_replace('#\\[tags](.*?)\\[/tags\\]#is', "", $chank[$i]);	
		}			
		$content  = implode('',$chank);		
	}else{
		$content='';
	}		
			
	$navigation_tpl = Flight::template()->sub_load_template('navigation.tpl');
	$content = $content.$navigation_tpl;
		
	if($data['current_page']>1)
    {
        $prev_link = Flight::get('base_url').'category/'.$name.'/page/'.($data['current_page']-1);
		$content=str_replace('[prev-link]', '<a href="'.$prev_link.'">', $content);
		$content=str_replace('[/prev-link]', "</a>", $content);	
	}else{
		$content=str_replace('[prev-link]', '', $content);
		$content=str_replace('[/prev-link]', '', $content);	
	}		
		
	if($posts_count==$data['limit']) {
		$next_link = Flight::get('base_url').'category/'.$name.'/page/'.($data['current_page']+1);
		$content=str_replace('[next-link]', '<a href="'.$next_link.'">', $content);
		$content=str_replace('[/next-link]', "</a>", $content);
	}else{
		$content=str_replace('[next-link]', '', $content);
		$content=str_replace('[/next-link]', '', $content);
	}
		
	$content=str_replace('{pages}', '', $content);
    
    /**
    *    Формирую массив с данными, с помощью плагинов переопределю, потом 
    */
    $data = array
    (
        'title'=>$config['site']['meta_name_title_category'],
        'description'=>$config['site']['meta_name_description_category'],
        'keywords'=>$config['site']['meta_name_keywords_category'],        
        'robots'=>$config['site']['meta_name_robots'],
        'generator'=>$config['site']['meta_name_generator']  
    );
    /**
    *    Добавляю в шаблон МЕТА для Категории
    */
	$headers = Flight::render_category_meta($category, $data);
    
	Flight::template()->set('{headers}', $headers);
	Flight::template()->set('{content}', $content);	    
    Flight::render_theme_footer();    
});

/**
*    Страница статьи сайта
*/
Flight::route('/article(/@name)', function($name) use ($config) {

    Flight::render_theme_header();    
    if($name==NULL)
    {
        Flight::notFound();
    }    
    $pieces = explode('-', $name);    
	$data['article_id'] = (int)$pieces[0];    
    
    /**
    *    Полчаю контент статьи
    */
	$post = Flight::get_article_content($data);
    
    $fullstory_tpl  = Flight::template()->sub_load_template('fullstory.tpl');		
	$fullstory_tpl=str_replace('{THEME}', Flight::get('base_url').'templates/'.$config['site']['current_template'].'/', $fullstory_tpl);
	$fullstory_tpl=str_replace('{title}', '<a href="'.Flight::get('base_url').'article/'.$post['id'].'-'.$post['url'].'">'.$post['h_title'].'</a>', $fullstory_tpl);
	$fullstory_tpl=str_replace('{full-story}', $post['full_story'], $fullstory_tpl);
	$fullstory_tpl=str_replace('{short-story}', $post['short_story'], $fullstory_tpl);
	$fullstory_tpl=str_replace('{link-category}', '<a href="'.Flight::get('base_url').'category/'.$post['category_id'].'-'.$post['category_url'].'">'.$post['category_name'].'</a>', $fullstory_tpl);
	$fullstory_tpl=str_replace('{category}', $post['category_name'], $fullstory_tpl);
	$fullstory_tpl=str_replace('{author}',  $config['site']['author'], $fullstory_tpl);
	$fullstory_tpl=str_replace('{date}', date('j-m-y',$post['created_at']), $fullstory_tpl);
	$fullstory_tpl=str_replace('{views}', rand(1000,5000), $fullstory_tpl);
	$fullstory_tpl=str_replace('{rating}', rand(1000,5000), $fullstory_tpl);
	$fullstory_tpl=str_replace('{comments-num}', rand(100,300), $fullstory_tpl);
	$fullstory_tpl=str_replace('{favorites}', '', $fullstory_tpl);
	$fullstory_tpl=str_replace('{poll}', '', $fullstory_tpl);
	$fullstory_tpl=str_replace('{pages}', '', $fullstory_tpl);
	$fullstory_tpl=str_replace('{addcomments}', '', $fullstory_tpl);
	$fullstory_tpl=str_replace('{comments}', '', $fullstory_tpl);
	$fullstory_tpl=str_replace('{navigation}', '', $fullstory_tpl);
	$fullstory_tpl=str_replace('[full-link]', '<a href="'.Flight::get('base_url').'article/'.$post['url'].'-'.$post['url'].'">', $fullstory_tpl);
	$fullstory_tpl=str_replace('[/full-link]', '</a>', $fullstory_tpl);
    $fullstory_tpl=str_replace('[day-news]', "", $fullstory_tpl);
	$fullstory_tpl=str_replace('[/day-news]', "", $fullstory_tpl);
    $fullstory_tpl=str_replace('[related-news]', "", $fullstory_tpl);
	$fullstory_tpl=str_replace('[/related-news]', "", $fullstory_tpl);
	/**
	*	Генерирую похожие
	*/
	$related_articles = $config['site']['related_articles'];
	$related_content = '';
	if($related_articles==0)
    {
		$related_content = '';				
	}elseif($related_articles==2) {
	/**
	*	Предидущая
	*/
		$previous = ORM::for_table('article')->find_one($data['article_id']-1);
		if($previous) $related_content.='<li><a href="'.Flight::get('base_url').'article/'.$previous['id'].'-'.$previous['url'].'">'.$previous['meta_title'].'</a></li>';
		/**
		*	Следующая
		*/
		$next = ORM::for_table('article')->find_one($data['article_id']+1);
		if($next) $related_content.='<li><a href="'.Flight::get('base_url').'article/'.$next['id'].'-'.$next['url'].'">'.$next['meta_title'].'</a></li>';				
	}else{
        $articles = ORM::for_table('article')->raw_query('SELECT * FROM article ORDER BY RANDOM() LIMIT '.(int)$related_articles)->find_array();
			foreach($articles as $article) {
				$related_content.='<li><a href="'.Flight::get('base_url').'article/'.$article['id'].'-'.$article['url'].'">'.$article['meta_title'].'</a></li>';
			}				
		}
	$fullstory_tpl=str_replace('{related-news}', $related_content, $fullstory_tpl);
	/**
	*		
	*/
	$fullstory_tpl=preg_replace('#\\[tags](.*?)\\[/tags\\]#is', "", $fullstory_tpl);
	$fullstory_tpl=preg_replace('#\\[com-link](.*?)\\[/com-link\\]#is', "", $fullstory_tpl);
	$fullstory_tpl=preg_replace('#\\[comments](.*?)\\[/comments\\]#is', "", $fullstory_tpl);
    $fullstory_tpl=preg_replace('#\\[edit-date](.*?)\\[/edit-date\\]#is', "", $fullstory_tpl);
	$fullstory_tpl=preg_replace('#\\[rating](.*?)\\[/rating\\]#is', "", $fullstory_tpl);
	$fullstory_tpl=preg_replace('#\\[complaint](.*?)\\[/complaint\\]#is', "", $fullstory_tpl);
	$fullstory_tpl=preg_replace('#\\[poll](.*?)\\[/poll\\]#is', "", $fullstory_tpl);
	$fullstory_tpl=preg_replace('#\\[print-link](.*?)\\[/print-link\\]#is', "", $fullstory_tpl);
		
	/**
    *    Добавляю в шаблон МЕТА для Статьи
    */
    $headers = Flight::render_article_meta($post);
    
	Flight::template()->set('{headers}', $headers);
	Flight::template()->set('{content}', $fullstory_tpl);
    Flight::render_theme_footer(); 
});

/**
*    Карта сайта
*/
Flight::route('/sitemap.xml', function() {
    /**
	*	Это xml
	*/
	header('Content-type: text/xml');
	/**
	* Беру все категории	
	*/
	$categories = 	ORM::for_table('category')->find_array();
	/**
	*	Беру 100 последних постов, начиная с 0
	*/
	$limit = 100;
	$offset = 0;
	$posts = ORM::for_table('article')->limit($limit)->offset($offset)->order_by_desc('created_at')->find_array();
	/**
	*	Шапка карты
	*/
	$sitemap ='<?xml version="1.0" encoding="UTF-8"?><urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">';
	/**
	*	Главная в карте
	*/
	$sitemap .='<url><loc>'.Flight::get('base_url').'</loc><changefreq>always</changefreq><priority>1.0</priority></url>';
	
	/**
	*	Категории в карте
	*/
	foreach($categories  as $category)
    {
		$sitemap .='<url><loc>'.Flight::get('base_url').'category/'.$category['category_id'].'-'.$category['category_url'].'</loc><changefreq>hourly</changefreq><priority>0.9</priority></url>';
	}
	/**
	*	Посты в карте
	*/
	foreach($posts as $post)
    {
		$sitemap .='<url><loc>'.Flight::get('base_url').'article/'.$post['id'].'-'.$post['url'].'</loc><changefreq>daily</changefreq><priority>0.8</priority></url>';
	}
	/**
	*	Закрываю тег
	*/
	$sitemap .="</urlset>";
	/**
	*	Вывожу карту
	*/
	echo $sitemap;
	exit;
});

/**
*    RSS сайта
*/
Flight::route('/rss.xml', function() {
    /**
	*		Это xml
	*/
	header('Content-type: text/xml');
	/**
	*	Беру 100 последних постов, начиная с 0
	*/
	$limit = 100;
	$offset = 0;
	$posts = ORM::for_table('article')->limit($limit)->offset($offset)->order_by_desc('created_at')->find_array();
	/**
	*		Шапка rss
	*/
	$rss ='<?xml version="1.0"?>
          <rss version="2.0">
          <channel>
          <title>'.$config['site']['meta_name_title_index'].'</title>
          <link>'.BASEURL.'</link>
          <description>'.$config['site']['meta_name_description_index'].'</description>';
	/**
	*	Посты в rss
	*/
	foreach($posts as $post) {
			$rss .='<item>
            <title>'.$post['meta_title'].'</title>
            <link>'.Flight::get('base_url').'article/'.$post['id'].'-'.$post['url'].'</link>
            <description>'.$post['meta_description'].'</description>
            <author>'.$config['site']['author'].'</author>
            <pubDate>'.date("D, d M Y H:i:s T", strtotime($post['created_at'])).'</pubDate>
            <guid>'.Flight::get('base_url').'article/'.$post['id'].'-'.$post['url'].'</guid>
         </item>';
	}
	/**
	*	Закрываю тег
	*/
	$rss .='</channel></rss>';
	echo $rss;
	exit;
});

/**
*    Robots.txt сайта
*/
Flight::route('/robots.txt', function() {
    /**
	*	Это text
	*/
	header('Content-type: text/plain');
		
	$robots = 'User-agent: Yandex
Host: '.str_replace(array("http://","/"),array("",""),Flight::get('base_url')).'
Disallow: /search/
Disallow: /find/
Sitemap: '.Flight::get('base_url').'sitemap.xml';
	echo $robots;
	exit;
});

/**
*   Humans.txt сайта
*/
Flight::route('/humans.txt', function() {
    /**
	*	Это text
	*/
	header('Content-type: text/plain');
		
	$humans = '
/* TEAM */
Chef:Admin
Contact: admin_mail [at] mail.mail
Twitter: @admin
From:Russian

Web designer: AdminDesign
Contact: design [at] mail.mail
Twitter: @design
From:Ukraine

/* SITE */
Last update:2015/07/04
Language: Russian / Ukraine
Doctype:HTML5
IDE: Sublime Text, Notepad++, FileZilla, Photoshop';
	echo $humans;
	exit;
});

/**
*   АДМИНКА
*/

/**
*    Логин
*/
Flight::route('GET /admin/login/', function() {
    if(Flight::session_check())
    {
        Flight::redirect('/admin/config/');
    }    
    $data=array(
        'page_title'=>'Thunder v2. Вход',
    );
    Flight::render('login.php', $data);
});

/**
*    Логин POST
*/
Flight::route('POST /admin/login/', function() use ($config) {
    $request = Flight::request();
    if(
        md5($request->data['password']) == $config['user']['password'] 
        AND 
        $request->data['login'] == $config['user']['login']
       )
    {
        Flight::session_start($request->data['login']);
        Flight::redirect('/admin/config/');
    }
    else
    {
        Flight::redirect('/admin/login/');
    }
        
});

/**
*   Выход
*/
Flight::route('GET /admin/logout/', function() {    
    Flight::session_stop();
});

/**
*   Конфиг
*/
Flight::route('GET /admin(/config/)', function() use ($config){
    if(!Flight::session_check())
    {
        Flight::redirect('/admin/login/');
    }
    /**
    *    Вытягиваю описания к сниппетам из Плагинов
    */
    $plugins_docs = '';    
    foreach (glob(Flight::get('plugins_root')."*.php") as $filename)
    {
        $plugins_docs = $plugins_docs.htmlspecialchars(file_get_contents($filename));
    }
    preg_match_all('/((?:\/\*(?:[^*]|(?:\*+[^*\/]))*\*+\/)|(?:\/\/.*))/', $plugins_docs , $matches);
    
    $data=array(
        'sitebar'=>Flight::get('flight.views.path').'/sidebar.php',
        'page_title'=>'Thunder v2. Главная',        
        'config'=>$config,
        'articles_count'=>ORM::for_table('article')->count(),
        'categories_count'=>ORM::for_table('category')->count(),
        'snippets_docs'=>$matches[1]
    );
    Flight::render('config.php', $data);
});

/**
*   Конфиг POST
*/
Flight::route('POST /admin/config/', function() use ($config){
    if(!Flight::session_check())
    {
        die('As we are confident in the victory Of good over evil');
    }
    $request = Flight::request();
    $config['site']=array();
    $config['site']= $request->data['site'];
    if(Flight::save(Flight::get('docs_root').'config.php', $config))
    {
        Flight::redirect('/admin/config/');
    }
});

/**
*   Генератор
*/
Flight::route('GET /admin/generate/', function() use ($config){
    if(!Flight::session_check())
    {
        Flight::redirect('/admin/login/');
    }
    
    $data=array(
        'sitebar'=>Flight::get('flight.views.path').'/sidebar.php',
        'page_title'=>'Thunder v2. Генератор',        
        'config'=>$config,
        'categories'=> ORM::for_table('category')->find_array(),
        'articles_count'=>ORM::for_table('article')->count(),
        'categories_count'=>ORM::for_table('category')->count()
    );
    Flight::render('generate.php', $data);
});

/**
*   Генератор POST
*/
Flight::route('POST /admin/generate/', function() {
    if(!Flight::session_check())
    {
       die('As we are confident in the victory Of good over evil');
    }
    
    $request = Flight::request();

    /**
    *    Если нет ключей, редирект назад
    */
    if($request->data['keywords'] == '')
    {
        Flight::redirect('/admin/generate/');
    }


    $template ='';
    
    $keywords = explode(PHP_EOL, $request->data['keywords']);
    /**
   	*     Перебираю все клучи, ибо они всему "голова"))
    */
    foreach($keywords as $keyword)
    {
        switch($request->data['domain'])
        {
        case 0:
            /**
            *    Для текущего домена
            */
            switch($request->data['export'])
            {
            case 0:
                /**
                *    list
                */
                $template = Flight::get('base_url')."search/{urlencode_keyword}/{category}";
                break;
            case 1:
                /**
                *    html
                */
                $template = "<a href=".Flight::get('base_url')."search/{urlencode_keyword}/{category}>{keyword}</a>";
                break;
            case 2:
                /**
                *    bbcode
                */
                $template = "[url=".Flight::get('base_url')."search/{urlencode_keyword}/{category}]{keyword}[/url]";
                break;
            case 3:
                /**
                *    twitter
                */
                $template = Flight::get('base_url')."search/{urlencode_keyword}/{category} # {keyword}";
                break;
            case 4:
                /**
                *    delim
                */
                $template = Flight::get('base_url')."search/{urlencode_keyword}/{category} | {keyword}";
                break;
            }
            
            if(isset($request->data['to_categories']))
            {
                /**
                *    Категории указаны, выбираю куда публиковать
                */
                $rand_category  = value(function() use ($request) {
                    $categories = $request->data['to_categories'];
                    $rand_catergory_id = array_rand($categories);            
                    return $categories[$rand_catergory_id];
                });               
            }
            else
            {
                /**
                *    Категории не указаны, сам решу куда постить
                */
                $rand_category  = '';
            }
            /**
            *    Отображаю 
            */
            echo str_replace(array('{urlencode_keyword}', '{keyword}','{category}'), array(urlencode($keyword), $keyword, $rand_category), $template);
            echo "<br/>";            
            break;
        case 1:
            /**
            *    Для списка доменов
            */
            switch($request->data['export'])
            {
            case 0:
                /**
                *   list
                */
                $template = " {domain}search/{urlencode_keyword}";
                break;
            case 1:
                /**
                *    html
                */
                $template = " <a href={domain}search/{urlencode_keyword}>{keyword}</a>";
                break;
            case 2:
                /**
                *   bbcode
                */
                $template = " [url={domain}search/{urlencode_keyword}]{keyword}[/url]";
                break;
            case 3:
                /**
                *    twitter
                */
                $template = " {domain}search/{urlencode_keyword} # {keyword}";
                break;
            case 4:
                /**
                *    delim
                */
                $template = " {domain}search/{urlencode_keyword} | {keyword}";
                break;
            }
            /**
            *    Если нет доменов, редирект назад
            */
            if($request->data['domains'] == '')
            {
                Flight::redirect('/admin/generate/');
            }            
            
            /**
            *    Все домены
            */
            $domains = explode(PHP_EOL, $request->data['domains']);
                
            switch($request->data['mode'])
            {
            case 0:
                /**
                *    Каждый ключ для случайного домена
                */
                $rand_domain_key = array_rand($domains);
                $rand_domain = $domains[$rand_domain_key];
                echo str_replace(array('{domain}', '{urlencode_keyword}', '{keyword}'), array($rand_domain, urlencode($keyword), $keyword), $template);
                echo "<br/>";  
                break;
            case 1:
                /**
                *    Все ключи для всех доменов
                */
                foreach($domains as $domain) {
                    echo str_replace(array('{domain}', '{urlencode_keyword}', '{keyword}'), array($domain, urlencode($keyword), $keyword), $template);
                    echo "<br/>";
                }
                break;
            }            
            break;
        }
    }    
});

/**
*   Ауты POST
*/
Flight::route('POST /admin/config/out', function() use ($config){
    if(!Flight::session_check())
    {
        die('As we are confident in the victory Of good over evil');
    }
    $request = Flight::request();
    $config['out']=array();
    $config['out']= $request->data['out'];
    if(Flight::save(Flight::get('docs_root').'config.php', $config))
    {
        Flight::redirect('/admin/config/');
    }
});

/**
*   Экпорт ссылок
*/
Flight::route('GET /admin/links/@type', function($type) {
    if(!Flight::session_check())
    {
        Flight::redirect('/admin/login/');
    }
    
    if($type==NULL)
    {
        $type = 'html';
    }
  
    $posts = ORM::for_table('article')->limit(999999999999)->offset(0)->order_by_desc('created_at')->find_array();
	if(count($posts)>0) {
		foreach($posts as $article) {
			switch ($type) {
				case 'html':
					echo htmlspecialchars('<a href="'.Flight::get('base_url').'article/'.$article['id'].'-'.$article['url'].'">'.$article['h_title'].'</a>');echo '<br/>';
					break;
				case 'bbcode':
					echo '[url='.Flight::get('base_url').'article/'.$article['id'].'-'.$article['url'].']'.$article['h_title'].'[/url]';echo '<br/>';
					break;
				case 'twitter':
					echo Flight::get('base_url').'article/'.$article['url'].' # '.$article['id'].'-'.$article['h_title'];echo '<br/>';
					break;
				case 'delim':
					echo Flight::get('base_url').'article/'.$article['id'].'-'.$article['url'].'|'.$article['h_title'];echo '<br/>';
					break;
				case 'url':
					echo Flight::get('base_url').'article/'.$article['id'].'-'.$article['url'];echo '<br/>';
					break;
				case 'key':
					echo $article['h_title'];echo '<br/>';
					break;
			}			
		}
	}
});

/**
*   Поиск :), он же, запускает генерацию ключей
*/
Flight::route('GET /search/@term(/@category_id)', function($term, $category_id) use ($config) {
    /**
    *    Если ли разрешение на дальнейшую генерацию
    */
    if
    (
        $config['site']['stop_generate']==1 
        OR
        (int)ORM::for_table('article')->count() >= (int)$config['site']['stop_generate_count']
    )
    {
        Flight::notFound();
    }
    
    $term = urldecode($term);    
    $article = ORM::for_table('article')->where('keyword',$term)->find_one();    
    if($article)
    {
        /**
        *    Такой ключ уже обработан, редиректим на страницу статьи:
        */
        Flight::redirect(Flight::get('base_url').'article/'.$article['id'].'-'.$article['url']);
    }
    else
    {
        /**
        *    Такой ключ еще не обработан
        */
        
        /**
        *    Формирую фейковый массив с данными, с помощью плагинов переопределю, потом 
        */
        $data = array
        (
            'keyword'=>$config['site']['article_main_keyword'],
            'meta_title'=>$config['site']['meta_name_title_article'],
            'meta_description'=>$config['site']['meta_name_description_article'],
            'meta_keywords'=>$config['site']['meta_name_keywords_article'],
            'h_title'=>$config['site']['h_title_article'],
            'url'=>URLify::filter($term),
            'short_story'=>'',
            'full_story'=>$config['site']['article_fullstory'],
            'category_id'=>1
        );
        /**
        *    Добавляю  статью в БД
        */
        $article = Flight::add_article_content($term, '', $data);
        /**
        *    Редирект на статью
        */
        Flight::redirect(Flight::get('base_url').'article/'.$article['id'].'-'.$article['url']);
    }
});

Flight::route('GET /find/', function() use ($config) {

	/**
    *    Если ли разрешение на дальнейшую генерацию
    */
    if
    (
        $config['site']['stop_generate']==1 
        OR
        (int)ORM::for_table('article')->count() >= (int)$config['site']['stop_generate_count']
    )
    {
        Flight::notFound();
    }

    /**
    *	Cуществует ли файл с оинформацией про файлы с ключами?
    */
    $filename = Flight::get('data_root').$config['site']['generate_from_file'];

    /**
	*	Существует ли физически файл с ключами
    */
    if(!file_exists($filename)){
    	die('Файла с ключами '.$filename.' не существует');
    }

    /**
	*	Существует в БД
    */
    $keyword = ORM::for_table('keyword')->where('keyword_name', $filename)->find_one();
	

    if($keyword){
    	/**
    	*	В базе зарегистрирован такой файл
    	*/
    	$current_line_number = $keyword->keyword_current;
    }else{
    	/**
    	*	В базе не зарегистрирован такой файл
    	*/
    	$keyword = ORM::for_table('keyword')->create();
        $keyword->keyword_name = $filename;
        $keyword->keyword_current = 0;
        $keyword->save();

        $current_line_number = 0;
    }   

	/**
	*	Все нормально. Работаем со строками
	*/
	$file = new SplFileObject($filename);

	$file->seek($current_line_number); 

	$term = $file->current();

	/**
	*	Если строки такой нет, каретку на 0;
	*/
	if(!$term)
	{
		$keyword->keyword_current = 0;
        $keyword->save();		
		$file->seek($keyword->keyword_current); 
		$term = $file->current();
	}	

	$data = array
    (
        'keyword'=>$config['site']['article_main_keyword'],
        'meta_title'=>$config['site']['meta_name_title_article'],
        'meta_description'=>$config['site']['meta_name_description_article'],
        'meta_keywords'=>$config['site']['meta_name_keywords_article'],
        'h_title'=>$config['site']['h_title_article'],
        'url'=>URLify::filter($term),
        'short_story'=>'',
        'full_story'=>$config['site']['article_fullstory'],
        'category_id'=>1
    );
    /**
    *    Добавляю  статью в БД
    */
    $article = Flight::add_article_content($term, '', $data);
    /**
    *	Увеличиваю номер строки на единицу
    */
    $keyword->keyword_current = $current_line_number + 1;
    $keyword->save();
});

Flight::start();