<?
	include_once("/home/duane/translingo.org/includes/general.php");
	set_time_limit(3000);
        fflush(stdout);
	$projects =& new DataObject_Projects();
	$projects->memid = $user->id;
	$projects->find(false);
	while($projects->fetch())
		$proj[$projects->id] = $projects->short;

	$form = new HTML_QuickForm('frmTest', 'post');
	$form->addElement('header', 'hdrTesting', 'testing form');
	$form->addElement('select', 'project', _("Project Name").":", $proj);
	$form->addElement('select', 'fileformat', _("File Format").":", array("1" => "UTF-8", "0" => "HTML Entities"));
	$form->addElement('file', 'pofile', _(".po file").":");
	$form->addElement('submit', 'submit', _("Upload file"));

	$form->setDefaults(array("project" => intval($_GET['pid'])));

	$renderer =& new HTML_QuickForm_Renderer_ArraySmarty($smarty);
	$form->accept($renderer);
	$smarty->assign('form', $renderer->toArray());

	$process = 0;
	if($form->validate())
		$process = 1;

	if($process == 1)
	{
		$upload = new HTTP_Upload('en');
		$file = $upload->getFiles('pofile');
		if(!$file->isValid())
		{
			$process = 0;
			$smarty->assign('errmsg', _("You didn't select a file to upload."));
		}
	}

	if($process == 1)
	{
		$props = $file->getProp();
		if($props['ext'] != "po" && $props['ext'] != "pot")
		{
			$process = 0;
			$smarty->assign('errmsg', _("You didn't upload a valid .po file."));
		}
	}

	if($process == 1)
	{
		$fileformat = $form->exportValue('fileformat');
		$pid = intval($form->exportValue('project'));

                $query = "CREATE TEMPORARY TABLE `basetmp` (
				`id` int(11) NOT NULL auto_increment,
				`pid` int(11) NOT NULL default '0',
				`comment` text NOT NULL,
				`string` text NOT NULL,
				PRIMARY KEY  (`id`),
				KEY `pid` (`pid`),
				FULLTEXT KEY `string` (`string`))";
                mysqli_query($_SESSION['_config']['mysqli'], $query);
		mysqli_query($_SESSION['_config']['mysqli'], "insert into `basetmp` select * from `base` where `pid`='$pid'");

		$comments = $msgid = $msgstr = "";
		$file->setName(gmdate("U").sprintf("%05d", "1").".po");
		$filename = "/home/duane/translingo.org/pofiles/".$file->moveTo('/home/duane/translingo.org/pofiles');
		$langs =& new DataObject_Translations();
		$langs->pid = $pid;
		$langs->groupBy("language");

		if($langs->count() > 0)
			$importfiles = exportmerge($pid, $filename);

		$fp = fopen($filename, "rb");
		while(!feof($fp))
		{
			$line = trim(fgets($fp, 4096));
			if(substr($line, 0, 1) == "#")
			{
				$comments .= $line."\n";
			} 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);

				$mid[] = doit($msgid, $fileformat);

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

				$msgid = str_replace("\\n", "\\\\n", $msgid);
				$msgid = mysqli_real_escape_string($_SESSION['_config']['mysqli'], doit($msgid, $fileformat));
				$comments = mysqli_real_escape_string($_SESSION['_config']['mysqli'], doit($comments, $fileformat));
				$query = "select * from `basetmp` where `pid`='$pid' and `string`='$msgid'";
				$res = mysqli_query($_SESSION['_config']['mysqli'], $query) or die("<b>A fatal MySQL error occured</b>.\n<br>Query: " . $query . "<br />\nError: (" . mysqli_errno($_SESSION['_config']['mysqli']) . ") " . mysqli_error($_SESSION['_config']['mysqli']));
				mysqli_query($_SESSION['_config']['mysqli'], "set autocommit=0");
				if(mysqli_num_rows($res) > 0)
				{
					$res = mysqli_query($_SESSION['_config']['mysqli'], "select * from `basetmp` where `pid`='$pid' and 
							`string`='$msgid' and `comment`!='$comments'");
					if(mysqli_num_rows($res) <= 0)
					{
						$query = "update `basetmp` set `comment`='$comments' where `string`='$msgid' and `pid`='$pid'";
//						echo $query."<br>\n";
						mysqli_query($_SESSION['_config']['mysqli'], $query);
						$updated++;
					}
				} else {
					$query = "insert into `base` set `pid`='$pid', `string`='$msgid',`comment`='$comments'";
//					echo $query."<br>\n";
					mysqli_query($_SESSION['_config']['mysqli'], $query);
					$query = "insert into `basetmp` set `pid`='$pid', `id`='".mysqli_insert_id($_SESSION['_config']['mysqli'])."', `string`='$msgid',`comment`='$comments'";
//					echo $query."<br>\n";
					mysqli_query($_SESSION['_config']['mysqli'], $query);
					$new++;
				}

				$comments = $msgid = $msgstr = "";
			}
		}

		$res = mysqli_query($_SESSION['_config']['mysqli'], "select * from `basetmp` where `pid`='$pid'");
		while($base = mysqli_fetch_assoc($res))
		{
			if(array_search($base['string'], $mid))
				continue;

			$query = "delete from `base` where `id`='$base[id]'";
//			echo $query."<br>\n";
			mysqli_query($_SESSION['_config']['mysqli'], $query);
			if(!array_search($base['string'], $mid))
				$deleted++;
			else {
				$query = "insert into `base` select * from `basetmp` where `id`='$base[id]'";
//				echo $query."<br>\n";
				mysqli_query($_SESSION['_config']['mysqli'], $query);
			}
		}

		$proj =& new DataObject_Projects();
		$proj->id = $form->exportValue('project');
		$proj->modified = gmdate("Y-m-d H:i:s");
		$proj->update();

		reimportpo($form->exportValue('project'), $importfiles, $time_start);

		mysqli_query($_SESSION['_config']['mysqli'], "commit");

		$smarty->assign('new', intval($new));
		$smarty->assign('updated', intval($updated));
		$smarty->assign('deleted', intval($deleted));

	        $smarty->display('lheader.tpl');
        	$smarty->display('okupload.tpl');

		$res=mysqli_query($_SESSION['_config']['mysqli'], "select notifyemail from projects where id='$pid'");
	        while($emails = mysqli_fetch_assoc($res))
                {
			if($emails['notifyemail']!="" && $new>0)
			{
				echo "Sending email to ".$emails['notifyemail']."<br/>";			
				mail($emails['notifyemail'], "[TransLingo.org] New translations", "New texts have been uploaded now that need to be translated.", "From: support@translingo.org\nReply-To: support@translingo.org");
			}

		}

        	$smarty->display('lfooter.tpl');

		exit;
	}

        $smarty->display('lheader.tpl');
        $smarty->display('upload.tpl');
        $smarty->display('lfooter.tpl');
?>