dolibarr 23.0.4
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 // Same rule than into admin/mails_templates.php: a non admin user creates only his own templates
335 if (!DolibarrApiAccess::$user->admin) {
336 $request_data['fk_user'] = (int) DolibarrApiAccess::$user->id;
337 }
338
339 foreach ($request_data as $field => $value) {
340 if ($field === 'caller') {
341 // 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
342 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
343 continue;
344 }
345 if ($field == 'id') {
346 throw new RestException(400, 'Creating with id field is forbidden');
347 }
348 if ($field == 'tms') {
349 throw new RestException(400, 'Creating with tms field is forbidden');
350 }
351 if ($field == 'fk_user') {
352 if (!DolibarrApiAccess::$user->admin) {
353 $value = (int) DolibarrApiAccess::$user->id; // Same rule than into admin/mails_templates.php
354 }
355 }
356
357 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
358 }
359
360 if ($this->email_template->create(DolibarrApiAccess::$user) < 0) {
361 throw new RestException(500, "Error creating email template", array_merge(array($this->email_template->error), $this->email_template->errors));
362 }
363
364 return ((int) $this->email_template->id);
365 }
366
387 public function putById($id, $request_data = null)
388 {
389 $allowaccess = $this->_checkAccessRights('creer');
390 if (!$allowaccess) {
391 throw new RestException(403, 'denied update access to email templates');
392 }
393
394 $result = $this->email_template->apiFetch($id, '', DolibarrApiAccess::$user);
395 if ($result <= 0 || $id == 0) {
396 throw new RestException(404, 'email template with id='.$id.' not found');
397 }
398 // Same rule than for delete and into admin/mails_templates.php: a non admin user can modify only his own templates
399 if (!DolibarrApiAccess::$user->admin && (int) DolibarrApiAccess::$user->id != $this->email_template->fk_user) {
400 throw new RestException(403, 'denied update access to email templates');
401 }
402
403 foreach ($request_data as $field => $value) {
404 if ($field == 'id') {
405 throw new RestException(400, 'Updating with id field is forbidden');
406 }
407 if ($field == 'datec') {
408 throw new RestException(400, 'Updating with datec field is forbidden');
409 }
410 if ($field == 'fk_user') {
411 if (!DolibarrApiAccess::$user->admin && (int) $value != $this->email_template->fk_user) {
412 throw new RestException(400, 'Updating with fk_user that is not yourself is not allowed if you are not admin');
413 }
414 }
415
416 if ($field === 'caller') {
417 // 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
418 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
419 continue;
420 }
421
422 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
423 }
424
425 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
426 return $this->_fetch($id, '');
427 } else {
428 throw new RestException(500, $this->email_template->error);
429 }
430 }
431
451 public function putbyLabel($label, $request_data = null)
452 {
453 $allowaccess = $this->_checkAccessRights('creer');
454 if (!$allowaccess) {
455 throw new RestException(403, 'denied update access to email templates');
456 }
457
458 $result = $this->email_template->apiFetch(0, $label, DolibarrApiAccess::$user);
459 if ($result <= 0) {
460 throw new RestException(404, 'email template not found');
461 }
462 // Same rule than for delete and into admin/mails_templates.php: a non admin user can modify only his own templates
463 if (!DolibarrApiAccess::$user->admin && (int) DolibarrApiAccess::$user->id != $this->email_template->fk_user) {
464 throw new RestException(403, 'denied update access to email templates');
465 }
466
467 $newlabel = $label;
468 foreach ($request_data as $field => $value) {
469 if ($field == 'id') {
470 throw new RestException(400, 'Updating with id field is forbidden');
471 }
472 if ($field == 'datec') {
473 throw new RestException(400, 'Updating with datec field is forbidden');
474 }
475 if ($field == 'fk_user') {
476 if (!DolibarrApiAccess::$user->admin && (int) $value != $this->email_template->fk_user) {
477 throw new RestException(400, 'Updating with fk_user that is not yourself is not allowed if you are not admin');
478 }
479 }
480
481 if ($field == 'label') {
482 $newlabel = $this->_checkValForAPI($field, $value, $this->email_template);
483 }
484 if ($field === 'caller') {
485 // 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
486 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
487 continue;
488 }
489
490 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
491 }
492
493 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
494 return $this->_fetch(0, $newlabel);
495 } else {
496 throw new RestException(500, $this->email_template->error);
497 }
498 }
499
515 private function _fetch($id, $label = '')
516 {
517 global $conf;
518
519 $allowaccess = $this->_checkAccessRights('lire');
520 if (!$allowaccess) {
521 throw new RestException(403, 'denied read access to email templates');
522 }
523
524 $result = $this->email_template->apiFetch($id, $label, DolibarrApiAccess::$user);
525 if ($result > 0) {
526 return $this->_cleanObjectDatas($this->email_template);
527 }
528 if ($result == 0) {
529 if ($id) {
530 throw new RestException(404, 'Email template with id='.((string) $id).' not found in entity='.(int) $conf->entity);
531 }
532 if ($label) {
533 throw new RestException(404, 'Email template with label '.$label.' not found in entity='.(int) $conf->entity);
534 }
535 throw new RestException(404, 'Email Template not found');
536 } else {
537 if (empty($this->email_template->error)) {
538 throw new RestException(400, 'Unknown error in your request');
539 } else {
540 throw new RestException(400, 'Error: '.$this->email_template->error);
541 }
542 }
543 }
544
545 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
558 protected function _cleanObjectDatas($object)
559 {
560 // phpcs:enable
561 $object = parent::_cleanObjectDatas($object);
562 dol_syslog(get_class($this)."::_cleanObjectDatas", LOG_DEBUG);
563
564
565 unset($object->import_key);
566 unset($object->array_languages);
567 unset($object->contacts_ids);
568 unset($object->linkedObjectsIds);
569 unset($object->canvas);
570 unset($object->fk_project);
571 unset($object->contact_id);
572 unset($object->user);
573 unset($object->origin_type);
574 unset($object->origin_id);
575 unset($object->ref);
576 unset($object->ref_ext);
577 unset($object->statut);
578 unset($object->status);
579 unset($object->civility_code);
580 unset($object->country_id);
581 unset($object->country_code);
582 unset($object->state_id);
583 unset($object->region_id);
584 unset($object->barcode_type);
585 unset($object->barcode_type_coder);
586 unset($object->mode_reglement_id);
587 unset($object->cond_reglement_id);
588 unset($object->demand_reason_id);
589 unset($object->transport_mode_id);
590 unset($object->shipping_method_id);
591 unset($object->shipping_method);
592 unset($object->fk_multicurrency);
593 unset($object->multicurrency_code);
594 unset($object->multicurrency_tx);
595 unset($object->multicurrency_total_ht);
596 unset($object->multicurrency_total_tva);
597 unset($object->multicurrency_total_ttc);
598 unset($object->multicurrency_total_localtax1);
599 unset($object->multicurrency_total_localtax2);
600 unset($object->last_main_doc);
601 unset($object->fk_account);
602 unset($object->note_public);
603 unset($object->note_private);
604 unset($object->total_ht);
605 unset($object->total_tva);
606 unset($object->total_localtax1);
607 unset($object->total_localtax2);
608 unset($object->total_ttc);
609 unset($object->lines);
610 unset($object->actiontypecode);
611 unset($object->name);
612 unset($object->lastname);
613 unset($object->firstname);
614 unset($object->civility_id);
615 unset($object->user_author);
616 unset($object->user_creation);
617 unset($object->user_creation_id);
618 unset($object->user_valid);
619 unset($object->user_validation);
620 unset($object->user_validation_id);
621 unset($object->user_closing_id);
622 unset($object->user_modification);
623 unset($object->user_modification_id);
624 unset($object->fk_user_creat);
625 unset($object->fk_user_modif);
626 unset($object->totalpaid);
627 unset($object->product);
628 unset($object->cond_reglement_supplier_id);
629 unset($object->deposit_percent);
630 unset($object->retained_warranty_fk_cond_reglement);
631 unset($object->warehouse_id);
632 unset($object->target);
633 unset($object->array_options);
634 unset($object->extraparams);
635 unset($object->specimen);
636 unset($object->date_validation);
637 unset($object->date_modification);
638 unset($object->date_cloture);
639 unset($object->rowid);
640
641 return $object;
642 }
643
653 private function _validate($data)
654 {
655 $email_template = array();
656 foreach (EmailTemplates::$FIELDS as $field) {
657 if (!isset($data[$field])) {
658 throw new RestException(400, $field." field missing");
659 }
660 $email_template[$field] = $data[$field];
661 }
662 return $email_template;
663 }
664
674 private function _checkAccessRights($accesstype)
675 {
676 // what kind of access management do we need?
677 $allowaccess = false;
678 if (isModEnabled("societe") && DolibarrApiAccess::$user->hasRight('societe', $accesstype)) {
679 $allowaccess = true;
680 }
681 if (isModEnabled('member') && DolibarrApiAccess::$user->hasRight('adherent', $accesstype)) {
682 $allowaccess = true;
683 }
684 if (isModEnabled("propal") && DolibarrApiAccess::$user->hasRight('propal', $accesstype)) {
685 $allowaccess = true;
686 }
687 if (isModEnabled('order') && DolibarrApiAccess::$user->hasRight('commande', $accesstype)) {
688 $allowaccess = true;
689 }
690 if (isModEnabled('invoice') && DolibarrApiAccess::$user->hasRight('facture', $accesstype)) {
691 $allowaccess = true;
692 }
693 if ($allowaccess) {
694 return $allowaccess;
695 } else {
696 throw new RestException(403, 'denied access to email templates');
697 }
698 }
699}
$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:33
_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.
Definition api.class.php:98
_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.
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.
deleteByLAbel($label)
Delete 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.
forgeSQLFromUniversalSearchCriteria($filter, &$errorstr='', $noand=0, $nopar=0, $noerror=0)
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.