dolibarr 25.0.0-alpha
api_emailtemplates.class.php
1<?php
2/*
3/* Copyright (C) 2025 Jon Bendtsen <jon.bendtsen.github@jonb.dk>
4 * Copyright (C) 2025 Frédéric France <frederic.france@free.fr>
5 *
6 * This program is free software; you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation; either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
20use Luracast\Restler\RestException;
21
22require_once DOL_DOCUMENT_ROOT.'/api/class/api.class.php';
23require_once DOL_DOCUMENT_ROOT.'/core/class/cemailtemplate.class.php';
24
32{
36 public static $FIELDS = array(
37 'label',
38 'topic',
39 'type_template'
40 );
41
45 public static $INTFIELDS = array(
46 'active',
47 'private',
48 'fk_user',
49 'joinfiles',
50 'position'
51 );
52
56 public $email_template;
57
61 public $element = 'email_templates';
62
66 public $table_element = 'c_email_templates';
67
71 public function __construct()
72 {
73 global $db;
74 $this->db = $db;
75 $this->email_template = new CEmailTemplate($this->db);
76 }
77
92 public function deleteById($id)
93 {
94 $allowaccess = $this->_checkAccessRights('supprimer');
95 if (!$allowaccess) {
96 throw new RestException(403, 'denied delete access to email templates');
97 }
98
99 $result = $this->email_template->apiFetch($id, '', DolibarrApiAccess::$user);
100 if (!$result || $id == 0) {
101 throw new RestException(404, 'Email Template with id '.$id.' not found');
102 }
103
104 if (!DolibarrApiAccess::$user->admin && (int) DolibarrApiAccess::$user->id != $this->email_template->fk_user) {
105 throw new RestException(403, 'denied delete access to email templates');
106 }
107
108 if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
109 throw new RestException(500, 'Error when delete email template : '.$this->email_template->errorsToString());
110 }
111
112 return array(
113 'success' => array(
114 'code' => 200,
115 'message' => 'email template deleted'
116 )
117 );
118 }
119
134 public function deleteByLabel($label)
135 {
136 $allowaccess = $this->_checkAccessRights('supprimer');
137 if (!$allowaccess) {
138 throw new RestException(403, 'denied delete access to email templates');
139 }
140
141 $result = $this->email_template->apiFetch(0, $label, DolibarrApiAccess::$user);
142 if (!$result) {
143 throw new RestException(404, "Email Template with label ".$label." not found");
144 }
145
146 if (!DolibarrApiAccess::$user->admin && (int) DolibarrApiAccess::$user->id != $this->email_template->fk_user) {
147 throw new RestException(403, 'denied delete access to email templates');
148 }
149
150 if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
151 throw new RestException(500, 'Error when delete email template : '.$this->email_template->errorsToString());
152 }
153
154 return array(
155 'success' => array(
156 'code' => 200,
157 'message' => 'email template deleted'
158 )
159 );
160 }
161
177 public function getById($id)
178 {
179 return $this->_fetch($id, '');
180 }
181
197 public function getByLabel($label)
198 {
199 return $this->_fetch(0, $label);
200 }
201
224 public function index($sortfield = "e.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $fk_user = '', $sqlfilters = '', $properties = '', $pagination_data = false)
225 {
226 $allowaccess = $this->_checkAccessRights('lire');
227 if (!$allowaccess) {
228 throw new RestException(403, 'denied read access to email templates');
229 }
230
231 $obj_ret = array();
232
233 $sql = "SELECT e.rowid";
234 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." AS e";
235 $sql .= " WHERE e.entity IN (".getEntity($this->element).")";
236 if (!$fk_user == '') {
237 $sql .= " AND e.fk_user = ".((int) $fk_user);
238 }
239 if (!DolibarrApiAccess::$user->admin) {
240 $sql .= " AND e.fk_user = ".((int) DolibarrApiAccess::$user->id);
241 }
242
243 // Add sql filters
244 if ($sqlfilters) {
245 $errormessage = '';
246 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
247 if ($errormessage) {
248 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
249 }
250 }
251
252 //this query will return total orders with the filters given
253 $sqlTotals = str_replace('SELECT e.rowid', 'SELECT count(e.rowid) as total', $sql);
254
255 $sql .= $this->db->order($sortfield, $sortorder);
256 if ($limit) {
257 if ($page < 0) {
258 $page = 0;
259 }
260 $offset = $limit * $page;
261
262 $sql .= $this->db->plimit($limit + 1, $offset);
263 }
264
265 dol_syslog(get_class($this)."::index", LOG_DEBUG);
266 $result = $this->db->query($sql);
267 dol_syslog(get_class($this)."::pindex", LOG_DEBUG);
268
269 if ($result) {
270 $num = $this->db->num_rows($result);
271 $min = min($num, ($limit <= 0 ? $num : $limit));
272 $i = 0;
273 while ($i < $min) {
274 $obj = $this->db->fetch_object($result);
275 $email_template_static = new CEmailTemplate($this->db);
276 if ($email_template_static->apiFetch($obj->rowid, '', DolibarrApiAccess::$user) > 0) {
277 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($email_template_static), $properties);
278 }
279 $i++;
280 }
281 } else {
282 throw new RestException(503, 'Error when retrieve email template list : '.$this->db->lasterror());
283 }
284
285 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
286 if ($pagination_data) {
287 $totalsResult = $this->db->query($sqlTotals);
288 $total = $this->db->fetch_object($totalsResult)->total;
289
290 $tmp = $obj_ret;
291 $obj_ret = [];
292
293 $obj_ret['data'] = $tmp;
294 $obj_ret['pagination'] = [
295 'total' => (int) $total,
296 'page' => $page, //count starts from 0
297 'page_count' => ceil((int) $total / $limit),
298 'limit' => $limit
299 ];
300 }
301
302 return $obj_ret;
303 }
304
323 public function post($request_data = null)
324 {
325 $allowaccess = $this->_checkAccessRights('creer');
326 if (!$allowaccess) {
327 throw new RestException(403, 'denied create access to email templates');
328 }
329
330 // Check mandatory fields
331 $result = $this->_validate($request_data);
332
333 foreach ($request_data as $field => $value) {
334 if ($field === 'caller') {
335 // 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
336 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
337 continue;
338 }
339 if ($field == 'id') {
340 throw new RestException(400, 'Creating with id field is forbidden');
341 }
342 if ($field == 'tms') {
343 throw new RestException(400, 'Creating with tms field is forbidden');
344 }
345 if ($field == 'fk_user') {
346 if (!DolibarrApiAccess::$user->admin) {
347 $request_data[$field] = (int) DolibarrApiAccess::$user->id; // Same rule than into admin/mails_templates.php
348 }
349 }
350
351 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
352 }
353
354 if ($this->email_template->create(DolibarrApiAccess::$user) < 0) {
355 throw new RestException(500, "Error creating email template", array_merge(array($this->email_template->error), $this->email_template->errors));
356 }
357
358 return ((int) $this->email_template->id);
359 }
360
381 public function putById($id, $request_data = null)
382 {
383 $allowaccess = $this->_checkAccessRights('creer');
384 if (!$allowaccess) {
385 throw new RestException(403, 'denied update access to email templates');
386 }
387
388 $result = $this->email_template->apiFetch($id, '', DolibarrApiAccess::$user);
389 if (!$result || $id == 0) {
390 throw new RestException(404, 'email template with id='.$id.' not found');
391 }
392
393 foreach ($request_data as $field => $value) {
394 if ($field == 'id') {
395 throw new RestException(400, 'Updating with id field is forbidden');
396 }
397 if ($field == 'datec') {
398 throw new RestException(400, 'Updating with datec field is forbidden');
399 }
400 if ($field == 'fk_user') {
401 if (!DolibarrApiAccess::$user->admin && (int) $value != $this->email_template->fk_user) {
402 throw new RestException(400, 'Updating with fk_user that is not yourself is not allowed if you are not admin');
403 }
404 }
405
406 if ($field === 'caller') {
407 // 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
408 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
409 continue;
410 }
411
412 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
413 }
414
415 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
416 return $this->_fetch($id, '');
417 } else {
418 throw new RestException(500, $this->email_template->errorsToString());
419 }
420 }
421
441 public function putbyLabel($label, $request_data = null)
442 {
443 $allowaccess = $this->_checkAccessRights('creer');
444 if (!$allowaccess) {
445 throw new RestException(403, 'denied update access to email templates');
446 }
447
448 $result = $this->email_template->apiFetch(0, $label, DolibarrApiAccess::$user);
449 if (!$result) {
450 throw new RestException(404, 'email template not found');
451 }
452
453 $newlabel = $label;
454 foreach ($request_data as $field => $value) {
455 if ($field == 'id') {
456 throw new RestException(400, 'Updating with id field is forbidden');
457 }
458 if ($field == 'datec') {
459 throw new RestException(400, 'Updating with datec field is forbidden');
460 }
461 if ($field == 'fk_user') {
462 if (!DolibarrApiAccess::$user->admin && (int) $value != $this->email_template->fk_user) {
463 throw new RestException(400, 'Updating with fk_user that is not yourself is not allowed if you are not admin');
464 }
465 }
466
467 if ($field == 'label') {
468 $newlabel = $this->_checkValForAPI($field, $value, $this->email_template);
469 }
470 if ($field === 'caller') {
471 // 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
472 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
473 continue;
474 }
475
476 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
477 }
478
479 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
480 return $this->_fetch(0, $newlabel);
481 } else {
482 throw new RestException(500, $this->email_template->errorsToString());
483 }
484 }
485
501 private function _fetch($id, $label = '')
502 {
503 global $conf;
504
505 $allowaccess = $this->_checkAccessRights('lire');
506 if (!$allowaccess) {
507 throw new RestException(403, 'denied read access to email templates');
508 }
509
510 $result = $this->email_template->apiFetch($id, $label, DolibarrApiAccess::$user);
511 if ($result > 0) {
512 return $this->_cleanObjectDatas($this->email_template);
513 }
514 if ($result == 0) {
515 if ($id) {
516 throw new RestException(404, 'Email template with id='.((string) $id).' not found in entity='.(int) $conf->entity);
517 }
518 if ($label) {
519 throw new RestException(404, 'Email template with label '.$label.' not found in entity='.(int) $conf->entity);
520 }
521 throw new RestException(404, 'Email Template not found');
522 } else {
523 if (empty($this->email_template->errorsToString())) {
524 throw new RestException(400, 'Unknown error in your request');
525 } else {
526 throw new RestException(400, 'Error: '.$this->email_template->errorsToString());
527 }
528 }
529 }
530
531 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
544 protected function _cleanObjectDatas($object)
545 {
546 // phpcs:enable
547 $object = parent::_cleanObjectDatas($object);
548 dol_syslog(get_class($this)."::_cleanObjectDatas", LOG_DEBUG);
549
550
551 unset($object->import_key);
552 unset($object->array_languages);
553 unset($object->contacts_ids);
554 unset($object->linkedObjectsIds);
555 unset($object->canvas);
556 unset($object->fk_project);
557 unset($object->contact_id);
558 unset($object->user);
559 unset($object->origin_type);
560 unset($object->origin_id);
561 unset($object->ref);
562 unset($object->ref_ext);
563 unset($object->statut);
564 unset($object->status);
565 unset($object->civility_code);
566 unset($object->country_id);
567 unset($object->country_code);
568 unset($object->state_id);
569 unset($object->region_id);
570 unset($object->barcode_type);
571 unset($object->barcode_type_coder);
572 unset($object->mode_reglement_id);
573 unset($object->cond_reglement_id);
574 unset($object->demand_reason_id);
575 unset($object->transport_mode_id);
576 unset($object->shipping_method_id);
577 unset($object->shipping_method);
578 unset($object->fk_multicurrency);
579 unset($object->multicurrency_code);
580 unset($object->multicurrency_tx);
581 unset($object->multicurrency_total_ht);
582 unset($object->multicurrency_total_tva);
583 unset($object->multicurrency_total_ttc);
584 unset($object->multicurrency_total_localtax1);
585 unset($object->multicurrency_total_localtax2);
586 unset($object->last_main_doc);
587 unset($object->fk_account);
588 unset($object->note_public);
589 unset($object->note_private);
590 unset($object->total_ht);
591 unset($object->total_tva);
592 unset($object->total_localtax1);
593 unset($object->total_localtax2);
594 unset($object->total_ttc);
595 unset($object->lines);
596 unset($object->actiontypecode);
597 unset($object->name);
598 unset($object->lastname);
599 unset($object->firstname);
600 unset($object->civility_id);
601 unset($object->user_author);
602 unset($object->user_creation);
603 unset($object->user_creation_id);
604 unset($object->user_valid);
605 unset($object->user_validation);
606 unset($object->user_validation_id);
607 unset($object->user_closing_id);
608 unset($object->user_modification);
609 unset($object->user_modification_id);
610 unset($object->fk_user_creat);
611 unset($object->fk_user_modif);
612 unset($object->totalpaid);
613 unset($object->product);
614 unset($object->cond_reglement_supplier_id);
615 unset($object->deposit_percent);
616 unset($object->retained_warranty_fk_cond_reglement);
617 unset($object->warehouse_id);
618 unset($object->target);
619 unset($object->array_options);
620 unset($object->extraparams);
621 unset($object->specimen);
622 unset($object->date_validation);
623 unset($object->date_modification);
624 unset($object->date_cloture);
625 unset($object->rowid);
626
627 return $object;
628 }
629
639 private function _validate($data)
640 {
641 $email_template = array();
642 foreach (EmailTemplates::$FIELDS as $field) {
643 if (!isset($data[$field])) {
644 throw new RestException(400, $field." field missing");
645 }
646 $email_template[$field] = $data[$field];
647 }
648 return $email_template;
649 }
650
660 private function _checkAccessRights($accesstype)
661 {
662 // what kind of access management do we need?
663 $allowaccess = false;
664 if (isModEnabled("societe") && DolibarrApiAccess::$user->hasRight('societe', $accesstype)) {
665 $allowaccess = true;
666 }
667 if (isModEnabled('member') && DolibarrApiAccess::$user->hasRight('adherent', $accesstype)) {
668 $allowaccess = true;
669 }
670 if (isModEnabled("propal") && DolibarrApiAccess::$user->hasRight('propal', $accesstype)) {
671 $allowaccess = true;
672 }
673 if (isModEnabled('order') && DolibarrApiAccess::$user->hasRight('commande', $accesstype)) {
674 $allowaccess = true;
675 }
676 if (isModEnabled('invoice') && DolibarrApiAccess::$user->hasRight('facture', $accesstype)) {
677 $allowaccess = true;
678 }
679 if ($allowaccess) {
680 return $allowaccess;
681 } else {
682 throw new RestException(403, 'denied access to email templates');
683 }
684 }
685}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
Object of table llx_c_email_templates.
Class for API REST v1.
Definition api.class.php:35
_filterObjectProperties($object, $properties)
Filter properties that will be returned on object.
_checkValForAPI($field, $value, $object)
Check and convert a string depending on its type/name.
_validate($data)
Validate fields before create or update object.
_fetch($id, $label='')
Get properties of an email template.
_cleanObjectDatas($object)
Clean sensible object datas @phpstan-template T.
deleteByLabel($label)
Delete an email template.
getById($id)
Get properties of a email template by id.
putbyLabel($label, $request_data=null)
Update an email template.
index($sortfield="e.rowid", $sortorder='ASC', $limit=100, $page=0, $fk_user='', $sqlfilters='', $properties='', $pagination_data=false)
List email templates.
__construct()
Constructor of the class.
post($request_data=null)
Create an email template.
deleteById($id)
Delete an email template.
_checkAccessRights($accesstype)
function to check for access rights - should probably have 1.
putById($id, $request_data=null)
Update an email template.
getByLabel($label)
Get properties of an email template by label.
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0, $forbiddenfields=array())
forgeSQLFromUniversalSearchCriteria
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
isModEnabled($module)
Is Dolibarr module enabled.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.