<?
//	ini_set('display_errors','On');
//	error_reporting(E_ALL);

	foreach($_REQUEST as $key => $val)
		$$key = $val;

	include_once('/usr/share/php/Auth.php');
	include_once('/usr/share/php/HTTP/Upload.php');
	include_once('/usr/share/php/smarty/Smarty.class.php');
	include_once('/usr/share/php/HTML/QuickForm/Renderer/ArraySmarty.php');
	include_once('/usr/share/php/HTML/QuickForm.php');
	include_once('/usr/share/php/DB/DataObject/FormBuilder.php');
	
	include_once('/home/duane/translingo.org/includes/Base.php');
	include_once('/home/duane/translingo.org/includes/Languages.php');
	include_once('/home/duane/translingo.org/includes/Projects.php');
	include_once('/home/duane/translingo.org/includes/Revisions.php');
	include_once('/home/duane/translingo.org/includes/Trans.php');
	include_once('/home/duane/translingo.org/includes/Translations.php');
	include_once('/home/duane/translingo.org/includes/Users.php');
	include_once('/home/duane/translingo.org/includes/Watch.php');

	include_once('/home/duane/translingo.org/includes/customauth.php');

	session_name("auth");
	session_start();

	session_register("_config");

	$dbser = parse_ini_file('/home/duane/translingo.org/includes/db.ini', true);
	foreach ($dbser as $class => $values) {
		$options = &PEAR::getStaticProperty($class, 'options');
	 	$options = $values;
	}

	$_SESSION['_config']['filepath'] = "/home/duane/translingo.org";

	$_SESSION['_config']['mysqli'] = mysqli_connect('', 'translingo', 'translingo', 'translingo', 3306, '/var/run/mysqld/mysqld.sock');
	$displang = '';
	if(isset($_GET['displang']))
	        $displang = mysqli_real_escape_string($_SESSION['_config']['mysqli'], substr(trim($_GET['displang']), 0, 5));
        if($displang != '')
                $_SESSION['_config']['language'] = $displang;

        $_SESSION['_config']['translations'] = array(
				"ar" => "&#1575;&#1604;&#1593;&#1585;&#1576;&#1610;&#1577; (ar_JO)",
				"ar_SY" => "&#1575;&#1604;&#1593;&#1585;&#1576;&#1610;&#1577; (ar_SY)",
				"bg_BG" => "&#1041;&#1098;&#1083;&#1075;&#1072;&#1088;&#1089;&#1082;&#1080;",
				"cs_CZ" => "&#268;e&scaron;tina",
                                "de_DE" => "Deutsch",
                                "en_AU" => "English",
				"es_ES" => "Espa&ntilde;ol",
				"fi_FI" => "Suomi",
                                "fr_FR" => "Fran&#xe7;ais",
				"pl_PL" => "Polski");

        if(!isset($_SESSION['_config']['language']))
        {
                $bits = explode(",", strtolower(str_replace(" ", "", $_SERVER['HTTP_ACCEPT_LANGUAGE'])));
                foreach($bits as $lang)
                {
                        $b = explode(";", $lang);
                        if(isset($b[1]) && substr($b[1], 0, 2) == "q=")
                                $c = floatval(substr($b[1], 2));
                        else
                                $c = 1;
                        $value["$c"] = trim($b[0]);
                }

                krsort($value);

                reset($value);

                foreach($value as $key => $val)
                {
                        $short = substr($val, 0, 2);
                        if($val == "en" || $short == "en")
                        {
                                $_SESSION['_config']['language'] = "en";
                                break;
                        }
                        if(file_exists($_SESSION['_config']['filepath']."/locale/$val/LC_MESSAGES/messages.mo"))
                        {
                                $_SESSION['_config']['language'] = $val;
                                break;
                        }
                        if(file_exists($_SESSION['_config']['filepath']."/locale/$short/LC_MESSAGES/messages.mo"))
                        {
                                $_SESSION['_config']['language'] = $short;
                                break;
                        }
                }
	}

        if(strlen($_SESSION['_config']['language']) != 5)
       	{
               	$lang = $_SESSION['_config']['language'];
                $_SESSION['_config']['language'] = "en_AU";
       	        foreach($_SESSION['_config']['translations'] as $key => $val)
               	{
                       	if(substr($lang, 0, 2) == substr($key, 0, 2))
                       	{
                               	$_SESSION['_config']['language'] = $val;
                                break;
                        }
                }
        }

        putenv("LANG=".$_SESSION['_config']['language']);
        setlocale(LC_ALL, $_SESSION['_config']['language'].".utf-8");
        $domain = 'messages';
        bindtextdomain("$domain", $_SESSION['_config']['filepath']."/locale");
        textdomain("$domain");

	$lang =& new DataObject_Languages();
	$lang->find(false);
	while($lang->fetch())
	{
		$lang2 = clone($lang);
		if($lang2->long == "")
		{
			$language[] = array("short" => $lang2->short, "long" => $lang2->short);
			$languages[$lang->short] = $lang->short;
		} else {
			$language[] = array("short" => $lang2->short, "long" => xmlentities($lang2->long));
			$languages[$lang->short] = xmlentities($lang->long);
		}
	}

	$baseurl = "http://www.translingo.org";
	$smarty = new Smarty;
	$smarty->assign('language', $language);
	$smarty->register_block('t', 'duane_translate');
	$smarty->template_dir = "/home/duane/translingo.org/templates";
	$smarty->compile_dir = "/home/duane/translingo.org/templates_c";
	$smarty->assign("baseurl", $baseurl);
	$smarty->assign("titledefault", _("Welcome to")." TransLingo.org");
	$smarty->assign("gmdate", gmdate("Y-m-d H:i:s"));

	$auth_container = new CustomAuthContainer(NULL);
	$auth = new Auth($auth_container, NULL, "loginFunction", false);
	$auth->start();

	if(isset($action) && $action == "logout")
	{
		$auth->logout();
		$auth->start();
		header("location: index.php");
		exit;
	}

	if($auth->getAuth())
	{
		$user =& $auth_container->getUser($auth->getUsername());
		if($user == false)
		{
			$_SESSION['_config']['errmsg'] = _("The email and/or password you entered were incorrect.");
			$auth->logout();
			$auth->start();
		} elseif($_POST['return']) {
			if($user->pid <= 0)
				header("location: main.php");
			else
				header("location: project.php?pid=$user->pid");
			exit;
		}
	}

	if($auth->getAuth() && strstr($_SERVER["PHP_SELF"], "login.php"))
	{
		if($user->pid <= 0)
			header("location: main.php");
		else
			header("location: project.php?pid=$user->pid");
		exit;
	}

	if(!$auth->getAuth() && !(strstr($_SERVER["PHP_SELF"], "index.php")||strstr($_SERVER["PHP_SELF"],"contact.php")) && !strstr($_SERVER["PHP_SELF"], "signup.php") &&
					!strstr($_SERVER["PHP_SELF"], "login.php") && $runningscript != 1 && 
					!strstr($_SERVER["PHP_SELF"], "verify.php") && !strstr($_SERVER["PHP_SELF"], "export2.php"))
	{
		header("location: login.php");
		exit;
	}

	$smarty->assign("access", $user->access);

	if($auth->getAuth())
		$smarty->assign("auth", $auth->getAuth());

	if($user->access > 0)
		$smarty->assign("access", $user->access);

	$bits = explode("-", trim(basename($_SERVER["PHP_SELF"])));
	if(!strstr($bits[0], ".php"))
		$smarty->assign('explode', $bits[0]);

	function microtime_float()
	{
		list($usec, $sec) = explode(" ", microtime());
		return ((float)$usec + (float)$sec);
	}

	function doit($string, $fileformat = 1)
	{
		if($fileformat == 1)
		{
			$newstring = xmlentities(stripslashes($string));
			if(strstr($newstring, "&amp;#"))
				$newstring = stripslashes($string);
		} else {
				$newstring = stripslashes($string);
		}
		$newstring = str_replace("{em}", "<em>", str_replace("{/em}", "</em>", $newstring));
		$newstring = str_replace("[em]", "<em>", str_replace("[/em]", "</em>", $newstring));
		$newstring = str_replace("{strong}", "<strong>", str_replace("{/strong}", "</strong>", $newstring));
		$newstring = str_replace("[strong]", "<strong>", str_replace("[/strong]", "</strong>", $newstring));

		return($newstring);
	}

	function xmlentities2($string, $format = 0)
	{
		// UTF-8 or HTML Entities in, ISO-8859-5 out?
//		if($format == 1)
//			$string = recode("html..utf-8", $string);
//		return(recode("iso-8859-5..html", $string));

		$str = $string;
		if($format == 1)
			$str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
		$str = htmlentities($str, ENT_NOQUOTES, 'ISO-8859-5');
		return($str);
	}
	function xmlentities($string, $format = 0)
	{
		// old - $str = recode("html..utf-8", $str);
		// new - $utf8_text = html_entity_decode( $text, ENT_QUOTES, "UTF-8" );
		$str = $string;
		if($format == 1)
			$str = html_entity_decode($str, ENT_NOQUOTES, 'UTF-8');
		$str = htmlentities($str, ENT_NOQUOTES, 'UTF-8');
		return($str);
	}

	function exportmerge($pid, $filename)
	{
		$files = array();

		$proj =& new DataObject_Projects();
		$proj->id = $pid;
		$proj->find(false);
		$proj->fetch();

		$langs =& new DataObject_Translations();
		$langs->pid = $pid;
		$langs->groupBy("language");
		$langs->find(false);
		while($langs->fetch())
		{
			$outfilename = "/home/duane/translingo.org/pofiles/".gmdate("U").sprintf("%05d", "1")."-".$langs->language.".po";
			$files[$langs->language] = $outfilename;
			$fp = fopen($outfilename, "w");
			fputs($fp, "# translation of messages.po to $langs->language.po\n");
			fputs($fp, "# This file is distributed under the same license as the PACKAGE package.\n");
			fputs($fp, "# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER.\n\n");
			fputs($fp, "msgid \"\"\n");
			fputs($fp, "msgstr \"\"\n");
			fputs($fp, "\"Project-Id-Version: de\\n\"\n");
			fputs($fp, "\"Report-Msgid-Bugs-To: \\n\"\n");
			fputs($fp, "\"POT-Creation-Date: $proj->created+0000\\n\"\n");
			fputs($fp, "\"PO-Revision-Date: ".gmdate("Y-m-d H:i:s")."+0000\\n\"\n");
			fputs($fp, "\"Last-Translator: Someone <someone@someisp.com>\\n\"\n");
			fputs($fp, "\"Language-Team:  <de@li.org>\\n\"\n");
			fputs($fp, "\"MIME-Version: 1.0\\n\"\n");
			fputs($fp, "\"Content-Type: text/plain; charset=UTF-8\\n\"\n");
			fputs($fp, "\"Content-Transfer-Encoding: 8bit\\n\"\n");
			fputs($fp, "\"X-Generator: http://www.TransLingo.org\\n\"\n");

			$query = "select * from `basetmp` where `pid`='$pid'";
			$bres = mysqli_query($_SESSION['_config']['mysqli'], $query)
					or die("<b>A fatal MySQL error occured</b>.\n<br />Query: ".$query.
						"<br />\nError: (".mysqli_errno().") ".mysqli_error());
			while($base = mysqli_fetch_assoc($bres))
			{
				$base['string'] = recode("html..utf-8", $base['string']);
				$res = mysqli_query($_SESSION['_config']['mysqli'], "select * from `translations`
						where `pid`='$pid' and `baseid`='".$base['id']."' and
							`language`='{$langs->language}'");
				$row = mysqli_fetch_assoc($res);
				mysqli_free_result($res);
				fputs($fp, "\n");
				fputs($fp, $base['comment']);
				fputs($fp, "msgid \"");
				if(strstr($base['string'], "\n"))
					fputs($fp, "\"\n\"");
				fputs($fp, str_replace("\n", "\"\n\"", stripslashes($base['string']))."\"\n");
				fputs($fp, "msgstr \"");
				if(strstr($row['string'], "\n"))
					fputs($fp, "\"\n\"");
				fputs($fp, str_replace("\n", "\"\n\"", stripslashes($row['string']))."\"\n");
			}
			mysqli_free_result($bres);
			fclose($fp);
		}

		foreach($files as $lang => $file)
			echo `/usr/bin/msgmerge -U --no-wrap '$file' '$filename'`;

		return($files);
	}

	function reimportpo($pid, $files, $time_start)
	{
		global $user;

		$proj =& new DataObject_Projects();
		$proj->id = $pid;
		$proj->find(false);
		$proj->fetch();

		$langs =& new DataObject_Trans();
		$langs->whereAdd("`pid` = '$pid'");
		$langs->delete(DB_DATAOBJECT_WHEREADD_ONLY);

		if(is_array($files))
		foreach($files as $lang => $file)
		{
			$fuzzy = 0;
			$comments = $msgid = $msgstr = "";
			$fp = fopen($file, "rb");
			while(!feof($fp))
			{
				$line = trim(fgets($fp, 4096));
				if(substr($line, 0, 1) == "#")
				{
					$comments .= $line."\n";
					if(strstr($comments, ", fuzzy"))
						$fuzzy = 1;
				} elseif(substr($line, 0, 5) == "msgid") {
					$last = "msgid";
					$msgid .= $line."\n";
				} elseif(substr($line, 0, 6) == "msgstr") {
					$last = "msgstr";
					$msgstr .= $line."\n";
				} elseif($line != "") {
					if($last == "msgid")
						$msgid .= $line."\n";
					else
						$msgstr .= $line."\n";
				}

				if($line == "" && $msgid != "")
				{
					$msgid = str_replace("msgid \"", "", $msgid);
					$msgid = str_replace("\"\n", "\n", $msgid);
					$msgid = str_replace("\n\"", "\n", $msgid);
					$msgid = str_replace("\n", "", $msgid);
					$msgid = trim($msgid);

					$msgstr = str_replace("msgstr \"", "", $msgstr);
					$msgstr = str_replace("\"\n", "\n", $msgstr);
					$msgstr = str_replace("\n\"", "\n", $msgstr);
					$msgstr = str_replace("\n", "", $msgstr);
					$msgstr = trim($msgstr);

					if($msgid == "" || $msgstr == "")
					{
						$fuzzy = 0;
						$comments = $msgid = $msgstr = "";
						continue;
					}

					$msgid = str_replace("\\n", "\\\\n", $msgid);
					$msgstr = str_replace("\\n", "\\\\n", $msgstr);
					$query = "select `id` from `basetmp` where `pid`='$pid' and `string`='".addslashes(xmlentities(stripslashes($msgid)))."'";
					$res = mysqli_query($_SESSION['_config']['mysqli'], $query);
					if(mysqli_num_rows($res) > 0)
					{
						$total++;
						$row = mysqli_fetch_assoc($res);
						$baseid = $row['id'];
						$query = "select * from `translations` where `pid`='$pid' and `baseid`='$baseid' and `language`='$lang' and `string`='".mysqli_escape_string($_SESSION['_config']['mysqli'],$msgstr)."'";
						$res = mysqli_query($_SESSION['_config']['mysqli'], $query);
						if(mysqli_num_rows($res) == 0)
						{
							$query = "select * from `translations` where `pid`='$pid' and `baseid`='$baseid' and `language`='$lang'";
//							echo $query."<br>\n";
							$res = mysqli_query($_SESSION['_config']['mysqli'], $query);
							if(mysqli_num_rows($res) == 0)
							{
								$query = "insert into `translations` set `pid`='$pid', `baseid`='$baseid', `language`='$lang', `revision`='".gmdate("Y-m-d H:i:s")."', `memid`='{$user->id}', `fuzzy`='$fuzzy', `string`='".mysqli_escape_string($_SESSION['_config']['mysqli'],$msgstr)."'";
								$new++;
							} else {
								$query = "update `translations` set `revision`='".gmdate("Y-m-d H:i:s")."', `memid`='{$user->id}', `fuzzy`='$fuzzy', `string`='".mysqli_escape_string($_SESSION['_config']['mysqli'],$msgstr)."' where `pid`='$pid' and `baseid`='$baseid' and `language`='$lang'";
								$updated++;
							}
//							echo $query."<br>\n";
							mysqli_query($_SESSION['_config']['mysqli'], $query);
						}
					}
					mysqli_free_result($res);
					$fuzzy = 0;
					$comments = $msgid = $msgstr = "";
				}
			}
		}
	}

	function babelfish($str, $lang)
	{
		$newstr = urlencode($str);
		$lang = substr($lang, 0, 2);
		$body = "doit=done&intl=1&tt=urltext&trtext=$newstr&lp=en_$lang";
		$header = "POST /tr HTTP/1.1\r\n".
				"Host: babelfish.altavista.com\r\n".
				"User-Agent: Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.7.8) Gecko/20050608 Firefox/1.0.4 (Ubuntu package 1.0.4)\r\n".
				"Accept-Language: en-us,en;q=0.5\r\n".
				"Accept-Charset: utf-8;q=0.8,*;q=0.7\r\n".
				"Referer: http://babelfish.altavista.com/\r\n".
				"Content-Type: application/x-www-form-urlencoded\r\n".
				"Content-Length: ".strlen($body)."\r\n\r\n".$body;
		$fp = fsockopen("babelfish.altavista.com", 80, $errno, $errstr, 30);
		if (!$fp) {
			return($str);
		}
		fputs($fp, $header);
		while(!feof($fp))
		{
			$line = trim(fgets($fp, 4096));

			if($line == "<!-- Target text (content) -->")
				$start = 1;
			if($start == 0)
				continue;
			if($line == "<!-- end: Target text (content) -->")
				break;
			$lines .= $line." ";
		}

		$lines = strip_tags($lines, "<div>");
		list($junk, $lines) = explode("<div style=padding:10px;>", $lines, 2);
		list($lines, $junk) = explode("</div>", $lines, 2);

		if(trim($lines) != "")
			$str = trim($lines);

		return($str);
	}

	function duane_translate($params, $text, &$smarty)
	{
		return _($text);
//		die;
	}
?>