dolibarr 24.0.1
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/lib/functions.lib.php';
24require_once DOL_DOCUMENT_ROOT.'/core/class/cemailtemplate.class.php';
25
33{
37 public static $FIELDS = array(
38 'label',
39 'topic',
40 'type_template'
41 );
42
46 public static $INTFIELDS = array(
47 'active',
48 'private',
49 'fk_user',
50 'joinfiles',
51 'position'
52 );
53
57 public $email_template;
58
62 public $element = 'email_templates';
63
67 public $table_element = 'c_email_templates';
68
72 public function __construct()
73 {
74 global $db;
75 $this->db = $db;
76 $this->email_template = new CEmailTemplate($this->db);
77 }
78
93 public function deleteById($id)
94 {
95 $allowaccess = $this->_checkAccessRights('supprimer');
96 if (!$allowaccess) {
97 throw new RestException(403, 'denied delete access to email templates');
98 }
99
100 $result = $this->email_template->apiFetch($id, '', DolibarrApiAccess::$user);
101 if (!$result || $id == 0) {
102 throw new RestException(404, 'Email Template with id '.$id.' not found');
103 }
104
105 if (!DolibarrApiAccess::$user->admin && (int) DolibarrApiAccess::$user->id != $this->email_template->fk_user) {
106 throw new RestException(403, 'denied delete access to email templates');
107 }
108
109 if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
110 throw new RestException(500, 'Error when delete email template : '.$this->email_template->error);
111 }
112
113 return array(
114 'success' => array(
115 'code' => 200,
116 'message' => 'email template deleted'
117 )
118 );
119 }
120
135 public function deleteByLabel($label)
136 {
137 $allowaccess = $this->_checkAccessRights('supprimer');
138 if (!$allowaccess) {
139 throw new RestException(403, 'denied delete access to email templates');
140 }
141
142 $result = $this->email_template->apiFetch(0, $label, DolibarrApiAccess::$user);
143 if (!$result) {
144 throw new RestException(404, "Email Template with label ".$label." not found");
145 }
146
147 if (!DolibarrApiAccess::$user->admin && (int) DolibarrApiAccess::$user->id != $this->email_template->fk_user) {
148 throw new RestException(403, 'denied delete access to email templates');
149 }
150
151 if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
152 throw new RestException(500, 'Error when delete email template : '.$this->email_template->error);
153 }
154
155 return array(
156 'success' => array(
157 'code' => 200,
158 'message' => 'email template deleted'
159 )
160 );
161 }
162
178 public function getById($id)
179 {
180 return $this->_fetch($id, '');
181 }
182
198 public function getByLabel($label)
199 {
200 return $this->_fetch(0, $label);
201 }
202
225 public function index($sortfield = "e.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $fk_user = '', $sqlfilters = '', $properties = '', $pagination_data = false)
226 {
227 $allowaccess = $this->_checkAccessRights('lire');
228 if (!$allowaccess) {
229 throw new RestException(403, 'denied read access to email templates');
230 }
231
232 $obj_ret = array();
233
234 $sql = "SELECT e.rowid";
235 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." AS e";
236 $sql .= " WHERE e.entity IN (".getEntity($this->element).")";
237 if (!$fk_user == '') {
238 $sql .= " AND e.fk_user = ".((int) $fk_user);
239 }
240 if (!DolibarrApiAccess::$user->admin) {
241 $sql .= " AND e.fk_user = ".((int) DolibarrApiAccess::$user->id);
242 }
243
244 // Add sql filters
245 if ($sqlfilters) {
246 $errormessage = '';
247 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
248 if ($errormessage) {
249 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
250 }
251 }
252
253 //this query will return total orders with the filters given
254 $sqlTotals = str_replace('SELECT e.rowid', 'SELECT count(e.rowid) as total', $sql);
255
256 $sql .= $this->db->order($sortfield, $sortorder);
257 if ($limit) {
258 if ($page < 0) {
259 $page = 0;
260 }
261 $offset = $limit * $page;
262
263 $sql .= $this->db->plimit($limit + 1, $offset);
264 }
265
266 dol_syslog(get_class($this)."::index", LOG_DEBUG);
267 $result = $this->db->query($sql);
268 dol_syslog(get_class($this)."::pindex", LOG_DEBUG);
269
270 if ($result) {
271 $num = $this->db->num_rows($result);
272 $min = min($num, ($limit <= 0 ? $num : $limit));
273 $i = 0;
274 while ($i < $min) {
275 $obj = $this->db->fetch_object($result);
276 $email_template_static = new CEmailTemplate($this->db);
277 if ($email_template_static->apiFetch($obj->rowid, '', DolibarrApiAccess::$user) > 0) {
278 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($email_template_static), $properties);
279 }
280 $i++;
281 }
282 } else {
283 throw new RestException(503, 'Error when retrieve email template list : '.$this->db->lasterror());
284 }
285
286 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
287 if ($pagination_data) {
288 $totalsResult = $this->db->query($sqlTotals);
289 $total = $this->db->fetch_object($totalsResult)->total;
290
291 $tmp = $obj_ret;
292 $obj_ret = [];
293
294 $obj_ret['data'] = $tmp;
295 $obj_ret['pagination'] = [
296 'total' => (int) $total,
297 'page' => $page, //count starts from 0
298 'page_count' => ceil((int) $total / $limit),
299 'limit' => $limit
300 ];
301 }
302
303 return $obj_ret;
304 }
305
324 public function post($request_data = null)
325 {
326 $allowaccess = $this->_checkAccessRights('creer');
327 if (!$allowaccess) {
328 throw new RestException(403, 'denied create access to email templates');
329 }
330
331 // Check mandatory fields
332 $result = $this->_validate($request_data);
333
334 foreach ($request_data as $field => $value) {
335 if ($field === 'caller') {
336 // 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
337 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
338 continue;
339 }
340 if ($field == 'id') {
341 throw new RestException(400, 'Creating with id field is forbidden');
342 }
343 if ($field == 'tms') {
344 throw new RestException(400, 'Creating with tms field is forbidden');
345 }
346 if ($field == 'fk_user') {
347 if (!DolibarrApiAccess::$user->admin) {
348 $request_data[$field] = (int) DolibarrApiAccess::$user->id; // Same rule than into admin/mails_templates.php
349 }
350 }
351
352 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
353 }
354
355 if ($this->email_template->create(DolibarrApiAccess::$user) < 0) {
356 throw new RestException(500, "Error creating email template", array_merge(array($this->email_template->error), $this->email_template->errors));
357 }
358
359 return ((int) $this->email_template->id);
360 }
361
382 public function putById($id, $request_data = null)
383 {
384 $allowaccess = $this->_checkAccessRights('creer');
385 if (!$allowaccess) {
386 throw new RestException(403, 'denied update access to email templates');
387 }
388
389 $result = $this->email_template->apiFetch($id, '', DolibarrApiAccess::$user);
390 if (!$result || $id == 0) {
391 throw new RestException(404, 'email template with id='.$id.' not found');
392 }
393
394 foreach ($request_data as $field => $value) {
395 if ($field == 'id') {
396 throw new RestException(400, 'Updating with id field is forbidden');
397 }
398 if ($field == 'datec') {
399 throw new RestException(400, 'Updating with datec field is forbidden');
400 }
401 if ($field == 'fk_user') {
402 if (!DolibarrApiAccess::$user->admin && (int) $value != $this->email_template->fk_user) {
403 throw new RestException(400, 'Updating with fk_user that is not yourself is not allowed if you are not admin');
404 }
405 }
406
407 if ($field === 'caller') {
408 // 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
409 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
410 continue;
411 }
412
413 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
414 }
415
416 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
417 return $this->_fetch($id, '');
418 } else {
419 throw new RestException(500, $this->email_template->error);
420 }
421 }
422
442 public function putbyLabel($label, $request_data = null)
443 {
444 $allowaccess = $this->_checkAccessRights('creer');
445 if (!$allowaccess) {
446 throw new RestException(403, 'denied update access to email templates');
447 }
448
449 $result = $this->email_template->apiFetch(0, $label, DolibarrApiAccess::$user);
450 if (!$result) {
451 throw new RestException(404, 'email template not found');
452 }
453
454 $newlabel = $label;
455 foreach ($request_data as $field => $value) {
456 if ($field == 'id') {
457 throw new RestException(400, 'Updating with id field is forbidden');
458 }
459 if ($field == 'datec') {
460 throw new RestException(400, 'Updating with datec field is forbidden');
461 }
462 if ($field == 'fk_user') {
463 if (!DolibarrApiAccess::$user->admin && (int) $value != $this->email_template->fk_user) {
464 throw new RestException(400, 'Updating with fk_user that is not yourself is not allowed if you are not admin');
465 }
466 }
467
468 if ($field == 'label') {
469 $newlabel = $this->_checkValForAPI($field, $value, $this->email_template);
470 }
471 if ($field === 'caller') {
472 // 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
473 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
474 continue;
475 }
476
477 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
478 }
479
480 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
481 return $this->_fetch(0, $newlabel);
482 } else {
483 throw new RestException(500, $this->email_template->error);
484 }
485 }
486
502 private function _fetch($id, $label = '')
503 {
504 global $conf;
505
506 $allowaccess = $this->_checkAccessRights('lire');
507 if (!$allowaccess) {
508 throw new RestException(403, 'denied read access to email templates');
509 }
510
511 $result = $this->email_template->apiFetch($id, $label, DolibarrApiAccess::$user);
512 if ($result > 0) {
513 return $this->_cleanObjectDatas($this->email_template);
514 }
515 if ($result == 0) {
516 if ($id) {
517 throw new RestException(404, 'Email template with id='.((string) $id).' not found in entity='.(int) $conf->entity);
518 }
519 if ($label) {
520 throw new RestException(404, 'Email template with label '.$label.' not found in entity='.(int) $conf->entity);
521 }
522 throw new RestException(404, 'Email Template not found');
523 } else {
524 if (empty($this->email_template->error)) {
525 throw new RestException(400, 'Unknown error in your request');
526 } else {
527 throw new RestException(400, 'Error: '.$this->email_template->error);
528 }
529 }
530 }
531
532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
545 protected function _cleanObjectDatas($object)
546 {
547 // phpcs:enable
548 $object = parent::_cleanObjectDatas($object);
549 dol_syslog(get_class($this)."::_cleanObjectDatas", LOG_DEBUG);
550
551
552 unset($object->import_key);
553 unset($object->array_languages);
554 unset($object->contacts_ids);
555 unset($object->linkedObjectsIds);
556 unset($object->canvas);
557 unset($object->fk_project);
558 unset($object->contact_id);
559 unset($object->user);
560 unset($object->origin_type);
561 unset($object->origin_id);
562 unset($object->ref);
563 unset($object->ref_ext);
564 unset($object->statut);
565 unset($object->status);
566 unset($object->civility_code);
567 unset($object->country_id);
568 unset($object->country_code);
569 unset($object->state_id);
570 unset($object->region_id);
571 unset($object->barcode_type);
572 unset($object->barcode_type_coder);
573 unset($object->mode_reglement_id);
574 unset($object->cond_reglement_id);
575 unset($object->demand_reason_id);
576 unset($object->transport_mode_id);
577 unset($object->shipping_method_id);
578 unset($object->shipping_method);
579 unset($object->fk_multicurrency);
580 unset($object->multicurrency_code);
581 unset($object->multicurrency_tx);
582 unset($object->multicurrency_total_ht);
583 unset($object->multicurrency_total_tva);
584 unset($object->multicurrency_total_ttc);
585 unset($object->multicurrency_total_localtax1);
586 unset($object->multicurrency_total_localtax2);
587 unset($object->last_main_doc);
588 unset($object->fk_account);
589 unset($object->note_public);
590 unset($object->note_private);
591 unset($object->total_ht);
592 unset($object->total_tva);
593 unset($object->total_localtax1);
594 unset($object->total_localtax2);
595 unset($object->total_ttc);
596 unset($object->lines);
597 unset($object->actiontypecode);
598 unset($object->name);
599 unset($object->lastname);
600 unset($object->firstname);
601 unset($object->civility_id);
602 unset($object->user_author);
603 unset($object->user_creation);
604 unset($object->user_creation_id);
605 unset($object->user_valid);
606 unset($object->user_validation);
607 unset($object->user_validation_id);
608 unset($object->user_closing_id);
609 unset($object->user_modification);
610 unset($object->user_modification_id);
611 unset($object->fk_user_creat);
612 unset($object->fk_user_modif);
613 unset($object->totalpaid);
614 unset($object->product);
615 unset($object->cond_reglement_supplier_id);
616 unset($object->deposit_percent);
617 unset($object->retained_warranty_fk_cond_reglement);
618 unset($object->warehouse_id);
619 unset($object->target);
620 unset($object->array_options);
621 unset($object->extraparams);
622 unset($object->specimen);
623 unset($object->date_validation);
624 unset($object->date_modification);
625 unset($object->date_cloture);
626 unset($object->rowid);
627
628 return $object;
629 }
630
640 private function _validate($data)
641 {
642 $email_template = array();
643 foreach (EmailTemplates::$FIELDS as $field) {
644 if (!isset($data[$field])) {
645 throw new RestException(400, $field." field missing");
646 }
647 $email_template[$field] = $data[$field];
648 }
649 return $email_template;
650 }
651
661 private function _checkAccessRights($accesstype)
662 {
663 // what kind of access management do we need?
664 $allowaccess = false;
665 if (isModEnabled("societe") && DolibarrApiAccess::$user->hasRight('societe', $accesstype)) {
666 $allowaccess = true;
667 }
668 if (isModEnabled('member') && DolibarrApiAccess::$user->hasRight('adherent', $accesstype)) {
669 $allowaccess = true;
670 }
671 if (isModEnabled("propal") && DolibarrApiAccess::$user->hasRight('propal', $accesstype)) {
672 $allowaccess = true;
673 }
674 if (isModEnabled('order') && DolibarrApiAccess::$user->hasRight('commande', $accesstype)) {
675 $allowaccess = true;
676 }
677 if (isModEnabled('invoice') && DolibarrApiAccess::$user->hasRight('facture', $accesstype)) {
678 $allowaccess = true;
679 }
680 if ($allowaccess) {
681 return $allowaccess;
682 } else {
683 throw new RestException(403, 'denied access to email templates');
684 }
685 }
686}
$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:
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $db
API class for accounts.
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.