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