<?PHP
// ------------------------------------------------------------------------- //
// <G a n e s h a> - Free Web Based Training System                          //
// ------------------------------------------------------------------------- //
// <G a n e s h a> - Plate-forme de téléformation gratuite et en open source //
// ------------------------------------------------------------------------- //
// Copyright (C) 2001  Anéma Formation  <http://www.anema-formation.fr/>     //
// ------------------------------------------------------------------------- //
//            Developer : Georges CALDEIRA <gcaldeira@anemalab.org>          //
// ------------------------------------------------------------------------- //
//               Infos on project <http://anemalab.org/>                     //
// ------------------------------------------------------------------------- //
//  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., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA //
// ------------------------------------------------------------------------- //

	$anema_file = "anema.inc.php" ;

	$Copyright = "// +----------------------------------------------------------------------------+\n";
	$Copyright.= "// | <G a n e s h a> - Free Web Based Training System                           |\n";
	$Copyright.= "// +----------------------------------------------------------------------------+\n";
	$Copyright.= "// | <G a n e s h a> - Plate-forme de téléformation gratuite et en open source  |\n";
	$Copyright.= "// +----------------------------------------------------------------------------|\n";
	$Copyright.= "// | Copyright (C) 2001  Anéma Formation  <http://www.anema-formation.fr/>      |\n";
	$Copyright.= "// +----------------------------------------------------------------------------+\n";
	$Copyright.= "// |           Developer : Georges CALDEIRA <gcaldeira@anemalab.org>            |\n";
	$Copyright.= "// +----------------------------------------------------------------------------+\n";
	$Copyright.= "// |              Infos on project <http://anemalab.org/>                       |\n";
	$Copyright.= "// +----------------------------------------------------------------------------+\n";
	$Copyright.= "// | This program is free software; you can redistribute it and/or modify       |\n";
	$Copyright.= "// | it under the terms of the GNU General Public License as published by       |\n";
	$Copyright.= "// | the Free Software Foundation; either version 2 of the License, or          |\n";
	$Copyright.= "// | (at your option) any later version.                                        |\n";
	$Copyright.= "// |                                                                            |\n";
	$Copyright.= "// | This program is distributed in the hope that it will be useful,            |\n";
	$Copyright.= "// | but WITHOUT ANY WARRANTY; without even the implied warranty of             |\n";
	$Copyright.= "// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the              |\n";
	$Copyright.= "// | GNU General Public License for more details.                               |\n";
	$Copyright.= "// |                                                                            |\n";
	$Copyright.= "// | You should have received a copy of the GNU General Public License          |\n";
	$Copyright.= "// | along with this program; if not, write to the Free Software                |\n";
	$Copyright.= "// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA   |\n";
	$Copyright.= "// +----------------------------------------------------------------------------+\n";

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	$version = "0.0" ;	 
	if( file_exists("../version.txt") ) {
		$file = "../version.txt" ;
		$fd=fopen($file,"rb");
		$version = fread($fd,filesize($file));
		fclose($fd);
	}

	/**
	* renomme un repertoire
	* @param	string $oldname repertoire a renommer
	* @param	string $newname nouveau nom
	* @access	public
	*/
	function renameDirectorie($oldname, $newname) { 
		if ( strlen( $oldname) == 0) {
			return(false); 
		}
		if ( ! is_dir( $oldname)) {
			return(false); 
		}
		if ( is_dir( $newname)) {
			return(false); 
		}
		if ( ! rename($oldname,$newname) ) {
			return(false); 
		}
		return(true);
	}
	
	/**
	* Affiche une chaine de debug et termine le script
	* @param	string	$val	valeur a afficher
	* @access	public
	*/
	function debug($val){
		if ( is_array($val) ) {
			print_r($val);
		} else {
			print("DEBUG : $val");
		}
		exit();
	}

	/**
	* Force l'affichage d'une nouvelle page
	* @param	string	$url	URL de la npuvelle page
	* @access	public
	*/
	function location($url) {
		header("Location: ".$url); 
		exit(); 
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	 function Retour() { 
		return ('<br><br><i><a HREF="javascript:history.go(-1)">-Retour-</a></i>');
	}

	/**
	* Retourne l'ID du fournisseur qui sera affecte a la variable $provider du 
	* fichier const.inc.php
	*/
	function IdFournisseur() {
	global $fournisseur ;
		switch($fournisseur) {
		case "Hebergeur classique" : 
		case "LocalHost" :	return "0"; 
		case "Free" : 		return "1"; 
		case "OnLine" :		return "2"; 
		case "Nexen" : 		return "3"; 
		case "Lycos" : 		return "4"; 
		}
	}

	/**
	* Retourne le real path en fonction de l'hebergeur
	*/
	function GetRealPath() {
	 global $fournisseur, $SCRIPT_FILENAME, $PATH_TRANSLATED ;
		switch($fournisseur) {
		case "Hebergeur classique" : 
		case "LocalHost" : 
		case "Free" :
				$mask = strstr($SCRIPT_FILENAME,"install")		;
				$ret  = str_replace($mask,"",$SCRIPT_FILENAME)	;
				if ( $ret == '' && isset($_SERVER['PATH_TRANSLATED']) ) {
					$mask = strstr($_SERVER['PATH_TRANSLATED'],"install")		;
					$ret  = str_replace($mask,"",$_SERVER['PATH_TRANSLATED'])	;					
				}
				break ;
		case "Lycos" :
				$mask = strstr($PATH_TRANSLATED,"install")		;
				$ret  = str_replace($mask,"",$PATH_TRANSLATED)	;
				break ;
		case "OnLine" :
		case "Nexen" :
				$ret = ""	;
				break		;
		}
		return($ret) ;
	}

	/**
	* Retourne l'URL en fonction de l'hebergeur
	*/
	function GetURL() {
		global $fournisseur, $PHP_SELF, $HTTP_REFERER;
		switch($fournisseur) {
		case "Hebergeur classique" : 
		case "LocalHost" : 
		case "Free" :
				$mask = strstr($HTTP_REFERER,"install")		;
				$ret  = str_replace($mask,"",$HTTP_REFERER)	;
				if ( $ret == '' && isset($_SERVER["HTTP_REFERER"]) ) {  // EasyPhp 1.7
					$mask = strstr($_SERVER["HTTP_REFERER"],"install")	;
					$ret  = str_replace($mask,"",$_SERVER["HTTP_REFERER"])	;
				}
				// Remplace le 127.0.0.1 par le nom de la machine
				// $_SERVER["COMPUTERNAME"] );
				//$ret  = str_replace("127.0.0.1",$_SERVER["COMPUTERNAME"],$ret)	;
				break ;
		case "Lycos" :
				$mask = strstr($PHP_SELF,"install")		;
				$ret  = str_replace($mask,"",$PHP_SELF)	;
				$ret  = "http://membres.lycos.fr" . $ret ;
				break ;
		case "OnLine" :
		case "Nexen" :
				$ret = "http://";
				break			;
		}
		return($ret) ;
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **  PHPMYADMIN + Modif Bug sur le '#'                                        **
	 *******************************************************************************/
	function split_sql($sql){
		$sql = trim($sql);
	// Modif Bug '#'
	//    $sql = ereg_replace("#[^\n]*\n", "", $sql);
		if(substr($sql,1,1)=="#") {
			$sql = ereg_replace("#[^\n]*\n", "", $sql);
		}

		$buffer = array();
		$ret = array();
		$in_string = false;

		for($i=0; $i<strlen($sql)-1; $i++) {
			 if($sql[$i] == ";" && !$in_string) {
				$ret[] = substr($sql, 0, $i);
				$sql = substr($sql, $i + 1);
				$i = 0;
			}

			if($in_string && ($sql[$i] == $in_string) && $buffer[0] != "\\") {
				 $in_string = false;
			} elseif(!$in_string && ($sql[$i] == "\"" || $sql[$i] == "'") && (!isset($buffer[0]) || $buffer[0] != "\\")) {
				 $in_string = $sql[$i];
			}
			if(isset($buffer[1])) {
				$buffer[0] = $buffer[1];
			}
			$buffer[1] = $sql[$i];
		 }

		if(!empty($sql)) {
			$ret[] = $sql;
		}

		return($ret);
	}

	/******************************************************************************
	**                                                                           **
	**                                                                           **
	**                                                                           **
	*******************************************************************************/
	function ConnectBdd() { 
	global $BDD;
		$connectid = @mysql_connect($BDD['server'], $BDD['user'], $BDD['pass'] ) 
			or die ("<b>Can't connect to the database !!</b>".Retour() ) ;
		if ($connectid) {
			 if (!@mysql_select_db($BDD['name'])) {
				  @mysql_close($connectid) ;
				  die ("<b>Can't open database !!</b>".Retour() ) ;				  
				  return(0);
			 }
			 return(1);
		}
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/	
	function InsertFile($sql_file){
		$myfile = @fopen($sql_file,"r") 
			or die("<b>Can't open file : ".$sql_file." </b>".Retour()); 
		$sql_query = addslashes(fread($myfile, filesize($sql_file)));
		fclose($myfile);
		$pieces  = split_sql($sql_query);
		$nb=count($pieces);
		for ($i=0; $i<$nb; $i++) {
			  $pieces[$i] = stripslashes(trim($pieces[$i]));
			  if(!empty($pieces[$i]) && $pieces[$i] != "#") {
				  $result = @mysql_query ( $pieces[$i]) 
					  or die("<b>Erreur insertion dans la base de donnees</b><br> Rqt = ".$pieces[$i]." <br>ErrNo = ".mysql_errno()." <br>Error = ".mysql_error()." <br>".Retour()); 
			  }
		}
	}


	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	function Update(){ 	
		// Update des modules
		$sSQL = "SELECT module_id,repertoire FROM list_module";
		$result = @mysql_query ( $sSQL) ;
		if ( $result == '' ) return;
		while($row = @mysql_fetch_array($result)) {
			$sSQL = "SELECT titre,numero,link FROM module_".$row["module_id"]; 
			$res  = @mysql_query ($sSQL) ;
			while($row2 = @mysql_fetch_array($res)) {
				$sSQL = "INSERT INTO module (id_module,titre,numero,link,norme,type) " ;
				$sSQL.= "VALUES (".$row["module_id"].",'".$row2["titre"]."',".$row2["numero"].",'".$row["repertoire"]."/".$row2["link"]."',0,1) " ;
				$ret  = @mysql_query ($sSQL) ;
			}
			$sSQL = "DROP TABLE IF EXISTS module_".$row["module_id"]; 
			$ret2  = @mysql_query ($sSQL) ;
		}

		// creation de la table news
		$sSQL = "SHOW TABLES LIKE 'news'";
		$result = @mysql_query ( $sSQL) ;
		if ( mysql_num_rows($result) == 0 ) {
			$sSQL = "CREATE TABLE news (";
  			$sSQL.= "id int(11) NOT NULL auto_increment,";
  			$sSQL.= "titre varchar(30) NOT NULL default '',";
  			$sSQL.= "msg text NOT NULL,";
  			$sSQL.= "date varchar(20) NOT NULL default '',";
  			$sSQL.= "id_groupe mediumint(9) NOT NULL default '0',";
  			$sSQL.= "id_user int(11) NOT NULL default '0',";
  			$sSQL.= "status char(1) NOT NULL default '',";
  			$sSQL.= "KEY id (id)";
			$sSQL.= ") TYPE=MyISAM;";
			$result = @mysql_query ( $sSQL) ;
			$sSQL = "INSERT INTO news VALUES (1, 'Ganesha', 'Ganesha est distribué par la société <br><a href=\"http://www.anema-formation.fr\" target=\"_blanck\" class=\"student\">Anema Formation</a>', '', 0, 0, '');";
			$result = @mysql_query ( $sSQL) ;
		} else {
			$sSQL = "ALTER TABLE news CHANGE text msg text NOT NULL" ;
			$result = @mysql_query ( $sSQL) ;
		}

		// Update des news
		$sSQL = "SELECT DISTINCT(id_groupe) FROM list_groupe WHERE id_groupe>0";
		$result = @mysql_query ( $sSQL) ;
		if ( $result == '' ) return ;
		while($row = @mysql_fetch_array($result)) {
			$sSQL = "SELECT * FROM news WHERE id_groupe=".$row['id_groupe'];
			$res = @mysql_query ($sSQL) ;
			if ( mysql_num_rows($res)==0 ) {
				$sSQL = "INSERT INTO news (id,titre,msg,date,id_groupe,id_user,status) ";
				$sSQL.= "VALUES ('','titre','message','',".$row['id_groupe'].",0,'') ";
				$result = @mysql_query ( $sSQL) ;				
			}
		}		

		// Update des repertoires pour les groupes sur le HD
		$sSQL = "SELECT DISTINCT(id_groupe),repertoire FROM list_groupe WHERE id_groupe>0";
		$result = @mysql_query ( $sSQL) ;
		//if ( $result == '' ) return ;
		$rep_groupe = RP_MAIN.'groupes/' ;

		while($row = @mysql_fetch_array($result)) {
			renameDirectorie($rep_groupe.$row['repertoire'], $rep_groupe.'GRP'.$row['id_groupe']) ;
			$id_groupe[] = $row['id_groupe'] ;
		}

		// Update des repertoires pour les groupes dans la bdd
		for($i=0;$i<count($id_groupe);$i++) {
			$sSQL = "UPDATE list_groupe SET repertoire='GRP".$id_groupe[$i]."' WHERE id_groupe=".$id_groupe[$i];
			$result = @mysql_query( $sSQL) ;
		}

	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	function DeletePhorum() { 
		$sSQL = "SELECT id FROM ga_forums";
		$result = @mysql_query ( $sSQL) ;
		if ( $result == '' ) return;
		while($row = @mysql_fetch_array($result)) {
			$sSQL = "DROP TABLE IF EXISTS g".$row["id"]; 
			$res  = @mysql_query ($sSQL) or die("<b>Erreur suppression de la table g".$row["module_id"]."</b>".Retour()); 
			$sSQL = "DROP TABLE IF EXISTS g".$row["id"]."_bodies"; 
			$res  = @mysql_query ($sSQL) or die("<b>Erreur suppression de la table g".$row["module_id"]."_bodies</b>".Retour()); 
		}
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	function CopyFile($source,$dest) {
		if ( ! @file_exists($source))
			die ("<b>Erreur fichier ".$source." inexistant</b><br>".Retour()) ;	
		@copy ( $source, $dest ) 
			or die ("<b>Erreur lors de la copie de </b>".$source." -> ".$dest.Retour());
	}
	 
	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	function CopyAnema() { 
	global $anema_file ;
		CopyFile ( $anema_file, RP_MAIN.$anema_file) 						;
		CopyFile ( $anema_file, RP_MAIN."bno/".$anema_file )    			;		
		CopyFile ( $anema_file, RP_MAIN."intro/".$anema_file )    			;
		CopyFile ( $anema_file, RP_MAIN."chat/".$anema_file )    			;
		CopyFile ( $anema_file, RP_MAIN."cv/".$anema_file ) 				;
		CopyFile ( $anema_file, RP_MAIN."formation/".$anema_file )			;
		CopyFile ( $anema_file, RP_MAIN."phorum/".$anema_file ) 			;
		CopyFile ( $anema_file, RP_MAIN."visiteurs20/".$anema_file )		;
		CopyFile ( $anema_file, RP_MAIN."visiteurs20/include/".$anema_file );
		CopyFile ( $anema_file, RP_GANESHA.$anema_file ) 					;
		CopyFile ( $anema_file, RP_GANESHA."admin/".$anema_file ) 			;
		//CopyFile ( $anema_file, RP_GANESHA."admin/insc/".$anema_file ) 		;
		CopyFile ( $anema_file, RP_GANESHA."bdd/".$anema_file ) 			;
		CopyFile ( $anema_file, RP_GANESHA."bdd/fpdf15/".$anema_file ) 		;
		CopyFile ( $anema_file, RP_GANESHA."aide/".$anema_file ) 			;
		CopyFile ( $anema_file, RP_GANESHA."commun/".$anema_file ) 			;
		CopyFile ( $anema_file, RP_GANESHA."stagiaire/".$anema_file ) 		;
		CopyFile ( $anema_file, RP_GANESHA."tuteur/".$anema_file ) 			;
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/	
	function WriteConfig($real_path, $server, $login, $password, $bdd, $url, $lang) { 
	global $Copyright ;
			if ( ! $fp = @fopen("./config.inc.php", "w") ) {
				return(false);
			}
			$date = getdate()				;
			$date = date("j/m/Y",$date["0"]);
			$url = trim($url);
			$real_path = trim($real_path);
			$data = "<?PHP\n";
			$data.= "///////////////////////////////////////////////////////\n";
			$data.= $Copyright ;
			$data.= "\n";
			$data.= "///////////////////////////////////////////////////////\n";
			$data.= "///// Auteur = G. CALDEIRA ".$date."\n";
			$data.= "///// Desc. : Gestion des constantes\n";
			$data.= "///////////////////////////////////////////////////////\n";		
			$data.= "\n";
			$data.= "// Gestion de la connexion a la base de donnees\n";
			$data.= "  \$BDD['name']   ='".trim($bdd)."';\n";
			$data.= "  \$BDD['user']   ='".trim($login)."';\n";
			$data.= "  \$BDD['pass']   ='".trim($password)."';\n";
			$data.= "  \$BDD['server'] ='".trim($server)."';\n";
			$data.= "\n";
			$data.= "// Chemin d'installation de la plate forme\n";
			$data.= "  define('RP_MAIN',    '".$real_path."');\n";
			$data.= "  define('RP_GANESHA', RP_MAIN.'ganesha/');\n";
			$data.= "\n";
			$data.= "// Adresse HTTP principale du site\n";
			$data.= "  define('HTTP_MAIN',    '".$url."') ;\n";  
			$data.= "  define('HTTP_GANESHA', HTTP_MAIN.'ganesha/')	;\n";
			$data.= "\n";
			$data.= "// Gestion dynamique de la langue\n";
			$data.= "  define('GLANG', 'lang/".$lang.".inc.php')\n" ;
			$data.= "\n";
			$data.= "?>";
			if ( ! $ret = @fwrite($fp, $data) ) {
				return(false);
			}
			if ( ! @fclose($fp) ) {
				return(false);
			}
			return(true);
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	function WriteAnema($real_path) { 
	global $Copyright, $anema_file ;
		$real_path = trim($real_path);
		if ( ! $fp = @fopen("./".$anema_file, "w") ) {
			return(false);
		}
		$data = "<?PHP\n" ;
		$data.= $Copyright ;
		$data.= "\n" ;
		$data.= "  \$connexion = (isset(\$HTTP_GET_VARS['connexion'])?\$HTTP_GET_VARS['connexion']:0);\n";
		$data.= "\n" ;
		$data.= "  \$inc_path   = '".$real_path."ganesha/inc/'   ;\n" ;		
		$data.= "  \$class_path = '".$real_path."ganesha/class/' ;\n" ;	
		$data.= "  include_once('".$real_path."ganesha/inc/include.inc.php')  ;\n" ;	
		$data.= "  include_once('".$real_path."ganesha/class/include.inc.php');\n" ;
		$data.= "\n";
		$data.= "  \$verif_connexion = (isset(\$verif_connexion)?\$verif_connexion:true);\n";
		$data.= "  if ( \$verif_connexion ) {\n";
		$data.= "    Init(\$connexion) ;\n";
		$data.= "  }\n";	
		$data.= "\n";
		$data.= "?>" ;
		if ( ! $ret = @fwrite($fp, $data) ) {
			return(false);	
		}
		if ( ! fclose($fp) ) {
			return(false);	
		}
		return(true);
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/
	function CopyConfig() { 
		CopyFile ( "config.inc.php", RP_GANESHA."inc/config.inc.php" );
	}

	/*******************************************************************************
	 **                                                                           **
	 **                                                                           **
	 **                                                                           **
	 *******************************************************************************/	
	function displayFile($file) {
		$contents = file($file);
		for($i=0;$i<count($contents);$i++) {
			//$val = str_replace(' ','&nbsp;',$contents[$i]);
			$val = htmlentities($contents[$i]) ;
			$val = str_replace(' ','&nbsp;',$val);
			print($val.'<br>');
		}		
	}

?>