<?php

/**------------------------------------------------
*
* This software is protected by copyright, please
* read the file COPYRIGHT.
* 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. Please
* read the file LICENCE.
*
* Ce fichier contient la classe Community
*
* @author Rooty <www.qware.fr|rooty@rooty.me>
* @since 2020/12/12
* @version 0.1
* @link www.qware.fr
* @package object_coordination
* @subpackage Community
* @copyright Copyleft 2020
*/

if ( !defined('SYSTEM_IN') )
{
	die("Hacking attempt");
}

/**
* Classe Community
*
* Classe d'affichage des communautés et des inscriptions
* @package object_coordination
* @subpackage Community
*/

Class Community extends CoordinationObj
{
/**
* Function affichant en lecture seule les communautés pour la page publique de Qware
* @access public
* @return chaine chaine html
*/
	function actionLecture()
	{
		global $SERVER_NAME, $SCRIPT_NAME, $CONF_PERSISTANT_SECURE,$CONF_DATA_PATH;

		/*Récupération des messages utilisateurs*/
		addMessageFile("user.ini");

		/* gestion du lib en fonction de la langue courante */
		$currentCode=$GLOBALS["SYSTEM_USER_SESSION"]->langue->getCode();
		$defaultCode=$GLOBALS["SYSTEM_DEFAULT_LANGUAGE_CODE"];
		/* fin récupération des codes par defaut */
		
		mxPageTitle("titlPageSelectCommunities");
		
		/* On inclus la template (voir package.template.php) */
		WithBlocPath("Community", "actionLecture");

		$tab = $GLOBALS['SYSTEM_MANAGER']['NODE']->getInstanceFromIdPere(1);

		for ($i=0; $i<count($tab);$i++)
		{
			$lib=$tab[$i]->getLibelle($currentCode);
			$key = $tab[$i]->getId();
			if ($lib=="")
			{
				$lib=$tabNode[$i]->getLibelle($defaultCode);
			}
			$tabNode[$i][0]= $key;
			$tabNode[$i][1]= $lib;
		}

		krsort($tabNode);	
		reset($tabNode);
		
		$idNode = $msg =""; //On fixe à rien l'identifiant du noeud par défaut
		/* On teste si l'id de communauté est passé (méthode GET ou POST) */
		if(isset($_REQUEST['param']))
		{
			//On masque le texte d'intro affiché par défaut à partir de message
			$GLOBALS["SYSTEM_TEMPLATE"]->MxText("ComTextdefault","");

			//Si aucune valeur, on demande à l'utilisateur de choisir une communauté
			if(!$_REQUEST['param'])
			{
				$GLOBALS["SYSTEM_TEMPLATE"]->MxText("ComText", getMessage("selectCom"));
				$GLOBALS["SYSTEM_CONTROL"]->messageSystem = "selectCom";
				$msg= "selectCom";
			}
			else //Sinon on récupère la valeur
			{
				$idNode = $_REQUEST['param'];
			}
		}

		$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("urlReturn", htmlentitiesconv($GLOBALS['CONF_PAGE_EXECUTION']."?id=".$GLOBALS['SYSTEM_USER_SESSION']->id."&system=navigationNode&navigationNodeId=".$GLOBALS["SYSTEM_USER_SESSION"]->entryNodeId));

		$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("urlAction", formatUrl($this->GetId(), "Community", "actionLecture", $msg));

		//Initialisation des compteurs
		$j =1;
		$c =1;
		$nbPrint=0;
		$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("ligne.col.ClassName","cadre1");
		//Parcours des noeuds
		for($i= (count($tabNode)-1);$i>0;$i--)
		{
			if ($tabNode[$i][0] != 2 && $tabNode[$i][0] != 3)
			{
				if( $nbPrint < 12)
				{
					//Affiche la communauté dans la langue courante et formate l'url pour le lien vers le détail
					$GLOBALS["SYSTEM_TEMPLATE"]->MxText("ligne.col.node",$tabNode[$i][1]);
					$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("ligne.col.urlget",formatUrl($this->getId(), "Community", "actionLecture", "", $tabNode[$i][0]));
					$GLOBALS['SYSTEM_TEMPLATE']->MxText("ligne.col.imgPath", $GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR']);

					switch($c)
					{
						case 1 :
						$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("ligne.col.color","cadre1");
						break;
						case 2 :
						$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("ligne.col.color","cadre2");
						break;
						default :
						$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("ligne.col.color","cadre3");
						break;
					}
					$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("ligne.col", "loop");
					$j++;
					$nbPrint++;
					if ($j==5)
					{
						$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("ligne", "loop");
						$c++;
						$j=1;
					}
				}

				//On récupère le nom de la communauté dans la langue courante
				$GLOBALS["SYSTEM_TEMPLATE"]->MxText("bloc1.entrynode", $tabNode[$i][1]);

				if($tabNode[$i][0] == $idNode) //si le noeud de la boucle égale celui sélectionné
				{
					//On récupère le texte du noeud choisi par l'internaute
// 					$sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$idNode;
					$sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$idNode." AND langue_id=".$GLOBALS["SYSTEM_USER_SESSION"]->langue->getId();
					# Exécution de Requete
					$result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);

					# Teste si il y a des enregistrements
					if ($GLOBALS['SYSTEM_DATABASE_CONN']->sql_numrows()>0)
					{
							$list = $GLOBALS['SYSTEM_DATABASE_CONN']->sql_fetchrow();
// 							$text = $list['text_resume'];
							$text = $list['textentrynode_resume'];
							//On masque le texte d'intro affiché par défaut à partir de message
							$GLOBALS["SYSTEM_TEMPLATE"]->MxText("ComTextdefault", "");
							$GLOBALS["SYSTEM_TEMPLATE"]->MxText("text_resume", $text);
					}

					# Destruction des éléments
					$GLOBALS['SYSTEM_DATABASE_CONN']->sql_freeresult();
					#Affichage des contenus
					$GLOBALS["SYSTEM_TEMPLATE"]->MxText("ComText",$tabNode[$i][1]);
					$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("bloc1.entrynodeid",$tabNode[$i][0]);
					$GLOBALS["SYSTEM_TEMPLATE"]->MxText("bloc1.entrynodeselected"," selected='selected' ");
					$url_inscrire = formatUrl($this->GetId(),"Community","formlecture","",$tabNode[$i][0]);
					$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("inscrire", "button", "ok", getMessage("registerCom"), " onclick=\"javascript:window.location.href='$url_inscrire';\"");
				}
				else
				{
					$GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("bloc1.entrynodeid",$tabNode[$i][0]);
					$GLOBALS["SYSTEM_TEMPLATE"]->MxText("bloc1.entrynodeselected","");
				}
				$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("bloc1", "loop");
			}
		}
		$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("ligne", "loop");
		ExitBloc();
		return "";
	}

/**
* Function affichant le texte de présentation détaillé pour le noeud d'entrée une fois authentifié
* @access public
* @return chaine chaine vide
*/
	function actionAccueil()
	{
		global $SERVER_NAME, $SCRIPT_NAME, $CONF_PERSISTANT_SECURE,$CONF_DATA_PATH;
		
		/*Récupération des messages utilisateurs*/
		addMessageFile("user.ini");

		/* gestion du lib en fonction de la langue courante */
		$currentCode=$GLOBALS["SYSTEM_USER_SESSION"]->langue->getCode();
		$defaultCode=$GLOBALS["SYSTEM_DEFAULT_LANGUAGE_CODE"];
		/* fin récupération des codes par defaut */
		
		/* On inclus la template (voir package.template.php) */
		WithBlocPath("Community", "actionAccueil");

		//Récupération de l'identifiant de la communauté : methode en fin de page
		$nodeId = recupCommunity();

		if(is_numeric($nodeId)) //si le noeud existe
		{
			//On récupère le texte du noeud choisi par l'internaute
			$sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$nodeId;
		        # Exécution de Requete
        		$result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);

		        # Teste si il y a des enregistrements
        		if ($GLOBALS['SYSTEM_DATABASE_CONN']->sql_numrows()>0)
                	{
                        	$list = $GLOBALS['SYSTEM_DATABASE_CONN']->sql_fetchrow();
                        	$text = $list['text'];
				$GLOBALS["SYSTEM_TEMPLATE"]->MxText("textAccueil",$text);
                	}else{
				$GLOBALS["SYSTEM_TEMPLATE"]->MxText("textAccueil",getMessage("NoText"));
			}

	    		# Destruction des éléments
    		    	$GLOBALS['SYSTEM_DATABASE_CONN']->sql_freeresult();
		}
		ExitBloc();
		return "";
	}



/**
* Function permettant de rafficher le contenu pour modification dans la bd
* @access public
* @return chaine chaine html
*/
    function actionAdmin()
    {

		/* On inclus la template (voir package.template.php) */
		WithBlocPath("Community", "actionAdmin");

        global $SERVER_NAME, $SCRIPT_NAME, $CONF_PERSISTANT_SECURE,$CONF_DATA_PATH;


        /* gestion du lib en fonction de la langue courante */
        $currentCode=$GLOBALS["SYSTEM_USER_SESSION"]->langue->getCode();
        $defaultCode=$GLOBALS["SYSTEM_DEFAULT_LANGUAGE_CODE"];
        /* fin récupération des codes par defaut */

		//Récupération de l'identifiant de la communauté : methode en fin de page
		$nodeId = recupCommunity();

        $url=$SCRIPT_NAME;
        $url=addIdToUrl($url); //Ajoute l'identifiant de navigation à l'url
        /* fin de l'url générale */

        # Requete sur identifiant de l objet de coordination correspondant
        $sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$nodeId;
        # Exécution de Requete
        $result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);

						
        # Teste si il y a des enregistrements
        if ($GLOBALS['SYSTEM_DATABASE_CONN']->sql_numrows()>0)
                {
                        $list = $GLOBALS['SYSTEM_DATABASE_CONN']->sql_fetchrow();
                        $text = $list['text'];
                        $text_resume = $list['text_resume'];
                }
				else
				{
					$text = $text_resume = "";
				}

        # Récupération des étiquette du formulaire
        $GLOBALS["SYSTEM_TEMPLATE"]->MxText("libelle", getMessage("textinfo"));
        $GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("urlAction", formatUrl($this->getId(),"Community","execAdmin"));


        # Destruction des éléments
        $GLOBALS['SYSTEM_DATABASE_CONN']->sql_freeresult();

        $wysiwyg = new wysi("text_resume", "fmtextinfo", $text_resume, "fck", "100%","200", ""); //Récupération du Webword
		$GLOBALS["SYSTEM_TEMPLATE"]->MxText("text_resume", $wysiwyg->Display());

        $wysiwyg = new wysi("text", "fmtextinfo", $text, "fck", "99%","400", ""); //Récupération du Webword
        $GLOBALS["SYSTEM_TEMPLATE"]->MxText("wysiwyg", $wysiwyg->Display());

	ExitBloc();
        return "";
	}

/**
* Function permettant de modifier le contenu dans la bd et redirection(traitement)
* @access public
* @return chaine chaine vide
*/
    function execAdmin()
    {
        global $SERVER_NAME, $SCRIPT_NAME, $CONF_PERSISTANT_SECURE,$CONF_DATA_PATH;

		//Récupération de l'identifiant de la communauté : methode en fin de page
		$nodeId = recupCommunity();

        # Requete sur identifiant de l objet de coordination correspondant
        $sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$nodeId;
        # Exécution de Requete
        $result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);

						
        # Teste si il y a des enregistrements
        if ($GLOBALS['SYSTEM_DATABASE_CONN']->sql_numrows()>0)
        {                       		
	        # Requete sur identifiant de l objet de coordination correspondant
    	    $sql="UPDATE ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode SET text='".$_POST['text']."',text_resume='".$_POST['text_resume']."' WHERE node_id=".$nodeId;

	        # Exécution de Requete
    	    $result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);
		}
		else
		{
	        # Requete sur identifiant de l objet de coordination correspondant
    	    $sql="INSERT INTO ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode (text, text_resume, node_id) VALUES ('".$_POST['text']."','".$_POST['text_resume']."',".$nodeId.")";

	        # Exécution de Requete
    	    $result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);		
		}

        # Destruction des éléments
        $GLOBALS['SYSTEM_DATABASE_CONN']->sql_freeresult();

        # Redirection vers le formulaire
        systemRedirect(formatUrl($this->getId(),"Community","actionAdmin","datamodified"));
        return "";
    }


/**
* Function permettant d'afficher le formulaire de pré-inscription pour enregistrement dans la bd
* @access public
* @param tableau
* @return chaine chaine html
*/
    function formLecture($tabPOST="")
    {
        global $SERVER_NAME, $SCRIPT_NAME, $CONF_PERSISTANT_SECURE,$CONF_DATA_PATH;

        /*Récupération des messages utilisateurs*/
		addMessageFile("user.ini");
		addMessageFile("subscriptions.ini");
		
		/* gestion du lib en fonction de la langue courante */
		$currentCode=$GLOBALS["SYSTEM_USER_SESSION"]->langue->getCode();
		$defaultCode=$GLOBALS["SYSTEM_DEFAULT_LANGUAGE_CODE"];
		/* fin récupération des codes par defaut */

		// titlPageInscription + ComText
		mxPageTitle("titlPageInscription");
		
		$arrayCallCss = array();
        $arrayCallCss[] = "data/css/bootstrap-datepicker/1.9.0/bootstrap-datepicker3.min.css";
        mxCallCss($arrayCallCss);

        $arrayCallJs = array();
        $arrayCallJs[] = "data/javascript/bootstrap-datepicker/1.9.0/bootstrap-datepicker.min.js";
        $arrayCallJs[] = "data/javascript/bootstrap-datepicker/1.9.0/locales/bootstrap-datepicker.fr.min.js";
        mxCallJs($arrayCallJs);
        
        $arrayRawJs[] = "\$(document).ready(function(){\$('.datepicker').datepicker(); });";
//         $arrayRawJs[] = "\$(document).ready(function(){\$(function(){\$(\"#fmtextinfo :input\").tooltip({position: \"top center\",offset: [0, 1],effect: \"slide\",opacity: 0.7,tip: '.tooltipRegUserForm'}),\$('.qaptcha').QapTcha({disabledSubmit: true,autoRevert : true,autoSubmit:false,PHPfile: "<mx:text id=\"urlQaptcha\"/>",txtLock: \"<mx:text id=\"textQaptchaLock\"/>\",txtUnlock: \"<mx:text id=\"textQaptchaUnlock\"/>\"});});";
        mxRawJs($arrayRawJs);
        
		/* On inclus la template (voir package.template.php) */
		WithBlocPath("Community", "formlecture");

		if(isset($_GET['param']))
		{
			$myNoeud = $GLOBALS['SYSTEM_MANAGER']['NODE']->createInstance($_GET['param']);
			$libmyNoeud = $myNoeud->getLibelle($currentCode);
			$messageInscriptionNoeud = "&nbsp;:&nbsp;".$libmyNoeud;
			$GLOBALS['SYSTEM_TEMPLATE']->MxText("messageInscriptionNoeud", $messageInscriptionNoeud);
			
			# Contenu du résumé de la communauté
			$sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$_GET['param']." AND langue_id=".$GLOBALS["SYSTEM_USER_SESSION"]->langue->getId();
			$result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);

			# Teste si il y a des enregistrements
			if ($GLOBALS['SYSTEM_DATABASE_CONN']->sql_numrows()>0)
			{
					$list = $GLOBALS['SYSTEM_DATABASE_CONN']->sql_fetchrow();
					$text = $list['textentrynode_resume'];
					$GLOBALS["SYSTEM_TEMPLATE"]->MxText("text_resume", $text);
			} else {
					$GLOBALS["SYSTEM_TEMPLATE"]->MxText("text_resume", $noCommunityTextResume);
			}
		}

		# Destruction des éléments
		$GLOBALS['SYSTEM_DATABASE_CONN']->sql_freeresult();
        # Récupération des étiquette du formulaire
        $GLOBALS["SYSTEM_TEMPLATE"]->MxAttribut("urlAction", formatUrl($this->getId(),"Community","execLecture","",$_GET['param']));

        $GLOBALS["SYSTEM_TEMPLATE"]->MxText("urlReturn",formatUrl($this->getId(),"Community","actionLecture"));
//         $GLOBALS["SYSTEM_TEMPLATE"]->MxText("urlQaptcha", formatUrl($this->getId(),"Community","formLectureQaptcha"));
		# Affichage des champs de formulaire pour l'inscription
		if(!$tabPOST)
		{
			$titre = array(getMessage("mr"),getMessage("mrs"), getMessage("miss"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxSelect("user_title", "user_title", "", $titre, getMessage("user_title"), "", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipSelectTitle"), ENT_QUOTES)."\"");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_first_name", "text", "user_first_name", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipFirstName"), ENT_QUOTES)."\"", getMessage("user_first_name"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_last_name", "text", "user_last_name", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipLastName"), ENT_QUOTES)."\"", getMessage("user_last_name"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_login", "text", "user_login", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipLogin"), ENT_QUOTES)."\"", getMessage("user_login"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_mail", "email", "user_mail", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipCourriel"), ENT_QUOTES)."\"", getMessage("user_mail"));
			
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_password", "password", "user_password", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipPassword"), ENT_QUOTES)."\"", getMessage("user_password"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_password2", "password", "user_password2", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipPassword2"), ENT_QUOTES)."\"", getMessage("user_password"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_birthdate", "text", "user_birthdate", "jj/mm/aaaa", "class=\"form\" required=\"true\" data-provide=\"datepicker\" data-date-format=\"dd/mm/yyyy\" data-date-language=\"fr\" title=\"".htmlspecialchars(getMessage("tipBirthDate"), ENT_QUOTES)."\"", getMessage("user_birthdate"));
			
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_msn", "text", "user_msn", "", "class=\"form\" title=\"".htmlspecialchars(getMessage("tipUserMsn"), ENT_QUOTES)."\"", getMessage("user_msn"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_jabber", "text", "user_jabber", "", "class=\"form\" title=\"".htmlspecialchars(getMessage("tipUserJabber"), ENT_QUOTES)."\"", getMessage("user_jabber"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_facebook", "text", "user_facebook", "", "class=\"form\" title=\"".htmlspecialchars(getMessage("tipUserFacebook"), ENT_QUOTES)."\"", getMessage("user_facebook"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_mastodon", "text", "user_mastodon", "", "class=\"form\" title=\"".htmlspecialchars(getMessage("tipUserMastodon"), ENT_QUOTES)."\"", getMessage("user_mastodon"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_website", "text", "user_website", "", "class=\"form\" title=\"".htmlspecialchars(getMessage("tipUserWebsite"), ENT_QUOTES)."\"", getMessage("user_website"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_code", "text", "user_postal_code", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipPostalCode"), ENT_QUOTES)."\"", getMessage("user_postal_code"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_adress", "text", "user_postal_adress", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipPostalAddress"), ENT_QUOTES)."\"", getMessage("user_postal_address"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_addressmand", "text", "user_postal_addressmand", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipPostalAddress"), ENT_QUOTES)."\"", getMessage("user_postal_address"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_city", "text", "user_city", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipCity"), ENT_QUOTES)."\"", getMessage("user_city"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_state", "text", "user_state", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipState"), ENT_QUOTES)."\"", getMessage("user_state"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_country", "text", "user_country", "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipCountry"), ENT_QUOTES)."\"", getMessage("user_country"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_tel", "text", "user_tel", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipTel"), ENT_QUOTES)."\"", getMessage("user_tel"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_fax", "text", "user_fax", "", "class=\"form\" required=\"false\" title=\"".htmlspecialchars(getMessage("tipFax"), ENT_QUOTES)."\"", getMessage("user_fax"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxCheckerField("charteSite", "checkbox", "charteSite", 1, "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipIAccept"), ENT_QUOTES)."\"");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxCheckerField("blocSubscriptionsForms".".subscriptionform", "checkbox", "subscriptionform", 1, "", "class=\"form\" required=\"true\" title=\"".htmlspecialchars(getMessage("tipAcceptSubscriptionForm"), ENT_QUOTES)."\"");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxCheckerField("blocSubscriptionsForms".".subsmladh", "checkbox", "subsmladh", 1, "", "title='".htmlspecialchars(getMessage("tipAcceptSubsMLAdh"), ENT_QUOTES)."'");
			if( file_exists($GLOBALS["CONF_DATA_PATH"]."data/message/".$currentCode."/charte_inscription_".$_GET['param'].".inc") )
			{
				$file=new File($GLOBALS["CONF_DATA_PATH"]."data/message/".$currentCode."/charte_inscription_".$_GET['param'].".inc", "r");
				$GLOBALS["SYSTEM_TEMPLATE"]->MxText("charteSiteContent", $file->readAll());
			} else
				$GLOBALS["SYSTEM_TEMPLATE"]->MxText("charteSiteContent", htmlspecialchars(getMessage("textNoCharte")));
		}
		else // On raffiche les données saisies par l'utilisateur
		{
			$titre = array(getMessage("mr"),getMessage("mrs"),getMessage("miss"));
			$GLOBALS["SYSTEM_TEMPLATE"]->MxSelect("user_title", "user_title",$_POST['user_title'], $titre, "", "");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_first_name", "text", "user_first_name", $_POST['user_first_name']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_last_name", "text", "user_last_name", $_POST['user_last_name']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_login", "text", "user_login", $_POST['user_login']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_password", "password", "user_password", "");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_password2", "password", "user_password2", "");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_mail", "text", "user_mail", $_POST['user_mail']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_birthdate", "text", "user_birthdate", $_POST['user_birthdate']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_msn", "text", "user_msn", $_POST['user_msn']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_jabber", "text", "user_jabber", $_POST['user_jabber']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_facebook", "text", "user_facebook", $_POST['user_facebook']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_mastodon", "text", "user_mastodon", $_POST['user_mastodon']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_website", "text", "user_website", $_POST['user_website']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_code", "text", "user_postal_code", $_POST['user_postal_code']);
			
			if( isset($_POST['user_postal_adress']) )
				$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_adress", "text", "user_postal_adress", $_POST['user_postal_adress']);
			else
				$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_adress", "text", "user_postal_adress", $_POST['user_postal_addressmand']);
			
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_postal_adressmand", "text", "user_postal_adressmand", $_POST['user_postal_adressmand']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_city", "text", "user_city", $_POST['user_city']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_state", "text", "user_state", $_POST['user_state']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_country", "text", "user_country", $_POST['user_country']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_tel", "text", "user_tel", $_POST['user_tel']);
			$GLOBALS["SYSTEM_TEMPLATE"]->MxFormField("user_fax", "text", "user_fax", $_POST['user_fax']);
			
			if(  isset($_POST["charteSite"]) && $_POST["charteSite"] == 1 )
				$GLOBALS["SYSTEM_TEMPLATE"]->MxCheckerField("charteSite", "checkbox", "charteSite", 1, "checked=checked");
			else
				$GLOBALS["SYSTEM_TEMPLATE"]->MxCheckerField("charteSite", "checkbox", "charteSite", 1, "");

			$GLOBALS["SYSTEM_TEMPLATE"]->MxCheckerField("blocSubscriptionsForms".".subsmladh", "checkbox", "subsmladh", 1, "", "title='".htmlspecialchars(getMessage("tipAcceptSubsMLAdh"), ENT_QUOTES)."'");
			$file=new File($GLOBALS["CONF_DATA_PATH"]."data/message/".$currentCode."/charte_inscription_".$_GET['param'].".inc", "r");
			$GLOBALS["SYSTEM_TEMPLATE"]->MxText("charteSiteContent", $file->readAll());
		}
		ExitBloc();
        return "";

    }

	public function formLectureQaptcha()
	{
	
		$GLOBALS["SYSTEM_TEMPLATE"] = new ModeliXeQware($GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR']."object_coordination/community/ajaxdata.mxt");
		$GLOBALS["SYSTEM_TEMPLATE"]->SetMxFileParameter($GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR'].$GLOBALS['SYSTEM_TEMPLATE_CONF']);
		$GLOBALS["SYSTEM_TEMPLATE"]->SetModeliXe(true);
		
		$aResponse['error'] = false;
	
		if(isset($_POST['action']) && isset($_POST['qaptcha_key']))
		{
			$_SESSION['qaptcha_key'] = false;	
			
			if(htmlentities($_POST['action'], ENT_QUOTES, 'UTF-8') == 'qaptcha')
			{
				$_SESSION['qaptcha_key'] = $_POST['qaptcha_key'];
				echo json_encode($aResponse);
			}
			else
			{
				$aResponse['error'] = true;
				echo json_encode($aResponse);
			}
		}
		else
		{
			$aResponse['error'] = true;
			echo json_encode($aResponse);
		}
	}

/**
* Function permettant de controler les doublons, d'inscrire dans la bd et redirection avec message
* @access public
* @return chaine chaine vide
*/
    function execLecture()
    {
        global $SERVER_NAME, $SCRIPT_NAME, $CONF_PERSISTANT_SECURE,$CONF_DATA_PATH;

		/* gestion du lib en fonction de la langue courante */
		$currentCode=$GLOBALS["SYSTEM_USER_SESSION"]->langue->getCode();
		$defaultCode=$GLOBALS["SYSTEM_DEFAULT_LANGUAGE_CODE"];
		/* fin récupération des codes par defaut */

		/*Récupération des messages utilisateurs*/
		addMessageFile("user.ini");
		//On vide la chaine de vérification des champs obligatoires
		$chaine = "";

		if($_POST)
		{
			foreach($_POST as $cle=>$val)
			{
			//	echo "cle = ".$cle." val =".$val."<br>";
				if($val=="" && ($cle !="user_comment" && $cle !="user_fax" && $cle !="user_organisation" && $cle !="user_country"))
				{
					$chaine .= getMessage($cle).", ";
				}
			}
			if($chaine!="")
			{
			$chaine .= getMessage('obligatory');
			}
		}

/*
* Olivier case du chemin.... :-(
* 22/06/05
*/
		//Si certains champs sont manquants pour l'inscription
		if ($chaine != "")
		{
			$GLOBALS["SYSTEM_CONTROL"]->messageSystem = $chaine;
			$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("DATA", "modify", $GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR']."object_coordination/community/formlecture.mxt");
			$GLOBALS["SYSTEM_TEMPLATE"]->WithMxPath("DATA", "relative");
			$this->formLecture($_POST);
			return "";
		}
		else
		{
			if($_POST["user_password"] != $_POST["user_password2"])
			{
				$GLOBALS["SYSTEM_CONTROL"]->messageSystem = "password_error";
				$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("DATA", "modify", 		$GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR']."object_coordination/community/formlecture.mxt");
				$GLOBALS["SYSTEM_TEMPLATE"]->WithMxPath("DATA", "relative");
				$this->formLecture($_POST);
				return "";
			}

		}
/*
* Olivier DEVAINE 13/01/05 -> plus besoin de la charte
*/
//		if(isset($_POST['user_chart']))
//		{
			/*Inclusion de la librairie UserManagerDb pour effectuer l'insertion et la vérif dans la table sys_user_temp*/
			include_once($GLOBALS['CONF_LIB_PATH']."lib/system/system_data/User/ressource/usermanagerdb.php");
			//Création de l'objet
			$MyManager=new UserManagerDb();
			//On fixe la table par la méthode getTable
			$MyManager->setTable("sys_user_temp");

			/*Inclusion de la librairie NodeGroupUserManagerDb pour effectuer l'insertion dans la table sys_node_group_user_temp*/
			include_once($GLOBALS['CONF_LIB_PATH']."lib/system/system_data/NodeGroupUser/ressource/nodegroupusermanagerdb.php");
			//Création de l'objet
			$MyNodeGroupUser=new NodeGroupUserManagerDb();
			//On fixe la table par la méthode getTable
			$MyNodeGroupUser->setTable("sys_node_group_user_temp");

			# Teste si il y a des enregistrements sur MyManager (table temporaire) ou sur la table des comptes
			if (($MyManager->checkValid($_POST["user_login"], $_POST["user_password"]) != 0) || ($GLOBALS['SYSTEM_MANAGER']['USER']->checkValid($_POST["user_login"], $_POST["user_password"]) != 0))
			{
				$GLOBALS["SYSTEM_CONTROL"]->messageSystem = "user_exist";
				$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("DATA", "modify", $GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR']."object_coordination/Community/formlecture.mxt");
				$GLOBALS["SYSTEM_TEMPLATE"]->WithMxPath("DATA", "relative");
				$this->formLecture($_POST);
	//			systemRedirect(formatUrl($this->getId(),"Community","formLecture","user_exist"));
			  }
			else
			  {
				//On créé un nouvel objet User pour effectuer l'insertion de chaque champs
				$MyUser=new User();

				$MyUser->setTitle($_POST['user_title']);
				$MyUser->setFirstName($_POST['user_first_name']);
				$MyUser->setLastName($_POST['user_last_name']);
				$MyUser->setLogin($_POST['user_login']);
				$MyUser->setPassword($_POST['user_password']);
				$MyUser->setMail($_POST['user_mail']);
				$MyUser->setPostalAddress($_POST['user_postal_address']);
				$MyUser->setPostalCode($_POST['user_postal_code']);
				$MyUser->setCity($_POST['user_city']);
				$MyUser->setState($_POST['user_state']);
				$MyUser->setCountry($_POST['user_country']);
				$MyUser->setOrganisation($_POST['user_organisation']);
				$MyUser->setTel($_POST['user_tel']);
				$MyUser->setFax($_POST['user_fax']);
				$MyUser->setComment($_POST['user_comment']);
				//On enregistre les paramètres
				$ObjUsersave = $MyManager->saveInstance($MyUser);

				//Insertion du noeud temporaire de l'utilisateur
				//Champs concernés : user_id, group_id, node_id, is_node_only, is_forbidden
				$MyNodeUser =new NodeGroupUser();
				$MyNodeUser->setUserId($ObjUsersave->getId());
				if(isset($_GET['param']))
				{
					$MyNodeUser->setNodeId($_GET['param']);
				}
				$MyNodeUser->setGroupId(0);
				$MyNodeUser->setIsForbidden(0);
				$MyNodeUser->setIsNodeOnly(0);

				//on enregistre les paramètres
				$test = $MyNodeGroupUser->saveInstance($MyNodeUser);

				/*Indexation dans le moteur de recherche*/
				if (includePackage("search.php")){
					$status=1;
					Search::addSearch("&param=".$ObjUsersave->getId(), "usertemp", array("actionManageRegister"=>"actionManageRegister"), $MyUser->getFirstName()." ".$MyUser->getLastName(), $MyUser->getMail()." ".$MyUser->getTel(), "", $status, 0, 0, 0, $_GET['param']);
					/*On récupère l'oid de l'objet dans les droits selon le nid de la communauté*/
					/*$oidObj = Search::getOidFromNameAndNode("usertemp", $_GET['param']);
					if($oidObj != 0)
					{
					Search::addSearch("&param=".$ObjUsersave->getId(), "usertemp", array("actionManageRegister"=>"actionManageRegister"), $MyUser->getFirstName()." ".$MyUser->getLastName(), $MyUser->getMail()." ".$MyUser->getTel(), "", $status, $oidObj);
					}*/
				}

				# Redirection vers le formulaire
				systemRedirect(absoluteUrl("user_subscribe",$_GET['param']));
			}
//		}
//		else //si la Charte n'est pas validée
//		{
//				$GLOBALS["SYSTEM_CONTROL"]->messageSystem = "chartnessaryaccept";
//				$GLOBALS["SYSTEM_TEMPLATE"]->MxBloc("DATA", "modify", $GLOBALS['SYSTEM_TEMPLATE_PATH'].$GLOBALS['SYSTEM_TEMPLATE_DIR']."object_coordination/Community/formLecture.mxt");
//				$GLOBALS["SYSTEM_TEMPLATE"]->WithMxPath("DATA", "relative");
//				$this->formLecture($_POST);
//		}
        return "";
    }

	/**
	* getAllRow4Export : recupere tous les enregistrements utilisé par l'objet de coordination 
	* le tableau est constiué de la nom_du_champ=valeur_du_champ
	* Si aucune données n'est à exporter, la méthode return null
	* @access public
	* @return tableau associatif
	*/
	function getAllRow4Export(){
		$nodeId = recupCommunity();
		$datas = array();
		
		if(is_numeric($nodeId)){
			$sql="SELECT * FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$nodeId;
        		$result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);
			if ($GLOBALS['SYSTEM_DATABASE_CONN']->sql_numrows()>0){
				$dataReturn = array();
				while($list = $GLOBALS['SYSTEM_DATABASE_CONN']->sql_fetchrow())
					$dataReturn[]=$list;
				$GLOBALS['SYSTEM_DATABASE_CONN']->sql_freeresult();

				$datas[0]["tableName"]=DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode";
				$datas[0]["datas"]=$dataReturn;
				return $datas;
			}
		}
		return null;
	}

	/**
	* setAllRow4Import : Insert les donnes en provenance du tableau associatif
	* le tableau est constiué de la nom_du_champ=valeur_du_champ
	* Si les enregistrements se sont bien sauvegardés, return true
	* @access public
	* @param boolean
	*/
	function setAllRow4Import($tableau){
		$nodeId = recupCommunity();

		if(is_numeric($nodeId)){
			$sql="DELETE FROM ".DATA_ACCES_TABLE_PREFIX.DATA_ACCES_OBJECT_PREFIX."textentrynode WHERE node_id=".$nodeId;
        		$result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);
		}

		for($j=0;$j < count($tableau);$j++){
			$tableName = $tableau[$j]["tableName"];
			$tableElem = $tableau[$j]["datas"];

			for($i=0;$i <count($tableElem);$i++){	
				unset($set);
				unset($values);
	
				foreach($tableElem[$i] as $key=>$value){
					if(!is_numeric($key)){
						(!isset($set))?$set=$key:$set.=",".$key;
						(!isset($values))?$values="'".$value."'":$values.=",'".$value."'";
					}
				}
				$sql = "INSERT INTO ".$tableName." (".$set.") VALUES(".$values.")";
				$result=$GLOBALS['SYSTEM_DATABASE_CONN']->sql_query($sql);
			}
		}
		return true;
	}
}
?>
