<?php

/**

* @version		1.1

* @package		DJ Classifieds

* @subpackage	DJ Classifieds Component

* @copyright	Copyright (C) 2010 Blue Constant Media LTD, All rights reserved.

* @license		http://www.gnu.org/licenses GNU/GPL

* @autor url    http://design-joomla.eu

* @autor email  contact@design-joomla.eu

* @Developer    Lukasz Ciastek - lukasz.ciastek@design-joomla.eu

* 

* 

* DJ Classifieds is free software: you can redistribute it and/or modify

* it under the terms of the GNU General Public License as published by

* the Free Software Foundation, either version 3 of the License, or

* (at your option) any later version.

*

* DJ Classifieds is distributed in the hope that it will be useful,

* but WITHOUT ANY WARRANTY; without even the implied warranty of

* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the

* GNU General Public License for more details.

*

* You should have received a copy of the GNU General Public License

* along with DJ Classifieds. If not, see <http://www.gnu.org/licenses/>.

* 

*/





defined ('_JEXEC') or die('Restricted access');

jimport('joomla.application.component.controller');

jimport('joomla.filesystem.file');

JTable::addIncludePath(JPATH_COMPONENT.DS.'tables');

//$lang =& JFactory::GetLanguage();

//$lang->load('com_djclassifieds');



class DJClassifiedsController extends JController

{

	

	function display()

	{	

		parent::display();

	}



	function show(){

		$cid = JRequest::getVar('cid', 0, '', 'int');

		if($cid>0){

			$db= &JFactory::getDBO();			

			$query = "SELECT COUNT(id) FROM #__djcf_categories WHERE published = 1 AND parent_id=".$cid;

			$db->setQuery($query);

			$cid_c = $db->loadResult();

			if($cid_c>0){

				JRequest::setVar('view','show');

				parent::display();	

			}else{

				JRequest::setVar('view','showlist');

				parent::display();	

			}

		}else{

			JRequest::setVar('view','show');

			parent::display();	

		}

		

	}

	

		

	function additem()

	{	

		global $mainframe, $option;



		/*$par = &JComponentHelper::getParams( 'com_djclassifieds' );

		if($par->get(user_type)==1){

			$user = & JFactory::getUser();



			if($user->id!='0'){

				JRequest::setVar('view','additem');

				parent::display();

			}else{

				$message = JText::_('Please login');

				$redirect= "index.php?option=com_user&view=login&re=additem";

				$redirect = JRoute::_($redirect);

				$this->setRedirect($redirect, $message);

			}



		}else{*/

			JRequest::setVar('view','additem');

			parent::display();

		//}

	}

	

	function edititem()

	{	

		global $mainframe, $option;	

		$user = & JFactory::getUser();		

		$id = JRequest::getVar('id', 0, '', 'int');		

		$db= &JFactory::getDBO();

		$query = "SELECT user_id FROM #__djcf_items WHERE id=".$id;

		$db->setQuery($query);

		$item = $db->loadResult();

		

		if($user->id!=0 && $item==$user->id){

			JRequest::setVar('view','additem');

			parent::display();

		}else{

			$redirect= 'index.php';				

			$message = JText::_("This item isn't available");	

			$this->setRedirect($redirect,$message);

		}	

	}

	

	function renew()

	{	

		global $mainframe, $option;	

		$user = & JFactory::getUser();		

		$id = JRequest::getVar('id', 0, '', 'int');		

		$db= &JFactory::getDBO();

		$query = "SELECT user_id,cat_id FROM #__djcf_items WHERE id=".$id;

		$db->setQuery($query);

		$item = $db->loadObject();

		

		

		if($user->id!=0 && $item->user_id==$user->id){

	

			$query = "SELECT cat_id, special FROM #__djcf_items WHERE id = ".$id;

			$db =& JFactory::getDBO();		

			$db->setQuery($query);

			$old_row = $db->loadObject();

		

			$date_time =& JFactory::getDate();

        	$par = &JComponentHelper::getParams( 'com_djclassifieds' );

        	$exp_days = (int)$par->get('exp_days');

		

			$date_time->_date = $date_time->_date+ $exp_days*24*60*60;

			$date_exp= explode(' ',$date_time->toMySQL());

		

			JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

    		$row = & JTable::getInstance('items', 'table');

			$row->load(JRequest::getVar('id', 0, '', 'int'));

			$row->date_exp=$date_exp[0];

			

			$query = "SELECT price,autopublish FROM #__djcf_categories WHERE id = ".$row->cat_id;

			$db =& JFactory::getDBO();		

			$db->setQuery($query);

			$cat = $db->loadObject();		

			

			if($redirect==''){

				$menus	= &JSite::getMenu();

				foreach($menus->_items as $m){

					if($m->link == 'index.php?option=com_djclassifieds&view=show&cid=0'){

						$itemid=$m->id;

						break;

					}

				}

				$redirect= 'index.php?option=com_djclassifieds&view=showitem&cid='.$row->cat_id.'&id='.$row->id.'&Itemid='.$itemid;

			}

		

			if($cat->price>0 || $row->special==1){

				if($cat->price>0){

					$row->pay_type .= 'cat,';

				}

				if($row->special==1){

					$row->pay_type .= 'special,';

				}

				

				$row->published = 0;

				$row->payed = 0;

				

				if (!$row->store())

    			{

	        		echo "<script> alert('".$row->getError()."');

					window.history.go(-1); </script>\n";

        			exit ();

    			}

				$link = 'index.php?option=com_djclassifieds&view=additempaypal&id='.$row->id.'&t=renew&Itemid='.$itemid;

     			$msg = JText::_('Please pay for renew ad');

				$link = JRoute::_($link);			

	 			$mainframe->redirect($link, $msg);	

			}



		    if (!$row->store()){

    	    	echo "<script> alert('".$row->getError()."');

				window.history.go(-1); </script>\n";

        		exit ();

    		}



			if($redirect==''){

				$menus	= &JSite::getMenu();

				foreach($menus->_items as $m){

					if($m->link == 'index.php?option=com_djclassifieds&view=show&cid=0'){

						$itemid=$m->id;

						break;

					}

				}

				$redirect= 'index.php?option=com_djclassifieds&view=showitem&cid='.$row->cat_id.'&id='.$row->id.'&Itemid='.$itemid;

			}

			$message = JText::_("Ad is renewed");	

			$this->setRedirect($redirect,$message);



		}else{

			$redirect= 'index.php';				

			$message = JText::_("This item isn't available");	

			$this->setRedirect($redirect,$message);

		}	

	}

	

	function useritems()

	{	

		global $mainframe, $option;

		$user = & JFactory::getUser();



		if($user->id!='0'){

			JRequest::setVar('view','useritems');

			parent::display();

		}else{

			$par = &JComponentHelper::getParams( 'com_djclassifieds' );

			if($par->get('user_type')=='1'){							

				$message = JText::_('Please login');

				$itemid = JRequest::getVar('Itemid', '', '', 'int');		

				$redirect= "index.php?option=com_djclassifieds&view=additem&re=useritems&Itemid=".$itemid;

				//$redirect = JRoute::_($redirect);

				$this->setRedirect($redirect, $message);				

			}else{

				$message = JText::_('Please login');	

				$redirect= "index.php";

				$this->setRedirect($redirect, $message);				

			}

		}

	}

	

	function showitem(){

		global $mainfame;



		JRequest::setVar('view','showitem');

		$user = & JFactory::getUser();		

		$id = JRequest::getVar('id', 0, '', 'int');		

		$db= &JFactory::getDBO();

		$query = "SELECT date_exp, user_id, published FROM #__djcf_items WHERE id=".$id;

		$db->setQuery($query);

		$item = $db->loadObject();

		

		if($item->published==0){

			$redirect= 'index.php';				

			$message = JText::_("This item isn't available");	

			$this->setRedirect($redirect,$message);

		}

		$date_exp = $item->date_exp; 

		$date_now =& JFactory::getDate();

		$date_all=$date_now->toMySQL();

		$date_exp = strtotime($date_exp);

		

		if($date_now->_date<$date_exp || $item->user_id==$user->id){

			$query = "UPDATE `#__djcf_items` SET display=display+1 WHERE id=".$id;

			$db->setQuery($query);

			$db->query();

			parent::display();

		}else{

			$redirect= 'index.php';				

			$message = JText::_("This item isn't available");	

			$this->setRedirect($redirect,$message);

		}	



	}

	

	  function makeimg($adres, $nw, $nh, $ext)

    {

        $par = &JComponentHelper::getParams( 'com_djclassifieds' );

		

		/* ------------------- */

		if (!$adres)

            return false;

		

		 if (! list ($w, $h, $type, $attr) = getimagesize($adres)) {

            if (! list ($w, $h, $type, $attr) = getimagesize($adres)) {

                return false;

    	    }

	    }

		

        switch($type)

        {

            case 1:

                $simg = imagecreatefromgif($adres);

                break;

            case 2:

                $simg = imagecreatefromjpeg($adres);

                break;

            case 3:

                $simg = imagecreatefrompng($adres);

                break;

        }

		

		$x = 0;

		$y = 0;

		$cw = $w;

		$ch = $h;

		

		$nw_half = (int)floor($nw/2);

		$nh_half = (int)floor($nh/2);

		$w_half = (int)floor($w/2);

		$h_half = (int)floor($h/2);

		

		if ($nw == 0 && $nh == 0) {

			$nw = 200;

			$nh = (int)(floor(($nw * $h) / $w));

		}

		elseif ($nw == 0) {

			$nw = (int)(floor(($nh * $w) / $h));

		}

		elseif ($nh == 0) {

			$nh = (int)(floor(($nw * $h) / $w));

		}

		elseif ($nw < $w || $nh < $h) {

	        if ($nw <= $nh)

	        {

				if ($w <= $h) {

					$ch = $h;

					$temp_w = (int)floor(($h * $nw)/$nh);

					if ($temp_w > $w) {

						$cw = $w;

					}

					else {

						$cw = $temp_w;

						$x = $w_half - (int)($temp_w/2);

					}

				}

				elseif ($w > $h) {

					$ch = $h;

					$temp_w = (int)floor(($h * $nw)/$nh);

					if ($temp_w > $w) {

						$cw = $w;

					}

					else {

						$cw = $temp_w;

						$x = $w_half - (int)($temp_w/2);

					}

				}

	        } 

			elseif ($nw > $nh) {

	        	if ($w <= $h) {

					$cw = $w;

					$temp_h = (int)floor(($nh * $w)/$nw);

					if ($temp_h > $h) {

						$ch = $h;

					}

					else {

						$ch = $temp_h;

						$y = $h_half - (int)($temp_h/2);

					}

				}

				elseif ($w > $h) {

					$cw = $w;

					$temp_h = (int)floor(($nh * $w)/$nw);

					if ($temp_h > $h) {

						$ch = $h;

					}

					else {

						$ch = $temp_h;

						$y = $h_half - (int)($temp_h/2);

					}

				}        

	        }

		}

		elseif ($nw == -1 || $nh == -1) {

			return false;

		}

		$dimg = imagecreatetruecolor($nw, $nh);

		$bgColor = imagecolorallocate($dimg, 255, 255, 255);

	    imagefill($dimg, 0, 0, $bgColor);

 		imagecopyresampled($dimg, $simg, 0, 0, $x, $y, $nw, $nh, $cw, $ch);

		

		$thumb_path = $adres.'.'.$ext.'.jpg';

	    if (is_file($thumb_path))

			unlink($thumb_path);

	  

	    imagejpeg($dimg, $thumb_path, 85);

		

		return true;

	}

	

	

function saveItem()

{



    global $mainframe;

	JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

    $row = & JTable::getInstance('items', 'table');

	$par = &JComponentHelper::getParams( 'com_djclassifieds' );

	

	

    if (!$row->bind(JRequest::get('post')))

    {



        echo "<script> alert('".$row->getError()."');



			window.history.go(-1); </script>\n";



        exit ();



    }

	

	if((int)$par->get('allow_htmltags','0')){

		$row->description = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);	

	}else{

		$row->description = nl2br(JRequest::getVar('description', '', 'post', 'string'));

	}

    

    $intro_desc = JRequest::getVar('intro_desc', '', 'post', 'string', JREQUEST_ALLOWRAW);

    $row->intro_desc = substr($intro_desc,0, 120);

    $row->contact = nl2br(JRequest::getVar('contact', '', 'post', 'string'));

	

    //add images

    $pliki = $_FILES['image'];

	

	if(count($pliki['name'])>0){

		$nw = (int)$par->get('th_width',-1);

    	$nh = (int)$par->get('th_height',-1);	

		$nws = $par->get('smallth_width',-1);

        $nhs = $par->get('smallth_height',-1);

		$nwm = $par->get('middleth_width',-1);

    	$nhm = $par->get('middleth_height',-1);		

		$nwb = $par->get('bigth_width',-1);

    	$nhb = $par->get('bigth_height',-1);	

		$img_maxsize = $par->get('img_maxsize',0);		

			if($img_maxsize>0){

				$img_maxsize = $img_maxsize*1024*1024;

			}

		

			$query = "SELECT id FROM #__djcf_items ORDER BY id DESC LIMIT 1";

			$db =& JFactory::getDBO();		

			$db->setQuery($query);

			$last_id =$db->loadResult();

			$last_id++;

	}

	

    for ($i = 0; $i < count($pliki['name']); $i++)

    {

        if (substr($pliki['type'][$i], 0, 5) == "image")

        {

        	$s_f = getimagesize($pliki['tmp_name'][$i]);

			if(is_array($s_f) && $s_f[0] > 2){

				if($img_maxsize>0 && $pliki['size'][$i]>$img_maxsize){

					continue;

				}

            	$n_name = $last_id.'_'.str_ireplace(' ', '_',$pliki['name'][$i]);            	

            	$sciezka = JPATH_BASE."/components/com_djclassifieds/images/".$n_name;

				$nimg= 0;			

				while(JFile::exists($sciezka)){

					$nimg++;

        			$n_name = $last_id.'_'.$nimg.'_'.str_ireplace(' ', '_',$pliki['name'][$i]);            	

            		$sciezka = JPATH_BASE."/components/com_djclassifieds/images/".$n_name;

				}

				$images .= $n_name.';';

            	move_uploaded_file($pliki['tmp_name'][$i], $sciezka);

            	$this->makeimg($sciezka, $nw, $nh, 'th');



				 	$this->makeimg($sciezka, $nws, $nhs, 'ths');

					$this->makeimg($sciezka, $nwm, $nhm, 'thm');

					$this->makeimg($sciezka, $nwb, $nhb, 'thb');



			}

        }

    }

    $row->image_url = $images;



	if(!$row->ordering){

			$query = "SELECT ordering FROM #__djcf_items WHERE cat_id = ".$row->cat_id." ORDER BY ordering DESC LIMIT 1";

			$db =& JFactory::getDBO();		

			$db->setQuery($query);

			$order =$db->loadObject();

			$row->ordering = $order->ordering + 1;

	}

		$session = &JFactory::getSession();		

		$session->set('captcha_sta','0');	

		

		$date_time =& JFactory::getDate();

		$date_all=$date_time->toMySQL();

		$date = explode(' ',$date_all);

		$row->date_start=$date[0];

		

        $par = &JComponentHelper::getParams( 'com_djclassifieds' );

        $exp_days = (int)$par->get('exp_days');

		

		$date_time->_date = $date_time->_date+ $exp_days*24*60*60;

		$date_exp= explode(' ',$date_time->toMySQL());

		$row->date_exp=$date_exp[0];



			$user	=& JFactory::getUser();

			$row->user_id=$user->id;				



		$query = "SELECT price,autopublish FROM #__djcf_categories WHERE id = ".$row->cat_id;

		$db =& JFactory::getDBO();		

		$db->setQuery($query);

		$cat = $db->loadObject();

		$price = $cat->price;				

		

		if($price>0 || $row->special==1){

				if($price>0){

					$row->pay_type = 'cat,';

				}

				if($row->special==1){

					$row->pay_type .= 'special,';

				}

			$row->published = 0;

			if (!$row->store())

    		{

        		echo "<script> alert('".$row->getError()."');

				window.history.go(-1); </script>\n";

        		exit ();

    		}

			$link = 'index.php?option=com_djclassifieds&view=additempaypal&id='.$row->id;

     		$msg = JText::_('Ad saved');

			$link = JRoute::_($link);			

	 		$mainframe->redirect($link, $msg);				

		}else{

			$row->payed=1;

			$redirect= '';

			

		  	 if($cat->autopublish=='0'){

				if($par->get('autopublish')=='1'){

					$row->published = 1;

					$message = JText::_('Ad added successfully'); 

				}else{

					$row->published = 0;

					$message = JText::_('Ad added successfully,waiting for publish'); 

					$redirect="index.php?option=com_djclassifieds&view=show&cid=0";					

				}

			 }elseif($cat->autopublish=='1'){

				$row->published = 1;

				$message = JText::_('Ad added successfully'); 

			 }elseif($cat->autopublish=='2'){

				$row->published = 0;

				$message = JText::_('Ad added successfully,waiting for publish');

				$redirect="index.php?option=com_djclassifieds&view=show&cid=0";

			 }			 

			

			if (!$row->store())

    		{

        		echo "<script> alert('".$row->getError()."');

				window.history.go(-1); </script>\n";

        		exit ();

    		}

			

			if($redirect==''){

				$menus	= &JSite::getMenu();

				foreach($menus->_items as $m){

					if($m->link == 'index.php?option=com_djclassifieds&view=show&cid=0'){

						$itemid=$m->id;

						break;

					}

				}

				$redirect= 'index.php?option=com_djclassifieds&view=showitem&cid='.$row->cat_id.'&id='.$row->id.'&Itemid='.$itemid;



			}

			

			if($par->get('notify_admin','0') && $par->get('notify_user_email','0')!=''){

				$mailto = $par->get('notify_user_email');

				$mailfrom = $mainframe->getCfg( 'mailfrom' );

				$config =& JFactory::getConfig();

				

				$query = "SELECT name FROM #__djcf_categories WHERE id = ".$row->cat_id." LIMIT 1";

				$db =& JFactory::getDBO();		

				$db->setQuery($query);

				$cat_name =$db->loadResult();

    

				$fromname=$config->getValue('config.sitename').' - '.JURI::base();

				$subject = JText::_('New ad in').' '.$config->getValue('config.sitename');

				$m_message = JText::_('New ad in').' '.$config->getValue('config.sitename')."\n\n";

				$m_message .= JText::_('Title').': '.$row->name."\n\n";

				$m_message .= JText::_('Category').': '.$cat_name."\n\n";

				$m_message .= JText::_('INTRO_DESCRIPTION').': '.$row->intro_desc."\n\n";

				$m_message .= JText::_('DESCRIPTION').': '.$row->description."\n\n";

				$m_message .= JText::_('From user').': '.$user->username.' id:'.$user->id."\n\n";

				

				JUtility::sendMail($mailfrom, $fromname, $mailto, $subject, $m_message);

			}

			

			$redirect = JRoute::_($redirect);



			$this->setRedirect($redirect,$message);	

		}



}



function saveEditItem(){



    global $mainframe;



	JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

    $row = & JTable::getInstance('items', 'table');

	$par = &JComponentHelper::getParams( 'com_djclassifieds' );

	

    if (!$row->bind(JRequest::get('post')))

    {



        echo "<script> alert('".$row->getError()."');



			window.history.go(-1); </script>\n";



        exit ();



    }

	

	if((int)$par->get('allow_htmltags','0')){

		$row->description = JRequest::getVar('description', '', 'post', 'string', JREQUEST_ALLOWRAW);	

	}else{

		$row->description = nl2br(JRequest::getVar('description', '', 'post', 'string'));

	}

	

	$row->contact = nl2br(JRequest::getVar('contact', '', 'post', 'string'));

   

	//removing images from folder and from database

    $images = $row->image_url;

    $usun = $_POST['usun'];

    $path_to_delete = JPATH_BASE."/components/com_djclassifieds/images/";



    for ($i = 0; $i < count($usun); $i++)

    {



        $images = str_replace($usun[$i].';', '', $images);

        //deleting the main image

        if (JFile::exists($path_to_delete.$usun[$i]))

        {

            JFile::delete($path_to_delete.$usun[$i]);

        }

        //deleting thumbnail of image

		if (JFile::exists($path_to_delete.$usun[$i].'.thb.jpg'))

        {

            JFile::delete($path_to_delete.$usun[$i].'.thb.jpg');

        }

        if (JFile::exists($path_to_delete.$usun[$i].'.th.jpg'))

        {

            JFile::delete($path_to_delete.$usun[$i].'.th.jpg');

        }

		if (JFile::exists($path_to_delete.$usun[$i].'.thm.jpg'))

        {

            JFile::delete($path_to_delete.$usun[$i].'.thm.jpg');

        }

        //deleting icon of image

        if (JFile::exists($path_to_delete.$usun[$i].'.ths.jpg'))

        {

            JFile::delete($path_to_delete.$usun[$i].'.ths.jpg');

        }

    }



 

    //add images

    $pliki = $_FILES['image'];

	

	$nw = (int)$par->get('th_width',-1);

    $nh = (int)$par->get('th_height',-1);

	$nws = $par->get('smallth_width',-1);

    $nhs = $par->get('smallth_height',-1);

	$nwm = $par->get('middleth_width',-1);

    $nhm = $par->get('middleth_height',-1);			

	$nwb = $par->get('bigth_width',-1);

    $nhb = $par->get('bigth_height',-1);		

	$img_maxsize = $par->get('img_maxsize',0);		

		if($img_maxsize>0){

			$img_maxsize = $img_maxsize*1024*1024;

		}



    for ($i = 0; $i < count($pliki['name']); $i++)

    {

        if (substr($pliki['type'][$i], 0, 5) == "image")

        {

       			if($img_maxsize>0 && $pliki['size'][$i]>$img_maxsize){

					continue;

				}

				$n_name = $row->id.'_'.$pliki['name'][$i];            	

            	$sciezka = JPATH_BASE."/components/com_djclassifieds/images/".$n_name;

				$nimg= 0;			

				while(JFile::exists($sciezka)){

					$nimg++;

        			$n_name = $row->id.'_'.$nimg.'_'.$pliki['name'][$i];            	

            		$sciezka = JPATH_BASE."/components/com_djclassifieds/images/".$n_name;

				}

				$images .= $n_name.';';

            	move_uploaded_file($pliki['tmp_name'][$i], $sciezka);

            	$this->makeimg($sciezka, $nw, $nh, 'th');

				

				$this->makeimg($sciezka, $nws, $nhs, 'ths');

				$this->makeimg($sciezka, $nwm, $nhm, 'thm');

				$this->makeimg($sciezka, $nwb, $nhb, 'thb');





        }

    }

    $row->image_url = $images;





	$menus	= &JSite::getMenu();



		foreach($menus->_items as $m){

			if($m->link == 'index.php?option=com_djclassifieds&view=show&cid=0'){

				$itemid=$m->id;

				break;

			}

		}



		$redirect= 'index.php?option=com_djclassifieds&view=showitem&cid='.$row->cat_id.'&id='.$row->id.'&Itemid='.$itemid;	





		$query = "SELECT price,autopublish FROM #__djcf_categories WHERE id = ".$row->cat_id;

		$db =& JFactory::getDBO();		

		$db->setQuery($query);

		$cat = $db->loadObject();

		$par = &JComponentHelper::getParams( 'com_djclassifieds' );

		

		$query = "SELECT cat_id, special,pay_type FROM #__djcf_items WHERE id = ".$row->id;

		$db =& JFactory::getDBO();		

		$db->setQuery($query);

		$old_row = $db->loadObject();

		

		if(($old_row->cat_id!=$row->cat_id && $cat->price>0) || ($old_row->special==0 && $row->special==1)){

				$row->pay_type = $old_row->pay_type;

				if($old_row->cat_id!=$row->cat_id && $cat->price>0){

					$row->pay_type .= 'cat,';

				}

				if($old_row->special==0 && $row->special==1){

					$row->pay_type .= 'special,';

				}

				

				$row->published = 0;

				$row->payed = 0;

				

				if (!$row->store())

    			{

	        		echo "<script> alert('".$row->getError()."');

					window.history.go(-1); </script>\n";

        			exit ();

    			}

				$link = 'index.php?option=com_djclassifieds&view=additempaypal&id='.$row->id.'&t=edit';

     			$msg = JText::_('Ad saved');

				$link = JRoute::_($link);			

	 			$mainframe->redirect($link, $msg);						

		}else if($old_row->pay_type!=''){

			$row->published = 0;

			$row->payed = 0;

			

			if (!$row->store())

    		{

	        	echo "<script> alert('".$row->getError()."');

				window.history.go(-1); </script>\n";

        		exit ();

    		}

				$link = 'index.php?option=com_djclassifieds&view=additempaypal&id='.$row->id.'&t=edit';

     			$msg = JText::_('Ad saved');

				$link = JRoute::_($link);			

	 			$mainframe->redirect($link, $msg);		

		}

		



		  	 if($cat->autopublish=='0'){

				if($par->get('autopublish')=='1'){

					$row->published = 1;

					$message = JText::_('Ad added successfully'); 

				}else{

					$row->published = 0;

					$message = JText::_('Ad added successfully,waiting for publish'); 

					$redirect="index.php?option=com_djclassifieds&view=show&cid=0";					

				}

			 }elseif($cat->autopublish=='1'){

				$row->published = 1;

				$message = JText::_('Ad added successfully'); 

			 }elseif($cat->autopublish=='2'){

				$row->published = 0;

				$message = JText::_('Ad added successfully,waiting for publish');

				$redirect="index.php?option=com_djclassifieds&view=show&cid=0";

			 }



    if (!$row->store())

    {

        echo "<script> alert('".$row->getError()."');

			window.history.go(-1); </script>\n";

        exit ();

    }

	

		$redirect = JRoute::_($redirect);		



		$this->setRedirect($redirect,$message);	

}





function ask(){

	global $mainframe, $option;

	$id= JRequest::getVar('item_id', 0, '', 'int');

	$db =& JFactory::getDBO();

	$user = & JFactory::getUser();

	if($user->id >0){

		$msg = strip_tags(JRequest::getVar('intro_desc'));

		$par = &JComponentHelper::getParams( 'com_djclassifieds' );

	

		$date_time =& JFactory::getDate();

		$date_now=$date_time->toMySQL();

	

		$date_time->_date = $date_time->_date - $par->get('ask_limit_one',5)*60;

		$date_last5 = $date_time->toMySQL();

		$date_time->_date = $date_time->_date - 55*60;

		$date_lasth = $date_time->toMySQL();



	

		$query = "SELECT COUNT(id) FROM #__djcf_itemsask a WHERE a.user_id = ".$user->id." AND a.item_id=".$id." AND a.date>'".$date_last5."'";	

		$db->setQuery($query);

		$check = $db->loadResult();

		if($check>0){

	     	$link = 'index.php?option=com_djclassifieds&view=showitem&id='.$id;

    	 	$msg = sprintf ( JText::_( 'ASK_MESSAGE_LIMIT' ), $par->get('ask_limit_one',5));

    	 	$mainframe->redirect($link, $msg);		

		}

	

		$query = "SELECT COUNT(id) FROM #__djcf_itemsask a WHERE a.user_id = ".$user->id." AND a.date>'".$date_lasth."'";	

		$db->setQuery($query);

		$check = $db->loadResult();



		if($check>$par->get('ask_limit_hour',15)){

	     	$link = 'index.php?option=com_djclassifieds&view=showitem&id='.$id;

    	 	$msg = JText::_('ASK_MESSAGE_LIMIT_HOUR');

    	 	$mainframe->redirect($link, $msg);		

		}

	

	

		$query="INSERT INTO #__djcf_itemsask (`id`, `item_id`, `user_id`, `message`, `date`)"

		  	." VALUES (NULL, '".$id."', '".$user->id."', '".$msg."', '".$date_now."')";

		$db->setQuery($query);

		$db->query();

	

	

		$query = 'SELECT i.name, u.email FROM #__djcf_items i , #__users u WHERE i.user_id = u.id AND i.id='."$id".'';

		$db->setQuery($query);

		$ob = $db->loadObject();

	

		$mailto = $ob->email;

		$mailfrom = $mainframe->getCfg( 'mailfrom' );

		$config =& JFactory::getConfig();

    

		$fromname=$config->getValue('config.sitename').' - '.JURI::base();

		$subject = sprintf ( JText::_( 'ASK_SELLER_TITLE' ), $config->getValue('config.sitename'));

	

		$message = JText::_('Users email').': '.$user->email."\n\n";

		$message .= sprintf ( JText::_( 'ASK_SELLER_MESSAGE' ), $ob->name, $msg);

		$message .= "\n\n".JText::_('From user').': '.$user->username;

		JUtility::sendMail($mailfrom, $fromname, $mailto, $subject, $message);



	     $link = 'index.php?option=com_djclassifieds&view=showitem&id='.$id;

    	 $msg = JText::_('Message send');

	}else{

		$link = 'index.php?option=com_djclassifieds&view=showitem&id='.$id;

     	$msg = JText::_('Please login');

	}

    $mainframe->redirect($link, $msg);				

}



function show_search(){	

		$se = JRequest::getVar('search', '', 'default', 'string');



		$menus	= &JSite::getMenu();



		foreach($menus->_items as $m){

			if($m->link == 'index.php?option=com_djclassifieds&view=show&cid=0'){

				$itemid=$m->id;

				break;

			}

		}



		$redirect= 'index.php?option=com_djclassifieds&view=show&cid=0&order=title&search='.$se.'&Itemid='.$itemid;		

		$redirect = JRoute::_($redirect);

		$this->setRedirect($redirect);

	}

	

	function paypal_notify(){

		$token = $_POST['transaction_subject'];

		global $mainframe, $option;

				

			$req = 'cmd=_notify-validate';			

			foreach ($_POST as $key => $value) {

				$value = urlencode(stripslashes($value));

				$req .= "&$key=$value";

			}



			// post back to PayPal system to validate

			$header .= "POST /cgi-bin/webscr HTTP/1.0\r\n";

			$header .= "Content-Type: application/x-www-form-urlencoded\r\n";

			$header .= "Content-Length: " . strlen($req) . "\r\n\r\n";

			//$fp = fsockopen ('ssl://www.sandbox.paypal.com', 443, $errno, $errstr, 30);

			$fp = fsockopen ('ssl://www.paypal.com', 443, $errno, $errstr, 30);



			// assign posted variables to local variables

			$item_name = $_POST['item_name'];

			$item_number = $_POST['item_number'];

			$payment_status = $_POST['payment_status'];

			$payment_amount = $_POST['mc_gross'];

			$payment_currency = $_POST['mc_currency'];

			$txn_id = $_POST['txn_id'];

			$receiver_email = $_POST['receiver_email'];

			$payer_email = $_POST['payer_email'];



			if (!$fp) {

				$redirect= 'index.php';				

				$message = JText::_('Paypal return error-http');	

				$this->setRedirect($redirect,$message);// HTTP ERROR

			} else {

				fputs ($fp, $header . $req);

				while (!feof($fp)) {

				$res = fgets ($fp, 1024);

				//print_r($res);echo '<br />';

			//	print_r($fp);

				//	$fil = fopen('data.txt', 'a');

				//	fwrite($fil, $res.'\n');

				//	fwrite($fil, $fp);

				//	fclose($fil);

				

				if (strcmp ($res, "VERIFIED") == 0) {



					$db =& JFactory::getDBO();

					$query = 'SELECT id FROM #__djcf_items WHERE paypal_token="'.$token.'"';

					$db->setQuery($query);

					$id = $db->loadResult();

					if($id){												

						$par = &JComponentHelper::getParams( 'com_djclassifieds' );

						JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

   				 		$row = & JTable::getInstance('items', 'table');

						$row->load($id);

						$row->payed=1;

												

						$query = "SELECT autopublish FROM #__djcf_categories WHERE id = ".$row->cat_id;

						$db =& JFactory::getDBO();		

						$db->setQuery($query);

						$ap = $db->loadResult();

						

						

					  	 if($ap=='0'){

							if($par->get('autopublish')=='1'){

								$row->published = 1;

							}else{

								$row->published = 0;

								$message = JText::_('Ad added successfully,waiting for publish'); 

								$redirect="index.php";					

							}

			 			}elseif($ap=='1'){

							$row->published = 1;							

			 			}elseif($ap=='2'){

							$row->published = 0;

							$message = JText::_('Ad added successfully,waiting for publish');

							$redirect="index.php?option=com_djclassifieds&view=show&cid=0";

			 			}

							

						if($row->published==1){

	

							$menus	= &JSite::getMenu();

							foreach($menus->_items as $m){

								if($m->link == 'index.php?option=com_djclassifieds&view=show&cid=0'){

									$itemid=$m->id;

									break;

								}

							}

			

							$redirect= 'index.php?option=com_djclassifieds&view=showitem&cid='.$row->cat_id.'&id='.$row->id.'&Itemid='.$itemid;	

							$redirect = JRoute::_($redirect);

							$message = JText::_('Announcement added successfully'); 						

						}

						

						$row->pay_type='';

						

				    	if (!$row->store()){

    			    		echo "<script> alert('".$row->getError()."');

							window.history.go(-1); </script>\n";

    			    		exit ();

    					}

			

						$this->setRedirect($redirect,$message);

			

					}else{

						$redirect= 'index.php';				

						$message = JText::_('There is no item with this id');	

						$this->setRedirect($redirect,$message);

					}

					

				}

				else if (strcmp ($res, "INVALID") == 0) {

					$redirect= 'index.php';				

					$message = JText::_('Paypal return error- invalid');	

					$this->setRedirect($redirect,$message);

				}

			}

			fclose ($fp);

		}		

			





	}

	

	function paypal(){

		$token = $_POST['transaction_subject'];

		global $mainframe, $option;



		if(JRequest::getVar('pay')=='ok'){



		$message = JText::_('Ad added successfully,waiting for publish');

		$redirect="index.php?option=com_djclassifieds&view=show&cid=0";

		$this->setRedirect($redirect,$message);

	 }else{

		$redirect= 'index.php';				

		$message = JText::_('Paypal return error-false');	

		$this->setRedirect($redirect,$message);

	  }



	}

	

	

		function deleteAd(){

		$user = & JFactory::getUser();

		global $mainframe, $option;

		$id = JRequest::getVar('id', 0, '', 'int');



		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

   		$row = & JTable::getInstance('items', 'table');

		$row->load($id);		



		if($row->user_id){

			if($row->user_id==$user->id){

				$row->delete();

				

    			$images = explode(';', $row->image_url);

    			$path_to_delete = JPATH_BASE."/components/com_djclassifieds/images/";



			    for ($i = 0; $i < count($images)-1; $i++)

    			{

	        		if (JFile::exists($path_to_delete.$images[$i])){

	            		JFile::delete($path_to_delete.$images[$i]);

	        		}

					if (JFile::exists($path_to_delete.$images[$i].'.thb.jpg')){

	            		JFile::delete($path_to_delete.$images[$i].'.thb.jpg');

	        		}

			        if (JFile::exists($path_to_delete.$images[$i].'.th.jpg')){

			            JFile::delete($path_to_delete.$images[$i].'.th.jpg');

			        }

					if (JFile::exists($path_to_delete.$images[$i].'.thm.jpg')){

			            JFile::delete($path_to_delete.$images[$i].'.thm.jpg');

			        }

			        //deleting icon of image

			        if (JFile::exists($path_to_delete.$images[$i].'.ths.jpg')){

			            JFile::delete($path_to_delete.$images[$i].'.ths.jpg');

			        }

		    	}

				

				$redirect= 'index.php?option=com_djclassifieds&view=useritems&Itemid='.$_POST['Itemid'];				

				$message = JText::_('Ad deleted');	

				

				$this->setRedirect($redirect,$message);

			}else{

				$this->setRedirect('index.php','Wrong Ad');

			}

		}else{

			$this->setRedirect('index.php');

		}

		

	}

	

	function delitem(){

		$user = & JFactory::getUser();

		global $mainframe, $option;

		$id = JRequest::getVar('id', 0, '', 'int');



		JTable::addIncludePath(JPATH_COMPONENT_ADMINISTRATOR.DS.'tables');

   		$row = & JTable::getInstance('items', 'table');

		$row->load($id);



		if($row->user_id){

			if($row->user_id==$user->id){

				$row->delete();

				$redirect= 'index.php';				

				$message = JText::_('Item deleted');	

				$this->setRedirect($redirect,$message);

			}else{

				$this->setRedirect('index.php');

			}

		}else{

			$this->setRedirect('index.php');

		}

		

	}

	

	function captcha(){

		global $mainframe, $option;



		include('views/additem/tmpl/recaptchalib.php');

		$privatekey = "6LfzhgkAAAAAAOJNzAjPz3vXlX-Bw0l-sqDgipgs";





		  $resp = recaptcha_check_answer ($privatekey,

                                  $_SERVER["REMOTE_ADDR"],

                                  $_POST["recaptcha_challenge_field"],

                                  $_POST["recaptcha_response_field"]);

		  if ($resp->is_valid) {

			$session = &JFactory::getSession();		

			$session->set('captcha_sta','1');

			JRequest::setVar('view','additem');

			parent::display();			

		  }else {

			JRequest::setVar('view','additem');

			parent::display();

		  }

	}



}