Fonction update

Signaler
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013
-
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013
-
Bonjour,

j'ai une page de mise à jour du profile utilisateur, et comme tout update il y a une vérification des champs. le problème rencontré, est que la fonction " positionExists" qui vérifie si un nickname existe déjà lors de l'enregistrement, on ne peut pas enregistrer 2 fois le meme nickname. Mais dans l'update j'ai besoin de garder cette fonction, car l'utilisateur a droit de changer de nickname, seulement.. lorsqu'il n'y a aucun changement.. le message informant qu'un nickname existe déjà ( le sien ) s'affiche... donc je ne peut pas valider la mise à jour du profile.... comment faire... voici les partie du code.. je pense que c'est simple a faire..mais je débute... merci de me donner un coup de main.

voici le début de la fonction "updateProfile()"

public function updateProfile()
{

Filter::checkPost('position', Lang::$word->ACC_NAMEPOSITION);

if ($value = $this->positionExists($_POST['position'])) {

if ($value == 1)
Filter::$msgs['position'] = Lang::$word->POSITION_R2;
if ($value == 2)
Filter::$msgs['position'] = Lang::$word->POSITION_R3;
if ($value == 3)
Filter::$msgs['position'] = Lang::$word->POSITION_R4;
}

et voici la fonction "positionExists"

private function positionExists($position)
{
$sql = self::$db->query("SELECT position"
. "\n FROM " . self::uTable
. "\n WHERE position = '" . sanitize($position) . "'"
. "\n LIMIT 1");

if (self::$db->numrows($sql) == 1) {
return true;
} else
return false;
}

merci de votre aide...

10 réponses

Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Bonjour.
Lorsque tu fais l'update d'un utilisateur. ..tu connais son id..
Dans ta vérification de son pseudo, utilise cet id dans ta requête pour ne pas inclure ce user eans la vérification. .
Un truc du genre :

And id not in ($id_user)
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

Hello Jordane,

merci pour ta réponse,

peux-tu me dire ou tu viens coller cette ligne ?

Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Il faut la mettre dans ta clause WHERE

Attention : Il faut remplacer les variables par les tiennes...
Le nom de ta colonne ID ainsi que le nom de ta variable qui contiendrait l'ID de ton user..

Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

Hello Jordane,

j'ai fais quelques test.. et résultat fonctionne pas, donc je tourne en rond sur la bonne ligne de commande...

si je te donne une partie des infos ( code PHP ), aurais-tu l'amabilité
m'écrire correctement la fonction pour l'update

le nom de ma colonne dans la db est : id
la variable : userid

  private function positionExists($position)
{
$sql = self::$db->query("SELECT position"
. "\n FROM " . self::uTable
. "\n WHERE position = '" . sanitize($position) . "'"
. "\n LIMIT 1");

if (self::$db->numrows($sql) == 1) {

return true;
} else
return false;
}
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Ca devrait ressemble à quelque chose du genre :


SELECT position FROM " . self::uTable . " WHERE position = '" . sanitize($position) . "' and id NOT IN ('".$userid ."' LIMIT 1");



Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

Hello jordane,

merci pour ta rapide réponse et ligne...

mon prob. c'est que cela n'est pas résolu, est lorsque j'applique cette ligne, mes message ( erreur ou pas ) ne s'affiche pas du tout..

aucune mise à jour ne s'effectue...

alors doit y avoir un couac ou une mauvaise compréhension chez moi, entre le dossier de la chaise et l'écran :o)

si tu as la page PHP, arriverais-tu à trouver le couac ?
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Bonjour,
J'ai fait une erreur... il faut sortir le LIMIT 1 de la parenthèse..
Et il ne faut appliquer la condition sur l'ID que dans le cas où ta variable iduser n'est pas vide.... bref, vos rajouter un if ...


private function positionExists($position,$userid=null ){
$and='';
if($userid){
$and = "and id NOT IN ('".$userid ."')";
}

$sql = self::$db->query("SELECT position FROM " . self::uTable . " WHERE position = '" . sanitize($position) . "'". $and ." LIMIT 1");

if (self::$db->numrows($sql) == 1) {
return true;
} else {
return false;
}




ca devrait etre mieux ^^
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

Hello Jordane,

es-tu sure..car Mon Dreamweaver m'indique des erreur de balize..,


Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
manque surement un espace dans $and

$and = " and id NOT IN ('".$userid ."') ";

Sinon, à quel endroit te dit il qu'il y a un souci ?
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

j'ai mis ta ligne,. j'imagine qu'il y devrait y avoir aussi un espace entre le point . et la variable $userid
('".$ userid ."')
...
mais aucune différence.. dan stous les cas... et les erreurs se répercute sur chaque nouvelle function dans ma page PHP..
voici la page, si tu veux y jeter un oeil.. peut-être aura tu le même probleme...

<?php


if (!defined("_VALID_PHP"))
die('Direct access to this location is not allowed.');

class Users
{
const uTable = "users";
public $logged_in = null;
public $uid = 0;
public $userid = 0;
public $cookie_id = 0;
public $username;
public $sesid;
public $email;
public $email_sponsor;
public $name;
public $userlevel;
public $avatar;
public $last;
private $lastlogin = "NOW()";

private static $db;


/**
* Users::__construct()
*
* @return
*/
function __construct()
{
self::$db = Registry::get("Database");
$this->startSession();
}


/**
* Users::startSession()
*
* @return
*/
private function startSession()
{
session_start();

$this->logged_in = $this->loginCheck();

if (!$this->logged_in) {
$this->username = $_SESSION['DDP_USERNAME'] = "Guest";
$this->sesid = sha1(session_id());
$this->userlevel = 0;
}
}

/**
* Users::loginCheck()
*
* @return
*/
private function loginCheck()
{

if (isset($_COOKIE['DDP_COOKIE']) && isset($_COOKIE['DDP_COOKIE_ID'])) {
$this->username = $_SESSION['DDP_USERNAME'] = $_COOKIE['DDP_COOKIE'];
$this->cookie_id = $_SESSION['cookie_id'] = $_COOKIE['DDP_COOKIE_ID'];
}

if (isset($_SESSION['DDP_USERNAME']) && isset($_SESSION['cookie_id']) && $_SESSION['DDP_USERNAME'] != "Guest") {
if (!$this->confirmCookie($_SESSION['DDP_USERNAME'], $_SESSION['cookie_id'])) {
unset($_SESSION['DDP_USERNAME']);
unset($_SESSION['cookie_id']);
unset($_SESSION['name']);
unset($_SESSION['uid']);
return false;
}

$row = $this->getUserInfo($_SESSION['DDP_USERNAME']);
$this->uid = $row->id;
$this->username = $row->username;
$this->email = $row->email;
$this->name = $row->fname . ' ' . $row->lname;
$this->userlevel = $row->userlevel;
$this->avatar = $row->avatar;
$this->last = $row->lastlogin;
$this->sesid = sha1(session_id());
return true;
} else {
return false;
}
}

/**
* Users::is_Admin()
*
* @return
*/
public function is_Admin()
{
return($this->userlevel == 9);

}

/**
* Users::login()
*
* @param mixed $username
* @param mixed $pass
* @param bool $uremember
* @return
*/
public function login($username, $pass, $uremember = false)
{

if ($username == "" && $pass == "") {
Filter::$msgs['username'] = Lang::$word->LOGIN_R5;
} else {
$status = $this->checkStatus($username, $pass);

switch ($status) {
case 0:
Filter::$msgs['username'] = Lang::$word->LOGIN_R1;
break;

case 1:
Filter::$msgs['username'] = Lang::$word->LOGIN_R2;
break;

case 2:
Filter::$msgs['username'] = Lang::$word->LOGIN_R3;
break;

case 3:
Filter::$msgs['username'] = Lang::$word->LOGIN_R4;
break;
}
}
if (empty(Filter::$msgs) && $status == 5) {
$row = $this->getUserInfo($username);
$this->uid = $_SESSION['userid'] = $row->id;
$this->username = $_SESSION['DDP_USERNAME'] = $row->username;
$this->email = $_SESSION['email'] = $row->email;
$this->name = $_SESSION['name'] = $row->fname . ' ' . $row->lname;
$this->last = $_SESSION['last'] = $row->lastlogin;
$this->cookie_id = $_SESSION['cookie_id'] = $this->generateRandID();
$this->userlevel = $_SESSION['userlevel'] = $row->userlevel;
$this->avatar = $_SESSION['avatar'] = $row->avatar;

$data = array(
'lastlogin' => $this->lastlogin,
'cookie_id' => $this->cookie_id,
'lastip' => sanitize($_SERVER['REMOTE_ADDR'])
);
self::$db->update(self::uTable, $data, "username='" . $this->username . "'");

if ($uremember) {
setcookie("DDP_COOKIE", $this->username, time() + COOKIE_EXPIRE, COOKIE_PATH);
setcookie("DDP_COOKIE_ID", $this->cookie_id, time() + COOKIE_EXPIRE, COOKIE_PATH);
}

return true;
} else
Filter::msgStatus();
}

/**
* Users::logout()
*
* @return
*/
public function logout()
{
if (isset($_COOKIE['DDP_COOKIE']) && isset($_COOKIE['DDP_COOKIE_ID'])) {
setcookie("DDP_COOKIE", "", time() - COOKIE_EXPIRE, COOKIE_PATH);
setcookie("DDP_COOKIE_ID", "", time() - COOKIE_EXPIRE, COOKIE_PATH);
}

unset($_SESSION['DDP_USERNAME']);
unset($_SESSION['email']);
unset($_SESSION['name']);
unset($_SESSION['cookie_id']);
unset($_SESSION['userid']);
session_destroy();
session_regenerate_id();

$this->logged_in = false;
$this->username = "Guest";
$this->userlevel = 0;
}

/**
* Users::getUserInfo()
*
* @param mixed $username
* @return
*/
private function getUserInfo($username)
{
$username = sanitize($username);
$username = self::$db->escape($username);

$sql = "SELECT *, CONCAT(fname,' ',lname) as fullname FROM " . self::uTable . " WHERE username = '" . $username . "'";
$row = self::$db->first($sql);
if (!$username)
return false;

return ($row) ? $row : 0;
}

/**
* Users::checkStatus()
*
* @param mixed $username
* @param mixed $pass
* @return
*/
public function checkStatus($username, $pass)
{
$username = sanitize($username);
$username = self::$db->escape($username);
$pass = sanitize($pass);

$sql = "SELECT password, active FROM " . self::uTable
. "\n WHERE username = '".$username."'";
$result = self::$db->query($sql);

if (self::$db->numrows($result) == 0)
return 0;

$row = self::$db->fetch($result);
$entered_pass = sha1($pass);

switch ($row->active) {
case "b":
return 1;
break;

case "n":
return 2;
break;

case "t":
return 3;
break;

case "y" && $entered_pass == $row->password:
return 5;
break;
}
}

/**
* Users::getUsers()
*
* @param bool $from
* @return
*/
public function getUsers($from = false)
{

$pager = Paginator::instance();
$pager->items_total = countEntries(self::uTable);
$pager->default_ipp = Registry::get("Core")->perpage;
$pager->paginate();

if (isset($_GET['sort'])) {
list($sort, $order) = explode("-", $_GET['sort']);
$sort = sanitize($sort);
$order = sanitize($order);
if (in_array($sort, array("username", "fname", "lname", "birth_day", "birth_month", "birth_year", "job", "address1", "address2", "zipcode", "city", "state", "country", "phone", "email", "skype", "quest1", "quest2", "quest3", "quest4", "quest5", "comment", "sponsor", "email_sponsor", "comment_admin", "terms", "entry", "position","created"))) {
$ord = ($order == 'DESC') ? " DESC" : " ASC";
$sorting = " " . $sort . $ord;
} else {
$sorting = " created DESC";
}
} else {
$sorting = " created DESC";
}

$clause = (isset($clause)) ? $clause : null;

if (isset($_POST['fromdate']) && $_POST['fromdate'] <> "" || isset($from) && $from != '') {
$enddate = date("Y-m-d");
$fromdate = (empty($from)) ? $_POST['fromdate'] : $from;
if (isset($_POST['enddate']) && $_POST['enddate'] <> "") {
$enddate = $_POST['enddate'];
}
$clause .= " WHERE created BETWEEN '" . trim($fromdate) . "' AND '" . trim($enddate) . " 23:59:59'";
}

$sql = "SELECT *, CONCAT(fname,' ',lname) as name,"
. "\n (SELECT COUNT(transactions.uid) FROM transactions WHERE transactions.uid = users.id) as totalitems"
. "\n FROM " . self::uTable
. "\n " . $clause
. "\n ORDER BY " . $sorting . $pager->limit;
$row = self::$db->fetch_all($sql);

return ($row) ? $row : 0;
}

/**
* Users::processUser()
*
* @return
*/
public function processUser()
{

if (!Filter::$id) {
Filter::checkPost('username', Lang::$word->USERNAME);

if ($value = $this->usernameExists($_POST['username'])) {
if ($value == 1)
Filter::$msgs['username'] = Lang::$word->USERNAME_R2;
if ($value == 2)
Filter::$msgs['username'] = Lang::$word->USERNAME_R3;
if ($value == 3)
Filter::$msgs['username'] = Lang::$word->USERNAME_R4;
}
}

Filter::checkPost('fname', Lang::$word->FNAME);
Filter::checkPost('lname', Lang::$word->LNAME);
Filter::checkPost('birth_month', Lang::$word->ACC_BIRTHM);
Filter::checkPost('birth_day', Lang::$word->ACC_BIRTHD);
Filter::checkPost('birth_year', Lang::$word->ACC_BIRTHY);
Filter::checkPost('job', Lang::$word->ACC_JOB);
Filter::checkPost('address1', Lang::$word->ACC_ADD1);
Filter::checkPost('zipcode', Lang::$word->ACC_ZIP);
Filter::checkPost('city', Lang::$word->ACC_CITY);
Filter::checkPost('state', Lang::$word->ACC_STATE);
Filter::checkPost('country', Lang::$word->ACC_COUNTRY);
Filter::checkPost('sponsor', Lang::$word->ACC_RECOMINF);
Filter::checkPost('entry', Lang::$word->ACC_ENTRY);
Filter::checkPost('quest1', Lang::$word->ACC_Q1);
Filter::checkPost('quest2', Lang::$word->ACC_Q2);
Filter::checkPost('quest3', Lang::$word->ACC_Q3);
Filter::checkPost('quest4', Lang::$word->ACC_Q4);
Filter::checkPost('quest5', Lang::$word->ACC_Q5);
Filter::checkPost('terms', Lang::$word->ACC_TERMS);

if (!Filter::$id) {
Filter::checkPost('password', Lang::$word->PASSWORD);
}

Filter::checkPost('email', Lang::$word->EMAIL);
if (!Filter::$id) {
if ($this->emailExists($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R2;
}
if (!$this->isValidEmail($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R3;

Filter::checkPost('email_sponsor', Lang::$word->ACC_RECOMAIL2);

if ($this->emailSponsorExists($_POST['email_sponsor']))
Filter::$msgs['email_sponsor'] = Lang::$word->EMAIL_SPR2;

if (!$this->isValidEmail2($_POST['email_sponsor']))
Filter::$msgs['email_sponsor'] = Lang::$word->EMAIL_SPR3;

Filter::checkPost('position', Lang::$word->ACC_NAMEPOSITION);

if ($this->positionExists($_POST['position']))
Filter::$msgs['position'] = Lang::$word->POSITION_R4;


if (!empty($_FILES['avatar']['name'])) {
if (!preg_match("/(\.jpg|\.png)$/i", $_FILES['avatar']['name'])) {
Filter::$msgs['avatar'] = Lang::$word->CONF_LOGO_R;
}
$file_info = getimagesize($_FILES['avatar']['tmp_name']);
if (empty($file_info))
Filter::$msgs['avatar'] = Lang::$word->CONF_LOGO_R;
}

if (empty(Filter::$msgs)) {

$data = array(
'username' => sanitize($_POST['username']),
'email' => sanitize($_POST['email']),
'lname' => sanitize($_POST['lname']),
'fname' => sanitize($_POST['fname']),
'birth_day' => sanitize($_POST['birth_day']),
'birth_month' => sanitize($_POST['birth_month']),
'birth_year' => sanitize($_POST['birth_year']),
'job' => sanitize($_POST['job']),
'address1' => sanitize($_POST['address1']),
'address2' => sanitize($_POST['address2']),
'zipcode' => sanitize($_POST['zipcode']),
'city' => sanitize($_POST['city']),
'state' => sanitize($_POST['state']),
'country' => sanitize($_POST['country']),
'skype' => sanitize($_POST['skype']),
'facebook' => sanitize($_POST['facebook']),
'position' => sanitize($_POST['position']),
'comment' => sanitize($_POST['comment']),
'zipcode' => sanitize($_POST['zipcode']),
'phone' => sanitize($_POST['phone']),
'sponsor' => sanitize($_POST['sponsor']),
'email_sponsor' => sanitize($_POST['email_sponsor']),
'terms' => sanitize($_POST['terms']),
'quest1' => sanitize($_POST['quest1']),
'quest2' => sanitize($_POST['quest2']),
'quest3' => sanitize($_POST['quest3']),
'quest4' => sanitize($_POST['quest4']),
'quest5' => sanitize($_POST['quest5']),
'entry' => sanitize($_POST['entry']),
'comment_admin' => sanitize($_POST['comment_admin']),
'notes' => sanitize($_POST['notes']),
'newsletter' => intval($_POST['newsletter']),
'userlevel' => intval($_POST['userlevel']),
'active' => sanitize($_POST['active'])
);

if (!Filter::$id)
$data['created'] = "NOW()";

if (Filter::$id)
$userrow = Registry::get("Core")->getRowById(self::uTable, Filter::$id);

if ($_POST['password'] != "") {
$data['password'] = sha1($_POST['password']);
} else {
$data['password'] = $userrow->password;
}

// Procces Avatar
if (!empty($_FILES['avatar']['name'])) {
$thumbdir = UPLOADS . "avatars/";
$tName = "AVT_" . randName();
$text = substr($_FILES['avatar']['name'], strrpos($_FILES['avatar']['name'], '.') + 1);
$thumbName = $thumbdir . $tName . "." . strtolower($text);
if (Filter::$id && $thumb = getValueById("avatar", self::uTable, Filter::$id)) {
@unlink($thumbdir . $thumb);
}
move_uploaded_file($_FILES['avatar']['tmp_name'], $thumbName);
$data['avatar'] = $tName . "." . strtolower($text);
}

(Filter::$id) ? self::$db->update(self::uTable, $data, "id='" . Filter::$id . "'") : self::$db->insert(self::uTable, $data);
$message = (Filter::$id) ? Lang::$word->USR_UPDATED : Lang::$word->USR_ADDED;

if (self::$db->affected()) {
Filter::msgOk($message);

if (isset($_POST['notify']) && intval($_POST['notify']) == 1) {
require_once (BASEPATH . "lib/class_mailer.php");
$mailer = $mail->sendMail();

$row = Registry::get("Core")->getRowById(Content::eTable, 3); // Envois Mail de Bienvenue lors de l'enregistrement

$body = str_replace(array(
'[USERNAME]',
'[PASSWORD]',
'[NAME]',
'[SITE_NAME]',
'[URL]'), array(
$data['username'],
$_POST['password'],
$data['fname'] . ' ' . $data['lname'],
Registry::get("Core")->site_name,
SITEURL), $row->body);

$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($data['email'] => $data['fname'] . ' ' . $data['lname']))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody(cleanOut($body), 'text/html');

$numSent = $mailer->send($message);
}

/*
* I get the actual status of the user. If it's different from the
one sent from the client, I send the email
*/
$sanitized = sanitize($_POST['active']);
if (sanitize($_POST['active'] != $userdata['active'])) {
$this->sendEmailStatusChanged($sanitized, $data);
}
} else
Filter::msgAlert(Lang::$word->NOPROCCESS);
} else
print Filter::msgStatus();
}


/**
* Users::updateProfile()
*
* @return
*/
public function updateProfile()
{

Filter::checkPost('position', Lang::$word->ACC_NAMEPOSITION);

if ($value = $this->positionExists($_POST['position'])) {
if ($value == 1)
Filter::$msgs['position'] = Lang::$word->POSITION_R2;
if ($value == 2)
Filter::$msgs['position'] = Lang::$word->POSITION_R3;
if ($value == 3)
Filter::$msgs['position'] = Lang::$word->POSITION_R4;
}

Filter::checkPost('fname', Lang::$word->FNAME);
Filter::checkPost('lname', Lang::$word->LNAME);
Filter::checkPost('pass', Lang::$word->PASSWORD);
Filter::checkPost('birth_month', Lang::$word->ACC_BIRTHM);
Filter::checkPost('birth_day', Lang::$word->ACC_BIRTHD);
Filter::checkPost('birth_year', Lang::$word->ACC_BIRTHY);
Filter::checkPost('job', Lang::$word->ACC_JOB);
Filter::checkPost('zipcode', Lang::$word->ACC_ZIP);
Filter::checkPost('city', Lang::$word->ACC_CITY);
Filter::checkPost('state', Lang::$word->ACC_STATE);
Filter::checkPost('country', Lang::$word->ACC_COUNTRY);
Filter::checkPost('sponsor', Lang::$word->ACC_RECOM);
Filter::checkPost('entry', Lang::$word->ACC_ENTRY);
Filter::checkPost('quest1', Lang::$word->ACC_Q1);
Filter::checkPost('quest2', Lang::$word->ACC_Q2);
Filter::checkPost('quest3', Lang::$word->ACC_Q3);
Filter::checkPost('quest4', Lang::$word->ACC_Q4);
Filter::checkPost('quest5', Lang::$word->ACC_Q5);
Filter::checkPost('terms', Lang::$word->ACC_TERMS);

Filter::checkPost('email', Lang::$word->EMAIL);

if ($this->emailExists($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R2;

if (!$this->isValidEmail($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R3;

Filter::checkPost('email_sponsor', Lang::$word->ACC_RECOMAIL2);

if ($this->emailSponsorExists($_POST['email_sponsor']))
Filter::$msgs['email_sponsor'] = Lang::$word->EMAIL_SPR2;

if (!$this->isValidEmail2($_POST['email_sponsor']))
Filter::$msgs['email_sponsor'] = Lang::$word->EMAIL_SPR3;


Filter::checkPost('position', Lang::$word->ACC_NAMEPOSITION);

if ($this->positionExists($_POST['position']))
Filter::$msgs['position'] = Lang::$word->POSITION_R4;


if (!empty($_FILES['avatar']['name'])) {
if (!preg_match("/(\.jpg|\.png)$/i", $_FILES['avatar']['name'])) {
Filter::$msgs['avatar'] = Lang::$word->CONF_LOGO_R;
}
$file_info = getimagesize($_FILES['avatar']['tmp_name']);
if (empty($file_info))
Filter::$msgs['avatar'] = Lang::$word->CONF_LOGO_R;
}

if (empty(Filter::$msgs)) {

$data = array(
'email' => sanitize($_POST['email']),
'lname' => sanitize($_POST['lname']),
'fname' => sanitize($_POST['fname']),
'birth_month' => sanitize($_POST['birth_month']),
'birth_day' => sanitize($_POST['birth_day']),
'birth_year' => sanitize($_POST['birth_year']),
'job' => sanitize($_POST['job']),
'phone' => sanitize($_POST['phone']),
'address1' => sanitize($_POST['address1']),
'address2' => sanitize($_POST['address2']),
'zipcode' => sanitize($_POST['zipcode']),
'city' => sanitize($_POST['city']),
'state' => sanitize($_POST['state']),
'country' => sanitize($_POST['country']),
'skype' => sanitize($_POST['skype']),
'facebook' => sanitize($_POST['facebook']),
'sponsor' => sanitize($_POST['sponsor']),
'email_sponsor' => sanitize($_POST['email_sponsor']),
'entry' => sanitize($_POST['entry']),
'position' => sanitize($_POST['position']),
'quest1' => sanitize($_POST['quest1']),
'quest2' => sanitize($_POST['quest2']),
'quest3' => sanitize($_POST['quest3']),
'quest4' => sanitize($_POST['quest4']),
'quest5' => sanitize($_POST['quest5']),
'comment' => sanitize($_POST['comment']),
'comment_admin' => sanitize($_POST['comment_admin']),
'terms' => sanitize($_POST['terms']),
'newsletter' => intval($_POST['newsletter'])
);

$userpass = getValueById("password", self::uTable, $this->uid);

if ($_POST['password'] != "") {
$data['password'] = sha1($_POST['password']);
} else
$data['password'] = $userpass;

// Procces Avatar
if (!empty($_FILES['avatar']['name'])) {
$thumbdir = UPLOADS . "avatars/";
$tName = "AVT_" . randName();
$text = substr($_FILES['avatar']['name'], strrpos($_FILES['avatar']['name'], '.') + 1);
$thumbName = $thumbdir . $tName . "." . strtolower($text);
if (Filter::$id && $thumb = getValueById("avatar", self::uTable, Filter::$id)) {
@unlink($thumbdir . $thumb);
}
move_uploaded_file($_FILES['avatar']['tmp_name'], $thumbName);
$data['avatar'] = $tName . "." . strtolower($text);
}

self::$db->update(self::uTable, $data, "id='" . $this->uid . "'");

(self::$db->affected()) ? Filter::msgOk(Lang::$word->_UA_PROFILE_OK) : Filter::msgAlert(Lang::$word->NOPROCCESS);
} else
print Filter::msgStatus();
}


/**
* User::sendEmailStatusChanged()
*
* @return
*/

public function sendEmailStatusChanged($status, $data) {
global $db, $core;
require_once(BASEPATH . "lib/class_mailer.php");
$m = new Mailer();
$mailer = $m->sendMail();
$body = "";
$row = null;
if ($status == "y") {
$row = Registry::get("Core")->getRowById(Content::eTable, 17); // Sent Mail Account Activation
$toBeReplaced = array('[NAME]', '[SITE_NAME]', '[URL]');
$replace = array($data['fname'] . ' ' . $data['lname'], $core->site_name, $core->site_url);
$body = str_replace($toBeReplaced, $replace, $row->body);
}
if ($status == "n") {
$row = Registry::get("Core")->getRowById(Content::eTable, 20); // Sent Mail Account Suspended
$toBeReplaced = array('[NAME]', '[SITE_NAME]', '[URL]');
$replace = array($data['fname'] . ' ' . $data['lname'], $core->site_name, $core->site_url);
$body = str_replace($toBeReplaced, $replace, $row->body);
}
if ($status == "b") {
$row = Registry::get("Core")->getRowById(Content::eTable, 18); // Sent Mail Account Banned
$toBeReplaced = array('[NAME]', '[SITE_NAME]', '[URL]');
$replace = array($data['fname'] . ' ' . $data['lname'], $core->site_name, $core->site_url);
$body = str_replace($toBeReplaced, $replace, $row->body);
}
if ($status == "t") {
$row = Registry::get("Core")->getRowById(Content::eTable, 19); // Sent Mail Account Disabled
$toBeReplaced = array('[NAME]', '[SITE_NAME]', '[URL]');
$replace = array($data['fname'] . ' ' . $data['lname'], $core->site_name, $core->site_url);
$body = str_replace($toBeReplaced, $replace, $row->body);
}
$newbody = cleanOut($body);
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($data['email'] => $data['fname'] . ' ' . $data['lname']))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($newbody, 'text/html');
$fail = array();
$accepted = $mailer->send($message,$fail);
print_r($fail);

}


/**
* User::register()
*
* @return
*/
public function register()
{

Filter::checkPost('username', Lang::$word->USERNAME);

if ($value = $this->usernameExists($_POST['username'])) {
if ($value == 1)
Filter::$msgs['username'] = Lang::$word->USERNAME_R2;
if ($value == 2)
Filter::$msgs['username'] = Lang::$word->USERNAME_R3;
if ($value == 3)
Filter::$msgs['username'] = Lang::$word->USERNAME_R4;
}

Filter::checkPost('position', Lang::$word->ACC_NAMEPOSITION);

if ($value = $this->positionExists($_POST['position'])) {
if ($value == 1)
Filter::$msgs['position'] = Lang::$word->POSITION_R2;
if ($value == 2)
Filter::$msgs['position'] = Lang::$word->POSITION_R3;
if ($value == 3)
Filter::$msgs['position'] = Lang::$word->POSITION_R4;
}

Filter::checkPost('fname', Lang::$word->FNAME);
Filter::checkPost('lname', Lang::$word->LNAME);
Filter::checkPost('pass', Lang::$word->PASSWORD);
Filter::checkPost('birth_month', Lang::$word->ACC_BIRTHM);
Filter::checkPost('birth_day', Lang::$word->ACC_BIRTHD);
Filter::checkPost('birth_year', Lang::$word->ACC_BIRTHY);
Filter::checkPost('job', Lang::$word->ACC_JOB);
Filter::checkPost('zipcode', Lang::$word->ACC_ZIP);
Filter::checkPost('city', Lang::$word->ACC_CITY);
Filter::checkPost('state', Lang::$word->ACC_STATE);
Filter::checkPost('country', Lang::$word->ACC_COUNTRY);
Filter::checkPost('sponsor', Lang::$word->ACC_RECOM);
Filter::checkPost('entry', Lang::$word->ACC_ENTRY);
Filter::checkPost('quest1', Lang::$word->ACC_Q1);
Filter::checkPost('quest2', Lang::$word->ACC_Q2);
Filter::checkPost('quest3', Lang::$word->ACC_Q3);
Filter::checkPost('quest4', Lang::$word->ACC_Q4);
Filter::checkPost('quest5', Lang::$word->ACC_Q5);
Filter::checkPost('terms', Lang::$word->ACC_TERMS);

if (strlen($_POST['pass']) < 6)
Filter::$msgs['pass'] = Lang::$word->PASSWORD_T2;
elseif (!preg_match("/^[a-z0-9_-]{6,15}$/", ($_POST['pass'] = trim($_POST['pass']))))
Filter::$msgs['pass'] = Lang::$word->PASSWORD_R2;
elseif ($_POST['pass'] != $_POST['pass2'])
Filter::$msgs['pass'] = Lang::$word->PASSWORD_R3;

Filter::checkPost('email', Lang::$word->EMAIL);

if ($this->emailExists($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R2;

if (!$this->isValidEmail($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R3;

Filter::checkPost('email_sponsor', Lang::$word->ACC_RECOMAIL2);

if ($this->emailSponsorExists($_POST['email_sponsor']))
Filter::$msgs['email_sponsor'] = Lang::$word->EMAIL_SPR2;

if (!$this->isValidEmail2($_POST['email_sponsor']))
Filter::$msgs['email_sponsor'] = Lang::$word->EMAIL_SPR3;


Filter::checkPost('captcha', Lang::$word->CAPTCHA);

if ($_SESSION['captchacode'] != $_POST['captcha'])
Filter::$msgs['captcha'] = Lang::$word->CAPTCHA_E2;

if (empty(Filter::$msgs)) {

$token = (Registry::get("Core")->reg_verify == 1) ? $this->generateRandID() : 0;
$pass = sanitize($_POST['pass']);

if (Registry::get("Core")->reg_verify == 1) {
$active = "t";
} elseif (Registry::get("Core")->auto_verify == 0) {
$active = "n";
} else {
$active = "y";
}

$data = array(
'username' => sanitize($_POST['username']),
'password' => sha1($_POST['pass']),
'email' => sanitize($_POST['email']),
'fname' => sanitize($_POST['fname']),
'lname' => sanitize($_POST['lname']),
'birth_month' => sanitize($_POST['birth_month']),
'birth_day' => sanitize($_POST['birth_day']),
'birth_year' => sanitize($_POST['birth_year']),
'job' => sanitize($_POST['job']),
'phone' => sanitize($_POST['phone']),
'address1' => sanitize($_POST['address1']),
'address2' => sanitize($_POST['address2']),
'zipcode' => sanitize($_POST['zipcode']),
'city' => sanitize($_POST['city']),
'state' => sanitize($_POST['state']),
'country' => sanitize($_POST['country']),
'skype' => sanitize($_POST['skype']),
'facebook' => sanitize($_POST['facebook']),
'sponsor' => sanitize($_POST['sponsor']),
'email_sponsor' => sanitize($_POST['email_sponsor']),
'entry' => sanitize($_POST['entry']),
'position' => sanitize($_POST['position']),
'quest1' => sanitize($_POST['quest1']),
'quest2' => sanitize($_POST['quest2']),
'quest3' => sanitize($_POST['quest3']),
'quest4' => sanitize($_POST['quest4']),
'quest5' => sanitize($_POST['quest5']),
'comment' => sanitize($_POST['comment']),
'comment_admin' => sanitize($_POST['comment_admin']),
'terms' => sanitize($_POST['terms']),
'newsletter' => intval($_POST['newsletter']),
'token' => $token,
'active' => $active,
'created' => "NOW()"
);

self::$db->insert(self::uTable, $data);

require_once(BASEPATH . "lib/class_mailer.php");

if (Registry::get("Core")->reg_verify == 1) {
$actlink = SITEURL . "/activate.php";
$row = Registry::get("Core")->getRowById(Content::eTable, 1); // Envois Mail confirmation pour enregistrement automatique ( confirmtion email )

$body = str_replace(array(
'[NAME]',
'[USERNAME]',
'[PASSWORD]',
'[TOKEN]',
'[EMAIL]',
'[PHONE]',
'[EMAIL_SPONSOR]',
'[ENTRY]',
'[POSITION]',
'[SPONSOR]',
'[TERMS]',
'[URL]',
'[LINK]',
'[SITE_NAME]'), array(
$data['fname'] . ' ' . $data['lname'],
$data['username'],
$data['phone'],
$data['entry'],
$data['position'],
$data['sponsor'],
$data['email_sponsor'],
$data['terms'],
$_POST['pass'],
$token,
$data['email'],
SITEURL,
$actlink,
Registry::get("Core")->site_name), $row->body);

$newbody = cleanOut($body);

$mailer = $mail->sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($data['email'] => $data['username']))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($newbody, 'text/html');

$mailer->send($message);

} elseif (Registry::get("Core")->auto_verify == 0) {
$row = Registry::get("Core")->getRowById(Content::eTable, 11); // Envois Mail au nouveau membre

$body = str_replace(array(
'[NAME]',
'[USERNAME]',
'[PASSWORD]',
'[BIRTH_DAY]',
'[BIRTH_MONTH]',
'[BIRTH_YEAR]',
'[JOB]',
'[ZIPCODE]',
'[CITY]',
'[STATE]',
'[COUNTRY]',
'[EMAIL]',
'[PHONE]',
'[ENTRY]',
'[SPONSOR]',
'[EMAIL_SPONSOR]',
'[POSITION]',
'[QUEST1]',
'[QUEST2]',
'[QUEST3]',
'[QUEST4]',
'[QUEST5]',
'[COMMENT]',
'[TERMS]',
'[URL]',
'[SITE_NAME]'), array(
$data['fname'] . ' ' . $data['lname'],
$data['username'],
$_POST['pass'],
$data['birth_day'],
$data['birth_month'],
$data['birth_year'],
$data['job'],
$data['zipcode'],
$data['city'],
$data['state'],
$data['country'],
$data['email'],
$data['phone'],
$data['sponsor'],
$data['email_sponsor'],
$data['entry'],
$data['position'],
$data['quest1'],
$data['quest2'],
$data['quest3'],
$data['quest4'],
$data['quest5'],
$data['comment'],
$data['terms'],
SITEURL,
Registry::get("Core") > site_name), $row->body);

$newbody = cleanOut($body);

$mailer = $mail->sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($data['email'] => $data['username']))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($newbody, 'text/html');

$mailer->send($message);


$srow = Registry::get("Core")->getRowById(Content::eTable, 15); // Envois Mail Sponsor

$sbody = str_replace(array(
'[NAME]',
'[USERNAME]',
'[EMAIL]',
'[ZIPCODE]',
'[CITY]',
'[STATE]',
'[COUNTRY]',
'[TERMS]',
'[SPONSOR]',
'[ENTRY]',
'[URL]',
'[SITE_NAME]'), array(
$data['fname'] . ' ' . $data['lname'],
$data['username'],
$_POST['email'],
$core->site_url,
$_POST['zipcode'],
$_POST['city'],
$_POST['state'],
$_POST['country'],
$_POST['terms'],
$_POST['sponsor'],
$_POST['entry'],
SITEURL,
Registry::get("Core") > site_name), $srow->body);

$snewbody = cleanOut($sbody);

$smailer = $mail->sendMail();
$smessage = Swift_Message::newInstance()
->setSubject($srow->subject)
->setTo(array($data['email'] => $data['username']))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($snewbody, 'text/html');

$smailer->send($smessage);


} else {
$row = Registry::get("Core")->getRowById(Content::eTable, 7); // Envois Mail quand tout est automatisé ( registration / activation )

$body = str_replace(array(
'[NAME]',
'[USERNAME]',
'[PASSWORD]',
'[URL]',
'[SITE_NAME]'), array(
$data['fname'] . ' ' . $data['lname'],
$data['username'],
$_POST['pass'],
SITEURL,
Registry::get("Core")->site_name), $row->body);

$newbody = cleanOut($body);

$mailer = $mail->sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($data['email'] => $data['username']))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($newbody, 'text/html');

$mailer->send($message);
}
if (Registry::get("Core")->notify_admin) {
$arow = Registry::get("Core")->getRowById(Content::eTable, 16); // Envois Mail Administration pour archives

$abody = str_replace(array(
'[USERNAME]',
'[EMAIL]',
'[NAME]',
'[URL]',
'[BIRTH_DAY]',
'[BIRTH_MONTH]',
'[BIRTH_YEAR]',
'[JOB]',
'[ZIPCODE]',
'[CITY]',
'[STATE]',
'[COUNTRY]',
'[EMAIL]',
'[PHONE]',
'[SPONSOR]',
'[EMAIL_SPONSOR]',
'[ENTRY]',
'[POSITION]',
'[QUEST1]',
'[QUEST2]',
'[QUEST3]',
'[QUEST4]',
'[QUEST5]',
'[COMMENT]',
'[TERMS]',
'[IP]'), array(
$data['username'],
$data['email'],
$data['fname'] . ' ' . $data['lname'],
$core->site_url,
$data['birth_day'],
$data['birth_month'],
$data['birth_year'],
$data['job'],
$data['zipcode'],
$data['city'],
$data['state'],
$data['country'],
$data['email'],
$data['phone'],
$data['sponsor'],
$data['email_sponsor'],
$data['entry'],
$data['position'],
$data['quest1'],
$data['quest2'],
$data['quest3'],
$data['quest4'],
$data['quest5'],
$data['comment'],
$data['terms'],
$_SERVER['REMOTE_ADDR']), $arow->body);

$anewbody = cleanOut($abody);

$amailer = $mail->sendMail();
$amessage = Swift_Message::newInstance()
->setSubject($arow->subject)
->setTo(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($anewbody, 'text/html');

$amailer->send($amessage);
}

(self::$db->affected() && $mailer) ? print "OK" : Filter::msgError(Lang::$word->_UA_PASSR_ERR);
} else
print Filter::msgStatus();
}

/**
* User::passReset()
*
* @return
*/
public function passReset()
{

Filter::checkPost('uname', Lang::$word->USERNAME);
Filter::checkPost('email', Lang::$word->EMAIL);

$uname = $this->usernameExists($_POST['uname']);
if (strlen($_POST['uname']) < 4 || strlen($_POST['uname']) > 30 || !preg_match("/^[a-z0-9_-]{4,15}$/", $_POST['uname']) || $uname != 3)
Filter::$msgs['uname'] = Lang::$word->USERNAME_R5;

if (!$this->emailExists($_POST['email']))
Filter::$msgs['uname'] = Lang::$word->EMAIL_R4;

Filter::checkPost('captcha', Lang::$word->CAPTCHA_E1);
if ($_SESSION['captchacode'] != $_POST['captcha'])
Filter::$msgs['captcha'] = Lang::$word->CAPTCHA_E2;

if (empty(Filter::$msgs)) {

$user = $this->getUserInfo($_POST['uname']);
$randpass = $this->getUniqueCode(12);
$newpass = sha1($randpass);

$data['password'] = $newpass;

self::$db->update(self::uTable, $data, "username = '" . $user->username . "'");

require_once(BASEPATH . "lib/class_mailer.php");
$row = Core::getRowById("email_templates", 2);

$body = str_replace(array(
'[USERNAME]',
'[PASSWORD]',
'[URL]',
'[LINK]',
'[IP]',
'[SITE_NAME]'), array(
$user->username,
$randpass,
SITEURL,
SITEURL,
$_SERVER['REMOTE_ADDR'],
Registry::get("Core")->site_name), $row->body);

$newbody = cleanOut($body);

$mailer = $mail->sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($user->email => $user->username))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($newbody, 'text/html');

(self::$db->affected() && $mailer->send($message)) ? Filter::msgOk(Lang::$word->_UA_PASSR_OK) : Filter::msgError(Lang::$word->_UA_PASSR_ERR);

} else
print Filter::msgStatus();
}

/**
* User::activateAccount()
*
* @return
*/
public function activateAccount()
{

$data['active'] = "y";
self::$db->update(self::uTable, $data, "id = '" . Filter::$id . "'");

require_once (BASEPATH . "lib/class_mailer.php");
$row = Registry::get("Core")->getRowById(Content::eTable, 15);
$usr = Registry::get("Core")->getRowById(self::uTable, Filter::$id);

$body = str_replace(array(
'[NAME]',
'[URL]',
'[SITE_NAME]'), array(
$usr->fname . ' ' .$usr->lname,
SITEURL,
Registry::get("Core")->site_name), $row->body);

$newbody = cleanOut($body);

$mailer = $mail->sendMail();
$message = Swift_Message::newInstance()
->setSubject($row->subject)
->setTo(array($usr->email => $usr->username))
->setFrom(array(Registry::get("Core")->site_email => Registry::get("Core")->site_name))
->setBody($newbody, 'text/html');

(self::$db->affected() && $mailer->send($message)) ? Filter::msgOk(Lang::$word->USR_ACCT_OK) : Filter::msgError(Lang::$word->USR_ACCT_ERR);

}

/**
* User::activateUser()
*
* @return
*/
public function activateUser()
{

Filter::checkPost('email', Lang::$word->EMAIL);

if (!$this->emailExists($_POST['email']))
Filter::$msgs['email'] = Lang::$word->EMAIL_R4;

Filter::checkPost('token', Lang::$word->_UA_TOKEN);

if (!$this->validateToken($_POST['token']))
Filter::$msgs['token'] = Lang::$word->_UA_TOKEN_R;

if (empty(Filter::$msgs)) {
$email = sanitize($_POST['email']);
$token = sanitize($_POST['token']);
$message = (Registry::get("Core")->auto_verify == 1) ? Lang::$word->_UA_ACCOK_1 : Lang::$word->_UA_ACCOK_2;

$data = array('token' => 0, 'active' => (Registry::get("Core")->auto_verify) ? "y" : "n");

self::$db->update(self::uTable, $data, "email = '" . $email . "' AND token = '" . $token . "'");
(self::$db->affected()) ? Filter::msgOk($message) : Filter::msgError(Lang::$word->_UA_TOKEN_ERR);
} else
print Filter::msgStatus();
}

/**
* Users::getUserList()
*
* @return
*/
public function getUserList()
{
$sql = "SELECT id, username, CONCAT(fname,' ',lname) as name FROM " . self::uTable
. "\n WHERE active = 'y'";
$row = self::$db->fetch_all($sql);

return ($row) ? $row : 0;
}

/**
* Users::getUserData()
*
* @return
*/
public function getUserData()
{

$sql = "SELECT *"
. "\n FROM " . self::uTable
. "\n WHERE id = '" . $this->uid . "'";
$row = self::$db->first($sql);

return ($row) ? $row : 0;
}

/**
* Users::usernameExists()
*
* @param mixed $username
* @return
*/
private function usernameExists($username)
{

$username = sanitize($username);
if (strlen(self::$db->escape($username)) < 4)
return 1;

//Username should contain only alphabets, numbers, underscores or hyphens.Should be between 4 to 15 characters long
$valid_uname = "/^[a-zA-Z0-9_-]{4,15}$/";
if (!preg_match($valid_uname, $username))
return 2;

$sql = self::$db->query("SELECT username"
. "\n FROM " . self::uTable
. "\n WHERE username = '" . $username . "'"
. "\n LIMIT 1");

$count = self::$db->numrows($sql);

return ($count > 0) ? 3 : false;
}

/**
* User::emailExists()
*
* @param mixed $email
* @return
*/
private function emailExists($email)
{
$sql = self::$db->query("SELECT email"
. "\n FROM " . self::uTable
. "\n WHERE email = '" . sanitize($email) . "'"
. "\n LIMIT 1");

if (self::$db->numrows($sql) == 1) {
return true;
} else
return false;
}

/**
* User::emailSponsorExists()
*
* @param mixed $email
* @return
*/
private function emailSponsorExists($email_sponsor)
{
$sql = self::$db->query("SELECT email_sponsor"
. "\n FROM " . self::uTable
. "\n WHERE email = '" . sanitize($email_sponsor) . "'"
. "\n LIMIT 1");

if (self::$db->numrows($sql) == 0) {
return true;
} else
return false;
}


/**
* User::positionExists()
*
* @param mixed $email
* @return
*/

private function positionExists($position)
{
$sql = self::$db->query("SELECT position"
. "\n FROM " . self::uTable
. "\n WHERE position = '" . sanitize($position) . "'"
. "\n LIMIT 1");

if (self::$db->numrows($sql) == 1) {
return true;
} else
return false;
}



private function positionExists($position,$userid=null){
$and='';

if($userid){
$and = " and id NOT IN ('". $userid ."') ";
}

$sql = self::$db->query("SELECT position FROM " . self::uTable . " WHERE position = '" . sanitize($position) . "'". $and ." LIMIT 1");

if (self::$db->numrows($sql) == 1) {
return true;
} else {
return false;
}



/**
* User::isValidEmail()
*
* @param mixed $email
* @return
*/
private function isValidEmail($email)
{
if (function_exists('filter_var')) {
if (filter_var($email, FILTER_VALIDATE_EMAIL)) {
return true;
} else
return false;
} else
return preg_match('/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $email);
}

/**
* User::isValidEmail2()
*
* @param mixed $email
* @return
*/
private function isValidEmail2($email_sponsor)
{
if (function_exists('filter_var')) {
if (filter_var($email_sponsor, FILTER_VALIDATE_EMAIL)) {
return true;
} else
return false;
} else
return preg_match('/^[a-zA-Z0-9._+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/', $email_sponsor);
}

/**
* User::confirmCookie()
*
* @param mixed $username
* @param mixed $cookie_id
* @return
*/
private function confirmCookie($username, $cookie_id)
{

$sql = "SELECT cookie_id FROM " . self::uTable . " WHERE username = '" . self::$db->escape($username) . "'";
$row = self::$db->first($sql);

$row->cookie_id = sanitize($row->cookie_id);
$cookie_id = sanitize($cookie_id);

if ($cookie_id == $row->cookie_id) {
return true;
} else
return false;
}

/**
* User::validateToken()
*
* @param mixed $token
* @return
*/
private function validateToken($token)
{
$token = sanitize($token, 40);
$sql = "SELECT token"
. "\n FROM " . self::uTable
. "\n WHERE token ='" . self::$db->escape($token) . "'"
. "\n LIMIT 1";
$result = self::$db->query($sql);

if (self::$db->numrows($result))
return true;
}

/**
* Users::getUniqueCode()
*
* @param string $length
* @return
*/
private function getUniqueCode($length = "")
{
$code = sha1(uniqid(rand(), true));
if ($length != "") {
return substr($code, 0, $length);
} else
return $code;
}

/**
* Users::generateRandID()
*
* @return
*/
private function generateRandID()
{
return sha1($this->getUniqueCode(24));
}

/**
* Users::levelCheck()
*
* @param string $levels
* @return
*/
public function levelCheck($levels)
{
$m_arr = explode(",", $levels);
reset($m_arr);

if ($this->logged_in and in_array($this->userlevel, $m_arr))
return true;
}

/**
* Users::getUserLevels()
*
* @return
*/
public function getUserLevels($level = false)
{
$arr = array(
9 => 'Super Admin',
1 => 'Registered User',
2 => 'User Level 2',
3 => 'User Level 3',
4 => 'User Level 4',
5 => 'User Level 5',
6 => 'User Level 6',
7 => 'User Level 7'
);

$list = '';
foreach ($arr as $key => $val) {
if ($key == $level) {
$list .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
} else
$list .= "<option value=\"$key\">$val</option>\n";
}
unset($val);
return $list;
}

/**
* Users::getUserFilter()
*
* @return
*/
public static function getUserFilter()
{
$arr = array(
'username-ASC' => Lang::$word->USERNAME . ' ↑',
'username-DESC' => Lang::$word->USERNAME . ' ↓',
'fname-ASC' => Lang::$word->FNAME . ' ↑',
'fname-DESC' => Lang::$word->FNAME . ' ↓',
'lname-ASC' => Lang::$word->LNAME . ' ↑',
'lname-DESC' => Lang::$word->LNAME . ' ↓',
'email-ASC' => Lang::$word->EMAIL . ' ↑',
'email-DESC' => Lang::$word->EMAIL . ' ↓',
'created-ASC' => Lang::$word->REGD . ' ↑',
'created-DESC' => Lang::$word->REGD . ' ↓',
);

$filter = '';
foreach ($arr as $key => $val) {
if ($key == get('sort')) {
$filter .= "<option selected=\"selected\" value=\"$key\">$val</option>\n";
} else
$filter .= "<option value=\"$key\">$val</option>\n";
}
unset($val);
return $filter;
}
}
?>

merci en tous les cas de ton aide et du temps consacré.
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Pourquoi, as tu dans ta page DEUX fonctions update du même nom?
"private function positionExists"

enlève l'ancienne et dis moi si tu as toujours tes soucis.
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

Hello Jordane,

normal.. non, mais normalement il en a une qui doit être en commentaire.. afin que je fasse mes test..( chose que j'ai pas mis dans la page ci-contre ).... j'ai testé avec ta modif et mise l'autre en commentaire.. aucune changement,... toujours des balise d'erreur détectée..
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
- Des balises d'erreur où ? (quelle(s) ligne(s) ? )
- Regarde s'il n'y a pas un point-virgule manquant ou en trop ( idem pour les crochets).
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Hormis un crochet oublié à la fin de la fonction...Je n'ai aucune autre erreur de syntaxe sur le code que je t'ai donné...


function positionExists($position,$userid=NULL)
{
$and='';
if($userid){
$and = "and id NOT IN ('".$userid ."')";
}
$sql = self::$db->query("SELECT position FROM " . self::uTable . " WHERE position = '" . sanitize($position) . "'". $and ." LIMIT 1");

if (self::$db->numrows($sql) == 1)
{ return true;
} else
{
return false;
}
}




Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

Hello Jordane,

y a amélioration :o) merci... plus de d'erreur de balise..
par contre.. la fonction fonctionne pas..

j'ai toujours un message que la donnée ( position ) existe déjà

donc.. si pour toi la variable que je t'ai dite et bien "$userid" ?
je confirme que la colonne dans la base de donnée est bien "id"

je ne sais pas pourquoi j'ai toujours cette info.. ?
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

ok, mais en mettant ainsi ( la fonction positionExists ) et l'appel de la fonction.... marche pas.. j'ai toujours message indiquant : que la donnée exitse déjà.. :o ??
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Essaye ça :

$value = $this->positionExists($_POST['position'], $this->uid))
ECHO $value;

par contre, ta fonction retourne TRUE ou FALSE .. elle ne te donne pas de valeurs 1,2, ou 3 ... tu as donc un souci dans le reste de ton code;. non ??
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

pourtant le code, fonctionne lors de l'enregistrement.. le check si le nom est déjà utilisé ou pas, s'effectue..

c'est une fois logué, dans la page profile user, quand l'utilisateur change son profile.. que cette fonction ne fonctionne plus.

j'avais fait une copie de la fonction de EmailExist, et changer les paramètre,ce qui me paraissait plus logique et simple à faire.

donc si cela fonctionne pour l'emailexist, devrait fonctionner avec d'autre variable pour positionExist.

mais je vais reprendre depuis le zéro du commetre un boulette à un endroit... à moins que cela te saute aux yeuy ou que t'ai solution sous la main..
Messages postés
29235
Date d'inscription
mercredi 22 octobre 2003
Statut
Modérateur
Dernière intervention
14 août 2020
335
Tu es bien d'accord que ta fonction retourne TRUE ou FALSE

if (self::$db->numrows($sql) == 1)
{
return true;
}
else
{
return false;
}

Si tu veux t'en assurer... essayes donc le code que je t'ai mis dans mon commentaire précédent...

après il te suffit juste de changer les tests que tu fais apres...
Si true : Existe ( chez un autre user)
Si false: N'existe pas (chez un autre user).

Enfin bon, Fais donc l'Echo de $Value .. déjà pour t'assurer qu'il te retourne bien la bonne valeur en fonction desparametres que tu auras passé à la fonction....ce qui permettra déjà de t'assurer que ta fonction Marche correctement;

Ce qui ne semble pas aller, c'est la suite de ton code ( les IF value==1..etc... ) puisque $value ne prend jamais les valeurs 1,2,3.
Messages postés
22
Date d'inscription
lundi 22 août 2005
Statut
Membre
Dernière intervention
14 décembre 2013

oui, je suis d'accord,

j'ai fait une confusion ( copie de fonction déjà existante )... alors maintenant,

j'ai ceci comme fonction positionExist ( qui est une copie de celle utiliser pour username à la création du compte, car les action sont identique à celle ci.

private function positionExists($position,$uid=NULL)
{
Echo $uid;
$position = sanitize($position);

if (strlen(self::$db->escape($position)) < 4)
return 1;

//position should contain only alphabets, numbers, underscores or hyphens.Should be between 4 to 15 characters long
$valid_position = "/^[a-zA-Z0-9_-]{4,15}$/";
if (!preg_match($valid_position, $position))
return 2;

$and='';
if($uid){
$and = "and id NOT IN ('".$uid ."')";
}
$sql = self::$db->query("SELECT position FROM " . self::uTable . " WHERE position = '" . sanitize($position) . "'". $and ." LIMIT 1");

$count = self::$db->numrows($sql);

return ($count > 0) ? 3 : false;
}

et la l'appel ( dans la fonction updateProfil )

		  Filter::checkPost('position', Lang::$word->ACC_NAMEPOSITION);

if ($value = $this->positionExists($_POST['position'], $uid)) {
if ($value == 1)
Filter::$msgs['position'] = Lang::$word->POSITION_R2;
if ($value == 2)
Filter::$msgs['position'] = Lang::$word->POSITION_R3;
if ($value == 3)
Filter::$msgs['position'] = Lang::$word->POSITION_R4;
}

cela te paraît-il juste ?...

résultat identique... il ne me laisse pas faire la mise à jour car.. nom déjà existant...


et ou dois-je planter cette balise pour test ?
(
 $value = $this->positionExists($_POST['position'], $this->uid)) 
ECHO $value;
) ?

et ou dois-je voir le résultat ?