<?php
/* Copyright (C) 2004-2018  Laurent Destailleur     <eldy@users.sourceforge.net>
 * Copyright (C) 2018-2019  Nicolas ZABOURI         <info@inovea-conseil.com>
 * Copyright (C) 2019       Frédéric France         <frederic.france@netlogic.fr>
 * Copyright (C) 2020       MB Informatique         <info@mb-informatique.fr>
 *
 * 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/>.
 */

/**
 * 	\defgroup   mbisignature     Module MBISignature
 *  \brief      MBISignature module descriptor.
 *
 *  \file       mbisignature/core/modules/modMBISignature.class.php
 *  \ingroup    mbisignature
 *  \brief      Description and activation file for module MBISignature
 */
include_once DOL_DOCUMENT_ROOT.'/core/modules/DolibarrModules.class.php';

/**
 *  Description and activation class for module MBISignature
 */
class modMBISignature extends DolibarrModules
{
    /**
     * Constructor. Define names, constants, directories, boxes, permissions
     *
     * @param DoliDB $db Database handler
     */
    public function __construct($db)
    {
        global $langs, $conf;
        $this->db = $db;
        $this->numero = 172350;
        $this->rights_class = 'mbisignature';
        $this->family = "MB Informatique";
        $this->module_position = '90';
        $this->name = preg_replace('/^mod/i', '', get_class($this));
        $this->description = "MBISignatureDescription";
        $this->descriptionlong = "MBISignature description (Long)";
        $this->editor_name = 'MB Informatique';
        $this->editor_url = 'https://www.mb-informatique.fr';
        $this->version = '1.12.1';
        $this->url_last_version = 'https://activation.mb-informatique.com/latest?module=' . $this->rights_class . '&get=name';
        $this->url_activation = 'https://activation.mb-informatique.com/activation';
        $this->const_name = 'MAIN_MODULE_'.strtoupper($this->name);
        $this->picto = 'logo@mbisignature';
        $this->module_parts = array(
            'triggers' => 1,
            'login' => 0,
            'substitutions' => 1,
            'menus' => 0,
            'tpl' => 0,
            'barcode' => 0,
            'models' => 1,
            'theme' => 0,
            'css' => array(),
            'js' => array(),
            'hooks' => array('propalcard', 'ordercard', 'expeditioncard', 'interventioncard', 'contractcard', 'thirdpartycard', 'ordersuppliercard', 'toprightmenu', 'expensereportcard', 'deliverycard'),
            'moduleforexternal' => 0,
        );
        $this->dirs = array("/mbisignature/temp");
        $this->config_page_url = array("setup.php@mbisignature");
        // Dependencies
        $this->hidden = false;
        // List of module class names as string that must be enabled if this module is enabled. Example: array('always1'=>'modModuleToEnable1','always2'=>'modModuleToEnable2', 'FR1'=>'modModuleToEnableFR'...)
        $this->depends = array();
        $this->requiredby = array(); // List of module class names as string to disable if this one is disabled. Example: array('modModuleToDisable1', ...)
        $this->conflictwith = array(); // List of module class names as string this module is in conflict with. Example: array('modModuleToDisable1', ...)
        $this->langfiles = array("mbisignature@mbisignature");
        $this->phpmin = array(5, 5);
        $this->need_dolibarr_version = array(8, 0);
        $this->warnings_activation = array("always"=>"By activating this module, I declare that I have read the End-User License Agreement - En activant ce module, je déclare avoir pris connaissance des Conditions Générales d'Utilisation"); // Warning to show when we activate module. array('always'='text') or array('FR'='textfr','ES'='textes'...)
        $this->warnings_activation_ext = array();
        $this->const = array();

        if (!isset($conf->mbisignature) || !isset($conf->mbisignature->enabled)) {
            $conf->mbisignature = new stdClass();
            $conf->mbisignature->enabled = 0;
        }

        $this->tabs = array();
        $this->dictionaries = array();
        $this->boxes = array();
        $this->cronjobs = array();
        $langs->load("mbisignature@mbisignature");
        $this->rights = array();
        $this->menu = array();
    }

    /**
     *  Function called when module is enabled.
     *  The init function add constants, boxes, permissions and menus (defined in constructor) into Dolibarr database.
     *  It also creates data directories
     *
     *  @param      string  $options    Options when enabling module ('', 'noboxes')
     *  @return     int             	1 if OK, 0 if KO
     */
    public function init($options = '')
    {
        global $conf, $langs;
        $langs->load("mbisignature@mbisignature");
        $result = $this->_load_tables('/mbisignature/sql/');
        if ($result < 0) return -1; // Do not activate module if error 'not allowed' returned when loading module SQL queries (the _load_table run sql with run_sql with the error allowed parameter set to 'default')

        // Permissions
        $this->remove($options, 0);

        $sql=array("INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_CONFIRMATION_MAIL', '" . $langs->trans('OPTION1') . "', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('DOUBLE_SIGNATURE', 'false', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_TEMPLATE', '" . $langs->trans('SIGNATURE_DEFAULT_TEMPLATE') . "', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_URL', '" . DOL_MAIN_URL_ROOT . "', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_DOC_PATH', '" . DOL_DATA_ROOT . "', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_PROPAL', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_ORDER', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_ORDER_SUPPLIER', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_EXPEDITION', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_INTERVENTION', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_DELIVERY', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_CONTRACT', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_SEPA_MANDATE', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_HOLIDAY', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_ENABLE_EXPENSE_REPORT', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_DISPLAY_NAME', 'false', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_SOCIAL_LINKS', 'false', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_DOCUMENT_PREVIEW', 'false', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_USE_CERTIFICATE', 'false', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_CRT', '" . DOL_DATA_ROOT . "/mycompany/certificate.crt', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_CRT_PRIVATE_KEY', '" . DOL_DATA_ROOT . "/mycompany/private.key', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_CUSTOM_RIBBON_COLOR', 'ff0000', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_CUSTOM_LINE_COLOR', '1e90ff', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_CUSTOM_CHECKBOX_COLOR', '26a69a', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_DISPLAY_LINE_AND_RIBBON', 'true', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_TEMPLATE_SUBJECT', '" . $langs->trans("Validé") . " {REF}', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_PROPAL_CAN_BE_REFUSED', 'false', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_COMPANY_STAMP', '" . DOL_DATA_ROOT . "/mycompany/stamp.png', " . $conf->entity . ")", "INSERT IGNORE INTO " . MAIN_DB_PREFIX . "const (name, value, entity) VALUES ('SIGNATURE_DISPLAY_COMMENT_SECTION', 'false', " . $conf->entity . ")");

        include_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
        $extrafields = new ExtraFields($this->db);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'propal', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'commande', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'commande_fournisseur', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'expedition', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'fichinter', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'contrat', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'societe', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'holiday', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'expensereport', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);
        $extrafields->addExtraField('signature_link', $langs->trans('Signaturelink'), 'text', 100, '2000', 'delivery', 0, 0, '', '', 0, '', '1', '', '', $conf->entity, '', '1', 0, 0);

        return $this->_init($sql, $options);
    }

    /**
     *  Function called when module is disabled.
     *  Remove from database constants, boxes and permissions from Dolibarr database.
     *  Data directories are not deleted
     *
     *  @param      string	$options    Options when enabling module ('', 'noboxes')
     *  @return     int                 1 if OK, 0 if KO
     */
    public function remove($options = '', $check_server = 1)
    {
        global $conf, $langs, $db;
        $langs->load("mbisignature@mbisignature");
        $opts = array('http' =>
            array(
                'method'  => 'POST',
                'timeout' => 4,
                'header'  => 'Content-Type: application/x-www-form-urlencoded',
                'content' => http_build_query(
                    array(
                        'token' => newToken(),
                        'action' => 'd4b996faf874c161947a7b9fcaa693d6ef4ce46c8d86d2202589eccb78c955880dcbde255d9415964611a2a899e61325eaf6cfa1dbca6ba3542c332576243001',
                        'order_ref' => $conf->global->MBI_SIGNATURE_ORDER_REF,
                        'licence' => $conf->global->MBI_SIGNATURE_LICENCE,
                        'instance_id' => substr($conf->file->instance_unique_id, 0, 20),
                        'product' => $langs->trans('ModuleMBISignatureName')
                    )
                )
            )
        );

        if ($check_server === 1) {
            $result = @file_get_contents($this->url_activation, false, stream_context_create($opts));
        } else {
            $result = true;
        }
        if ($result === false) {
            setEventMessage($langs->trans("MBI_ACTIVATION_SERVER_NOT_AVAILABLE"), "errors");
            return 0;
        } else {
            dolibarr_del_const($db, "MBI_SIGNATURE_ORDER_REF", -1);
            dolibarr_del_const($db, "MBI_SIGNATURE_LICENCE", -1);
        }
        $sql = array();
        return $this->_remove($sql, $options);
    }
}
