<?php
defined( '_JEXEC' ) or die( 'Restricted access' );

//ajout greg pour bug iso
header('Content-Type: text/html; charset=utf-8'); 

//include_once(JPATH_COMPONENT.DS.'gmaccess.class.php');
require_once( JApplicationHelper::getPath( 'admin_html' ) );
JTable::addIncludePath(JPATH_COMPONENT.DS.'tables');

$cid = JRequest::getVar( 'cid', array(0), '', 'array' ); 
$id = $cid[0]; 
$aro = JRequest::getVar('aro', 999999);
$axosection = JRequest::getVar('axosection', '');
$axo = JRequest::getVar('axo', 0);

$sectiontype  = JRequest::getVar('sectiontype', 'content');
$redirection  = JRequest::getVar('redirection', 0);

$testuser = & JFactory::getUser();
if (!$testuser->authorize( 'com_gmaccess', 'manage' ) && !$redirection) {
	if ($task != "patchfiles") {
		$mainframe->redirect( 'index.php', JText::_('ALERTNOTAUTH') );
	}
}

switch($task)
{
	case "add":
        editGroup($option, '99999');
       	break;
	case "individuel":
		showUser($option);
		break;
	case 'edit':
		editGroup( $option, $id );
		break;
	
	case 'saveg':
	case 'save':
		saveGroup( $option, $task, $id );
		break;
	case "saveindiv":
        		saveIndiv($option, $task);
       			break;
	case "saveaccess":
        		saveAccess($option, $task, $id);
       			break;
	case 'remove':
	removeGroup( $option );
		break;
	case 'removeaccess':
	removeAccess( $option );
		break;
	case 'cancel':
		cancelGroup();
		break;
	case "canceled":
	case "groupe":
		showGroups( $option ); 
		break;
	case "cancela":
	case 'gmaccess':
		showAccess($option);
		break;
	case 'addaccess':
		editAccess($option, 0);
		break;
	case 'editaccess':
		editAccess($option, $id);
		break;
	case 'front':
		showfront($option, $axosection, $axo);
		break;
	case 'backend':
		showback($option, $aro);
		break;
	case 'redirect2':
	case 'saveback':
		saveback($option, $aro);
		break;
	case 'redirect':
	case 'savefront':
		savefront($option, $axosection, $axo, $redirection, $sectiontype);
		break;
	case 'patchfiles':
		patchfiles();
		break;
	case 'menu':
	default: 
	AccessMenuGM( $option );
		break;  
	
}

function editGroup( $option, $uid )
{
	$db =& JFactory::getDBO(); 
	$row =& JTable::getInstance('gmaccess', 'table'); 

	
	
	if ($uid==0 OR $uid==1) {
		echo "<script> alert('".JText::_( 'GMA_NOEDIT DEF')."'); window.history.go(-1); </script>\n";
		exit();
	}
	if ($uid <> '99999'){
    	$row->load($uid);
	}
	if ($row->access_groupe==2) {
		echo "<script> alert('".JText::_( 'GMA_NOEDIT IND')."'); window.history.go(-1); </script>\n";
        exit();
	}
	//$row->load($id);
	
	$uSelect = array();
    $uNonselect = array(); 
	$membres = "";
	$gSelect = array();
	$gNonselect = array();
	$groupes = "";
	
    // identifie les membres sélectionnés
	$membre_ids = array();
	if ($row->id_groupe){
		$sql = "select id_membre from `#__gm_membre` where id_groupe=$row->id_groupe";
		
		$db->setQuery ($sql);
		$membre_ids = $db->loadResultArray();
		$membres = implode(",", $membre_ids);
	}
    if ($membres) {
        $db->setQuery("SELECT id,name,username " . "\nFROM #__users " . "\nWHERE id IN (" . $membres . ")" . "\nORDER BY name ASC"
            );
        $uInGroupe = $db->loadObjectList();
		
        if (!$db->getErrorNum()) {
            foreach($uInGroupe as $user) {
                $uSelect[] = JHTML::_('select.option',$user->id, $user->id . "-" . $user->name . "(" . $user->username . ")");
            } 
        } 
    } 
	// identifie les groupes sélectionnés
	$groupe_ids = array();
	if ($row->id_groupe){
		$sql = "select id_groupeimbrique from `#__gm_groupeimbrique` where id_groupe=$row->id_groupe";
		
		$db->setQuery ($sql);
		$groupe_ids = $db->loadResultArray();
		$groupes = implode(",", $groupe_ids);
	}
    if ($groupes) {
        $db->setQuery("SELECT id_groupe,nom_groupe " . "\nFROM #__gm_groupe " . "\nWHERE id_groupe IN (" . $groupes . ")" . "\nORDER BY nom_groupe ASC"
            );
		$gInGroupe = $db->loadObjectList();
        if (!$db->getErrorNum()) {
            foreach($gInGroupe as $groupe) {
                $gSelect[] = JHTML::_('select.option',$groupe->id_groupe, $groupe->id_groupe . "-" . $groupe->nom_groupe . "");
            } 
        } 
    } 
	
    // identifie les membres non sélectionnés
    $query = "SELECT id,name,username FROM #__users ";
    if ($membres) {
        $query .= "\nWHERE id NOT IN (" . $membres . ")" ;
    } 
    $query .= "\nORDER BY block, name ASC";
    $db->setQuery($query);
    $uNotInGroupe = $db->loadObjectList();
    foreach($uNotInGroupe as $user) {
        $uNonselect[] = JHTML::_('select.option',$user->id, $user->id . "-" . $user->name . "(" . $user->username . ")");
    } 
	
	if ($uid == '99999'){
    	$groupestotal = array('0','1');
	}else{
	
		$groupestotal = array('0','1',$row->id_groupe);
	}
	if ( !is_array( $groupe_ids ) ) {
		$groupe_ids = array();
	}
	$groupestotal = array_merge($groupestotal,$groupe_ids);
	$groupestotal = array_unique($groupestotal);
	$groupestotal = implode(",",$groupestotal);
	//print $groupestotal;
	 // identifie les groupes non sélectionnés
    $query = "SELECT id_groupe,nom_groupe FROM #__gm_groupe ";
    //if ($groupes) {
        $query .= "\nWHERE id_groupe NOT IN (" . $groupestotal . ")" ;
    //} 
    $query .= "\nORDER BY nom_groupe ASC";
    $db->setQuery($query);
    $gNotInGroupe = $db->loadObjectList();
	if ( is_array( $gNotInGroupe ) && count( $gNotInGroupe ) > 0 ){
		
		foreach($gNotInGroupe as $groupe) {
			$gNonselect[] = JHTML::_('select.option',$groupe->id_groupe, $groupe->id_groupe . "-" . $groupe->nom_groupe . "");
		} 
	} else {
		$gNonselect = array();
	}
    $membresList = JHTML::_('select.genericList', $uSelect, 'users_selected[]',
        'class="inputbox" size="15" onDblClick="moveOptions(document.adminForm[\'users_selected[]\'], document.adminForm.users_not_selected)" multiple="multiple"', 'value', 'text', null);
    $utilisateursList = JHTML::_('select.genericList', $uNonselect,
        'users_not_selected', 'class="inputbox" size="15" onDblClick="moveOptions(document.adminForm.users_not_selected, document.adminForm[\'users_selected[]\'])" multiple="multiple"',
        'value', 'text', null);
		
	$gimbriquesList = JHTML::_('select.genericList', $gSelect, 'groupes_selected[]',
        'class="inputbox" size="15" onDblClick="moveOptions(document.adminForm[\'groupes_selected[]\'], document.adminForm.groupes_not_selected)" multiple="multiple"', 'value', 'text', null);
    $groupesList = JHTML::_('select.genericList', $gNonselect,
        'groupes_not_selected', 'class="inputbox" size="15" onDblClick="moveOptions(document.adminForm.groupes_not_selected, document.adminForm[\'groupes_selected[]\'])" multiple="multiple"',
        'value', 'text', null);
	//passage des arguments
    HTML_gmaccess::editGroup($option, $row, $membresList, $utilisateursList, $gimbriquesList, $groupesList);

}
function editAccess( $option, $uid )
{
	$db =& JFactory::getDBO(); 
	$row =& JTable::getInstance('droitsgmaccess', 'table'); 
	if ($uid) {
		$row->load($uid);
	}

	
   
	
	
	//passage des arguments
    HTML_gmaccess::editAccess($option, $row);

}
function saveGroup( $option, $task, $uid )
{
	
	global $mainframe;
	$db =& JFactory::getDBO(); 
	$row =& JTable::getInstance('gmaccess', 'table');
	//$isNew = ($row->id == '');
	
	if (!$row->bind(JRequest::get('post')))
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
    if (!$row->check()) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    } 
    if (!$row->store()) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    } 
    $row->checkin();
	$membres = JRequest::getVar( 'users_selected', '', 'post', array() );

	
	$db->setQuery ("Delete from #__gm_membre where id_groupe=$row->id_groupe");
	$db->query();
	foreach ($membres as $membre){
		$db->setQuery ("Insert into #__gm_membre (id_groupe, id_membre) values ($row->id_groupe, $membre)");
		$db->query();
	}
	$groupes = JRequest::getVar( 'groupes_selected', '', 'post', array() );

	
	$db->setQuery ("Delete from #__gm_groupeimbrique where id_groupe=$row->id_groupe");
	$db->query();
	foreach ($groupes as $groupe){
		$db->setQuery ("Insert into #__gm_groupeimbrique (id_groupe, id_groupeimbrique) values ($row->id_groupe, $groupe)");
		$db->query();
	}

			$msg = JText::_( 'GMA_GROUP SAVED'); 
			$link = 'index.php?option=' . $option . '&task=groupe'; 
	
	$mainframe->redirect($link, $msg);
    //mosRedirect("index2.php?option=com_gmaccess&section=groups&task=show");
	
}
function saveAccess( $option, $task, $uid )
{
	
	global $mainframe;
	$db =& JFactory::getDBO(); 
	$row =& JTable::getInstance('droitsgmaccess', 'table');
	//$isNew = ($row->id == '');
	
	if (!$row->bind(JRequest::get('post')))
	{
		echo "<script> alert('".$row->getError()."'); window.history.go(-1); </script>\n";
		exit();
	}
	
    if (!$row->check()) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    } 
    if (!$row->store()) {
        echo "<script> alert('" . $row->getError() . "'); window.history.go(-1); </script>\n";
        exit();
    } 
    $row->checkin();
	
			$msg = JText::_( 'GMA_RIGHT SAVED'); 
			$link = 'index.php?option=' . $option . '&task=gmaccess'; 
	
	$mainframe->redirect($link, $msg);
    //mosRedirect("index2.php?option=com_gmaccess&section=groups&task=show");
	
}
function saveIndiv($option, $task)
{
	global $mainframe;
	$cid = JRequest::getVar( 'cid', array(), '', 'array' );
	$db =& JFactory::getDBO(); 

	
    if (!is_array($cid) || count($cid) < 1) {
        echo "<script> alert('".JText::_( 'GMA_SELECT USER')."'); window.history.go(-2);</script>\n";
	
        exit;
		
    } 
    if (count($cid)) {
		foreach ($cid as $aid) {
			// charger les infos utilisateur
			$user =& JUser::getInstance((int)$aid);
			$usernameg = $user->get( 'username' );
			$userid = $user->get( 'id' );
			//$row->load( $aid );
			$db->setQuery( "SELECT id_groupe FROM #__gm_groupe WHERE nom_groupe='$usernameg' AND access_groupe=2" );
			$idgroupe = $db->loadResult();
			if (!$idgroupe) {
				$db->setQuery("DELETE FROM #__gm_groupe WHERE id_groupe=$idgroupe");
				//$db->setQuery("DELETE FROM #__gm_groupe WHERE nom_groupe='$row->username' AND access_groupe=2");
				$db->query();
				$db->setQuery("DELETE FROM #__gm_membre WHERE id_groupe=$idgroupe");
				$db->query();
				$nomgroupe = JText::_( 'GMA_IND GROUP')." ".$user->get( 'name' ). " (".$user->get( 'username' ).")";
				$db->setQuery ("INSERT INTO #__gm_groupe (nom_groupe, description_groupe, access_groupe) values ('$usernameg', '$nomgroupe', 2)");
				$db->query();
				$db->setQuery( "SELECT id_groupe FROM #__gm_groupe WHERE nom_groupe='$usernameg' AND access_groupe=2" );
				$idgroupe = $db->loadResult();
				$db->setQuery ("INSERT INTO #__gm_membre (id_groupe, id_membre) values ($idgroupe, $userid)");
				$db->query();
			}
		}
		$msg =  JText::_( 'GMA_GROUP NAME')." ".count($cid);
	}

	$mainframe->redirect( 'index.php?option=' . $option . '&task=groupe', count($cid). JText::_( 'GMA_GROUP SAVED') );
   
   //$mainframe->redirect('index.php?option=' . $option, $msg);

}
function showGroups( $option ) 
{ 
	global $mainframe;
	
	$db =& JFactory::getDBO(); 
	
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
	
	$query = 'SELECT COUNT(a.id_groupe)'
		. ' FROM #__gm_groupe AS a'
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
	
	$query = "SELECT * FROM #__gm_groupe ORDER BY access_groupe,nom_groupe"; 
	$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	//$db->setQuery( $query ); 
	$rows = $db->loadObjectList(); 

	if ($db->getErrorNum()) { 
		echo $db->stderr(); 
		return false; 
	} 

	HTML_gmaccess::showGroups( $option, $rows, $pageNav ); 
} 

function removeGroup( $option )
{
	global $mainframe;
	$cid = JRequest::getVar( 'cid', array(), '', 'array' );
	
	$db =& JFactory::getDBO();
    if (!is_array($cid) || count($cid) < 1) {
        echo "<script> alert('". JText::_( 'GMA_SELECT GROUP')."'); window.history.go(-1);</script>\n";
        exit;
    } 
    if (count($cid)) {
		foreach ($cid as $aid) {
			// contôle les groupes par défaut
			if ( $aid <= 1 ) {
				echo "<script> alert('". JText::_( 'GMA_NODEL')."'); window.history.go(-1);</script>\n";
       			 exit;
			} 
		}
        $cids = implode(',', $cid); 
        $db->setQuery("DELETE FROM #__gm_membre WHERE id_groupe IN ($cids)");
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        }
		$db->setQuery("DELETE FROM #__gm_groupeimbrique WHERE id_groupe IN ($cids)");
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        }
		$db->setQuery("DELETE FROM #__gm_groupeimbrique WHERE id_groupeimbrique IN ($cids)");
        if (!$db->query()) {
            echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
        }
		$db->setQuery("DELETE FROM #__gm_groupe WHERE id_groupe IN ($cids)");
		if (!$db->query()) {
			echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
		}
    } 
   //mosRedirect("index2.php?option=com_gmaccess&task=groupe");
	
	$mainframe->redirect( 'index.php?option=' . $option . '&task=groupe',  JText::_( 'GMA_DEL GRP') );

}
function removeAccess( $option )
{
	global $mainframe;
	$cid = JRequest::getVar( 'cid', array(), '', 'array' );
	
	$db =& JFactory::getDBO();
    if (!is_array($cid) || count($cid) < 1) {
		echo "<script> alert('". JText::_( 'GMA_SELECT REG')."'); window.history.go(-1);</script>\n";
        exit;
    } 
    if (count($cid)) {
		$cids = implode(',', $cid);
        
		$db->setQuery("DELETE FROM #__gmaccess WHERE id IN ($cids)");
		if (!$db->query()) {
			echo "<script> alert('" . $db->getErrorMsg() . "'); window.history.go(-1); </script>\n";
		}
    } 
   //mosRedirect("index2.php?option=com_gmaccess&task=groupe");
	
	$mainframe->redirect( 'index.php?option=' . $option . '&task=gmaccess',  JText::_( 'GMA_DEL REG') );

}
function cancelGroup()
{
	global $mainframe;

	

	// Initialize variables
	$db =& JFactory::getDBO();
	$row =& JTable::getInstance('gmaccess', 'table');
	$row->bind( JRequest::get( 'post' ));
	$row->checkin();

	$mainframe->redirect('index.php?option=com_gmaccess&task=groupe');
}
function showAccess( $option ) 
{ 
	global $mainframe;
	
	$db =& JFactory::getDBO(); 
	
		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );
		$source = JRequest::getVar('source2', 0);
		$where = '';
		if ($source==1) {
			$where = 'WHERE source = 0';
		} elseif ($source==2) {
			$where = 'WHERE source = 1';
		} elseif ($source==3) {
			$where = 'WHERE source = 2';
		}
		
	
	$query = 'SELECT COUNT(a.id)'
		. ' FROM #__gmaccess AS a '.$where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );
	
	$query = "SELECT * FROM #__gmaccess ".$where." ORDER BY source,id"; 
	$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
	//$db->setQuery( $query ); 
	$rows = $db->loadObjectList(); 
	
	$list = array();
		$list[] = JHTML::_( 'select.option', '0', JText::_( 'All') );
		$list[] = JHTML::_( 'select.option', '1', JText::_( 'GMA_LJOOMLA') );
		$list[] = JHTML::_( 'select.option', '2', JText::_( 'GMA_LSPECIF') );
		$list[] = JHTML::_( 'select.option', '3', JText::_( 'GMA_LURLCOMP') );
		
	
		$filtre_source = JHTML::_( 'select.genericlist', $list, 'source2', 'size="1" class="inputbox" onchange="document.adminForm.submit();"', 'value', 'text', $source);
	
	if ($db->getErrorNum()) { 
		echo $db->stderr(); 
		return false; 
	} 

	HTML_gmaccess::showAccess( $option, $rows, $pageNav, $filtre_source ); 
} 
function showUser($option)  {
	global $mainframe;

		$db				=& JFactory::getDBO();
		$currentUser	=& JFactory::getUser();
		$acl			=& JFactory::getACL();

		$search				= $mainframe->getUserStateFromRequest( "$option.search",			'search', 			'',			'string' );
		$search				= JString::strtolower( $search );

		$limit		= $mainframe->getUserStateFromRequest( 'global.list.limit', 'limit', $mainframe->getCfg('list_limit'), 'int' );
		$limitstart = $mainframe->getUserStateFromRequest( $option.'.limitstart', 'limitstart', 0, 'int' );

		$where = array();
		if (isset( $search ) && $search!= '')
		{
			$searchEscaped = $db->Quote( '%'.$db->getEscaped( $search, true ).'%', false );
			$where[] = 'a.username LIKE '.$searchEscaped.' OR a.email LIKE '.$searchEscaped.' OR a.name LIKE '.$searchEscaped;
		}




		$orderby = ' ORDER BY name ASC';
		$where = ( count( $where ) ? ' WHERE (' . implode( ') AND (', $where ) . ')' : '' );

		$query = 'SELECT COUNT(a.id)'
		. ' FROM #__users AS a'
		. $where
		;
		$db->setQuery( $query );
		$total = $db->loadResult();

		jimport('joomla.html.pagination');
		$pageNav = new JPagination( $total, $limitstart, $limit );

		$query = 'SELECT a.*, g.name AS groupname'
			. ' FROM #__users AS a'
			. ' INNER JOIN #__core_acl_aro AS aro ON aro.value = a.id'
			. ' INNER JOIN #__core_acl_groups_aro_map AS gm ON gm.aro_id = aro.id'
			. ' INNER JOIN #__core_acl_aro_groups AS g ON g.id = gm.group_id'
			. $where
			. ' GROUP BY a.id'
			. $orderby
		;
		$db->setQuery( $query, $pageNav->limitstart, $pageNav->limit );
		$rows = $db->loadObjectList();

	HTML_gmaccess::showUser( $rows, $pageNav, $search, $option );	
	
	
}
function AccessMenuGM( $option )
{
    HTML_gmaccess::AccessMenuGM($option);
}
function About( $option )
{
    HTML_gmaccess::About( $option );
}		
function showfront($option, $axosection, $axo, $redirection=0, $sectiontype='content')
{
    HTML_gmaccess::showfront($option, $axosection, $axo, $redirection, $sectiontype);
}	
function showback($option, $aro)
{
    HTML_gmaccess::showback($option, $aro);
}
function saveback($option, $aro=999999)
{

	global $mainframe;
	
	$db				=& JFactory::getDBO();
	$aro = JRequest::getVar('aro', 999999);
	$aro2 = JRequest::getVar('aro2', 999999);
	$change = JRequest::getVar('change', 0);

	
	if ($change) {
	
			
		$query4 = 'SELECT *' .
				' FROM #__gmaccess' .
				' WHERE source = 0' .
				' ORDER BY id';
			$db->setQuery($query4);
			$droits = $db->loadObjectList(); // component list
		


		if ( is_array( $droits ) && count( $droits ) > 0 ){
			foreach ($droits as $droit) {
					$db->setQuery ("DELETE FROM #__gmacl WHERE acosection='".$droit->acosection."' AND aco='".$droit->aco."' AND aro=$aro AND axosection='".$droit->axosection."' AND axo='".$droit->axo."'" );
					$db->query();
					if ( JRequest::getVar('joom'.$droit->id, '')){ 
							
							$db->setQuery ("INSERT into #__gmacl (acosection, aco, arosection, aro, axosection, axo) values ('".$droit->acosection."', '".$droit->aco."', 'users', $aro, '".$droit->axosection."', '".$droit->axo."')");
							$db->query();
						}
			}
		
		}
		
		// Gestion des Menus Types
		require_once( JPATH_ADMINISTRATOR.DS.'components'.DS.'com_menus'.DS.'helpers'.DS.'helper.php' );
		$menuTypes 	= MenusHelper::getMenuTypelist();
		
		if (count($menuTypes)) {
			foreach ($menuTypes as $menuType) {
				$db->setQuery ("DELETE FROM #__gmacl WHERE acosection='com_menus' AND aco='edit' AND aro=$aro AND axosection='menu' AND axo='".$menuType->menutype."'" );
					$db->query();
					if ( JRequest::getVar('menu'.$menuType->id, '')){ 
							
							$db->setQuery ("INSERT into #__gmacl (acosection, aco, arosection, aro, axosection, axo) values ('com_menus', 'edit', 'users', $aro, 'menu', '".$menuType->menutype."')");
							$db->query();
						}
			
			}
		
		}
		
//composants
		$query = 'SELECT *' .
				' FROM #__components' .
				' WHERE '.$db->NameQuote( 'option' ).' <> "com_frontpage"' .
				' AND '.$db->NameQuote( 'option' ).' <> "com_media"' .
				' AND enabled = 1' .
				' ORDER BY ordering, name';
			$db->setQuery($query);
			$comps = $db->loadObjectList(); // component list
			$subs = array(); // sub menus

			// first pass to collect sub-menu items
			foreach ($comps as $comp)
			{
				if ($comp->parent)
				{
					if (!array_key_exists($comp->parent, $subs)) {
						$subs[$comp->parent] = array ();
					}
					$subs[$comp->parent][] = $comp;
				}
			}
			if ( is_array( $comps ) && count( $comps ) > 0 ){
				foreach ($comps as $comp) {
					if ($comp->parent == 0 && (trim($comp->admin_menu_link) || array_key_exists($comp->id, $subs))) {
						$db->setQuery ("DELETE FROM #__gmacl WHERE acosection='".$comp->option."' AND aco='manage' AND aro=$aro AND axosection='' AND axo=''" );
					$db->query();
						$compo = str_replace("com_", "", $comp->option);
						if ( JRequest::getVar('manage'.$compo, '')){ 
							
							$db->setQuery ("INSERT into #__gmacl (acosection, aco, arosection, aro, axosection, axo) values ('".$comp->option."', 'manage', 'users', $aro,'' ,'' )");
							$db->query();
						}
					}
				}
			}
			
			
		$query3 = 'SELECT *' .
				' FROM #__gmaccess' .
				' WHERE source = 1' .
				' ORDER BY id';
			$db->setQuery($query3);
			$droits = $db->loadObjectList(); // component list
		


		if ( is_array( $droits ) && count( $droits ) > 0 ){
			foreach ($droits as $droit) {
					$db->setQuery ("DELETE FROM #__gmacl WHERE acosection='".$droit->acosection."' AND aco='".$droit->aco."' AND aro=$aro AND axosection='".$droit->axosection."' AND axo='".$droit->axo."'" );
					$db->query();
					if ( JRequest::getVar('spec'.$droit->id, '')){ 
							
							$db->setQuery ("INSERT into #__gmacl (acosection, aco, arosection, aro, axosection, axo) values ('".$droit->acosection."', '".$droit->aco."', 'users', $aro, '".$droit->axosection."', '".$droit->axo."')");
							$db->query();
						}
			}
		
		}
			
	}
	$task = JRequest::getVar('task', '');
	if ($task=='redirect2') {
		$mainframe->redirect('index.php?option=com_gmaccess');
		//mosRedirect("index2.php?option=com_gmaccess");
	}else{
		$mainframe->redirect('index.php?option=com_gmaccess&task=backend&aro='.$aro2);
		//mosRedirect("index2.php?option=com_gmaccess&task=backend&aro=".$aro2);
	 }
}

function savefront($option, $axosection, $axo, $redirection=0, $sectiontype='content')
{

	global $mainframe;
	
	$db				=& JFactory::getDBO();

	$redirection  = JRequest::getVar('redirection', 0);
	$axosection2  = JRequest::getVar('axosection2', '');
	$axo2  = JRequest::getVar('axo2', 0);
	$axosection  = JRequest::getVar('axosection', '');
	$sectiontype  = JRequest::getVar('sectiontype', 'content');
	$axo  = JRequest::getVar('axo', 0);
	$access = JRequest::getVar('access', 0);
	$change = JRequest::getVar('change', 0);
	
if ($change) {
	switch ( $axosection ) {
		case 'item':
			if ($axo) {
				$db->setQuery ("Update #__content set access=$access where id=$axo");
				$db->query();
				$row =& JTable::getInstance('content');
				// load the row from the db table
				$row->load( $axo );
				
				fonctionGmaccess::savegmaccess( $row, 'item' );
				}
			break;

		case 'category':
			if ($axo) {
				$db->setQuery ("Update #__categories set access=$access where id=$axo");
				$db->query();
				$row =& JTable::getInstance('category');
				// load the row from the db table
				$row->load( $axo );
				fonctionGmaccess::savegmaccess( $row, 'category' );
				}
			break;
		case 'section':
			if ($axo) {
				$db->setQuery ("Update #__sections set access=$access where id=$axo");
				$db->query();
				$row =& JTable::getInstance('section');
				// load the row from the db table
				$row->load( $axo );
				
				fonctionGmaccess::savegmaccess( $row, 'section' );
				}
			break;
		case 'module':
			if ($axo) {
				$db->setQuery ("Update #__modules set access=$access where id=$axo");
				$db->query();
				$row =& JTable::getInstance('module');
				// load the row from the db table
				$row->load( $axo );
				
				fonctionGmaccess::savegmaccess( $row, 'module' );
				}
			break;
		case 'menu':
			if ($axo) {
				$db->setQuery ("Update #__menu set access=$access where id=$axo");
				$db->query();
				$row =& JTable::getInstance('menu');
				// load the row from the db table
				$row->load( $axo );
				
				fonctionGmaccess::savegmaccess( $row, 'menu' );
				}
			break;
		case 'plugin':
			if ($axo) {
				$db->setQuery ("Update #__plugins set access=$access where id=$axo");
				$db->query();
				$row =& JTable::getInstance('plugin');
				// load the row from the db table
				$row->load( $axo );
				
				fonctionGmaccess::savegmaccess( $row, 'plugin' );
				}
			break;
		case 'content':
			
				
				fonctionGmaccess::savegmaccess2( 'content' );
				
			break;
		case 'component':
			if ($axo) {
				
				$row =& JTable::getInstance('component');
				// load the row from the db table
				$row->load( $axo );
				
				
				fonctionGmaccess::savegmaccesscomponent( $row );
				}
			break;
		case 'componenturl':
			if ($axo) {
				
				$query = "SELECT * FROM #__gmaccess WHERE id = ".$axo; 
				$db->setQuery( $query);
	
				$row = $db->loadObject(); 
				
				fonctionGmaccess::savegmaccesscomponenturl( $row );
				}
			break;
		case 'contact':
			if ($axo) {
				$db->setQuery ("Update #__contact_details set access=$access where id=$axo");
				$db->query();
				$query = "SELECT * FROM #__contact_details WHERE id = ".$axo; 
				$db->setQuery( $query);
	
				$row = $db->loadObject(); 
				
				
				fonctionGmaccess::savegmaccess( $row, 'contact' );
				}
			break;
		default:
			
			break;
	}
}
$task = JRequest::getVar('task', '');
if ($redirection) {
	//redirectgma($axosection, $axo, $sectiontype);
	switch ( $axosection ) {
		case 'category':
			$mainframe->redirect('index3.php?option=com_gmaccess&task=front&axosection='.$axosection.'&axo='.$axo.'&redirection=1&sectiontype='. $sectiontype);
			break;
		default:
			$mainframe->redirect('index3.php?option=com_gmaccess&task=front&axosection='.$axosection.'&axo='.$axo.'&redirection=1');			
			break;
	}
}elseif ($task=='redirect') {
	$mainframe->redirect('index.php?option=com_gmaccess');

}else{
	$mainframe->redirect('index.php?option=com_gmaccess&task=front&axosection='.$axosection2.'&axo='.$axo2);
 }
}

function redirectgma($axosection, $axo, $sectiontype) {
	global $database, $mainframe;
	switch ( $axosection ) {
		case 'item':
			$row =& JTable::getInstance('content');
			
				// load the row from the db table
				$row->load( $axo );
			if ($row->sectionid==0) {
				$mainframe->redirect( 'index.php?option=com_typedcontent');
			}else{
				$mainframe->redirect( 'index.php?option=com_content');
			}
			break;

		case 'category':
			$mainframe->redirect( 'index.php?option=com_categories&section='.$sectiontype.'');
			break;
		case 'section':
			$mainframe->redirect( 'index.php?option=com_sections&scope=content');
				
			break;
		case 'module':
			$mainframe->redirect( 'index.php?option=com_modules');
				
			break;
		case 'menu':
			$row =& JTable::getInstance('menu');
				// load the row from the db table
				$row->load( $axo );
			$mainframe->redirect( 'index.php?option=com_menus&menutype='.$row->menutype);
			break;
		case 'plugin':
			$mainframe->redirect( 'index2php?option=com_mambots');
			break;
		default:
			
			break;
	}
	
}
function patchfiles() {
	global $mainframe;
	
	jimport('joomla.filesystem.folder');
	jimport('joomla.filesystem.file');	
	
	if (JFolder::exists(JPATH_SITE.DS."administrator/components/com_gmaccess/patch")){
			$patchtemplates = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/templates", JPATH_SITE.DS."templates", JPATH_SITE.DS."administrator/gmbackup/templates" );
			$patchadministrator = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/administrator", JPATH_SITE.DS."administrator", JPATH_SITE.DS."administrator/gmbackup/administrator" );
			$patchcomponents = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/components", JPATH_SITE.DS."components", JPATH_SITE.DS."administrator/gmbackup/components" );
			$patchlanguage = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/language", JPATH_SITE.DS."language", JPATH_SITE.DS."administrator/gmbackup/language" );
			$patchlibraries = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/libraries", JPATH_SITE.DS."libraries", JPATH_SITE.DS."administrator/gmbackup/libraries" );
			$patchmodules = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/modules", JPATH_SITE.DS."modules", JPATH_SITE.DS."administrator/gmbackup/modules" );
			$patchplugins = patch(JPATH_SITE.DS."administrator/components/com_gmaccess/patch/plugins", JPATH_SITE.DS."plugins", JPATH_SITE.DS."administrator/gmbackup/plugins" );
		}
	
	$result = $mainframe->logout();

	if (!JError::isError($result)) {
			$msg = JText::_( 'GMA_SUCESS' );
			$mainframe->redirect('index.php?option=com_login', $msg);
	}

}
function patch($src, $dest, $back, $path = '', $force = false)
	{
		// Initialize variables
		jimport('joomla.client.helper');
		$FTPOptions = JClientHelper::getCredentials('ftp');

		if ($path) {
			$src = JPath::clean($path.DS.$src);
			$dest = JPath::clean($path.DS.$dest);
			$back = JPath::clean($path.DS.$back);
		}

		// Eliminate trailing directory separators, if any
		$src = rtrim($src, DS);
		$dest = rtrim($dest, DS);
		$back = rtrim($back, DS);

		if (!JFolder::exists($src)) {
			return JError::raiseError(-1, JText::_('Cannot find source folder'));
		}
		/*if (JFolder::exists($dest) && !$force) {
			return JError::raiseError(-1, JText::_('Folder already exists'));
		}

		// Make sure the destination exists
		if (! JFolder::create($dest)) {
			return JError::raiseError(-1, JText::_('Unable to create target folder'));
		}*/

		if ($FTPOptions['enabled'] == 1)
		{
			// Connect the FTP client
			jimport('joomla.client.ftp');
			$ftp = & JFTP::getInstance($FTPOptions['host'], $FTPOptions['port'], null, $FTPOptions['user'], $FTPOptions['pass']);

			if(! ($dh = @opendir($src))) {
				return JError::raiseError(-1, JText::_('Unable to open source folder'));
			}
			// Walk through the directory copying files and recursing into folders.
			while (($file = readdir($dh)) !== false) {
				$sfid = $src . DS . $file;
				$dfid = $dest . DS . $file;
				$bfid = $back.DS.$file;
				switch (filetype($sfid)) {
					case 'dir':
						if ($file != '.' && $file != '..') {
							if (! JFolder::create($bfid)) {
								return JError::raiseError(-1, JText::_('Unable to create target folder'));
							}
							$ret = patch($sfid, $dfid, $bfid, null, $force);
							if ($ret !== true) {
								return $ret;
							}
						}
						break;

					case 'file':
						$bfid = JPath::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $bfid), '/');
						if (! $ftp->store($dfid, $bfid)) {
							return JError::raiseError(-1, JText::_('Copy failed'));
						}
						//Translate path for the FTP account
						$dfid = JPath::clean(str_replace(JPATH_ROOT, $FTPOptions['root'], $dfid), '/');
						if (! $ftp->store($sfid, $dfid)) {
							return JError::raiseError(-1, JText::_('Copy failed'));
						}
						break;
				}
			}
		} else {
			if(! ($dh = @opendir($src))) {
				return JError::raiseError(-1, JText::_('Unable to open source folder'));
			}
			// Walk through the directory copying files and recursing into folders.
			while (($file = readdir($dh)) !== false) {
				$sfid = $src.DS.$file;
				$dfid = $dest.DS.$file;
				$bfid = $back.DS.$file;
				switch (filetype($sfid)) {
					case 'dir':
						if ($file != '.' && $file != '..') {
							if (! JFolder::create($bfid)) {
								return JError::raiseError(-1, JText::_('Unable to create target folder'));
							}
							$ret = patch($sfid, $dfid, $bfid, null, $force);
							if ($ret !== true) {
								return $ret;
							}
						}
						break;

					case 'file':
						if (!@ copy($dfid, $bfid)) {
							return JError::raiseError(-1, JText::_('Copy failed'));
						}
						if (!@ copy($sfid, $dfid)) {
							return JError::raiseError(-1, JText::_('Copy failed'));
						}
						break;
				}
			}
		}
		return true;
	}


?>