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

/**
* AuthenthificationProcess()
* Authentification d'un utilisateur
* 
* @param  $login 
* @param  $pass 
* @param  $type ='PUBLIC' || 'ADMIN'
* @return boolean (true) ou message d'erreur
*/

function AuthenthificationProcess($login, $pass, $type)
{
    LogAccess($type, $login);
    $crypt_pass = crypt($pass, SALT_CRYPT);
    $requete = SQL_Get_UserInfo4Auth($login, $crypt_pass);

    $data = $GLOBALS['sql_object']->DBSelect(SQL_Get_UserInfo4Auth($login, $crypt_pass));
    if ($data != 0 && count($data) == 1) {
        if ($type == 'PUBLIC') {
            $requete = SQL_Get_UserWorkshop($login, $crypt_pass);
            $data_w = $GLOBALS['sql_object']->DBSelect(SQL_Get_UserWorkshop($login, $crypt_pass));
            $workshop_list = '';
            for ($i = 0; $i < count($data_w); $i++) {
                $workshop_list .= "/" . $data_w[$i]['jwu_workshop_id'];
            } 
            $table['id'] = $data[0]['user_id'];
            $table['whois'] = base64_encode($crypt_pass);
            $table['login'] = $login;
            $table['workshop'] = base64_encode($workshop_list);
            DestroyUserCookie();
            SetUserCookie($table);
        } 
        if ($type == 'ADMIN') {
            // préparation du tableau de droits
            $right['dashboard'] = $data[0]['rights_dashboard'];
            $right['workshop'] = $data[0]['rights_workshop'];
            $right['project'] = $data[0]['rights_project'];
            $right['publication'] = $data[0]['rights_publication'];
            $right['news'] = $data[0]['rights_news'];
            $right['yellowpages'] = $data[0]['rights_yellowpages'];
            $right['theme'] = $data[0]['rights_theme'];
            $right['scale'] = $data[0]['rights_scale'];
            $right['level'] = $data[0]['rights_level'];
            $right['category_user'] = $data[0]['rights_category_user']; 
            // est simple utilisateur
            if (!array_search ('A' , $right) && !array_search ('O' , $right)) {
                return $GLOBALS['lang']['divers']['errorauth']; 
                // est utilisateur avec droits
            } else {
                $_SESSION['sess_is_known'] = true;
                $_SESSION['sess_id'] = base64_encode($data[0]['user_id']);
                $_SESSION['sess_whois'] = base64_encode($crypt_pass);
                $_SESSION['sess_login'] = $login;
                $_SESSION['sess_right'] = $right;
                Set_Cookie_last_connexion();
            } 
        } 
        return true;
    } else {
        $error_msg = $GLOBALS['lang']['divers']['errorauth'];
        return $error_msg;
    } 
} 

/**
* WorkshopAuth_id()
* 
* @param  $id_user 
* @param  $sql_object 
* @param  $id_workshop 
* @return boolean 
*/
function WorkshopAuth_id ($id_user, $sql_object, $id_workshop)
{
    $data = $sql_object->DBSelect(SQL_Get_UserInfo4Authid($id_user));
    $workshop_list = '';
    $result = false;
    for ($i = 0; $i < count($data); $i++) {
        if ($id_workshop == $data[$i]['jwu_workshop_id']) $result = true;
    } 
    return $result;
} 

/**
* AuthUser4Workshop()
* 
* @param integer $workshop_id 
* @param object $sql_object 
* @return boolean 
*/
function AuthUser4Workshop ($workshop_id, $sql_object)
{
    $data = $sql_object->DBSelect(SQL_Get_UserWorkshopOwner($workshop_id));
    for ($i = 0; $i < count($data); $i++) {
        if (GetSessionElement('id') == $data[$i]['jwu_user_id']) return true;
    } 
    return false;
} 

/**
* IsSuperAdmin()
* 
* @return boolean 
*/
function IsSuperAdmin()
{
    return HaveRight('theme');
} 

/**
* HaveRights()
* 
* @param string $item 
* @return bool 
*/
function HaveRight($item)
{
    switch ($item) {
        case 'category_user':
            if (GetSessionElement('right_category_user') != 'A') return false;
            else return true;
        case 'theme':
            if (GetSessionElement('right_theme') != 'A') return false;
            else return true;
        case 'level':
            if (GetSessionElement('right_level') != 'A') return false;
            else return true;
        case 'scale':
            if (GetSessionElement('right_scale') != 'A') return false;
            else return true;
        case 'yellowpages':
            if (GetSessionElement('right_yellowpages') != 'A') return false;
            else return true;
        case 'news':
            if (GetSessionElement('right_news') != 'U') return true;
            else return false;
        case 'project':
            if (GetSessionElement('right_project') != 'A') return false;
            else return true;
        case 'publication':
            if (GetSessionElement('right_publication') != 'U') return true;
            else return false;
        case 'workshop':
            if (GetSessionElement('right_workshop') != 'U') return true;
            else return false;
        case 'dashboard':
            if (GetSessionElement('right_dashboard') != 'U') return true;
            else return false;
        default:
            return false;
    } 
} 

/**
* GetSessionElement()
* 
* @param string $item (id, whois, login, right)
* @return $result
*/

function GetSessionElement($item)
{
    switch ($item) {
        case 'id':
            return base64_decode($_SESSION['sess_id']);
            break;
        case 'whois':
            return base64_decode($_SESSION['sess_whois']);
            break;
        case 'login':
            return $_SESSION['sess_login'];
            break;
        case 'right_theme':
            return $_SESSION['sess_right']['theme'];
            break;
        case 'right_dashboard':
            return $_SESSION['sess_right']['dashboard'];
            break;
        case 'right_workshop':
            return $_SESSION['sess_right']['workshop'];
            break;
        case 'right_project':
            return $_SESSION['sess_right']['project'];
            break;
        case 'right_publication':
            return $_SESSION['sess_right']['publication'];
            break;
        case 'right_news':
            return $_SESSION['sess_right']['news'];
            break;
        case 'right_yellowpages':
            return $_SESSION['sess_right']['yellowpages'];
            break;
        case 'right_scale':
            return $_SESSION['sess_right']['scale'];
            break;
        case 'right_level':
            return $_SESSION['sess_right']['level'];
            break;
        case 'right_category_user':
            return $_SESSION['sess_right']['category_user'];
            break;
    } 
} 

/**
* SetUserCookie()
* set les infos contenu en tableau PHP en cookie
* 
* @param  $table 
* @return void 
*/
function SetUserCookie($table)
{
    while (list($key, $value) = @each($table)) {
        setcookie('linea21[' . $key . ']', $value, (time() + 3600 * 720), '/');
    } 
} 

/**
* DestroyUserCookie()
* Détruit les infos contenu en cookie
* 
* @return void 
*/
function DestroyUserCookie()
{
    while (list($key, $val) = @each($_COOKIE['linea21'])) {
        setcookie('linea21[' . $key . ']', '', (time() - 3600), '/');
    } 
} 

/**
* UpdateCookiePassword()
* Mise à jour du mot de passe dans le cookie (cas de changement)
* 
* @param  $newpass 
* @return void 
*/
function UpdateCookiePassword($newpass)
{
    $newpass = base64_encode($newpass);
    setcookie('linea21[whois]', $newpass, (time() + 3600 * 720), '/');
} 

/**
* UpdateCookieWorkshop()
* Ajout d'un Groupe de travail aux droits d'un utiliateur
* 
* @param  $workshop_id 
* @return 
*/
function UpdateCookieWorkshop($workshop_id)
{
    $string_id = base64_decode($_COOKIE['linea21']['workshop']);
    $string_id .= "/" . $workshop_id;
    $string_id = base64_encode($string_id);
    setcookie('linea21[workshop]', $string_id, (time() + 3600 * 720), '/');
} 

/**
* CookieWorkshopid()
* vérification de l'inscription de l'utilisateur au groupe de travail
* 
* @param  $workshop_id 
* @return boolean
*/
function CookieWorkshopid($workshop_id)
{
    if (isset($_COOKIE['linea21']['workshop'])) {
        $string_id = base64_decode($_COOKIE['linea21']['workshop']);

        $string_id = str_replace(" ", "", $string_id);
        $table_id = @explode('/', $string_id);
        for ($i = 0; $i < count($table_id); $i++) {
            if ($workshop_id == $table_id[$i])return true;
        } 
        return false;
    } 
    return false;
} 

/**
* Set_Cookie_last_connexion()
*/
function Set_Cookie_last_connexion()
{
    setcookie('linea21_lastcon', time(), (time() + 3600 * 720), '/');
} 

/**
* LogAccess()
* 
* @param integer $login 
* @param integer $pass 
* @return void 
*/
function LogAccess($type, $login = -1, $pass = -1)
{
    if ($type == 'PUBLIC') $file = LOG_PUBLIC_ACCESS;
    if ($type == 'ADMIN') $file = LOG_ADMIN_ACCESS;
    $sep = '##';
    $fp = @fopen($file, 'a');
    @fwrite($fp, i2c_realip() . $sep); // adresse
    @fwrite($fp, $_SERVER['HTTP_USER_AGENT'] . $sep); //agent
    @fwrite($fp, $_SERVER['HTTP_REFERER'] . $sep); // referer
    @fwrite($fp, $_SERVER['REQUEST_METHOD'] . $sep); // methode requetes HTTP
    @fwrite($fp, $_SERVER['REQUEST_URI'] . $sep); // script courant
    @fwrite($fp, $_SERVER['QUERY_STRING'] . $sep); // requete url
    @fwrite($fp, $_SERVER['HTTP_COOKIE'] . $sep); // cookie
    @fwrite($fp, date('[d-m-y H:i:s]' . $sep)); // date
    if ($login != -1) @fwrite($fp, $login . $sep); // login
    if ($pass != -1) @fwrite($fp, $pass . $sep); // mot de passe
    @fwrite($fp, END_LINE);
    @fclose($fp);
} 
// Returns the real IP address of the user
function i2c_realip()
{ 
    // No IP found (will be overwritten by for
    // if any IP is found behind a firewall)
    $ip = false; 
    // If HTTP_CLIENT_IP is set, then give it priority
    if (!empty($_SERVER["HTTP_CLIENT_IP"])) {
        $ip = $_SERVER["HTTP_CLIENT_IP"];
    } 
    // User is behind a proxy and check that we discard RFC1918 IP addresses
    // if they are behind a proxy then only figure out which IP belongs to the
    // user.  Might not need any more hackin if there is a squid reverse proxy
    // infront of apache.
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
        // Put the IP's into an array which we shall work with shortly.
        $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);
        if ($ip) {
            array_unshift($ips, $ip);
            $ip = false;
        } 

        for ($i = 0; $i < count($ips); $i++) {
            // Skip RFC 1918 IP's 10.0.0.0/8, 172.16.0.0/12 and
            // 192.168.0.0/16 -- jim kill me later with my regexp pattern
            // below.
            if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {
                $ip = $ips[$i];
                break;
            } 
        } 
    } 
    // Return with the found IP or the remote address
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
} 

?>