<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee/shared/field/field-op.class.php` is part of Officity.

Sushee is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with Sushee. If not, see <http://www.gnu.org/licenses/>.
*/
	require_once(dirname(__FILE__).'/include.php');

	class Sushee_FieldElementOperation extends AbstractElementOperation
	{	
		function __construct()
		{
			parent::__construct(new Sushee_FieldElement());		
		}
		
		function __destruct()
		{
			
		}
		
		/* *** */
		
		public function _create()
		{
			$result = false;
			
           	$this->element->parse($_POST);
	
           	// dependency : optional
           	if (URLParam::isNotEmpty('dependency') && 
	           	URLParam::isNotEmpty('targetModule') && 
	           	URLParam::isNotEmpty('targetID'))
           	{                
	        	$this->element->setDependencyByName(
	            	$this->fetchURLParam('dependency'), 
	               	$this->fetchURLParam('targetModule'), 
	               	$this->fetchURLParam('targetID'),
	               	$this->fetchURLParam('mode', 'reverse'), 
	               	'append'
               	);
           	}
           	else
           	{
	    		if (URLParam::isNotEmpty('dependency') || 
	            	URLParam::isNotEmpty('targetModule') || 
	            	URLParam::isNotEmpty('targetID'))
	           	{
	            	// throw exception
	                $this->fetchURLParam('dependency');
	                $this->fetchURLParam('targetModule'); 
	                $this->fetchURLParam('targetID');
	           	}
			}
			
			$this->element->setElementAttr('translate', 'true'); // automatic translation via Google
			
            // check for list import
	        if (($this->element->getInfo('TYPE') == 'list') && 
	        		($this->element->getInfo('LISTNAME') == 'new'))
	        {
	        	$list_name = $this->importCSVList($_POST['list-values']);
	        	$this->element->setInfo('LISTNAME', $list_name);
	        }
			
	        $result = $this->element->create(self::EXECUTE);   
	        if ($result === true)
	        {
	        	$this->JSON_response->set('ID', $this->element->getID());
		        //$this->element->emptyCache(true); // empty FIELD cache
	        }
	           
	        return $result;
		}
		
		public function _update()
		{
           $this->element->setID($this->fetchURLParam('ID'));            
           $this->element->parse($_POST);         

           $this->element->setElementAttr('translate', 'true'); // automatic translate via Google
           
	        // check for list import
	        if (($this->element->getInfo('TYPE') == 'list') && 
	        		($this->element->getInfo('LISTNAME') == 'new'))
	        {
	        	$list_name = $this->importCSVList($_POST['list-values']);
	        	$this->element->setInfo('LISTNAME', $list_name);
	        }
	       	        
           return $this->element->update(self::EXECUTE);
		}
		
		protected function importCSVList($csv_values)
		{
			$csv_values = trim($csv_values);
			
			// checks
            if (empty($csv_values))
            {
                $this->abort('Please provide some list values!');
            }
            
		    $lines = explode(chr(10), $csv_values);
            $l = count($lines);
            if ($l == 0)
            {
                $this->abort('Please provide some list values!');
            }
            
			list($prev_domain, $prev_list, $language_id, $label, $value) = explode(',', trim($lines[0]), 5);

            for ($i=1; $i<=$l; $i++)
            {
                $lines[$i-1] = trim($lines[$i-1]);
                list($domain, $list, $language_id, $label, $value) = explode(',', $lines[$i-1], 5);
                
                if (empty($domain) || empty($list) || empty($language_id) || empty($label) || empty($value))
            	{
            		$this->abort('Error importing list values: missing information at line '.$i.'!');
            	}
            	
                if (($domain != $prev_domain) || ($list != $prev_list))
            	{
            		$this->abort('Error importing list values: inconsistency in domain and/or list name at line '.$i.'!');
            		$prev_domain = $domain;
            		$prev_list = $list;
            	}
            }

            $result = true;
            $output_message = '';
            
            $DATABASE = $GLOBALS["generic_backoffice_db"];
            $db_connection = db_connect();
            
            for ($i=1; $i<=$l; $i++)
            {
                list($domain, $list, $language_id, $label, $value) = explode(',', $lines[$i-1], 5);
                $label = self::encode_list_value($label);
                $value = self::encode_list_value($value);
                
                $sql_query  = "INSERT INTO `$DATABASE`.`lists` (`Name` ,`Domain` ,`LanguageID` ,`Label` ,`Value`) ";
                $sql_query .= "VALUES ('$list', '$domain', '$language_id', '$label', '$value');";

                if ($db_connection->Execute($sql_query) == false)
                {
                	$result = false;
                    $output_message .= $db_connection->ErrorMsg().chr(13).chr(10);
                }
            }
            
            if ($result == false)
            {
            	$this->abort('Error importing list values: '.$output_message);
            }
            
            return $prev_list;
		}
		
	    static function encode_list_value($raw_value)
	    {
	        $value = trim($raw_value);
	        $value = utf8_To_UnicodeEntities($value);
	        //var_dump($value);
	        //die('error');
	        return $value;
	    }
	}
?>