<?php

/**
 * This file is part of LEPTON Core, released under the GNU GPL
 *
 * @function		easymultilang_menu
 * @author          LEPTON Project
 * @copyright       2010-2021 LEPTON Project
 * @link            https://lepton-cms.org
 * @license         http://www.gnu.org/licenses/gpl.html
 * @license_terms   please see LICENSE and COPYING files in your package
 *
 */

// include class.secure.php to protect this file and the whole CMS!
if(!defined("SEC_FILE")){define("SEC_FILE",'/framework/class.secure.php' );}
if (defined('LEPTON_PATH')) {	
	include LEPTON_PATH.SEC_FILE;
} else {
	$oneback = "../";
	$root = $oneback;
	$level = 1;
	while (($level < 10) && (!file_exists($root.SEC_FILE))) {
		$root .= $oneback;
		$level += 1;
	}
	if (file_exists($root.SEC_FILE)) { 
		include $root.SEC_FILE;  
	} else {
		trigger_error(sprintf("[ %s ] Can't include class.secure.php!", $_SERVER['SCRIPT_NAME']), E_USER_ERROR);
	}
}
// end include class.secure.php


	/**
	 *	Function easymultilang_menu.
	 *
	 *	@param	bool returns 
	 * 			case true = a list of langauge and name
	 *			case false = generates default string 
	 *	@return	str	The generated menu HTML code	 
	 *
	 */
	function easymultilang_menu($list = false )
	{
		global $database;
		
		$langarr  = array( );
		$classarr = array( );
		
		$aPage = array();
        $sTempQuery = (defined("PAGE_ID"))
                ? "SELECT * FROM ".TABLE_PREFIX."pages WHERE `page_id` = ". PAGE_ID." "
                : "SELECT * FROM ".TABLE_PREFIX."pages WHERE `page_code` = 'home' "
                ;

        $database->execute_query(
            $sTempQuery,
            true,
            $aPage,
            false
        );	

		if (!empty($aPage))
		{
			$lang              = $aPage[ "language" ];
			$code              = $aPage[ "page_code" ];
			$langarr[ $lang ]  = "";
			$classarr[ $lang ] = "easymultilang_current";
		}
		elseif ( isset( $_SESSION[ 'LANGUAGE' ] ) && strlen( $_SESSION[ 'LANGUAGE' ] ) == 2 )
		{
			$lang = "";
			$code = "home";
		}
		else
		{
		    // L* 5.3 :: this ist not realy clear!
			$lang = ""; // dummy language for search page
			$code = "home";
		}
		
		//	in some cases (for instance multi page form) we do not want a language menu at all
		//	with page_code: 'none' we switch the language menu off
		if ( $code == "none" )
		{
			return false;
		}
		
		// 1. call home  --> all languages
		$aPageHome = array();
		$database->execute_query(
			"SELECT * FROM ".TABLE_PREFIX."pages WHERE page_code = 'home' and language = '".$lang."' ",
			true,
			$aPageHome,
			true
		);		

		if (count($aPageHome) > 0 )			
		{
			foreach ($aPageHome as $cp)
			{
				$l              = $cp[ "language" ];
				$langarr[ $l ]  = $cp[ "link" ];
				if($classarr[ $l ] != "easymultilang_current")
				{
				    $classarr[ $l ] = "easymultilang";
				}
			}
		}
		// 2. call current page and replace result
		$aCurrentPage = array();
		$database->execute_query(
			"SELECT * FROM ".TABLE_PREFIX."pages WHERE page_code = '".$code."' and language != '".$lang."' AND visibility != 'none' ",
			true,
			$aCurrentPage,
			true
		);			

		if (count($aCurrentPage) > 0 )
		{
			foreach ($aCurrentPage as $cp)
			{
				$l              = $cp[ "language" ];
				$langarr[ $l ]  = $cp[ "link" ];
				$classarr[ $l ] = "easymultilang";
			}
		}
		
		// sort array to always have the same language at the same position
		ksort( $langarr );

        // returns a blank list of items      
		if ($list === true)
		{
            $return_array = array();
			foreach ( $langarr as $key => $value )
			{	
                $real_language = $database->get_one("SELECT name FROM " . TABLE_PREFIX . "addons where type = 'language' and directory = '".$key."' ");
                $return_array[$key] = array(
                    'value'=>$value,
                    'language'=>$real_language
                );
			}		
			return $return_array;
        }
		
		// loop
		$aMenuValues = [];
		foreach ( $langarr as $key => $value )
		{
			$aResult = array();
			$database->execute_query(
				"SELECT * FROM ".TABLE_PREFIX."addons WHERE type = 'language' and directory = '".$key."' ",
				true,
				$aResult,
				false
			);					

			if (empty($aResult))
			{
				$txt  = $aResult[ "name" ];
				$link = LEPTON_URL . PAGES_DIRECTORY . $value . ".php?lang=$key";
				if (file_exists(LEPTON_PATH ."/modules/lib_lepton/flags/custom/" . strtolower( $key ) . ".png")) 
				{
					$flag = LEPTON_URL ."/modules/lib_lepton/flags/custom/" . strtolower( $key ) . ".png";
				} else {
					$flag = LEPTON_URL ."/modules/lib_lepton/flags/" . strtolower( $key ) . ".png";
				}

				$values = array(
                    'CLASS'   => $classarr[ $key ],
                    'IMG'     => $flag,
                    'TXT'     => $txt 
				);
				
				if ( $classarr[ $key ] == "easymultilang_current" )
				{
					$values[ 'ASTART' ] = '';
					$values[ 'AEND' ]   = '';
				}
				else
				{
					$values[ 'ASTART' ] = "<a href='$link' title='$txt'>";
					$values[ 'AEND' ]   = '</a>';
				}
				$aMenuValues[] = $values;
			}
		}
		
		// Aldus:: L* 4.4
		$html = "";
        $sMenuTemplateFile = LEPTON_PATH."/templates/".DEFAULT_TEMPLATE."/frontend/easymultilang/menu.lte";
		if(file_exists( $sMenuTemplateFile ))
		{
		    // use twig
		    $oTWIG = lib_twig_box::getInstance();
		    $oTWIG->registerPath( LEPTON_PATH."/templates/".DEFAULT_TEMPLATE."/frontend/easymultilang/", "easymultilang");
		    $html = $oTWIG->render(
		        "@easymultilang/menu.lte",
		        [
		            "allMenuItems" => $aMenuValues
		        ]
		    );
		    
		} else {
		    // use this template ...
		    $html_template_str = "\n<span class='{{ CLASS }}'>{{ ASTART }}<img src='{{ IMG }}' alt='{{ TXT }}' /> {{ TXT }}{{ AEND }}</span>";

		    foreach($aMenuValues as &$ref)
		    {
		        $sTempLine = $html_template_str;
		        foreach($ref as $key=>$value)
		        {
		            $sTempLine = str_replace("{{ ".$key." }}", $value, $sTempLine);
		        }
		        $html .= $sTempLine;
		    }
		}
		return $html;
	}
