<?php
/**
 * @package linea21.core
 * @subpackage user
 * @author linea21 <info@linea21.com>
 * @version $id SVN
 * @access public
 * @license http://opensource.org/licenses/gpl-3.0.html
 * User Management
 */

class user {
  /* @param
   * */
  var $TDB_USER = T_USER; // nom de la table.
  var $URI_INPUT = "user/avatar/"; // dossier racine de stockage des photos
  var $NB_USERS = 30; // affichage par défaut du nombre d'utilisateurs
  var $UPLOAD_MAX_MO = 10240; // taille maximale d'upload des avatars en octets
  var $ID;
  var $LOGIN;
  var $PASSWORD;
  var $COMMUNITY = USER_COMMUNITY;
  var $CATEGORY;
  var $RIGHT;
  var $PROFILE;
  var $DATE_CREA;
  var $VALIDITY;
  var $LAST_MODIFY;

  var $R_ID;
  var $R_DASHBOARD;
  var $R_WORKSHOP;
  var $R_PROJECT;
  var $R_PUBLICATION;
  var $R_NEWS;
  var $R_YELLOWPAGES;
  var $R_THEME;
  var $R_SCALE;
  var $R_LEVEL;
  var $R_CATEGORY_USER;

  var $P_ID;
  var $P_EMAIL;
  var $P_EMAIL_DISPLAY;

  var $P_CITY;
  var $P_BIRTHDATE;
  var $P_LEISURES;
  var $P_JOB;
  var $P_AVATAR;
  var $P_QUOTATION;
  var $P_SIGNATURE;

  /**
   * user::CheckDataIntegrity()
   * Vérification intégrité des données
   *
   * @access public
   * @param array $table : contient les composants d'un user
   * @param object $sql_object
   * @return boolean si vrai renvoie true sinon message d'erreurs (string)
   */
  function CheckDataIntegrity($table, $sql_object = null)
  {
    if (isset($sql_object)) {
      $result = $this->_checkLoginValidity($table[0], $sql_object);
      if (is_string($result)) return $result;
    }
    $result = $this->_checkEmailValidity($table[1]);
    if (is_string($result)) return $result;
    return true;
  }

  /**
   * user::_checkLoginValidity()
   * validation d'un login
   *
   * @access private
   * @param string $login : login rentré par l'utilisateur
   * @param object $sql_object
   * @return bool $result
   * si valide true sinon message d'erreur (string)
   */
  function _checkLoginValidity($login, $sql_object)
  {
    $login = trim($login);
    if (!preg_match('|^[a-zA-Z0-9]+$|', $login)) return $GLOBALS['lang']['user']['login_prohibited'];
    if (strlen($login) < 5) return $GLOBALS['lang']['user']['login_tooshort'];
    if (strlen($login) > 20) $GLOBALS['lang']['user']['login_toolong'];
    $requete = "SELECT user_id FROM " . $this->TDB_USER . " WHERE lower(user_login)= '" . strtolower($login) . "' AND user_validity='Y';";

    $result = $sql_object->DBSelect($requete);

    if ($result != 0) return $GLOBALS['lang']['user']['login_used'];

    return true;
  }

  /**
   * user::checkPasswordValidity()
   * validation d'un password
   *
   * @access publi
   * @param string $password password rentre par l'utilisateur
   * @param string $pass2 (option)
   * @return bool si valide true sinon message d'erreur (string)
   */
  function checkPasswordValidity($password, $pass2 = -1)
  {
    if (strlen($password) < 5) return $GLOBALS['lang']['user']['pass_tooshort'];
    if (strlen($password) > 15) return $GLOBALS['lang']['user']['pass_toolong'];
    if ($pass2 != -1 && $password != $pass2) return $GLOBALS['lang']['user']['pass_not_same'];

    return true;
  }

  /**
   * user::_checkEmailValidity()
   * validation d'un email
   *
   * @access private
   * @param string $email email rentre par l'utilisateur
   * @return string $result
   * return 1 si valide sinon message d'erreur (string)
   */
  function _checkEmailValidity($email)
  {
    $email = strtolower($email);
    $emailinvalide = $GLOBALS['lang']['user']['invalid_mail'] . " :'" . $email . "'";
    if (strlen($email) < 6 || !ereg("@", $email) || preg_match_all("/([^a-zA-Z0-9_\@\.\-])/i", $email, $trouve) || !preg_match("/^([a-z0-9_]|\\-|\\.)+@(([a-z0-9_]|\\-)+\\.)+[a-z]{2,4}\$/i", $email)) {
      return $emailinvalide;
    }
    list($compte, $domaine) = split("@", $email, 2);
    if (function_exists('checkdnsrr')) {
      if (!checkdnsrr($domaine, "MX")) return $emailinvalide;
    }
    return 1;
  }

  /**
   * user::_setUserCategory()
   * determine automatique la categorie d'un utilisateur en fonction de ses droits
   * et renseigne l'objet
   *
   * @access private
   * @param array $table_right tableau des droits de l'utilisateur
   * @return bool $result
   */
  function _setUserCategory($table_right)
  {
    if (isset($table_right['category_user']) && $table_right['category_user'] == 'A') $this->CATEGORY = 1;
    else {
      if ($table_right['dashboard'] == 'O' || $table_right['publication'] == 'O' || $table_right['news'] == 'O' || $table_right['workshop'] == 'O') $this->CATEGORY = 2;
      else $this->CATEGORY = 3;
    }

    return true;
  }

  /**
   * user::_AddProfile()
   * Ajout d'un profil
   *
   * @access private
   * @param object $sql_object
   * @return integer $last_id
   */
  function _AddProfile($sql_object)
  {
    $requete = "INSERT INTO " . T_PROFILE . " (profile_email, profile_email_display, profile_city, profile_birthdate, profile_leisures, profile_job, profile_avatar, profile_quotation, profile_signature, profile_date_crea) VALUES ('" . $this->P_EMAIL . "', '" . $this->P_EMAIL_DISPLAY . "','', '0001-01-01', '', '', '', '', '', NOW());";
    $last_id = $sql_object->DBInsert ($requete, 1);
    return $last_id;
  }

  /**
   * user::_AddRight()
   * stockage des droits d' un utilisateur BDD
   *
   * @access private
   * @param array $table_right contient les droits
   * @param object $sql_object
   * @return integer $last_id
   */
  function _AddRight($table_right, $sql_object)
  {
    $this->R_DASHBOARD = $table_right['dashboard'];
    $this->R_WORKSHOP = $table_right['workshop'];
    $this->R_PROJECT = $table_right['project'];
    $this->R_PUBLICATION = $table_right['publication'];
    $this->R_NEWS = $table_right['news'];
    $this->R_YELLOWPAGES = $table_right['yellowpages'];
    $this->R_THEME = $table_right['theme'];
    $this->R_SCALE = $table_right['scale'];
    $this->R_LEVEL = $table_right['level'];
    $this->R_CATEGORY_USER = $table_right['category_user'];
    $requete = "INSERT INTO " . T_RIGHT . " (rights_dashboard, rights_workshop, rights_project, rights_publication, rights_news, rights_yellowpages, rights_theme, rights_scale, rights_level, rights_category_user, rights_date_crea)VALUES ('" . $this->R_DASHBOARD . "', '" . $this->R_WORKSHOP . "', '" . $this->R_PROJECT . "', '" . $this->R_PUBLICATION . "', '" . $this->R_NEWS . "', '" . $this->R_YELLOWPAGES . "', '" . $this->R_THEME . "', '" . $this->R_SCALE . "', '" . $this->R_LEVEL . "', '" . $this->R_CATEGORY_USER . "', NOW());";
    $last_id = $sql_object->DBInsert ($requete, 1);
    return $last_id;
  }

  /**
   * user::GetNewPassword()
   * creation aleatoire d'un password
   *
   * @access public
   * @param int $length taille du password
   * @return string $password
   */
  function GetNewPassword($length = PASSWD_LENGTH)
  {
    $str = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
    $password = '';
    for ($i = 0; $i < $length; $i++) {
      $password .= substr($str, rand(0, strlen($str) - 1), 1);
    }
    return $password;
  }

  /**
   * user::InitUserRight()
   * formatage du tableau de droit suivant profil prédeterminé
   *
   * @access public
   * @param string $type niveau utilisateur : SIMPLE_USER ou ADMIN_USER
   * @return array $table_right : tableau des droits de l'utilisateur
   */
  function InitUserRight($type = 'SIMPLE_USER')
  {
    $table_user = array ("dashboard" => 'U', "workshop" => 'U', "publication" => 'U', "project" => 'U',
            "news" => 'U', "yellowpages" => 'U', "theme" => 'U',
            "scale" => 'U', "level" => 'U', "category_user" => 'U');

    switch ($type) {
      case 'SIMPLE_USER':
        $table_right = $table_user;
        break;
      case 'ADMIN_USER':
        $table_right = array ("dashboard" => 'A', "workshop" => 'A', "publication" => 'A',
                    "project" => 'A', "news" => 'A', "yellowpages" => 'A',
                    "theme" => 'A', "scale" => 'A', "level" => 'A',
                    "category_user" => 'A');
        break;
      default:
        $table_right = $table_user;
        break;
    }

    return $table_right;
  }


  /**
   * user::UpdateUserPassword()
   * changement de password (mise à jour) dans la bdd
   *
   * @access public
   * @param int $ID identifiant utilisateur
   * @param string $pass nouveau password non crypté
   * @param object $sql_object
   * @return bool $result
   */
  function UpdateUserPassword($ID, $pass, $sql_object)
  {
    if (is_numeric($ID)) {
      $this->ID = $ID;
    } else exit;
    $this->PASSWORD = crypt($pass, SALT_CRYPT);
    $requete = "UPDATE " . $this->TDB_USER . " SET user_password='" . $this->PASSWORD . "' WHERE user_id='" . $this->ID . "';";
    $result = $sql_object->DBQuery ($requete);

    return $result;
  }

  /**
   * user::AddUser()
   * Ajout d'un utilisateur
   *
   * @access public
   * @param array $table_user contient les composants de l'utilisateur
   * @param array $table_right contient les droits attribués au nouvel utilisateur
   * @param object $sql_object
   * @return integer $last_id
   * renvoie un message d'erreur ou un numerique id de l'insertion
   */
  function AddUser($table_user, $table_right, $sql_object)
  {
    $table_user=$sql_object->DBescape($table_user);

    $this->LOGIN = strip_input(trim($table_user[0]));
    $this->P_EMAIL = strtolower($table_user[1]);
    $this->P_EMAIL_DISPLAY = $table_user[2];
    $this->PASSWORD = crypt($table_user[3], SALT_CRYPT);
    $this->_SetUserCategory($table_right);
    $this->PROFILE = $this->_AddProfile($sql_object);
    $this->RIGHT = $this->_AddRight($table_right, $sql_object);
    $requete = "INSERT INTO " . $this->TDB_USER . " (user_login, user_password, user_community, user_category, user_rights, user_profile, user_date_crea) VALUES ('" . $this->LOGIN . "', '" . $this->PASSWORD . "', " . $this->COMMUNITY . ", " . $this->CATEGORY . ", " . $this->RIGHT . ", " . $this->PROFILE . ", NOW());";

    $result = $sql_object->DBInsert ($requete, 1);
    return $result;
  }

  /**
   * user::DeleteUser()
   * suppression d'un utilisateur
   *
   * @access public
   * @param int $ID identifiant de l'utilisateur
   * @param object $sql_object
   * @return bool $result
   */
  function DeleteUser($ID, $sql_object)
  {
    if (is_numeric($ID)) {
      $this->ID = $ID;
    } else return false;
    $requete = "UPDATE " . $this->TDB_USER . " SET user_validity='N' WHERE user_id=" . $this->ID . ";";
    $result = $sql_object->DBQuery ($requete);
    $requete = "DELETE FROM " . J_WORK_USERS . " WHERE jwu_user_id=" . $this->ID . ";";
    $result = $sql_object->DBQuery ($requete);
    return $result;
  }

  /**
   * user::ModifyProfile()
   * modification d'un profil utilisateur
   *
   * @access public
   * @param int $id identifiant d'un profil
   * @param object $sql_object
   * @param array $table_profile contient les composants d'un profil
   * @return bool $result
   */
  function ModifyProfile($ID, $table_profile, $sql_object)
  {
    $table_profile=$sql_object->DBescape($table_profile);

    if (is_numeric($ID)) {
      $this->ID = $ID;
    } else return false;

    $this->P_EMAIL = strtolower($table_profile[0]);

    $requete = "UPDATE " . $this->TDB_USER . " SET user_last_modify=NOW() WHERE user_id='" . $this->ID . "';";
    $result = $sql_object->DBSelect ($requete);

    $requete = "SELECT user_profile FROM " . $this->TDB_USER . " WHERE user_id='" . $this->ID . "' LIMIT 1;";
    $data = $sql_object->DBSelect ($requete, 'OBJECT');
    if ($data!=0 && count($data) == 1) {
      $this->P_ID = $data[0]->user_profile;
    } else return false;
    $this->P_EMAIL_DISPLAY = strtoupper($table_profile[1]);
    $this->P_CITY = strip_input(ucfirst(trim($table_profile[2])));
    $this->P_BIRTHDATE = ($table_profile[3]=='--') ? '0001-01-01' : formatDate($table_profile[3], true);
    $this->P_LEISURES = strip_input(trim($table_profile[4]));
    $this->P_JOB = strip_input(trim($table_profile[5]));
    $this->P_QUOTATION = strip_input(trim($table_profile[6]));
    $this->P_SIGNATURE = strip_input(trim($table_profile[7]));
    $this->P_AVATAR = strip_input($table_profile[8]);

    $requete = "UPDATE " . T_PROFILE . " SET profile_email='" . $this->P_EMAIL . "', profile_email_display='" . $this->P_EMAIL_DISPLAY . "', profile_city='" . $this->P_CITY . "', profile_birthdate='" . $this->P_BIRTHDATE . "', profile_leisures='" . $this->P_LEISURES . "', profile_job='" . $this->P_JOB . "', profile_quotation='" . $this->P_QUOTATION . "', profile_signature='" . $this->P_SIGNATURE . "', profile_avatar='" . $this->P_AVATAR . "' WHERE profile_id='" . $this->P_ID . "';";

    $result = $sql_object->DBQuery ($requete);

    return $result;
  }

  /**
   * user::ModifyRight()
   * modification des droits d'un utilisateur
   *
   * @access public
   * @param int $ID identifiant de l'utilisateur
   * @param object $sql_object
   * @param array $table_right contient un tableau associatif de droit
   * @return bool $result
   */
  function ModifyRight($ID, $table_right, $sql_object)
  {
    if (is_numeric($ID)) {
      $this->ID = $ID;
    } else return false;

    $update = '';
    $sep = ', ';
    if (isset($table_right['dashboard'])) {
      $this->R_DASHBOARD = $table_right['dashboard'];
      $update .= "rights_dashboard='" . $this->R_DASHBOARD . "'";
    }
    if (isset($table_right['project'])) {
      $this->R_PROJECT = $table_right['project'];
      $update .= $sep . "rights_project='" . $this->R_PROJECT . "'";
    }
    if (isset($table_right['publication'])) {
      $this->R_PUBLICATION = $table_right['publication'];
      $update .= $sep . "rights_publication='" . $this->R_PUBLICATION . "'";
    }
    if (isset($table_right['workshop'])) {
      $this->R_WORKSHOP = $table_right['workshop'];
      $update .= $sep . "rights_workshop='" . $this->R_WORKSHOP . "'";
    }
    if (isset($table_right['news'])) {
      $this->R_NEWS = $table_right['news'];
      $update .= $sep . "rights_news='" . $this->R_NEWS . "'";
    }
    if (isset($table_right['yellowpages'])) {
      $this->R_YELLOWPAGES = $table_right['yellowpages'];
      $update .= $sep . "rights_yellowpages='" . $this->R_YELLOWPAGES . "'";
    }
    if (isset($table_right['theme'])) {
      $this->R_THEME = $table_right['theme'];
      $update .= $sep . "rights_theme='" . $this->R_THEME . "'";
    }
    if (isset($table_right['scale'])) {
      $this->R_SCALE = $table_right['scale'];
      $update .= $sep . "rights_scale='" . $this->R_SCALE . "'";
    }
    if (isset($table_right['level'])) {
      $this->R_LEVEL = $table_right['level'];
      $update .= $sep . "rights_level='" . $this->R_LEVEL . "'";
    }
    if (isset($table_right['category_user'])) {
      $this->R_CATEGORY_USER = $table_right['category_user'];
      $update .= $sep . "rights_category_user='" . $this->R_CATEGORY_USER . "'";
    }

    $requete = "UPDATE " . $this->TDB_USER . " SET user_last_modify=NOW() WHERE user_id='" . $this->ID . "';";
    $result = $sql_object->DBSelect ($requete);
    $requete = "SELECT user_rights FROM " . $this->TDB_USER . " WHERE user_id='" . $this->ID . "';";
    $result = $sql_object->DBSelect ($requete);

    if ($result == 0) return false;
    if (count($result) == 1) {
      $this->R_ID = $result[0]['user_rights'];
    } else return false;
    $requete = "UPDATE " . T_RIGHT . " SET " . $update . " WHERE rights_id='" . $this->R_ID . "';";
    $result = $sql_object->DBQuery ($requete);
    
    if ($result) {
      $this->_SetUserCategory($table_right);
      $requete = "UPDATE " . $this->TDB_USER . " SET user_category='" . $this->CATEGORY . "' WHERE user_id='" . $this->ID . "';";
      
      $result = $sql_object->DBQuery ($requete);
    }
    return $result;
  }


}

?>
