<?php

/**
* 
* \brief tools to manage Posh users
* includes/users_tools.php
**/

/**
* \brief function checkPoshUserbyId
*
*

    password can be optional
    
    groupname also is used to add user in specific group

* example:
    require_once('../includes/users_tools.php');  

    $datas = array(
                    'username' => 'user test',
                    'lang'      => 'fr',
                    'usertype' => 'I',
        #            'password'  => 'passwordtest',
                    'long_name' => "user test",
                    'groupname' => 'rotototo',
                    'DB'        => $DB,
                    'DB2'       => $DB2,
                    'group0'    => 3,
                    'group1'    => 2  
                );
        
    managePoshUser($datas);
*
*
**/
function checkPoshUserbyId (&$datas) {
    $userid = $datas['userid'];
    $DB->getResults($users_getUserInformation,
                        $DB->escape($userid)
                    );
    if ($DB->nbResults() > 0) {

    }
    $DB->freeResults();
}

/**
* \brief function checkPoshUserByEmail
*
*
*
**/
function checkPoshUserByEmail (&$datas) {
    $username = $datas['username'];
    $DB = $datas['DB'];
    global $users_getuseridFromUsername;
    $DB->getResults($users_getuseridFromUsername,
                        $DB->quote($username)
                    );
    if ($DB->nbResults() > 0) {
        $row=$DB->fetch(0);
        $datas['userid'] = $row['id'];
        $DB->freeResults();
        return true;
    } else {
        $DB->freeResults();
        return false;
    }
}

/**
* \brief function addPoshUser
*
*   check if user with email exists
*
*
*   @param[in] array
*                           username
                            userid
                            long_name
                            password
                            user_type
                            lang
                            groupname   group to add
*
*/
function managePoshUser (&$datas) {
    if (checkPoshUserByEmail($datas) ) {
        if (updatePoshUser($datas) ) {
            $userid = $datas['userid'];
            getPoshGroupsUser($datas);
            InsertUserInPoshUsergroup($datas);
            updatePoshPagesGroup2user($datas);
            deletePoshMapping2user($datas);
            mapPoshGroup2user($datas);
        } else {
            //cannot update user
        }
    } else {
        if ( createPoshUser($datas) ) {
            getPoshGroupsUser($datas);
            InsertUserInPoshUsergroup($datas);
            addPoshPagesGroup2newuser($datas);
            mapPoshGroup2user($datas);

        } else {
            //cann,ot create user
        }
    }
}

/**
* \brief function createPoshUser
*
*
*
*/
function createPoshUser (&$datas) {
    $DB = $datas['DB'];
    global $users_addNew, $users_logUserAdd;
    $user = $datas['username'];
    $long_name = $datas['long_name'];
    $user_type = $datas['usertype'];
    $password = $datas['password'];
    $key        = md5($user.$password);
    $datas['md5pass'] = $key;
    $lang = $datas['lang'];
    $DB->execute($users_addNew2,$DB->quote($user),$DB->quote($long_name),
                            $DB->quote($user_type),
                            $DB->quote($password),
                            $DB->quote($key),
                            $DB->quote($lang)
                );
    $userid = $DB->getId();
    if ($userid > 0) {
        $datas['userid'] = $userid;
        addPageToNewUser($datas);
        $DB->execute($users_logUserAdd,$userid);
        $DB->freeResults();
        return true;
    }
    $DB->freeResults();
    return false;
}
/**
* \brief function updatePoshUser
*
*
*
*/
function updatePoshUser (&$datas) {
    $DB = $datas['DB'];
    global $users_updateWithPass,$users_updateWithoutPass;
	$username   = $datas["username"];
    $userid     = $datas["userid"];
    $password   = $datas["password"];
    $long_name  = $datas['long_name'];
    $usertype  = $datas['usertype'];
    $password   = $datas['password'];
    $key        = md5($username.$password);
    $lang       = $datas['lang'];
    
    if ($username!="" && $password!="" && $password!="xxxxxxxx") {
		$DB->execute($users_updateWithPass,
                            $DB->quote($username),
                            $DB->quote($long_name),
                            $DB->quote($usertype),
                            $DB->quote($password),
                            $DB->quote($key),
                            $DB->quote($lang),
                            $DB->escape($userid)
                        );
     }
     else 
     { 
		$DB->execute($users_updateWithoutPass,
                                $DB->quote($username),
                                $DB->quote($long_name),
                                $DB->quote($user_type),
                                $DB->quote($lang),
                                $DB->escape($userid)
                        
                    );        
    }
    return true;
}

function InsertUserInPoshUsergroup (&$datas) {
    
    $DB = $datas['DB'];
    global $users_addInGroup;
    $groupname = isset($datas['groupname']) ? $datas['groupname'] : '';
    if (
        $groupname
        && !isset($datas['groups'][$groupname]) //check if user is already mapped to group
        && existsUserGroup($datas)          //check if group exists
        ) {
        //map user to group
        $userid = $datas['userid'];
        $groupid = $datas['groupid'];
        //count group and add this group
        
        $nbgroup = 0;
        foreach ($datas as $c => $v) {
            if (preg_match('/group\d+/',$c)) {
                $nbgroup += 1;
            }
        }
        $datas['group'.$nbgroup] = $groupid;
        $DB->execute($users_addInGroup,
                        $DB->escape($userid),
                        $DB->escape($groupid)
                    );
    }
}

function existsUserGroup (&$datas) {
    $DB = $datas['DB'];
    global $isGroupName;
    $groupname = $datas['groupname'];
    $DB->getResults($isGroupName,0,$DB->quote($groupname));
    if ($DB->nbResults() > 0) {
        $row = $DB->fetch(0);
        $datas['groupid'] = $row['id'];
        return true;
    }
    return false;
}

function addPageToNewUser (&$datas) {
    global $users_getPublicAndGroupPages,
                $page_getPagesModule,
                $user_addProfilePages,
                $modules_addNewMod;
    $DB = $datas['DB'];
    $DB2 = $datas['DB2'];
    $userid = $datas['userid'];
    $datas['profiles'] = array();
    $DB->getResults($users_getPublicAndGroupPages,0);
    while ($row = $DB->fetch(0))
    {
        $DB->execute($user_addProfilePages,
                                $DB->escape($userid),
                                $DB->quote($row['name']),
                                $DB->escape($row['nbcol']),
                                $DB->escape($row['style']),
                                $DB->quote($row['controls']),
                                $DB->quote($row['showtype']),
                                $DB->escape($row['seq']),
                                $DB->quote($row['icon']),
                                $DB->quote($row['modulealign']),
                                $DB->quote($row['type']),
                                $DB->quote($row['param']),
                                $DB->escape($row['id']),
                                $DB->escape($row['removable'])
                    );
        $profid=$DB->getId();
        $datas['profiles'][$profid] = array($row['name']);            
        //must check the modules
        $temp_id=$row['id'];
        if ($row['type'] == 1)    {
            $DB2->getResults($page_getPagesModule,$temp_id);
            while ($rows = $DB2->fetch(0))
            {
                /*
                $DB2->execute($scrconfigplace_addNewMod,
                                $DB2->escape($rows['item_id']),
                                $DB2->escape($userid),
                                $DB2->escape($profid),
                                $DB2->escape($rows['posx']),
                                $DB2->escape($rows['posy']),
                                $DB2->escape($rows['posj']),
                                $DB2->escape($rows['x']),
                                $DB2->escape($rows['y']),
                                $DB2->quote($rows['variables']),
                                $DB2->escape($rows['uniq']),
                                $DB2->escape($rows['blocked']),
                                $DB2->escape($rows['minimized']) 
                              );
                              */
               $DB2->execute($modules_addNewMod,
                                $DB2->escape($rows['item_id']),
                                $DB2->escape($rows['posx']),
                                $DB2->escape($rows['posy']),
                                $DB2->escape($rows['posj']),
                                $DB2->escape($rows['x']),
                                $DB2->escape($rows['y']),
                                $DB2->quote($rows['variables']),
                                $DB2->quote($rows['uniq']),
                                $DB2->escape($rows['blocked']),
                                $DB2->escape($rows['minimized']),
                                $DB2->escape($userid),
                                $DB2->escape($temp_id)   
                    );   
            }
            $DB2->freeResults();
        }
    }
}


/*
*
* \def addPoshPagesGroup2newuser
*   
*   \brief
*   add page and modules for groups to new user
*
*   @params[in]  array $datas
*                   array(
*                   DB => $DB,
*                   DB2 => $DB2,
*                   userid => $userid,
*                   group<n> => 'id of group',
 *                  group<n+1>  => 'id of group'
 *               )
 *
 *      group list begins to 0
 *      
 *
*/
function addPoshPagesGroup2newuser (&$datas) {
    global $users_getPublicAndGroupPages,
            $user_addProfilePages,
            $page_getPagesModule,
            $modules_addNewMod;
            
    $DB = $datas['DB'];
    $DB2 = $datas['DB2'];
    $userid = $datas['userid'];
    $cpt=0;	
    while (isset($datas["group".$cpt]))
    { 
        $DB->getResults($users_getPublicAndGroupPages, $DB->escape($datas["group".$cpt]));
        while ($row = $DB->fetch(0))
        {		
            $DB->execute($user_addProfilePages,
                                $DB->escape($userid),
                                $DB->quote($row['name']),
                                $DB->escape($row['nbcol']),
                                $DB->escape($row['style']),
                                $DB->quote($row['controls']),
                                $DB->quote($row['showtype']),
                                $DB->escape($row['seq']),
                                $DB->quote($row['icon']),
                                $DB->quote($row['modulealign']),
                                $DB->quote($row['type']),
                                $DB->quote($row['param']),
                                $DB->escape($row['id']),
                                $DB->escape($row['removable'])
                         );			
            $profid=$DB->getId();
            //must check the modules
            $temp_id=$row['id'];
            if ($row['type']==1)    {
                $DB2->getResults($page_getPagesModule,$temp_id);
                while ($rows = $DB2->fetch(0))
                {
                    /*
                    $DB2->execute($scrconfigplace_addNewMod,
                                                $DB2->escape($rows['item_id']),
                                                $DB2->escape($userid),
                                                $DB2->escape($profid),
                                                $DB2->escape($rows['posx']),
                                                $DB2->escape($rows['posy']),
                                                $DB2->escape($rows['posj']),
                                                $DB2->escape($rows['x']),
                                                $DB2->escape($rows['y']),
                                                $DB2->quote($rows['variables']),
                                                $DB2->escape($rows['uniq']),
                                                $DB2->escape($rows['blocked']),
                                                $DB2->escape($rows['minimized']) 
                                         );*/
                               $DB2->execute($modules_addNewMod,
                                    $DB2->escape($rows['item_id']),
                                    $DB2->escape($rows['posx']),
                                    $DB2->escape($rows['posy']),
                                    $DB2->escape($rows['posj']),
                                    $DB2->escape($rows['x']),
                                    $DB2->escape($rows['y']),
                                    $DB2->quote($rows['variables']),
                                    $DB2->quote($rows['uniq']),
                                    $DB2->escape($rows['blocked']),
                                    $DB2->escape($rows['minimized']),
                                    $DB2->escape($userid),
                                    $DB2->escape($temp_id)   
                                );   
                }
                $DB2->freeResults();
            }
        }
        $cpt++;
        $DB->freeResults();
    }
}

/*
*
* \def updatePoshPagesGroup2user
*
*   @params[in]  array $datas
*                   array(
*                   DB => $DB,
*                   DB2 => $DB2,
*                   userid => $userid,
*                   group<n> => 'id of group',
 *                  group<n+1>  => 'id of group'
 *               )
 *
 *      group list begins to 0
*/
function updatePoshPagesGroup2user (&$datas) {

    //declare request (see db_layer admin to get contents of these requests)
    global $user_newgroup_id,
            $users_getUserGroup,
            $user_group_id,
            $pages_getGroupPages,
            $users_getUserProfilesId,
            $users_deleteProfileModules,
            $users_deleteToUpdateTabs,
            $users_getExistingUserGroup,
            $users_getPublicAndGroupPages,
            $user_addProfilePages,
            $page_getPagesModule,
            $modules_addNewMod;
            
    $DB = $datas['DB'];
    $DB2 = $datas['DB2'];
    $userid = $datas['userid'];
	
    //Delete the users pages for the groups he's been suppressed
    $user_group_id = array ();
    $user_pages_id = array ();
    $user_newgroup_id = array ();
    $cpt=0;
    //get new groups
    while (isset($datas["group".$cpt])) {
        array_push ($user_newgroup_id, $datas["group".$cpt]);
        $cpt++;
    }
    
    //get old group mapping
    $DB->getResults($users_getUserGroup,$DB->escape($userid));
    while ($row = $DB->fetch(0)) {
       array_push ($user_group_id, $row['id']);
    }
    $DB->freeResults();
    
    //compare the two tabs on delete the user pages if not in the group anymore
    for ($i=0;$i<count($user_group_id);$i++) {
        if (!in_array($user_group_id[$i],$user_newgroup_id)) {
            $DB->getResults($pages_getGroupPages,$DB->escape($user_group_id[$i]));
            while ($row = $DB->fetch(0)) {
                array_push ($user_pages_id, $row['id']);
            }
            $DB->freeResults();
            
            for ($j=0;$j<count($user_pages_id);$j++)
            {
                //delete all modules
                //$DB->getResults($users_getUserProfilesId,$DB->escape($user_pages_id[$j]),$DB->escape($userid));
                //while ($row = $DB->fetch(0)) {
                //    $profile_id=$row['id'];
                $DB->execute($users_deleteProfileModules,$DB->escape($user_pages_id[$j]));
                //}
                //$DB->freeResults();
                //delete in profile
                $DB->execute($users_deleteToUpdateTabs,$DB->escape($user_pages_id[$j]),$DB->escape($userid));
            }
        }
    }
        
	//group page
	$cpt=0;
	while (isset($datas["group".$cpt]))
	{
		//verify if the page doesn't already exists
		$DB2->getResults($users_getExistingUserGroup,$DB2->escape($datas["group".$cpt]),$DB2->escape($userid));
		if ($DB2->nbResults()==0)   {
			$DB->getResults($users_getPublicAndGroupPages,$DB->escape($datas["group".$cpt]));
			while ($row = $DB->fetch(0))
			{	
                $DB->execute($user_addProfilePages,
                                        $DB->escape($userid),
                                        $DB->quote($row['name']),
                                        $DB->escape($row['nbcol']),
                                        $DB->escape($row['style']),
                                        $DB->quote($row['controls']),
                                        $DB->quote($row['showtype']),
                                        $DB->escape($row['seq']),
                                        $DB->quote($row['icon']),
                                        $DB->quote($row['modulealign']),
                                        $DB->quote($row['type']),
                                        $DB->quote($row['param']),
                                        $DB->escape($row['id']),
                                        $DB->escape($row['removable'])
                              );			
                $profid=$DB->getId();
                //must check the modules
                $temp_id=$row['id'];
                if ($row['type']==1) {
                    $DB2->getResults($page_getPagesModule,$temp_id);
                    while ($rows = $DB2->fetch(0))
                    {
                        /*
                        $DB2->execute($scrconfigplace_addNewMod,
                                                $DB2->escape($rows['item_id']),
                                                $DB2->escape($userid),
                                                $DB2->escape($profid),
                                                $DB2->escape($rows['posx']),
                                                $DB2->escape($rows['posy']),
                                                $DB2->escape($rows['posj']),
                                                $DB2->escape($rows['x']),
                                                $DB2->escape($rows['y']),
                                                $DB2->quote($rows['variables']),
                                                $DB2->escape($rows['uniq']),
                                                $DB2->escape($rows['blocked']),
                                                $DB2->escape($rows['minimized']) 
                                      );
                                      */
                         $DB2->execute($modules_addNewMod,
                                    $DB2->escape($rows['item_id']),
                                    $DB2->escape($rows['posx']),
                                    $DB2->escape($rows['posy']),
                                    $DB2->escape($rows['posj']),
                                    $DB2->escape($rows['x']),
                                    $DB2->escape($rows['y']),
                                    $DB2->quote($rows['variables']),
                                    $DB2->quote($rows['uniq']),
                                    $DB2->escape($rows['blocked']),
                                    $DB2->escape($rows['minimized']),
                                    $DB2->escape($userid),
                                    $DB2->escape($temp_id)   
                        );   
                    }
                    $DB2->freeResults();
                }
			}
            $DB->freeResults();
		}
		$cpt++;
	}
}

/*
*
* \def deletePoshMapping2user
*
*   deleete group mapping for an user (userid)
*
*
*
*/
function deletePoshMapping2user (&$datas) {
    
    if ( !isset($datas['usertype']) || $datas['usertype'] != 'I' ) {
        return false;
    }
    $DB = $datas['DB'];
    $DB2 = $datas['DB2'];
    $userid = $datas['userid'];
    global $user_removeFromGroup;
    $DB->execute($user_removeFromGroup,$DB->escape($userid));
}

/*
*   \def mapPoshGroup2user
*
*   map Poshgroup to user
*
*/
function mapPoshGroup2user (&$datas) {
    global $users_addInGroup;
    $DB = $datas['DB'];
    $DB2 = $datas['DB2'];
    $userid = $datas['userid'];
    $i=0;
    while (isset($datas["group".$i]))
    {
    	$DB->execute($users_addInGroup,
                        $DB->escape($userid),
                        $DB->escape($datas["group".$i])
                    );
    	//launch_hook('admin_set_user_group',$userid,$datas["group".$i]);
    	$i++;
    }
}

/**
* \brief function getGroupsUser
*
*
*
*/
function getPoshGroupsUser (&$datas) {
    $DB = $datas['DB'];
    global $users_getUserGroup;
    $userid = $datas['userid'];
    $groupname = $datas['groupname'];
    $DB->getResults($users_getUserGroup,$DB->escape($userid));
    if ($DB->nbResults() > 0) {
        $groupid = 0;
        while ($row = $DB->fetch(0)) {
                $datas['groups'][$groupname] = $groupid;
        }
    }
    $DB->freeResults();
}

?>
