<?php
/*
* @package LabCMS
* @copyright (c) 2006 Alexander Levin aka Loki (loki_angel@mail.ru)
* @support http://labcms.ru
* @license http://opensource.org/licenses/gpl-license.php GNU Public License
*/

class news_main extends ModuleTools
{
	public function __construct()
	{
		$this->module=Factory::create('news.module');
		Tpl::i()->append(
			'feed_rss',
			array(
				'path'=>_url(null, null, 'xml'),
				'name'=>_m('Новости сайта').' '.config::get('core.site_name')
			)
		);
		//ключик позволяющий загружать файлы на сервер
		if (access('edit') || access('add')) LabCMS::setAllowFileUpload();
	}
	
	public function getList()
	{
		if (isset($_GET['data_type']) && $_GET['data_type']=='xml') return $this->_rss();

		$page=isset($_GET['var1'])?intval($_GET['var1']):1;
		if ($page<=0) $page=1;
		
		$filter=array(
			'lang_id'=>LabCMS::i()->lang['id'],
			'ignore_date'=>access('edit')?true:false
		);
		$order=array('date'=>'desc', 'new_id'=>'desc');
		$data=$this->module->getNewsByFilter($filter, $order, config::get('news_at_page'), $page);
		
		if ($data['count']) {
			$this->_setCommentsCount($data['collection']);

			self::_assign('pager', Factory::create('Paginator', $data['count'], config::get('news_at_page'), $page)->getPages());
			self::_assign('news', $data['collection']);
		}
		
		self::_setTpl('news');
	}
	
	protected function _rss()
	{
		self::_setTpl('string:{$xml}', true);

		$filter=array(
			'lang_id'=>LabCMS::i()->lang['id']
		);
		
		$order=array('date'=>'desc', 'new_id'=>'desc');
		
		$data=$this->module->getNewsByFilter($filter, $order, config::get('news_rss'), 1);
		
		sendXmlHeaders();
		$rss=array(
			'title'=>config::get('core.site_name'),
			'link'=>config::get('core.siteUrl'),
			'description'=>config::get('core.description')
		);
		foreach ($data['collection'] as $new) {
			$new->text=str_ireplace('[more]', '', $new->text);
			$rss['feed'][]=array(
				'title'=>$new->title,
				'description'=>$new->text,
				'link'=>config::get('core.siteUrl')._url($new->id, 'item'),
				'pubDate'=>$new->date
			);
		}
		$xml=genereteFeed($rss);
		self::_assign('xml', $xml);
	}
	
	protected function _setCommentsCount(&$news)
	{
		if (is_array($news) && config::get('use_comments')) {
            $api=Factory::create('lc_comments.api');
			$c_count=$api->getCommentsCounters(array_keys($news));
			foreach ($news as $id=>$new) {
				$news[$id]->comments=empty($c_count[$id])?0:intval($c_count[$id]);
			}
		}	
	}
	
	public function add()
	{
		if (!access('add')) return LabCMS::i()->error403();
		
		$form=$this->module->buildEditForm();

		if ($form->validate()) {
			$new=Factory::create('news.entity', $form->getValue());
			$new->lang_id=LabCMS::i()->lang['id'];
			preg_match('/(\d{2})\.(\d{2})\.(\d{4})/', $new->date, $d);
			$new->date=mktime(0, 0, 0, $d[2], $d[1], $d[3]);
			$this->module->addNew($new);
			refresh('', _url($new->id, 'item'));
		}
		
		self::_assign('form', $this->_renderForm($form));
		self::_setTpl('form');
	}
	
	public function edit()
	{
		if (!access('edit')) return LabCMS::i()->error403();
		$new=$this->module->getNewById($_GET['var1']);
		if (!$new->id) return self::_error(_m('Запись не найдена'));

		$form=$this->module->buildEditForm($new);
		
		if ($form->validate()) {
			$new->set($form->getValue());
			preg_match('/(\d{2})\.(\d{2})\.(\d{4})/', $new->date, $d);
			$new->date=mktime(0, 0, 0, $d[2], $d[1], $d[3]);
			$this->module->updateNew($new);
			refresh('', _url($new->id, 'item'));
		}
		
		self::_assign('form', $this->_renderForm($form));
		self::_setTpl('form');
	}
	
	public function delete()
	{
		if (!access('delete')) return LabCMS::i()->error403();
		User::checkToken();
		$new=$this->module->getNewById($_GET['var1']);
		if (!$new->id) return self::_error(_m('Запись не найдена'));
		$this->module->deleteNew($new);
		$mObject=Factory::create('lc_comments.api');
		$mObject->deleteItem($_GET['var1']);
		refresh('', _url($_GET['var2']));
	}
	
	public function item()
	{
		$new=$this->module->getNewById($_GET['var1']);
		if (!$new->id) return self::_error(_m('Запись не найдена'));
		$new->text=str_ireplace('[more]', '', $new->text);

		self::_assign('new', $new);
		self::_setTpl('show');
		
		if (config::get('use_comments')) {
			$api=Factory::create('lc_comments.api');
			$item=$api->getCommentsItem($new->id, _url($new->id, 'item'), config::get('core.title'));
			$comments=$item->getComments();
			self::_assign('comment_votes', $item->getUserItemVotes());
			self::_assignByRef('comments_item', $item);
			self::_assignByRef('comments', $comments);
		}

		config::set('core.title', $new->title?$new->title:date('d.m.Y', $new->date).' / '.config::get('core.title'));
	}
}