Current File : /home/k/a/r/karenpetzb/www/items/category/controllers.tar
StatisticController.php000060400000022673150713030120011266 0ustar00<?php

class Backoffice_StatisticController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Logs";
		$this->isConnectedWithRole('isStats');  
	}
	function indexAction()
	{
		$this->_forward('/');

	}

	function logdefaultcleanAction() {
		$logDefault = new LogDefault();
		$logDefault->delete("1=1");
		$this->_forward('logdefault');
	}
	function logadmincleanAction() {
		$logAdmin = new LogAdmin();
		$logAdmin->delete("1=1");
		$this->_forward('logadmin');
	}
	function statsAction() {
		try {
			$this->view->titlePage = "Logs des administrateurs";
			$this->view->currentMenu = "Stats";

			$command = new Command();
			$this->view->statsBestSellYear = $command->statsBestSellForYear();
			$this->view->statsBestSellMonth = $command->statsBestSellForMonth();
			$this->view->statsNbProductYear = $command->statsNbProductYear();
			$this->view->statsNbProductMonth = $command->statsNbProductMonth();
			$this->view->statsCategoryCmdYear = $command->statsCategoryCmdYear();
			$this->view->statsCategoryCmdMonth = $command->statsCategoryCmdMonth();
			
			$statsSearch = new StatsSearch();
			$this->view->statsKeyWordYear = $statsSearch->statsKeyWordYear();
			
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
			
	}
	
	function logadminAction() {
		try {
			$this->view->titlePage = "Logs des administrateurs";
			$this->view->currentMenu = "Logs";
			$adminNamespace = $this->getSession();

			//Gestion des tris
			$table = 'DATE_LOG';
			$tri = 'DESC';

			if ($this->_request->getParam('col'))
			{
				$adminNamespace->triAdminCol_logadmin = $this->_request->getParam('col');
				($adminNamespace->triAdminSens_logadmin == 'ASC') ? $adminNamespace->triAdminSens_logadmin = 'DESC' : $adminNamespace->triAdminSens_logadmin = 'ASC';
			}
			if (isset($adminNamespace->triAdminCol_logadmin)) {
				$table = $adminNamespace->triAdminCol_logadmin;
				$tri = $adminNamespace->triAdminSens_logadmin;
			}
			
			if (!isset($adminNamespace->triAdminNumber_logadmin)) {
				$adminNamespace->triAdminNumber_logadmin = 100;
			}
			if ($this->_request->getParam('nb')) {
				$adminNamespace->triAdminNumber_logadmin = $this->_request->getParam('nb');
			}
			$paginationNumber = $adminNamespace->triAdminNumber_logadmin;
			
			$logAdmin = new LogAdmin();
			$listlogs = $logAdmin->select()->order($table.' '.$tri);
			
			$this->setPaginator($listlogs, $this->_getParam('page',1), $paginationNumber);
		
		
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
			
	}

	function logdefaultAction() {
		try {
			$this->view->titlePage = "Logs des utilisateurs";
			$this->view->currentMenu = "Logs";
			$adminNamespace = $this->getSession();
				
			//Gestion des tris
			$table = 'DATE_LOG';
			$tri = 'DESC';

			if ($this->_request->getParam('col'))
			{
				$adminNamespace->triAdminCol_logdefault = $this->_request->getParam('col');
				($adminNamespace->triAdminSens_logdefault == 'ASC') ? $adminNamespace->triAdminSens_logdefault = 'DESC' : $adminNamespace->triAdminSens_logdefault = 'ASC';
			}
			if (isset($adminNamespace->triAdminCol_logdefault)) {
				$table = $adminNamespace->triAdminCol_logdefault;
				$tri = $adminNamespace->triAdminSens_logdefault;
			}
				 
			if (!isset($adminNamespace->triAdminNumber_logdefault)) {
				$adminNamespace->triAdminNumber_logdefault = 100;
			}
			if ($this->_request->getParam('nb')) {
				$adminNamespace->triAdminNumber_logdefault = $this->_request->getParam('nb');
			}
			$paginationNumber = $adminNamespace->triAdminNumber_logdefault;
			
			$logDefault = new LogDefault();
			$listlogs = $logDefault->select()->order($table.' '.$tri);
			
			$this->setPaginator($listlogs, $this->_getParam('page',1), $paginationNumber);
		 
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
			
	}
	 
	function searchkeyAction() {
	try {
			$this->view->titlePage = "Liste des recherches";
			$adminNamespace = $this->getSession();
				
			//Gestion des tris
			$table = 'DATESTART';
			$tri = 'DESC';

			if ($this->_request->getParam('col'))
			{
				$adminNamespace->triAdminCol_logsearch = $this->_request->getParam('col');
				($adminNamespace->triAdminSens_logsearch == 'ASC') ? $adminNamespace->triAdminSens_logsearch = 'DESC' : $adminNamespace->triAdminSens_logsearch = 'ASC';
			}
			if (isset($adminNamespace->triAdminCol_logsearch)) {
				$table = $adminNamespace->triAdminCol_logsearch;
				$tri = $adminNamespace->triAdminSens_logsearch;
			}
			
			if (!isset($adminNamespace->triAdminNumber_logsearch)) {
				$adminNamespace->triAdminNumber_logsearch = 100;
			}
			
			if ($this->_request->getParam('nb')) {
				$adminNamespace->triAdminNumber_logsearch = $this->_request->getParam('nb');
			}
			 
			$paginationNumber = $adminNamespace->triAdminNumber_logsearch;
			
			$statsSearch = new StatsSearch();
			$listlogs = $statsSearch->select()->order($table.' '.$tri);
			 
			$this->setPaginator($listlogs, $this->_getParam('page',1), $paginationNumber);
		  
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
	}

	function keymapAction() {
	try {
			$this->view->titlePage = "Carte des mots cl�s";
			$adminNamespace = $this->getSession();
			
			$keymap = new KeyMap();
			$this->view->listMapCat = $keymap->getAllByCAT();
			$this->view->listMapBrend = $keymap->getAllByBREND();
			
			$categorie = new Category();
			$select = $categorie->select()->order('NOM ASC');
			$this->view->listCat = $categorie->fetchAll($select);
			
			$brend = new SupplierBrend();
			$select = $brend->select()->order('BREND ASC');
			$this->view->listBrend = $brend->fetchAll($select);
			
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
	}
	
	function keymapcateditAction() {
		try {
			if ($this->_request->isPost()) {
					
				$params = $this->_request->getPost();
				$catId = (int) $params['catId'];
				$color = 'DEFAULT';
				if (!empty($params['colorKey'])) {
					$color = $params['colorKey'];
				}
								
				if ($catId > 0) {
					$keymap = new KeyMap();
					$key = $keymap->getKeyByCatID($catId);
					if (isset($key) && $key != null && !empty($key['CAT_NOM'])) {
						$data = array (
				 		'SIZE' => $params['sizeKey'],
				 		'POSITION' => $params['positionKey'],
						'TYPE' => 'CAT',
						'COLOR' => $color
						);
						$keymap->update($data, 'ID = '.$key['ID']);
					} else {
						$data = array (
						'CATID' => $catId,
				 		'SIZE' => $params['sizeKey'],
				 		'POSITION' => $params['positionKey'],
						'TYPE' => 'CAT',
						'COLOR' => $color
						);
						$keymap->insert($data);
					}
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
		$this->_forward('/keymap');
	}
	
function keymapbrendeditAction() {
	try {
			if ($this->_request->isPost()) {
						
				$params = $this->_request->getPost();
				$brendId = (int) $params['brendId'];
				$color = 'DEFAULT';
				if (!empty($params['colorKey'])) {
					$color = $params['colorKey'];
				}
				
				if ($brendId > 0) {
					$keymap = new KeyMap();
					$key = $keymap->getKeyByBrendID($brendId);
					
					if (isset($key) && $key != null && !empty($key['BREND_NOM'])) {
						
						$data = array (
				 		'SIZE' => $params['sizeKey'],
				 		'POSITION' => $params['positionKey'],
						'TYPE' => 'BREND',
						'COLOR' => $color
						);
						$keymap->update($data, 'ID = '.$key['ID']);
					} else {
						$data = array (
						'BRENDID' => $brendId,
				 		'SIZE' => $params['sizeKey'],
				 		'POSITION' => $params['positionKey'],
						'TYPE' => 'BREND',
						'COLOR' => $color
						);
						$keymap->insert($data);
					}
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
		$this->_forward('/keymap');
	}
	

function keymapshowAction()
	{
		if ($this->_request->isPost()) {
				
			$params = $this->_request->getPost();
			
			if ($params['keyType'] == 'CAT') {
				$id = $params['catIdShow'];
			} else {
				$id = $params['brendIdShow'];
			}
			$data = array('isSHOW' => $params['showvalue']); 
			
			try {
				if ( $id > 0) {
					$keymap = new KeyMap();
					if ($params['keyType'] == 'CAT') {
						$keymap->update($data, 'CATID = '.$id);
					} else {
						$keymap->update($data, 'BRENDID = '.$id);
					}
				}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
				$this->_forward('/keymap');
			}
		}
		$this->_forward('/keymap');
	}
	
	function clickstatsipAction() {
		try {
			$this->view->titlePage = "Statistiques des clicks";
			
			$clickStats = new ClickStats();
			$this->view->listSource = $clickStats->getSourceStats();
			
			$listIp = $clickStats->getIPStats();
			
			$this->view->listIp = $listIp;
			
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
	}
	
	function clickstatsproductAction() {
		try {
			$this->view->titlePage = "Statistiques des clicks";
			
			$clickStats = new ClickStats();
			$this->view->listClick = $clickStats->getProductDetail();
			
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = $e->getMessage();
		}
	}
}

	
?>CommandController.php000060400000036473150713030120010700 0ustar00<?php
class Backoffice_CommandController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Command";
		$this->isConnectedWithRole('isCommand');  
	}
	function indexAction()
	{
		$this->_forward('/listcommand');

	}
	function searchAction()
	{
		try {
			$this->view->titlePage = "Rechercher une commande";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$startSearch = false;

			$isCheckedValidating = false;
			$searchValue = "";
			if ($this->_request->isPost()) {
				$post = $this->_request->getPost();
				$filter = new Zend_Filter();
				$filter	->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringTrim());
				$searchValue = $filter->filter($post['searchValue']);
				if (isset($post['searchType'])) {
					$isCheckedValidating = true;
				}
				$startSearch = true;
			} 

			//Gestion des tris
			$titlePage = "";
			$listcommand = array();
			if ($startSearch) {
                $adminNamespace = $this->getSession();                
                $adminNamespace->cmdSearchValue = $searchValue;
                $adminNamespace->cmdSearchValidating = $isCheckedValidating;
                
				//Appel model pour listing				
				$command = new Command();
				$titlePage .= " : ".$searchValue;
				$listcommand = $command->findCommandsByMultiSearch($isCheckedValidating, $searchValue);
			}
					
			$this->view->titlePage .= $titlePage; 
			$this->view->listcommand = $listcommand;
			$this->view->searchType = $isCheckedValidating;
			$this->view->searchValue = $searchValue;
		} catch (Zend_Exception $e) { $this->errorHandler($e); $this->view->messageError = $e->getMessage(); }
	}

	function listAction()
	{
		$this->view->titlePage = "Gestion des commandes";
		$adminNamespace = $this->getSession();
			
		//Gestion des tris
		$table = 'STATUT';
		$tri = 'ASC';

		if ($this->_request->getParam('col'))
		{
			$adminNamespace->triCmdCol = $this->_request->getParam('col');
			($adminNamespace->triCmdSens == 'ASC') ? $adminNamespace->triCmdSens = 'DESC' : $adminNamespace->triCmdSens = 'ASC';
		}
		if (isset($adminNamespace->triCmdCol)) {
			$table = $adminNamespace->triCmdCol;
			$tri = $adminNamespace->triCmdSens;
		}
			
		//Appel model pour listing
		$command = new Command();
		$select = $command->select()->where('STATUT <> 0 AND isARCHIVE = 1')->order($table.' '.$tri);
			
		$this->view->listcommand = $command->fetchAll($select);
			
	}

	function listcommandAction()
	{
		$this->view->titlePage = "Gestion des commandes";
		$adminNamespace = $this->getSession();
			
		//Gestion des tris
		$table = 'STATUT';
		$tri = 'ASC';

		if ($this->_request->getParam('col'))
		{
			$adminNamespace->triCmdCol = $this->_request->getParam('col');
			($adminNamespace->triCmdSens == 'ASC') ? $adminNamespace->triCmdSens = 'DESC' : $adminNamespace->triCmdSens = 'ASC';
		}
		if (isset($adminNamespace->triCmdCol)) {
			$table = $adminNamespace->triCmdCol;
			$tri = $adminNamespace->triCmdSens;
		}
			
		//Appel model pour listing
		$command = new Command();
		$select = $command->select()->where('isARCHIVE = 1 AND STATUT IN (1, 2, 3, 4)')->order($table.' '.$tri);
			
		$this->view->listcommand = $command->fetchAll($select);
			
	}

	function listdevisAction()
	{
		$this->view->titlePage = "Gestion des devis";
		$adminNamespace = $this->getSession();
			
		//Gestion des tris
		$table = 'STATUT';
		$tri = 'ASC';

		if ($this->_request->getParam('col'))
		{
			$adminNamespace->triCmdCol = $this->_request->getParam('col');
			($adminNamespace->triCmdSens == 'ASC') ? $adminNamespace->triCmdSens = 'DESC' : $adminNamespace->triCmdSens = 'ASC';
		}
		if (isset($adminNamespace->triCmdCol)) {
			$table = $adminNamespace->triCmdCol;
			$tri = $adminNamespace->triCmdSens;
		}
			
		//Appel model pour listing
		$command = new Command();
		$select = $command->select()->where('isARCHIVE = 1 AND STATUT IN (10, 11)')->order($table.' '.$tri);
			
		$this->view->listcommand = $command->fetchAll($select);
			
	}

	//Same as UserController, module default
	private function computeFactureTVA($facture, $paysLivraison) {
		$fact = new Facture();
		$fact->computeFactureTVA($facture, $paysLivraison);
		return $facture;
	}

	function editAction() {
try {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		$command = new Command();
		if($this->getRequest()->isPost()) {
			$id = (int)$this->_request->getPost('idcmd');
			$statut = (int)$this->_request->getPost('statut');
			$delivery_trackinglink = $this->_request->getPost('delivery_trackinglink');
			$delivery_trackingnumber = $this->_request->getPost('delivery_trackingnumber');
                        
			if ($id > 0 && $statut>0) {
				try {
					if ($statut == 3 || $statut == 11) {
						$date = new Zend_Date();
						$data = array ( 'STATUT' => $statut, 'DATEEND' => $date->toString('YYYY-MM-dd HH:mm:ss') );

					} else {
						$data = array ( 'STATUT' => $statut, 'DATEEND' => '0000-00-00 00:00:00');
					}
                    if (isset($delivery_trackinglink) && !empty($delivery_trackinglink) &&
                        isset($delivery_trackingnumber) && !empty($delivery_trackingnumber)) {
                        $data['DELIVERY_TRACKINGLINK'] = $delivery_trackinglink;
                        $data['DELIVERY_TRACKINGNUMBER'] = $delivery_trackingnumber;
                    }
                    
					$command->update($data, 'ID = '.$id);
					$this->view->messageSuccess = "Le statut a �t� modifi�";
					$this->log("Le statut a �t� modifi� : ".$id,'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}

		if ($this->getRequest()->getParam('id') && (int)$this->getRequest()->getParam('id')>0) {
			$id = (int)$this->getRequest()->getParam('id');
		}
		$isExist = $command->fetchRow("ID = ".$id);
		if ($isExist) {			 
        
			$myCommand = $command->getCommandAsFacture($id);
            $this->view->facture = $myCommand;
			$titlePage = "Modifier une commande";

			switch ($myCommand['STATUT']) {
				case 10 :
					$titlePage = "Modifier un devis";
					break;
				case 11 :
					$titlePage = "Modifier un devis";
					break;
			}

			$this->view->titlePage = $titlePage;
		}        
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	} 
    
	function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$command = new Command();
					$commandProduct = new CommandProduct();

					$commandProduct->delete('IDCOMMAND = '.$id);

					$command->delete('ID = '.$id);

					$this->view->messageSuccess = "La commande a �t� supprim�e ";
					$this->log("La commande a �t� supprim�e",'info');
                    
                    $adminNamespace = $this->getSession();    
                    if (isset($adminNamespace->cmdSearchValue) && isset($adminNamespace->cmdSearchValidating)) {
                        $isCheckedValidating = $adminNamespace->cmdSearchValidating;
                        $searchValue = $adminNamespace->cmdSearchValue;
                        
                        //Gestion des tris 
                        $listcommand = array(); 
                        //Appel model pour listing			 
                        $titlePage = "Rechercher une commande : ".$searchValue;
                        $listcommand = $command->findCommandsByMultiSearch($isCheckedValidating, $searchValue);	         
                        
                        $this->view->titlePage .= $titlePage; 
                        $this->view->listcommand = $listcommand;
                        $this->view->searchType = $isCheckedValidating;
                        $this->view->searchValue = $searchValue;
                    } 
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
        $this->render('search');

	}
	
	function ajaxdelcommandAction() { 
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					
					$command = new Command();
					$commandProduct = new CommandProduct(); 
					$commandProduct->delete('IDCOMMAND = '.$id); 
					$command->delete('ID = '.$id); 
					$this->view->messageSuccess = "SUCCESS";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "ERROR";
				}
			}
		}  
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxmessage');
	}

	function delcommandAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$command = new Command();
					$commandProduct = new CommandProduct();

					$commandProduct->delete('IDCOMMAND = '.$id);

					$command->delete('ID = '.$id);

					$this->view->messageSuccess = "La commande a �t� supprim�e ";

					$this->log("La commande a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/listcommand');

	}

	function deldevisAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$command = new Command();
					$commandProduct = new CommandProduct();

					$commandProduct->delete('IDCOMMAND = '.$id);

					$command->delete('ID = '.$id);

					$this->view->messageSuccess = "Le devis a �t� supprim� ";

					$this->log("Le devis a �t� supprim�",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/listdevis');

	}

	function archiveAction() {
		if($this->getRequest()->isPost()) {
			$checkBoxValues = $this->_request->getPost('checkBoxValues');
			$checkBoxValues = substr($checkBoxValues, 0, -1);
			try {
				if (!empty($checkBoxValues)) {
					$command = new Command();

					$data = array ( 'isARCHIVE' => 0);
					$command->update($data, 'ID in ('.$checkBoxValues.')');

					$this->log("Les commandes ont �t� archiv�es "+$checkBoxValues,'info');
				}
			} catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
			}
		}
		$this->_forward('/listcommand');
	}
	function archivecommandAction() {
		if($this->getRequest()->isPost()) {
			$checkBoxValues = $this->_request->getPost('checkBoxValues');
			$checkBoxValues = substr($checkBoxValues, 0, -1);
			try {
				if (!empty($checkBoxValues)) {
					$command = new Command();

					$data = array ( 'isARCHIVE' => 0);
					$command->update($data, 'ID in ('.$checkBoxValues.')');

					$this->log("Les commandes ont �t� archiv�es "+$checkBoxValues,'info');
				}
			} catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
			}
		}
		$this->_forward('/listcommand');
	}
	function archivedevisAction() {
		if($this->getRequest()->isPost()) {
			$checkBoxValues = $this->_request->getPost('checkBoxValues');
			$checkBoxValues = substr($checkBoxValues, 0, -1);
			try {
				if (!empty($checkBoxValues)) {
					$command = new Command();

					$data = array ( 'isARCHIVE' => 0);
					$command->update($data, 'ID in ('.$checkBoxValues.')');

					$this->log("Les devis ont �t� archiv�es "+$checkBoxValues,'info');
				}
			} catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
			}
		}
		$this->_forward('/listdevis');
	}
    
	function deliverymailAction() {
        $id = 0;
		if ($this->getRequest()->getParam('id') && (int)$this->getRequest()->getParam('id')>0) {
			$id = (int)$this->getRequest()->getParam('id');
		}

        if ($id > 0) {
            $command = new Command();
            $isExist = $command->fetchRow("ID = ".$id);
            if ($isExist) {			
                $facture = $command->getCommandAsFacture($id);
                $this->view->facture =$facture;     
                
                if (isset($facture['DELIVERY_TRACKINGLINK']) && !empty($facture['DELIVERY_TRACKINGLINK']) &&
                    isset($facture['DELIVERY_TRACKINGNUMBER']) && !empty($facture['DELIVERY_TRACKINGNUMBER'])) {
                    
                    try {
                        $view = new Zend_View();
                        $view->addScriptPath('../application/modules/backoffice/views/scripts/command/');
                        $view->assign("facture",$facture);
                        $body = $view->render("facture_deliverytrack.phtml");
                        $from =  $this->serviceClient_Mail;
                        $objet = "Votre commande : ".$facture['REFERENCE'];
                        $to = $facture['USER_EMAIL'];

                        $mail = new Zend_Mail();
                        $mail->setBodyHtml($body);
                        $mail->setFrom($from, $this->siteName);
                        $mail->addTo($to);
                        $mail->setSubject($objet);
                        $mail->send();
					    $this->view->messageSuccess = "L'email de suivi de livraison a �t� envoy� a : ".$to;
                        $this->log("L'email de suivi de livraison a �t� envoy� a : ".$to,'info');
                    }
                    catch (Zend_Exception $e) {
                        $this->log($e->getMessage(),'err');
                    }
                } else {
					$this->view->messageError = "Vous devez valider l'ajout du lien de suivi de livraison";
                }
            }
        } 
        $this->view->titlePage = "Modifier une commande";
        $this->render("edit");
	}
    
    
	function traitementmailAction() {
        $id = 0;
		if ($this->getRequest()->getParam('id') && (int)$this->getRequest()->getParam('id')>0) {
			$id = (int)$this->getRequest()->getParam('id');
		}

        if ($id > 0) {
            $command = new Command();
            $isExist = $command->fetchRow("ID = ".$id);
            if ($isExist) {			
                $facture = $command->getCommandAsFacture($id);
                $this->view->facture =$facture;     
                 
                try {
                    $view = new Zend_View();
                    $view->addScriptPath('../application/modules/backoffice/views/scripts/command/');
                    $view->assign("facture",$facture);
                    $body = $view->render("facture_traitementinprogress.phtml");
                    $from =  $this->serviceClient_Mail;
                    $objet = "Votre commande : ".$facture['REFERENCE'];
                    $to = $facture['USER_EMAIL'];

                    $mail = new Zend_Mail();
                    $mail->setBodyHtml($body);
                    $mail->setFrom($from, $this->siteName);
                    $mail->addTo($to);
                    $mail->setSubject($objet);
                    $mail->send();
					$this->view->messageSuccess = "L'email de la commande en cours de traitement a �t� envoy� a : ".$to;
                    $this->log("L'email de la commande en cours de traitement a �t� envoy� a : ".$to,'info');
                }
                catch (Zend_Exception $e) {
                    $this->log($e->getMessage(),'err');
                } 
            }
        } 
        $this->view->titlePage = "Modifier une commande";
        $this->render("edit");
	}
}
?>ProductController.php000060400000264177150713030120010746 0ustar00<?php
class Backoffice_ProductController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Product";

		$this->isConnectedWithRole('isProduct'); 
	}
	public function indexAction()
	{
		$this->_forward('/list');

	}
    
    private function indexproductById($id) {
       try {    
			if ($id > 0) {
                try
                {      
                    if (empty($this->FeatureElasticSearchWsdl) || empty($this->FeatureElasticSearchUsername) || empty($this->FeatureElasticSearchKey)) {
		                return ;
                    }
                    $soapClient = $this->getSoapClient($this->FeatureElasticSearchWsdl);
                    $request = $this->getSoapHeader($this->FeatureElasticSearchUsername, $this->FeatureElasticSearchKey);
                    $request->ProductId = $id;
                
                    $parameters = new stdClass();
                    $parameters->request = $request;
                    $soapClient->PushProduct($parameters);
                    $soapClient = null; 
                }
                catch (SoapFault $fault)
                {
					$this->log('SOAP : indexproductById : '.$fault->faultcode.' '.$fault->faultstring,'err'); 
                }   
            }
		}
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err'); 
		}  
    }
    
    public function indexproductAction() {
       try {    
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
                $soapClient = $this->getSoapClient($this->FeatureElasticSearchWsdl);
                $result = new stdClass();
                try
                {     
                    $request = $this->getSoapHeader($this->FeatureElasticSearchUsername, $this->FeatureElasticSearchKey);
                    $request->ProductId = $id;
                
                    $parameters = new stdClass();
                    $parameters->request = $request;
                    $result = $soapClient->PushProduct($parameters);
                }
                catch (SoapFault $fault)
                {
					$this->log('SOAP : indexProductAction : '.$fault->faultcode.' '.$fault->faultstring,'err'); 
                }
                $soapClient = null;    
            }
		}
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err'); 
		} 
		$this->_forward('/edit');
    }
	 
	public function uploadpicsAction() {
		if(!empty($_FILES['file']) && !empty($_FILES['file']['name'])) {
			$nomOrigine = $_FILES['file']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpeg", "jpg", "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				$repertoireDestination = 'items/product/'.$this->_request->getParam('idcat').'/';
				$this->checkDirectoryExist($repertoireDestination);
				
				/*$date = new Zend_Date();					
				$nomDestination = $date->toString('dd-MM-YYYY_HH-mm-ss').".".$extensionFichier;*/
                
				$nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
                $fileoriginal = $repertoireDestination.$nomDestination;
                
				$adminNamespace = $this->getSession();
				if (move_uploaded_file($_FILES["file"]["tmp_name"],$fileoriginal)) {
					try {
						$picture = new Picture();
						$data = array (
					 		'URL' => $fileoriginal,
					 		'IDPRODUCT' => $this->_request->getParam('id'),
							'POSITION' => $adminNamespace->imgPosDefault
						);
						$picture->insert($data);

						$messageSuccess = "L'image a �t� ajout�e";
                        
                        //Resize picture
                        $info = getimagesize($fileoriginal) ;
                        list($width_old, $height_old) = $info;
                        $maxwidth = $this->FeaturePictureResizeWidth;
                        $maxheight = $this->FeaturePictureResizeHeight;
                            
                        if ($width_old > $maxwidth || $height_old > $maxheight) {     
                            Utils_Tool::smart_resize_image($fileoriginal , null, $maxwidth , $maxheight , true , $fileoriginal , true , false ,50 );
                            $messageSuccess .= " et redimensionn�e.";
                        }  
                           
                        $this->view->messageSuccess = $messageSuccess; 
					} catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		}
		$this->_forward('/edit');
	}

	public function editpictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$picture = new Picture();
				for ($i=0; $i<$params['nbrImg']; $i++) {
					$data = array (
					 		'POSITION' => $params['position'.$i],
					 		'STRING1' => $params['string1_'.$i],
					 		'STRING2' => $params['string2_'.$i]
					);
					$picture->update($data,'ID = '.$params['id'.$i]);
				}
				$this->view->messageSuccess = "Les images ont �t� modifi�es";

			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}
	public function setpictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$picture = new Picture();
				$adminNamespace = $this->getSession();
				$data = array (
					 		'URL' => $params['picture'],
					 		'IDPRODUCT' => $this->_request->getParam('id'),
							'POSITION' => $adminNamespace->imgPosDefault,
					 		'STRING1' => '',
					 		'STRING2' => ''
							
					 		);
					 		$picture->insert($data);
					 		$this->view->messageSuccess = "Les images ont �t� modifi�es";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}
	public function delpictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('pic')) {
			$id = (int)$this->_request->getParam('pic');
			if ($id > 0) {
				try {
					$picture = new Picture();
					$picture->delete('ID = '.$id);

					$this->view->messageSuccess = "L'image a �t� supprim�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/edit');

	}
	public function erasepictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$product = new Product();
				$sql = "
						SELECT p.NOM NOM, p.ID ID 
						FROM product AS p
						LEFT JOIN picture AS pic ON pic.IDPRODUCT = p.ID
						WHERE pic.URL = '".$params['picture']."' 
						AND p.ID <> ".$params['id'];
				$isExistProduct = $product->getAdapter()->fetchRow($sql);

				$pic = new Picture();
				if (!$isExistProduct) {
					unlink($params['picture']);
					$this->view->messageSuccess = "L'image a �t� supprim�e definitivement";
				} else {
					if ($isExistProduct['ID'] == $params['id']) {
						unlink($params['picture']);
						$pic->delete('URL LIKE ?',$params['picture']);
						$this->view->messageSuccess = "L'image a �t� supprim�e definitivement";
					} else {
						$this->view->messageError = "L'image est utilis�e par : ".$isExistProduct['NOM'];
					}
				}

			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}
	public function searchAction()
	{
		$this->view->titlePage = "Recherche avanc�e des produits";

		$supplierBrend = new SupplierBrend();
		$this->view->listbrend = $supplierBrend->fetchAll($supplierBrend->select()->order('BREND ASC'));

		$adminNamespace = $this->getSession();
			
		$option = new Option();
		$this->view->listoption = $option->fetchAll();
		$this->view->listSearch = array();
		if ($this->_request->isPost() || isset($adminNamespace->searchCategory)) {

			$params = $this->_request->getParams();

			$filter = new Zend_Filter_StringTrim();

			$nomtemp = $filter->filter($params['search']);

			if (empty($nomtemp)) { $nomtemp = '%'; } else { $nomtemp = '%'.$nomtemp.'%'; }
			if (!empty($params['prixMin']) && !empty($params['prixMax'])) { $params['prix'] = 'BETWEEN '.(float)$params['prixMin'].' AND '.(float)$params['prixMax'] ; }
			
			$product = new Product();
			$select = "
				SELECT DISTINCT p.NOM NOM, p.DESCRIPTIONSHORT DESCRIPTIONSHORT, p.PRIX PRIX, p.ID ID, p.isACTIVE isACTIVE, p.isPROMO isPROMO
				FROM product AS p
				LEFT JOIN productchild AS pc ON pc.IDPRODUCT = p.ID
				LEFT JOIN productchild_option AS pco ON pco.IDPRODUCTCHILD = pc.ID
				LEFT JOIN product_option AS po ON po.IDPRODUCT = p.ID ";
			if (!empty($params['image']) && $params['image']==0) { $select .= "LEFT JOIN picture AS pic ON pic.IDPRODUCT = p.ID "; }
			
			$select .= "WHERE (p.NOM LIKE '".$nomtemp."' OR pc.REFERENCE LIKE '".$nomtemp."' OR pc.DESIGNATION LIKE '".$nomtemp."') ";
			// Requete trop longue avec : OR p.DESCRIPTIONSHORT LIKE '".$nomtemp."' OR p.DESCRIPTIONTECH LIKE '".$nomtemp."' OR p.DESCRIPTIONLONG LIKE '".$nomtemp."' OR p.DESCRIPTIONNORME LIKE '".$nomtemp."'
		
			if (!empty($params['prixMin']) && !empty($params['prixMax'])) { $select .= "AND (pc.PRIX >= ".$params['prixMin']." AND p.PRIX <= ".$params['prixMax'].") "; }
			if (!empty($params['prixMin']) && empty($params['prixMax'])) { $select .= "AND pc.PRIX >= ".$params['prixMin']." "; }
			if (empty($params['prixMin']) && !empty($params['prixMax'])) { $select .= "AND pc.PRIX <= ".$params['prixMax']." "; }			
			if (!empty($params['image']) && $params['image']==0) { $select .= "AND pic.POSITION = 1 "; }
			if (!empty($params['image']) && $params['image']==1) { $select .= "AND NOT EXISTS ( SELECT * FROM picture pic WHERE pic.IDPRODUCT = p.ID AND pic.POSITION = 1) "; }			
			if (!empty($params['idcategorySearch']) && $params['idcategorySearch']!='All') { $select .= "AND p.IDCATEGORY = ".$params['idcategorySearch'].' '; }
			if (!empty($params['active']) && $params['active']!=2) { $select .= "AND p.isACTIVE LIKE '".$params['active']."' "; }
			if (!empty($params['activePromo']) && $params['activePromo']!=2) { $select .= "AND p.isPROMO LIKE '".$params['activePromo']."' "; }
			if (!empty($params['idbrend']) && $params['idbrend']!='All') { $select .= "AND p.IDBREND = ".$params['idbrend']." "; }
			if (!empty($params['etatstock']) && $params['etatstock']!=3) { $select .= "AND pc.ETATSTOCK LIKE '".$params['etatstock']."' "; }
			if (!empty($params['optionId']) && $params['optionId']!='All') { $select .= "AND pco.IDOPTION LIKE '".$params['optionId']."' "; }
			if (!empty($params['optionValue'])) { $select .= "AND pco.VALUE LIKE '".$params['optionValue']."' "; }

			$select .= "ORDER BY NOM ASC";
			
			try {
				$picture = new Picture();
				$sql = $picture->fetchAll('POSITION = 1');
				$listpics = array();
				foreach ($sql as $row) {
					$listpics[$row['IDPRODUCT']] = $row['URL'];
				}
				$this->view->listproductpicture = $listpics;
					
				$listTemp = $product->getAdapter()->fetchAll($select);
				$this->view->listSearch = $listTemp;
				if ($nomtemp == '%') {
					$nomtemp = '';
				}
				$params['search'] = $filter->filter($params['search']);
				if (!empty($params['search']) && empty($params['idcategorySearch'])) {
					$params = array (
				 		'search' => $params['search'],
				 		'prixMin' => '',
				 		'prixMax' => '',
				 		'active' => '2',
				 		'image' => '2',
				 		'activePromo' => '2',
				 		'idbrend' => 'All',
				 		'etatstock' => '3',
				 		'optionId' => 'All',
				 		'optionValue' => '',
				 		'idcategorySearch' => 'All'
				 		);	
				}
				
				$this->view->populateForm = $params;

				$this->view->messageSuccess = count($listTemp).' Resultats';
				$this->view->messageError = "";

			} catch (Exception $e) {
				$this->log($e->getMessage(),'err');
				$this->view->messageSuccess = "";
				$this->view->messageError = $e->getMessage().' <br><br>'.$select;
			}
		} else {

			$params = array (
			 		'search' => '',
			 		'prixMin' => '',
			 		'prixMax' => '',
			 		'active' => '2',
			 		'image' => '2',
			 		'activePromo' => '2',
			 		'idbrend' => 'All',
			 		'etatstock' => '3',
			 		'optionId' => 'All',
			 		'optionValue' => '',
			 		'idcategorySearch' => 'All'
			 		);
			 		$this->view->populateForm = $params ;
		}
	}

	public function listAction()
	{
		$this->view->titlePage = "Rechercher des produits";
		$adminNamespace = $this->getSession();
			
		//Gestion des tris
		$table = 'NOM';
		$tri = 'ASC';
		$this->view->searchCategory = 0;
		$this->view->listproducts = array();
		if ($this->_request->isPost() || isset($adminNamespace->searchCategory)) {
			if ($this->_request->getParam('categorySearch') != null) {
				$adminNamespace->searchCategory = $this->_request->getParam('categorySearch');
				
				$adminNamespace->searchCategoryActive = "1";
				if ($this->_request->getParam('isActive') != null) {
					$adminNamespace->searchCategoryActive = "0";
				}
			}
			$isActive = $adminNamespace->searchCategoryActive;
			$id = $adminNamespace->searchCategory;
			$this->view->searchCategory = $id;
			$this->view->searchCategoryActive = $adminNamespace->searchCategoryActive;

			//Appel model pour listing

			$category = new Category();
			$select = "
				SELECT c0.ID ID0, c1.ID ID1, c2.ID ID2, c3.ID ID3, c4.ID ID4, c5.ID ID5, 
						c6.ID ID6, c7.ID ID7, c8.ID ID8, c9.ID ID9, c10.ID ID10
				FROM category AS c0
				LEFT JOIN category AS c1 ON c1.IDPARENT = c0.ID
				LEFT JOIN category AS c2 ON c2.IDPARENT = c1.ID
				LEFT JOIN category AS c3 ON c3.IDPARENT = c2.ID 
				LEFT JOIN category AS c4 ON c4.IDPARENT = c3.ID 
				LEFT JOIN category AS c5 ON c5.IDPARENT = c4.ID 
				LEFT JOIN category AS c6 ON c6.IDPARENT = c5.ID 
				LEFT JOIN category AS c7 ON c7.IDPARENT = c6.ID 
				LEFT JOIN category AS c8 ON c8.IDPARENT = c7.ID 
				LEFT JOIN category AS c9 ON c9.IDPARENT = c8.ID 
				LEFT JOIN category AS c10 ON c10.IDPARENT = c9.ID 
				WHERE c0.ID = ".$id;

			$listTemp = $category->getAdapter()->fetchAll($select);
			$listTemp2 = array();
			$listCat = "";

			foreach ($listTemp as $row) {
				for ($level=0 ; $level<11; $level++) {
					if ((!isset($listTemp2['ID'.$level]) || $listTemp2['ID'.$level] != $row['ID'.$level]) && $row['ID'.$level] != null) {
						$listTemp2['ID'.$level] = $row['ID'.$level];
						if ($listCat!="") {
							$listCat .= ' ,'.$row['ID'.$level];
						} else {
							$listCat = $row['ID'.$level];
						}
					}
				}
			}

			$select = "SELECT ID, NOM, DESCRIPTIONSHORT, PRIX, isACTIVE, isPROMO, IDCATEGORY
			FROM product 
			WHERE IDCATEGORY IN (".$listCat.")
			AND isACTIVE = ".$isActive."
			ORDER BY NOM ASC"; 
 
			$product = new Product();
			$listprods = $product->getAdapter()->fetchAll($select);

			$this->view->messageSuccess = sizeof($listprods)." resultats";
			$picture = new Picture();
			$sql = $picture->fetchAll('POSITION = 1');
			$listpics = array();
			foreach ($sql as $row) {
				$listpics[$row['IDPRODUCT']] = $row['URL'];
			}
			$this->view->listproductpicture = $listpics;
			$this->view->listproducts = $listprods;
		}
	}

	public function editlistAction () {
		if ($this->_request->isPost()) {
			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));

			//get the form params
			$params = $this->_request->getPost();


			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'DESCRIPTIONSHORT' => $filter->filter($params['descshort']),
			 		'PRIX' => $filter->filter($params['prix'])
			);

			if ($validator->isValid($data['NOM']) &&
			$validator->isValid($data['DESCRIPTIONSHORT']) &&
			$validator->isValid($data['PRIX'])
			) {
					
				try {
					$product = new Product();
					$product->update($data, 'ID = '.$params['productid']);

					$this->view->messageSuccess = "Le produit a �t� mis a jour";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
					$this->_forward('/list');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/list');

	}

	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter un produit";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

			
		$supplierBrend = new SupplierBrend();
		$this->view->listbrend = $supplierBrend->fetchAll($supplierBrend->select()->order('BREND ASC'));

			
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$date = new Zend_Date();

			$navtemp = $filter->filter($params['nom']);
			$navnom =  $this->generateNavigationString($navtemp);
			$keywords =  $this->generateKeyWords($navtemp);

			$data = array (
			 		'NOM' => $navtemp,
			 		'NAVNOM' => $navnom,
			 		'KEYWORDS' => $keywords,
					'NAVTITRE' => $navtemp,
					'NAVDESC' => $params['descshort'],
			 		'DESCRIPTIONSHORT' => $params['descshort'],
			 		'DESCRIPTIONLONG' => $params['desclong'],
			 		'PRIX' => $filter->filter($params['prix']),
			 		'isACTIVE' => $filter->filter($params['active']),
					'DATEPROMO' => $date->toString('YYYY-MM-dd'),
			 		'isPROMO' => '1',
			 		'IDBREND' => $filter->filter($params['idbrend']),
			 		'IDCATEGORY' => $filter->filter($params['idcategory'])
			);

			if ($validator->isValid($data['NOM']) &&
			$validator->isValid($data['NAVNOM']) &&
			$validator->isValid($data['DESCRIPTIONSHORT']) &&
			$validator->isValid($data['DESCRIPTIONLONG']) &&
			$validator->isValid($data['PRIX'])
			) {
				if ($data['IDBREND'] != 0) {
					try {
						$product = new Product();
						$product->insert($data);
							
						$this->view->messageSuccess = "Le produit a �t� ajout�";
							
						$lastId = $product->getAdapter()->lastInsertId();
						$this->_redirect('/backoffice/product/edit/showProduct/'.$lastId);
							
					} catch (Zend_Exception $e) {
						$this->log($e->getMessage(), 'err');
						$this->view->populateForm = $data;
					}
				} else {
					$this->view->messageError = "S�l�ctionner une marque";

					$this->view->populateForm = $data;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateForm = $data;
			}

		} else {
			$temp = array (
		 			'NOM' => '',
			 		'DESCRIPTIONSHORT' => '',
			 		'DESCRIPTIONLONG' => '',
			 		'PRIX' => '',
			 		'IDBREND' => '',
			 		'IDCATEGORY' => '',
			 		'isACTIVE' => '1',
			 		'isPROMO' => '1'
			 		);
			 		$this->view->populateForm = $temp;
		}
	}

    private function computeUrlNavigationParent($row) {
        return $row['NAVNOM_URLPARENTS']."/".$row['NAVNOM'];
    }
    
	public function editAction()
	{
		try {
			$this->view->titlePage = "Modifier un Produit";
			$isProcuctEnable = true;
	
			$supplierBrend = new SupplierBrend();
			$this->view->listbrend = $supplierBrend->fetchAll($supplierBrend->select()->order('BREND ASC'));
	
			$option = new Option();
			$this->view->listoption = $option->select()->order('NOM ASC')->query()->fetchAll();
	
			$optionList = new OptionList();
			$this->view->optionsbylist = $optionList->getAll();
					
			$category2 = new Category2();
			$this->view->listallcategories2 = $category2->getAllCategoriesByID(0);
				
			$adminNamespace = $this->getSession();
	
			$id = 0;
	
			if ((int)$this->_request->getParam('showProduct') != null) {
				$id = (int)$this->_request->getParam('showProduct');
			}  else if ((int)$this->_request->getParam('id') != null) {
				$id = (int)$this->_request->getParam('id');
			}
			if ($id > 0) {
				$picture = new Picture();
				$listPicture = $picture->fetchAll('IDPRODUCT = '.$id);
				$this->view->listPicture = $listPicture;
				
				$productChildQte = new ProductChildQte();
				$this->view->productChildQte = $productChildQte->getAllByProduct($id);
	
				$product = new Product();	
				$row = $product->fetchRow('ID = '.$id);
				if ($row) {
	
					$currentProduct = $row->toArray();  
					$currentProduct['ONSELECT_OPTION'] = $optionList->getByIdProduct($id);
					$currentProduct['PRIXLOWEST'] = $product->calculateLowestPrice($id);
                                        
                    $category = new Category();
                    $currentCategory = $category->fetchRow('ID = '.$currentProduct['IDCATEGORY']);
					$currentProduct['NAVNOM_URLPARENTS'] = $this->computeUrlNavigationParent($currentCategory);
                    
					$this->view->populateForm = $currentProduct;
	
					
					if ($currentProduct['isACTIVE'] == 1) {
						$isProcuctEnable = false;
					}
                    $isProductOutOfStock = false;
					if ($currentProduct['STOCK'] == 4) {
						$isProductOutOfStock = true;
					}
	
					$productCategory = new ProductCategory2();
					$this->view->productCategories = $productCategory->getAllCategoriesByProductID($id);
	
					if ($listPicture->count()<1) {
						$this->view->messageError = "Aucune image n'est configur�e";
						$adminNamespace->imgPosDefault = 1;
						$isProcuctEnable = false;
					} else {
						$isOK = false;
						foreach ($listPicture as $pic) {
							if ($pic->POSITION == 1) {
								$isOK = true;
								break;
							}
						}
						if (!$isOK) {
							$this->view->messageError = "L'image principale n'est pas d�finie (1)";
							$adminNamespace->imgPosDefault = 1;
							//$isProcuctEnable = false;
						} else {
							$adminNamespace->imgPosDefault = $listPicture->count() + 1;
	
						}
	
					}
	
					$this->view->isProcuctEnable = $isProcuctEnable; 
					$this->view->isProductOutOfStock = $isProductOutOfStock; 
                    
					$productOption = new ProductOption();
					$this->view->listproductoption = $productOption->getOptionsByIdProduct($id);
	
					 
					$productChild = new ProductChild();
					$listProduct = $productChild->getChildsByIdProduct($id);
	
					$listChild = array(); 
					for ($i = 0; $i<sizeof($listProduct); $i++) {
						$listChild[$listProduct[$i]['ID']]['ID'] = $listProduct[$i]['ID'];
						$listChild[$listProduct[$i]['ID']]['REFERENCE'] = $listProduct[$i]['REFERENCE'];
						$listChild[$listProduct[$i]['ID']]['POIDS'] = $listProduct[$i]['POIDS'];
						$listChild[$listProduct[$i]['ID']]['DESIGNATION'] = $listProduct[$i]['DESIGNATION'];
						$listChild[$listProduct[$i]['ID']]['PRIX'] = $listProduct[$i]['PRIX'];
						$listChild[$listProduct[$i]['ID']]['ETATSTOCK'] = $listProduct[$i]['ETATSTOCK'];
						$listChild[$listProduct[$i]['ID']]['isDEVIS'] = $listProduct[$i]['isDEVIS'];
						$listChild[$listProduct[$i]['ID']]['isFRANCODENIED'] = $listProduct[$i]['isFRANCODENIED'];
						$listChild[$listProduct[$i]['ID']]['QUANTITYMIN'] = $listProduct[$i]['QUANTITYMIN'];
						$listChild[$listProduct[$i]['ID']]['isPROMO'] = $listProduct[$i]['isPROMO'];
						$listChild[$listProduct[$i]['ID']]['POINTFIDELITE'] = $listProduct[$i]['POINTFIDELITE'];
	  
						$listChild[$listProduct[$i]['ID']]['IMAGEPROMO'] = $listProduct[$i]['IMAGEPROMO'];
	
						$listChild[$listProduct[$i]['ID']]['OPTION_VALUE_'.$listProduct[$i]['IDOPTION']] = $listProduct[$i]['VALUE'];
						$listChild[$listProduct[$i]['ID']]['OPTION_ID_'.$listProduct[$i]['IDOPTION']] = $listProduct[$i]['IDCHILD'];
					 
					}
					$this->view->listChild = $listChild; 
	
					$childFTFDS = new ProductChildFTFDS();
					$listFTFDS = $childFTFDS->getFTFDSByIdProduct($id);
					$this->view->listFTFDS = $listFTFDS;
	
	
					$productAccessoire = new ProductAccessoire();
					$listAccessoires = $productAccessoire->getAccessoiresByProductID($id, 'pa.REFACCESSOIRE ASC');
					$this->view->listAccessoires = $listAccessoires;
	
					$productAnnexe = new ProductAnnexe();
					$listAnnexes = $productAnnexe->getAnnexesByProductID($id, 'NOM ASC');;
					$this->view->listAnnexes = $listAnnexes;
	
					$this->view->currentProduct = $id;
	
	
					$paramsXML = array(
					'PRODUCT' => $currentProduct,  
				 	'PICS'=> $listPicture, 
					);
					$this->view->siteMapShow = $this->generateSiteMapShow($paramsXML, $currentProduct['NAVNOM_URLPARENTS']);
				} else {
					$this->_forward('/list');
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err'); 
		}
	}

	private function generateSiteMapShow($params, $navParentUrl) {
		$navnoms = array();
		$product = $params['PRODUCT'];

		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		array_push($navnoms, str_replace("page/","",$filter->filter($product['NAVNOM'])));
		array_push($navnoms, str_replace("page/","",$filter->filter($product['CUSTOM_NAVNOM1'])));
		array_push($navnoms, str_replace("page/","",$filter->filter($product['CUSTOM_NAVNOM2'])));
		array_push($navnoms, str_replace("page/","",$filter->filter($product['CUSTOM_NAVNOM3'])));
			
		$br = "<br/>";
		$tab = "&nbsp;&nbsp;&nbsp;";
		$tab2 = $tab.$tab.$tab;
		$url = "";

		foreach ($navnoms as $navnom) {
			if (!empty($navnom)) {
				$url .= $br.htmlentities("<url>");
				$url .= $br.$tab;
				$url .= htmlentities("<loc>".$this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlProduct($navParentUrl, $navnom, $product['ID'])."</loc>");
				$url .= $br;
				foreach($params['PICS'] as $row) {
					$url .= $tab.htmlentities("<image:image>");
					$url .= $br.$tab2;
					$url .= htmlentities("<image:loc>".$this->baseUrl_SiteCommerceUrl."/".$row['URL']."</image:loc>");

					if (!empty($row['STRING1'])) {
						$url .= $br.$tab2;
						$url .= htmlentities("<image:title>".$row['STRING1']."</image:title>");
					}

					if (!empty($row['STRING2'])) {
						$url .= $br.$tab2;
						$url .= htmlentities("<image:caption>".$row['STRING2']."</image:caption>");
					}
					$url .= $br.$tab;
					$url .= htmlentities("</image:image>");
					$url .= $br;
				}
				$url .= htmlentities("</url>");
			}
		}

		return $url;
	}

	public function editproductAction()
	{

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			//valideurs pour les chaines
			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$isDevisProduct = 1;
			if (isset($params['devisonproduct']) && $params['devisonproduct']) {
				$isDevisProduct = 0;
			}

			$data = array (
			 		'NOM' => $filter->filter($params['nom']), 
			 		'DESCRIPTIONSHORT' => $params['descshort'],
			 		'DESCRIPTIONLONG' => $params['desclong'],
			 		'DESCRIPTIONTECH' => $params['desctech'],
			 		'DESCRIPTIONNORME' => $params['descnorme'],
			 		'PRIX' => $filter->filter($params['prix']),
			 		'isACTIVE' => $filter->filter($params['active']),
			 		'IDCATEGORY' => (int)$filter->filter($params['idcategory']),
			 		'DATEPROMO' => $params['sd'],
			 		'ID' => $filter->filter($params['id']),
			 		'IDBREND' => $filter->filter($params['idbrend']),
					'isSHOWBREND' => $filter->filter($params['showbrend']),
					'isDEVIS' => $isDevisProduct,
					'STOCK' => (int)$params['stock'] ,
					'BOOSTED_HOME' => (int)$params['boostedhome'],
					'BOOSTED_BESTSELLER' => (int)$params['boostedbestseller']
			);


			if ($validator->isValid($data['NOM']) &&
			$validator->isValid($data['DESCRIPTIONSHORT']) &&
			$validator->isValid($data['DESCRIPTIONLONG']) &&
			$validator2->isValid($data['PRIX'])
			) {
				try {

					$product = new Product();
					$product->update($data, 'ID = '.$data['ID']);

					$this->view->messageSuccess = "Le produit a �t� modifi�";

					$this->log("Le produit a �t� modifi� : ".$data['ID'],'info');
                    $this->indexproductById($data['ID']);
                
				} catch (Zend_Exception $e) {

					$this->log($e->getMessage(),'err');
					$this->view->messageError = "V�rifier les param�tres";

					$this->view->populateForm = $data;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/edit');
	}

	public function editproductcategoriesAction()
	{

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));

			//valideurs pour les chaines
			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			try {
				$id = (int) $params['id'];
				$data = array (
				 		'ID' => $id,
				 		'IDCATEGORY_DUP1' => (int)$filter->filter($params['idcategory_duplicat1']),
				 		'IDCATEGORY_DUP2' => (int)$filter->filter($params['idcategory_duplicat2']),
				 		'IDCATEGORY_DUP3' => (int)$filter->filter($params['idcategory_duplicat3']) 
				);

				$product = new Product();
				$product->update($data, 'ID = '.$id);

				if (!empty($params['idcategory_promosolde'])) {
					$productCategory = new ProductCategory2();
					$productCategory->delete('IDPRODUCT = '.$id);
					foreach ($params['idcategory_promosolde'] as $row) {
						if ((int)$row > 0) {
							$dataTemp = array ('IDPRODUCT' => $id, 'IDCATEGORY' => (int)$row);
							$productCategory->insert($dataTemp);
						}
					}
				}
					
				$this->view->messageSuccess = "Les cat�gories ont �t� modifi�es";

				$this->log("Les cat�gories ont �t� modifi�es : ".$id,'info');
			} catch (Zend_Exception $e) {

				$this->log($e->getMessage(),'err');
				$this->view->messageError = "Les cat�gories n'ont pas �t� modifi�es";

				$this->view->populateForm = $data;
			}
		}
		$this->_forward('/edit');
	}

	public function editproductkeywordscleanAction()
	{

		$this->view->messageSuccess = "";
		$this->view->messageError = "";


		//get the form params
		$id = (int)$this->_request->getParam('id');

		$data = array ( 'KEYWORDS' => ''  );
			
		try {
			if ($id > 0) {
				$product = new Product();
				$product->update($data, 'ID = '.$id);

				$this->view->messageSuccess = "Les mots cl�s ont �t� modifi�s";

				$this->log("Les mots cl�s ont �t� modifi�s : ".$id,'info');
			}
		} catch (Zend_Exception $e) {

			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Les mots cl�s n'ont pas �t� modifi�s";
		}

		$this->_forward('/edit');
	}

	public function editproductkeywordsAction()
	{
		try {
			$this->view->messageSuccess = "";
			$this->view->messageError = "";

			if ($this->_request->isPost()) {

				//valideurs pour les chaines
				$validator = new Zend_Validate();
				$validator -> addValidator(new Zend_Validate_NotEmpty())
				-> addValidator(new Zend_Validate_StringLength(3));

				//get the form params
				$params = $this->_request->getPost();

				$keywords =  $this->generateKeyWords($params['nom']);

				$data = array ( 'KEYWORDS' => $keywords  );

				if ($validator->isValid($data['KEYWORDS']))  {
					$id = (int)$params['id'];
					if ($id > 0) {
						$product = new Product();
						$product->update($data, 'ID = '.$id);

						$this->view->messageSuccess = "Les mots cl�s ont �t� modifi�s";

						$this->log("Les mots cl�s ont �t� modifi�s : ".$id,'info');
					}
				} else {
					foreach ($validator->getErrors() as $errorCode) {
						$this->view->messageError .=  $this->getErrorValidator($errorCode);
					}
				}
			}
		} catch (Zend_Exception $e) {

			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Les mots cl�s n'ont pas �t� modifi�s";
		}
		$this->_forward('/edit');
	}

	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$product = new Product();
					$productOtion = new ProductOption();
					$productChild = new ProductChild();
					$productChildOption = new ProductChildOption();
					$productAccessoire = new ProductAccessoire();
					$picture = new Picture();

					$childs = $productChild->fetchAll('IDPRODUCT = '.$id);

					foreach ($childs as $row) {
						$productChildOption->delete('IDPRODUCTCHILD = '.$row->ID);
						$productAccessoire->delete('REFACCESSOIRE = "'.$row->REFERENCE.'"');
					}
					$productChild->delete('IDPRODUCT = '.$id);
					$picture->delete('IDPRODUCT = '.$id);
					$productOtion->delete('IDPRODUCT = '.$id);
					$product->delete('ID = '.$id);

					$this->view->messageSuccess = "Le produit a �t� supprim�";

					$this->log("Le produit a �t� supprim�",'info');
				} catch (Zend_Exception $e) {

					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');

	}

	public function editchildAction()
	{
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));

			//valideurs pour les chaines
			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$date = new Zend_Date();

			$isDevisPrice = 1;
			if (isset($params['devisprice']) && $params['devisprice']) {
				$isDevisPrice = 0;
			}

			$quantiteMin = (int)$params['quantiteMin'];
			if ($quantiteMin == 0) {
				$quantiteMin = 1;
			}

			$dataChild = array (
			 		'REFERENCE' => $filter->filter($params['reference']),
			 		'DESIGNATION' => $filter->filter($params['designation']),
			 		'PRIX' => $filter->filter($params['prixNormal']),
			 		'ETATSTOCK' => $filter->filter($params['etatstock']),
			 		'QUANTITYMIN' => $filter->filter($quantiteMin),
					'isDEVIS' => $isDevisPrice,
			 		'IMAGEPROMO' => $filter->filter($params['imagePromo']),
			 		'DATEMODIF' => $date->toString('YYYY-MM-dd HH:mm:ss'),
			 		'IDPRODUCT' => (int)$this->_request->getParam('id')
			);
			$listOption = unserialize($params['listOption']);

			if ($validator->isValid($dataChild['REFERENCE']) &&
			$validator2->isValid($dataChild['PRIX'])&&
			$validator->isValid($dataChild['DESIGNATION'])
			) {

				try {
					$productChild = new ProductChild();
					$productChild->update($dataChild, 'ID = '.$params['idchild']);

					$productChildOption = new ProductChildOption();
					foreach ($listOption as $option) {
						$dataOption = array (
						 		'IDPRODUCTCHILD' => $params['idchild'],
						 		'IDOPTION' => $option,
						 		'VALUE' => $params['option'.$option]
						);
						$isOk = $productChildOption->update($dataOption,'IDPRODUCTCHILD = '.$params['idchild'].' AND IDOPTION = '.$option);
						if (!$isOk) {

							$productChildOption->delete('IDPRODUCTCHILD = '.$params['idchild'].' AND IDOPTION = '.$option);
							$productChildOption->insert($dataOption);
						}
					}


					$this->view->messageSuccess = "Le produit a ete modifie";

					$this->log("Le produit child a ete modifie : ".$params['idchild'],'info');
                    
				} catch (Zend_Exception $e) {

					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La r�f�rence existe d�ja";

					$this->view->populateChild = $dataChild;
					$this->_forward('/edit');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateChild = $dataChild;
			}

		}
		$this->_forward('/edit');
	}
	public function editchildsAction()
	{
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			for ($index = 0; $index < $params['nbRows']; $index++) {
				if (isset($params[$index."reference"]) && !empty($params[$index."reference"]) &&
				isset($params[$index."designation"]) && !empty($params[$index."designation"])
				) {
					$optionsValues = array();
					$listOption = unserialize($params['listOption']);
					foreach ($listOption as $option) {
						$optionsValues['option'.$option] = $params[$index."option".$option];
					}
					$isDevisPrice = 1;
					if (isset($params[$index.'devisprice']) && $params[$index.'devisprice']) {
						$isDevisPrice = 0;
					}

					$isFrancoDenied = 1;
					if (isset($params[$index.'francodenied']) && $params[$index.'francodenied']) {
						$isFrancoDenied = 0;
					}

					$this->editSingleChild($index,
					$params,
					$isDevisPrice,
					$isFrancoDenied,
					$listOption,
					$optionsValues,
					(int)$this->_request->getParam('id'));
				}
			}


		}
		$this->_forward('/edit');
	}
	private function editSingleChild($line, $paramsRequest,  $isDevisPrice,$isFrancoDenied,  $listOption, $optionsValues, $idProduct) {

		$idChild = $paramsRequest[$line.'idchild'];
		$quantity = $paramsRequest[$line.'quantiteMin'];
		$reference = $paramsRequest[$line.'reference'];
		$poids = $paramsRequest[$line.'poids'];
		$designation = $paramsRequest[$line.'designation'];
		$prixNormal =$paramsRequest[$line.'prixNormal'] ;
		$etatstock = $paramsRequest[$line.'etatstock'];
		$imagePromo = $paramsRequest[$line.'imagePromo'];

        $pointFidelite = 0;
        if (isset($paramsRequest[$line.'pointFidelite'])) {
            $pointFidelite = (int)$paramsRequest[$line.'pointFidelite'];
        }

		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		//valideurs pour les chaines
		$validator2 = new Zend_Validate();
		$validator2 -> addValidator(new Zend_Validate_NotEmpty());

		$quantiteMin = (int)$quantity;
		if ($quantiteMin == 0) {
			$quantiteMin = 1;
		}
		$date = new Zend_Date();
		$adminNamespace = $this->getSession();
		$dataChildReturn = array (
		$line.'REFERENCE' => $filter->filter($reference),
		$line.'POIDS' => $filter->filter($poids),
		$line.'DESIGNATION' => $designation,
		$line.'PRIX' => $filter->filter($prixNormal),
		$line.'ETATSTOCK' => $filter->filter($etatstock),
		$line.'QUANTITYMIN' => $filter->filter($quantiteMin),
		$line.'isDEVIS' => $isDevisPrice,
		$line.'isFRANCODENIED' => $isFrancoDenied,
		$line.'IMAGEPROMO' => $filter->filter($imagePromo),
		$line.'DATEMODIF' => $date->toString('YYYY-MM-dd HH:mm:ss'),
		$line.'IDPRODUCT' => $idProduct,
		$line.'POINTFIDELITE' => $pointFidelite
		);

		$dataChild = array (
		 		'REFERENCE' => $filter->filter($reference),
		 		'POIDS' => $filter->filter($poids),
		 		'DESIGNATION' => $designation,
		 		'PRIX' => $filter->filter($prixNormal),
		 		'ETATSTOCK' => $filter->filter($etatstock),
		 		'QUANTITYMIN' => $filter->filter($quantiteMin),
		 		'isDEVIS' => $isDevisPrice,
		 		'isFRANCODENIED' => $isFrancoDenied,
		 		'IMAGEPROMO' => $filter->filter($imagePromo),
		 		'DATEMODIF' => $date->toString('YYYY-MM-dd HH:mm:ss'),
		 		'IDPRODUCT' => $idProduct ,
		 		'POINTFIDELITE' => $pointFidelite 
		);

		if ($validator->isValid($dataChild['REFERENCE']) &&
		$validator2->isValid($dataChild['PRIX'])&&
		$validator->isValid($dataChild['DESIGNATION'])
		) {
			try {

				$productChild = new ProductChild();
				$productChild->update($dataChild, 'ID = '.$idChild);

				$productChildOption = new ProductChildOption();
				foreach ($listOption as $option) {
					$dataOption = array (
					 		'IDPRODUCTCHILD' => $idChild,
					 		'IDOPTION' => $option,
					 		'VALUE' => $optionsValues['option'.$option]
					);
					$isOk = $productChildOption->update($dataOption,'IDPRODUCTCHILD = '.$idChild.' AND IDOPTION = '.$option);
					if (!$isOk) {
						$productChildOption->delete('IDPRODUCTCHILD = '.$idChild.' AND IDOPTION = '.$option);
						$productChildOption->insert($dataOption);
					}
				}
					
				$this->view->messageSuccess = "Le produit a �t� modifi�";
                $this->indexproductById($idProduct);
                
				return true;
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = "La r�f�rence existe d�ja";
				$this->view->populateChild = $dataChildReturn;
			}
		} else {
			foreach ($validator->getErrors() as $errorCode) {
				$this->view->messageError .=  $this->getErrorValidator($errorCode);
			}
			$this->view->populateChild = $dataChildReturn;
		}
		return false;
	}
	public function delchildAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('idchild')) {
			$idchild = (int)$this->_request->getParam('idchild');
			$id = (int)$this->_request->getParam('id');
			if ($idchild > 0 && $id > 0) {
				try {
					$childFTFDS = new ProductChildFTFDS();
					$child = $childFTFDS->fetchRow('ID_CHILD = '.$idchild);
					
					if (!$child) {
							$productChild = new ProductChild();
	
							$productChild->delete('ID = '.$idchild);
	
							$productChildOption = new ProductChildOption();
	
							$productChildOption->delete('IDPRODUCTCHILD = '.$idchild);
	
							$this->view->messageSuccess = "Le produit a �t� supprim�";
					} else {
						$this->view->messageError = "Un document est associ�e a ce produit, vous devez la supprimer avant de supprimer le produit";
					}


				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/edit');

	}
	public function addchildAction()
	{
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));

			//valideurs pour les chaines
			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$date = new Zend_Date();

			$adminNamespace = $this->getSession();

			$isDevisPrice = 1;
			if (isset($params['devisprice']) && $params['devisprice']) {
				$isDevisPrice = 0;
			}
			$quantiteMin = (int)$params['quantiteMin'];
			if ($quantiteMin == 0) {
				$quantiteMin = 1;
			}

			$dataChild = array (
			 		'REFERENCE' => $filter->filter($params['reference']),
			 		'DESIGNATION' => $filter->filter($params['designation']),
			 		'PRIX' => $filter->filter($params['prixNormal']),
			 		'ETATSTOCK' => $filter->filter($params['etatstock']),
			 		'QUANTITYMIN' => $filter->filter($quantiteMin),
			 		'isDEVIS' => $isDevisPrice,
			 		'IMAGEPROMO' => $filter->filter($params['imagePromo']),
			 		'DATEMODIF' => $date->toString('YYYY-MM-dd HH:mm:ss'),
			 		'IDPRODUCT' => (int)$this->_request->getParam('id')
			);
			$listOption = unserialize($params['listOption']);

			if ($validator->isValid($dataChild['REFERENCE']) &&
			$validator2->isValid($dataChild['PRIX'])&&
			$validator->isValid($dataChild['DESIGNATION'])
			) {

				try {
					$productChild = new ProductChild();
					$productChild->insert($dataChild);

					$lastid = $productChild->getAdapter()->lastInsertId();

					$productChildOption = new ProductChildOption();
					foreach ($listOption as $option) {
						$dataOption = array (
						 		'IDPRODUCTCHILD' => $lastid,
						 		'IDOPTION' => $option,
						 		'VALUE' => $params['option'.$option]
						);
						$productChildOption->insert($dataOption);
					}


					$this->view->messageSuccess = "Le produit a �t� ajout�";

				} catch (Zend_Exception $e) {

					$this->view->messageError = "La r�f�rence existe d�j�";

					$this->log($e->getMessage(),'err');
					$this->view->populateChild = $dataChild;
					$this->_forward('/edit');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateChild = $dataChild;
			}

		}
		$this->_forward('/edit');
	}
	public function addchildsAction()
	{
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//get the form params
			$params = $this->_request->getPost();
			for ($index = 0; $index < 2; $index++) {
				try {
					if (isset($params[$index."reference"]) && !empty($params[$index."reference"]) &&
					isset($params[$index."designation"]) && !empty($params[$index."designation"])
					) {
						$optionsValues = array();
						$listOption = unserialize($params['listOption']);
						foreach ($listOption as $option) {
							$optionsValues['option'.$option] = $params[$index."option".$option];
						}
						$isDevisPrice = 1;
						if (isset($params[$index.'devisprice']) && $params[$index.'devisprice']) {
							$isDevisPrice = 0;
						}
						$this->addSingleChild($index, $isDevisPrice,
						$params[$index.'quantiteMin'],
						$params[$index.'reference'],
						$params[$index.'poids'],
						$params[$index.'designation'],
						$params[$index.'prixNormal'],
						$params[$index.'etatstock'],
						$params[$index.'imagePromo'],
						$listOption,
						$optionsValues,
						(int)$this->_request->getParam('id'));
					}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "V�rifier les param�tres";
				}
			}


		}
		$this->_forward('/edit');
	}

	private function addSingleChild($line, $isDevisPrice, $quantity, $reference, $poids, $designation, $prixNormal, $etatstock, $imagePromo, $listOption, $optionsValues, $idProduct) {

		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		//valideurs pour les chaines
		$validator2 = new Zend_Validate();
		$validator2 -> addValidator(new Zend_Validate_NotEmpty());

		$quantiteMin = (int)$quantity;
		if ($quantiteMin == 0) {
			$quantiteMin = 1;
		}
		$date = new Zend_Date();
		$adminNamespace = $this->getSession();
		$dataChildReturn = array (
		$line.'REFERENCE' => $filter->filter($reference),
		$line.'POIDS' => $filter->filter($poids),
		$line.'DESIGNATION' => $filter->filter($designation),
		$line.'PRIX' => $filter->filter($prixNormal),
		$line.'ETATSTOCK' => $filter->filter($etatstock),
		$line.'QUANTITYMIN' => $filter->filter($quantiteMin),
		$line.'isDEVIS' => $isDevisPrice,
		$line.'IMAGEPROMO' => $filter->filter($imagePromo),
		$line.'DATEMODIF' => $date->toString('YYYY-MM-dd HH:mm:ss'),
		$line.'IDPRODUCT' => $idProduct
		);
		
		$poids = $filter->filter($poids);
		if (empty($poids)) { $poids = 0; }
		
		$quantiteMin = $filter->filter($quantiteMin);
		if (empty($quantiteMin)) {	$quantiteMin = 1;	}
		
		$imagePromo = $filter->filter($imagePromo);
		if (empty($imagePromo)) { $imagePromo = 0; }

		$dataChild = array (
		 		'REFERENCE' => $filter->filter($reference),
		 		'POIDS' => $poids,
		 		'DESIGNATION' => $filter->filter($designation),
		 		'PRIX' => $filter->filter($prixNormal),
		 		'ETATSTOCK' => $filter->filter($etatstock),
		 		'QUANTITYMIN' => $quantiteMin,
		 		'isDEVIS' => $isDevisPrice,
		 		'IMAGEPROMO' => $imagePromo,
		 		'DATEMODIF' => $date->toString('YYYY-MM-dd HH:mm:ss'),
		 		'IDPRODUCT' => $idProduct
		);

		if ($validator->isValid($dataChild['REFERENCE']) &&
		$validator2->isValid($dataChild['PRIX'])&&
		$validator->isValid($dataChild['DESIGNATION'])
		) {
			try {
				$productChild = new ProductChild();
				if (!$productChild->isChildReferenceExist($dataChild['REFERENCE'])){
					$productChild->insert($dataChild);
	
					$lastid = $productChild->getAdapter()->lastInsertId();
	
					$productChildOption = new ProductChildOption();
					foreach ($listOption as $option) {
						$dataOption = array (
						 		'IDPRODUCTCHILD' => $lastid,
						 		'IDOPTION' => $option,
						 		'VALUE' => $optionsValues['option'.$option]
						);
						$productChildOption->insert($dataOption);
					}
					$this->view->messageSuccess = "Le produit a �t� ajout�";
					return true;
				} else {
					$this->view->populateChild = $dataChildReturn;
					$this->view->messageError = "La r�f�rence existe d�ja";
					return false;
				}
			} catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
				$this->view->messageError = "La r�f�rence existe d�ja";
				$this->view->populateChild = $dataChildReturn;
			}
		} else {
			foreach ($validator->getErrors() as $errorCode) {
				$this->view->messageError =  $this->getErrorValidator($errorCode);
			}
			foreach ($validator2->getErrors() as $errorCode) {
				$this->view->messageError =  $this->getErrorValidator($errorCode);
			}
			$this->view->populateChild = $dataChildReturn;
		}
		return false;
	}

	public function addproductoptionAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {
			$params = $this->_request->getPost();

			$data = array (
			 		'IDPRODUCT' => (int)$this->_request->getParam('id'),
			 		'IDOPTION' => $params['idoption']
			);

			try {
				$product = new Product();
				$sql = 'SELECT p.NOM
					FROM product p 
					LEFT JOIN product_option AS po ON po.IDPRODUCT = p.ID
					WHERE p.ID = '.$data['IDPRODUCT'].'
					AND po.IDOPTION = '.$data['IDOPTION'];

				$isExistOption = $product->getAdapter()->fetchRow($sql);

				if (!$isExistOption) {

					$productOption = new ProductOption();

					$productOption->insert($data);

					$this->view->messageSuccess = "L'option a �t� ajout�e";
				} else {
					$this->view->messageError = "L'option existe d�ja";
				}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');
	}
	public function delproductoptionAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		$adminNamespace = $this->getSession();
		if($this->_request->getParam('idopt')) {
			$idopt = (int)$this->_request->getParam('idopt');
			$id = (int)$this->_request->getParam('id');
			if ($idopt > 0 && $id > 0) {
				try {

					$productOption = new ProductOption();
					$productChildOption = new ProductChildOption();
					$productOption->delete('IDOPTION = '.$idopt.' AND IDPRODUCT = '.$id);

					$sql = "
		    			 DELETE pco 
		    			 FROM productchild_option AS pco 
		    			 LEFT JOIN productchild AS pc ON pc.ID = pco.IDPRODUCTCHILD
						WHERE pco.IDOPTION = ".$idopt." 
						AND pc.IDPRODUCT = ".$id;

					$productChildOption->getAdapter()->query($sql);


					$this->view->messageSuccess = "L'option a �t� supprim�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/edit');
	}

	public function optionprofilAction() {
		$this->view->titlePage = "Listing des Profils d'options";
		if ($this->_request->isPost() && (int)$this->_request->getParam('id') ==0) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$options = $params['profilOptions'];
			$optionValues = "";
			foreach ($options as $idOption) {
				$optionValues .= $idOption.";";
			}
			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
					'OPTS' => $optionValues
			);

			if ($validator->isValid($data['NOM'])) {

				try {
					$optionProfil = new OptionProfil();
					$optionProfil->insert($data);

					$this->view->messageSuccess = "Le profil a �t� ajout�";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');

					$this->view->messageError = "Le profil existe d�ja";

				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}

		}

		$option = new Option();
		$listOptions = $option->select()->order('NOM ASC')->query()->fetchAll();
		$this->view->listoption = $listOptions;

		$optionProfil = new OptionProfil();
		$this->view->listprofils = $optionProfil->getProfils();
	}
	public function optionprofildelAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$optionProfil = new OptionProfil();

					$optionProfil->delete('ID = '.$id);

					$this->view->messageSuccess = "Le profil a �t� supprim�";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
					$this->_forward('/optionprofil');
				}
			}
		}
		$this->_forward('/optionprofil');
	}

	public function optionAction() {
		$this->view->titlePage = "Gestion des caract�ristiques du produit";
		$this->view->currentMenu = "Option";

		if ($this->_request->isPost() && (int)$this->_request->getParam('id') ==0) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'NOM' => $filter->filter($params['nom'])
			);

			if ($validator->isValid($data['NOM'])) {

				try {
					$option = new Option();
					$option->insert($data);

					$this->view->messageSuccess = "La caract�ristique a �t� ajout�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La caract�ristique existe d�ja";

				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}

		}
		$option = new Option();
		$this->view->listoption = $option->select()->order('NOM ASC')->query()->fetchAll();

	}
	public function optioneditAction()
	{
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'ID' => $filter->filter($params['id'])
			);

			if ($validator->isValid($data['NOM'])
			) {

				try {
					$option = new Option();
					$option->update($data, 'ID = '.$data['ID']);

					$this->view->messageSuccess = "La caract�ristique a �t� modifi�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La caract�ristique existe d�j�";

					$this->_forward('option');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('option');
	}
	public function optiondelAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$product = new Product();
					$sql = 'SELECT p.NOM
					FROM product p 
					LEFT JOIN productchild AS pc ON pc.IDPRODUCT = p.ID
					LEFT JOIN productchild_option AS pco ON pco.IDPRODUCTCHILD = pc.ID
					WHERE pco.IDOPTION = '.$id ;
					$isExistProduct = $product->getAdapter()->fetchRow($sql);

					if (!$isExistProduct) {

						$option = new Option();

						$option->delete('ID = '.$id);

						$this->view->messageSuccess = "La caract�ristique a �t� supprim�e";
					} else {
						$this->view->messageError = "La caract�ristique est utilis�e par : <b>".$isExistProduct['NOM']."</b>";
					}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
					$this->_forward('/option');
				}
			}
		}
		$this->_forward('/option');
	}

	public function editftfdsAction() {

		$params = $this->_request->getPost();

		if(!empty($params['idchild_ftfds']) && !empty($_FILES['file_ftfds']) && !empty($_FILES['file_ftfds']['name'])) {
			$nomOrigine = $_FILES['file_ftfds']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("pdf");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				// incluant l'heure a la seconde pres
				$repertoireDestination = 'items/ftfds/';
				$this->checkDirectoryExist($repertoireDestination);
				
				$nomDestination = $params['idchild_ftfds'].".".$extensionFichier;

				if (move_uploaded_file($_FILES["file_ftfds"]["tmp_name"],$repertoireDestination.$nomDestination)) {
					try {
						$childFTFDS = new ProductChildFTFDS();
						$data = array (
					 		'URL' => $repertoireDestination.$nomDestination,
					 		'ID_CHILD' => $params['idchild_ftfds']
						);
						$childFTFDS->insert($data);
						$this->view->messageSuccess = "Le document a �t� ajout�e ";
					} catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		} else {
			$this->view->messageError = "Veuillez s�lectionner un document au format pdf";
		}

		$this->_forward('/edit');
	}

	public function delftfdsAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('idchild')) {
			$idchild = (int)$this->_request->getParam('idchild');
			if ($idchild > 0) {
				try {
					$childFTFDS = new ProductChildFTFDS();
					$child = $childFTFDS->fetchRow('ID_CHILD = '.$idchild);
					$childFTFDS->delete('ID_CHILD = '.$idchild);
					unlink($child['URL']);
					$this->view->messageSuccess = "Le document a �t� supprim�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/edit');
	}


	public function editdocAction() {

		$params = $this->_request->getPost();

		if(!empty($params['docname_product']) && !empty($_FILES['file_doc']) && !empty($_FILES['file_doc']['name'])) {
			$nomOrigine = $_FILES['file_doc']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("pdf");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				// incluant l'heure a la seconde pres
				$repertoireDestination = 'items/doc/';
				$this->checkDirectoryExist($repertoireDestination);
				
				$nomDestination = $params['docid_product'].".".$extensionFichier;

				if (move_uploaded_file($_FILES["file_doc"]["tmp_name"],$repertoireDestination.$nomDestination)) {
					try {
						$product = new Product();
						$data = array (
					 		'DOCURL' => $repertoireDestination.$nomDestination,
					 		'DOCNAME' => $params['docname_product']
						);
						$product->update($data, "ID = ".$params['docid_product']);
						$this->view->messageSuccess = "Le document a �t� ajout� ";
					} catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		} else {
			$this->view->messageError = "Veuillez s�lectionner un document au format pdf";
		}

		$this->_forward('/edit');
	}

	public function deldocAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$product = new Product();
					$row = $product->fetchRow('ID = '.$id)->toArray();
					$docurl = $row['DOCURL'];
					unlink($docurl);
					$data = array (
					 		'DOCURL' => "",
					 		'DOCNAME' => ""
					 		);
					 		$product->update($data, "ID = ".$id);
					 		$this->view->messageSuccess = "Le document a �t� supprim�";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/edit');
	}



	public function livraisonAction() {
		$this->view->titlePage = "Configuration de la livraison";

		$livraison_type = new LivraisonType();
		$this->view->livraisontypes = $livraison_type->getTypes();

		$livraison_poids = new LivraisonPoids();
		$this->view->livraisonpoids = $livraison_poids->getLists();
	}

	public function addlivraisontypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'NOM' => $filter->filter($params['livraison_nom']),
			 		'CMDFRANCO' => $filter->filter($params['livraison_franco'])
			);

			if ($validator->isValid($data['NOM'])
			) {

				try {
					$livraison_type = new LivraisonType();
					$livraison_type->insert($data);

					$this->view->messageSuccess = "Le type de livraison a �t� ajout�";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "Le type de livraison existe d�ja";

					$this->_forward('/livraison');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/livraison');
	}

	public function dellivraisontypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$livraison_type = new LivraisonType();
					$livraison_poids = new LivraisonPoids();
					$livraison_type->delete("ID = ".$id);
					$livraison_poids->delete("TYPE = ".$id);
					$this->view->messageSuccess = "Le type de livraison a �t� supprim�";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/livraison');
	}

	public function editlivraisontypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'NOM' => $filter->filter($params['livraison_nom']),
			 		'CMDFRANCO' => $filter->filter($params['livraison_franco'])
			);

			if ($validator->isValid($data['NOM'])
			) {

				try {
					$livraison_type = new LivraisonType();
					$livraison_type->update($data, "ID = ".$params['livraison_id']);

					$this->view->messageSuccess = "Le type de livraison a �t� modifi�";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "Le type de livraison n'a pas �t� modifi�";

					$this->_forward('/livraison');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/livraison');
	}

	public function addlivraisonpoidsAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			if (isset($params['livraison_poids_type'])) {
				$data = array (
				 		'TO' => floatval($params['livraison_poids_to']),
				 		'FROM' => floatval($params['livraison_poids_from']),
				 		'TYPE' => floatval($params['livraison_poids_type']),
				 		'PRICE' => floatval($params['livraison_poids_price'])
				);
				if ($data['TO'] > 0 && $data['TYPE'] > 0) {

					try {
						$livraison_poids = new LivraisonPoids();
						$livraison_poids->insert($data);

						$this->view->messageSuccess = "Le poids de la livraison a �t� ajout�";

					} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
						$this->view->messageError = "Le poids de la livraison n'a pas �t� ajout�";
						$this->_forward('/livraison');
					}
				} else {
					$this->view->messageError = "Le poids de la livraison n'a pas �t� ajout�";
					$this->_forward('/livraison');
				}
			}

		}
		$this->_forward('/livraison');
	}

	public function editlivraisonpoidsAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'TO' => floatval($params['livraison_poids_to']),
			 		'FROM' => floatval($params['livraison_poids_from']),
			 		'TYPE' => floatval($params['livraison_poids_type']),
			 		'PRICE' => floatval($params['livraison_poids_price'])
			);

			if ($data['TO'] > 0 && $data['TYPE'] > 0 ) {

				try {
					$livraison_poids = new LivraisonPoids();
					$livraison_poids->update($data, "ID = ".$params['livraison_poids_id']);

					$this->view->messageSuccess = "Le poids de la livraison a �t� modifi�";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "Le poids de la livraison n'a pas �t� modifi�";

					$this->_forward('/livraison');
				}
			} else {
				$this->view->messageError = "Le poids de la livraison n'a pas �t� modifi�";

				$this->_forward('/livraison');
			}
		}
		$this->_forward('/livraison');
	}

	public function dellivraisonpoidsAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$livraison_poids = new LivraisonPoids();
					$livraison_poids->delete("ID = ".$id);
					$this->view->messageSuccess = "Le poids de la livraison a �t� supprim�";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/livraison');
	}

	public function livraisoncatAction(){
		$this->view->titlePage = "Configuration g�n�ralis�e du poids";

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {
			//get the form params
			try {
					
				$params = $this->_request->getPost();

				if (isset($params["livraison_poids_id"]) && !empty($params["livraison_poids_id"])) {
					$listCatId = array();
					$listCatId = $params['livraison_poids_id'];
					$productChild = new ProductChild();
					foreach ($listCatId as $catId) {
						if (isset($params["livraison_poids_".$catId]) && !empty($params["livraison_poids_".$catId]) && $params["livraison_poids_".$catId] > 0) {
							$sql = "UPDATE productchild, product SET productchild.poids=".floatval($params["livraison_poids_".$catId])." WHERE productchild.idproduct=product.id AND product.idcategory=".$catId;
							$productChild->getAdapter()->query($sql);
						}
					}
					$this->view->messageSuccess = "Les produits ont �t� mis a jour";
				}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
	}

	public function keywordsengineAction() {
		$this->view->titlePage = "Configuration des mots cl�s";

		$keyword = new KeyWord();
		$listkeywords = $keyword->getLists();

		$this->setPaginator($listkeywords, $this->_getParam('page',1), 50);

	}


	public function keywordsengineresetAction() {
		try {
			$product = new Product();
			$sql = "SELECT KEYWORDS FROM product" ;
			$keyProducts = $product->getAdapter()->fetchAll($sql);
			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StringToLower());

			$keys = array();
			foreach ($keyProducts as $row) {
				$keyArray = preg_split("/[\s]*[,][\s]*/", $row['KEYWORDS']);
				for ($index = 0; $index < sizeof($keyArray); $index++) {
					$keyTemp = $filter->filter($keyArray[$index]);
					if (!in_array($keyTemp, $keys) && !empty($keyTemp)) {
						array_push($keys, $keyTemp);
					}
				}
			}

			$keyword = new KeyWord();
			for ($index = 0; $index < sizeof($keys); $index++) {
				try {
					$data = array( "KEYWORD" => $keys[$index] );
					$keyword->insert($data);
				} catch (Zend_Exception $e) { }
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$this->_forward('/keywordsengine');
	}


	public function addkeywordsengineAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringToLower())
			->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));


			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			if (isset($params['keyword']) && $validator->isValid($params['keyword'])) {
				$data = array (
				 		'KEYWORD' => $filter->filter($params['keyword'])
				);
				$keyword = new KeyWord();
				if (!$keyword->isExist($data['KEYWORD'])) {
					try {
						$keyword->insert($data);

						$this->view->messageSuccess = "Le mot cl� a �t� ajout�";

					} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
						$this->view->messageError = "Le mot cl� n'a pas �t� ajout�";
					}
				} else {
					$this->view->messageError = "Le mot cl� existe";
				}
			} else {
				$this->view->messageError = "Le mot cl� n'a pas �t� ajout�";
			}

		}
		$this->_forward('/keywordsengine');
	}
	public function editkeywordsengineAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringToLower())
			->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));


			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'KEYWORD' => $filter->filter($params['keyword'])
			);

			try {
				$keyword = new KeyWord();
				$result = $keyword->update($data, "ID = ".$params['keyword_id']);

				if ($result) {
					$this->view->messageSuccess = "Le mot cl� a �t� modifi�";
				} else {
					$this->view->messageError = "Le mot cl� existe";
				}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = "Le mot cl� n'a pas �t� modifi�";
			}
		}
		$this->_forward('/keywordsengine');
	}

	public function delkeywordsengineAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$keyword = new KeyWord();
					$keyword->delete("ID = ".$id);
					$this->view->messageSuccess = "Le mot cl� a �t� supprim�";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/keywordsengine');
	}


	public function ajaxautocompletekeywordAction() {
		$result = array();
		try {
			if ($this->getRequest()->isPost()) {
				$filter = new Zend_Filter();
				$filter->addFilter(new Zend_Filter_StringTrim())
				->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringToLower())
				->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));

				$keyword = new KeyWord();
				$key = $filter->filter(utf8_decode($this->getRequest()->getPost('search')));

				$result = $keyword->findByKeyword($key);
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$this->view->messageSuccess = serialize($result);

		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxvalue');
	}

	public function ajaxautocompletekeywordinsertAction() {
		$currentKeywords = "";
		$idproduct = 0;

		if ($this->getRequest()->isPost()) {
			try {
				$filter = new Zend_Filter();
				$filter->addFilter(new Zend_Filter_StringTrim())
				->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringToLower())
				->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));

				$key = $filter->filter(utf8_decode($this->getRequest()->getPost('search')));
				$idproduct = (int)$this->getRequest()->getPost('idproduct');

				$validator = new Zend_Validate();
				$validator -> addValidator(new Zend_Validate_NotEmpty());

				if ($validator->isValid($key) && $idproduct > 0) {
					$product = new Product();
					$row = $product->fetchRow('ID = '.$idproduct)->toArray();

					if (empty($row['KEYWORDS'])) {
						$currentKeywords = $key;
					} else {
						$currentKeywords = $row['KEYWORDS'].",".$key;
					}
					$data = array( "KEYWORDS" => $currentKeywords);
					$product->update($data, 'ID = '.$idproduct);
				}
			} catch (Zend_Exception $e) { 
					$this->log($e->getMessage(),'err');}
		}

		if (!empty($currentKeywords)) {
			$this->view->messageSuccess = $currentKeywords;
		} else {
			if ($idproduct > 0) {
				$product = new Product();
				$row = $product->fetchRow('ID = '.$idproduct)->toArray();
				$this->view->messageSuccess = $row['KEYWORDS'];
			}
		}

		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxvalue');
	}

	public function autocompletekeywordaddAction() {
		$currentKeywords = "";
		$idproduct = 0;

		if ($this->getRequest()->isPost()) {
			try {
				$filter = new Zend_Filter();
				$filter->addFilter(new Zend_Filter_StringTrim())
				->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringToLower())
				->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));


				$key = $filter->filter($this->getRequest()->getPost('keywords_list'));
				$idproduct = (int)$this->getRequest()->getPost('id');

				$validator = new Zend_Validate();
				$validator -> addValidator(new Zend_Validate_NotEmpty());

				if ($validator->isValid($key) && $idproduct > 0) {
					$keyword = new KeyWord();
					if (!$keyword->isExist($key)) {
						$data = array( "KEYWORD" => $key);
						$keyword->insert($data);
					}
					$product = new Product();
					$row = $product->fetchRow('ID = '.$idproduct)->toArray();

					if (empty($row['KEYWORDS'])) {
						$currentKeywords = $key;
					} else {
						$currentKeywords = $row['KEYWORDS'].",".$key;
					}
					$data = array( "KEYWORDS" => $currentKeywords);
					$product->update($data, 'ID = '.$idproduct);
					$this->view->messageSuccess = "Le mot cl� a �t� ajout�";
				}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = "Le mot cl� n'a pas �t� ajout�";
			}
		}
		$this->_forward('/edit');
	}

	public function ajaxproductaccessoirelistbycatAction() {
		try {
			if ($this->getRequest()->isPost()) {
				$idcat = (int) $this->getRequest()->getPost('idcategory');
				$idcurrentproduct = (int) $this->getRequest()->getPost('idproduct');

				$product = new Product();
				$listproducts = $product->getProductsByIdCategory($idcat, 'NOM ASC');
				$this->view->listProducts = $listproducts;
				$this->view->currentProduct = $idcurrentproduct;

				$productAccessoire = new ProductAccessoire();
				$this->view->listAccessoires = $productAccessoire->getAccessoiresByProductID($idcurrentproduct, 'pa.REFACCESSOIRE ASC');;
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxaccessoireproductlist');
	}


	public function addproductaccessoireAction() {
		$productAccessoire = new ProductAccessoire();
		$productChild = new ProductChild();
		try {
			if ($this->getRequest()->isPost()) {
				$params = $this->_request->getPost();
				$idproduct = (int) $params['id'];
				$refaccessoire = $params['reference_acc'];
				if ($idproduct > 0 && !empty($refaccessoire) ) {
					if ($productChild->isChildReferenceExist($params['reference_acc'])) {
						$isOk = $productAccessoire->insertAccessoire($idproduct, $refaccessoire);
						if ($isOk) {
							$this->view->messageSuccess = "L'accessoire a �t� ajout�";
						} else {
							$this->view->messageError = "L'accessoire n'a pas �t� ajout�, il est d�j� pr�sent pour ce produit";
						}
					} else {
						$this->view->messageError = "La r�f�rence n'existe pas";
					}

				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$this->_forward('/edit');
	}

	public function ajaxdelproductaccessoireAction() {
		$productAccessoire = new ProductAccessoire();
		try {
			if ($this->getRequest()->isPost()) {
				$params = $this->_request->getPost();
				$idAccessoire = (int) $params['idAccessoire'];
				$idproduct = (int) $params['idproduct'];
				if ($idAccessoire > 0 ) {
					$productAccessoire->deleteAccessoire($idAccessoire);
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$listAccessoires = $productAccessoire->getAccessoiresByProductID($idproduct, 'pa.REFACCESSOIRE ASC');
		$this->view->listAccessoires = $listAccessoires ;
		$this->view->currentProduct = $idproduct;
			
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxaccessoirelist');
	}

	public function ajaxproductannexelistbycatAction() {
		try {
			if ($this->getRequest()->isPost()) {
				$idcat = (int) $this->getRequest()->getPost('idcategory');
				$idcurrentproduct = (int) $this->getRequest()->getPost('idproduct');

				$product = new Product();
				$listproducts = $product->getProductsByIdCategory($idcat, 'NOM ASC');
				$this->view->listProducts = $listproducts;
				$this->view->currentProduct = $idcurrentproduct;

				$productAnnexe = new ProductAnnexe();
				$this->view->listAnnexes = $productAnnexe->getAnnexesByProductID($idcurrentproduct, 'NOM ASC');;
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxannexeproductlist');
	}

	public function ajaxaddproductannexeAction() {
		$productAnnexe = new ProductAnnexe();
		try {
			if ($this->getRequest()->isPost()) {
				$params = $this->_request->getPost();
				$idproduct = (int) $params['idproduct'];
				$idannexe = (int) $params['idannexe'];
				if ($idproduct > 0 && $idannexe > 0 && ($idproduct != $idannexe)) {
					$productAnnexe->insertAnnexe($idproduct, $idannexe);
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$listproducts = $productAnnexe->getAnnexesByProductID($idproduct, 'NOM ASC');
		$this->view->listProducts = $listproducts;
		$this->view->listAnnexes = $listproducts;
		$this->view->currentProduct = $idproduct;
			
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxannexeproductlist');
	}

	public function ajaxdelproductannexeAction() {
		$productAnnexe = new ProductAnnexe();
		try {
			if ($this->getRequest()->isPost()) {
				$params = $this->_request->getPost();
				$idproduct = (int) $params['idproduct'];
				$idannexe = (int) $params['idannexe'];
				if ($idproduct > 0 && $idannexe > 0 && ($idproduct != $idannexe)) {
					$productAnnexe->deleteAnnexe($idproduct, $idannexe);
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$listproducts = $productAnnexe->getAnnexesByProductID($idproduct, 'NOM ASC');
		$this->view->listProducts = $listproducts;
		$this->view->listAnnexes = $listproducts;
		$this->view->currentProduct = $idproduct;
			
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxannexeproductlist');
	}

	public function editnavheaderAction () {
		try {
			if ($this->getRequest()->isPost()) {
				$params = $this->_request->getPost();

				$filter = new Zend_Filter();
				$filter	->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringTrim());

				$filter2 = new Zend_Filter();
				$filter2->addFilter(new Zend_Filter_StringTrim())
				->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringToLower())
				->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));


				$key = $params['keywords_list'];
				$keyToAdd = "";
				
				$keyArray = explode(",", $key);
				
				$keyword = new KeyWord();
				for ($index = 0; $index < sizeof($keyArray); $index++) {
					$keyTemp = $filter2->filter($keyArray[$index]);		
					$keyTemp = $filter->filter($keyTemp);	
					if (!empty($keyTemp)) {
						if (empty($keyToAdd)) {
							$keyToAdd = $keyTemp;
						} else {
							$keyToAdd .=", ".$keyTemp;
						}
						if (!$keyword->isExist($keyTemp)) {
							$data = array( "KEYWORD" => $keyTemp);
							$keyword->insert($data);
						}
					}
				}
				$data = array (
					'NAVTITRE' => $filter->filter($params['navtitre']),
					'NAVDESC' => $filter->filter($params['navdesc']),
					'KEYWORDS' => $keyToAdd
				);
				$product = new Product();
				$product->update($data, 'ID = '.(int) $params['id']);
                $this->indexproductById((int) $params['id']);
			}				
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		$this->_forward('/edit');
	}

	public function editcustomnavnomAction() {
		try {
			if ($this->getRequest()->isPost()) {
				$params = $this->_request->getPost();

				$filter = new Zend_Filter();
				$filter	->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringTrim());
				//valideurs pour les chaines
				$validator = new Zend_Validate();
				$validator -> addValidator(new Zend_Validate_NotEmpty())
				-> addValidator(new Zend_Validate_StringLength(3));
					
				$data = array (
					'NAVNOM' => $this->verifyNavigationString($filter->filter($params['navnom']), $params['nom'], ''), 
					'CUSTOM_NAVNOM1' => $filter->filter($params['navnom_custom1']),
					'CUSTOM_NAVNOM2' => $filter->filter($params['navnom_custom2']),
					'CUSTOM_NAVNOM3' => $filter->filter($params['navnom_custom3'])
				);
					
				if ($validator->isValid($data['NAVNOM'])) {
					for ($index = 1; $index < 4; $index++) {
						if (!empty($data['CUSTOM_NAVNOM'.$index])) {
							$data['CUSTOM_NAVNOM'.$index] = $this->verifyNavigationString($data['CUSTOM_NAVNOM'.$index], $data['CUSTOM_NAVNOM'.$index], '');
						}
					}
					$product = new Product();
					$product->update($data, 'ID = '.(int) $params['id']);

                    $this->indexproductById((int) $params['id']);
					$this->view->messageSuccess = "Le nom de navigation a �t� modifi�";
				} else {
					$this->view->messageError = "Le nom de navigation n'a pas �t� modifi�";
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
			$this->view->messageError = "Le nom de navigation n'a pas �t� modifi�";
		}
		$this->_forward('/edit');
	}
	
	public function addchildqteprixAction() {
		try {
			if ($this->_request->isPost()) { 
				//filtres pour changer les chaines
				$filter = new Zend_Filter();
				$filter	->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringTrim());
	 
				$params = $this->_request->getPost();
				$min = (int) $params['min'];
				$max = (int) $params['max'];
				$prix = $filter->filter($params['prix']);
				$item_id = (int) $params['item_id'];
				
				if (isset($params['maxend'])) {
					$maxend = $params['maxend'];
					if ($maxend) { $max = 999999999; }
				} 
				
				if ($min > 0 && $max > 0 && $prix > 0 && $item_id > 0) {
					if ($min < $max) {
						$dataQte = array (
						 		'MIN' => $min,
						 		'MAX' => $max,
						 		'PRIX' => $prix,
						 		'IDPRODUCTCHILD' => $item_id 
						); 
						$productChildQte = new ProductChildQte();
						$productChildQte->insert($dataQte);
						$this->view->messageSuccess = "Le prix d�gressif a �t� ajout�";
					} else { $this->view->messageError = "V�rifier les quantit�s"; }
				} else { $this->view->messageError = "V�rifier les param�tres"; }
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
			$this->view->messageError = "Le prix d�gressif n'a pas �t� ajout�";
		}
		$this->_forward('/edit');
	} 
	
	public function delchildqteprixAction() {
		try {
			if($this->_request->getParam('item_id')) {
				$id = (int)$this->_request->getParam('item_id');
				if ($id > 0) {
					$productChildQte = new ProductChildQte();
					$isDeleted = $productChildQte->delete('ID = '.$id); 
					if ($isDeleted) {
						$this->view->messageSuccess = "Le prix d�gressif a �t� supprim�";
					} else {
						$this->view->messageError = "Le prix d�gressif n'a pas �t� supprim�";
					} 
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
			$this->view->messageError = "Le prix d�gressif n'a pas �t� supprim�";
		}
		$this->_forward('/edit');
	} 
	public function editchildqteprixactivationAction() {
		try {
			if ($this->_request->isPost()) {
				$params = $this->_request->getPost(); 
				
				$isActive = 0;
				if (isset($params['activateItemPrix'])) { $isActive = 1; }  
				
				$id = (int)$params['id'];  
				if ($id > 0) {
					$data = array (
						'isQTEPRIXACTIVE' => $isActive 
					);
					$product = new Product();
					$isUpdated = $product->update($data, 'ID = '.$id); 
					if ($isUpdated > 0) {
						$this->view->messageSuccess = "Le prix d�gressif a �t� modifi�";
					} else {
						$this->view->messageError = "Le prix d�gressif n'a pas �t� modifi�";
					} 
                    $this->indexproductById($id);
				} 
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
			$this->view->messageError = "Le prix d�gressif n'a pas �t� modifi�";
		}
		$this->_forward('/edit');
	} 
	
	public function addcaracteristiquelistAction() {
		try {
			if ($this->_request->isPost()) {
				$params = $this->_request->getPost(); 
				 
				$idoption = (int)$params['idoption'];   
				$id = (int)$params['id'];  
				if ($idoption > 0 && $id > 0) {
					$data = array (
						'ONSELECT_IDOPTION' => $idoption 
					);
					$product = new Product();
					$isUpdated = $product->update($data, 'ID = '.$id); 
					if ($isUpdated > 0) {
						$this->view->messageSuccess = "La liste des caract�ristiques a �t� modifi�";
					} else {
						$this->view->messageError = "La liste des caract�ristiques n'a pas �t� modifi�";
					} 
				} 
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
			$this->view->messageError = "La liste des caract�ristiques n'a pas �t� modifi�";
		}
		$this->_forward('/edit');
	} 
	
	public function delcaracteristiquelistAction() {
		try {
			if($this->_request->getParam('id')) {
				$id = (int)$this->_request->getParam('id');
				if ($id > 0) {
					$data = array (
						'ONSELECT_IDOPTION' => 0 
					);
					$product = new Product();
					$isUpdated = $product->update($data, 'ID = '.$id); 
					if ($isUpdated > 0) {
						$this->view->messageSuccess = "La liste des caract�ristiques a �t� modifi�";
					} else {
						$this->view->messageError = "La liste des caract�ristiques n'a pas �t� modifi�";
					} 
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
			$this->view->messageError = "La liste des caract�ristiques n'a pas �t� modifi�";
		}
		$this->_forward('/edit');
	} 
	
}
?>ErrorController.php000060400000004514150713030120010402 0ustar00<?php

class ErrorController  extends Zend_Controller_Action
{

	public function errorAction()
	{
		$errors = $this->_getParam('error_handler');
		$this->initLog();
		$exception = $errors->exception;
		$message = "Une erreure est survenue : ".$exception->getMessage().";<br/>URL : ".$this->getRequest()->getRequestUri();

		switch ($errors->type) {
			case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_CONTROLLER:
				$message .= "<br/>TYPE : Le controller n'existe pas";
				break;
			case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_NO_ACTION:
				$message .= "<br/>TYPE : Page introuvable";
				break;
			case Zend_Controller_Plugin_ErrorHandler::EXCEPTION_OTHER:
				switch ($exception) {
					case 'Zend_View_Exception' :
						$message = "<br/>TYPE : 500 : Erreur de traitement d'une vue";
						break;
					case 'Zend_Db_Exception' :
						$message.= "<br/>TYPE : 503 : Erreur de traitement dans la base de donn�es";
						break;
					case 'Metier_Exception' :
						$message.= "<br/>TYPE : 200 : Erreur metier";
						break;
					default:
						$message.= "<br/>TRACE : ".$exception->getTraceAsString();
						break;
				}
				break;
		}
		$message .= "<br/>USER AGENT : ".getenv("HTTP_USER_AGENT");
		$botDetector = new BotDetector();
		$isBot = $botDetector->isBot(getenv("HTTP_USER_AGENT"));
		if ($isBot != 'ERROR') {
			$message .= "<br/>Bot : ".$isBot;
			$this->log($message,'warn');
		} else {
			$this->log($message,'err');
		} 
		$this->view->title = 'Un probl�me est survenu';
        $this->_response->clearBody();
        $this->_response->clearHeaders();
        $this->_response->setHttpResponseCode(404);
	}

	private function initLog() {
		$registry = Zend_Registry::getInstance();
		$loggerDefault = $registry->get('loggerDefault');

		$controller = Zend_Controller_Front::getInstance()->getRequest();
		$loggerDefault->setEventItem('controller', $controller->getControllerName().'::'.$controller->getActionName());
			
		$registry->set('loggerDefault', $loggerDefault);
	}

	private function log($message , $level) {
		$loggerDefault = Zend_Registry::get('loggerDefault');
		if ($level == 'info') {
			$loggerDefault->info($message);
		} elseif ($level == 'err') {
			$loggerDefault->err($message);
		} elseif ($level == 'warn') {
			$loggerDefault->warn($message);
		} elseif ($level == 'crit') {
			$loggerDefault->crit($message);
		}
	}

}
?>MaintenanceController.php000060400000073461150713030120011542 0ustar00<?php

class Backoffice_MaintenanceController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Scripts";
		$this->isConnectedWithRole('isMaintenance'); 
	}
	public function indexAction()
	{

	} 
	/*
     * Image de produits - Redimmensionnement de l'image
     */
	public function resizepictureAction()
	{
       try {  
       
            echo "------------ PRODUITS ------------<br />";
           for($i = 0; $i < 500; $i++) {
                $dirname = 'items/product/'.$i;
                $this->resizepictureofdirectory($dirname);
           }
             
            echo "------------ CATEGORIES ------------<br />";
           for($i = 0; $i < 500; $i++) {
                $dirname = 'items/category/'.$i;
                $this->resizepictureofdirectory($dirname);
           }
             
            echo "------------ CATEGORIES SUBSIDIAIRES ------------<br />";
           for($i = 0; $i < 500; $i++) {
                $dirname = 'items/category2/'.$i;
                $this->resizepictureofdirectory($dirname);
           }
             
            echo "------------ FOURNISSEURS ------------<br />";
            $dirname = 'items/supplier';
            $this->resizepictureofdirectory($dirname);
       
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	} 
    
    private function resizepictureofdirectory($dirname)
	{
            $maxwidth = $this->FeaturePictureResizeWidth;
            $maxheight = $this->FeaturePictureResizeHeight;
           if (is_dir($dirname)) {
		        $dir_handle = opendir($dirname);
		        if (!isset($dir_handle)) {
		            return false;
                }
		        while($file = readdir($dir_handle)) {
			        if ($file != "." && $file != "..") {
                        $fileoriginal = $dirname."/".$file;
				        if (is_dir($fileoriginal)) {
                            $this->resizepictureofdirectory($fileoriginal);
                        } else {
                            
                            $info = getimagesize($fileoriginal) ;
                            list($width_old, $height_old) = $info;
                            
                            if ($width_old > $maxwidth || $height_old > $maxheight) {
                                echo "Redimensionnement de l'image : ".$fileoriginal." (Width : Old - ".$width_old." Max - ".$maxwidth.", Height : Old - ".$height_old." Max - ".$maxheight.")<br />";
                               Utils_Tool::smart_resize_image($fileoriginal , null, $maxwidth , $maxheight , true , $fileoriginal , true , false ,50 );
                            }
    
                        }
			        }
		        }
           }
    }
	/*
     * Image de produits - Renommage des nom de type date
     */
    
    function cleanproductimagenamedeterminename($row){        
        $newName = "";    
        if (empty($newName) && !empty($row['STRING1']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($row['STRING1']).".".$extension)) {
            $newName = $this->generateNavigationString($row['STRING1']);
        } else if (empty($newName) && !empty($row['STRING2']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($row['STRING2']).".".$extension)) {
            $newName = $this->generateNavigationString($row['STRING2']);
        } else if (empty($newName) && !empty($row['CUSTOM_NAVNOM1']) && !file_exists($repertoireDestination."/".$row['CUSTOM_NAVNOM1'].".".$extension)) {
            $newName = $row['CUSTOM_NAVNOM1'];
        } else if (empty($newName) && !empty($row['NAVNOM']) && !file_exists($repertoireDestination."/".$row['NAVNOM'].".".$extension)) {
            $newName = $row['NAVNOM'];
        }
    }
    
	function cleanproductimagenameAction()
	{
        $pattern = "/items\/product\/[0-9]*\/[0-9]{2}-[0-9]{2}-[0-9]{4}_[0-9]{2}-[0-9]{2}-[0-9]{2}.\w*/";
        
        $i = 0;
        try {
            $picture = new Picture();
            $sqlDoublon = "SELECT COUNT(*) AS nbr_doublon, p.URL AS URL FROM picture p GROUP BY p.URL HAVING COUNT(*) > 1";    
            $datas = $picture->getAdapter()->fetchAll($sqlDoublon);
            foreach($datas as $row)
            {
                $urlToUpdate = $row['URL'];
                
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                    
                    $sqlPicDoublon = "SELECT pic.STRING1 AS STRING1, p.NAVNOM AS NAVNOM, pic.STRING2 AS STRING2, p.CUSTOM_NAVNOM1 AS CUSTOM_NAVNOM1, p.ID AS ID,pic.ID AS IDPICTURE, pic.URL AS URL FROM picture pic LEFT JOIN product AS p ON p.ID = pic.IDPRODUCT LEFT JOIN category AS c ON c.ID = p.IDCATEGORY WHERE pic.URL='".$urlToUpdate."' order by p.IDCATEGORY";
                    
                    $datasDoublons = $picture->getAdapter()->fetchAll($sqlPicDoublon);
                    
                    $newName = "";   
                    
                    foreach($datasDoublons as $rowDoublon)
                    {
                        $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                        
                        $elementsChemin = pathinfo($urlToUpdate);
                        $extension = strtolower($elementsChemin['extension']);
                           
                        if (empty($newName) && !empty($rowDoublon['STRING1']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($rowDoublon['STRING1']).".".$extension)) {
                            $newName = $this->generateNavigationString($rowDoublon['STRING1']);
                        } else if (empty($newName) && !empty($rowDoublon['STRING2']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($rowDoublon['STRING2']).".".$extension)) {
                            $newName = $this->generateNavigationString($rowDoublon['STRING2']);
                        } else if (empty($newName) && !empty($rowDoublon['CUSTOM_NAVNOM1']) && !file_exists($repertoireDestination."/".$rowDoublon['CUSTOM_NAVNOM1'].".".$extension)) {
                            $newName = $rowDoublon['CUSTOM_NAVNOM1'];
                        } else if (empty($newName) && !empty($rowDoublon['NAVNOM']) && !file_exists($repertoireDestination."/".$rowDoublon['NAVNOM'].".".$extension)) {
                            $newName = $rowDoublon['NAVNOM'];
                        }
                        
                        if (!empty($newName)) {
                            $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                            if (!file_exists($repertoireDestination)) {
                                rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                            }
                            
                            $data = array();
                            $data['URL'] = $repertoireDestination;
                            $picture->update($data, 'ID = '.$rowDoublon['IDPICTURE']);                       
                            
                            $i++;
                            echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$rowDoublon['IDPICTURE']."<br />";
                            
                        }
                    }
                }
            }
            $sql = "SELECT pic.STRING1 AS STRING1, p.NAVNOM AS NAVNOM, pic.STRING2 AS STRING2, p.CUSTOM_NAVNOM1 AS CUSTOM_NAVNOM1, p.ID AS ID,pic.ID AS IDPICTURE, pic.URL AS URL FROM picture pic LEFT JOIN product AS p ON p.ID = pic.IDPRODUCT LEFT JOIN category AS c ON c.ID = p.IDCATEGORY order by p.IDCATEGORY";
            $datas = $picture->getAdapter()->fetchAll($sql);
            foreach($datas as $row)
            { 
                $urlToUpdate = $row['URL'];
                               
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                                    
                    $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                    
                    $elementsChemin = pathinfo($urlToUpdate);
                    $extension = strtolower($elementsChemin['extension']);
                    
                    $newName = "";    
                    if (empty($newName) && !empty($row['STRING1']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($row['STRING1']).".".$extension)) {
                        $newName = $this->generateNavigationString($row['STRING1']);
                    } else if (empty($newName) && !empty($row['STRING2']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($row['STRING2']).".".$extension)) {
                        $newName = $this->generateNavigationString($row['STRING2']);
                    } else if (empty($newName) && !empty($row['CUSTOM_NAVNOM1']) && !file_exists($repertoireDestination."/".$row['CUSTOM_NAVNOM1'].".".$extension)) {
                        $newName = $row['CUSTOM_NAVNOM1'];
                    } else if (empty($newName) && !empty($row['NAVNOM']) && !file_exists($repertoireDestination."/".$row['NAVNOM'].".".$extension)) {
                        $newName = $row['NAVNOM'];
                    }
                    
                    if (!empty($newName)) {
                        $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                        
                        rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                        
                        $data = array();
                        $data['URL'] = $repertoireDestination;
                        $picture->update($data, 'ID = '.$row['IDPICTURE']);                       
                        
                        $i++;
                        echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$row['IDPICTURE']."<br />";
                        
                    }
                } 
            }
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
    
	/*
     * Image de cat�gories subsidiaire - Renommage des nom de type date
     */    
	function cleancategorysubsimagenameAction()
	{
        $pattern = "/items\/category2\/[0-9]*\/[0-9]{2}-[0-9]{2}-[0-9]{4}_[0-9]{2}-[0-9]{2}-[0-9]{2}.\w*/";
        
        $i = 0;
        try {
            $category = new Category2();
            $sqlDoublon = "SELECT COUNT(*) AS nbr_doublon, c.URL AS URL FROM category2 c GROUP BY c.URL HAVING COUNT(*) > 1";    
            $datas = $category->getAdapter()->fetchAll($sqlDoublon);
            foreach($datas as $row)
            {
                $urlToUpdate = $row['URL'];
                
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                    
                    $sqlPicDoublon = "SELECT c.URL AS URL, c.ID AS ID, c.NAVNOM AS NAVNOM FROM category2 AS c WHERE c.URL='".$urlToUpdate."'";
                    
                    $datasDoublons = $category->getAdapter()->fetchAll($sqlPicDoublon);
                    
                    $newName = "";   
                    
                    foreach($datasDoublons as $rowDoublon)
                    {
                        $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                        
                        $elementsChemin = pathinfo($urlToUpdate);
                        $extension = strtolower($elementsChemin['extension']);
                        
                        if (empty($newName)) {
                            $newName = $rowDoublon['NAVNOM'];
                        }  
                        
                        if (!empty($newName)) {
                            $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                            if (!file_exists($repertoireDestination)) {
                              rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                            }
                            
                            $data = array();
                            $data['URL'] = $repertoireDestination;
                            $category->update($data, 'ID = '.$rowDoublon['ID']);                       
                            
                            $i++;
                            echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$rowDoublon['ID']."<br />";
                            
                        }
                    }
                }
            }
            $sql = "SELECT c.URL AS URL, c.ID AS ID, c.NAVNOM AS NAVNOM FROM category2 AS c";
            $datas = $category->getAdapter()->fetchAll($sql);
            foreach($datas as $row)
            { 
                $urlToUpdate = $row['URL'];
                
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                    
                    $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                    
                    $elementsChemin = pathinfo($urlToUpdate);
                    $extension = strtolower($elementsChemin['extension']);
                    
                    $newName = "";    
                    if (empty($newName) && !empty($row['NAVNOM']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($row['NAVNOM']).".".$extension)) {
                        $newName = $row['NAVNOM'];
                    } 
                    
                    if (!empty($newName)) {
                        $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                        
                       rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                        
                        $data = array();
                        $data['URL'] = $repertoireDestination;
                        $category->update($data, 'ID = '.$row['ID']);                       
                        
                        $i++;
                        echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$row['ID']."<br />";
                        
                    }
                } 
            }
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
    
    
	/*
     * Image de fournisseur - Renommage des nom de type date
     */    
	function cleansupplierimagenameAction()
	{
        $pattern = "/items\/supplier\/[0-9]{2}-[0-9]{2}-[0-9]{4}_[0-9]{2}-[0-9]{2}-[0-9]{2}.\w*/";
        
        $i = 0;
        try {
            $supplierBrend = new SupplierBrend();
            $sql = "SELECT c.URL AS URL, c.ID AS ID, c.BREND AS BREND FROM supplier_brend AS c";
            $datas = $supplierBrend->getAdapter()->fetchAll($sql);
            foreach($datas as $row)
            { 
                $urlToUpdate = $row['URL'];
                
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                    
                    $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                    
                    $elementsChemin = pathinfo($urlToUpdate);
                    $extension = strtolower($elementsChemin['extension']);
                    
                    $newName = $this->generateNavigationString($row['BREND']);    
                    if (!empty($newName) && file_exists($repertoireDestination."/".$newName.".".$extension)) {
                        $newName = "";
                    } 
                    
                    if (!empty($newName)) {
                        $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                        
                       rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                        
                        $data = array();
                        $data['URL'] = $repertoireDestination;
                        $supplierBrend->update($data, 'ID = '.$row['ID']);                       
                        
                        $i++;
                        echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$row['ID']."<br />";
                        
                    }
                } 
            }
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
    
	/*
     * Image de cat�gories - Renommage des nom de type date
     */
    
	function cleancategoryimagenameAction()
	{
        $pattern = "/items\/category\/[0-9]*\/[0-9]{2}-[0-9]{2}-[0-9]{4}_[0-9]{2}-[0-9]{2}-[0-9]{2}.\w*/";
        
        $i = 0;
        try {
            $category = new Category();
            $sqlDoublon = "SELECT COUNT(*) AS nbr_doublon, c.URL AS URL FROM category c GROUP BY c.URL HAVING COUNT(*) > 1";    
            $datas = $category->getAdapter()->fetchAll($sqlDoublon);
            foreach($datas as $row)
            {
                $urlToUpdate = $row['URL'];
                
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                    
                    $sqlPicDoublon = "SELECT c.URL AS URL, c.ID AS ID, c.NAVNOM AS NAVNOM FROM category AS c WHERE c.URL='".$urlToUpdate."'";
                    
                    $datasDoublons = $category->getAdapter()->fetchAll($sqlPicDoublon);
                    
                    $newName = "";   
                    
                    foreach($datasDoublons as $rowDoublon)
                    {
                        $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                        
                        $elementsChemin = pathinfo($urlToUpdate);
                        $extension = strtolower($elementsChemin['extension']);
                        
                        if (empty($newName)) {
                            $newName = $rowDoublon['NAVNOM'];
                        }  
                        
                        if (!empty($newName)) {
                            $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                            if (!file_exists($repertoireDestination)) {
                                rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                            }
                            
                            $data = array();
                            $data['URL'] = $repertoireDestination;
                            $category->update($data, 'ID = '.$rowDoublon['ID']);                       
                            
                            $i++;
                            echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$rowDoublon['ID']."<br />";
                            
                        }
                    }
                }
            }
            $sql = "SELECT c.URL AS URL, c.ID AS ID, c.NAVNOM AS NAVNOM FROM category AS c";
            $datas = $category->getAdapter()->fetchAll($sql);
            foreach($datas as $row)
            { 
                $urlToUpdate = $row['URL'];
                
                if (preg_match($pattern, $urlToUpdate, $match) && file_exists($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate)) {
                    
                    $repertoireDestination = substr($urlToUpdate, 0, strrpos($urlToUpdate, '/'));
                    
                    $elementsChemin = pathinfo($urlToUpdate);
                    $extension = strtolower($elementsChemin['extension']);
                    
                    $newName = "";    
                    if (empty($newName) && !empty($row['NAVNOM']) && !file_exists($repertoireDestination."/".$this->generateNavigationString($row['NAVNOM']).".".$extension)) {
                        $newName = $row['NAVNOM'];
                    } 
                    
                    if (!empty($newName)) {
                        $repertoireDestination = $repertoireDestination."/".$newName.".".$extension;
                        
                        rename($_SERVER['DOCUMENT_ROOT']."/".$urlToUpdate, $_SERVER['DOCUMENT_ROOT']."/".$repertoireDestination);
                        
                        $data = array();
                        $data['URL'] = $repertoireDestination;
                        $category->update($data, 'ID = '.$row['ID']);                       
                        
                        $i++;
                        echo "Ancien : ".$urlToUpdate." => Nouveau : ".$repertoireDestination." => ID : ".$row['ID']."<br />";
                        
                    }
                } 
            }
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
    
    
    
	/*
     * Product - Designation reference - strip_tags
     */
	function cleanproductdesignationreferenceAction()
	{
		$i = 0;
        try {
            $productChild = new ProductChild();        
            $sql = "SELECT p.ID, p.DESIGNATION FROM productchild p";
            $datas = $productChild->getAdapter()->fetchAll($sql);
            $data = array();
            foreach($datas as $row)
            { 
                $row['DESIGNATION'] = strip_tags($row['DESIGNATION']);
                $productChild->update($row, 'ID = '.$row['ID']);
                $i++;
            }   
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
	/*
     * Category - NAVNOM_URLPARENTS - Initialisation
     */
	function generatecategoryurlaccessAction()
	{
		$i = 0;
		try {
            $category = new Category();        
            $sql = "SELECT c.ID ID, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS FROM category c ORDER BY c.NOM ASC ";
            $cats = $category->getAdapter()->fetchAll($sql);
            $data = array();
            foreach($cats as $row)
            { 
                $row['NAVNOM_URLPARENTS'] = $category->getTreeInLineAsPathOf($row['ID']);
                $category->update($row, 'ID = '.$row['ID']);
				$i++;
            }   
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	}
    
	/*
     * Category2 - NAVNOM_URLPARENTS - Initialisation
     */
	function generatecategory2urlaccessAction()
	{
		$i = 0;
		try {
            $category = new Category2();        
            $sql = "SELECT c.ID ID, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS FROM category2 c ORDER BY c.NOM ASC ";
            $cats = $category->getAdapter()->fetchAll($sql);
            $data = array();
            foreach($cats as $row)
            { 
                $row['NAVNOM_URLPARENTS'] = $category->getTreeInLineAsPathOf($row['ID']);
                $category->update($row, 'ID = '.$row['ID']);
				$i++;
            }   
			$this->view->messageSuccess = $i." SUCCESS";
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	}

	/*
	 * Produits - NAVNOM - Formatage
	 */
	public function generatenavnomproductAction(){
		$i = 0;
		try {
			$sql = 'SELECT p.ID ID, p.NOM NOM, p.NAVNOM NAVNOM FROM product p';
			$product = new Product();
			$productList = $product->getAdapter()->fetchAll($sql);
			foreach ($productList AS $row) {
				$navnom = $this->generateNavigationString($row['NOM']);
				$data = array ( 'NAVNOM' => $navnom );
				$product->update($data, 'ID = '.$row['ID']);
				$i++;
			}
			$this->view->messageSuccess = $i." SUCCESS";
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	}

	/*
	 * Categories - NAVNOM - Formatage
	 */
	public function generatenavnomcategorieAction(){
		$i = 0;
		try {
			$sql = 'SELECT c.ID ID, c.NOM NOM, c.URL URL, c.NAVNOM NAVNOM FROM category c';
			$category = new Category();
			$catsList = $category->getAdapter()->fetchAll($sql);
			foreach ($catsList AS $row) {
				$navnom = $this->generateNavigationString($row['NOM']);
				$data = array ( 'NAVNOM' => $navnom );
				$category->update($data, 'ID = '.$row['ID']);
				$i++;
			}
			$this->view->messageSuccess = $i." SUCCESS";
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	}

	/*
	 * Categories - NAVNOM - Retire certains char.
	 */
	public function deletecaracspecialAction(){
		$i = 0;
		try {
			$sql = 'SELECT c.ID ID, c.NOM NOM, c.URL URL, c.NAVNOM NAVNOM FROM category c';
			$category = new Category();
			$catsList = $category->getAdapter()->fetchAll($sql);

			foreach ($catsList AS $row) {
				$navnom = $this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$data = array ( 'NAVNOM' => $navnom );
				$category->update($data, 'ID = '.$row['ID']);
				$i++;
			}
			$this->view->messageSuccess = $i." SUCCESS";
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	}

	/*
	 * User - Paiement - Verification
	 */
	public function usercheckAction(){
		$i = 0;
		try {
			$sql = 'SELECT * FROM user WHERE MODEPAIEMENT = 6';
			$user = new User();
			$list = $user->getAdapter()->fetchAll($sql);

			foreach ($list AS $row) {
				$data = array ( 'isRECEPFACTURE' => 'Y' );
				$user->update($data, 'ID = '.$row['ID']);
				$i++;
			}
			$this->view->messageSuccess = $i." SUCCESS";
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
	}
    

	/*
	 * Produit inactif => Produit actif + Disponibilit� : Epuis�
	 */
    function productchangeinactivetoepuiseAction() {
        $i = 0;
		try {
			$sql = 'SELECT * FROM product WHERE isActive = 1';
			$product = new Product();
			$list = $product->getAdapter()->fetchAll($sql);

			foreach ($list AS $row) {
				$data = array ( 'isActive' => 0,  'STOCK' => 4);
				$product->update($data, 'ID = '.$row['ID']);
				$i++;
			}
			$this->view->messageSuccess = $i." SUCCESS";
		}
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
    


	/*
      Calcul des meilleures ventes
	 */
    function productcomputebestsellerAction() {
        $i = 0;
		try {
			$product = new Product();
			$data = array ( 'BOOSTED_BESTSELLER' => 99999);
			$product->update($data, 'ID > 0 ');  
			$sql = 'SELECT p.ID, p.NOM, sum(cp.CHILDPRIXTOTAL) TOTAL FROM product p
                    LEFT JOIN command_product cp ON cp.productid = p.id
                    LEFT JOIN command c ON cp.IDCOMMAND = c.id
                    where c.STATUT <> 0
                    group by p.ID
                    order by TOTAL desc';
			$list = $product->getAdapter()->fetchAll($sql);
            $number = 1;
			foreach ($list AS $row) {
				$data = array ( 'BOOSTED_BESTSELLER' => $number);
				$product->update($data, 'ID = '.$row['ID']);
                $number++;
				$i++;
			}
			$this->view->messageSuccess = $i." SUCCESS";
		}
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
    
	
	/*
	 * Met le site en maintenance
	 */
	public function switchtomaintenanceAction() {
		$this->view->messageError = "Non disponible";
		$this->render('message');
	}
    
    /*
    ElasticSearch
    */
     
     
    function elasticsearchglobaleindeaxationAction() {
        $i = 0;
		try { 
            
            //Envoi a Elasticsearch        
            $soapClient = $this->getSoapClient($this->FeatureElasticSearchWsdl);
            $result = new stdClass();
            try
            {     
                $request = $this->getSoapHeader($this->FeatureElasticSearchUsername, $this->FeatureElasticSearchKey);
                
                $parameters = new stdClass();
                $parameters->request = $request;
                $soapClient->PushGlobalProducts($parameters);
            }
            catch (SoapFault $fault)
            {
	            echo "Fault code: {$fault->faultcode}";
	            echo "Fault string: {$fault->faultstring}";
            }
            $soapClient = null;   
			$this->view->messageSuccess = $i." SUCCESS";
		}
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
			$this->view->messageError = "Erreur de script : ".$e->getMessage();
		}
		$this->render('message');
    }
}
FidelitypointController.php000060400000010773150713030120012140 0ustar00<?php
class Backoffice_FidelitypointController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "User";
		$this->isConnectedWithRole('isUser');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier la carte fid�lit�";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty());

		$annonce = new CarteFidelite();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'POINTFIDELITE' => (int)$params['fidelitypoint'],
			 		'isSHOW' => $params['isshow']
			);

			if ($validator->isValid($dataAnnonce['TITRE']) &&
			$validator->isValid($dataAnnonce['CONTENT'])
			) {
				try {
					$id = (int)$params['id'];
					if ( $id > 0) {
							
						$annonce->update($dataAnnonce,'ID = '.$id);
						$this->view->messageSuccess = "L'offre a �t� modifi�e";
						$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
						$this->log("L'offre a �t� modifi�e : ".$id,'info');
					}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->populateFormAnnonce = $dataAnnonce;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormAnnonce = $dataAnnonce;
			}

		}
		$this->_forward('/list');
	}

	public function addAction() {
			
		$this->view->titlePage = "Ajouter une offre";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'POINTFIDELITE' => (int)$params['fidelitypoint'],
			 		'isSHOW' => $params['isshow']
			);
			if (
			$validator->isValid($dataAnnonce['TITRE']) &&
			$validator->isValid($dataAnnonce['CONTENT'])
			) {
				try {
					$annonce = new CarteFidelite();
					$annonce->insert($dataAnnonce);
					$this->view->messageSuccess = "L'offre a �t� ajout�e";
					$this->log("L'offre a �t� ajout�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->populateFormAnnonce = $dataAnnonce;
				}

			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormAnnonce = $dataAnnonce;
			}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion de la carte fid�lit�";
		$adminNamespace = $this->getSession();
			
		//Appel model pour listing
		$annonces = new CarteFidelite();
		$result = $annonces->select()->order('isSHOW ASC')->order('POINTFIDELITE ASC')->query()->fetchAll();
			
		$this->view->listannonce = $result;
	}

	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new CarteFidelite();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'offre a �t� supprim�e";
					$this->log("L'offre a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');
	}

}
?>AnnoncefrontController.php000060400000010743150713030120011744 0ustar00<?php
class Backoffice_AnnoncefrontController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "AnnonceFront";
		$this->isConnectedWithRole('isPromo');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty());

		$annonce = new AnnonceFrontHeader();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonceFront = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow']
					);

					if ($validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT'])
					) {
						try {
							$id = (int)$params['id'];
							if ( $id > 0) {
									
								$annonce->update($dataAnnonce,'ID = '.$id);
								$this->view->messageSuccess = "L'information a �t� modifi�e";
								$this->view->populateFormAnnonceFront = $annonce->fetchRow('ID = '.$id);
								$this->log("L'information a �t� modifi�e ".$id,'info');
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceFront = $dataAnnonce;
						}
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError =  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceFront = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}


	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow']
					);
					if (
					$validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT'])
					) {
						try {
							$annonce = new AnnonceFrontHeader();
							$annonce->insert($dataAnnonce);
							$this->view->messageSuccess = "L'information a �t� ajout�e";
							$this->log("L'information a �t� ajout�e",'info');
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceFront = $dataAnnonce;
						}

					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceFront = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des informations sur la page d'accueil"; 
		
		//Appel model pour listing
		$annonces = new AnnonceFrontHeader();
		$result = $annonces->getAllAnnonces();
			
		$this->view->listannoncefront = $result;
	}



	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceFrontHeader();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'information a �t� supprim�e";

					$this->log("L'information a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}

}
?>Category2Controller.php000060400000040105150713030120011144 0ustar00<?php

class Backoffice_Category2Controller extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "CategorySubs";
 
		$this->isConnectedWithRole('isCategory'); 
        
        
		$category = new Category2();
		$this->view->listallcategories2 = $category->getAllCategoriesByID(0);
	}
	function indexAction()
	{
		$this->_forward('/list');
	}
    
    /*
     * Duplicat de CategoryController
     */

	function listAction()
	{
		$this->view->titlePage = "Gestion des cat�gories subsidiaires";
        
		//Gestion des tris
		$table = 'NOM';
		$tri = 'ASC';
	}

	function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$category = new Category2();
					if ($category->fetchRow('IDPARENT = '.$id)) {
						$this->view->messageError = 'Cette cat�gorie est parente';
					} else {
						$productCategory2 = new ProductCategory2();
						$select = $productCategory2->getAllProductsByCategoryID($id);
						if (isset($select) && !empty($select)) {
							$this->view->messageError = 'Cette cat�gorie est utilis�e par le produit : <b>'.$select[0]['NOM']."</b>";
						} else {

							$category->delete('ID = '.$id);

							$this->delete_directory('items/category2/'.$id);

							$this->view->messageSuccess = "La cat�gorie a et� supprim�e";
							$this->log("La cat�gorie a et� supprim�e",'info');

						}
					}
				}
                catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');

	}

	function editAction() {
		$this->view->titlePage = "Modifier une cat�gorie subsidiaire";
		//populate form
		if ($this->_request->getParam('id')) { $id = (int)$this->_request->getParam('id'); }
		if ($this->_request->getParam('idCat')) { $id = (int)$this->_request->getParam('idCat'); }

		if ($id > 0) {
			$category = new Category2();
			$row = $category->fetchRow('ID = '.$id);
			if ($row) {
				$this->view->populateForm = $row->toArray();
                
				$listCat = array();
				$listCat = $category->getTreeCatsOf($id);
				if (!empty($listCat) && !$listCat['SUBS']) {
					$categoryTypeTri = new CategoryTypeTri();
					$this->view->listNavigationTri = $categoryTypeTri->getListTriByCategoryInOneRow($id);
				}
			} else { $this->_forward('/list'); }
		} else {
			$this->_forward('/list');
		}
	}

	function editcategoryAction()
	{
        
		$this->view->titlePage = "Modifier une cat�gorie subsidiaire";
		$id = 0;
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
					'IDPARENT' => $filter->filter($params['idparent']),
			 		'DESCRIPTION' => $filter->filter($params['desc']), 
			 		'CHOICEDOC' => $filter->filter($params['docChoice'])
			);

			if ($validator->isValid($data['NOM'])) {

				try {

					$id = $params['id'];

					$category = new Category2();
					$category->update($data, 'ID = '.$id);

					$this->view->messageSuccess = "La cat�gorie a �t� modifi�e";
					if($this->uploadNewPics($id)) {
						$this->view->messageSuccess .= " , l'image aussi";
					}

					if($this->uploadNewChoicePics($id)) {
						$this->view->messageSuccess .= " , le comment choisir aussi";
					}
                    $nbSubs = $category->updateTreeInLineAsPathOfChilds($id, true);

					$this->view->messageSuccess .= " , ".$nbSubs." urls d'acc�s modifi�es.";

					$this->log("La cat�gorie a �t� modifi�e : ".$id,'info');

				}
                catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La cat�gorie existe d�j�";
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
			}

		}
		$this->_forward('/edit');
	}

	function customnavnomeditAction()
	{
		$this->view->titlePage = "Modifier une cat�gorie subsidiaire";
		$id = 0;
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$navnom = $this->verifyNavigationString($filter->filter($params['navnom']), $params['nom'], '');

			$keywords = "";
			if (isset($params['keywords']) && !empty($params['keywords'])) {
				$keywords = $params['keywords'];
			} else {
				$navnomStrip =  explode("-", $navnom);
				for ($index = 0; $index < sizeof($navnomStrip); $index++) {
					$word = $navnomStrip[$index];
					if (empty($keywords)) {
						if (strlen($word) > 3){ $keywords .= $word; }
					} else {
						if (strlen($word) > 3){ $keywords .= ",".$word; }
					}
				}
			}

			//Refractor the params
			$data = array (
					'NAVTITRENOM' => $filter->filter($params['navtitrenom']),
			 		'NAVNOM' => $navnom,
					'KEYWORDS' => $keywords,
					'NAVDESCRIPTION' => $filter->filter($params['navdescription'])  
			);

			if ($validator->isValid($data['NAVNOM']) &&
			$validator->isValid($data['KEYWORDS'])) {
				if (empty($data['NAVTITRENOM'])) {
					$data['NAVTITRENOM'] = $filter->filter($params['nom']);
				}
				if (empty($data['NAVDESCRIPTION'])) {
					$data['NAVDESCRIPTION'] = "";
				}
				try {
					$id = $params['id'];

					$category = new Category2();
                    
                    if (isset($params['urlaccess']) && $params['idparent'] == 0) {
                        $data['NAVNOM_URLPARENTS'] = $this->verifyNavigationString('',$filter->filter($params['urlaccess']), '');
                    }
                    
                    if (empty($data['NAVNOM_URLPARENTS'])) {
                        $data['NAVNOM_URLPARENTS'] = $category->getTreeInLineAsPathOf($id);
                    }
                    
					$category->update($data, 'ID = '.$id);

                    $nbSubs = $category->updateTreeInLineAsPathOfChilds($id, false);
                    
					$this->view->messageSuccess = "La cat�gorie a �t� modifi�e, ".$nbSubs." urls d'acc�s modifi�es.";

				}
                catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La cat�gorie existe d�j�";
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}

		}
		$this->_forward('/edit');
	}

	function editactiveAction()
	{
		$this->view->titlePage = "Modifier une cat�gorie subsidiaire";
		if ($this->_request->isPost()) {
			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$data = array (
			 		'isACTIVE' => $params['active']
			);

			try {

				$id = (int)$params['id'];

				$category = new Category2();
				$category->update($data, 'ID = '.$id);
                          
			}
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(),'err');
				$this->log($e->getMessage(),'err');
			}
		}
		$this->_forward('/edit');
	}

	function addAction()
	{
        
		$this->view->titlePage = "Ajouter une cat�gorie subsidiaire";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
        
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$navnom = $this->verifyNavigationString($filter->filter($params['navnom']), $params['nom'], '');

			$keywords = "";
			if (isset($params['keywords']) && !empty($params['keywords'])) {
				$keywords = $params['keywords'];
			} else {

				$navnomStrip =  explode("-", $navnom);
				for ($index = 0; $index < sizeof($navnomStrip); $index++) {
					$word = $navnomStrip[$index];
					if (empty($keywords)) {
						if (strlen($word) > 3){ $keywords .= $word; }
					} else {
						if (strlen($word) > 3){ $keywords .= ",".$word; }
					}
				}
			}

			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
					'NAVTITRENOM' => $filter->filter($params['nom']),
			 		'DESCRIPTION' => $filter->filter($params['desc']),
			 		'NAVDESCRIPTION' => $filter->filter($params['desc']),
			 		'NAVNOM' => $navnom,
			 		'KEYWORDS' => $keywords,
			 		'IDPARENT' => $filter->filter($params['idparent'])
			);
			if ($validator->isValid($data['NOM']) &&
			$validator->isValid($data['NAVNOM'])
			) {
				try {
					$category = new Category2();
                    $data['NAVNOM_URLPARENTS'] = $category->getTreeInLineAsPathOf($data['IDPARENT']);
					$category->insert($data);

					//create items folder for pics
					$lastid = $category->getAdapter()->lastInsertId();

					if ($lastid > 0) {
						mkdir ("items/category2/".$lastid, 0777);
						$this->view->messageSuccess = "La cat�gorie a �t� ajout�e";
						if($this->uploadNewPics($lastid)) {
							$this->view->messageSuccess .= " , l'image a �t� upload�";
						}

						$this->log("La cat�gorie a �t� ajout�e",'info');
					}
				}
                catch (Zend_Exception $e) {
					$this->view->messageError = "La cat�gorie existe d�j�";
					$this->log($e->getMessage(),'err');
					$this->view->populateForm = $data;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateForm = $data;
			}
		}
	}
	function uploadNewPics($idCat) {
		if(!empty($_FILES['picCat']) && !empty($_FILES['picCat']['name'])) {
			$nomOrigine = $_FILES['picCat']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				// incluant l'heure a la seconde pres
				$repertoireDestination = 'items/category2/'.$idCat.'/';
				$this->checkDirectoryExist($repertoireDestination);
				
                $nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
                $fileoriginal = $repertoireDestination.$nomDestination;
				if (move_uploaded_file($_FILES["picCat"]["tmp_name"],$fileoriginal)) {
					try {
						$category = new Category2();
						$data = array (
					 		'URL' => $fileoriginal
						);
						$category->update($data,'ID = '.$idCat);

                         //Resize picture
                        $info = getimagesize($fileoriginal) ;
                        list($width_old, $height_old) = $info;
                        $maxwidth = $this->FeaturePictureResizeWidth;
                        $maxheight = $this->FeaturePictureResizeHeight;
                            
                        if ($width_old > $maxwidth || $height_old > $maxheight) {     
                            Utils_Tool::smart_resize_image($fileoriginal , null, $maxwidth , $maxheight , true , $fileoriginal , true , false ,50 );
                        }  
                        
						return true;
					}
                    catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
						return false;
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		}

		return false;
	}

	function uploadNewChoicePics($idCat) {
		if(!empty($_FILES['picChoice']) && !empty($_FILES['picChoice']['name'])) {
			$nomOrigine = $_FILES['picChoice']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				// incluant l'heure a la seconde pres
				$repertoireDestination = 'items/category_choice2/'.$idCat.'/';
				$this->checkDirectoryExist($repertoireDestination);
				
				$date = new Zend_Date();
                
				//$nomDestination = $date->toString('dd-MM-YYYY_HH-mm-ss').".".$extensionFichier;
                $nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
                
				if (move_uploaded_file($_FILES["picChoice"]["tmp_name"],$repertoireDestination.$nomDestination)) {
					try {
						$category = new Category2();
						$data = array (
					 		'CHOICEURL' => $repertoireDestination.$nomDestination
						);
						$category->update($data,'ID = '.$idCat);

						return true;
					}
                    catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
						return false;
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		}

		return false;
	}
	function setpictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$category = new Category2();
				$data = array (
				 		'URL' => $params['picture']
				);
				$category->update($data,'ID = '.$params['idCat']);
				$this->view->messageSuccess = "L'image a �t� modifi�e";
			}
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}

	function erasepictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();

			try {
				$category = new Category2();

				unlink($params['picture']);
				$data = array (
			 		'URL' => ''
			 		);
                $category->update($data,"ID = ".$params['idCat']." AND URL = '".$params['picture']."'");
                $this->view->messageSuccess = "L'image a �t� supprim�e d�finitivement";
			}
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}


	function setpicturechoiceAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$category = new Category2();
				$data = array (
				 	'CHOICEURL' => $params['picture']
				);
				$category->update($data,'ID = '.$params['idCat']);
				$this->view->messageSuccess = "L'image a �t� modifi�e";
			}
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}

	function erasepicturechoiceAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();

			try {
				$category = new Category2();
				unlink($params['picture']);
				$data = array (
			 		'CHOICEURL' => ''
			 		);
                $category->update($data,"ID = ".$params['idCat']." AND CHOICEURL = '".$params['picture']."'");
                $this->view->messageSuccess = "L'image a �t� supprim�e d�finitivement";
			}
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}
}
?>BlogCommentController.php000060400000014400150713030120011512 0ustar00<?php
class Backoffice_BlogCommentController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
  
		$this->view->currentMenu = "BlogComment";
	} 
    
    public function indexAction()
	{
		$this->_forward('/search');
    }
    public function searchAction()
	{
        $this->view->titlePage = "Rechercher un commentaire";  
        $data = array (  
                 'message' => "",
                 'is_publish' => 0,
                 'is_close' => 0, 
                 'id_subject' => 0
        ); 
         try {
            $this->view->listSearchs = array();
		    $blogSubject = new BlogSubject();
            $this->view->listSubjects = $blogSubject->AllSubjects();
		    if ($this->_request->isPost()) {
 
		        //filtres pour changer les chaines
		        $filter = new Zend_Filter();
		        $filter	->addFilter(new Zend_Filter_StripTags())
		        ->addFilter(new Zend_Filter_StringTrim());

		        //get the form params
		        $params = $this->_request->getPost();

                $idSubject = 0;
                if (isset($params['id_subject'])) {
                    $idSubject = (int)$params['id_subject'];
                }
		        //Refractor the params
		        $data = array (  
			 	        'message' => $filter->filter($params['message']),
			 	        'is_publish' => (int)$params['is_publish'],
			 	        'is_close' => (int)$params['is_close'],
			 	        'id_subject' => $idSubject
		        ); 
					
		        $blogComment = new BlogComment();
				$this->view->listSearchs = $blogComment->search($data); 
            }
        }
        catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		} 
		$this->view->populateData = $data; 
    }
    
    

	public function addAction()
	{
        $this->view->titlePage = "Ajouter un commentaire";
        $this->view->messageSuccess = "";
        $this->view->messageError = "";

        $data = array (  
                 'is_publish' =>  1,  
                 'message' => "",
                 'pseudo' => "Administrateur", 
                 'id_subject' => 0
        );  
		try {
		    $blogSubject = new BlogSubject();
            $this->view->listSubjects = $blogSubject->AllSubjects();
		    if ($this->_request->isPost()) {

			    //filtres pour changer les chaines
			    $filter = new Zend_Filter();
			    $filter	->addFilter(new Zend_Filter_StripTags())
			    ->addFilter(new Zend_Filter_StringTrim());

			    //valideurs pour les chaines
			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());


			    //get the form params
			    $params = $this->_request->getPost();

                $id_subject =0;
                if (isset($params['id_subject'])) {
                    $id_subject = (int)$params['id_subject'];
                } 
             
			    $data = array (  
			 		    'id_subject' => $id_subject,
			 	        'is_publish' =>  (int)$params['is_publish'], 
			 		    'pseudo' => $filter->filter($params['pseudo']),
			 		    'message' => $params['message'], 
			 		    'date_updated' => date('Y-m-d H:i:s') 
			    );
			    if (
			    $validator->isValid($data['message']) &&
			    $validator->isValid($data['pseudo']) && 
                $id_subject > 0
			    ) {
		                $blogComment = new BlogComment();
					    $blogComment->insert($data);
					    $this->view->messageSuccess = "Le commentaire a �t� ajout�";

			    } else {
				    foreach ($validator->getErrors() as $errorCode) {
					    $this->view->messageError .=  $this->getErrorValidator($errorCode);
				    }
                    if ($id_subject == 0) {
					    $this->view->messageError .= "Choisissez un sujet.";
                    }
			    } 
            } 
		}
        catch (Zend_Exception $e) { 
			$this->log($e->getMessage(),'err');
		}
		$this->view->populateData = $data;
	}
    
	public function editAction()
	{
        $this->view->titlePage = "Modifier un commentaire";
        $this->view->messageSuccess = "";
        $this->view->messageError = "";
		try {
			
		    //filtres pour changer les chaines
		    $filter = new Zend_Filter();
		    $filter	->addFilter(new Zend_Filter_StripTags())
		    ->addFilter(new Zend_Filter_StringTrim());

		    //valideurs pour les chaines
		    $validator = new Zend_Validate();
		    $validator -> addValidator(new Zend_Validate_NotEmpty());

		    $blogComment = new BlogComment();
		    if ($this->getRequest()->getParam('id')) {
			    $id = (int)$this->getRequest()->getParam('id');
			    if ($id>0) {
				    $this->view->populateData = $blogComment->fetchRow('ID = '.$id);
			    }
		    }
        
		    $blogSubject = new BlogSubject();
            $this->view->listSubjects = $blogSubject->AllSubjects();

		    if ($this->getRequest()->isPost()) {

			    //get the form params
			    $params = $this->_request->getPost();
             
                $id_subject =0;
                if ((int)$params['id_subject'] > 0) {
                    $id_subject = (int)$params['id_subject'];
                } 
            
			    //Refractor the params 
			    $data = array (  
			 		    'id_subject' => $id_subject,
			 	        'is_publish' =>  (int)$params['is_publish'], 
			 		    'pseudo' => $filter->filter($params['pseudo']),
			 		    'message' => $params['message'], 
			 		    'date_updated' => date('Y-m-d H:i:s') 
			    );
            
			    if (
			    $validator->isValid($data['message']) &&
			    $validator->isValid($data['pseudo']) && 
                $id_subject > 0
			    ) {
					    $id = (int)$params['id'];
					    if ( $id > 0) {
							
						    $blogComment->update($data,'ID = '.$id); 
						    $this->view->messageSuccess = "Le commentaire a �t� modifi�";
					    }
                        $this->view->populateData = $blogComment->fetchRow('ID = '.$id);
			    } else {
				    foreach ($validator->getErrors() as $errorCode) {
					    $this->view->messageError .=  $this->getErrorValidator($errorCode);
				    }
                    $this->view->populateData = $data;
                    if ($id_subject == 0) {
					    $this->view->messageError .= "Choisissez un sujet.";
                    }
			    }
            }
		}
        catch (Zend_Exception $e) {
			$this->view->populateData = $data;
			$this->log($e->getMessage(),'err');
		}
	}
 
}
?>AnnoncegalleryController.php000060400000021724150713030120012254 0ustar00<?php
class Backoffice_AnnoncegalleryController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "AnnonceGallery";
		$this->isConnectedWithRole('isCategory');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

    public function ajaxshowallpictureAction() {
		$annonces = new AnnonceGallery();
		$result = $annonces->getAllAnnonces();
		$this->view->listAnnonceGallery = $result;

		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxshowallpicture');
    }
    

	function editpositionAction() {
		
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();
			
			$id = 0;
			$position = 0;
			$category = 0;
			if (!empty($params['id'])) { $id = (int)$params['id']; }
			if (!empty($params['position'])) { $position = (int)$params['position']; }
			if (!empty($params['category'])) { $category = (int)$params['category']; }

			if($id > 0 && $category > 0) {
				try {
					$annonce = new AnnonceGallery();
					$dataAnnonce = array (
						'POSITION' => $position
					);
					$annonce->update($dataAnnonce,'ID = '.$id); 

					$annonceList = $annonce->select()
											->where("ID <> ".$id." AND ID_CATS LIKE '%:".$category.":%'")
											->order('POSITION ASC')
											->query()->fetchAll();
					 
					$count = 0;
					foreach($annonceList as $row)
					{
						if ($count == $position) {
							$count++;
						}
						$dataAnnonce['POSITION'] = $count;
						$annonce->update($dataAnnonce,'ID = '.$row['ID']); 
						$count++;
					}
					 $this->view->messageSuccess = "Les positions ont �t� mises � jour";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err'); 
					$this->view->messageError = "La mise � jour n'a pas �t� r�alis�e";
				} 
			} 
		}

		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('message');
    }

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une image";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		$annonce = new AnnonceGallery();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonceGallery = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 	'ID' => (int)$params['id'],
			 	'NOM' => $filter->filter($params['nom']),
			 	'CONTENT' => $params['content'],
			 	'CONTENT_SHORT' => $filter->filter($params['content_short']),
			 	'CONTENT_LONG' => $params['content_long'],
			 	'POSITION' => (int) $filter->filter($params['position']),
			 	'isSHOW' => $params['isshow'],
				'ID_CATS' => ''
			);
					
			if (isset($params['categories'])) {
				foreach($params['categories'] as $value)
				{
					$dataAnnonce['ID_CATS'] .= ":".$value.":";
				}
			} 
			try {
				$id = (int)$params['id'];
				if ( $id > 0) {
									
					$annonce->update($dataAnnonce,'ID = '.$id);
					$this->view->messageSuccess = "L'image a �t� modifi�e";
                                 
					$this->uploadNewPicsAndSave($id);

					$this->view->populateFormAnnonceGallery = $annonce->fetchRow('ID = '.$id);
					$this->log("L'image a �t� modifi�e ".$id,'info');
				}
			} catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
				$this->view->populateFormAnnonceGallery = $dataAnnonce;
			} 

		}
	}
	 
    function uploadNewPicsAndSave($id) {
        $url = $this->uploadNewPics($id, 'picture');
		if(!empty($url)) {
			try {
				$annonce = new AnnonceGallery();
				$data = array (
					'URL' => $url
				);
				$annonce->update($data,'ID = '.$id);

				return true;
			} catch (Exception $e) {
				$this->view->messageError = $e->getMessage();
				return false;
			}
		}
		return false;
	}
    function uploadNewPics($idCat, $field) {
        if(!empty($_FILES[$field]) && !empty($_FILES[$field]['name'])) {
			$nomOrigine = $_FILES[$field]['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				$repertoireDestination = 'items/gallery/'.$idCat.'/';
				$this->checkDirectoryExist($repertoireDestination);
				
                $nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
				$fileoriginal = $repertoireDestination.$nomDestination;
                
				if (move_uploaded_file($_FILES[$field]["tmp_name"],$fileoriginal)) {
                        //Resize picture
                        $fileResizedName = $repertoireDestination.$this->generateNavigationString($elementsChemin['filename']);
                        
                        //Admin
                        Utils_Tool::smart_resize_image($fileoriginal , null, 100 , null , true , $fileResizedName."_100.".$extensionFichier , false , false ,80 ); 
                                
                        if (isset($this->FeatureSiteThemeCms) && !empty($this->FeatureSiteThemeCms)) { 
		                    foreach ($this->FeatureSiteThemeCms as $row) { 
                                if (isset($row['WIDTH_THUMB']) && $row['WIDTH_THUMB'] > 0) {
                                    Utils_Tool::smart_resize_image($fileoriginal , null, $row['WIDTH_THUMB'] , null , true , $fileResizedName."_".$row['WIDTH_THUMB'].".".$extensionFichier , false , false ,80 ); 
                                }
                            } 
	                    }

					return $repertoireDestination.$nomDestination;
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		}
		return "";
    }

	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une image";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'CONTENT_SHORT' => $filter->filter($params['content_short']),
			 		'CONTENT_LONG' => $params['content_long'],
			 		'POSITION' => (int) $filter->filter($params['position']),
			 		'isSHOW' => $params['isshow'],
					'ID_CATS' => ''
			);
					
			if (isset($params['categories'])) {
				foreach($params['categories'] as $value)
				{
					$dataAnnonce['ID_CATS'] .= ":".$value.":";
				}
			}
			if(!empty($_FILES['picture']) && !empty($_FILES['picture']['name'])) {
					 
				try {
					$annonce = new AnnonceGallery();
					$annonce->insert($dataAnnonce);

					$lastid = $annonce->getAdapter()->lastInsertId();                             
					$this->uploadNewPicsAndSave($lastid);
								
					$this->view->messageSuccess = "L'image a �t� ajout�e";
								
					$this->log("L'image a �t� ajout�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->populateFormAnnonceGallery = $dataAnnonce;
				} 
			} else {
				$this->view->messageError = "L'image est obligatoire";
			}
		}
	}
	
	

	public function listAction()
	{
		$this->view->titlePage = "Gestion des images"; 
			
		//Appel model pour listing
		$annonces = new AnnonceGallery();
		$result = $annonces->getAllAnnonces();
         
		$this->view->listAnnonceGallery = $result;
	}



	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceGallery();

					$annonce->delete('ID = '.$id);
                    
                    $this->delete_directory('items/gallery/'.$id);

					$this->view->messageSuccess = "L'image a �t� supprim�e";

					$this->log("L'image a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}

}
?>AuthController.php000060400000003735150713030120010216 0ustar00<?php

class AuthController  extends Modules_Default_Controllers_MainController
{
	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}
	public function indexAction()
	{

	}
	public function logoutAction()
	{
		Zend_Auth::getInstance()->clearIdentity();
		$this->view->user = null;
		$this->_redirect('/');
	}
	public function loginAction()
	{

		$this->view->message = '';
		if ($this->_request->isPost()) {

			// collect the data from the user
			Zend_Loader::loadClass('Zend_Filter_StripTags');
			$f = new Zend_Filter_StripTags();
			$username = $f->filter($this->_request->getPost('username'));
			$password = $f->filter($this->_request->getPost('password'));

			if (empty($username) || empty($password)) {

				$this->view->message = 'Les champs sont obligatoire.';
					
			} else {

				// setup Zend_Auth adapter for a database table
				Zend_Loader::loadClass('Zend_Auth_Adapter_DbTable');
				$dbAdapter = Zend_Registry::get('dbAdapter');

				$authAdapter = new Zend_Auth_Adapter_DbTable($dbAdapter,
															'user',
															'LOGIN',
															'MDP',
															'MD5(?) AND ROLE = "0"'); 
					
				// Set the input credential values to authenticate against
				$authAdapter->setIdentity($username);
				$authAdapter->setCredential($password);

				// do the authentication
				$auth = Zend_Auth::getInstance();
				$result = $auth->authenticate($authAdapter);
				//$result = $authAdapter->authenticate();
					
				if ($result->isValid()) {

					// success: store database row to auth's storage
					// system. (Not the password though!) //array('IDUSER', 'LOGIN'));
					$data = $authAdapter->getResultRowObject(null, 'mdp');

					$auth->getStorage()->write($data);

					$this->log("Login : ".$username,'info');
					$this->_redirect('/backoffice/');
				} else {
					// failure: clear database row from session
					$this->view->message = 'Les identifiants sont incorrects.';
				}
			}
		}
		$this->render();
	}
}

?>FaqController.php000060400000021723150713030120010021 0ustar00<?php

class Backoffice_FaqController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
 
		$this->isConnectedWithRole('isFooter'); 
	}
	function indexAction()
	{
		$this->_forward('/list');

	}
	
	public function listAction() {
		$this->view->titlePage = "FAQ";
		
		$faqType = new FAQType();
		$this->view->faqtypes = $faqType->getTypesAll();

		$faq = new FAQ();
		$this->view->faq = $faq->getListsAll();
	}
	
	public function addfaqtypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'NOM' => $filter->filter($params['faq_nom'])
			);

			if ($validator->isValid($data['NOM'])
			) {

				try {
					$faq_type = new FAQType();
					$faq_type->insert($data);

					$this->view->messageSuccess = "La cat�gorie a �t� ajout�e";

				} catch (Zend_Exception $e) {
					$this->view->messageError = "La cat�gorie existe d�ja";
					$this->log($e->getMessage(),'err');

					$this->_forward('/list');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/list');
	}
	
	public function delfaqtypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$faqtype = new FAQType();
					$faq = new FAQ();
					
					if ($faq->isTypeExist($id) == false) {
						$faqtype->delete("ID = ".$id);
						$this->view->messageSuccess = "La cat�gorie a �t� supprim�e";
					} else {
						$this->view->messageError = "La cat�gorie est utilis�e";
					}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}
	
	public function editfaqtypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'NOM' => $filter->filter($params['faq_nom'])
			);

			if ($validator->isValid($data['NOM'])
			) {

				try {
					$faqType = new FAQType();
					$faqType->update($data, "ID = ".$params['faq_id']);

					$this->view->messageSuccess = "La cat�gorie a �t� modifi�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La cat�gorie n'a pas �t� modifi�e";

					$this->_forward('/list');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/list');
	}
	public function activefaqtypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$faqtype = new FAQType();
					$data = array (
					 		'isACTIVE' => 1
					);
					$faqtype->update($data, "ID = ".$id);
					$this->view->messageSuccess = "La cat�gorie est activ�e";
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}
	public function unactivefaqtypeAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$faqtype = new FAQType();
					$data = array (
					 		'isACTIVE' => 0
					);
					$faqtype->update($data, "ID = ".$id);
					$this->view->messageSuccess = "La cat�gorie est d�sactiv�e";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}
public function addfaqAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'QUESTION' => $filter->filter($params['faq_question']),
			 		'REPONSE' => $filter->filter($params['faq_reponse']),
			 		'POSITION' => $filter->filter($params['faq_position']),
			 		'TYPE' => $filter->filter($params['faq_type'])
			);

			if ($validator->isValid($data['QUESTION']) &&
			$validator->isValid($data['REPONSE'])) {

				try {
					$faq = new FAQ();
					$faq->insert($data);

					$this->view->messageSuccess = "La question a �t� ajout�e";

				} catch (Zend_Exception $e) {
					$this->view->messageError = "La question existe d�ja";

					$this->log($e->getMessage(),'err');
					$this->_forward('/list');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/list');
	}
	
	public function delfaqAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$faq = new FAQ();
					$faq->delete("ID = ".$id);
					$this->view->messageSuccess = "La question a �t� supprim�e";
					
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}
	
	public function editfaqAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			$data = array (
			 		'QUESTION' => $filter->filter($params['faq_question']),
			 		'REPONSE' => $filter->filter($params['faq_reponse']),
			 		'POSITION' => $filter->filter((int)$params['faq_position']),
			 		'TYPE' => $filter->filter($params['faq_type'])
			);

			if ($validator->isValid($data['QUESTION']) &&
			$validator->isValid($data['REPONSE'])) {

				try {
					$faq = new FAQ();
					$faq->update($data, "ID = ".$params['faq_id']);

					$this->view->messageSuccess = "La question a �t� modifi�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La question n'a pas �t� modifi�e";

					$this->_forward('/list');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('/list');
	}
	public function activefaqAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$faq = new FAQ();
					$data = array (
					 		'isACTIVE' => 1
					);
					$faq->update($data, "ID = ".$id);
					$this->view->messageSuccess = "La question est activ�e";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}
	public function unactivefaqAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$faq = new FAQ();
					$data = array (
					 		'isACTIVE' => 0
					);
					$faq->update($data, "ID = ".$id);
					$this->view->messageSuccess = "La question est d�sactiv�e";
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}
}
?>EbpController.php000060400000067715150713030120010033 0ustar00<?php
class Backoffice_EbpController extends Modules_Backoffice_Controllers_MainController {
	function init() {
		$this->view->title = "Administration";
		$this->view->currentMenu = "Ebp";
		$this->isConnectedWithRole ( 'isStats' );
	}
	public function indexAction() {
			$this->view->titlePage = "Gestion commerciale EBP";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
	}
	private $_SEPARATOR = ';';
	private function cleanUp($value) {
		$result = $value;
		$filter = new Zend_Filter ();
		$filter->addFilter ( new Zend_Filter_StringTrim () )->addFilter ( new Zend_Filter_StripTags () );
		$result = $filter->filter ( $result );
		$result = html_entity_decode ( $result, ENT_QUOTES, "ISO-8859-1" );
		$result = str_replace ( "\r\n", "", $result );
		$result = str_replace ( '�', " ", $result );
		// $result = str_replace("'","",$result);
		$result = str_replace ( $this->_SEPARATOR, "", $result );
		return $result;
	}
	private function cleanUpSpace($value) {
		$filter = new Zend_Filter ();
		$filter->addFilter ( new Zend_Filter_Alnum () );
		$value = str_replace ( $this->_SEPARATOR, "", $value );
		return $filter->filter ( $value );
	}
	private function cleanUpAddQuote($value) {
		return '"' . $this->cleanUp ( $value ) . '"';
	}
	function exportclientsAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			$user = new User ();
			$select = $user->select ()->order ( "ID ASC" );
			$listusers = $user->fetchAll ( $select );
			
			foreach ( $listusers as $row ) {
				$result = $row ['ID'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Code Famille
				                              // Facturation
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['ADRESSE'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Adresse 2
				$result .= $this->_SEPARATOR; // Adresse 3
				$result .= $this->_SEPARATOR; // Adresse 4
				$result .= $this->cleanUpSpace ( $row ['CP'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['VILLE'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['DEPARTEMENT'] ) . $this->_SEPARATOR;
				$result .= "FR" . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Site Web
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['PRENOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['FONCTION'] ) . $this->_SEPARATOR;
				$result .= $row ['TEL'] . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Tel Portable
				$result .= $row ['FAX'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['EMAIL'] ) . $this->_SEPARATOR;
				// Livraison
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['ADRESSE'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Adresse 2
				$result .= $this->_SEPARATOR; // Adresse 3
				$result .= $this->_SEPARATOR; // Adresse 4
				$result .= $this->cleanUpSpace ( $row ['CP'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['VILLE'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['DEPARTEMENT'] ) . $this->_SEPARATOR;
				$result .= "FR" . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Site Web
				                              // Contact
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['PRENOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['FONCTION'] ) . $this->_SEPARATOR;
				$result .= $row ['TEL'] . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Tel Portable
				$result .= $row ['FAX'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['EMAIL'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Compte comptable
				$result .= $this->cleanUpSpace ( $row ['NUMIDFISC'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUpSpace ( $row ['SIRET'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Code NAF
				$result .= "0";
				
				$fichier->Insertion ( $result );
			}
			$fichier->output ( 'ebp_clients' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	private function getEmptyFournisseur() {
		$result = "0" . $this->_SEPARATOR;
		$result .= "Aucun" . $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Code Famille
		                              // Facturation
		$result .= $this->_SEPARATOR; // Civilite
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Adresse 2
		$result .= $this->_SEPARATOR; // Adresse 3
		$result .= $this->_SEPARATOR; // Adresse 4
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Departement
		$result .= "FR" . $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Site Web
		$result .= $this->_SEPARATOR; // Civilite
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Tel Portable
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		// Livraison
		$result .= $this->_SEPARATOR; // Civilite
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Adresse 2
		$result .= $this->_SEPARATOR; // Adresse 3
		$result .= $this->_SEPARATOR; // Adresse 4
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Departement
		$result .= "FR" . $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Site Web
		                              // Contact
		$result .= $this->_SEPARATOR; // Civilite
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Tel Portable
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR;
		$result .= $this->_SEPARATOR; // Compte comptable
		$result .= $this->_SEPARATOR; // NUMIDFISC
		$result .= $this->_SEPARATOR; // SIRET
		$result .= $this->_SEPARATOR; // Code NAF
		$result .= "0";
		return $result;
	}
	function exportfournisseursAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			$supplier = new Supplier ();
			$select = $supplier->select ()->order ( "ID ASC" );
			$listsuppliers = $supplier->fetchAll ( $select );
			
			$supplierBrend = new SupplierBrend ();
			
			$fichier->Insertion ( $this->getEmptyFournisseur () );
			
			foreach ( $listsuppliers as $row ) {
				
				$listbrends = $supplierBrend->select ()->where ( "IDSUPPLIER = " . $row ['ID'] )->query ()->fetchAll ();
				
				foreach ( $listbrends as $rowBrend ) {
					$result = $rowBrend ['ID'] . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $rowBrend ['BREND'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Code Famille
					                              // Facturation
					$result .= $this->_SEPARATOR; // Civilite
					$result .= $this->cleanUp ( $row ['ADDRESSE'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Adresse 2
					$result .= $this->_SEPARATOR; // Adresse 3
					$result .= $this->_SEPARATOR; // Adresse 4
					$result .= $this->cleanUpSpace ( $row ['CP'] ) . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['VILLE'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Departement
					$result .= "FR" . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Site Web
					$result .= $this->_SEPARATOR; // Civilite
					$result .= $this->cleanUp ( $row ['PRENOM'] ) . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR;
					$result .= $row ['TEL'] . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Tel Portable
					$result .= $row ['FAX'] . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['EMAIL'] ) . $this->_SEPARATOR;
					// Livraison
					$result .= $this->_SEPARATOR; // Civilite
					$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['ADDRESSE'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Adresse 2
					$result .= $this->_SEPARATOR; // Adresse 3
					$result .= $this->_SEPARATOR; // Adresse 4
					$result .= $this->cleanUpSpace ( $row ['CP'] ) . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['VILLE'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Departement
					$result .= "FR" . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Site Web
					                              // Contact
					$result .= $this->_SEPARATOR; // Civilite
					$result .= $this->cleanUp ( $row ['PRENOM'] ) . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR;
					$result .= $row ['TEL'] . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Tel Portable
					$result .= $row ['FAX'] . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['EMAIL'] ) . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Compte comptable
					$result .= $this->_SEPARATOR; // NUMIDFISC
					$result .= $this->_SEPARATOR; // SIRET
					$result .= $this->_SEPARATOR; // Code NAF
					$result .= "0";
					
					$fichier->Insertion ( $result );
				}
			}
			$fichier->output ( 'ebp_fournisseurs' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	function exportcategoriesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			$category = new Category ();
			$select = $category->select ()->order ( "ID ASC" );
			$listcategories = $category->fetchAll ( $select );
			
			foreach ( $listcategories as $row ) {
				$result = $row ['ID'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR;
				$result .= $this->_SEPARATOR;
				$result .= $this->_SEPARATOR;
				$result .= "False" . $this->_SEPARATOR;
				$result .= "0" . $this->_SEPARATOR;
				$result .= "0";
				
				$fichier->Insertion ( $result );
			}
			$fichier->output ( 'ebp_categories' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	private function getUrlPage($params) {
		return $this->baseUrl_SiteCommerceUrl . "/" . $params ['PAGE'] . "-" . $params ['ID'] . ".html";
	}
	function exportarticlesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			
			$sql = "SELECT p.ID ID, p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.DESCRIPTIONLONG DESCLONG, p.PRIX PRIX, p.isDEVIS isDEVISPRODUCT,
					p.DOCNAME DOCNAME, p.DOCURL DOCURL, p.IDBREND IDBREND,
					p.isPROMO isPROMO, pic.URL URLIMAGE, sb.BREND BREND, sb.URL BRENDURL, p.IDCATEGORY IDCATEGORY, c.NOM CATEGORYNOM,
					p.DESCRIPTIONTECH DESCTECH, p.DESCRIPTIONNORME DESCNORME
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID
					LEFT JOIN supplier_brend sb ON sb.ID = p.IDBREND
					LEFT JOIN category AS c ON c.ID = p.IDCATEGORY
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";
			
			$product = new Product ();
			$productChild = new ProductChild ();
			$listProducts = $product->getAdapter ()->fetchAll ( $sql );
			
			foreach ( $listProducts as $row ) {
				$sqlChild = "
						SELECT pc.ID ID ,pc.REFERENCE REFERENCE,pc.DESIGNATION DESIGNATION,pc.PRIX PRIX, pc.isPROMO isPROMO ,
						pc.IMAGEPROMO IMAGEPROMO,pc.isDEVIS isDEVIS, pc.QUANTITYMIN QUANTITYMIN
							FROM productchild AS pc
						WHERE pc.IDPRODUCT = " . $row ['ID'] . "
						ORDER BY pc.PRIX ASC";
				
				$productChildTemp = $productChild->getAdapter ()->fetchAll ( $sqlChild );
				
				$navnom = $this->verifyNavigationString ( $row ['NAVNOM'], $row ['NOM'], '' );
				
				$urlImage = $this->baseUrl_SiteCommerceUrl . "/" . $row ['URLIMAGE'];
				$urlPage = $this->getUrlPage ( array (
						'PAGE' => $navnom,
						'ID' => $row ['ID'] 
				) );
				
				$fraislivraison = "";
				$garantie = "";
				
				$reference = "";
				$description = "";
				foreach ( $productChildTemp as $rowChild ) {
					$reference = $this->cleanUp ( $rowChild ['REFERENCE'] );
					
					$description = $this->cleanUp ( $rowChild ['DESIGNATION'] );
					
					$result = $rowChild ['ID'] . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
					$result .= $row ['IDCATEGORY'] . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Prix de revient
					$result .= $rowChild ['PRIX'] . $this->_SEPARATOR;
					$result .= $this->tva . $this->_SEPARATOR;
					$result .= $description . $this->_SEPARATOR;
					$result .= $reference . $this->_SEPARATOR; // Code barre
					$result .= $this->_SEPARATOR; // Code unite
					$result .= $this->_SEPARATOR; // Type d'article
					$result .= $this->_SEPARATOR; // Code emplacement
					$result .= $row ['IDBREND'] . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Code �co
					
					$fichier->Insertion ( $result );
				}
			}
			
			$fichier->output ( 'ebp_articles' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	private function formatDate($datevalue) {
		$date = new Zend_Date ();
		$date->set ( $datevalue );
		return $date->toString ( 'dd/MM/YYYY' );
	}
	private function getCommandDevisLine($listcommands) {
		$commandLine = new CommandProduct ();
		$fichier = new FichierExcel ();
		$result = "Document - Num�ro du document;Document - Date;Document - Code client;Document - Nom du client;Document - Adresse 1 (facturation);Document - Code postal (facturation);Document - Ville (facturation);Document - Code Pays (facturation);Document - Nom (contact) (facturation);Document - Pr�nom (facturation);Document - T�l�phone fixe (facturation);Document - Fax (facturation);Document - E-mail (facturation);Document - Nom (adresse) (livraison);Document - Adresse 1 (livraison);Document - Code postal (livraison);Document - Ville (livraison);Document - Code Pays (livraison);Document - T�l�phone fixe (livraison);Document - Fax (livraison);Document - E-mail (livraison);Document - Frais de port HT;Document - Total Brut HT;Document - Total TTC;Document - Taux de TVA port;Ligne - Code article;Ligne - Quantit�;Ligne - Taux de TVA;Ligne - PV HT;Ligne - Montant Net HT;Ligne - Montant de remise unitaire HT cumul�";
		$fichier->Colonne ( $result );
		foreach ( $listcommands as $row ) {
			$result = '"' . $row ['REFERENCE'] . '"' . $this->_SEPARATOR;
			$result .= '"' . $this->formatDate ( $row ['DATESTART'] ) . '"' . $this->_SEPARATOR;
			$result .= '"' . $row ['IDUSER'] . '"' . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_NOM'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['FACT_ADRESSE'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['FACT_CP'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['FACT_VILLE'] ) . $this->_SEPARATOR;
			$result .= "FR" . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_NOM'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_PRENOM'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_TEL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_FAX'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_EMAIL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_RAISONSOCIAL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_ADRESSE'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_CP'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_VILLE'] ) . $this->_SEPARATOR;
			$result .= "FR" . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_TEL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_FAX'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_EMAIL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['PRIXFRAISPORT'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['PRIXTOTALHTFP'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['PRIXTOTALTTC'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $this->getCurrentTva ( $row ['DATESTART'] ) ) . $this->_SEPARATOR;
			
			$selectLine = $commandLine->select ()->where ( "IDCOMMAND = " . $row ["ID"] );
			$listLines = $commandLine->fetchAll ( $selectLine );
			foreach ( $listLines as $rowLine ) {
				$resultLine = $result;
				
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDID'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDQUANTITY'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $this->getCurrentTva ( $row ['DATESTART'] ) ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDPRIX'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDPRIXTOTAL'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDPRIXREMISE'] ) . $this->_SEPARATOR;
				
				$fichier->Insertion ( $resultLine );
			}
		}
		return $fichier;
	}
	function exportcommandesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$command = new Command ();
			
			$date = new Zend_Date ();
			$date->addMonth ( - 3 );
			$select = "
				SELECT *
				FROM command
				WHERE isARCHIVE = 1
				AND STATUT IN (1, 2, 3)
				AND DATESTART >= '" . $date->toString ( 'YYYY-MM-dd' ) . "'";
			
			$listcommands = $command->getAdapter ()->fetchAll ( $select );
			
			$fichier = $this->getCommandDevisLine ( $listcommands );
			
			$fichier->output ( 'ebp_commandes' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	function exportdevisAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$command = new Command ();
			
			$date = new Zend_Date ();
			$date->addMonth ( - 3 );
			$select = "
				SELECT *
				FROM command
				WHERE isARCHIVE = 1
				AND STATUT IN (10, 11)
				AND DATESTART >= '" . $date->toString ( 'YYYY-MM-dd' ) . "'";
			
			$listcommands = $command->getAdapter ()->fetchAll ( $select );
			
			$fichier = $this->getCommandDevisLine ( $listcommands );
			
			$fichier->output ( 'ebp_devis' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	function importcategoriesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$nomTemp = 'csvfile';
			
			if ($this->isValidCSVFile ( $nomTemp )) {
				$nomOrigine = $_FILES [$nomTemp] ['name'];
				
				$date = new Zend_Date ();
				$nomDestination = "importcategories-" . $date->toString ( 'dd-MM-YYYY_HH-mm-ss' ) . ".csv";
				
				if ($this->uploadCsvFile ( $_FILES [$nomTemp] ["tmp_name"], $nomDestination )) {
					
					$header = array (
							0 => 'ID',
							1 => 'NOM',
							2 => 'NOUSE1',
							3 => 'NOUSE2',
							4 => 'NOUSE3',
							5 => 'NOUSE4',
							6 => 'NOUSE5',
							7 => 'NOUSE6' 
					);
					$dataRows = $this->csv_to_array ( $this->csv_import . $nomDestination, $header );
					if (sizeof ( $dataRows [0] ) == sizeof ( $header )) {
						
						$category = new Category ();
						$filesAdded = 0;
						$filesUpdated = 0;
						$filesError = 0;
						foreach ( $dataRows as $row ) {
							
							$id = $row ["ID"];
							$nom = $this->cleanUp ( $row ["NOM"] );
							
							$currentCat = $category->select ()->where ( "ID = ?", $id )->query ()->fetch ();
							
							if ($currentCat != null && ! empty ( $currentCat )) {
								try {
									// Update
									if ($currentCat ['NOM'] != $nom) {
										$data = array (
												'NOM' => $nom 
										);
										$category->update ( $data, 'ID = ' . $id );
										$filesUpdated ++;
									}
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							} else {
								try {
									$navnom = $this->verifyNavigationString ( "", $nom, '' );
									$keywords = $this->generateKeyWords ( $navnom );
									// Insert
									$data = array (
											'NOM' => $nom,
											'NAVTITRENOM' => $nom,
											'DESCRIPTION' => $nom,
											'NAVDESCRIPTION' => $nom,
											'NAVNOM' => $navnom,
											'KEYWORDS' => $keywords,
											'IDPARENT' => 0 
									);
									$category->insert ( $data );
									
									$lastid = $category->getAdapter()->lastInsertId();
									if ($lastid > 0) {
										mkdir ("items/category/".$lastid, 0777);
										mkdir ("items/product/".$lastid, 0777);
									}
									
									$filesAdded ++;
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							}
						}
						$this->view->messageSuccess = "Importation des fiches Familles articles<br/>
														Fiches ajout�es : " . $filesAdded . "<br/>
														Fiches modifi�es : " . $filesUpdated . "<br/>
														Fiches non import�es : " . $filesError . "<br/>";
					} else {
						$this->view->messageError = "Le fichier n'est pas au format attendu pour les Familles articles";
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas pu etre import�.";
				}
			}
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
		$this->render ( '/index' );
	}
	function importarticlesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$nomTemp = 'csvfile';
			
			if ($this->isValidCSVFile ( $nomTemp )) {
				$nomOrigine = $_FILES [$nomTemp] ['name'];
				
				$date = new Zend_Date ();
				$nomDestination = "importarticles-" . $date->toString ( 'dd-MM-YYYY_HH-mm-ss' ) . ".csv";
				
				if ($this->uploadCsvFile ( $_FILES [$nomTemp] ["tmp_name"], $nomDestination )) {
					
					$header = array (
							0 => 'ID',
							1 => 'NOM',
							2 => 'IDCATEGORY',
							3 => 'NOUSE1',
							4 => 'PRIX',
							5 => 'TVA',
							6 => 'DESCRIPTION',
							7 => 'REFERENCE',
							8 => 'NOUSE2',
							9 => 'NOUSE3',
							10 => 'NOUSE4',
							11 => 'IDBREND',
							12 => 'NOUSE5' 
					);
					
					$dataRows = $this->csv_to_array ( $this->csv_import . $nomDestination, $header );
					if (sizeof ( $dataRows [0] ) == sizeof ( $header )) {
						
						$product = new Product ();
						$productLine = new ProductChild ();
						$filesAdded = 0;
						$filesUpdated = 0;
						$filesError = 0;
						
						$date = new Zend_Date ();
						foreach ( $dataRows as $row ) {
							
							$id = $row ["ID"];
							$prix = $this->cleanUp ( $row ["PRIX"] );
							$description = $this->cleanUp ( $row ["DESCRIPTION"] );
							$reference = $this->cleanUp ( $row ["REFERENCE"] );
							
							$tva = $this->cleanUp ( $row ["TVA"] );
							$nom_prod = $this->cleanUp ( $row ["NOM"] );
							$idCat_prod = $this->cleanUp ( $row ["IDCATEGORY"] );
							$idbrend_prod = $this->cleanUp ( $row ["IDBREND"] );
							
							$currentProdLine = $productLine->select ()->where ( "REFERENCE = ?", $reference )->query ()->fetch ();
							
							if ($currentProdLine != null && ! empty ( $currentProdLine )) {
								try {
									
									// Update
									$dataChild = array (
											'DESIGNATION' => $description,
											'PRIX' => $prix,
											'DATEMODIF' => $date->toString ( 'YYYY-MM-dd HH:mm:ss' ) 
									);
									
									$productChild = new ProductChild ();
									$productChild->update ( $dataChild, 'ID = ' . $id );
									$filesUpdated ++;
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							} else {
								try {
									// Insert
									$navnom = $this->verifyNavigationString ( "", $nom_prod, '' );
									$keywords = $this->generateKeyWords ( $navnom );
									
									$data = array (
											'NOM' => $nom_prod,
											'NAVNOM' => $navnom,
											'KEYWORDS' => $keywords,
											'NAVTITRE' => '',
											'NAVDESC' => '',
											'DESCRIPTIONSHORT' => $nom_prod,
											'DESCRIPTIONLONG' => $nom_prod,
											'PRIX' => $prix,
											'isACTIVE' => 1,
											'DATEPROMO' => $date->toString ( 'YYYY-MM-dd' ),
											'isPROMO' => '1',
											'IDCATEGORY' => $idCat_prod,
											'ISSHOWBREND' => 1 
									);
									$product->insert ( $data );
									$lastId = $product->getAdapter ()->lastInsertId ();
									
									$dataChild = array (
											'REFERENCE' => $reference,
											'DESIGNATION' => $description,
											'PRIX' => $prix,
											'ETATSTOCK' => 0,
											'QUANTITYMIN' => 1,
											'isDEVIS' => 1,
											'IMAGEPROMO' => 0,
											'DATEMODIF' => $date->toString ( 'YYYY-MM-dd HH:mm:ss' ),
											'IDPRODUCT' => $lastId 
									);
									
									$productChild = new ProductChild ();
									$productChild->insert ( $dataChild );
									
									$filesAdded ++;
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							}
						}
						$this->view->messageSuccess = "Importation des fiches Articles<br/>
														Fiches ajout�es : " . $filesAdded . "<br/>
														Fiches modifi�es : " . $filesUpdated . "<br/>
														Fiches non import�es : " . $filesError . "<br/>";
					} else {
						$this->view->messageError = "Le fichier n'est pas au format attendu pour les Articles";
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas pu etre import�.";
				}
			}
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
		$this->render ( '/index' );
	}
	var $csv_import = 'csvfiles/import/';
	private function uploadCsvFile($tmpName, $destName) {
		if (! file_exists ( $this->csv_import )) {
			mkdir ( $this->csv_import, 0777, true );
		}
		return move_uploaded_file ( $tmpName, $this->csv_import . $destName );
	}
	private function isValidCSVFile($name) {
		if (! empty ( $_FILES [$name] ) && ! empty ( $_FILES [$name] ['name'] )) {
			$nomOrigine = $_FILES [$name] ['name'];
			$elementsChemin = pathinfo ( $nomOrigine );
			$extensionFichier = strtolower($elementsChemin ['extension']);
			$extensionsAutorisees = array (
					"csv" 
			);
			if (! (in_array ( $extensionFichier, $extensionsAutorisees ))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue (.csv)";
			} else {
				return true;
			}
		} else {
			$this->view->messageError = "Vous pouvez exporter les donn�es via EBP -> Outils -> Exportation de donn�es";
		}
		return false;
	}
	private function csv_to_array($filename = '', $header, $delimiter = ';') {
		if (! file_exists ( $filename ) || ! is_readable ( $filename ))
			return FALSE;
		
		$data = array ();
		if (($handle = fopen ( $filename, 'r' )) !== FALSE) {
			while ( ($row = fgetcsv ( $handle, 1000, $delimiter )) !== FALSE ) {
				if (! $header) {
					$header = $row;
				} else if (sizeof ( $header ) == sizeof ( $row )) {
					$data [] = array_combine ( $header, $row );
				}
			}
			fclose ( $handle );
		}
		return $data;
	}
}
?>IndexController.php000060400000002425150713030120010357 0ustar00<?php

class IndexController  extends Modules_Default_Controllers_MainController
{

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
	}

	public function indexAction()
	{
        $this->setCanonicalUrl($this->baseUrl_SiteCommerceUrl."/");
		$this->view->title = $this->TextHomeMetaTitle;
		$this->view->metadescription = $this->TextHomeMetaDescription;
        
		if ($this->isSiteGallery) {
			$id = 1;
			
		    $annonceGallery = new AnnonceGallery(); 
            $this->view->listAllGalleries = $annonceGallery->getAnnoncesByShow($id);
			
			$category = new Category();  
			$currentCat = $category->fetchRow("ID = ".$id);
			
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());

			$this->view->title = $currentCat['NAVTITRENOM'];
			$this->view->metadescription = $filter->filter($currentCat['NAVDESCRIPTION']);  
			$this->view->metakeywords = $currentCat['KEYWORDS']; 
		}
		if ($this->isSiteEbusiness) {
	        $annonces = new AnnonceContent();
	        $result = $annonces->getAnnoncesByShow(0);
	        $this->view->listads = $result;

	        $annoncesfrontHeader = new  AnnonceFrontHeader();
	        $this->view->listinfos = $annoncesfrontHeader->getAnnonces();
        }

	}

}



?>UserController.php000060400000135326150713030120010235 0ustar00<?php


class UserController extends Modules_Default_Controllers_MainController
{
	public function init() {
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}
	public function indexAction() {

	}
    
    public function deletecaddyfidelitypointAction() {
        try {
            $auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			if ($auth->hasIdentity() && isset($storage['user'])) {
		        if ($this->getRequest()->getParam('id')) {          
                    $id = (int) $this->getRequest()->getParam('id');
                    if ($id > 0) {
                        $userNamespace = $this->getSession();
                        if (isset($userNamespace->myObjectCaddyFidelite)) { 
                            $caddyFidelite = $userNamespace->myObjectCaddyFidelite;
                            $caddyFidelite->removeItem($id);
                            $userNamespace->myObjectCaddyFidelite = $caddyFidelite;
                        }
                    }    
                }            
            }
        } catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
        $this->_redirect('/mon-panier.html');
    }

	public function addcaddyfidelitypointAction() {

        try {
            $auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			if ($auth->hasIdentity() && isset($storage['user'])) {
		        if ($this->getRequest()->getParam('id')) {          
                    $id = (int) $this->getRequest()->getParam('id');
                    if ($id > 0) {
                        $carteFidelite = new CarteFidelite();
                        $isAvailable = $carteFidelite->isAnnonceAvailableForUser($storage['user']['id'], $id);
                        if ($isAvailable) {
                            $userNamespace = $this->getSession();
                            if (!isset($userNamespace->myObjectCaddyFidelite)) { $userNamespace->myObjectCaddyFidelite = new CaddyFidelite(); }
                            $caddyFidelite = $userNamespace->myObjectCaddyFidelite;
                            $caddyFidelite->addItem($id);
                            $userNamespace->myObjectCaddyFidelite = $caddyFidelite;
                        }
                    }    
                }            
            }
        } catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
        $this->_redirect('/mon-panier.html');
	}
	private function computeFactureTVA($facture, $paysLivraison) {
		$fact = new Facture();
		$fact->computeFactureTVA($facture, $paysLivraison);
		return $facture;
	}

	public function commandeAction()
	{
		if ($this->getRequest()->getParam('ref')) {
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();

			$linksMenu[0]['NAVURL'] = '/mon-compte.html';
			$linksMenu[0]['NAVNOM'] = 'Mon compte';
			$this->view->linksMenu = $linksMenu;

			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StripTags());

			if ($auth->hasIdentity() && isset($storage['user'])) {

				$commande = new Command();
				$ref = $filter->filter($this->getRequest()->getParam('ref'));
				$isExist = $commande->fetchRow("REFERENCE = '".$ref."'");
				if ($isExist) {

					$resultCommande = $commande->findCommandByUserAndRef($storage['user']['id'],$ref );

					$myCommand = array();
					$myCommand['CADDY'] = array();
					$myCommand['CADDYFIDELITE'] = array();
					$i = 0;

                    $idCommand = 0;
					foreach ($resultCommande AS $row) {
						if ($i == 0) {
							$myCommand['REFERENCE'] = $row['REFERENCE'];
							$myCommand['ID'] = $row['ID'];
                            $idCommand = $row['ID'];

							$myCommand['PRIXTOTALTTC'] = sprintf("%.2f", $row['TOTALTTC']);
							$myCommand['PRIXTOTALHTFP'] = sprintf("%.2f", $row['TOTALHTFP']);
							$myCommand['PRIXFRAISPORTPOUR'] = $row['FRAISPORTPOUR'];
							$myCommand['PRIXFRAISPORT'] = sprintf("%.2f", $row['FRAISPORT']);
							$myCommand['PRIXTOTALHT'] = sprintf("%.2f", $row['TOTALHT']);
							$myCommand['PRIXTOTALHTHR'] = sprintf("%.2f", $row['TOTALHTHR']);
							$myCommand['PRIXREMISEEUR'] = sprintf("%.2f", $row['REMISEEUR']);
							$myCommand['DATESTART'] = $row['DATESTART'];

							$myCommand = $this->computeFactureTVA($myCommand, $row['LIVPAYS']);

							$myCommand['STATUT'] = $row['STATUT'];
							$myCommand['LIV_RAISONSOCIAL'] = $row['LIVRAISONSOCIAL'];
							$myCommand['LIV_ADRESSE'] = $row['LIVADRESSE'];
							$myCommand['LIV_CP'] = $row['LIVCP'];
							$myCommand['LIV_VILLE'] = $row['LIVVILLE'];
							$myCommand['LIV_PAYS'] = $row['LIVPAYS'];
							$myCommand['FACT_RAISONSOCIAL'] = $row['FACTRAISONSOCIAL'];
							$myCommand['FACT_ADRESSE'] = $row['FACTADRESSE'];
							$myCommand['FACT_CP'] = $row['FACTCP'];
							$myCommand['FACT_VILLE'] = $row['FACTVILLE'];
							$myCommand['FACT_PAYS'] = $row['FACTPAYS'];
							$myCommand['USER_NOM'] = $row['USERNOM'];
							$myCommand['USER_PRENOM'] = $row['USERPRENOM'];
							$myCommand['USER_TEL'] = $row['USERTEL'];
							$myCommand['USER_FAX'] = $row['USERFAX'];
							$myCommand['USER_NUMCOMPTE'] = $row['USERNUMCOMPTE'];
							$myCommand['USER_EMAIL'] = $row['USEREMAIL'];
							$myCommand['USER_MODEPAIEMENT'] = $row['USERMODEPAIEMENT'];
							$myCommand['LIV_NOM'] = $row['LIV_NOM'];
							$myCommand['CODEREDUCTION'] = $row['CODEREDUCTION'];
							$myCommand['USER_MODEPAIEMENT_TYPE'] = $row['USER_MODEPAIEMENT_TYPE'];
							$myCommand['USER_MODEPAIEMENT_LABEL'] = $row['USER_MODEPAIEMENT_LABEL'];
						}

						$myCommand['CADDY'][$i]['ID'] = $row['CHILDID'];
						$myCommand['CADDY'][$i]['REFERENCE'] = $row['CHILDREF'];
						$myCommand['CADDY'][$i]['DESIGNATION'] = $row['DESIGNATION'];
						$myCommand['CADDY'][$i]['isPROMO'] = $row['CHILDisPROMO'];
						$myCommand['CADDY'][$i]['isDEVIS'] = $row['CHILDisDEVIS'];
						$myCommand['CADDY'][$i]['PRIX'] = sprintf("%.2f", $row['CHILDPRIX']);
						$myCommand['CADDY'][$i]['QUANTITY'] = $row['CHILDQUANTITY'];
						$myCommand['CADDY'][$i]['PROMOPRIX'] = sprintf("%.2f", $row['CHILDPROMOPRIX']);
						$myCommand['CADDY'][$i]['PRIXTOTAL'] = sprintf("%.2f", $row['CHILDPRIXTOTAL']);
						$myCommand['CADDY'][$i]['REMISEPRIX'] = sprintf("%.2f", $row['CHILDPRIXREMISE']);
						$myCommand['CADDY'][$i]['REMISEPRIXTAUXE'] = sprintf("%.2f", $row['CHILDREMISEPRIXTAUXE']);
						$myCommand['CADDY'][$i]['REMISEPRIXTAUXP'] = $row['CHILDREMISEPRIXTAUXP'];
						$myCommand['CADDY'][$i]['PRODUCTID'] = $row['PRODUCTID'];
						$myCommand['CADDY'][$i]['PRODUCTNOM'] = $row['PRODUCTNOM'];
						$myCommand['CADDY'][$i]['STOCK'] = $row['STOCK'];
						$myCommand['CADDY'][$i]['SELECTEDOPTION'] = $row['SELECTEDOPTION'];
                        
						$myCommand['CADDY'][$i]['NAVPRODUCTNOM'] = $this->verifyNavigationString($row['PRODUCTNAVNOM'], $row['PRODUCTNOM'],'');
						$myCommand['CADDY'][$i]['NAVNOM_URLPARENTS'] = $row['NAVNOM_URLPARENTS'];
						$i++;
					}
                    
                    
					$i = 0;
					$resultCommandeFidelite = $commande->findCommandFideliteByUserAndRef($idCommand);
					foreach ($resultCommandeFidelite AS $row) {
						$myCommand['CADDYFIDELITE'][$i]['IDFIDELITE'] = $row['IDFIDELITE'];
						$myCommand['CADDYFIDELITE'][$i]['NOM'] = $row['NOM'];
						$myCommand['CADDYFIDELITE'][$i]['NBPOINT'] = $row['NBPOINT'];
                        $i++;
                    }
						
					if ($myCommand['STATUT'] == 1 || $myCommand['STATUT'] == 2 || $myCommand['STATUT'] == 3) {
						$this->view->title = 'Votre Facture';
					} else {
						$this->view->title = 'Votre Devis';
					}


					$this->view->facture = $myCommand;
					$this->render('facture');
				} else {
					$this->_redirect('/mon-compte.html');
				}
			} else {
				$this->_redirect('/connectez-vous.html');
			}
		} else {
			$this->_redirect('/mon-compte.html');
		}
	}
	public function newsletteraddAction()
	{
		if ($this->getRequest()->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StringToLower());

			$validatorEmail = new Zend_Validate_EmailAddress();

			$email = $filter->filter($this->getRequest()->getPost('nltr_email'));
			$date = new Zend_Date();
			$dateins = $date->toString('YYYY-MM-dd HH:mm:ss');
			$code = md5($dateins.'_'.$email);

			if ($validatorEmail->isValid($email)) {
				$myNltr = new UserNewsletter();
				$isExist = $myNltr->fetchRow("EMAIL = '".$email."'");
				if(!$isExist) {
					$data = array(
						'EMAIL' => $email,
						'CODE' => $code,
						'DATEINS' => $dateins
					);
					$myNltr->insert($data);
					$this->view->messageSuccess =   "Vous �tes maintenant membre de notre <b>Newsletter</b>";//"Pour effacer : <a href='/user/newsletter/nltr_quit/$code'>$code</a>";
				} else {
					$this->view->messageError =  "L'email existe d�j�";
				}
			} else {
				$this->view->messageError =  "V�rifier votre email";
			}
		}
		$this->_forward('ajaxmessage','ajax');
	}
	public function newsletterAction()
	{
		if ($this->getRequest()->getParam('nltr_quit')) {
			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$code = $filter->filter($this->getRequest()->getParam('nltr_quit'));

			$myNltr = new UserNewsletter();
			$isExist = $myNltr->fetchRow("CODE = '".$code."'");

			if ($isExist) {
				$myNltr->delete("CODE = '".$code."'");
			}
			$this->view->nltrMessageError = "Vous avez �t� d�sinscrit";
		}
		$this->_forward('index','index');
	}

	public function deconnexionAction()
	{
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage())->clearIdentity();

		$this->view->user = null;
		$this->resetSession();

		$this->_redirect('/connectez-vous.html');
	}

	public function ajaxdeconnexionAction()
	{
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage())->clearIdentity();
		$this->view->user = null;
		$this->resetSession();

		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
	}

	private function passgen() {
		$chaine ="mnoTUzS5678kVvwxy9WXYZRNCDEFrslq41GtuaHIJKpOPQA23LcdefghiBMbj0";
		srand((double)microtime()*1000000);
		for($i=0; $i<8; $i++){
			@$pass .= $chaine[rand()%strlen($chaine)];
		}
		return $pass;
	}


	public function passwordforgetAction() {
        try {
		    $this->view->title = 'Mot de passe oubli� ?';
		    $linksMenu[0]['NAVURL'] = '/connectez-vous.html';
		    $linksMenu[0]['NAVNOM'] = 'Identifiez-vous !';
		    $this->view->linksMenu = $linksMenu;
		    $this->view->showSlide = 1;

		    $filter = new Zend_Filter();
		    $filter	->addFilter(new Zend_Filter_StripTags())
		    ->addFilter(new Zend_Filter_StringTrim());

		    $validatorEmail = new Zend_Validate_EmailAddress();

		    if ($this->getRequest()->isPost()) {
			    $email = $filter->filter($this->getRequest()->getPost('emailpassword'));
			    if ($validatorEmail->isValid($email)) {
				    $user = new User();
				    $isExist = $user->fetchRow("EMAIL = '".$email."'");

				    if ($isExist) {

					    $newMDP = $this->passgen();
					    $mail = new Zend_Mail();

					    $mail->setBodyHtml("Cher(�re) ".$isExist['NOM']." ".$isExist['PRENOM'].",<br><br>
					    Nous avons bien re�u votre message nous demandant de vous aider � retrouver vos identifiants. <br>
					    Vous trouverez ci-dessous votre nouveau mot de passe. <br>
					    Si celui ci ne vous convient pas, vous pouvez le modifier � tout moment.<br><br>
					    Votre pseudo : ".$isExist['LOGIN']."<br>
					    Votre mot de passe : ".$newMDP."<br><br>
					    <a href='".$this->baseUrl_SiteCommerceUrl."/mon-compte.html'>Vous pouvez vous connecter ici</a><br><br>
					    ".$this->siteName);

					    $mail->setFrom($this->serviceClient_Mail, $this->siteName);
					    $mail->addTo($isExist['EMAIL'], $isExist['NOM'].' '.$isExist['PRENOM']);
					    $mail->setSubject($this->siteName.', votre mot de passe');
					    $mail->send();

					    $data = array('MDP' => md5($newMDP));
					    $user->update($data, 'ID = '.$isExist['ID']);

					    $this->view->messageSuccessPass = "Nous venons de vous envoyer par email votre nouveau mot de passe.";
				    } else {
				     $this->view->messageErrorPass = "V�rifier votre email";
				    }

			    } else {
				    $this->view->messageErrorPass = "V�rifier votre email";
			    }
		    }
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
		$this->render('connexion');
	}
	public function connexionAction() {
		$this->view->title = 'Identifiez-vous !';
		$linksMenu[0]['NAVURL'] = '/connectez-vous.html';
		$linksMenu[0]['NAVNOM'] = 'Identifiez-vous !';
		$this->view->linksMenu = $linksMenu;
		$this->view->showSlide = 1;

		if ($this->getRequest()->isPost()) {
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$login = $filter->filter($this->getRequest()->getPost('connexion_login'));
			$mdp = $filter->filter($this->getRequest()->getPost('connexion_mdp'));

			$user = new User();


			if ($validator->isValid($login) && $validator->isValid($mdp)) {
				$messageSuccess = $this->connectMe($login, $mdp);
				if ($messageSuccess == "SUCCESS") {

					$this->retrievecommandbyuser();

					$currentAncre = $this->getRequest()->getPost('current_con_ancre');
					if (isset($currentAncre) && !empty($currentAncre)) {
						if ($currentAncre == "commandes") {
							$this->_redirect('/mon-compte.html#commandes');
						} else if ($currentAncre == "selection") {
							$this->_redirect('/mon-compte.html#selection');
						}
					} else {
						$userNamespace = $this->getSession();
						$myCaddyTemp = $userNamespace->myObjectCaddy;
						if (isset($myCaddyTemp->items) && !empty($myCaddyTemp->items)) {
							$this->_redirect('/mon-panier.html');
						} else {
							$this->_redirect('/');
						}
					}

				} else {
					$this->view->messageErrorConnect =  $messageSuccess;
					$this->view->user = null;

					$currentAncre = $this->getRequest()->getPost('current_con_ancre');
					if (isset($currentAncre) && !empty($currentAncre)) {
						$this->view->current_con_ancre = $currentAncre;
					}
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageErrorConnect =  $this->getErrorValidator($errorCode);
				}
			}
		}
	}

	public function ajaxrefreshcaddytypeAction() {
		if ($this->isConnected()) {
			$user = $this->getStorageUser();
			if ($user['iscaddytype'] == 'Y') { $this->view->messageSuccess = 'SUCCESS';
			} else { $this->view->messageSuccess = 'ERROR'; }
		}
		$this->_forward('ajaxvalue','ajax');
	}

	public function ajaxrefreshcaddysizeAction() {
		$userNamespace = $this->getSession();
		$result = 'Aucun produit';
		if (isset($userNamespace->myObjectCaddy) && !empty($userNamespace->myObjectCaddy)) {
			$myCaddy = $userNamespace->myObjectCaddy;
			$size = $myCaddy->getTotalSize();
			if ($size > 1) {
				$result = $size.' PRODUITS';
			} else if ($size == 1) {
				$result = $size.' PRODUIT';
			}
		}
		$this->view->messageSuccess = $result;
		$this->_forward('ajaxvalue','ajax');
	}

	public function ajaxconnexionAction() {
		if ($this->getRequest()->isPost()) {
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$login = $filter->filter($this->getRequest()->getPost('connexionleft_login'));
			$mdp = $filter->filter($this->getRequest()->getPost('connexionleft_mdp'));

			if ($validator->isValid($login) && $validator->isValid($mdp)) {
				$messageSuccess = $this->connectMe($login, $mdp);
				if ($messageSuccess == "SUCCESS") {

					$this->retrievecommandbyuser();

					$auth = Zend_Auth::getInstance();
					$auth->setStorage($this->getSessionStorage());
					$storage = $auth->getStorage()->read();
				} else {
					$this->view->messageError = $messageSuccess;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('ajaxaccount','ajax');
	}

	public function moncompteAction() {
		$this->view->title = 'Mon Compte';
		if ($this->isConnected()) {

			$linksMenu[0]['NAVURL'] = '/mon-compte.html';
			$linksMenu[0]['NAVNOM'] = 'Mon compte';
			$this->view->linksMenu = $linksMenu;

			$user = $this->getStorageUser();

			$command = new Command();
			$this->view->myCommands = $command->findCommandsByUser($user['id']);
			$this->view->myDevis = $command->findDevisByUser($user['id']);
			$this->view->caddyType = $this->getCaddyTypeByUserConnected();
            
            $carteFidelite = new CarteFidelite();
			$this->view->carteFidelite = $carteFidelite->getInfosByUser($user['id']);
            
			$this->view->listfidelitegift = $carteFidelite->getAnnoncesByShow(1);
            
            
			$this->view->populateFormEdit = $user;

		}  else { $this->_redirect('/connectez-vous.html'); }
	}

	public function enregistrementAction() {
		$isAdd = false;

		$this->view->title = 'Cr�ation de votre compte';
		$linksMenu[0]['NAVURL'] = '/user/enregistrement';
		$linksMenu[0]['NAVNOM'] = ' Identifiez-vous !';
		$this->view->linksMenu = $linksMenu;

		$this->view->showSlide = 2;

		if ($this->getRequest()->isPost()) {

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());
			$filter2 = new Zend_Filter();
			$filter2->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_Digits());

			$filterMaj = new Zend_Filter();
			$filterMaj->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StringToUpper());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$validatorTel = new Zend_Validate();
			$validatorTel -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(10));

			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());

			$validatorEmail = new Zend_Validate_EmailAddress();

			$adduser_login = $filter->filter($this->getRequest()->getPost('adduser_login'));
			$adduser_mdp = $filter->filter($this->getRequest()->getPost('adduser_mdp'));
			$adduser_mdp2 = $filter->filter($this->getRequest()->getPost('adduser_mdp2'));

			$adduser_civility = $filter->filter($this->getRequest()->getPost('adduser_civility'));
            $adduser_nom = $filterMaj->filter($this->getRequest()->getPost('adduser_nom'));
			$adduser_prenom = $filter->filter($this->getRequest()->getPost('adduser_prenom'));
            
			$adduser_fct = $filter->filter($this->getRequest()->getPost('adduser_fct'));
			$adduser_tel = $filter2->filter($this->getRequest()->getPost('adduser_tel'));
			$adduser_fax = $filter2->filter($this->getRequest()->getPost('adduser_fax'));
			$adduser_email = $adduser_login;// $filter->filter($this->getRequest()->getPost('adduser_email'));


			$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse'));
			$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp'));
			$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville'));
			$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays'));
			$adduser_departement = $filter->filter($this->getRequest()->getPost('adduser_departement'));
			$adduser_region = $filter->filter($this->getRequest()->getPost('adduser_region'));
			$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adressecomplete'));

			$adresse_type = $this->getRequest()->getPost('address_type');
			if ($adresse_type == 'new') {
				$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse'));
				$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp'));
				$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville'));
				$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays'));
				$adduser_departement = $filter->filter($this->getRequest()->getPost('adduser_departement'));
				$adduser_region = $filter->filter($this->getRequest()->getPost('adduser_region'));
				$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adressecomplete'));
			} else {
				$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse_old'));
				$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp_old'));
				$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville_old'));
				$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays_old'));
				$adduser_departement = '';
				$adduser_region = '';
				$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adresse_old'));
			}

			$adduser_raisonsocial = $filterMaj->filter($this->getRequest()->getPost('adduser_raisonsocial'));
			$adduser_siret = $filterMaj->filter($this->getRequest()->getPost('adduser_siret'));
			$adduser_numidfisc = $filterMaj->filter($this->getRequest()->getPost('adduser_numidfisc'));
			$adduser_codeape = $filterMaj->filter($this->getRequest()->getPost('adduser_codeape'));
			$adduser_sectactivite = $filterMaj->filter($this->getRequest()->getPost('adduser_sectactivite'));

			$adduser_comm = $filter->filter($this->getRequest()->getPost('adduser_comm'));

			$adduser_newsletter = $filter->filter($this->getRequest()->getPost('adduser_newsletter'));

			$typeUser = $filter->filter($this->getRequest()->getPost('adduser_typeuser'));

			$date = new Zend_Date();
			$dateinsc = $date->toString('YYYY-MM-dd HH:mm:ss');

			$data = array(
                                  'LOGIN' => $adduser_login, 
                                  'MDP' => md5($adduser_mdp), 
                                  'ROLE' => 0, 
                                  'NOM' => $adduser_nom, 
                                  'PRENOM' => $adduser_prenom,
                                  'CIVILITE' => $adduser_civility, 
                                  'FONCTION' => $adduser_fct, 
                                  'RAISONSOCIAL' => $adduser_raisonsocial, 
                                  'ADRESSE' => $adduser_adresse, 
                                  'CP' => $adduser_cp, 
                                  'VILLE' => $adduser_ville, 
                                  'DEPARTEMENT' => $adduser_departement, 
                                  'REGION' => $adduser_region, 
								  'ADRESSECOMPLETE' => $adduser_adressecomplete,
                                  'PAYS' => $adduser_pays, 
                                  'EMAIL' => $adduser_email, 
                                  'TEL' => $adduser_tel, 
                                  'FAX' => $adduser_fax, 
                                  'SIRET' => $adduser_siret, 
								  'NUMIDFISC' => $adduser_numidfisc,
                                  'CODEAPE' => $adduser_codeape, 
                                  'SECTACTIVITE' => $adduser_sectactivite, 
                                  'COMMENTAIRE' => $adduser_comm,  
                                  'TYPE' => $typeUser, 
                                  'DATEINSC' => $dateinsc);

			$isTypeOk = false;
			if ($validator2->isValid($typeUser)) {
				$isTypeOk = true;
			}

			$errorType = 0;
			if ($validator->isValid($adduser_mdp) && $validator->isValid($adduser_mdp2) &&
			$validator2->isValid($adduser_civility) &&
			$validator2->isValid($adduser_nom) && $validator2->isValid($adduser_adresse) &&
			$validator2->isValid($adduser_prenom) && $validator2->isValid($adduser_ville) &&
			$validator2->isValid($adduser_pays) &&
			$validatorEmail->isValid($adduser_login) && $validator2->isValid($adduser_cp)
			) {
				if ($isTypeOk) {
					if ($typeUser == "Professionnel") {
						if ($validator2->isValid($adduser_raisonsocial) &&
						$validator2->isValid($adduser_siret) &&
						$validator2->isValid($adduser_numidfisc) &&
						$validator2->isValid($adduser_codeape)) {

						} else {
							$errorType = 3;
							foreach ($validator2->getErrors() as $errorCode) {
								$this->view->messageErrorAddUser =  $this->getErrorValidator($errorCode);
							}
						}
					}
				} else {
					$errorType = 2;
					$this->view->messageErrorAddUser =  "Vous devez choisir entre Particulier et Professionnel. ";
				}
			} else {
				$errorType = 1;
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageErrorAddUser =  $this->getErrorValidator($errorCode);
				}
				foreach ($validator2->getErrors() as $errorCode) {
					$this->view->messageErrorAddUser =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageErrorAddUser =  $this->getErrorValidator($errorCode);
				}
			}


			if ($errorType == 0) {
				if ($validatorTel->isValid($adduser_tel)) {
					if ($adduser_mdp2 == $adduser_mdp) {

						try {
							$user = new User();

							$isExistLogin = $user->fetchRow("LOGIN = '".$adduser_login."'");

							if (!$isExistLogin) {

								$isExistEmail = $user->fetchRow("EMAIL = '".$adduser_email."'");
								if (!$isExistEmail) {
									$isAdd = $user->insert($data);
									$this->log("Nouveau client : ".$adduser_email,'info');
									if ($adduser_newsletter) {
										$user_newsletter = new UserNewsletter();
										$code = md5($dateinsc.'_'.$adduser_email);
											
										$isExistNL = $user_newsletter->fetchRow("EMAIL = '".$adduser_email."'");

										if(!$isExistNL) {
											$dataNL = array(
						 	 					'EMAIL' => $adduser_email,
						 	 					'DATEINS' => $dateinsc,
						 	 					'CODE' => $code
											);
											$user_newsletter->insert($dataNL);
										}
									}
									$messageSuccess = $this->connectMe($adduser_login, $adduser_mdp);
									if ($messageSuccess != "SUCCESS") {
										$this->view->messageErrorAddUser = $messageSuccess;
									}

								} else {
									$this->view->messageErrorAddUser =  "L'email est d�j� utilis�.";
								}
							} else {
								$this->view->messageErrorAddUser =  "L'identifiant existe d�j�";
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$data['newsletter'] = $adduser_newsletter;
							$this->view->populateFormAdd = $data;
							$this->view->messageErrorAddUser =  "Une erreur est survenue, v�rifier vos informations.";
							$this->render('connexion');
						}
					} else {
						$this->view->messageErrorAddUser =  "V�rifier votre mot de passe";
					}
				} else {
					$this->view->messageErrorAddUser =  "V�rifier votre num�ro de t�l�phone";
				}
			}

			$data['newsletter'] = $adduser_newsletter;
			$this->view->populateFormAdd = $data;

		}
		if ($isAdd) {
			$currentAncre = $this->getRequest()->getPost('current_save_ancre');
			if (isset($currentAncre) && !empty($currentAncre)) {
				if ($currentAncre == "commandes") {
					$this->_redirect('/mon-compte.html#commandes');
				} else if ($currentAncre == "selection") {
					$this->_redirect('/mon-compte.html#selection');
				}
			} else {
				$userNamespace = $this->getSession();
				$myCaddyTemp = $userNamespace->myObjectCaddy;
				if (isset($myCaddyTemp->items) && !empty($myCaddyTemp->items)) {
					$this->_redirect('/mon-panier.html');
				} else {
					$this->_redirect('/');
				}
			}
		} else {
			$currentAncre = $this->getRequest()->getPost('current_save_ancre');
			if (isset($currentAncre) && !empty($currentAncre)) {
				$this->view->current_save_ancre = $currentAncre;
			}
			$this->render('connexion');
		}
	}

	public function actualiserAction() {

		$linksMenu[0]['NAVURL'] = '/mon-compte.html';
		$linksMenu[0]['NAVNOM'] = 'Mon compte';
		$this->view->linksMenu = $linksMenu;
		if ($this->getRequest()->isPost()) {

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());
			$filter2 = new Zend_Filter();
			$filter2->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_Digits());

			$filterMaj = new Zend_Filter();
			$filterMaj->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StringToUpper());


			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$validatorTel = new Zend_Validate();
			$validatorTel -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(10));

			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());


			$validatorEmail = new Zend_Validate_EmailAddress();

			$edituser_civility = $filter->filter($this->getRequest()->getPost('edituser_civility'));
			$edituser_nom = $filterMaj->filter($this->getRequest()->getPost('edituser_nom'));
			$edituser_prenom = $filter->filter($this->getRequest()->getPost('edituser_prenom'));
			$edituser_fct = $filter->filter($this->getRequest()->getPost('edituser_fct'));
			$edituser_tel = $filter2->filter($this->getRequest()->getPost('edituser_tel'));
			$edituser_fax = $filter2->filter($this->getRequest()->getPost('edituser_fax'));
			$edituser_email = $filter->filter($this->getRequest()->getPost('edituser_email'));

			$adresse_type = $this->getRequest()->getPost('address_type');
			if ($adresse_type == 'new') {
				$edituser_adresse = $filter->filter($this->getRequest()->getPost('edituser_adresse'));
				$edituser_cp = $filter->filter($this->getRequest()->getPost('edituser_cp'));
				$edituser_ville = $filter->filter($this->getRequest()->getPost('edituser_ville'));
				$edituser_pays = $filter->filter($this->getRequest()->getPost('edituser_pays'));
				$edituser_departement = $filter->filter($this->getRequest()->getPost('edituser_departement'));
				$edituser_region = $filter->filter($this->getRequest()->getPost('edituser_region'));
				$edituser_adressecomplete = $filter->filter($this->getRequest()->getPost('edituser_adressecomplete'));
			} else {
				$edituser_adresse = $filter->filter($this->getRequest()->getPost('edituser_adresse_old'));
				$edituser_cp = $filter->filter($this->getRequest()->getPost('edituser_cp_old'));
				$edituser_ville = $filter->filter($this->getRequest()->getPost('edituser_ville_old'));
				$edituser_pays = $filter->filter($this->getRequest()->getPost('edituser_pays_old'));
				$edituser_departement = '';
				$edituser_region = '';
				$edituser_adressecomplete = $filter->filter($this->getRequest()->getPost('edituser_adresse_old'));
			}

			$edituser_raisonsocial = $filterMaj->filter($this->getRequest()->getPost('edituser_raisonsocial'));
			$edituser_siret = $filterMaj->filter($this->getRequest()->getPost('edituser_siret'));
			$edituser_numidfisc = $filterMaj->filter($this->getRequest()->getPost('edituser_numidfisc'));
			$edituser_codeape = $filterMaj->filter($this->getRequest()->getPost('edituser_codeape'));
			$edituser_sectactivite = $filterMaj->filter($this->getRequest()->getPost('edituser_sectactivite'));

			$edituser_comm = $filter->filter($this->getRequest()->getPost('edituser_comm'));
			//$edituser_modepaiement = $filter->filter($this->getRequest()->getPost('edituser_modepaiement'));

			$typeUser = $filter->filter($this->getRequest()->getPost('edituser_typeuser'));


			$isTypeOk = false;
			if ($validator2->isValid($typeUser)) {
				$isTypeOk = true;
			}

			$errorType = 0;
			if ($validator2->isValid($edituser_civility) &&
			$validator2->isValid($edituser_nom) && $validator2->isValid($edituser_adresse) &&
			$validator2->isValid($edituser_prenom) && $validator2->isValid($edituser_ville) &&
			$validator2->isValid($edituser_pays) &&
			$validatorEmail->isValid($edituser_email)  && $validator2->isValid($edituser_cp)
			) {
				if ($isTypeOk) {
					if ($typeUser == "Professionnel") {
						if ($validator2->isValid($edituser_raisonsocial) &&
						$validator2->isValid($edituser_siret) &&
						$validator2->isValid($edituser_numidfisc) &&
						$validator2->isValid($edituser_codeape)) {

						} else {
							$errorType = 3;
							foreach ($validator2->getErrors() as $errorCode) {
								$this->view->messageErrorEditUser =  $this->getErrorValidator($errorCode);
							}
						}
					}
				} else {
					$errorType = 2;
					$this->view->messageErrorEditUser =  "Vous devez choisir entre Particulier et Professionnel. ";
				}
			} else {
				$errorType = 1;
					
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageErrorEditUser =  $this->getErrorValidator($errorCode);
				}
				foreach ($validator2->getErrors() as $errorCode) {
					$this->view->messageErrorEditUser =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageErrorEditUser =  $this->getErrorValidator($errorCode);
				}
			}


			if ($errorType == 0) {
				if ($typeUser == "Particulier") {
					//$edituser_modepaiement = 1;
					$edituser_raisonsocial = "";
				}

				if ($validatorTel->isValid($edituser_tel)) {

					try {
						$user = new User();
						$auth = Zend_Auth::getInstance();
						$auth->setStorage($this->getSessionStorage());
						$storage = $auth->getStorage()->read();
						$isExistEmail = $user->fetchRow("EMAIL = '".$edituser_email."' AND ID <> ".$storage['user']['id']);
						/*
						 if($storage['user']['iscredit'] == 0 && ($edituser_modepaiement != 1 && $edituser_modepaiement != 2 && $edituser_modepaiement != 6) ) {
							$edituser_modepaiement = 1;
							}
							*/
						$data = array(
	                                  'ROLE' => 0, 
	                                  'NOM' => $edituser_nom, 
	                                  'PRENOM' => $edituser_prenom,
	                                  'CIVILITE' => $edituser_civility, 
	                                  'FONCTION' => $edituser_fct, 
	                                  'RAISONSOCIAL' => $edituser_raisonsocial, 
	                                  'ADRESSE' => $edituser_adresse, 
	                                  'CP' => $edituser_cp, 
	                                  'VILLE' => $edituser_ville, 
	                                  'PAYS' => $edituser_pays, 
	                                  'DEPARTEMENT' => $edituser_departement, 
	                                  'REGION' => $edituser_region, 
	                                  'ADRESSECOMPLETE' => $edituser_adressecomplete, 
	                                  'EMAIL' => $edituser_email, 
	                                  'TEL' => $edituser_tel, 
	                                  'FAX' => $edituser_fax, 
	                                  'SIRET' => $edituser_siret, 
									  'NUMIDFISC' => $edituser_numidfisc,
	                                  'CODEAPE' => $edituser_codeape, 
	                                  'SECTACTIVITE' => $edituser_sectactivite, 
	                                  'COMMENTAIRE' => $edituser_comm,  
	                                  'TYPE' => $typeUser);

						if (!$isExistEmail) {

							$isEdit = $user->update($data, 'ID = '.$storage['user']['id']);

							$myUser = $user->fetchRow("ID = ".$storage['user']['id']);

							$userAuth = $this->computUserInfo($myUser);

							$storage = $auth->getStorage();
							$storage->write(array( 'user' => $userAuth));

							$this->view->user = $userAuth;

							$this->view->messageSuccessEditUser =  "Vos informations ont �t� modifi�es.";
						} else {
							$this->view->messageErrorEditUser =  "L'email est d�j� utilis�";
						}
					} catch (Zend_Exception $e) {
						$this->view->messageErrorEditUser =  "Une erreur est survenue, v�rifier vos informations";
						$this->_forward('moncompte');
					}
				} else {
					$this->view->messageErrorEditUser =  "V�rifier votre num�ro de t�l�phone";
				}
			}
		}
		$this->_forward('moncompte');
	}

	public function modifierAction() {

		$linksMenu[0]['NAVURL'] = '/mon-compte.html';
		$linksMenu[0]['NAVNOM'] = 'Mon compte';
		$this->view->linksMenu = $linksMenu;
		if ($this->getRequest()->isPost()) {

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$validatorEmail = new Zend_Validate_EmailAddress();

			$edituser_login = $filter->filter($this->getRequest()->getPost('edituser_login'));
			$edituser_mdp = $filter->filter($this->getRequest()->getPost('edituser_mdp'));
			$edituser_mdp2 = $filter->filter($this->getRequest()->getPost('edituser_mdp2'));

			$data = array(
                   'LOGIN' => $edituser_login, 
                   'MDP' => md5($edituser_mdp));

			if (
			$validator->isValid($edituser_login) &&
			$validator->isValid($edituser_mdp) &&
			$validator->isValid($edituser_mdp2) &&
			$validatorEmail->isValid($edituser_login)
			) {
				if ($edituser_mdp2 == $edituser_mdp) {

					try {
						$user = new User();
							
						$auth = Zend_Auth::getInstance();
						$auth->setStorage($this->getSessionStorage());
						$storage = $auth->getStorage()->read();
							
						$isExistLogin = $user->fetchRow("LOGIN = '".$edituser_login."' AND ID <> ".$storage['user']['id']);

						if (!$isExistLogin) {
							$isEdit = $user->update($data,'ID = '.$storage['user']['id']);

							$messageResult = $this->connectMe($edituser_login,$edituser_mdp);

							if ($messageResult == "SUCCESS") {
								$auth = Zend_Auth::getInstance();
								$auth->setStorage($this->getSessionStorage());
								$storage = $auth->getStorage()->read();

								if ($auth->hasIdentity() && isset($storage['user'])) {
									$this->view->user = $storage['user'];
								}
							}
							$this->view->messageSuccessEditUser =  "Vos identifiants ont �t� modifi�s.";

						} else {
							$this->view->messageErrorEditUser =  "L'identifiant existe d�j�";
						}
					} catch (Zend_Exception $e) {
						$this->view->messageErrorEditUser =  "Une erreur est survenue, v�rifier vos informations.";
						$this->_forward('moncompte');
					}
				} else {
					$this->view->messageErrorEditUser =  "V�rifier votre mot de passe";
				}
			}  else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageErrorEditUser =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageErrorEditUser =  $this->getErrorValidator($errorCode);
				}
			}

			$this->_forward('moncompte');

		}
	}



	public function retrievecommandbyrefAction() {
		$result = "ERROR";
		if ($this->getRequest()->isPost()) {
			try {
				$params = $this->getRequest()->getPost();
				$refCommand = $params["ref"];
				$auth = Zend_Auth::getInstance();
				$auth->setStorage($this->getSessionStorage());
				$storage = $auth->getStorage()->read();

				if ($auth->hasIdentity() && isset($storage['user']) &&
				isset($refCommand) && !empty($refCommand)) {

					$myCaddy = new Caddy();

					$command = new Command();
					$resultCommand = $command->findCommandCaddyRetrieve($storage['user']['id'],$refCommand );

					foreach ($resultCommand AS $row) {
						$item = new Item();

						$item->idChild = $row['CHILDID'];
						$item->qteChild = $row['CHILDQUANTITY'];
						$item->idProduit = $row['PRODUCTID'];
						$item->nom = $row['PRODUCTNOM'];
						$item->descshort = $row['DESCSHORT'];
						$item->navnom = $this->verifyNavigationString($row['PRODUCTNAVNOM'],$row['PRODUCTNOM'], '');
						$item->url = $row['URL'];
						$item->designation = $row['DESIGNATION'];
						$item->isAccessoire = 'N';
						$item->stock = $row['STOCK'];
						$item->selectedOption = $row['SELECTEDOPTION'];

						array_push($myCaddy->items, $item);
					}

					$userNamespace = $this->getSession();
					$userNamespace->myObjectCaddy = $myCaddy;
					$result = "SUCCESS";
				}
			} catch (Zend_Exception $e) {
				$this->log("Error retrievecommandbyref : ".$e->getMessage(),'err');
			}
		}
		$this->view->messageSuccess = $result;
		$this->_forward('ajaxvalue', 'ajax');
	}

	private function retrievecommandbyuser() {
		try {
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();

			if ($auth->hasIdentity() && isset($storage['user'])) {
				$userNamespace = $this->getSession();
				if (isset($userNamespace->myObjectCaddy)) {
					$caddyTemp = $userNamespace->myObjectCaddy;
					if (!empty($caddyTemp->items)) { return false; }
				}
					
				$myCaddy = new Caddy();
				$myCaddy->getCaddyTemp($storage['user']['id']);
				$userNamespace->myObjectCaddy = $myCaddy;
			}
		} catch (Zend_Exception $e) {
			$this->log("Error retrievecommandbyuser : ".$e->getMessage(),'err');
		}
		return false;
	}


	public function ajaxdeletedevisAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if ($this->isConnected()) {
			$user = $this->getStorageUser();
			$command = new Command();
			if($this->_request->getParam('id')) {
				$id = (int)$this->_request->getParam('id');
				if ($id > 0) {
					try {
						$result = $command->deleteDevisByUser($user['id'], $id);

						if ($result == 'OK') {
							$this->view->messageSuccess = "Le devis a �t� supprim�";
							$this->log("Le devis a �t� supprim�",'info');
						} else if ($result == 'USER') {
							$this->view->messageError = "Le devis n'a pas �t� supprim�, vous n'avez pas les droits.";
							$this->log("Le devis n'a pas �t� supprim�, vous n'avez pas les droits",'warn');
						} else {
							$this->view->messageError = "Le devis n'a pas �t� supprim�, vous n'avez pas les droits.";
							$this->log("Le devis n'a pas �t� supprim�, vous n'avez pas les droits",'err');
						}
					} catch (Zend_Exception $e) {
						$this->log($e->getMessage(),'err');
						$this->view->messageError = $e->getMessage();
					}
				}
			}
			$this->view->myDevis = $command->findDevisByUser($user['id']);
		}

		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render('ajaxlistdevis');
	}


	private function getCaddyTypeByUserConnected() {
		$caddyType = array();
		try {
			if ($this->isConnected()) {
				$user = $this->getStorageUser();
				if ($user['iscaddytype'] == 'Y') {
					$userNamespace = $this->getSession();
					if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
					$caddy = $userNamespace->myObjectCaddy;
					$userCaddyType = new UserCaddyType();
					$caddyType = $userCaddyType->computeFrontCaddyTypeByUser($user, $caddy, true);
				}
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
		return $caddyType;
	}

	public function sendmailtoconseillerAction() {
		try {
			$botDetector = new BotDetector();
			$isBot = $botDetector->isBot(getenv("HTTP_USER_AGENT"));
			if ($isBot != 'ERROR') {
				$this->_redirect($this->baseUrl_SiteCommerceUrl);
			}
				
			$linksMenu[0]['NAVURL'] = '/contacter-un-conseiller.html';
			$linksMenu[0]['NAVNOM'] = "Demande d'informations";
			$this->view->linksMenu = $linksMenu;

			if ($this->isConnected()) { $this->view->isConnected = true;
			} else { $this->view->isConnected = false; }

			if ($this->getRequest()->isPost()) {

				$filter = new Zend_Filter();
				$filter	->addFilter(new Zend_Filter_StripTags())
				->addFilter(new Zend_Filter_StringTrim());

				$validatorMessage = new Zend_Validate();
				$validatorMessage -> addValidator(new Zend_Validate_NotEmpty())
				-> addValidator(new Zend_Validate_StringLength(4));

				$validatorTel = new Zend_Validate();
				$validatorTel -> addValidator(new Zend_Validate_NotEmpty())
				-> addValidator(new Zend_Validate_StringLength(10));

				$validatorEmail = new Zend_Validate_EmailAddress();
					

				$params = $this->getRequest()->getPost();
				$message = $filter->filter($params['user_message']);
				$tel = "";
				$email = "";
				$messageNotConnected = "";
				$user = array();
				$fromEmail = $this->no_reply_Mail;
				$fromName = "Invit�";

				$isMailValid = false;

				if ($this->isConnected()) {
					$user = $this->getStorageUser();
					$fromEmail = $user['email'];
					$fromName = $user['prenom']." ".$user['prenom'];
					$tel = $user['tel'];
					$email = $user['email'];
					$isMailValid = true;
				} else {
					$messageNotConnected = 'Non connect�';
					$messageNotConnected .= '<br /><br />';
					$messageNotConnected .= 'IP : '.$_SERVER['REMOTE_ADDR'];
					$messageNotConnected .= '<br /><br />';

					$tel = $filter->filter($params['user_tel']);
					$email = $filter->filter($params['user_email']);
						
					if ($validatorTel->isValid($tel) || $validatorEmail->isValid($email)) {
						$isMailValid = true;
						if (!empty($email)) { $fromEmail = $email; $messageNotConnected .= 'Email : '.$email.'<br /><br />';}
						if (!empty($tel)) { $messageNotConnected .= 'T�l�phone : '.$tel.'<br /><br />'; }
					} else {
						$this->view->messageErrorAskConseiller = "Vous devez nous communiquer votre <b>email</b> ou votre <b>t�l�phone</b> pour prendre contact avec vous.";
					}
				}
				if ($isMailValid) {
					if ($validatorMessage->isValid($message)) {
						$isSend = $this->sendMailToCommercial($message, $messageNotConnected, $user, $fromEmail, $fromName);
						if ($isSend) {
							$this->view->messageSuccessAskConseiller = "Votre demande d'informations a �t� envoy�, un conseiller vous contactera au plus vite.";
						} else {
							$this->view->messageErrorAskConseiller = "Votre demande d'informations n'a pas �t� envoy�, contactez nous au ".$this->tel_contact.".";
						}
					} else {
						$this->view->messageErrorAskConseiller = "Votre message doit contenir au moins 4 caract�res.";
					}
				}
					
				$this->view->messageMail = $email;
				$this->view->messageTel = $tel;
				$this->view->messageBody = $message;
			}
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	private function sendMailToCommercial($message,$messageNotConnected, $user, $fromEmail, $fromName) {
		try {
			$view = new Zend_View();
			$view->addScriptPath('../application/modules/default/views/helpers/');
			$view->assign("message",$message);
			$view->assign("messageNotConnected",$messageNotConnected);
			$view->assign("user",$user);
				
			$body = $view->render("mail_user_to_commercial.phtml");
			$subject = "[INFORMATION] ".$fromName;
				
			$mail = new Zend_Mail();
			$mail->setBodyHtml($body);
			$mail->setFrom($fromEmail, $fromName);
			$mail->addTo($this->serviceClient_Mail);
			$mail->setSubject($subject);

			$mail->send();
			$this->log("L'email de demande d'informations a �t� envoy� par : ".$fromEmail.", ".$fromName,'info');
			return true;
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
		return false;
	}
}
?>SupplierController.php000060400000046770150713030120011126 0ustar00<?php
class Backoffice_SupplierController extends Modules_Backoffice_Controllers_MainController
{
	
	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Supplier";
		$this->isConnectedWithRole('isSupplier');
	}
	function indexAction()
	{
		$this->_forward('/list');
		
	}
	function searchAction()
	{
		 $this->view->titlePage = "Rechercher un Fournisseur";
		$adminNamespace = $this->getSession();	 
	    $this->view->messageSuccess = "";
		$this->view->messageError = "";
		
	    
	    if ($this->getRequest()->isPost()) {
			$post = $this->getRequest()->getPost();
			
			
			$recherche = '%'.$post['searchValue'].'%';
			
			$this->view->titlePage .= " : ".$post['searchValue']; 
			//Appel model pour listing
			$supplier = new Supplier();
			$supplierBrend = new SupplierBrend();
			
			if ($post['searchType'] != 'BREND') {
	    		$select = $supplier->select()
	    				->where($post['searchType'].' LIKE ? ',$recherche)
	    				->order($post['searchType'].' ASC ');
	    		$listsuppliers = $supplier->fetchAll($select)->toArray();
			} else {
				$select = "SELECT s.*
					 FROM supplier AS s
						LEFT JOIN supplier_brend AS sb ON sb.IDSUPPLIER = s.ID";
						if (!empty($post['searchType'])) {
							$select .= " WHERE sb.".$post['searchType']." LIKE '".$recherche."' ";
						}
						
				$select .= " ORDER BY BREND ASC";
				$listsuppliers = $supplier->getAdapter()->fetchAll($select);
			}
			
			$this->view->listsupplierCount = count($listsuppliers);
			$this->view->listsupplier = $listsuppliers;
			
			if ($this->view->listsupplierCount == 0) {
				$this->view->messageError = "Aucun resultats";
			}
	    } 
	}
	function editbrendAction () {
		
		if ($this->getRequest()->isPost()) {
		 //get the form params
			$params = $this->getRequest()->getPost();
			//filtres pour changer les chaines
		 	$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim());
		 	
			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
					   -> addValidator(new Zend_Validate_StringLength(2));
	
            $isShowBrendPage = (int)$params['isshowbrendpage'];
                       
			//Refractor the params
			$dataBrend = array (
			 		'BREND' => $filter->filter($params['brend']),
			 		'IS_SHOW_BREND_PAGE' => $isShowBrendPage
			);
             
			$supplierBrend = new SupplierBrend();
			$supplier = new Supplier();
			
		 	if ($validator->isValid($dataBrend['BREND'])) {
		 		
			 	try {
			 		$isExistBrend = $supplierBrend->fetchRow("BREND LIKE '".$dataBrend['BREND']."' AND ID <> ".$params['idBrend']);
		 		 	
			 		if (!$isExistBrend) {
			 			$supplierBrend->update($dataBrend, 'ID = '.$params['idBrend']);
				 	 	$this->view->messageSuccess = "La marque a �t� modif�e";
			 		} else {
			 			$this->view->messageError = "La marque existe d�j�";
			 		}
			 	
			 	} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				    $this->view->messageError = "La marque existe d�j�";
		    	 	
				}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 	}
		 	$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
	}
	
	
	function addbrendAction () {
		
		if ($this->getRequest()->isPost()) {
		 //get the form params
			$params = $this->getRequest()->getPost();
			//filtres pour changer les chaines
		 	$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim());
		 	
			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
					   -> addValidator(new Zend_Validate_StringLength(2));
	
				   
			//Refractor the params
			$dataBrend = array (
			 		'BREND' => $filter->filter($params['brend']),
			 		'IDSUPPLIER' => $filter->filter($params['id']),
					'URL' => ''
			);
			$supplierBrend = new SupplierBrend();
			$supplier = new Supplier();
			
		 	if ($validator->isValid($dataBrend['BREND'])) {
		 		
			 	try {
			 		
			 		
			 		$isExistBrend = $supplierBrend->fetchRow("BREND LIKE '".$dataBrend['BREND']."'");
		 		 	
			 		if (!$isExistBrend) {
			 			if (!empty($_FILES['picture']['name'])) {
			 				$url = $this->uploadNewPicsGetURL('picture');
					 	 	 if ($url != false) {
					 	 	 	$dataBrend['URL'] = $url;
					 	 	 }
			 			}
			 			
				 	 	 $supplierBrend->insert($dataBrend);
				 	 	$this->view->messageSuccess = "La marque a �t� ajout�e";
			 		} else {
			 			$this->view->messageError = "La marque existe d�j�";
			 		}
			 	
			 	} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				    $this->view->messageError = "La marque existe d�j�";
		    	 	
				}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 	}
		 	$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
	}
	
	function delbrendAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		$supplier = new Supplier();
		$supplierBrend = new SupplierBrend();
		if ($this->getRequest()->isPost('delBrendForm')) {
		
			$params = $this->getRequest()->getPost();
			
			try {
				$product = new Product(); 	 
				
				$isExistProduct = $product->fetchRow("IDBREND = ".$params['idBrend']);
		 		 	
			 		if (!$isExistProduct) {
			    		$supplierBrend->delete('ID = '.$params['idBrend']);
			    		
			    		$this->view->messageSuccess = "La marque a �t� supprim�e";
			 		} else {
			 			$this->view->messageError = "La marque est utilis�e par un produit : <b>".$isExistProduct['NOM']."</b>";
			 		}
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
		 		$this->view->messageError = $e->getMessage();    
			}
			$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');
	}
function editAction()
    {
    	
		$this->view->titlePage = "Modifier un fournisseur";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		 
		//filtres pour changer les chaines
		 	$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim());
		 	
		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty());
	
		$validatorEmail = new Zend_Validate_EmailAddress();
    	
		$supplier = new Supplier();	
		$supplierBrend = new SupplierBrend();

		if ($this->getRequest()->isPost() && $this->getRequest()->getPost('company')) {
		 	
			//get the form params
			$params = $this->_request->getPost();
			
			//Refractor the params
			$dataSupplier = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'PRENOM' => $filter->filter($params['prenom']),
			 		'COMPANY' => $filter->filter($params['company']),
			 		'ADDRESSE' => $filter->filter($params['address']),
			 		'CP' => $filter->filter($params['cp']),
			 		'VILLE' => $filter->filter($params['ville']),
			 		'EMAIL' => $filter->filter($params['email']),
			 		'TEL' => $filter->filter($params['tel']),
			 		'FAX' => $filter->filter($params['fax']),
			 		'DESCRIPTIONSHORT' => $filter->filter($params['descshort']),
			 		'DESCRIPTIONLONG' => $params['desclong']
			);
			
		 	if ($validator->isValid($dataSupplier['NOM']) &&
			 	$validator->isValid($dataSupplier['PRENOM']) &&
			 	$validator->isValid($dataSupplier['COMPANY']) &&
			 	$validatorEmail->isValid($dataSupplier['EMAIL']) 
		 	) {
		 		
			 	try {
			 		
			 	 $id = (int)$params['id'];
			 	 
			 	 if ( $id > 0) {
			 	 	
		 		 		$isExistSupplier = $supplier->fetchRow("COMPANY LIKE '".$dataSupplier['COMPANY']."' AND ID <> ".$id);
		 		 		
		 		 		if (!$isExistSupplier) {
				 	 		$url = $this->uploadNewPicsGetURL('picture');
					 		if ($url != false) {
						 		$dataSupplier['URL'] = $url;
						 		$supplier->update($dataSupplier,'ID = '.$id);
						 		 $this->view->messageSuccess = "Le fournisseur a �t� modifi�, l'image a �t� upload�e"; 
					 		} else {
					 			 $supplier->update($dataSupplier, 'ID = '.$id);
					 			 $this->view->messageSuccess = "Le fournisseur a �t� modifi�"; 
					 		}	
		 		 		}  else {
					 		 $this->view->messageError= "Le fournisseur existe d�j�"; 
		 		 		} 	
			 	 }
			 	} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
		    	 	$this->view->populateFormSupplier = $dataSupplier;
			    
				}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 		foreach ($validatorEmail->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
			   $this->view->populateFormSupplier = $dataSupplier;
		 	}
		 	
		 }
			 if ($this->getRequest()->getParam('id')) {
			 	$id = (int)$this->getRequest()->getParam('id');
			 }
	     	if ($this->getRequest()->isPost('addBrendForm') ||
				 $this->getRequest()->isPost('editSupplierForm') 
			 ) { 
				$params = $this->_request->getPost();
			 	$id = $params['id'];
			 }
		 	if ($id>0) {
		 		$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$id);
		 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$id)->toArray();
		 	}
    }
    
	function addAction()
    {
    	
		$this->view->titlePage = "Ajouter un fournisseur";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		 if ($this->_request->isPost('addSupplierForm')) {
		 	
		 	//filtres pour changer les chaines
		 	$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim());
		 	
			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());
			//valideurs pour FILE
			$validatorFile = new Zend_Validate();
			$validatorFile -> addValidator(new Zend_Validate_File_Exists())
					   -> addValidator(new Zend_Validate_File_IsImage());
					   
			$validatorEmail = new Zend_Validate_EmailAddress();
			 	   
			//get the form params
			$params = $this->_request->getPost();
			
			//Refractor the params
			$dataSupplier = array (
			 		'NOM' => $filter->filter($params['lastname']),
			 		'PRENOM' => $filter->filter($params['firstname']),
			 		'COMPANY' => $filter->filter($params['company']),
			 		'ADDRESSE' => $filter->filter($params['address']),
			 		'CP' => $filter->filter($params['cp']),
			 		'VILLE' => $filter->filter($params['ville']),
			 		'EMAIL' => $filter->filter($params['email']),
			 		'TEL' => $filter->filter($params['tel']),
			 		'FAX' => $filter->filter($params['fax']),
					'URL' => ''
			);
			$dataBrend = array (
			 		'BREND' => $filter->filter($params['brend']),
					'URL' => '',
					'IDSUPPLIER' => ''
			);
		 	if (
		 		$validator->isValid($dataBrend['BREND']) &&
		 		$validator->isValid($dataSupplier['NOM']) &&
			 	$validator->isValid($dataSupplier['PRENOM']) &&
			 	$validator->isValid($dataSupplier['COMPANY']) &&
			 	$validatorEmail->isValid($dataSupplier['EMAIL']) 
		 	) {
		 		 	try {
		 		 		$supplier = new Supplier();
		 		 		$supplierBrend = new SupplierBrend();
		 		 		
		 		 		$isExistBrend = $supplierBrend->fetchRow("BREND LIKE '".$dataBrend['BREND']."'");
		 		 		$isExistSupplier = $supplier->fetchRow("COMPANY LIKE '".$dataSupplier['COMPANY']."'");
		 		 		
		 		 		if (!$isExistBrend && !$isExistSupplier) {
					 		$url = $this->uploadNewPicsGetURL('picture');
					 		if ($url != false) {
						 		$dataBrend['URL'] = $url;
						 		$dataSupplier['URL'] = $url;
					 		}	
						 	 
					    	 $supplier->insert($dataSupplier);
					    	 
					    	 $lastid = $supplier->getAdapter()->lastInsertId();
					    	 $dataBrend['IDSUPPLIER'] = $lastid;
					    	 
					    	 
							 $supplierBrend->insert($dataBrend);
					    	
					    	 $this->view->messageSuccess = "Le fournisseur a �t� ajout�"; 
		 		 		} else {
		 		 			$this->view->messageError = "La marque ou le fournisseur existe d�j�"; 
					    	$this->view->populateFormSupplier = $dataSupplier;
					    	$this->view->populateFormBrend = $dataBrend;
		 		 		} 
				 	} catch (Zend_Exception $e) {
				 		
					$this->log($e->getMessage(),'err');
				    	$this->view->populateFormSupplier = $dataSupplier;
				    	$this->view->populateFormBrend = $dataBrend;
					}
		 	} else {		 		
			 	foreach ($validator->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 		foreach ($validatorEmail->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
		 		foreach ($validatorFile->getErrors() as $errorCode) {
			 		 $this->view->messageError =  $this->getErrorValidator($errorCode);
			    }
			    $this->view->populateFormSupplier = $dataSupplier;
			    $this->view->populateFormBrend = $dataBrend;
		 	}
		 	
		 }
    }
    
	function listAction()
	{
	    $this->view->titlePage = "Gestion des fournisseurs";
	    $adminNamespace = $this->getSession();	
	    
	    //Gestion des tris
    	$table = 'COMPANY';
		$tri = 'ASC';
		
	    if ($this->_request->getParam('col')) 
	    {
	    	$adminNamespace->triSupplierCol = $this->_request->getParam('col');
	    	($adminNamespace->triSupplierSens == 'ASC') ? $adminNamespace->triSupplierSens = 'DESC' : $adminNamespace->triSupplierSens = 'ASC';
	    } 
		 if (isset($adminNamespace->triSupplierCol)) {
	    	$table = $adminNamespace->triSupplierCol;
	    	$tri = $adminNamespace->triSupplierSens;
	    }
	    
	    //Appel model pour listing
		$supplier = new Supplier();
		
		$sql = "SELECT s.ID ID, s.COMPANY COMPANY,s.NOM NOM, s.PRENOM PRENOM, s.ADDRESSE ADDRESSE, s.CP CP, s.VILLE VILLE, s.EMAIL EMAIL, s.TEL TEL, s.FAX FAX,
					 s.URL URL
				FROM supplier AS s
				ORDER BY ".$table." ".$tri;
    	$result = $supplier->getAdapter()->fetchAll($sql);
	    
    	$this->view->listsupplier = $result;
	    
	}
	
	function delAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$product = new Product();
					$supplier = new Supplier();
					$supplierBrend = new SupplierBrend();
					
					$sql = "
						SELECT DISTINCT p.NOM NOMPRODUCT , sb.BREND BREND 
						FROM product AS p
						LEFT JOIN supplier_brend AS sb ON sb.ID = p.IDBREND
						LEFT JOIN supplier AS s ON s.ID = sb.IDSUPPLIER
						WHERE s.ID = ".$id;
					$isExistProduct = $product->getAdapter()->fetchRow($sql);
		 		 		
	 		 		if (!$isExistProduct) {
	 		 			$supplier->delete('ID = '.$id);
	    		
	 		 			$supplierBrend->delete('IDSUPPLIER = '.$id);
	    				$this->view->messageSuccess = "Le fournisseur a �t� supprim�";
	 		 		} else {
	 		 			$this->view->messageError = "La marque : <b>".$isExistProduct['BREND']."</b> poss�de des produits : <b>".$isExistProduct['NOMPRODUCT']."</b>";
			 		
	 		 		}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
			 		$this->view->messageError = $e->getMessage();    
				}
			}
		}
		$this->_forward('/list');	
		
	}
	
function uploadNewPicsGetURL($nomTemp) {
		if(!empty($_FILES[$nomTemp]) && !empty($_FILES[$nomTemp]['name'])) {
			$nomOrigine = $_FILES[$nomTemp]['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
			    $this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {    
			    // Copie dans le repertoire du script avec un nom
			    $repertoireDestination = 'items/supplier/';
				$this->checkDirectoryExist($repertoireDestination);

				$nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
                $fileoriginal = $repertoireDestination.$nomDestination;
			
			    if (move_uploaded_file($_FILES[$nomTemp]["tmp_name"],$fileoriginal)) {
			    	 	//Resize picture
                        $info = getimagesize($fileoriginal) ;
                        list($width_old, $height_old) = $info;
                        $maxwidth = $this->FeaturePictureResizeWidth;
                        $maxheight = $this->FeaturePictureResizeHeight;
                            
                        if ($width_old > $maxwidth || $height_old > $maxheight) {     
                            Utils_Tool::smart_resize_image($fileoriginal , null, $maxwidth , $maxheight , true , $fileoriginal , true , false ,50 );
                        }  
                        
						$data = array (
					 		'URL' => $fileoriginal
						);
			        	return $data['URL'];
			    	 
			    } else {
			        return false;
			    }
			}
		}
		
		return false;
	}

	
	function setpictureAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			$supplier = new Supplier();
			$supplierBrend = new SupplierBrend();
			try {
				$data = array (
				 		'URL' => $params['picture']
					);
					if ((int)$params['idSelected']>0) {
						$supplierBrend->update($data,'ID = '.$params['idSelected']);
		    			$this->view->messageSuccess = "L'image de la marque a �t� modifi�e";
					} else {
						$this->view->messageError = "Vous devez selectionner une marque";
					}
				
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
			 		$this->view->messageError = $e->getMessage();    
			}
			$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
		
	}

	function erasepictureAction() {
		
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			$product = new Product();
			$supplier = new Supplier();
			$supplierBrend = new SupplierBrend();
			try {
				$sql = "
						SELECT DISTINCT p.NOM NOMPRODUCT , sb.BREND BREND 
						FROM product AS p
						LEFT JOIN supplier_brend AS sb ON sb.ID = p.IDBREND
						LEFT JOIN supplier AS s ON s.ID = sb.IDSUPPLIER
						WHERE sb.URL = '".$params['picture']."'";
				$isExistProduct = $product->getAdapter()->fetchRow($sql);
		 		 		
					
				if (!$isExistProduct) {
					unlink($params['picture']);
					$data = array (
			 		'URL' => ''
					);
					$supplierBrend->update($data,"URL = '".$params['picture']."'");
		    		
		    		$this->view->messageSuccess = "L'image a �t� supprim�e d�finitivement";	
				} else {	
					$this->view->messageError = "La marque : <b>".$isExistProduct['BREND']."</b> poss�de des produits : <b/>".$isExistProduct['NOMPRODUCT']."</b>";
			 		
				}
				
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
		 		$this->view->messageError = $e->getMessage();    
			}
		
			$this->view->populateFormSupplier = $supplier->fetchRow('ID = '.$params['id']);
	 		$this->view->populateFormBrend = $supplierBrend->fetchAll('IDSUPPLIER = '.$params['id'])->toArray();
		 }
		 
		$this->render('/edit');	
	}
}
?>AnnoncefooterController.php000060400000012273150713030120012112 0ustar00<?php
class Backoffice_AnnoncefooterController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Gestion des annonces en bas de page";
		$this->view->currentMenu = "AnnonceFooter";
		$this->isConnectedWithRole('isPromo');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		$annonce = new AnnonceFooter();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonceFooter = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow'],
					'CONT_NAME' => '',
					'CAT_ID' => ''
					);

					if (isset($params['controllername'])) {
						foreach($params['controllername'] as $value)
						{
							$dataAnnonce['CONT_NAME'] .= $value.";";
						}
					}
					if (isset($params['categorie'])) {
						foreach($params['categorie'] as $value)
						{
							$dataAnnonce['CAT_ID'] .= $value.";";
						}
					}

					if ($validator->isValid($dataAnnonce['TITRE']) &&
					$validator->isValid($dataAnnonce['CONTENT'])
					) {
						try {
							$id = (int)$params['id'];
							if ( $id > 0) {
									
								$annonce->update($dataAnnonce,'ID = '.$id);
								$this->view->messageSuccess = "L'annonce a �t� modifi�e";
								$this->view->populateFormAnnonceFooter = $annonce->fetchRow('ID = '.$id);
								$this->log("L'annonce a �t� modifi�e ".$id,'info');
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceFooter = $dataAnnonce;
						}
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceFooter = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}


	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow'],
					'CONT_NAME' => '',
					'CAT_ID' => ''
					);
					if (isset($params['controllername'])) {
						foreach($params['controllername'] as $value)
						{
							$dataAnnonce['CONT_NAME'] .= $value.";";
						}
					}
					if (
					$validator->isValid($dataAnnonce['TITRE']) &&
					$validator->isValid($dataAnnonce['CONTENT'])
					) {
						try {
							$annonce = new AnnonceFooter();
							$annonce->insert($dataAnnonce);
							$this->view->messageSuccess = "L'annonce a �t� ajout�e";
							$this->log("L'annonce a �t� ajout�e",'info');
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceFooter = $dataAnnonce;
						}

					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceFooter = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des annonces en bas de page";
			
		//Appel model pour listing
		$annonces = new AnnonceFooter();
		$result = $annonces->select()->order('isSHOW ASC')->order('TITRE ASC')->query()->fetchAll();
			
		$this->view->listannoncefooter = $result;
	}



	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceFooter();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'annonce a �t� supprim�e";

					$this->log("L'annonce a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}

}
?>AnnonceController.php000060400000010457150713030120010675 0ustar00<?php
class Backoffice_AnnonceController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
 
		$this->isConnectedWithRole('isPromo');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une Annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		$annonce = new AnnonceContent();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow']
			);

			if ($validator->isValid($dataAnnonce['TITRE']) &&
			$validator->isValid($dataAnnonce['CONTENT'])
			) {
				try {
					$id = (int)$params['id'];
					if ( $id > 0) {
							
						$annonce->update($dataAnnonce,'ID = '.$id);
						$this->view->messageSuccess = "L'annonce a �t� modifi�e";
						$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
					}
				} catch (Zend_Exception $e) {
					$this->view->populateFormAnnonce = $dataAnnonce;
					$this->log($e->getMessage(),'err');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormAnnonce = $dataAnnonce;
			}

		}
		$this->_forward('/list');
	}

	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une Annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow']
			);
			if (
			$validator->isValid($dataAnnonce['TITRE']) &&
			$validator->isValid($dataAnnonce['CONTENT'])
			) {
				try {
					$annonce = new AnnonceContent();
					$annonce->insert($dataAnnonce);
					$this->view->messageSuccess = "L'annonce a �t� ajout�e";
				} catch (Zend_Exception $e) {
					$this->view->populateFormAnnonce = $dataAnnonce;
					$this->log($e->getMessage(),'err');
				}

			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormAnnonce = $dataAnnonce;
			}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Listing des Annonces";
		$adminNamespace = $this->getSession();
		 
		//Appel model pour listing
		$annonces = new AnnonceContent();
		$result = $annonces->select()->order('isSHOW ASC')->order('TITRE ASC')->query()->fetchAll();
				 
		$this->view->listannonce = $result;		 
	}

	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceContent();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'annonce a �t� supprim�e";

				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');
	}

}
?>ProductglobalController.php000060400000024125150713030120012112 0ustar00<?php
class Backoffice_ProductglobalController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Promos";
		$this->isConnectedWithRole('isAdmin'); 
	}
	function indexAction()
	{
		$this->_forward('/list');
	}

	public function listAction() {
		$this->view->titlePage = "G�n�ralit�s";
		$promoCommand = new PromoCommand();

		$isFrais = $promoCommand->fetchAll('MONTANTFRAISCMD > 0 AND MONTANTFRAISCMD IS NOT NULL','MONTANTFRAISCMD ASC');
		if ($isFrais) {
			$this->view->remiseFrais = $isFrais;
		}
		$isValide = $promoCommand->fetchRow('MONTANTVALID > 0 AND MONTANTVALID IS NOT NULL');
		if ($isValide) {
			$this->view->validCommand = $isValide;
		}
		
		
		$supplierBrend = new SupplierBrend();
		$this->view->listbrend = $supplierBrend->fetchAll($supplierBrend->select()->order('BREND ASC'));
		
	}

	public function addpricecategoryAction() {
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$idCatSelected = $params['listcategory'];
				$pricesign = $params['pricesign'];
				$pricepour = $params['pricepour'];

				if ($idCatSelected != 'none') {
					$pricepour = intval($pricepour);
					if ($pricepour > 0) {
						$category = new Category();
						$dataID = "";
						if ($idCatSelected == 0) {
							$data = $category->fetchAll();
							foreach ($data as $row) {
								if ($dataID == "") {
									$dataID = $row['ID'];
								} else {
									$dataID .= " , ".$row['ID'];
								}
							}
						} else {
							$dataID = $category->getAllSubsIDByIDToString($idCatSelected);
						}

						$product = new Product();
						$productChild = new ProductChild();

						$listProducts = $product->fetchAll('IDCATEGORY IN ('.$dataID.')');
						foreach ($listProducts as $rowProduct) {
							$actualProductPrice = $rowProduct['PRIX'];
							if ($pricesign == '+') {
								$newProductPrice = $rowProduct['PRIX'] + (($rowProduct['PRIX'] * $pricepour) / 100);
							} else {
								$newProductPrice = $rowProduct['PRIX'] - (($rowProduct['PRIX'] * $pricepour) / 100);
							}
							$newProductPrice = sprintf("%.2f",$newProductPrice);
							$dataProductUpdated = array();
							$dataProductUpdated['PRIX'] = $newProductPrice;
							$product->update($dataProductUpdated,'ID = '.$rowProduct['ID']);
								
							$listChilds = $productChild->fetchAll('IDPRODUCT = '.$rowProduct['ID']);
							foreach ($listChilds as $rowChild) {
								$actualPrice = $rowChild['PRIX'];
								if ($pricesign == '+') {
									$newPrice = $rowChild['PRIX'] + (($rowChild['PRIX'] * $pricepour) / 100);
								} else {
									$newPrice = $rowChild['PRIX'] - (($rowChild['PRIX'] * $pricepour) / 100);
								}
								$newPrice = sprintf("%.2f",$newPrice);
								$dataChildUpdated = array();
								$dataChildUpdated['PRIX'] = $newPrice;
								$productChild->update($dataChildUpdated,'ID = '.$rowChild['ID']);
							}

						}

						if ($pricesign == '+') {
							$this->view->messageSuccess = "Les produits ont �t� augment�s de ".$pricesign.$pricepour." % ";
						} else {
							$this->view->messageSuccess = "Les produits ont �t� diminu�s de ".$pricesign.$pricepour." % ";
						}
					} else {
						$this->view->messageError = "Le pourcentage doit �tre sup�rieur � 0";
					}
				} else {
					$this->view->messageError = "Une cat�gorie doit �tre s�lectionn�e";
				}


			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('list');
	}

	public function addpricebrendAction() {
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$idBrendSelected = $params['listbrend'];
				$pricesign = $params['pricesign'];
				$pricepour = $params['pricepour'];

				if ($idBrendSelected != 'none') {
					$pricepour = intval($pricepour);
					if ($pricepour > 0) {
						
						$product = new Product();
						$productChild = new ProductChild();

						$listProducts = $product->fetchAll('IDBREND = '.$idBrendSelected);
						foreach ($listProducts as $rowProduct) {
							$actualProductPrice = $rowProduct['PRIX'];
							if ($pricesign == '+') {
								$newProductPrice = $rowProduct['PRIX'] + (($rowProduct['PRIX'] * $pricepour) / 100);
							} else {
								$newProductPrice = $rowProduct['PRIX'] - (($rowProduct['PRIX'] * $pricepour) / 100);
							}
							$newProductPrice = sprintf("%.2f",$newProductPrice);
							$dataProductUpdated = array();
							$dataProductUpdated['PRIX'] = $newProductPrice;
							$product->update($dataProductUpdated,'ID = '.$rowProduct['ID']);
								
							$listChilds = $productChild->fetchAll('IDPRODUCT = '.$rowProduct['ID']);
							foreach ($listChilds as $rowChild) {
								$actualPrice = $rowChild['PRIX'];
								if ($pricesign == '+') {
									$newPrice = $rowChild['PRIX'] + (($rowChild['PRIX'] * $pricepour) / 100);
								} else {
									$newPrice = $rowChild['PRIX'] - (($rowChild['PRIX'] * $pricepour) / 100);
								}
								$newPrice = sprintf("%.2f",$newPrice);
								$dataChildUpdated = array();
								$dataChildUpdated['PRIX'] = $newPrice;
								$productChild->update($dataChildUpdated,'ID = '.$rowChild['ID']);
							}

						}

						if ($pricesign == '+') {
							$this->view->messageSuccess = "Les produits ont �t� augment�s de ".$pricesign.$pricepour." % ";
						} else {
							$this->view->messageSuccess = "Les produits ont �t� diminu�s de ".$pricesign.$pricepour." % ";
						}
					} else {
						$this->view->messageError = "Le pourcentage doit �tre sup�rieur � 0";
					}
				} else {
					$this->view->messageError = "Une marque doit �tre s�lectionn�e";
				}


			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		
		$this->_forward('list');
	}
	
	function commandaddAction() {
    try {
		if ($this->getRequest()->isPost()) {
	
			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());
	
			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());
	
	
			$promoCommand = new PromoCommand();
			$productChild = new ProductChild();
	
			$params = array();
			$params = $this->getRequest()->getPost();
	
			if ($params['remise'] == '5') {
				if (isset($params['montantfrais']) && (int)$params['montantfrais'] > 0 && $validator->isValid($params['montantfrais'])) {
					$isExistFrais = $promoCommand->fetchRow("MONTANTVALID IS NOT NULL");
					if ($isExistFrais) {
						$date = new Zend_Date();
	
						$data = array (
								'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
								'MONTANTVALID' => $filter->filter($params['montantfrais'])
						);
						$promoCommand->update($data,'ID = '.$isExistFrais['ID']);
	
						$this->view->messageSuccess = "La validit� de la commande a �t� modifi�e ";
	
					} else {
						$date = new Zend_Date();
	
						$data = array (
								'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
								'MONTANTVALID' => $filter->filter($params['montantfrais'])
						);
						$promoCommand->insert($data);
						$this->view->messageSuccess = "La validit� de la commande a �t� modifi�e ";
					}
				} else {
					$this->view->messageError = "Le montant de la commande doit etre sup�rieur � 0";
				}
			}
			if (isset($params['remisepour']) && isset($params['remiseeuro'])) {
					 
			    $remiseeuro = !empty($params['remiseeuro']) ? $params['remiseeuro'] : 0;
				$remisepour = (int)$params['remisepour'];
				$isOK = true;
				if ($remiseeuro > 0 && $remisepour > 0) {
					$this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE. ";
					$isOK = false;
				}
				if ($remiseeuro == 0 && $remisepour == 0) {
					$this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE et est obligatoire. ";
					$isOK = false;
				}
				if (($validator->isValid($remiseeuro) ||
						$validator->isValid($remisepour)) && $isOK == true
				) {
					switch ($params['remise']) {
						case 4 :
							if (isset($params['montantfrais']) && (int)$params['montantfrais'] > 0) {
								$isExistFrais = $promoCommand->fetchRow("MONTANTFRAISCMD IS NOT NULL AND MONTANTFRAISCMD = ".$params['montantfrais']);
								if ($isExistFrais) {
									$date = new Zend_Date();
	
									$data = array (
											'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
											'MONTANTFRAISCMD' => $filter->filter($params['montantfrais']),
											'REMISEEURO' => $remiseeuro,
											'REMISEPOUR' => $remisepour
									);
									$promoCommand->update($data,'ID = '.$isExistFrais['ID']);
	
									$this->view->messageSuccess = "Les frais de livraison sont modifi�s ";
	
								} else {
									$date = new Zend_Date();
	
									$data = array (
											'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
											'MONTANTFRAISCMD' => $filter->filter($params['montantfrais']),
											'REMISEEURO' => $remiseeuro,
											'REMISEPOUR' => $remisepour
									);
									$promoCommand->insert($data);
									$this->view->messageSuccess = "Les frais de livraison sont modifi�s ";
								}
							} else {
								$this->view->messageError = "Le montant de la commande doit etre sup�rieur � 0";
							}
							break;
						default:
							$this->_forward('command');
							break;
	
					}
				} else {
					foreach ($validator->getErrors() as $errorCode) {
						$this->view->messageError .=  $this->getErrorValidator($errorCode);
					}
				}
			}
		}
            } catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
			$this->view->messageError = "V�rifier les param�tres";
		}
		$this->_forward('list');
		
	}
	function commanddelAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$promoCommand = new PromoCommand();
				$promoCommand->delete('ID = '.$id);
				$this->view->messageSuccess = "La configuration � �t� supprim�e ";
			} else {
				$this->view->messageError = "La configuration n'a pas �t� supprim�e ";
	
			}
		}
		$this->_forward('list');
	}
}
?>AnnoncecontentController.php000060400000010654150713030120012267 0ustar00<?php
class Backoffice_AnnoncecontentController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "AnnonceContent";
		$this->isConnectedWithRole('isPromo');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty());

		$annonce = new AnnonceContent();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow']
			);

			if ($validator->isValid($dataAnnonce['TITRE']) &&
			$validator->isValid($dataAnnonce['CONTENT'])
			) {
				try {
					$id = (int)$params['id'];
					if ( $id > 0) {
							
						$annonce->update($dataAnnonce,'ID = '.$id);
						$this->view->messageSuccess = "L'annonce a �t� modifi�e";
						$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
						$this->log("L'annonce a �t� modifi�e : ".$id,'info');
					}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->populateFormAnnonce = $dataAnnonce;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormAnnonce = $dataAnnonce;
			}

		}
		$this->_forward('/list');
	}

	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'TITRE' => $filter->filter($params['titre']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow']
			);
			if (
			$validator->isValid($dataAnnonce['TITRE']) &&
			$validator->isValid($dataAnnonce['CONTENT'])
			) {
				try {
					$annonce = new AnnonceContent();
					$annonce->insert($dataAnnonce);
					$this->view->messageSuccess = "L'annonce a �t� ajout�e";
					$this->log("L'annonce a �t� ajout�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->populateFormAnnonce = $dataAnnonce;
				}

			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormAnnonce = $dataAnnonce;
			}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des publicit�s sur la page d'accueil";
		$adminNamespace = $this->getSession();
			
		//Appel model pour listing
		$annonces = new AnnonceContent();
		$result = $annonces->select()->order('isSHOW ASC')->order('TITRE ASC')->query()->fetchAll();
			
		$this->view->listannonce = $result;
	}

	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceContent();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'annonce a �t� supprim�e";
					$this->log("L'annonce a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');
	}

}
?>AdminController.php000060400000017302150713030120010340 0ustar00<?php

class Backoffice_AdminController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";  
		$this->view->currentMenu = "Admin";
		$this->isConnectedWithRole('isAdmin');
	}
	function indexAction()
	{
		$this->_forward('/list');

	}
	function setroleAction()
	{
		if ($this->_request->isPost()) {
				
			$params = $this->_request->getPost();
			if ($params['roletype'] == 'isPromo') { $data = array('isPROMO' => $params['rolevalue']); }
			if ($params['roletype'] == 'isCategory') { $data = array('isCATEGORY' => $params['rolevalue']); }
			if ($params['roletype'] == 'isCommand') { $data = array('isCOMMAND' => $params['rolevalue']); }
			if ($params['roletype'] == 'isProduct') { $data = array('isPRODUCT' => $params['rolevalue']); }
			if ($params['roletype'] == 'isSupplier') { $data = array('isSUPPLIER' => $params['rolevalue']); }
			if ($params['roletype'] == 'isUser') { $data = array('isUSER' => $params['rolevalue']); }
			if ($params['roletype'] == 'isAdmin') { $data = array('isADMIN' => $params['rolevalue']); }
			if ($params['roletype'] == 'isFooter') { $data = array('isFOOTER' => $params['rolevalue']); }
			if ($params['roletype'] == 'isStats') { $data = array('isSTATS' => $params['rolevalue']); }
				
			$id = $params['idadmin'];
				
			try {
				if ( $id > 0) {
					$admin = new Admin();

					$admin->update($data, 'ID = '.$id);
				}
			} catch (Zend_Exception $e) {
				$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				$this->_forward('/list');
			}
		}
		$this->_forward('/list');
	}
	function listAction()
	{
		$this->view->titlePage = "Gestion des administrateurs";
		$adminNamespace = $this->getSession();
	  
		//Gestion des tris
		$table = 'NOM';
		$tri = 'ASC';

		if ($this->_request->getParam('col'))
		{
			$adminNamespace->triAdminCol = $this->_request->getParam('col');
			($adminNamespace->triAdminSens == 'ASC') ? $adminNamespace->triAdminSens = 'DESC' : $adminNamespace->triAdminSens = 'ASC';
		}
		if (isset($adminNamespace->triAdminCol)) {
			$table = $adminNamespace->triAdminCol;
			$tri = $adminNamespace->triAdminSens;
		}
	  
		//Appel model pour listing
		$admin = new Admin();
		$select = $admin->select()->where("Login <> 'Maintenance'")->order($table.' '.$tri);
	  
		$this->view->listadmins = $admin->fetchAll($select);
	  
	}

	function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$admin = new Admin();

					$admin->delete('ID = '.$id);

					$this->view->messageSuccess = "L'administrateur � �t� supprim�";
					$this->log("L'administrateur a ete supprime",'info');
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');

	}

	function editAction()
	{
		 
		$this->view->titlePage = "Modifer un administrateur";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$validatorEmail = new Zend_Validate_EmailAddress();

			//get the form params
			$params = $this->_request->getPost();
				
			//Refractor the params
			$dataTemp = array (
			 		'NOM' => $filter->filter($params['lastname']),
			 		'ID' => $filter->filter($params['id']),
			 		'PRENOM' => $filter->filter($params['firstname']),
			 		'LOGIN' => $filter->filter($params['login']),
			 		'EMAIL' => $filter->filter($params['email'])
			);
			 
			$mdp = $filter->filter($params['editpassword']);
			$mdp2 = $filter->filter($params['editpassword2']);
			
				
			if ($validator->isValid($dataTemp['NOM']) &&
			$validator->isValid($dataTemp['PRENOM']) &&
			$validator->isValid($dataTemp['LOGIN']) &&
			$validatorEmail->isValid($dataTemp['EMAIL'])
			) {
					
				$data = array (
			 		'NOM' => $dataTemp['NOM'],
			 		'PRENOM' => $dataTemp['PRENOM'],
			 		'LOGIN' => $dataTemp['LOGIN'],
			 		'EMAIL' => $dataTemp['EMAIL']
				);
				
				if ($validator->isValid($mdp) && $validator->isValid($mdp2) &&
				     ($mdp == $mdp2)) {
					$data['MDP'] =  md5($mdp);
				}
			
			
				try {

					$id = $dataTemp['ID'];
					 
					if ( $id > 0) {
						$admin = new Admin();
							
						$n = $admin->update($data, 'ID = '.$id);
						 
						$this->log('Update : '.$n.' : '.$data['NOM'].' '.$data['PRENOM'],'info');
						 
						$this->_forward('/list');
					}
				} catch (Zend_Exception $e) {

					$this->view->messageError = "L'email ou le login existe d�j�";
					 
					$this->log($e->getMessage(),'err');
					 
					$this->view->populateForm = $dataTemp;
					 
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateForm = $dataTemp;
			}

		} else {
			//populate form
			$id = (int)$this->_request->getParam('id');
			 
			if ($id > 0) {
				$admin = new Admin();
				$row = $admin->fetchRow('ID = '.$id);
				$this->view->populateForm = $row->toArray();
			}
		}
	}

	function addAction()
	{
		 
		$this->view->titlePage = "Ajouter un administrateur";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$validatorEmail = new Zend_Validate_EmailAddress();

			//get the form params
			$params = $this->_request->getPost();
				
			//Refractor the params
			$mdp = $filter->filter($params['addpassword']);
			$mdp2 = $filter->filter($params['addpassword2']);
				
			$dataTemp = array (
			 		'NOM' => $filter->filter($params['lastname']),
			 		'PRENOM' => $filter->filter($params['firstname']),
			 		'LOGIN' => $filter->filter($params['addlogin']),
			 		'EMAIL' => $filter->filter($params['email'])
			);
				
			if ($validator->isValid($dataTemp['NOM']) &&
			$validator->isValid($dataTemp['PRENOM']) &&
			$validator->isValid($dataTemp['LOGIN']) &&
			$validatorEmail->isValid($dataTemp['EMAIL']) &&
			$validator->isValid($mdp) &&
			$validator->isValid($mdp2) &&
			($mdp == $mdp2)
			) {
					
				$data = array (
			 		'NOM' => $dataTemp['NOM'],
			 		'PRENOM' => $dataTemp['PRENOM'],
			 		'LOGIN' => $dataTemp['LOGIN'],
			 		'MDP' => md5($mdp),
			 		'EMAIL' => $dataTemp['EMAIL'],
			 		'ROLE' => '100'
			 		);
			 		try {
			 			$admin = new Admin();
			 			$admin->insert($data);

			 			$this->view->messageSuccess = "L'administrateur a �t� ajout�";
			 			$this->log("L'administrateur a �t� ajout�",'info');
			 		} catch (Zend_Exception $e) {

			 			$this->view->messageError = "L'email ou le login existe d�j�";
			 			$this->log($e->getMessage(),'err');
			 			$this->view->populateForm = $dataTemp;
			 		}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateForm = $dataTemp;
			}

		}
	}

}
?>ToolController.php000060400000006510150713030120010224 0ustar00<?php

class Backoffice_ToolController extends Modules_Backoffice_Controllers_MainController
{

	function init() {	}

	function redactorlistpicturesAction() {
		$repertoireDestination = "/items/datas/images/";
		$array = array();
		try {
			$scanned_directory = array_diff(scandir($_SERVER['DOCUMENT_ROOT'].$repertoireDestination), array('..', '.'));
			foreach ($scanned_directory as $image) {
				$path = $repertoireDestination.$image;
				array_push($array, array("thumb" => $path, "image" => $path, "title" => $image));
			}

		} catch (Exception $e) {
			$array = array( 'error' => $e->getMessage());
			$this->log($e->getMessage(),'err');
		}
		echo Zend_Json::encode($array);

		exit();
	}


	function redactoruploadpicturesAction() {
		$repertoireDestination = "/items/datas/images/";
		$array = array();

		try {
			if(!empty($_FILES['file']) && !empty($_FILES['file']['name'])) {
				$nomOrigine = $_FILES['file']['name'];
				$elementsChemin = pathinfo($nomOrigine);
				$extensionFichier = strtolower($elementsChemin['extension']);
				$extensionsAutorisees = array("jpeg", "jpg", "gif", "png");
				if (!(in_array($extensionFichier, $extensionsAutorisees))) {
					$array = array( 'error' => "Extension attendue : jpeg, jpg, gif, png");
				} else {
					if (move_uploaded_file($_FILES["file"]["tmp_name"],$_SERVER['DOCUMENT_ROOT'].$repertoireDestination.$nomOrigine)) {
						$array = array(
							'filelink' => $repertoireDestination.$nomOrigine,
							'filename' => $nomOrigine
						);
					} else {
						$array = array( 'error' => "Impossible d'enregistrer l'image");
					}
				}
			}
		} catch (Exception $e) {
			$array = array( 'error' => $e->getMessage());
			$this->log($e->getMessage(),'err');
		}
		echo Zend_Json::encode($array);

		exit();
	}


	function redactorlistfilesAction() {
		$repertoireDestination = "/items/datas/fichiers/";
		$array = array();
		try {
			$scanned_directory = array_diff(scandir($_SERVER['DOCUMENT_ROOT'].$repertoireDestination), array('..', '.'));
			foreach ($scanned_directory as $image) {
				$path = $repertoireDestination.$image;
				array_push($array, array("thumb" => $path, "image" => $path, "title" => $image));
			}

		} catch (Exception $e) {
			$array = array( 'error' => $e->getMessage());
			$this->log($e->getMessage(),'err');
		}
		echo Zend_Json::encode($array);

		exit();
	}
	
	function redactoruploadfilesAction() {
		$repertoireDestination = "/items/datas/fichiers/";
		$array = array();

		try {
			if(!empty($_FILES['file']) && !empty($_FILES['file']['name'])) {
				$nomOrigine = $_FILES['file']['name'];
				$elementsChemin = pathinfo($nomOrigine);
				$extensionFichier = strtolower($elementsChemin['extension']);
				$extensionsAutorisees = array("pdf");
				if (!(in_array($extensionFichier, $extensionsAutorisees))) {
					$array = array( 'error' => "Extension attendue : pdf");
				} else {
					if (move_uploaded_file($_FILES["file"]["tmp_name"],$_SERVER['DOCUMENT_ROOT'].$repertoireDestination.$nomOrigine)) {
						$array = array(
							'filelink' => $repertoireDestination.$nomOrigine,
							'filename' => $nomOrigine
						);
					} else {
						$array = array( 'error' => "Impossible d'enregistrer le fichier");
					}
				}
			}

		} catch (Exception $e) {
			$array = array( 'error' => $e->getMessage());
			$this->log($e->getMessage(),'err');
		}
		echo Zend_Json::encode($array);

		exit();
	}
}
?>BlogCategoryController.php000060400000014766150713030120011704 0ustar00<?php
class Backoffice_BlogCategoryController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration"; 
		$this->view->currentMenu = "BlogCategory";
	}
    function indexAction()
	{
		$this->_forward('/list');

	}

	function listAction()
	{
		try {
		    $this->view->titlePage = "Gestion des cat�gories du blog";
            
		    $blogCategory = new BlogCategory();
            $this->view->listallblogcategories = $blogCategory->AllCategories(0);
        } catch (Zend_Exception $e) { 
			$this->view->messageError = $e->getMessage();
			$this->log($e->getMessage(),'err');
		}
	}
    function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$category = new BlogCategory();
					if ($category->fetchRow('id_parent = '.$id)) {
						$this->view->messageError = 'Cette cat�gorie est parente';
					} else {
						$subject = new BlogSubject();
						$select = $subject->fetchRow('id_category = '.$id);
						if ($select) {
							$this->view->messageError = 'Cette cat�gorie est utilis�e par le sujet : <b>'.$select->title."<b/>";
						} else {

							$category->delete('id = '.$id); 
							$this->view->messageSuccess = "La cat�gorie du blog a et� supprim�e";
							$this->log("La cat�gorie du blog a et� supprim�e",'info');

						}
					}
				}
                catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');

	} 
	public function addAction()
	{
        $data = array ( 
                 'is_publish' => 0, 
                 'is_close' => 0, 
                 'title' => "",
                 'sub_title' => "",
                 'message' => ""
        );
		try {
            $blogCategory = new BlogCategory();
            $this->view->listallblogcategories = $blogCategory->AllCategories(0);
		    $this->view->titlePage = "Ajouter une cat�gorie";
		    $this->view->messageSuccess = "";
		    $this->view->messageError = ""; 
		    if ($this->_request->isPost()) {
 
		        //filtres pour changer les chaines
		        $filter = new Zend_Filter();
		        $filter	->addFilter(new Zend_Filter_StripTags())
		        ->addFilter(new Zend_Filter_StringTrim());
             
		        //get the form params
		        $params = $this->_request->getPost();

		        //Refractor the params
		        $data = array ( 
			 	        'is_publish' =>  (int)$params['is_publish'], 
			 	        'title' => $filter->filter($params['title']),
			 	        'message' => $params['message'],
			 	        'sub_title' => $params['sub_title'],
			 	        'is_close' =>  (int)$params['is_close'],
                        'date_updated' => date('Y-m-d H:i:s') ,
                        'id_parent' => (int)$params['idparent'] 
		        );  
			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());
                 if (
			    $validator->isValid($data['title']) && 
                $data['id_parent'] > 0
			    ) { 
				        $blogCategory->insert($data);
				        $this->view->messageSuccess = "La cat�gorie a �t� ajout�e"; 
                        $data['title'] = "";
                        $data['sub_title'] = "";
                        $data['message'] = "";
                 } else {
                     foreach ($validator->getErrors() as $errorCode) {
                         $this->view->messageError .=  $this->getErrorValidator($errorCode);
                     }
                     if ($data['id_parent'] == 0) {
                         $this->view->messageError .= "Choisissez une cat�gorie parente.";
                     }
                 } 
            }
		}
        catch (Zend_Exception $e) { 
			$this->log($e->getMessage(),'err');
        } 
		$this->view->populateData = $data; 
	}
    
    public function editAction()
	{
        $data = array ( 
                 'is_publish' => 0, 
                 'is_close' => 0, 
                 'title' => "",
                 'sub_title' => "",
                 'message' => ""
        );
		try {
		    $blogCategory = new BlogCategory();
            $this->view->listallblogcategories = $blogCategory->AllCategories(0);
		    $this->view->titlePage = "Modifier une cat�gorie";
		    $this->view->messageSuccess = "";
		    $this->view->messageError = "";
			
		    //filtres pour changer les chaines
		    $filter = new Zend_Filter();
		    $filter	->addFilter(new Zend_Filter_StripTags())
		    ->addFilter(new Zend_Filter_StringTrim());
         
		    if ($this->getRequest()->getParam('id')) {
			    $id = (int)$this->getRequest()->getParam('id');
			    if ($id>0) {
				    $this->view->populateData = $blogCategory->fetchRow('ID = '.$id);
			    }
		    }
		    if ($this->getRequest()->isPost()) {

			    //get the form params
			    $params = $this->_request->getPost();

			    //Refractor the params
			    $data = array ( 
                        'id' => (int)$params['id'],
			 	        'is_publish' =>  (int)$params['is_publish'], 
			 	        'title' => $filter->filter($params['title']),
			 	        'message' => $params['message'],
			 	        'sub_title' => $params['sub_title'],
			 	        'is_close' =>  (int)$params['is_close'],
                        'date_updated' => date('Y-m-d H:i:s') ,
                        'id_parent' => (int)$params['idparent'] 
		        );  
                $this->view->populateData = $data;

			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());
                 if (
			    $validator->isValid($data['title']) 
			    ) { 
				    $id = (int)$params['id'];
				    if ( $id > 0) {
							
					    $blogCategory->update($data,'ID = '.$id); 
					    $this->view->messageSuccess = "La cat�gorie a �t� modifi�e";
					    $this->view->populateData = $blogCategory->fetchRow('ID = '.$id);
				    }
                 } else {
                     foreach ($validator->getErrors() as $errorCode) {
                         $this->view->messageError .=  $this->getErrorValidator($errorCode);
                     }
                     if ($data['id_parent'] == 0) {
                         $this->view->messageError .= "Choisissez une cat�gorie parente.";
                     }
                 } 
		    }
        }
        catch (Zend_Exception $e) {
            $this->view->populateData = $data;
            $this->log($e->getMessage(),'err');
        } 
	}

}
?>BlogSubjectController.php000060400000016475150713030120011525 0ustar00<?php
class Backoffice_BlogSubjectController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration"; 
		$this->view->currentMenu = "BlogSubject";
	}
    function indexAction()
	{
		$this->_forward('/search');

	}
     
    public function searchAction()
	{
        $this->view->titlePage = "Rechercher un sujet";  
		$data = array (  
			 	'title' => "",
			 	'is_publish' => 0,
			 	'is_close' => 0, 
			 	'id_category' => 0
		);
        $blogCategory = new BlogCategory();
        $this->view->listallblogcategories = $blogCategory->AllCategories(0); 
        $this->view->listallsubjects = array();
        try { 
        
		    if ($this->_request->isPost()) { 
                //filtres pour changer les chaines
                $filter = new Zend_Filter();
                $filter	->addFilter(new Zend_Filter_StripTags())
                ->addFilter(new Zend_Filter_StringTrim());

                //get the form params
                $params = $this->_request->getPost();

                //Refractor the params
                $data = array (  
                         'title' => $filter->filter($params['title']),
                         'is_publish' => (int)$params['is_publish'],
                         'is_close' => (int)$params['is_close'],
                         'id_category' => (int)$params['id_category']
                ); 
                
                $blogSubject = new BlogSubject(); 
                $this->view->listallsubjects = $blogSubject->getPostBySearch($data);  
		    }
		    $this->view->populateData = $data; 
        } catch (Zend_Exception $e) {
            $this->view->populateData = $data;
            $this->log($e->getMessage(),'err');
        } 
    }


    function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try { 
					$subject = new BlogSubject(); 
					$subject->delete('id = '.$id); 
					$this->view->messageSuccess = "Le sujet a et� supprim�";
					$this->log("Le sujet a et� supprim�",'info'); 
				}
                catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');

	} 
	public function addAction()
	{
        $data = array ( 
                 'is_publish' => 0, 
                 'is_close' => 0, 
                 'title' => "",
                 'sub_title' => "",
                 'message' => "", 
                 'id_category' => 0
        );
		try {
            $blogCategory = new BlogCategory();
            $this->view->listallblogcategories = $blogCategory->AllCategories(0);
		    $this->view->titlePage = "Ajouter un sujet";
		    $this->view->messageSuccess = "";
		    $this->view->messageError = ""; 
		    if ($this->_request->isPost()) {
 
		        //filtres pour changer les chaines
		        $filter = new Zend_Filter();
		        $filter	->addFilter(new Zend_Filter_StripTags())
		        ->addFilter(new Zend_Filter_StringTrim());
             
		        //get the form params
		        $params = $this->_request->getPost();

		        //Refractor the params
		        $data = array ( 
			 	        'is_publish' =>  (int)$params['is_publish'], 
			 	        'title' => $filter->filter($params['title']),
			 	        'message' => $params['message'],
			 	        'sub_title' => $params['sub_title'],
			 	        'is_close' =>  (int)$params['is_close'],
                        'date_updated' => date('Y-m-d H:i:s') ,
                        'id_category' => (int)$params['id_category'] 
		        );  
			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());
                 if (
			    $validator->isValid($data['title']) && 
                $data['id_category'] > 0
			    ) { 
                        $blogSubject = new BlogSubject();
				        $blogSubject->insert($data);
				        $this->view->messageSuccess = "Le sujet a �t� ajout�"; 
                        $data['title'] = "";
                        $data['sub_title'] = "";
                        $data['message'] = "";
                 } else {
                     foreach ($validator->getErrors() as $errorCode) {
                         $this->view->messageError .=  $this->getErrorValidator($errorCode);
                     }
                     if ($data['id_category'] == 0) {
                         $this->view->messageError .= "Choisissez une cat�gorie.";
                     }
                 } 
            }
		}
        catch (Zend_Exception $e) { 
			$this->log($e->getMessage(),'err');
        } 
		$this->view->populateData = $data; 
	}
    
    public function editAction()
	{
        $data = array ( 
                 'is_publish' => 0, 
                 'is_close' => 0, 
                 'title' => "",
                 'sub_title' => "",
                 'message' => "", 
                 'id_category' => 0
        );
		try {
		    $blogCategory = new BlogCategory();
            $blogSubject = new BlogSubject();
            $this->view->listallblogcategories = $blogCategory->AllCategories(0);
		    $this->view->titlePage = "Modifier un sujet";
		    $this->view->messageSuccess = "";
		    $this->view->messageError = "";
			
		    //filtres pour changer les chaines
		    $filter = new Zend_Filter();
		    $filter	->addFilter(new Zend_Filter_StripTags())
		    ->addFilter(new Zend_Filter_StringTrim());
         
		    if ($this->getRequest()->getParam('id')) {
			    $id = (int)$this->getRequest()->getParam('id');
			    if ($id>0) {
				    $this->view->populateData = $blogSubject->fetchRow('ID = '.$id);
			    }
		    }
		    if ($this->getRequest()->isPost()) {

			    //get the form params
			    $params = $this->_request->getPost();

			    //Refractor the params
			    $data = array ( 
                        'id' => (int)$params['id'],
			 	        'is_publish' =>  (int)$params['is_publish'], 
			 	        'title' => $filter->filter($params['title']),
			 	        'message' => $params['message'],
			 	        'sub_title' => $params['sub_title'],
			 	        'is_close' =>  (int)$params['is_close'],
                        'date_updated' => date('Y-m-d H:i:s') ,
                        'id_category' => (int)$params['id_category'] 
		        );  
                $this->view->populateData = $data;

			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());
                 if ( $validator->isValid($data['title'])  ) { 
				    $id = (int)$params['id'];
				    if ( $id > 0) { 
					    $blogSubject->update($data,'ID = '.$id); 
					    $this->view->messageSuccess = "Le sujet a �t� modifi�.";
					    $this->view->populateData = $blogSubject->fetchRow('ID = '.$id);
				    }
                 } else {
                     foreach ($validator->getErrors() as $errorCode) {
                         $this->view->messageError .=  $this->getErrorValidator($errorCode);
                     }
                     if ($data['id_category'] == 0) {
                         $this->view->messageError .= "Choisissez une cat�gorie.";
                     }
                 } 
		    }
        }
        catch (Zend_Exception $e) {
            $this->view->populateData = $data;
            $this->log($e->getMessage(),'err');
        } 
	}

}
?>AnnoncecmsController.php000060400000012744150713030120011401 0ustar00<?php
class Backoffice_AnnoncecmsController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "AnnonceCms";
		$this->isConnectedWithRole('isCategory');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier un article";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		$annonce = new AnnonceCms();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonceCms = $annonce->fetchRow('ID = '.$id);
			}
		}
		
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();
            
			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'CONTENT_SHORT' => $filter->filter($params['content_short']),
			 		'CONTENT_LONG' => $params['content_long'],
			 		'POSITION' => (int) $filter->filter($params['position']),
			 		'isSHOW' => $params['isshow'],
					'ID_CATS' => ''
					);
					
					if (isset($params['categories'])) {
						foreach($params['categories'] as $value)
						{
							$dataAnnonce['ID_CATS'] .= ":".$value.":";
						}
					}
					if ($validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT'])&&
					!empty($dataAnnonce['ID_CATS'])
					) {
						try {
							$id = (int)$params['id'];
							if ( $id > 0) {
									
								$annonce->update($dataAnnonce,'ID = '.$id);
								$this->view->messageSuccess = "L'article a �t� modifi�";
								$this->view->populateFormAnnonceCms = $annonce->fetchRow('ID = '.$id);
								$this->log("L'article a �t� modifi� ".$id,'info');
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceCms = $dataAnnonce;
						}
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceCms = $dataAnnonce;
					}

		}
	}


	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter un article";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'CONTENT_SHORT' => $filter->filter($params['content_short']),
			 		'CONTENT_LONG' => $params['content_long'],
			 		'POSITION' => (int) $filter->filter($params['position']),
			 		'isSHOW' => $params['isshow'],
					'ID_CATS' => ''
					);
					
					if (isset($params['categories'])) {
						foreach($params['categories'] as $value)
						{
							$dataAnnonce['ID_CATS'] .= ":".$value.":";
						}
					}
					
					if (
					$validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT']) &&
					!empty($dataAnnonce['ID_CATS'])
					) {
						try {
							$annonce = new AnnonceCms();
							$annonce->insert($dataAnnonce);
							$this->view->messageSuccess = "L'article a �t� ajout�";
							$this->log("L'article a �t� ajout�",'info');
							
					        $lastid = $annonce->getAdapter()->lastInsertId();
							 
                            $this->_request->setParam('id', $lastid);
		                    $this->_forward('/edit'); 
							
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceCms = $dataAnnonce;
						}

					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceCms = $dataAnnonce;
					}

		}
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des articles"; 
			
		//Appel model pour listing
		$annonces = new AnnonceCms();
		$result = $annonces->getAllAnnonces();

		$category = new Category();
		$this->view->listallcategories = $category->getAllCategoriesByID(0);
		
		$this->view->listAnnoncecms = $result;
	}



	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceCms();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'article a �t� supprim�";

					$this->log("L'article a �t� supprim�",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}

}
?>ProductoptionlistController.php000060400000010362150713030120013054 0ustar00<?php
class Backoffice_ProductoptionlistController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";

		$this->isConnectedWithRole('isProduct'); 
	}
	public function indexAction()
	{
		$this->_forward('/option');

	}
public function optionAction() {
		$this->view->titlePage = "Gestion des caract�ristiques s�lectionnable";
		$this->view->currentMenu = "Option";
		
		$optionList = new OptionList();
		if ($this->_request->isPost() && (int)$this->_request->getParam('id') ==0) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			$values = explode(",", $params['value']);
			$result = "";
			foreach ($values as $value) {
				$valTemp = $filter->filter($value);
				if (!empty($valTemp)) {
					if (empty($result))  {
						$result .= $filter->filter($valTemp);
					} else {
						$result .= "::".$filter->filter($valTemp);
					}
				}
			}	
						
			$data = array (
			 		'NAME' => $filter->filter($params['name']),
			 		'VALUE' => $result
			);

			if ($validator->isValid($data['NAME']) && $validator->isValid($data['VALUE'])) {

				try { 
					$optionList->insert($data); 
					$this->view->messageSuccess = "La caract�ristique a �t� ajout�e"; 
				} catch (Zend_Exception $e) { 
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La caract�ristique existe d�j�"; 
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			} 
		} 
		$this->view->listoption = $optionList->getAll();
	}
	public function optioneditAction()
	{
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();
			
			$values = explode(",", $params['value']);
			$result = "";
			foreach ($values as $value) {
				$valTemp = $filter->filter($value);
				if (!empty($valTemp)) {
					if (empty($result))  {
						$result .= $filter->filter($valTemp);
					} else {
						$result .= "::".$filter->filter($valTemp);
					}
				}
			}	
			
			$data = array (
			 		'NAME' => $filter->filter($params['name']),
			 		'VALUE' => $result,
			 		'ID' => $filter->filter($params['id'])
			);

			if ($validator->isValid($data['NAME']) && $validator->isValid($data['VALUE']) ) {

				try {
					$optionList = new OptionList();
					$optionList->update($data, 'ID = '.$data['ID']);

					$this->view->messageSuccess = "La caract�ristique a �t� modifi�e";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La caract�ristique existe d�ja";

					$this->_forward('option');
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('option');
	}
	public function optiondelAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try { 
					$optionList = new OptionList();
					$isExistProduct = $optionList->getProductByIdOption($id); 
					if (!$isExistProduct) { 
						$optionList->delete('ID = '.$id);

						$this->view->messageSuccess = "La caract�ristique a �t� supprim�e";
					} else {
						$this->view->messageError = "La caract�ristique est utilis�e par : <b/>".$isExistProduct['NOM']."</b>";
					}
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
					$this->_forward('/option');
				}
			}
		}
		$this->_forward('/option');
	}
	
}
?>CsvController.php000060400000105322150713030120010043 0ustar00<?php
class Backoffice_CsvController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Export";
		$this->isConnectedWithRole('isStats');
	}
	function indexAction()
	{
		$this->_forward('/export');
	}
    
	function exporthelloAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender();


			$this->view->titlePage = "Exporter le fichier CSV";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";


			$fichier = new FichierExcel();
			$fichier->Colonne("Nom du produit;Description du produit;Lien image du produit;Url vers la fiche produit sur le site du client;Lien vers une documentation sur le produit au format pdf;Identifiant unique du produit;Mot cl� 1;Mot cl� 2;Mot cl� 3;Mot cl� 4;Mot cl� 5;Mot cl� 6;Mot cl� 7;Mot cl� 8;Mot cl� 9;Mot cl� 10;Prix HT en �;Domaine d'utilisation;Marque du produit;Frais de port;Delai de livraison;Garantie;Disponibilit�;Quantit� minimum;EAN");

			$sql = "SELECT p.ID ID, p.NOM NOM, p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.DESCRIPTIONLONG DESCLONG, p.PRIX PRIX, p.isDEVIS isDEVISPRODUCT,
					p.DOCNAME DOCNAME, p.DOCURL DOCURL, p.IDBREND IDBREND,
					p.isPROMO isPROMO, pic.URL URLIMAGE, sb.BREND BREND, sb.URL BRENDURL, p.IDCATEGORY IDCATEGORY, c.NOM CATEGORYNOM, c.NAVNOM CATEGORYNAV, 
					p.DESCRIPTIONTECH DESCTECH, p.DESCRIPTIONNORME DESCNORME, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
					LEFT JOIN supplier_brend sb ON sb.ID = p.IDBREND
					LEFT JOIN category AS c ON c.ID = p.IDCATEGORY
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";

			$product = new Product();
			$productChild = new ProductChild();
			$listProducts = $product->getAdapter()->fetchAll($sql);

			foreach ($listProducts as $row) {
				$sqlChild = "
						SELECT pc.ID ID ,pc.REFERENCE REFERENCE,pc.DESIGNATION DESIGNATION,pc.PRIX PRIX, pc.isPROMO isPROMO ,
						pc.IMAGEPROMO IMAGEPROMO,pc.isDEVIS isDEVIS, pc.QUANTITYMIN QUANTITYMIN
							FROM productchild AS pc
						WHERE pc.IDPRODUCT = ".$row['ID']." 
						ORDER BY pc.PRIX ASC";
					
				$productChildTemp = $productChild->getAdapter()->fetchAll($sqlChild);
					
				$navnom = 	$this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$urlImage = $this->baseUrl_SiteCommerceUrl."/".$row['URLIMAGE'];
				//$urlPage = $this->baseUrl_SiteCommerceUrl."/produits/detail/page/".$navnom."/p/".$row['ID'];
				$urlPage = $this->getUrlPage(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'], 'PAGE' => $navnom, 'ID' => $row['ID']));

					
				$motcle = array();
				$navnomStrip =  explode("-", $navnom);
				for ($index = 0; $index < sizeof($navnomStrip); $index++) {
					$word = $navnomStrip[$index];
					if (strlen($word) > 3){
						array_push($motcle, $word);
					}
				}
				if (sizeof($motcle) < 10) {
					$navnomcat = explode("-", $row['CATEGORYNAV']);
					for ($index = 0; $index < sizeof($navnomcat); $index++) {
						$word = $navnomcat[$index];
						if (strlen($word) > 3){
							array_push($motcle, $word);
						}
					}
					if (sizeof($motcle) < 10) {
						$brend = $row['BREND'];
						array_push($motcle, $brend);
					}
					if (sizeof($motcle) < 10) {
						for ($index = sizeof($motcle); $index < 10; $index++) {
							array_push($motcle, $this->siteName);
						}
					}
				}
				$reference = "";
				$prix = "";
				$description = "";
				foreach ($productChildTemp as $rowChild) {
					$reference = $rowChild['REFERENCE'];
					$prix = $rowChild['PRIX'];
					$descTemp = $row['DESCSHORT']." ".$rowChild['DESIGNATION'];

					$description = $this->cleanUp($descTemp);
					$description = addslashes($description);
					break;
				}
				$fichier->Insertion('"'.$row['NOM'].'";"'.$description.'";"'.$urlImage.'";"'.$urlPage.'";"'.$row['DOCURL'].'";"'.$reference.'";"'.$motcle[0].'";"'.$motcle[1].'";"'.$motcle[2].'";"'.$motcle[3].'";"'.$motcle[4].'";"'.$motcle[5].'";"'.$motcle[6].'";"'.$motcle[7].'";"'.$motcle[8].'";"'.$motcle[9].'";'.$prix.';;"'.$row['BREND'].'";;"48H par TNT";;0;;');
			}

			$fichier->output('hellopro_fr');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}
	function exportleguideAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender();

			$this->view->titlePage = "Exporter le fichier CSV";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";

			$fichier = new FichierExcel();
			$fichier->Colonne("categorie;identifiant_unique;titre;description;prix;url_produit;url_image;frais_de_livraison;disponibilite;delais_de_livraison;garantie;reference_modele;D3E;marque;ean;prix_barre;type_promotion;devise;occasion;URL_mobile");


			$sql = "SELECT p.ID ID, p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.DESCRIPTIONLONG DESCLONG, p.PRIX PRIX, p.isDEVIS isDEVISPRODUCT,
					p.DOCNAME DOCNAME, p.DOCURL DOCURL, p.IDBREND IDBREND,
					p.isPROMO isPROMO, pic.URL URLIMAGE, sb.BREND BREND, sb.URL BRENDURL, p.IDCATEGORY IDCATEGORY, c.NOM CATEGORYNOM,
					p.DESCRIPTIONTECH DESCTECH, p.DESCRIPTIONNORME DESCNORME, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
					LEFT JOIN supplier_brend sb ON sb.ID = p.IDBREND
					LEFT JOIN category AS c ON c.ID = p.IDCATEGORY
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";

			$product = new Product();
			$productChild = new ProductChild();
			$listProducts = $product->getAdapter()->fetchAll($sql);

			foreach ($listProducts as $row) {
				$sqlChild = "
						SELECT pc.ID ID ,pc.REFERENCE REFERENCE,pc.DESIGNATION DESIGNATION,pc.PRIX PRIX, pc.isPROMO isPROMO ,
						pc.IMAGEPROMO IMAGEPROMO,pc.isDEVIS isDEVIS, pc.QUANTITYMIN QUANTITYMIN
							FROM productchild AS pc
						WHERE pc.IDPRODUCT = ".$row['ID']." 
						ORDER BY pc.PRIX ASC";
					
				$productChildTemp = $productChild->getAdapter()->fetchAll($sqlChild);
					
				$navnom = $this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$urlImage = $this->baseUrl_SiteCommerceUrl."/".$row['URLIMAGE'];
				//$urlPage = $this->baseUrl_SiteCommerceUrl."/produits/detail/".$navnom."/p/".$row['ID'];
				$urlPage = $this->getUrlPage(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'],'PAGE' => $navnom, 'ID' => $row['ID']));
					
				$fraislivraison = "";
				$garantie="";
					
				$reference = "";
				$prix = "";
				$description = "";
				foreach ($productChildTemp as $rowChild) {
					$reference = $rowChild['REFERENCE'];
					$prix = $rowChild['PRIX'];
					$descTemp = $row['DESCSHORT']." ".$rowChild['DESIGNATION'];

					$description = $this->cleanUp($descTemp);
					$description = addslashes($description);
					break;
				}
				$fichier->Insertion('"'.$row['CATEGORYNOM'].'";"'.$reference.'";"'.$row['NOM'].'";"'.$description.'";"'.$prix.'";"'.$urlPage.'";"'.$urlImage.'";"'.$fraislivraison.'";"0";"48 heures";"'.$garantie.'";;;;;;;;;');

			}

			$fichier->output('leguide_fr');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	function exportkelkooAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender();

			$this->view->titlePage = "Exporter le fichier CSV";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";

			$fichier = new FichierText();
			$fichier->Colonne("id|model|brand|description|price|url|merchantcat|image|ean|sku|used|availability|deliveryprice|deliveryTime|deliveryinfo|warranty|ecotax|catkkid|taggingmatching|voucher|voucherdesc|voucherurl|vouchercode|voucherstart|voucherend|pricenorebate|percentagepromo|promostart|promoend|offertype|flag|shopinfo|validity");

			$sql = "SELECT p.ID ID, p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.DESCRIPTIONLONG DESCLONG, p.PRIX PRIX, p.isDEVIS isDEVISPRODUCT,
					p.DOCNAME DOCNAME, p.DOCURL DOCURL, p.IDBREND IDBREND,
					p.isPROMO isPROMO, pic.URL URLIMAGE, sb.BREND BREND, sb.URL BRENDURL, p.IDCATEGORY IDCATEGORY, c.NOM CATEGORYNOM, c.NAVNOM CATEGORYNAV, c.DESCRIPTION CATEGORYDESC, 
					p.DESCRIPTIONTECH DESCTECH, p.DESCRIPTIONNORME DESCNORME, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
					LEFT JOIN supplier_brend sb ON sb.ID = p.IDBREND
					LEFT JOIN category AS c ON c.ID = p.IDCATEGORY
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";

			$product = new Product();
			$productChild = new ProductChild();
			$listProducts = $product->getAdapter()->fetchAll($sql);

			foreach ($listProducts as $row) {
				$sqlChild = "
						SELECT pc.ID ID ,pc.REFERENCE REFERENCE,pc.DESIGNATION DESIGNATION,pc.PRIX PRIX, pc.isPROMO isPROMO ,
						pc.IMAGEPROMO IMAGEPROMO,pc.isDEVIS isDEVIS, pc.QUANTITYMIN QUANTITYMIN
							FROM productchild AS pc
						WHERE pc.IDPRODUCT = ".$row['ID']." 
						ORDER BY pc.PRIX ASC";
					
				$productChildTemp = $productChild->getAdapter()->fetchAll($sqlChild);
					
				$navnom = $this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$urlImage = $this->baseUrl_SiteCommerceUrl."/".$row['URLIMAGE'];
				//$urlPage = $this->baseUrl_SiteCommerceUrl."/produits/detail/page/".$navnom."/p/".$row['ID'];
				$urlPage = $this->getUrlPage(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'],'PAGE' => $navnom, 'ID' => $row['ID']));
					
				$motcle = array();
				$navnomStrip =  explode("-", $navnom);
				for ($index = 0; $index < sizeof($navnomStrip); $index++) {
					$word = $navnomStrip[$index];
					if (strlen($word) > 3){
						array_push($motcle, $word);
					}
				}
				if (sizeof($motcle) < 10) {
					$navnomcat = explode("-", $row['CATEGORYNAV']);
					for ($index = 0; $index < sizeof($navnomcat); $index++) {
						$word = $navnomcat[$index];
						if (strlen($word) > 3){
							array_push($motcle, $word);
						}
					}
					if (sizeof($motcle) < 10) {
						$brend = $row['BREND'];
						array_push($motcle, $brend);
					}
					if (sizeof($motcle) < 10) {
						for ($index = sizeof($motcle); $index < 10; $index++) {
							array_push($motcle, $this->siteName);
						}
					}
				}
				$reference = "";
				$prix = "";
				$description = "";
				foreach ($productChildTemp as $rowChild) {
					$reference = $rowChild['REFERENCE'];
					$prix = $rowChild['PRIX'];
					$descTemp = $row['DESCSHORT']." ".$rowChild['DESIGNATION'];

					$description = $this->cleanUp($descTemp);
					$description = str_replace("|", "", $description);
					$description = addslashes($description);

					break;
				}
				$catkid = "";
				$shopinfo = $this->siteName." : ".str_replace("|", "", $this->cleanUp($row['CATEGORYDESC']));
				$validity = "";
				$fichier->Insertion('"'.$reference.'"|"'.$row['NOM'].'"|"'.$row['BREND'].'"|"'.$description.'"|'.$prix.'|"'.$urlPage.'"|"'.$row['CATEGORYNOM'].'"|"'.$urlImage.'"||||1||"Sous 48 heures"|"Livraison TNT Express"|||'.$catkid.'|"'.$motcle[0].' '.$motcle[1].' '.$motcle[2].' '.$motcle[3].' '.$motcle[4].'"|||||||||||single||"'.$shopinfo.'"|"'.$validity.'"');

			}

			$fichier->output('kelkoo_fr');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	function exportciaoAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender();


			$this->view->titlePage = "Exporter le fichier CSV";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";

			$fichier = new FichierExcel();
			$fichier->Colonne("Name;Brand;MNP;Deeplink;Imagelink;Price;ShippingCost;Delivery;Merchant;Category;SKU;offerID;Description");

			$sql = "SELECT p.ID ID, p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.DESCRIPTIONLONG DESCLONG, p.PRIX PRIX, p.isDEVIS isDEVISPRODUCT,
					p.DOCNAME DOCNAME, p.DOCURL DOCURL, p.IDBREND IDBREND,
					p.isPROMO isPROMO, pic.URL URLIMAGE, sb.BREND BREND, sb.URL BRENDURL, p.IDCATEGORY IDCATEGORY, c.NOM CATEGORYNOM, c.NAVNOM CATEGORYNAV, 
					p.DESCRIPTIONTECH DESCTECH, p.DESCRIPTIONNORME DESCNORME, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
					LEFT JOIN supplier_brend sb ON sb.ID = p.IDBREND
					LEFT JOIN category AS c ON c.ID = p.IDCATEGORY
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";

			$product = new Product();
			$productChild = new ProductChild();
			$listProducts = $product->getAdapter()->fetchAll($sql);

			foreach ($listProducts as $row) {
				$sqlChild = "
						SELECT pc.ID ID ,pc.REFERENCE REFERENCE,pc.DESIGNATION DESIGNATION,pc.PRIX PRIX, pc.isPROMO isPROMO ,
						pc.IMAGEPROMO IMAGEPROMO,pc.isDEVIS isDEVIS, pc.QUANTITYMIN QUANTITYMIN
							FROM productchild AS pc
						WHERE pc.IDPRODUCT = ".$row['ID']." 
						ORDER BY pc.PRIX ASC";
					
				$productChildTemp = $productChild->getAdapter()->fetchAll($sqlChild);
					
				$navnom = $this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$urlImage = $this->baseUrl_SiteCommerceUrl."/".$row['URLIMAGE'];
				//$urlPage = $this->baseUrl_SiteCommerceUrl."/produits/detail/page/".$navnom."/p/".$row['ID'];
				$urlPage = $this->getUrlPage(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'],'PAGE' => $navnom, 'ID' => $row['ID']));
					
					
				$reference = "";
				$prix = "";
				$description = "";
				foreach ($productChildTemp as $rowChild) {
					$reference = $rowChild['REFERENCE'];
					$prix = $rowChild['PRIX'];
					$descTemp = $row['DESCSHORT']." ".$rowChild['DESIGNATION'];

					$description = $this->cleanUp($descTemp);
					$description = addslashes($description);
					break;
				}
				$fichier->Insertion('"'.$row['NOM'].'";"'.$row['BREND'].'";;"'.$urlPage.'";"'.$urlImage.'";'.$prix.';;"48h";;"'.$row['CATEGORYNOM'].'";"EUR";"'.$reference.'";"'.$description.'"');
			}

			$fichier->output('ciao_fr');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	public function sitemapxmlAction() {
		try {

			$this->view->titlePage = "Exporter le sitemap";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";

			if ($this->_request->isPost()) {
				//get the form params
				$params = $this->_request->getPost();

				$changefreq = $params['changefreq'];
				$priority = $params['priority'];
				$isImageActive = $params['all_image'];
				$isCheckLinkActive = $params['checklink'];
				$isCustomNavnomActive = $params['all_navnom'];

				// Instance de la class DomDocument
				$doc = new DOMDocument();

				// Definition de la version et l'encodage
				$doc->version = '1.0';
				$doc->encoding = 'UTF-8';

				$isImage = true;
				if ($isImageActive == "N") { $isImage = false; }

				$body_elt = $doc->createElementNS('http://www.sitemaps.org/schemas/sitemap/0.9', 'urlset');
				$doc->appendChild($body_elt);

				if ($isImage) {
					$body_elt->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:image', 'http://www.google.com/schemas/sitemap-image/1.1');
					//$body_elt->setAttributeNS('http://www.w3.org/2000/xmlns/' ,'xmlns:video', 'http://www.google.com/schemas/sitemap-video/1.1');
				}

				$isDupliateByNavNom = false;

				$isCheckLink = false;
				if ($isCheckLinkActive == "Y") { $isCheckLink = true; }

				$isCustomNavnom = false;
				if ($isCustomNavnomActive == "Y") {  $isCustomNavnom = true; }

				$countDefault = $this->sitemapAddUrlDefault($doc, $body_elt, $isCheckLink);
					
				$countProduct = $this->sitemapAddUrlProducts($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom,$isImage, $isCheckLink, $isCustomNavnom);
					
				$countCategorie = $this->sitemapAddUrlCategories($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom,$isImage, $isCheckLink);

				$countCategorie2 = $this->sitemapAddUrlCategories2($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom,$isImage, $isCheckLink);
                
				$countServices = $this->sitemapAddUrlInfos($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom,$isImage, $isCheckLink);


				$this->view->messageSuccess = "Le Sitemap a �t� remplac�.";
				if ($countProduct['RESULT'] == 'SUCCESS') {
					$this->view->messageSuccess .= " Produits : <b>".$countProduct['OK']."</b> urls,";
				} else {
					$this->view->messageError .= "Erreur sur les produits : ".$countProduct['OK']." urls OK, script interrompu.  ".$countProduct['RESULT'];
				}
					
				if ($countCategorie['RESULT'] == 'SUCCESS') {
					$this->view->messageSuccess .= " Cat�gories : <b>".$countCategorie['OK']."</b> urls,";
				} else {
					$this->view->messageError .= "Erreur sur les cat�gories : ".$countCategorie['OK']." urls OK, script interrompu.  ".$countCategorie['RESULT'];
				}
                
				if ($countCategorie2['RESULT'] == 'SUCCESS') {
					$this->view->messageSuccess .= " Cat�gories subsidiaires : <b>".$countCategorie2['OK']."</b> urls,";
				} else {
					$this->view->messageError .= "Erreur sur les cat�gories subsidiaires : ".$countCategorie2['OK']." urls OK, script interrompu.  ".$countCategorie2['RESULT'];
				}

				if ($countServices['RESULT'] == 'SUCCESS') {
					$this->view->messageSuccess .= " Informations : <b>".$countServices['OK']."</b> urls,";
				} else {
					$this->view->messageError .= "Erreur sur les informations : ".$countServices['OK']." urls OK, script interrompu.  ".$countServices['RESULT'];
				}

				if ($countDefault['RESULT'] == 'SUCCESS') {
					$this->view->messageSuccess .= " Connexions : <b>".$countDefault['OK']."</b> urls,";
				} else {
					$this->view->messageError .= "Erreur sur les connexions : ".$countDefault['OK']." urls OK, script interrompu.  ".$countDefault['RESULT'];
				}

				$this->view->messageSuccess .= " Total de liens : <b>".($countProduct['OK']+$countCategorie['OK']+$countCategorie2['OK']+$countServices['OK']+$countDefault['OK'])."</b>";
					
				if ($isCheckLink) {
					$this->view->messageSuccess .= "  V�rification des liens -> OK : <b>".($countProduct['OK']+$countCategorie['OK']+$countCategorie2['OK']+$countServices['OK']+$countDefault['OK'])."</b>";
					$this->view->messageError .= " V�rification des liens -> Liens morts : <b>".($countProduct['NOK']+$countCategorie['NOK']+$countCategorie2['NOK']+$countServices['NOK']+$countDefault['NOK'])."</b>";
				}

				$doc->formatOutput = true;
				// Sauver le document XML sous le nom simple.xml
				$doc->save('sitemap.xml');
				//echo $doc->saveXML();
			
				if($this->pingBingForSitemap()) {
					$this->view->messageSuccess .= ", Mise � niveau de Bing";
				}
				if($this->pingGoogleForSitemap()) {
					$this->view->messageSuccess .= ", Mise � niveau de Google";
				}
			}
		} catch (Zend_Exception $e) {
			$this->log('Erreur lors de la generation du sitemap XML : '.$e->getMessage(),'err');
			$this->view->messageError = "Erreur lors de la g�n�ration du sitemap XML : ".$e->getMessage();
		}
	}

	private function pingBingForSitemap() {
		return $this->sendUrlPostByRequest('http://www.bing.com/ping?sitemap='.$this->baseUrl_SiteCommerceUrl.'/sitemap.xml');		
	}

	private function pingGoogleForSitemap() {
		return $this->sendUrlPostByRequest('http://www.google.com/webmasters/sitemaps/ping?sitemap='.$this->baseUrl_SiteCommerceUrl.'/sitemap.xml');
	}	

	private function sendUrlPostByRequest($url) {
		$a = @get_headers($url);
		if ($a) {   
			if (strstr($a[0],'200')) { 
				return true; 
			}
		} 
		
		return false;
	}
	
	private function isLinkDead ($url) {
		if ($this->sendUrlPostByRequest($url)) {
			return false;
		}
		return true;
	}
	
	private function sitemapAddUrlProducts($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom, $isImage, $isCheckLink, $isCustomNavnom) {

		try {
			$countOk = 0;
			$countNOk = 0;

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_CustomAccent())
			->addFilter(new Zend_Filter_Alnum(array('allowwhitespace' => true)));

			$filterLight = new Zend_Filter();
			$filterLight->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());
				
			$sql = "SELECT p.ID ID, p.NOM NOM, p.NAVNOM NAVNOM, pic.URL URLIMAGE,
					p.CUSTOM_NAVNOM1 CUSTOM_NAVNOM1 ,p.CUSTOM_NAVNOM2 CUSTOM_NAVNOM2 , 
					p.CUSTOM_NAVNOM3 CUSTOM_NAVNOM3, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
			       LEFT JOIN category c ON p.IDCATEGORY = c.ID
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";

			$product = new Product();
			$listProducts = $product->getAdapter()->fetchAll($sql);

			$picture = new Picture();

			$date = new Zend_Date();
			$currentDate = $date->toString('YYYY-MM-dd');

			$type = 1; 

			foreach ($listProducts as $row) { 
				$url_elt = $doc->createElement('url');
				$body_elt->appendChild($url_elt);

				$navnom = 	$this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');
				$urlPage = $this->getUrlPageProduct(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'],'PAGE' => $navnom, 'ID' => $row['ID'], 'TYPE' => $type));

				$loc_elt = $doc->createElement('loc',  $urlPage);
				$url_elt->appendChild($loc_elt);

				if ($isImage) {
					$listPicture = $picture->fetchAll('IDPRODUCT = '.$row['ID']);

					foreach ($listPicture as $pic) {
						$image_elt  = $doc->createElement('image:image');
						$url_elt->appendChild($image_elt);

						$urlImage = $this->baseUrl_SiteCommerceUrl."/".$pic['URL'];

						$imageloc_elt = $doc->createElement('image:loc',$urlImage);
						$image_elt->appendChild($imageloc_elt);

						$string1 = $filter->filter($pic['STRING1']);
						if (isset($string1) && !empty($string1)) {
							$imagetitle_elt = $doc->createElement('image:title', $string1);
							$image_elt->appendChild($imagetitle_elt);
						}
						$string2 = $filter->filter($pic['STRING2']);
						if (isset($string2) && !empty($string2)) {
							$imagecaption_elt = $doc->createElement('image:caption', $string2);
							$image_elt->appendChild($imagecaption_elt);
						}
					}
				}

				$lastmod_elt  = $doc->createElement('lastmod', $currentDate);
				$changefreq_elt  = $doc->createElement('changefreq', $changefreq);
				$priority_elt  = $doc->createElement('priority', $priority);
				$url_elt->appendChild($lastmod_elt);
				$url_elt->appendChild($changefreq_elt);
				$url_elt->appendChild($priority_elt);
						
						
				if ($isCheckLink && $this->isLinkDead($urlPage)) { $countNOk++;
				} else { $countOk++; } 

				if ($isCustomNavnom) {
					for ($index = 1; $index < 4; $index++) {
						$navnomTemp = $filterLight->filter($row['CUSTOM_NAVNOM'.$index]);
						if (!empty($navnomTemp)) { 
								$url_elt = $doc->createElement('url');
								$body_elt->appendChild($url_elt);
									
								$navnom = 	$this->verifyNavigationString($navnomTemp, $navnomTemp, '');
								$urlPage = $this->getUrlPageProduct(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'],'PAGE' => $navnom, 'ID' => $row['ID'], 'TYPE' => $type));
									
								$loc_elt = $doc->createElement('loc',  $urlPage);
								$url_elt->appendChild($loc_elt);
									
								if ($isImage) {
									$listPicture = $picture->fetchAll('IDPRODUCT = '.$row['ID']);
									//$urlPage = $this->baseUrl_SiteCommerceUrl."/produits/detail/page/".$navnom."/p/".$row['ID'];
										
									foreach ($listPicture as $pic) {
										$image_elt  = $doc->createElement('image:image');
										$url_elt->appendChild($image_elt);
											
										$urlImage = $this->baseUrl_SiteCommerceUrl."/".$pic['URL'];
											
										$imageloc_elt = $doc->createElement('image:loc',$urlImage);
										$image_elt->appendChild($imageloc_elt);
											
										$string1 = $filter->filter($pic['STRING1']);
										if (isset($string1) && !empty($string1)) {
											$imagetitle_elt = $doc->createElement('image:title', $string1);
											$image_elt->appendChild($imagetitle_elt);
										}
										$string2 = $filter->filter($pic['STRING2']);
										if (isset($string2) && !empty($string2)) {
											$imagecaption_elt = $doc->createElement('image:caption', $string2);
											$image_elt->appendChild($imagecaption_elt);
										}
									}
								}
									
								$lastmod_elt  = $doc->createElement('lastmod', $currentDate);
								$changefreq_elt  = $doc->createElement('changefreq', $changefreq);
								$priority_elt  = $doc->createElement('priority', $priority);
								$url_elt->appendChild($lastmod_elt);
								$url_elt->appendChild($changefreq_elt);
								$url_elt->appendChild($priority_elt);


								if ($isCheckLink && $this->isLinkDead($urlPage)) { $countNOk++;
								} else { $countOk++; }
							} 
					}
				}
			}
		} catch (Zend_Exception $e) {
			$this->log('Erreur lors de la generation du sitemapAddUrlProducts : '.$e->getMessage(),'err');
			return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => $e->getMessage());
		}
		return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => 'SUCCESS');
	}
	private function sitemapAddUrlCategories($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom, $isImage, $isCheckLink) {
			
		try {
			$countOk = 0;
			$countNOk = 0;

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_CustomAccent())
			->addFilter(new Zend_Filter_Alnum(array('allowwhitespace' => true)));

			$sql = "SELECT c.ID ID, c.NOM NOM, c.URL URL, c.NAVNOM NAVNOM, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
			FROM category c WHERE c.isACTIVE = 1";

			$categorie = new Category();
			$listCats = $categorie->getAdapter()->fetchAll($sql);

			$date = new Zend_Date();
			$currentDate = $date->toString('YYYY-MM-dd');

			$type = 1; 

			foreach ($listCats as $row) { 
				$url_elt = $doc->createElement('url');
				$body_elt->appendChild($url_elt);

				$navnom = 	$this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');
				$urlPage = $this->getUrlPageCategory(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'], 'PAGE' => $navnom, 'ID' => $row['ID'], 'TYPE' => $type));

				$loc_elt = $doc->createElement('loc',  $urlPage);
				$url_elt->appendChild($loc_elt);

				if ($isImage) {
					if (isset($row['URL']) && !empty($row['URL'])) {
						$image_elt  = $doc->createElement('image:image');
						$url_elt->appendChild($image_elt);

						$urlImage = $this->baseUrl_SiteCommerceUrl."/".$row['URL'];

						$imageloc_elt = $doc->createElement('image:loc',$urlImage);
						$image_elt->appendChild($imageloc_elt);

						$string1 = $filter->filter($row['NOM']);
						if (isset($string1) && !empty($string1)) {
							$imagetitle_elt = $doc->createElement('image:title', $string1);
							$image_elt->appendChild($imagetitle_elt);
						}
					}
				}

				$lastmod_elt  = $doc->createElement('lastmod', $currentDate);
				$changefreq_elt  = $doc->createElement('changefreq', $changefreq);
				$priority_elt  = $doc->createElement('priority', $priority);
				$url_elt->appendChild($lastmod_elt);
				$url_elt->appendChild($changefreq_elt);
				$url_elt->appendChild($priority_elt);

				if ($isCheckLink && $this->isLinkDead($urlPage)) { $countNOk++;
				} else { $countOk++; } 
			}
		} catch (Zend_Exception $e) {
			$this->log('Erreur lors de la generation du sitemapAddUrlCategories : '.$e->getMessage(),'err');
			return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => $e->getMessage());
		}
		return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => 'SUCCESS');
	}

	private function sitemapAddUrlCategories2($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom, $isImage, $isCheckLink) {
        
		try {
			$countOk = 0;
			$countNOk = 0;

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_CustomAccent())
			->addFilter(new Zend_Filter_Alnum(array('allowwhitespace' => true)));

			$sql = "SELECT c.ID ID, c.NOM NOM, c.URL URL, c.NAVNOM NAVNOM, c.NAVNOM_URLPARENTS NAVNOM_URLPARENTS
			FROM category2 c WHERE c.isACTIVE = 1";

			$categorie = new Category();
			$listCats = $categorie->getAdapter()->fetchAll($sql);

			$date = new Zend_Date();
			$currentDate = $date->toString('YYYY-MM-dd');

			$type = 2; 

			foreach ($listCats as $row) { 
					$url_elt = $doc->createElement('url');
					$body_elt->appendChild($url_elt);

					$navnom = 	$this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');
					$urlPage = $this->getUrlPageCategory(array('NAVNOM_URLPARENTS' => $row['NAVNOM_URLPARENTS'], 'PAGE' => $navnom, 'ID' => $row['ID'], 'TYPE' => $type));

					$loc_elt = $doc->createElement('loc',  $urlPage);
					$url_elt->appendChild($loc_elt);

					if ($isImage) {
						if (isset($row['URL']) && !empty($row['URL'])) {
							$image_elt  = $doc->createElement('image:image');
							$url_elt->appendChild($image_elt);

							$urlImage = $this->baseUrl_SiteCommerceUrl."/".$row['URL'];

							$imageloc_elt = $doc->createElement('image:loc',$urlImage);
							$image_elt->appendChild($imageloc_elt);

							$string1 = $filter->filter($row['NOM']);
							if (isset($string1) && !empty($string1)) {
								$imagetitle_elt = $doc->createElement('image:title', $string1);
								$image_elt->appendChild($imagetitle_elt);
							}
						}
					}

					$lastmod_elt  = $doc->createElement('lastmod', $currentDate);
					$changefreq_elt  = $doc->createElement('changefreq', $changefreq);
					$priority_elt  = $doc->createElement('priority', $priority);
					$url_elt->appendChild($lastmod_elt);
					$url_elt->appendChild($changefreq_elt);
					$url_elt->appendChild($priority_elt);

					if ($isCheckLink && $this->isLinkDead($urlPage)) {
                        $countNOk++;
					} else { $countOk++; } 
			}
		}
        catch (Zend_Exception $e) {
			$this->log('Erreur lors de la generation du sitemapAddUrlCategories2 : '.$e->getMessage(),'err');
			return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => $e->getMessage());
		}
		return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => 'SUCCESS');
	}
	private function sitemapAddUrlInfos($doc, $body_elt, $changefreq, $priority, $isDupliateByNavNom,$isImage, $isCheckLink) {
			
		try {
			$countOk = 0;
			$countNOk = 0;

			$footers = new FooterContent();
			$listFooter = $footers->fetchAll();

			$date = new Zend_Date();
			$currentDate = $date->toString('YYYY-MM-dd');


			$type = 1; 

			foreach ($listFooter AS $row) { 
					$urlPage = $this->getUrlPageInfo(array('TITRE' => $row['TITRE'], 'ID' => $row['ID'], 'URL' => $row['URL'], 'TYPE' => $type));

					$url_elt = $doc->createElement('url');
					$body_elt->appendChild($url_elt);

					$loc_elt = $doc->createElement('loc',  $urlPage);
					$url_elt->appendChild($loc_elt);

					$lastmod_elt  = $doc->createElement('lastmod', $currentDate);
					$changefreq_elt  = $doc->createElement('changefreq', $changefreq);
					$priority_elt  = $doc->createElement('priority', $priority);
					$url_elt->appendChild($lastmod_elt);
					$url_elt->appendChild($changefreq_elt);
					$url_elt->appendChild($priority_elt);

					if ($isCheckLink && $this->isLinkDead($urlPage)) { $countNOk++;
					} else { $countOk++; } 
			}

		} catch (Zend_Exception $e) {
			$this->log('Erreur lors de la generation du sitemapAddUrlInfos : '.$e->getMessage(),'err');
			return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => $e->getMessage());
		}
		return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => 'SUCCESS');
	}

	private function sitemapAddUrlDefault($doc, $body_elt, $isCheckLink) {

		try {
			$countOk = 0;
			$countNOk = 0;
				
			$date = new Zend_Date();
			$currentDate = $date->toString('YYYY-MM-dd');

			$addArray = array();
			$addArray[0]['loc'] = $this->baseUrl_SiteCommerceUrl."/";
			$addArray[0]['changefreq'] = "monthly";
			$addArray[0]['priority'] = "0.9";

			$addArray[1]['loc'] = $this->baseUrl_SiteCommerceUrl."/mon-panier.html";
			$addArray[1]['changefreq'] = "monthly";
			$addArray[1]['priority'] = "0.9";

			$addArray[2]['loc'] = $this->baseUrl_SiteCommerceUrl."/connectez-vous.html";
			$addArray[2]['changefreq'] = "monthly";
			$addArray[2]['priority'] = "0.9";

			$addArray[3]['loc'] = $this->baseUrl_SiteCommerceUrl."/enregistrez-vous.html";
			$addArray[3]['changefreq'] = "monthly";
			$addArray[3]['priority'] = "0.9";

			$addArray[4]['loc'] = $this->baseUrl_SiteCommerceUrl."/services/faq/";
			$addArray[4]['changefreq'] = "monthly";
			$addArray[4]['priority'] = "0.9";

			$addArray[5]['loc'] = $this->baseUrl_SiteCommerceUrl."/retrouver-mon-mot-de-passe.html";
			$addArray[5]['changefreq'] = "monthly";
			$addArray[5]['priority'] = "0.9";


			for ($i = 0; $i < sizeof($addArray); $i++) {
					
				$url_elt = $doc->createElement('url');
				$body_elt->appendChild($url_elt);
					
				$loc_elt = $doc->createElement('loc',  $addArray[$i]['loc']);
				$url_elt->appendChild($loc_elt);


				$lastmod_elt  = $doc->createElement('lastmod', $currentDate);
				$changefreq_elt  = $doc->createElement('changefreq', $addArray[$i]['changefreq']);
				$priority_elt  = $doc->createElement('priority', $addArray[$i]['priority']);
				$url_elt->appendChild($lastmod_elt);
				$url_elt->appendChild($changefreq_elt);
				$url_elt->appendChild($priority_elt);

				if ($isCheckLink && $this->isLinkDead($addArray[$i]['loc'])) { $countNOk++;
				} else { $countOk++; }
			}


		} catch (Zend_Exception $e) {
			$this->log('Erreur lors de la generation du sitemapAddUrlDefault : '.$e->getMessage(),'err');
			return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => $e->getMessage());
		}
		return array('OK' => $countOk, 'NOK' => $countNOk, 'RESULT' => 'SUCCESS');
	}

	private function cleanUp($value) {
		$result = $value;
		$filter = new Zend_Filter();
		$filter->addFilter(new Zend_Filter_StringTrim())
		->addFilter(new Zend_Filter_StripTags());
		$result =$filter->filter($result);
		$result = html_entity_decode($result,ENT_QUOTES,"ISO-8859-1");
		$result = str_replace("\r\n", "", $result);
		$result = str_replace('"',"'",$result);
		$result = str_replace(';',"'",$result);
		return $result;
	}

	private function getUrlPage($params) {
		//produit
		return $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlProduct($params['NAVNOM_URLPARENTS'], $params['PAGE'], $params['ID']);
	}

	private function getUrlPageProduct($params) {
		//produit
		switch ($params['TYPE']) {
			case 1 :
				return $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlProduct($params['NAVNOM_URLPARENTS'], $params['PAGE'], $params['ID']);
				break;
		}
	}
	
	private function getUrlPageCategory($params) {
		//category
		switch ($params['TYPE']) {
			case 1 :
				return $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlCategory($params['NAVNOM_URLPARENTS'], $params['PAGE'], $params['ID']);
				break;
			case 1 :
				return $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlCategory2($params['NAVNOM_URLPARENTS'], $params['PAGE'], $params['ID']);
				break;
		}
	}
	private function getUrlPageInfo($params) {
		//Info
		$navnom = $this->verifyNavigationString("", $params['TITRE'], "");
		$urlPage = "";
		if (empty($params['URL'])) {
			switch ($params['TYPE']) {
				case 1 :
					$urlPage = $this->baseUrl_SiteCommerceUrl."/info-".$params['ID']."/".$navnom.".html";
					break;
			}
		} else {
			$urlPage = "http://".$params['URL'];
		}
		return $urlPage;
	}
}
?>PromotionController.php000060400000136235150713030120011305 0ustar00<?php
class Backoffice_PromotionController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Promos";
		$this->isConnectedWithRole('isPromo'); 
	}
	function indexAction()
	{
		$this->_forward('/product');

	}

	function frontAction()
	{
		$this->view->titlePage = "Les promotions de la page d'Accueil";
		$promoFront = new PromoFront();
			
		$listFrontSQL = "
		SELECT p.NOM NOM, p.DESCRIPTIONSHORT DESCSHORT, p.ID IDPRODUCT,
				pf.REFERENCE REFERENCE, pf.POSITION POSITION, pf.ID ID
				FROM promo_front AS pf
				LEFT JOIN productchild AS pc ON pc.REFERENCE = pf.REFERENCE
				LEFT JOIN product AS p ON pc.IDPRODUCT = p.ID
				ORDER BY pf.POSITION ASC";
		$listFront = $promoFront->getAdapter()->fetchAll($listFrontSQL);
		$this->view->listFront = $listFront;
	}
	function frontaddAction()
	{
		if ($this->getRequest()->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$promoFront = new PromoFront();
			$productChild = new ProductChild();

			$params = array();
			$params = $this->getRequest()->getPost();

			if ($validator->isValid($params['reference']))
			{
				$isExistProduct = $productChild->fetchRow("REFERENCE = '".$params['reference']."'");
				if ($isExistProduct ) {
					if ($isExistProduct['isPROMO'] == 0) {
						$isExistFront = $promoFront->fetchRow("REFERENCE = '".$params['reference']."'");
						if (!$isExistFront) {
							$date = new Zend_Date();
							$data = array (
		 		 						'REFERENCE' => $filter->filter($params['reference']),
										'POSITION' => (int)$params['position'],
 	 									'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss')
							);
							$promoFront->insert($data);
						} else {
							$this->view->messageError = "Le produit est d�j� affich�";
						}
					} else {
						$this->view->messageError = "La r�f�rence n'est pas en promotion";
					}
				} else {
					$this->view->messageError = "La r�f�rence ".$params['reference']." n'existe pas.";
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('front');
	}

	function fronteditAction() {
		if ($this->getRequest()->isPost()) {

			$promoFront = new PromoFront();
			$params = $this->getRequest()->getPost();

			$date = new Zend_Date();
			$data = array (
 	 						'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss'),
					 		'POSITION' => (int)$params['position']
			);
			$promoFront->update($data,'ID = '.$params['promoid']);

			$this->view->messageSuccess = "Le produit est affich�";

		}
		$this->_forward('front');
	}
	function frontdelAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$promoFront = new PromoFront();
				$promoFront->delete('ID = '.$id);
				$this->view->messageSuccess = "L'article n'est plus affich� sur la page d'accueil";
			}
		}
		$this->_forward('front');

	}

	function productAction() {
		$this->view->titlePage = "Les promotions sur les Produits";
		$supplierBrend = new SupplierBrend();
		$this->view->listbrend = $supplierBrend->fetchAll($supplierBrend->select()->order('BREND ASC'));

		$promoProduct = new PromoProduct();

		//Promo par article
		$listPromo1SQL = "
		SELECT p.NOM NOM, p.DESCRIPTIONSHORT DESCSHORT, p.ID ID, ppc.ID IDPROMO,
				pc.REFERENCE REFERENCE, ppc.REMISEEURO REMISEEURO, ppc.REMISEPOUR REMISEPOUR
				FROM promo_productchild AS ppc
				LEFT JOIN productchild AS pc ON pc.REFERENCE = ppc.REFERENCE
				LEFT JOIN product AS p ON pc.IDPRODUCT = p.ID
				WHERE ppc.REFERENCE IS NOT NULL
				ORDER BY pc.REFERENCE ASC";
		$listPromo1 = $promoProduct->getAdapter()->fetchAll($listPromo1SQL);
		$this->view->listPromo1 = $listPromo1;

		//Promotion sur X selon Y
		$listPromo2SQL = "
		SELECT ppc.REMISEEURO REMISEEURO, ppc.REMISEPOUR REMISEPOUR,ppc.ID IDPROMO,
				 ppc.CHILDREFBUY CHILDREFBUY, ppc.CHILDREFPROMO CHILDREFPROMO,
				 ppc.CHILDREFBUYNB CHILDREFBUYNB, ppc.CHILDREFPROMONB CHILDREFPROMONB
				 FROM promo_productchild AS ppc
				WHERE ppc.CHILDREFBUY IS NOT NULL 
				AND ppc.CHILDREFPROMO IS NOT NULL
				ORDER BY ppc.CHILDREFBUY, ppc.CHILDREFPROMO ASC";

		$this->view->listPromo2 = $promoProduct->getAdapter()->fetchAll($listPromo2SQL);

		//Promotion Date
		$listPromo3SQL = "
		SELECT ppc.DATEPROMOSTART DATEPROMOSTART, ppc.DATEPROMOEND DATEPROMOEND,ppc.ID IDPROMO,
			ppc.REMISEEURO REMISEEURO, ppc.REMISEPOUR REMISEPOUR
				FROM promo_productchild AS ppc
				WHERE ppc.DATEPROMOSTART IS NOT NULL 
				AND ppc.DATEPROMOEND IS NOT NULL 
				ORDER BY ppc.DATEPROMOSTART, ppc.DATEPROMOEND ASC";
		$this->view->listPromo3 = $promoProduct->getAdapter()->fetchAll($listPromo3SQL);

		//Promotion Gamme
		$listPromo4SQL = "
		SELECT c.NOM NOMCATEGORY, c.ID IDCATEGORY, ppc.ID IDPROMO,
			ppc.REMISEEURO REMISEEURO, ppc.REMISEPOUR REMISEPOUR
				FROM promo_productchild AS ppc
				LEFT JOIN category AS c ON c.ID = ppc.IDCATEGORY
				WHERE ppc.IDCATEGORY IS NOT NULL
				ORDER BY c.NOM ASC";
		$this->view->listPromo4 = $promoProduct->getAdapter()->fetchAll($listPromo4SQL);

		//Promotion Marque
		$listPromo5SQL = "
		SELECT sb.BREND BREND, sb.ID IDBREND, ppc.ID IDPROMO,
			ppc.REMISEEURO REMISEEURO, ppc.REMISEPOUR REMISEPOUR
				FROM promo_productchild AS ppc
				LEFT JOIN supplier_brend AS sb ON sb.ID = ppc.IDBREND
				WHERE ppc.IDBREND IS NOT NULL
				ORDER BY sb.BREND ASC";
		$this->view->listPromo5 = $promoProduct->getAdapter()->fetchAll($listPromo5SQL);


	}
	function productdelAction() {
        try {
		    if ($this->getRequest()->getParam('id')) {
			    $id = (int)$this->getRequest()->getParam('id');
			    if ($id > 0 ) {
				    $promoProduct = new PromoProduct();

				    $promoProduct->delete('ID = '.$id);
				    $this->view->messageSuccess = "La promotion a �t� supprim�e ";

			    } else {
				    $this->view->messageError = "La promotion n'a pas �t� supprim�e ";

			    }
		    }
		    if ($this->getRequest()->getParam('idref')) {
			    $idRef = (int)$this->getRequest()->getParam('idref');
			    if ($idRef > 0 ) {
				    $promoProduct = new PromoProduct();
				    $productChild = new ProductChild();

				    $resultSQL = "
				    SELECT p.NOM NOM,p.ID IDPRODUCT, p.isPROMO isPROMOPRODUCT, 
						    pp.ID, pp.REFERENCE REFERENCE
					    FROM promo_productchild AS pp
					    LEFT JOIN productchild AS pc ON pc.REFERENCE = pp.REFERENCE
					    LEFT JOIN product AS p ON pc.IDPRODUCT = p.ID
					    WHERE pp.ID = ".$idRef;
                        
				    $result = $promoProduct->getAdapter()->fetchRow($resultSQL);

				    $data = array (
					    'isPROMO' => 1
				    );
				    $productChild->update($data,"REFERENCE = '".$result['REFERENCE']."'");

				    $isLastPromo = $productChild->fetchRow("isPROMO = 0 AND IDPRODUCT = ".$result['IDPRODUCT']);
				    if (!$isLastPromo) {
					    $product = new Product();
					    $product->update($data,"ID = ".$result['IDPRODUCT']);
				    }
					
				    $promoProduct->delete('ID = '.$idRef);
				    $this->view->messageSuccess = "La promotion a �t� supprim�e ";

			    } else {
				    $this->view->messageError = "La promotion n'a pas �t� supprim�e ";

			    }
		    }
        } catch (Zend_Exception $e) {
			$this->log('productdelAction : '.$e->getMessage(),'err');
		}
		$this->_forward('product');
	}
	function productaddAction() {
        try {
		    if ($this->getRequest()->isPost()) {

			    //filtres pour changer les chaines
			    $filter = new Zend_Filter();
			    $filter	->addFilter(new Zend_Filter_StripTags())
			    ->addFilter(new Zend_Filter_StringTrim());

			    //valideurs pour les chaines
			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());


			    $promoProduct = new PromoProduct();
			    $productChild = new ProductChild();

			    $params = array();
			    $params = $this->getRequest()->getPost();

			    $remiseeuro = !empty($params['remiseeuro']) ? $params['remiseeuro'] : 0;
			    $remisepour = (int)$params['remisepour'];
			    $isOK = true;
			    if ($remiseeuro > 0 && $remisepour > 0) {
				    $this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE. ";
				    $isOK = false;
			    }
			    if ($remiseeuro == 0 && $remisepour == 0) {
				    $this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE et est obligatoire. ";
				    $isOK = false;
			    }
			    if (($validator->isValid($remiseeuro) ||
			    $validator->isValid($remisepour)) && $isOK == true
			    ) {
				    switch ($params['promo']) {
					    case 1 :
						    if ($validator->isValid($params['reference'])) {

							    $isExistChild = $productChild->fetchRow("REFERENCE = '".$params['reference']."'");
							    $isExistPromo = $promoProduct->fetchRow("REFERENCE = '".$params['reference']."'");
							    if ($isExistChild) {
								    if ($isExistPromo) {
									    $this->view->messageError = "La r�f�rence : ".$params['reference']." est d�ja en promotion. ";
								    } else {
									    $date = new Zend_Date();

									    $data = array (
				 		 						    'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss'),
												    'REMISEEURO' => $remiseeuro,
										 		    'REMISEPOUR' => $remisepour,
										 		    'REFERENCE' => $filter->filter($params['reference'])
									    );
									    $promoProduct->insert($data);

									    $product = new Product();
									    $data2 = array (
				 		 						    'isPROMO' => 0
									    );
									    $product->update($data2, 'ID = '.$isExistChild['IDPRODUCT']);
									    $productChild->update($data2, "REFERENCE = '".$isExistChild['REFERENCE']."'");

									    $this->view->messageSuccess = "La r�f�rence : ".$data['REFERENCE']." est maintenant est promotion. ";
								    }
							    } else {
								    $this->view->messageError = "La r�f�rence : ".$params['reference']." n'existe pas. ";
							    }
						    } else {
							    foreach ($validator->getErrors() as $errorCode) {
								    $this->view->messageError .=  $this->getErrorValidator($errorCode);
							    }
						    }
						    break;
					    case 2 :
						
						    if ($validator->isValid($params['referencebuy']) &&
						    $validator->isValid($params['referencepromo']) &&
						    ((int)$params['referencepromonb']>0) &&
						    ((int)$params['referencebuynb']>0)
						    ) {

							    $isExistChild1 = $productChild->fetchRow("REFERENCE = '".$params['referencebuy']."'");
							    $isExistChild2 = $productChild->fetchRow("REFERENCE = '".$params['referencepromo']."'");

							    if ($isExistChild1 && $isExistChild2 && $params['referencebuy'] != $params['referencepromo']) {
								    $isExistPromo = $promoProduct->fetchRow("CHILDREFBUY = '".$params['referencebuy']."' AND CHILDREFPROMO = '".$params['referencepromo']."'");
									
								    if ($isExistPromo) {
									    $this->view->messageError = "La r�f�rence : ".$params['referencepromo']." est d�j� en promotion. ";
								    } else {
									    $date = new Zend_Date();

									    $data = array (
				 		 						    'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss'),
												    'REMISEEURO' => $remiseeuro,
										 		    'REMISEPOUR' => $remisepour,
										 		    'CHILDREFBUY' => $filter->filter($params['referencebuy']),
										 		    'CHILDREFPROMO' => $filter->filter($params['referencepromo']),
										 		    'CHILDREFPROMONB' => $filter->filter((int)$params['referencepromonb']),
										 		    'CHILDREFBUYNB' => $filter->filter((int)$params['referencebuynb'])
									    );
									    $promoProduct->insert($data);

									    $this->view->messageSuccess = "Si <b>".$data['CHILDREFBUYNB']."</b> articles de <b>".$data['CHILDREFBUY']."</b> sont achet�s alors <b>".$data['CHILDREFPROMONB']."</b> articles de <b>".$data['CHILDREFPROMO']."</b> sont en promotion ";
								    }
							    } else {
								    if ($params['referencebuy'] == $params['referencepromo']) {
									    $this->view->messageError = "Les r�f�rences sont identiques";

								    } else {
									    $this->view->messageError = "La r�f�rence : ".$params['referencebuy']." ou ".$params['referencepromo']." n'existe pas. ";

								    }
							    }
						    } else {
							    foreach ($validator->getErrors() as $errorCode) {
								    $this->view->messageError .=  $this->getErrorValidator($errorCode);
							    }
						    }
						    break;
					    case 3 :
						    $validator->addValidator(new Zend_Validate_Date());

						    if ($validator->isValid($params['sd']) &&
						    $validator->isValid($params['ed'])
						    ) {
							    $isExistPromo = $promoProduct->fetchRow("DATEPROMOSTART = '".$params['sd']."' AND DATEPROMOEND = '".$params['ed']."' ");

							    if ($isExistPromo) {
								    $this->view->messageError = "La promotion pour cette p�riode existe d�j� ";
							    } else {
								    $date = new Zend_Date();

								    $data = array (
			 		 						    'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss'),
											    'REMISEEURO' => $remiseeuro,
									 		    'REMISEPOUR' => $remisepour,
									 		    'DATEPROMOSTART' => $filter->filter($params['sd']),
									 		    'DATEPROMOEND' => $filter->filter($params['ed'])
								    );
								    $promoProduct->insert($data);
									
								    $this->view->messageSuccess = "Les produits o� la date de promotion est comprise entre ".$params['sd']." et ".$params['ed']." sont en promotions. ";
							    }
						    } else {
							    foreach ($validator->getErrors() as $errorCode) {
								    $this->view->messageError .=  $this->getErrorValidator($errorCode);
							    }
						    }
						    break;
							
					    case 4 :
						    if ($params['listcategory'] > 0 ) {

							    $isExistPromo = $promoProduct->fetchRow("IDCATEGORY = ".$params['listcategory']);

							    if ($isExistPromo) {
								    $this->view->messageError = "La promotion pour cette gamme existe d�j� ";
							    } else {
								    $date = new Zend_Date();

								    $data = array (
			 		 						    'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss'),
											    'REMISEEURO' => $remiseeuro,
									 		    'REMISEPOUR' => $remisepour,
									 		    'IDCATEGORY' => $filter->filter($params['listcategory'])
								    );
								    $promoProduct->insert($data);
									
								    $this->view->messageSuccess = "Les produits de la gamme sont maintenant en promotion. ";
							    }
						    } else {
							    $this->view->messageError = "S�lectionner une cat�gorie";

						    }
						    break;
							
					    case 5 :
						    if ($params['listbrend'] > 0 ) {

							    $isExistPromo = $promoProduct->fetchRow("IDBREND = ".$params['listbrend']);

							    if ($isExistPromo) {
								    $this->view->messageError = "La promotion pour cette marque existe d�j� ";
							    } else {
								    $date = new Zend_Date();

								    $data = array (
			 		 						    'DATEINSERTPROMO' => $date->toString('YYYY-MM-dd HH-mm-ss'),
											    'REMISEEURO' => $remiseeuro,
									 		    'REMISEPOUR' => $remisepour,
									 		    'IDBREND' => $filter->filter($params['listbrend'])
								    );
								    $promoProduct->insert($data);
									
								    $this->view->messageSuccess = "Les produits de la marque sont maintenant en promotion. ";
							    }
						    } else {
							    $this->view->messageError = "S�lectionner une marque";

						    }
						    break;
					    default:
						    $this->_forward('product');
						    break;
							
				    }
			    } else {
				    foreach ($validator->getErrors() as $errorCode) {
					    $this->view->messageError .=  $this->getErrorValidator($errorCode);
				    }
			    }
		    }
        } catch (Zend_Exception $e) {
			$this->log('productaddAction : '.$e->getMessage(),'err');
			$this->view->messageError = "V�rifier les param�tres";
		}
		$this->_forward('product');
	}

	function commandAction() {
		$this->view->titlePage = "Les remises sur les Commandes";
		$promoCommand = new PromoCommand();

		$isAll = $promoCommand->fetchRow('isALL = 0 AND isALL IS NOT NULL');
		if ($isAll) {
			$this->view->remiseAll = $isAll;
		}
		$isMontant = $promoCommand->fetchRow('MONTANTEQUAL > 0 AND MONTANTEQUAL IS NOT NULL');
		if ($isMontant) {
			$this->view->remiseMontant = $isMontant;
		}
		
		$listRemise1SQL = "
		SELECT p.NOM NOM,p.ID IDPRODUCT, p.DESCRIPTIONSHORT DESCSHORT, prc.ID ID,prc.CHILDNBR CHILDNBR,
				prc.CHILDREFERENCE CHILDREFERENCE, prc.REMISEEURO REMISEEURO, prc.REMISEPOUR REMISEPOUR
				FROM promo_command AS prc
				LEFT JOIN productchild AS pc ON pc.REFERENCE = prc.CHILDREFERENCE
				LEFT JOIN product AS p ON pc.IDPRODUCT = p.ID
				WHERE prc.CHILDREFERENCE IS NOT NULL
				ORDER BY prc.CHILDREFERENCE ASC";
		$listRemise1 = $promoCommand->getAdapter()->fetchAll($listRemise1SQL);
		$this->view->listRemise1 = $listRemise1;

	}

	function commandaddAction() {
		if ($this->getRequest()->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			$promoCommand = new PromoCommand();
			$productChild = new ProductChild();

			$params = array();
			$params = $this->getRequest()->getPost();

			if ($params['remise'] == '5') {
				if (isset($params['montantfrais']) && (int)$params['montantfrais'] > 0 && $validator->isValid($params['montantfrais'])) {
					$isExistFrais = $promoCommand->fetchRow("MONTANTVALID IS NOT NULL");
					if ($isExistFrais) {
						$date = new Zend_Date();

						$data = array (
  						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
  						'MONTANTVALID' => $filter->filter($params['montantfrais'])
						);
						$promoCommand->update($data,'ID = '.$isExistFrais['ID']);

						$this->view->messageSuccess = "La validit� de la commande a �t� modifi�e ";

					} else {
						$date = new Zend_Date();

						$data = array (
  						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
  						'MONTANTVALID' => $filter->filter($params['montantfrais'])
						);
						$promoCommand->insert($data);
						$this->view->messageSuccess = "La validit� de la commande a �t� modifi�e ";
					}
				} else {
					$this->view->messageError = "Le montant de la commande doit etre sup�rieur � 0";
				}
			}
			if (isset($params['remisepour']) && isset($params['remiseeuro'])) {
					
				$remiseeuro = (int)$params['remiseeuro'];
				$remisepour = (int)$params['remisepour'];
				$isOK = true;
				if ($remiseeuro > 0 && $remisepour > 0) {
					$this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE. ";
					$isOK = false;
				}
				if ($remiseeuro == 0 && $remisepour == 0) {
					$this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE et est obligatoire. ";
					$isOK = false;
				}
				if (($validator->isValid($remiseeuro) ||
				$validator->isValid($remisepour)) && $isOK == true
				) {
					switch ($params['remise']) {
						case 1 :
							$isExistAll = $promoCommand->fetchRow("isALL IS NOT NULL");
							if ($isExistAll) {
								$date = new Zend_Date();

								$data = array (
				 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
				 		 						'isALL' => '0',
												'REMISEEURO' => $filter->filter($params['remiseeuro']),
										 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoCommand->update($data,'ID = '.$isExistAll['ID']);
									
								$this->view->messageSuccess = "Toutes les commandes ont maintenant une remise ";

							} else {
								$date = new Zend_Date();

								$data = array (
				 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
				 		 						'isALL' => '0',
												'REMISEEURO' => $filter->filter($params['remiseeuro']),
										 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoCommand->insert($data);
								$this->view->messageSuccess = "Toutes les commandes ont maintenant une remise ";
							}

							break;
						case 2 :
							if ($validator->isValid($params['montant']) &&
							(int)$params['montant'] > 0
							) {
									
								$isExistMontant = $promoCommand->fetchRow("MONTANTEQUAL IS NOT NULL");

								if ($isExistMontant) {
									$date = new Zend_Date();

									$data = array (
				 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
				 		 						'MONTANTEQUAL' => $filter->filter($params['montant']),
												'REMISEEURO' => $filter->filter($params['remiseeuro']),
										 		'REMISEPOUR' => $filter->filter($params['remisepour'])
									);
									$promoCommand->update($data,'ID = '.$isExistMontant['ID']);

									$this->view->messageSuccess = "Toutes les commandes ont maintenant une remise ";

								} else {
									$date = new Zend_Date();

									$data = array (
				 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
				 		 						'MONTANTEQUAL' => $filter->filter($params['montant']),
												'REMISEEURO' => $filter->filter($params['remiseeuro']),
										 		'REMISEPOUR' => $filter->filter($params['remisepour'])
									);
									$promoCommand->insert($data);
									$this->view->messageSuccess = "Toutes les commandes ont maintenant une remise ";
								}
							} else {
								foreach ($validator->getErrors() as $errorCode) {
									$this->view->messageError .=  $this->getErrorValidator($errorCode);
								}
							}
							break;
						case 3 :
							if ($validator->isValid($params['nbrreference']) &&
							$validator->isValid($params['reference']) &&
							(int)$params['nbrreference'] > 0
							) {
									
								$isExistReferenceChild = $productChild->fetchRow("REFERENCE = '".$params['reference']."' ");
								if ($isExistReferenceChild) {
									$isExistReference = $promoCommand->fetchRow("CHILDREFERENCE = '".$params['reference']."' ");

									if ($isExistReference) {
										$this->view->messageError = "Les commandes ont d�j� une remise sur cet article ";

									} else {
										$date = new Zend_Date();

										$data = array (
						 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
						 		 						'CHILDREFERENCE' => $filter->filter($params['reference']),
						 		 						'CHILDNBR' => $filter->filter($params['nbrreference']),
														'REMISEEURO' => $filter->filter($params['remiseeuro']),
												 		'REMISEPOUR' => $filter->filter($params['remisepour'])
										);
										$promoCommand->insert($data);
										$this->view->messageSuccess = "Toutes les commandes ont maintenant une remise ";
									}
								} else {
									$this->view->messageError =  "La r�f�rence ".$params['reference']." n'existe pas";

								}
							} else {
								foreach ($validator->getErrors() as $errorCode) {
									$this->view->messageError .=  $this->getErrorValidator($errorCode);
								}
								if ((int)$params['nbrreference'] == 0) {
									$this->view->messageError .=  "Le nombre d'articles doit etre sup�rieur � 0";

								}
							}
							break;
						case 4 :
							if (isset($params['montantfrais']) && (int)$params['montantfrais'] > 0) {
								$isExistFrais = $promoCommand->fetchRow("MONTANTFRAISCMD IS NOT NULL AND MONTANTFRAISCMD = ".$params['montantfrais']);
								if ($isExistFrais) {
									$date = new Zend_Date();

									$data = array (
	 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
	 		 						'MONTANTFRAISCMD' => $filter->filter($params['montantfrais']),
									'REMISEEURO' => $filter->filter($params['remiseeuro']),
									'REMISEPOUR' => $filter->filter($params['remisepour'])
									);
									$promoCommand->update($data,'ID = '.$isExistFrais['ID']);

									$this->view->messageSuccess = "Les frais de livraison sont modifi�s ";

								} else {
									$date = new Zend_Date();

									$data = array (
	 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
	 		 						'MONTANTFRAISCMD' => $filter->filter($params['montantfrais']),
									'REMISEEURO' => $filter->filter($params['remiseeuro']),
									'REMISEPOUR' => $filter->filter($params['remisepour'])
									);
									$promoCommand->insert($data);
									$this->view->messageSuccess = "Les frais de livraison sont modifi�s ";
								}
							} else {
								$this->view->messageError = "Le montant de la commande doit etre sup�rieur � 0";
							}
							break;
						default:
							$this->_forward('command');
							break;

					}
				} else {
					foreach ($validator->getErrors() as $errorCode) {
						$this->view->messageError .=  $this->getErrorValidator($errorCode);
					}
				}
			}
		}
		$this->_forward('command');
	}
	function commanddelAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$promoCommand = new PromoCommand();
				$promoCommand->delete('ID = '.$id);
				$this->view->messageSuccess = "La remise a �t� supprim�e ";
			} else {
				$this->view->messageError = "La remise n'a pas �t� supprim�e ";

			}
		}
		$this->_forward('command');
	}
	function userAction() {
		$this->view->titlePage = "Les remises des Clients";
		$promoUser = new PromoUser();
		$user = new User();
		$supplierBrend = new SupplierBrend();
		$this->view->listbrend = $supplierBrend->fetchAll($supplierBrend->select()->order('BREND ASC'));

		$codeIntern = new CodeIntern();
		$this->view->listAllCIntern = $codeIntern->fetchAll($codeIntern->select()->order('CODE ASC'));

		$listAllUserSQL = "
		SELECT u.NOM NOM,u.ID IDUSER, u.PRENOM PRENOM
				FROM user AS u 
				ORDER BY u.NOM, u.PRENOM ASC";
		$listAllUser = $user->getAdapter()->fetchAll($listAllUserSQL);
		if ($listAllUser) {
			$this->view->listAllUser = $listAllUser;
		}

		$listUserSQL = "
		SELECT u.NOM NOM,u.ID IDUSER, u.PRENOM PRENOM, 
				pu.ID ID, pu.REMISEEURO REMISEEURO, pu.REMISEPOUR REMISEPOUR
				FROM promo_user AS pu
				LEFT JOIN user AS u ON u.ID = pu.IDUSER
				WHERE pu.IDUSER IS NOT NULL
				ORDER BY u.NOM, u.PRENOM ASC";
		$listUser = $promoUser->getAdapter()->fetchAll($listUserSQL);
		if ($listUser) {
			$this->view->listUser = $listUser;
		}

		$isDateInsc = $promoUser->fetchRow('isDATEINSCR = 0');
		if ($isDateInsc) {
			$this->view->dateInsc = $isDateInsc;
		}
		$isFirstCmd = $promoUser->fetchRow('isFIRSTCMD = 0');
		if ($isFirstCmd) {
			$this->view->firstCmd = $isFirstCmd;
		}

		$listUserBrendSQL = "
		SELECT u.NOM NOM,u.ID IDUSER, u.PRENOM PRENOM, 
				pu.ID ID, pu.REMISEEURO REMISEEURO, pu.REMISEPOUR REMISEPOUR, pu.USERIDBREND USERIDBREND, pu.USERBRENDID USERBRENDID, sb.BREND BREND, sb.IDSUPPLIER IDSUPPLIER
				FROM promo_user AS pu
				LEFT JOIN user AS u ON u.ID = pu.USERIDBREND
				LEFT JOIN supplier_brend AS sb ON sb.ID = pu.USERBRENDID
				WHERE pu.USERIDBREND IS NOT NULL
				AND pu.USERBRENDID IS NOT NULL
				ORDER BY u.NOM, u.PRENOM ASC";
		$listUserBrend = $promoUser->getAdapter()->fetchAll($listUserBrendSQL);
		if ($listUserBrend) {
			$this->view->listUserBrend = $listUserBrend;
		}

		$listCinternBrendSQL = "
		SELECT pu.ID ID, pu.REMISEEURO REMISEEURO, pu.REMISEPOUR REMISEPOUR, uci.LABEL LABELINTERN, uci.CODE CODEINTERN,
			pu.CINTERNIDBREND CINTERNIDBREND, sb.BREND BREND, pu.CINTERNBRENDID CINTERNBRENDID, sb.IDSUPPLIER IDSUPPLIER
				FROM promo_user AS pu
				LEFT JOIN user_cintern AS uci ON uci.ID = pu.CINTERNIDBREND
				LEFT JOIN supplier_brend AS sb ON sb.ID = pu.CINTERNBRENDID
				WHERE pu.CINTERNIDBREND IS NOT NULL 
				AND pu.CINTERNBRENDID IS NOT NULL 
				ORDER BY uci.CODE,sb.BREND ASC";
		$listCinternBrend = $promoUser->getAdapter()->fetchAll($listCinternBrendSQL);
		if ($listCinternBrend) {
			$this->view->listCinternBrend = $listCinternBrend;
		}



	}
	function useraddAction() {
		if ($this->getRequest()->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			$promoUser = new PromoUser();

			$params = array();
			$params = $this->getRequest()->getPost();

			$remiseeuro = (int)$params['remiseeuro'];
			$remisepour = (int)$params['remisepour'];
			$isOK = true;
			if ($remiseeuro > 0 && $remisepour > 0) {
				$this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE. ";
				$isOK = false;
			}
			if ($remiseeuro == 0 && $remisepour == 0) {
				$this->view->messageError = "La remise est soit en EURO, soit en POURCENTAGE et est obligatoire. ";
				$isOK = false;
			}
			if (($validator->isValid($remiseeuro) ||
			$validator->isValid($remisepour)) && $isOK == true
			) {
				switch ($params['remise']) {
					case 1 :
						$isExistAnnif = $promoUser->fetchRow("isDATEINSCR IS NOT NULL");
						if ($isExistAnnif) {
							$date = new Zend_Date();

							$data = array (
	 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
	 		 						'isDATEINSCR' => '0',
									'REMISEEURO' => $filter->filter($params['remiseeuro']),
							 		'REMISEPOUR' => $filter->filter($params['remisepour'])
							);
							$promoUser->update($data,'ID = '.$isExistAnnif['ID']);

							$this->view->messageSuccess = "Tout les clients ont maintenant une remise selon leurs dates d'inscription";

						} else {
							$date = new Zend_Date();

							$data = array (
	 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
	 		 						'isDATEINSCR' => '0',
									'REMISEEURO' => $filter->filter($params['remiseeuro']),
							 		'REMISEPOUR' => $filter->filter($params['remisepour'])
							);
							$promoUser->insert($data);
							$this->view->messageSuccess = "Tout les clients ont maintenant une remise selon leurs dates d'inscription";

						}

						break;
					case 2 :
						$isExistFirst = $promoUser->fetchRow("isFIRSTCMD IS NOT NULL");
						if ($isExistFirst) {
							$date = new Zend_Date();

							$data = array (
	 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
	 		 						'isFIRSTCMD' => '0',
									'REMISEEURO' => $filter->filter($params['remiseeuro']),
							 		'REMISEPOUR' => $filter->filter($params['remisepour'])
							);
							$promoUser->update($data,'ID = '.$isExistFirst['ID']);

							$this->view->messageSuccess = "Tout les clients ont maintenant une remise si c'est la premi�re commande";

						} else {
							$date = new Zend_Date();

							$data = array (
	 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
	 		 						'isFIRSTCMD' => '0',
									'REMISEEURO' => $filter->filter($params['remiseeuro']),
							 		'REMISEPOUR' => $filter->filter($params['remisepour'])
							);
							$promoUser->insert($data);
							$this->view->messageSuccess = "Tout les clients ont maintenant une remise si c'est la premi�re commande";

						}

						break;
					case 3 :
						$iduser = (int)$params['iduser'];
						if ($iduser > 0) {
							$isExistUser = $promoUser->fetchRow("IDUSER IS NOT NULL AND IDUSER = ".$iduser);
							if ($isExistUser) {
								$date = new Zend_Date();

								$data = array (
		 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
		 		 						'IDUSER' => (int)$params['iduser'],
										'REMISEEURO' => $filter->filter($params['remiseeuro']),
								 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoUser->update($data,'ID = '.$isExistUser['ID']);

								$this->view->messageSuccess = "Le client � maintenant une remise sur sa prochaine commande";

							} else {
								$date = new Zend_Date();

								$data = array (
		 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
		 		 						'IDUSER' => (int)$params['iduser'],
										'REMISEEURO' => $filter->filter($params['remiseeuro']),
								 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoUser->insert($data);
								$this->view->messageSuccess = "Le client � maintenant une remise sur sa prochaine commande";

							}
						} else {
							$this->view->messageError = "S�lectionner un utilisateur";

						}
						break;

					case 4 :
						$iduser = (int)$params['iduser'];
						$idbrend = (int)$params['idbrend'];
						if ($iduser > 0 && $idbrend > 0) {
							$isExistUserBrend = $promoUser->fetchRow("USERIDBREND IS NOT NULL AND USERIDBREND = ".$iduser." AND USERBRENDID IS NOT NULL AND USERBRENDID = ".$idbrend);
							if ($isExistUserBrend) {
								$date = new Zend_Date();

								$data = array (
		 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
		 		 						'USERIDBREND' => $iduser,
		 		 						'USERBRENDID' => $idbrend,
										'REMISEEURO' => $filter->filter($params['remiseeuro']),
								 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoUser->update($data,'ID = '.$isExistUserBrend['ID']);

								$this->view->messageSuccess = "Le client � maintenant une remise sur les produits de la marque";

							} else {
								$date = new Zend_Date();

								$data = array (
		 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
		 		 						'USERIDBREND' => $iduser,
		 		 						'USERBRENDID' => $idbrend,
										'REMISEEURO' => $filter->filter($params['remiseeuro']),
								 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoUser->insert($data);
								$this->view->messageSuccess = "Le client � maintenant une remise sur les produits de la marque";

							}
						} else {
							$this->view->messageError = "S�lectionner un client et une marque";

						}
						break;

					case 5 :
						$idcintern = (int)$params['idcintern'];
						$idbrend = (int)$params['idbrend'];
						if ($idcintern > 0 && $idbrend > 0) {
							$isExistCinternBrend = $promoUser->fetchRow("CINTERNIDBREND IS NOT NULL AND CINTERNIDBREND = ".$idcintern." AND CINTERNBRENDID IS NOT NULL AND CINTERNBRENDID = ".$idbrend);
							if ($isExistCinternBrend) {
								$date = new Zend_Date();

								$data = array (
		 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
		 		 						'CINTERNIDBREND' => $idcintern,
		 		 						'CINTERNBRENDID' => $idbrend,
										'REMISEEURO' => $filter->filter($params['remiseeuro']),
								 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoUser->update($data,'ID = '.$isExistCinternBrend['ID']);

								$this->view->messageSuccess = "Le code interne a maintenant une remise sur les produits de la marque";

							} else {
								$date = new Zend_Date();

								$data = array (
		 		 						'DATEINSERTREMISE' => $date->toString('YYYY-MM-dd HH-mm-ss'),
		 		 						'CINTERNIDBREND' => $idcintern,
		 		 						'CINTERNBRENDID' => $idbrend,
										'REMISEEURO' => $filter->filter($params['remiseeuro']),
								 		'REMISEPOUR' => $filter->filter($params['remisepour'])
								);
								$promoUser->insert($data);
								$this->view->messageSuccess = "Le code interne � maintenant une remise sur les produits de la marque";

							}
						} else {
							$this->view->messageError = "S�lectionner un code interne et une marque";

						}
						break;
					default:
						$this->_forward('user');
						break;

				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('user');
	}
	function userdelAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$promoUser = new PromoUser();
				$promoUser->delete('ID = '.$id);
				$this->view->messageSuccess = "La remise a �t� supprim�e ";
			} else {
				$this->view->messageError = "La remise n'a pas �t� supprim�e ";

			}
		}
		$this->_forward('user');
	}
	function giftAction() {
		$this->view->titlePage = "Les Avantages";
		$promoGift = new PromoGift();

		$listProductGiftSQL = "
		SELECT pg.PRODREFBUY PRODREFBUY, pg.PRODREFGIFT PRODREFGIFT,pg.ID ID,
				pg.PRODNBBUY PRODNBBUY,pg.PRODNBGIFT PRODNBGIFT 
				 FROM promo_gift AS pg
				WHERE pg.PRODREFBUY IS NOT NULL 
				AND pg.PRODREFGIFT IS NOT NULL
				ORDER BY pg.PRODREFBUY, pg.PRODREFGIFT ASC";
		$listProductGift = $promoGift->getAdapter()->fetchAll($listProductGiftSQL);
		$this->view->listProductGift = $listProductGift;

		$listCmdGiftSQL = "
		SELECT pg.CMDMONTANT CMDMONTANT, pg.CMDPRODREFGIFT CMDPRODREFGIFT,pg.ID ID, pc.IDPRODUCT
				 FROM promo_gift AS pg
				 LEFT JOIN productchild AS pc ON pc.REFERENCE = pg.CMDPRODREFGIFT
				WHERE pg.CMDMONTANT IS NOT NULL 
				AND pg.CMDPRODREFGIFT IS NOT NULL
				ORDER BY pg.CMDPRODREFGIFT ASC";
		$listCmdGift = $promoGift->getAdapter()->fetchAll($listCmdGiftSQL);
		$this->view->listCmdGift = $listCmdGift;
	}

	function giftaddAction() {
		if ($this->getRequest()->isPost()) {
			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			$params = $this->getRequest()->getPost();
			$promoGift = new PromoGift();
			$productChild = new ProductChild();

			switch ($params['gift']) {
				case 1 :
					$buy = $filter->filter($params['referencebuy']);
					$nbbuy = $filter->filter((int)$params['referencenbbuy']);
					$gift = $filter->filter($params['referencegift']);
					$nbgift = $filter->filter((int)$params['referencenbgift']);
					if ($validator->isValid($buy) &&
					$validator->isValid($gift) && 
					((int)$nbbuy>0) && 
					((int)$nbgift>0) ) {
						$isExistBuy = $productChild->fetchRow("REFERENCE = '".$buy."' ");

						if ($isExistBuy) {
							$isExistGift = $productChild->fetchRow("REFERENCE = '".$gift."' ");
							if ($isExistGift) {
								$isExistPromo = $promoGift->fetchRow("PRODREFBUY = '".$buy."' AND PRODREFGIFT = '".$gift."'");
								if (!$isExistPromo) {
									$date = new Zend_Date();
									$data = array (
			 		 						'DATEINSERTGIFT' => $date->toString('YYYY-MM-dd HH-mm-ss'),
			 		 						'PRODREFBUY' => $buy,
											'PRODREFGIFT' => $gift,
											'PRODNBGIFT' => $nbgift,
											'PRODNBBUY' => $nbbuy
									);

									$promoGift->insert($data);
									$this->view->messageSuccess = "L'avantage est maintenant disponible";
								} else {
									$this->view->messageError = "L'avantage existe d�j�";
								}
							} else {
								$this->view->messageError = "La r�f�rence ".$params['referencegift']." n'existe pas";
							}
						} else {
							$this->view->messageError = "La r�f�rence ".$params['referencebuy']." n'existe pas";
						}

					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
					}
					break;
				case 2 :
					$reference = $filter->filter($params['reference']);
					if ($validator->isValid($params['montant']) &&
					$validator->isValid($reference)) {
						if ((int)$params['montant'] > 0) {
							$isExistGift = $productChild->fetchRow("REFERENCE = '".$reference."' ");

							if ($isExistGift) {
								$isExistPromo = $promoGift->fetchRow("CMDMONTANT = '".$params['montant']."' AND CMDPRODREFGIFT = '".$reference."'");
								if (!$isExistPromo) {
									$date = new Zend_Date();
									$data = array (
			 		 						'DATEINSERTGIFT' => $date->toString('YYYY-MM-dd HH-mm-ss'),
			 		 						'CMDMONTANT' => $filter->filter($params['montant']),
											'CMDPRODREFGIFT' => $reference
									);

									$promoGift->insert($data);
									$this->view->messageSuccess = "L'avantage est maintenant disponible";
								} else {
									$this->view->messageError = "L'avantage existe d�j�";
								}
							} else {
								$this->view->messageError = "La r�f�rence ".$reference." n'existe pas";
							}
						} else {
							$this->view->messageError = "Le montant doit etre > 0";
						}
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
					}
					break;

			}
		}
		$this->_forward('gift');
	}

	function giftdelAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$promoGift = new PromoGift();
				$promoGift->delete('ID = '.$id);
				$this->view->messageSuccess = "L'avantage a �t� supprim�e ";
			} else {
				$this->view->messageError = "L'avantage n'a pas �t� supprim�e ";

			}
		}
		$this->_forward('gift');
	}
	
	function codereductionAction(){
		$this->view->titlePage = "Les Codes de r�duction";
		$codeReduction = new CodeReduction();
		$listCodes = $codeReduction->getAllCodes();
		$this->view->listReduc = $listCodes;
	}
	
	private function passgen() {
		$chaine ="mnoTUzS5678kVvwxy9WXYZRNCDEFrslq41GtuaHIJKpOPQA23LcdefghiBMbj0";
		srand((double)microtime()*1000000);
		for($i=0; $i<8; $i++){
			@$pass .= $chaine[rand()%strlen($chaine)];
		}
		return $pass;
	}
	
	function addcodereductionproduitAction(){
		if ($this->getRequest()->isPost()) {
			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$params = array();
			$params = $this->getRequest()->getPost();
			
			$codereduc_euro = $params['codereduc_euro'];
			$codereduc_pour = (int)$params['codereduc_pour'];
			$isOK = true;
			if ($codereduc_euro > 0 && $codereduc_pour > 0) {
				$this->view->messageError = "La r�duction est soit en EURO, soit en POURCENTAGE. ";
				$isOK = false;
			}
			if ($codereduc_euro == 0 && $codereduc_pour == 0) {
				$this->view->messageError = "La r�duction est soit en EURO, soit en POURCENTAGE et est obligatoire. ";
				$isOK = false;
			}
			
			$codereduc_ref = $params['codereduc_ref'];
			$codereduc_nbr = (int)$params['codereduc_nbr'];
			$sd = $params['sd2'];
			$ed = $params['ed2'];
			
			if (($validator->isValid($codereduc_euro) ||
			$validator->isValid($codereduc_pour)) && 
			$isOK == true &&
			$validator->isValid($codereduc_ref) && 
			$validator->isValid($codereduc_nbr) 
			) {
				$validator2 = new Zend_Validate();
				$validator2->addValidator(new Zend_Validate_Date());

				if ($validator2->isValid($sd) &&
				$validator2->isValid($ed)
				) {
					$code = $this->passgen();
					$labelProd = "produit";
					$labelDroit = "donne";
					if ($codereduc_nbr > 1) { $labelProd .= "s"; $labelDroit .= "nt"; }
					$labelPrix = "";
					if ($codereduc_pour > 0) { $labelPrix = $codereduc_pour. " %";
					} else { $labelPrix = $codereduc_euro. " euros"; }
					$libelle = $codereduc_nbr." ".$labelProd." de la r�ference : ".$codereduc_ref." ".$labelDroit." droit � ".$labelPrix." de r�duction. ";
					
					$codeReduction = new CodeReduction();
					$data = array(
						"CODE" => $code,
						"LIBELLE" => $libelle,
						"PRODUITREF" => $codereduc_ref,
						"PRODUITNBR" => $codereduc_nbr,
						"EURO" => $codereduc_euro,
						"POUR" => $codereduc_pour,
						"DATESTART" => $sd,
						"DATEEND" => $ed,
						"isACTIF" => 1
					);
					$codeReduction->insert($data);
					$this->view->messageSuccess = "CODE : ".$code." : ".$libelle;
				} else {
					foreach ($validator->getErrors() as $errorCode) {
						$this->view->messageError .=  $this->getErrorValidator($errorCode);
					}
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('codereduction');
	}
	
	function addcodereductioncommandeAction(){
		if ($this->getRequest()->isPost()) {
			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$params = array();
			$params = $this->getRequest()->getPost();
			
			$codereduc_euro = $params['codereduc_euro'];
			$codereduc_pour = (int)$params['codereduc_pour'];
			$isOK = true;
			if ($codereduc_euro > 0 && $codereduc_pour > 0) {
				$this->view->messageError = "La r�duction est soit en EURO, soit en POURCENTAGE. ";
				$isOK = false;
			}
			if ($codereduc_euro == 0 && $codereduc_pour == 0) {
				$this->view->messageError = "La r�duction est soit en EURO, soit en POURCENTAGE et est obligatoire. ";
				$isOK = false;
			}
			
			$codereduc_cmdmin = $params['codereduc_cmdmin'];
			$sd = $params['sd1'];
			$ed = $params['ed1'];
			
		if (($validator->isValid($codereduc_euro) ||
			$validator->isValid($codereduc_pour)) && 
			$isOK == true &&
			$validator->isValid($codereduc_cmdmin) 
			) {
				$validator2 = new Zend_Validate();
				$validator2->addValidator(new Zend_Validate_Date());

				if ($validator2->isValid($sd) &&
				$validator2->isValid($ed)
				) {
					if ($codereduc_cmdmin > 0) {
						
						$code = $this->passgen();
						$labelPrix = "";
						if ($codereduc_pour > 0) { $labelPrix = $codereduc_pour. " %";
						} else { $labelPrix = $codereduc_euro. " euros"; }
						$libelle = "Pour ".$codereduc_cmdmin." euros de commande, il y a ".$labelPrix." de r�duction. ";
					
						$codeReduction = new CodeReduction();
						$data = array(
							"CODE" => $code,
							"LIBELLE" => $libelle,
							"CMDTOTAL" => $codereduc_cmdmin,
							"EURO" => $codereduc_euro,
							"POUR" => $codereduc_pour,
							"DATESTART" => $sd,
							"DATEEND" => $ed,
							"isACTIF" => 1
						);
						$codeReduction->insert($data);
						$this->view->messageSuccess = "CODE : ".$code."<br/> ".$libelle;
					}
				} else {
					foreach ($validator->getErrors() as $errorCode) {
						$this->view->messageError .=  $this->getErrorValidator($errorCode);
					}
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('codereduction');
	}
	
	
	function delcodereductionAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$codeReduction = new CodeReduction();
				$codeReduction->delete('ID = '.$id);
				$this->view->messageSuccess = "Le code de r�duction a �t� supprim�e ";
			} else {
				$this->view->messageError = "Le code de r�duction n'a pas �t� supprim�e ";

			}
		}
		$this->_forward('codereduction');
	}

	function activecodereductionAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$codeReduction = new CodeReduction();
				$data = array(
					"isACTIF" => 1
				);
				$codeReduction->update($data,'ID = '.$id);
				$this->view->messageSuccess = "Le code de r�duction est actif ";
			} 
		}
		$this->_forward('codereduction');
	}

	function unactivecodereductionAction() {
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id > 0 ) {
				$codeReduction = new CodeReduction();
				$data = array(
					"isACTIF" => 0
				);
				$codeReduction->update($data,'ID = '.$id);
				$this->view->messageSuccess = "Le code de r�duction est inactif ";
			}
		}
		$this->_forward('codereduction');
	}
}
?>AnnonceleftController.php000060400000012117150713030120011543 0ustar00<?php
class Backoffice_AnnonceleftController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "AnnonceLeft";
		$this->isConnectedWithRole('isPromo');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une Annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		$annonce = new AnnonceLeft();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonceLeft = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow'],
					'ID_CATS' => ''
					);
					
					if (isset($params['categories'])) {
						foreach($params['categories'] as $value)
						{
							$dataAnnonce['ID_CATS'] .= ":".$value.":";
						}
					}
					if ($validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT'])&&
					!empty($dataAnnonce['ID_CATS'])
					) {
						try {
							$id = (int)$params['id'];
							if ( $id > 0) {
									
								$annonce->update($dataAnnonce,'ID = '.$id);
								$this->view->messageSuccess = "La publicit� a �t� modifi�e";
								$this->view->populateFormAnnonceLeft = $annonce->fetchRow('ID = '.$id);
								$this->log("La publicit� a �t� modifi�e ".$id,'info');
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceLeft = $dataAnnonce;
						}
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceLeft = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}


	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une Annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow'],
					'ID_CATS' => ''
					);
					
					if (isset($params['categories'])) {
						foreach($params['categories'] as $value)
						{
							$dataAnnonce['ID_CATS'] .= ":".$value.":";
						}
					}
					
					if (
					$validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT']) &&
					!empty($dataAnnonce['ID_CATS'])
					) {
						try {
							$annonce = new AnnonceLeft();
							$annonce->insert($dataAnnonce);
							$this->view->messageSuccess = "La publicit� a �t� ajout�e";
							$this->log("La publicit� a �t� ajout�e",'info');
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonceLeft = $dataAnnonce;
						}

					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonceLeft = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des publicit�s par cat�gories"; 
			
		//Appel model pour listing
		$annonces = new AnnonceLeft();
		$result = $annonces->getAllAnnonces();

		$category = new Category();
		$this->view->listallcategories = $category->getAllCategoriesByID(0);
		
		$this->view->listannonceleft = $result;
	}



	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceLeft();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "La publicit� a �t� supprim�e";

					$this->log("La publicit� a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}

}
?>PrestashopController.php000060400000065162150713030120011447 0ustar00<?php
class Backoffice_PrestashopController extends Modules_Backoffice_Controllers_MainController {
	function init() {
		$this->view->title = "Administration";
		$this->view->currentMenu = "Prestashop";
		$this->isConnectedWithRole ( 'isMaintenance' );
	}
	public function indexAction() {
			$this->view->titlePage = "Gestion commerciale Prestashop";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
	}
	private $_SEPARATOR = ';';
	private function cleanUp($value) {
		$result = $value;
		$filter = new Zend_Filter ();
		$filter->addFilter ( new Zend_Filter_StringTrim () )->addFilter ( new Zend_Filter_StripTags () );
		$result = $filter->filter ( $result );
		$result = html_entity_decode ( $result, ENT_QUOTES, "ISO-8859-1" );
		$result = str_replace ( "\r\n", "", $result );
		$result = str_replace ( '�', " ", $result );  
		$result = str_replace ( '"', '\"', $result );  
		$result = str_replace ( $this->_SEPARATOR, "", $result );
		return !empty($result) ? '"'.$result.'"' : "";
	}
	private function cleanUpSpace($value) {
		$filter = new Zend_Filter ();
		$filter->addFilter ( new Zend_Filter_Alnum () );
		$value = str_replace ( $this->_SEPARATOR, "", $value );
		return $filter->filter ( $value );
	}
	private function cleanUpAddQuote($value) {
		return '"' . $this->cleanUp ( $value ) . '"';
	}
	function exportclientsAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			$user = new User ();
			$select = $user->select ()->order ( "ID ASC" );
			$listusers = $user->fetchAll ( $select );
			
			foreach ( $listusers as $row ) {
				$result = $row ['ID'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Code Famille
				                              // Facturation
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['ADRESSE'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Adresse 2
				$result .= $this->_SEPARATOR; // Adresse 3
				$result .= $this->_SEPARATOR; // Adresse 4
				$result .= $this->cleanUpSpace ( $row ['CP'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['VILLE'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['DEPARTEMENT'] ) . $this->_SEPARATOR;
				$result .= "FR" . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Site Web
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['PRENOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['FONCTION'] ) . $this->_SEPARATOR;
				$result .= $row ['TEL'] . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Tel Portable
				$result .= $row ['FAX'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['EMAIL'] ) . $this->_SEPARATOR;
				// Livraison
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['ADRESSE'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Adresse 2
				$result .= $this->_SEPARATOR; // Adresse 3
				$result .= $this->_SEPARATOR; // Adresse 4
				$result .= $this->cleanUpSpace ( $row ['CP'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['VILLE'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['DEPARTEMENT'] ) . $this->_SEPARATOR;
				$result .= "FR" . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Site Web
				                              // Contact
				$result .= $row ['CIVILITE'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['PRENOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['FONCTION'] ) . $this->_SEPARATOR;
				$result .= $row ['TEL'] . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Tel Portable
				$result .= $row ['FAX'] . $this->_SEPARATOR;
				$result .= $this->cleanUp ( $row ['EMAIL'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Compte comptable
				$result .= $this->cleanUpSpace ( $row ['NUMIDFISC'] ) . $this->_SEPARATOR;
				$result .= $this->cleanUpSpace ( $row ['SIRET'] ) . $this->_SEPARATOR;
				$result .= $this->_SEPARATOR; // Code NAF
				$result .= "0";
				
				$fichier->Insertion ( $result );
			}
			$fichier->output ( 'ebp_clients' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	} 
	function exportfournisseursAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : Prestashop";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			$supplier = new Supplier ();
			$select = $supplier->select ()->order ( "ID ASC" );
			$listsuppliers = $supplier->fetchAll ( $select );
			
			$supplierBrend = new SupplierBrend ();
			
		    $result = "ID" . $this->_SEPARATOR;
		    $result .= "Active (0/1)" . $this->_SEPARATOR;
		    $result .= "Name *".$this->_SEPARATOR; 
		    $result .= "Description".$this->_SEPARATOR;  
		    $result .= "Short description".$this->_SEPARATOR;
		    $result .= "Meta title".$this->_SEPARATOR;  
		    $result .= "Meta keywords".$this->_SEPARATOR; 
		    $result .= "Meta description".$this->_SEPARATOR; 
		    $result .= "Image URL";  
			$fichier->Insertion ($result);
			
			foreach ( $listsuppliers as $row ) {
				
				$listbrends = $supplierBrend->select()->where ( "IDSUPPLIER = " . $row ['ID'] )->query ()->fetchAll ();
				
				foreach ( $listbrends as $rowBrend ) { 
					$result = $rowBrend['ID'].$this->_SEPARATOR;
					$result .= '1'. $this->_SEPARATOR;
					$result .= $this->cleanUp ( $rowBrend ['BREND'] ) . $this->_SEPARATOR;
					$result .= '"'.str_replace ( '"', '\"',$row ['DESCRIPTIONLONG'] ).'"'.$this->_SEPARATOR;   
					$result .= $this->cleanUp ( $row ['DESCRIPTIONSHORT'] ).$this->_SEPARATOR;   
					$result .=  $this->cleanUp ( $rowBrend ['BREND']." - Achat / Vente produits ".$rowBrend ['BREND']." pour professionnel").$this->_SEPARATOR;   
					$result .= $this->cleanUp ( $rowBrend ['BREND'].", ".$row ['COMPANY']).$this->_SEPARATOR;   
					$result .= $this->cleanUp ( $row ['DESCRIPTIONSHORT'] ).$this->_SEPARATOR;   
					$result .=$this->baseUrl_SiteCommerceUrl."/".$rowBrend ['URL'];   
					
					$fichier->Insertion ( $result );
				}
			}
			$fichier->output ( 'presta_fabricants' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	function exportcategoriesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : Prestashop";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
            //Prestashop 
            $result = "ID". $this->_SEPARATOR;
			$result .= "Active (0/1)" . $this->_SEPARATOR;
			$result .= "Name *". $this->_SEPARATOR;
			$result .= "Parent category".$this->_SEPARATOR;
			$result .= "Root category (0/1)".$this->_SEPARATOR;
			$result .= "Description".$this->_SEPARATOR;
			$result .= "Meta title". $this->_SEPARATOR;
			$result .=  "Meta keywords". $this->_SEPARATOR;
			$result .= "Meta description". $this->_SEPARATOR; 
			$result .= "URL rewritten".$this->_SEPARATOR;
			$result .= "Image URL";
				
			$fichier = new FichierExcel ();
            
			$fichier->Insertion ( $result );
            
			$category = new Category ();
             $sql = "SELECT c.*  FROM category AS c  where idparent = 0 order by ID asc";   
	        $listcategories =$category->getAdapter ()->fetchAll($sql);
            
            $this->exportcategoriescsvline($fichier, $listcategories, "Accueil");
			
			$fichier->output ( 'presta_categories' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
    private function exportcategoriescsvline($fichier, $listcategories, $parentName) {
    
			$category = new Category ();
        foreach ( $listcategories as $row ) {
            $isroot =  '0';
                
            $id = "";//$row ['ID'];
			$result = $id. $this->_SEPARATOR;
			$result .= $row ['isACTIVE'] . $this->_SEPARATOR;
			$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
			$result .= $parentName .$this->_SEPARATOR;
			$result .= $isroot.$this->_SEPARATOR;
            $name = !empty($row['DESCRIPTIONLONG']) ? $row ['DESCRIPTIONLONG'] : $row ['DESCRIPTION'];
                 
			$result .= '"'.str_replace ( '"', '\"',$name).'"'.$this->_SEPARATOR;
			$result .= $this->cleanUp ( $row ['NAVTITRENOM'] ). $this->_SEPARATOR; 
			$result .=  '"'.str_replace ( '"', '\"',substr($row ['KEYWORDS'], 0, 255)).'"'. $this->_SEPARATOR; 
			$result .=  '"'.str_replace ( '"', '\"',substr($row ['NAVDESCRIPTION'], 0, 255)).'"'. $this->_SEPARATOR; 
			$result .= $this->_SEPARATOR;
			$result .= $this->baseUrl_SiteCommerceUrl."/".$row ['URL'];
				
			$fichier->Insertion ( $result );
            
             $sql = "SELECT c.*  FROM category AS c  where idparent = ".$row ['ID']." order by NOM asc";   
	        $listcategoriesubs =$category->getAdapter ()->fetchAll($sql);
            if (!empty($listcategoriesubs)) {
                $this->exportcategoriescsvline($fichier, $listcategoriesubs, $this->cleanUp ( $row ['NOM'] ));
            }
		}
    }
    
	private function getUrlPage($params) {
		return $this->baseUrl_SiteCommerceUrl . "/" . $params ['PAGE'] . "-" . $params ['ID'] . ".html";
	}
	function exportarticlesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : Prestashop";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$fichier = new FichierExcel ();
			
			$sql = "SELECT p.ID ID, p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.DESCRIPTIONLONG DESCLONG, p.PRIX PRIX, p.isDEVIS isDEVISPRODUCT,
					p.DOCNAME DOCNAME, p.DOCURL DOCURL, p.IDBREND IDBREND,
					p.isPROMO isPROMO, pic.URL URLIMAGE, sb.BREND BREND, sb.URL BRENDURL, p.IDCATEGORY IDCATEGORY, c.NOM CATEGORYNOM,
					p.DESCRIPTIONTECH DESCTECH, p.DESCRIPTIONNORME DESCNORME
					FROM product p
					LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID
					LEFT JOIN supplier_brend sb ON sb.ID = p.IDBREND
					LEFT JOIN category AS c ON c.ID = p.IDCATEGORY
					WHERE p.isACTIVE = 0
					AND pic.POSITION = 1
					GROUP BY ID
					ORDER BY p.ID ASC";
			
			$product = new Product ();
			$productChild = new ProductChild ();
			$listProducts = $product->getAdapter ()->fetchAll ( $sql );
			
			foreach ( $listProducts as $row ) {
				$sqlChild = "
						SELECT pc.ID ID ,pc.REFERENCE REFERENCE,pc.DESIGNATION DESIGNATION,pc.PRIX PRIX, pc.isPROMO isPROMO ,
						pc.IMAGEPROMO IMAGEPROMO,pc.isDEVIS isDEVIS, pc.QUANTITYMIN QUANTITYMIN
							FROM productchild AS pc
						WHERE pc.IDPRODUCT = " . $row ['ID'] . "
						ORDER BY pc.PRIX ASC";
				
				$productChildTemp = $productChild->getAdapter ()->fetchAll ( $sqlChild );
				
				$navnom = $this->verifyNavigationString ( $row ['NAVNOM'], $row ['NOM'], '' );
				
				$urlImage = $this->baseUrl_SiteCommerceUrl . "/" . $row ['URLIMAGE'];
				$urlPage = $this->getUrlPage ( array (
						'PAGE' => $navnom,
						'ID' => $row ['ID'] 
				) );
				
				$fraislivraison = "";
				$garantie = "";
				
				$reference = "";
				$description = "";
				foreach ( $productChildTemp as $rowChild ) {
					$reference = $this->cleanUp ( $rowChild ['REFERENCE'] );
					
					$description = $this->cleanUp ( $rowChild ['DESIGNATION'] );
					
					$result = $rowChild ['ID'] . $this->_SEPARATOR;
					$result .= $this->cleanUp ( $row ['NOM'] ) . $this->_SEPARATOR;
					$result .= $row ['IDCATEGORY'] . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Prix de revient
					$result .= $rowChild ['PRIX'] . $this->_SEPARATOR;
					$result .= $this->tva . $this->_SEPARATOR;
					$result .= $description . $this->_SEPARATOR;
					$result .= $reference . $this->_SEPARATOR; // Code barre
					$result .= $this->_SEPARATOR; // Code unite
					$result .= $this->_SEPARATOR; // Type d'article
					$result .= $this->_SEPARATOR; // Code emplacement
					$result .= $row ['IDBREND'] . $this->_SEPARATOR;
					$result .= $this->_SEPARATOR; // Code �co
					
					$fichier->Insertion ( $result );
				}
			}
			
			$fichier->output ( 'ebp_articles' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	private function formatDate($datevalue) {
		$date = new Zend_Date ();
		$date->set ( $datevalue );
		return $date->toString ( 'dd/MM/YYYY' );
	}
	private function getCommandDevisLine($listcommands) {
		$commandLine = new CommandProduct ();
		$fichier = new FichierExcel ();
		$result = "Document - Num�ro du document;Document - Date;Document - Code client;Document - Nom du client;Document - Adresse 1 (facturation);Document - Code postal (facturation);Document - Ville (facturation);Document - Code Pays (facturation);Document - Nom (contact) (facturation);Document - Pr�nom (facturation);Document - T�l�phone fixe (facturation);Document - Fax (facturation);Document - E-mail (facturation);Document - Nom (adresse) (livraison);Document - Adresse 1 (livraison);Document - Code postal (livraison);Document - Ville (livraison);Document - Code Pays (livraison);Document - T�l�phone fixe (livraison);Document - Fax (livraison);Document - E-mail (livraison);Document - Frais de port HT;Document - Total Brut HT;Document - Total TTC;Document - Taux de TVA port;Ligne - Code article;Ligne - Quantit�;Ligne - Taux de TVA;Ligne - PV HT;Ligne - Montant Net HT;Ligne - Montant de remise unitaire HT cumul�";
		$fichier->Colonne ( $result );
		foreach ( $listcommands as $row ) {
			$result = '"' . $row ['REFERENCE'] . '"' . $this->_SEPARATOR;
			$result .= '"' . $this->formatDate ( $row ['DATESTART'] ) . '"' . $this->_SEPARATOR;
			$result .= '"' . $row ['IDUSER'] . '"' . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_NOM'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['FACT_ADRESSE'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['FACT_CP'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['FACT_VILLE'] ) . $this->_SEPARATOR;
			$result .= "FR" . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_NOM'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_PRENOM'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_TEL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_FAX'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_EMAIL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_RAISONSOCIAL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_ADRESSE'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_CP'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['LIV_VILLE'] ) . $this->_SEPARATOR;
			$result .= "FR" . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_TEL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_FAX'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['USER_EMAIL'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['PRIXFRAISPORT'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['PRIXTOTALHTFP'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $row ['PRIXTOTALTTC'] ) . $this->_SEPARATOR;
			$result .= $this->cleanUpAddQuote ( $this->getCurrentTva ( $row ['DATESTART'] ) ) . $this->_SEPARATOR;
			
			$selectLine = $commandLine->select ()->where ( "IDCOMMAND = " . $row ["ID"] );
			$listLines = $commandLine->fetchAll ( $selectLine );
			foreach ( $listLines as $rowLine ) {
				$resultLine = $result;
				
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDID'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDQUANTITY'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $this->getCurrentTva ( $row ['DATESTART'] ) ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDPRIX'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDPRIXTOTAL'] ) . $this->_SEPARATOR;
				$resultLine .= $this->cleanUpAddQuote ( $rowLine ['CHILDPRIXREMISE'] ) . $this->_SEPARATOR;
				
				$fichier->Insertion ( $resultLine );
			}
		}
		return $fichier;
	}
	function exportcommandesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$command = new Command ();
			
			$date = new Zend_Date ();
			$date->addMonth ( - 3 );
			$select = "
				SELECT *
				FROM command
				WHERE isARCHIVE = 1
				AND STATUT IN (1, 2, 3)
				AND DATESTART >= '" . $date->toString ( 'YYYY-MM-dd' ) . "'";
			
			$listcommands = $command->getAdapter ()->fetchAll ( $select );
			
			$fichier = $this->getCommandDevisLine ( $listcommands );
			
			$fichier->output ( 'ebp_commandes' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	function exportdevisAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$command = new Command ();
			
			$date = new Zend_Date ();
			$date->addMonth ( - 3 );
			$select = "
				SELECT *
				FROM command
				WHERE isARCHIVE = 1
				AND STATUT IN (10, 11)
				AND DATESTART >= '" . $date->toString ( 'YYYY-MM-dd' ) . "'";
			
			$listcommands = $command->getAdapter ()->fetchAll ( $select );
			
			$fichier = $this->getCommandDevisLine ( $listcommands );
			
			$fichier->output ( 'ebp_devis' );
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
	}
	function importcategoriesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$nomTemp = 'csvfile';
			
			if ($this->isValidCSVFile ( $nomTemp )) {
				$nomOrigine = $_FILES [$nomTemp] ['name'];
				
				$date = new Zend_Date ();
				$nomDestination = "importcategories-" . $date->toString ( 'dd-MM-YYYY_HH-mm-ss' ) . ".csv";
				
				if ($this->uploadCsvFile ( $_FILES [$nomTemp] ["tmp_name"], $nomDestination )) {
					
					$header = array (
							0 => 'ID',
							1 => 'NOM',
							2 => 'NOUSE1',
							3 => 'NOUSE2',
							4 => 'NOUSE3',
							5 => 'NOUSE4',
							6 => 'NOUSE5',
							7 => 'NOUSE6' 
					);
					$dataRows = $this->csv_to_array ( $this->csv_import . $nomDestination, $header );
					if (sizeof ( $dataRows [0] ) == sizeof ( $header )) {
						
						$category = new Category ();
						$filesAdded = 0;
						$filesUpdated = 0;
						$filesError = 0;
						foreach ( $dataRows as $row ) {
							
							$id = $row ["ID"];
							$nom = $this->cleanUp ( $row ["NOM"] );
							
							$currentCat = $category->select ()->where ( "ID = ?", $id )->query ()->fetch ();
							
							if ($currentCat != null && ! empty ( $currentCat )) {
								try {
									// Update
									if ($currentCat ['NOM'] != $nom) {
										$data = array (
												'NOM' => $nom 
										);
										$category->update ( $data, 'ID = ' . $id );
										$filesUpdated ++;
									}
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							} else {
								try {
									$navnom = $this->verifyNavigationString ( "", $nom, '' );
									$keywords = $this->generateKeyWords ( $navnom );
									// Insert
									$data = array (
											'NOM' => $nom,
											'NAVTITRENOM' => $nom,
											'DESCRIPTION' => $nom,
											'NAVDESCRIPTION' => $nom,
											'NAVNOM' => $navnom,
											'KEYWORDS' => $keywords,
											'IDPARENT' => 0 
									);
									$category->insert ( $data );
									
									$lastid = $category->getAdapter()->lastInsertId();
									if ($lastid > 0) {
										mkdir ("items/category/".$lastid, 0777);
										mkdir ("items/product/".$lastid, 0777);
									}
									
									$filesAdded ++;
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							}
						}
						$this->view->messageSuccess = "Importation des fiches Familles articles<br/>
														Fiches ajout�es : " . $filesAdded . "<br/>
														Fiches modifi�es : " . $filesUpdated . "<br/>
														Fiches non import�es : " . $filesError . "<br/>";
					} else {
						$this->view->messageError = "Le fichier n'est pas au format attendu pour les Familles articles";
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas pu etre import�.";
				}
			}
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
		$this->render ( '/index' );
	}
	function importarticlesAction() {
		try {
			$this->_helper->viewRenderer->setNeverRender ();
			
			$this->view->titlePage = "Gestion commerciale : EBP";
			$this->view->messageSuccess = "";
			$this->view->messageError = "";
			
			$nomTemp = 'csvfile';
			
			if ($this->isValidCSVFile ( $nomTemp )) {
				$nomOrigine = $_FILES [$nomTemp] ['name'];
				
				$date = new Zend_Date ();
				$nomDestination = "importarticles-" . $date->toString ( 'dd-MM-YYYY_HH-mm-ss' ) . ".csv";
				
				if ($this->uploadCsvFile ( $_FILES [$nomTemp] ["tmp_name"], $nomDestination )) {
					
					$header = array (
							0 => 'ID',
							1 => 'NOM',
							2 => 'IDCATEGORY',
							3 => 'NOUSE1',
							4 => 'PRIX',
							5 => 'TVA',
							6 => 'DESCRIPTION',
							7 => 'REFERENCE',
							8 => 'NOUSE2',
							9 => 'NOUSE3',
							10 => 'NOUSE4',
							11 => 'IDBREND',
							12 => 'NOUSE5' 
					);
					
					$dataRows = $this->csv_to_array ( $this->csv_import . $nomDestination, $header );
					if (sizeof ( $dataRows [0] ) == sizeof ( $header )) {
						
						$product = new Product ();
						$productLine = new ProductChild ();
						$filesAdded = 0;
						$filesUpdated = 0;
						$filesError = 0;
						
						$date = new Zend_Date ();
						foreach ( $dataRows as $row ) {
							
							$id = $row ["ID"];
							$prix = $this->cleanUp ( $row ["PRIX"] );
							$description = $this->cleanUp ( $row ["DESCRIPTION"] );
							$reference = $this->cleanUp ( $row ["REFERENCE"] );
							
							$tva = $this->cleanUp ( $row ["TVA"] );
							$nom_prod = $this->cleanUp ( $row ["NOM"] );
							$idCat_prod = $this->cleanUp ( $row ["IDCATEGORY"] );
							$idbrend_prod = $this->cleanUp ( $row ["IDBREND"] );
							
							$currentProdLine = $productLine->select ()->where ( "REFERENCE = ?", $reference )->query ()->fetch ();
							
							if ($currentProdLine != null && ! empty ( $currentProdLine )) {
								try {
									
									// Update
									$dataChild = array (
											'DESIGNATION' => $description,
											'PRIX' => $prix,
											'DATEMODIF' => $date->toString ( 'YYYY-MM-dd HH:mm:ss' ) 
									);
									
									$productChild = new ProductChild ();
									$productChild->update ( $dataChild, 'ID = ' . $id );
									$filesUpdated ++;
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							} else {
								try {
									// Insert
									$navnom = $this->verifyNavigationString ( "", $nom_prod, '' );
									$keywords = $this->generateKeyWords ( $navnom );
									
									$data = array (
											'NOM' => $nom_prod,
											'NAVNOM' => $navnom,
											'KEYWORDS' => $keywords,
											'NAVTITRE' => '',
											'NAVDESC' => '',
											'DESCRIPTIONSHORT' => $nom_prod,
											'DESCRIPTIONLONG' => $nom_prod,
											'PRIX' => $prix,
											'isACTIVE' => 1,
											'DATEPROMO' => $date->toString ( 'YYYY-MM-dd' ),
											'isPROMO' => '1',
											'IDCATEGORY' => $idCat_prod,
											'ISSHOWBREND' => 1 
									);
									$product->insert ( $data );
									$lastId = $product->getAdapter ()->lastInsertId ();
									
									$dataChild = array (
											'REFERENCE' => $reference,
											'DESIGNATION' => $description,
											'PRIX' => $prix,
											'ETATSTOCK' => 0,
											'QUANTITYMIN' => 1,
											'isDEVIS' => 1,
											'IMAGEPROMO' => 0,
											'DATEMODIF' => $date->toString ( 'YYYY-MM-dd HH:mm:ss' ),
											'IDPRODUCT' => $lastId 
									);
									
									$productChild = new ProductChild ();
									$productChild->insert ( $dataChild );
									
									$filesAdded ++;
								} catch ( Zend_Exception $e ) {
									$filesError ++;
									$this->log ( $e->getMessage (), 'warn' );
								}
							}
						}
						$this->view->messageSuccess = "Importation des fiches Articles<br/>
														Fiches ajout�es : " . $filesAdded . "<br/>
														Fiches modifi�es : " . $filesUpdated . "<br/>
														Fiches non import�es : " . $filesError . "<br/>";
					} else {
						$this->view->messageError = "Le fichier n'est pas au format attendu pour les Articles";
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas pu etre import�.";
				}
			}
		} catch ( Zend_Exception $e ) {
			$this->log ( $e->getMessage (), 'err' );
		}
		$this->render ( '/index' );
	}
	var $csv_import = 'csvfiles/import/';
	private function uploadCsvFile($tmpName, $destName) {
		if (! file_exists ( $this->csv_import )) {
			mkdir ( $this->csv_import, 0777, true );
		}
		return move_uploaded_file ( $tmpName, $this->csv_import . $destName );
	}
	private function isValidCSVFile($name) {
		if (! empty ( $_FILES [$name] ) && ! empty ( $_FILES [$name] ['name'] )) {
			$nomOrigine = $_FILES [$name] ['name'];
			$elementsChemin = pathinfo ( $nomOrigine );
			$extensionFichier = strtolower($elementsChemin ['extension']);
			$extensionsAutorisees = array (
					"csv" 
			);
			if (! (in_array ( $extensionFichier, $extensionsAutorisees ))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue (.csv)";
			} else {
				return true;
			}
		} else {
			$this->view->messageError = "Vous pouvez exporter les donn�es via EBP -> Outils -> Exportation de donn�es";
		}
		return false;
	}
	private function csv_to_array($filename = '', $header, $delimiter = ';') {
		if (! file_exists ( $filename ) || ! is_readable ( $filename ))
			return FALSE;
		
		$data = array ();
		if (($handle = fopen ( $filename, 'r' )) !== FALSE) {
			while ( ($row = fgetcsv ( $handle, 1000, $delimiter )) !== FALSE ) {
				if (! $header) {
					$header = $row;
				} else if (sizeof ( $header ) == sizeof ( $row )) {
					$data [] = array_combine ( $header, $row );
				}
			}
			fclose ( $handle );
		}
		return $data;
	}
}
?>FooterController.php000060400000015050150713030120010544 0ustar00<?php
class Backoffice_FooterController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Footer";
		$this->isConnectedWithRole('isFooter'); 
	}
	public function indexAction()
	{
		$this->_forward('/list');

	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier un pied de page";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty());

		$footer = new FooterContent();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormFooter = $footer->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataFooter = array (
			 		'ID' => (int)$params['id'],
			 		'TITRE' => $filter->filter($params['titre']),
			 		'URL' => $filter->filter($params['url']),
			 		'CONTENT' => $params['content']
			);

			if ($validator->isValid($dataFooter['TITRE'])
			) {
				if ((empty($dataFooter['URL']) && empty($dataFooter['CONTENT'])) ||
				(!empty($dataFooter['URL']) && !empty($dataFooter['CONTENT']))
				) {
					$this->view->messageError = "Le pied de page est soit un lien vers une autre page, soit du contenu";

					$this->view->populateFormFooter = $dataFooter;
				} else {
					try {
							
						$id = (int)$params['id'];
							
						if ( $id > 0) {

							$footer->update($dataFooter,'ID = '.$id);
							$this->view->messageSuccess = "Le pied de page a �t� modifi�";
							$this->view->populateFormFooter = $footer->fetchRow('ID = '.$id);

							$this->log("Le pied de page a �t� modifi� : ".$id,'info');
						}
					} catch (Zend_Exception $e) {
						$this->log($e->getMessage(),'err');
						$this->view->populateFormFooter = $dataFooter;
					}
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormFooter = $dataFooter;
			}

		}

			
			
	}

	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter un pied de page";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataFooter = array (
			 		'TITRE' => $filter->filter($params['titre']),
			 		'URL' => $filter->filter($params['url']),
			 		'CONTENT' => $params['content']
			);
			if (
			$validator->isValid($dataFooter['TITRE'])
			) {
					
				if ((empty($dataFooter['URL']) && empty($dataFooter['CONTENT'])) ||
				(!empty($dataFooter['URL']) && !empty($dataFooter['CONTENT']))
				) {
					$this->view->messageError = "Le pied de page est soit un lien vers une autre page, soit du contenu";

					$this->view->populateFormFooter = $dataFooter;
				} else {
					try {
						$footer = new FooterContent();
						$footer->insert($dataFooter);
						$this->view->messageSuccess = "Le pied de page a �t� ajout�";
						$this->log("Le pied de page a �t� ajout�",'info');
					} catch (Zend_Exception $e) {
						$this->log($e->getMessage(),'err');
						$this->view->populateFormFooter = $dataFooter;
					}
				}
					
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
				$this->view->populateFormFooter = $dataFooter;
			}

		}
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des pieds de page"; 
		//Appel model pour listing
		$footer = new FooterContent();

		$result = $footer->fetchAll();
			
		$this->view->listfooter = $result;
			
	}

	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$footer = new FooterContent();

					$footer->delete('ID = '.$id);
					$this->view->messageSuccess = "Le pied de page a �t� supprim�";
					$this->log("Le pied de page a �t� supprim�",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');

	}
	
	public function docAction() { 
		$this->view->titlePage = "Gestion des documents"; 
		$this->view->currentMenu = "Document";
	}

	public function adddocAction() { 
		if(!empty($_FILES['file']) && !empty($_FILES['file']['name'])) {
			$nomOrigine = $_FILES['file']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("pdf");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else { 
				$repertoireDestination = 'doc/';
				$this->checkDirectoryExist($repertoireDestination);
				//$date = new Zend_Date();
					
				$nomDestination = $nomOrigine;//$date->toString('dd-MM-YYYY_HH-mm-ss').".".$extensionFichier;
					 
				if (move_uploaded_file($_FILES["file"]["tmp_name"],$repertoireDestination.$nomDestination)) {
					try {
						$this->view->messageSuccess = "Le document a �t� ajout� ";
					} catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		} else {
			$this->view->messageError = "S�lectionner un fichier PDF";
		}
		$this->_forward('doc');
	}
	public function deldocAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				unlink($params['doc']);
				$this->view->messageSuccess = "Le document a �t� supprim� d�finitivement";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('doc');
	}

}
?>AnnoncerightController.php000060400000012257150713030120011733 0ustar00<?php
class Backoffice_AnnoncerightController extends Modules_Backoffice_Controllers_MainController
{

	public function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "AnnonceRight";
		$this->isConnectedWithRole('isPromo');
	}
	public function indexAction()
	{
		$this->_forward('/list');
	}

	public function editAction()
	{
			
		$this->view->titlePage = "Modifier une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		
        try {
		//filtres pour changer les chaines
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());

		//valideurs pour les chaines
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty())
		-> addValidator(new Zend_Validate_StringLength(3));

		$annonce = new AnnonceRight();
		if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
			if ($id>0) {
				$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
			}
		}
		if ($this->getRequest()->isPost()) {

			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'ID' => (int)$params['id'],
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow'],
			 		'POSITION' => $params['position'],
					'ID_CATS' => ''
					);
					
					/*if (isset($params['categories'])) {
						foreach($params['categories'] as $value)
						{
							$dataAnnonce['ID_CATS'] .= ":".$value.":";
						}
					}*/
					if ($validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT'])
					) {
						try {
							$id = (int)$params['id'];
							if ( $id > 0) {
									
								$annonce->update($dataAnnonce,'ID = '.$id);
								$this->view->messageSuccess = "L'annonce a �t� modifi�e";
								$this->view->populateFormAnnonce = $annonce->fetchRow('ID = '.$id);
								$this->log("L'annonce a �t� modifi�e ".$id,'info');
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonce = $dataAnnonce;
						}
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonce = $dataAnnonce;
					}

		}
        } catch (Zend_Exception $e) {
			$this->log("Error edit : ".$e->getMessage(),'err');
		}
		$this->_forward('/list');
	}


	public function addAction()
	{
			
		$this->view->titlePage = "Ajouter une annonce";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(3));


			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$dataAnnonce = array (
			 		'NOM' => $filter->filter($params['nom']),
			 		'CONTENT' => $params['content'],
			 		'isSHOW' => $params['isshow'],
			 		'POSITION' => $params['position'],
					'ID_CATS' => ''
					);
					/*
					if (isset($params['categories'])) {
						foreach($params['categories'] as $value)
						{
							$dataAnnonce['ID_CATS'] .= ":".$value.":";
						}
					}*/
					
					if (
					$validator->isValid($dataAnnonce['NOM']) &&
					$validator->isValid($dataAnnonce['CONTENT'])
					) {
						try {
							$annonce = new AnnonceRight();
							$annonce->insert($dataAnnonce);
							$this->view->messageSuccess = "L'annonce a �t� ajout�e";
							$this->log("L'annonce a �t� ajout�e",'info');
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->populateFormAnnonce = $dataAnnonce;
						}

					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError .=  $this->getErrorValidator($errorCode);
						}
						$this->view->populateFormAnnonce = $dataAnnonce;
					}

		}
		$this->_forward('/list');
	}

	public function listAction()
	{
		$this->view->titlePage = "Gestion des mises en avant sur la page d'accueil"; 
			
		//Appel model pour listing
		$annonces = new AnnonceRight();
		$result = $annonces->getAllAnnonces();

		/*$category = new Category();
		$this->view->listallcategories = $category->getAllCategoriesByID(0);
		*/
		$this->view->listannonce = $result;
	}



	public function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$annonce = new AnnonceRight();

					$annonce->delete('ID = '.$id);
					$this->view->messageSuccess = "L'annonce a �t� supprim�e";

					$this->log("L'annonce a �t� supprim�e",'info');
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = $e->getMessage();
				}
			}
		}
		$this->_forward('/list');
	}

}
?>CategoryController.php000060400000063640150713030120011073 0ustar00<?php

class Backoffice_CategoryController extends Modules_Backoffice_Controllers_MainController
{

	function init()
	{
		$this->view->title = "Administration";
		$this->view->currentMenu = "Category";

		$this->isConnectedWithRole('isCategory'); 
	}
	function indexAction()
	{
		$this->_forward('/list');

	}
    
	function listAction()
	{
		$this->view->titlePage = "Gestion des cat�gories";
			
		//Gestion des tris
		$table = 'NOM';
		$tri = 'ASC';
	}

	function delAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if($this->_request->getParam('id')) {
			$id = (int)$this->_request->getParam('id');
			if ($id > 0) {
				try {
					$category = new Category();
					if ($category->fetchRow('IDPARENT = '.$id)) {
						$this->view->messageError = 'Cette cat�gorie est parente';
					} else {
						$product = new Product();
						$select = $product->fetchRow('IDCATEGORY = '.$id);
						if ($select) {
							$this->view->messageError = 'Cette cat�gorie est utilis�e par le produit : <b>'.$select->NOM."<b/>";
						} else {

							$category->delete('ID = '.$id);

							$this->delete_directory('items/category/'.$id);
							$this->delete_directory('items/product/'.$id);

							$this->view->messageSuccess = "La cat�gorie a et� supprim�e";
							$this->log("La cat�gorie a et� supprim�e",'info');

						}
					}
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/list');

	}

	function editAction() {
		$this->view->titlePage = "Modifier une cat�gorie";
		//populate form
		if ($this->_request->getParam('id')) { $id = (int)$this->_request->getParam('id'); }
		if ($this->_request->getParam('idCat')) { $id = (int)$this->_request->getParam('idCat'); }

		if ($id > 0) {
			$category = new Category();
			$row = $category->fetchRow('ID = '.$id);
			if ($row) {
				$this->view->populateForm = $row->toArray();
 
				$listCat = array();
				$listCat = $category->getTreeCatsOf($id);
				if (!empty($listCat) && !$listCat['SUBS']) {
					$categoryTypeTri = new CategoryTypeTri();
					$this->view->listNavigationTri = $categoryTypeTri->getListTriByCategoryInOneRow($id);
				}

                
		        if ($this->isSiteGallery) {
		            $annonces = new AnnonceCms();
		            $this->view->listAnnoncecms = $annonces->getAllAnnoncesByCategory($id);
                     
		            $annonces = new AnnonceGallery();
		            $this->view->listAnnonceGallery = $annonces->getAllAnnoncesByCategory($id);

		        }

			} else { $this->_forward('/list'); }
		} else {
			$this->_forward('/list');
		}
	}

	function editmigrateAction()
	{ 
		$this->view->titlePage = "Modifier une cat�gorie";
        if ($this->_request->isPost()) {
            //get the form params
			$params = $this->_request->getPost();
             
			try {

				$id = (int)$params['id'];
				$idReceiver = (int)$params['idcategory'];
                    
                if ($id > 0 && $idReceiver > 0) { 
                    $category = new Category();  
                    if ($category->canBeMigrate($id)) { 
                            //Migration des produits
                            $dataProduct = array (
			 		            'IDCATEGORY' => $idReceiver
			                ); 
                            $product = new Product();  
				            $product->update($dataProduct, 'IDCATEGORY = '.$id);
                            
                            $dataCategory = array (
			 		            'isACTIVE' => false
			                ); 
				            $category->update($dataCategory, 'ID = '.$id);
                            
				            $this->view->messageSuccess .= "La cat�gorie a �t� migr�e, la redirection est effectu�e";
                    
				            $this->log("La cat�gorie a �t� migr�e de ".$id." vers ".$idReceiver,'info'); 
                    } else {
					    $this->view->messageError .= "La cat�gorie est parente";
                    }

                } else {                    
					$this->view->messageError .= "V�rifier les param�tres";
                }
 
			} catch (Zend_Exception $e) {
				$this->log($e->getMessage(),'err');
				$this->view->messageError = "Impossible de migrer la cat�gorie".$e->getMessage();
			} 
        }
		$this->_forward('/edit');
	}
    
	function editcategoryAction()
	{
			
		$this->view->titlePage = "Modifier une cat�gorie";
		$id = 0;
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());


			//get the form params
			$params = $this->_request->getPost();

			$docChoice = '';
			if (isset($params['docChoice'])) {
				$docChoice = $filter->filter($params['docChoice']);
			}
			
			$urlRedirect = '';
			if (isset($params['urlredirect'])) {
				$urlRedirect = $filter->filter($params['urlredirect']);
			}
			//Refractor the params
			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
					'IDPARENT' => $filter->filter($params['idparent']),
			 		'DESCRIPTION' => $params['desc'], 
			 		'DESCRIPTIONLONG' => $params['desclong'], 
			 		'DESCRIPTIONSHORT' => $params['descshort'], 
			 		'URLREDIRECT' => $urlRedirect, 
			 		'CHOICEDOC' => $docChoice
			);
             
			if (isset($params['position'])) {
				$data['POSITION'] = (int)$params['position'];
			}



			if ($validator->isValid($data['NOM'])) {

				try {

					$id = $params['id'];

					$category = new Category();
					$category->update($data, 'ID = '.$id);

					$this->view->messageSuccess = "La cat�gorie a �t� modifi�e";
					if($this->uploadNewPicsAndSave($id)) {
						$this->view->messageSuccess .= " , l'image aussi";
					}
					if($this->uploadNewPicsSlideAndSave($id)) {
						$this->view->messageSuccess .= " , l'image du slide aussi";
					}

					if($this->uploadNewChoicePics($id)) {
						$this->view->messageSuccess .= " , le comment choisir aussi";
					}
                    
                    $nbSubs = $category->updateTreeInLineAsPathOfChilds($id, true);

					$this->view->messageSuccess .= " , ".$nbSubs." urls d'acc�s modifi�es.";

					$this->log("La cat�gorie a �t� modifi�e : ".$id,'info');

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La cat�gorie existe d�j�";
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError =  $this->getErrorValidator($errorCode);
				}
			}

		}
		$this->_forward('/edit');
	}

	function customnavnomeditAction()
	{
		$this->view->titlePage = "Modifier une cat�gorie";
		$id = 0;
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$navnom = $this->verifyNavigationString($filter->filter($params['navnom']), $params['nom'], '');
            
			$keywords = "";
			if (isset($params['keywords']) && !empty($params['keywords'])) {
				$keywords = $params['keywords'];
			} else {
				$navnomStrip =  explode("-", $navnom);
				for ($index = 0; $index < sizeof($navnomStrip); $index++) {
					$word = $navnomStrip[$index];
					if (empty($keywords)) {
						if (strlen($word) > 3){ $keywords .= $word; }
					} else {
						if (strlen($word) > 3){ $keywords .= ",".$word; }
					}
				}
			}

			//Refractor the params
			$data = array (
					'NAVTITRENOM' => $filter->filter($params['navtitrenom']),
			 		'NAVNOM' => $navnom,
					'KEYWORDS' => $keywords,
					'NAVDESCRIPTION' => $filter->filter($params['navdescription'])
			);
            
			if ($validator->isValid($data['NAVNOM']) &&
			$validator->isValid($data['KEYWORDS'])) {
				if (empty($data['NAVTITRENOM'])) {
					$data['NAVTITRENOM'] = $filter->filter($params['nom']);
				}
				if (empty($data['NAVDESCRIPTION'])) {
					$data['NAVDESCRIPTION'] = "";
				}
				try {
					$id = $params['id'];

                    $category = new Category();
                    
                    if (isset($params['urlaccess']) && $params['idparent'] == 0) {
                        $data['NAVNOM_URLPARENTS'] = $this->verifyNavigationString('',$filter->filter($params['urlaccess']), '');
                    }
                    
                    if (empty($data['NAVNOM_URLPARENTS'])) {
                        $data['NAVNOM_URLPARENTS'] = $category->getTreeInLineAsPathOf($id);
                        if (empty($data['NAVNOM_URLPARENTS'])) {
                            $data['NAVNOM_URLPARENTS'] = $navnom;
                        }
                    }
                    
					$category->update($data, 'ID = '.$id);
                    
                    $nbSubs = $category->updateTreeInLineAsPathOfChilds($id, false);

					$this->view->messageSuccess = "La cat�gorie a �t� modifi�e, ".$nbSubs." urls d'acc�s modifi�es.";

				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
					$this->view->messageError = "La cat�gorie existe d�j�";
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
			}

		}
		$this->_forward('/edit');
	}
    
	function editthemeAction()
	{
		$this->view->titlePage = "Modifier le th�me";
		if ($this->_request->isPost()) {
			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$data = array (
			 		'ID_THEME' => $params['idtheme']
			);

			try {

				$id = (int)$params['id'];

				$category = new Category();
				$category->update($data, 'ID = '.$id);
                 $this->view->messageSuccess = "Le th�me a �t� modifi�"; 
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
			}
		}
		$this->_forward('/edit');
	}
	function editactiveAction()
	{
		$this->view->titlePage = "Modifier une cat�gorie";
		if ($this->_request->isPost()) {
			//get the form params
			$params = $this->_request->getPost();

			//Refractor the params
			$data = array (
			 		'isACTIVE' => $params['active']
			);

			try {

				$id = (int)$params['id'];

				$category = new Category();
				$category->update($data, 'ID = '.$id);

				//inversement des bool
				if ($data['isACTIVE'] == 1) {
					$data['isACTIVE'] = 0;
				} else {
					$data['isACTIVE'] = 1;
				}
				$dataProduct = array(
						'isACTIVE' => $data['isACTIVE']
				);
				$produit = new Product();
				$nb = $produit->updateByCategory($id, $dataProduct);
				$this->view->messageSuccess = "La cat�gorie a �t� modifi�e";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
			}
		}
		$this->_forward('/edit');
	}

	function addAction()
	{
			
		$this->view->titlePage = "Ajouter une cat�gorie";
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
			
		if ($this->_request->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			//get the form params
			$params = $this->_request->getPost();

			$navnom = $this->verifyNavigationString($filter->filter($params['navnom']), $params['nom'], '');

			$keywords = "";
			if (isset($params['keywords']) && !empty($params['keywords'])) {
				$keywords = $params['keywords'];
			} else {

				$navnomStrip =  explode("-", $navnom);
				for ($index = 0; $index < sizeof($navnomStrip); $index++) {
					$word = $navnomStrip[$index];
					if (empty($keywords)) {
						if (strlen($word) > 3){ $keywords .= $word; }
					} else {
						if (strlen($word) > 3){ $keywords .= ",".$word; }
					}
				}
			}

			$data = array (
			 		'NOM' => $filter->filter($params['nom']),
					'NAVTITRENOM' => $filter->filter($params['nom']),
			 		'DESCRIPTION' => $filter->filter($params['desc']),
			 		'NAVDESCRIPTION' => $filter->filter($params['desc']),
			 		'NAVNOM' => $navnom,
			 		'KEYWORDS' => $keywords,
			 		'IDPARENT' => $filter->filter($params['idparent'])
			);
             
			if ($validator->isValid($data['NOM']) &&
			$validator->isValid($data['NAVNOM'])
			) {
				try {
					$category = new Category();
                    $data['NAVNOM_URLPARENTS'] = $category->getTreeInLineAsPathOf($data['IDPARENT']);                    
                    if (empty($data['NAVNOM_URLPARENTS'])) {
                        $data['NAVNOM_URLPARENTS'] = $navnom;
                    }
					$category->insert($data);

					//create items folder for pics
					$lastid = $category->getAdapter()->lastInsertId();

					if ($lastid > 0) { 
                        $this->checkDirectoryExist("items/category/".$lastid);
                        $this->checkDirectoryExist("items/product/".$lastid);

						$this->view->messageSuccess = "La cat�gorie a �t� ajout�e";
						if($this->uploadNewPicsAndSave($lastid)) {
							$this->view->messageSuccess .= " , l'image a �t� upload�e";
						}

						$this->log("La cat�gorie a �t� ajout�e",'info');
						//Listing Categories
						$category = new Category();
						$this->view->listallcategories = $category->getAllCategoriesByID(0);
                        
                        $this->_request->setParam('id', $lastid);
		                $this->_forward('/edit'); 

					}
				} catch (Zend_Exception $e) {
					$this->view->messageError = "La cat�gorie existe d�j�";
					$this->log($e->getMessage(),'err');
					$this->view->populateForm = $data;
				}
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageError .=  $this->getErrorValidator($errorCode);
				}
				$this->view->populateForm = $data;
			}
		}
	}
     
	function uploadNewPics($idCat, $field) {
        if(!empty($_FILES[$field]) && !empty($_FILES[$field]['name'])) {
			$nomOrigine = $_FILES[$field]['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				$repertoireDestination = 'items/category/'.$idCat.'/';
				$this->checkDirectoryExist($repertoireDestination);
				
                $nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
				$fileoriginal = $repertoireDestination.$nomDestination;
                
				if (move_uploaded_file($_FILES[$field]["tmp_name"],$fileoriginal)) {
                        //Resize picture
                        $info = getimagesize($fileoriginal) ;
                        list($width_old, $height_old) = $info;
                        $maxwidth = $this->FeaturePictureResizeWidth;
                        $maxheight = $this->FeaturePictureResizeHeight;
                            
                        if ($width_old > $maxwidth || $height_old > $maxheight) {     
                            Utils_Tool::smart_resize_image($fileoriginal , null, $maxwidth , $maxheight , true , $fileoriginal , true , false ,50 );
                        }  
                        
					return $repertoireDestination.$nomDestination;
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		}
		return "";
    }
	function uploadNewPicsAndSave($idCat) {
        $url = $this->uploadNewPics($idCat, 'picCat');
		if(!empty($url)) {
			try {
				$category = new Category();
				$data = array (
					'URL' => $url
				);
				$category->update($data,'ID = '.$idCat);

				return true;
			} catch (Exception $e) {
				$this->view->messageError = $e->getMessage();
				return false;
			}
		}
		return false;
	}
	function uploadNewPicsSlideAndSave($idCat) {
        $url = $this->uploadNewPics($idCat, 'picSlideCat');
		if(!empty($url)) {
			try {
				$category = new Category();
				$data = array (
					'URL_SLIDE' => $url
				);
				$category->update($data,'ID = '.$idCat);

				return true;
			} catch (Exception $e) {
				$this->view->messageError = $e->getMessage();
				return false;
			}
		}
		return false;
	}

	function uploadNewChoicePics($idCat) {
		if(!empty($_FILES['picChoice']) && !empty($_FILES['picChoice']['name'])) {
			$nomOrigine = $_FILES['picChoice']['name'];
			$elementsChemin = pathinfo($nomOrigine);
			$extensionFichier = strtolower($elementsChemin['extension']);
			$extensionsAutorisees = array("jpg", "jpeg",  "gif", "png");
			if (!(in_array($extensionFichier, $extensionsAutorisees))) {
				$this->view->messageError = "Le fichier n'a pas l'extension attendue";
			} else {
				// Copie dans le repertoire du script avec un nom
				// incluant l'heure a la seconde pres
				$repertoireDestination = 'items/category_choice/'.$idCat.'/';
				$this->checkDirectoryExist($repertoireDestination);
				
				$date = new Zend_Date();
					
				//$nomDestination = $date->toString('dd-MM-YYYY_HH-mm-ss').".".$extensionFichier;
                $nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier;
					
				if (move_uploaded_file($_FILES["picChoice"]["tmp_name"],$repertoireDestination.$nomDestination)) {
					try {
						$category = new Category();
						$data = array (
					 		'CHOICEURL' => $repertoireDestination.$nomDestination
						);
						$category->update($data,'ID = '.$idCat);

						return true;
					} catch (Exception $e) {
						$this->view->messageError = $e->getMessage();
						return false;
					}
				} else {
					$this->view->messageError = "Le fichier n'a pas �t� upload�";
				}
			}
		}

		return false;
	}
	function setpictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$category = new Category();
                if (isset($params['typeimage']) && $params['typeimage'] == 1) {
				    $data = array (
				 		    'URL_SLIDE' => $params['picture']
				    );
                } else {
				    $data = array (
				 		    'URL' => $params['picture']
				    );
                }
				$category->update($data,'ID = '.$params['idCat']);
				$this->view->messageSuccess = "L'image a �t� modifi�e";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}

	function erasepictureAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();

			try {
				$category = new Category();

				unlink($params['picture']);
				$data = array (
			 		'URL' => ''
			 		);
			 		$category->update($data,"ID = ".$params['idCat']." AND URL = '".$params['picture']."'");
			 		$this->view->messageSuccess = "L'image a �t� supprim�e d�finitivement";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}


	function setpicturechoiceAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			try {
				$category = new Category();
				$data = array (
				 	'CHOICEURL' => $params['picture']
				);
				$category->update($data,'ID = '.$params['idCat']);
				$this->view->messageSuccess = "L'image a �t� modifi�e";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}

	function erasepicturechoiceAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";

		if($this->_request->isPost()) {
			$params = $this->_request->getPost();

			try {
				$category = new Category();
				unlink($params['picture']);
				$data = array (
			 		'CHOICEURL' => ''
			 		);
			 		$category->update($data,"ID = ".$params['idCat']." AND CHOICEURL = '".$params['picture']."'");
			 		$this->view->messageSuccess = "L'image a �t� supprim�e d�finitivement";
			} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				$this->view->messageError = $e->getMessage();
			}
		}
		$this->_forward('/edit');

	}
	
	
	function deletegalleryAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if($this->_request->getParam('id') && $this->_request->getParam('idgallery')) {
			$id = (int)$this->_request->getParam('id');
			$idgallery = (int)$this->_request->getParam('idgallery');
			if ($id > 0 && $idgallery > 0) {
				try {
					
					$annonce = new AnnonceGallery();
					$dataAnnonceCurrent = $annonce->fetchRow('ID = '.$idgallery);
					
					$dataAnnonce = array ( 
						'ID_CATS' => str_replace(":".$id.":", "", $dataAnnonceCurrent['ID_CATS'])
					);
				 
					$annonce->update($dataAnnonce,'ID = '.$idgallery); 
			 		$this->view->messageSuccess = "L'image a �t� supprim�e de la cat�gorie";
					$this->log("L'image ".$idgallery." a �t� supprim�e de la cat�gorie".$id,'info');
					
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/edit'); 
	}
	
	function deletecmsAction() {

		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		if($this->_request->getParam('id') && $this->_request->getParam('idarticle')) {
			$id = (int)$this->_request->getParam('id');
			$idarticle = (int)$this->_request->getParam('idarticle');
			if ($id > 0 && $idarticle > 0) {
				try {
					
					$annonce = new AnnonceCms();
					$dataAnnonceCurrent = $annonce->fetchRow('ID = '.$idarticle);
					
					$dataAnnonce = array ( 
						'ID_CATS' => str_replace(":".$id.":", "", $dataAnnonceCurrent['ID_CATS'])
					);
				 
			 		$annonce->update($dataAnnonce,'ID = '.$idarticle); 
			 		$this->view->messageSuccess = "L'article a �t� supprim� de la cat�gorie";
					$this->log("L'article ".$idarticle." a �t� supprim� de la cat�gorie".$id,'info');
					
				} catch (Zend_Exception $e) {
					$this->view->messageError = $e->getMessage();
					$this->log($e->getMessage(),'err');
				}
			}
		}
		$this->_forward('/edit');
	}
	
	
	function addmultiplegalleryAction() {
		$this->view->messageSuccess = "";
		$this->view->messageError = "";
		  
		if($this->_request->isPost()) {
			$params = $this->_request->getPost();
			  
			$id = (int)$this->_request->getParam('idCat');
			$annonce = new AnnonceGallery();
			
			 if ($id > 0) { 
				$dataAnnonce = array (
						'NOM' => "",
						'CONTENT' => "",
						'CONTENT_SHORT' => "",
						'CONTENT_LONG' => "",
						'POSITION' => 0,
						'isSHOW' => 0,
						'ID_CATS' => ":".$id.":"
				); 
				try { 
					$annonce->insert($dataAnnonce);
					$lastid = $annonce->getAdapter()->lastInsertId();                               
					$result = $this->uploadHandlerFileUpload($lastid); 
					
					if (isset($result['success']) && $result['success'] == true) {

						$this->log("L'image a �t� ajout�e ".$lastid ,'info'); 
						
					} else {
						 
						$annonce->delete('ID = '.$lastid);						
						$this->delete_directory('items/gallery/'.$lastid);
						$this->log("L'image a �t� ajout�e puis supprim�e : ".$result['error'],'err'); 
					}	
								 
					echo json_encode($result);  
					
				} catch (Zend_Exception $e) { 
					$this->log($e->getMessage(),'err');
				}
			} 
		}
		 
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout(); 
		$this->render('ajaxvalue'); 
	} 
	
	function uploadHandlerFileUpload($id) { 
		$uploader = new UploadHandler();
 
		$uploader->allowedExtensions = array("jpg", "jpeg",  "gif", "png"); 
		$uploader->sizeLimit = null; 
		$uploader->inputName = "qqfile";
		
		$repertoireGallery = 'items/gallery/';
		$_REQUEST['qquuid'] = $id; 
		
		$currentName = '';
		 if (isset($_REQUEST['qqfilename'])) {
			 $currentName = $_REQUEST['qqfilename'];
		} else if (isset($_FILES[$uploader->inputName])) {
            $currentName = $_FILES[$uploader->inputName]['name'];
		}
		 
		$elementsChemin = pathinfo($currentName);
		$extensionFichier = strtolower($elementsChemin['extension']); 
		$nomDestination = $this->generateNavigationString($elementsChemin['filename']).".".$extensionFichier; 
		 
		// If you want to use the chunking/resume feature, specify the folder to temporarily save parts.
		$this->checkDirectoryExist($repertoireGallery."chunks");
		$uploader->chunksFolder = $repertoireGallery."chunks";
  

		// Call handleUpload() with the name of the folder, relative to PHP's getcwd()
		$result = $uploader->handleUpload($repertoireGallery, $nomDestination);
 
		if (isset($result['success']) && $result['success'] == true) {
			$repertoireDestination = $repertoireGallery.$id."/";
			$fileoriginal = $repertoireDestination.$nomDestination;	 
			
			//Resize picture		
			 $fileResizedName = $repertoireDestination.$this->generateNavigationString($elementsChemin['filename']); 
							
			//Admin
			Utils_Tool::smart_resize_image($fileoriginal , null, 100 , null , true , $fileResizedName."_100.".$extensionFichier , false , false ,80 ); 
					
			if (isset($this->FeatureSiteThemeCms) && !empty($this->FeatureSiteThemeCms)) { 
				foreach ($this->FeatureSiteThemeCms as $row) { 
					if (isset($row['WIDTH_THUMB']) && $row['WIDTH_THUMB'] > 0) {
						Utils_Tool::smart_resize_image($fileoriginal , null, $row['WIDTH_THUMB'] , null , true , $fileResizedName."_".$row['WIDTH_THUMB'].".".$extensionFichier , false , false ,80 ); 
					}
				} 
			}
			
			//Save url
			$url = $repertoireDestination.$result["uploadName"];
			if(!empty($url)) {
				try { 
					$annonce = new AnnonceGallery();
					$data = array ( 'URL' => $url, 'NOM' => $elementsChemin['filename'] );
					$annonce->update($data,'ID = '.$id);  
				} catch (Exception $e) {
					$this->log($e->getMessage(),'err');
				}
			} 
		}

		return $result;
	}  
	
}
?>BlogController.php000060400000007636150713055030010213 0ustar00<?php

class BlogController  extends Modules_Default_Controllers_MainController
{

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}
    
	public function actualitesAction()
	{ 
		try {
            $blogCategory = new BlogCategory();
            $blogSubject = new BlogSubject(); 
            $id = 1;
            $this->view->type_name = "actualites"; 
            if ($this->getRequest()->getParam('id')) {
			    $id = (int)$this->getRequest()->getParam('id');  
		    } 

            $currentCategory = $blogCategory->fetchRow('ID = '.$id); 
            $this->view->currentCategory = $currentCategory; 
            $this->view->title = $currentCategory['title'];  
             
            $this->view->listSubjects = $blogSubject->AllSubjectsBy($id); 
            $this->view->listCategories = $blogCategory->getAllActivesCategories(1);  
        }
        catch (Zend_Exception $e) { 
			$this->view->messageError = $e->getMessage();
			$this->log($e->getMessage(),'err');
		}
	} 

    
	public function sujetAction()
	{ 
		try {
            $blogCategory = new BlogCategory();
            $blogSubject = new BlogSubject(); 
            $blogComment = new BlogComment(); 
            $id = 0; 
            if ($this->getRequest()->getParam('id')) {
			    $id = (int)$this->getRequest()->getParam('id');  
                
			    $added = (int)$this->getRequest()->getParam('a'); 
                if ($added == 1) {
                    $this->view->messageSuccess = "Le commentaire a �t� ajout�";
                } else if ($added == 2) {
                    $this->view->messageError = "Le commentaire n'a pas �t� ajout�";
                }
                
                $currentSubject = $blogSubject->fetchRow('ID = '.$id); 
			    $currentCategory = $blogCategory->fetchRow('ID = '.$currentSubject['id_category']); 
                $this->view->listSubjects = $blogSubject->AllSubjectsBy($currentSubject['id_category']); 
                $this->view->listComments = $blogComment->AllCommentsBy($id); 
                
                $this->view->listCategories = $blogCategory->getAllActivesCategories(1); 
                
                $this->view->currentCategory = $currentCategory; 
                $this->view->currentSubject = $currentSubject; 
                $this->view->title = $currentSubject['title'];  
		    }  
        }
        catch (Zend_Exception $e) { 
			$this->view->messageError = $e->getMessage();
			$this->log($e->getMessage(),'err');
		}
	}  
	public function addpostAction()
	{ 
		try {
		    if ($this->_request->isPost()) {
                $filter = new Zend_Filter();
			    $filter	->addFilter(new Zend_Filter_StripTags())
			    ->addFilter(new Zend_Filter_StringTrim());

			    $validator = new Zend_Validate();
			    $validator -> addValidator(new Zend_Validate_NotEmpty());

			    $params = array();
			    $params = $this->getRequest()->getPost();
			    $id = (int)$params['subject_id'];  
			    $pseudo = $filter->filter($params['pseudo']);
			    $message = $filter->filter($params['commentaire']);

                if ($validator->isValid($pseudo) && $validator->isValid($message) && $id > 0) {
                
                    $data = array (  
                                'id_subject' => $id,
                                'is_publish' =>  1,   
                                'pseudo' => $pseudo,
                                'message' => $message, 
                                'date_updated' => date('Y-m-d H:i:s') 
                    );

                    $blogComment = new BlogComment();
                    $blogComment->insert($data);
                    $this->_redirect('/blog/sujet/id/'.$id.'/a/1');
                }  else {
                    $this->_redirect('/blog/sujet/id/'.$id.'/a/2');
                }
            }
		} catch (Zend_Exception $e) { 
			$this->log($e->getMessage(),'err');
		}  
        $this->_redirect('/');
    }
}

?>CommandeController.php000060400000143440150713055030011045 0ustar00<?php

class CommandeController  extends Modules_Default_Controllers_MainController
{
	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}

	public function indexAction()
	{
		$this->_redirect('/mon-panier.html');
	}
	public function livraisonAction()
	{
		$this->view->title = 'Livraison';
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();

		if ($auth->hasIdentity() && isset($storage['user'])) {

			$usernamespace = $this->getSession();
			$myFacture = $usernamespace->myFactureValidate;

			if (isset($myFacture) && $myFacture->isFactureValid(1)) {

				$this->view->etapeCommande = 3;
				$this->view->linksMenu = $this->generateLinksMenu(3);

				$dataLiv = array();

				if (isset($usernamespace->addresseLiv) && !empty($usernamespace->addresseLiv)) {
					$dataLiv = $usernamespace->addresseLiv;
				} else {
					$raisonsocial = "";
					if ($storage['user']['type'] == "Professionnel") {
						$raisonsocial = $storage['user']['raisonsocial'];
					} else {
						$raisonsocial = $storage['user']['prenom']." ".$storage['user']['nom'];
					}
					$dataLiv = array('raisonsocial' => $raisonsocial,
                                  'adresse' => $storage['user']['adresse'], 
                                  'adressecomplete' => $storage['user']['adressecomplete'], 
                                  'cp' => $storage['user']['cp'], 
                                  'ville' => $storage['user']['ville'], 
                                  'pays' => $storage['user']['pays'],
                                  'type' => $storage['user']['type']);
					$usernamespace->addresseLiv = $dataLiv;
				}

				$this->view->adresseLiv = $dataLiv;
					
			} else {
				$this->_redirect('/mon-panier.html');
			}
		}  else {
			$this->_redirect('/mon-panier-connexion.html');
		}
	}
	public function ajaxlivraisonAction()
	{
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();

		if ($auth->hasIdentity() && isset($storage['user'])) {

			$usernamespace = $this->getSession();
			$myFacture = $usernamespace->myFactureValidate;
			if (isset($myFacture) && $myFacture->isFactureValid(1)) {
				if ($this->getRequest()->isPost()) {
					$filter = new Zend_Filter();
					$filter	->addFilter(new Zend_Filter_StripTags())
					->addFilter(new Zend_Filter_StringTrim())
					->addFilter(new Zend_Filter_HtmlEntities(ENT_COMPAT, 'UTF-8')); //for mootools

					$validator = new Zend_Validate();
					$validator -> addValidator(new Zend_Validate_NotEmpty());

					$livuser_raisonsocial = $filter->filter(strtoupper($this->getRequest()->getPost('livuser_raisonsocial')));

					$adresse_type = $this->getRequest()->getPost('address_type');
					if ($adresse_type == 'new') {
						$livuser_adresse = $filter->filter($this->getRequest()->getPost('livuser_adresse'));
						$livuser_cp = $filter->filter($this->getRequest()->getPost('livuser_cp'));
						$livuser_ville = $filter->filter($this->getRequest()->getPost('livuser_ville'));
						$livuser_pays = $filter->filter($this->getRequest()->getPost('livuser_pays'));
						$livuser_adressecomplete = $filter->filter($this->getRequest()->getPost('livuser_adressecomplete'));
					} else {
						$livuser_adresse = $filter->filter($this->getRequest()->getPost('livuser_adresse_old'));
						$livuser_cp = $filter->filter($this->getRequest()->getPost('livuser_cp_old'));
						$livuser_ville = $filter->filter($this->getRequest()->getPost('livuser_ville_old'));
						$livuser_pays = $filter->filter($this->getRequest()->getPost('livuser_pays_old'));
						$livuser_adressecomplete = $filter->filter($this->getRequest()->getPost('livuser_adresse_old'));
					}

					if ($validator->isValid($livuser_raisonsocial) &&
					$validator->isValid($livuser_adresse) &&
					$validator->isValid($livuser_ville) &&
					$validator->isValid($livuser_pays) &&
					$validator->isValid($livuser_cp)
					) {
						$dataLiv = array(
	                                  'raisonsocial' =>$livuser_raisonsocial, 
	                                  'adresse' => $livuser_adresse, 
									  'adressecomplete' => $livuser_adressecomplete,
	                                  'cp' => $livuser_cp, 
	                                  'ville' => $livuser_ville, 
	                                  'pays' => $livuser_pays, 
	                                  'type' => $storage['user']['type']);
							
						$usernamespace->addresseLiv = $dataLiv;
						$this->view->adresseLiv = $dataLiv;
						$this->view->messageSuccess = "Votre adresse a �t� modifi�e";
					} else {
						foreach ($validator->getErrors() as $errorCode) {
							$this->view->messageError =  $this->getErrorValidator($errorCode);
						}
					}
				}
			}
		}
		$this->_forward('ajaxlivraison','ajax');
	}

	public function connexionAction() {
		$this->view->title = 'Connexion';
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();

		if ($auth->hasIdentity() && isset($storage['user'])) {
			$this->_redirect('/mon-panier-livraison.html');
		} else {
			$this->view->linksMenu = $this->generateLinksMenu(2);
		}
	}

	public function ajaxconnexionAction() {
		if ($this->getRequest()->isPost()) {
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$login = $filter->filter($this->getRequest()->getPost('connexion_login'));
			$mdp = $filter->filter($this->getRequest()->getPost('connexion_mdp'));

			if ($validator->isValid($login) && $validator->isValid($mdp)) {
				$this->view->messageSuccess = $this->connectMe($login, $mdp);
			} else {
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
			}
		}
		$this->_forward('ajaxvalue','ajax');
	}

	public function ajaxenregistrementAction() {
		$isAdd = false;
		if ($this->getRequest()->isPost()) {

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());
			$filter2 = new Zend_Filter();
			$filter2->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_Digits());

			$filterMaj = new Zend_Filter();
			$filterMaj->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StringToUpper());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(4));

			$validatorTel = new Zend_Validate();
			$validatorTel -> addValidator(new Zend_Validate_NotEmpty())
			-> addValidator(new Zend_Validate_StringLength(10));

			$validator2 = new Zend_Validate();
			$validator2 -> addValidator(new Zend_Validate_NotEmpty());
 
			$validatorEmail = new Zend_Validate_EmailAddress();

			$adduser_login = $filter->filter($this->getRequest()->getPost('adduser_login'));
			$adduser_mdp = $filter->filter($this->getRequest()->getPost('adduser_mdp'));
			$adduser_mdp2 = $filter->filter($this->getRequest()->getPost('adduser_mdp2'));

			$adduser_civility = $filter->filter($this->getRequest()->getPost('adduser_civility'));
			$adduser_nom = $filterMaj->filter($this->getRequest()->getPost('adduser_nom'));
			$adduser_prenom = $filter->filter($this->getRequest()->getPost('adduser_prenom'));
             
			$adduser_fct = $filter->filter($this->getRequest()->getPost('adduser_fct'));
			$adduser_tel = $filter2->filter($this->getRequest()->getPost('adduser_tel'));
			$adduser_fax = $filter2->filter($this->getRequest()->getPost('adduser_fax'));
			$adduser_email = $adduser_login;// $filter->filter($this->getRequest()->getPost('adduser_email'));


			$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse'));
			$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp'));
			$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville'));
			$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays'));
			$adduser_departement = $filter->filter($this->getRequest()->getPost('adduser_departement'));
			$adduser_region = $filter->filter($this->getRequest()->getPost('adduser_region'));
			$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adressecomplete'));

			$adresse_type = $this->getRequest()->getPost('address_type');
			if ($adresse_type == 'new') {
				$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse'));
				$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp'));
				$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville'));
				$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays'));
				$adduser_departement = $filter->filter($this->getRequest()->getPost('adduser_departement'));
				$adduser_region = $filter->filter($this->getRequest()->getPost('adduser_region'));
				$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adressecomplete'));
			} else {
				$adduser_adresse = $filter->filter($this->getRequest()->getPost('adduser_adresse_old'));
				$adduser_cp = $filter->filter($this->getRequest()->getPost('adduser_cp_old'));
				$adduser_ville = $filter->filter($this->getRequest()->getPost('adduser_ville_old'));
				$adduser_pays = $filter->filter($this->getRequest()->getPost('adduser_pays_old'));
				$adduser_departement = '';
				$adduser_region = '';
				$adduser_adressecomplete = $filter->filter($this->getRequest()->getPost('adduser_adresse_old'));
			}

			$adduser_raisonsocial = $filterMaj->filter($this->getRequest()->getPost('adduser_raisonsocial'));
			$adduser_siret = $filterMaj->filter($this->getRequest()->getPost('adduser_siret'));
			$adduser_numidfisc = $filterMaj->filter($this->getRequest()->getPost('adduser_numidfisc'));
			$adduser_codeape = $filterMaj->filter($this->getRequest()->getPost('adduser_codeape'));
			$adduser_sectactivite = $filterMaj->filter($this->getRequest()->getPost('adduser_sectactivite'));

			$adduser_comm = $filter->filter($this->getRequest()->getPost('adduser_comm'));

			$adduser_newsletter = $filter->filter($this->getRequest()->getPost('adduser_newsletter'));

			$typeUser = $filter->filter($this->getRequest()->getPost('adduser_typeuser'));

			$date = new Zend_Date();
			$dateinsc = $date->toString('YYYY-MM-dd HH:mm:ss');

			$data = array(
                                  'LOGIN' => utf8_decode($adduser_login), 
                                  'MDP' => md5($adduser_mdp), 
                                  'ROLE' => 0, 
                                  'NOM' => utf8_decode($adduser_nom), 
                                  'PRENOM' => utf8_decode($adduser_prenom),
                                  'CIVILITE' => $adduser_civility, 
                                  'FONCTION' => utf8_decode($adduser_fct), 
                                  'RAISONSOCIAL' => utf8_decode($adduser_raisonsocial), 
                                  'ADRESSE' => utf8_decode($adduser_adresse), 
                                  'CP' => utf8_decode($adduser_cp), 
                                  'VILLE' => utf8_decode($adduser_ville), 
                                  'DEPARTEMENT' => utf8_decode($adduser_departement), 
                                  'REGION' => utf8_decode($adduser_region), 
								  'ADRESSECOMPLETE' => utf8_decode($adduser_adressecomplete),
                                  'PAYS' => utf8_decode($adduser_pays), 
                                  'EMAIL' => utf8_decode($adduser_email), 
                                  'TEL' => $adduser_tel, 
                                  'FAX' => $adduser_fax, 
                                  'SIRET' => utf8_decode($adduser_siret), 
								  'NUMIDFISC' => utf8_decode($adduser_numidfisc),
                                  'CODEAPE' => utf8_decode($adduser_codeape), 
                                  'SECTACTIVITE' => utf8_decode($adduser_sectactivite), 
                                  'COMMENTAIRE' => utf8_decode($adduser_comm),  
                                  'TYPE' => $typeUser, 
                                  'DATEINSC' => $dateinsc);

			$isTypeOk = false;
			if ($validator2->isValid($typeUser)) {
				$isTypeOk = true;
			}

			$errorType = 0;
			if ($validator->isValid($adduser_mdp) && $validator->isValid($adduser_mdp2) &&
			$validator2->isValid($adduser_civility) &&
			$validator2->isValid($adduser_nom) && $validator2->isValid($adduser_adresse) &&
			$validator2->isValid($adduser_prenom) && $validator2->isValid($adduser_ville) &&
			$validator2->isValid($adduser_pays) &&
			$validatorEmail->isValid($adduser_login) && $validator2->isValid($adduser_cp)
			) {
				if ($isTypeOk) {
					if ($typeUser == "Professionnel") {
						if ($validator2->isValid($adduser_raisonsocial) &&
						$validator2->isValid($adduser_siret) &&
						$validator2->isValid($adduser_numidfisc) &&
						$validator2->isValid($adduser_codeape)) {

						} else { 
							$errorType = 3;
							foreach ($validator2->getErrors() as $errorCode) {
								$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
							}
						}
					}
				} else {
					$errorType = 2;
					$this->view->messageSuccess =  "Vous devez choisir entre Particulier et Professionnel. ";
				}
			} else {
				$errorType = 1; 
				foreach ($validator->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
				foreach ($validator2->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
				foreach ($validatorEmail->getErrors() as $errorCode) {
					$this->view->messageSuccess =  $this->getErrorValidator($errorCode);
				}
			}


			if ($errorType == 0) {
				if ($validatorTel->isValid($adduser_tel)) {
					if ($adduser_mdp2 == $adduser_mdp) {

						try {
							$user = new User();

							$isExistLogin = $user->fetchRow("LOGIN = '".$adduser_login."'");

							if (!$isExistLogin) {

								$isExistEmail = $user->fetchRow("EMAIL = '".$adduser_email."'");
								if (!$isExistEmail) {
									$isAdd = $user->insert($data);
									$this->log("Nouveau client : ".$adduser_email,'info');
									if ($adduser_newsletter) {
										$user_newsletter = new UserNewsletter();
										$code = md5($dateinsc.'_'.$adduser_email);
											
										$isExistNL = $user_newsletter->fetchRow("EMAIL = '".$adduser_email."'");

										if(!$isExistNL) {
											$dataNL = array(
						 	 					'EMAIL' => $adduser_email,
						 	 					'DATEINS' => $dateinsc,
						 	 					'CODE' => $code
											);
											$user_newsletter->insert($dataNL);
										}
									}

									$this->view->messageSuccess = $this->connectMe($adduser_login, $adduser_mdp);
								} else {
									$this->view->messageSuccess =  "L'email est d�j� utilis�.";
								}
							} else {
								$this->view->messageSuccess =  "L'identifiant existe d�j�";
							}
						} catch (Zend_Exception $e) {
							$this->log($e->getMessage(),'err');
							$this->view->messageSuccess =  "Une erreur est survenue, v�rifier vos informations.";
						}
					} else {
						$this->view->messageSuccess =  "V�rifier votre mot de passe";
					}
				} else {
					$this->view->messageSuccess =  "V�rifier votre num�ro de t�l�phone";
				}
			}
		}
		$this->_forward('ajaxvalue','ajax');
	}


	private function computeBill($statut,$reference,$id,$facture,$addresseLiv, $user) {
		$fact_raisonsociale = $user['prenom']." ".strtoupper($user['nom']);
		if ($user['type'] == "Professionnel") {
			$fact_raisonsociale = $user['raisonsocial'];
		} 
		$USER_MODEPAIEMENT_LABEL = " Paiement s�curis� en ligne";
		switch ($user['modepaiement']) {
			case 1 : $USER_MODEPAIEMENT_LABEL = " Paiement s�curis� en ligne"; break;
			case 2 : $USER_MODEPAIEMENT_LABEL = " Contre remboursement";break;
			case 3 : $USER_MODEPAIEMENT_LABEL = " Paiement diff�r� - 30 jours";break;
			case 4 : $USER_MODEPAIEMENT_LABEL = " Paiement diff�r� - 45 jours";break;
			case 5 : $USER_MODEPAIEMENT_LABEL = " Paiement diff�r� - 60 jours";break;
			case 6 : $USER_MODEPAIEMENT_LABEL = " A r�ception de la facture";break;
		}
        
        if($statut == 10) {
            $USER_MODEPAIEMENT_LABEL = "Devis";
        }

		$data = array (
						'REFERENCE' => $reference, 
						'PRIXTOTALHTHR' => $facture->total_HT_HR,
						'PRIXREMISEEUR' => $facture->total_remise,
						'PRIXTOTALHT' => $facture->total_HT,
						'PRIXFRAISPORT' => $facture->total_frais_port,
						'PRIXFRAISPORTPOUR' => $facture->total_frais_port_pour,
						'PRIXTOTALHTFP' => $facture->total_HT_FP,
						'PRIXTOTALTTC' => $facture->total_TTC,
						'PRIXTOTALTVA' => $facture->total_TVA,
						'DATESTART' => $facture->date_start, 
						'IDUSER' => $user['id'],
						'STATUT' => $statut,
						'LIV_RAISONSOCIAL' => $addresseLiv['raisonsocial'],
						'LIV_ADRESSE' => $addresseLiv['adresse'],
						'LIV_CP' => $addresseLiv['cp'],
						'LIV_VILLE' => $addresseLiv['ville'],
						'LIV_PAYS' => $addresseLiv['pays'],
						'FACT_RAISONSOCIAL' => $fact_raisonsociale,
						'FACT_ADRESSE' => $user['adresse'],
						'FACT_CP' => $user['cp'],
						'FACT_VILLE' => $user['ville'],
						'FACT_PAYS' => $user['pays'],
						'USER_NOM' =>$user['nom'],
						'USER_PRENOM' =>$user['prenom'],
						'USER_TEL' =>$user['tel'],
						'USER_FAX' =>$user['fax'],
						'USER_NUMCOMPTE' =>$user['numcompte'],
						'USER_EMAIL' =>$user['email'],
						'USER_MODEPAIEMENT' =>$user['modepaiement'],
						'USER_TYPE' =>$user['type'],
						'USER_MODEPAIEMENT_LABEL' =>$USER_MODEPAIEMENT_LABEL,
						'CADDY' => $facture->facture_lines,
						'INFOLIV' => $facture->livraison,
						'CODEREDUCTION' => $facture->code_reduction,
						'ID_COMMAND' => $id
		);
        $data['CADDYFIDELITE'] = array();
        if($statut != 10) {
            $data['CADDYFIDELITE'] = $facture->facture_fidelite_lines;
        } else {
            $facture->facture_fidelite_lines = array();            
        }
		return $data;
	}
 
	public function validationAction()
	{
		try {
			$this->view->title = 'Confirmation de votre commande';
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();

			if ($auth->hasIdentity() && isset($storage['user'])) {
				
				$this->view->user = $storage['user'];

				$usernamespace = $this->getSession();
				$addresseLiv = $usernamespace->addresseLiv;
				$facture = $usernamespace->myFactureValidate;

				if ($this->isExisteArray($addresseLiv) && $facture->isFactureValid(2)) {
					$this->view->etapeCommande = 4;
					$this->view->linksMenu = $this->generateLinksMenu(4); 
					$usernamespace->myFactureValidate = $facture;

					$data = $this->insertNewCommand(0,'Validating','',$facture, $addresseLiv,$storage['user']);
					$usernamespace->commandAdded = $data;

					$facture = $this->computeBill(0,$data['REFERENCE'],$data['ID'],$facture, $addresseLiv, $storage['user']);
					$this->view->facture = $facture;

					$promo = new PromoCalculator();
					$this->view->isCommandValid = $promo->isCommandValid($facture['PRIXTOTALHT']);

				} else {
					$this->_redirect('/mon-panier.html');
				}
			}  else {
				$this->_redirect('/connectez-vous.html');
			}
		} catch (Zend_Exception $e) {
			$this->log("Erreur : validationAction() ".$e->getMessage(),'err');
			$this->_redirect('/');
		}
	}

	private function isExisteArray($array) {
		if (isset($array) && sizeof($array) > 0) {
			return true;
		} else {
			return false;
		}
	}
	public function paiementAction() {
		try {

			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			$ispaiementOk = false;
            $sendmail = true;
			
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$modepaiement = $storage['user']['modepaiement']; 
				$payment_status = 'Pending';
				$txn_id = '';
				
				$type_paiement = '';
				$type = 0;
				$type_prefix = 'Mode de paiement : ';
				switch ($modepaiement) {
					case 1 :
						$type_paiement = $type_prefix.'Paiement s�curis� en ligne';
						$ispaiementOk = true;
                        $sendmail = false;
						if ($this->ipnPaypalListenerValidate()) {
							$payment_status = $this->_request->getParam('payment_status');
							$txn_id = $this->_request->getParam('txn_id');
						} 
						break;
					default :
						$ispaiementOk = false;
						break;
				}
				
				if ((int)$this->getRequest()->getParam('type') > 0) {
					$type = (int)$this->getRequest()->getParam('type'); 
					switch ($type) {
						case 1 : 
							$ispaiementOk = true; 
							$type_paiement = $type_prefix.'Par ch�que';
							break;
						case 2 : 
							$ispaiementOk = true; 
							$type_paiement = $type_prefix.'Par virement';
							break;
						case 3 : 
							$ispaiementOk = true; 
							switch ($modepaiement) { 
								case 2 : $type_paiement = $type_prefix."Contre remboursement";break;
								case 3 : $type_paiement = $type_prefix."Paiement diff�r� - 30 jours";break;
								case 4 : $type_paiement = $type_prefix."Paiement diff�r� - 45 jours";break;
								case 5 : $type_paiement = $type_prefix."Paiement diff�r� - 60 jours";break;
								case 6 : $type_paiement = $type_prefix."A r�ception de la facture";break;
							} 
							break; 
					}
				} 
			} else {
			    $this->log("Erreur : paiementAction() No user",'warn');
            }

			if ($ispaiementOk) {
			    $this->log("Erreur : paiementAction() Paiement Ok",'warn');
				$this->finishandclosepaiement($payment_status, $txn_id, $type_paiement, $type, $sendmail);				
			}  else {
			    $this->log("Erreur : paiementAction() Redirect Home",'warn');
				$this->_redirect('/');
			}

		}catch (Zend_Exception $e) {
			$this->log("Erreur : paiementAction() ".$e->getMessage(),'err');
			$this->_redirect('/');
		}
	}

	private function sendMailCommande($facture, $to) {


		$view = new Zend_View();
		$view->addScriptPath('../application/modules/default/views/scripts/commande/');
		$view->assign("facture",$facture);
		$view->assign("baseUrl", "http://".$this->site_actualshort);
		$view->assign("baseUrl_SiteCommerceUrl", $this->baseUrl_SiteCommerceUrl);
		$view->assign("serviceClient_Mail", $this->serviceClient_Mail);
		
		$view->assign("siteName", $this->siteName);
		$view->assign("site_addresse3_title", $this->site_addresse3_title);
		$view->assign("site_addresse3_address", $this->site_addresse3_address);
		$view->assign("site_addresse3_cp", $this->site_addresse3_cp);
		$view->assign("site_addresse", $this->site_addresse);
		$view->assign("site_actualshort", $this->site_actualshort);
		
		$view->assign("site_rib_numbers", $this->site_rib_numbers);
		$view->assign("site_rib_iban", $this->site_rib_iban);
		$view->assign("site_rib_bic", $this->site_rib_bic);
		$view->assign("site_rib_bankname", $this->site_rib_bankname);

		$body = $view->render("facture_mail.phtml");

		$from =  $this->serviceClient_Mail;

		if ($facture['STATUT'] == 1) { $objet = "Votre commande : ".$facture['REFERENCE']; } else {$objet = "Votre devis : ".$facture['REFERENCE'];}

		$mail = new Zend_Mail();
		$mail->setBodyHtml($body);
		$mail->setFrom($from, $this->siteName);
		$mail->addTo($to);
		$mail->setSubject($objet);
		try {
			$mail->send();
			$this->log("L'email de commande a �t� envoy� a : ".$to,'info');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	private function referencegen() {
		$chaine ="mnoTUzS5678kVvwxy9WXYZRNCDEFrslq41GtuaHIJKpOPQA23LcdefghiBMbj0";
		srand((double)microtime()*1000000);
		for($i=0; $i<10; $i++){
			@$pass .= $chaine[rand()%strlen($chaine)];
		}
		return $pass;
	}

	private function generateLinksMenu($etapeCommande){
		$linksMenu = array();
		switch ($etapeCommande) {
			case 2 :
				$linksMenu[0]['NAVURL'] = '/mon-panier.html';
				$linksMenu[0]['NAVNOM'] = 'Mon Panier';
				$linksMenu[1]['NAVURL'] = '/mon-panier-connexion.html';
				$linksMenu[1]['NAVNOM'] = 'Identification';
				break;

			case 3 :
				$linksMenu[0]['NAVURL'] = '/mon-panier.html';
				$linksMenu[0]['NAVNOM'] = 'Mon Panier';
				$linksMenu[1]['NAVURL'] = '/mon-panier-livraison.html';
				$linksMenu[1]['NAVNOM'] = 'Livraison';
				break;

			case 4 :
				$linksMenu[0]['NAVURL'] = '/mon-panier.html';
				$linksMenu[0]['NAVNOM'] = 'Mon Panier';
				$linksMenu[1]['NAVURL'] = '/mon-panier-livraison.html';
				$linksMenu[1]['NAVNOM'] = 'Livraison';
				$linksMenu[2]['NAVURL'] = '/mon-panier-validation.html';
				$linksMenu[2]['NAVNOM'] = 'Validation';
				break;

		}

		return $linksMenu;
	}
    
	private function updateCommandFidelite($id, $facture) {
        $commandFidelite = new CommandFidelite();
        $commandFidelite->delete('IDCOMMAND = '.$id); 
		foreach ($facture->facture_fidelite_lines as $row) {
			$dataCaddyFidelite = array (
						'IDFIDELITE' => $row->fidelite_id,
						'NBPOINT' => $row->fidelite_nbpoint,                  
						'NOM' => $row->fidelite_nom,
						'IDCOMMAND' => $id
			);
			$commandFidelite->insert($dataCaddyFidelite);
		}
    }

	private function updateCommand($id, $payment_status,$txn, $statut) {

		try {
			$command = new Command();
			$data = array(
			'PAYMENT_STATUS' => $payment_status,
			'TXN_ID' => $txn,
			'STATUT' => $statut
			);
			$command->update($data,'ID = '.$id);
            
            if ($statut != 10 && $this->carte_fidelite_enabled) {
                 $facture = $command->getCommandAsFacture($id);
			     $commandProduct = new CommandProduct();
			     $productChild = new ProductChild();
                 foreach($facture['CADDY'] as $row) {
                    $child = $productChild->fetchRow('ID = '.$row['ID']);
                    $dataProd = array(
			            'POINTFIDELITE' => $child['POINTFIDELITE'],
			            'POINTFIDELITESUM' => $child['POINTFIDELITE'] * $row['QUANTITY']
			        );
			        $commandProduct->update($dataProd,'ID = '.$row['IDLINE']);
                }
            }
		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la mise a jour de la commande : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}

	private function updateCommandByID($id, $payment_status,$txn, $statut) {
		try {
			$command = new Command();
			$data = array(
			'PAYMENT_STATUS' => $payment_status,
			'TXN_ID' => $txn,
			'STATUT' => $statut
			);
			$command->update($data,'ID = '.$id);

			$currentCommand = $command->fetchRow('ID = '.$id);
			if (isset($currentCommand) && !empty($currentCommand) && !empty($currentCommand['CODEREDUCTION'])) {
				$codeReduction = new CodeReduction();
				$date = new Zend_Date();
				$data = array(
					"isACTIF" => 0,
					"NOM" => $currentCommand['USER_NOM'],
					"PRENOM" => $currentCommand['USER_PRENOM'],
					"IDUSER" => $currentCommand['IDUSER'],
					"ID" => $id,
					"DATEUSE" => $date->toString('YYYY-MM-dd HH:mm:ss')
				);
				$codeReduction->update($data,"CODE = '".$currentCommand['CODEREDUCTION']."'");
			}

		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la mise a jour de la commande ID : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}


	private function updateCommandByIDUNVERIFIED($id, $paymentStat) {
		try {
			$command = new Command();
			$data = array(
			'PAYMENT_STATUS' => $paymentStat,
			'STATUT' => 1
			);
			$command->update($data,'ID = '.$id);
		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la mise a jour de la commande ID : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}

	private function deleteNewCommand($id) {
		try {
			$command = new Command();
			$commandProduct = new CommandProduct();

			$commandProduct->delete('IDCOMMAND = '.$id);
			$command->delete('ID = '.$id);
		} catch(Zend_Exception $e) {
			$this->log('Erreur lors de la suppression de la commande : '.$id.' Message : '.$e->getMessage(),'err');
			return false;
		}
		return true;
	}


	private function insertNewCommand($statut,$payment_status,$txn, $myFacture, $addresseLiv, $user) {
		$command = new Command();
		$fact_raisonsociale = $user['prenom']." ".strtoupper($user['nom']);
		if ($user['type'] == "Professionnel") {
			$fact_raisonsociale = $user['raisonsocial'];
		}
		$codereduction = "";
		$codereductioneuro = 0;
		$livnom = "";
		if (isset($myFacture->code_reduction) && !empty($myFacture->code_reduction)) {
			$codereductioneuro = $myFacture->code_reduction['EURO'];
			$codereduction = $myFacture->code_reduction['CODE'];
		}
		if (isset($myFacture->livraison) && !empty($myFacture->livraison)) {
			$livnom = $myFacture->livraison['NOMLIV'];
		}
			
		$data = array (
						'REFERENCE' => 'REF-'.$this->referencegen(),
						'PRIXTOTALHTHR' => $myFacture->total_HT_HR,
						'PRIXREMISEEUR' => $myFacture->total_remise,
						'PRIXTOTALHT' => $myFacture->total_HT,
						'PRIXFRAISPORT' => $myFacture->total_frais_port,
						'PRIXFRAISPORTPOUR' => $myFacture->total_frais_port_pour,
						'PRIXTOTALHTFP' => $myFacture->total_HT_FP,
						'PRIXTOTALTTC' => $myFacture->total_TTC,
						'DATESTART' => $myFacture->date_start,
						'STATUT' => $statut,
						'PAYMENT_STATUS' => $payment_status,
						'TXN_ID' => $txn,
						'IDUSER' => $user['id'],
						'LIV_RAISONSOCIAL' => $addresseLiv['raisonsocial'],
						'LIV_ADRESSE' => $addresseLiv['adresse'],
						'LIV_CP' => $addresseLiv['cp'],
						'LIV_VILLE' => $addresseLiv['ville'],
						'LIV_PAYS' => $addresseLiv['pays'],
						'FACT_RAISONSOCIAL' => $fact_raisonsociale,
						'FACT_ADRESSE' => $user['adresse'],
						'FACT_CP' => $user['cp'],
						'FACT_VILLE' => $user['ville'],
						'FACT_PAYS' => $user['pays'],
						'USER_NOM' =>$user['nom'],
						'USER_PRENOM' =>$user['prenom'],
						'USER_TEL' =>$user['tel'],
						'USER_FAX' =>$user['fax'],
						'USER_EMAIL' =>$user['email'],
						'USER_NUMCOMPTE' =>$user['numcompte'],
						'USER_MODEPAIEMENT' =>$user['modepaiement'],
						'USER_MODEPAIEMENT_TYPE' => 0,
						'LIV_NOM' =>$livnom,
						'CODEREDUCTIONEURO' => $codereductioneuro,
						'CODEREDUCTION' => $codereduction
		);

		$command->insert($data);

		$lastID = $command->getAdapter()->lastInsertId($command,'ID');

		$date = new Zend_Date();
		$myReference = $this->lpad_zero($lastID, 5)."-".$date->toString('YY');
		$dataRef = array ( 'REFERENCE' => $myReference );
		$command->update($dataRef,"ID = ".$lastID);
			
		$commandProduct = new CommandProduct();
		$userCaddyType = new UserCaddyType();

		foreach ($myFacture->facture_lines as $row) {
			$dataCaddy = array (
						'CHILDID' => $row->item_id,
						'CHILDREF' => $row->item_reference,
						'CHILDisPROMO' => $row->item_isPromo,
						'CHILDisDEVIS' => $row->item_isDevis,
						'CHILDPRIX' => $row->item_prix,
						'CHILDQUANTITY' => $row->item_qte,
						'CHILDPROMOPRIX' => $row->getPrixAfterRemise(),
						'CHILDPRIXTOTAL' => $row->getPrixTotalHT(true),
						'CHILDPRIXREMISE' => $row->getPrixRemise(),
						'CHILDREMISEPRIXTAUXE' => $row->remise_euro,
						'CHILDREMISEPRIXTAUXP' => $row->remise_pour,
						'PRODUCTID' => $row->product_id,
						'IDCOMMAND' => $lastID,
						'SELECTEDOPTION' => $row->item_selectedOption,
                        'POINTFIDELITE' => 0,
                        'POINTFIDELITESUM' => 0
			);
			$userCaddyType->addNewUserItem($row->item_reference, $user['id']);
			$commandProduct->insert($dataCaddy);
		}

		$dataReturn = array(
			'REFERENCE' => $myReference,
			'ID' => $lastID
		);
		return $dataReturn;
	}

	public function paypalipnvalidationtestAction() {
		$resultPaypal = $this->ipnPaypalListener();
		$this->_redirect('/');
	}

	public function paypalipnvalidationAction() {
		$resultPaypal = $this->ipnPaypalListener();
		$this->_redirect('/');
	}

	private function sendMail($body, $from, $to, $objet) {
		$mail = new Zend_Mail();
		$mail->setBodyHtml($body);
		$mail->setFrom($from, $this->siteName.' : PAYPAL');
		$mail->addTo($to);
		$mail->setSubject($objet);
		try {
			$mail->send();
			$this->log("L'email a �t� envoy� a : ".$to,'info');
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
	}

	private function ipnPaypalListener() {
		
		$idCommand = $this->_request->getParam('item_number');
		if (empty($idCommand)) {
			$idCommand = $this->_request->getParam('custom');			
		}
		
		$dataIPN = array(
			'transaction_subject' => $this->_request->getParam('transaction_subject'),
			'txn_type' => $this->_request->getParam('txn_type'),
			'payment_date' => $this->_request->getParam('payment_date'),
			'last_name' => $this->_request->getParam('last_name'),
			'residence_country' => $this->_request->getParam('residence_country'),
			'pending_reason' => $this->_request->getParam('pending_reason'),
			'item_name' => $this->_request->getParam('item_name'),
			'payment_gross' => $this->_request->getParam('payment_gross'),
			'payment_currency' => $this->_request->getParam('mc_currency'),
			'business' => $this->_request->getParam('business'),
			'payment_type' => $this->_request->getParam('payment_type'),
			'protection_eligibility' => $this->_request->getParam('protection_eligibility'),
			'payer_status' => $this->_request->getParam('payer_status'),
			'verify_sign' => $this->_request->getParam('verify_sign'),
			'txn_id' => $this->_request->getParam('txn_id'),
			'payer_email' => $this->_request->getParam('payer_email'),
			'tax' => $this->_request->getParam('tax'),
			'test_ipn' => $this->_request->getParam('test_ipn'),
			'first_name' => $this->_request->getParam('first_name'),
			'receiver_email' => $this->_request->getParam('receiver_email'),
			'quantity' => $this->_request->getParam('quantity'),
			'payer_id' => $this->_request->getParam('payer_id'),
			'receiver_id' => $this->_request->getParam('receiver_id'),
			'item_number' => $idCommand,
			'payment_status' => $this->_request->getParam('payment_status'),
			'handling_amount' => $this->_request->getParam('handling_amount'),
			'shipping' => $this->_request->getParam('shipping'),
			'payment_amount' => $this->_request->getParam('mc_gross'),
			'custom' => $this->_request->getParam('custom'),
			'charset' => $this->_request->getParam('charset'),
			'notify_version' => $this->_request->getParam('notify_version'),
			'merchant_return_link' => $this->_request->getParam('merchant_return_link')
		);

		// read the post from PayPal system and add 'cmd'
		$req = 'cmd=_notify-validate';

		foreach ($_POST as $key => $value) {
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}
		
		$this->log('PAYPAL : IPN INCOMING : req : '.$req,'info');

		// 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";

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

		$notify_email = $this->reglement_Mail;

		if (!$fp) {
			return false;
		} else {
			fputs ($fp, $header . $req);
			while (!feof($fp)) {
				$res = fgets ($fp, 1024);
				if (strcmp ($res, "VERIFIED") == 0) {
					if ($this->isTxnidUnique($dataIPN)) {

						if ($dataIPN['payment_status'] == 'Completed' && $dataIPN['receiver_id'] == $this->paypal_business) {
							$paypal_payment = new PaypalPaiement();
							$paypal_payment->insert($dataIPN);

							$this->updateCommandByID($idCommand,$dataIPN['payment_status'],$dataIPN['txn_id'],1);
		                    $this->log('PAYPAL : IPN-VERIFIED : res : '.$res.' : req : '.$req,'info');
							$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-VERIFIED');

				            $command = new Command();                            
                            $facture = $command->getCommandAsFacture($idCommand);
                            $this->finishandclosepaiementsendmail($facture, $idCommand, true, "Mode de paiement : Paiement s�curis� en ligne", 0);
                            
							return true;

						} else {
							$this->updateCommandByIDUNVERIFIED($idCommand, 'Incorrect');
							$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-VERIFIED INCORRECT');
							$this->log('PAYPAL : IPN-VERIFIED INCORRECT : res : '.$res.' : req : '.$req,'warn');
						}
					} else {
						$this->updateCommandByIDUNVERIFIED($idCommand, 'Duplicated');
						$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-VERIFIED DUPLICATED TRANSACTION');
						$this->log('PAYPAL : IPN-VERIFIED DUPLICATED TRANSACTION : res : '.$res.' : req : '.$req,'warn');
					}

				} else if (strcmp ($res, "INVALID") == 0) {
					$this->updateCommandByIDUNVERIFIED($idCommand, 'Invalid');
					$this->sendMail("$res\n $req \n", $notify_email, $notify_email, 'PAYPAL : IPN-INVALID');
					$this->log('PAYPAL : IPN-INVALID : res : '.$res.' : req : '.$req,'warn');
				}

			}
			fclose ($fp);
		}
		return false;
	}
    
    private function finishandclosepaiementsendmail($facture, $idCommand, $sendmail, $type_paiement, $type) {
		$command = new Command();
		$dataTemp = array(
				'USER_MODEPAIEMENT_LABEL' => $type_paiement,
				'USER_MODEPAIEMENT_TYPE' => $type
		);
		$command->update($dataTemp,'ID = '.$idCommand);
        
        if ($sendmail) {
            $facture['USER_MODEPAIEMENT_LABEL'] = $type_paiement;
		    $facture['USER_MODEPAIEMENT_TYPE'] = $type;                
		    $this->sendMailCommande($facture,$this->devisCommande_Mail);
		    $this->sendMailCommande($facture,$facture['USER_EMAIL']);
        }                
	    /*
        if (isset($this->ekomi_email) && !empty($this->ekomi_email)) {
		    $this->sendMailCommande($factureDevis,$this->ekomi_email);
        }*/                
    }

	private function ipnPaypalListenerValidate() {
	
		$idCommand = $this->_request->getParam('item_number');
		if (empty($idCommand)) {
			$idCommand = $this->_request->getParam('custom');			
		}
		
		$dataIPN = array(
			'transaction_subject' => $this->_request->getParam('transaction_subject'),
			'txn_type' => $this->_request->getParam('txn_type'),
			'payment_date' => $this->_request->getParam('payment_date'),
			'last_name' => $this->_request->getParam('last_name'),
			'residence_country' => $this->_request->getParam('residence_country'),
			'pending_reason' => $this->_request->getParam('pending_reason'),
			'item_name' => $this->_request->getParam('item_name'),
			'payment_gross' => $this->_request->getParam('payment_gross'),
			'payment_currency' => $this->_request->getParam('mc_currency'),
			'business' => $this->_request->getParam('business'),
			'payment_type' => $this->_request->getParam('payment_type'),
			'protection_eligibility' => $this->_request->getParam('protection_eligibility'),
			'payer_status' => $this->_request->getParam('payer_status'),
			'verify_sign' => $this->_request->getParam('verify_sign'),
			'txn_id' => $this->_request->getParam('txn_id'),
			'payer_email' => $this->_request->getParam('payer_email'),
			'tax' => $this->_request->getParam('tax'),
			'test_ipn' => $this->_request->getParam('test_ipn'),
			'first_name' => $this->_request->getParam('first_name'),
			'receiver_email' => $this->_request->getParam('receiver_email'),
			'quantity' => $this->_request->getParam('quantity'),
			'payer_id' => $this->_request->getParam('payer_id'),
			'receiver_id' => $this->_request->getParam('receiver_id'),
			'item_number' => $idCommand,
			'payment_status' => $this->_request->getParam('payment_status'),
			'handling_amount' => $this->_request->getParam('handling_amount'),
			'shipping' => $this->_request->getParam('shipping'),
			'payment_amount' => $this->_request->getParam('mc_gross'),
			'custom' => $this->_request->getParam('custom'),
			'charset' => $this->_request->getParam('charset'),
			'notify_version' => $this->_request->getParam('notify_version'),
			'merchant_return_link' => $this->_request->getParam('merchant_return_link')
		);

		$notify_email = $this->reglement_Mail;

		// read the post from PayPal system and add 'cmd'
		$req = 'cmd=_notify-validate';

		foreach ($_POST as $key => $value) {
			$value = urlencode(stripslashes($value));
			$req .= "&$key=$value";
		}

		$this->log('PAYPAL : IPN INCOMING : req : '.$req,'info');
		
		// 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";

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

		if (!$fp) {
			return false;
		} else {
			fputs ($fp, $header . $req);
			while (!feof($fp)) {
				$res = fgets ($fp, 1024);
				if (strcmp ($res, "VERIFIED") == 0) {
					if (!$this->isTxnidUnique($dataIPN)) {
						if ($dataIPN['payment_status'] == 'Completed' && $dataIPN['receiver_id'] == $this->paypal_business) {
							return true;
						}
					}
				} else if (strcmp ($res, "INVALID") == 0) {
					return false;
				}
			}
			fclose ($fp);
		}
		return false;
	}
	private function isTxnidUnique($data) {
		$paypal_payment = new PaypalPaiement();
		$row = $paypal_payment->fetchRow("txn_id = '".$data['txn_id']."'");
		if($row) { return false; } else { return true; }
	}


	public function devisAction() {
		$this->view->title = 'Confirmation de votre devis';
			
		try {
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$usernamespace = $this->getSession();
				$addresseLiv = $usernamespace->addresseLiv;
				$facture = $usernamespace->myFactureValidate;
				if ($this->isExisteArray($addresseLiv) && $facture->isFactureValid(2) && isset($usernamespace->commandAdded)) {

					$dataReturn = $usernamespace->commandAdded;
					$this->updateCommand($dataReturn['ID'],'Pending','',10);

					if (isset($facture->code_reduction) && !empty($facture->code_reduction)) {
						$codeReduction = new CodeReduction();
						$date = new Zend_Date();
						$data = array(
						"isACTIF" => 0,
						"NOM" => $storage['user']['nom'],
						"PRENOM" => $storage['user']['prenom'],
						"IDUSER" => $storage['user']['id'],
						"REFERENCE" => $dataReturn['REFERENCE'],
						"DATEUSE" => $date->toString('YYYY-MM-dd HH:mm:ss')
						);
						$codeReduction->update($data,"CODE = '".$facture->code_reduction['CODE']."'");
					}

					$factureDevis = $this->computeBill(10,$dataReturn['REFERENCE'],$dataReturn['ID'], $facture,$addresseLiv, $storage['user']);
					$this->view->facture = $factureDevis;
                    
                    $command = new Command();                            
                    $facture = $command->getCommandAsFacture($dataReturn['ID']);
					$this->sendMailCommande($facture,$this->devisCommande_Mail);
					$this->sendMailCommande($facture,$facture['USER_EMAIL']);
                    
					$this->view->linksMenu = $this->generateLinksMenu(4);
					$usernamespace->addresseLiv = array();
					$usernamespace->myFactureValidate = array();

					unset($usernamespace->addresseLiv);
					unset($usernamespace->myFactureValidate);
					unset($usernamespace->commandAdded);

					$usernamespace->myObjectCaddy =array();
					unset($usernamespace->myObjectCaddy);
                    
				    $usernamespace->myObjectCaddyFidelite = array();
				    unset($usernamespace->myObjectCaddyFidelite);
				} else { $this->_redirect('/'); }
			} else { $this->_redirect('/connectez-vous.html'); }
		} catch (Zend_Exception $e) {
			$this->log('Erreur : devisAction() : '.$e->getTraceAsString(),'err');
			$this->_redirect('/');
		}
	}

	private function lpad_zero($chaine,$taille) {
		return str_pad($chaine,$taille,"0",STR_PAD_LEFT);
	}
	
	private function finishandclosepaiement($payment_status, $txn_id, $type_paiement, $type, $sendmail) {
		if (!isset($this->site_rib_numbers)) {
			$this->initVariables();
		}
		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();
		
		if ($auth->hasIdentity() && isset($storage['user'])) {
		
			$usernamespace = $this->getSession();
			$addresseLiv = $usernamespace->addresseLiv;
			$myFacture = $usernamespace->myFactureValidate;
		
			if ($this->isExisteArray($addresseLiv) && $myFacture->isFactureValid(2) && isset($usernamespace->commandAdded)) {
		
				$this->view->title = 'Confirmation de votre commande';
		
				$data = $usernamespace->commandAdded;
				$this->updateCommand($data['ID'],$payment_status,$txn_id,1);
                
				$this->updateCommandFidelite($data['ID'], $myFacture);
        
				$facture = $this->computeBill(1,$data['REFERENCE'],$data['ID'], $myFacture,$addresseLiv,$storage['user']);
                
                $facture['USER_MODEPAIEMENT_LABEL'] = $type_paiement;
		        $facture['USER_MODEPAIEMENT_TYPE'] = $type; 
                $this->view->facture = $facture;
                
				$command = new Command();                            
                $factureMail = $command->getCommandAsFacture($data['ID']);
                $this->finishandclosepaiementsendmail($factureMail, $data['ID'], $sendmail, $type_paiement, $type);
                            
				$this->view->linksMenu = $this->generateLinksMenu(4);
		
				$this->log("Nouvelle commande : ".$data['REFERENCE'],'info');
				$this->view->verifMessage = 1;
		
				$usernamespace->addresseLiv = array();
				$usernamespace->myFactureValidate = array();
		
				unset($usernamespace->addresseLiv);
				unset($usernamespace->myFactureValidate);
				unset($usernamespace->commandAdded);
		
				$usernamespace->myObjectCaddy = array();
				unset($usernamespace->myObjectCaddy);
                
				$usernamespace->myObjectCaddyFidelite = array();
				unset($usernamespace->myObjectCaddyFidelite);
			} else {
				$this->_redirect('/mon-panier.html');
			}
		}   else {
			$this->_redirect('/connectez-vous.html');
		}
	}
	public function citelispaiementAction() {
		require_once('../library/citelis/configuration/identification.php');
		require_once('../library/citelis/configuration/options.php');
		require_once('../library/citelis/lib/lib_debug.php');
				
		$array = array();
		$payline = new paylineSDK(MERCHANT_ID, ACCESS_KEY, PROXY_HOST, PROXY_PORT, PROXY_LOGIN, PROXY_PASSWORD, PRODUCTION);
		$payline->returnURL = RETURN_URL;
		$payline->cancelURL = CANCEL_URL;
		$payline->notificationURL = NOTIFICATION_URL;
		
		// PAYMENT
		$array['payment']['amount'] = $_POST['amount'];
		$array['payment']['currency'] = PAYMENT_CURRENCY;
		$array['payment']['action'] = PAYMENT_ACTION;
		$array['payment']['mode'] = PAYMENT_MODE;
		
		// ORDER
		$array['order']['ref'] = $_POST['ref'];
		$array['order']['amount'] = $_POST['amount'];
		$array['order']['currency'] = PAYMENT_CURRENCY;
		
		// CONTRACT NUMBERS
		$array['payment']['contractNumber'] = CONTRACT_NUMBER;
		$contracts = explode(";",CONTRACT_NUMBER_LIST);
		$array['contracts'] = $contracts;
		$secondContracts = explode(";",SECOND_CONTRACT_NUMBER_LIST);
		$array['secondContracts'] = $secondContracts;
		
		// EXECUTE
		$result = $payline->doWebPayment($array);
		
		if(isset($result) && $result['result']['code'] == '00000'){		
			//Sauvegarde du token
			$usernamespace = $this->getSession();
			$usernamespace->commandAddedLastTokenCitelis = $result["token"];
			$this->_redirect($result["redirectURL"]);
		} elseif(isset($result)) {
			$this->log("Erreur commande citelis : ".$result['result']['code']. ' '.$result['result']['longMessage'],'err');
			$this->_redirect('/mon-panier-validation.html');
		}
	}
	
	public function paiementcitelisAction() {
		try {
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			$ispaiementOk = false;
				
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$usernamespace = $this->getSession();
				$this->log("Token recu : ".$this->_request->getParam("token"). ' / Token sauvegard� : '.$usernamespace->commandAddedLastTokenCitelis,'info');
				if ($usernamespace->commandAddedLastTokenCitelis == $this->_request->getParam("token")) {				
					$ispaiementOk = true;
				}
			}

			if ($ispaiementOk) {
				$this->finishandclosepaiement("Pending",$this->_request->getParam("token"), "Mode de paiement : Paiement s�curis� en ligne", 0, true);
			 	$this->render('paiement');
			}  else {
				$this->_redirect('/');
			}
	
		}catch (Zend_Exception $e) {
			$this->log("Erreur : paiementcitelisAction() ".$e->getMessage(),'err');
			$this->_redirect('/');
		}
	}
	
	public function citelisipnvalidationAction() {
		$this->ipnCitelisListener();
		$this->_redirect('/');
	}
	
	private function ipnCitelisListener() { 
		require_once('../library/citelis/configuration/identification.php');
		require_once('../library/citelis/configuration/options.php');
		require_once('../library/citelis/lib/lib_debug.php');
		try {	
			// GET TOKEN
			$token = $this->_request->getParam("token");
			if(isset($token)){
				$this->log("WebPaymentDetailsRequest - Token : ".$token,'info');
				$array = array();
				$payline = new paylineSDK(MERCHANT_ID, ACCESS_KEY, PROXY_HOST, PROXY_PORT, PROXY_LOGIN, PROXY_PASSWORD, PRODUCTION);
					
				$array['token'] = $token;
	    		$array['version'] = '3';
				// EXECUTE
				$result = $payline->getWebPaymentDetails($array);
				if(isset($result)){
					$command = new Command();
					$currentCommand = $command->fetchRow('TXN_ID = "'.$token.'"');
					$idCommand = $currentCommand["ID"];
					
					$output = print_a($result, 1, true);
					if ($result['result']['code'] == "00000" || $result['result']['code'] == "01001" ) {
						$this->updateCommandByID($idCommand,"Completed", $token,1);
						
						$this->log('CITELIS : IPN-VERIFIED : res : '.$output,'info');
						$this->sendMail($output." \n", $notify_email, $notify_email, 'CITELIS : IPN-VERIFIED');
					} else {
						$this->updateCommandByIDUNVERIFIED($idCommand, 'Incorrect');
						$this->log('CITELIS : IPN-VERIFIED INCORRECT : res : '.$output,'warn');
						$this->sendMail($output." \n"." \n", $notify_email, $notify_email, 'CITELIS : IPN-VERIFIED INCORRECT');
					}
				} else {
					$this->log("WebPaymentDetailsRequest - No results",'info');
				}
			} else {
				$this->log("WebPaymentDetailsRequest - Token Missing ",'info');
			}
		} catch (Zend_Exception $e) {
			$this->log('Erreur : ipnCitelisListener() : '.$e->getTraceAsString(),'err');
		}
  	}
}?>
ServicesController.php000060400000002723150713055030011103 0ustar00<?php

class ServicesController  extends Modules_Default_Controllers_MainController
{

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}

	public function indexAction()
	{
		$this->_forward('information');
	}
	public function informationAction()
	{
		if ($this->getRequest()->getParam('p') && (int)$this->getRequest()->getParam('p')>0) {
				
			$id = (int)$this->getRequest()->getParam('p');
			$footer = new FooterContent();
            $detailFooterRow = $footer->fetchRow('ID = '.$id);
            if ($detailFooterRow) {
                $detailFooter = $detailFooterRow->toArray();
                 
                $linksMenu[0]['NAVURL'] = "";
                $linksMenu[0]['NAVNOM'] = $detailFooter['TITRE'];
                $this->view->linksMenu = $linksMenu;
				
                $this->view->title = $detailFooter['TITRE'];
                $this->view->service = $detailFooter;
            } else {
                $this->log("Impossible de trouver l'information : ".$this->getRequest()->getRequestUri(), 'warn');
                $this->_redirect('/');
            }
		}
	}

	public function faqAction() {
		$linksMenu[0]['NAVURL'] = '/services/faq';
		$linksMenu[0]['NAVNOM'] = 'FAQ';
		$this->view->linksMenu = $linksMenu;
			
		$this->view->title = 'Foire aux questions';
			
		$faq = new FAQ();
		$this->view->faqs = $faq->getLists();
		$faqtype = new FAQType();
		$this->view->faqType = $faqtype->getTypes();
	}
}



?>AjaxController.php000060400000002357150713055030010206 0ustar00<?php

class AjaxController extends Modules_Default_Controllers_MainController
{
	private $layout;

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->checkMaintenance();
	}
	public function indexAction()
	{
		$this->_forward('ajaxmessage');
	}

	public function ajaxmessageAction() {
		$this->render();
	}
	public function ajaxvalueAction() {
		$this->render();
	}
	public function ajaxcaddyAction() {
		$this->render();
	}
	public function ajaxlivraisonAction() {
		$this->render();
	}
	public function ajaxaccountAction() {
		$this->render();
	}



	public function autocompletekeywordAction() {
		$result = array();
		if ($this->getRequest()->isPost()) {
			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringToLower())
			->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));

			$keyword = new KeyWord();
			$key = $filter->filter(utf8_decode($this->getRequest()->getPost('search')));
			$result = $keyword->findByKeyword($key);
		}
		$this->view->messageSuccess = serialize($result);
		$this->render('ajaxvalue');
	}
}
?>ProduitspromotionController.php000060400000025367150713055030013111 0ustar00<?php

class ProduitsPromotionController extends Modules_Default_Controllers_MainController
{

	private $myCaddy;

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();

	}
    
    private function computeUrlNavigationParent($row) {
        return $row['NAVNOM_URLPARENTS']."/".$row['CATNAVNOM'];
    }
    
	public function indexAction()
	{
		$params = $this->getRequest()->getParams();
		$params['c'] = 1;
		$params['page'] = 'nos-promotions';
		$this->getRequest()->setParams($params);
		$this->_forward('/categorie');
	}
	private function computeProductListToShow($list, $user) {
		try {
			$listProducts = array();
			$metakeywords = '';

			$isAllPromos = false;
			$currentPromoAll = array();
			$currentPromo = array();
			$listUserCodeInternIdBrendFound = array();
			$listUserCodeInternIdBrends = array();
			$listIdBrendFound = array();
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
			$listIdBrends = array();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$promoUser = new PromoUser();
			$product= new Product();
 
			if (!empty($list)) {
				$idCategory = $list[0]['CATID'];
				$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
				if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
			}
			$productChildQte = new ProductChildQte();

			foreach ($list AS $row) {
				$currentProduct = array();
				$currentProduct['ID'] = $row['ID'];
				$currentProduct['NOM'] = $row['NOM'];
				//$currentProduct['DESCSHORT'] = $this->cutString($row['DESCSHORT'], 80);
				$currentProduct['DESCSHORT'] = $row['DESCSHORT'];
				$currentProduct['URL'] = $row['URL'];
				$currentProduct['BREND'] = $row['BREND'];
				$currentProduct['isSHOWBREND'] = $row['isSHOWBREND'];
				$currentProduct['BRENDURL'] = $row['BRENDURL'];
				$currentProduct['NBREFERENCE'] = $row['NBREFERENCE'];
				$currentProduct['isDEVISPRODUCT'] = $row['isDEVISPRODUCT'];
                $currentProduct['NAVNOM_URLPARENTS'] = $this->computeUrlNavigationParent($row);

				if (isset($row['NAVNOM'])) {
					$navnom = $row['NAVNOM'];
				} else {
					$navnom = $row['PRODNAVNOM'];
				}

				$currentProduct['NAVNOM'] = $this->verifyNavigationString($navnom, $row['NOM'], '');
                

				$currentProduct['NAVTITRE'] = $row['NAVTITRE'];
				$currentProduct['NAVDESC'] = $row['NAVDESC'];

				$isFirst = false;

				if (empty($metakeywords)) {
					$metakeywords .= $row['KEYWORDS_PROD'];
				} else {
					$metakeywords .= ','.$row['KEYWORDS_PROD'];
				}

				$currentProduct['isPROMO'] = $row['isPROMO'];
				$currentProduct['PRIX'] = $row['PRIX'];

				/*
				 * PRIX DEGRESSIF
				 */
				$currentProduct['isPRIXDEGRESSIF'] = $productChildQte->isPrixDegressifByProductID($row['ID']);
					
				/*
				 * CALCUL PROMO
				 */
				$idBrend = $row['BRENDID'];

				if (!in_array($idBrend, $listIdBrends, true)) {
					$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
					array_push($listIdBrends, $idBrend);
					if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
				}
				if ($row['isPROMO'] == 1) {
					$isRemise = false;
					if (in_array($idBrend, $listIdBrends, true)) {
						foreach ($listIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend) {
								$currentProduct['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
					if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
						$currentProduct['isPROMO'] = 0;
						if ($currentPromoAll['REMISEEURO'] > 0) {
							$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
						}
						if ($currentPromoAll['REMISEPOUR'] > 0) {
							$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
						}
					}
				}
				if (isset($user) && !empty($user)) {
					$userId = $user['id'];
					$codeIntern = $user['cintern'];
					$isRemise = false;

					if (!empty($codeIntern)) {
						if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
							array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
							if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
						}
						if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
									$currentProduct['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
					}
					if (!$isRemise) {
						if (!in_array($idBrend, $listUserIdBrends, true)) {
							$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
							array_push($listUserIdBrends, $idBrend);
							if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
						}
						if (in_array($idBrend, $listUserIdBrends, true)) {
							foreach ($listUserIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend) {
									$currentProduct['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
					}
				}


				if ($currentProduct['PRIX'] <= 0 ) { $currentProduct['PRIX'] = $row['PRIX']; }
				
				$currentProduct['PRIXLOWEST'] = $product->calculateLowestPrice($currentProduct['ID']);
				
				array_push($listProducts, $currentProduct);
			}
			return $result = array( 'PRODUCTS' => $listProducts, 'META_KEY' =>  $metakeywords);
		} catch (Zend_Exception $e) {
			$this->log('Erreur computeProductListToShow : '.$e->getMessage(),'err');
		}
		return $result = array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
	}
	public function categorieAction()
	{
		$userNamespace = $this->getSession();
		$category = new Category2();
		$product = new Product();

		$auth = Zend_Auth::getInstance();
		$auth->setStorage($this->getSessionStorage());
		$storage = $auth->getStorage()->read();
		$currentUser = array();
		if ($auth->hasIdentity() && isset($storage['user'])) {
			$currentUser = $storage['user'];
		}
		if ($this->getRequest()->getParam('c')) {
			$id = (int)$this->getRequest()->getParam('c');

			if ($id>0) {

				try {
					$this->checkTypeOfPromo($id);
					$listCat = array();
					$listCat = $category->getTreeCatsOf($id);
					if (!empty($listCat)) {
						$this->view->listCat = $listCat;

						$this->view->isPromoPage = true;
						$breadcrumb = $category->getTreeInLineOf($id);
						$this->view->breadcrumb = $breadcrumb;
						$this->view->actualDesign = $this->showDesign(0, 0);

						if (empty($listCat['NAVTITRENOM'])) {
							$listCat['NAVTITRENOM'] = $listCat['NOM'];
						}
						if (empty($listCat['NAVDESCRIPTION'])) {
							$listCat['NAVDESCRIPTION'] = $listCat['DESCRIPTION'];
						}

						$filter = new Zend_Filter();
						$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());

						$this->view->metadescription = $listCat['NAVDESCRIPTION'];
						$this->view->title = $listCat['NAVTITRENOM'];
						$isTri_metaKeyword = false;

						$annoncesleft = new AnnonceLeft();
						$this->view->listads = $annoncesleft->getAnnoncesByShow($id);

						if (!$listCat['SUBS']) {
							$triSql = 'NOM ASC';
							//List of products
							$productList = $product->getProductsByIdCategoryForPromotion($id, $triSql);


							$this->view->orderNameProduct = $userNamespace->objOrderNameProduct;
							$resultProduct = $this->computeProductListToShow($productList, $currentUser);
							$this->view->listAllProducts = $resultProduct['PRODUCTS'];

                            if (!empty($listCat['KEYWORDS'])) {
                                $this->view->metakeywords = $listCat['KEYWORDS'];
                            } else {                                
                                $this->view->metakeywords = $resultProduct['META_KEY'];
                            }
							
							//Show product page
							$this->render('nosproduits');
						} else {
							$metakeywords = $listCat['KEYWORDS'];

                            if (empty($metakeywords)) {
							    for ($index = 0; $index < sizeOf($listCat['SUBS']); $index++) {
								    if (empty($metakeywords)) {
									    $metakeywords .= $listCat['SUBS'][$index]['KEYWORDS'];
								    } else {
									    $metakeywords .= ','.$listCat['SUBS'][$index]['KEYWORDS'];
								    }
							    }
                            }
							$this->view->metakeywords = $metakeywords;
						}
					} else {
						$this->log('Impossible de trouver la categorie : '.$this->getRequest()->getRequestUri(), 'warn');
						$this->_redirect('/');
					}

				} catch (Zend_Exception $e) {
					$this->log('Erreur pour trouver : '.$this->getRequest()->getRequestUri()." ".$e->getMessage(),'err');
					$this->_redirect('/');
				}
			} else {
				$this->_redirect('/');
			}
		}  else {
			$this->_redirect('/');
		}
	}

	private function checkTypeOfPromo($id) {
		$category = new Category2();
		$firstCategory = $category->getParentFirstOf($id);
		if ($firstCategory != null) {
			$currentId = $firstCategory["ID"];
			if ($currentId == 2) { $this->view->prefixPromoClass = "eco-"; }
			if ($currentId == 1) { $this->view->prefixPromoClass = ""; }
		}
	}

	private function isPromoActive($myPromo) {
		if ($myPromo) {
			if ($myPromo['REMISEEURO'] > 0) { return true; }
			if ($myPromo['REMISEPOUR'] > 0) { return true; }
		}
		return false;
	}
}
?>ProduitsController.php000060400000246061150713055030011136 0ustar00<?php

class ProduitsController extends Modules_Default_Controllers_MainController
{

	private $myCaddy;

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
		$this->checkMaintenance();
	}
	public function indexAction()
	{
		$this->_redirect('/');
	}
    public function ajaxdownloaddocumentAction() {
    
        $message = "";
        $isSuccess = false;
        if ($this->getRequest()->isPost()) {
        
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$validatorEmail = new Zend_Validate_EmailAddress();
                
			$params = array();
			$params = $this->getRequest()->getPost();

			$civility = $filter->filter($params['civility_doc']);
			$name = $filter->filter($params['name_doc']);
			$firstname = $filter->filter($params['firstname_doc']);
			$email = $filter->filter($params['email_doc']);
			$product_id = (int) $params['product_id_doc'];
            
			if ($validator->isValid($civility) && $validator->isValid($name)  && $validator->isValid($firstname)
             && $validatorEmail->isValid($email)  && $product_id > 0) {
             
				$product = $this->computeProductDetail($product_id);
                $linkProd = $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlProduct($product['NAVNOM_URLPARENTS'], $product['NAVNOM'], $product['ID']);
	            $linkCat = $this->baseUrl_SiteCommerceUrl."/".Utils_Tool::getFormattedUrlCategory($product['NAVNOM_URLPARENTS'], $product['CATNAVNOM'], $product['IDCATEGORY']);
                $prodName = $product['NOM'];
                $catName = $product['CATNOM'];
                
                $docUrl =$product['DOCURL'];
                if (empty($docUrl)) {
					$listFTFDS = $this->getFTFDSByIdProd($product_id);
                    if (isset($listFTFDS) && !empty($listFTFDS) && sizeof($listFTFDS) > 0) {
                           $docUrl = $listFTFDS[0]['URL'];
                    }
                }
                
                $destFullName = $civility." ".$firstname." ".$name;
                
                $fromEmail = $this->no_reply_Mail;
                $fromName = $this->siteName;
                $toEmail = $email;
                
                try {
                    $userGuest = new UserGuest();
                    $date = new Zend_Date();
                    $data = array (
						'INFORMATION' => $destFullName,
						'ACTION' => "Fiche technique � t�l�charger : ".$prodName,
						'EMAIL' => $toEmail,
                        'DATEINSERT' => $date->toString('YYYY-MM-dd HH:mm:ss')
					);
					$userGuest->insert($data);
                    
			        $view = new Zend_View();
			        $view->addScriptPath('../application/modules/default/views/helpers/');
			        $view->assign("user_name",$name);
			        $view->assign("user_firstname",$firstname);
			        $view->assign("user_email",$email);
			        $view->assign("user_civility",$civility);
			        $view->assign("user_fullname",$destFullName);
                    
			        $view->assign("site_url",$this->siteName);
			        $view->assign("product_url",$linkProd);
			        $view->assign("category_url",$linkCat);
			        $view->assign("category_name",$catName);
			        $view->assign("product_name",$prodName);
			        $view->assign("document_link",$this->baseUrl_SiteCommerceUrl."/".$docUrl);
                    
                    $body = $view->render("mail_ajaxdownloaddocument.phtml");
			        $subject = "Fiche technique : ".$prodName;
				
			        $mail = new Zend_Mail();
			        $mail->setBodyHtml($body);
			        $mail->setFrom($fromEmail, $fromName);
			        $mail->addTo($toEmail);
			        $mail->setSubject($subject);

			        $mail->send();
			        $this->log("L'email de fiche technique a �t� envoy� par : ".$fromEmail.", ".$fromName." � ".$toEmail,'info');
 
		        } catch (Zend_Exception $e) {
			        $this->log($e->getMessage(),'err');
		        }         
             
                $message = "Le mail � �t� envoy� � <b>".$destFullName."</b>.";
                $isSuccess = true;
            }   else if ($product_id > 0) {
				$product = $this->computeProductDetail($product_id);
			    $this->view->detailProduct = $product;
            }  
        }
        
        $this->view->message = $message;
        $this->view->isSuccess = $isSuccess;
        
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
    }
    public function ajaxsendfriendAction() {
    
        $message = "";
        $isSuccess = false;
        if ($this->getRequest()->isPost()) {
        
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$params = array();
			$params = $this->getRequest()->getPost();

			$name = $filter->filter($params['name_friend']);
			$email = $filter->filter($params['email_friend']);
			$message = nl2br(htmlspecialchars($params['message_friend']));
			$product_id = (int) $params['product_id_friend'];
            
			if ($validator->isValid($name)  && $validator->isValid($email) && $validator->isValid($message) && $product_id > 0) {
            
                $fromEmail = $this->no_reply_Mail;
                $fromName = $name;
                $toEmail = $email;
				$product = $this->computeProductDetail($product_id);
                
                 try {
                 
                    $userGuest = new UserGuest();
					$date = new Zend_Date();
                    $data = array (
						'INFORMATION' => $name,
						'ACTION' => "Conseillez cet article : ".$product["NOM"],
						'EMAIL' => $toEmail,
                        'DATEINSERT' => $date->toString('YYYY-MM-dd HH:mm:ss')
					);
					$userGuest->insert($data);
                    
			        $view = new Zend_View();
			        $view->addScriptPath('../application/modules/default/views/helpers/');              
			        $view->assign("text_message",$message);
                    
                    $body = $view->render("mail_ajaxsendfriend.phtml");
			        $subject = "Voici un article conseill� par ".$name;
				 
			        $mail = new Zend_Mail();
			        $mail->setBodyHtml(utf8_decode($body));
			        $mail->setFrom($fromEmail, $fromName);
			        $mail->addTo($toEmail);
			        $mail->setSubject($subject);

			        $mail->send();
			        $this->log("L'email de conseille a �t� envoy� par : ".$fromEmail.", ".$fromName." � ".$toEmail,'info');
 
		        } catch (Zend_Exception $e) {
			        $this->log($e->getMessage(),'err');
		        }      
             
                $message = "Le mail � �t� envoy� � <b>".$email."</b>.";
                $isSuccess = true;
            }    
        }
        
        $this->view->message = $message;
        $this->view->isSuccess = $isSuccess;
        
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
    }
        
	public function nosmarquesAction() {        
		$this->view->title = 'Nos marques';
        $brand = new SupplierBrend();
        $this->view->brends = $brand->getAllShowableBrends();
    }
    
	public function nosmarquesdetailAction() {   
		$this->view->title = 'Nos marques'; 
        if ($this->getRequest()->getParam('id')) {
			$id = (int)$this->getRequest()->getParam('id');
            if ($id > 0) {
                try {
                    $brand = new SupplierBrend();
                    $brendData = $brand->getBrendByID($id);
                    $this->view->brends = $brendData;
                    $this->view->title = 'Nos marques - '.$brendData["BREND"]; 
		        } catch (Zend_Exception $e) {
			        $this->log("Error nosmarquesdetailAction : ".$id." : ".$e->getMessage(),'err');
                    $this->_forward('nosmarques','produits');
		        }
            } 
        }else {
            $this->_forward('nosmarques','produits');
        }
    }
    
	public function ajaxshowchildqtepriceAction() {
		$this->view->detailProductQte = array();
		$id = (int)$this->getRequest()->getParam('id');
		if ($id > 0) {
			$productChildQte = new ProductChildQte();
			$detailProductQte = $productChildQte->getAllActiveByItem($id);
				
			//Calcul des promos pour le prix degressif
			$productChild = new ProductChild();
			$childs = $productChild->getChildsInfoByListId($id);
			$promo = new PromoCalculator();
			$facture = new Facture();
			foreach ($detailProductQte AS $row) {
				$factureLine = new FactureLine();
				$childs[0]["PRIX"] = $row["PRIX"];
				$factureLine->setLineInfo($childs[0], 1, "N");
				$factureLine->setPromoCaddyType(false);
				$facture->addLine($factureLine);
				$promo->computeAllPromos($facture, null);
				$row["PRIX"] = $factureLine->getPrixTotalHT(true);
			}
				
			if (!empty($detailProductQte)) {
				$this->view->detailProductQte = $detailProductQte;
			}
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
	}
	public function ajaxshowallchildsAction() {
		$id = (int)$this->getRequest()->getParam('id');
		if ($id > 0) {
			$myProduct = $this->computeProductDetail($id);
			if ($myProduct) {
				$this->view->detailProduct = $myProduct;
				$category = new Category();
				$categoryFirst = $category->getParentFirstOf($myProduct['IDCATEGORY']);
				$this->view->actualDesign = $this->showDesign($categoryFirst['ID'], $categoryFirst);
			} else {
				$this->view->detailProduct = array();
				$this->view->actualDesign = array();
			}
		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
	}

	public function ajaxcodereductionAction() {
		if ($this->getRequest()->isPost()) {

			//filtres pour changer les chaines
			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringTrim());

			//valideurs pour les chaines
			$validator = new Zend_Validate();
			$validator -> addValidator(new Zend_Validate_NotEmpty());

			$params = array();
			$params = $this->getRequest()->getPost();

			$codeReduc = $filter->filter($params['codeReduc']);
			$this->view->messageSuccessReduc = "NOK";

			$user_namespace = $this->getSession();
			if (isset($user_namespace->urlCurrentProduct) && !empty($user_namespace->urlCurrentProduct)) {
				$this->view->urlCurrentProduct = $user_namespace->urlCurrentProduct;
			}

			if ($validator->isValid($codeReduc)) {

				$codeReduction = new CodeReduction();
				$resultCode = $codeReduction->getVerifyCodeBy($codeReduc);
				if (isset($resultCode) && !empty($resultCode)) {
					if ($resultCode['isACTIF'] == 1) {

						$usernamespace =  $this->getSession();
							
						$myFacture = $usernamespace->myFactureValidate;

						$myFacture->code_reduction = $resultCode;

						$myFacture->code_reduction['EURO'] = $myFacture->getPrixCodeReduction();
						$usernamespace->myFactureValidate = $myFacture;
						$this->view->messageSuccessReduc = "OK";
						$this->view->messageMessReduc = "Le code de r�duction est disponible";
					} else { $this->view->messageMessReduc = "Le code de r�duction n'est pas actif"; }
				} else { $this->view->messageMessReduc = "Le code de r�duction n'est plus disponible"; }
			} else {
				$usernamespace =  $this->getSession();
				$myFacture = $usernamespace->myFactureValidate;
				$myFacture->code_reduction = array();
				$usernamespace->myFactureValidate = $myFacture;

				$this->view->messageMessReduc = "Le code de r�duction n'est pas valide";
			}
		}
		$this->computeMonPanier();
		$this->_forward('ajaxcaddy','ajax');
	}

	private function computeLivraison ($totalHT) {
		$result = array();
		$result['fraisLivEUR'] = 0;
		$result['fraisLivPOUR'] = 0;
		$result['francoEur'] = 0;
		$result['resteFrancoLiv'] = 0;
		$promoCommand = new PromoCommand();
		try {
			$fraisCMD = $promoCommand->fetchAll('MONTANTFRAISCMD IS NOT NULL','MONTANTFRAISCMD ASC')->toArray();
			if ($fraisCMD) {
				foreach ($fraisCMD as $rowFrais) {
					if ($totalHT < $rowFrais['MONTANTFRAISCMD']) {
						if ($rowFrais['REMISEEURO'] > 0) {
							$result['fraisLivEUR'] = $rowFrais['REMISEEURO'];
						} else if ($rowFrais['REMISEPOUR'] > 0) {
							$result['fraisLivEUR'] = sprintf("%.2f", ($totalHT * $rowFrais['REMISEPOUR']) / 100);
							$result['fraisLivPOUR'] = $rowFrais['REMISEPOUR'];
						}
						break;
					}
				}
				foreach ($fraisCMD as $rowFrais) {
					$result['francoEur'] = $rowFrais['MONTANTFRAISCMD'];
				}
					
				if($totalHT < $result['francoEur']) {
					$result['resteFrancoLiv'] = $result['francoEur'] - $totalHT;
				}
			}
		} catch (Zend_Exception $e) {
			$this->log("Error computeOldLivraison : ".$e->getMessage(),'err');
		}
		return $result;
	}

	public function monpanierAction() {
		if ($this->getRequest()->getParam('paypalVerifError')) {
			$this->view->paypalVerifError = "Votre commande n'a pas �t� prise en compte, rev�rifier vos informations";
		}

		$user_namespace = $this->getSession();

		if (isset($user_namespace->urlCurrentProduct) && !empty($user_namespace->urlCurrentProduct)) {
			$this->view->urlCurrentProduct = $user_namespace->urlCurrentProduct;
		}
        
		$this->view->title = 'Mon Panier';
		$this->view->etapeCommande = 1;
		$linksMenu = array();
		$linksMenu[0]['NAVURL'] = '/mon-panier.html';
		$linksMenu[0]['NAVNOM'] = 'Mon Panier';

		$this->view->linksMenu = $linksMenu;

		$this->saveCaddyTemp();

		$this->computeMonPanier();
        
	}

	private function saveCaddyTemp() {

		$userNamespace = $this->getSession();
		if (isset($userNamespace->myObjectCaddy) && !empty($userNamespace->myObjectCaddy)) {
			$myCaddy = $userNamespace->myObjectCaddy;
			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();

			if ($auth->hasIdentity() && isset($storage['user']) && !empty($myCaddy->items)) {
				$caddyTemp = new CaddyTemp();
				$caddyTemp->delete('USERID = '.$storage['user']['id']);

				foreach ($myCaddy->items as $item) {
					$data = array (
						'CHILDID' => $item->idChild,
						'CHILDQUANTITY' => $item->qteChild,
						'PRODUCTID' => $item->idProduit,
						'PRODUCTNOM' => $item->nom,
						'DESCSHORT' => $item->descshort,
						'NAVNOM' => $item->navnom,
						'URL' => $item->url,
						'DESIGNATION' => $item->designation,
						'USERID' => $storage['user']['id'],
						'SELECTEDOPTION' => $item->selectedOption 
					);

					$caddyTemp->insert($data);
				}
                
                if ($this->carte_fidelite_enabled) {
                    $carteFidelite = new CarteFidelite();
                    $this->view->myCaddyFideliteAvailable = $carteFidelite->getAnnoncesByAvailability($storage['user']['id']);
                    $this->view->myCaddyFideliteAllExceptCurrents = $carteFidelite->getAnnoncesByAvailabilityWithoutCurrent($storage['user']['id']);
                    $this->view->myUserFideliteInfo = $carteFidelite->getInfosByUser($storage['user']['id']);
                }
			}
		}
	}

	private function generateFacture($facture, $caddy) {
		foreach($caddy->items as $item) {
			$optionList = new OptionList();
			$productChild = new ProductChild();
			$results = $productChild->getChildsInfoByListId($item->idChild);
			foreach ($results AS $row) {
				$myItem = $caddy->getItemByIdAndOption($row['IDCHILD'], $item->selectedOption);

				if ($myItem != null) {
					$factureLine = new FactureLine();
					$factureLine->setLineInfo($row, $myItem->qteChild, $myItem->isAccessoire);

					$factureLine->item_selectedOption = $myItem->selectedOption;
						
					$factureLine->product_navnom = $this->verifyNavigationString($factureLine->product_navnom, $factureLine->product_nom, '');

					$factureLine->setPromoCaddyType(false);

					$facture->addLine($factureLine);
				}
			}
		}   
        
		$userNamespace = $this->getSession();    
        if (isset($userNamespace->myObjectCaddyFidelite) && !empty($userNamespace->myObjectCaddyFidelite)) {
            $fidelitegifts = $userNamespace->myObjectCaddyFidelite;
		        foreach($fidelitegifts->items as $item) {
			        $factureLine = new FactureLine();
			        $factureLine->setFideliteGift($item);
                    $facture->addFideliteLine($factureLine);
                }
        }
                
	}

	private function generateFactureCaddyType($facture, $caddy) {
		$userCaddyType = new UserCaddyType();
		foreach($caddy->itemsCaddyType as $item) {
			$results = $userCaddyType->getArticleByCaddyIdList($item->id);
			foreach ($results AS $row) {
				$myItem = $caddy->getItemCaddyTypeByIdChildAndOption($row['IDCHILD'], $item->selectedOption);
				if ($myItem != null && ($row['REMISEEURO'] > 0 || $row['REMISEPOUR'] > 0)) {

					$factureLine = new FactureLine();
					$factureLine->product_navnom = $this->verifyNavigationString($factureLine->product_navnom, $factureLine->product_nom, '');
					$factureLine->setLineInfo($row, $myItem->qte, 'N');
					$factureLine->caddytype_id = $myItem->id;
						
					$factureLine->item_selectedOption = $myItem->selectedOption;

					if ($row['REMISEEURO'] > 0) {
						$factureLine->remise_euro = $row['REMISEEURO'];
						$factureLine->setPromoCaddyType(true);
						$factureLine->caddytype_isActif = 'Y';
					} else if ($row['REMISEPOUR'] > 0) {
						$factureLine->remise_pour = $row['REMISEPOUR'];
						$factureLine->setPromoCaddyType(true);
						$factureLine->caddytype_isActif = 'Y';
					}

					if ($factureLine->isCaddyTypeActif()) {
						$poidsCurrent = $factureLine->getPoidsTotal();
						if ($poidsCurrent > 0) { $facture->total_poids += $poidsCurrent ;
						} else { $facture->isAncienPoids = true;  }
						if ($factureLine->isFrancoDenied()) { $facture->isFrancoDenied = true; }

						$facture->total_HT_HR += $factureLine->getPrixTotalHT(true);

						$facture->addLine($factureLine);
					}
				}
			}
		}
	}
		
	private function computeFactureGlobalByQteDegressif($myFacture) {
		$productChildQte = new ProductChildQte();
		$productChild = new ProductChild();
		foreach ($myFacture->facture_lines as $lines) {
			$result = $productChild->getChildPriceByIdChild($lines->item_id);
			$currentPrice = $productChildQte->getCurrentPrice($lines->item_id, $lines->item_qte, $result['PRIX']);
			$lines->item_prix = sprintf("%.2f",$currentPrice);
		}
	}

	public function computeMonPanier() {
		$userNamespace = $this->getSession();
		$myCaddyTemp = $userNamespace->myObjectCaddy;
		if ((isset($myCaddyTemp->items) && !empty($myCaddyTemp->items)) ||
		(isset($myCaddyTemp->itemsCaddyType) && !empty($myCaddyTemp->itemsCaddyType))) {

			$auth = Zend_Auth::getInstance();
			$auth->setStorage($this->getSessionStorage());
			$storage = $auth->getStorage()->read();
			$user = array();
			if ($auth->hasIdentity() && isset($storage['user'])) {
				$user = $storage['user'];
			}

			$myFacture_CodeReduc = array();
			if (isset($userNamespace->myFactureValidate)) {
				$myFacture = $userNamespace->myFactureValidate;
				if (isset($myFacture->code_reduction) && !empty($myFacture->code_reduction)) {
					$myFacture_CodeReduc = $myFacture->code_reduction;
				}
			}

			$myFacture = new Facture();

			$userNamespace->myFactureValidate = $myFacture;

			$resteFrancoLiv = 0;

			$this->generateFacture($myFacture, $myCaddyTemp);
			if (isset($user) && !empty($user) && $user['iscaddytype'] == 'Y') {
				//Panier Type apres le calcul des promos
				$this->generateFactureCaddyType($myFacture, $myCaddyTemp);
			}
			/*Recuperation du prix degressif*/
			$this->computeFactureGlobalByQteDegressif($myFacture);

			$myFacture->code_reduction = $myFacture_CodeReduc;

			/*
			 * CALCUL DES PROMOS
			 */
			$promo = new PromoCalculator();
			$promo->computeAllPromos($myFacture, $user);

			$resteToValid = $promo->getPrixCommandValidation($myFacture);
			if ($resteToValid > 0) {
				$this->view->isCommandValid = "Vous ne pouvez pas valider votre commande,<br/> il vous manque la somme de <b>".$resteToValid."</b> euros, pour atteindre le <b>minimum requis</b>.";
			}

			$myFacture->total_HT = $myFacture->getPrixTotalHT();

			/*
			 * MODE DE LIVRAISON
			 */

			//Calcul des frais de livraison
			$lastFraisLivEur = 0;

			$arrayLivraison = $this->computeLivraison($myFacture->total_HT);
			if (isset($arrayLivraison) && !empty($arrayLivraison)) {
				if ($myFacture->total_HT == 0) {
					$myFacture->total_frais_port = sprintf("%.2f", 0);
					$myFacture->total_frais_port_pour  = 0;
				} else {
					$myFacture->total_frais_port = $arrayLivraison['fraisLivEUR'];
					$myFacture->total_frais_port_pour  = $arrayLivraison['fraisLivPOUR'];
				}

				$lastFraisLivEur  = $arrayLivraison['francoEur'];
				$resteFrancoLiv  = $arrayLivraison['resteFrancoLiv'];
			}

			$myFacture->total_HT_FP = $myFacture->getPrixTotalHT_FP(false);
			$myFacture->total_TVA = $myFacture->getPrixTotalTVA(false);
			$myFacture->total_TTC = $myFacture->getPrixTotalTTC(false);
			$myFacture->total_remise = $myFacture->getPrixRemise();

			$myFacture->resteFrancoLiv = $resteFrancoLiv;
			if ($myFacture->resteFrancoLiv > 0) {
				$this->view->resteFrancoLiv = "Il vous reste <b>".number_format(sprintf("%.2f", $myFacture->resteFrancoLiv), 2, ',', ' ')."</b> euros, avant d'avoir le franco de port.";
			}
            
			if ($this->carte_fidelite_enabled) {
                $carteFidelite = new CarteFidelite();
                $myUserFideliteInfo = $carteFidelite->getInfosByUser($user['id']);                
                if (!$myFacture->isCarteFidelitePointsValid($myUserFideliteInfo['POINTFIDELITETOTAL'])) {
                	$this->view->isCommandValid = "Vous ne pouvez pas valider votre commande,<br/> vous n'avez pas assez de <b>points fid�lit�</b>.";
			    }
			}
            
			$userNamespace->myFactureValidate = $myFacture;
			$this->view->myFacture = $myFacture;
			$this->view->user_facture_validate = $myFacture;
            
		} else {
			$userNamespace->myFactureValidate = new Facture();
			$userNamespace->myObjectCaddy = new Caddy();
			$this->view->myFacture = $userNamespace->myFactureValidate;
			$this->view->user_facture_validate = $userNamespace->myFactureValidate;
            
		}
	}



	public function formatNumber($number) {
		return number_format($number, 2, ',', ' ');
	}

	public function getCaddyProducts($myCaddyTemp) {

		$i = 0;
		foreach($myCaddyTemp->items as $item) {
			if ($i == 0 ) {
				$stringTempP = $item->idProduit;
				$stringTempC = $item->idChild;
			} else {
				$stringTempP .= ', '.$item->idProduit;
				$stringTempC .= ', '.$item->idChild;
			}
			$i++;
		}



		$sql = "
			SELECT p.NOM NOM,p.NAVNOM NAVNOM, p.DESCRIPTIONSHORT DESCSHORT, p.ID IDPRODUCT, pic.URL URL,p.isPROMO isPROMO, pc.DESIGNATION DESIGNATION, p.STOCK STOCK,
			pc.ID IDCHILD, pc.REFERENCE REFERENCE, pc.isDEVIS isDEVIS, pc.isPROMO isPROMOCHILD, pc.PRIX PRIX, p.DATEPROMO DATEPROMO,
			p.IDCATEGORY IDCATEGORY, p.IDBREND IDBREND, p.isSHOWBREND isSHOWBREND, pc.QUANTITYMIN QUANTITYMIN, pc.POIDS POIDS, pc.isFRANCODENIED isFRANCODENIED
			FROM product p
			LEFT JOIN picture pic ON pic.IDPRODUCT = p.ID 
			LEFT JOIN productchild pc ON pc.IDPRODUCT = p.ID
			WHERE p.ID IN ( ".$stringTempP." )
			AND pc.ID IN ( ".$stringTempC." )
			AND p.isACTIVE = 0
			AND pic.POSITION = 1
			";


		$product = new Product();
		$result = $product->getAdapter()->fetchAll($sql);


		$promoProduct = new PromoProduct();
		$i = 0;

		$childRefBuy = '';
		$myTemp = array();
		foreach ($result AS $row) {

			$myItem = $myCaddyTemp->getItemById($row['IDCHILD']);

			if ($myItem != null)
			{
				$myTemp[$i]['CHILD']['isACCESSOIRE'] = $myItem->isAccessoire;

				$myTemp[$i]['CHILD']['ID'] = $row['IDCHILD'];
				$myTemp[$i]['CHILD']['REFERENCE'] = $row['REFERENCE'];
				$myTemp[$i]['CHILD']['DESIGNATION'] = $row['DESIGNATION'];
				$myTemp[$i]['CHILD']['isPROMO'] = $row['isPROMOCHILD'];
				$myTemp[$i]['CHILD']['isDEVIS'] = $row['isDEVIS'];
				$myTemp[$i]['CHILD']['POIDS'] = $row['POIDS'];
				$myTemp[$i]['CHILD']['isFRANCODENIED'] = $row['isFRANCODENIED'];
				$myTemp[$i]['CHILD']['QUANTITYMIN'] = $row['QUANTITYMIN'];
				$myTemp[$i]['CHILD']['PRIX'] = sprintf("%.2f",$row['PRIX']);
				$myTemp[$i]['CHILD']['REMISEEURO'] = 0;
				$myTemp[$i]['CHILD']['REMISEPOUR'] = 0;

				$myTemp[$i]['CHILD']['QUANTITY'] = $myItem->qteChild;

				//Insertion du code pour la gestion des promos
				$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX']);

				if ($row['isPROMOCHILD'] == 0) {
					//Produit - REFERENCE
					$myPromo = $promoProduct->fetchRow("REFERENCE = '".$row['REFERENCE']."'");
					if ($myPromo['REMISEEURO'] > 0) {
						$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX'] - $myPromo['REMISEEURO']);
					}
					if ($myPromo['REMISEPOUR'] > 0) {
						$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX'] - (($row['PRIX'] * $myPromo['REMISEPOUR']) / 100));
					}

					if ($myTemp[$i]['CHILD']['PROMOPRIX'] < 0) {
						$myTemp[$i]['CHILD']['PROMOPRIX'] = sprintf("%.2f",$row['PRIX']);
					}
				}

				if ($myTemp[$i]['CHILD']['isDEVIS'] == 0) {
					$myTemp[$i]['CHILD']['PRIX'] = 0;
					$myTemp[$i]['CHILD']['PROMOPRIX'] = 0;
				}

				$myTemp[$i]['PRODUIT']['ID'] = $row['IDPRODUCT'];
				$myTemp[$i]['PRODUIT']['NOM'] = $row['NOM'];
				$myTemp[$i]['PRODUIT']['DESCSHORT'] = $row['DESCSHORT'];
				$myTemp[$i]['PRODUIT']['isPROMO'] = $row['isPROMO'];
				$myTemp[$i]['PRODUIT']['IDBREND'] = $row['IDBREND'];
				$myTemp[$i]['PRODUIT']['isSHOWBREND'] = $row['isSHOWBREND'];
				$myTemp[$i]['PRODUIT']['IDCATEGORY'] = $row['IDCATEGORY'];
				$myTemp[$i]['PRODUIT']['DATEPROMO'] = $row['DATEPROMO'];
				$myTemp[$i]['PRODUIT']['STOCK'] = $row['STOCK'];

				$myTemp[$i]['PRODUIT']['NAVNOM'] = $this->verifyNavigationString($row['NAVNOM'], $row['NOM'], '');

				$myTemp[$i]['PRODUIT']['URL'] = $row['URL'];


				$i++;
			}
		}
		return $myTemp;

	}


	public function ajaxaddpanierAction() {
		if ($this->getRequest()->isPost('productAddForm')) {
			$params = $this->getRequest()->getPost();

			$idProduct = $params['idProd'];

			for ($i = 0; $i < $params['nbr']; $i++) {
				if (isset($params['idChild_'.$i])) {
					$idchild = $params['idChild_'.$i];

					if (isset($params['quantity_'.$idchild])) {
						$qte = intval($params['quantity_'.$idchild]);
						$quantityMin = intval($params['qtyMinChild_'.$i]);
						$isAccessoire = $params['isAccessoire_'.$i];
						$selectedOptionValue = '';
						if (isset($params['selectedOption_'.$i]) && !empty($params['selectedOption_'.$i])) {
							$selectedOptionValue = $params['selectedOption_'.$i];
						}

						if ($qte > 0) {

							$qte = $this->computeQtyMin($qte, $quantityMin);

							$this->ajouterArticle( $idchild, $qte, $isAccessoire, $selectedOptionValue);
							$this->view->messageError = '';
							$this->view->messageSuccess = "Le produit a &eacute;t&eacute; ajout&eacute; &agrave; votre panier";
						} else {
							$this->supprimerArticle($idchild, $selectedOptionValue);
							$this->view->messageSuccess = "Votre panier a &eacute;t&eacute; actualis&eacute;";
							$this->view->messageError = '';
						}
					}
				}
			}

		}
		$layout = Zend_Layout::getMvcInstance();
		$layout->disableLayout();
		$this->render();
	}

	public function ajaxcountcaddyAction() {
		$userNamespace = $this->getSession();
		$myCaddy = $userNamespace->myObjectCaddy;
		$nbArticles = 0;
		if (isset($myCaddy->items)) {
			$nbArticles=count($myCaddy->items);
		}
		if ($nbArticles > 1) {
			$this->view->messageSuccess = $nbArticles.' PRODUITS';
		} else if ($nbArticles == 0) {
			$this->view->messageSuccess = 'Aucun produit';
		} else {
			$this->view->messageSuccess = $nbArticles.' PRODUIT';
		}
		$this->_forward('ajaxvalue', 'ajax');
	}
	/*
	 * Caddy
	 *
	 */
	public function ajaxcheckcaddyAction() {
		if ($this->getRequest()->isPost('caddyCheckForm')) {
			$params = $this->getRequest()->getPost();

			if (isset($params['Child'],$params['Quantity'])) {
				$listChild = $params['Child'];
				$listQuantity = $params['Quantity'];
				$listQuantityMin = $params['QuantityMin'];
				$listAcc= $params['Accessoire'];
				$listCaddyType= $params['CaddyType'];
				$listSelectedOption= $params['selectedOption'];

				for ($i = 0; $i < sizeof($listChild); $i++) {
					if (isset($listChild[$i],$listQuantity[$i])) {
						$idchild = intval($listChild[$i]);
						$qte = intval($listQuantity[$i]);
						$quantityMin = intval($listQuantityMin[$i]);
						$isAccessoire = $listAcc[$i];
						$idCaddyType = intval($listCaddyType[$i]);
						$selectedOption = $listSelectedOption[$i];

						if ($qte > 0) {
							$qte = $this->computeQtyMin($qte, $quantityMin);

							if ($idCaddyType > 0) {
								$this->ajouterArticleCaddyType($idCaddyType, $qte, $selectedOption);
							} else {
								$this->ajouterArticle($idchild, $qte, $isAccessoire, $selectedOption);
							}
							$this->view->messageError="";
							$this->view->messageSuccess = "Votre caddy a &eacute;t&eacute; modifi&eacute;";
						} else {
							if ($idCaddyType > 0) {
								$this->supprimerArticleCaddyType($idCaddyType, $selectedOption);
							} else {
								$this->supprimerArticle($idchild, $selectedOption);
							}
						}
					}
				}
			}
		}

		$this->_forward('ajaxmessage','ajax');
	}

	private function computeQtyMin($qte, $qteMin)
	{
		$reste = $qte % $qteMin;
		$value = ($qte - $reste) / $qteMin;

		if ($reste != 0) {
			$value++;
		}
		$result = $qteMin * $value;
		return $result;
	}



	private function ajouterArticleCaddyType($idCaddyType, $qteChild, $selectedOption){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->addItemToCaddyType($idCaddyType, $qteChild, $selectedOption);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function ajouterArticle($idChild, $qteChild, $isAccessoire, $selectedOptionValue){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->addItemToCaddy($idChild, $qteChild, $isAccessoire, $selectedOptionValue);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function supprimerArticle($idChild, $selectedOptionValue){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->delItemToCaddy($idChild, $selectedOptionValue);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function supprimerArticleCaddyType($idCaddyType, $selectedOptionValue){
		try {
			$userNamespace = $this->getSession();
			if (!isset($userNamespace->myObjectCaddy)) { $userNamespace->myObjectCaddy = new Caddy(); }
			$caddy = $userNamespace->myObjectCaddy;
			$caddy->delItemToCaddyType($idCaddyType, $selectedOptionValue);
			$userNamespace->myObjectCaddy = $caddy;
		} catch (Zend_Exception $e) { $this->log($e->getMessage(), 'err'); }
	}

	private function computeProductChildsList($id, $idCat, $idBrend) {
		$myListChild = array();
		try {
			$productChild = new ProductChild();
			$productChildTemp = $productChild->getProductChildsByIdProduct($id);

			$myListChild = $this->computeProductChildsListArray($productChildTemp, $idCat, $idBrend);
		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		return $myListChild;
	}


	private function computeProductChildsListArray($productChilds, $idCat, $idBrend) {
		$myListChild = array();
		try {
			$i = -1;
			$actualChild = 0;

			$isAllPromos = false;
			$currentPromoAll = array();
			$currentPromo = array();
			$listUserCodeInternIdBrendFound = array();
			$listUserCodeInternIdBrends = array();
			$listIdBrendFound = array();
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
			$listIdBrends = array();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$promoUser = new PromoUser();

            $user = array();
            try {
			    $auth = Zend_Auth::getInstance();
			    $auth->setStorage($this->getSessionStorage());
			    $storage = $auth->getStorage()->read();
			    if ($auth->hasIdentity() && isset($storage['user'])) {
				    $user = $storage['user'];
                }
            }
            catch (Zend_Exception $e) {
                $this->log($e->getMessage(), 'err');
            }


			if (!empty($productChilds)) {
				$idCategory = $idCat;
				$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
				if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
			}

			$userNamespace = $this->getSession();
			$myCaddy = $userNamespace->myObjectCaddy;
				
			$productChildQte = new ProductChildQte();
			foreach ($productChilds as $child) {
				if ($child['ID'] != $actualChild) {
					$i++;
					/* Prix Unitaire par Quantite*/
					$myListChild[$i]['QTEPRIXITEM'] = $productChildQte->getQteByItem($child['ID']);
					$myListChild[$i]['isQTEPRIXACTIVE'] = $child['isQTEPRIXACTIVE'];
					$child['PRIX'] = $productChildQte->getCurrentPrice($child['ID'], $myCaddy->getQuantity($child['ID']), $child['PRIX']);
						
					$myListChild[$i]['ID'] = $child['ID'];
					$myListChild[$i]['PRODUCTNAVNOM'] = $this->verifyNavigationString($child['PRODUCTNAVNOM'], $child['PRODUCTNOM'], '') ;
					$myListChild[$i]['PRODUCTNOM'] = $child['PRODUCTNOM'];
					$myListChild[$i]['PRODUCTID'] = $child['PRODUCTID'];
					$myListChild[$i]['REFERENCE'] = $child['REFERENCE'];
					$myListChild[$i]['DESIGNATION'] = $child['DESIGNATION'];
					$myListChild[$i]['PRIX'] = sprintf("%.2f",$child['PRIX']);
					$myListChild[$i]['isPROMO'] = $child['isPROMO'];
					$myListChild[$i]['isDEVIS'] = $child['isDEVIS'];
					$myListChild[$i]['QUANTITYMIN'] = $child['QUANTITYMIN'];

					$myListChild[$i]['PROMOPRIX'] = '';
					if ($child['isPROMO'] == 0) {
						$myPromo = $promoProduct->fetchRow("REFERENCE = '".$child['REFERENCE']."'");
						if ($myPromo['REMISEEURO'] > 0) {
							$myListChild[$i]['PROMOPRIX'] = sprintf("%.2f",$child['PRIX'] - $myPromo['REMISEEURO']);
						}
						if ($myPromo['REMISEPOUR'] > 0) {
							$myListChild[$i]['PROMOPRIX'] = sprintf("%.2f",$child['PRIX'] - (($child['PRIX'] * $myPromo['REMISEPOUR']) / 100));
						}
						if ($myListChild[$i]['PROMOPRIX'] < 0) { $myListChild[$i]['PROMOPRIX'] = 0; }
					}

					$myListChild[$i]['IMAGEPROMO'] = $child['IMAGEPROMO'];
					$myListChild[$i]['OPTION_VALUES'] = array();
					$actualChild = $child['ID'];


					/*
					 * CALCUL PROMO
					 */

					if (!in_array($idBrend, $listIdBrends, true)) {
						$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
						array_push($listIdBrends, $idBrend);
						if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
					}
					if ($child['isPROMO'] == 1) {
						$isRemise = false;
						if (in_array($idBrend, $listIdBrends, true)) {
							foreach ($listIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend) {
									$myListChild[$i]['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
						if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
							$myListChild[$i]['isPROMO'] = 0;
							if ($currentPromoAll['REMISEEURO'] > 0) {
								$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromoAll['REMISEEURO']);
							}
							if ($currentPromoAll['REMISEPOUR'] > 0) {
								$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromoAll['REMISEPOUR']);
							}
						}
					}
					if (isset($user) && !empty($user)) {
						$userId = $user['id'];
						$codeIntern = $user['cintern'];
						$isRemise = false;

						if (!empty($codeIntern)) {
							if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
								$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
								array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
								if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
							}
							if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
								foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
									if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
										$myListChild[$i]['isPROMO'] = 0;
										$currentPromo = $brendPromos['PROMO'];
										if ($currentPromo['REMISEEURO'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromo['REMISEEURO']);
											$isRemise = true;
										}
										if ($currentPromo['REMISEPOUR'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromo['REMISEPOUR']);
											$isRemise = true;
										}
										break;
									}
								}
							}
						}
						if (!$isRemise) {
							if (!in_array($idBrend, $listUserIdBrends, true)) {
								$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
								array_push($listUserIdBrends, $idBrend);
								if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
							}
							if (in_array($idBrend, $listUserIdBrends, true)) {
								foreach ($listUserIdBrendFound as $brendPromos) {
									if ($brendPromos['ID'] == $idBrend) {
										$myListChild[$i]['isPROMO'] = 0;
										$currentPromo = $brendPromos['PROMO'];
										if ($currentPromo['REMISEEURO'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculEuro($myListChild[$i]['PRIX'], $currentPromo['REMISEEURO']);
											$isRemise = true;
										}
										if ($currentPromo['REMISEPOUR'] > 0) {
											$myListChild[$i]['PROMOPRIX'] = $promoCalculator->calculPour($myListChild[$i]['PRIX'], $currentPromo['REMISEPOUR']);
											$isRemise = true;
										}
										break;
									}
								}
							}
						}
					}
					if ($myListChild[$i]['PROMOPRIX'] < 0) { $myListChild[$i]['PROMOPRIX'] = $myListChild[$i]['PRIX']; }
				}
				$myListChild[$i]['OPTION_VALUES'][$child['OPTIONID']]['OPTIONVALUE'] = $child['OPTIONVALUE'];
				$myListChild[$i]['OPTION_VALUES'][$child['OPTIONID']]['OPTIONID'] = $child['OPTIONID'];
			}

		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(), 'err');
		}
		return $myListChild;
	}

	private function checkTypeOfPromo($id) {
		$category = new Category2();
		$firstCategory = $category->getParentFirstOf($id);
		if ($firstCategory != null) {
			$currentId = $firstCategory["ID"];
			if ($currentId == 2) { $this->view->prefixPromoClass = "eco-"; }
		}
	}

	private function computeProductDetail($id) {
		try {
			$product = new Product();

			//Get Product
			$productTemp = $product->getProductById($id);

            $currentUser = array();
            try {
                $auth = Zend_Auth::getInstance();
                $auth->setStorage($this->getSessionStorage());
                $storage = $auth->getStorage()->read();
                if ($auth->hasIdentity() && isset($storage['user'])) {
                    $currentUser = $storage['user'];
                }
            }
            catch (Zend_Exception $e) { }

			if ($productTemp) {
				//Get Picture
				$picture = new Picture();
				$productPics = $picture->getAllByIdProduct($id);

				//Produits Annexe
				$productAnnexe = new ProductAnnexe();
				$productList = $productAnnexe->getAnnexesByProductID($id, 'NOM ASC');
				$listAnnexes = $this->computeProductListToShow($productList, $currentUser);
				$this->view->listAnnexes = $listAnnexes['PRODUCTS'];

				//Produits Accessoire
				$productAccessoire = new ProductAccessoire();
				$listAccessoires = $productAccessoire->getAccessoiresOptionsByProductID($id, 'NOM ASC');

				$listAccessoireChilds = $this->computeProductChildsListArray($listAccessoires, $productTemp[0]['IDCATEGORY'], $productTemp[0]['IDBREND']);

				$myProduct = array();

				$myProduct['PRODUCT_ACCESSOIRE'] = $listAccessoireChilds;

				if ($product->isInCategorySubsidiaire($productTemp[0]['ID'], 2)) {
					$this->view->prefixPromoClass = "eco-";
				}

				$myProduct['ID'] = $productTemp[0]['ID'];
				$myProduct['NOM'] = $productTemp[0]['NOM'];

				$myProduct['NAVNOM'] = $this->verifyNavigationString( $productTemp[0]['NAVNOM'], $productTemp[0]['NOM'], "");

				$myProduct['NAVTITRE'] = $productTemp[0]['NAVTITRE'];
				$myProduct['NAVDESC'] = $productTemp[0]['NAVDESC'];

				if (empty($myProduct['NAVTITRE'])) {
					$myProduct['NAVTITRE'] = $myProduct['NOM'];
				}
				if (empty($myProduct['NAVDESC'])) {
					$myProduct['NAVDESC'] = $productTemp[0]['DESCSHORT'];
				}
				$myProduct['NAVNOM_URLPARENTS'] = $this->computeUrlNavigationParent($productTemp[0]);

				$myProduct['KEYWORDS'] = $productTemp[0]['KEYWORDS'];
				$myProduct['DESCSHORT'] = $productTemp[0]['DESCSHORT'];
				$myProduct['DESCLONG'] = $productTemp[0]['DESCLONG'];
				$myProduct['DESCNORME'] = $productTemp[0]['DESCNORME'];
				$myProduct['DESCTECH'] = $productTemp[0]['DESCTECH'];
				$myProduct['PRIX'] = sprintf("%.2f",$productTemp[0]['PRIX']);
				$myProduct['PRIXLOWEST'] = $product->calculateLowestPrice($productTemp[0]['ID']);
				$myProduct['isPROMO'] = $productTemp[0]['isPROMO'];
				$myProduct['IDCATEGORY'] = $productTemp[0]['IDCATEGORY'];
				$myProduct['CATNOM'] = $productTemp[0]['CATNOM'];
				$myProduct['CATNAVNOM'] = $productTemp[0]['CATNAVNOM'];
				$myProduct['URL'] = $productTemp[0]['URL'];
				$myProduct['BREND'] = $productTemp[0]['BREND'];
				$myProduct['IDBREND'] = $productTemp[0]['IDBREND'];
				$myProduct['isSHOWBREND'] = $productTemp[0]['isSHOWBREND'];
				$myProduct['BRENDURL'] = $productTemp[0]['BRENDURL'];
				$myProduct['isDEVISPRODUCT'] = $productTemp[0]['isDEVISPRODUCT'];
				$myProduct['DOCNAME'] = $productTemp[0]['DOCNAME'];
				$myProduct['DOCURL'] = $productTemp[0]['DOCURL'];
				$myProduct['STOCK'] = $productTemp[0]['STOCK'];
				$myProduct['isQTEPRIXACTIVE'] = $productTemp[0]['isQTEPRIXACTIVE'];
				$myProduct['BOOSTED_BESTSELLER'] = $productTemp[0]['BOOSTED_BESTSELLER'];

				$myProduct['ONSELECT_IDOPTION'] = $productTemp[0]['ONSELECT_IDOPTION'];
				if ($myProduct['ONSELECT_IDOPTION'] > 0) {
					$optionList = new OptionList();
					$myProduct['ONSELECT_OPTION'] = $optionList->getByIdProduct($myProduct['ID']);
				}

				$myProduct['LISTPICS'] = $productPics;

				$i = 0;
				$myProduct['LISTOPTION'] = array();
				foreach ($productTemp as $option) {
                    $hasOption = false;
                    foreach ($myProduct['LISTOPTION'] as $current_option) {
                        if ($current_option['IDOPTION'] == $option['IDOPTION']) {
                            $hasOption = true;
                            break;
                        }
                    }
                    if (!$hasOption) {
                        $myProduct['LISTOPTION'][$i]['NOMOPTION'] = $option['NOMOPTION'];
                        $myProduct['LISTOPTION'][$i]['IDOPTION'] = $option['IDOPTION'];
                        $i++;
                    }
				}

				$myProduct['LISTCHILD'] = $this->computeProductChildsList($id, $myProduct['IDCATEGORY'], $myProduct['IDBREND']);

				return $myProduct;
			} else { return false;}
		} catch (Zend_Exception $e) {
			$this->log("ComputeProductDetail : "+$e->getMessage(), 'err');
		}
		return false;
	}
    
    private function checkForProductRedirection($row) {
	    $link = "";
	    if(isset($row['PRODUCT_URL'])) {
		    $link = "/".$row['PRODUCT_URL'];
	    } else if (isset($row['NAVNOM'])) {
		    $link = "/".Utils_Tool::getFormattedUrlProduct($row['NAVNOM_URLPARENTS'], $row['NAVNOM'], $row['ID']);
	    } else if (isset($row['PRODNAVNOM'])){
		    $link = "/".Utils_Tool::getFormattedUrlProduct($row['NAVNOM_URLPARENTS'], $row['PRODNAVNOM'], $row['ID']);
	    } 
        if ($this->FeatureRedirectionAuto) {
            $front = Zend_Controller_Front::getInstance();
            $currentpage = $front->getRequest()->getRequestUri();
            if ($link != $currentpage) {
                $this->send301Redirection($this->baseUrl_SiteCommerceUrl.$link);
            }
        }
        $this->setCanonicalUrl($this->baseUrl_SiteCommerceUrl.$link);
    }
    private function checkForCategoryRedirection($row) {
	    $link = "/".Utils_Tool::getFormattedUrlCategory($row['NAVNOM_URLPARENTS'], $row['NAVNOM'], $row['ID']); 
        if ($this->FeatureRedirectionAuto) {
            $front = Zend_Controller_Front::getInstance();
            $currentpage = $front->getRequest()->getRequestUri();
        
            if ($link != $currentpage) {
                $this->send301Redirection($this->baseUrl_SiteCommerceUrl.$link);
            }
        }
        $this->setCanonicalUrl($this->baseUrl_SiteCommerceUrl.$link);
    }

	public function detailAction()
	{
		if ($this->getRequest()->getParam('p')) {
			$id = (int)$this->getRequest()->getParam('p');

			if ($id>0) {
                $user_namespace = null;
				try {
					$user_namespace = $this->getSession();
	            } catch (Zend_Exception $e) {  
                
                }
	
				try {				
                    $myProduct = $this->computeProductDetail($id);

					if ($myProduct) {
                    
                        $this->checkForProductRedirection($myProduct);

                        if (isset($user_namespace) && !empty($user_namespace)){
						    $user_namespace->urlCurrentProduct = $this->getRequest()->getRequestUri();

						    $user_namespace->currentProductDetail = $myProduct;
                        }

						$category = new Category();

						$breadcrumb = $category->getTreeInLineOf($myProduct['IDCATEGORY']);

						$this->view->listFTFDS = $this->getFTFDSByIdProd($id);

						$this->view->breadcrumb = $breadcrumb;
                        
                        if (isset($user_namespace) && !empty($user_namespace)){
						    $user_namespace->currentProductDetailDesign = $this->showDesign($breadcrumb[0]['ID'], $breadcrumb[0]);
						    $this->view->actualDesign = $user_namespace->currentProductDetailDesign;
                        }
						$this->view->title = $myProduct['NAVTITRE'];

						$filter = new Zend_Filter();
						$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());
						$this->view->metadescription = $filter->filter($myProduct['NAVDESC']);
						$this->view->metakeywords = $myProduct['KEYWORDS'];

						$this->view->detailProduct = $myProduct;
                                                
                        $isProductOutOfStock = false;
                        if ($myProduct['STOCK'] == 4) {
                            $isProductOutOfStock = true;
                        }
                        $this->view->isProductOutOfStock = $isProductOutOfStock; 
                        
					} else { $this->log('Le produit est introuvable : '.$this->getRequest()->getRequestUri(), 'warn'); $this->_redirect('/'); }
				} catch (Zend_Exception $e) {  $this->log($e->getMessage(), 'err'); $this->_redirect('/');  }
			} else { $this->_redirect('/');  }
		}  else { $this->_redirect('/');  }
	}


	private function isPromoActive($myPromo) {
		if ($myPromo) {
			if ($myPromo['REMISEEURO'] > 0) { return true; }
			if ($myPromo['REMISEPOUR'] > 0) { return true; }
		}
		return false;
	}


	private function computeProductListToShowOld($list, $user) {
		$i = 0;
		$j = 1;
		$isFirst = true;
		$listProducts = array();
		$metakeywords = '';

		$isAllPromos = false;
		$currentPromoAll = array();
		$currentPromo = array();
		$listUserCodeInternIdBrendFound = array();
		$listUserCodeInternIdBrends = array();
		$listIdBrendFound = array();
		$listUserIdBrendFound = array();
		$listUserIdBrends = array();
		$listIdBrends = array();
		$promoCalculator = new PromoCalculator();
		$promoProduct = new PromoProduct();
		$promoUser = new PromoUser();
 
		if (!empty($list)) {
			$idCategory = $list[0]['CATID'];
			$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
			if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
             
		}

		foreach ($list AS $row) {
			if ($j == 9 ) {
				$j = 1;
				$i++;
				$isFirst = true;
			} else {
				if (!$isFirst) {
					$j++;
				}
			}

			$listProducts[$i][$j]['ID'] = $row['ID'];
			$listProducts[$i][$j]['NOM'] = $row['NOM'];
			$listProducts[$i][$j]['DESCSHORT'] = $this->cutString($row['DESCSHORT'], 80);
			$listProducts[$i][$j]['URL'] = $row['URL'];
			$listProducts[$i][$j]['BREND'] = $row['BREND'];
			$listProducts[$i][$j]['isSHOWBREND'] = $row['isSHOWBREND'];
			$listProducts[$i][$j]['BRENDURL'] = $row['BRENDURL'];
			$listProducts[$i][$j]['NBREFERENCE'] = $row['NBREFERENCE'];
			$listProducts[$i][$j]['isDEVISPRODUCT'] = $row['isDEVISPRODUCT'];
			$listProducts[$i][$j]['BOOSTED_BESTSELLER'] = $row['BOOSTED_BESTSELLER'];

			$listProducts[$i][$j]['NAVNOM'] = $this->verifyNavigationString($row['PRODNAVNOM'], $row['NOM'], '');
			$listProducts[$i][$j]['NAVNOM_URLPARENTS'] = $row['NAVNOM_URLPARENTS'];

			$listProducts[$i][$j]['NAVTITRE'] = $row['NAVTITRE'];
			$listProducts[$i][$j]['NAVDESC'] = $row['NAVDESC'];

			$isFirst = false;

			if (empty($metakeywords)) {
				$metakeywords .= $row['KEYWORDS_PROD'];
			} else {
				$metakeywords .= ','.$row['KEYWORDS_PROD'];
			}

			$listProducts[$i][$j]['isPROMO'] = $row['isPROMO'];
			$listProducts[$i][$j]['PRIX'] = $row['PRIX'];

			/*
			 * CALCUL PROMO
			 */
			$idBrend = $row['BRENDID'];

			if (!in_array($idBrend, $listIdBrends, true)) {
				$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
				array_push($listIdBrends, $idBrend);
				if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
			}
			if ($row['isPROMO'] == 1) {
				$isRemise = false;
				if (in_array($idBrend, $listIdBrends, true)) {
					foreach ($listIdBrendFound as $brendPromos) {
						if ($brendPromos['ID'] == $idBrend) {
							$listProducts[$i][$j]['isPROMO'] = 0;
							$currentPromo = $brendPromos['PROMO'];
							if ($currentPromo['REMISEEURO'] > 0) {
								$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
								$isRemise = true;
							}
							if ($currentPromo['REMISEPOUR'] > 0) {
								$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
								$isRemise = true;
							}
							break;
						}
					}
				}
				if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
					$listProducts[$i][$j]['isPROMO'] = 0;
					if ($currentPromoAll['REMISEEURO'] > 0) {
						$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
					}
					if ($currentPromoAll['REMISEPOUR'] > 0) {
						$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
					}
				}
			}
			if (isset($user) && !empty($user)) {
				$userId = $user['id'];
				$codeIntern = $user['cintern'];
				$isRemise = false;

				if (!empty($codeIntern)) {
					if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
						$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
						array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
						if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
					}
					if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
						foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
								$listProducts[$i][$j]['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
				}
				if (!$isRemise) {
					if (!in_array($idBrend, $listUserIdBrends, true)) {
						$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
						array_push($listUserIdBrends, $idBrend);
						if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
					}
					if (in_array($idBrend, $listUserIdBrends, true)) {
						foreach ($listUserIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend) {
								$listProducts[$i][$j]['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$listProducts[$i][$j]['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
				}
			}


			if ($listProducts[$i][$j]['PRIX'] <= 0 ) { $listProducts[$i][$j]['PRIX'] = $row['PRIX']; }
		}
		return $result = array( 'PRODUCTS' => $listProducts, 'META_KEY' =>  $metakeywords);
	}
    
    private function computeUrlNavigationParent($row) {
        return $row['NAVNOM_URLPARENTS']."/".$row['CATNAVNOM'];
    }
 

	private function computeProductListToShowFromEs($user, $searchWord, $listFacets) {
		try {
            if (empty($this->FeatureElasticSearchWsdl) || empty($this->FeatureElasticSearchUsername) || empty($this->FeatureElasticSearchKey) || $this->FeatureElasticSearchEnableOnSearch == false) {
		        return array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
            }
            $facetsValues = "";
            if (!empty($listFacets)){
                $facetsValues = json_encode($listFacets);
            }
            $this->log("Elastic search => Search word : ".$searchWord. " / Facets : ".$facetsValues,'info');
             
            $result = new stdClass();
            $isCalledSucceed = false;
            try
            {     
                $soapClient = $this->getSoapClient($this->FeatureElasticSearchWsdl);
                $request = $this->getSoapHeader($this->FeatureElasticSearchUsername, $this->FeatureElasticSearchKey);
                    
                $request->SearchWord = $searchWord;
                if (!empty($listFacets)){
                    $request->Facets = $facetsValues;
                }
                
                $parameters = new stdClass();
                $parameters->request = $request;
                    
                $result = $soapClient->SearchProducts($parameters);
                
                $isCalledSucceed = true;
                $soapClient = null;   
            }
            catch (SoapFault $fault)
            {
				$this->log($fault->faultstring,'err');
            }
                
            if (!$isCalledSucceed || $result->SearchProductsResult->Total == 0) {
		        return array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
            }   
            //------------------------------------------------------
            
            $listProducts = array();  
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
		    $listIdBrends = array(); 
		    $listIdBrendFound = array();
			$promoUser = new PromoUser();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$product = new Product();
			$metakeywords = '';  
            
			$isAllPromos = false;
              
            $listOfFacets = array();
            
            if (isset($result->SearchProductsResult->Facets->ProductFacet)) {
                if (!is_array($result->SearchProductsResult->Facets->ProductFacet)) { 
                    array_push($listOfFacets, $result->SearchProductsResult->Facets->ProductFacet); 
                } else {
                    $listOfFacets = $result->SearchProductsResult->Facets->ProductFacet;
                }
            }
            
            $listOfProducts = array();
            if ($result->SearchProductsResult->Total == 1) {
                array_push($listOfProducts, $result->SearchProductsResult->Products->ProductDetail); 
            } else {
                $listOfProducts = $result->SearchProductsResult->Products->ProductDetail;
            }
            
			foreach ($listOfProducts as $row) { 
                try
                {     
				    $currentProduct = array();
				    $currentProduct['ID'] = $row->ProductId;
				    $currentProduct['NOM'] = $row->Name;
				    $currentProduct['DESCSHORT'] = $row->ShortDescription;
				    $currentProduct['PRODUCT_URL'] = $row->ProductUrl;
			  
				    $currentProduct['NAVNOM'] =  $row->MetaNavigationName; 
				    $currentProduct['NAVTITRE'] =  $row->MetaTitle;
				    $currentProduct['NAVDESC'] =  $row->MetaDescription;
                  
                    $isPromo = false; 
                    $currentPrice = 99999; 
                    if (isset($row->ProductPrice)) {
				        $currentProduct['isDEVISPRODUCT'] = !$row->ProductPrice->IsDevis;
				        $currentProduct['PRIX'] = $row->ProductPrice->Price;
				        $currentProduct['PRIXLOWEST'] = $currentProduct['PRIX'];
				        $currentProduct['isPRIXDEGRESSIF'] = $row->ProductPrice->IsDegresivePrice;
				        $currentProduct['isPROMO'] = !$row->ProductPrice->IsPromo;
                        $currentPrice = $row->ProductPrice->Price; 
                        $isPromo = $currentProduct['isPROMO'];
                    } else {
				        $currentProduct['isDEVISPRODUCT'] = "";
				        $currentProduct['PRIX'] = $currentPrice;
				        $currentProduct['PRIXLOWEST'] = $currentProduct['PRIX'];
				        $currentProduct['isPRIXDEGRESSIF'] = 0;
				        $currentProduct['isPROMO'] = 1;
                    }
					
                    if (isset($row->Category)) {
				        $currentProduct['CATID'] = $row->Category->Id;
				        $currentProduct['CATNOM'] = $row->Category->Name;
                        $currentProduct['NAVNOM_URLPARENTS'] = $row->Category->NavigationName;
                    } else {
				        $currentProduct['CATID'] = 0;
				        $currentProduct['CATNOM'] = "";
                        $currentProduct['NAVNOM_URLPARENTS'] = "";
                    }
                
                    if (isset($row->Reranking)) {
                        $currentProduct['BOOSTED_BESTSELLER'] = $row->Reranking->BestSeller; 
                    } else {
                        $currentProduct['BOOSTED_BESTSELLER'] = 99999; 
                    }
                 
				    $currentProduct['URL'] = $row->DefaultPictureUrl; 
                
				    $idBrend = 0;
                    if (isset($row->Brand)) {
				        $currentProduct['isSHOWBREND'] = !$row->Brand->IsShow;
				        $currentProduct['BREND'] = $row->Brand->Name;
				        $currentProduct['BRENDURL'] = $row->Brand->Url;
                        $idBrend = $row->Brand->Id;
                    } else {
				        $currentProduct['isSHOWBREND'] = false;
				        $currentProduct['BREND'] = "";
				        $currentProduct['BRENDURL'] = "";
                    }
				    $currentProduct['NBREFERENCE'] = $row->NbReferences;
                 
                
			        $listUserCodeInternIdBrendFound = array();
			        $listUserCodeInternIdBrends = array();
                   
				    /*
				        * CALCUL PROMO
				        */ 
                
				    if (!in_array($idBrend, $listIdBrends, true)) {
					    $myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
					    array_push($listIdBrends, $idBrend);
					    if ($this->isPromoActive($myPromo)) {
                            $isPromo = true;
                            array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); 
                        }
				    }
				    if ($isPromo) {
					    $isRemise = false;
					    if (in_array($idBrend, $listIdBrends, true)) {
						    foreach ($listIdBrendFound as $brendPromos) {
							    if ($brendPromos['ID'] == $idBrend) {
								    $currentProduct['isPROMO'] = 0;
								    $currentPromo = $brendPromos['PROMO'];
								    if ($currentPromo['REMISEEURO'] > 0) {
									    $currentProduct['PRIX'] = $promoCalculator->calculEuro($currentPrice, $currentPromo['REMISEEURO']);
									    $isRemise = true;
								    }
								    if ($currentPromo['REMISEPOUR'] > 0) {
									    $currentProduct['PRIX'] = $promoCalculator->calculPour($currentPrice, $currentPromo['REMISEPOUR']);
									    $isRemise = true;
								    }
								    break;
							    }
						    }
					    }
					    if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
						    $currentProduct['isPROMO'] = 0;
						    if ($currentPromoAll['REMISEEURO'] > 0) {
							    $currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
						    }
						    if ($currentPromoAll['REMISEPOUR'] > 0) {
							    $currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
						    }
					    }
				    }
				    if (isset($user) && !empty($user)) {
					    $userId = $user['id'];
					    $codeIntern = $user['cintern'];
					    $isRemise = false;

					    if (!empty($codeIntern)) {
						    if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							    $myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
							    array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
							    if ($this->isPromoActive($myPromo)) { 
                                    $isPromo = true;
                                    array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); 
                                }
						    }
						    if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							    foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
								    if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
									    $currentProduct['isPROMO'] = 0;
									    $currentPromo = $brendPromos['PROMO'];
									    if ($currentPromo['REMISEEURO'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculEuro($currentPrice, $currentPromo['REMISEEURO']);
										    $isRemise = true;
									    }
									    if ($currentPromo['REMISEPOUR'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculPour($currentPrice, $currentPromo['REMISEPOUR']);
										    $isRemise = true;
									    }
									    break;
								    }
							    }
						    }
					    }
					    if (!$isRemise) {
						    if (!in_array($idBrend, $listUserIdBrends, true)) {
							    $myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
							    array_push($listUserIdBrends, $idBrend);
							    if ($this->isPromoActive($myPromo)) { 
                                    $isPromo = true;
                                    array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); 
                                }
						    }
						    if (in_array($idBrend, $listUserIdBrends, true)) {
							    foreach ($listUserIdBrendFound as $brendPromos) {
								    if ($brendPromos['ID'] == $idBrend) {
									    $currentProduct['isPROMO'] = 0;
									    $currentPromo = $brendPromos['PROMO'];
									    if ($currentPromo['REMISEEURO'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculEuro($currentPrice, $currentPromo['REMISEEURO']);
										    $isRemise = true;
									    }
									    if ($currentPromo['REMISEPOUR'] > 0) {
										    $currentProduct['PRIX'] = $promoCalculator->calculPour($currentPrice, $currentPromo['REMISEPOUR']);
										    $isRemise = true;
									    }
									    break;
								    }
							    }
						    }
					    } 
                    }  
				    if ($currentProduct['PRIX'] <= 0 ) { 
                        $currentProduct['PRIX'] = $currentPrice; 
                    } 
				    $currentProduct['PRIXLOWEST'] = $product->calculateLowestPrice($currentProduct['ID']);
					
				    array_push($listProducts, $currentProduct);
                }
                catch (Zend_Exception $e)
                {
			        $this->log($e->getMessage(),'err');
                }
            } 
            
			return array( 'PRODUCTS' => $listProducts, 'FACETS' => $listOfFacets, 'META_KEY' =>  $metakeywords);
		} catch (Zend_Exception $e) {
			$this->log('computeProductListToShowFromEs : '.$e->getMessage(),'err');
		}
		return array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
    }
      
      
	private function computeProductListToShow($list, $user) {
		try {
			$listProducts = array();
			$metakeywords = '';

			$isAllPromos = false;
			$currentPromoAll = array();
			$currentPromo = array();
			$listUserCodeInternIdBrendFound = array();
			$listUserCodeInternIdBrends = array();
			$listUserIdBrendFound = array();
			$listUserIdBrends = array();
			$listIdBrends = array();
			$listIdBrendFound = array();
			$promoCalculator = new PromoCalculator();
			$promoProduct = new PromoProduct();
			$promoUser = new PromoUser();
			$product= new Product();

			if (!empty($list)) {
				$idCategory = $list[0]['CATID'];
				$myPromo = $promoProduct->getRemiseByProductCategory($idCategory);
				if ($this->isPromoActive($myPromo)) { $isAllPromos = true; $currentPromoAll = $myPromo; }
			}
			$productChildQte = new ProductChildQte();

			foreach ($list AS $row) {
				$currentProduct = array();
				$currentProduct['ID'] = $row['ID'];
				$currentProduct['NOM'] = $row['NOM'];
				$currentProduct['CATID'] = $row['CATID'];
				$currentProduct['CATNOM'] = $row['CATNOM'];
				$currentProduct['DESCSHORT'] = $row['DESCSHORT'];
				$currentProduct['URL'] = $row['URL'];
				$currentProduct['BREND'] = $row['BREND'];
				$currentProduct['isSHOWBREND'] = $row['isSHOWBREND'];
				$currentProduct['BRENDURL'] = $row['BRENDURL'];
				$currentProduct['NBREFERENCE'] = $row['NBREFERENCE'];
				$currentProduct['isDEVISPRODUCT'] = $row['isDEVISPRODUCT'];
                $currentProduct['NAVNOM_URLPARENTS'] = $this->computeUrlNavigationParent($row);
                $currentProduct['BOOSTED_BESTSELLER'] = $row['BOOSTED_BESTSELLER'];

				if (isset($row['NAVNOM'])) {
					$navnom = $row['NAVNOM'];
				} else {
					$navnom = $row['PRODNAVNOM'];
				}

				$currentProduct['NAVNOM'] = $this->verifyNavigationString($navnom, $row['NOM'], '');

				$currentProduct['NAVTITRE'] = $row['NAVTITRE'];
				$currentProduct['NAVDESC'] = $row['NAVDESC'];

				$isFirst = false;

				if (empty($metakeywords)) {
					$metakeywords .= $row['KEYWORDS_PROD'];
				} else {
					$metakeywords .= ','.$row['KEYWORDS_PROD'];
				}

				$currentProduct['isPROMO'] = $row['isPROMO'];
				$currentProduct['PRIX'] = $row['PRIX'];

				/*
				 * PRIX DEGRESSIF
				 */
				$currentProduct['isPRIXDEGRESSIF'] = $productChildQte->isPrixDegressifByProductID($row['ID']);
					
				/*
				 * CALCUL PROMO
				 */
				$idBrend = $row['BRENDID'];

				if (!in_array($idBrend, $listIdBrends, true)) {
					$myPromo = $promoProduct->getRemiseByProductBrend($idBrend);
					array_push($listIdBrends, $idBrend);
					if ($this->isPromoActive($myPromo)) { array_push($listIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
				}
				if ($row['isPROMO'] == 1) {
					$isRemise = false;
					if (in_array($idBrend, $listIdBrends, true)) {
						foreach ($listIdBrendFound as $brendPromos) {
							if ($brendPromos['ID'] == $idBrend) {
								$currentProduct['isPROMO'] = 0;
								$currentPromo = $brendPromos['PROMO'];
								if ($currentPromo['REMISEEURO'] > 0) {
									$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
									$isRemise = true;
								}
								if ($currentPromo['REMISEPOUR'] > 0) {
									$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
									$isRemise = true;
								}
								break;
							}
						}
					}
					if ($isAllPromos && !empty($currentPromoAll) && !$isRemise ) {
						$currentProduct['isPROMO'] = 0;
						if ($currentPromoAll['REMISEEURO'] > 0) {
							$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromoAll['REMISEEURO']);
						}
						if ($currentPromoAll['REMISEPOUR'] > 0) {
							$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromoAll['REMISEPOUR']);
						}
					}
				}
				if (isset($user) && !empty($user)) {
					$userId = $user['id'];
					$codeIntern = $user['cintern'];
					$isRemise = false;

					if (!empty($codeIntern)) {
						if (!in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							$myPromo = $promoUser->getRemiseByCodeInternMarque($idBrend, $codeIntern);
							array_push($listUserCodeInternIdBrends, $idBrend.'-'.$codeIntern);
							if ($this->isPromoActive($myPromo)) { array_push($listUserCodeInternIdBrendFound, array('ID' => $idBrend, 'CODE' => $codeIntern, 'PROMO' => $myPromo)); }
						}
						if (in_array($idBrend.'-'.$codeIntern, $listUserCodeInternIdBrends, true)) {
							foreach ($listUserCodeInternIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend && $brendPromos['CODE'] == $codeIntern ) {
									$currentProduct['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
					}
					if (!$isRemise) {
						if (!in_array($idBrend, $listUserIdBrends, true)) {
							$myPromo = $promoUser->getRemiseByMarque($idBrend, $userId);
							array_push($listUserIdBrends, $idBrend);
							if ($this->isPromoActive($myPromo)) { array_push($listUserIdBrendFound, array('ID' => $idBrend, 'PROMO' => $myPromo)); }
						}
						if (in_array($idBrend, $listUserIdBrends, true)) {
							foreach ($listUserIdBrendFound as $brendPromos) {
								if ($brendPromos['ID'] == $idBrend) {
									$currentProduct['isPROMO'] = 0;
									$currentPromo = $brendPromos['PROMO'];
									if ($currentPromo['REMISEEURO'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculEuro($row['PRIX'], $currentPromo['REMISEEURO']);
										$isRemise = true;
									}
									if ($currentPromo['REMISEPOUR'] > 0) {
										$currentProduct['PRIX'] = $promoCalculator->calculPour($row['PRIX'], $currentPromo['REMISEPOUR']);
										$isRemise = true;
									}
									break;
								}
							}
						}
					}
				}


				if ($currentProduct['PRIX'] <= 0 ) { $currentProduct['PRIX'] = $row['PRIX']; }
 
				$currentProduct['PRIXLOWEST'] = $product->calculateLowestPrice($currentProduct['ID']);
					
				array_push($listProducts, $currentProduct);
			}
			return $result = array( 'PRODUCTS' => $listProducts, 'META_KEY' =>  $metakeywords);
		} catch (Zend_Exception $e) {
			$this->log('ComputeProductListToShow : '.$e->getMessage(),'err');
		}
		return $result = array( 'PRODUCTS' => array(), 'META_KEY' =>  '');
	}

	private function getLastCharOf($str) { return $str{strlen($str)-1}; }

    private function ebusinessCategoryAction($id) {
         $currentUser = array();
		try {
		    $auth = Zend_Auth::getInstance();
		    $auth->setStorage($this->getSessionStorage());
		    $storage = $auth->getStorage()->read();
		    if ($auth->hasIdentity() && isset($storage['user'])) {
			    $currentUser = $storage['user'];
            }
        }
        catch (Zend_Exception $e) {
        }

        $category = new Category();
		$product = new Product();
        $productList = array();
		$listCat = array();
		$listCat = $category->getTreeCatsOfWithLevel($id, true);
                    
		if (!empty($listCat)) {
                    
            $this->checkForCategoryRedirection($listCat);
                        
			$this->view->listCat = $listCat;
			$breadcrumb = $category->getTreeInLineOf($id);
			$this->view->breadcrumb = $breadcrumb;
			$this->view->actualDesign = $this->showDesign($breadcrumb[0]['ID'], $breadcrumb[0]);

			if (empty($listCat['NAVTITRENOM'])) {
				$listCat['NAVTITRENOM'] = $listCat['NOM'];
			}
			if (empty($listCat['NAVDESCRIPTION'])) {
				$listCat['NAVDESCRIPTION'] = $listCat['DESCRIPTION'];
			}

			/* Referencement automatique
				$key = new KeyMap();
				$key->updateCatEntry($id);
				*/

			$filter = new Zend_Filter();
			$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());

			$this->view->metadescription = $filter->filter($listCat['NAVDESCRIPTION']);
			$this->view->title = $listCat['NAVTITRENOM'];
			//$isTri_metaKeyword = false;

			$annoncesleft = new AnnonceLeft();
			$this->view->listads = $annoncesleft->getAnnoncesByShow($id);
						
			if (!$listCat['SUBS']) {
				$triSql = 'BOOSTED_BESTSELLER ASC';
				switch ($this->_request->getParam('tri')) {
					case 1:
						$triSql = "PRIX ASC";
						break;
					case 2:
						$triSql = "PRIX DESC";
						break;
					case 3:
						$triSql = 'NOM ASC';
						break;
					case 4:
						$triSql = 'NOM DESC';
						break;
					case 5:
						$triSql = 'BOOSTED_BESTSELLER ASC';
						break;
										
				}
				$this->view->currentCategory =$listCat;
								
				//List of products
				$productList = $product->getProductsByIdCategory($id, $triSql);
								
				$resultProduct = $this->computeProductListToShow($productList, $currentUser);
				$this->view->listAllProducts = $resultProduct['PRODUCTS'];
                            
                if (!empty($listCat['KEYWORDS'])) {
                    $this->view->metakeywords = $listCat['KEYWORDS'];
                } else {                                
                    $this->view->metakeywords = $resultProduct['META_KEY'];
                }
								
				//Show product page
				$this->render('nosproduits');
			} else {
				$metakeywords = $listCat['KEYWORDS'];

                if (empty($metakeywords)) {
                    for ($index = 0; $index < sizeOf($listCat['SUBS']); $index++) {
                        if (empty($metakeywords)) {
                            $metakeywords .= $listCat['SUBS'][$index]['KEYWORDS'];
                        } else {
                            $metakeywords .= ','.$listCat['SUBS'][$index]['KEYWORDS'];
                        }
                    }
                }
				$this->view->metakeywords = $metakeywords;
                if ($this->FeatureProductShowBestSellerOnCategory) {
					$productList = $product->getAllProductsBestSellerByCatId($id);
					$resultProduct = $this->computeProductListToShow($productList, $currentUser);
					$this->view->listAllProductsBestSeller = $resultProduct['PRODUCTS'];
                } 
				$productList = $product->getAllTreeSubProductsByCatId($id);
				$resultProduct = $this->computeProductListToShow($productList, $currentUser);                             
				$this->view->listAllProducts = $resultProduct['PRODUCTS'];
			}
		} else {
			$this->log('Impossible de trouver la categorie : '.$this->getRequest()->getRequestUri(), 'warn');
			$this->_redirect('/');
		}
    }

    private function gallerieCategoryAction($id) {
		$annonce = new AnnonceCms(); 
        $this->view->listAllArticles = $annonce->getAnnoncesByShow($id);
        
		$annonceGallery = new AnnonceGallery(); 
        $this->view->listAllGalleries = $annonceGallery->getAnnoncesByShow($id);

        $category = new Category();  
		$currentCat = $category->fetchRow("ID = ".$id);
		
		$this->view->currentCat = $currentCat;
		
		$this->view->currentCatSubs = $category->getTreeCatsOfWithLevel($id, true);
		
		if (empty($currentCat['NAVTITRENOM'])) {
			$currentCat['NAVTITRENOM'] = $currentCat['NOM'];
		}
		if (empty($currentCat['NAVDESCRIPTION'])) {
			$currentCat['NAVDESCRIPTION'] = $currentCat['DESCRIPTION'];
		}
		$filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())->addFilter(new Zend_Filter_StringTrim());

		$this->view->title = $currentCat['NAVTITRENOM'];
		$this->view->metadescription = $filter->filter($currentCat['NAVDESCRIPTION']);  
		$this->view->metakeywords = $currentCat['KEYWORDS']; 
    }

	public function categorieAction()
	{ 
		if ($this->getRequest()->getParam('c')) {
			$id = (int)$this->getRequest()->getParam('c');

			if ($id>0) {

				try {
                    if ($this->isSiteEbusiness) {
                        $this->ebusinessCategoryAction($id);
                    } 
                    if ($this->isSiteGallery) {
                        $this->gallerieCategoryAction($id);
                    } 
				} catch (Zend_Exception $e) {
					$this->log('Erreur pour trouver : '.$this->getRequest()->getRequestUri()." ".$e->getMessage(),'err');
					$this->_redirect('/');
				}
			} else {
				$this->_redirect('/');
			}
		}  else {
			$this->_redirect('/');
		}
	}
 
	public function rechercheAction () {
        $listFacetsSelected = array(); 
		try {
			$date = new Zend_Date();
			$date_start = $date->toString('YYYY-MM-dd HH:mm:ss');

			$filter = new Zend_Filter();
			$filter->addFilter(new Zend_Filter_StringTrim())
			->addFilter(new Zend_Filter_StripTags())
			->addFilter(new Zend_Filter_StringToLower())
			->addFilter(new Zend_Filter_CustomAlnum(array('allowwhitespace' => true)));

			$keyTemp = $filter->filter($this->getRequest()->getParam('key'));
			if ($keyTemp=='Rechercher') { $keyTemp = ''; }

			$title = 'Votre s�lection';
			$linksMenu = array();

			if (strlen($keyTemp) == 0) {
				$linksMenu[0]['NAVURL'] = '/produits/recherche';
				$linksMenu[0]['NAVNOM'] = $title;

			} else {
				$title .= ' : "'.$keyTemp.'"';
				$linksMenu[0]['NAVURL'] = '/produits/recherche?key='.$keyTemp;
				$linksMenu[0]['NAVNOM'] = 'Votre s�lection : '.$keyTemp;
			}

			$this->view->linksMenu = $linksMenu;
			$this->view->title = $title;
			$this->view->searchKey = $keyTemp;

			if (!empty($keyTemp) && strlen($keyTemp) >= 2 ) {
                
                $currentUser = array();
                try {
                    $auth = Zend_Auth::getInstance();
                    $auth->setStorage($this->getSessionStorage());
                    $storage = $auth->getStorage()->read();
                    if ($auth->hasIdentity() && isset($storage['user'])) {
                        $currentUser = $storage['user'];
                    }
                }
                catch (Zend_Exception $e) { }
 
                foreach ( $this->getRequest()->getParams() as $key => $value) {
                    if (Utils_Tool::startsWith($key, "facet_") ) {
                        $keys = explode("_", $key);
                        $idFacet = $keys[1]."_".$keys[2];
                        $listFacetsSelected[$idFacet] = $value; 
                    }
                }  
                
				$resultProduct = $this->computeProductListToShowFromEs($currentUser, $keyTemp, $listFacetsSelected);
                
                if (sizeof($resultProduct['PRODUCTS']) == 0) {
                    $listFacetsSelected = array(); 
					$this->log("Alternative search => Search word : ".$keyTemp,'info');
                    $product = new Product();
				    $productList = $product->getProductsBySearch($keyTemp);
                    
				    $resultProduct = $this->computeProductListToShow($productList, $currentUser); 
                }
                
                $currentFacets = array();
                if (isset($resultProduct['FACETS']) && !empty($resultProduct['FACETS'])) {
                    $currentFacets = $resultProduct['FACETS'];
                }
				$this->view->listSearchFacets =  $currentFacets;
				$this->view->listSearchPages =  $resultProduct['PRODUCTS'];
				$this->view->nbrProd = sizeof($resultProduct['PRODUCTS']);

				try {
					$date = new Zend_Date();
					$data = array (
								'VALUE' => $keyTemp,
								'DATEEND' => $date->toString('YYYY-MM-dd HH:mm:ss'),
								'IP' => $_SERVER['REMOTE_ADDR'],
								'DATESTART' => $date_start
					);

					$statsSearch = new StatsSearch();
					$statsSearch->insert($data);
				} catch (Zend_Exception $e) {
					$this->log($e->getMessage(),'err');
				}

			} else {
				$this->view->listSearchPages = array();
				$this->view->listSearchFacets = array();
				$this->view->nbrProd = 0;
			}

		} catch (Zend_Exception $e) {
			$this->log($e->getMessage(),'err');
		}
        
        if ($this->getRequest()->isXmlHttpRequest()) {
		    $layout = Zend_Layout::getMvcInstance();
		    $layout->disableLayout();
        }
	}


	private function getFTFDSByIdProd($id) {
		$childFTFDS = new ProductChildFTFDS();
		$selectFTFDS = "SELECT pcftfds.ID_CHILD ID_CHILD ,pcftfds.URL URL
							FROM productchild_ftfds AS pcftfds 
						LEFT JOIN productchild AS pc ON pcftfds.ID_CHILD = pc.ID
						WHERE pc.IDPRODUCT = ".$id;

		$listFTFDS = $childFTFDS->getAdapter()->fetchAll($selectFTFDS);
		return $listFTFDS;
	}

	public function monpaniercleanupAction() {
		$userNamespace = $this->getSession();

		if (!isset($userNamespace->myObjectCaddy)) {
			$userNamespace->myObjectCaddy = new Caddy();
		}

		$caddy = $userNamespace->myObjectCaddy;
		$caddy->cleanUp();
		$userNamespace->myObjectCaddy = $caddy;
        $userNamespace->myObjectCaddyFidelite = new CaddyFidelite();
        
		$this->_forward('/monpaniertype');
	}

	public function monpaniertypeeditAction() {
		try {
			$linksMenu[0]['NAVURL'] = '/mon-panier-type-actualiser.html';
			$linksMenu[0]['NAVNOM'] = 'Mon Panier type';
			$this->view->linksMenu = $linksMenu;

			$this->view->title = 'Int�grer vos produits directement � votre panier';

			if ($this->isConnected()) {
				if ($this->_request->isPost()) {
					$params = $this->_request->getPost();
					if (isset($params['Child'],$params['Quantity'], $params['CaddyType'])) {
						$listChild = $params['Child'];
						$listQuantity = $params['Quantity'];
						$listQuantityMin = $params['QuantityMin'];
						$listCaddyType =  $params['CaddyType'];
						$listSelectedOption =  $params['selectedOption'];

						for ($i = 0; $i < sizeof($listChild); $i++) {
							if (isset($listChild[$i],$listQuantity[$i])) {
								$idchild = $listChild[$i];
								$qte = intval($listQuantity[$i]);
								$quantityMin = intval($listQuantityMin[$i]);
								$idCaddyType = intval($listCaddyType[$i]);
								$selectedOption = $listSelectedOption[$i];

								if ($qte > 0) {
									$qte = $this->computeQtyMin($qte, $quantityMin);
									if ($idCaddyType > 0 ) {
										$this->ajouterArticleCaddyType($idCaddyType, $qte, $selectedOption);
									} else {
										$this->ajouterArticle($idchild,$qte, 'N', $selectedOption);
									}
								} else {
									if ($idCaddyType > 0 ) {
										$this->supprimerArticleCaddyType($idCaddyType, $selectedOption);
									} else {
										$this->supprimerArticle($idchild, $selectedOption);
									}
								}
							}
						}
					}
				}
			}
		} catch (Zend_Exception $e) { $this->log($e->getMessage(),'err'); }
		$this->_redirect('/mon-panier.html');
	}

}
?>ContactController.php000060400000012352150713055030010712 0ustar00<?php

class ContactController  extends Modules_Default_Controllers_MainController
{

	public function init()
	{
		$this->view->baseUrl = $this->getBaseUrl();
	}

	public function indexAction()
	{
        $isAjaxResponse = false;
		if ($this->_request->isPost())
        {
	        $this->sendEmail();
            $isAjaxResponse = true;
        } else if (isset($_GET["required"]) || isset($_GET["type"]) || isset($_GET["value"])) {
	        $this->validateData();
            $isAjaxResponse = true;
        }

        if ($isAjaxResponse) {
		    $layout = Zend_Layout::getMvcInstance();
		    $layout->disableLayout();
		    $this->render('empty');
        }
	} 
    
    // Validates data and sending e-mail
    function sendEmail()
    {
        $filter = new Zend_Filter();
		$filter	->addFilter(new Zend_Filter_StripTags())
		->addFilter(new Zend_Filter_StringTrim());
        
		$validator = new Zend_Validate();
		$validator -> addValidator(new Zend_Validate_NotEmpty());

		$params = $this->_request->getPost();

	    $output = '';
	    $error = 0;
	    if(!$validator->isValid($params['name']))
	    {
		    $output .= '<p>Ins�rer votre nom</p>';
		    $error = 1;
	    }
        
        $validatorEmail = new Zend_Validate_EmailAddress();
        
	    if(!$validator->isValid($params['email']))
	    {
		    $output .= '<p>Ins�rer votre e-mail</p>';
		    $error = 1;
	    }
	    elseif(!$validatorEmail->isValid($params['email']))
	    {
		    $output .= '<p>Mauvais e-mail</p>';
		    $error = 1;
	    }
	
	    if(!$validator->isValid($params['message']))
	    {
		    $output .= '<p>Ins�rer votre message</p>';
		    $error = 1;
	    }
	    if($error)
	    {
		    echo '<blockquote class="error margin_1line margin_bottom_1line">'.utf8_encode($output).'</blockquote>';
	    }
	    else
	    {
			$this->trySendEmail($params, 0);
	    }
    }
	 function trySendEmail($params, $count) {
		 
		$to = $this->contact_Mail;
		$subject = "Message depuis la gallery";
		$mbody = "
		Emetteur:
		".$params['name']."
		".$params['email']."
		
		Message:
		".$params['message']."
		
		";
		try {  
			$mail = new Zend_Mail();
			$mail->setBodyHtml($mbody);
			$mail->setFrom(strip_tags($params['email']), $params['name']);
			$mail->addTo($to);
			$mail->setSubject($subject);
			$mail->send();

			echo '<blockquote class="success margin_1line margin_bottom_1line">'.utf8_encode('E-mail envoy�').'</blockquote>';
			   
		} catch (Zend_Exception $e) { 
			if ($count <= 3) {
				$count += 1; 
				$this->trySendEmail($params, $count);
			} else { 
				echo '<blockquote class="error margin_1line margin_bottom_1line">'.utf8_encode('Une erreur est survenue ... Veuillez r�essayer.').'</blockquote>';		
				$this->log($e->getMessage(),'err'); 
			}
		} 
	 }

    function validateData() {
	 
	    $required = $this->_request->getParam('required');
	    $type = $this->_request->getParam('type');
	    $value = $this->_request->getParam('value');

	    $this->validateRequired($required, $value, $type);

	    switch ($type) {
		    case 'number':
			    $this->validateNumber($value);
			    break;
		    case 'alphanum':
			    $this->validateAlphanum($value);
			    break;
		    case 'alpha':
			    $this->validateAlpha($value);
			    break;
		    case 'date':
			    $this->validateDate($value);
			    break;
		    case 'email':
			    $this->validateEmail($value);
			    break;
		    case 'url':
			    $this->validateUrl($value);
		    case 'all':
			    $this->validateAll($value);
			    break;
	    }
    }

    // The function to check if a field is required or not
    function validateRequired($required, $value, $type) {
	    if($required == "required") {

		    // Check if we got an empty value
		    if($value == "") {
			    echo "false";
			    exit();
		    }
	    } else {
		    if($value == "") {
			    echo "none";
			    exit();
		    }
	    }
    }

    // Validation of an Email Address
    function validateEmail($value) {
        $validatorEmail = new Zend_Validate_EmailAddress();        
	    if($validatorEmail->isValid($value)) {
		    echo "true";
	    } else {
		    echo "false";
	    }
    }

    // Validation of a date
    function validateDate($value) {
	    if(ereg("^(([1-9])|(0[1-9])|(1[0-2]))\/(([0-9])|([0-2][0-9])|(3[0-1]))\/(([0-9][0-9])|([1-2][0,9][0-9][0-9]))$", $value, $regs)) {
		    echo "true";
	    } else {
		    echo "false";
	    }
    }

    // Validation of an URL
    function validateUrl($value) {
	    if(ereg("^(http|https|ftp)\://[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(:[a-zA-Z0-9]*)?/?([a-zA-Z0-9\-\._\?\,\'/\\\+&amp;%\$#\=~])*[^\.\,\)\(\s]$", $value, $regs)) {
		    echo "true";
	    } else {
		    echo "false";
	    }
    }

    // Validation of characters
    function validateAlpha($value) {
	    if(ereg("^[a-zA-Z]+$", $value, $regs)) {
		    echo "true";
	    } else {
		    echo "false";
	    }
    }

    // Validation of characters and numbers
    function validateAlphanum($value) {
	    if(ereg("^[a-zA-Z0-9]+$", $value, $regs)) {
		    echo "true";
	    } else {
		    echo "false";
	    }
    }

    // Validation of numbers
    function validateNumber($value) {
	    if(ereg("^[0-9]+$", $value, $regs)) {
		    echo "true";
	    } else {
		    echo "false";
	    }
    }

    // Validation of numbers
    function validateAll($value) {
		    echo "true";
    }

}



?>