<?php
/* Copyright (C) 2017  Laurent Destailleur <eldy@users.sourceforge.net>
 * 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        class/vehicle.class.php
 * \ingroup     fleetmanagment
 * \brief       This file is a CRUD class file for FleetManagment (Create/Read/Update/Delete)
 */

// Put here all includes required by your class file
require_once DOL_DOCUMENT_ROOT . '/core/class/commonobject.class.php';
//require_once DOL_DOCUMENT_ROOT . '/societe/class/societe.class.php';
//require_once DOL_DOCUMENT_ROOT . '/product/class/product.class.php';
dol_include_once('/fleetmanagment/lib/fleetmanagment.lib.php');

/**
 * Class for FleetManagment
 */
class Vehicle extends CommonObject
{
    /**
     * @var string ID of module.
     */
    public $module = 'fleetmanagment';

    /**
     * @var string ID to identify managed object.
     */
    public $element = 'vehicle';

    /**
     * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management.
     */
    public $table_element = 'fleetmanagment_vehicle';

    /**
     * @var int  Does this object support multicompany module ?
     * 0=No test on entity, 1=Test with field entity, 'field@table'=Test with link by field@table
     */
    public $ismultientitymanaged = 1;

    /**
     * @var int  Does object support extrafields ? 0=No, 1=Yes
     */
    public $isextrafieldmanaged = 1;

    /**
     * @var string String with name of icon for fleetmanagment. Must be the part after the 'object_' into object_fleetmanagment.png
     */
    public $picto = 'vehicle@fleetmanagment';


    const STATUS_LIBRE = 0;
    const STATUS_RESERVE = 1;
    const STATUS_TRANSIT = 2;
    const STATUS_PARC = 3;
    const STATUS_SELL = 4;
    const STATUS_MAINTENANCE = 9;


    /**
     *  'type' field format ('integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]', 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:Sortfield]]]]', 'varchar(x)', 'double(24,8)', 'real', 'price', 'text', 'text:none', 'html', 'date', 'datetime', 'timestamp', 'duration', 'mail', 'phone', 'url', 'password')
     *         Note: Filter can be a string like "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.nature:is:NULL)"
     *  'label' the translation key.
     *  'picto' is code of a picto to show before value in forms
     *  'enabled' is a condition when the field must be managed (Example: 1 or '$conf->global->MY_SETUP_PARAM)
     *  'position' is the sort order of field.
     *  'notnull' is set to 1 if not null in database. Set to -1 if we must set data to null if empty ('' or 0).
     *  'visible' says if field is visible in list (Examples: 0=Not visible, 1=Visible on list and create/update/view forms, 2=Visible on list only, 3=Visible on create/update/view form only (not list), 4=Visible on list and update/view form only (not create). 5=Visible on list and view only (not create/not update). Using a negative value means field is not shown by default on list but can be selected for viewing)
     *  'noteditable' says if field is not editable (1 or 0)
     *  'default' is a default value for creation (can still be overwrote by the Setup of Default Values if field is editable in creation form). Note: If default is set to '(PROV)' and field is 'ref', the default value will be set to '(PROVid)' where id is rowid when a new record is created.
     *  'index' if we want an index in database.
     *  'foreignkey'=>'tablename.field' if the field is a foreign key (it is recommanded to name the field fk_...).
     *  'searchall' is 1 if we want to search in this field when making a search from the quick search button.
     *  'isameasure' must be set to 1 or 2 if field can be used for measure. Field type must be summable like integer or double(24,8). Use 1 in most cases, or 2 if you don't want to see the column total into list (for example for percentage)
     *  'css' and 'cssview' and 'csslist' is the CSS style to use on field. 'css' is used in creation and update. 'cssview' is used in view mode. 'csslist' is used for columns in lists. For example: 'css'=>'minwidth300 maxwidth500 widthcentpercentminusx', 'cssview'=>'wordbreak', 'csslist'=>'tdoverflowmax200'
     *  'help' is a 'TranslationString' to use to show a tooltip on field. You can also use 'TranslationString:keyfortooltiponlick' for a tooltip on click.
     *  'showoncombobox' if value of the field must be visible into the label of the combobox that list record
     *  'disabled' is 1 if we want to have the field locked by a 'disabled' attribute. In most cases, this is never set into the definition of $fields into class, but is set dynamically by some part of code.
     *  'arrayofkeyval' to set a list of values if type is a list of predefined values. For example: array("0"=>"Draft","1"=>"Active","-1"=>"Cancel"). Note that type can be 'integer' or 'varchar'
     *  'autofocusoncreate' to have field having the focus on a create form. Only 1 field should have this property set to 1.
     *  'comment' is not used. You can store here any text of your choice. It is not used by application.
     *  'validate' is 1 if need to validate with $this->validateField()
     *  'copytoclipboard' is 1 or 2 to allow to add a picto to copy value into clipboard (1=picto after label, 2=picto after value)
     *
     *  Note: To have value dynamic, you can set value to 0 in definition and edit the value on the fly into the constructor.
     */

    // BEGIN MODULEBUILDER PROPERTIES
	/**
	 * @var array  Array with all fields and their property. Do not use it as a static var. It may be modified by constructor.
	 */
	public $fields=array(
		'rowid' => array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>'1', 'position'=>1, 'notnull'=>1, 'visible'=>0, 'noteditable'=>'1', 'index'=>1, 'css'=>'left', 'comment'=>"Id"),
		'ref' => array('type'=>'varchar(128)', 'label'=>'Ref', 'enabled'=>'1', 'position'=>5, 'notnull'=>1, 'visible'=>4, 'noteditable'=>'1', 'index'=>1, 'searchall'=>1, 'showoncombobox'=>'1', 'comment'=>"Reference of object"),
		'label' => array('type'=>'varchar(255)', 'label'=>'Label', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>0, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
		'num_serie' => array('type'=>'varchar(255)', 'label'=>'NumSerie', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
		'power' => array('type'=>'double(24,8)', 'label'=>'Power', 'enabled'=>'1', 'position'=>31, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
		'power_dyn' => array('type'=>'double(24,8)', 'label'=>'PowerDyn', 'enabled'=>'1', 'position'=>31, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
		'kilometrage' => array('type'=>'double(24,8)', 'label'=>'kilometrage', 'enabled'=>'1', 'position'=>31, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
		'engine_size' => array('type'=>'double(24,8)', 'label'=>'EngineSize', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1, 'searchall'=>1, 'css'=>'minwidth300', 'cssview'=>'wordbreak', 'showoncombobox'=>'2',),
		'fk_soc_buy' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__) AND client = 1', 'label'=>'ThirdPartyBuy', 'enabled'=>'1', 'position'=>34, 'notnull'=>-1, 'visible'=>1, 'index'=>1,),
		'fk_soc_sell' => array('type'=>'integer:Societe:societe/class/societe.class.php:1:status=1 AND entity IN (__SHARED_ENTITIES__) AND fournisseur = 1', 'label'=>'ThirdPartySell', 'enabled'=>'1', 'position'=>36, 'notnull'=>-1, 'visible'=>1, 'index'=>1,),
		'imatriculation' => array('type'=>'varchar(255)', 'label'=>'Immatriculation', 'enabled'=>'1', 'position'=>19, 'notnull'=>1, 'visible'=>1, 'index'=>1, 'searchall'=>1, 'cssview'=>'wordbreak', 'help'=>"ImatriculationHelpText",),
		'modele' => array('type'=>'sellist:c_fleetmanagment_vehicle_modele:label:rowid::active=1', 'label'=>'ModeleVehicle', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1,),
		'marque' => array('type'=>'sellist:c_fleetmanagment_vehicle_marque:label:rowid::active=1', 'label'=>'Marque', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>1,),
		'carburant' => array('type'=>'sellist:c_fleetmanagment_vehicle_carburant:label:rowid::active=1', 'label'=>'Carburant', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>0,),
		'type' => array('type'=>'sellist:c_fleetmanagment_vehicle_type:label:rowid::active=1', 'label'=>'Type', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>0,),
		'buy_price' => array('type'=>'price', 'label'=>'buy_price', 'enabled'=>'1', 'position'=>35, 'notnull'=>0, 'visible'=>-1,),
		'sell_price' => array('type'=>'price', 'label'=>'sell_price', 'enabled'=>'1', 'position'=>37, 'notnull'=>0, 'visible'=>-1,),
		'nbPlaces' => array('type'=>'integer', 'label'=>'nbPlaces', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'CO2_emission' => array('type'=>'integer', 'label'=>'CO2Emission', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'poids_a_vide' => array('type'=>'integer', 'label'=>'poidsAVide', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'poids_net' => array('type'=>'integer', 'label'=>'poidsNet', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'boite_de_vitesses' => array('type'=>'varchar(255)', 'label'=>'BoiteDeVitesses', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'taille_pneu_avant' => array('type'=>'varchar(255)', 'label'=>'taillePneuAvant', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'taille_pneu_arriere' => array('type'=>'varchar(255)', 'label'=>'taillePneuArriere', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'hybride' => array('type'=>'varchar(255)', 'label'=>'Hybride', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'categorie_hybride' => array('type'=>'varchar(255)', 'label'=>'categorieHybride', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'garantie_constructeur' => array('type'=>'varchar(255)', 'label'=>'garantieConstructeur', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'carrosserie_couleur' => array('type'=>'varchar(255)', 'label'=>'carrosserieCouleur', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'cnit' => array('type'=>'varchar(255)', 'label'=>'CNIT', 'enabled'=>'1', 'position'=>38, 'notnull'=>0, 'visible'=>-1,),
		'publish' => array('type'=>'integer', 'label'=>'Publish', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>0,),
		'publish_date' => array('type'=>'timestamp', 'label'=>'PublishDate', 'enabled'=>'1', 'position'=>30, 'notnull'=>0, 'visible'=>0,),
		'description' => array('type'=>'text', 'label'=>'Description', 'enabled'=>'1', 'position'=>60, 'notnull'=>0, 'visible'=>3,),
		'note_public' => array('type'=>'html', 'label'=>'NotePublic', 'enabled'=>'1', 'position'=>61, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak',),
		'note_private' => array('type'=>'html', 'label'=>'NotePrivate', 'enabled'=>'1', 'position'=>62, 'notnull'=>0, 'visible'=>0, 'cssview'=>'wordbreak',),
		'first_inscription' => array('type'=>'date', 'label'=>'FirstInscription', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>-1,),
		'next_ct_periodique' => array('type'=>'date', 'label'=>'NextCtPeriodique', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>-1,),
		'date_desinscription' => array('type'=>'date', 'label'=>'DateDesinscription', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>-1,),
		'date_enregistrement' => array('type'=>'date', 'label'=>'DateEnregistrement', 'enabled'=>'1', 'position'=>70, 'notnull'=>0, 'visible'=>-1,),
		'date_creation' => array('type'=>'datetime', 'label'=>'DateCreation', 'enabled'=>'1', 'position'=>500, 'notnull'=>1, 'visible'=>-2,),
		'tms' => array('type'=>'timestamp', 'label'=>'DateModification', 'enabled'=>'1', 'position'=>501, 'notnull'=>0, 'visible'=>-2,),
		'fk_user_creat' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserAuthor', 'enabled'=>'1', 'position'=>510, 'notnull'=>1, 'visible'=>-2, 'foreignkey'=>'user.rowid',),
		'fk_user_modif' => array('type'=>'integer:User:user/class/user.class.php', 'label'=>'UserModif', 'enabled'=>'1', 'position'=>511, 'notnull'=>-1, 'visible'=>-2,),
		'fk_order' => array('type'=>'varchar(14)', 'label'=>'fk_Order', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
		'fk_order_fourn' => array('type'=>'varchar(14)', 'label'=>'fk_Order_Fourn', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
		'import_key' => array('type'=>'varchar(14)', 'label'=>'ImportId', 'enabled'=>'1', 'position'=>1000, 'notnull'=>-1, 'visible'=>-2,),
		'status' => array('type'=>'integer', 'label'=>'Status', 'enabled'=>'1', 'position'=>1000, 'notnull'=>1, 'visible'=>6, 'index'=>1,),
		'entity' => array('type'=>'integer', 'label'=>'Entity', 'enabled'=>'1', 'position'=>20, 'notnull'=>1, 'visible'=>0, 'default'=>'1', 'index'=>1,),
	);
	public $rowid;
	public $ref;
	public $label;
	public $num_serie;
	public $power;
	public $power_dyn;
	public $kilometrage;
	public $engine_size;
	public $fk_soc_buy;
	public $fk_soc_sell;
	public $imatriculation;
	public $modele;
	public $marque;
	public $carburant;
	public $type;
	public $buy_price;
	public $sell_price;
	public $nbPlaces;
	public $CO2_emission;
	public $poids_a_vide;
	public $poids_net;
	public $boite_de_vitesses;
	public $taille_pneu_avant;
	public $taille_pneu_arriere;
	public $hybride;
	public $categorie_hybride;
	public $garantie_constructeur;
	public $carrosserie_couleur;
	public $cnit;
	public $publish;
	public $publish_date;
	public $description;
	public $note_public;
	public $note_private;
	public $first_inscription;
	public $next_ct_periodique;
	public $date_desinscription;
	public $date_enregistrement;
	public $date_creation;
	public $tms;
	public $fk_user_creat;
	public $fk_user_modif;
	public $fk_order;
	public $fk_order_fourn;
	public $import_key;
	public $status;
	public $entity;
	// END MODULEBUILDER PROPERTIES


    // If this object has a subtable with lines


    /**
     * Constructor
     *
     * @param DoliDb $db Database handler
     */
    public function __construct(DoliDB $db)
    {
        global $conf, $langs, $mysoc;
        $this->db = $db;

        if (empty($conf->global->MAIN_SHOW_TECHNICAL_ID) && isset($this->fields['rowid'])) {
            $this->fields['rowid']['visible'] = 0;
        }
        if (empty($conf->multicompany->enabled) && isset($this->fields['entity'])) {
            $this->fields['entity']['enabled'] = 0;
        }

        switch ($conf->global->FLEETMANAGMENT_ADDON_ID) {
            case "yye7Cz2BPhSeJs2ouy4xUw9vw48zmQ6xs86H8jkPyJ983rSM8ZaaYFfuR9ohvPGr":
                if (isset($this->fields['carburant'])) {
                    $this->fields['carburant']['visible'] = 0;
                }
                if (isset($this->fields['type'])) {
                    $this->fields['type']['visible'] = 0;
                }
                if (isset($this->fields['fk_soc_sell'])){
                    $this->fields['fk_soc_sell']['visible'] = 1;
                }
                if (isset($this->fields['fk_soc_buy'])){
                    $this->fields['fk_soc_buy']['visible'] = 1;
                }
                break;
            case "6TbSsDo8un9z5Sx9JhJca6zys5aggCCngHt69mmkY3KBSSUfciRkVoUgVEaZVvEgziYEavmYhnUn4Ft":
                if (isset($this->fields['buy_price'])) {
                    $this->fields['buy_price']['visible'] = 0;
                }
                if (isset($this->fields['sell_price'])) {
                    $this->fields['sell_price']['visible'] = 0;
                }
                if (isset($this->fields['fk_soc_buy'])) {
                    $this->fields['fk_soc_buy']['visible'] = 0;
                }
                if (isset($this->fields['fk_soc_sell'])) {
                    $this->fields['fk_soc_sell']['visible'] = 0;
                }
                break;
        }

        // Unset fields that are disabled
        foreach ($this->fields as $key => $val) {
            if (isset($val['enabled']) && empty($val['enabled'])) {
                unset($this->fields[$key]);
            }
        }

        // Translate some data of arrayofkeyval
        if (is_object($langs)) {
            foreach ($this->fields as $key => $val) {
                if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) {
                    foreach ($val['arrayofkeyval'] as $key2 => $val2) {
                        $this->fields[$key]['arrayofkeyval'][$key2] = $langs->trans($val2);
                    }
                }
            }
        }
    }

    /**
     * Create object into database
     *
     * @param User $user User that creates
     * @param bool $notrigger false=launch triggers after, true=disable triggers
     * @return int             <0 if KO, Id of created object if OK
     */
    public function create(User $user, $notrigger = false)
    {
        global $langs, $conf, $soc;
        $this->date_creation = dol_now();
        $resultcreate = $this->createCommon($user, $notrigger);
        if (empty($this->ref) && $resultcreate > 0) {
            $this->fk_user_creat = $user->id;
            switch ($conf->global->FLEETMANAGMENT_ADDON_ID) {
                case "yye7Cz2BPhSeJs2ouy4xUw9vw48zmQ6xs86H8jkPyJ983rSM8ZaaYFfuR9ohvPGr":
                    if ($conf->multicompany->enabled) {
                        $this->ref = $conf->global->MAIN_INFO_SOCIETE_NOM[0] . "-" . $this->getNextNumMultiRef();
                    }
                    break;
                default :
                    $this->ref = "VEH-" . str_pad($resultcreate, 8 - (strlen(strval($resultcreate))), 0, STR_PAD_LEFT);
            }
            $resultcreate = $this->updateCommon($user);
            $this->add_notification_auto($user, $langs->trans("EVENTVEHICULECreate", $this->ref));
            return $resultcreate;
        }
        return $resultcreate;
    }

    /**
     * Clone an object into another one
     *
     * @param User $user User that creates
     * @param int $fromid Id of object to clone
     * @return    mixed                New object created, <0 if KO
     */
    public function createFromClone(User $user, $fromid)
    {
        global $langs, $extrafields, $conf;
        $error = 0;

        dol_syslog(__METHOD__, LOG_DEBUG);

        $object = new self($this->db);

        $this->db->begin();

        // Load source object
        $result = $object->fetchCommon($fromid);
        if ($result > 0 && !empty($object->table_element_line)) {
            $object->fetchLines();
        }

        // get lines so they will be clone
        //foreach($this->lines as $line)
        //	$line->fetch_optionals();

        // Reset some properties
        unset($object->id);
        unset($object->fk_user_creat);
        unset($object->import_key);

        // Clear fields
        if (property_exists($object, 'ref')) {
            $object->ref = empty($this->fields['ref']['default']) ? "copy_of_" . $object->ref : $this->fields['ref']['default'];
        }
        if (property_exists($object, 'label')) {
            $object->label = empty($this->fields['label']['default']) ? $langs->trans("CopyOf") . " " . $object->label : $this->fields['label']['default'];
        }
        if (property_exists($object, 'status')) {
            $object->status = self::STATUS_LIBRE;
        }
        if (property_exists($object, 'date_creation')) {
            $object->date_creation = dol_now();
        }
        if (property_exists($object, 'date_modification')) {
            $object->date_modification = null;
        }

        // Clear extrafields that are unique
        if (is_array($object->array_options) && count($object->array_options) > 0) {
            $extrafields->fetch_name_optionals_label($this->table_element);
            foreach ($object->array_options as $key => $option) {
                $shortkey = preg_replace('/options_/', '', $key);
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
                    //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
                    unset($object->array_options[$key]);
                }
            }
        }

        // Create clone
        $object->context['createfromclone'] = 'createfromclone';
        $result = $object->createCommon($user);
        if ($result < 0) {
            $error++;
            $this->error = $object->error;
            $this->errors = $object->errors;
        }

        if (!$error) {
            // copy internal contacts
            if ($this->copy_linked_contact($object, 'internal') < 0) {
                $error++;
            }
        }

        if (!$error) {
            // copy external contacts if same company
            if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
                if ($this->copy_linked_contact($object, 'external') < 0) {
                    $error++;
                }
            }
        }

        unset($object->context['createfromclone']);

        // End
        if (!$error) {
            $this->db->commit();
            return $object;
        } else {
            $this->db->rollback();
            return -1;
        }
    }

    /**
     * Clone an object into another one
     *
     * @param User $user User that creates
     * @param int $fromid Id of object to clone
     * @return    mixed                New object created, <0 if KO
     */
    public function createFromCloneEntity(User $user, $fromid, vehicle $currentObject, $soc_id = null, $fk_commande = null)
    {
        global $langs, $extrafields, $conf;
        $error = 0;
        require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';

        dol_syslog(__METHOD__, LOG_DEBUG);

        $object = new self($this->db);

        $this->db->begin();

        // Load source object
        $result = $object->fetchCommon($fromid);
        if ($result > 0 && !empty($object->table_element_line)) {
            $object->fetchLines();
        }

        // get lines so they will be clone
        //foreach($this->lines as $line)
        //	$line->fetch_optionals();

        // Reset some properties
        unset($object->id);
        unset($object->fk_user_creat);
        unset($object->import_key);

        // Clear fields
        if (property_exists($object, 'ref')) {
            $object->ref = !empty($object->ref) ? $object->ref : "";
        }
        if (property_exists($object, 'label')) {
            $object->label = !empty($object->label) ? $object->label : "";
        }
        if (property_exists($object, 'status')) {
            $object->status = self::STATUS_LIBRE;
        }
        if (property_exists($object, 'date_creation')) {
            $object->date_creation = dol_now();
        }
        if (property_exists($object, 'date_modification')) {
            $object->date_modification = null;
        }
        $object->entity = $conf->entity;
        // Clear extrafields that are unique
        if (is_array($object->array_options) && count($object->array_options) > 0) {
            $extrafields->fetch_name_optionals_label($this->table_element);
            foreach ($object->array_options as $key => $option) {
                $shortkey = preg_replace('/options_/', '', $key);
                if (!empty($extrafields->attributes[$this->table_element]['unique'][$shortkey])) {
                    //var_dump($key); var_dump($clonedObj->array_options[$key]); exit;
                    unset($object->array_options[$key]);
                }
            }
        }

        // Create clone
        $object->context['createfromclone'] = 'createfromclone';
        $result = $object->createCommon($user);
        if ($result < 0) {
            $error++;
            $this->error = $object->error;
            $this->errors = $object->errors;
        }

        if (!$error) {
            // copy internal contacts
            if ($this->copy_linked_contact($object, 'internal') < 0) {
                $error++;
            }
        }

        if (!$error) {
            // copy external contacts if same company
            if (!empty($object->socid) && property_exists($this, 'fk_soc') && $this->fk_soc == $object->socid) {
                if ($this->copy_linked_contact($object, 'external') < 0) {
                    $error++;
                }
            }
        }

        unset($object->context['createfromclone']);
        if (!empty($currentObject->sell_price) && $currentObject->sell_price > 0) {
            $object->buy_price = $currentObject->sell_price;
        }
        if (!empty($soc_id)) {
            $object->fk_soc_buy = $soc_id;
        }
        if (!empty($fk_commande)) {
            $object->add_object_linked("order_supplier", $fk_commande);
        }

        $object->add_notification_auto($user, $langs->trans("TransfertVehicle", $object->ref,));
        $currentObject->add_notification_auto($user, $langs->trans("TransfertVehicleOtherEntity", $object->ref));
        $currentObject->status = self::STATUS_SELL;
        $currentObject->update($user, 1);
        $srcfile = "";
        $destfile = "";
        if ($this->entity == 1) {
            $srcfile = DOL_DATA_ROOT . "/fleetmanagment/vehicle/" . get_exdir(0, 0, 0, 1, $this);
        } else {
            $srcfile = DOL_DATA_ROOT . "/" . $this->entity . "/fleetmanagment/vehicle/" . get_exdir(0, 0, 0, 1, $this);

        }
        if ($object->entity == 1) {
            $destfile = DOL_DATA_ROOT . "/fleetmanagment/vehicle/" . $this->ref;
        } else {
            $destfile = DOL_DATA_ROOT . "/" . $object->entity . "/fleetmanagment/vehicle/" . $this->ref;
        }
        $res = dolCopyDir($srcfile, $destfile, $conf->global->MAIN_UMASK, 1);

        // End
        if (!$error) {
            $this->db->commit();
            return $object;
        } else {
            $this->db->rollback();
            return -1;
        }
    }


    /**
     * Load object in memory from the database
     *
     * @param int $id Id object
     * @param string $ref Ref
     * @return int         <0 if KO, 0 if not found, >0 if OK
     */
    public function fetch($id, $ref = null)
    {
        $result = $this->fetchCommon($id, $ref);
        if ($result > 0 && !empty($this->table_element_line)) {
            $this->fetchLines();
        }
        return $result;
    }

    /**
     * Load object in memory from the database
     *
     * @param int $import_key import_key object
     * @return int         <0 if KO, 0 if not found, >0 if OK
     */
    public function fetch_fk_order($import_key)
    {
        $result = $this->fetchCommon('', '', ' AND fk_order = ' . $import_key);
        if ($result > 0 && !empty($this->table_element_line)) {
            $this->fetchLines();
        }
        return $result;
    }

    /**
     * Load object in memory from the database
     *
     * @param int $import_key import_key object
     * @return int         <0 if KO, 0 if not found, >0 if OK
     */
    public function fetch_fk_order_fourn($import_key)
    {
        global $conf;
        if ($conf->global->FLEETMANAGMENT_ADDON_ID != "yye7Cz2BPhSeJs2ouy4xUw9vw48zmQ6xs86H8jkPyJ983rSM8ZaaYFfuR9ohvPGr") return 0;
        $this->ismultientitymanaged = 0;
        $result = $this->fetchCommon('', '', ' AND fk_order_fourn = ' . $import_key);
        if ($result > 0 && !empty($this->table_element_line)) {
            $this->ismultientitymanaged = 1;
            $this->fetchLines();
        }
        return $result;
    }


    /**
     * Load object lines in memory from the database
     *
     * @return int         <0 if KO, 0 if not found, >0 if OK
     */
    public function fetchLines()
    {
        $this->lines = array();

        $result = $this->fetchLinesCommon();
        return $result;
    }


    /**
     * Load list of objects in memory from the database.
     *
     * @param string $sortorder Sort Order
     * @param string $sortfield Sort field
     * @param int $limit limit
     * @param int $offset Offset
     * @param array $filter Filter array. Example array('field'=>'valueforlike', 'customurl'=>...)
     * @param string $filtermode Filter mode (AND or OR)
     * @return array|int                 int <0 if KO, array of pages if OK
     */
    public function fetchAll($sortorder = '', $sortfield = '', $limit = 0, $offset = 0, array $filter = array(), $filtermode = 'AND')
    {
        global $conf;

        dol_syslog(__METHOD__, LOG_DEBUG);

        $records = array();

        $sql = "SELECT ";
        $sql .= $this->getFieldList('t');
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
        if (isset($this->ismultientitymanaged) && $this->ismultientitymanaged == 1) {
            $sql .= " WHERE t.entity IN (" . getEntity($this->element) . ")";
        } else {
            $sql .= " WHERE 1 = 1";
        }
        // Manage filter
        $sqlwhere = array();
        if (count($filter) > 0) {
            foreach ($filter as $key => $value) {
                if ($key == 't.rowid') {
                    $sqlwhere[] = $key . " = " . ((int)$value);
                } elseif (in_array($this->fields[$key]['type'], array('date', 'datetime', 'timestamp'))) {
                    $sqlwhere[] = $key . " = '" . $this->db->idate($value) . "'";
                } elseif ($key == 'customsql') {
                    $sqlwhere[] = $value;
                } elseif (strpos($value, '%') === false) {
                    $sqlwhere[] = $key . " IN (" . $this->db->sanitize($this->db->escape($value)) . ")";
                } else {
                    $sqlwhere[] = $key . " LIKE '%" . $this->db->escape($value) . "%'";
                }
            }
        }
        if (count($sqlwhere) > 0) {
            $sql .= " AND (" . implode(" " . $filtermode . " ", $sqlwhere) . ")";
        }

        if (!empty($sortfield)) {
            $sql .= $this->db->order($sortfield, $sortorder);
        }
        if (!empty($limit)) {
            $sql .= $this->db->plimit($limit, $offset);
        }

        $resql = $this->db->query($sql);
        if ($resql) {
            $num = $this->db->num_rows($resql);
            $i = 0;
            while ($i < ($limit ? min($limit, $num) : $num)) {
                $obj = $this->db->fetch_object($resql);

                $record = new self($this->db);
                $record->setVarsFromFetchObj($obj);

                $records[$record->id] = $record;

                $i++;
            }
            $this->db->free($resql);

            return $records;
        } else {
            $this->errors[] = 'Error ' . $this->db->lasterror();
            dol_syslog(__METHOD__ . ' ' . join(',', $this->errors), LOG_ERR);

            return -1;
        }
    }

    /**
     * Update object into database
     *
     * @param User $user User that modifies
     * @param bool $notrigger false=launch triggers after, true=disable triggers
     * @return int             <0 if KO, >0 if OK
     */
    public function update(User $user, $notrigger = false)
    {
        global $langs;
        $res = $this->updateCommon($user, $notrigger);
        if ($res > 0) {
            $this->add_notification_auto($user, $langs->trans("EVENTVEHICULEModify", $this->ref));
        }
        return $res;
    }

    /**
     * Delete object in database
     *
     * @param User $user User that deletes
     * @param bool $notrigger false=launch triggers after, true=disable triggers
     * @return int             <0 if KO, >0 if OK
     */
    public function delete(User $user, $notrigger = false)
    {
        return $this->deleteCommon($user, $notrigger);
    }


    public function reserve($user, $notrigger = 0)
    {
        global $langs;
        // Protection
        if ($this->status != self::STATUS_LIBRE) {
            return 0;
        }
        $res = $this->setStatusCommon($user, self::STATUS_RESERVE, $notrigger, 'FLEETMANAGMENT_RESERVE');
        if ($res > 0) {
            $this->add_notification_auto($user, $langs->trans("UpdateStatutToReserve", $this->ref));
        }
        return $res;
    }

    public function publish($user, $notrigger = 0)
    {
        global $conf, $langs;
        if ($conf->global->FLEETMANAGMENT_ADDON_ID != "yye7Cz2BPhSeJs2ouy4xUw9vw48zmQ6xs86H8jkPyJ983rSM8ZaaYFfuR9ohvPGr") return 0;
        $this->publish = 1;
        $this->publish_date = dol_now();
        $res = $this->updateCommon($user, $notrigger);
        if ($res > 0) {
            $this->add_notification_auto($user, $langs->trans("EVENT_VEHICLE_PUBLISH", $this->ref));
        }
    }

    public function not_publish($user, $notrigger = 0)
    {
        global $conf, $langs;
        if ($conf->global->FLEETMANAGMENT_ADDON_ID != "yye7Cz2BPhSeJs2ouy4xUw9vw48zmQ6xs86H8jkPyJ983rSM8ZaaYFfuR9ohvPGr") return 0;
        $this->publish = 0;
        $this->publish_date = null;
        $res = $this->updateCommon($user, $notrigger);
        if ($res > 0) {
            $this->add_notification_auto($user, $langs->trans("EVENT_VEHICLE_NOT_PUBLISH", $this->ref));
        }
    }

    public function libre($user, $notrigger = 0)
    {
        global $langs;
        // Protection
        if ($this->status != self::STATUS_RESERVE) {
            return 0;
        }

        $res = $this->setStatusCommon($user, self::STATUS_LIBRE, $notrigger, 'FLEETMANAGMENT_LIBRE');
        if ($res > 0) {
            $this->add_notification_auto($user, $langs->trans("UpdateStatutToLibre", $this->ref));
        }
        return $res;
    }

    /**
     *  Return a link to the object card (with optionaly the picto)
     *
     * @param int $withpicto Include picto in link (0=No picto, 1=Include picto into link, 2=Only picto)
     * @param string $option On what the link point to ('nolink', ...)
     * @param int $notooltip 1=Disable tooltip
     * @param string $morecss Add more css on link
     * @param int $save_lastsearch_value -1=Auto, 0=No save of lastsearch_values when clicking, 1=Save lastsearch_values whenclicking
     * @return    string                              String with URL
     */
    public function getNomUrl($withpicto = 0, $option = '', $notooltip = 0, $morecss = '', $save_lastsearch_value = -1)
    {
        global $conf, $langs, $hookmanager;

        if (!empty($conf->dol_no_mouse_hover)) {
            $notooltip = 1; // Force disable tooltips
        }

        $result = '';

        $label = img_picto('', $this->picto) . ' <u>' . $langs->trans("FleetManagment") . '</u>';
        if (isset($this->status)) {
            $label .= ' ' . $this->getLibStatut(5);
        }
        $label .= '<br>';
        $label .= '<b>' . $langs->trans('Ref') . ':</b> ' . $this->ref;

        $url = dol_buildpath('/fleetmanagment/vehicle_card.php', 1) . '?id=' . $this->id;
        if ($option != 'nolink') {
            // Add param to save lastsearch_values or not
            $add_save_lastsearch_values = ($save_lastsearch_value == 1 ? 1 : 0);
            if ($save_lastsearch_value == -1 && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
                $add_save_lastsearch_values = 1;
            }
            if ($url && $add_save_lastsearch_values) {
                $url .= '&save_lastsearch_values=1';
            }
        }

        $linkclose = '';
        if (empty($notooltip)) {
            if (!empty($conf->global->MAIN_OPTIMIZEFORTEXTBROWSER)) {
                $label = $langs->trans("ShowFleetManagment");
                $linkclose .= ' alt="' . dol_escape_htmltag($label, 1) . '"';
            }
            $linkclose .= ' title="' . dol_escape_htmltag($label, 1) . '"';
            $linkclose .= ' class="classfortooltip' . ($morecss ? ' ' . $morecss : '') . '"';
        } else {
            $linkclose = ($morecss ? ' class="' . $morecss . '"' : '');
        }
        if ($option == 'nolink' || empty($url)) {
            $linkstart = '<span';
        } else {
            $linkstart = '<a href="' . $url . '"';
        }
        $linkstart .= $linkclose . '>';
        if ($option == 'nolink' || empty($url)) {
            $linkend = '</span>';
        } else {
            $linkend = '</a>';
        }

        $result .= $linkstart;

        if (empty($this->showphoto_on_popup)) {
            if ($withpicto) {
                $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'fleetmanagment@fleetmanagment'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright' : '') . 'classfortooltip" style="width:20px" '), 0, 0, $notooltip ? 0 : 1);
            }
        } else {
            if ($withpicto) {
                require_once DOL_DOCUMENT_ROOT . '/core/lib/files.lib.php';
                list($class, $module) = explode('@', $this->picto);
                $upload_dir = $conf->$module->multidir_output[$conf->entity] . "/$class/" . dol_sanitizeFileName($this->ref);
                $filearray = dol_dir_list($upload_dir, "files");
                $filename = $filearray[0]['name'];
                if (!empty($filename)) {
                    $pospoint = strpos($filearray[0]['name'], '.');

                    $pathtophoto = $class . '/' . $this->ref . '/thumbs/' . substr($filename, 0, $pospoint) . '_mini' . substr($filename, $pospoint);
                    if (empty($conf->global->{strtoupper($module . '_' . $class) . '_FORMATLISTPHOTOSASUSERS'})) {
                        $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><div class="photoref"><img class="photo' . $module . '" alt="No photo" border="0" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div></div>';
                    } else {
                        $result .= '<div class="floatleft inline-block valignmiddle divphotoref"><img class="photouserphoto userphoto" alt="No photo" border="0" src="' . DOL_URL_ROOT . '/viewimage.php?modulepart=' . $module . '&entity=' . $conf->entity . '&file=' . urlencode($pathtophoto) . '"></div>';
                    }

                    $result .= '</div>';
                } else {
                    $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="' . (($withpicto != 2) ? 'paddingright ' : '') . 'classfortooltip"'), 0, 0, $notooltip ? 0 : 1);
                }
            }
        }

        if ($withpicto != 2) {
            $result .= "  " . $this->ref;
        }

        $result .= $linkend;
        if ($withpicto != 2) $result .= (($addlabel && $this->label) ? $sep . dol_trunc($this->label, ($addlabel > 1 ? $addlabel : 0)) : '');

        global $action, $hookmanager;
        $hookmanager->initHooks(array('fleetmanagmentdao'));
        $parameters = array('id' => $this->id, 'getnomurl' => $result);
        $reshook = $hookmanager->executeHooks('getNomUrl', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
        if ($reshook > 0) {
            $result = $hookmanager->resPrint;
        } else {
            $result .= $hookmanager->resPrint;
        }

        return $result;
    }

    /**
     *  Return the label of the status
     *
     * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
     * @return    string                   Label of status
     */
    public function getLabelStatus($mode = 0)
    {
        return $this->LibStatut($this->status, $mode);
    }

    /**
     *  Return the label of the status
     *
     * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
     * @return    string                   Label of status
     */
    public function getLibStatut($mode = 0)
    {
        return $this->LibStatut($this->status, $mode);
    }

    // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps

    /**
     *  Return the status
     *
     * @param int $status Id status
     * @param int $mode 0=long label, 1=short label, 2=Picto + short label, 3=Picto, 4=Picto + long label, 5=Short label + Picto, 6=Long label + Picto
     * @return string                   Label of status
     */
    public function LibStatut($status, $mode = 0)
    {
        // phpcs:enable
        if (empty($this->labelStatus) || empty($this->labelStatusShort)) {
            global $langs;
            //$langs->load("fleetmanagment@fleetmanagment");
            $this->labelStatus[self::STATUS_LIBRE] = $langs->transnoentitiesnoconv('Libre');
            $this->labelStatus[self::STATUS_TRANSIT] = $langs->transnoentitiesnoconv('Transit');
            $this->labelStatus[self::STATUS_SELL] = $langs->transnoentitiesnoconv('SellVeh');
            $this->labelStatus[self::STATUS_RESERVE] = $langs->transnoentitiesnoconv('Reserve');
            $this->labelStatus[self::STATUS_MAINTENANCE] = $langs->transnoentitiesnoconv('Maintenance');
            $this->labelStatusShort[self::STATUS_LIBRE] = $langs->transnoentitiesnoconv('Libre');
            $this->labelStatusShort[self::STATUS_TRANSIT] = $langs->transnoentitiesnoconv('Transit');
            $this->labelStatusShort[self::STATUS_SELL] = $langs->transnoentitiesnoconv('SellVeh');
            $this->labelStatusShort[self::STATUS_RESERVE] = $langs->transnoentitiesnoconv('Reserve');
            $this->labelStatusShort[self::STATUS_MAINTENANCE] = $langs->transnoentitiesnoconv('Maintenance');
        }
        $statusType = 'status' . $status;
        if ($status == self::STATUS_LIBRE) $statusType = 'status4';
        if ($status == self::STATUS_TRANSIT) $statusType = 'status3';
        if ($status == self::STATUS_SELL) $statusType = 'status5';
        if ($status == self::STATUS_RESERVE) $statusType = 'status2';
        if ($status == self::STATUS_MAINTENANCE) $statusType = 'status6';


        return dolGetStatus($this->labelStatus[$status], $this->labelStatusShort[$status], '', $statusType, $mode);
    }

    /**
     *    Load the info information in the object
     *
     * @param int $id Id of object
     * @return    void
     */
    public function info($id)
    {
        $sql = "SELECT rowid, date_creation as datec, tms as datem,";
        $sql .= " fk_user_creat, fk_user_modif";
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
        $sql .= " WHERE t.rowid = " . ((int)$id);

        $result = $this->db->query($sql);
        if ($result) {
            if ($this->db->num_rows($result)) {
                $obj = $this->db->fetch_object($result);
                $this->id = $obj->rowid;
                if (!empty($obj->fk_user_author)) {
                    $cuser = new User($this->db);
                    $cuser->fetch($obj->fk_user_author);
                    $this->user_creation = $cuser;
                }

                if (!empty($obj->fk_user_valid)) {
                    $vuser = new User($this->db);
                    $vuser->fetch($obj->fk_user_valid);
                    $this->user_validation = $vuser;
                }

                if (!empty($obj->fk_user_cloture)) {
                    $cluser = new User($this->db);
                    $cluser->fetch($obj->fk_user_cloture);
                    $this->user_cloture = $cluser;
                }

                $this->date_creation = $this->db->jdate($obj->datec);
                $this->date_modification = $this->db->jdate($obj->datem);
                $this->date_validation = $this->db->jdate($obj->datev);
            }

            $this->db->free($result);
        } else {
            dol_print_error($this->db);
        }
    }

    /**
     * Initialise object with example values
     * Id must be 0 if object instance is a specimen
     *
     * @return void
     */
    public function initAsSpecimen()
    {
        // Set here init that are not commonf fields
        // $this->property1 = ...
        // $this->property2 = ...

        $this->initAsSpecimenCommon();
    }


    public function getNextNumMultiRef()
    {
        global $langs, $conf;
        if ($conf->global->FLEETMANAGMENT_ADDON_ID != "yye7Cz2BPhSeJs2ouy4xUw9vw48zmQ6xs86H8jkPyJ983rSM8ZaaYFfuR9ohvPGr") return 0;
        $langs->load("fleetmanagment@fleetmanagment");
        $sql = "SELECT ref";
        $sql .= " FROM " . MAIN_DB_PREFIX . $this->table_element . " as t";
        $sql .= " WHERE t.ref LIKE '" . $conf->global->MAIN_INFO_SOCIETE_NOM[0] . "-%' ORDER BY t.date_creation DESC LIMIT 1";
        $resql = $this->db->query($sql);
        if (!$resql) {
            dol_print_error();
            exit();
        } else {
            if ($resql->num_rows == 0) {
                return 1;
            } else {
                $obj = $this->db->fetch_object($resql);
                return intval(substr($obj->ref, 2)) + 1;
            }
        }
        return "ERROR";
    }


    /**
     *  Returns the reference to the following non used object depending on the active numbering module.
     *
     * @return string            Object free reference
     */
    public function getNextNumRef()
    {
        global $langs, $conf;
        $langs->load("fleetmanagment@fleetmanagment");

        if (empty($conf->global->FLEETMANAGMENT_VEHICLE_ADDON)) {
            $conf->global->FLEETMANAGMENT_VEHICLE_ADDON = 'mod_fleetmanagment_standard';
        }

        if (!empty($conf->global->FLEETMANAGMENT_VEHICLE_ADDON)) {
            $mybool = false;

            $file = $conf->global->FLEETMANAGMENT_VEHICLE_ADDON . ".php";
            $classname = $conf->global->FLEETMANAGMENT_VEHICLE_ADDON;

            // Include file with class
            $dirmodels = array_merge(array('/'), (array)$conf->modules_parts['models']);
            foreach ($dirmodels as $reldir) {
                $dir = dol_buildpath($reldir . "core/modules/fleetmanagment/");

                // Load file with numbering class (if found)
                $mybool |= @include_once $dir . $file;
            }

            if ($mybool === false) {
                dol_print_error('', "Failed to include file " . $file);
                return '';
            }

            if (class_exists($classname)) {
                $obj = new $classname();
                $numref = $obj->getNextValue($this);

                if ($numref != '' && $numref != '-1') {
                    return $numref;
                } else {
                    $this->error = $obj->error;
                    //dol_print_error($this->db,get_class($this)."::getNextNumRef ".$obj->error);
                    return "";
                }
            } else {
                print $langs->trans("Error") . " " . $langs->trans("ClassNotFound") . ' ' . $classname;
                return "";
            }
        } else {
            print $langs->trans("ErrorNumberingModuleNotSetup", $this->element);
            return "";
        }
    }

    private function add_notification_auto($user, $text, $type_code = 'AC_OTH_AUTO')
    {
        global $langs;
        require_once DOL_DOCUMENT_ROOT . "/comm/action/class/actioncomm.class.php";
        $actioncomm = new ActionComm($this->db);
        $actioncomm->type_id = $type_code; // Event insert into agenda automatically
        $actioncomm->contact_id = 0;
        $actioncomm->code = 'FLEET_MANAGEMENT';
        $actioncomm->label = $text;
        $actioncomm->datep = dol_now();
        $actioncomm->datef = dol_now();
        $actioncomm->percentage = -1; // Not applicable
        $actioncomm->authorid = $user->id; // User saving action
        $actioncomm->userownerid = $user->id; // Owner of action
        $actioncomm->fk_element = $this->id;
        $actioncomm->elementtype = $this->element . '@' . $this->module;
        $res = $actioncomm->create($user);
        return $res;
    }

    /**
     * Return HTML string to put an input field into a page
     * Code very similar with showInputField of extra fields
     *
     * @param array $val Array of properties for field to show (used only if ->fields not defined)
     * @param string $key Key of attribute
     * @param string|array $value Preselected value to show (for date type it must be in timestamp format, for amount or price it must be a php numeric value, for array type must be array)
     * @param string $moreparam To add more parameters on html input tag
     * @param string $keysuffix Prefix string to add into name and id of field (can be used to avoid duplicate names)
     * @param string $keyprefix Suffix string to add into name and id of field (can be used to avoid duplicate names)
     * @param string|int $morecss Value for css to define style/length of field. May also be a numeric.
     * @param int $nonewbutton Force to not show the new button on field that are links to object
     * @return string
     */
    public function showInputField($val, $key, $value, $moreparam = '', $keysuffix = '', $keyprefix = '', $morecss = 0, $nonewbutton = 0)
    {
        global $conf, $langs, $form, $user;
        $action =  GETPOST("action");
        if (!is_object($form)) {
            require_once DOL_DOCUMENT_ROOT . '/core/class/html.form.class.php';
            $form = new Form($this->db);
        }

        if (!empty($this->fields)) {
            $val = $this->fields[$key];
        }

        // Validation tests and output
        $fieldValidationErrorMsg = '';
        $validationClass = '';
        $fieldValidationErrorMsg = $this->getFieldError($key);
        if (!empty($fieldValidationErrorMsg)) {
            $validationClass = ' --error'; // the -- is use as class state in css :  .--error can't be be defined alone it must be define with another class like .my-class.--error or input.--error
        } else {
            $validationClass = ' --success'; // the -- is use as class state in css :  .--success can't be be defined alone it must be define with another class like .my-class.--success or input.--success
        }

        $out = '';
        $type = '';
        $isDependList = 0;
        $param = array();
        $param['options'] = array();
        $reg = array();
        $size = !empty($this->fields[$key]['size']) ? $this->fields[$key]['size'] : 0;
        // Because we work on extrafields
        if (preg_match('/^(integer|link):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
            $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] . ':' . $reg[5] => 'N');
            $type = 'link';
        } elseif (preg_match('/^(integer|link):(.*):(.*):(.*)/i', $val['type'], $reg)) {
            $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] => 'N');
            $type = 'link';
        } elseif (preg_match('/^(integer|link):(.*):(.*)/i', $val['type'], $reg)) {
            $param['options'] = array($reg[2] . ':' . $reg[3] => 'N');
            $type = 'link';
        } elseif (preg_match('/^(sellist):(.*):(.*):(.*):(.*)/i', $val['type'], $reg)) {
            $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] . ':' . $reg[5] => 'N');
            $type = 'sellist';
        } elseif (preg_match('/^(sellist):(.*):(.*):(.*)/i', $val['type'], $reg)) {
            $param['options'] = array($reg[2] . ':' . $reg[3] . ':' . $reg[4] => 'N');
            $type = 'sellist';
        } elseif (preg_match('/^(sellist):(.*):(.*)/i', $val['type'], $reg)) {
            $param['options'] = array($reg[2] . ':' . $reg[3] => 'N');
            $type = 'sellist';
        } elseif (preg_match('/varchar\((\d+)\)/', $val['type'], $reg)) {
            $param['options'] = array();
            $type = 'varchar';
            $size = $reg[1];
        } elseif (preg_match('/varchar/', $val['type'])) {
            $param['options'] = array();
            $type = 'varchar';
        } else {
            $param['options'] = array();
            $type = $this->fields[$key]['type'];
        }

        // Special case that force options and type ($type can be integer, varchar, ...)
        if (!empty($this->fields[$key]['arrayofkeyval']) && is_array($this->fields[$key]['arrayofkeyval'])) {
            $param['options'] = $this->fields[$key]['arrayofkeyval'];
            $type = 'select';
        }

        $label = $this->fields[$key]['label'];
        //$elementtype=$this->fields[$key]['elementtype'];	// Seems not used
        $default = (!empty($this->fields[$key]['default']) ? $this->fields[$key]['default'] : '');
        $computed = (!empty($this->fields[$key]['computed']) ? $this->fields[$key]['computed'] : '');
        $unique = (!empty($this->fields[$key]['unique']) ? $this->fields[$key]['unique'] : 0);
        $required = (!empty($this->fields[$key]['required']) ? $this->fields[$key]['required'] : 0);
        $autofocusoncreate = (!empty($this->fields[$key]['autofocusoncreate']) ? $this->fields[$key]['autofocusoncreate'] : 0);

        $langfile = (!empty($this->fields[$key]['langfile']) ? $this->fields[$key]['langfile'] : '');
        $list = (!empty($this->fields[$key]['list']) ? $this->fields[$key]['list'] : 0);
        $hidden = (in_array(abs($this->fields[$key]['visible']), array(0, 2)) ? 1 : 0);

        $objectid = $this->id;

        if ($computed) {
            if (!preg_match('/^search_/', $keyprefix)) {
                return '<span class="opacitymedium">' . $langs->trans("AutomaticallyCalculated") . '</span>';
            } else {
                return '';
            }
        }

        // Set value of $morecss. For this, we use in priority showsize from parameters, then $val['css'] then autodefine
        if (empty($morecss) && !empty($val['css'])) {
            $morecss = $val['css'];
        } elseif (empty($morecss)) {
            if ($type == 'date') {
                $morecss = 'minwidth100imp';
            } elseif ($type == 'datetime' || $type == 'link') {    // link means an foreign key to another primary id
                $morecss = 'minwidth200imp';
            } elseif (in_array($type, array('int', 'integer', 'price')) || preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
                $morecss = 'maxwidth75';
            } elseif ($type == 'url') {
                $morecss = 'minwidth400';
            } elseif ($type == 'boolean') {
                $morecss = '';
            } else {
                if (round($size) < 12) {
                    $morecss = 'minwidth100';
                } elseif (round($size) <= 48) {
                    $morecss = 'minwidth200';
                } else {
                    $morecss = 'minwidth400';
                }
            }
        }

        // Add validation state class
        if (!empty($validationClass)) {
            $morecss .= ' ' . $validationClass;
        }

        if (in_array($type, array('date'))) {
            $tmp = explode(',', $size);
            $newsize = $tmp[0];
            $showtime = 0;

            // Do not show current date when field not required (see selectDate() method)
            if (!$required && $value == '') {
                $value = '-1';
            }

            // TODO Must also support $moreparam
            $out = $form->selectDate($value, $keyprefix . $key . $keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1);
        } elseif (in_array($type, array('datetime'))) {
            $tmp = explode(',', $size);
            $newsize = $tmp[0];
            $showtime = 1;

            // Do not show current date when field not required (see selectDate() method)
            if (!$required && $value == '') $value = '-1';

            // TODO Must also support $moreparam
            $out = $form->selectDate($value, $keyprefix . $key . $keysuffix, $showtime, $showtime, $required, '', 1, (($keyprefix != 'search_' && $keyprefix != 'search_options_') ? 1 : 0), 0, 1, '', '', '', 1, '', '', 'tzuserrel');
        } elseif (in_array($type, array('duration'))) {
            $out = $form->select_duration($keyprefix . $key . $keysuffix, $value, 0, 'text', 0, 1);
        } elseif (in_array($type, array('int', 'integer'))) {
            $tmp = explode(',', $size);
            $newsize = $tmp[0];
            $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '"' . ($newsize > 0 ? ' maxlength="' . $newsize . '"' : '') . ' value="' . dol_escape_htmltag($value) . '"' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
        } elseif (in_array($type, array('real'))) {
            $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '"' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
        } elseif (preg_match('/varchar/', $type)) {
            $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '"' . ($size > 0 ? ' maxlength="' . $size . '"' : '') . ' value="' . dol_escape_htmltag($value) . '"' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
            if($action == "create" && $key == "imatriculation" && !empty($conf->global->FLEETMANAGMENT_IMPORT_INFORMATION_IN_FORM) && !empty($conf->global->FLEETMANAGMENT_IMMATRICULATION_API) && !empty($conf->global->FLEETMANAGMENT_URL_API_IMATRICULATION)){
                $out .= '<a id="import_vehicle" class="tab inline-block" href="#" title=""><span class="fa fa-cloud-download valignmiddle paddingleft"></span></a>';
            }
        } elseif (in_array($type, array('mail', 'phone', 'url'))) {
            $out = '<input type="text" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '" ' . ($moreparam ? $moreparam : '') . ($autofocusoncreate ? ' autofocus' : '') . '>';
        } elseif (preg_match('/^text/', $type)) {
            if (!preg_match('/search_/', $keyprefix)) {        // If keyprefix is search_ or search_options_, we must just use a simple text field
                require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
                $doleditor = new DolEditor($keyprefix . $key . $keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, false, ROWS_5, '90%');
                $out = $doleditor->Create(1);
            } else {
                $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '" ' . ($moreparam ? $moreparam : '') . '>';
            }
        } elseif (preg_match('/^html/', $type)) {
            if (!preg_match('/search_/', $keyprefix)) {        // If keyprefix is search_ or search_options_, we must just use a simple text field
                require_once DOL_DOCUMENT_ROOT . '/core/class/doleditor.class.php';
                $doleditor = new DolEditor($keyprefix . $key . $keysuffix, $value, '', 200, 'dolibarr_notes', 'In', false, false, !empty($conf->fckeditor->enabled) && $conf->global->FCKEDITOR_ENABLE_SOCIETE, ROWS_5, '90%');
                $out = $doleditor->Create(1);
            } else {
                $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . dol_escape_htmltag($value) . '" ' . ($moreparam ? $moreparam : '') . '>';
            }
        } elseif ($type == 'boolean') {
            $checked = '';
            if (!empty($value)) {
                $checked = ' checked value="1" ';
            } else {
                $checked = ' value="1" ';
            }
            $out = '<input type="checkbox" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . $checked . ' ' . ($moreparam ? $moreparam : '') . '>';
        } elseif ($type == 'price') {
            if (!empty($value)) {        // $value in memory is a php numeric, we format it into user number format.
                $value = price($value);
            }
            $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '> ' . $langs->getCurrencySymbol($conf->currency);
        } elseif (preg_match('/^double(\([0-9],[0-9]\)){0,1}/', $type)) {
            if (!empty($value)) {        // $value in memory is a php numeric, we format it into user number format.
                $value = price($value);
            }
            $out = '<input type="text" class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '> ';
        } elseif ($type == 'select') {
            $out = '';
            if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
                $out .= ajax_combobox($keyprefix . $key . $keysuffix, array(), 0);
            }

            $out .= '<select class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . ($moreparam ? $moreparam : '') . '>';
            if ((!isset($this->fields[$key]['default'])) || ($this->fields[$key]['notnull'] != 1)) {
                $out .= '<option value="0">&nbsp;</option>';
            }
            foreach ($param['options'] as $key => $val) {
                if ((string)$key == '') {
                    continue;
                }
                list($val, $parent) = explode('|', $val);
                $out .= '<option value="' . $key . '"';
                $out .= (((string)$value == (string)$key) ? ' selected' : '');
                $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
                $out .= '>' . $val . '</option>';
            }
            $out .= '</select>';
        } elseif ($type == 'sellist') {
            $out = '';
            if (!empty($conf->use_javascript_ajax) && empty($conf->global->MAIN_EXTRAFIELDS_DISABLE_SELECT2)) {
                include_once DOL_DOCUMENT_ROOT . '/core/lib/ajax.lib.php';
                $out .= ajax_combobox($keyprefix . $key . $keysuffix, array(), 0);
            }
            $out .= '<select class="flat ' . $morecss . ' maxwidthonsmartphone" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" ' . ($moreparam ? $moreparam : '') . '>';
            if (is_array($param['options'])) {
                $param_list = array_keys($param['options']);
                $InfoFieldList = explode(":", $param_list[0]);
                $parentName = '';
                $parentField = '';
                // 0 : tableName
                // 1 : label field name
                // 2 : key fields name (if differ of rowid)
                // 3 : key field parent (for dependent lists)
                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
                $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');

                if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
                    if (strpos($InfoFieldList[4], 'extra.') !== false) {
                        $keyList = 'main.' . $InfoFieldList[2] . ' as rowid';
                    } else {
                        $keyList = $InfoFieldList[2] . ' as rowid';
                    }
                }
                if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
                    list($parentName, $parentField) = explode('|', $InfoFieldList[3]);
                    $keyList .= ', ' . $parentField;
                }

                $fields_label = explode('|', $InfoFieldList[1]);
                if (is_array($fields_label)) {
                    $keyList .= ', ';
                    $keyList .= implode(', ', $fields_label);
                }

                $sqlwhere = '';
                $sql = "SELECT " . $keyList;
                $sql .= " FROM " . MAIN_DB_PREFIX . $InfoFieldList[0];
                if (!empty($InfoFieldList[4])) {
                    // can use SELECT request
                    if (strpos($InfoFieldList[4], '$SEL$') !== false) {
                        $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
                    }

                    // current object id can be use into filter
                    if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
                        $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
                    } else {
                        $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
                    }

                    //We have to join on extrafield table
                    if (strpos($InfoFieldList[4], 'extra') !== false) {
                        $sql .= " as main, " . MAIN_DB_PREFIX . $InfoFieldList[0] . "_extrafields as extra";
                        $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
                    } else {
                        $sqlwhere .= " WHERE " . $InfoFieldList[4];
                    }
                } else {
                    $sqlwhere .= ' WHERE 1=1';
                }
                // Some tables may have field, some other not. For the moment we disable it.
                if (in_array($InfoFieldList[0], array('tablewithentity'))) {
                    $sqlwhere .= " AND entity = " . ((int)$conf->entity);
                }
                $sql .= $sqlwhere;
                //print $sql;

                $sql .= ' ORDER BY ' . implode(', ', $fields_label);

                dol_syslog(get_class($this) . '::showInputField type=sellist', LOG_DEBUG);
                $resql = $this->db->query($sql);
                if ($resql) {
                    $out .= '<option value="0">&nbsp;</option>';
                    $num = $this->db->num_rows($resql);
                    $i = 0;
                    while ($i < $num) {
                        $labeltoshow = '';
                        $obj = $this->db->fetch_object($resql);

                        // Several field into label (eq table:code|libelle:rowid)
                        $notrans = false;
                        $fields_label = explode('|', $InfoFieldList[1]);
                        if (count($fields_label) > 1) {
                            $notrans = true;
                            foreach ($fields_label as $field_toshow) {
                                $labeltoshow .= $obj->$field_toshow . ' ';
                            }
                        } else {
                            $labeltoshow = $obj->{$InfoFieldList[1]};
                        }
                        $labeltoshow = dol_trunc($labeltoshow, 45);

                        if ($value == $obj->rowid) {
                            foreach ($fields_label as $field_toshow) {
                                $translabel = $langs->trans($obj->$field_toshow);
                                if ($translabel != $obj->$field_toshow) {
                                    $labeltoshow = dol_trunc($translabel) . ' ';
                                } else {
                                    $labeltoshow = dol_trunc($obj->$field_toshow) . ' ';
                                }
                            }
                            $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
                        } else {
                            if (!$notrans) {
                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
                                if ($translabel != $obj->{$InfoFieldList[1]}) {
                                    $labeltoshow = dol_trunc($translabel, 18);
                                } else {
                                    $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]});
                                }
                            }
                            if (empty($labeltoshow)) {
                                $labeltoshow = '(not defined)';
                            }
                            if ($value == $obj->rowid) {
                                $out .= '<option value="' . $obj->rowid . '" selected>' . $labeltoshow . '</option>';
                            }

                            if (!empty($InfoFieldList[3]) && $parentField) {
                                $parent = $parentName . ':' . $obj->{$parentField};
                                $isDependList = 1;
                            }

                            $out .= '<option value="' . $obj->rowid . '"';
                            $out .= ($value == $obj->rowid ? ' selected' : '');
                            $out .= (!empty($parent) ? ' parent="' . $parent . '"' : '');
                            $out .= '>' . $labeltoshow . '</option>';
                        }

                        $i++;
                    }
                    $this->db->free($resql);
                } else {
                    print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . '. Check setup of extra parameters.<br>';
                }
            }
            $out .= '</select>';
            if (!empty($val["dictionaries"]) && $user->rights->fleetmanagment->vehicle->dictionariesWrite && $_SERVER["SCRIPT_NAME"] == "/custom/fleetmanagment/vehicle_card.php") {
                $out .= '<a id="' . $InfoFieldList[0] . 'link" class="tab inline-block" href="#" title=""><span class="fa fa-plus-circle valignmiddle paddingleft"></span></a>';
                if (!empty($val["popupAjax"])) {
                    $out .= add_field_dictionaries($InfoFieldList[0], $val["label"], $key);
                    $out .= '
					<script>
					$(document).ready(function() {
	                    $("#' . $InfoFieldList[0] . 'link").click(function(e) { 
                            $("#dialog-confirm-' . $InfoFieldList[0] . '").dialog("open"); 
                            return false; 
                        });
					});
                    </script> ';
                }
            }
        } elseif ($type == 'checkbox') {
            $value_arr = explode(',', $value);
            $out = $form->multiselectarray($keyprefix . $key . $keysuffix, (empty($param['options']) ? null : $param['options']), $value_arr, '', 0, $morecss, 0, '100 % ');
        } elseif ($type == 'radio') {
            $out = '';
            foreach ($param['options'] as $keyopt => $val) {
                $out .= ' < input class="flat ' . $morecss . '" type = "radio" name = "' . $keyprefix . $key . $keysuffix . '" id = "' . $keyprefix . $key . $keysuffix . '" ' . ($moreparam ? $moreparam : '');
                $out .= ' value = "' . $keyopt . '"';
                $out .= ' id = "' . $keyprefix . $key . $keysuffix . '_' . $keyopt . '"';
                $out .= ($value == $keyopt ? 'checked' : '');
                $out .= ' /><label for="' . $keyprefix . $key . $keysuffix . '_' . $keyopt . '" > ' . $val . '</label ><br > ';
            }
        } elseif ($type == 'chkbxlst') {
            if (is_array($value)) {
                $value_arr = $value;
            } else {
                $value_arr = explode(',', $value);
            }

            if (is_array($param['options'])) {
                $param_list = array_keys($param['options']);
                $InfoFieldList = explode(":", $param_list[0]);
                $parentName = '';
                $parentField = '';
                // 0 : tableName
                // 1 : label field name
                // 2 : key fields name (if differ of rowid)
                // 3 : key field parent (for dependent lists)
                // 4 : where clause filter on column or table extrafield, syntax field='value' or extra.field=value
                $keyList = (empty($InfoFieldList[2]) ? 'rowid' : $InfoFieldList[2] . ' as rowid');

                if (count($InfoFieldList) > 3 && !empty($InfoFieldList[3])) {
                    list ($parentName, $parentField) = explode(' | ', $InfoFieldList[3]);
                    $keyList .= ', ' . $parentField;
                }
                if (count($InfoFieldList) > 4 && !empty($InfoFieldList[4])) {
                    if (strpos($InfoFieldList[4], 'extra . ') !== false) {
                        $keyList = 'main . ' . $InfoFieldList[2] . ' as rowid';
                    } else {
                        $keyList = $InfoFieldList[2] . ' as rowid';
                    }
                }

                $fields_label = explode(' | ', $InfoFieldList[1]);
                if (is_array($fields_label)) {
                    $keyList .= ', ';
                    $keyList .= implode(', ', $fields_label);
                }

                $sqlwhere = '';
                $sql = "SELECT " . $keyList;
                $sql .= ' FROM ' . MAIN_DB_PREFIX . $InfoFieldList[0];
                if (!empty($InfoFieldList[4])) {
                    // can use SELECT request
                    if (strpos($InfoFieldList[4], '$SEL$') !== false) {
                        $InfoFieldList[4] = str_replace('$SEL$', 'SELECT', $InfoFieldList[4]);
                    }

                    // current object id can be use into filter
                    if (strpos($InfoFieldList[4], '$ID$') !== false && !empty($objectid)) {
                        $InfoFieldList[4] = str_replace('$ID$', $objectid, $InfoFieldList[4]);
                    } else {
                        $InfoFieldList[4] = str_replace('$ID$', '0', $InfoFieldList[4]);
                    }

                    // We have to join on extrafield table
                    if (strpos($InfoFieldList[4], 'extra') !== false) {
                        $sql .= ' as main, ' . MAIN_DB_PREFIX . $InfoFieldList[0] . '_extrafields as extra';
                        $sqlwhere .= " WHERE extra.fk_object=main." . $InfoFieldList[2] . " AND " . $InfoFieldList[4];
                    } else {
                        $sqlwhere .= " WHERE " . $InfoFieldList[4];
                    }
                } else {
                    $sqlwhere .= ' WHERE 1 = 1';
                }
                // Some tables may have field, some other not. For the moment we disable it.
                if (in_array($InfoFieldList[0], array('tablewithentity'))) {
                    $sqlwhere .= " AND entity = " . ((int)$conf->entity);
                }
                // $sql.=preg_replace(' /^ and /','',$sqlwhere);
                // print $sql;

                $sql .= $sqlwhere;
                dol_syslog(get_class($this) . '::showInputField type = chkbxlst', LOG_DEBUG);
                $resql = $this->db->query($sql);
                if ($resql) {
                    $num = $this->db->num_rows($resql);
                    $i = 0;

                    $data = array();

                    while ($i < $num) {
                        $labeltoshow = '';
                        $obj = $this->db->fetch_object($resql);

                        $notrans = false;
                        // Several field into label (eq table:code|libelle:rowid)
                        $fields_label = explode(' | ', $InfoFieldList[1]);
                        if (count($fields_label) > 1) {
                            $notrans = true;
                            foreach ($fields_label as $field_toshow) {
                                $labeltoshow .= $obj->$field_toshow . ' ';
                            }
                        } else {
                            $labeltoshow = $obj->{$InfoFieldList[1]};
                        }
                        $labeltoshow = dol_trunc($labeltoshow, 45);

                        if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
                            foreach ($fields_label as $field_toshow) {
                                $translabel = $langs->trans($obj->$field_toshow);
                                if ($translabel != $obj->$field_toshow) {
                                    $labeltoshow = dol_trunc($translabel, 18) . ' ';
                                } else {
                                    $labeltoshow = dol_trunc($obj->$field_toshow, 18) . ' ';
                                }
                            }

                            $data[$obj->rowid] = $labeltoshow;
                        } else {
                            if (!$notrans) {
                                $translabel = $langs->trans($obj->{$InfoFieldList[1]});
                                if ($translabel != $obj->{$InfoFieldList[1]}) {
                                    $labeltoshow = dol_trunc($translabel, 18);
                                } else {
                                    $labeltoshow = dol_trunc($obj->{$InfoFieldList[1]}, 18);
                                }
                            }
                            if (empty($labeltoshow)) {
                                $labeltoshow = '(not defined)';
                            }

                            if (is_array($value_arr) && in_array($obj->rowid, $value_arr)) {
                                $data[$obj->rowid] = $labeltoshow;
                            }

                            if (!empty($InfoFieldList[3]) && $parentField) {
                                $parent = $parentName . ':' . $obj->{$parentField};
                                $isDependList = 1;
                            }

                            $data[$obj->rowid] = $labeltoshow;
                        }

                        $i++;
                    }
                    $this->db->free($resql);

                    $out = $form->multiselectarray($keyprefix . $key . $keysuffix, $data, $value_arr, '', 0, '', 0, '100 % ');
                } else {
                    print 'Error in request ' . $sql . ' ' . $this->db->lasterror() . ' . Check setup of extra parameters .<br > ';
                }
            }
        } elseif ($type == 'link') {
            $param_list = array_keys($param['options']); // $param_list='ObjectName:classPath[:AddCreateButtonOrNot[:Filter[:Sortfield]]]'
            $param_list_array = explode(':', $param_list[0]);
            $showempty = (($required && $default != '') ? 0 : 1);

            if (!preg_match(' / search_ / ', $keyprefix)) {
                if (!empty($param_list_array[2])) {        // If the entry into $fields is set to add a create button
                    if (!empty($this->fields[$key]['picto'])) {
                        $morecss .= ' widthcentpercentminusxx';
                    } else {
                        $morecss .= ' widthcentpercentminusx';
                    }
                } else {
                    if (!empty($this->fields[$key]['picto'])) {
                        $morecss .= ' widthcentpercentminusx';
                    }
                }
            }

            $out = $form->selectForForms($param_list[0], $keyprefix . $key . $keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1);

            if (!empty($param_list_array[2])) {        // If the entry into $fields is set to add a create button
                if (!GETPOSTISSET('backtopage') && empty($val['disabled']) && empty($nonewbutton)) {    // To avoid to open several times the 'Create Object' button and to avoid to have button if field is protected by a "disabled".
                    list($class, $classfile) = explode(':', $param_list[0]);
                    if (file_exists(dol_buildpath(dirname(dirname($classfile)) . ' / card . php'))) {
                        $url_path = dol_buildpath(dirname(dirname($classfile)) . ' / card . php', 1);
                    } else {
                        $url_path = dol_buildpath(dirname(dirname($classfile)) . ' / ' . strtolower($class) . '_card . php', 1);
                    }
                    $paramforthenewlink = '';
                    $paramforthenewlink .= (GETPOSTISSET('action') ? ' & action = ' . GETPOST('action', 'aZ09') : '');
                    $paramforthenewlink .= (GETPOSTISSET('id') ? ' & id = ' . GETPOST('id', 'int') : '');
                    $paramforthenewlink .= ' & fk_' . strtolower($class) . ' = --IDFORBACKTOPAGE--';
                    // TODO Add Javascript code to add input fields already filled into $paramforthenewlink so we won't loose them when going back to main page
                    $out .= '<a class="butActionNew" title="' . $langs->trans("New") . '" href="' . $url_path . '?action=create&backtopage=' . urlencode($_SERVER['PHP_SELF'] . ($paramforthenewlink ? '?' . $paramforthenewlink : '')) . '"><span class="fa fa-plus-circle valignmiddle"></span></a>';
                }
            }
        } elseif ($type == 'password') {
            // If prefix is 'search_', field is used as a filter, we use a common text field.
            $out = '<input type="' . ($keyprefix == 'search_' ? 'text' : 'password') . '" class="flat ' . $morecss . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '" value="' . $value . '" ' . ($moreparam ? $moreparam : '') . '>';
        } elseif
        ($type == 'array') {
            $newval = $val;
            $newval['type'] = 'varchar(256)';

            $out = '';
            if (!empty($value)) {
                foreach ($value as $option) {
                    $out .= '<span><a class="' . dol_escape_htmltag($keyprefix . $key . $keysuffix) . '_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
                    $out .= $this->showInputField($newval, $keyprefix . $key . $keysuffix . '[]', $option, $moreparam, '', '', $morecss) . '<br></span>';
                }
            }
            $out .= '<a id="' . dol_escape_htmltag($keyprefix . $key . $keysuffix) . '_add" href="javascript:;"><span class="fa fa-plus-circle valignmiddle"></span></a>';

            $newInput = '<span><a class="' . dol_escape_htmltag($keyprefix . $key . $keysuffix) . '_del" href="javascript:;"><span class="fa fa-minus-circle valignmiddle"></span></a> ';
            $newInput .= $this->showInputField($newval, $keyprefix . $key . $keysuffix . '[]', '', $moreparam, '', '', $morecss) . '<br></span>';

            if (!empty($conf->use_javascript_ajax)) {
                $out .= '
					<script>
					$(document).ready(function() {
						$("a#' . dol_escape_js($keyprefix . $key . $keysuffix) . '_add").click(function() {
							$("' . dol_escape_js($newInput) . '").insertBefore(this);
						});

						$(document).on("click", "a.' . dol_escape_js($keyprefix . $key . $keysuffix) . '_del", function() {
							$(this).parent().remove();
						});
					});
					</script>';
            }
        }
        if (!empty($hidden)) {
            $out = '<input type="hidden" value="' . $value . '" name="' . $keyprefix . $key . $keysuffix . '" id="' . $keyprefix . $key . $keysuffix . '"/>';
        }

        if ($isDependList == 1) {
            $out .= $this->getJSListDependancies('_common');
        }
        /* Add comments
         if ($type == 'date') $out.=' (YYYY-MM-DD)';
         elseif ($type == 'datetime') $out.=' (YYYY-MM-DD HH:MM:SS)';
         */

// Display error message for field
        if (!empty($fieldValidationErrorMsg) && function_exists('getFieldErrorIcon')) {
            $out .= ' ' . getFieldErrorIcon($fieldValidationErrorMsg);
        }

        return $out;
    }


    /**
     *    Fetch array of objects linked to current object (object of enabled modules only). Links are loaded into
     *        this->linkedObjectsIds array +
     *        this->linkedObjects array if $loadalsoobjects = 1 or $loadalsoobjects = type
     *  Possible usage for parameters:
     *  - all parameters empty -> we look all link to current object (current object can be source or target)
     *  - source id+type -> will get list of targets linked to source
     *  - target id+type -> will get list of sources linked to target
     *  - source id+type + target type -> will get list of targets of the type linked to source
     *  - target id+type + source type -> will get list of sources of the type linked to target
     *
     * @param int $sourceid Object source id (if not defined, id of object)
     * @param string $sourcetype Object source type (if not defined, element name of object)
     * @param int $targetid Object target id (if not defined, id of object)
     * @param string $targettype Object target type (if not defined, element name of object)
     * @param string $clause 'OR' or 'AND' clause used when both source id and target id are provided
     * @param int $alsosametype 0=Return only links to object that differs from source type. 1=Include also link to objects of same type.
     * @param string $orderby SQL 'ORDER BY' clause
     * @param int|string $loadalsoobjects Load also array this->linkedObjects. Use 0 to increase performances, Use 1 to load all, Use value of type ('facture', 'facturerec', ...) to load only a type of object.
     * @return int                                <0 if KO, >0 if OK
     * @see    add_object_linked(), updateObjectLinked(), deleteObjectLinked()
     */
    public function fetchObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $clause = 'OR', $alsosametype = 1, $orderby = 'sourcetype', $loadalsoobjects = 1)
    {
        global $conf, $hookmanager, $action;

        $this->linkedObjectsIds = array();
        $this->linkedObjects = array();

        $justsource = false;
        $justtarget = false;
        $withtargettype = false;
        $withsourcetype = false;

        $parameters = array('sourcetype' => $sourcetype, 'sourceid' => $sourceid, 'targettype' => $targettype, 'targetid' => $targetid);
        // Hook for explicitly set the targettype if it must be differtent than $this->element
        $reshook = $hookmanager->executeHooks('setLinkedObjectSourceTargetType', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
        if ($reshook > 0) {
            if (!empty($hookmanager->resArray['sourcetype'])) $sourcetype = $hookmanager->resArray['sourcetype'];
            if (!empty($hookmanager->resArray['sourceid'])) $sourceid = $hookmanager->resArray['sourceid'];
            if (!empty($hookmanager->resArray['targettype'])) $targettype = $hookmanager->resArray['targettype'];
            if (!empty($hookmanager->resArray['targetid'])) $targetid = $hookmanager->resArray['targetid'];
        }

        if (!empty($sourceid) && !empty($sourcetype) && empty($targetid)) {
            $justsource = true; // the source (id and type) is a search criteria
            if (!empty($targettype)) {
                $withtargettype = true;
            }
        }
        if (!empty($targetid) && !empty($targettype) && empty($sourceid)) {
            $justtarget = true; // the target (id and type) is a search criteria
            if (!empty($sourcetype)) {
                $withsourcetype = true;
            }
        }

        $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
        $targetid = (!empty($targetid) ? $targetid : $this->id);
        $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->module . '_' . $this->element);
        $targettype = (!empty($targettype) ? $targettype : $this->module . '_' . $this->element);

        /*if (empty($sourceid) && empty($targetid))
         {
         dol_syslog('Bad usage of function. No source nor target id defined (nor as parameter nor as object id)', LOG_ERR);
         return -1;
         }*/

        // Links between objects are stored in table element_element
        $sql = 'SELECT rowid, fk_source, sourcetype, fk_target, targettype';
        $sql .= ' FROM ' . MAIN_DB_PREFIX . 'element_element';
        $sql .= " WHERE ";
        if ($justsource || $justtarget) {
            if ($justsource) {
                $sql .= "fk_source = " . ((int)$sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
                if ($withtargettype) {
                    $sql .= " AND targettype = '" . $this->db->escape($targettype) . "'";
                }
            } elseif ($justtarget) {
                $sql .= "fk_target = " . ((int)$targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
                if ($withsourcetype) {
                    $sql .= " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
                }
            }
        } else {
            $sql .= "(fk_source = " . ((int)$sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "')";
            $sql .= " " . $clause . " (fk_target = " . ((int)$targetid) . " AND targettype = '" . $this->db->escape($targettype) . "')";
        }
        $sql .= ' ORDER BY ' . $orderby;
        dol_syslog(get_class($this) . "::fetchObjectLink", LOG_DEBUG);
        $resql = $this->db->query($sql);
        if ($resql) {
            $num = $this->db->num_rows($resql);
            $i = 0;
            while ($i < $num) {
                $obj = $this->db->fetch_object($resql);
                if ($justsource || $justtarget) {
                    if ($justsource) {
                        $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
                    } elseif ($justtarget) {
                        $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
                    }
                } else {
                    if ($obj->fk_source == $sourceid && $obj->sourcetype == $sourcetype) {
                        $this->linkedObjectsIds[$obj->targettype][$obj->rowid] = $obj->fk_target;
                    }
                    if ($obj->fk_target == $targetid && $obj->targettype == $targettype) {
                        $this->linkedObjectsIds[$obj->sourcetype][$obj->rowid] = $obj->fk_source;
                    }
                }
                $i++;
            }

            if (!empty($this->linkedObjectsIds)) {
                $tmparray = $this->linkedObjectsIds;
                foreach ($tmparray as $objecttype => $objectids) {       // $objecttype is a module name ('facture', 'mymodule', ...) or a module name with a suffix ('project_task', 'mymodule_myobj', ...)
                    // Parse element/subelement (ex: project_task, cabinetmed_consultation, ...)
                    $module = $element = $subelement = $objecttype;
                    $regs = array();
                    if ($objecttype != 'supplier_proposal' && $objecttype != 'order_supplier' && $objecttype != 'invoice_supplier'
                        && preg_match('/^([^_]+)_([^_]+)/i', $objecttype, $regs)) {
                        $module = $element = $regs[1];
                        $subelement = $regs[2];
                    }

                    $classpath = $element . '/class';
                    // To work with non standard classpath or module name
                    if ($objecttype == 'facture') {
                        $classpath = 'compta/facture/class';
                    } elseif ($objecttype == 'facturerec') {
                        $classpath = 'compta/facture/class';
                        $module = 'facture';
                    } elseif ($objecttype == 'propal') {
                        $classpath = 'comm/propal/class';
                    } elseif ($objecttype == 'supplier_proposal') {
                        $classpath = 'supplier_proposal/class';
                    } elseif ($objecttype == 'shipping') {
                        $classpath = 'expedition/class';
                        $subelement = 'expedition';
                        $module = 'expedition_bon';
                    } elseif ($objecttype == 'delivery') {
                        $classpath = 'delivery/class';
                        $subelement = 'delivery';
                        $module = 'delivery_note';
                    } elseif ($objecttype == 'invoice_supplier' || $objecttype == 'order_supplier') {
                        $classpath = 'fourn/class';
                        $module = 'fournisseur';
                    } elseif ($objecttype == 'fichinter') {
                        $classpath = 'fichinter/class';
                        $subelement = 'fichinter';
                        $module = 'ficheinter';
                    } elseif ($objecttype == 'subscription') {
                        $classpath = 'adherents/class';
                        $module = 'adherent';
                    } elseif ($objecttype == 'contact') {
                        $module = 'societe';
                    }
                    // Set classfile
                    $classfile = strtolower($subelement);
                    $classname = ucfirst($subelement);

                    if ($objecttype == 'order') {
                        $classfile = 'commande';
                        $classname = 'Commande';
                    } elseif ($objecttype == 'invoice_supplier') {
                        $classfile = 'fournisseur.facture';
                        $classname = 'FactureFournisseur';
                    } elseif ($objecttype == 'order_supplier') {
                        $classfile = 'fournisseur.commande';
                        $classname = 'CommandeFournisseur';
                    } elseif ($objecttype == 'supplier_proposal') {
                        $classfile = 'supplier_proposal';
                        $classname = 'SupplierProposal';
                    } elseif ($objecttype == 'facturerec') {
                        $classfile = 'facture-rec';
                        $classname = 'FactureRec';
                    } elseif ($objecttype == 'subscription') {
                        $classfile = 'subscription';
                        $classname = 'Subscription';
                    } elseif ($objecttype == 'project' || $objecttype == 'projet') {
                        $classpath = 'projet/class';
                        $classfile = 'project';
                        $classname = 'Project';
                    } elseif ($objecttype == 'conferenceorboothattendee') {
                        $classpath = 'eventorganization/class';
                        $classfile = 'conferenceorboothattendee';
                        $classname = 'ConferenceOrBoothAttendee';
                        $module = 'eventorganization';
                    } elseif ($objecttype == 'conferenceorbooth') {
                        $classpath = 'eventorganization/class';
                        $classfile = 'conferenceorbooth';
                        $classname = 'ConferenceOrBooth';
                        $module = 'eventorganization';
                    } elseif ($objecttype == 'mo') {
                        $classpath = 'mrp/class';
                        $classfile = 'mo';
                        $classname = 'Mo';
                        $module = 'mrp';
                    }

                    // Here $module, $classfile and $classname are set, we can use them.
                    if ($conf->$module->enabled && (($element != $this->element) || $alsosametype)) {
                        if ($loadalsoobjects && (is_numeric($loadalsoobjects) || ($loadalsoobjects === $objecttype))) {
                            dol_include_once('/' . $classpath . '/' . $classfile . '.class.php');
                            //print '/'.$classpath.'/'.$classfile.'.class.php '.class_exists($classname);
                            if (class_exists($classname)) {
                                foreach ($objectids as $i => $objectid) {    // $i is rowid into llx_element_element
                                    $object = new $classname($this->db);
                                    $ret = $object->fetch($objectid);
                                    if ($ret >= 0) {
                                        $this->linkedObjects[$objecttype][$i] = $object;
                                    }
                                }
                            }
                        }
                    } else {
                        unset($this->linkedObjectsIds[$objecttype]);
                    }
                }
            }
            return 1;
        } else {
            dol_print_error($this->db);
            return -1;
        }
    }


    /**
     *    Delete all links between an object $this
     *
     * @param int $sourceid Object source id
     * @param string $sourcetype Object source type
     * @param int $targetid Object target id
     * @param string $targettype Object target type
     * @param int $rowid Row id of line to delete. If defined, other parameters are not used.
     * @param User $f_user User that create
     * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
     * @return                        int    >0 if OK, <0 if KO
     * @see    add_object_linked(), updateObjectLinked(), fetchObjectLinked()
     */
    public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0)
    {
        global $user;
        $deletesource = false;
        $deletetarget = false;
        $f_user = isset($f_user) ? $f_user : $user;

        if (!empty($sourceid) && !empty($sourcetype) && empty($targetid) && empty($targettype)) {
            $deletesource = true;
        } elseif (empty($sourceid) && empty($sourcetype) && !empty($targetid) && !empty($targettype)) {
            $deletetarget = true;
        }

        $sourceid = (!empty($sourceid) ? $sourceid : $this->id);
        $sourcetype = (!empty($sourcetype) ? $sourcetype : $this->element);
        $targetid = (!empty($targetid) ? $targetid : $this->id);
        $targettype = (!empty($targettype) ? $targettype : $this->module . "_" . $this->element);
        $this->db->begin();
        $error = 0;

        if (!$notrigger) {
            // Call trigger
            $this->context['link_id'] = $rowid;
            $this->context['link_source_id'] = $sourceid;
            $this->context['link_source_type'] = $sourcetype;
            $this->context['link_target_id'] = $targetid;
            $this->context['link_target_type'] = $targettype;
            $result = $this->call_trigger('OBJECT_LINK_DELETE', $f_user);
            if ($result < 0) {
                $error++;
            }
            // End call triggers
        }

        if (!$error) {
            $sql = "DELETE FROM " . MAIN_DB_PREFIX . "element_element";
            $sql .= " WHERE";
            if ($rowid > 0) {
                $sql .= " rowid = " . ((int)$rowid);
            } else {
                if ($deletesource) {
                    $sql .= " fk_source = " . ((int)$sourceid) . " AND sourcetype = '" . $this->db->escape($sourcetype) . "'";
                    $sql .= " AND fk_target = " . ((int)$this->id) . " AND targettype = '" . $this->db->escape($targettype) . "'";
                } elseif ($deletetarget) {
                    $sql .= " fk_target = " . ((int)$targetid) . " AND targettype = '" . $this->db->escape($targettype) . "'";
                    $sql .= " AND fk_source = " . ((int)$this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "'";
                } else {
                    $sql .= " (fk_source = " . ((int)$this->id) . " AND sourcetype = '" . $this->db->escape($this->element) . "')";
                    $sql .= " OR";
                    $sql .= " (fk_target = " . ((int)$this->id) . " AND targettype = '" . $this->db->escape($this->element) . "')";
                }
            }
            dol_syslog(get_class($this) . "::deleteObjectLinked", LOG_DEBUG);
            if (!$this->db->query($sql)) {
                $this->error = $this->db->lasterror();
                $this->errors[] = $this->error;
                $error++;
            }
        }

        if (!$error) {
            $this->db->commit();
            return 1;
        } else {
            $this->db->rollback();
            return 0;
        }
    }


    public function setStatutTransit($user, $notrigger = 0)
    {
        global $langs;
        // Protection
        if ($this->status != self::STATUS_RESERVE) {
            return 0;
        }
        $sql = "UPDATE " . MAIN_DB_PREFIX . $this->table_element;
        $sql .= " SET status = " . ((int)self::STATUS_TRANSIT);
        $sql .= " WHERE rowid = " . ((int)$this->id);
        $resql = $this->db->query($sql);
        if ($resql) {
            return 1;
        } else {
            return -1;
        }
        return -2;
    }

}



