<?php
/* daCode http://www.dacode.org/
 * src/phplib/users.php3
 * $Id: users.php3,v 1.195 2001/07/22 22:07:15 penso Exp $
 * Laurent Desarmes <laurent@linuxfr.org>
 * Fabien Penso <penso@linuxfr.org>
 *
 * Depends: Config Db Html
*/

Class User {
	var $db;
	var $session;
	var $html;
	var $ldap;
	var $user_id;
	var $fname;
	var $lname;
	var $login;
	var $email;
	var $level;
	var $param;
	var $timestamp;
	var $fake_email;
	var $last;
	var $checked;
	var $sig_id;
	var $homesite;
	var $signature;
	var $hide_sig;
	var $skip_referer;
	var $password;
	var $status;
	var $score;
	var $supp_info;

	Function User() {
		global $HTTP_COOKIE_VARS, $HTTP_REFERER, $config, $text;

		$this->db = LoadClass('Db');
		$this->session = LoadClass('Session');
		$this->cache = LoadClass('Cache');
		$this->utils = LoadClass('Utils');
		$this->html  = LoadClass('Html');

		if ($config->ldap_hostname) {
			$this->ldap  = LoadClass('Ldap');
		}

		if ($config->nodb == 1) {
			$text = lecho("Sorry but the site is currently down for maintenance.").
				lecho ("Thank you to come back in a few minutes !");
			echo $this->html->parsetemplate("basic.tmpl");
			exit;
		}


		$this->user_id=$this->session->user_id;
		$this->fname=$this->session->fname;
		$this->lname=$this->session->lname;
		$this->login=$this->session->login;
		$this->email=$this->session->email;
		$this->level=$this->session->level;
		$this->param=$this->session->param;
		$this->timestamp=$this->session->timestamp;
		$this->fake_email=$this->session->fake_email;
		$this->homesite=$this->session->homesite;
		$this->last=$this->session->last;
		$this->checked=$this->session->checked;
		$this->sig_id=$this->session->sig_id;
		$this->status=$this->session->status;
		$this->score=$this->session->score;
		$this->signature=$this->session->signature;
		$this->password=$this->session->password;
		$this->supp_info=$this->session->supp_info;
		$this->HTTP_REFERER=$HTTP_REFERER;
	}

	/*
	 *  Display user information.
	 */
	Function identity() {
		if (($this->param & pow(2,0)) &&
			(!empty($this->fname) || !empty($this->lname)))
			return "$this->fname $this->lname";
		return $this->login;
	}

	/*
	 * Get informations about a user 
	 */
	Function get_info($id=0) {
		global $config;

		if ($id == '0' || 
			!ereg("^[0-9]+$",$id)) {
			return;
		}

		/* We build SQL */
		$sqlc_q = "SELECT ".
		  $config->tables['users'].".id,".
		  $config->tables['users'].".login,".
		  $config->tables['users'].".lname,".
		  $config->tables['users'].".fname,".
		  $config->tables['users'].".email,".
		  $config->tables['users'].".fake_email,".
		  $config->tables['users'].".level,".
		  $config->tables['users'].".param,".
		  $config->tables['users'].".created,".
		  $config->tables['users'].".homesite,".
		  $config->tables['sig'].".sig,".
		  $config->tables['users'].".status,".
		  $config->tables['sessions'].".lastseen".
		  

		  " FROM ".$config->tables['users'].",".$config->tables['sig'].
		  ",".$config->tables['sessions'].

		  " WHERE ".
		  $config->tables['users'].".sig_id=".
		  $config->tables['sig'].".id AND ".
		  $config->tables['users'].".id=".
		  $config->tables['sessions'].".user_id AND ".
		  $config->tables['users'].".id='".addslashes($id)."'".

		  " ORDER BY ".$config->tables['sessions'].".lastseen DESC";
		/***********************/

		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed: ".$this->db->error(). " -->\n";
			return lecho("Problem. Please contact the webmaster.<br>\n");
		}

		if ($this->db->num_rows() == 0) {
			$this->db->free();
			return lecho("This id doesn't exists.<br>\n");
		}

		$c=$this->db->fetch_array();

		$out = "<table width=\"100%\"><tr><td class=\"newstext\">".
		  "ID</td><td class=\"newstext\">$c[0]</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("Login")."</td><td class=\"newstext\">".
		  htmlentities($c[1])."</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("Last Name")."</td><td class=\"newstext\">".
		  htmlentities($c[2])."</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("First Name")."</td><td class=\"newstext\">".
		  htmlentities($c[3])."</td></tr>".
		  
		  "<tr><td class=\"newstext\">".lecho("Fake E-Mail")."</td><td class=\"newstext\">".
		  htmlentities($c[5])."</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("Homesite")."</td><td class=\"newstext\">".
		  htmlentities($c[9])."</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("Signature")."</td><td class=\"newstext\">".
		  $c[10]."</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("Created Date")."</td><td class=\"newstext\">".
		  $this->utils->stamp2date($c[8],"longwyear")."</td></tr>".

		  "<tr><td class=\"newstext\">".lecho("Lastseen Date")."</td><td class=\"newstext\">".
		  $this->utils->stamp2date($c[12],"longwyear")."</td></tr>".
		  
		  "<tr><td colspan=\"2\" align=\"center\"><a href=\"".
		  $config->basehref."messages/post.".$config->php.
		  "?user_id_dest=".$c['id']."\"><img alt=\"message\" border=\"0\" src=\"".
		  $this->session->imgurl('mail')."\"></a></td></tr>";

		if (gettype($config->supp_fields) == "array" &&
			count($config->supp_fields) > 0) {
			$out .= "<tr><td colspan=\"2\" align=\"center\"><br><hr width=\"50%\"><br></td></tr>\n";

			$sqlc_q = "SELECT supp_info FROM ".$config->tables['users_supp'].
			  " WHERE user_id='".addslashes($c[0])."'";
			$ret = $this->db->query($sqlc_q);

			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
				  lecho("Please contact the webmaster."). "</span><br>";
			}

			if ($this->db->num_rows()) {
				$c=$this->db->fetch_array();
				$supp_info = unserialize($c[0]);
				
				if (gettype($supp_info) == "array") {
					reset($supp_info);
					while(list($key,$val) = each($supp_info)) {
						if (!$config->supp_fields[$key]['public'] &&
							!$this->checked) {
							$val = lecho("Must be logged...");
						}
						$out .= "<tr><td class=\"newstext\">".$key.
						  "</td><td class=\"newstext\">".nl2br(htmlentities($val))."</td></tr>";
					}
				}
			}
		}
		/// finished supp. fields ///

		$out .= "</table>\n";

		return $this->html->simplebox($out);
		  
	}

	/*
	 * Get last people connected (authentified people)
	 */
	Function get_lastconnected($nb=10) {
		global $config;
		$out="";

		if (!is_integer($nb) or $nb<1 or $nb>5000) {
			$nb = 10; // sqlchecked: it must be in [1..5000];
		}

		$fcontents = $this->cache->check_box("60","user_lastconnected",$nb);
		if (!empty($fcontents)) {
			return $fcontents;
		}

		$sqlc_q = "SELECT ".
		  $config->tables['users'].".id,".
		  $config->tables['users'].".login,".
		  $config->tables['users'].".lname,".
		  $config->tables['users'].".fname,".
		  $config->tables['users'].".param,".
		  $config->tables['sessions'].".lastseen".

		  " FROM ".
		  $config->tables['users'].",".
		  $config->tables['sessions'].

		  " WHERE ".
		  $config->tables['users'].".id=".
		  $config->tables['sessions'].".user_id".

		  " ORDER BY ".
		  $config->tables['sessions'].".lastseen DESC LIMIT $nb";

		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			return "<span class=\"newstext\">". lecho("Something went wrong. ").
			  lecho("Please contact the webmaster."). "</span><br>";
		}

		while ($c=$this->db->fetch_array()) {
			if ($c['param'] & pow(2,4)) {
				continue;
			}
			// Now we choose to show login or fname/lname
			if (($c['param'] & pow(2,0)) && $c['id'] != 1 &&
				(!empty($c['lname']) || !empty($c['fname']))) {
				$usermask = $c['fname']." ".$c['lname'];
			} else {
				$usermask = $c['login'];
			}

			$out .= "&nbsp;".$this->utils->stamp2time($c['lastseen'],"short").
			  " <a href=\"".$config->basehref."users/?a=vu&amp;user_id=".
			  $c['id']."\">".htmlentities($usermask)."</a><br>\n";
		}
		$this->db->free();

		$this->cache->write_box("user_lastconnected",$nb,$out);
		return $out;

	}

	Function makerand($nb=8) {
		mt_srand((double)microtime()*1000000);
		$r="";
		$r1=array(48,65,97);
		$r2=array(57,90,122);
		for($i=1; $i<=$nb; $i++) {
			$j=mt_rand(0,2);
			$r.=sprintf("%c",mt_rand($r1[$j],$r2[$j]));
		}
		return $r;
	}

	Function makepasswd($nb=8) {
		$tmp="";
		srand((double)microtime()*1000000);
		for($i=0;$i<$nb;$i++) {
			switch(rand(0,2)) {
				case 0:
					$a=97; $b=122;
					break;
				case 1:
					$a=65; $b=90;
					break;
				case 2:
					$a=48; $b=57;
					break;
			}
			$tmp.=sprintf("%c",rand($a,$b));
		}
		return $tmp;
	}

	/*
	 * Text written in authentication box
	 */
	Function logintext() {
		global $config;

		return "<form method=\"post\" action=\"".$config->basehref.
			"users/login.".$config->php."\">".
			"<table border=\"0\" cellspacing=\"1\" cellpadding=\"1\" ".
			"width=\"100%\">\n<tr><td class=\"newstext\">\n<center>".
			"<select name=\"table[time]\">".
			"<option value=\"3600\">1 ".lecho("hour").
			"<option value=\"86400\">1 ".lecho("day").
			"<option value=\"2592000\">1 ".lecho("month").
			"<option value=\"31104000\" selected>1 ".lecho("year").
			"</select></center></td></tr>".

			"<tr><td class=\"newstext\"><center>".
			"<input type=\"text\" name=\"table[login]\" value=\"".lecho("Login").
			"\" size=\"10\" maxlength=\"20\" ".
			"onfocus=\"if (this.value=='".lecho("Login").
			"') this.value=''\"></center></td></tr>".

			"<tr><td class=\"newstext\"><center>".
			"<input type=\"password\" name=\"table[passwd]\" size=\"10\"".
			" maxlength=\"20\" value=\"passwordez\" onfocus=\"this.value=''\">".
			"</center></td></tr>".

			"<tr><td class=\"newstext\">\n<center>".
			"<input type=\"image\" src=\"".$this->session->imgurl('submit').
			"\" alt=\"".lecho("Submit")."\"".
			" style=\"border: 0px\">".
			"</center>".
			"</td></tr>\n".
			"</table></form><br>\n".

			"<center><span class=\"newstext\"><a href=\"".$config->basehref.
			"users/?a=na\">".lecho("New Account")."</a><br>".
			"<a href=\"".$config->basehref."users/?a=rp\">".
			lecho("Forgot your Password ?")."</a><br></span></center>";
	}

	/*
	 * Function to show the box which you can use to log in
	 */
	Function loginbox() {
		global $config;

		if ($this->checked) {
			// in the loginbox, a new entry: comments
			$tmp = "<center>\n".
				' <a href="'.$config->basehref.
					'users/?a=mu">'.lecho('Preferences')."</a>\n".
				" <br>\n".
				' <a href="'.$config->basehref.
					'users/?a=cs">'.lecho('Close your Session')."</a>\n".
				" <br>\n".
				' <a href="'.$config->basehref.
					'users/myposts.'.$config->php.'?order=id">'.lecho('Comments')."</a>\n".
				" <br>\n".
				"</center>\n";
			$title = '<u>'.$this->identity().'</u>';
		} else {
			$tmp = $this->logintext();
			$title = lecho("Authentication");
		}
		return $this->html->sidebox($title,$tmp,'login');
	}

	/*
	 * Function used to log in
	 */
	Function do_login($row) {
		global $config,$HTTP_HOST;

		$unique_id=$this->makerand(19);

		if ($row['login'] && $row['passwd'] && $row['time']) {

			$ip=$this->utils->ip();

			if ($this->ident($row['login'],$row['passwd'])==1) {

				$expire=$row['time'];
				if ($this->login!=$row['login']) {
					setcookie("login",$this->login,time()+$expire,"/",$config->cookiedomain);
				}

				$sqlc_q = "INSERT INTO ".$config->tables['sessions'].
					" (id,user_id,ip,lastseen,expire) VALUES ('".
					addslashes($unique_id)."','".
					addslashes($this->user_id)."','".
					addslashes($ip)."',CURRENT_TIMESTAMP,".
					addslashes($this->db->compat_date_add($expire)).")";

				$ret = $this->db->query($sqlc_q);
				if (!$ret) {
					echo "<!-- SQL failed: ".$this->db->error(). " -->\n";
					return -1;
				}

				if ($this->db->affected_rows()==1) {
					unset($row['passwd']);
					setcookie("session_id",$unique_id,time()+$expire,"/",$config->cookiedomain);
					return 1;
				}

			} else {
				echo lecho("Wrong password...\n");
				return -1;
			}
		} else {
			header("Cache-Control: no-cache, must-revalidate");
			header("Pragma: no-cache");
			header("Location: ".$config->basehref);
			exit;
		}
	}

	/*
	 * Returns 1 if ident is right, 0 else.
	 */
	Function ident($login,$passwd) {
		global $config;

		if ($config->ldap_hostname) {
		    $this->ldap->search("(login=$login)");
		    $attrs = $this->ldap->fetch();
		    $ldap_passwd = $attrs["userpassword"][0];
		    $ldap_passwd = strtok($ldap_passwd,'}');
		    $ldap_passwd = strtok('}');

		    if ($this->utils->crypt_dacode($passwd, $ldap_passwd) == 1) {
				$this->lname=$attrs["lname"][0];
				$this->fname=$attrs["fname"][0];
				$this->login=$attrs["login"][0];
				$this->email=$attrs["email"][0];
				$this->fake_email=$attrs["fake_email"][0];
				$this->user_id=$attrs["id"][0];
				$this->level=(int) $attrs["level"][0];
				$this->timestamp=$attrs["created"][0];
				return 1;
		    }
		    return 0;
		} else {
			$sqlc_q = "SELECT id,lname,fname,passwd,email,fake_email,level,".
			  "created FROM ".$config->tables['users']." WHERE login='".
			  addslashes($login)."'";

			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: ".$this->db->error(). " -->\n";
				return -1;
			}
			if ($this->db->num_rows() == 0) {
				$this->db->free();
				return 0;
			}

			$c=$this->db->fetch_array();
			if ($this->utils->crypt_dacode($passwd, $c[3]) == 1) {
				$this->user_id=$c[0];
				$this->lname=$c[1];
				$this->fname=$c[2];
				$this->login=$login;
				$this->email=$c[4];
				$this->fake_email=$c[5];
				$this->level= (int) $c[6];
				$this->timestamp=$c[7];
				return 1;
			}
			$this->db->free();

			return 0;
		}
	}

	/*
	 * Create a new account
	 */
	Function newaccount($form) {
		global $HTTP_REFERER;
		global $config;

		$out = "";
		if (!preg_match("/^\w{3,20}$/i",$form['login2'])) {
			$out .= "<span class=\"newstext\">-&nbsp;".
			  lecho("Login must be 3 characters long").
			  $form['login']."</span><br>\n";
			$form['login'] = "";
		}

    	// If we have supplementary fields, we verify they are
    	// not too big
		if (gettype($config->supp_fields) == "array" &&
			count($config->supp_fields) > 0) {
			$table_tmp = array();
			reset($config->supp_fields);
			while(list($key,$val) = each($config->supp_fields)) {
				if (strlen($form[$key]) > $val['max_length']) {
					$out .= "<span class=\"newstext\">&nbsp;".$key.lecho(" can't be that big.").
					  lecho(" Sorry."). "</span><br>\n";
				}
			}
		}

		if (! preg_match("/^[\w_\-\.]+@[\w_\-\.]+$/",$form['email'])) {
			$out .= "<span class=\"newstext\">-&nbsp;".lecho("Email looks wrong").
			  "</span><br>\n";
			$form['email'] = "";
		} else {
			$sqlc_q = "SELECT login FROM ". $config->tables['users'].
				" WHERE email='".addslashes($form['email'])."'";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo lecho("SQL Failed: ").$this->db->error();
				return -1;
			}
			if ($this->db->num_rows()) {
				$out .= '<br>'.lecho("An account use already this mail");
				$form['email'] = "";
			}
			$this->db->free();
		}
		$sqlc_q = "SELECT login FROM ".$config->tables['users'].
			" WHERE login='".addslashes($form['login2'])."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo lecho("SQL Failed: ").$this->db->error();
			return -1;
		}
		if ($this->db->num_rows()) {
			$out .= '<br><br>'.lecho("An account already exists with this login");
			$form['login'] = "";
		}
		$this->db->free();

		if (!empty($out)) {
			return $out;
		}

		//   Make sure there is no HTML sequence in user table
		$form['passwd'] = '';
		if (!$this->utils->html_safe($form)) {
			return '<br>'.lecho("Invalid &lt; sign in datas");
		}

		$form['passwd'] = $this->makepasswd();

		$encrypted_passwd = $this->utils->crypt_dacode($form['passwd']);

		$sqlc_q = "INSERT INTO ".$config->tables['users'].
			" (lname,fname,login,passwd,email,fake_email,created,level,theme) ".
			"VALUES ('".
			addslashes($form['lname'])."','".
			addslashes($form['fname'])."','".
			addslashes($form['login2'])."','".
			addslashes($encrypted_passwd)."','".
			addslashes($form['email'])."','".
			addslashes($form['fake_email'])."',".
			"CURRENT_TIMESTAMP,'".
			addslashes($config->usersdefaultlevel)."','".
			addslashes($config->dft_prefs['theme'])."')";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
			return -1;
		}

		$user_id = $this->db->last_insert_id();

		if ($config->ldap_hostname) {
		    $sqlc_q = "SELECT created FROM ".$config->tables['users'].
			  " WHERE id='".addslashes($user_id)."'";
		    $ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return -1;
			}
		    $row=$this->db->fetch_array();
		    
		    $this->ldap->cd($config->ldap_basedn);
		    $this->ldap->mkdir("login",addslashes($form['login2']));
		    $node = "login=".addslashes($form['login2']).",".$config->ldap_basedn;
		    $this->ldap->cd($node);

		    $attrs["objectClass"] = "dacode";
		    $attrs["login"] = $form['login2'];
		    $attrs["id"] = $user_id;
		    $attrs["lname"] = $form['lname'];
		    $attrs["fname"] = $form['fname'];
		    $attrs["userpassword"] = "{crypt}".$encrypted_passwd;
		    $attrs["email"] = $form['email'];
		    $attrs["fake_email"] = $form['fake_email'];
		    $attrs["score"] = $form['score'];
		    $attrs["theme"] = $config->dft_prefs['theme'];
		    $attrs["created"] = $row["created"];
		    
		    $this->ldap->modify($attrs);
		}

		// If we have supplementary fields
		if (gettype($config->supp_fields) == "array" &&
			count($config->supp_fields) > 0) {
			$table_tmp = array();
			reset($config->supp_fields);
			while(list($key,$val) = each($config->supp_fields)) {
				$table_tmp[$key] = $form[$key];
			}

			reset($table_tmp);
			$tmp_serialize = serialize($table_tmp);

			//   Make sure there is no HTML sequence in user table
			if (!$this->utils->html_safe($tmp_serialize)) {
				return '<br>'.lecho("Invalid &lt; sign in datas");
			}

			$sqlc_q = "INSERT INTO ".$config->tables['users_supp'].
			  " (user_id,supp_info) VALUES ('".
			  addslashes($user_id)."','".
			  addslashes($tmp_serialize)."')";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
				  lecho("Please contact the webmaster."). "</span><br>";
			}
		}
		/// finished supp. fields ///

		$text = lecho("You asked for an account. In order to validate it, you'll need \n").
			lecho("to authenticate yourself at least one time this week, or your account \n").
			lecho("will be deleted.\n\n");

		$text .= lecho("Login") . ": ".$form['login2']."\n".
			lecho("Password") . ": ".$form['passwd']."\n";

		if ($this->utils->send_email($form['email'],lecho("New Account"),$text)) {
			return lecho("Your password was sent to the address ").$form['email'];
		} else {
			return lecho("Error");
		}
	}

	/*
	 * Show form for people who forgot their password
	 */
	Function show_forget () {
		global $config;

		$tmp = lecho("Fill only one field"). "<br><br><form method=\"post\" action=\"".
					$config->basehref."users/password.".$config->php."\">".
					"<table border=\"0\" cellspacing=\"1\" cellpadding=\"1\" width=\"100%\">".
					"<tr align=\"center\"><td>".lecho("Login")."</td>".
					"<td><input TYPE=\"text\" name=\"al_login\" value=".
					"\"$this->login\" size=10 maxlength=20></td></tr>".
					"<tr align=\"center\"><td>".lecho("E-Mail")."</td>".
					"<td><input type=\"text\" name=\"al_email\" size=10".
					$this->email."></td></tr>".
					"<tr align=\"center\"><td colspan=2>".
					"<input type=\"submit\" name=\"submit\" value=\"".
					lecho("Receive Password")."\"></td></tr>".
					"</table>".
					"</form>";

		return $this->html->simplebox($tmp);
	}

	/*
	 * Send password to a user
	 */
	Function send_password ($login="",$email="") {
		global $config;

		if ((empty($login) && empty($email)) || ($login==lecho("Anonymous"))) {
			header("Location: $this->HTTP_REFERER");
			exit;
		}

		// As we don't know the clear password, we generate one and we send it again.
		// But first let's check if user exists
		if (!empty($login)) {
			$sqlc_q = "SELECT passwd,email,login FROM ".$config->tables['users']." WHERE ".
				"login='".addslashes($login)."'";
		} else {
			$sqlc_q = "SELECT passwd,email,login FROM ".$config->tables['users']." WHERE ".
				"email='".addslashes($email)."'";
		}

		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed: ".$this->db->error(). " -->";
			return -1;
		}

		if (!$this->db->num_rows()==1) {
			$out = lecho("Not Found");
			return $tmp;
		}

		$tmp = $this->db->fetch_array();

		$passwd_new = $this->makepasswd();
		$encrypted_passwd = $this->utils->crypt_dacode($passwd_new);

		$sqlc_q = "UPDATE ".$config->tables['users']." SET passwd='".
			addslashes($encrypted_passwd)."', created=created WHERE login='".
			addslashes($tmp[2])."' AND email='".addslashes($tmp[1])."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed: ".$this->db->error(). " -->";
			return -1;
		}

		$text = lecho("Login") . ": $tmp[2]\n".
				lecho("Password") . ": $passwd_new\n";

		if ($this->utils->send_email($tmp[1],"daCode: ".lecho("Password"),$text)) {
			$out.= lecho("Password Sent");
		} else {
			$out.= lecho("Error");
		}
		return $out;
	}

	/* Get signature !*/
	Function get_sig($id) {
		global $config;

		$tmp = "";

		$sqlc_q = "SELECT sig FROM ".$config->tables['sig']." WHERE id='".
				addslashes($id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			$tmp .= lecho("SQL Failed: ").$this->db->error();
			return $tmp;
		}

		if ($this->db->num_rows()==1) {
			$c=$this->db->fetch_array();
			if ($c[0]) {
				$this->signature=$c[0];
			}
		}
		$this->db->free();
		return $this->signature;
	}

	/* Print table for settings */
	Function print_setting() {
		global $config;

		$tmp = "";
		if (!$this->checked) {
			$tmp .=  lecho("Must be logged...")."<br>\n";
			return $tmp;
		}

		$tmp = "<form method=\"post\" action=\"".$config->basehref.
			"users/settings.".$config->php."\">".
			"<table border=\"0\" cellspacing=\"1\" cellpadding=\"1\"".
			" width=\"100%\"><tr><td class=\"sboxtext\">".lecho("Login").
			"</td><td class=\"sboxtext\">".htmlentities($this->login).
			"</td></tr>".

			"<tr><td class=\"sboxtext\">".lecho("Last Name")."</td>".
			"<td class=\"sboxtext\"><input type=\"text\" name=\"table[lname]\" ".
			"size=\"30\" value=\"".htmlspecialchars($this->lname)."\"></td></tr>".

			"<tr><td class=\"sboxtext\">".lecho("First Name")."</td>".
			"<td class=\"sboxtext\"><input type=\"text\" name=\"table[fname]\" ".
			"size=\"30\" value=\"".htmlspecialchars($this->fname)."\"></td></tr>".

			"<tr><td class=\"sboxtext\">".lecho("E-Mail")."</td>".
			"<td class=\"sboxtext\"><input type=\"text\" name=\"table[email]\" ".
			"size=\"30\" value=\"".htmlspecialchars($this->email)."\"></td></tr>".

			"<tr><td class=\"sboxtext\">".lecho("Fake E-Mail")."</td>".
			"<td class=\"sboxtext\"><input type=\"text\" name=\"table[fake_email]\" ".
			"size=\"30\" value=\"".htmlspecialchars($this->fake_email)."\"></td></tr>".

			"<tr><td class=\"sboxtext\">".lecho("Homesite")."</td>".
			"<td class=\"sboxtext\"><input type=\"text\" name=\"table[homesite]\" ".
			"size=\"30\" value=\"".htmlspecialchars($this->homesite)."\"></td></tr>".

			"<tr><td class=\"sboxtext\">".lecho("Signature")."</td>".
			"<td class=\"sboxtext\"><textarea name=\"table[signature]\" cols=\"30\"".
			" rows=\"2\">\n".$this->get_sig($this->sig_id)."</textarea></td></tr>".

			"<tr><td class=\"sboxtext\">"."Theme"."</td>".
			"<td class=\"sboxtext\"><select name=\"table[theme]\" class=\"sboxtext\">\n";

		reset($config->listofthemes);
		while (list($i, $theme) = each ($config->listofthemes)) {
			$tmp .= "<option class=\"sboxtext\" value=\"".$i."\"";
			if ($theme == $config->theme_name) {
				$tmp .= " selected";
			}
			$tmp .= ">".$theme."</option>\n";
		}
		$tmp .= "</select></td></tr>\n";

		$tmp .= "<tr><td class=\"sboxtext\">Score</td><td><select name=\"table[score]\">\n";
		for ($i=-1;$i<=5;$i++) {
			$tmp .= "<option value=\"$i\"";
			if ($i == $this->score) {
				$tmp .= " selected";
			}
			$tmp .= ">$i</option>\n";
		}
		$tmp .= "</select></td></tr>\n";

		$tmp .= "<tr><td class=\"sboxtext\">".lecho("Hide signatures").
		  "</td><td><select name=\"table[hide_sig]\">\n".
		  "<option value=\"1\"".($this->param & pow(2,2) ? " selected" : "").
		  ">".lecho("Yes")."</option>\n".
		  "<option value=\"0\"".($this->param & pow(2,2) ? "" : " selected").
		  ">".lecho("No")."</option>\n";
		$tmp .= "</select></td></tr>\n";

		$tmp .= "<tr><td class=\"sboxtext\">".lecho("Display").
		  "</td><td class=\"sboxtext\"><select name=\"table[identity]\">\n".
		  "<option value=\"1\"".($this->param & pow(2,0) ? " selected" : "").
		  ">".lecho("First Name")." ".lecho("Last Name")."</option>\n".
		  "<option value=\"0\"".($this->param & pow(2,0) ? "" : " selected").
		  ">".lecho("Login")."</option>\n";
		$tmp .= "</select></td></tr>\n";

		$tmp .= "<tr><td class=\"sboxtext\">".lecho("Skip referer").
		  "</td><td class=\"sboxtext\"><select name=\"table[skip_referer]\">\n".
		  "<option value=\"1\"".($this->param & pow(2,3) ? " selected" : "").
		  ">".lecho("Yes")."</option>\n".
		  "<option value=\"0\"".($this->param & pow(2,3) ? "" : " selected").
		  ">".lecho("No")."</option>\n";
		$tmp .= "</select></td></tr>\n";


		$tmp .= "<tr><td class=\"sboxtext\">".lecho("Don't be listed in last users").
		  "</td><td><select name=\"table[no_last_users]\">\n".
		  "<option value=\"1\"".($this->param & pow(2,4) ? " selected" : "").
		  ">".lecho("Yes")."</option>\n".
		  "<option value=\"0\"".($this->param & pow(2,4) ? "" : " selected").
		  ">".lecho("No")."</option>\n";
		$tmp .= "</select></td></tr>\n";

		// If we have supplementary fields
		if (gettype($config->supp_fields) == "array" &&
			count($config->supp_fields) > 0) {
			$tmp .= "<tr><td colspan=\"2\"><center><hr width=\"50%\"></center></td></tr>";
			reset($config->supp_fields);
			while(list($key,$val) = each($config->supp_fields)) {
				$tmp .= "<tr><td class=\"newstext\">".ucfirst($key)."</td>\n".
				  "<td class=\"newstext\">";
				if ($val['type'] == "text") {
					$tmp .= "<input type=\"".$val['type']."\" size=\"".
					  $val['length']."\" maxlength=\"".
					  $val['max_length']."\" name=\"table[$key]\" value=\"".
					  htmlspecialchars($this->supp_info[$key])."\">";
				} else if ($val['type'] == "textarea") {
					list($cols,$rows) = split (",", $val['length'], 2);
					$tmp .= "<textarea wrap=\"virtual\" cols=\"$cols\" rows=\"$rows\" name=\"table[$key]\">".
					  $this->supp_info[$key]."</textarea>\n";
				}
				$tmp .= "</td></tr>\n";
			}
		}
		/// finished supp. fields ///

		$tmp .= "<tr><td>&nbsp;</td></tr>\n".
		  "<tr align=\"center\"><td colspan=2><input type=\"submit\"".
		  " name=\"submit\" value=\"".lecho("Confirm")."\"></td></tr>";



		$tmp .= "</table></form>";

		$out = $this->html->simplebox($tmp) . "<br><br>";

		$tmp = "<form method=\"post\" action=\"".$config->basehref.
		  "users/modpasswd.".$config->php."\">".
		  "<table border=\"0\" cellspacing=\"1\" cellpadding=\"1\"".
		  "width=\"100%\"><tr><td class=\"sboxtext\">".lecho("Old Password").
		  "</td><td class=\"sboxtext\"><input type=\"password\" name=\"table[oldpasswd]\" ".
		  "size=\"30\"></td></tr>".
		  "<tr><td class=\"sboxtext\">".lecho("New Password").
		  "</td><td class=\"sboxtext\">".
		  "<input type=\"password\" name=\"table[newpasswd]\" size=\"30\">".
		  "</td></tr>".
		  "<tr><td class=\"sboxtext\">".lecho("New Password again").
		  "</td><td class=\"sboxtext\">".
		  "<input type=\"password\" name=\"table[newpasswd2]\" size=\"30\">".
		  "</td></tr><tr><td>&nbsp;</td></tr>\n<tr align=\"center\">".
		  "<td colspan=\"2\" class=\"sboxtext\"><input type=\"submit\" name=\"submit\" value=\"".
		  lecho("Confirm")."\"></td></tr></table></form>\n";

		$out .= $this->html->simplebox($tmp) . "<br><br>";

		return $out;
	}

	Function do_change_password($row) {
		global $config;

		if (!$this->checked) {
			$tmp .=  lecho("Must be logged...")."<br>\n";
			return $tmp;
		}

		if (!$this->utils->crypt_dacode($row['oldpasswd'], $this->password)) {
			$tmp .= lecho("Wrong old password!");
			return $tmp;
		}
		if (($row['newpasswd'] != $row['newpasswd2']) || empty($row['newpasswd'])) {
			$tmp .= lecho("Passwords don't match! Try again...")."<BR>\n";
			$tmp .= lecho("Maybe password empty?");
			return $tmp;
		}

		$encrypted_passwd = $this->utils->crypt_dacode($row['newpasswd']);

		$sqlc_q = "UPDATE ".$config->tables['users']." SET passwd='".
			addslashes($encrypted_passwd)."', created=created WHERE id='".
			addslashes($this->user_id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			$tmp .= lecho("SQL Failed: ").$this->db->error();
			return $tmp;
		}

		if ($config->ldap_hostname) {
			$this->ldap->cd("login=".$this->login.",".$config->ldap_basedn);
			$attrs["userpassword"] = "{crypt}".$encrypted_passwd;
			$this->ldap->modify($attrs);
		}

		header("Location: ".$config->basehref);
	}

	Function do_change_setting ($row) {
		global $config;

		$out = "";

		if (!$this->checked) {
			$tmp .=  lecho("Must be logged...")."<br>\n";
			return $tmp;
		}
		if (!preg_match("/^http:\/\//U",$row['homesite'],$matches) &&
				!empty($row['homesite'])) {
			echo "Homesite must start with http://";
			exit;
		}

		// If we have supplementary fields, we verify they are not too big
		if (gettype($config->supp_fields) == "array") {
			$table_tmp = array();
			reset($config->supp_fields);
			while(list($key,$val) = each($config->supp_fields)) {
				if (strlen($row[$key]) > $val['max_length']) {
					$out .= "<span class=\"newstext\">-&nbsp;".$key.lecho(" can't be that big.").
					  lecho(" Sorry."). "</span><br>\n";
				}
			}
		}

		if (strlen($out) > 0) {
			echo $out;
			exit;
		}

		$sqlc_q = "SELECT id FROM ".$config->tables['sig']." WHERE sig='".
				addslashes($row['signature'])."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo lecho("SQL Failed: ").$this->db->error();
			exit;
		}

		if ($this->db->num_rows()==1) {
			$c=$this->db->fetch_array();
			if ($c[0]) {
				$new_sig_id=$c[0];
			}
			$this->db->free();
		} else {
			$this->db->free();
			if (!$this->utils->html_safe($row['signature'])) {
				return '<br>'.lecho("Invalid &lt; sign in datas");
			}
			$sqlc_q = "INSERT INTO ".$config->tables['sig']." (sig) VALUES ('".
				addslashes($row['signature'])."')";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo lecho("SQL Failed: ").$this->db->error();
				exit;
			}
			$new_sig_id=$this->db->last_insert_id();
		}

		$param = "";
		$param = $param | ($row['identity'] ? pow(2,0) : 0);
		$param = $param | ($row['hide_sig'] ? pow(2,2) : 0);
		$param = $param | ($row['skip_referer'] ? pow(2,3) : 0);
		$param = $param | ($row['no_last_users'] ? pow(2,4): 0);


		if (!$this->utils->html_safe($row)) {
			return '<br>'.lecho("Invalid &lt; sign in datas");
		}
		$sqlc_q = "UPDATE ".$config->tables['users']. " SET ".
			"fname='".addslashes($row['fname'])."',".
			"lname='".addslashes($row['lname'])."',".
			"homesite='".addslashes($row['homesite'])."',".
			"sig_id='".addslashes($new_sig_id)."',".
			"fake_email='".addslashes($row['fake_email'])."',".
			"theme='".addslashes($row['theme'])."',".
			"score='".addslashes($row['score'])."',".
			"param='".addslashes($param)."',".
			"created=created WHERE id='".
			addslashes($this->user_id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo lecho("SQL Failed: ").$this->db->error();
			exit;
		}

		// If we have supplementary fields
		if (gettype($config->supp_fields) == "array" &&
			count($config->supp_fields) > 0) {
			$table_tmp = array();
			reset($config->supp_fields);
			while(list($key,$val) = each($config->supp_fields)) {
				$table_tmp[$key] = $row[$key];
			}

			reset($table_tmp);
			$tmp_serialize = serialize($table_tmp);

			$sqlc_q = "SELECT user_id FROM ".$config->tables['users_supp'].
			  " WHERE user_id='".addslashes($this->user_id)."'";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo lecho("SQL Failed: ").$this->db->error();
				exit;
			}
			if (!$this->utils->html_safe($tmp_serialize)) {
				return '<br>'.lecho("Invalid &lt; sign in datas");
			}
			if ($this->db->num_rows() == '0') {
				$sqlc_q = "INSERT INTO ".$config->tables['users_supp'].
				  " (user_id,supp_info) VALUES ('".addslashes($this->user_id)."','".
				  addslashes($tmp_serialize)."')";
			} else {
				$sqlc_q = "UPDATE ".$config->tables['users_supp'].
				  " set supp_info='". addslashes($tmp_serialize)."' WHERE ".
				  "user_id='".addslashes($this->user_id)."'";
			}
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
				  lecho("Please contact the webmaster."). "</span><br>";
			}
		}
		/// finished supp. fields ///

		// Then we check if real mail has been changed.

		if ($row['email'] != $this->email) {
			$sqlc_q = "SELECT email FROM ".$config->tables['users']." WHERE ".
				"email LIKE '".addslashes($row['email'])."'";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
					lecho("Please contact the webmaster."). "</span><br>";
			}
			
			if ($this->db->num_rows()) {
				echo lecho("Someone else use this mail address already. ".
					  "Please go back and use another one, ".
					  "or click on I forgot my password.");
				exit;
			}
			$tempo_id = $this->utils->makerand(40);

			if (!$this->utils->html_safe($row['email'])) {
				return '<br>'.lecho("Invalid &lt; sign in datas");
			}
			$sqlc_q = "INSERT INTO ".$config->tables['users_tempo']." (user_id,email,tempo_id) ".
				" VALUES ('".addslashes($this->user_id)."','".addslashes($row['email']).
				"','".addslashes($tempo_id)."')";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
					lecho("Please contact the webmaster."). "</span><br>";
			}

			$text = $this->login.
				lecho (" has asked to change the email address from:\n").
				$this->email."\n".lecho("to:\n").$row['email']."\n\n";

			$text .= lecho("For the change to take effect, please visit:\n")."\n".
				$config->basehref."users/valid.".$config->php."?tempo_id=".
				$tempo_id."\n\n".
				lecho("If you didn't ask this modification, please ignore it or contact sysadmin:\n").
				$config->mailadmin;

			if (!$this->utils->send_email($row['email'],lecho("Account change"),$text)) {
				return lecho("Error");
			}

		}


		if ($config->ldap_hostname) {
		    
		    $this->ldap->cd("login=".$this->login.",".$config->ldap_basedn);
		    
		    $attrs["lname"] = $row['lname'];
		    $attrs["fname"] = $row['fname'];
		    $attrs["email"] = $row['email'];
		    $attrs["fake_email"] = $row['fake_email'];
		    $attrs["homesite"] = $row['homesite'];
		    $attrs["theme"] = $row['theme'];
		    $attrs["score"] = $row['score'];
		    
		    $this->ldap->modify($attrs);
		}

	}

	Function show_email_form($tempo_id="") {
		global $config;

		$sqlc_q = "SELECT email,user_id FROM ".$config->tables['users_tempo'].
			" WHERE tempo_id='".addslashes($tempo_id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
			return "<span class=\"newstext\">". lecho("Something went wrong. ").
				lecho("Please contact the webmaster."). "</span><br>";
		}
		if (!$this->db->num_rows()) {
			return lecho("This id doesn't exists.<br>\n");
		} else {
			$c=$this->db->fetch_array();
			// We fetch the last email address used.
			$sqlc_q = "SELECT email,login FROM ".$config->tables['users']." WHERE ".
				"id='".addslashes($c[1])."'";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
					lecho("Please contact the webmaster."). "</span><br>";
			}
			if (!$this->db->num_rows()) {
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
					lecho("Please contact the webmaster."). "</span><br>";
			}
			$c_old = $this->db->fetch_array();


			$tmp = "<form method=\"post\" action=\"".
				$config->basehref."users/valid_send.".$config->php."\">".
		  		"<table border=\"0\" cellspacing=\"1\" cellpadding=\"1\"".
		  		" width=\"100%\"><tr><td class=\"sboxtext\">".
		  		lecho("Enter your password to valid the change from ").
				htmlentities($c_old[0]).lecho(" to ").$c[0].lecho(" for the account ").
				$c_old[1]."</td><td class=\"sboxtext\">".
				"<input type=\"password\" name=\"table[password]\" size=\"30\" value=\"\">".
				"<input type=\"hidden\" name=\"table[tempo_id]\" value=\"".
				htmlentities($tempo_id)."\"></td></tr>".
				"<tr><td colspan=\"2\" align=\"center\">".
				"<input type=\"submit\" value=\"".lecho("Submit").
				"\"></td></tr></table></form>";
			return $tmp ;
		}
	}

	Function show_email_valid($row) {
		global $config;

		$sqlc_q = "SELECT email,user_id FROM ".$config->tables['users_tempo']." WHERE ".
			"tempo_id='".addslashes($row['tempo_id'])."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
			return "<span class=\"newstext\">". lecho("Something went wrong. ").
				lecho("Please contact the webmaster."). "</span><br>";
		}
		if (!$this->db->num_rows()) {
			return lecho("This id doesn't exists.<br>\n");
		} else {
			$c=$this->db->fetch_array();
			// We fetch the last email address used.
			$sqlc_q = "SELECT passwd,login FROM ".$config->tables['users']." WHERE ".
				"id='".addslashes($c[1])."'";
			$ret = $this->db->query($sqlc_q);
			if (!$ret) {
				echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
					lecho("Please contact the webmaster."). "</span><br>";
			}
			if (!$this->db->num_rows()) {
				return "<span class=\"newstext\">". lecho("Something went wrong. ").
					lecho("Please contact the webmaster."). "</span><br>";
			}
			$c_old = $this->db->fetch_array();

			if (!$this->utils->html_safe($c[0])) {
				return '<br>'.lecho("Invalid &lt; sign in datas");
			}
			if ($this->utils->crypt_dacode($row['password'], $c_old[0]) == 1) {

				$sqlc_q = "UPDATE ".$config->tables['users']." SET created=created,".
					"email='".addslashes($c[0])."' WHERE id='".addslashes($c[1])."'";
				$ret = $this->db->query($sqlc_q);
				if (!$ret) {
					echo "!-- SQL failed: $sqlc_q".$this->db->error()." -->";
					return "<span class=\"newstext\">". lecho("Something went wrong. ").
						lecho("Please contact the webmaster."). "</span><br>";
				}
				$sqlc_q = "DELETE FROM ".$config->tables['users_tempo']." WHERE ".
					"user_id='".addslashes($c[1])."'";
				$ret = $this->db->query($sqlc_q);
				if (!$ret) {
					echo "<!-- SQL failed: $sqlc_q".$this->db->error()." -->";
					return "<span class=\"newstext\">". lecho("Something went wrong. ").
						lecho("Please contact the webmaster."). "</span><br>";
				}

				if ($config->ldap_hostname) {
				    
				    $this->ldap->cd("login=".$c_old[1].",".$config->ldap_basedn);
				    
				    $attrs["email"] = $c[0];
				    
				    $this->ldap->modify($attrs);
				}

				return lecho("Your email address has been changed...\n");
			} else {
				return lecho("Wrong password...\n");
			}
		}
	}

	Function create_account_text () {
		return "<span class=\"newstext\"><br>".
		  lecho("This form allows you to create an user account. An user account allows you to access additional features, like the choice of your default theme, the summary of all your comments and their answers, and the possibility to submit tips.<br><br>").
		  
		  lecho("The authentication system used is based on cookies. Neither your login nor your password are stocked on your computer, only an unique id, generated during the validation of the browser's informations, is saved in your cookies. You don't have to type your password each type you visit the site.<br><br>").

		  lecho("In order to validate your account's application, a message will be sent at the e-mail address you'll give. It'll give you a random password, and will remind you the login you asked for. You'll then only need to come back here within a week to authenticate yourself, else the account will be deleted.<br><br>").

		  lecho("Warning, the field called <b>Login</b> must contain from 3 to 20 unmarked letters <br><br>")."</span>";
	}

	Function create_account ($table="") {
		global $config;

		if (is_array($table)) {
			return $this->newaccount($table);
		}

		$out = "<form method=\"post\" action=\"".$config->basehref."users/?a=na\">".
		  "<table><tr><td class=\"newstext\">Login/Nick</td>".
		  "<td class=\"newstext\">".
		  "<input type=\"text\" name=\"table[login2]\" size=\"20\" maxlength=\"20\"></td>\n".
		  "<td class=\"newstext\"><b>".lecho("Necessary")."</b></td></tr>\n".
		  "<tr><td class=\"newstext\">Email</td>".
		  "<td class=\"newstext\">".
		  "<input type=\"text\" name=\"table[email]\" size=\"30\" maxlength=\"128\"></td>".
		  "<td class=\"newstext\"><b>".lecho("Necessary")."</b></td></tr>\n".
		  "<tr><td class=\"newstext\">Fake Email</td><td colspan=\"2\" class=\"newstext\">".
		  "<input type=\"text\" name=\"table[fake_email]\" size=\"30\" maxlength=\"128\">".
		  "</td></tr><tr><td class=\"newstext\">Nom</td><td colspan=\"2\" class=\"newstext\">".
		  "<input type=\"text\" name=\"table[lname]\" size=\"30\" maxlength=\"40\"></td></tr>\n".
		  "<tr><td class=\"newstext\">Prénom</td><td colspan=\"2\" class=\"newstext\">".
		  "<input type=\"text\" name=\"table[fname]\" size=\"30\" maxlength=\"40\"></td></tr>\n";

		// If we have supplementary fields
		if (gettype($config->supp_fields) == "array" &&
			count($config->supp_fields) > 0) {
			$out .= "<td colspan=\"3\"><center><hr width=\"50%\"></center></td>";
			reset($config->supp_fields);
			while(list($key,$val) = each($config->supp_fields)) {
				$out .= "<tr><td class=\"newstext\">".ucfirst($key)."</td>\n".
				  "<td colspan=\"2\" class=\"newstext\">";
				if ($val['type'] == "text") {
					$out .= "<input type=\"".$val['type']."\" size=\"".
					  $val['length']."\" maxlength=\"".
					  $val['max_length']."\" name=\"table[$key]\">";
				} else if ($val['type'] == "textarea") {
					list($cols,$rows) = split (",", $val['length'], 2);
					$out .= "<textarea wrap=\"virtual\" cols=\"$cols\" rows=\"$rows\" name=\"table[$key]\">".
					  "</textarea>\n";
				}
				$out .= "</td></tr>\n";
			}
		}
		/// finished supp. fields ///

		$out .=	"<tr><td colspan=\"3\" align=\"center\">".
		  "<input type=\"submit\" name=\"submit\" value=\"Ajouter\">".
		  "<input type=\"reset\" value=\"Annuler\"></td></tr></table></form>";

		$out = $this->html->simplebox($this->create_account_text()) . "<br><br>" .
		  $this->html->simplebox($out);
		return $out;
	}

	/* This mypost function is used to get info on yours recents Posts.
	 * Some useful info on your post will be displayed.
	 * And there is a link to the view of each post :
	 *      href=comments/thread.php3
	 */
	Function mypost($order="id") {
		global $config;

		$LIMIT = 10;  // The max you can select. sqlchecked because it is const;

		/* We check if params look fines */
		$fields = array("subject","news_id","id","timestamp");
		if (! ( $this->checked && ereg('^('.join('|',$fields).')$' , $order))) {
			return "<tr><th class=\"boxheader\">".lecho("not checked, not a field")."</th></tr>\n";
		}
		// $order= is sqlchecked now, must be in $fields;
		
		/* ONE : We select what comments are interesting */
		$sqlc_q = 'SELECT '. join(",",$fields).
			' FROM '.$config->tables['comments'].
			" WHERE user_id='".addslashes($this->user_id)."' ORDER BY $order DESC".
			" LIMIT $LIMIT";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed:".$this->db->error();
			echo "SQL Command: $sqlc_q -->\n";
			exit ;
		}
		while($c = $this->db->fetch_array()) {
			$set_of_comments[] = $c;
			$set_of_news[$c[1]] = 1;
		}
		$this->db->free();

		if (empty($set_of_news)) {
			return "<tr><th class=\"boxheader\">".lecho("not yet a poster ???")."</th></tr>\n";
		}

		// Array bloody sucks in php3 !!! :-(
		// emulating PHP4 : $print_news = array_keys($set_of_news);
		reset($set_of_news);
		while (list($k)=each($set_of_news)) {
			$print_news[] = addslashes($k);
		}
		$list_news = "('". join("','",$print_news) ."')"; // sqlchecked: each element is addsl.;


		/* TWO: We get more infos for the selected set of news */
			// we want the Title...
		$sqlc_q = "SELECT id,title".
			" FROM ".$config->tables['news'].
			" WHERE id IN ".$list_news;
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed:".$this->db->error();
			echo "SQL Command: $sqlc_q -->\n";
			exit ;
		}
		while(list($news_id,$title) = $this->db->fetch_array()) {
			$news_title[$news_id] = $title;
		}
		$this->db->free();
			// ... and we want the Tree of the news.
		$sqlc_q = "SELECT id,com_parent,timestamp".
			" FROM ".$config->tables['comments'].
			" WHERE news_id IN ".$list_news;
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "<!-- SQL failed:".$this->db->error();
			echo "SQL Command: $sqlc_q -->\n";
			exit ;
		}
		while($node = $this->db->fetch_array()) {
			$tree[$node[0]] = array($node[1],$node[2]); // ugly PHP3 :-(
			// PHP4 not tested : $tree[array_pop($node)] = $node;
		}
		$this->db->free();
		krsort($tree);
		reset($tree);
		while (list($id,$node) = each($tree)) {
			$tree[$node['0']]['2'] += 1+$node['2'];
			$max = ($node['3'] ? $node['3'] : $node['1']);
			if ($max > $tree[$node['0']]['3']) {
				$tree[$node['0']]['3'] = $max;
			}
		}
		/* now, a node is
		 *      0=> the id of its parent,
		 *      1=> the timestamp of the node,
		 *      2=> the size of its subtree,
		 *      3=> the max(timestamp) of all nodes of its subtree.
		 */


		/* THREE: We process the output */
		// we process each line of the table ...
		$cellnocomment = "  <td class=\"boxtext\">\n".
					'   0 '.lecho('comment')."\n".
					"  </td>\n";
		reset($set_of_comments);
		$out = "";
		while(list($k,$c) = each($set_of_comments)) {
			list($subject,$news_id,$com_id,$timestamp) = $c;
			$count = 0; // the size of the branch
			$n = $com_id;
			while ($tree[$n][0] > 0) {
				$n = $tree[$n][0];
				$count++;
			}
			$out .= " <tr>\n".
				'  <td class="boxtext">'.$news_title[$news_id]."</td>\n".
				"  <td class=\"boxtext\">\n".
				"   <b>\n".
				'    <a href="'.$config->basehref.'comments/thread.'.$config->php.
					"?news_id=$news_id&amp;com_id=$com_id".
					"\">$subject</a>\n".
				"   </b>\n".
				"  </td>\n".
				"  <td class=\"boxtext\">".$this->utils->stamp2date($timestamp,"long").
				"</td>\n".

				($count==0 ? $cellnocomment :  // cell before
				"  <td class=\"boxtext\">\n".
				'   <a href="'.$config->basehref.'comments/thread.'.$config->php.
					"?news_id=$news_id&amp;com_id=$com_id&amp;before=1".
					"\">$count ".
					($count>1?lecho('comments'):lecho('comment'))."</a>\n".
				'   - '.$this->utils->interval($tree[$n][1],$timestamp)."\n".
				"  </td>\n"
				).

				($tree[$com_id][2]==0 ? $cellnocomment :  // cell after
				"  <td class=\"boxtext\">\n".
				'   <a href="'.$config->basehref.'comments/thread.'.$config->php.
					"?news_id=$news_id&amp;com_id=$com_id&amp;after=1".
					'">'.$tree[$com_id][2].' '.
					($tree[$com_id][2]>1?lecho('comments'):lecho('comment'))."</a>\n".
				'   - '.$this->utils->interval($timestamp,$tree[$com_id][3])."\n".
				"  </td>\n"
				).

				" </tr>\n";
		}

			// ... and we add the header of the table
		if ($out) {
			$TH_ORDER = '  <th class="boxheader"><a href="'.
				$config->basehref."users/myposts.".$config->php.'?order';
			return " <tr>\n".
				"$TH_ORDER=news_id\">news</a></th>\n".
				"$TH_ORDER=subject\">".lecho('Subject')."</a></th>\n".
				"$TH_ORDER=id\">".lecho('on')."</a></th>\n".
					// TODO lecho
				"  <th class=\"boxheader\">".lecho("before")."</th>\n".
				"  <th class=\"boxheader\">".lecho("after")."</th>\n".
				" </tr>\n$out";
		} else {
			return "<tr><td class=\"boxheader\">".lecho("no result")."</td></tr>\n";
		}
	}

}

?>
