<?php
/* $Id: lang.inc.php,v 1.28 2003/11/27 15:51:12 k-fish Exp $ */

if (!defined('ROOTPATH')) die("This is a library.");

class Lang{

    function Lang(){
    }

    // =====================================================
    // auto assign the language file into the smarty
    // context, also assign some additional files
    // which are in each page (navigation and footer...)
    // RETURNS ALL keys and values of Language file in Hash
    // =====================================================
    function setLocaledText($language, $module, $s='') {
	global $smarty, $hashmap, $appconf, $myEnv;
	$language = ($language=="login") ? $appconf["def_language"] : trim($language);

	// allways do navigation, footer, general translation
	// do not do general if the user is already in general module (see below)
	$navi = Lang::readLanguageFile($language, "_navi", "general");
	$footer = Lang::readLanguageFile($language, "_footer", "general");
	if($module != "general")
	    $general = Lang::readLanguageFile($language, "general", "general");

	// module language file
	if (!isset($myEnv["translate_module"]) or $myEnv["translate_module"]==true)
      $module = Lang::readLanguageFile($language, $module, $s);

	if($module != "settings")
	    $settings = Lang::readLanguageFile($language, 'settings', 'settings');
	else
	    $settings = array();

	if(isset($general))
	    $hashmap = array_merge($settings, $module, $navi, $footer, $general );
	else
	    $hashmap = array_merge($settings, $module, $navi, $footer);

	// this will go away, always use $hashmap.xyz in templates!
	$smarty->assign($hashmap);
	// this is the 'official way' to localize templates!
	$smarty->assign("hashmap",$hashmap);
    }

    function cleanCacheFiles(){
	$dir = opendir(CACHE_FOLDER . "/../");
	while (($fn = readdir($dir)) !== false) {
	    if(strpos($fn, ".lang.bin")>0){
		unlink(CACHE_FOLDER.'/../'.$fn);
	    }
	}
	closedir($dir);
    }
	
    function _writeCacheFile($language, $filename, $module, $data){
	if(SETUP_RUNNING or !is_writable(CACHE_FOLDER))
	    return false;

	$fn = CACHE_FOLDER."../$language.$filename.$module.lang.bin";
	$fp = fopen($fn, 'wb');
	fwrite($fp,serialize($data));
	fclose($fp);

	return true;
    }

    function _readCacheFile($language, $filename, $module){
	$fn = CACHE_FOLDER."../$language.$filename.$module.lang.bin";
	if(is_readable($fn) && @filemtime(ROOTPATH."/modules/$module/lang/$module.$language.lang") <= @filemtime($fn)){
	    $GLOBALS['log']->message(MGW_INFO, "Using language cache for: $module", __LINE__, __FILE__);
	    $fp = fopen($fn, 'rb');
	    $hashtable = fread($fp, unserialize(fread($fp, filesize($fn))));
	    fclose($fp);
	    return $hashtable;
	}

	$GLOBALS['log']->message(MGW_INFO, "Not using language cache for: $module", __LINE__, __FILE__);
	return false;
    }

    // =====================================================
    // Parser for reading in the language file
    // see the language development guide for
    // details how to define the language file
    // =====================================================
    function readLanguageFile($language, $filename, $module='') {
	global $myEnv, $appconf;
	$language= ($language=="login") ? $appconf["def_language"] : trim($language);
	$module = ($module == '') ? $myEnv['module'] : $module;

	if($hashtable = Lang::_readCacheFile($language, $filename, $module))
	    return $hashtable;

	$fn = ROOTPATH . "/modules/$module/lang/$filename.$language.lang";

	if (!file_exists($fn)){
	    $GLOBALS['log']->message(MGW_ERROR, "Language file: $fn not found!", __LINE__, __FILE__);
	    $fn = ROOTPATH."/modules/$module/lang/$filename.en.lang";
	}

	$fp = fopen($fn, "r");
	if($fp) {
	    while (!feof ($fp)) {
		$buffer = fgets($fp, 4096);
		if(trim($buffer)!='' && $buffer{0} != '#') {
		    $arr1 = split ("=", $buffer, 2);
		    if(strstr($buffer,'=')) {
			$key = trim($arr1[0]);
			$val = trim($arr1[1]);
			$hashtable["$key"]=$val;
		    }
		    else {
			$val .= ' '.trim($arr1[0]);
			$hashtable["$key"]=$val;
		    }
		}
	    }
	}
	fclose ($fp);
	Lang::_writeCacheFile($language, $filename, $module, $hashtable);
	return $hashtable;
    }

    // =====================================================
    // A function for parameter based strings
    // You can pass the string (which you got most likely
    // from the language file) and an array with parameters.
    // Then the vars in the string will be replaced with
    // the paramters in the array (see language dev. guide) 
    // =====================================================
    function getParmLang($string, $parmarray) {
	// add one empty array element at first position because of naming conventions
	// in detail: in your language file you start with <$1> and not <$0>
	array_unshift($parmarray, "");

	return preg_replace("/<\\$([0-9])>/e", '$parmarray[\1]', $string);
    }
	
    // 15-01-2002 12:21, rabol : <srabol@mail.tele.dk>
    // function to get a string from the current language, 
    // or a string telling you that the string is missing
    function getLanguageString($string){
	global $hashmap, $myEnv;

	if(isset($hashmap[$string])) {
	    return $hashmap[$string];
	} else {
	    if(SETUP_RUNNING || LANG_DEBUG) { //only true during setup
		$filename = ROOTPATH."/" . "missing.".$_SESSION['SETUP']['lang'].".lang";
		$missing = $myEnv["module"]." -> ".$string;
		if(file_exists($filename)) {
		    $fp = fopen($filename,"rb");
		    $content = fread($fp, filesize($filename));
		    $pos = strpos($content,$missing);
		    if($pos === false) {
			fclose($fp);
			$fp = fopen($filename,"a+");
			fputs($fp,$missing."\n");
			fclose($fp);
		    }	 
		} else {
		    $fp = fopen($filename,"w+");
		    fputs($fp,$missing."\n");
		    fclose($fp);
		}
	    }
	}
	return "* " . $string . " * ";
    }
}
?>
