<?php

/*
Copyright (C) sensmotdire  GnunuX http://sensmotdire.gnunux.info/dist/

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

//use pear DB
require_once 'DB.php';
require "lang-fr.php";
require "config.php";

// display error
function displayError($message)
{
	die ("<strong>$message</strong>");
}

// translate sentense with global $lang var
function translate($sentence)
{
	global $lang;
	if (isset($lang[$sentence]))
		return $lang[$sentence];
	else
		return $sentence;
}

// class to use database
class dataBase
{
	var $db;
	var $res;

	function __construct($config_dsn)
	{
		require "config.php";
		$db = new DB();
		$this->db = $db->connect($config_dsn);
		if ((new PEAR)->isError($this->db)) {
			displayError('Erreur a la connexion a la base : '
				. $this->db->getMessage());
		}
	}

	function execRequest($request)
	{
		$this->res = $this->db->query("$request");
		if ((new PEAR)->isError($this->res)) {
			displayError('Erreur a l\'execution de la requete : '
				. $this->res->getMessage());
		}
		return $this->res;
	}

	function execSearchCondAccent($what, $where, $cond, $value, $order="")
	{
                $input=mb_eregi_replace("e", "(e|é|è|ê)", $value);
                $input=mb_eregi_replace("a", "(a|â|à)", $input);
		$input=mb_eregi_replace("u", "(u|ù|û)", $input);
                $input=mb_eregi_replace("i", "(i|ï|î)", $input);
                $input=mb_eregi_replace("o", "(o|ô)", $input);
                $input=mb_eregi_replace("c", "(c|ç)", $input);

		$request = "SELECT $what FROM $where WHERE $cond REGEXP \"^$input$\"";
		if ( $order != "" ) { $request .= " ORDER BY `$order` ASC"; };
		return $this->execRequest($request);
	}
	function execSearchCond($what, $where, $cond, $value, $order="")
        {
                $request = "SELECT $what FROM $where WHERE $cond = \"$value\"";
                if ( $order != "" ) { $request .= " ORDER BY `$order` ASC"; };
                return $this->execRequest($request);
        }

	#use by complete_database.php
        function execSearchAll($what, $where, $order="")
        {
                $request = "SELECT $what FROM $where";
                if ( $order != "" ) { $request .= " ORDER BY `$order` ASC"; };
                return $this->execRequest($request);
        }

	function nextResult()
	{
		$this->res->fetchInto($row, DB_FETCHMODE_ASSOC);
		return $row;
	}

	function close()
	{
		$this->res->free();
	}
}

function removeextraspace($word)
{
	return implode(" ",array_filter(explode(" ",$word)));
}

// remove french accent
function removeaccent($word)
{
	$word=utf8_encode(utf8_decode($word));
	$word = str_ireplace("é", "e", $word);
	$word = str_ireplace("è", "e", $word);
	$word = str_ireplace("ê", "e", $word);
        $word = str_ireplace("à", "a", $word);
        $word = str_ireplace("â", "a", $word);
        $word = str_ireplace("ï", "i", $word);
        $word = str_ireplace("î", "i", $word);
        $word = str_ireplace("ô", "o", $word);
        $word = str_ireplace("ù", "u", $word);
        $word = str_ireplace("û", "u", $word);
	$word = str_ireplace("ç", "c", $word);
	$word = str_ireplace("œ", "e", $word);
	return $word;
}
function stripword($word)
{
	$word=strtolower(stripcslashes($word));
        if (!checkword($word))
        {
                $word=mb_convert_encoding($word,"UTF-8","ISO-8859-1");
                if (!checkword($word))
                        $word="";
        }
	return $word;
}

// verify if $word content other char than [a-z] accent or '
function checkword($word)
{
	$word = removeaccent($word);
	$word = mb_eregi_replace("'", "", $word);
	$word = mb_eregi_replace("-", "", $word);
	$word = mb_eregi_replace(" ", "", $word);
	$word = mb_eregi_replace(":", "", $word);
	$word = mb_eregi_replace("\*", "", $word);
	$word = mb_eregi_replace("\?", "", $word);
	if (ctype_alpha($word)) {
		return true;
	} else {
		return false;
	}
}

function display_suggest($verb)
{
	$return = "\n\t\t\t\t<div class=\"suggest\">";
//	$return .= "\n\t\t\t\t\t<form method=\"post\" action=\"send.php\">";
//	$return .= "\n\t\t\t\t\t\t<p class=\"report\">" . translate("The conjugated verbs result from a base of knowledge free and open.") . " <a href=\"#a" . $verb . "\" id=\"c" . $verb . "d\" class=\"hidden\" accesskey=\"7\">" . translate("Thank you to announce the errors or the omissions") . "</a>.</p>";
//	$return .= "\n\t\t\t\t\t\t<fieldset class=\"areasuggest\" id=\"c" . $verb . "div\">";
//	$return .= "\n\t\t\t\t\t\t\t<legend>";
//	$return .= "\n\t\t\t\t\t\t\t\t<a id=\"a" . "$verb\">" . translate("Suggestions") . "</a>";
//	$return .= "\n\t\t\t\t\t\t\t</legend>";
//	$return .= "\n\t\t\t\t\t\t\t<label>" . translate ("Mail address (optinal)") . ": <input type=\"text\" name=\"mail\" /></label><br />";
//	$return .= "\n\t\t\t\t\t\t\t<textarea cols=\"90\" rows=\"5\" name=\"texte\" id=\"c" . $verb . "divt\"></textarea>";
//	$return .= "\n\t\t\t\t\t\t\t<input type=\"hidden\" name=\"verb\" value=\"" . $verb . "\" />";
//	$return .= "\n\t\t\t\t\t\t\t<p>" . translate("Search verb") . ": $verb</p>";
//	$return .= "\n\t\t\t\t\t\t\t<input type=\"hidden\" name=\"verb64\" value=\"" . bin2hex($verb) . "\" />";
//	$return .= "\n\t\t\t\t\t\t\t<p>" . translate("Binary code") . ": " . bin2hex($verb) . "</p>";
//	$return .= "\n\t\t\t\t\t\t\t<input type=\"hidden\" name=\"uagent\" value=\"" . $_SERVER['HTTP_USER_AGENT'] . "\" />";
//	$return .= "\n\t\t\t\t\t\t\t<p>" . translate("User agent") . ": " . $_SERVER['HTTP_USER_AGENT'] . "</p>";
//	$return .= "\n\t\t\t\t\t\t\t<br /><input type=\"submit\" value=\"" . translate("Submit") . "\" />";
//	$return .= "\n\t\t\t\t\t\t</fieldset>";
//	$return .= "\n\t\t\t\t\t</form>";
	$return .= "\n\t\t\t\t</div>";
	return $return;
}

function display_close_button ()
{
	$return = '<p id="pclose"><a href="';
	if (array_key_exists('HTTP_REFERER', $_SERVER))
		$return .= $_SERVER['HTTP_REFERER'];
	else
		$return .= "index.html";
	$return .= '" id="close" accesskey="1">' . translate("Close") . '</a></p>';
	return $return;
}

// check if word begin by a vowel
function beginvowel($word, $asp="no")
{
	$word = removeaccent($word);
	$letter=$word[0];
	if ($letter == "h" and "$asp" == "")
		$letter="a";
	if ( $letter == "a" or $letter == "e" or $letter == "i" or $letter == "o" or $letter == "u" or $letter == "y")
		return true;
	else
		return false;
}

// main class
class display
{
	var $return;
	var $begin;
	var $aspirateh;
	var $conjugation;
	var $searchword;
	var $word;

	function __construct($word, $searchword)
	{
		global $config_dsn;
		// search information about $word
		$allData = new dataBase ($config_dsn);
		$allData->execSearchCond('*', 'verbsfr', 'infinitif', "$word");
		$row = $allData->nextResult();
		$this->aspirateh=$row['aspirateh'];
		$template=$row['template'];
		$this->begin = $row['base'];
		# search the conjugation
		$allData->execSearchCond('*', 'conjugationfr', 'template', "$template");

		$this->conjugation = $allData->nextResult();
		$allData->close();
		$this->return = "\n\t\t\t" . '<div class="tabbertab" id="' . $word . '">' . "\n\t\t\t\t<h2>" . translate("The verb") . " " . $row['infinitif'] . "</h2>\n\t\t\t\t\t<div class=\"verbiste\"><a href=\"#$word" . "iv\" class=\"hidden\" id=\"d$word\"><img alt=\">\" class=\"twisty\" src=\"images/twisty-down.gif\" /> Conjugaison</a><div id=\"d$word" . "iv\" class=\"conj\">";
		$allData->close();
		$this->searchword=$searchword;
		$this->word=$word;
	}

	function display_tenses($tense, $add_accent, $info)
	{
		foreach ($tense as $mod => $tensepron)
		{
			//fixme: ca ne sert plus a rien le pronom
			foreach ($tensepron as $tense => $pronouns) {
				foreach ($pronouns as $num => $pronoun) {
					$search=$mod."_".$tense."_".$num;
					if($this->conjugation != null) {
						$term_array=explode("-",$this->conjugation[$search]);
						foreach ( $term_array as $term )
							if ($term != "") {
								if ( ! isset($return2))
									$return2 = '';
								$return2 .= "\n\t\t\t\t\t\t<li>" . conjugate_verb($this->begin,$term,$this->aspirateh,$num,$tense,$mod,removeextraspace($info[1]), "", $info[0]) . "</li>";
							}
					};
				}
				if ( isset($return2)) {
					if ( ! isset($return))
						$return = '';
					$return .= "\n\t\t\t\t\t<h4>" . translate("$tense") . "</h4>\n\t\t\t\t\t<ul>$return2\n\t\t\t\t\t</ul>";
				}
				unset($return2);
			}
			if ( isset($return))
				$this->return .= "\n\t\t\t\t" . '<div class="mod">' . "\n\t\t\t\t\t<h3>" . translate("$mod") . "</h3>$return\n\t\t\t\t</div>";
			unset($return);
		}
	}

	function close ()
	{
		global $config_dsn;
		$verb=$this->word;
		$this->return .= display_suggest($verb);
		$allData = new dataBase ($config_dsn);
		$this->return .= "\n\t\t\t\t\t</div></div>";
		$allData->execSearchCond('*', 'wiktionaryfr', 'infinitive', $verb);
		$wiktionary = $allData->nextResult();
		$this->return .= display_wiktionary ($wiktionary['Definitions'], "Définitions", "def", $verb);
		$this->return .= display_wiktionary ($wiktionary['Etymologie'], 'Étymologie', 'etym', $verb);
		$this->return .= display_wiktionary ($wiktionary['Note'], 'Note', 'note', $verb);
		$this->return .= display_wiktionary ($wiktionary['Synonymes'], 'Synonymes', 'syn', $verb);
		$this->return .= display_wiktionary ($wiktionary['Antonymes'], 'Antonymes', 'ant', $verb);
		$this->return .= display_wiktionary ($wiktionary['Apparentes'], 'Apparentés', 'apr', $verb);
		$this->return .= display_wiktionary ($wiktionary['Derives'], 'Dérivés', 'der', $verb);
		$this->return .= display_wiktionary ($wiktionary['Expressions'], 'Expressions', 'exp', $verb);
		$this->return .= display_wiktionary ($wiktionary['Troponymes'], 'Troponymes', 'tropo', $verb);
		$this->return .= display_wiktionary ($wiktionary['Homophones'], 'Homophones', 'homo', $verb);
		$this->return .= display_wiktionary ($wiktionary['Prononciation'], 'Prononciation', 'pron', $verb);
		$this->return .= display_wiktionary ($wiktionary['Vocabulaire'], 'Vocabulaire', 'voc', $verb);
		$this->return .= display_wiktionary ($wiktionary['Hyponymes'], 'Hyponymes', 'hypo', $verb);
		$this->return .= display_wiktionary ($wiktionary['Paronymes'], 'Paronymes', 'paro', $verb);
		$this->return .= display_wiktionary ($wiktionary['Hyperonymes'], 'Hyperonymes', 'hyper', $verb);
		$allData->close();
		//end of the class tabbertab
		$this->return .= "\n\t\t\t\t<p class=\"report\">La conjugaison est issu de verbiste sous GNU Publique Générale GNU, le contenu issu de Wiktionnaire disponible sous GNU Free Documentation License.</p>";
		$this->return .= "\n\t\t\t</div>";
		unset ($this->begin);
		return $this->return;
	}
}

function display_wiktionary ($search, $name, $id, $verb)
{
	if ( $search != "" )
		return "\n\t\t\t" . '<div class="wiktionary"><a href="#ab' . $verb . $id . '" class="hidden" id="' . $verb . $id . '"><img alt=">"class="twisty" src="images/twisty-down.gif" /> ' . $name . '</a><div id="' . $verb . $id . 'iv" class="' . $id . '"><a id="ab' . $verb . $id . '"></a>' . $search . '<p class="report">Ces informations sont librement accessibles et modifiables sur le site wiktionnaire. <a href="http://fr.wiktionary.org/wiki/' . $verb . '">Retrouver ' . $verb . ' sur wiktionnaire</a>.</p></div></div>';
}

class display_html
{
	var $title;
	var $return;
	function __construct($title)
	{
		$this->title=$title;
                $this->return = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/2001/REC-xhtml11-20010531/DTD/xhtml11-flat.dtd">';
                $this->return .= '<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fr">';
	}

	function head()
	{
		global $URL;
		$this->return .= "\n<head>";
		$this->return .= "\n\t<title>" . $this->title . "</title>";
		$this->return .= "\n\t" . '<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />';
		$this->return .= "\n\t" . '<meta name="robots" content="index,follow" />';
		$this->return .= "\n\t" . '<meta name="description" content="' . translate("Interface in line of French conjugation sensmotdire") . '" />';
		$this->return .= "\n\t" . '<meta name="keyword" content="sensmotdire - ' . translate("the free French conjugation on line") . '" />';
		$this->return .= "\n\t" . '<meta name="author" content="GnunuX" />';
		$this->return .= "\n\t" . '<link rel="icon" type="image/png" href="images/sensmotdire.png" />';
		$this->return .= "\n\t" . '<link href="css/sensmotdire.css" rel="stylesheet" type="text/css" />';
		$this->return .= "\n\t" . '<script type="text/javascript" src="js/sensmotdire.js.php"></script>';
# pour ie		$this->return .= "\n\t" . '<script src="js/scriptaculous.js?load=effects" type="text/javascript"></script>';
		$this->return .= "\n\t" . '<link rel ="search" title="sensmotdire" type="application/opensearchdescription+xml" href="' . $URL . 'sensmotdire.xml" />';
		$this->return .= "\n\t" . '<link rel="alternate" title="rss" type="application/rss+xml" href="' . $URL . 'rss20.xml" />';
		$this->return .= "\n</head>";
	}
	function body($content,$id="")
	{
		if ($id == "")
			$this->return .= "\n<body>";
		else
			$this->return .= "\n<body id=\"$id\">";
			$this->return .= "<!--
Copyright (C) sensmotdire  GnunuX http://sensmotdire.gnunux.info/dist/

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
-->";

		$this->return .= "$content";
		$this->return .= "\n</body>";
	}
	function close()
	{
		global $acronym;
		$this->return .= "\n</html>";
		$tmp=$this->return;
		foreach ($acronym as $word => $acro)
			$tmp=mb_eregi_replace($word, "<acronym title=\"$acro\">$word</acronym>", $tmp);
		unset($this->return);
		return $tmp;
	}

}
function conjugate_verb($begin,$term,$hasp,$num,$tense,$mod,$compare,$accent="",$prono="no",$html="yes")
{
	global $tenses, $forme_prono_vowel, $forme_prono, $forme_prono_imperative;
	if (beginvowel($begin . $term, $hasp))
		$begin_by_vowel="yes";
	else
		$begin_by_vowel="no";
	$pronoun=$tenses[$mod][$tense][$num];
	$return='';
	if ($pronoun != "")
		$return="$pronoun ";

	if ($begin_by_vowel=="yes")
	{
		$tmp_forme_prono=$forme_prono_vowel[$num];
		$tmp_forme_prono_inf="s'";
	} else {
		$tmp_forme_prono=$forme_prono[$num] . " ";
		$tmp_forme_prono_inf="se ";
	}

	if ( "$prono" == "yes" and !( $mod == "imperative" or ( $mod == "participle" and $tense == "past")))
	{
		if ($mod == "infinitive" or $mod == "participle")
			$return.=$tmp_forme_prono_inf;
		else
			$return.=$tmp_forme_prono;
	} else {
		if ( "$return" == "je " )
			if ($begin_by_vowel=="yes")
				$return = "j'";
		if ( "$return" == "que je " )
			if ($begin_by_vowel=="yes")
				$return = "que j'";
	}
	if ($html == "yes")
		$term2='<span class="combined">' . $term . '</span>';
	else
		$term2=$term;
	$verb=$begin . $term2;
	if ($accent == "")
		$verb2=$begin . $term;
	else
		$verb2=removeaccent($verb) . removeaccent($term);
	if ($html == "yes" and $compare == $verb2)
		$verb="<strong>" . $verb . "</strong>";
	$verb2=$return . $verb2;
	$return .= $verb;

	if ( "$prono" == "yes" and $mod == "imperative" )
	{
		$return .= "-" . $forme_prono_imperative[$num];
		$verb2 .= "-" . $forme_prono_imperative[$num];
	}
	if ($html == "yes" and $compare == $verb2)
		$return="<strong>" . $return . "</strong>";
	return $return;
}
function is_an_infinitive_verb($word, $add_accent="no")
{
	// search informations into database 'verbsfr' the 'template' refered
	// to $word
	if ($add_accent == "yes")
		return false;
	global $config_dsn;
	$allData = new dataBase ($config_dsn);
	$allData->execSearchCond('infinitif', 'verbsfr', 'infinitif', "$word");
	$row = $allData->nextResult();
	$allData->close();
	if ($row && $row['infinitif'] != "")
		return $row['infinitif'];
	else
		return false;
}

function is_a_conjugated_verb($word, $add_accent="no")
{
	global $pronouns, $forme_prono, $forme_prono_vowel, $forme_prono_imperative, $config_dsn;
	$add_forme_prono="no";
	//remove empty array
	$word=removeextraspace($word);
	$orig_word=$word;
	$word_array=explode(" ",$word);
	$add_pronouns="";
	if ( $word_array[0] == "que" )
		array_shift($word_array);
	if ( preg_match("/^qu'/", $word_array[0] ) )
		$word_array[0]=mb_substr($word_array[0], 3);
        if ( in_array($word_array[0], $pronouns) )
        {
                array_shift($word_array);
                $add_pronouns="yes";

        } elseif ( preg_match("/^j'/", $word_array[0] ) ) {
		$add_pronouns="yes";
		$word_array[0]=mb_substr($word_array[0], 2);
	}
	if ( in_array($word_array[0], $forme_prono ) )
	{
		array_shift($word_array);
		$add_pronouns="yes";
		$add_forme_prono="yes";
	} elseif ( in_array(mb_substr($word_array[0], 0, 2), $forme_prono_vowel ) ) {
		$word_array[0]=mb_substr($word_array[0], 2);
		$add_forme_prono="yes";
		$add_pronouns="yes";
	} else {
		$tmp=explode("-", $word_array[0]);
		if (count($tmp) != "1")
		{
			if ( in_array($tmp[count($tmp)-1], $forme_prono_imperative ) )
			{
				unset ($tmp[count($tmp)-1]);
				$word_array[0]=implode("-", $tmp);
				$add_forme_prono="yes";
				$add_pronouns="yes";
			}
		}
	}
	if (!(isset($word_array[1]) and $add_pronouns == "yes"))
	{
		foreach ( $word_array as $word )
		{
			if (!$verb = is_an_infinitive_verb($word, $add_accent) or $add_pronouns == "yes")
			{
			        $allData = new dataBase ($config_dsn);
			        $allData2 = new dataBase ($config_dsn);
				for ($i = 0; $i < mb_strlen($word);$i++)
				{
					$begin = mb_substr($word, 0, $i);
					if ( $add_accent == "yes" )
					{
						$end   = removeaccent(mb_substr($word, $i));
						$allData->execSearchCondAccent('*', 'verbsfr', 'base', "$begin");
					} else {
						$end   = mb_substr($word, $i);
						$allData->execSearchCond('*', 'verbsfr', 'base', "$begin");
					}
					while ($row = $allData->nextResult())
					{
						$allData2->execSearchCond('*', 'conjugationfr', 'template', $row['template']);
						while ($tab = $allData2->nextResult())
						{
							if ( $add_accent == "yes" )
								$tab = array_map("removeaccent", $tab);
							if ( $result=preg_grep("*(-$end-)*", $tab))
								if ( $add_pronouns != "" )
								{
									foreach ($result as $mod => $num)
									{
										$mod=explode("_",$mod);
										if ($orig_word == conjugate_verb($begin, $end, $row['aspirateh'], $mod[2], $mod[1], $mod[0], "", $add_accent, $add_forme_prono, "no"))
										{
											$verbs[$row['infinitif']]=array($add_forme_prono, $orig_word);
											break;
										}
									}
								} else
									$verbs[$row['infinitif']]=array($add_forme_prono, $word);
						}
					}
				}
				$allData->close();
				$allData2->close();
			} else
				$verbs[$verb]=array($add_forme_prono, $verb);
		}
	}
	if (isset($verbs))
		return $verbs;
}


?>
