diff --git a/htdocs/core/lib/security.lib.php b/htdocs/core/lib/security.lib.php
index d0b32123977..59a88cbd77b 100644
--- a/htdocs/core/lib/security.lib.php
+++ b/htdocs/core/lib/security.lib.php
@@ -626,6 +626,11 @@ function restrictedArea(User $user, $features, $object = 0, $tableandshare = '',
$readok = 0;
$nbko++;
}
+ } elseif ($feature == 'webhook') {
+ if (empty($user->admin)) {
+ $readok = 0;
+ $nbko++;
+ }
} elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->read)
$tmpreadok = 1;
foreach ($feature2 as $subfeature) {
@@ -727,6 +732,11 @@ function restrictedArea(User $user, $features, $object = 0, $tableandshare = '',
$createok = 0;
$nbko++;
}
+ } elseif ($feature == 'webhook') {
+ if (empty($user->admin)) {
+ $createok = 0;
+ $nbko++;
+ }
} elseif (!empty($feature2)) { // This is for permissions on 2 levels (module->object->write)
foreach ($feature2 as $subfeature) {
if ($subfeature == 'user' && $user->id == $objectid && $user->hasRight('user', 'self', 'creer')) {
@@ -990,7 +1000,7 @@ function checkUserAccessToObject($user, array $featuresarray, $object = 0, $tabl
$checktask = array('projet_task'); // Test for task object
$checkhierarchy = array('expensereport', 'holiday'); // check permission among the hierarchy of user
$checkuser = array('bookmark'); // check permission among the fk_user (must be myself or null)
- $nocheck = array('barcode', 'stock'); // No test
+ $nocheck = array('barcode', 'stock', 'webhook'); // No test
//$checkdefault = 'all other not already defined'; // Test on entity + link to third party on field $dbt_keyfield. Not allowed if link is empty (Ex: invoice, orders...).
diff --git a/htdocs/core/modules/modWebhook.class.php b/htdocs/core/modules/modWebhook.class.php
index 2d2a62d0c8e..cbac1ef664a 100644
--- a/htdocs/core/modules/modWebhook.class.php
+++ b/htdocs/core/modules/modWebhook.class.php
@@ -261,21 +261,6 @@ class modWebhook extends DolibarrModules
$r = 0;
// Add here entries to declare new permissions
/* BEGIN MODULEBUILDER PERMISSIONS */
- $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used)
- $this->rights[$r][1] = 'Read Webhooks'; // Permission label
- $this->rights[$r][4] = 'webhook_target';
- $this->rights[$r][5] = 'read'; // In php code, permission will be checked by test if ($user->rights->webhook->webhook_target->read)
- $r++;
- $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used)
- $this->rights[$r][1] = 'Create/Update Webhooks'; // Permission label
- $this->rights[$r][4] = 'webhook_target';
- $this->rights[$r][5] = 'write'; // In php code, permission will be checked by test if ($user->rights->webhook->webhook_target->write)
- $r++;
- $this->rights[$r][0] = $this->numero . sprintf("%02d", $r + 1); // Permission id (must not be already used)
- $this->rights[$r][1] = 'Delete Webhooks'; // Permission label
- $this->rights[$r][4] = 'webhook_target';
- $this->rights[$r][5] = 'delete'; // In php code, permission will be checked by test if ($user->rights->webhook->webhook_target->delete)
- $r++;
/* END MODULEBUILDER PERMISSIONS */
// Main menu entries to add
diff --git a/htdocs/core/triggers/interface_95_modWebhook_WebhookTriggers.class.php b/htdocs/core/triggers/interface_95_modWebhook_WebhookTriggers.class.php
index ab85678c9ec..46dd1fdfd91 100644
--- a/htdocs/core/triggers/interface_95_modWebhook_WebhookTriggers.class.php
+++ b/htdocs/core/triggers/interface_95_modWebhook_WebhookTriggers.class.php
@@ -33,6 +33,7 @@
require_once DOL_DOCUMENT_ROOT.'/core/triggers/dolibarrtriggers.class.php';
require_once DOL_DOCUMENT_ROOT.'/webhook/class/target.class.php';
+require_once DOL_DOCUMENT_ROOT.'/webhook/class/triggerhistory.class.php';
/**
* Class of triggers for Webhook module
@@ -77,6 +78,7 @@ class InterfaceWebhookTriggers extends DolibarrTriggers
// Or you can execute some code here
$nbPosts = 0;
$errors = 0;
+ $errorforhistory = 0;
$static_object = new Target($this->db);
$target_url = $static_object->fetchAll(); // TODO Replace this with a search with filter on $action trigger to avoid to filter later.
@@ -133,10 +135,12 @@ class InterfaceWebhookTriggers extends DolibarrTriggers
// warning; the test page use its own call
$response = getURLContent($tmpobject->url, $method, $jsonstr, 1, $headers, array('http', 'https'), 2, -1);
+ $errormsg = "";
if (empty($response['curl_error_no']) && $response['http_code'] >= 200 && $response['http_code'] < 300) {
$nbPosts++;
} else {
$errormsg = "The WebHook for ".$action." failed to get URL ".$tmpobject->url." with httpcode=".(!empty($response['http_code']) ? $response['http_code'] : "")." curl_error_no=".(!empty($response['curl_error_no']) ? $response['curl_error_no'] : "");
+ $errorforhistory ++;
if ($tmpobject->type == Target::TYPE_BLOCKING) {
$errors++;
@@ -150,6 +154,19 @@ class InterfaceWebhookTriggers extends DolibarrTriggers
$this->errors[] = dol_trunc($response['content'], 200);
}*/
}
+
+ $triggerhistory = new TriggerHistory($this->db);
+ $triggerhistory->trigger_code = $action;
+ $triggerhistory->trigger_data = $jsonstr;
+ $triggerhistory->fk_target = $tmpobject->id;
+ $triggerhistory->url = $tmpobject->url;
+ $triggerhistory->error_message = $errormsg;
+ $triggerhistory->status = ($errorforhistory == 0 ? 1 : -1);
+ $resql = $triggerhistory->create($user);
+ if (!$resql) {
+ $errors++;
+ $this->errors = array_merge($this->errors, $triggerhistory->errors);
+ }
}
}
diff --git a/htdocs/langs/en_US/admin.lang b/htdocs/langs/en_US/admin.lang
index 1f093b43ae5..ee7d8319b16 100644
--- a/htdocs/langs/en_US/admin.lang
+++ b/htdocs/langs/en_US/admin.lang
@@ -2475,6 +2475,7 @@ ScriptIsEmpty=The script is empty
ShowHideTheNRequests=Show/hide the %s SQL request(s)
DefinedAPathForAntivirusCommandIntoSetup=Define a path for an antivirus program into %s
TriggerCodes=Triggerable events
+TriggerCode=Triggerable event
TriggerCodeInfo=Enter here the trigger code(s) that must generate a post of a web request (only external URL are allowed). You can enter several trigger codes separated by a comma.
EditableWhenDraftOnly=If unchecked, the value can only be modified when object has a draft status
PermissionToEditField=Overwrite the permissions to edit the field. Keeping empty (default) will check the permission to create/update the object.
@@ -2682,6 +2683,11 @@ ByDefault=By default
Sources=Sources
XYearSupport=%s-year support
CacheForTranslationIsUsed=Warning, translation files seems loaded into a cache system. If you force some translations from here, think to reset the cache to have the change effective.
+TriggerData=Data sent to URL
+ErrorMessage=Error message received
+TriggerHistory=Trigger history
+ShowTriggerHistory=Show trigger history
+DeleteTriggereHistoryRecord=Delete trigger history record
MAIN_ENABLE_AJAX_TOOLTIP=Use Ajax lazy load of tooltip content with Ajax
MAIN_CACHE_COUNT=Keep the count of elements visible into badges in a cache (value may need several minutes to be up to date)
MAIN_DO_FETCH_IN_ONE_SQL_REQUEST=Load content of object and lines into one request
diff --git a/htdocs/webhook/class/triggerhistory.class.php b/htdocs/webhook/class/triggerhistory.class.php
new file mode 100644
index 00000000000..a614a6191ad
--- /dev/null
+++ b/htdocs/webhook/class/triggerhistory.class.php
@@ -0,0 +1,918 @@
+
+ * Copyright (C) 2023-2024 Frédéric France
+ * Copyright (C) 2025 Alice Adminson
+ *
+ * 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 .
+ */
+
+/**
+ * \file class/triggerhistory.class.php
+ * \ingroup webhook
+ * \brief This file is a CRUD class file for (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';
+
+/**
+ * Class for
+ */
+class TriggerHistory extends CommonObject
+{
+ /**
+ * @var string ID of module.
+ */
+ public $module = 'webhook';
+
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'webhook_triggerhistory';
+
+ /**
+ * @var string Name of table without prefix where object is stored. This is also the key used for extrafields management (so extrafields know the link to the parent table).
+ */
+ public $table_element = 'webhook_history';
+
+ /**
+ * @var string If permission must be checkec with hasRight('webhook', 'read') and not hasright('mymodyle', 'triggerhistory', 'read'), you can uncomment this line
+ */
+ //public $element_for_permission = 'webhook';
+
+ /**
+ * @var string String with name of icon for triggerhistory. Must be a 'fa-xxx' fontawesome code (or 'fa-xxx_fa_color_size') or 'triggerhistory@webhook' if picto is file 'img/object_history.png'.
+ */
+ public $picto = 'fa-calendar-alt';
+
+
+ const STATUS_SUCCESS = 1;
+ const STATUS_ERROR = -1;
+
+ /**
+ * 'type' field format:
+ * 'integer', 'integer:ObjectClass:PathToClass[:AddCreateButtonOrNot[:Filter[:Sortfield]]]',
+ * 'select' (list of values are in 'options'. for integer list of values are in 'arrayofkeyval'),
+ * 'sellist:TableName:LabelFieldName[:KeyFieldName[:KeyFieldParent[:Filter[:CategoryIdType[:CategoryIdList[:SortField]]]]]]',
+ * 'chkbxlst:...',
+ * 'varchar(x)',
+ * 'text', 'text:none', 'html',
+ * 'double(24,8)', 'real', 'price', 'stock',
+ * 'date', 'datetime', 'timestamp', 'duration',
+ * 'boolean', 'checkbox', 'radio', 'array',
+ * 'mail', 'phone', 'url', 'password', 'ip'
+ * Note: Filter must be a Dolibarr Universal Filter syntax string. Example: "(t.ref:like:'SO-%') or (t.date_creation:<:'20160101') or (t.status:!=:0) or (t.nature:is:NULL)"
+ * 'length' the length of field. Example: 255, '24,8'
+ * 'label' the translation key.
+ * 'langfile' the key of the language file for translation.
+ * 'alias' the alias used into some old hard coded SQL requests
+ * '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 'getDolGlobalInt("MY_SETUP_PARAM")' or 'isModEnabled("multicurrency")' ...)
+ * '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 (not create). 5=Visible on list and view form (not create/not update). 6=visible on list and update/view form (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)
+ * 'alwayseditable' says if field can be modified also when status is not draft ('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 recommended 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'
+ * 'placeholder' to set the placeholder of a varchar field.
+ * 'help' and 'helplist' 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 like the constructor of the class.
+ * '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 you need to validate the field with $this->validateField(). Need MAIN_ACTIVATE_VALIDATION_RESULT.
+ * '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
+ /**
+ * @inheritdoc
+ * 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" => 1, "noteditable" => 1, "index" => 1, "css" => "left", "comment" => "Id"),
+ "note_private" => array("type" => "text", "label" => "NotePrivate", "enabled" => 1, 'position' => 62, 'notnull' => 0, "visible" => 0, "cssview" => "wordbreak", "validate" => 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", "picto" => "user", "enabled" => 1, 'position' => 510, 'notnull' => 1, "visible" => -2, "csslist" => "tdoverflowmax150"),
+ "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" => 2000, "notnull" => 1, 'default' => '1', "visible" => 1, "index" => 1, "arrayofkeyval" => array("1" => "Success", "-1" => "Error"), "validate" => 1),
+ "trigger_data" => array("type" => "text", "label" => "TriggerData", "enabled" => 1, 'position' => 10, 'notnull' => 1, "visible" => 1),
+ "fk_target" => array("type" => "integer:target:webhook/class/target.class.php:0:(status:=:1)", "label" => "Target", "enabled" => 1, 'position' => 20, 'notnull' => 1, "visible" => 1),
+ "url" => array("type" => "varchar(255)", "label" => "Url", "enabled" => 1, 'position' => 30, 'notnull' => 1, "visible" => 1),
+ "trigger_code" => array("type" => "varchar(128)", "label" => "TriggerCode", "enabled" => 1, 'position' => 11, 'notnull' => 1, "visible" => 1),
+ "error_message" => array("type" => "text", "label" => "ErrorMessage", "enabled" => 1, 'position' => 50, 'notnull' => 0, "visible" => 1),
+ );
+ /**
+ * @var int
+ */
+ public $rowid;
+ /**
+ * @var string
+ */
+ public $note_public;
+ /**
+ * @var string
+ */
+ public $note_private;
+ /**
+ * @var int
+ */
+ public $date_creation;
+ /**
+ * @var int
+ */
+ public $tms;
+ /**
+ * @var int
+ */
+ public $fk_user_creat;
+ /**
+ * @var string
+ */
+ public $import_key;
+ /**
+ * @var int
+ */
+ public $status;
+ /**
+ * @var string
+ */
+ public $trigger_data;
+ /**
+ * @var int
+ */
+ public $fk_target;
+ /**
+ * @var string
+ */
+ public $url;
+ /**
+ * @var string
+ */
+ public $trigger_code;
+ /**
+ * @var string
+ */
+ public $error_messsage;
+ // END MODULEBUILDER PROPERTIES
+
+
+ // If this object has a subtable with lines
+
+ // /**
+ // * @var string Name of subtable line
+ // */
+ // public $table_element_line = 'webhook_historyline';
+
+ // /**
+ // * @var string Field name with ID of parent key if this object has a parent, Or Field name of in child tables to link to this record.
+ // */
+ // public $fk_element = 'fk_history';
+
+ // /**
+ // * @var string Name of subtable class that manage subtable lines
+ // */
+ // public $class_element_line = 'Historyline';
+
+ // /**
+ // * @var array List of child tables. To test if we can delete object.
+ // */
+ // protected $childtables = array('mychildtable' => array('name'=>'', 'fk_element'=>'fk_history'));
+
+ // /**
+ // * @var array List of child tables. To know object to delete on cascade.
+ // * If name matches '@ClassName:FilePathClass:ParentFkFieldName' (the recommended mode) it will
+ // * call method ClassName->deleteByParentField(parentId, 'ParentFkFieldName') to fetch and delete child object.
+ // * Using an array like childtables should not be implemented because a child may have other child, so we must only use the method that call deleteByParentField().
+ // */
+ // protected $childtablesoncascade = array('webhook_historydet');
+
+ // /**
+ // * @var HistoryLine[] Array of subtable lines
+ // */
+ // public $lines = array();
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $langs;
+
+ $this->db = $db;
+ $this->ismultientitymanaged = 0;
+ $this->isextrafieldmanaged = 1;
+
+ if (!getDolGlobalInt('MAIN_SHOW_TECHNICAL_ID') && isset($this->fields['rowid']) && !empty($this->fields['ref'])) {
+ $this->fields['rowid']['visible'] = 0;
+ }
+ if (!isModEnabled('multicompany') && isset($this->fields['entity'])) {
+ $this->fields['entity']['enabled'] = 0;
+ }
+
+ // Example to show how to set values of fields definition dynamically
+ /*if ($user->hasRight('webhook', 'triggerhistory', 'read')) {
+ $this->fields['myfield']['visible'] = 1;
+ $this->fields['myfield']['noteditable'] = 0;
+ }*/
+
+ // 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 int<0,1> $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int<-1,max> Return integer <0 if KO, Id of created object if OK
+ */
+ public function create(User $user, $notrigger = 0)
+ {
+ $result = $this->createCommon($user, $notrigger);
+
+ // uncomment lines below if you want to validate object after creation
+ // if ($result > 0) {
+ // $this->fetch($this->id); // needed to retrieve some fields (ie date_creation for masked ref)
+ // $resultupdate = $this->validate($user, $notrigger);
+ // if ($resultupdate < 0) { return $resultupdate; }
+ // }
+
+ return $result;
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $ref Ref
+ * @param int<0,1> $noextrafields 0=Default to load extrafields, 1=No extrafields
+ * @param int<0,1> $nolines 0=Default to load lines, 1=No lines
+ * @return int<-1,1> Return integer <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $ref = null, $noextrafields = 0, $nolines = 0)
+ {
+ $result = $this->fetchCommon($id, $ref, '', $noextrafields);
+ if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) {
+ $this->fetchLines($noextrafields);
+ }
+ return $result;
+ }
+
+ /**
+ * Load object lines in memory from the database
+ *
+ * @param int<0,1> $noextrafields 0=Default to load extrafields, 1=No extrafields
+ * @return int<-1,1> Return integer <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetchLines($noextrafields = 0)
+ {
+ $this->lines = array();
+
+ $result = $this->fetchLinesCommon('', $noextrafields);
+ return $result;
+ }
+
+
+ /**
+ * Load list of objects in memory from the database.
+ * Using a fetchAll() with limit = 0 is a very bad practice. Instead try to forge yourself an optimized SQL request with
+ * your own loop with start and stop pagination.
+ *
+ * @param string $sortorder Sort Order
+ * @param string $sortfield Sort field
+ * @param int<0,max> $limit Limit the number of lines returned
+ * @param int<0,max> $offset Offset
+ * @param string $filter Filter as an Universal Search string.
+ * Example: '((client:=:1) OR ((client:>=:2) AND (client:<=:3))) AND (client:!=:8) AND (nom:like:'a%')'
+ * @param string $filtermode No longer used
+ * @return array|int<-1,-1> <0 if KO, array of pages if OK
+ */
+ public function fetchAll($sortorder = '', $sortfield = '', $limit = 1000, $offset = 0, string $filter = '', $filtermode = 'AND')
+ {
+ dol_syslog(__METHOD__, LOG_DEBUG);
+
+ $records = array();
+
+ $sql = "SELECT ";
+ $sql .= $this->getFieldList('t');
+ $sql .= " FROM ".$this->db->prefix().$this->table_element." as t";
+ if ($this->isextrafieldmanaged == 1) {
+ $sql .= " LEFT JOIN ".$this->db->prefix().$this->table_element."_extrafields as te ON te.fk_object = t.rowid";
+ }
+ if ($this->ismultientitymanaged == 1) {
+ $sql .= " WHERE t.entity IN (".getEntity($this->element).")";
+ } else {
+ $sql .= " WHERE 1 = 1";
+ }
+
+ // Manage filter
+ $errormessage = '';
+ $sql .= forgeSQLFromUniversalSearchCriteria($filter, $errormessage);
+ if ($errormessage) {
+ $this->errors[] = $errormessage;
+ dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
+ return -1;
+ }
+
+ 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);
+
+ if (!empty($record->isextrafieldmanaged)) {
+ $record->fetch_optionals();
+ }
+
+ $records[$record->id] = $record;
+
+ $i++;
+ }
+ $this->db->free($resql);
+
+ return $records;
+ } else {
+ $this->errors[] = 'Error '.$this->db->lasterror();
+ dol_syslog(__METHOD__.' '.implode(',', $this->errors), LOG_ERR);
+
+ return -1;
+ }
+ }
+
+ /**
+ * Update object into database
+ *
+ * @param User $user User that modifies
+ * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int<-1,1> Return integer <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = 0)
+ {
+ return $this->updateCommon($user, $notrigger);
+ }
+
+ /**
+ * Delete object in database
+ *
+ * @param User $user User that deletes
+ * @param int<0,1> $notrigger 0=launch triggers, 1=disable triggers
+ * @return int<-1,1> Return integer <0 if KO, >0 if OK
+ */
+ public function delete(User $user, $notrigger = 0)
+ {
+ return $this->deleteCommon($user, $notrigger);
+ //return $this->deleteCommon($user, $notrigger, 1);
+ }
+
+ /**
+ * Delete a line of object in database
+ *
+ * @param User $user User that delete
+ * @param int $idline Id of line to delete
+ * @param int<0,1> $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int<-2,1> >0 if OK, <0 if KO
+ */
+ public function deleteLine(User $user, $idline, $notrigger = 0)
+ {
+ if ($this->status < 0) {
+ $this->error = 'ErrorDeleteLineNotAllowedByObjectStatus';
+ return -2;
+ }
+
+ return $this->deleteLineCommon($user, $idline, $notrigger);
+ }
+
+ /**
+ * Set draft status
+ *
+ * @param User $user Object user that modify
+ * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int<0,1> Return integer <0 if KO, >0 if OK
+ */
+ public function setDraft($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status <= self::STATUS_SUCCESS) {
+ return 0;
+ }
+
+ /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('webhook','write'))
+ || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('webhook','webhook_advance','validate'))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_ERROR, $notrigger, 'WEBHOOK_MYOBJECT_UNVALIDATE');
+ }
+
+ /**
+ * Set cancel status
+ *
+ * @param User $user Object user that modify
+ * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int<-1,1> Return integer <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function cancel($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status != self::STATUS_SUCCESS) {
+ return 0;
+ }
+
+ /* if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('webhook','write'))
+ || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('webhook','webhook_advance','validate'))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_ERROR, $notrigger, 'WEBHOOK_MYOBJECT_CANCEL');
+ }
+
+ /**
+ * Set back to validated status
+ *
+ * @param User $user Object user that modify
+ * @param int<0,1> $notrigger 1=Does not execute triggers, 0=Execute triggers
+ * @return int<-1,1> Return integer <0 if KO, 0=Nothing done, >0 if OK
+ */
+ public function reopen($user, $notrigger = 0)
+ {
+ // Protection
+ if ($this->status == self::STATUS_SUCCESS) {
+ return 0;
+ }
+
+ /*if (! ((!getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('webhook','write'))
+ || (getDolGlobalInt('MAIN_USE_ADVANCED_PERMS') && $user->hasRight('webhook','webhook_advance','validate'))))
+ {
+ $this->error='Permission denied';
+ return -1;
+ }*/
+
+ return $this->setStatusCommon($user, self::STATUS_SUCCESS, $notrigger, 'WEBHOOK_MYOBJECT_REOPEN');
+ }
+
+ /**
+ * getTooltipContentArray
+ *
+ * @param array $params Params to construct tooltip data
+ * @since v18
+ * @return array{optimize?:string,picto?:string,ref?:string}
+ */
+ public function getTooltipContentArray($params)
+ {
+ global $langs;
+
+ $datas = [];
+
+ if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
+ return ['optimize' => $langs->trans("ShowTriggerHistory")];
+ }
+ $datas['picto'] = img_picto('', $this->picto).' '.$langs->trans("").'';
+ $datas['picto'] .= ' '.$this->getLibStatut(5);
+ return $datas;
+ }
+
+ /**
+ * Return a link to the object card (with optionally 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 = '';
+ $params = [
+ 'id' => (string) $this->id,
+ 'objecttype' => $this->element.($this->module ? '@'.$this->module : ''),
+ 'option' => $option,
+ ];
+ $classfortooltip = 'classfortooltip';
+ $dataparams = '';
+ $label = img_picto('', $this->picto).' '.$langs->trans("TriggerHistory").'';
+ $label .= ' '.$this->getLibStatut(5);
+ $label .= ' ';
+ $label .= ''.$langs->trans('Ref').': '.$this->ref;
+ $url = dol_buildpath('/webhook/triggerhistory_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 && isset($_SERVER["PHP_SELF"]) && preg_match('/list\.php/', $_SERVER["PHP_SELF"])) {
+ $add_save_lastsearch_values = 1;
+ }
+ if ($add_save_lastsearch_values) {
+ $url .= '&save_lastsearch_values=1';
+ }
+ }
+
+ $linkclose = '';
+ if (empty($notooltip)) {
+ if (getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER')) {
+ $label = $langs->trans("ShowTriggerHistory");
+ $linkclose .= ' alt="'.dolPrintHTMLForAttribute($label).'"';
+ }
+ $linkclose .= ($label ? ' title="'.dolPrintHTMLForAttribute($label).'"' : ' title="tocomplete"');
+ $linkclose .= $dataparams.' class="'.$classfortooltip.($morecss ? ' '.$morecss : '').'"';
+ } else {
+ $linkclose = ($morecss ? ' class="'.$morecss.'"' : '');
+ }
+
+ if ($option == 'nolink') {
+ $linkstart = '';
+ if ($option == 'nolink') {
+ $linkend = '';
+ } else {
+ $linkend = '';
+ }
+
+ $result .= $linkstart;
+
+ if (empty($this->showphoto_on_popup)) {
+ if ($withpicto) {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), (($withpicto != 2) ? 'class="paddingright"' : ''), 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 (!getDolGlobalString(strtoupper($module.'_'.$class).'_FORMATLISTPHOTOSASUSERS')) {
+ $result .= '
';
+ } else {
+ $result .= '
';
+ }
+
+ $result .= '';
+ } else {
+ $result .= img_object(($notooltip ? '' : $label), ($this->picto ? $this->picto : 'generic'), ($notooltip ? (($withpicto != 2) ? 'class="paddingright"' : '') : 'class="'.(($withpicto != 2) ? 'paddingright ' : '').'"'), 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($this->element.'dao'));
+ $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 a thumb for kanban views
+ *
+ * @param string $option Where point the link (0=> main card, 1,2 => shipment, 'nolink'=>No link)
+ * @param ?array $arraydata Array of data
+ * @return string HTML Code for Kanban thumb.
+ */
+ public function getKanbanView($option = '', $arraydata = null)
+ {
+ global $conf, $langs;
+
+ $selected = (empty($arraydata['selected']) ? 0 : $arraydata['selected']);
+
+ $return = '
'."\n";
+
+ // Common attributes
+ //$keyforbreak='fieldkeytoswitchonsecondcolumn'; // We change column just before this field
+ //unset($object->fields['fk_project']); // Hide field already shown in banner
+ //unset($object->fields['fk_soc']); // Hide field already shown in banner
+ include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_view.tpl.php';
+
+ // Other attributes. Fields from hook formObjectOptions and Extrafields.
+ include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
+
+ print '