<?php
# ************** LICENCE ****************
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version

	POSH is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
# ***************************************
#  SESSION management 
#
# !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
# ***************************************

session_name(__SESSION);
session_start();
if(isset($_COOKIE[__SESSION])) {
	set_cookie(__SESSION,$_COOKIE[__SESSION]);
}
/*! init_session

    @param[in]  $id, $user, $type, $lang, $longname

*/
function init_session($id,$user,$type,$lang,$longname,$activity,$picture = '',$email = '')
{
	if (isset($id))
    {
        $_SESSION['user_id'] = $id;
    }
	if (isset($user))
    {
        $_SESSION['username'] = $user;
    }
	if (isset($type))
    {
        $_SESSION['type'] = $type;
    }
	if (isset($lang) && $lang)
    {
        $_SESSION['lang'] = $lang;
    }
	if (isset($longname))
    {
        $_SESSION['longname'] = $longname;
    }
	
	$_SESSION['email'] = $email;
    
    $_SESSION['availability'] = (isset($activity) ? $activity : 'o');
    $_SESSION['picture'] = (isset($picture) ? $picture : '');
}
/*! close_session

    
    
*/
function close_session()
{
	session_unset();
	session_destroy();
}


/*! parseHTTPLanguage

    If variable disapppear, we add en language

*/
function parseHTTPLanguage () {
    global $languages;
  /* default to "everything is acceptable", as RFC2616 specifies */
  
  if ( isset($_SERVER["HTTP_ACCEPT_LANGUAGE"])  )
  {  
    $acceptLang=(($_SERVER["HTTP_ACCEPT_LANGUAGE"] == '') ? 'en,fr' :
    $_SERVER["HTTP_ACCEPT_LANGUAGE"]);
    $alparts = @preg_split("/,/",$acceptLang);
  	if(preg_match('/-/',$alparts[0])) {
		$tmp = @preg_split("/;/",$acceptLang);
		$tmpLangCtn = @preg_split("/,/",$tmp[0]);
		if(!empty($tmpLangCtn[0]) && !empty($tmpLangCtn[1])) {
			$tmp[0] = $tmpLangCtn[1].','.$tmpLangCtn[0];
			$acceptLang = $tmpLangCtn[1].','.$tmpLangCtn[0].';'.$tmp[1].';'.$tmp[2].';'.$tmp[3];
			$alparts = @preg_split("/,/",$acceptLang); 
		}
	}
    /* Parse the contents of the Accept-Language header.*/
    foreach($alparts as $part)
    {
        $part = trim($part);
        if(preg_match("/;/", $part))
        {
            $lang = @preg_split("/;/",$part);
            $score = @preg_split("/=/",$lang[1]);
            $languages[strToLower($lang[0])]=$score[1];
        }
        else
        {
            $languages[strToLower($part)]=1;
        }
    }
 }
 else
 {
   $languages['en']=1;
 }
 arsort($languages);
}
/*!  getDefaultLanguage

    using parseHTTPLanguage before 

*/
function getDefaultLanguage ($__AVLANGS)
{
    global $languages;
    //default language in __AVLANGS
    $chosen_language = $__AVLANGS[0];
	
    foreach ( $languages as $lang => $score)
    {
        $lc = @preg_split("/-/", $lang);
        $deflang = $lc ?  $lc[0] : $lang;
        if ( $score == 1 && in_array($deflang, $__AVLANGS) )
        {
            $chosen_language = $deflang;
            break;
        }
        else if (  in_array($deflang, $__AVLANGS)  )
        {
            $chosen_language = $deflang;
            break;
       }
    }
    if (!defined("__LANG"))
		define("__LANG", $chosen_language);
}

//language selection
if (isset($_GET["lang"]))
{
    if (    preg_match( '/^[a-z]{2}$/', $_GET["lang"] ) 
         || preg_match( '/^[a-z]{2}\-[a-z]{2}$/', $_GET["lang"] ) 
          ) {
        $_SESSION['lang'] = $_GET["lang"];
    } else {
        $_SESSION['lang'] = $__AVLANGS[0];
    }
}
if (isset($_SESSION['lang']))
{ 
	define("__LANG",$_SESSION['lang']);
}
else
{
    //parse http_accept_language, then get default language (score == 1)
   parseHTTPLanguage();
   getDefaultLanguage($__AVLANGS);
}

// Check that connection level is OK depending on the one requested in page
if( isset($not_access) && $not_access == 1)
{
	$tabGranted = explode(",", $granted);
	$uType = isset($_SESSION['type'])?$_SESSION['type']:'';
	// Exit if user not authorized
	/*
	if( !in_array($uType,$tabGranted) && $_SESSION['type']!="A" ) {
		exit();
	}*/
	
	if (
		(!is_array($_SESSION) || !array_key_exists("user_id",$_SESSION)) ||
		( !(in_array($uType,$tabGranted)) && $granted!="" && $uType!="A")
	)
	{
		if( $uType!="N" )
			close_session();
		if (isset($pagename))
		{
            if ( (isset($disconnected_mode_allowed) && $disconnected_mode_allowed == 'yes') || $uType=="N") {
				exit();
				}
			header('location:'.__LOCALFOLDER.'portal/login.php?message=You have been disconnected');
		}
		else
		{
			header('location:'.__LOCALFOLDER.'/index.php');
		}
        exit();
	}
}

function getPoshUserGroups ($DB) {
    global $user_getgroups;
    $groups = '';
    $DB->getResults(
                $user_getgroups,
                $DB->escape($_SESSION['user_id'])
            );
    if ($DB->nbResults() > 0) {
        $_SESSION['usergroups'] = array();
        while($row = $DB->fetch(0)) {
            $id = $row['id'];
            $name = $row['name'];
            $parent_id = $row['parent_id'];
            $name = preg_replace("/'/","\'",$name);
            $groups .= "\n\t'$id':{'name':'$name','parent_id':$parent_id},";
            $_SESSION['usergroups'][$id] = array( 'name' => $name, 'parent_id' => $parent_id );
        }
        $groups = preg_replace('/,$/','',$groups);
    }
    $DB->freeResults();
    echo "\n    \$p.app.user.usergroups = {\n $groups \n    };\n";
    
    //get the list of my followers
    $networks = '';
    if (__enterprise) {
        global $xmlnetworkusers_getFollowersFB;
        global $xmlnetworkusers_getFollowersTW;
        if (__NETWORK_TYPE == "R")
        $DB->getResults($xmlnetworkusers_getFollowersFB,$DB->escape($_SESSION['user_id']),$DB->escape(0),$DB->escape(999));
        else
        $DB->getResults($xmlnetworkusers_getFollowersTW,$DB->escape($_SESSION['user_id']),$DB->escape($_SESSION['user_id']),$DB->escape(0),$DB->escape(999));
        while($row=$DB->fetch(0))
        {
            $follower_id = $row['id']; 
            $_SESSION['networks'][$follower_id] = array();
           $networks .= "\n\t'$follower_id':{},";
        }
        $DB->freeResults(); 

    }
	$networks = preg_replace('/,$/','',$networks);
	echo "\n    \$p.app.user.usernetworks = { $networks \n    };\n";    
}

function set_cookie($name,$value,$delay=0,$path="",$domain="") {
	
	if(defined("__OPEN_TAB_BASED_ON_SUBDOMAIN")) {
		if(__OPEN_TAB_BASED_ON_SUBDOMAIN) {
			if(empty($domain)) {
				$host = isset($_SERVER['HTTP_HOST'])?$_SERVER['HTTP_HOST']:"";
				preg_match("/[^\.\/]+\.[^\.\/]+$/",$host,$domain);
				$domain = isset($domain[0])?$domain[0]:"";
			}
			setcookie($name,$value,$delay,$path,$domain);
		} else {
			setcookie($name,$value,$delay);
		}
	}else {
		setcookie($name,$value,$delay);
	}

}

?>
