<?php
/*
Officity - Web application platform - Version 6.0 - 2011-07-05

François Dispaux, Boris Verdeyen, Thomas Hermant,
Jérémie Roy, Grégory Meurice, Abdelila Harbi, 
Marc Mignonsin, Jonathan Sanchez, Julien Gonzalez, Pierre Fouchez

Sushee and Officity is © Copyright 2011 Nectil SA.

`/sushee-source/sushee/Library/updates/20090312-stats-v4/resources/common_functionsTEMP.inc.php` is part of Officity.

Sushee 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 3 of the License, or
(at your option) any later version.

Officity and Sushee are distributed in the hope that they 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 Sushee. If not, see <http://www.gnu.org/licenses/>.
*/ 

error_reporting(E_ERROR | /*E_WARNING |*/ E_PARSE);
ini_set('session.gc_maxlifetime',86400);
ini_set('default_charset','UTF-8');
//ini_set("memory_limit","64M");
function isNectilMaster($url){
	$nectil_master = $GLOBALS["NectilMasterURL"];
	if(substr($nectil_master,0,4)=='www.')
		$nectil_master_alternative = substr($nectil_master,4);
	else
		$nectil_master_alternative = 'www.'.$nectil_master;
	$ok = false;
	
	if ($url==$GLOBALS['SusheeProtocol'].$nectil_master || $url==$GLOBALS['SusheeProtocol']."127.0.0.1" || $url==$GLOBALS['SusheeProtocol']."localhost" )
		$ok = true;
	if($nectil_master_alternative!='' && $url==$GLOBALS['SusheeProtocol'].$nectil_master_alternative )
		$ok = true;
	if(isset($GLOBALS["NectilMasterURL2"]) && $GLOBALS["NectilMasterURL2"]!='' && $ok===false){
		$nectil_master2_array = explode(',',$GLOBALS["NectilMasterURL2"]);
		foreach($nectil_master2_array as $nectil_master2){
			if($url==$GLOBALS['SusheeProtocol'].$nectil_master2)
				$ok = true;
			if($ok === false){
				if(substr($nectil_master2,0,4)=='www.')
					$nectil_master2_alternative = substr($nectil_master2,4);
				else
					$nectil_master2_alternative = 'www.'.$nectil_master2;
				if($nectil_master2_alternative!='' && $url==$GLOBALS['SusheeProtocol'].$nectil_master2_alternative)
					$ok = true;
			}
		}
	}
	return $ok;
}
function startTimer(){
	$GLOBALS["time_start"] = getmicrotime();
	$GLOBALS["steps"]=0;
	$GLOBALS["last_step"]= $GLOBALS["time_start"];
}
function chmod_Nectil($target_location){
	//global $directoryCHMOD;
	error_reporting(E_ERROR /*| E_WARNING*/ | E_PARSE);
	if(is_dir($target_location))
		$directoryCHMOD=0777;
	else
		$directoryCHMOD=0666;
	$old_umask = umask(0);
	chmod($target_location,$directoryCHMOD);
	umask($old_umask);
}
//start timer for performance counting
startTimer();
function getTimer($verbose=FALSE){
	$time_end = getmicrotime();
    $time_elapsed = $time_end - $GLOBALS["time_start"];
	if (isset($GLOBALS["last_step"]))
		$since_last_step = $time_end - $GLOBALS["last_step"];
	else
		$since_last_step = $time_elapsed;
	$GLOBALS["steps"]++;
	$GLOBALS["last_step"]=$time_end;
	if ($verbose)
		return $since_last_step;
		//return "(".$GLOBALS["steps"].") <b>".round($time_elapsed)."sec.</b> +".(($since_last_step>0.6)?"<span style='color:red;'>".$since_last_step."</span>":$since_last_step)."<br/>";
	else
		return $time_elapsed;
}
function redirect($redirect){
	header("HTTP/1.1 301 Moved Permanently");
	header ('location: '.$redirect);
	header("Connection: close");
	exit();
}

function formatMailAdress($address, $comment = false) {

    $address = trim($address);
    $comment = trim($comment);

    return $comment ? '"' . $comment . '" <' . $address . '>' : $address;
 }
function sendMail($recipient_email,$subject,$body="",$sender="Nectil",$sender_email="info@nectil.com",$headers=""){
	if (getServerOS()=='windows')
		$crlf = "\r\n";
	else
		$crlf = "\n";
	if($sender_email!="")
		$headers.="From: \"".str_replace("\"","'",$sender)."\" <$sender_email>".$crlf;
	$headers .= "MIME-Version: 1.0".$crlf;
	//$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
	mail($recipient_email,$subject,$body,$headers);
}

function sendHTMLMail($sender,$sender_mail,$recipient,$recipient_email,$subject,$html,$text_alt='',$file=''){
	include_once(dirname(__FILE__).'/../common/Mail/mime.php');
	if (getServerOS()=='windows')
		$crlf = "\r\n";
	else
		$crlf = "\n";
	$mime = new Mail_mime($crlf);
	if($text_alt){
		$mime->setTXTBody(UnicodeEntities_To_utf8($text_alt));
	}else if($html){
		$mime->setTXTBody(generatePlainTextFromHTML($html));
	}
	if($html)
		$mime->setHTMLBody($html);
	if($file){
		$attachment = $GLOBALS["directoryRoot"].$file;
		if(is_file($attachment)){
			$mime->addAttachment($attachment);
		}
	}
	$message = $mime->get(array("text_charset"=>"utf-8","head_charset"=>"utf-8","html_charset"=>"utf-8"));
	$real_from = formatMailAdress($sender_mail,$sender);
	$hdrs = array(
		  'From'    => $real_from,
		  'return-path' => $real_from,
		  'errors-to' => $real_from,
		  'bounces-to' => $real_from
		  );
	$mime_headers_array = $mime->headers($hdrs);
	$headers = $mime->txtHeaders();
	$to = formatMailAdress($recipient_email,$recipient);
	$headers_array = $mime->_encodeHeaders(array('To'=>UnicodeEntities_To_utf8($to),'Subject'=>UnicodeEntities_To_utf8($subject)));
	$res = mail($headers_array['To'],$headers_array['Subject'], $message, $headers);
	return $res;
}

function xslt_error_handler($handler, $errno, $level, $info){
	$args = func_get_args();
	$infos = $args[3];
	$copy = array();
	foreach($infos as $key => $value){
		//echo $key." is ".$value."<br/>";
		$copy[$key]=$value;
	}
	
	
	if (substr($copy["URI"],0,7)=="file://")
		$copy["URI"]=substr($copy["URI"],7);
	$xsl_str = file_in_string($copy["URI"]);
	$xsl_str = str_replace("\r\n","\n",$xsl_str);
	$xsl_lines = explode("\n",$xsl_str);
	
	echo "<html>";
	echo "<head><title>".ucfirst($copy["msg"])."</title></head>";
	echo "<body>";
	echo "<h1>".ucfirst($copy["msg"])."</h1>";
	echo "<p style='font-size:110%;'>You have an error on line <strong>".$copy["line"]."</strong><br/> in file <span style:'text-decoration:underline;'>".$copy["URI"]."</span></p>";
	
	echo "<p style='line-height:18px;padding:5px;margin-left:20px;background-color:lightgrey;'>";
	echo "<code>".encode_to_XML($xsl_lines[$copy["line"]-2])."<br/><span style='color:red;'>".encode_to_XML($xsl_lines[$copy["line"]-1])."</span><br/>".encode_to_XML($xsl_lines[$copy["line"]])."</code></p>";
	if ($copy["code"]==2)
		echo "<p style='padding:5px;margin-left:20px;background-color:lightyellow;'><strong>Hint: </strong> Try to use the native characters instead. <ul><li> &amp;eacute; becomes &#233; <small style='color:grey;'>(or &amp;#233;)</small> </li><li>&amp;nbsp; becomes &amp;#160;</li></ul></p>";
		//&#160;
	echo "</body>";
	echo "</html>";
	die();
}
function getServerOS(){
	$uname= php_uname();
	if (strtoupper(substr($uname, 0, 3))=="WIN")
		return "windows";
	else if(strtoupper(substr($uname, 0, 5))=="LINUX")
		return "linux";
	else
		return "other";
}
function generateID($params){
	if (!is_array($params))
		$params=array($params);
	$total='';
	foreach($params as $elem){
		if (is_array($elem))
			$elem=implode('',$elem);
		$total.=$elem;
	}
	return md5($total);
}



function flash_query($stringofXML){
	$output_xml = FALSE;
	$stringofXML = utf8_decode(utf8_To_UnicodeEntities($stringofXML));
	//require(dirname(__FILE__)."/../private/request.php");
	require_once(dirname(__FILE__)."/../private/request_function.inc.php");
	$strRet = request($stringofXML);
	return $strRet;
}
function query($stringofXML="",$navigation=TRUE,$restrict_language=TRUE,$public=TRUE,$supp_params=TRUE,$no_response_node=false,$priority_language=false){

	// --- reajusting language if changed ---
	if(isset($_GET['language']) && $_GET['language'] != $GLOBALS['NectilLanguage'])
		$GLOBALS['NectilLanguage'] = $_GET['language'];

	if(!isset($GLOBALS['stats_saved']) && $GLOBALS['no_stats']!==true){
		$userAgent=$_SERVER['HTTP_USER_AGENT'];
		$ip=$_SERVER['REMOTE_ADDR'];
		$host=$_SERVER['HTTP_HOST'];
		$today=$GLOBALS["sushee_today"];
		$user_id=$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'];
		$element_id=$_GET['ID'];
		$viewing_code=$_GET['viewing_code'];
		$language=$GLOBALS['NectilLanguage'];//?????????????????????????????????
		$remote_host=$_SERVER['REMOTE_HOST'];
		$path=$_SERVER['REQUEST_URI'];
		$referer=$_SERVER['HTTP_REFERER'];
		$referrerCode=$_GET['referrerCode'];
		$bannerCode=$_GET['bannerCode'];

		$db_conn = db_connect();
		$sql = "SELECT * FROM `weblogs` WHERE 1=-1;";
		$pseudo_rs = $db_conn->Execute($sql);
		if($pseudo_rs){
			$stats = array();
			$stats['CreationDate']=$today;
			$stats['URL']=$path;
			$stats['Host']=$host;
			$stats['IP']=$ip;
			$stats['ViewingCode']=$viewing_code;
			$stats['UserAgent']=$userAgent;
			$stats['elementID']=$element_id;
			$stats['parentID']=$_GET['parentID'];
			$stats['fromURL']=$referer;
			$stats['provider']=$remote_host;
			$stats['userID']=$user_id;
			$stats['LanguageID']=$language;
			$stats['referrerCode']=$referrerCode;
			$stats['bannerCode']=$bannerCode;
			$insert_sql = $db_conn->GetInsertSQL($pseudo_rs,$stats);
			$db_conn->Execute($insert_sql);
		}

		include_once(dirname(__FILE__)."/../common/visit_log.class.php");
		$visit=new visit_log($_COOKIE['visitorID'], $today, $host,
			$ip, $userAgent, $remote_host, $user_id, $language,$url);

		if(visit_log::$kill_spam && $visit->isSpamer()){
			die("You look like a spamer robot, if you are not, wait a few second and continue");
		}

		if(isset($_GET['viewing_code']) && $_GET['viewing_code']!='' && $_GET['owner']!=='false' && substr($stats['URL'],0,8)!='/Kernel/' && strlen($_GET['viewing_code'])>32){
			// --- first getting back its current Mail2Web state ---
			require_once(dirname(__FILE__)."/../private/mailing_functions.inc.php");
			$mailingID = substr($_GET['viewing_code'],33);
			$_GET['viewing_code'] = substr($_GET['viewing_code'],0,32);
			$recip_row = $db_conn->GetRow('SELECT * FROM `mailing_recipients` WHERE `ViewingCode`="'.$_GET['viewing_code'].'"'.(($mailingID!==false)?' AND `MailingID`=\''.$mailingID.'\' ':''));
			$url_update = '';
			if(is_array($recip_row)){
				if($recip_row['Mail2Web']==0){
					// putting the url of the current page
					$url_update.=',Mail2WebFirstURL="'.$path.'"';
				}
				// if there is and ID, also putting the title of the media in the current language
				if(isset($_GET['ID'])){
					if($recip_row['Mail2WebMediaID'])
						$viewedIDs = explode(',',$recip_row['Mail2WebMediaID']);
					else
					$viewedIDs = array();
					if(!in_array($_GET['ID'],$viewedIDs))
						$is_new = true;
					if($is_new){
						$viewedIDs[]=$_GET['ID'];
						$url_update.=',Mail2WebMediaID="'.implode(",", $viewedIDs).'"';
						$descrip_sql = 'SELECT * FROM `descriptions` WHERE `ModuleTargetID`=5 AND `Status`="published" AND `TargetID`="'.$_GET['ID'].'" AND LanguageID="'.$_SESSION[$GLOBALS["nectil_url"]]["language"].'";';
						$media_row = $db_conn->GetRow($descrip_sql);
						if($recip_row['Mail2WebMediaTitle'])
							$viewedTitles = explode(',',$recip_row['Mail2WebMediaTitle']);
						else
						$viewedTitles = array();
						$viewedTitles[]=str_replace(',','',$media_row['Title']);
						$url_update.=',Mail2WebMediaTitle="'.implode(",", $viewedTitles).'"';
					}
				}
				if($recip_row['ViewingDate']!='0000-00-00 00:00:00')
					$viewingDate = $recip_row['ViewingDate'];
				else
				$viewingDate = $GLOBALS['sushee_today'];
				$recip_mail2web_sql = 'UPDATE `mailing_recipients` SET `Status`="sent",`HTMLInMailbox`=1,`ViewingDate`="'.$viewingDate.'",`Mail2Web`=`Mail2Web`+1'.$url_update.' WHERE `ViewingCode`="'.$_GET['viewing_code'].'"'.(($mailingID!==false)?' AND `MailingID`=\''.$mailingID.'\' ':'');
				$db_conn->Execute($recip_mail2web_sql);
				updateContactValidity($recip_row['ContactID'],0);
				if($recip_row['Mail2Web']==0){
					updateMailingNbrNbrHTMLInMailbox($recip_row['MailingID']);
					updateMailingNbrMail2Web($recip_row['MailingID']);
				}
				updateMailingNbrSeen($recip_row['MailingID']);
			}
		}
		//!!!!!!!!referrerCode bannerCode?!!!!!!!!!!!!!!!!!
		include_once(dirname(__FILE__)."/../common/web_log.class.php");
		if(!$visit->is_bot){
			$web_log=new web_log($today, $host, $path, $element_id, $viewing_code, $language, $referer,$referrerCode,$bannerCode);
		}
	}

	$output_xml = FALSE;
	if (substr($stringofXML,-4)==".xml" && file_exists(getcwd()."/".$stringofXML)){
		$handle = fopen(getcwd()."/".$stringofXML, "r");
		while (!feof($handle)) {
			$buffer = fgets($handle, 4096);
			$newstringofXML.=$buffer;
		}
		$stringofXML=$newstringofXML;
	}
	$stringofXML = utf8_decode(utf8_To_UnicodeEntities($stringofXML));

	require_once(dirname(__FILE__)."/../private/request_function.inc.php");
	$strRet = request($stringofXML,$no_response_node,$supp_params,$navigation,false,$restrict_language,$priority_language,true,$public);

	//-------------------------------------
	// --- saving statistic information ---
	if(!isset($GLOBALS['stats_saved']) && $GLOBALS['no_stats']!==true){
		
		$visit->save();
		if(!$visit->is_bot){
			$web_log->visit_id=$visit->visit_id;
			$web_log->save();
		}
		$GLOBALS['stats_saved']=true;

	}
	return $strRet;
}

function isCrawler($agent){
	return eregi ( "(bot)|(google)|(slurp)|(spider)|(crawl)|(archive)|(linkwalker)|(findlinks)|(biglotron)|(worm)|(twiceler)",$agent);
}

function fromSearchEngine($fromUrl){
	return eregi ( "(query=)|(search\?)|(&q=)|(\?q=)",$fromUrl);
}

function checkCaptcha($value,$name='default'){
	$captcha = getCaptcha($name);
	if($captcha===false)
		return false;
	if(str_replace('o','0',strtolower($value))===strtolower($captcha))
		return true;
	return false;
}

function getCaptcha($name='default'){
	debug_log('getCaptcha'.$name);
	if(!isset($_SESSION[$GLOBALS["nectil_url"]]['captcha'][$name]))
		return false;
	debug_log('captcha get '.$_SESSION[$GLOBALS["nectil_url"]]['captcha'][$name]);
	return $_SESSION[$GLOBALS["nectil_url"]]['captcha'][$name];
}


function transform($xml,$template,$more_params=array(),$nectil_url_at_end=true,$nl2br=true,$html_on_error=true,$output_type="html"){

	include_once(dirname(__FILE__)."/../common/Cache/Lite.php");
	$options = array(
		'cacheDir' => $GLOBALS["nectil_dir"].'/Files/cache/',
		'lifeTime' => 2592000 /*30*24*3600*/
	);
	/*if(!file_exists($GLOBALS["nectil_dir"].'/Files/cache/')){
		include_once(dirname(__FILE__)."/../file/file_functions.inc.php");
		makeDir($GLOBALS["nectil_dir"].'/Files/cache/');
	}*/
	
	if (isset($_GET['cache']) && $_GET['cache']==='refresh'){
		$remove = true;
		unset($_GET['cache']);
	}
	$cwd = getcwd();
	if (file_exists($cwd."/$template"))
		$filetime = filemtime($cwd."/$template");
	else if(file_exists($template))
		$filetime = filemtime($template);
	if (file_exists($cwd."/common.xsl"))
		$common_filetime = filemtime($cwd."/common.xsl");
	else if(file_exists("common.xsl"))
		$common_filetime = filemtime("common.xsl");
	$id = generateID(array($_GET,$_POST,$_SESSION[$GLOBALS["nectil_url"]]["language"],$xml,$template,$more_params,$filetime,$common_filetime));
	
	// Create a Cache_Lite object
	$Cache_Lite = new Cache_Lite($options);
	
	if ($remove==true){
		$Cache_Lite->remove($id,'transform');
	}
	$sess = &$_SESSION[$GLOBALS["nectil_url"]];
	if ($GLOBALS["cache"]===TRUE && $_GET['cache']!=='false' && $sess["xml"]!="true" && $_GET["xml_debug"]!="true"  && $_GET["xml"]!="true"  && ($data = $Cache_Lite->get($id,'transform')) ) {
		
		return $data;
	}else{
		$data = real_transform($xml,$template,$more_params,$nl2br,$html_on_error,$output_type);
		if($nectil_url_at_end)
			$data = addNectilLink($data);
		if ($GLOBALS["cache"]===TRUE)
			$Cache_Lite->save($data,$id,'transform');
		
		return $data;
	}
	
	//return real_transform($xml,$template,$more_params);
}

function pdf_transform($result,$template,$download = true){
	require_once(dirname(__FILE__)."/../common/pdf.class.php");
	
	if($_GET['fo']==='true'){
		$XSLFoGen = new XSLFoGenerator();
		$XSLFoGen->setTemplate($this->template);
		$res = $XSLFoGen->execute($xml);
		
		$this->fo_file = $XSLFoGen->getFile();
		$fo_str = $this->fo_file->toString();
		xml_out($fo_str);
	}else{
		$generator = new SusheePDFGenerator();
		
		if($GLOBALS['PDFGenerator']=='ibex'){
			$generator->setPDFGenerator(new IbexPDFGenerator());
		}else{
			$generator->setPDFGenerator(new FopPDFGenerator());
		}
		

		$generator->setTemplate($template);

		if($_GET['cache']==='refresh' || $_GET['cache']==='false'){
			$generator->setCacheMode(false);
		}

		$sys = $generator->execute($result);
		$pdf_file = $generator->getFile();
		debug_log($sys);
		if ($pdf_file->exists() && $_GET['debug']!=='true' && $download==true){
			$pdf_file->forceDownload();

		}else if($download==true){
			echo $sys;
		}
		if ($pdf_file->exists())
			return $pdf_file->getPath();
		else
			return false;
	}

}

function getFilesRoot(){
	global $directoryRoot;
	return $directoryRoot;
}

function transform_to_pdf($result,$template,$download = true){
	global $directoryRoot;
	global $slash;
	$res = pdf_transform($result,$template,$download);
	if($res)
		return $directoryRoot.$res;
	else 
		return $res;
}

function addNectilLink($data){
	if(substr($data,0,5)=='<?xml')
		$close_meta = '/';
	else
		$close_meta = '';
	$opening_head_tag = strpos($data,"<head>");
	$closing_head_tag = strpos($data,"</head>");
	if($closing_head_tag!==false && $opening_head_tag!==false){
		
		$html_head = strtolower(substr($data,$opening_head_tag,$closing_head_tag-$opening_head_tag));
		if(strpos($html_head,'name="generator"')===false)
			$new_meta = '<meta name="generator" content="Nectil Content Management System - CMS - HTML, Flash PDF and XML"'.$close_meta.'>';
		if(strpos($html_head,'name="description"')===false)
			$new_meta.='<meta name="description" content="'.$GLOBALS['resident_name'].' - Powered by Nectil"'.$close_meta.'>';
		if(strpos($html_head,'name="keywords"')===false)
			$new_meta.='<meta name="keywords" content="'.$GLOBALS['resident_name'].' - Powered by Nectil"'.$close_meta.'>';
		$data = substr_replace($data,$new_meta,$closing_head_tag,0);
	}
	return $data;
}

function nectil_xslt_transform($transform_config){
	require_once(dirname(__FILE__).'/../common/xslt.class.php');
	
	$xml = $transform_config['xml'];
	$template = $transform_config['template'];
	$more_params = $transform_config['more_params'];
	$html_on_error = $transform_config['html_on_error'];
	$params = array_merge(nectil_xslt_params(),$more_params);
	
	$transformer = new SusheeXSLTransformer();
	$transformer->setParams($params);
	$transformer->setTemplate($template);
	if (function_exists("xslt_create") && $GLOBALS['use_libxslt']!==true && $transform_config['use_libxslt']!==true && $GLOBALS['use_saxon']!==true){
		$transformer->setprocessor(new SablotronXSLTProcessor());
	}elseif($GLOBALS['use_saxon']){
		$transformer->setprocessor(new SaxonXSLTProcessor());
	}else if($GLOBALS['use_phpxslt']){
		$transformer->setprocessor(new PHPXSLTProcessor());
	}else{
		$transformer->setprocessor(new LibXSLTProcessor());
	}
	$transformer->outputError($html_on_error);
	return $transformer->execute($xml);
}


function nectil_xslt_transform20090130($transform_config){
	global $slash;
	$xml = $transform_config['xml'];
	$template = $transform_config['template'];
	$more_params = $transform_config['more_params'];
	$html_on_error = $transform_config['html_on_error'];
	$fileBase = "file://".dirname($template)."/";
	
	$params = array_merge(nectil_xslt_params(),$more_params);
	$params["template_file"]=substr($template,0,strrpos($template,"."));
	if (function_exists("xslt_create") && $GLOBALS['use_libxslt']!==true && $transform_config['use_libxslt']!==true && $GLOBALS['use_saxon']!==true){
		$arguments = array('/_xml' => $xml);
		$xsltproc = xslt_create();
		if($xsltproc===false)
			return false;
		if($html_on_error===true)
		   xslt_set_error_handler($xsltproc, "xslt_error_handler");
		xslt_set_base ( $xsltproc, $fileBase );
		if (getServerOS()=='windows')
		   $template = "file://".$template;
		
		$html = xslt_process($xsltproc, 'arg:/_xml', "$template", NULL, $arguments,$params);
		
		if (empty($html)) {
		   if($html_on_error===true){
			   debug_log("html_on_error");
			$xslt_error = xslt_error($xsltproc);
			xslt_free($xsltproc);
			die('XSLT processing error: '.$xslt_error );
		   }else
			return false;
		}
		xslt_free($xsltproc);
   }else{
	    // creating a temporary file containing the xml to transform
		
		makeDir($GLOBALS["directoryRoot"].$slash."tmp");
		$tmpdir = $GLOBALS["directoryRoot"].$slash."tmp".$slash;
		$microtime = str_replace('.','', getmicrotime());
		$tmp_xml_file = $tmpdir.$microtime.'.xml';
		while(file_exists($tmp_xml_file)){
			$index++;
			$tmp_xml_file = $tmpdir.$microtime.'-'.$index.'.xml';
		}
		saveInFile($xml,$tmp_xml_file);
		// generating the command to execute
		if($GLOBALS['use_saxon']){
			$java = makeExecutableUsable($GLOBALS["javaExecutable"]);
			$saxon_jar = realpath(dirname(__FILE__).'/../common/saxon/saxon8.jar');
			$command = $java."  -jar \"".$saxon_jar."\" -novw -s \"".$tmp_xml_file."\" \"".$template."\"  2>&1 ";
		}else{
			$xsltproc = "xsltproc";
			if(getServerOS()=='windows' && file_exists(dirname(__FILE__).'/../common/xsltproc/xsltproc.exe'))
				$xsltproc='"'.realpath(dirname(__FILE__).'/../common/xsltproc/xsltproc.exe').'"';
			if(isset($GLOBALS["xsltproc"]))
				$xsltproc = $GLOBALS["xsltproc"];
			$xsltproc_params = '';
			if(sizeof($more_params)>0){
				foreach($more_params as $param_name=>$param_value){
					$xsltproc_params.='--stringparam "'.encodeQuote($param_name).'" "'.encodeQuote($param_value).'" ';
				}
			}
			$command = "$xsltproc ".$xsltproc_params." \"".$template."\" \"".$tmp_xml_file."\" 2>&1 ";
		}
		
		// executing the xsltproc command
		//debug_log($command);
		$command = batchFile($command);
		$html_array = array();
		session_write_close();
		exec($command,$html_array,$res);
		session_start();
		$result_xsl = implode("\n",$html_array);
		// if there was an error display it
		if($res>0){
			$line = false;
			$xsl_str = file_in_string($template);
			$xsl_str = str_replace("\r\n","\n",$xsl_str);
			$xsl_lines = explode("\n",$xsl_str);
			$line_pos = strpos($result_xsl,'line ');
			if($line_pos){
				$space_pos = strpos($result_xsl,' ',$line_pos+6);
				if(!$space_pos)
					$space_pos = strpos($result_xsl,"\n",$line_pos+6);
				if($space_pos)
					$line = substr($result_xsl,$line_pos+5,$space_pos-$line_pos-5);
			}
			if($line)
				$line_msg = ' on line '.$line;
			$html = '<html><body><h1>Error '.$line_msg.':</h1><p style="font-size:110%;line-height:1.3;">';
		}
		if($res>0)
			$html.= str_replace('^','<br/>',encode_to_XML($result_xsl));
		else
			$html.= str_replace('<br></br>','<br/>',$result_xsl);
		if($res>0 && $line){
			$html.= "</p><p style='line-height:18px;padding:5px;margin-left:20px;background-color:lightgrey;'>";
			$html.= "<code>".encode_to_XML($xsl_lines[$line-2])."<br/><span style='color:red;'>".encode_to_XML($xsl_lines[$line-1])."</span><br/>".encode_to_XML($xsl_lines[$line])."<br/>".encode_to_XML($xsl_lines[$line+1])."</code></p>";
			$html.='</body></html>';
			
		}
		// deleting the temporary original xml file
		unlink($tmp_xml_file);
		if($html_on_error===false && $res>0){
			//debug_log($html);
			return false;
		}
			
   }
   return $html;
}
function get_xml_from_post_data($log=true){
	$HTTP_RAW_POST_DATA = $GLOBALS['HTTP_RAW_POST_DATA'];
	$stringofXML = utf8_decode(utf8_To_UnicodeEntities($HTTP_RAW_POST_DATA));
	$stringofXML=trim($stringofXML);
	if( $stringOfXML!="" && substr($stringofXML,-1) != ">" ){
		$stringofXML.=">";
	}
	if($log){
		$perm = 'a+';
		if(file_exists($GLOBALS["nectil_dir"]."/Files/log.txt") && filesize($GLOBALS["nectil_dir"]."/Files/log.txt")>1048576)
			$perm = 'w+';
		if ( (file_exists($GLOBALS["nectil_dir"]."/Files/log.txt") && is_writable($GLOBALS["nectil_dir"]."/Files/log.txt")) || (!file_exists($GLOBALS["nectil_dir"]."/Files/log.txt") && is_writable($GLOBALS["nectil_dir"]."/Files/")) ){
			$file = fopen($GLOBALS["nectil_dir"]."/Files/log.txt", $perm); // binary update mode
			fwrite($file, "\n---------------------------------------------------\n".$stringofXML);
			fclose($file);
			//chmod ($GLOBALS["nectil_dir"]."/Files/log.txt", 0777);
		}
	}
	// building a tree with the xmlString
	$xml = new XML($stringofXML);
	return $xml;
}

function getLanguage(){
	return $GLOBALS["NectilLanguage"];
}

function nectil_xslt_params(){
	$params = array('today'=>$GLOBALS["sushee_today"]);
	$params["language"]=$GLOBALS["NectilLanguage"];
	$params["sessionID"]=session_id();
	
	$params["files_url"]=$GLOBALS["files_url"];
	$params["files_dir"]=$GLOBALS["nectil_dir"]."/Files";
	$params["public_dir"]=$GLOBALS["nectil_dir"]."/Public";
	
	$params["this_url"]=$_SERVER['REQUEST_URI'];
	$params["this_script"]=basename($_SERVER['SCRIPT_NAME']);
	$params["language_url"]=$params["this_url"];
	$params["language_url"]=str_replace(array("cache=false&","cache=false"),"",$params["language_url"]);
	$params["language_url"]=preg_replace ( '/&language=.[^&]*/i', '', $params["language_url"]);
	$params["language_url"]=preg_replace ( '/\?language=.[^&]*$/i', '?', $params["language_url"]);
	$params["language_url"]=preg_replace ( '/\?language=.[^&]*&/i', '?', $params["language_url"]);
	if (strpos($params["language_url"],'?')===FALSE)
	$params["language_url"]=$params["language_url"].'?';
	else if(substr($params["language_url"],-1)!='&' && substr($params["language_url"],-1)!='?')
	$params["language_url"]=$params["language_url"].'&';
	$params["logged"]="false";
	$params["edition"]="false";
	$params["all_languages"]=$sess["all_languages"];
	if (isset($_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID']))
		$params["logged"]="true";
	if (isset($_SESSION[$GLOBALS["nectil_url"]]['edition']) && $_SESSION[$GLOBALS["nectil_url"]]['edition']=="true")
		$params["edition"]="true";
	return $params;
}

function resolve_template_path($template){
	global $slash;
	if(substr($template,0,7)=='file://'){
		$template = substr($template,7);
	}else if(file_exists(getcwd ().$slash."$template")){
		$template = getcwd().$slash."$template";
	}else if(file_exists("$template")){
		$template = realpath("$template");
	}
	return $template;
}

function real_transform($xml,$template,$more_params=array(),$nl2br=true,$html_on_error=true){
	$template = resolve_template_path($template);
	
	if($nl2br)
		$xml = nl2br($xml);
	if( ($sess["xml"]=="true" || $_GET["xml_debug"]=="true" || $_GET["xml"]=="true" || (!file_exists("$template"))) && ($GLOBALS['xmlVisible']!='false' || substr($_SERVER["DOCUMENT_ROOT"].$_SERVER['REQUEST_URI'],0,strlen($GLOBALS["library_dir"]))==$GLOBALS["library_dir"])){
	  xml_out($xml);
	}
   
   $xml = generate_utf8($xml);
   
   $transform_config = array('xml'=>$xml,'template'=>$template,'more_params'=>$more_params,'html_on_error'=>$html_on_error);
   $xslt_html = nectil_xslt_transform($transform_config);
   
   return utf8_To_UnicodeEntities(bbdecode($xslt_html));
}

function transform_to_text($xml,$template,$more_params=array()){
	$template = resolve_template_path($template);
	
	$xml = nl2br($xml);
	
	$xml = generate_utf8($xml);
	
	$transform_config = array('xml'=>$xml,'template'=>$template,'more_params'=>$more_params,'html_on_error'=>false);
	$xslt_text = nectil_xslt_transform($transform_config);
	return $xslt_text;
}

function handleFieldOperator($operator,$former_value,$value){
	switch($operator){
		case 'md5':
		case 'MD5':
			return md5($value);
		case 'encrypt':
			return mysql_password($value);
		case 'before':
			return $value.$former_value;
		case 'append':
			return $former_value.$value;
		case '+':
			return $former_value+$value;
		case '-':
			return $former_value-$value;
		case '*':
			return $former_value*$value;
		case '/':
			if($value!=0)
			return $former_value/$value;
		case '++':
			return $former_value+1;
		case '--':
			return $former_value-1;
		default:
			return $value;
	}
}

function isLogged(){
	return isset($_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID']);
}

function create($xml,$current_path,$firstNodePath){
	$firstNode = $xml->nodeName($current_path.'/*[1]');
	include_once(dirname(__FILE__)."/../private/create.inc.php");
	$query_result = createQuery("",$xml,"CREATE",$current_path,$firstNode,$firstNodePath);
	$message_xml = new XML('<?xml version="1.0" encoding="utf-8"?>'.$query_result);
	return $message_xml->getData('/MESSAGE/@elementID');
}
function update($xml,$current_path,$firstNodePath){
	$firstNode = $xml->nodeName($current_path.'/*[1]');
	include_once(dirname(__FILE__)."/../private/update.inc.php");
	$query_result = updateQuery("",$xml,"UPDATE",$current_path,$firstNode,$firstNodePath);
	$message_xml = new XML('<?xml version="1.0" encoding="utf-8"?>'.$query_result);
	//echo "/*".$message_xml->getData('/MESSAGE/attribute::modificationDate')."*/";
	return $message_xml->getData('/MESSAGE/@modificationDate');
}


function shorten($path){

	if ( substr($path,0,strlen($_SERVER["DOCUMENT_ROOT"]))===$_SERVER["DOCUMENT_ROOT"] )
	$short_path = substr($path,strlen($_SERVER["DOCUMENT_ROOT"]));
	return $short_path;
}

function checkSpam($message){
	$message = strtolower($message);
	if(strpos($message,'mime-version:')!==false)
		return true;
	if(strpos($message,'to:')!==false)
		return true;
	if(strpos($message,'bcc:')!==false)
		return true;
	if(strpos($message,'cc:')!==false)
		return true;
	if(strpos($message,'subject:')!==false)
		return true;
	if(strpos($message,'content-type:')!==false)
		return true;
	if(strpos($message,'multipart/alternative;')!==false)
		return true;
	if(strpos($message,'boundary=')!==false)
		return true;
	if(strpos($message,'content-transfer-encoding:')!==false)
		return true;
}


function file_in_string($path){
	if (file_exists($path)){
		$handle = fopen($path, "r");
		while (!feof($handle)) {
   			$buffer = fgets($handle, 4096);
   			$str.=$buffer;
		}
		return $str;
	}else 
		return false;
}
function dir_xml($path){
	include_once(dirname(__FILE__)."/../file/file_functions.inc.php");
	if ($dir = @opendir($path)) {
        /* loop once for each name in the directory */
		$fileList = "<?xml version='1.0' encoding='utf-8'?><DIR>";
        while($file = readdir($dir)) {
            $isFileVisible=true;
			// if the name is not a directory and the name is not the name of this program file
			$extension = substr($file,-4);
            if($file == "." || $file == ".." || $file == "$ThisFileName" || ($extension!=".xml" && $extension!=".XML") )
                $isFileVisible = false;
            
            if($isFileVisible) {
				$file_xml = new XML(/*$path.'/'.$file*/);
				$file_xml->setSkipWhiteSpaces(true);
				$file_xml->importFromFile($path.'/'.$file);
				if ($file_xml->loaded){
					if ($file_xml->match("/FILE"))
						$fileList.=$file_xml->toString("/","",false);
					else if ($file_xml->match("/DIR")){
						$fileList.=$file_xml->toString("/DIR/FILE","",false);
					}
				}
            }
        }
		$fileList.="</DIR>";
		return unutf8($fileList);
    }
    else {
		die( xml_msg("1","-1","-1","Directory doesn't exist:".$path));
    }
}

function login($email,$password){
	$output_xml = FALSE;
	$stringofXML='<QUERY><LOGIN>'.encode_to_XML(stripcslashes($email)).'</LOGIN><LANGUAGEID>'.$_SESSION[$GLOBALS["nectil_url"]]["language"].'</LANGUAGEID><PASSWORD>'.encode_to_XML(stripcslashes($password)).'</PASSWORD></QUERY>';
	$stringofXML = utf8_encode($stringofXML);
	
	require_once(dirname(__FILE__)."/../public/login.php");
	return $strRet;
}
function sendNewPassword($contactID,$nectil_url="",$signer = array()){
	if(!is_numeric($contactID))
		$sql = 'SELECT * FROM `contacts` WHERE Email1="'.encodeQuote($contactID).'" AND Activity=1;';
	else
		$sql = 'SELECT * FROM `contacts` WHERE ID='.$contactID.' AND Activity=1;';
	$db_conn = db_connect();
	$row = $db_conn->GetRow($sql);
	if($row && $row['Password']){
		$language = $row['LanguageID'];
		if(isset($signer[$language]))
			$signer_name = $signer[$language];
		else if(isset($signer['und']))
			$signer_name = $signer['und'];
		// must generate a new password, put it in db and send it
		$nectil_login = $row['Email1'];
		$nectilContact = $row;
		$nectil_password = generate_password(8,1,'L');
		$upd_sql = 'UPDATE `contacts` SET `Password`="'.mysql_password($nectil_password).'" WHERE ID='.$row['ID'].';';
		$res = $db_conn->Execute($upd_sql);
		include(dirname(__FILE__)."/../common/useful_texts.inc.php");
		if(isset($GLOBALS['keyringsSender']))
			$keyringsMail = $GLOBALS['keyringsSender'];
		else
			$keyringsMail = "keyrings@nectil.com";
		if($GLOBALS['resident_name'])
			$sender = $GLOBALS['resident_name'];
		else
			$sender = "Nectil";
		sendMail($nectil_login,$forgot_password_title,$forgot_password_txt,$sender,$keyringsMail);
		return true;
	}
	return false;
}

function generate_password($digits=8,$c=1,$st='L'){
   if(!ereg("^([4-9]|((1|2){1}[0-9]{1}))$",$digits)) // 4-29 chars allowed
     $digits=4;
   for(;;)
   {
     $pwd=null; $o=null;
     // Generates the password ....
     for ($x=0;$x<$digits;)
     {
         $y = rand(1,1000);
         if($y>350 && $y<601) $d=chr(rand(48,57));
         if($y<351) $d=chr(rand(65,90));
         if($y>600) $d=chr(rand(97,122));
         if($d!=$o)
         {           
           $o=$d; $pwd.=$d; $x++;
         }
     }
     // if you want that the user will not be confused by O or 0 ("Oh" or "Null")
     // or 1 or l ("One" or "L"), set $c=true;
     if($c)
     {
         $pwd=eregi_replace("(l|i)","1",$pwd);
         $pwd=eregi_replace("(o)","0",$pwd);
     }
     // If the PW fits your purpose (e.g. this regexpression) return it, else make a new one
     // (You can change this regular-expression how you want ....)
     if(ereg("^[a-zA-Z]{1}([a-zA-Z]+[0-9][a-zA-Z]+)+",$pwd))
         break;   
   }
   if($st=="L") $pwd=strtolower($pwd);
   if($st=="U") $pwd=strtoupper($pwd);
   return $pwd;
}
function getInfos(&$moduleInfo,$IDs){
	$db_conn = db_connect();
	if (!is_array($IDs))
		$IDs = array($IDs);
	$sql = "SELECT * FROM `".$moduleInfo->tableName."` WHERE ";
	for($i=0;$i<sizeof($IDs);$i++){
		$sql.=" `ID`='".$IDs[$i]."'";
		if ($i!=sizeof($IDs)-1)
		$sql.=" OR";
	}
	//echo $sql;
	$rs = $db_conn->Execute($sql);
	return $rs;
}
function getInfo(&$moduleInfo,$ID){
	$db_conn = db_connect();
	$sql = "SELECT * FROM `".$moduleInfo->tableName."` WHERE `ID`='$ID';";
	$row = $db_conn->GetRow($sql);
	return $row;
}

function resetModule(&$moduleInfo){
	$db_conn = db_connect();
	$sql = "DELETE FROM `".$moduleInfo->tableName."` WHERE `ID`!=1 AND `IsLocked`=0;";
	$db_conn->Execute($sql);
	return $sql;
}
function getServicesArray(){
	$db_conn = db_connect(TRUE);
	$sql = "SELECT * FROM services;";
	$rs = $db_conn->Execute($sql);
	$services = array();
	if ($rs){
		while($row = $rs->FetchRow()){
			$services[$row["Denomination"]]=$row;
			$services[$row["Denomination"]]["SECURITY"]="W";
		}
	}
	return $services;
}
function osLogs($requestName,$firstNode,$beginRequestTime=0,$requestElementID=0,$completeRequest=''){
	$osLogs = array();
	$connected = array();
	$osLogs['ResidentID']=$GLOBALS['residentID'];
	$osLogs['UserID']=$connected['UserID']=$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'];
	$osLogs['TimeStamp']=$connected['TimeStamp']=$GLOBALS['sushee_today'];
	$osLogs['IP']=$connected['IP']=$_SERVER['REMOTE_ADDR'];
	$osLogs['Provider']=$_SERVER['REMOTE_HOST'];
	$osLogs['RequestFile']=__FILE__;
	$osLogs['RequestType']=$requestName;
	$osLogs['RequestTarget']=$firstNode;
	$osLogs['Request']=$completeRequest;
	$moduleInfo = moduleInfo($firstNode);
	if($moduleInfo->loaded)
		$osLogs['ModuleID']=$moduleInfo->ID;
	$osLogs['ElementID']=$requestElementID;
	$osLogs['Queries']=$GLOBALS["EXECS"]-$nb_queries;
	$osLogs['RequestTime']=getTimer()-$beginRequestTime;
	
	// insertion in db
	$db_conn = db_connect();
	if($firstNode!='CONNECTED' && !($requestName=='CHECK' && $firstNode=='MAILSACCOUNT')){
		$sql = "SELECT * FROM `oslogs` WHERE `ID`=-1;";
		$pseudo_rs = $db_conn->Execute($sql);
		if($pseudo_rs){
			$insert_sql = $db_conn->GetInsertSQL($pseudo_rs, $osLogs);
			$db_conn->Execute($insert_sql);
		}
		if($requestName!='LOGOUT')
			$connected['Type']='real';
		else
			$connected['Type']='logout';
	}else{
		$connected['Type']='connected';
	}
	if(isset($_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'])){
		$sql = "SELECT * FROM `connected` WHERE `UserID`=-1;";
		$pseudo_rs = $db_conn->Execute($sql);
		if($pseudo_rs){
			if($requestName!='LOGOUT'){
				// delete previous logs
				$del_prev_connected = 'DELETE FROM `connected` WHERE (`Type`="'.$connected['Type'].'" OR `Type`="logout") AND `UserID`='.$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'];
				$db_conn->Execute($del_prev_connected);
				// inserting new one
				$insert_sql = $db_conn->GetInsertSQL($pseudo_rs, $connected);
				$db_conn->Execute($insert_sql);
			}else{
				$del_prev_connected = 'DELETE FROM `connected` WHERE `UserID`='.$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID'];
				$db_conn->Execute($del_prev_connected);
				$insert_sql = $db_conn->GetInsertSQL($pseudo_rs, $connected);
				$db_conn->Execute($insert_sql);
			}
		}
	}
}

function generateInfoXML(&$moduleInfo,&$elem,&$fields_array,$profile_array,$output='html',$info_tag=true,$include_creator_info=false,$include_weekdays=false,$include_modifier_info=false,$include_owner_info=false){
	// get fields with a least "R"
	//$fields_array=$moduleInfo->getFieldsBySecurity("R");
	$indesign_excludes = array('ID'=>true,'CREATIONDATE'=>true,'MODIFICATIONDATE'=>true,'ACTIVITY'=>true,'ISLOCKED'=>true,'CREATORID'=>true,'MODIFIERID'=>true);
	if ($info_tag)
		$str='<INFO>';
	else
		$str='';
	if ($profile_array===FALSE || $profile_array===NULL){
		$fields_nbr = count($fields_array);
		for($i=0;$i<$fields_nbr;$i++){
			$n=$fields_array[$i];
			$value=$elem[$n];
			$n=strtoupper($n);
			if ($output!=='indesign' || ($output==='indesign' && $value!='' && !isset($indesign_excludes[$n])) ){
				if($include_weekdays===true)
					$fieldType = $moduleInfo->getFieldType($fields_array[$i]);
				if ($moduleInfo->isXMLField($fields_array[$i])){
					$str.='<'.$n.'>'.$value.'</'.$n.'>';
				}else if($include_weekdays===true && ($fieldType=='D' || $fieldType=='T') && $value!='0000-00-00 00:00:00' && $value!='9999-12-31 23:59:59'){
					$day = substr($value,8,2);
					$month = substr($value,5,2);
					$year = substr($value,0,4);
					$time = mktime(0,0,0,$month,$day,$year);
					$str.='<'.$n.' weekday="'.date('w',$time).'">'.$value.'</'.$n.'>';
				}else{
					$str.='<'.$n.'>'.encode_to_XML($value).'</'.$n.'>';
				}
				if ($output=='indesign')
					$str.="\n";
			}
		}
	}else{
		$fields_nbr = count($fields_array);
		$profile_nbr = count($profile_array);
		$fields_ok = 0;
		for($i=0;$i<$fields_nbr;$i++){
			$n=$fields_array[$i];
			$value=$elem[$n];
			$n=strtoupper($n);
			// we still have to check the profile asks it
			// by default we consider it is asked (if there is no profile)
			//$asked = TRUE;
			// warning : if <INFO> node is empty (and has a get attribute, otherwise this function would not be called) we consider all fields must be included
			$asked = FALSE;
			if (isset($profile_array[$n]))
				$asked = TRUE;
			if ($asked){
				if ($output!=='indesign' || ($output==='indesign' && $value!='' && !isset($indesign_excludes[$n])) ){
					if($include_weekdays===true)
						$fieldType = $moduleInfo->getFieldType($fields_array[$i]);
					if ($moduleInfo->isXMLField($fields_array[$i])){
						$str.='<'.$n.'>'.$value.'</'.$n.'>';
					}else if($include_weekdays===true && ($fieldType=='D' || $fieldType=='T') && $value!='0000-00-00 00:00:00' && $value!='9999-12-31 23:59:59'){
						$day = substr($value,8,2);
						$month = substr($value,5,2);
						$year = substr($value,0,4);
						$time = mktime(0,0,0,$month,$day,$year);
						$str.='<'.$n.' weekday="'.date('w',$time).'">'.$value.'</'.$n.'>';
					}else{
						$str.='<'.$n.'>'.encode_to_XML($value).'</'.$n.'>';
					}
					if ($output=='indesign')
						$str.="\n";
				}
				$fields_ok++;
				if ($fields_ok==$profile_nbr)// we did all the fields
					break;
			}
			
		 }
	}
	if($include_creator_info || $include_modifier_info || $include_owner_info){
		
		$moduleContactInfo = moduleInfo('contact');
		
		if($include_creator_info){
			$creator_info = getInfo($moduleContactInfo,$elem['CreatorID']);
			$creator_str = generateXMLOutput($creator_info,$moduleContactInfo,array('profile_name'=>'publication'));
			$str.=$creator_str;
		}
		if($include_modifier_info){
			if($include_creator_info && $elem['CreatorID'] == $elem['ModifierID']){
				//$modifier_str = $creator_str;
			}else{
				$modifier_info = getInfo($moduleContactInfo,$elem['ModifierID']);
				$modifier_str = generateXMLOutput($modifier_info,$moduleContactInfo,array('profile_name'=>'publication'));
				$str.=$modifier_str;
			}
			
		}
		if($include_owner_info){
			if($include_creator_info && $elem['CreatorID'] == $elem['OwnerID']){
				//$owner_str = $creator_str;
			}else if($include_modifier_info && $elem['ModifierID'] == $elem['OwnerID']){
				//$owner_str = $modifier_str;
			}else{
				$owner_info = getInfo($moduleContactInfo,$elem['OwnerID']);
				$owner_str = generateXMLOutput($owner_info,$moduleContactInfo,array('profile_name'=>'publication'));
				$str.=$owner_str;
			}
			
		}
	}
	
	if ($info_tag)
		$str.='</INFO>';
	return $str;
}
function getLanguageInfo($ID){
	$db_conn = db_connect(TRUE);
	$sql = "SELECT * FROM languages WHERE ID='$ID';";
	$row = $db_conn->GetRow($sql);
	return $row;
}
function getCountryInfo($ID){
	$db_conn = db_connect(TRUE); // it's common
	$sql = "SELECT * FROM countries WHERE ID='$ID';";
	$row = $db_conn->GetRow($sql);
	return $row;
}
function resetNectilSession(){
	unset($_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID']);
	unset($_SESSION[$GLOBALS["nectil_url"]]["private"]);
	unset($_SESSION[$GLOBALS["nectil_url"]]["public"]);
	unset($_SESSION[$GLOBALS["nectil_url"]]['SESSIONua']);
	unset($_SESSION[$GLOBALS["nectil_url"]]['SESSIONIP']);
}
function logout(){
	resetNectilSession();
}
function prepareNectilSession(){
	if (!isset($_SESSION[$GLOBALS["nectil_url"]]['public']))
		$_SESSION[$GLOBALS["nectil_url"]]['public'] = array("moduleInfo_array"=>array(),"moduleInfo_array_byID"=>array(),"depType_array"=>array(),"depType_array_byID"=>array());
	if (!isset($_SESSION[$GLOBALS["nectil_url"]]['private']))
		$_SESSION[$GLOBALS["nectil_url"]]['private'] = array("moduleInfo_array"=>array(),"moduleInfo_array_byID"=>array(),"depType_array"=>array(),"depType_array_byID"=>array());
	if(!isset($GLOBALS[$GLOBALS['nectil_url']]['public']))
		$GLOBALS[$GLOBALS["nectil_url"]]['public'] = array("moduleInfo_array"=>array(),"moduleInfo_array_byID"=>array(),"depType_array"=>array(),"depType_array_byID"=>array());
}
// function that gets back a global moduleInfo instead of duplicating each time
function moduleInfo($moduleName/* can be the ID too*/){
	prepareNectilSession();
	//return new moduleInfo($moduleName);
	if ($GLOBALS['dev_request']===TRUE)
		$sess_mod_array =  &$_SESSION[$GLOBALS['nectil_url']]['public'];
	else
		$sess_mod_array =  &$_SESSION[$GLOBALS['nectil_url']]['private'];
	if (!is_numeric($moduleName)){
		$moduleName = strtolower($moduleName);
		
		
		if ( !isset($sess_mod_array['moduleInfo_array']) || !isset($sess_mod_array['moduleInfo_array'][$moduleName]) ){
			  $moduleInfo = new moduleInfo($moduleName);
			  if($moduleInfo->loaded){
				  $ID = $moduleInfo->ID;
				  $sess_mod_array['moduleInfo_array'][$moduleName]=$moduleInfo;
				  $sess_mod_array['moduleInfo_array_byID'][$ID]=$moduleInfo;
			  }
			  return $moduleInfo;
			  //return $sess_mod_array['moduleInfo_array'][$moduleName];
		}else{ // we return the object defined earlier
			return $sess_mod_array['moduleInfo_array'][$moduleName];
		}
	}else{
		
		/*if ($GLOBALS['serverOS']=='windows')
			return new moduleInfo($moduleName);*/
		if ( !isset($sess_mod_array['moduleInfo_array_byID']) || !isset($sess_mod_array['moduleInfo_array_byID'][$moduleName]) ){
			$moduleInfo = new moduleInfo($moduleName);
			if($moduleInfo->loaded){
				$sess_mod_array['moduleInfo_array_byID'][$moduleName]=$moduleInfo;
				$sess_mod_array['moduleInfo_array'][$moduleInfo->name]=$moduleInfo;
			}
			return $moduleInfo;
			//return $sess_mod_array['moduleInfo_array_byID'][$moduleName];
		}else{
			return $sess_mod_array['moduleInfo_array_byID'][$moduleName];
		}
	}
}
function depType($depName/* can be the ID too*/,$moduleName="",$return_dependency=NULL){
	prepareNectilSession();
	if ($GLOBALS['dev_request']===TRUE)
		$sess_mod_array =  &$_SESSION[$GLOBALS['nectil_url']]['public'];
	else
		$sess_mod_array =  &$_SESSION[$GLOBALS['nectil_url']]['private'];
	if ($GLOBALS['serverOS']=='windows')
		return new dependencyType($depName,$moduleName,$return_dependency);
	if (!is_numeric($depName)){
		if ( !isset($sess_mod_array['depType_array']) || !isset($sess_mod_array['depType_array'][$depName]) ){
			  $sess_mod_array['depType_array'][$depName]=new dependencyType($depName,$moduleName,$return_dependency);
			  $sess_mod_array['depType_array_byID'][$sess_mod_array['depType_array'][$depName]->ID]=$sess_mod_array['depType_array'][$depName];
			  return $sess_mod_array['depType_array'][$depName];
		}else{ // we return the object defined earlier
			return $sess_mod_array['depType_array'][$depName];
		}
	}else{
		if ( !isset($sess_mod_array['depType_array_byID']) || !isset($sess_mod_array['depType_array_byID'][$depName]) ){
			$sess_mod_array['depType_array_byID'][$depName]=new dependencyType($depName,$moduleName,$return_dependency);
			$sess_mod_array['depType_array'][$sess_mod_array['depType_array_byID'][$depName]->name]=$sess_mod_array['depType_array_byID'][$depName];
			return $sess_mod_array['depType_array_byID'][$depName];
		}else{
			return $sess_mod_array['depType_array_byID'][$depName];
		}
	}
}

function generateMsgXML($strType,$strMsg,$strError=0,$elementID='',$name='',$creationDate='',$modificationDate='',$suppl=''){
	$strRet="<MESSAGE msgType='$strType' errorCode='$strError'".(($elementID)?" elementID='$elementID'":'').(($name)?" name='$name'":'').(($creationDate!='')?" creationDate='$creationDate'":"")." ".(($modificationDate!='')?" modificationDate='$modificationDate'":"")." $suppl>$strMsg</MESSAGE>";
	return $strRet;
}
// to ensure compatibility with the V1 style scripting
function xml_msg($strType,$strID,$strSID,$strMsg,$strError=0){
	header ("content-type: text/xml");
	$strRet="<?xml version=\"1.0\"?><RESPONSE userID=\"".$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID']."\" sessionID=\"".session_id()."\">".generateMsgXML($strType,$strMsg,$strError)."</RESPONSE>";
	return $strRet;
}
function generate_utf8($str){
	return UnicodeEntities_To_utf8(utf8_encode($str));
}
function unutf8($str){
	return utf8_decode(UnicodeEntities_To_utf8($str));
}
function xml_out($str){
	header ("content-type: text/xml; charset=UTF-8");
	$strRet = generate_utf8($str);
	$perm = 'a+';
	if(file_exists($GLOBALS["nectil_dir"]."/Files/out.log") && filesize($GLOBALS["nectil_dir"]."/Files/out.log")>1048576)
		$perm = 'w+';
	if ( (file_exists($GLOBALS["nectil_dir"]."/Files/out.log") && is_writable($GLOBALS["nectil_dir"]."/Files/out.log")) || (!file_exists($GLOBALS["nectil_dir"]."/Files/out.log") && is_writable($GLOBALS["nectil_dir"]."/Files/")) ){
		$file = fopen($GLOBALS["nectil_dir"]."/Files/out.log", $perm); // binary update mode
		fwrite($file, "\r\n---------------------------------------------------\r\n".$strRet);
		fclose($file);
		//chmod ($GLOBALS["nectil_dir"]."/Files/out.log", 0777);
	}
	die($strRet);
}
function debug_log($str){
	$strRet = /*generate_utf8(*/$str/*)*/;
	$perm = 'a+';
	if(file_exists($GLOBALS["nectil_dir"]."/Files/debug.log") && filesize($GLOBALS["nectil_dir"]."/Files/debug.log")>1048576)
		$perm = 'w+';
	if ( (file_exists($GLOBALS["nectil_dir"]."/Files/debug.log") && is_writable($GLOBALS["nectil_dir"]."/Files/debug.log")) || (!file_exists($GLOBALS["nectil_dir"]."/Files/debug.log") && is_writable($GLOBALS["nectil_dir"]."/Files/")) ){
		$file = fopen($GLOBALS["nectil_dir"]."/Files/debug.log", $perm); // binary update mode
		fwrite($file, "\r\n---------------------------------------------------\r\n".date("Y-m-d H:i:s")." ".$_SESSION[$GLOBALS["nectil_url"]]['SESSIONuserID']."- ".$strRet);
		fclose($file);
		//chmod ($GLOBALS["nectil_dir"]."/Files/debug.log", 0777);
	}
}

function makeExecutableUsable($exec){
	$exec = "\"".$exec."\"";
	return $exec;
}
function batchFile($command){
	global $slash;
	$OS = getServerOS();
	if($OS=='windows'){
		$command = 'call '.$command;
	}
	return $command;
}
function saveInFile($msg,$filename){ 
	// open file
	$fd = fopen($filename, "w+");
	fwrite($fd,$msg);
	fclose($fd);
	//chmod ($filename, 0777);
	chmod_Nectil($filename);
}

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

function removeaccents($string){
   $string = utf8_To_UnicodeEntities($string);
   $search = array("&#192;","&#193;","&#194;","&#195;","&#196;","&#197;","&#224;","&#225;","&#226;","&#227;","&#228;","&#229;","&#210;","&#211;","&#212;","&#213;","&#214;","&#216;","&#242;","&#243;","&#244;","&#245;","&#246;","&#248;","&#200;","&#201;","&#202;","&#203;","&#232;","&#233;","&#234;","&#235;","&#199;","&#231;","&#204;","&#205;","&#206;","&#207;","&#236;","&#237;","&#238;","&#239;","&#217;","&#218;","&#219;","&#220;","&#249;","&#250;","&#251;","&#252;","&#255;","&#209;","&#241;");
   $replace = array("a","a","a","a","a","a","a","a","a","a","a","a","o","o","o","o","o","o","o","o","o","o","o","o","e","e","e","e","e","e","e","e","c","c","i","i","i","i","i","i","i","i","u","u","u","u","u","u","u","u","y","n","n");	
   // en reserve : &#167; 
   //$string= strtr($string, utf8_decode(unhtmlentities(implode("",$search))),implode("",$replace));
   $string= strtr($string,unhtmlentities(implode("",$search)),implode("",$replace));
   $multiletter_search = array("&#8212;","&#179;","&#178;","&#176;","&#180;","&#187;","&#171;","&#169;","&#8221;","&#8220;","&#160;","&#8211;","&#8216;","&#8217;","&#339;","&#230;","&#8230;","&#8364;","&#8226;","&#367;","&#269;","&#345;","&#253;","&#382;","&#283;","&#353;","&#337;","&#128;","&#357;");
   $multiletter_replace = array("-","3","2","o","'","\"","\"","c","\"","\""," ","-","'","'","oe","ae","...","euro","*","u","c","r","y","z","e","s","o","euro","t");
   $search = array_merge ($search, $multiletter_search);
   $replace = array_merge ($replace, $multiletter_replace);
   $string = str_replace($search,$replace,$string);
   return $string;
}

function is_utf8($string) {
   return (preg_match('/^([\x00-\x7f]|[\xc2-\xdf][\x80-\xbf]|\xe0[\xa0-\xbf][\x80-\xbf]|[\xe1-\xec][\x80-\xbf]{2}|\xed[\x80-\x9f][\x80-\xbf]|[\xee-\xef][\x80-\xbf]{2}|f0[\x90-\xbf][\x80-\xbf]{2}|[\xf1-\xf3][\x80-\xbf]{3}|\xf4[\x80-\x8f][\x80-\xbf]{2})*$/', $string) === 1);
}

function setDownloadHeaders($filename,$filesize=NULL,$charset=false){
	header("Pragma: public");
    header("Expires: 0"); // set expiration time
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
    header( "Content-type: application/force-download".(($charset!==false)?";charset:".$charset:'') );
    header("Content-Transfer-Encoding: Binary");
	if ($filesize!=NULL)
    	header("Content-length: ".$filesize);
    header("Connection: close");
    header( "Content-Disposition: attachment; filename=\"".encodeQuote($filename)."\"");
}
function getDependencyTypesArray($rs){
	if ($rs){
		$depTypes=array();
		while($row = $rs->FetchRow()){
			$depTypes[$row["Denomination"]]=$row;
			$depTypes[$row["Denomination"]]["SECURITY"]="W";
		}
		return $depTypes;
	}else
		return array();
}
function hasTypedLinks($moduleOriginID,$originID){
	$db_conn = db_connect();
	$typesSet = new DependencyTypeSet(false,$moduleOriginID);
	$typesVector = $typesSet->getTypes();
	$sql = "SELECT `OriginID` FROM `dependencies` WHERE `TargetID`='$originID' AND `DependencyTypeID` IN(".$typesVector->implode().") ORDER BY `DependencyTypeID` LIMIT 0,1;";
    $rs = $db_conn->Execute($sql);
    return ($rs->RecordCount()>0); // here we don't return the sql because what is important is the recordSet exists or not
}
function deleteModuleFreelinks($moduleID){
	$db_conn = db_connect();
	$moduleInfo = moduleInfo($moduleID);
	$sql = "SELECT links.* FROM links LEFT  JOIN ".$moduleInfo->tableName." ON links.TargetID = ".$moduleInfo->tableName.".ID AND links.ModuleTargetID=$moduleID WHERE links.DependencyTypeID = 0 ";
	$sql.= " AND (".$moduleInfo->tableName.".ID IS NULL OR ".$moduleInfo->tableName.".IsLocked=0);";
	$total_sql = $sql;
	$rs = $db_conn->Execute($sql);
	$sql2 = "SELECT links.* FROM links LEFT  JOIN ".$moduleInfo->tableName." ON links.TargetID = ".$moduleInfo->tableName.".ID AND links.ModuleTargetID=$moduleID WHERE links.DependencyTypeID = 0 ";
	$sql2.= " AND (".$moduleInfo->tableName.".ID IS NULL OR ".$moduleInfo->tableName.".IsLocked=0);";
	$rs2 = $db_conn->Execute($sql);
	if($rs){
		$row = $rs->FetchRow();
		while ($row ){
			$del_sql = "DELETE FROM links WHERE DependencyTypeID=0 AND ModuleOriginID=".$row['ModuleOriginID']." AND ModuleTargetID=".$row['ModuleTargetID']." AND OriginID=".$row['OriginID']." AND TargetID=".$row['TargetID'].";";
			$db_conn->Execute($del_sql);
			$total_sql.=$del_sql;
			$row = $rs->FetchRow();
			if (!$row && $sql2){
				$total_sql.=$sql2;
				$rs = $rs2;
				$row = $rs->FetchRow();
				$sql2 = "";
			}
		}
	}
	return $total_sql;
}

include_once(dirname(__FILE__)."/../common/encoding_functions.inc.php");
//include_once(dirname(__FILE__)."/../common/nectil_user.class.php");
include_once(dirname(__FILE__)."/../common/config.inc.php");
require_once(dirname(__FILE__)."/../common/db_config.inc.php");
if (file_exists(dirname(__FILE__)."/../../db_config.inc.php"))
	include_once(dirname(__FILE__)."/../../db_config.inc.php");
require_once(dirname(__FILE__)."/../common/db_functions.inc.php");
require_once(dirname(__FILE__)."/../file/file_functions.inc.php");
/*require_once(dirname(__FILE__)."/../common/services.inc.php");*/
require_once(dirname(__FILE__)."/../common/XML.class.php");
require_once(dirname(__FILE__)."/../common/module.class.php");
require_once(dirname(__FILE__)."/../common/dependency.class.php");
include_once(dirname(__FILE__)."/../common/useful_vars.inc.php");
include_once(dirname(__FILE__)."/../common/image_functions.inc.php");
if (file_exists($GLOBALS["Public_dir"]."config.inc.php"))
	include_once($GLOBALS["Public_dir"]."config.inc.php");

?>
