<?php

/**
  * Language class, Language.php
  * Languages management
  * @category classes
  *
  * @author PrestaShop <support@prestashop.com>
  * @copyright PrestaShop
  * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
  * @version 1.0
  *
  */

class		Language extends ObjectModel
{
	public 		$id;
	
	/** @var string Name */
	public 		$name;
	
	/** @var string 2 letters iso code */
	public 		$iso_code;
	
	/** @var boolean Status */
	public 		$active = true;
	
	protected 	$fieldsRequired = array('name', 'iso_code');
	protected 	$fieldsSize = array('name' => 32, 'iso_code' => 3);
	protected 	$fieldsValidate = array('name' => 'isGenericName', 'iso_code' => 'isLanguageIsoCode', 'active' => 'isBool');
	
	protected 	$table = 'lang';
	protected 	$identifier = 'id_lang';
	
	/** @var array Languages cache */
	private static $_LANGUAGES;

	public function getFields()
	{
		parent::validateFields();
		
		$fields['name'] = pSQL($this->name);
		$fields['iso_code'] = pSQL(strtolower($this->iso_code));
		$fields['active'] = intval($this->active);
		
		return $fields;
	}
	
	public function add($autodate = true, $nullValues = false)
	{
		if (!parent::add($autodate))
			return false;
			
		$result2 = Db::getInstance()->ExecuteS('SELECT * FROM `'._DB_PREFIX_.'tab_lang` WHERE `id_lang` = '.intval(Configuration::get('PS_LANG_DEFAULT')));
		$query = 'INSERT INTO `'._DB_PREFIX_.'tab_lang` VALUES ';
		foreach ($result2 AS $row2)
		{
			$query .= '(';
			$row2['id_lang'] = $this->id;
			foreach ($row2 AS $field)
				$query .= '\''.pSQL($field, true).'\',';
			$query = rtrim($query, ',').'),';
		}
		$query = rtrim($query, ',');
		return Db::getInstance()->Execute($query);
	}
	
	public function delete()
	{
		$mailTemplates = false;
		$result = Db::getInstance()->ExecuteS('SHOW TABLES FROM `'._DB_NAME_.'`');
		/* Database translations deletion */
		foreach ($result AS $row)
			if (preg_match('/_lang/', $row['Tables_in_'._DB_NAME_]))
				if (!Db::getInstance()->Execute('DELETE FROM `'.$row['Tables_in_'._DB_NAME_].'` WHERE `id_lang` = '.intval($this->id)))
					return false;
		/* Translation's file deletion */
		unlink(_PS_TRANSLATIONS_DIR_.$this->iso_code.'/admin.php');
		unlink(_PS_TRANSLATIONS_DIR_.$this->iso_code.'/errors.php');
		unlink(_PS_TRANSLATIONS_DIR_.$this->iso_code.'/fields.php');
		unlink(_PS_TRANSLATIONS_DIR_.$this->iso_code.'/modules.php');
		rmdir(_PS_TRANSLATIONS_DIR_.$this->iso_code);
		/* Theme translation's file deletion */
		unlink(_PS_THEME_DIR_.'lang/'.$this->iso_code.'.php');
		/* Mail template deletion */
		if (file_exists(_PS_MAIL_DIR_.$this->iso_code))
			$mailTemplates = scandir(_PS_MAIL_DIR_.$this->iso_code);
		if ($mailTemplates)
		{
			foreach ($mailTemplates AS $file)
				if ($file != '.' AND $file != '..')
				unlink(_PS_MAIL_DIR_.$this->iso_code.'/'.$file);
			rmdir(_PS_MAIL_DIR_.$this->iso_code);
		}
		/* "No picture" deletion */
		unlink(_PS_PROD_IMG_DIR_.$this->iso_code.'-default-small.jpg');
		unlink(_PS_PROD_IMG_DIR_.$this->iso_code.'-default-medium.jpg');
		unlink(_PS_PROD_IMG_DIR_.$this->iso_code.'-default-large.jpg');
		return parent::delete();
	}
	
	/**
	  * Return available languages
	  *
	  * @return array Languages
	  */
	static public function getLanguages($active = true)
	{
		$languages = array();
		foreach (self::$_LANGUAGES AS $language)
			if (!$active OR ($active AND intval($language['active'])))
				$languages[] = $language;
		return $languages;
	}

	static public function getLanguage($id_lang)
	{
		if (!array_key_exists(intval($id_lang), self::$_LANGUAGES))
			return false;
		return self::$_LANGUAGES[intval($id_lang)];
	}

	/**
	  * Return iso code from id
	  *
	  * @param integer $id_lang Language ID
	  * @return string Iso code
	  */
	static public function getIsoById($id_lang)
	{
		if (isset(self::$_LANGUAGES[intval($id_lang)]['iso_code']))
			return self::$_LANGUAGES[intval($id_lang)]['iso_code'];
		return false;
	}
	
	/**
	  * Return id from iso code
	  *
	  * @param string $iso_code Iso code
	  * @return integer Language ID
	  */
	static public function getIdByIso($iso_code)
	{
	 	if (!Validate::isLanguageIsoCode($iso_code))
	 		die(Tools::displayError());

		$result = Db::getInstance()->getRow('
		SELECT `id_lang`
		FROM `'._DB_PREFIX_.'lang`
		WHERE `iso_code` = \''.pSQL(strtolower($iso_code)).'\'');
		if (isset($result['id_lang']))
			return intval($result['id_lang']);
	}

	/**
	  * Return array (id_lang, iso_code)
	  *
	  * @param string $iso_code Iso code
	  * @return array  Language (id_lang, iso_code)
	  */
	static public function getIsoIds() 
	{
		$result = Db::getInstance()->ExecuteS('
		SELECT `id_lang`, `iso_code`
		FROM `'._DB_PREFIX_.'lang`');

		return $result;
	}
	
	static public function copyLanguageData($from, $to)
	{
		$result = Db::getInstance()->ExecuteS('SHOW TABLES FROM `'._DB_NAME_.'`');
		foreach ($result AS $row)
			if (preg_match('/_lang/', $row['Tables_in_'._DB_NAME_]) AND $row['Tables_in_'._DB_NAME_] != _DB_PREFIX_.'lang')
			{
				$result2 = Db::getInstance()->ExecuteS('SELECT * FROM `'.$row['Tables_in_'._DB_NAME_].'` WHERE `id_lang` = '.intval($from));
				if (!sizeof($result2))
					continue;
				Db::getInstance()->Execute('DELETE FROM `'.$row['Tables_in_'._DB_NAME_].'` WHERE `id_lang` = '.intval($to));
				$query = 'INSERT INTO `'.$row['Tables_in_'._DB_NAME_].'` VALUES ';
				foreach ($result2 AS $row2)
				{
					$query .= '(';
					$row2['id_lang'] = $to;
					foreach ($row2 AS $field)
						$query .= '\''.pSQL($field, true).'\',';
					$query = rtrim($query, ',').'),';
				}
				$query = rtrim($query, ',');
				Db::getInstance()->Execute($query);
			}
		return true;
	}
	
	static public function createItemsList($fromLang, $fromTheme, $toLang = false, $toTheme = false)
	{
		$number = -1;
		$items = array();
		$modules = Module::getModulesDirOnDisk();
		$copy = ($toLang AND $toTheme) ? true : false;
		
		if (!$toLang OR $fromLang != $toLang)
		{
			// commons items (/translations/)
			$commons = getDirContent(_PS_TRANSLATIONS_DIR_.$fromLang);
			foreach ($commons as $item)
				$items[_PS_TRANSLATIONS_DIR_.$fromLang.'/'.$item] = ($copy ? _PS_TRANSLATIONS_DIR_.$toLang.'/'.$item : ++$number);
			
			// modules items (/modules/module_name/)
			foreach ($modules as $item)
			{
				$dir = _PS_MODULE_DIR_.$item.'/';
				if (file_exists($dir.$fromLang.'.php'))
					$items[$dir.$fromLang.'.php'] = ($copy ? $dir.$toLang.'.php' : ++$number);
			}
			
			// emails items (/mails/)
			$emails = getDirContent(_PS_MAIL_DIR_.$fromLang);
			foreach ($emails as $item)
				$items[_PS_MAIL_DIR_.$fromLang.'/'.$item] = ($copy ? _PS_MAIL_DIR_.$toLang.'/'.$item : ++$number);
		}

		// theme front items (/themes/theme_name/lang/)
		if (file_exists(_PS_ALL_THEMES_DIR_.$fromTheme.'/lang/'.$fromLang.'.php'))
		{
			$destLang = ($toLang ? $toLang : $fromLang);
			$items[_PS_ALL_THEMES_DIR_.$fromTheme.'/lang/'.$fromLang.'.php'] = ($copy ? _PS_ALL_THEMES_DIR_.$toTheme.'/lang/'.$destLang.'.php' : ++$number);
		}
		
		// theme modules items (/themes/theme_name/modules/module_name/)
		foreach ($modules as $item)
		{
			$dir = _PS_ALL_THEMES_DIR_.$fromTheme.'/modules/'.$item.'/';
			$destDir = ($copy) ? _PS_ALL_THEMES_DIR_.$toTheme.'/modules/'.$item.'/'.$toLang : false;
			if (file_exists($dir.$fromLang.'.php'))
				$items[$dir.$fromLang.'.php'] = ($destDir ? $destDir.'.php' : ++$number);
		}
		
		return $items;
	}
	
	/**
	  * Load all languages in memory for caching
	  */
	static public function loadLanguages()
	{
		self::$_LANGUAGES = array();
		$result = Db::getInstance()->ExecuteS('SELECT `id_lang`, `name`, `iso_code`, `active` FROM `'._DB_PREFIX_.'lang`');
		foreach ($result AS $row)
			self::$_LANGUAGES[intval($row['id_lang'])] = array('id_lang' => intval($row['id_lang']), 'name' => $row['name'], 'iso_code' => $row['iso_code'], 'active' => intval($row['active']));
	}
}

?>