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 .= '
No photo
'; + } else { + $result .= '
No photo
'; + } + + $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 = '
'; + $return .= '
'; + $return .= ''; + $return .= img_picto('', $this->picto); + $return .= ''; + $return .= '
'; + $return .= ''.$this->getNomUrl().''; + if ($selected >= 0) { + $return .= ''; + } + if (is_object($this->thirdparty)) { + $return .= '
'.$this->thirdparty->getNomUrl(1).'
'; + } + /*if (property_exists($this, 'amount')) { + $return .= '
'; + $return .= ''.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).''; + }*/ + $return .= '
'.$this->getLibStatut(3).'
'; + $return .= '
'; + $return .= '
'; + $return .= '
'; + + return $return; + } + + /** + * Return the label of the status + * + * @param int<0,6> $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<0,6> $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 label of a given status + * + * @param int $status Id status + * @param int<0,6> $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 (is_null($status)) { + return ''; + } + + if (empty($this->labelStatus) || empty($this->labelStatusShort)) { + global $langs; + //$langs->load("webhook@webhook"); + $this->labelStatus[self::STATUS_SUCCESS] = $langs->transnoentitiesnoconv('Success'); + $this->labelStatus[self::STATUS_ERROR] = $langs->transnoentitiesnoconv('Error'); + $this->labelStatusShort[self::STATUS_SUCCESS] = $langs->transnoentitiesnoconv('Success'); + $this->labelStatusShort[self::STATUS_ERROR] = $langs->transnoentitiesnoconv('Error'); + } + + $statusType = 'status'.$status; + if ($status == self::STATUS_SUCCESS) { + $statusType = 'status4'; + } + if ($status == self::STATUS_ERROR) { + $statusType = 'status8'; + } + + 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,"; + $sql .= " date_creation as datec, tms as datem"; + if (!empty($this->fields['date_validation'])) { + $sql .= ", date_validation as datev"; + } + if (!empty($this->fields['fk_user_creat'])) { + $sql .= ", fk_user_creat"; + } + if (!empty($this->fields['fk_user_modif'])) { + $sql .= ", fk_user_modif"; + } + if (!empty($this->fields['fk_user_valid'])) { + $sql .= ", fk_user_valid"; + } + $sql .= " FROM ".$this->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($this->fields['fk_user_creat'])) { + $this->user_creation_id = $obj->fk_user_creat; + } + if (!empty($this->fields['fk_user_modif'])) { + $this->user_modification_id = $obj->fk_user_modif; + } + if (!empty($this->fields['fk_user_valid'])) { + $this->user_validation_id = $obj->fk_user_valid; + } + $this->date_creation = $this->db->jdate($obj->datec); + $this->date_modification = empty($obj->datem) ? '' : $this->db->jdate($obj->datem); + if (!empty($obj->datev)) { + $this->date_validation = empty($obj->datev) ? '' : $this->db->jdate($obj->datev); + } + } + + $this->db->free($result); + } else { + dol_print_error($this->db); + } + } + + /** + * Initialize object with example values + * Id must be 0 if object instance is a specimen + * + * @return int + */ + public function initAsSpecimen() + { + // Set here init that are not commonf fields + // $this->property1 = ... + // $this->property2 = ... + + return $this->initAsSpecimenCommon(); + } + + /** + * Create an array of lines + * + * @return CommonObjectLine[]|int array of lines if OK, <0 if KO + */ + public function getLinesArray() + { + $this->lines = array(); + + $objectline = new HistoryLine($this->db); + $result = $objectline->fetchAll('ASC', 'position', 0, 0, '(fk_history:=:'.((int) $this->id).')'); + + if (is_numeric($result)) { + $this->setErrorsFromObject($objectline); + return $result; + } else { + $this->lines = $result; + return $this->lines; + } + } + + /** + * Return validation test result for a field. + * Need MAIN_ACTIVATE_VALIDATION_RESULT to be called. + * + * @param array|string,position:int,notnull?:int,visible:int<-2,5>|string,noteditable?:int<0,1>,default?:int<0,1>|string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,csslist?:string,help?:string,showoncombobox?:int<0,2>,disabled?:int<0,1>,arrayofkeyval?:array,comment?:string,validate?:int<0,1>}> $fields Array of properties of field to show + * @param string $fieldKey Key of attribute + * @param string $fieldValue value of attribute + * @return bool Return false if fail, true on success, set $this->error for error message + */ + public function validateField($fields, $fieldKey, $fieldValue) + { + // Add your own validation rules here. + // ... + + return parent::validateField($fields, $fieldKey, $fieldValue); + } + + /** + * Action executed by scheduler + * CAN BE A CRON TASK. In such a case, parameters come from the schedule job setup field 'Parameters' + * Use public function doScheduledJob($param1, $param2, ...) to get parameters + * + * @return int 0 if OK, <>0 if KO (this function is used also by cron so only 0 is OK) + */ + public function doScheduledJob() + { + //global $conf, $langs; + + //$conf->global->SYSLOG_FILE = 'DOL_DATA_ROOT/dolibarr_mydedicatedlogfile.log'; + + $error = 0; + $this->output = ''; + $this->error = ''; + + dol_syslog(__METHOD__." start", LOG_INFO); + + $now = dol_now(); + + $this->db->begin(); + + // ... + + $this->db->commit(); + + dol_syslog(__METHOD__." end", LOG_INFO); + + return $error; + } +} + + +require_once DOL_DOCUMENT_ROOT.'/core/class/commonobjectline.class.php'; + +/** + * Class HistoryLine. You can also remove this and generate a CRUD class for lines objects. + */ +class HistoryLine extends CommonObjectLine +{ + // To complete with content of an object HistoryLine + // We should have a field rowid, fk_history and position + + /** + * To overload + * @see CommonObjectLine + */ + public $parent_element = ''; // Example: '' or 'triggerhistory' + + /** + * To overload + * @see CommonObjectLine + */ + public $fk_parent_attribute = ''; // Example: '' or 'fk_history' + + /** + * Constructor + * + * @param DoliDB $db Database handler + */ + public function __construct(DoliDB $db) + { + $this->db = $db; + + $this->isextrafieldmanaged = 0; + } +} diff --git a/htdocs/webhook/lib/webhook.lib.php b/htdocs/webhook/lib/webhook.lib.php index dbf6e2fdf9c..d5de6d8568a 100644 --- a/htdocs/webhook/lib/webhook.lib.php +++ b/htdocs/webhook/lib/webhook.lib.php @@ -44,6 +44,10 @@ function webhookAdminPrepareHead() $head[$h][2] = 'targets'; $h++; + $head[$h][0] = DOL_URL_ROOT . '/webhook/triggerhistory_list.php?mode=modulesetup'; + $head[$h][1] = $langs->trans("TriggerHistory"); + $head[$h][2] = 'triggerhistory'; + $h++; /* $head[$h][0] = dol_buildpath("/webhook/admin/myobject_extrafields.php", 1); diff --git a/htdocs/webhook/lib/webhook_triggerhistory.lib.php b/htdocs/webhook/lib/webhook_triggerhistory.lib.php new file mode 100644 index 00000000000..c4ac0673550 --- /dev/null +++ b/htdocs/webhook/lib/webhook_triggerhistory.lib.php @@ -0,0 +1,108 @@ + + * + * 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 lib/webhook_triggerhistory.lib.php + * \ingroup webhook + * \brief Library files with common functions for + */ + +/** + * Prepare array of tabs for + * + * @param TriggerHistory $object TriggerHistory + * @return array Array of tabs + */ +function triggerhistoryPrepareHead($object) +{ + global $db, $langs, $conf; + + $langs->load("webhook@webhook"); + + $showtabofpagecontact = 0; + $showtabofpagenote = 1; + $showtabofpagedocument = 0; + $showtabofpageagenda = 0; + + $h = 0; + $head = array(); + + $head[$h][0] = dol_buildpath("/webhook/triggerhistory_card.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Card"); + $head[$h][2] = 'card'; + $h++; + + /*if ($showtabofpagecontact) { + $head[$h][0] = dol_buildpath("/webhook/history_contact.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Contacts"); + $head[$h][2] = 'contact'; + $h++; + }*/ + + if (isset($object->fields['note_public']) || isset($object->fields['note_private'])) { + $nbNote = 0; + if (!empty($object->note_private)) { + $nbNote++; + } + if (!empty($object->note_public)) { + $nbNote++; + } + $head[$h][0] = dol_buildpath('/webhook/triggerhistory_note.php', 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Notes'); + if ($nbNote > 0) { + $head[$h][1] .= (!getDolGlobalInt('MAIN_OPTIMIZEFORTEXTBROWSER') ? ''.$nbNote.'' : ''); + } + $head[$h][2] = 'note'; + $h++; + } + + /*if ($showtabofpagedocument) { + require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php'; + require_once DOL_DOCUMENT_ROOT.'/core/class/link.class.php'; + $upload_dir = $conf->webhook->dir_output."/triggerhistory/".dol_sanitizeFileName($object->ref); + $nbFiles = count(dol_dir_list($upload_dir, 'files', 0, '', '(\.meta|_preview.*\.png)$')); + $nbLinks = Link::count($db, $object->element, $object->id); + $head[$h][0] = dol_buildpath("/webhook/history_document.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans('Documents'); + if (($nbFiles + $nbLinks) > 0) { + $head[$h][1] .= ''.($nbFiles + $nbLinks).''; + } + $head[$h][2] = 'document'; + $h++; + } + + if ($showtabofpageagenda) { + $head[$h][0] = dol_buildpath("/webhook/history_agenda.php", 1).'?id='.$object->id; + $head[$h][1] = $langs->trans("Events"); + $head[$h][2] = 'agenda'; + $h++; + }*/ + + // Show more tabs from modules + // Entries must be declared in modules descriptor with line + //$this->tabs = array( + // 'entity:+tabname:Title:@webhook:/webhook/mypage.php?id=__ID__' + //); // to add new tab + //$this->tabs = array( + // 'entity:-tabname:Title:@webhook:/webhook/mypage.php?id=__ID__' + //); // to remove a tab + complete_head_from_modules($conf, $langs, $object, $head, $h, 'triggerhistory@webhook'); + + complete_head_from_modules($conf, $langs, $object, $head, $h, 'triggerhistory@webhook', 'remove'); + + return $head; +} diff --git a/htdocs/webhook/target_card.php b/htdocs/webhook/target_card.php index 2a71f9170f1..fcbac81cde4 100644 --- a/htdocs/webhook/target_card.php +++ b/htdocs/webhook/target_card.php @@ -85,20 +85,7 @@ include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be 'inclu // Permissions // There is several ways to check permission. // Set $enablepermissioncheck to 1 to enable a minimum low level of checks -$enablepermissioncheck = getDolGlobalBool("WEBHOOK_ENABLE_PERMISSION_CHECK"); -if ($enablepermissioncheck) { - $permissiontoread = (bool) $user->hasRight('webhook', 'target', 'read'); - $permissiontoadd = (bool) $user->hasRight('webhook', 'target', 'write'); // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php - $permissiontodelete = (bool) $user->hasRight('webhook', 'target', 'delete') || ((bool) $permissiontoadd && isset($object->status) && $object->status == $object::STATUS_DRAFT); - $permissionnote = (bool) $user->hasRight('webhook', 'target', 'write'); // Used by the include of actions_setnotes.inc.php - $permissiondellink = (bool) $user->hasRight('webhook', 'target', 'write'); // Used by the include of actions_dellink.inc.php -} else { - $permissiontoread = true; - $permissiontoadd = true; // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php - $permissiontodelete = true; - $permissionnote = true; - $permissiondellink = true; -} +$permissiontoread = $permissiontoadd = $permissiontodelete = $permissionnote = $permissiondellink = (!empty($user->admin) ? 1 : 0); $upload_dir = $conf->webhook->multidir_output[isset($object->entity) ? $object->entity : 1].'/target'; diff --git a/htdocs/webhook/target_list.php b/htdocs/webhook/target_list.php index 1a0a18e77f9..47bfa828dd0 100644 --- a/htdocs/webhook/target_list.php +++ b/htdocs/webhook/target_list.php @@ -140,16 +140,7 @@ $arrayfields = dol_sort_array($arrayfields, 'position'); // There is several ways to check permission. // Set $enablepermissioncheck to 1 to enable a minimum low level of checks -$enablepermissioncheck = 0; -if ($enablepermissioncheck) { - $permissiontoread = $user->hasRight('webhook', 'target', 'read'); - $permissiontoadd = $user->hasRight('webhook', 'target', 'write'); - $permissiontodelete = $user->hasRight('webhook', 'target', 'delete'); -} else { - $permissiontoread = 1; - $permissiontoadd = 1; - $permissiontodelete = 1; -} +$permissiontoread = $permissiontoadd = $permissiontodelete = (!empty($user->admin) ? 1 : 0); // Security check (enable the most restrictive one) if ($user->socid > 0) { diff --git a/htdocs/webhook/triggerhistory_card.php b/htdocs/webhook/triggerhistory_card.php new file mode 100644 index 00000000000..7b7dc3c82f4 --- /dev/null +++ b/htdocs/webhook/triggerhistory_card.php @@ -0,0 +1,592 @@ + + * Copyright (C) 2024-2025 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 history_card.php + * \ingroup webhook + * \brief Page to create/edit/view triggerhistory + */ + + +// General defined Options +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('MAIN_AUTHENTICATION_MODE')) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined('MAIN_LANG_DEFAULT')) define('MAIN_LANG_DEFAULT', 'auto'); // Force LANG (language) to a particular value +//if (! defined('MAIN_SECURITY_FORCECSP')) define('MAIN_SECURITY_FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined('NOLOGIN')) define('NOLOGIN', '1'); // Do not use login - if this page is public (can be called outside logged session). This includes the NOIPCHECK too. +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // Do not load html.form.class.php +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // Do not load and show top and left menu +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOSESSION')) define('NOSESSION', '1'); // On CLI mode, no need to use web sessions +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) + + +// Load Dolibarr environment +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formprojet.class.php'; +dol_include_once('/webhook/class/triggerhistory.class.php'); +dol_include_once('/webhook/lib/webhook_triggerhistory.lib.php'); + +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Societe $mysoc + * @var Translate $langs + * @var User $user + */ + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "other", "admin")); + +// Get parameters +$id = GETPOSTINT('id'); +$ref = GETPOST('ref', 'alpha'); +$lineid = GETPOSTINT('lineid'); + +$action = GETPOST('action', 'aZ09'); +$confirm = GETPOST('confirm', 'alpha'); +$cancel = GETPOST('cancel', 'aZ09'); +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // if not set, a default page will be used +$backtopageforcancel = GETPOST('backtopageforcancel', 'alpha'); // if not set, $backtopage will be used +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$dol_openinpopup = GETPOST('dol_openinpopup', 'aZ09'); + +// Initialize a technical objects +$object = new TriggerHistory($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array($object->element.'card', 'globalcard')); // Note that conf->hooks_modules contains array +$soc = null; + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Initialize array of search criteria +$search_all = trim(GETPOST("search_all", 'alpha')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha')) { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } +} + +if (empty($action) && empty($id) && empty($ref)) { + $action = 'view'; +} + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be 'include', not 'include_once'. + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$permissiontoread = $permissiontoadd = $permissiontodelete = $permissionnote = $permissiondellink = (!empty($user->admin) ? 1 : 0); + +$upload_dir = $conf->webhook->multidir_output[!empty($object->entity) ? $object->entity : 1].'/triggerhistory'; + +// Security check (enable the most restrictive one) +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (isset($object->status) && ($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->module, $object, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft); +if (!isModEnabled($object->module)) { + accessforbidden("Module ".$object->module." not enabled"); +} +if (!$permissiontoread) { + accessforbidden(); +} + +$error = 0; + + +/* + * Actions + */ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + $backurlforlist = dol_buildpath('/webhook/history_list.php', 1); + + if (empty($backtopage) || ($cancel && empty($id))) { + if (empty($backtopage) || ($cancel && strpos($backtopage, '__ID__'))) { + if (empty($id) && (($action != 'add' && $action != 'create') || $cancel)) { + $backtopage = $backurlforlist; + } else { + $backtopage = dol_buildpath('/webhook/history_card.php', 1).'?id='.((!empty($id) && $id > 0) ? $id : '__ID__'); + } + } + } + + $triggermodname = 'WEBHOOK_MYOBJECT_MODIFY'; // Name of trigger action code to execute when we modify record + + // Actions cancel, add, update, update_extras, confirm_validate, confirm_delete, confirm_deleteline, confirm_clone, confirm_close, confirm_setdraft, confirm_reopen + include DOL_DOCUMENT_ROOT.'/core/actions_addupdatedelete.inc.php'; + + // Actions when linking object each other + include DOL_DOCUMENT_ROOT.'/core/actions_dellink.inc.php'; + + // Actions when printing a doc from card + include DOL_DOCUMENT_ROOT.'/core/actions_printing.inc.php'; + + // Action to move up and down lines of object + //include DOL_DOCUMENT_ROOT.'/core/actions_lineupdown.inc.php'; + + // Action to build doc + include DOL_DOCUMENT_ROOT.'/core/actions_builddoc.inc.php'; + + if ($action == 'set_thirdparty' && $permissiontoadd) { + $object->setValueFrom('fk_soc', GETPOSTINT('fk_soc'), '', null, 'date', '', $user, $triggermodname); + } + if ($action == 'classin' && $permissiontoadd) { + $object->setProject(GETPOSTINT('projectid')); + } + + // Actions to send emails + $triggersendname = 'WEBHOOK_MYOBJECT_SENTBYMAIL'; + $autocopy = 'MAIN_MAIL_AUTOCOPY_MYOBJECT_TO'; + $trackid = 'triggerhistory'.$object->id; + include DOL_DOCUMENT_ROOT.'/core/actions_sendmails.inc.php'; +} + + + + +/* + * View + */ + +$form = new Form($db); +$formfile = new FormFile($db); +$formproject = new FormProjets($db); + +$title = $langs->trans("TriggerHistory")." - ".$langs->trans('Card'); +//$title = $object->ref." - ".$langs->trans('Card'); +if ($action == 'create') { + $title = $langs->trans("NewObject", $langs->transnoentitiesnoconv("TriggerHistory")); +} +$help_url = ''; + +llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-webhook page-card'); + +// Example : Adding jquery code +// print ''; + + +// Part to create +if ($action == 'create') { + if (empty($permissiontoadd)) { + accessforbidden('NotEnoughPermissions', 0, 1); + } + + print load_fiche_titre($title, '', $object->picto); + + print '
'; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + if ($dol_openinpopup) { + print ''; + } + + print dol_get_fiche_head(array(), ''); + + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_add.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_add.tpl.php'; + + print '
'."\n"; + + print dol_get_fiche_end(); + + print $form->buttonsSaveCancel("Create"); + + print '
'; + + //dol_set_focus('input[name="ref"]'); +} + +// Part to edit record +if (($id || $ref) && $action == 'edit') { + print load_fiche_titre($langs->trans(""), '', $object->picto); + + print '
'; + print ''; + print ''; + print ''; + if ($backtopage) { + print ''; + } + if ($backtopageforcancel) { + print ''; + } + + print dol_get_fiche_head(); + + print ''."\n"; + + // Common attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/commonfields_edit.tpl.php'; + + // Other attributes + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_edit.tpl.php'; + + print '
'; + + print dol_get_fiche_end(); + + print $form->buttonsSaveCancel(); + + print '
'; +} + +// Part to show record +if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'create'))) { + $head = triggerhistoryPrepareHead($object); + + print dol_get_fiche_head($head, 'card', $langs->trans(""), -1, $object->picto, 0, '', '', 0, '', 1); + + $formconfirm = ''; + + // Confirmation to delete (using preloaded confirm popup) + if ($action == 'delete' || ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile))) { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('DeleteTriggereHistoryRecord'), $langs->trans('ConfirmDeleteObject'), 'confirm_delete', '', 0, 'action-delete'); + } + // Confirmation to delete line + if ($action == 'deleteline') { + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id.'&lineid='.$lineid, $langs->trans('DeleteLine'), $langs->trans('ConfirmDeleteLine'), 'confirm_deleteline', '', 0, 1); + } + + // Clone confirmation + if ($action == 'clone') { + // Create an array for form + $formquestion = array(); + $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneAsk', $object->ref), 'confirm_clone', $formquestion, 'yes', 1); + } + + // Confirmation of action xxxx (You can use it for xxx = 'close', xxx = 'reopen', ...) + // if ($action == 'xxx') { + // $text = $langs->trans('ConfirmActionXxx', $object->ref); + // if (isModEnabled('notification')) { + // require_once DOL_DOCUMENT_ROOT . '/core/class/notify.class.php'; + // $notify = new Notify($db); + // $text .= '
'; + // $text .= $notify->confirmMessage('MYOBJECT_CLOSE', $object->socid, $object); + // } + + // $formquestion = array(); + + // $forcecombo=0; + // if ($conf->browser->name == 'ie') $forcecombo = 1; // There is a bug in IE10 that make combo inside popup crazy + // $formquestion = array( + // // 'text' => $langs->trans("ConfirmClone"), + // // array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneMainAttributes"), 'value' => 1), + // // array('type' => 'checkbox', 'name' => 'update_prices', 'label' => $langs->trans("PuttingPricesUpToDate"), 'value' => 1), + // // array('type' => 'other', 'name' => 'idwarehouse', 'label' => $langs->trans("SelectWarehouseForStockDecrease"), 'value' => $formproduct->selectWarehouses(GETPOST('idwarehouse')?GETPOST('idwarehouse'):'ifone', 'idwarehouse', '', 1, 0, 0, '', 0, $forcecombo)) + // ); + // $formconfirm = $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('XXX'), $text, 'confirm_xxx', $formquestion, 0, 1, 220); + // } + + // Call Hook formConfirm + $parameters = array('formConfirm' => $formconfirm, 'lineid' => $lineid); + $reshook = $hookmanager->executeHooks('formConfirm', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if (empty($reshook)) { + $formconfirm .= $hookmanager->resPrint; + } elseif ($reshook > 0) { + $formconfirm = $hookmanager->resPrint; + } + + // Print form confirm + print $formconfirm; + + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
'; + /* + // Ref customer + $morehtmlref .= $form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string', '', 0, 1); + $morehtmlref .= $form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, $usercancreate, 'string'.(getDolGlobalInt('THIRDPARTY_REF_INPUT_SIZE') ? ':'.getDolGlobalInt('THIRDPARTY_REF_INPUT_SIZE') : ''), '', null, null, '', 1); + // Thirdparty + $morehtmlref .= '
'.$object->thirdparty->getNomUrl(1, 'customer'); + if (!getDolGlobalInt('MAIN_DISABLE_OTHER_LINK') && $object->thirdparty->id > 0) { + $morehtmlref .= ' ('.$langs->trans("OtherOrders").')'; + } + // Project + if (isModEnabled('project')) { + $langs->load("projects"); + $morehtmlref .= '
'; + if ($permissiontoadd) { + $morehtmlref .= img_picto($langs->trans("Project"), 'project', 'class="pictofixedwidth"'); + if ($action != 'classify') { + $morehtmlref .= ''.img_edit($langs->transnoentitiesnoconv('SetProject')).' '; + } + $morehtmlref .= $form->form_project($_SERVER['PHP_SELF'].'?id='.$object->id, $object->socid, $object->fk_project, ($action == 'classify' ? 'projectid' : 'none'), 0, 0, 0, 1, '', 'maxwidth300'); + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= $proj->getNomUrl(1); + if ($proj->title) { + $morehtmlref .= ' - '.dol_escape_htmltag($proj->title).''; + } + } + } + } + */ + $morehtmlref .= '
'; + + + dol_banner_tab($object, 'id', $linkback, 1, 'rowid', '', $morehtmlref); + + + print '
'; + print '
'; + print '
'; + print ''."\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 '
'; + print '
'; + print '
'; + + print '
'; + + print dol_get_fiche_end(); + + + /* + * Lines + */ + + if (!empty($object->table_element_line)) { + // Show object lines + $result = $object->getLinesArray(); + + print '
+ + + + + + '; + + if (!empty($conf->use_javascript_ajax) && $object->status == 0) { + include DOL_DOCUMENT_ROOT.'/core/tpl/ajaxrow.tpl.php'; + } + + print '
'; + if (!empty($object->lines) || ($object->status == $object::STATUS_ERROR && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { + print ''; + } + + if (!empty($object->lines)) { + $object->printObjectLines($action, $mysoc, null, GETPOSTINT('lineid'), 1); + } + + // Form to add new line + if ($object->status == 0 && $permissiontoadd && $action != 'selectlines') { + if ($action != 'editline') { + // Add products/services form + + $parameters = array(); + $reshook = $hookmanager->executeHooks('formAddObjectLine', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } + if (empty($reshook)) { + $object->formAddObjectLine(1, $mysoc, $soc); + } + } + } + + if (!empty($object->lines) || ($object->status == $object::STATUS_ERROR && $permissiontoadd && $action != 'selectlines' && $action != 'editline')) { + print '
'; + } + print '
'; + + print "
\n"; + } + + + // Buttons for actions + + if ($action != 'presend' && $action != 'editline') { + print '
'."\n"; + $parameters = array(); + $reshook = $hookmanager->executeHooks('addMoreActionsButtons', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); + } + + if (empty($reshook)) { + /*// Send + if (empty($user->socid)) { + print dolGetButtonAction('', $langs->trans('SendMail'), 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=presend&token='.newToken().'&mode=init#formmailbeforetitle'); + } + + // Back to draft + if ($object->status == $object::STATUS_SUCCESS) { + print dolGetButtonAction('', $langs->trans('SetToDraft'), 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=confirm_setdraft&confirm=yes&token='.newToken(), '', $permissiontoadd); + }*/ + + // Modify + print dolGetButtonAction('', $langs->trans('Modify'), 'default', $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=edit&token='.newToken(), '', $permissiontoadd); + + /*// Validate + if ($object->status == $object::STATUS_ERROR) { + if (empty($object->table_element_line) || (is_array($object->lines) && count($object->lines) > 0)) { + print dolGetButtonAction('', $langs->trans('Validate'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=confirm_validate&confirm=yes&token='.newToken(), '', $permissiontoadd); + } else { + $langs->load("errors"); + print dolGetButtonAction($langs->trans("ErrorAddAtLeastOneLineFirst"), $langs->trans("Validate"), 'default', '#', '', 0); + } + } + + // Clone + if ($permissiontoadd) { + print dolGetButtonAction('', $langs->trans('ToClone'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.(!empty($object->socid) ? '&socid='.$object->socid : '').'&action=clone&token='.newToken(), '', $permissiontoadd); + } + + // Disable / Enable + if ($permissiontoadd) { + if ($object->status == $object::STATUS_ENABLED) { + print dolGetButtonAction('', $langs->trans('Disable'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=disable&token='.newToken(), '', $permissiontoadd); + } else { + print dolGetButtonAction('', $langs->trans('Enable'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=enable&token='.newToken(), '', $permissiontoadd); + } + } + if ($permissiontoadd) { + if ($object->status == $object::STATUS_VALIDATED) { + print dolGetButtonAction('', $langs->trans('Cancel'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=close&token='.newToken(), '', $permissiontoadd); + } else { + print dolGetButtonAction('', $langs->trans('Re-Open'), 'default', $_SERVER['PHP_SELF'].'?id='.$object->id.'&action=reopen&token='.newToken(), '', $permissiontoadd); + } + } + */ + + // Delete (with preloaded confirm popup) + $deleteUrl = $_SERVER["PHP_SELF"].'?id='.$object->id.'&action=delete&token='.newToken(); + $buttonId = 'action-delete-no-ajax'; + if ($conf->use_javascript_ajax && empty($conf->dol_use_jmobile)) { // We can use preloaded confirm if not jmobile + $deleteUrl = ''; + $buttonId = 'action-delete'; + } + $params = array(); + print dolGetButtonAction('', $langs->trans("Delete"), 'delete', $deleteUrl, $buttonId, $permissiontodelete, $params); + } + print '
'."\n"; + } + + + // Select mail models is same action as presend + if (GETPOST('modelselected')) { + $action = 'presend'; + } + + if ($action != 'presend') { + print '
'; + print ''; // ancre + + $includedocgeneration = 0; + + // Show links to link elements + $tmparray = $form->showLinkToObjectBlock($object, array(), array('triggerhistory'), 1); + if (is_array($tmparray)) { + $linktoelem = $tmparray['linktoelem']; + $htmltoenteralink = $tmparray['htmltoenteralink']; + print $htmltoenteralink; + $somethingshown = $form->showLinkedObjectBlock($object, $linktoelem); + } else { + // backward compatibility + $somethingshown = $form->showLinkedObjectBlock($object, $tmparray); + } + + print '
'; + + $MAXEVENT = 10; + + $morehtmlcenter = dolGetButtonTitle($langs->trans('SeeAll'), '', 'fa fa-bars imgforviewmode', dol_buildpath('/webhook/history_agenda.php', 1).'?id='.$object->id); + + print '
'; + } + + // Presend form + $modelmail = 'triggerhistory'; + $defaulttopic = 'InformationMessage'; + $diroutput = $conf->webhook->dir_output; + $trackid = 'triggerhistory'.$object->id; + + include DOL_DOCUMENT_ROOT.'/core/tpl/card_presend.tpl.php'; +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/triggerhistory_list.php b/htdocs/webhook/triggerhistory_list.php new file mode 100644 index 00000000000..aab57dd6c04 --- /dev/null +++ b/htdocs/webhook/triggerhistory_list.php @@ -0,0 +1,925 @@ + + * Copyright (C) 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 history_list.php + * \ingroup webhook + * \brief List page for triggerhistory + */ + +// General defined Options +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('MAIN_AUTHENTICATION_MODE')) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined('MAIN_LANG_DEFAULT')) define('MAIN_LANG_DEFAULT', 'auto'); // Force LANG (language) to a particular value +//if (! defined('MAIN_SECURITY_FORCECSP')) define('MAIN_SECURITY_FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined('NOLOGIN')) define('NOLOGIN', '1'); // Do not use login - if this page is public (can be called outside logged session). This includes the NOIPCHECK too. +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // Do not load html.form.class.php +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // Do not load and show top and left menu +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOSESSION')) define('NOSESSION', '1'); // On CLI mode, no need to use web sessions +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) + + +// Load Dolibarr environment +require '../main.inc.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/date.lib.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/company.lib.php'; +// load module libraries +require_once __DIR__.'/class/triggerhistory.class.php'; +// for other modules +//dol_include_once('/othermodule/class/otherobject.class.php'); + +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "other", "admin")); + +// Get parameters +$action = GETPOST('action', 'aZ09') ? GETPOST('action', 'aZ09') : 'view'; // The action 'create'/'add', 'edit'/'update', 'view', ... +$massaction = GETPOST('massaction', 'alpha'); // The bulk action (combo box choice into lists) +$show_files = GETPOSTINT('show_files'); // Show files area generated by bulk actions ? +$confirm = GETPOST('confirm', 'alpha'); // Result of a confirmation +$cancel = GETPOST('cancel', 'alpha'); // We click on a Cancel button +$toselect = GETPOST('toselect', 'array:int'); // Array of ids of elements selected into a list +$contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : str_replace('_', '', basename(dirname(__FILE__)).basename(__FILE__, '.php')); // To manage different context of search +$backtopage = GETPOST('backtopage', 'alpha'); // Go back to a dedicated page +$optioncss = GETPOST('optioncss', 'aZ'); // Option for the css output (always '' except when 'print') +$mode = GETPOST('mode', 'aZ'); // The display mode ('list', 'kanban', 'hierarchy', 'calendar', 'gantt', ...) +$groupby = GETPOST('groupby', 'aZ09'); // Example: $groupby = 'p.fk_opp_status' or $groupby = 'p.fk_statut' + +$id = GETPOSTINT('id'); +$ref = GETPOST('ref', 'alpha'); + +// Load variable for pagination +$limit = GETPOSTINT('limit') ? GETPOSTINT('limit') : $conf->liste_limit; +$sortfield = GETPOST('sortfield', 'aZ09comma'); +$sortorder = GETPOST('sortorder', 'aZ09comma'); +$page = GETPOSTISSET('pageplusone') ? (GETPOSTINT('pageplusone') - 1) : GETPOSTINT('page'); +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + // If $page is not defined, or '' or -1 or if we click on clear filters + $page = 0; +} +$offset = $limit * $page; +$pageprev = $page - 1; +$pagenext = $page + 1; + +// Initialize technical objects +$object = new TriggerHistory($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array($contextpage)); // Note that conf->hooks_modules contains array of activated contexes + +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); +//$extrafields->fetch_name_optionals_label($object->table_element_line); + +$search_array_options = $extrafields->getOptionalsFromPost($object->table_element, '', 'search_'); + +// Default sort order (if not yet defined by previous GETPOST) +if (!$sortfield) { + reset($object->fields); // Reset is required to avoid key() to return null. + $sortfield = "t.".key($object->fields); // Set here default search field. By default 1st field in definition. +} +if (!$sortorder) { + $sortorder = "ASC"; +} + +// Initialize array of search criteria +$search_all = trim(GETPOST('search_all', 'alphanohtml')); +$search = array(); +foreach ($object->fields as $key => $val) { + if (GETPOST('search_'.$key, 'alpha') !== '') { + $search[$key] = GETPOST('search_'.$key, 'alpha'); + } + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = dol_mktime(0, 0, 0, GETPOSTINT('search_'.$key.'_dtstartmonth'), GETPOSTINT('search_'.$key.'_dtstartday'), GETPOSTINT('search_'.$key.'_dtstartyear')); + $search[$key.'_dtend'] = dol_mktime(23, 59, 59, GETPOSTINT('search_'.$key.'_dtendmonth'), GETPOSTINT('search_'.$key.'_dtendday'), GETPOSTINT('search_'.$key.'_dtendyear')); + } +} + +$fieldstosearchall = array(); +// List of fields to search into when doing a "search in all" +// foreach ($object->fields as $key => $val) { +// if (!empty($val['searchall'])) { +// $fieldstosearchall['t.'.$key] = $val['label']; +// } +// } +// $parameters = array('fieldstosearchall'=>$fieldstosearchall); +// $reshook = $hookmanager->executeHooks('completeFieldsToSearchAll', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +// if ($reshook > 0) { +// $fieldstosearchall = empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']; +// } elseif ($reshook == 0) { +// $fieldstosearchall = array_merge($fieldstosearchall, empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']); +// } + +// Definition of array of fields for columns +$tableprefix = 't'; +$arrayfields = array(); +foreach ($object->fields as $key => $val) { + // If $val['visible']==0, then we never show the field + if (!empty($val['visible'])) { + $visible = (int) dol_eval((string) $val['visible'], 1); + $arrayfields[$tableprefix.'.'.$key] = array( + 'label' => $val['label'], + 'checked' => (($visible < 0) ? '0' : '1'), + 'enabled' => (string) (int) (abs($visible) != 3 && (bool) dol_eval((string) $val['enabled'], 1)), + 'position' => $val['position'], + 'help' => isset($val['help']) ? $val['help'] : '' + ); + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; + +$object->fields = dol_sort_array($object->fields, 'position'); +//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right'); +$arrayfields = dol_sort_array($arrayfields, 'position'); + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$permissiontoread = $permissiontoadd = $permissiontodelete = (!empty($user->admin) ? 1 : 0); + +// Security check (enable the most restrictive one) +if ($user->socid > 0) { + accessforbidden(); +} +//if ($user->socid > 0) accessforbidden(); +//$socid = 0; if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->module, 0, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft); +if (!isModEnabled("webhook")) { + accessforbidden('Module webhook not enabled'); +} +if (!$permissiontoread) { + accessforbidden(); +} + + +/* + * Actions + */ + +if (GETPOST('cancel', 'alpha')) { + $action = 'list'; + $massaction = ''; +} +if (!GETPOST('confirmmassaction', 'alpha') && $massaction != 'presend' && $massaction != 'confirm_presend') { + $massaction = ''; +} + +$parameters = array('arrayfields' => &$arrayfields); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} + +if (empty($reshook)) { + // Selection of new fields + include DOL_DOCUMENT_ROOT.'/core/actions_changeselectedfields.inc.php'; + + // Purge search criteria + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers + foreach ($object->fields as $key => $val) { + $search[$key] = ''; + if (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + $search[$key.'_dtstart'] = ''; + $search[$key.'_dtend'] = ''; + } + } + $search_all = ''; + $toselect = array(); + $search_array_options = array(); + } + if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha') + || GETPOST('button_search_x', 'alpha') || GETPOST('button_search.x', 'alpha') || GETPOST('button_search', 'alpha')) { + $massaction = ''; // Protection to avoid mass action if we force a new search during a mass action confirmation + } + + // Mass actions + $objectclass = 'TriggerHistory'; + $objectlabel = 'TriggerHistory'; + $uploaddir = $conf->webhook->dir_output; + + global $error; + include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; + + // You can add more action here + // if ($action == 'xxx' && $permissiontoxxx) ... +} + + + +/* + * View + */ + +$form = new Form($db); + +$now = dol_now(); + +$title = $langs->trans(""); +//$help_url = "EN:Module_History|FR:Module_History_FR|ES:Módulo_History"; +$help_url = ''; +$morejs = array(); +$morecss = array(); + + +// Build and execute select +// -------------------------------------------------------------------- +$sql = "SELECT"; +$sql .= " ".$object->getFieldList('t'); +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key." as options_".$key : ""); + } +} +// Add fields from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListSelect', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/,\s*$/', '', $sql); + +$sqlfields = $sql; // $sql fields to remove for count total + +$sql .= " FROM ".$db->prefix().$object->table_element." as t"; +//$sql .= " LEFT JOIN ".$db->prefix()."anothertable as rc ON rc.parent = t.rowid"; +if (isset($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { + $sql .= " LEFT JOIN ".$db->prefix().$object->table_element."_extrafields as ef on (t.rowid = ef.fk_object)"; +} +// Add table from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListFrom', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +if ($object->ismultientitymanaged == 1) { + $sql .= " WHERE t.entity IN (".getEntity($object->element, (GETPOSTINT('search_current_entity') ? 0 : 1)).")"; +} else { + $sql .= " WHERE 1 = 1"; +} +foreach ($search as $key => $val) { + if (array_key_exists($key, $object->fields)) { + if ($key == 'status' && $search[$key] == -1) { + continue; + } + $field_spec = $object->fields[$key]; + if ($field_spec === null) { + continue; + } + $mode_search = (($object->isInt($field_spec) || $object->isFloat($field_spec)) ? 1 : 0); + if ((strpos($field_spec['type'], 'integer:') === 0) || (strpos($field_spec['type'], 'sellist:') === 0) || !empty($field_spec['arrayofkeyval'])) { + if ($search[$key] == '-1' || ($search[$key] === '0' && (empty($field_spec['arrayofkeyval']) || !array_key_exists('0', $field_spec['arrayofkeyval'])))) { + $search[$key] = ''; + } + $mode_search = 2; + } + if ($field_spec['type'] === 'boolean') { + $mode_search = 1; + if ($search[$key] == '-1') { + $search[$key] = ''; + } + } + if (empty($field_spec['searchmulti'])) { + if (!is_array($search[$key]) && $search[$key] != '') { + $sql .= natural_search("t.".$db->escape($key), $search[$key], (($key == 'status') ? 2 : $mode_search)); + } + } else { + if (is_array($search[$key]) && !empty($search[$key])) { + $sql .= natural_search("t.".$db->escape($key), implode(',', $search[$key]), (($key == 'status') ? 2 : $mode_search)); + } + } + } else { + if (preg_match('/(_dtstart|_dtend)$/', $key) && $search[$key] != '') { + $columnName = preg_replace('/(_dtstart|_dtend)$/', '', $key); + if (preg_match('/^(date|timestamp|datetime)/', $object->fields[$columnName]['type'])) { + if (preg_match('/_dtstart$/', $key)) { + $sql .= " AND t.".$db->sanitize($columnName)." >= '".$db->idate($search[$key])."'"; + } + if (preg_match('/_dtend$/', $key)) { + $sql .= " AND t.".$db->sanitize($columnName)." <= '".$db->idate($search[$key])."'"; + } + } + } + } +} +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); +} +/* +// If the internal user must only see his customers, force searching by him +$search_sale = 0; +if (!$user->hasRight('societe', 'client', 'voir')) { + $search_sale = $user->id; +} +// Search on sale representative +if ($search_sale && $search_sale != '-1') { + if ($search_sale == -2) { + $sql .= " AND NOT EXISTS (SELECT sc.fk_soc FROM ".$db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc)"; + } elseif ($search_sale > 0) { + $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".$db->prefix()."societe_commerciaux as sc WHERE sc.fk_soc = t.fk_soc AND sc.fk_user = ".((int) $search_sale).")"; + } +} +// Search on socid +if ($socid) { + $sql .= " AND t.fk_soc = ".((int) $socid); +} +*/ +//$sql.= dolSqlDateFilter("t.field", $search_xxxday, $search_xxxmonth, $search_xxxyear); +// Add where from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_sql.tpl.php'; +// Add where from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + +/* If a group by is required +$sql .= " GROUP BY "; +foreach($object->fields as $key => $val) { + $sql .= "t.".$db->sanitize($key).", "; +} +// Add fields from extrafields +if (!empty($extrafields->attributes[$object->table_element]['label'])) { + foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { + $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? "ef.".$key.', ' : ''); + } +} +// Add groupby from hooks +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; +$sql = preg_replace('/,\s*$/', '', $sql); +*/ + +// Add HAVING from hooks +/* +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldListHaving', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= empty($hookmanager->resPrint) ? "" : " HAVING 1=1 ".$hookmanager->resPrint; +*/ + +// Count total nb of records +$nbtotalofrecords = ''; +if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { + /* The fast and low memory method to get and count full list converts the sql into a sql count */ + $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql); + $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount); + + $resql = $db->query($sqlforcount); + if ($resql) { + $objforcount = $db->fetch_object($resql); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } else { + dol_print_error($db); + } + + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller than the paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } + $db->free($resql); +} + +// Complete request and execute it with limit +$sql .= $db->order($sortfield, $sortorder); +if ($limit) { + $sql .= $db->plimit($limit + 1, $offset); +} + +$resql = $db->query($sql); +if (!$resql) { + dol_print_error($db); + exit; +} + +$num = $db->num_rows($resql); + + +// Direct jump if only one record found +if ($num == 1 && getDolGlobalInt('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all && !$page) { + $obj = $db->fetch_object($resql); + $id = $obj->rowid; + header("Location: ".dol_buildpath('/webhook/history_card.php', 1).'?id='.((int) $id)); + exit; +} + + +// Output page +// -------------------------------------------------------------------- + +llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'mod-webhook page-list bodyforlist'); // Can use also classforhorizontalscrolloftabs instead of bodyforlist for a horizontal scroll in the table instead of page + +if ($mode == 'modulesetup') { + require_once DOL_DOCUMENT_ROOT.'/webhook/lib/webhook.lib.php'; + + + $help_url = ''; + $page_name = "WebhookSetup"; + // Subheader + $linkback = ''.$langs->trans("BackToModuleList").''; + print load_fiche_titre($langs->trans($page_name), $linkback, 'title_setup'); + + $head = webhookAdminPrepareHead(); + print dol_get_fiche_head($head, 'triggerhistory', $langs->trans($page_name), -1, "webhook"); +} +// Example : Adding jquery code +// print ''; + +$arrayofselected = is_array($toselect) ? $toselect : array(); + +$param = ''; +if (!empty($mode)) { + $param .= '&mode='.urlencode($mode); +} +if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { + $param .= '&contextpage='.urlencode($contextpage); +} +if ($limit > 0 && $limit != $conf->liste_limit) { + $param .= '&limit='.((int) $limit); +} +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} +if ($groupby != '') { + $param .= '&groupby='.urlencode($groupby); +} +foreach ($search as $key => $val) { + if (is_array($search[$key])) { + foreach ($search[$key] as $skey) { + if ($skey != '') { + $param .= '&search_'.$key.'[]='.urlencode($skey); + } + } + } elseif (preg_match('/(_dtstart|_dtend)$/', $key) && !empty($val)) { + $param .= '&search_'.$key.'month='.GETPOSTINT('search_'.$key.'month'); + $param .= '&search_'.$key.'day='.GETPOSTINT('search_'.$key.'day'); + $param .= '&search_'.$key.'year='.GETPOSTINT('search_'.$key.'year'); + } elseif ($search[$key] != '') { + $param .= '&search_'.$key.'='.urlencode($search[$key]); + } +} +// Add $param from extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_param.tpl.php'; +// Add $param from hooks +$parameters = array('param' => &$param); +$reshook = $hookmanager->executeHooks('printFieldListSearchParam', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$param .= $hookmanager->resPrint; + +// List of mass actions available +$arrayofmassactions = array( + //'validate'=>img_picto('', 'check', 'class="pictofixedwidth"').$langs->trans("Validate"), + //'generate_doc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("ReGeneratePDF"), + //'builddoc'=>img_picto('', 'pdf', 'class="pictofixedwidth"').$langs->trans("PDFMerge"), + //'presend'=>img_picto('', 'email', 'class="pictofixedwidth"').$langs->trans("SendByMail"), +); +if (!empty($permissiontodelete)) { + $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); +} +if (GETPOSTINT('nomassaction') || in_array($massaction, array('presend', 'predelete'))) { + $arrayofmassactions = array(); +} +$massactionbutton = $form->selectMassAction('', $arrayofmassactions); + +print '
'."\n"; +if ($optioncss != '') { + print ''; +} +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; +print ''; + + +$newcardbutton = ''; +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewList'), '', 'fa fa-bars imgforviewmode', $_SERVER["PHP_SELF"].'?mode=common'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', ((empty($mode) || $mode == 'common') ? 2 : 1), array('morecss' => 'reposition')); +$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanban'), '', 'fa fa-th-list imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanban'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', ($mode == 'kanban' ? 2 : 1), array('morecss' => 'reposition')); +//$newcardbutton .= dolGetButtonTitle($langs->trans('ViewKanbanGroupBy'), '', 'fa fa-grip-vertical imgforviewmode', $_SERVER["PHP_SELF"].'?mode=kanbangroupby&groupby=p.fk_opp_status'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', ($mode == 'kanbangroupby' ? 2 : 1), array('morecss' => 'reposition')); +//$newcardbutton .= dolGetButtonTitle($langs->trans('HierarchicView'), '', 'fa fa-stream paddingleft imgforviewmode', $_SERVER["PHP_SELF"].'?mode=hierarchy'.preg_replace('/(&|\?)*(mode|groupby)=[^&]+/', '', $param), '', (($mode == 'hierarchy') ? 2 : 1), array('morecss' => 'reposition')); +$newcardbutton .= dolGetButtonTitleSeparator(); +$newcardbutton .= dolGetButtonTitle($langs->trans('New'), '', 'fa fa-plus-circle', dol_buildpath('/webhook/history_card.php', 1).'?action=create&backtopage='.urlencode($_SERVER['PHP_SELF']), '', $permissiontoadd); + +print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, $object->picto, 0, $newcardbutton, '', $limit, 0, 0, 1); + +// Add code for pre mass action (confirmation or email presend form) +$topicmail = "SendHistoryRef"; +$modelmail = "triggerhistory"; +$objecttmp = new TriggerHistory($db); +$trackid = 'xxxx'.$object->id; +include DOL_DOCUMENT_ROOT.'/core/tpl/massactions_pre.tpl.php'; + +if ($search_all) { + $setupstring = ''; + // @phan-suppress-next-line PhanEmptyForeach + foreach ($fieldstosearchall as $key => $val) { + $fieldstosearchall[$key] = $langs->trans($val); + $setupstring .= $key."=".$val.";"; + } + print ''."\n"; + print '
'.$langs->trans("FilterOnInto", $search_all).implode(', ', $fieldstosearchall).'
'."\n"; +} + +$moreforfilter = ''; +/*$moreforfilter.='
'; +$moreforfilter.= $langs->trans('MyFilter') . ': '; +$moreforfilter.= '
';*/ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('printFieldPreListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +if (empty($reshook)) { + $moreforfilter .= $hookmanager->resPrint; +} else { + $moreforfilter = $hookmanager->resPrint; +} +$parameters = array( + 'arrayfields' => &$arrayfields, +); + +if (!empty($moreforfilter)) { + print '
'; + print $moreforfilter; + print '
'; +} + +$varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; +$htmlofselectarray = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, $conf->main_checkbox_left_column); // This also change content of $arrayfields with user setup +$selectedfields = (($mode != 'kanban' && $mode != 'kanbangroupby') ? $htmlofselectarray : ''); +$selectedfields .= (count($arrayofmassactions) ? $form->showCheckAddButtons('checkforselect', 1) : ''); + +print '
'; // You can use div-table-responsive-no-min if you don't need reserved height for your table +print ''."\n"; + +// Fields title search +// -------------------------------------------------------------------- +print ''; +// Action column +if ($conf->main_checkbox_left_column) { + print ''; +} +foreach ($object->fields as $key => $val) { + //$searchkey = empty($search[$key]) ? '' : $search[$key]; + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('id', 'rowid', 'ref', 'status')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + if (!empty($arrayfields['t.'.$key]['checked'])) { + print ''; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_input.tpl.php'; + +// Fields from hook +$parameters = array('arrayfields' => $arrayfields); +$reshook = $hookmanager->executeHooks('printFieldListOption', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; +}*/ +// Action column +if (!$conf->main_checkbox_left_column) { + print ''; +} +print ''."\n"; + +$totalarray = array(); +$totalarray['nbfield'] = 0; + +// Fields title label +// -------------------------------------------------------------------- +print ''; +// Action column +if ($conf->main_checkbox_left_column) { + print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; + $totalarray['nbfield']++; +} +foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowrap'; + } elseif (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('id', 'rowid', 'ref', 'status')) && $val['label'] != 'TechnicalID' && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + $cssforfield = preg_replace('/small\s*/', '', $cssforfield); // the 'small' css must not be used for the title label + if (!empty($arrayfields['t.'.$key]['checked'])) { + print getTitleFieldOfList($arrayfields['t.'.$key]['label'], 0, $_SERVER['PHP_SELF'], 't.'.$key, '', $param, ($cssforfield ? 'class="'.$cssforfield.'"' : ''), $sortfield, $sortorder, ($cssforfield ? $cssforfield.' ' : ''), 0, (empty($val['helplist']) ? '' : $val['helplist']))."\n"; + $totalarray['nbfield']++; + } +} +// Extra fields +include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; +// Hook fields +$parameters = array('arrayfields' => $arrayfields, 'param' => $param, 'sortfield' => $sortfield, 'sortorder' => $sortorder, 'totalarray' => &$totalarray); +$reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; +/*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; + $totalarray['nbfield']++; +}*/ +// Action column +if (!$conf->main_checkbox_left_column) { + print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; + $totalarray['nbfield']++; +} +print ''."\n"; + +// Detect if we need a fetch on each output line +$needToFetchEachLine = 0; +if (isset($extrafields->attributes[$object->table_element]['computed']) && is_array($extrafields->attributes[$object->table_element]['computed']) && count($extrafields->attributes[$object->table_element]['computed']) > 0) { + foreach ($extrafields->attributes[$object->table_element]['computed'] as $key => $val) { + if (!is_null($val) && preg_match('/\$object/', $val)) { + $needToFetchEachLine++; // There is at least one compute field that use $object + } + } +} + + +// Loop on record +// -------------------------------------------------------------------- +$i = 0; +$savnbfield = $totalarray['nbfield']; +$totalarray = array(); +$totalarray['nbfield'] = 0; +$imaxinloop = ($limit ? min($num, $limit) : $num); +while ($i < $imaxinloop) { + $obj = $db->fetch_object($resql); + if (empty($obj)) { + break; // Should not happen + } + + // Store properties in $object + $object->setVarsFromFetchObj($obj); + + /* + $object->thirdparty = null; + if ($obj->fk_soc > 0) { + if (!empty($conf->cache['thirdparty'][$obj->fk_soc])) { + $companyobj = $conf->cache['thirdparty'][$obj->fk_soc]; + } else { + $companyobj = new Societe($db); + $companyobj->fetch($obj->fk_soc); + $conf->cache['thirdparty'][$obj->fk_soc] = $companyobj; + } + + $object->thirdparty = $companyobj; + }*/ + + if ($mode == 'kanban' || $mode == 'kanbangroupby') { + if ($i == 0) { + print ''; + } + } else { + // Show line of result + $j = 0; + print ''; + + // Action column + if ($conf->main_checkbox_left_column) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + // Fields + foreach ($object->fields as $key => $val) { + $cssforfield = (empty($val['csslist']) ? (empty($val['css']) ? '' : $val['css']) : $val['csslist']); + if (in_array($val['type'], array('date', 'datetime', 'timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } elseif ($key == 'status') { + $cssforfield .= ($cssforfield ? ' ' : '').'center'; + } + + if (in_array($val['type'], array('timestamp'))) { + $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; + } elseif ($key == 'ref') { + $cssforfield .= ($cssforfield ? ' ' : '').'nowraponall'; + } + + if (in_array($val['type'], array('double(24,8)', 'double(6,3)', 'integer', 'real', 'price')) && !in_array($key, array('id', 'rowid', 'ref', 'status')) && empty($val['arrayofkeyval'])) { + $cssforfield .= ($cssforfield ? ' ' : '').'right'; + } + //if (in_array($key, array('fk_soc', 'fk_user', 'fk_warehouse'))) $cssforfield = 'tdoverflowmax100'; + + if (!empty($arrayfields['t.'.$key]['checked'])) { + print '$key) && !in_array($key, array('ref'))) { + print ' title="'.dol_escape_htmltag((string) $object->$key).'"'; + } + print '>'; + if ($key == 'status') { + print $object->getLibStatut(5); + } elseif ($key == 'rowid') { + print $object->showOutputField($val, $key, (string) $object->id, ''); + } else { + print $object->showOutputField($val, $key, (string) $object->$key, ''); + } + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + if (!empty($val['isameasure']) && $val['isameasure'] == 1) { + if (!$i) { + $totalarray['pos'][$totalarray['nbfield']] = 't.'.$key; + } + if (!isset($totalarray['val'])) { + $totalarray['val'] = array(); + } + if (!isset($totalarray['val']['t.'.$key])) { + $totalarray['val']['t.'.$key] = 0; + } + $totalarray['val']['t.'.$key] += $object->$key; + } + } + } + // Extra fields + include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_print_fields.tpl.php'; + // Fields from hook + $parameters = array('arrayfields' => $arrayfields, 'object' => $object, 'obj' => $obj, 'i' => $i, 'totalarray' => &$totalarray); + $reshook = $hookmanager->executeHooks('printFieldListValue', $parameters, $object, $action); // Note that $action and $object may have been modified by hook + print $hookmanager->resPrint; + + /*if (!empty($arrayfields['anotherfield']['checked'])) { + print ''; + }*/ + + // Action column + if (empty($conf->main_checkbox_left_column)) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } + } + + print ''."\n"; + } + + $i++; +} + +// Show total line +include DOL_DOCUMENT_ROOT.'/core/tpl/list_print_total.tpl.php'; + +// If no record found +if ($num == 0) { + $colspan = 1; + foreach ($arrayfields as $key => $val) { + if (!empty($val['checked'])) { + $colspan++; + } + } + print ''; +} + + +$db->free($resql); + +$parameters = array('arrayfields' => $arrayfields, 'sql' => $sql); +$reshook = $hookmanager->executeHooks('printFieldListFooter', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +print $hookmanager->resPrint; + +print '
'; + $searchpicto = $form->showFilterButtons('left'); + print $searchpicto; + print ''; + if (!empty($val['arrayofkeyval']) && is_array($val['arrayofkeyval'])) { + if (empty($val['searchmulti'])) { + print $form->selectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), 1, 0, 0, '', 1, 0, 0, '', 'maxwidth100'.($key == 'status' ? ' search_status width100 onrightofpage' : ''), 1); + } else { + print $form->multiselectarray('search_'.$key, $val['arrayofkeyval'], (isset($search[$key]) ? $search[$key] : ''), 0, 0, 'maxwidth100'.($key == 'status' ? ' search_status width100 onrightofpage' : ''), 1); + } + } elseif ((strpos($val['type'], 'integer:') === 0) || (strpos($val['type'], 'sellist:') === 0)) { + print $object->showInputField($val, $key, (isset($search[$key]) ? $search[$key] : ''), '', '', 'search_', $cssforfield.' maxwidth250', 1); + } elseif (preg_match('/^(date|timestamp|datetime)/', $val['type'])) { + print '
'; + print $form->selectDate($search[$key.'_dtstart'] ? $search[$key.'_dtstart'] : '', "search_".$key."_dtstart", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('From')); + print '
'; + print '
'; + print $form->selectDate($search[$key.'_dtend'] ? $search[$key.'_dtend'] : '', "search_".$key."_dtend", 0, 0, 1, '', 1, 0, 0, '', '', '', '', 1, '', $langs->trans('to')); + print '
'; + } elseif ($key == 'lang') { + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php'; + $formadmin = new FormAdmin($db); + print $formadmin->select_language((isset($search[$key]) ? $search[$key] : ''), 'search_lang', 0, array(), 1, 0, 0, 'minwidth100imp maxwidth125', 2); + } elseif ($val['type'] === 'boolean') { + print $form->selectyesno('search_' . $key, $search[$key] ?? '', 1, false, 1); + } else { + print ''; + } + print '
'; + $searchpicto = $form->showFilterButtons(); + print $searchpicto; + print '
'.$langs->trans("AnotherField").'
'; + print '
'; + } + // Output Kanban + $selected = -1; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + } + //print $object->getKanbanView('', array('thirdparty'=>$object->thirdparty, 'selected' => $selected)); + print $object->getKanbanView('', array('selected' => $selected)); + if ($i == ($imaxinloop - 1)) { + print '
'; + print '
'; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print ''.$obj->anotherfield.''; + if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined + $selected = 0; + if (in_array($object->id, $arrayofselected)) { + $selected = 1; + } + print ''; + } + print '
'.$langs->trans("NoRecordFound").'
'."\n"; +print '
'."\n"; + +print '
'."\n"; + +if (in_array('builddoc', array_keys($arrayofmassactions)) && ($nbtotalofrecords === '' || $nbtotalofrecords)) { + $hidegeneratedfilelistifempty = 1; + if ($massaction == 'builddoc' || $action == 'remove_file' || $show_files) { + $hidegeneratedfilelistifempty = 0; + } + + require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php'; + $formfile = new FormFile($db); + + // Show list of available documents + $urlsource = $_SERVER['PHP_SELF'].'?sortfield='.$sortfield.'&sortorder='.$sortorder; + $urlsource .= str_replace('&', '&', $param); + + $filedir = $diroutputmassaction; + $genallowed = $permissiontoread; + $delallowed = $permissiontoadd; + + print $formfile->showdocuments('massfilesarea_'.$object->module, '', $filedir, $urlsource, 0, $delallowed, '', 1, 1, 0, 48, 1, $param, $title, '', '', '', null, $hidegeneratedfilelistifempty); +} + +// End of page +llxFooter(); +$db->close(); diff --git a/htdocs/webhook/triggerhistory_note.php b/htdocs/webhook/triggerhistory_note.php new file mode 100644 index 00000000000..36e7bf20d67 --- /dev/null +++ b/htdocs/webhook/triggerhistory_note.php @@ -0,0 +1,198 @@ + + * Copyright (C) 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 webhook/history_note.php + * \ingroup webhook + * \brief Tab for notes on + */ + + +// General defined Options +//if (! defined('CSRFCHECK_WITH_TOKEN')) define('CSRFCHECK_WITH_TOKEN', '1'); // Force use of CSRF protection with tokens even for GET +//if (! defined('MAIN_AUTHENTICATION_MODE')) define('MAIN_AUTHENTICATION_MODE', 'aloginmodule'); // Force authentication handler +//if (! defined('MAIN_LANG_DEFAULT')) define('MAIN_LANG_DEFAULT', 'auto'); // Force LANG (language) to a particular value +//if (! defined('MAIN_SECURITY_FORCECSP')) define('MAIN_SECURITY_FORCECSP', 'none'); // Disable all Content Security Policies +//if (! defined('NOBROWSERNOTIF')) define('NOBROWSERNOTIF', '1'); // Disable browser notification +//if (! defined('NOIPCHECK')) define('NOIPCHECK', '1'); // Do not check IP defined into conf $dolibarr_main_restrict_ip +//if (! defined('NOLOGIN')) define('NOLOGIN', '1'); // Do not use login - if this page is public (can be called outside logged session). This includes the NOIPCHECK too. +//if (! defined('NOREQUIREAJAX')) define('NOREQUIREAJAX', '1'); // Do not load ajax.lib.php library +//if (! defined('NOREQUIREDB')) define('NOREQUIREDB', '1'); // Do not create database handler $db +//if (! defined('NOREQUIREHTML')) define('NOREQUIREHTML', '1'); // Do not load html.form.class.php +//if (! defined('NOREQUIREMENU')) define('NOREQUIREMENU', '1'); // Do not load and show top and left menu +//if (! defined('NOREQUIRESOC')) define('NOREQUIRESOC', '1'); // Do not load object $mysoc +//if (! defined('NOREQUIRETRAN')) define('NOREQUIRETRAN', '1'); // Do not load object $langs +//if (! defined('NOREQUIREUSER')) define('NOREQUIREUSER', '1'); // Do not load object $user +//if (! defined('NOSCANGETFORINJECTION')) define('NOSCANGETFORINJECTION', '1'); // Do not check injection attack on GET parameters +//if (! defined('NOSCANPOSTFORINJECTION')) define('NOSCANPOSTFORINJECTION', '1'); // Do not check injection attack on POST parameters +//if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK', '1'); // Do not check style html tag into posted data +//if (! defined('NOTOKENRENEWAL')) define('NOTOKENRENEWAL', '1'); // Do not roll the Anti CSRF token (used if MAIN_SECURITY_CSRF_WITH_TOKEN is on) + + +// Load Dolibarr environment +require '../main.inc.php'; +dol_include_once('/webhook/class/triggerhistory.class.php'); +dol_include_once('/webhook/lib/webhook_triggerhistory.lib.php'); + +/** + * @var Conf $conf + * @var DoliDB $db + * @var HookManager $hookmanager + * @var Translate $langs + * @var User $user + */ + +// Load translation files required by the page +$langs->loadLangs(array("webhook@webhook", "companies", "admin")); + +// Get parameters +$id = GETPOSTINT('id'); +$ref = GETPOST('ref', 'alpha'); +$action = GETPOST('action', 'aZ09'); +$cancel = GETPOST('cancel', 'aZ09'); +$backtopage = GETPOST('backtopage', 'alpha'); + +// Initialize a technical objects +$object = new TriggerHistory($db); +$extrafields = new ExtraFields($db); +$diroutputmassaction = $conf->webhook->dir_output.'/temp/massgeneration/'.$user->id; +$hookmanager->initHooks(array($object->element.'note', 'globalcard')); // Note that conf->hooks_modules contains array +// Fetch optionals attributes and labels +$extrafields->fetch_name_optionals_label($object->table_element); + +// Load object +include DOL_DOCUMENT_ROOT.'/core/actions_fetchobject.inc.php'; // Must be 'include', not 'include_once'. Include fetch and fetch_thirdparty but not fetch_optionals +if ($id > 0 || !empty($ref)) { + $upload_dir = $conf->webhook->multidir_output[empty($object->entity) ? $conf->entity : $object->entity]."/".$object->id; +} + + +// There is several ways to check permission. +// Set $enablepermissioncheck to 1 to enable a minimum low level of checks +$permissiontoread = $permissiontoadd = $permissiontodelete = (!empty($user->admin) ? 1 : 0); + +// Security check (enable the most restrictive one) +//if ($user->socid > 0) accessforbidden(); +//if ($user->socid > 0) $socid = $user->socid; +//$isdraft = (($object->status == $object::STATUS_DRAFT) ? 1 : 0); +//restrictedArea($user, $object->module, $object->id, $object->table_element, $object->element, 'fk_soc', 'rowid', $isdraft); +if (!isModEnabled("webhook")) { + accessforbidden(); +} +if (!$permissiontoread) { + accessforbidden(); +} + + +/* + * Actions + */ + +$parameters = array(); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} +if (empty($reshook)) { + include DOL_DOCUMENT_ROOT.'/core/actions_setnotes.inc.php'; // Must be 'include', not 'include_once' +} + + +/* + * View + */ + +$form = new Form($db); + +$title = $langs->trans('').' - '.$langs->trans("Notes"); +//$title = $object->ref." - ".$langs->trans("Notes"); +$help_url = ''; +//$help_url='EN:Customers_Orders|FR:Commandes_Clients|ES:Pedidos de clientes'; + +llxHeader('', $title, $help_url, '', 0, 0, '', '', '', 'mod-webhook page-card_notes'); + +if ($id > 0 || !empty($ref)) { + $object->fetch_thirdparty(); + + $head = triggerhistoryPrepareHead($object); + + print dol_get_fiche_head($head, 'note', $langs->trans(""), -1, $object->picto); + + // Object card + // ------------------------------------------------------------ + $linkback = ''.$langs->trans("BackToList").''; + + $morehtmlref = '
'; + /* + // Ref customer + $morehtmlref.=$form->editfieldkey("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', 0, 1); + $morehtmlref.=$form->editfieldval("RefCustomer", 'ref_client', $object->ref_client, $object, 0, 'string', '', null, null, '', 1); + // Thirdparty + $morehtmlref.='
'.$langs->trans('ThirdParty') . ' : ' . (is_object($object->thirdparty) ? $object->thirdparty->getNomUrl(1) : ''); + // Project + if (isModEnabled('project')) { + $langs->load("projects"); + $morehtmlref.='
'.$langs->trans('Project') . ' '; + if ($permissiontoadd) + { + if ($action != 'classify') + //$morehtmlref.='' . img_edit($langs->transnoentitiesnoconv('SetProject')) . ' : '; + $morehtmlref.=' : '; + if ($action == 'classify') { + //$morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'projectid', 0, 0, 1, 1); + $morehtmlref.='
'; + $morehtmlref.=''; + $morehtmlref.=''; + $morehtmlref.=$formproject->select_projects($object->socid, $object->fk_project, 'projectid', $maxlength, 0, 1, 0, 1, 0, 0, '', 1); + $morehtmlref.=''; + $morehtmlref.='
'; + } else { + $morehtmlref.=$form->form_project($_SERVER['PHP_SELF'] . '?id=' . $object->id, $object->socid, $object->fk_project, 'none', 0, 0, 0, 1); + } + } else { + if (!empty($object->fk_project)) { + $proj = new Project($db); + $proj->fetch($object->fk_project); + $morehtmlref .= ': '.$proj->getNomUrl(); + } else { + $morehtmlref .= ''; + } + } + }*/ + $morehtmlref .= '
'; + + + dol_banner_tab($object, 'ref', $linkback, 1, 'ref', 'ref', $morehtmlref); + + + print '
'; + print '
'; + + + $cssclass = "titlefield"; + include DOL_DOCUMENT_ROOT.'/core/tpl/notes.tpl.php'; + + print '
'; + + print dol_get_fiche_end(); +} + +// End of page +llxFooter(); +$db->close();