View file veppa_wallpaper/sys/app/controllers/IndexController.php

File size: 16.5Kb
<?php

/**
 * Free Wallpaper Script
 *
 * Free Wallpaper Script by Vepa Halliyev is licensed under a Creative Commons Attribution-Share Alike 3.0 License.
 *
 * @package		Free Wallpaper Script
 * @author		Vepa Halliyev
 * @copyright	Copyright (c) 2009, Vepa Halliyev, veppa.com.
 * @license		http://www.veppa.com/free-wallpaper-script/
 * @link		http://www.veppa.com/free-wallpaper-script/
 * @since		Version 1.0
 * @filesource
 * @version		1.2 (10.05.2010)
 */

/**
 * class IndexController handles all front end pages
 *
 * @author Vepa Halliyev <veppa.com>
 * @since  0.1
 * 
 * 
 * urls:
 * /
 * /d/23/
 * /h/
 * /l/
 * /r/
 * 
 * /tag/love/
 * /tag/love/d/2
 * /tag/love/h/
 * /tag/love/l/
 * /tag/love/r/
 * 
 */
class IndexController extends Controller
{

	static private $num = 30; // number of records per page

	function __construct()
	{
		AuthUser::load();

		$this->_meta = new stdClass();
		$this->setLayout('frontend');
	}

	function index()
	{
		// get latest wallpapers 
		$vars['latest_wallpapers'] = Wallpaper::findAllFrom('Wallpaper', 'public=1 ORDER BY id DESC LIMIT 5', array());
		// exclude already displayed wallpapers from other lists to display diggerent wallpapers in one page
		$ex_ids = Wallpaper::excludeIdsQuery($vars);
		$vars['hottest_wallpapers'] = Wallpaper::findAllFrom('Wallpaper', 'public=1 ' . $ex_ids . ' ORDER BY week DESC LIMIT 5', array());
		// exclude already displayed wallpapers from other lists to display diggerent wallpapers in one page
		$ex_ids = Wallpaper::excludeIdsQuery($vars);
		$vars['downloaded_wallpapers'] = Wallpaper::findAllFrom('Wallpaper', 'public=1 ' . $ex_ids . ' ORDER BY dwn DESC LIMIT 5', array());
		// exclude already displayed wallpapers from other lists to display diggerent wallpapers in one page
		$ex_ids = Wallpaper::excludeIdsQuery($vars);
		$vars['top_wallpapers'] = Wallpaper::findAllFrom('Wallpaper', 'public=1 ' . $ex_ids . ' ORDER BY rank DESC LIMIT 5', array());

		$vars['latest_title'] = __('Latest wallpapers');
		$vars['hottest_title'] = __('Hottest wallpapers');
		$vars['downloaded_title'] = __('Most downloaded wallpapers');
		$vars['top_title'] = __('Top rated wallpapers');

		$vars['latest_link'] = '<a href="' . get_url('l/') . '">' . __('view all &raquo;') . '</a>';
		$vars['hottest_link'] = '<a href="' . get_url('h/') . '">' . __('view all &raquo;') . '</a>';
		$vars['downloaded_link'] = '<a href="' . get_url('d/') . '">' . __('view all &raquo;') . '</a>';
		$vars['top_link'] = '<a href="' . get_url('r/') . '">' . __('view all &raquo;') . '</a>';

		$this->_addCommonListVars($vars);

		$this->display('index/index', $vars);
	}

	function indexOrder($order = '', $page = 1)
	{

		if($page < 1)
		{
			$page = 1;
		}

		$st = ($page - 1) * self::$num;

		$limit = 'LIMIT ' . $st . ',' . self::$num;

		switch($order)
		{
			case 'l':
				$order_sql = 'id';
				$this->setMeta('title', __('All wallpapers ordered by latest'));
				break;
			case 'h':
				$order_sql = 'week';
				$this->setMeta('title', __('All wallpapers ordered by hottest'));
				break;
			case 'd':
				$order_sql = 'dwn';
				$this->setMeta('title', __('All wallpapers ordered by most downloaded'));
				break;
			case 'r':
				$order_sql = 'rank';
				$this->setMeta('title', __('All wallpapers ordered by top ranked'));
				break;
			default:
				page_not_found();
		}

		// get latest wallpapers 
		$vars['wallpapers'] = Wallpaper::findAllFrom('Wallpaper', 'public=1 ORDER BY ' . $order_sql . ' DESC ' . $limit, array());

		// get paginator 
		$total = Wallpaper::countFrom('Wallpaper', 'public=1');
		$total_pages = ceil($total / self::$num);
		$vars['paginator'] = Paginator::render($page, $total_pages, get_url($order . '/{page}/'), true, get_url($order . '/'));
		$vars['order_links'] = $this->_orderLinks($order, get_url());


		$this->_addCommonListVars($vars);

		$this->display('index/list', $vars);
	}

	private function _tagOrder($tag, $order = '', $page = 1, $total, $tag_object, $where)
	{

		// page and limit
		if($page < 1)
		{
			$page = 1;
		}
		$st = ($page - 1) * self::$num;

		// paginator
		$total_pages = ceil($total / self::$num);
		$url = Tag::url($tag, $order, '{page}');
		$vars['paginator'] = Paginator::render($page, $total_pages, $url, true);
		$vars['order_links'] = $this->_orderLinks($order, Tag::url($tag));


		// get wallpapers
		switch($order)
		{
			case 'l':
				$order_sql = 'id';
				$this->setMeta('title', __('{name} wallpapers ordered by latest', array('{name}' => $tag)));
				break;
			case 'h':
				$order_sql = 'week';
				$this->setMeta('title', __('{name} wallpapers ordered by hottest', array('{name}' => $tag)));
				break;
			case 'd':
				$order_sql = 'dwn';
				$this->setMeta('title', __('{name} wallpapers ordered by most downloaded', array('{name}' => $tag)));
				break;
			case 'r':
				$order_sql = 'rank';
				$this->setMeta('title', __('{name} wallpapers ordered by top ranked', array('{name}' => $tag)));
				break;
			default:
				page_not_found();
		}

		// get latest wallpapers 
		$vars['wallpapers'] = Wallpaper::getByTagId($tag_object->t_id, $order_sql, $st, self::$num);

		// todo add tags 
		// Wallpaper::appendObject($vars['wallpapers'],'id',);

		$this->_addCommonListVars($vars);

		$this->display('index/list', $vars);
	}

	function wallpaper($permalink)
	{
		// check if asked to login 
		if($_GET['login'])
		{
			AuthUser::isLoggedIn(true);
		}

		// add comment
		$this->_addComment();

		// parse permalink and display wallpaper
		// get wallpaper id
		$id = $this->_extractId($permalink);

		if(!$id)
		{
			page_not_found();
		}

		$vars['wallpaper'] = Wallpaper::findByIdFrom('Wallpaper', $id, 'id');

		if(!$vars['wallpaper'])
		{
			page_not_found();
		}

		$vars['comments'] = Comment::findAllFrom('Comment', 'cm_wid=? AND cm_active=1 ORDER BY cm_id', array($id));
		Comment::appendObject($vars['comments'], 'cm_added_by', 'User');
		$vars['related_wallpapers'] = Wallpaper::relatedWallpapers($id, 15);

		$this->_addCommonListVars($vars);

		$title = __(Thumbgrid::imgAlt($vars['wallpaper']));

		$this->setMeta('title', $title);
		$this->setMeta('description', $title . ' : ' . $vars['wallpaper']->tags . ' - ' . Config::option('site_description'));
		$this->setMeta('keywords', $vars['wallpaper']->tags);

		$this->display('index/wallpaper', $vars);
	}

	private function _addComment()
	{
		if(get_request_method() == 'POST')
		{
			// if logged in then no need for name and website
			if(!AuthUser::isLoggedIn(false))
			{
				$rules['cm_name'] = 'trim|required|xss_clean';
				$rules['cm_website'] = 'trim|xss_clean';
				$rules['vImageCodP'] = 'required|callback__validate_security_code';
			}

			$rules['cm_body'] = 'trim|required|xss_clean';
			$rules['cm_wid'] = 'required';

			$fields['cm_name'] = __('Name');
			$fields['cm_website'] = __('Website');
			$fields['cm_body'] = __('Comment');
			$fields['cm_wid'] = __('Wallpaper');
			$fields['vImageCodP'] = __('Security code');

			use_helper('Vimage');
			$vImage = new Vimage();
			$this->validation()->set_controller($vImage);

			$this->validation()->set_rules($rules);
			$this->validation()->set_fields($fields);

			if($this->validation()->run())
			{
				$fields = array_keys($rules);

				$cm = new Comment(Record::filterCols($_POST, array_keys($rules)));

				if(Config::option('approve_user_comments'))
				{
					// if logged in then approve comments
					if(AuthUser::isLoggedIn(false))
					{
						$cm->cm_active = 1;
						$msg = __('Your comment added.');
					}
				}


				$cm->save('cm_id');

				Flash::set('success', $msg?$msg:__('Your comment will be displayed after approval by moderator.'));

				// get wallpaper permalink 
				$w = Wallpaper::findByIdFrom('Wallpaper', $_POST['cm_wid'], 'id');
				$url = Thumbgrid::makeGoodUrl($w->id, 'wallpaper', $w->name);
				redirect($url);
			}
		}

		return new Comment($_POST);
	}

	private function _extractId($string)
	{
		// get wallpaper id
		$arr = explode('_', $string);
		$arr = explode('.html', $arr[1]);

		return intval(str_replace('w', '', $arr[0]));
	}

	function download($permalink)
	{
		// parse permalink and display wallpaper
		// get wallpaper id
		$id = $this->_extractId($permalink);

		if(!$id)
		{
			page_not_found();
		}

		$wallpaper = Wallpaper::findByIdFrom('Wallpaper', $id, 'id');

		if(!$wallpaper)
		{
			page_not_found();
		}

		// update download count
		$wallpaper->increaseDownloadCount();

		$this->display('index/download', array(
			'wallpaper' => $wallpaper,
			'page_mode' => 'download'
		));
	}

	function tag($tag, $order = '', $page = 1)
	{
		$tag = rawurldecode($tag);

		// get total wallpaper count 
		// if less than 30 display by hottest 
		// else display latest and others as in index page 


		$tag_object = Tag::findOneFrom('Tag', 't_name=?', array($tag));
		if(!$tag_object)
		{
			// check if tag is category
			$cat = Category::findOneFrom('Category', 'name=?', array($tag));
			if(!$cat)
			{
				page_not_found();
			}
		}


		// get total wallpapers in with this tag
		$total = Wallpaper::getByTagIdCount($tag_object->t_id);

		if($order)
		{
			return $this->_tagOrder($tag, $order, $page, $total, $tag_object, $where);
		}


		if($total <= self::$num)
		{
			// display only hottest order 
			return $this->_tagOrder($tag, 'h', 1, $total, $tag_object, $where);
		}


		// display 4 different orders		

		$vars['latest_wallpapers'] = Wallpaper::getByTagId($tag_object->t_id, 'id', 0, 20);
		$vars['hottest_wallpapers'] = Wallpaper::getByTagId($tag_object->t_id, 'week', 0, 5);
		$vars['downloaded_wallpapers'] = Wallpaper::getByTagId($tag_object->t_id, 'dwn', 0, 5);
		$vars['top_wallpapers'] = Wallpaper::getByTagId($tag_object->t_id, 'rank', 0, 5);

		$vars['latest_title'] = __('Latest wallpapers');
		$vars['hottest_title'] = __('Hottest wallpapers');
		$vars['downloaded_title'] = __('Most downloaded wallpapers');
		$vars['top_title'] = __('Top rated wallpapers');

		$vars['latest_link'] = '<a href="' . Tag::url($tag, 'l') . '">' . __('view all &raquo;') . '</a>';
		$vars['hottest_link'] = '<a href="' . Tag::url($tag, 'h') . '">' . __('view all &raquo;') . '</a>';
		$vars['downloaded_link'] = '<a href="' . Tag::url($tag, 'd') . '">' . __('view all &raquo;') . '</a>';
		$vars['top_link'] = '<a href="' . Tag::url($tag, 'r') . '">' . __('view all &raquo;') . '</a>';

		$vars['tag'] = $tag;
		$this->setMeta('title', __('{name} wallpapers', array('{name}' => $tag)));

		$this->_addCommonListVars($vars);

		$this->display('index/index', $vars);
	}

	private function _addCommonListVars(& $vars)
	{
		$vars['tags'] = Tag::getPopularTags(20);
		$vars['categories'] = Category::getCategories();
		$vars['max_downloads'] = Wallpaper::getMax('dwn');
		$vars['max_hotness'] = Wallpaper::getMax('week');
	}

	private function _orderLinks($order, $prefix = '')
	{
		$arr_links = array(
			'l' => __('Latest'),
			'd' => __('Downloads'),
			'h' => __('Hottest'),
			'r' => __('Rating'),
		);

		foreach($arr_links as $k => $v)
		{
			if($order == $k)
			{
				$links[] = '<span class="sel">' . $v . '</span> ';
			}
			else
			{
				$links[] = '<a href="' . $prefix . $k . '/' . '" ' . $sel . '>' . $v . '</a> ';
			}
		}
		return __('Order by') . ': ' . implode('', $links);
	}

	function resize()
	{
		// initialize classes 
		$id = $_POST['id'];
		$size = $_POST['size'];

		//print_r($_REQUEST);
		//exit();

		if($id)
		{
			$wallpaper = Wallpaper::findByIdFrom('Wallpaper', $id, 'id');
			if($wallpaper)
			{
				// update download count
				$wallpaper->increaseDownloadCount();

				$thumb = new Thumbgrid();
				// TODO ehere should chek if wallpaper is public, if not then if owner downloads?

				if($size)
				{
					if($wallpaper->img && $thumb->if_size_smaller($wallpaper->size, $size))
					{
						$resized = $wallpaper->resize($size);
						//echo 'resized';
					}
					//echo 'size ok';
					$download_name = Inflector::slugify($wallpaper->name) . '-' . $size . '.jpg';
				}
				else
				{
					$resized = Wallpaper::imgSrc($wallpaper, 'o');
					//echo 'original size';
					$download_name = Inflector::slugify($wallpaper->name) . '.jpg';
				}

				//var_dump($resized);
				FileDir::forceDownload($resized, $download_name);
			}
		}

		echo 'incorrect download/resize request';
	}

	function upload()
	{
		// if user logged in then send to admin upload
		/* if(AuthUser::isLoggedIn(false))
		  {
		  // redirect to admin login page
		  redirect(get_url('admin/wallpapers/add/'));
		  } */

		$categories = Category::getCategories();

		$wallpaper = $this->_upload($categories);

		$this->display('index/upload', array(
			'wallpaper' => $wallpaper,
			'categories' => $categories
		));
	}

	private function _upload($categories = array())
	{

		if(get_request_method() == 'POST')
		{
			// mix tags with categories
			$_POST['tags'] = Tag::mixWithCategories($_POST['tags'], $categories, $_POST['categories']);

			$rules['name'] = 'trim|required|strip_tags|xss_clean';
			$rules['tags'] = 'trim|required|strip_tags|xss_clean';
			$rules['artist'] = 'trim|strip_tags|xss_clean';
			$rules['site'] = 'trim|strip_tags|xss_clean';
			$rules['description'] = 'trim|strip_tags|xss_clean';
			$fields['name'] = __('Name');

			$this->validation()->set_rules($rules);
			$this->validation()->set_fields($fields);

			$fields = 'name,artist,site,description,img,size,tags';
			if($this->validation()->run())
			{
				if(false === $uploaded_file = Wallpaper::upload('img'))
				{
					$this->validation()->set_error(Wallpaper::displayErrors('', ' '));
					return false;
				}


				// image uploaded and resized. add record to database

				$post = $_POST;

				$post['img'] = $uploaded_file['name'];
				$post['size'] = $uploaded_file['size'];

				$wallpaper = new Wallpaper(Wallpaper::filterCols($post, $fields));

				// if user is moderator make wallpaper automaticly public.
				if(AuthUser::hasPermission('moderator'))
				{
					$wallpaper->public = 1;
				}

				if(!$wallpaper->save('id'))
				{
					// error saving. delete image
					Wallpaper::deleteWallpaperImg($wallpaper->img);

					$this->validation()->set_error(__('Error adding uploded wallpaper.'), $field);
					return false;
				}

				// wallpaper added. redirect to add page to avoid double insertion
				Flash::set('success', __('Wallpaper uploaded.'));
				redirect(get_url('index/upload/'));

				return true;
			}
			else
			{
				return new Wallpaper(Wallpaper::filterCols($post, $fields));
			}
		}


		return false;
	}

	function rate()
	{
		//rate wallpaper 
		$w_id = $_POST['id'];
		$rating = $_POST['rate'];

		echo Vote::vote($w_id, $rating);
		exit();
	}

	function search()
	{
		$vars = array();
		$this->_addCommonListVars($vars);
		$this->display('index/search', $vars);
	}

	/**
	 * find rated wallpapers from existing list. display them as voted for this visitor.
	 * @return unknown_type
	 */
	function checkRating()
	{
		$w_ids = $_POST['w_ids'];
		$arr_id = explode(",", trim($w_ids, ","));

		$vote = new Vote($db);
		echo $vote->filterVotedWallpaperIds($arr_id);
		exit();
	}

	function feed()
	{
		$wallpapers = Wallpaper::findAllFrom('Wallpaper', 'public=1 ORDER BY id DESC LIMIT 20', array());

		echo '<?xml version="1.0" encoding="utf-8"?>';
		echo '<rss version="2.0" xmlns:media="http://search.yahoo.com/mrss/">
				<channel>
					<title>' . Config::option('site_title') . '</title>
				    <link>' . get_url() . '</link>
				    <description>Latest wallpapers on ' . Config::option('site_title') . '</description>';

		foreach($wallpapers as $w)
		{
			$link = Thumbgrid::makeGoodUrl($w->id, 'wallpaper', $w->name);
			$src = Wallpaper::img($w, 'mid');
			$title = View::escape($w->name);
			echo '<item>
					<title><![CDATA[' . $title . ']]></title>
					<link>' . $link . '</link>
					<description><![CDATA[<a href="' . $link . '"><img src="' . $src . '" hspace=3 vspace=3/></a>]]></description>	
					<pubDate>' . date('r', $w->added_at) . '</pubDate>
					<guid isPermaLink="false">' . $link . '</guid>
		            <media:content url="' . $src . '" type="image/jpeg"/>
		    		<media:title>' . $title . '</media:title>
		    		<media:thumbnail url="' . $src . '" height="75" width="75" />
				    <enclosure url="' . $src . '" type="image/jpeg" />	
				</item>';
		}

		echo '</channel></rss>';
	}

}