diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php
index 7d2fd5da518..0493d7bab09 100644
--- a/htdocs/admin/mails_templates.php
+++ b/htdocs/admin/mails_templates.php
@@ -44,6 +44,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/lib/admin.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
require_once DOL_DOCUMENT_ROOT.'/core/lib/accounting.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/cemailtemplate.class.php';
/**
* @var Conf $conf
@@ -283,7 +284,7 @@ $permissiontoadd = 1;
$permissiontoedit = ($user->admin ? 1 : 0);
$permissiontodelete = ($user->admin ? 1 : 0);
if ($rowid > 0) {
- $tmpmailtemplate = new ModelMail($db);
+ $tmpmailtemplate = new cEmailTemplate($db);
$tmpmailtemplate->fetch($rowid);
if ($tmpmailtemplate->fk_user == $user->id) {
$permissiontoedit = 1;
diff --git a/htdocs/api/class/api_emailtemplates.class.php b/htdocs/api/class/api_emailtemplates.class.php
new file mode 100644
index 00000000000..1c3b339bc8c
--- /dev/null
+++ b/htdocs/api/class/api_emailtemplates.class.php
@@ -0,0 +1,641 @@
+
+ *
+ * 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 .
+ */
+
+use Luracast\Restler\RestException;
+
+require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/lib/functions.lib.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/cemailtemplate.class.php';
+
+/**
+ * API for handling Object of table llx_c_email_templates
+ *
+ * @access protected
+ * @class DolibarrApiAccess {@requires user,external}
+ */
+class EmailTemplates extends DolibarrApi
+{
+ /**
+ * @var string[] Mandatory fields, checked when create and update object
+ */
+ public static $FIELDS = array(
+ 'label',
+ 'topic',
+ 'type_template'
+ );
+
+ /**
+ * @var string[] Mandatory fields which needs to be an integer, checked when create and update object
+ */
+ public static $INTFIELDS = array(
+ 'active',
+ 'private',
+ 'fk_user',
+ 'joinfiles',
+ 'position'
+ );
+
+ /**
+ * @var cEmailTemplate {@type cEmailTemplate}
+ */
+ public $email_template;
+
+ /**
+ * @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 = 'c_email_templates';
+
+ /**
+ * Constructor of the class
+ */
+ public function __construct()
+ {
+ global $db;
+ $this->db = $db;
+ $this->email_template = new cEmailTemplate($this->db);
+ }
+
+ /**
+ * Delete an email template
+ *
+ * @param int $id email template ID
+ * @return array
+ * @phan-return array>
+ * @phpstan-return array>
+ *
+ * @url DELETE {id}
+ *
+ * @throws RestException 403
+ * @throws RestException 404
+ * @throws RestException 500
+ */
+ public function deleteById($id)
+ {
+ $allowaccess = $this->_checkAccessRights('lire');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied read access to email templates');
+ }
+
+ $result = $this->email_template->apifetch($id, '');
+ if (!$result || $id == 0) {
+ throw new RestException(404, 'Email Template with id '.$id.' not found');
+ }
+
+ if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
+ throw new RestException(500, 'Error when delete email template : '.$this->email_template->error);
+ }
+
+ return array(
+ 'success' => array(
+ 'code' => 200,
+ 'message' => 'email template deleted'
+ )
+ );
+ }
+
+ /**
+ * Delete an email template
+ *
+ * @param string $label email template label
+ * @return array
+ * @phan-return array>
+ * @phpstan-return array>
+ *
+ * @url DELETE label/{label}
+ *
+ * @throws RestException 403
+ * @throws RestException 404
+ * @throws RestException 500
+ */
+ public function deleteByLAbel($label)
+ {
+ $allowaccess = $this->_checkAccessRights('lire');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied read access to email templates');
+ }
+
+ $result = $this->email_template->apifetch(0, $label);
+ if (!$result) {
+ throw new RestException(404, "Email Template with label ".$label." not found");
+ }
+
+ if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
+ throw new RestException(500, 'Error when delete email template : '.$this->email_template->error);
+ }
+
+ return array(
+ 'success' => array(
+ 'code' => 200,
+ 'message' => 'email template deleted'
+ )
+ );
+ }
+
+ /**
+ * Get properties of a email template by id
+ *
+ * Return an array with email template information
+ *
+ * @param int $id ID of email template
+ * @return Object Object with cleaned properties
+ * @phan-return cEmailTemplate
+ * @phpstan-return cEmailTemplate
+ *
+ * @url GET {id}
+ *
+ * @throws RestException 403
+ * @throws RestException 404
+ */
+ public function getById($id)
+ {
+ return $this->_fetch($id, '');
+ }
+
+ /**
+ * Get properties of an email template by label
+ *
+ * Return an array with order information
+ *
+ * @param string $label Label of object
+ * @return Object Object with cleaned properties
+ * @phan-return cEmailTemplate
+ * @phpstan-return cEmailTemplate
+ *
+ * @url GET label/{label}
+ *
+ * @throws RestException 403
+ * @throws RestException 404
+ */
+ public function getByLabel($label)
+ {
+ return $this->_fetch(0, $label);
+ }
+
+ /**
+ * List email templates
+ *
+ * Get a list of email templates
+ *
+ * @param string $sortfield Sort field
+ * @param string $sortorder Sort order
+ * @param int $limit Limit for list
+ * @param int $page Page number
+ * @param string $fk_user User ids to filter email templates of (example '1' or '1,2,3') {@pattern /^[0-9,]*$/i}
+ * @param string $sqlfilters Other criteria to filter answers separated by a comma. Syntax example "(e.active:=:1) and (e.module:=:'adherent')"
+ * @param string $properties Restrict the data returned to these properties. Ignored if empty. Comma separated list of properties names
+ * @param bool $pagination_data If this parameter is set to true the response will include pagination data. Default value is false. Page starts from 0*
+ * @return array Array of order objects
+ * @phan-return cEmailTemplate[]|array{data:cEmailTemplate[],pagination:array{total:int,page:int,page_count:int,limit:int}}
+ * @phpstan-return cEmailTemplate[]|array{data:cEmailTemplate[],pagination:array{total:int,page:int,page_count:int,limit:int}}
+ *
+ * @url GET
+ *
+ * @throws RestException 404 Not found
+ * @throws RestException 503 Error
+ */
+ public function index($sortfield = "e.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $fk_user = '', $sqlfilters = '', $properties = '', $pagination_data = false)
+ {
+ $allowaccess = $this->_checkAccessRights('lire');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied read access to email templates');
+ }
+
+ $obj_ret = array();
+
+ $sql = "SELECT e.rowid";
+ $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." AS e";
+ $sql .= " WHERE e.entity IN (".getEntity($this->table_element).")";
+ if (!$fk_user == '') {
+ $sql .= " AND e.fk_user = ".((int) $fk_user);
+ }
+
+ // Add sql filters
+ if ($sqlfilters) {
+ $errormessage = '';
+ $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
+ if ($errormessage) {
+ throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
+ }
+ }
+
+ //this query will return total orders with the filters given
+ $sqlTotals = str_replace('SELECT e.rowid', 'SELECT count(e.rowid) as total', $sql);
+
+ $sql .= $this->db->order($sortfield, $sortorder);
+ if ($limit) {
+ if ($page < 0) {
+ $page = 0;
+ }
+ $offset = $limit * $page;
+
+ $sql .= $this->db->plimit($limit + 1, $offset);
+ }
+
+ dol_syslog(get_class($this)."::index", LOG_DEBUG);
+ $result = $this->db->query($sql);
+ dol_syslog(get_class($this)."::pindex", LOG_DEBUG);
+
+ if ($result) {
+ $num = $this->db->num_rows($result);
+ $min = min($num, ($limit <= 0 ? $num : $limit));
+ $i = 0;
+ while ($i < $min) {
+ $obj = $this->db->fetch_object($result);
+ $email_template_static = new cEmailTemplate($this->db);
+ if ($email_template_static->apifetch($obj->rowid, '') > 0) {
+ $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($email_template_static), $properties);
+ }
+ $i++;
+ }
+ } else {
+ throw new RestException(503, 'Error when retrieve email template list : '.$this->db->lasterror());
+ }
+
+ //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
+ if ($pagination_data) {
+ $totalsResult = $this->db->query($sqlTotals);
+ $total = $this->db->fetch_object($totalsResult)->total;
+
+ $tmp = $obj_ret;
+ $obj_ret = [];
+
+ $obj_ret['data'] = $tmp;
+ $obj_ret['pagination'] = [
+ 'total' => (int) $total,
+ 'page' => $page, //count starts from 0
+ 'page_count' => ceil((int) $total / $limit),
+ 'limit' => $limit
+ ];
+ }
+
+ return $obj_ret;
+ }
+
+ /**
+ * Create an email template
+ *
+ * Example: {"module":"adherent","type_template":"member","active": 1,"label":"(SendingEmailOnAutoSubscription)","fk_user":0,"joinfiles": "0", ... }
+ * Required: {"label":"myBestTemplate","topic":"myBestOffer","type_template":"propal_send"}
+ *
+ * @param array $request_data Request data
+ * @phan-param ?array $request_data
+ * @phpstan-param ?array $request_data
+ *
+ * @url POST
+ *
+ * @return int ID of email template
+ *
+ * @throws RestException 400
+ * @throws RestException 403
+ * @throws RestException 500
+ */
+ public function post($request_data = null)
+ {
+ $allowaccess = $this->_checkAccessRights('creer');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied create access to email templates');
+ }
+
+ // Check mandatory fields
+ $result = $this->_validate($request_data);
+
+ foreach ($request_data as $field => $value) {
+ if ($field === 'caller') {
+ // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
+ $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
+ continue;
+ }
+ if ($field == 'id') {
+ throw new RestException(400, 'Creating with id field is forbidden');
+ }
+
+ $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
+ }
+
+ if ($this->email_template->create(DolibarrApiAccess::$user) < 0) {
+ throw new RestException(500, "Error creating email template", array_merge(array($this->email_template->error), $this->email_template->errors));
+ }
+
+ return ((int) $this->email_template->id);
+ }
+
+ /**
+ * Update an email template
+ *
+ * Example: {"module":"adherent","type_template":"member","active": 1,"label":"(SendingEmailOnAutoSubscription)","fk_user":0,"joinfiles": "0", ... }
+ * Required: {"label":"myBestTemplate","topic":"myBestOffer","type_template":"propal_send"}
+ *
+ * @param int $id Id of order to update
+ * @param array $request_data Data
+ * @phan-param ?array $request_data
+ * @phpstan-param ?array $request_data
+ *
+ * @url PUT {id}
+ *
+ * @return Object Object with cleaned properties
+ *
+ * @throws RestException 403
+ * @throws RestException 404
+ * @throws RestException 500
+ */
+ public function putById($id, $request_data = null)
+ {
+ $allowaccess = $this->_checkAccessRights('creer');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied update access to email templates');
+ }
+
+ $result = $this->email_template->apifetch($id, '');
+ if (!$result || $id == 0) {
+ throw new RestException(404, 'email template with id='.$id.' not found');
+ }
+
+ foreach ($request_data as $field => $value) {
+ if ($field == 'id') {
+ continue;
+ }
+ if ($field === 'caller') {
+ // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
+ $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
+ continue;
+ }
+
+ $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
+ }
+
+ if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
+ return $this->_fetch($id, '');
+ } else {
+ throw new RestException(500, $this->email_template->error);
+ }
+ }
+
+ /**
+ * Update an email template
+ *
+ * Example: {"module":"adherent","type_template":"member","active": 1,"label":"(SendingEmailOnAutoSubscription)","fk_user":0,"joinfiles": "0", ... }
+ * Required: {"label":"myBestTemplate","topic":"myBestOffer","type_template":"propal_send"}
+ *
+ * @param string $label Label of order to update
+ * @param array $request_data Data
+ * @phan-param ?array $request_data
+ * @phpstan-param ?array $request_data
+ *
+ * @url PUT label/{label}
+ *
+ * @return Object Object with cleaned properties
+ *
+ * @throws RestException 403
+ * @throws RestException 404
+ * @throws RestException 500
+ */
+ public function putbyLabel($label, $request_data = null)
+ {
+ $allowaccess = $this->_checkAccessRights('creer');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied update access to email templates');
+ }
+
+ $result = $this->email_template->apifetch(0, $label);
+ if (!$result) {
+ throw new RestException(404, 'email template not found');
+ }
+
+ $newlabel = $label;
+ foreach ($request_data as $field => $value) {
+ if ($field == 'id') {
+ continue;
+ }
+ if ($field == 'label') {
+ $newlabel = $this->_checkValForAPI($field, $value, $this->email_template);
+ }
+ if ($field === 'caller') {
+ // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again with the caller
+ $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
+ continue;
+ }
+
+ $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
+ }
+
+ if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
+ return $this->_fetch(0, $newlabel);
+ } else {
+ throw new RestException(500, $this->email_template->error);
+ }
+ }
+
+ /**
+ * Get properties of an email template
+ *
+ * Return an array with email templates
+ *
+ * @param int $id ID of email_template
+ * @param string $label Label of email_template
+ * @return Object Object with cleaned properties
+ * @phan-return cEmailTemplate
+ * @phpstan-return cEmailTemplate
+ *
+ * @throws RestException 400
+ * @throws RestException 403
+ * @throws RestException 404
+ */
+ private function _fetch($id, $label = '')
+ {
+ global $conf;
+
+ $allowaccess = $this->_checkAccessRights('lire');
+ if (!$allowaccess) {
+ throw new RestException(403, 'denied read access to email templates');
+ }
+
+ $result = $this->email_template->apifetch($id, $label);
+ if ($result > 0) {
+ return $this->_cleanObjectDatas($this->email_template);
+ }
+ if ($result == 0) {
+ if ($id) {
+ throw new RestException(404, 'Email template with id='.((string) $id).' not found in entity='.(int) $conf->entity);
+ }
+ if ($label) {
+ throw new RestException(404, 'Email template with label '.$label.' not found in entity='.(int) $conf->entity);
+ }
+ throw new RestException(404, 'Email Template not found');
+ } else {
+ if (empty($this->email_template->error)) {
+ throw new RestException(400, 'Unknown error in your request');
+ } else {
+ throw new RestException(400, 'Error: '.$this->email_template->error);
+ }
+ }
+ }
+
+ // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
+ /**
+ * Clean sensible object datas
+ *
+ * @param Object $object Object to clean
+ * @phan-param cEmailTemplate $object
+ * @phpstan-param cEmailTemplate $object
+ *
+ * @return Object Object with cleaned properties
+ * @phan-return cEmailTemplate
+ * @phpstan-return cEmailTemplate
+ */
+ protected function _cleanObjectDatas($object)
+ {
+ // phpcs:enable
+ $object = parent::_cleanObjectDatas($object);
+ dol_syslog(get_class($this)."::_cleanObjectDatas", LOG_DEBUG);
+
+
+ unset($object->import_key);
+ unset($object->array_languages);
+ unset($object->contacts_ids);
+ unset($object->linkedObjectsIds);
+ unset($object->canvas);
+ unset($object->fk_project);
+ unset($object->contact_id);
+ unset($object->user);
+ unset($object->origin_type);
+ unset($object->origin_id);
+ unset($object->ref);
+ unset($object->ref_ext);
+ unset($object->statut);
+ unset($object->status);
+ unset($object->civility_code);
+ unset($object->country_id);
+ unset($object->country_code);
+ unset($object->state_id);
+ unset($object->region_id);
+ unset($object->barcode_type);
+ unset($object->barcode_type_coder);
+ unset($object->mode_reglement_id);
+ unset($object->cond_reglement_id);
+ unset($object->demand_reason_id);
+ unset($object->transport_mode_id);
+ unset($object->shipping_method_id);
+ unset($object->shipping_method);
+ unset($object->fk_multicurrency);
+ unset($object->multicurrency_code);
+ unset($object->multicurrency_tx);
+ unset($object->multicurrency_total_ht);
+ unset($object->multicurrency_total_tva);
+ unset($object->multicurrency_total_ttc);
+ unset($object->multicurrency_total_localtax1);
+ unset($object->multicurrency_total_localtax2);
+ unset($object->last_main_doc);
+ unset($object->fk_account);
+ unset($object->note_public);
+ unset($object->note_private);
+ unset($object->total_ht);
+ unset($object->total_tva);
+ unset($object->total_localtax1);
+ unset($object->total_localtax2);
+ unset($object->total_ttc);
+ unset($object->lines);
+ unset($object->actiontypecode);
+ unset($object->name);
+ unset($object->lastname);
+ unset($object->firstname);
+ unset($object->civility_id);
+ unset($object->user_author);
+ unset($object->user_creation);
+ unset($object->user_creation_id);
+ unset($object->user_valid);
+ unset($object->user_validation);
+ unset($object->user_validation_id);
+ unset($object->user_closing_id);
+ unset($object->user_modification);
+ unset($object->user_modification_id);
+ unset($object->fk_user_creat);
+ unset($object->fk_user_modif);
+ unset($object->totalpaid);
+ unset($object->product);
+ unset($object->cond_reglement_supplier_id);
+ unset($object->deposit_percent);
+ unset($object->retained_warranty_fk_cond_reglement);
+ unset($object->warehouse_id);
+ unset($object->target);
+ unset($object->array_options);
+ unset($object->extraparams);
+ unset($object->specimen);
+ unset($object->date_validation);
+ unset($object->date_modification);
+ unset($object->date_cloture);
+ unset($object->rowid);
+
+ return $object;
+ }
+
+ /**
+ * Validate fields before create or update object
+ *
+ * @param ?array $data Data to validate
+ * @return array Return array with validated mandatory fields and their value
+ * @phan-return array Return array with validated mandatory fields and their value
+ *
+ * @throws RestException 400
+ */
+ private function _validate($data)
+ {
+ $email_template = array();
+ foreach (EmailTemplates::$FIELDS as $field) {
+ if (!isset($data[$field])) {
+ throw new RestException(400, $field." field missing");
+ }
+ $email_template[$field] = $data[$field];
+ }
+ return $email_template;
+ }
+
+ /**
+ * function to check for access rights - should probably have 1. parameter which is read/write/delete/...
+ * Why a separate function? because we probably needs to check so many many different kinds of objects
+ *
+ * @param string $accesstype accesstype: read, write, delete, ...
+ * @return bool Return true if access is granted else false
+ *
+ * @throws RestException 403
+ */
+ private function _checkAccessRights($accesstype)
+ {
+ // what kind of access management do we need?
+ $allowaccess = false;
+ if (isModEnabled("societe") && DolibarrApiAccess::$user->hasRight('societe', $accesstype)) {
+ $allowaccess = true;
+ }
+ if (isModEnabled('member') && DolibarrApiAccess::$user->hasRight('adherent', $accesstype)) {
+ $allowaccess = true;
+ }
+ if (isModEnabled("propal") && DolibarrApiAccess::$user->hasRight('propal', $accesstype)) {
+ $allowaccess = true;
+ }
+ if (isModEnabled('order') && DolibarrApiAccess::$user->hasRight('commande', $accesstype)) {
+ $allowaccess = true;
+ }
+ if (isModEnabled('invoice') && DolibarrApiAccess::$user->hasRight('facture', $accesstype)) {
+ $allowaccess = true;
+ }
+ if ($allowaccess) {
+ return $allowaccess;
+ } else {
+ throw new RestException(403, 'denied access to email templates');
+ }
+ }
+}
diff --git a/htdocs/core/class/cemailtemplate.class.php b/htdocs/core/class/cemailtemplate.class.php
new file mode 100644
index 00000000000..81aba62d381
--- /dev/null
+++ b/htdocs/core/class/cemailtemplate.class.php
@@ -0,0 +1,574 @@
+
+ * Copyright (C) 2005-2012 Regis Houssin
+ * Copyright (C) 2010-2011 Juanjo Menent
+ * Copyright (C) 2015-2017 Marcos García
+ * Copyright (C) 2015-2017 Nicolas ZABOURI
+ * Copyright (C) 2018-2024 Frédéric France
+ * Copyright (C) 2022 Charlene Benke
+ * Copyright (C) 2023 Anthony Berton
+ * Copyright (C) 2024-2025 MDW
+ * Copyright (C) 2025 Jon Bendtsen
+ *
+ * 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 .
+ */
+require_once DOL_DOCUMENT_ROOT.'/core/class/doldeprecationhandler.class.php';
+
+/**
+ * Object of table llx_c_email_templates
+ */
+class cEmailTemplate extends CommonObject
+{
+ const TRIGGER_PREFIX = 'EMAILTEMPLATE';
+ /**
+ * @var string ID to identify managed object.
+ */
+ public $element = 'email_template';
+
+ /**
+ * @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 = 'c_email_templates';
+
+
+ // BEGIN MODULEBUILDER PROPERTIES
+ /**
+ * @var array|string,position:int,notnull?:int,visible:int<-6,6>|string,alwayseditable?:int<0,1>,noteditable?:int<0,1>,default?:string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,csslist?:string,help?:string,showoncombobox?:int<0,4>,disabled?:int<0,1>,arrayofkeyval?:array,autofocusoncreate?:int<0,1>,comment?:string,copytoclipboard?:int<1,2>,validate?:int<0,1>,showonheader?:int<0,1>}> 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' => 10, 'notnull' => 1, 'visible' => -1,),
+ "module" => array("type" => "varchar(32)", "label" => "Module", 'enabled' => 1, 'position' => 20, 'notnull' => 0, 'visible' => -1,),
+ "type_template" => array("type" => "varchar(32)", "label" => "Typetemplate", 'enabled' => 1, 'position' => 25, 'notnull' => 0, 'visible' => -1,),
+ "lang" => array("type" => "varchar(6)", "label" => "Lang", 'enabled' => 1, 'position' => 30, 'notnull' => 0, 'visible' => -1,),
+ "private" => array("type" => "smallint(6)", "label" => "Private", 'enabled' => 1, 'position' => 35, 'notnull' => 1, 'visible' => -1,),
+ "fk_user" => array("type" => "integer:User:user/class/user.class.php", "label" => "Fkuser", 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => -1, "css" => "maxwidth500 widthcentpercentminusxx", "csslist" => "tdoverflowmax150",),
+ "datec" => array("type" => "datetime", "label" => "DateCreation", 'enabled' => 1, 'position' => 45, 'notnull' => 0, 'visible' => -1,),
+ "tms" => array("type" => "timestamp", "label" => "DateModification", 'enabled' => 1, 'position' => 50, 'notnull' => 1, 'visible' => -1,),
+ "label" => array("type" => "varchar(255)", "label" => "Label", 'enabled' => 1, 'position' => 55, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1, "css" => "minwidth300", "cssview" => "wordbreak", "csslist" => "tdoverflowmax150",),
+ "position" => array("type" => "smallint(6)", "label" => "Position", 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "active" => array("type" => "integer", "label" => "Active", 'enabled' => 1, 'position' => 65, 'notnull' => 1, 'visible' => -1, 'alwayseditable' => 1,),
+ "topic" => array("type" => "text", "label" => "Topic", 'enabled' => 1, 'position' => 70, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "content" => array("type" => "mediumtext", "label" => "Content", 'enabled' => 1, 'position' => 75, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "content_lines" => array("type" => "text", "label" => "Contentlines", "enabled" => "getDolGlobalString('MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES')", 'position' => 80, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "enabled" => array("type" => "varchar(255)", "label" => "Enabled", 'enabled' => 1, 'position' => 85, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "joinfiles" => array("type" => "varchar(255)", "label" => "Joinfiles", 'enabled' => 1, 'position' => 90, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "email_from" => array("type" => "varchar(255)", "label" => "Emailfrom", 'enabled' => 1, 'position' => 95, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "email_to" => array("type" => "varchar(255)", "label" => "Emailto", 'enabled' => 1, 'position' => 100, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "email_tocc" => array("type" => "varchar(255)", "label" => "Emailtocc", 'enabled' => 1, 'position' => 105, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "email_tobcc" => array("type" => "varchar(255)", "label" => "Emailtobcc", 'enabled' => 1, 'position' => 110, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ "defaultfortype" => array("type" => "smallint(6)", "label" => "Defaultfortype", 'enabled' => 1, 'position' => 115, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
+ );
+ /**
+ * @var int
+ */
+ public $rowid;
+ /**
+ * @var string type of the template
+ */
+ public $type_template;
+ /**
+ * @var int|string
+ */
+ public $datec;
+ /**
+ * @var int
+ */
+ public $tms;
+ /**
+ * @var int
+ */
+ public $active;
+ /**
+ * @var string if 0 hidden from GUI, if 1 visible in GUI
+ */
+ public $enabled;
+ /**
+ * @var int is the template a default or not
+ */
+ public $defaultfortype;
+
+ /**
+ * @var int ID
+ */
+ public $id;
+
+ /**
+ * @var string Model mail label
+ */
+ public $label;
+
+ /**
+ * @var int Owner of email template
+ */
+ public $fk_user;
+
+ /**
+ * @var int Is template private
+ */
+ public $private;
+
+ /**
+ * @var string Model mail topic
+ */
+ public $topic;
+
+ /**
+ * @var string Model mail content
+ */
+ public $content;
+ /**
+ * @var string Model to use to generate the string with each lines
+ */
+ public $content_lines;
+
+ /**
+ * @var string language of the template
+ */
+ public $lang;
+ /**
+ * @var int<0,1>
+ */
+ public $joinfiles;
+
+ /**
+ * @var string sender email address
+ */
+ public $email_from;
+
+ /**
+ * @var string recipient email address
+ */
+ public $email_to;
+
+ /**
+ * @var string Additional visible recipients
+ */
+ public $email_tocc;
+
+ /**
+ * @var string additional hidden recipients
+ */
+ public $email_tobcc;
+
+ /**
+ * @var string Module the template is dedicated for
+ */
+ public $module;
+
+ /**
+ * @var int Position of template in a combo list
+ */
+ public $position;
+ // END MODULEBUILDER PROPERTIES
+
+
+
+ /**
+ * Constructor
+ *
+ * @param DoliDB $db Database handler
+ */
+ public function __construct(DoliDB $db)
+ {
+ global $langs;
+
+ $this->db = $db;
+ $this->ismultientitymanaged = 1;
+ $this->isextrafieldmanaged = 1;
+
+ // @phan-suppress-next-line PhanTypeMismatchProperty
+ 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('test', 'mailtemplate', '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 email template
+ * Required fields: label, type_template, topic
+ *
+ * @param User $user Object user that make creation
+ * @param int $notrigger Disable all triggers
+ * @return int Return integer <0 if KO, >0 if OK
+ */
+ public function create($user, $notrigger = 0)
+ {
+ global $conf;
+ $error = 0;
+
+ dol_syslog(get_class($this)."::create user=".$user->id);
+
+ // Check parameters
+ if (!empty($this->label)) { // We check that label is not already used
+ $result = $this->isExistingObject($this->element, 0, $this->label); // Check label is not yet used
+ if ($result > 0) {
+ $this->error = 'ErrorLabelAlreadyExists';
+ dol_syslog(get_class($this)."::create ".$this->error, LOG_WARNING);
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ $now = dol_now();
+
+ $this->db->begin();
+
+ $sql = "INSERT INTO ".MAIN_DB_PREFIX.$this->table_element." (entity,";
+ $sql .= " module, type_template, lang, private, fk_user, datec, label,";
+ $sql .= " position, defaultfortype, enabled, active, email_from, email_to,";
+ $sql .= " email_tocc, email_tobcc, topic, joinfiles, content, content_lines)";
+ $sql .= " VALUES (";
+ $sql .= " ".((int) $conf->entity).",";
+ if (is_null($this->module)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".$this->db->escape($this->module)."',";
+ }
+ $sql .= " '".$this->db->escape($this->type_template)."',";
+ if (is_null($this->lang)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".$this->db->escape($this->lang)."',";
+ }
+ $sql .= " ".((int) $this->private).",";
+ if (is_null($this->fk_user)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".((int) $this->fk_user)."',";
+ }
+ if (is_null($this->datec)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " ".((int) $this->datec).",";
+ }
+ $sql .= " '".$this->db->escape($this->label)."',";
+ $sql .= " ".((int) $this->position).", ".((int) $this->defaultfortype ).",";
+ if (is_null($this->enabled)) {
+ $sql .= " 1,";
+ } else {
+ $sql .= " '".((int) $this->enabled)."',";
+ }
+ if (is_null($this->active)) {
+ $sql .= " 1,";
+ } else {
+ $sql .= " '".((int) $this->active)."',";
+ }
+ if (is_null($this->email_from)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".$this->db->escape($this->email_from)."',";
+ }
+ if (is_null($this->email_to)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".$this->db->escape($this->email_to)."',";
+ }
+ if (is_null($this->email_tocc)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".$this->db->escape($this->email_tocc)."',";
+ }
+ if (is_null($this->email_tobcc)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".$this->db->escape($this->email_tobcc)."',";
+ }
+ $sql .= " '".$this->db->escape($this->topic)."',";
+ $sql .= " ".((int) $this->joinfiles).",";
+ if (is_null($this->content)) {
+ $sql .= " NULL,";
+ } else {
+ $sql .= " '".((string) $this->db->escape($this->content))."',";
+ }
+ if (is_null($this->content_lines)) {
+ $sql .= " NULL";
+ } else {
+ $sql .= " '".((string) $this->db->escape($this->content_lines))."'";
+ }
+ $sql .= ")";
+
+
+ dol_syslog(get_class($this)."::create", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if ($resql) {
+ $this->id = $this->db->last_insert_id(MAIN_DB_PREFIX.$this->table_element);
+
+ if (!$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger(self::TRIGGER_PREFIX.'_CREATE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+
+ if (!$error) {
+ $this->db->commit();
+ return $this->id;
+ } else {
+ $this->db->rollback();
+ return -1 * $error;
+ }
+ } else {
+ $this->error = $this->db->lasterror();
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Update database with changed email template
+ *
+ * @param User $user User that modify
+ * @param int $notrigger 0=launch triggers after, 1=disable triggers
+ * @return int Return integer <0 if KO, >0 if OK
+ */
+ public function update(User $user, $notrigger = 0)
+ {
+ $error = 0;
+
+ // Update request
+ $sql = "UPDATE ".MAIN_DB_PREFIX.$this->table_element." SET";
+ $sql .= " module=".($this->module ? "'".$this->db->escape($this->module)."', " : 'NULL, ');
+ $sql .= " type_template=".($this->type_template ? "'".$this->db->escape($this->type_template)."', " : 'NULL, ');
+ $sql .= " lang=".($this->lang ? "'".$this->db->escape($this->lang)."', " : 'NULL, ');
+ $sql .= " private=".((int) $this->private).",";
+ $sql .= " fk_user=".((int) $this->fk_user).",";
+ $sql .= " datec=".((int) $this->datec).",";
+ $sql .= " label=".($this->label ? "'".$this->db->escape($this->label)."', " : 'NULL, ');
+ $sql .= " position=".((int) $this->position).",";
+ $sql .= " defaultfortype=".((int) $this->defaultfortype).",";
+ $sql .= " enabled=".($this->enabled ? "'".$this->db->escape($this->enabled)."', " : 'NULL, ');
+ $sql .= " active=".((int) $this->active).",";
+ $sql .= " email_from=".($this->email_from ? "'".$this->db->escape($this->email_from)."', " : 'NULL, ');
+ $sql .= " email_to=".($this->email_to ? "'".$this->db->escape($this->email_to)."', " : 'NULL, ');
+ $sql .= " email_tocc=".($this->email_tocc ? "'".$this->db->escape($this->email_tocc)."', " : 'NULL, ');
+ $sql .= " email_tobcc=".($this->email_tobcc ? "'".$this->db->escape($this->email_tobcc)."', " : 'NULL, ');
+ $sql .= " topic=".($this->topic ? "'".$this->db->escape($this->topic)."', " : 'NULL, ');
+ $sql .= " joinfiles=".((int) $this->joinfiles).",";
+ $sql .= " content=".($this->content ? "'".$this->db->escape($this->content)."', " : 'NULL, ');
+ $sql .= " content_lines=".($this->content_lines ? "'".$this->db->escape($this->content_lines)."'" : 'NULL');
+ $sql .= " WHERE rowid=".((int) $this->id);
+
+ $this->db->begin();
+
+ dol_syslog(get_class($this)."::update", LOG_DEBUG);
+ $resql = $this->db->query($sql);
+ if (!$resql) {
+ $error++;
+ $this->errors[] = "Error ".$this->db->lasterror();
+ }
+
+ if (!$error && !$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger(self::TRIGGER_PREFIX.'_MODIFY', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+
+ // Commit or rollback
+ if ($error) {
+ foreach ($this->errors as $errmsg) {
+ dol_syslog(get_class($this)."::update ".$errmsg, LOG_ERR);
+ $this->error .= ($this->error ? ', '.$errmsg : $errmsg);
+ }
+ $this->db->rollback();
+ return -1 * $error;
+ } else {
+ $this->db->commit();
+ return 1;
+ }
+ }
+
+ /**
+ * Delete the email template
+ *
+ * @param User $user User object
+ * @param int $notrigger 1=Does not execute triggers, 0= execute triggers
+ * @return int Return integer <=0 if KO, >0 if OK
+ */
+ public function delete($user, $notrigger = 0)
+ {
+ $error = 0;
+
+ dol_syslog(get_class($this)."::delete ".$this->id, LOG_DEBUG);
+
+ $this->db->begin();
+
+ if (!$notrigger) {
+ // Call trigger
+ $result = $this->call_trigger(self::TRIGGER_PREFIX.'_DELETE', $user);
+ if ($result < 0) {
+ $error++;
+ }
+ // End call triggers
+ }
+
+ // Delete object link
+ if (!$error) {
+ $sql = "DELETE FROM ".MAIN_DB_PREFIX.$this->table_element." WHERE rowid = ".((int) $this->id);
+ $res = $this->db->query($sql);
+ if (!$res) {
+ $error++;
+ $this->error = $this->db->lasterror();
+ $this->errors[] = $this->error;
+ dol_syslog(get_class($this)."::delete error ".$this->error, LOG_ERR);
+ }
+ }
+
+ if (!$error) {
+ dol_syslog(get_class($this)."::delete ".$this->id." by ".$user->id, LOG_DEBUG);
+ $this->db->commit();
+ return 1;
+ } else {
+ $this->db->rollback();
+ return -1;
+ }
+ }
+
+ /**
+ * Load object in memory from the database
+ *
+ * @param int $id Id object
+ * @param string $label Ref
+ * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields
+ * @param int $nolines 0=Default to load extrafields, 1=No extrafields
+ * @return int Return integer <0 if KO, 0 if not found, >0 if OK
+ */
+ public function fetch($id, $label = null, $noextrafields = 0, $nolines = 0)
+ {
+ // The table llx_c_email_templates has no field ref. The field ref was named "label" instead. So we change the call to fetchCommon.
+ //$result = $this->fetchCommon($id, $label, '', $noextrafields);
+ $result = $this->fetchCommon($id, '', " AND t.label = '".$this->db->escape($label)."'", $noextrafields);
+
+ if ($result > 0 && !empty($this->table_element_line) && empty($nolines)) {
+ $this->fetchLines($noextrafields);
+ }
+ return $result;
+ }
+
+ /**
+ * Get email template from database.
+ *
+ * @param int $id row Id of email template
+ * @param string $label label of email template
+ * @return int >0 if OK, <0 if KO, 0 if not found
+ */
+ public function apifetch($id, $label = '')
+ {
+ // Check parameters
+ if (($id ==0 || empty($id)) && empty($label)) {
+ dol_syslog(get_class($this)."::apifetch id and label are empty", LOG_DEBUG);
+ $this->error = 'id='.$id.' and label are empty';
+ return -1;
+ }
+
+ $sql = "SELECT e.rowid, e.entity, e.module, e.type_template, e.lang,";
+ $sql .= " e.private, e.fk_user, e.datec, e.tms, e.label, e.position,";
+ $sql .= " e.defaultfortype, e.enabled, e.active, e.email_from, e.email_to,";
+ $sql .= " e.email_tocc, e.email_tobcc, e.topic, e.joinfiles, e.content,";
+ $sql .= " e.content_lines FROM ".$this->db->prefix().$this->table_element." as e";
+ if ($id) {
+ $sql .= " WHERE e.rowid = ".((int) $id);
+ } else {
+ $sql .= " WHERE e.entity IN (".getEntity($this->table_element).")";
+ if ($label) {
+ $sql .= " AND e.label = '".$this->db->escape($label)."'";
+ }
+ }
+
+ dol_syslog(get_class($this)."::apifetch", LOG_DEBUG);
+ $result = $this->db->query($sql);
+ if ($result) {
+ $obj = $this->db->fetch_object($result);
+ if ($obj) {
+ $this->id = (int) $obj->rowid;
+ $this->entity = (int) $obj->entity;
+
+ $this->active = (int) $obj->active;
+ $this->content = (string) $obj->content;
+ $this->content_lines = (string) $obj->content_lines;
+ $this->datec = (int) $obj->datec;
+ $this->defaultfortype = (int) $obj->defaultfortype;
+ $this->email_from = (string) $obj->email_from;
+ $this->email_to = (string) $obj->email_to;
+ $this->email_tobcc = (string) $obj->email_tobcc;
+ $this->email_tocc = (string) $obj->email_tocc;
+ $this->enabled = (string) $obj->enabled;
+ $this->fk_user = (int) $obj->fk_user;
+ $this->joinfiles = (int) $obj->joinfiles;
+ $this->label = (string) $obj->label;
+ $this->lang = (string) $obj->lang;
+ $this->module = (string) $obj->module;
+ $this->position = (int) $obj->position;
+ $this->private = (int) $obj->private;
+ $this->tms = $obj->tms;
+ $this->topic = (string) $obj->topic;
+ $this->type_template = (string) $obj->type_template;
+
+ // direct copy from facture.class.php
+ $this->date_creation = $this->db->jdate($obj->datec);
+
+ return 1;
+ } else {
+ if ($id) {
+ $this->error = 'Email template with id '.((string) $id).' not found sql='.$sql;
+ } elseif ($label) {
+ $this->error = 'Email template with label '.$label.' not found sql='.$sql;
+ }
+ return 0;
+ }
+ } else {
+ $this->error = $this->db->error();
+ return -1;
+ }
+ }
+}
+
+/**
+ * old class name for Object of table llx_c_email_templates
+ * I prefer the cEmailTemplate name as it better reflects the database
+ */
+class ModelMail extends cEmailTemplate
+{
+ // just another name
+}
diff --git a/htdocs/core/class/html.formmail.class.php b/htdocs/core/class/html.formmail.class.php
index 45883d298db..4ca80a39a34 100644
--- a/htdocs/core/class/html.formmail.class.php
+++ b/htdocs/core/class/html.formmail.class.php
@@ -31,6 +31,7 @@
* \brief Fichier de la class permettant la generation du formulaire html d'envoi de mail unitaire
*/
require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
+require_once DOL_DOCUMENT_ROOT.'/core/class/cemailtemplate.class.php';
/**
@@ -2137,217 +2138,3 @@ class FormMail extends Form
return $tmparray;
}
}
-
-
-require_once DOL_DOCUMENT_ROOT.'/core/class/commonobject.class.php';
-
-/**
- * Object of table llx_c_email_templates
- *
- * TODO Move this class into a file cemailtemplate.class.php
- */
-class ModelMail extends CommonObject
-{
- /**
- * @var string ID to identify managed object.
- */
- public $element = 'email_template';
-
- /**
- * @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 = 'c_email_templates';
-
-
- // BEGIN MODULEBUILDER PROPERTIES
- /**
- * @var array|string,position:int,notnull?:int,visible:int<-6,6>|string,alwayseditable?:int<0,1>,noteditable?:int<0,1>,default?:string,index?:int,foreignkey?:string,searchall?:int<0,1>,isameasure?:int<0,1>,css?:string,csslist?:string,help?:string,showoncombobox?:int<0,4>,disabled?:int<0,1>,arrayofkeyval?:array,autofocusoncreate?:int<0,1>,comment?:string,copytoclipboard?:int<1,2>,validate?:int<0,1>,showonheader?:int<0,1>}> 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' => 10, 'notnull' => 1, 'visible' => -1,),
- "module" => array("type" => "varchar(32)", "label" => "Module", 'enabled' => 1, 'position' => 20, 'notnull' => 0, 'visible' => -1,),
- "type_template" => array("type" => "varchar(32)", "label" => "Typetemplate", 'enabled' => 1, 'position' => 25, 'notnull' => 0, 'visible' => -1,),
- "lang" => array("type" => "varchar(6)", "label" => "Lang", 'enabled' => 1, 'position' => 30, 'notnull' => 0, 'visible' => -1,),
- "private" => array("type" => "smallint(6)", "label" => "Private", 'enabled' => 1, 'position' => 35, 'notnull' => 1, 'visible' => -1,),
- "fk_user" => array("type" => "integer:User:user/class/user.class.php", "label" => "Fkuser", 'enabled' => 1, 'position' => 40, 'notnull' => 0, 'visible' => -1, "css" => "maxwidth500 widthcentpercentminusxx", "csslist" => "tdoverflowmax150",),
- "datec" => array("type" => "datetime", "label" => "DateCreation", 'enabled' => 1, 'position' => 45, 'notnull' => 0, 'visible' => -1,),
- "tms" => array("type" => "timestamp", "label" => "DateModification", 'enabled' => 1, 'position' => 50, 'notnull' => 1, 'visible' => -1,),
- "label" => array("type" => "varchar(255)", "label" => "Label", 'enabled' => 1, 'position' => 55, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1, "css" => "minwidth300", "cssview" => "wordbreak", "csslist" => "tdoverflowmax150",),
- "position" => array("type" => "smallint(6)", "label" => "Position", 'enabled' => 1, 'position' => 60, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "active" => array("type" => "integer", "label" => "Active", 'enabled' => 1, 'position' => 65, 'notnull' => 1, 'visible' => -1, 'alwayseditable' => 1,),
- "topic" => array("type" => "text", "label" => "Topic", 'enabled' => 1, 'position' => 70, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "content" => array("type" => "mediumtext", "label" => "Content", 'enabled' => 1, 'position' => 75, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "content_lines" => array("type" => "text", "label" => "Contentlines", "enabled" => "getDolGlobalString('MAIN_EMAIL_TEMPLATES_FOR_OBJECT_LINES')", 'position' => 80, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "enabled" => array("type" => "varchar(255)", "label" => "Enabled", 'enabled' => 1, 'position' => 85, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "joinfiles" => array("type" => "varchar(255)", "label" => "Joinfiles", 'enabled' => 1, 'position' => 90, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "email_from" => array("type" => "varchar(255)", "label" => "Emailfrom", 'enabled' => 1, 'position' => 95, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "email_to" => array("type" => "varchar(255)", "label" => "Emailto", 'enabled' => 1, 'position' => 100, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "email_tocc" => array("type" => "varchar(255)", "label" => "Emailtocc", 'enabled' => 1, 'position' => 105, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "email_tobcc" => array("type" => "varchar(255)", "label" => "Emailtobcc", 'enabled' => 1, 'position' => 110, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- "defaultfortype" => array("type" => "smallint(6)", "label" => "Defaultfortype", 'enabled' => 1, 'position' => 115, 'notnull' => 0, 'visible' => -1, 'alwayseditable' => 1,),
- );
- /**
- * @var int
- */
- public $rowid;
- /**
- * @var string
- */
- public $type_template;
- /**
- * @var int|string
- */
- public $datec;
- /**
- * @var int
- */
- public $tms;
- /**
- * @var int
- */
- public $active;
- /**
- * @var string
- */
- public $enabled;
- /**
- * @var int
- */
- public $defaultfortype;
-
- /**
- * @var int ID
- */
- public $id;
-
- /**
- * @var string Model mail label
- */
- public $label;
-
- /**
- * @var int Owner of email template
- */
- public $fk_user;
-
- /**
- * @var int Is template private
- */
- public $private;
-
- /**
- * @var string Model mail topic
- */
- public $topic;
-
- /**
- * @var string Model mail content
- */
- public $content;
- /**
- * @var string Model to use to generate the string with each lines
- */
- public $content_lines;
-
- /**
- * @var string
- */
- public $lang;
- /**
- * @var int<0,1>
- */
- public $joinfiles;
-
- /**
- * @var string
- */
- public $email_from;
- /**
- * @var string
- */
- public $email_to;
- /**
- * @var string
- */
- public $email_tocc;
- /**
- * @var string
- */
- public $email_tobcc;
-
- /**
- * @var string Module the template is dedicated for
- */
- public $module;
-
- /**
- * @var int Position of template in a combo list
- */
- public $position;
- // END MODULEBUILDER PROPERTIES
-
-
-
- /**
- * Constructor
- *
- * @param DoliDB $db Database handler
- */
- public function __construct(DoliDB $db)
- {
- global $langs;
-
- $this->db = $db;
- $this->ismultientitymanaged = 0;
- $this->isextrafieldmanaged = 1;
-
- // @phan-suppress-next-line PhanTypeMismatchProperty
- 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('test', 'mailtemplate', '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);
- }
- }
- }
- }
- }
-
-
- /**
- * Load object in memory from the database
- *
- * @param int $id Id object
- * @param string $ref Ref
- * @param int $noextrafields 0=Default to load extrafields, 1=No extrafields
- * @return int Return integer <0 if KO, 0 if not found, >0 if OK
- */
- public function fetch($id, $ref = null, $noextrafields = 0)
- {
- // The table llx_c_email_templates has no field ref. The field ref was named "label" instead. So we change the call to fetchCommon.
- // $result = $this->fetchCommon($id, $ref, '', $noextrafields);
-
- return $this->fetchCommon($id, '', (empty($ref) ? '' : " AND t.label = '".$this->db->escape($ref)."'"), $noextrafields);
- }
-}
diff --git a/htdocs/core/lib/functions2.lib.php b/htdocs/core/lib/functions2.lib.php
index cb3ef2a1c85..a094248fbd0 100644
--- a/htdocs/core/lib/functions2.lib.php
+++ b/htdocs/core/lib/functions2.lib.php
@@ -2651,7 +2651,7 @@ function getModuleDirForApiClass($moduleobject)
if ($moduleobject == 'contracts') {
$moduledirforclass = 'contrat';
- } elseif (in_array($moduleobject, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents', 'objectlinks'))) {
+ } elseif (in_array($moduleobject, array('admin', 'login', 'setup', 'access', 'status', 'tools', 'documents', 'objectlinks', 'emailtemplates'))) {
$moduledirforclass = 'api';
} elseif (in_array($moduleobject, ['contact', 'contacts', 'customer', 'thirdparty', 'thirdparties'])) {
$moduledirforclass = 'societe';
diff --git a/test/hurl/api/emailtemplates/10_emailtemplates.hurl b/test/hurl/api/emailtemplates/10_emailtemplates.hurl
new file mode 100644
index 00000000000..c1fa92cb23c
--- /dev/null
+++ b/test/hurl/api/emailtemplates/10_emailtemplates.hurl
@@ -0,0 +1,98 @@
+# GET emailtemplates
+GET http://{{hostnport}}/api/index.php/emailtemplates
+HTTP 200
+
+# GET sorted emailtemplates
+GET http://{{hostnport}}/api/index.php/emailtemplates?sortfield=e.rowid&sortorder=ASC
+HTTP 200
+
+# GET sorted emailtemplates
+GET http://{{hostnport}}/api/index.php/emailtemplates?sortfield=e.rowid&sortorder=DSC
+HTTP 200
+
+# GET with limit and page
+GET http://{{hostnport}}/api/index.php/emailtemplates?limit=100&page=1
+HTTP 200
+
+# GET with fk_user
+GET http://{{hostnport}}/api/index.php/emailtemplates?fk_user=0
+HTTP 200
+
+# GET with properties=id%2Cstatus
+GET http://{{hostnport}}/api/index.php/emailtemplates?properties=id%2Cstatus
+HTTP 200
+
+# GET with pagination_data=false
+GET http://{{hostnport}}/api/index.php/emailtemplates?pagination_data=false
+HTTP 200
+
+# GET with pagination_data=true
+GET http://{{hostnport}}/api/index.php/emailtemplates?pagination_data=true
+HTTP 200
+[Asserts]
+jsonpath "$.data" exists
+jsonpath "$.pagination.total" >= 0
+jsonpath "$.pagination.page" >= 0
+jsonpath "$.pagination.page_count" >= 0
+jsonpath "$.pagination.limit" == 100
+
+# GET mailing with ID 0 - which should not exist
+GET http://{{hostnport}}/api/index.php/emailtemplates/0
+HTTP 400
+{"error":{"code":400,"message":"Bad Request: Error: id=0 and label are empty"}}
+
+# POST {}
+POST http://{{hostnport}}/api/index.php/emailtemplates
+{}
+HTTP 400
+{"error":{"code":400,"message":"Bad Request: label field missing"}}
+
+# POST topic required
+POST http://{{hostnport}}/api/index.php/emailtemplates
+{ "id" : 42, "label" : "automatic test using 10_emailtemplates.hurl"}
+HTTP 400
+{"error":{"code":400,"message":"Bad Request: topic field missing"}}
+
+# POST type_template field required
+POST http://{{hostnport}}/api/index.php/emailtemplates
+{ "id" : 42, "label" : "automatic test using 10_emailtemplates.hurl", "topic" : "automatic test using 10_emailtemplates.hurl" }
+HTTP 400
+{"error":{"code":400,"message":"Bad Request: type_template field missing"}}
+
+# POST No id in post request data
+POST http://{{hostnport}}/api/index.php/emailtemplates
+{ "id" : 42, "label" : "automatic test using 10_emailtemplates.hurl", "topic" : "automatic test using 10_emailtemplates.hurl", "type_template" : "all" }
+HTTP 400
+{"error":{"code":400,"message":"Bad Request: Creating with id field is forbidden"}}
+
+# DELETE
+DELETE http://{{hostnport}}/api/index.php/emailtemplates/
+HTTP 405
+
+# DELETE mailing with ID 0 - which should not exist
+DELETE http://{{hostnport}}/api/index.php/emailtemplates/0
+HTTP 404
+{"error":{"code":404,"message":"Not Found: Email Template with id 0 not found"}}
+
+# PUT
+PUT http://{{hostnport}}/api/index.php/emailtemplates/
+{}
+HTTP 405
+
+# PUT
+PUT http://{{hostnport}}/api/index.php/emailtemplates/0
+{}
+HTTP 404
+{"error":{"code":404,"message":"Not Found: email template with id=0 not found"}}
+
+
+# GET emailtemplates DOLAPIENTITY: 1
+GET http://{{hostnport}}/api/index.php/emailtemplates
+DOLAPIENTITY: 1
+HTTP 200
+
+# GET emailtemplates DOLAPIENTITY: 2
+GET http://{{hostnport}}/api/index.php/emailtemplates
+DOLAPIENTITY: 2
+HTTP 401
+{"error":{"code":401,"message":"Unauthorized: Error user not valid (not found with api key or bad status or bad validity dates) (conf->entity=2)"}}
diff --git a/test/hurl/gui/admin/10_mails_templates.hurl b/test/hurl/gui/admin/10_mails_templates.hurl
new file mode 100644
index 00000000000..d24ba9e349d
--- /dev/null
+++ b/test/hurl/gui/admin/10_mails_templates.hurl
@@ -0,0 +1,19 @@
+GET http://{{hostnport}}/admin/mails_templates.php
+HTTP 200
+[Asserts]
+body not contains "Enter login details"
+body contains ""
+body contains "Emails setup"
+body contains "Email templates"
+body contains "Attach file"
+body contains "Code"
+body contains "Default"
+body contains "Language"
+body contains "Module/Application"
+body contains "Owner"
+body contains "Position"
+body contains "Private"
+body contains "Status"
+body contains "Subject"
+body contains "Type of template"
+body contains "NewEMailTemplate"