<?php

/**
 * 	Referer information
 *	@author SPEED Interactive Agency
 *	@project web-cms
 *	@year 2009-2013
 */

if(!$dprotect) die ('Access Denied!');

class Core {
    
        public function Core() {
            
        }
        
	############################################
	# DATABASE CONNECTION
	############################################	
	
	public function dbConnect () {		
		try {   
			$this->db = new PDO('mysql:host='.DB_HOST.';dbname='.DB_NAME, DB_USER, DB_PASS);
			$this->db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
			$this->db->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);
			$this->db->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, true); 	
			$this->db->query("SET NAMES utf8");		
		} catch(PDOException $e){
			DEBUG ? die('DATABASE CONNECTION ERROR: ' . $e->getMessage()) : die();
		}
	}

	public function dbDisconnect () {	
		unset($this->db);
	}
	
	############################################
	# CORE FUNCTIONS
	############################################
	
	public function postRequest($url, $data)
	{		
		$data = http_build_query($data);
		$context_options = array (
	        'http' => array (
	        'method' => 'POST',
	        'header'=> "Content-type: application/x-www-form-urlencoded\r\n"
	        . "Content-Length: " . strlen($data) . "\r\n",
	        'content' => $data
        )
        );
		$context = stream_context_create($context_options);
		$fp = @fopen($url, 'r', false, $context);
		if($fp) {
			$response = stream_get_contents($fp);
			fclose($fp);
			return $response;
		} else {
			return false;
		}
	}

	public function generatePassword($length=16) {
		$chars = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
		$password = '';
		for ($i = 0; $i < $length; $i++) {
			$password .= $chars[(rand() % strlen($chars))];
		}
		return $password;
	}

	public function checkElementInString($list, $str) {
		$hit = false;
		foreach($list as $k => $v) {
			if(strstr($str, $v)) $hit = true;
		}
		return $hit;
	}		

	public static function check($str, $what='default') {
	
		switch($what) {
			case 'email':
				if (preg_match('/^[_\.0-9a-z-]+@([0-9a-z][0-9a-z-]+\.)+[a-z]{2,4}$/i', $str)) {
					return true;
				} else {
					return false;
				}
			break;
			case 'url':
				if (preg_match('/^(http:\/\/[\.0-9a-z-]+\.[a-z]{2,4}\/?.*)$/i', $str, $tmp)) {
					return $tmp[1];
				} else {
					if(preg_match('/^(http:\/\/[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\/[_=\.,\/\?0-9a-z-]+\.jpe?g)$/i', $str, $tmp)) {
						return $tmp[1];	
					} else {
						return false;
					}
				}
			break;
			case 'domain':
				if (preg_match('/^([\.0-9a-z-]+\.[a-z]{2,4})$/i', $str, $tmp)) {
					return $tmp[1];
				} else {
					if(preg_match('/^([0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3})$/i', $str, $tmp)) {
						return $tmp[1];	
					} else {
						return false;
					}
				}
			break;
			case 'ip':
				if(preg_match('/^([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})\.([0-9]{1,3})$/i', $str, $tmp)
				   && $tmp[1] < 256 && $tmp[1] > 0 && $tmp[2] < 256 && $tmp[3] < 256 && $tmp[4] < 256) {
					return $tmp[1].'.'.$tmp[2].'.'.$tmp[3].'.'.$tmp[4];	
				} else {
					return false;
				}
			break;
			case 'phone':
				$str = str_replace("-", "", str_replace(" ", "", $str));
				if (preg_match('/^\+[0-9]{11}$/i', $str)) {
					return $str;
				} else {
					return false;
				}
			break;
			case 'link':
				if (preg_match('/^[0-9a-z_\-]+$/i', $str)) {
					return $str;
				} else {
					return false;
				}
			break;
                        case 'flink':
				$elements = Array('!', '#', '$', '%', '^', '&', '*', '(', ')', '=', '{', '}', '[', ']', ';', '"', "'", '|', '<', '>', chr(92), '+', '_', ':', ',', '.', '/', '?', '`', '~', '@');
				$pl = Array('ę', 'ó', 'ą', 'ś', 'ł', 'ż', 'ź', 'ć', 'ń', '�?', 'Ó', 'Ą', 'Ś', '�?', 'Ż', 'Ź', 'Ć', '�?');
				$no_pl = Array('e', 'o', 'a', 's', 'l', 'z', 'z', 'c', 'n', 'E', 'O', 'A', 'S', 'L', 'Z', 'Z', 'C', 'N');
				return str_replace($elements, '', strtolower(str_replace($pl, $no_pl, str_replace(' ', '-', preg_replace('/\s\s+/i', ' ', str_replace('-', ' ', trim(strip_tags($str))))))));
			break;
			case 'user':
				$reserved = Array("mail", "admin", "webmaster", "postmaster", "administrator");
				if (preg_match('/^[a-zA-Z0-9]+$/i', $str) && strlen($str)>2 && !in_array($str, $reserved)) {
					return true;
				} else {
					return false;
				}			
			break;
			case 'password':
				if (strlen($str)>3) {
					return true;
				} else {
					return false;
				}			
			break;
			case 'vulgarism':
				$vulgar = Array('zajeb', 'kurw', 'huj', 'pierd', 'fuck', 'whore', 'dick', 'suck', 'prick', 'cipa', 
				'cipy', 'cipo', 'cipe', 'cipę', 'cipą', 'zjeb', 'kutas', 'dupa', 'dupe', 'dupy', 'dziwka', 'dziwke', 'dziwki');
				if ($this->checkElementInString($vulgar, $str)) {
					return false;
				} else {
					return true;
				}
			case 'html':
				//return htmlspecialchars(str_replace(Array('"', "'"), "", $str));
                                return htmlspecialchars($str);
			break;		
			case 'htmldec':
				return htmlspecialchars_decode($str);
			break;
			case 'plain':
				if(!is_array($str)) {
					$elements = Array('!', '#', '$', '%', '^', '&', '*', '=', '{', '}', ';', '"', "'", '|', '<', '>', chr(92));
					return str_replace($elements, '', strip_tags($str));
				} else {
					return $str;
				}
			break;
			case 'hardplain':
				$elements = Array('!', '#', '$', '%', '^', '&', '*', '(', ')', '=', '{', '}', '[', ']', ';', '"', "'", '|', '<', '>', chr(92), '+', '_', ':', ',', '.', '/', '?', '`', '~', '@');
				$pl = Array('ę', 'ó', 'ą', 'ś', 'ł', 'ż', 'ź', 'ć', 'ń', '�?', 'Ó', 'Ą', 'Ś', '�?', 'Ż', 'Ź', 'Ć', '�?');
				$no_pl = Array('e', 'o', 'a', 's', 'l', 'z', 'z', 'c', 'n', 'E', 'O', 'A', 'S', 'L', 'Z', 'Z', 'C', 'N');
				return str_replace($pl, $no_pl, str_replace($elements, '', strip_tags($str)));
			break;
                        case 'generatelink':
                                $elements = Array('!', '#', '$', '%', '^', '&', '*', '(', ')', '=', '{', '}', '[', ']', ';', '"', "'", '|', '<', '>', chr(92), '+', '_', ':', ',', '.', '/', '?', '`', '~', '@', ' ');
				$pl = Array('ę', 'ó', 'ą', 'ś', 'ł', 'ż', 'ź', 'ć', 'ń', '�?', 'Ó', 'Ą', 'Ś', '�?', 'Ż', 'Ź', 'Ć', '�?');
				$no_pl = Array('e', 'o', 'a', 's', 'l', 'z', 'z', 'c', 'n', 'E', 'O', 'A', 'S', 'L', 'Z', 'Z', 'C', 'N');
				return strtolower(str_replace($pl, $no_pl, str_replace($elements, '_', strip_tags($str))));
			case 'default':
				if (preg_match('/^[ _,\.ęóąśłżźćń�?ÓĄŚ�?ŻŹĆ�?a-zA-Z0-9-]+$/i', $str)) {
					return true;
				} else {
					return false;
				}
			break;
			default:
				return false;
		}
	}
	
	public function extractLink($link) 
	{	
		if($link) {
			$link = explode('/', $link);
			foreach($link as $k => $v) {
				$link[$k] = $this->check($v, 'plain');
			}
			return $link;
		} else {
			return false;				
		}
	}
	
	public function xssFilter() 
	{
		foreach($_POST as $k => $v) {
			!is_array($v) ? $_POST[$k] = $this->check($v, 'plain') : null;
		}
	}
	
	public function extension($filename) 
	{
		if(preg_match('/^(.*)\.(.*)$/i', $filename, $ext))
		{
			return strtolower($ext[2]);
		} else {
			return FALSE;
		}
	}
        
        public function isValidDate($date)
        {
            if (preg_match("/^(\d{4})-(\d{2})-(\d{2})$/i", $date, $matches)) {
                if (checkdate($matches[2], $matches[3], $matches[1])) {
                    return true;
                }
            }
            return false;
        }
        
        public function isValidTime($time)
        {
            if (preg_match("/^([01][0-9]|2[0-3]):([0-5][0-9]):([0-5][0-9])$/i", $time)) {
                    return true;
            }
            return false;
        }        
	
	############################################
	# LOGIN FUNCTIONS
	############################################
	
	public function loginUser ($user, $password) {
		
		global $config;

                if($user == $config['user'] && md5($password) == $config['pass']) {
                        $_SESSION['auth']['user'] = $user;
                        $_SESSION['auth']['hash'] = md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $_SESSION['auth']['user']);			
                        return true;
                }
                
                if(!$_SESSION['auth']['hash']) {
			$_SESSION['msg']['text'] = 'Błąd logowania.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
		
	}
	
	public function logoutUser () 
	{			
		if($_SESSION['auth']['hash'] == md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $_SESSION['auth']['user'])) {
			unset($_SESSION['auth']);
			return true;		
		} else {
			return false;
		}
	}
	
	public function checkLogedIn () 
	{			
		if($_SESSION['auth']['hash'] == md5($_SERVER['REMOTE_ADDR'] . $_SERVER['HTTP_USER_AGENT'] . $_SESSION['auth']['user'])) {
			return true;
		} else {
			unset($_SESSION['auth']);
			return false;
		}
	}
	
	############################################
	# CONFIGURATION FUNCTIONS
	############################################
	
	public function readConfiguration() 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`config`
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);		
   			$stmt->execute();
			$result = $stmt->fetch(PDO::FETCH_ASSOC);
			foreach($result as $k => $v) {
				$retval[$k] = $v;
                                
                                if ($k == 'slogan') $retval[$k] = $this->check($v, 'htmldec');
			}
			$stmt->closeCursor();
			return $retval; 
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function updateConfig() 
	{								         
            
                if($_POST['pass']) $_POST['pass'] = md5($_POST['pass']); else unset($_POST['pass']);
                $_POST['slogan'] = $this->check($_POST['slogan'], 'html');
                
		foreach($_POST as $k => $v) {
			if($k!='action') {
				$query .= "`$k` = :$k,\n";                                
			}
		}
			
		try{
			$sql = "
				UPDATE
					`config`
				SET 
					$query
					`control` = 1
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			foreach($_POST as $k => $v) {
				if($k!='action') {
					$stmt->bindValue(":$k", $v, PDO::PARAM_STR);
				}
			}

   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		return true;
	}	
	
	############################################
	# PAGES FUNCTIONS
	############################################
	
	public function addPage($link, $title, $description, $keywords, $text) 
	{
		if(!$title) {
			$_SESSION['msg']['text'] = 'You need to fill title.';
			$_SESSION['msg']['err'] = true;
			return false;
		}

		if(!$this->check($link, 'link')) {
			$_SESSION['msg']['text'] = 'Incorrect characters in link. Allowed characters are: "a"-"z", "0"-"9" oraz "-" i "_".';
			$_SESSION['msg']['err'] = true;
			return false;
		}

		if(!$text) {
			$_SESSION['msg']['text'] = 'You need to fill content.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
						
		try{
			$sql = "
				INSERT INTO 
					`pages`
				SET 
					`link` = :link,
					`title` = '".$this->check(addslashes($title), 'html')."',
					`description` = :description,
					`keywords` = :keywords,
					`text` = '".$this->check(addslashes($text), 'html')."'
				";                        
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':link', $link, PDO::PARAM_STR);
			$stmt->bindValue(':description', $description, PDO::PARAM_STR);
			$stmt->bindValue(':keywords', $keywords, PDO::PARAM_STR);
   			$stmt->execute();
			$stmt->closeCursor();
			$last = $this->db->lastInsertId();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		$this->db->query("UPDATE `pages` SET `order`=".$last." WHERE `id`=".$last." LIMIT 1;");
		return true;
	}
	
        
	public function updatePage($id, $link, $title, $description, $keywords, $text) 
	{
		if(!$title) {
			$_SESSION['msg']['text'] = 'You need to fill title.';
			$_SESSION['msg']['err'] = true;
			return false;
		}

		if(!$this->check($link, 'link')) {
			$_SESSION['msg']['text'] = 'Incorrect characters in link. Allowed characters are: "a"-"z", "0"-"9" oraz "-" i "_".';
			$_SESSION['msg']['err'] = true;
			return false;
		}

		if(!$text) {
			$_SESSION['msg']['text'] = 'You need to fill content.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
			
		try{
			$sql = "
				UPDATE
					`pages`
				SET 
					`link` = :link,
					`title` = '".$this->check(addslashes($title), 'html')."',
					`description` = :description,
					`keywords` = :keywords,
					`text` = '".$this->check(addslashes($text), 'html')."'
				WHERE 
					`id` = :id
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':link', $link, PDO::PARAM_STR);
			$stmt->bindValue(':description', $description, PDO::PARAM_STR);
			$stmt->bindValue(':keywords', $keywords, PDO::PARAM_STR);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
		return true;
	}
	
	public function pageDetailsForId($id) 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`pages`
				WHERE
					`id` = :id
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			$retval['title'] = $this->check(stripslashes($retval['title']), 'htmldec');
			$retval['text'] = $this->check(stripslashes($retval['text']), 'htmldec');
			return $retval ? $retval : array();	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function pageDetailsForLink($link) 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`pages`
				WHERE
					`link` = :link
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':link', $link, PDO::PARAM_STR);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			$retval['title'] = $this->check(stripslashes($retval['title']), 'htmldec');
			$retval['text'] = $this->check(stripslashes($retval['text']), 'htmldec');
			return $retval ? $retval : array();	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}	
	
	public function searchPages($text="", $page=1, $perpage=5) 
	{
		if($text) $cond .= " AND (`title` LIKE :text OR `text` LIKE :text)";
		
		$page < 1 ? $page = 1 : null;
		$perpage < 1 ? $perpage = 5 : null;

		try{
			
			$sql = "
				SELECT
					COUNT(`id`) AS `count`
				FROM
					`pages`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$this->check($text, 'html').'%', PDO::PARAM_STR);
   			$stmt->execute();
			$number = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
						
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		$retval['pages'] = ceil($number['count'] / $perpage);
		$page > $retval['pages'] ? $page =$retval['pages'] : null; 

		if(!$number['count']) {
			return $retval;
		}
				
		try{
			$sql = "
				SELECT
					*
				FROM
					`pages`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				LIMIT
					:page, :perpage;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$this->check($text, 'html').'%', PDO::PARAM_STR);
			$stmt->bindValue(':page', ($page-1)*$perpage, PDO::PARAM_INT);
			$stmt->bindValue(':perpage', $perpage, PDO::PARAM_INT);			
   			$stmt->execute();
			$i=1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval['data'][$result['id']][$k] = $v; 
				}
				$retval['data'][$result['id']]['title'] = $this->check(stripslashes($retval['data'][$result['id']]['title']), 'htmldec');
				$retval['data'][$result['id']]['text'] = $this->check(stripslashes($retval['data'][$result['id']]['text']), 'htmldec');
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			$i = 1;
			if($order) foreach($order as $k => $v) {
				if($i == 1) {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];					
					$i++;
				} elseif ($i == count($result)) {
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				} else {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				}
			}
			$stmt->closeCursor();
			return $retval;	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}

	}
        
        public function listPages() {
		try{
			$sql = "
				SELECT
					*
				FROM
					`pages`
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
	}
	
	public function delPage($id) 
	{	
		try{
			$sql = "
				DELETE FROM 
					`pages`
				WHERE
					`id` = :id
				AND
					`static` = 0
				LIMIT 1;
				DELETE FROM 
					`gal2pages`
				WHERE
					`page` = :id;
				";
			$stmt = $this->db->prepare($sql);
     		$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);
			return true;
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}	        
	
	public function swapPage($src, $dst) {
		if(is_numeric($src) && is_numeric($dst)) {
			$this->db->query("UPDATE `pages` SET `order`=1 WHERE `order`=".$src." LIMIT 1;");
			$this->db->query("UPDATE `pages` SET `order`=".$src." WHERE `order`=".$dst." LIMIT 1;");
			$this->db->query("UPDATE `pages` SET `order`=".$dst." WHERE `order`=1 LIMIT 1;");
			return true;
		} else {
			return false;
		}
	}
        
        ############################################
	# ADVERTS FUNCTIONS
	############################################	
        
	public function updateAdvert($id, $text, $active) 
	{
		if(!$text) {
			$_SESSION['msg']['text'] = 'You need to fill content.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
			
		try{
			$sql = "
				UPDATE
					`adverts`
				SET 
					`text` = '".$this->check(addslashes($text), 'html')."',
                                        `active` = ".$active."
				WHERE 
					`id` = :id
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
		return true;
	}
	
	public function advertDetailsForId($id) 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`adverts`
				WHERE
					`id` = :id
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			$retval['title'] = $this->check(stripslashes($retval['title']), 'htmldec');
			$retval['text'] = $this->check(stripslashes($retval['text']), 'htmldec');
			return $retval ? $retval : array();	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function searchAdverts($text="", $page=1, $perpage=5) 
	{
		if($text) $cond .= " AND (`title` LIKE :text OR `text` LIKE :text)";
		
		$page < 1 ? $page = 1 : null;
		$perpage < 1 ? $perpage = 5 : null;

		try{
			
			$sql = "
				SELECT
					COUNT(`id`) AS `count`
				FROM
					`adverts`
				WHERE
					1 ".$cond."
				ORDER BY
					`id` ASC
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$this->check(addslashes($text), 'html').'%', PDO::PARAM_STR);
   			$stmt->execute();
			$number = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
						
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		$retval['pages'] = ceil($number['count'] / $perpage);
		$page > $retval['pages'] ? $page =$retval['pages'] : null; 

		if(!$number['count']) {
			return $retval;
		}
				
		try{
			$sql = "
				SELECT
					*
				FROM
					`adverts`
				WHERE
					1 ".$cond."
				ORDER BY
					`id` ASC
				LIMIT
					:page, :perpage;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$this->check(addslashes($text), 'html').'%', PDO::PARAM_STR);
			$stmt->bindValue(':page', ($page-1)*$perpage, PDO::PARAM_INT);
			$stmt->bindValue(':perpage', $perpage, PDO::PARAM_INT);			
   			$stmt->execute();
			$i=1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval['data'][$result['id']][$k] = $v; 
				}
				$retval['data'][$result['id']]['title'] = $this->check(stripslashes($retval['data'][$result['id']]['title']), 'htmldec');
				$retval['data'][$result['id']]['text'] = $this->check(stripslashes($retval['data'][$result['id']]['text']), 'htmldec');
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			$i = 1;
			if($order) foreach($order as $k => $v) {
				if($i == 1) {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];					
					$i++;
				} elseif ($i == count($result)) {
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				} else {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				}
			}
			$stmt->closeCursor();
			return $retval;	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}

	}
        
        public function listAdverts() {
		try{
			$sql = "
				SELECT
					*
				FROM
					`adverts`
				ORDER BY
					`id` ASC
				";
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v;
				}
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
	}
        
        ############################################
	# Boxes FUNCTIONS
	############################################
	
	public function addBox($title, $text) 
	{
		if(!$title) {
			$_SESSION['msg']['text'] = 'You need to fill title.';
			$_SESSION['msg']['err'] = true;
			return false;
		}

		if(!$text) {
			$_SESSION['msg']['text'] = 'You need to fill content.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
						
		try{
			$sql = "
				INSERT INTO 
					`boxes`
				SET 
					`title` = '".$this->check(addslashes($title), 'html')."',
					`text` = '".$this->check(addslashes($text), 'html')."'
				";                        
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			$stmt->closeCursor();
			$last = $this->db->lastInsertId();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		$this->db->query("UPDATE `pages` SET `order`=".$last." WHERE `id`=".$last." LIMIT 1;");
		return true;
	}
	
        
	public function updateBox($id, $title, $text) 
	{
		if(!$title) {
			$_SESSION['msg']['text'] = 'You need to fill title.';
			$_SESSION['msg']['err'] = true;
			return false;
		}

		if(!$text) {
			$_SESSION['msg']['text'] = 'You need to fill content.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
			
		try{
			$sql = "
				UPDATE
					`boxes`
				SET 
					`title` = '".$this->check(addslashes($title), 'html')."',
					`text` = '".$this->check(addslashes($text), 'html')."'
				WHERE 
					`id` = :id
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
		return true;
	}
	
	public function boxDetailsForId($id) 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`boxes`
				WHERE
					`id` = :id
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			$retval['title'] = $this->check(stripslashes($retval['title']), 'htmldec');
			$retval['text'] = $this->check(stripslashes($retval['text']), 'htmldec');
			return $retval ? $retval : array();	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function searchBoxes($text="", $page=1, $perpage=5) 
	{
		if($text) $cond .= " AND (`title` LIKE :text OR `text` LIKE :text)";
		
		$page < 1 ? $page = 1 : null;
		$perpage < 1 ? $perpage = 5 : null;

		try{
			
			$sql = "
				SELECT
					COUNT(`id`) AS `count`
				FROM
					`boxes`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$this->check(addslashes($text), 'html').'%', PDO::PARAM_STR);
   			$stmt->execute();
			$number = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
						
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		$retval['pages'] = ceil($number['count'] / $perpage);
		$page > $retval['pages'] ? $page =$retval['pages'] : null; 

		if(!$number['count']) {
			return $retval;
		}
				
		try{
			$sql = "
				SELECT
					*
				FROM
					`boxes`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				LIMIT
					:page, :perpage;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$this->check(addslashes($text), 'html').'%', PDO::PARAM_STR);
			$stmt->bindValue(':page', ($page-1)*$perpage, PDO::PARAM_INT);
			$stmt->bindValue(':perpage', $perpage, PDO::PARAM_INT);			
   			$stmt->execute();
			$i=1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval['data'][$result['id']][$k] = $v; 
				}
				$retval['data'][$result['id']]['title'] = $this->check(stripslashes($retval['data'][$result['id']]['title']), 'htmldec');
				$retval['data'][$result['id']]['text'] = $this->check(stripslashes($retval['data'][$result['id']]['text']), 'htmldec');
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			$i = 1;
			if($order) foreach($order as $k => $v) {
				if($i == 1) {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];					
					$i++;
				} elseif ($i == count($result)) {
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				} else {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				}
			}
			$stmt->closeCursor();
			return $retval;	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}

	}
        
        public function listBoxes() {
		try{
			$sql = "
				SELECT
					*
				FROM
					`boxes`
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
	}
	
	public function delBox($id) 
	{	
		try{
			$sql = "
				DELETE FROM 
					`boxes`
				WHERE
					`id` = :id
				LIMIT 1;
				";
			$stmt = $this->db->prepare($sql);
     		$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);
			return true;
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}	        
	
	public function swapBox($src, $dst) {
		if(is_numeric($src) && is_numeric($dst)) {
			$this->db->query("UPDATE `boxes` SET `order`=1 WHERE `order`=".$src." LIMIT 1;");
			$this->db->query("UPDATE `boxes` SET `order`=".$src." WHERE `order`=".$dst." LIMIT 1;");
			$this->db->query("UPDATE `boxes` SET `order`=".$dst." WHERE `order`=1 LIMIT 1;");
			return true;
		} else {
			return false;
		}
	}
        
        ############################################
	# GALLERIES FUNCTIONS
	############################################
	
	public function addGallery($name) {

		if(!$name) {
			$_SESSION['msg']['text'] = 'Podaj nazwę galerii.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
						
		try{
			$sql = "
				INSERT INTO 
					`galleries`
				SET 
					`name` = :name
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':name', $name, PDO::PARAM_STR);
   			$stmt->execute();
			$stmt->closeCursor();
			$last = $this->db->lastInsertId();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		$this->db->query("UPDATE `galleries` SET `order`=".$last." WHERE `id`=".$last." LIMIT 1;");
		return true;
	}
	
	public function updateGallery($id, $name) {

		if(!$name) {
			$_SESSION['msg']['text'] = 'Podaj nazwę galerii.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
			
		try{
			$sql = "
				UPDATE
					`galleries`
				SET 
					`name` = :name
				WHERE 
					`id` = :id
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':name', $name, PDO::PARAM_STR);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
		return true;
	}
	
	public function galleryDetailsForId($id) {
		try{
			$sql = "
				SELECT
					*
				FROM
					`galleries`
				WHERE
					`id` = :id
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			return $retval ? $retval : array();	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function searchGalleries($text="", $page=1, $perpage=5) 
	{
		if($text) $cond .= " AND (`name` LIKE :text)";
		
		$page < 1 ? $page = 1 : null;
		$perpage < 1 ? $perpage = 5 : null;

		try{
			
			$sql = "
				SELECT
					COUNT(`id`) AS `count`
				FROM
					`galleries`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$text.'%', PDO::PARAM_STR);;
   			$stmt->execute();
			$number = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
						
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		$retval['pages'] = ceil($number['count'] / $perpage);
		$page > $retval['pages'] ? $page =$retval['pages'] : null; 

		if(!$number['count']) {
			return $retval;
		}
				
		try{
			$sql = "
				SELECT
					*
				FROM
					`galleries`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				LIMIT
					:page, :perpage;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$text.'%', PDO::PARAM_STR);;
			$stmt->bindValue(':page', ($page-1)*$perpage, PDO::PARAM_INT);
			$stmt->bindValue(':perpage', $perpage, PDO::PARAM_INT);			
   			$stmt->execute();
			$i = 1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval['data'][$result['id']][$k] = $v; 
				}
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			$i = 1;
			foreach($order as $k => $v) {
				if($i == 1) {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];					
					$i++;
				} elseif ($i == count($result)) {
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				} else {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				}
			}

			$stmt->closeCursor();
			return $retval;	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}

	}
	
	public function delGallery($id) 
	{	
		try{
			$sql = "
				DELETE FROM 
					`galleries`
				WHERE
					`id` = :id AND `static` = 0;
				LIMIT 1;
				";
			$stmt = $this->db->prepare($sql);
     		$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);
			return true;
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function listGalleries() {
		try{
			$sql = "
				SELECT
					*
				FROM
					`galleries`
                                WHERE 
                                        `id` > 9
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
	}
        
        public function listGalleriesForRedactor() {
		try{
			$sql = "
				SELECT
					*
				FROM
					`galleries`
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
                                $retval[$result['id']]['images'] = $this->imagesForGallery($result['id']);
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
	}
        
	
	public function swapGallery($src, $dst) {
		if(is_numeric($src) && is_numeric($dst)) {
			$this->db->query("UPDATE `galleries` SET `order`=1 WHERE `order`=".$src." LIMIT 1;");
			$this->db->query("UPDATE `galleries` SET `order`=".$src." WHERE `order`=".$dst." LIMIT 1;");
			$this->db->query("UPDATE `galleries` SET `order`=".$dst." WHERE `order`=1 LIMIT 1;");
			return true;
		} else {
			return false;
		}
	}
	
	############################################
	# IMAGES FUNCTIONS
	############################################
	
	public function convertUploadedImage($handler) 
	{	
		global $config;
		list($width, $height) = getimagesize($handler['tmp_name']);
		
		if($width > $height) {
			if($width > $config['maxw']) {
				$scale = $config['maxw'] / $width;
				$newwidth = $config['maxw'];
				$newheight = floor($height * $scale);
			}
		} else {
			if($height > $config['maxh']) {
				$scale = $config['maxh'] / $height;
				$newheight = $config['maxh'];
				$newwidth = floor($width * $scale);
			}
		}
							
		if($newwidth && $newheight) {
			$destination = imagecreatetruecolor($newwidth, $newheight);
			$ext = $this->extension($handler['name']);
			switch($ext) {
				case 'jpeg':
				case 'jpg':
					$source = imagecreatefromjpeg($handler['tmp_name']);
					imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					imagejpeg($destination, $handler['tmp_name'], $config['quality']);
				break;
				case 'gif':
					$source = imagecreatefromgif($handler['tmp_name']);
					imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					imagegif($destination, $handler['tmp_name']);
				break;
				case 'png':
					$source = imagecreatefrompng($handler['tmp_name']);
					imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
					imagepng($destination, $handler['tmp_name']);
				break;
			}
		}
	}
	
	public function createThumbnail($source_file, $destination_file) 
	{
		global $config;
		list($width, $height) = getimagesize($source_file);
		
		$scale = $config['maxhm'] / $height;
		$newheight = $config['maxhm'];
		$newwidth = floor($width * $scale);
		
		$ext = $this->extension($source_file);
		$destination = imagecreatetruecolor($newwidth, $newheight);
		switch($ext) {
			case 'jpeg':
			case 'jpg':
				$source = imagecreatefromjpeg($source_file);
				imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
				imagejpeg($destination, $destination_file, $config['qualitym']);
			break;
			case 'gif':
				$source = imagecreatefromgif($source_file);
				imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
				imagegif($destination, $destination_file);
			break;
			case 'png':
				$source = imagecreatefrompng($source_file);
				imagecopyresampled($destination, $source, 0, 0, 0, 0, $newwidth, $newheight, $width, $height);
				imagepng($destination, $destination_file);
			break;
		}
	}
	
	public function addImage($gallery, $filename) 
	{					
		try{
			$sql = "
				INSERT INTO 
					`images`
				SET 
					`gallery` = :gallery,
					`filename` = :filename
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':gallery', $gallery, PDO::PARAM_INT);
			$stmt->bindValue(':filename', $filename, PDO::PARAM_STR);
   			$stmt->execute();
			$stmt->closeCursor();
			$last = $this->db->lastInsertId();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		$this->db->query("UPDATE `images` SET `order`=".$last." WHERE `id`=".$last." LIMIT 1;");
		return true;
		
	}
	
	public function imagesForGallery($gallery) 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`images`
				WHERE
					`gallery` = :gallery
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':gallery', $gallery, PDO::PARAM_INT);
   			$stmt->execute();
			$i = 1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			if($order) {
				$i = 1;
				foreach($order as $k => $v) {
					if($i == 1) {
						$retval[$v['id']]['next'] = $order[$i+1]['order'];					
						$i++;
					} elseif ($i == count($result)) {
						$retval[$v['id']]['prev'] = $order[$i-1]['order'];
						$i++;
					} else {
						$retval[$v['id']]['next'] = $order[$i+1]['order'];
						$retval[$v['id']]['prev'] = $order[$i-1]['order'];
						$i++;
					}
				}
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	public function delImage ($id) 
	{
		global $config;	
		try{
			$sql = "
				SELECT
					`filename`
				FROM
					`images`
				WHERE
					`id`  = :id
				LIMIT 1  
				;";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$image = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		if($image['filename']) {
			try{
				$sql = "
					DELETE FROM
						`images`
					WHERE
						`id`  = :id
					LIMIT 1  
					;";
					
				$stmt = $this->db->prepare($sql);
				$stmt->bindValue(':id', $id, PDO::PARAM_INT);
	   			$stmt->execute();
				if($stmt->rowCount()) {
					$stmt->closeCursor();
					unset($stmt);
					unlink($config['imagedir'].'/'.$image['filename']);
					unlink($config['thumbdir'].'/'.$image['filename']);
					return true;	
				}
			} catch(PDOException $e){
				DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
			}
		}
		return false;
	}			

	public function swapImage($gallery, $src, $dst) {
		if(is_numeric($src) && is_numeric($dst) && is_numeric($gallery)) {
			$this->db->query("UPDATE `images` SET `order`=1 WHERE `gallery`=".$gallery." AND `order`=".$src." LIMIT 1;");
			$this->db->query("UPDATE `images` SET `order`=".$src." WHERE `gallery`=".$gallery." AND `order`=".$dst." LIMIT 1;");
			$this->db->query("UPDATE `images` SET `order`=".$dst." WHERE `gallery`=".$gallery." AND `order`=1 LIMIT 1;");
			return true;
		} else {
			return false;
		}
	}        
        
       ############################################
	# FILES FUNCTIONS
	############################################
	
	function addDownload($name) {

		if(!$name) {
			$_SESSION['msg']['title'] = 'Podaj nazwę kategorii.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
						
		try{
			$sql = "
				INSERT INTO 
					`download`
				SET 
					`name` = :name
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':name', $name, PDO::PARAM_STR);
   			$stmt->execute();
			$stmt->closeCursor();
			$last = $this->db->lastInsertId();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		$this->db->query("UPDATE `download` SET `order`=".$last." WHERE `id`=".$last." LIMIT 1;");
		return true;
	}
        
        function listDownload() {
		try{
			$sql = "
				SELECT
					*
				FROM
					`download`
                                WHERE 
                                        `id` > 9
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
   			$stmt->execute();
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
                                //$retval[$result['id']]['ext'] = $this->extension($retval[$result['id']]['filename']);
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
	}
	
	function updateDownload($id, $name) {

		if(!$name) {
			$_SESSION['msg']['title'] = 'Podaj nazwę kategorii.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
			
		try{
			$sql = "
				UPDATE
					`download`
				SET 
					`name` = :name
				WHERE 
					`id` = :id
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':name', $name, PDO::PARAM_STR);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
		return true;
	}
	
	function downloadDetailsForId($id) {
		try{
			$sql = "
				SELECT
					*
				FROM
					`download`
				WHERE
					`id` = :id
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			return $retval ? $retval : array();	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	function searchDownload($text="", $page=1, $perpage=5) 
	{
		if($text) $cond .= " AND (`name` LIKE :text)";
		
		$page < 1 ? $page = 1 : null;
		$perpage < 1 ? $perpage = 5 : null;

		try{
			
			$sql = "
				SELECT
					COUNT(`id`) AS `count`
				FROM
					`download`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$text.'%', PDO::PARAM_STR);;
   			$stmt->execute();
			$number = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
						
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		$retval['pages'] = ceil($number['count'] / $perpage);
		$page > $retval['pages'] ? $page =$retval['pages'] : null; 

		if(!$number['count']) {
			return $retval;
		}
				
		try{
			$sql = "
				SELECT
					*
				FROM
					`download`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				LIMIT
					:page, :perpage;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$text.'%', PDO::PARAM_STR);;
			$stmt->bindValue(':page', ($page-1)*$perpage, PDO::PARAM_INT);
			$stmt->bindValue(':perpage', $perpage, PDO::PARAM_INT);			
   			$stmt->execute();
			$i = 1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval['data'][$result['id']][$k] = $v; 
				}
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			$i = 1;
			foreach($order as $k => $v) {
				if($i == 1) {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];					
					$i++;
				} elseif ($i == count($result)) {
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				} else {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				}
			}

			$stmt->closeCursor();
			return $retval;	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}

	}
	
	function delDownload($id) 
	{	
		try{
			$sql = "
				DELETE FROM 
					`download`
				WHERE
					`id` = :id AND `static` = 0
				LIMIT 1;
				";
			$stmt = $this->db->prepare($sql);
     		$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);
			return true;
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}		
	
	function swapDownload($src, $dst) {
		if(is_numeric($src) && is_numeric($dst)) {
			$this->db->query("UPDATE `download` SET `order`=1 WHERE `order`=".$src." LIMIT 1;");
			$this->db->query("UPDATE `download` SET `order`=".$src." WHERE `order`=".$dst." LIMIT 1;");
			$this->db->query("UPDATE `download` SET `order`=".$dst." WHERE `order`=1 LIMIT 1;");
			return true;
		} else {
			return false;
		}
	}
	
	############################################
	# FILES FUNCTIONS
	############################################		
	
	function addFile($download, $filename, $filetitle) 
	{					
		try{
			$sql = "
				INSERT INTO 
					`files`
				SET 
					`download` = :download,
					`filename` = :filename,
                                        `filetitle` = :filetitle
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':download', $download, PDO::PARAM_INT);
			$stmt->bindValue(':filename', $filename, PDO::PARAM_STR);
                        $stmt->bindValue(':filetitle', $filetitle, PDO::PARAM_STR);
   			$stmt->execute();
			$stmt->closeCursor();
			$last = $this->db->lastInsertId();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		$this->db->query("UPDATE `files` SET `order`=".$last." WHERE `id`=".$last." LIMIT 1;");
		return true;
		
	}
	
	function filesForDownload($download) 
	{
		try{
			$sql = "
				SELECT
					*
				FROM
					`files`
				WHERE
					`download` = :download
				ORDER BY
					`order` ASC
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':download', $download, PDO::PARAM_INT);
   			$stmt->execute();
			$i = 1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval[$result['id']][$k] = $v; 
				}
                                $retval[$result['id']]['ext'] = $this->extension($retval[$result['id']]['filename']);
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			if($order) {
				$i = 1;
				foreach($order as $k => $v) {
					if($i == 1) {
						$retval[$v['id']]['next'] = $order[$i+1]['order'];					
						$i++;
					} elseif ($i == count($result)) {
						$retval[$v['id']]['prev'] = $order[$i-1]['order'];
						$i++;
					} else {
						$retval[$v['id']]['next'] = $order[$i+1]['order'];
						$retval[$v['id']]['prev'] = $order[$i-1]['order'];
						$i++;
					}
				}
			}
			$stmt->closeCursor();
			return $retval;	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}
	
	function delFile ($id) 
	{
		global $config;	
		try{
			$sql = "
				SELECT
					`filename`
				FROM
					`files`
				WHERE
					`id`  = :id
				LIMIT 1  
				;";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$image = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		if($image['filename']) {
			try{
				$sql = "
					DELETE FROM
						`files`
					WHERE
						`id`  = :id
					LIMIT 1  
					;";
					
				$stmt = $this->db->prepare($sql);
				$stmt->bindValue(':id', $id, PDO::PARAM_INT);
	   			$stmt->execute();
				if($stmt->rowCount()) {
					$stmt->closeCursor();
					unset($stmt);
					unlink($config['filedir'].'/'.$image['filename']);					
					return true;	
				}
			} catch(PDOException $e){
				DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
			}
		}
		return false;
	}	
        
        function fileDetailsForId($id) {
		try{
			$sql = "
				SELECT
					*
				FROM
					`files`
				WHERE
					`id` = :id
	 			LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);	
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);	
   			$stmt->execute();
			$retval = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
			return $retval ? $retval : array();	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
	}

	function swapFile($download, $src, $dst) {
		if(is_numeric($src) && is_numeric($dst) && is_numeric($download)) {
			$this->db->query("UPDATE `files` SET `order`=1 WHERE `download`=".$download." AND `order`=".$src." LIMIT 1;");
			$this->db->query("UPDATE `files` SET `order`=".$src." WHERE `download`=".$download." AND `order`=".$dst." LIMIT 1;");
			$this->db->query("UPDATE `files` SET `order`=".$dst." WHERE `download`=".$download." AND `order`=1 LIMIT 1;");
			return true;
		} else {
			return false;
		}
	}  
        
        function updateFile($id, $filetitle) {

            
		if(!$filetitle) {
			$_SESSION['msg']['title'] = 'Podaj opis pliku.';
			$_SESSION['msg']['err'] = true;
			return false;
		}
			
		try{
			$sql = "
				UPDATE
					`files`
				SET 
					`filetitle` = :filetitle
				WHERE 
					`id` = :id
				LIMIT 1;
				";
				
			$stmt = $this->db->prepare($sql);
			$stmt->bindValue(':filetitle', $filetitle, PDO::PARAM_STR);
			$stmt->bindValue(':id', $id, PDO::PARAM_INT);
   			$stmt->execute();
			$stmt->closeCursor();
			unset($stmt);	
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}		
		return true;
	}
        
        function searchFiles($text="", $page=1, $perpage=5) 
	{
		if($text) $cond .= " AND (`filetitle` LIKE :text)";
		
		$page < 1 ? $page = 1 : null;
		$perpage < 1 ? $perpage = 5 : null;

		try{
			
			$sql = "
				SELECT
					COUNT(`id`) AS `count`
				FROM
					`files`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$text.'%', PDO::PARAM_STR);;
   			$stmt->execute();
			$number = $stmt->fetch(PDO::FETCH_ASSOC);
			$stmt->closeCursor();
						
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}
		
		$retval['pages'] = ceil($number['count'] / $perpage);
		$page > $retval['pages'] ? $page =$retval['pages'] : null; 

		if(!$number['count']) {
			return $retval;
		}
				
		try{
			$sql = "
				SELECT
					*
				FROM
					`files`
				WHERE
					1 ".$cond."
				ORDER BY
					`order` ASC
				LIMIT
					:page, :perpage;
				";
				
			$stmt = $this->db->prepare($sql);
			if($text) $stmt->bindValue(':text', '%'.$text.'%', PDO::PARAM_STR);;
			$stmt->bindValue(':page', ($page-1)*$perpage, PDO::PARAM_INT);
			$stmt->bindValue(':perpage', $perpage, PDO::PARAM_INT);			
   			$stmt->execute();
			$i = 1;
			while($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
				foreach($result as $k => $v) {
					$retval['data'][$result['id']][$k] = $v; 
				}
                                $retval['data'][$result['id']]['ext'] = $this->extension($retval['data'][$result['id']]['filename']);
				$order[$i]['id'] = $result['id'];
				$order[$i]['order'] = $result['order']; 
				$i++;
			}
			$i = 1;
			foreach($order as $k => $v) {
				if($i == 1) {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];					
					$i++;
				} elseif ($i == count($result)) {
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				} else {
					$retval['data'][$v['id']]['next'] = $order[$i+1]['order'];
					$retval['data'][$v['id']]['prev'] = $order[$i-1]['order'];
					$i++;
				}
			}

			$stmt->closeCursor();
			return $retval;	
			
		} catch(PDOException $e){
			DEBUG ? die('SQL Error: '.$e->getMessage()) : die();
		}

	}          
	
	
}
 
?>