View file veppa_wallpaper/sys/app/models/Vote.php

File size: 2.41Kb
<?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
 */
/**
 * class User
 *
 * @author Vepa Halliyev <veppa.com>
 * @since  0.1
 */

class Vote extends Record
{
	const TABLE_NAME = 'vote';
	
	private static $cols = array(
		'v_wid'	=>	1,                   
		'v_ip'	=>	1,                   
		'v_vote'	=>	1,        
		'v_time'	=>	1  
	);
	

	public function __construct($data = false, $locale_db = false)
	{
		$this->setColumns(self::$cols);
		parent::__construct($data,$locale_db);
	}

	
	function beforeInsert()
	{
		$this->v_time = REQUEST_TIME;
		
		// update wallpaper vote 
		$w = Wallpaper::findByIdFrom('Wallpaper',$this->v_wid,'id');
		if($w)
		{
			if($this->v_vote>0)
			{
				$w->rank++;
			}
			else
			{
				$w->rank--;
			}
			$w->votes++;
			
			return $w->save('id');
		}
		return false;
	}
	

	static function filterVotedWallpaperIds($w_ids)
	{
		$w_ids = array_unique($w_ids);
	
		if(count($w_ids)>0)
		{		
			$v_ip = self::myip();
			
			// return if some of this wallpapers voted before by this person
			$votes = Vote::findAllFrom('Vote',"v_ip=? AND v_wid IN ('".implode("','",$w_ids)."')",array($v_ip));
			
			
			foreach($votes as $v)
			{
				$r .= $v->v_wid.':'.($v->v_vote>0?'up':'down').',';
			}
			
			$r = trim($r,",");
		}
		
		return $r;
	}
	
	static function vote($v_wid,$v_vote){
		
		// vote and return current vote
		$v_ip = self::myip();

		// find current vote
		$vote = self::findOneFrom('Vote','v_ip=? AND v_wid=?',array($v_ip,$v_wid));
		if(!$vote)
		{
			// check vote for validity
			if($v_vote!='-1')
			{
				// if not -1 then must be 1 no other value
				$v_vote = '1';
			}
			
			// insert new record
			$vote = new Vote();
			$vote->v_wid = $v_wid;
			$vote->v_ip = $v_ip;
			$vote->v_vote = $v_vote;	

			$vote->save('new_id');
		}
		
		
		$r = ($vote->v_vote > 0?'up':'down');
		return $r;
			
	}
	
	static function myip()
	{
		$input = new Input();
		return $input->ip_address();
	}
 
	
} // end User class