dolibarr 24.0.0-beta
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 $table_element = 'c_email_templates';
63
67 public function __construct()
68 {
69 global $db;
70 $this->db = $db;
71 $this->email_template = new CEmailTemplate($this->db);
72 }
73
88 public function deleteById($id)
89 {
90 $allowaccess = $this->_checkAccessRights('lire');
91 if (!$allowaccess) {
92 throw new RestException(403, 'denied read access to email templates');
93 }
94
95 $result = $this->email_template->apifetch($id, '');
96 if (!$result || $id == 0) {
97 throw new RestException(404, 'Email Template with id '.$id.' not found');
98 }
99
100 if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
101 throw new RestException(500, 'Error when delete email template : '.$this->email_template->error);
102 }
103
104 return array(
105 'success' => array(
106 'code' => 200,
107 'message' => 'email template deleted'
108 )
109 );
110 }
111
126 public function deleteByLAbel($label)
127 {
128 $allowaccess = $this->_checkAccessRights('lire');
129 if (!$allowaccess) {
130 throw new RestException(403, 'denied read access to email templates');
131 }
132
133 $result = $this->email_template->apifetch(0, $label);
134 if (!$result) {
135 throw new RestException(404, "Email Template with label ".$label." not found");
136 }
137
138 if (!$this->email_template->delete(DolibarrApiAccess::$user)) {
139 throw new RestException(500, 'Error when delete email template : '.$this->email_template->error);
140 }
141
142 return array(
143 'success' => array(
144 'code' => 200,
145 'message' => 'email template deleted'
146 )
147 );
148 }
149
165 public function getById($id)
166 {
167 return $this->_fetch($id, '');
168 }
169
185 public function getByLabel($label)
186 {
187 return $this->_fetch(0, $label);
188 }
189
212 public function index($sortfield = "e.rowid", $sortorder = 'ASC', $limit = 100, $page = 0, $fk_user = '', $sqlfilters = '', $properties = '', $pagination_data = false)
213 {
214 $allowaccess = $this->_checkAccessRights('lire');
215 if (!$allowaccess) {
216 throw new RestException(403, 'denied read access to email templates');
217 }
218
219 $obj_ret = array();
220
221 $sql = "SELECT e.rowid";
222 $sql .= " FROM ".MAIN_DB_PREFIX.$this->table_element." AS e";
223 $sql .= " WHERE e.entity IN (".getEntity($this->table_element).")";
224 if (!$fk_user == '') {
225 $sql .= " AND e.fk_user = ".((int) $fk_user);
226 }
227
228 // Add sql filters
229 if ($sqlfilters) {
230 $errormessage = '';
231 $sql .= forgeSQLFromUniversalSearchCriteria($sqlfilters, $errormessage);
232 if ($errormessage) {
233 throw new RestException(400, 'Error when validating parameter sqlfilters -> '.$errormessage);
234 }
235 }
236
237 //this query will return total orders with the filters given
238 $sqlTotals = str_replace('SELECT e.rowid', 'SELECT count(e.rowid) as total', $sql);
239
240 $sql .= $this->db->order($sortfield, $sortorder);
241 if ($limit) {
242 if ($page < 0) {
243 $page = 0;
244 }
245 $offset = $limit * $page;
246
247 $sql .= $this->db->plimit($limit + 1, $offset);
248 }
249
250 dol_syslog(get_class($this)."::index", LOG_DEBUG);
251 $result = $this->db->query($sql);
252 dol_syslog(get_class($this)."::pindex", LOG_DEBUG);
253
254 if ($result) {
255 $num = $this->db->num_rows($result);
256 $min = min($num, ($limit <= 0 ? $num : $limit));
257 $i = 0;
258 while ($i < $min) {
259 $obj = $this->db->fetch_object($result);
260 $email_template_static = new CEmailTemplate($this->db);
261 if ($email_template_static->apifetch($obj->rowid, '') > 0) {
262 $obj_ret[] = $this->_filterObjectProperties($this->_cleanObjectDatas($email_template_static), $properties);
263 }
264 $i++;
265 }
266 } else {
267 throw new RestException(503, 'Error when retrieve email template list : '.$this->db->lasterror());
268 }
269
270 //if $pagination_data is true the response will contain element data with all values and element pagination with pagination data(total,page,limit)
271 if ($pagination_data) {
272 $totalsResult = $this->db->query($sqlTotals);
273 $total = $this->db->fetch_object($totalsResult)->total;
274
275 $tmp = $obj_ret;
276 $obj_ret = [];
277
278 $obj_ret['data'] = $tmp;
279 $obj_ret['pagination'] = [
280 'total' => (int) $total,
281 'page' => $page, //count starts from 0
282 'page_count' => ceil((int) $total / $limit),
283 'limit' => $limit
284 ];
285 }
286
287 return $obj_ret;
288 }
289
308 public function post($request_data = null)
309 {
310 $allowaccess = $this->_checkAccessRights('creer');
311 if (!$allowaccess) {
312 throw new RestException(403, 'denied create access to email templates');
313 }
314
315 // Check mandatory fields
316 $result = $this->_validate($request_data);
317
318 foreach ($request_data as $field => $value) {
319 if ($field === 'caller') {
320 // 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
321 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
322 continue;
323 }
324 if ($field == 'id') {
325 throw new RestException(400, 'Creating with id field is forbidden');
326 }
327 if ($field == 'tms') {
328 throw new RestException(400, 'Creating with tms field is forbidden');
329 }
330
331 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
332 }
333
334 if ($this->email_template->create(DolibarrApiAccess::$user) < 0) {
335 throw new RestException(500, "Error creating email template", array_merge(array($this->email_template->error), $this->email_template->errors));
336 }
337
338 return ((int) $this->email_template->id);
339 }
340
361 public function putById($id, $request_data = null)
362 {
363 $allowaccess = $this->_checkAccessRights('creer');
364 if (!$allowaccess) {
365 throw new RestException(403, 'denied update access to email templates');
366 }
367
368 $result = $this->email_template->apifetch($id, '');
369 if (!$result || $id == 0) {
370 throw new RestException(404, 'email template with id='.$id.' not found');
371 }
372
373 foreach ($request_data as $field => $value) {
374 if ($field == 'id') {
375 throw new RestException(400, 'Updating with id field is forbidden');
376 }
377 if ($field == 'datec') {
378 throw new RestException(400, 'Updating with datec field is forbidden');
379 }
380
381 if ($field === 'caller') {
382 // 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
383 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
384 continue;
385 }
386
387 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
388 }
389
390 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
391 return $this->_fetch($id, '');
392 } else {
393 throw new RestException(500, $this->email_template->error);
394 }
395 }
396
416 public function putbyLabel($label, $request_data = null)
417 {
418 $allowaccess = $this->_checkAccessRights('creer');
419 if (!$allowaccess) {
420 throw new RestException(403, 'denied update access to email templates');
421 }
422
423 $result = $this->email_template->apifetch(0, $label);
424 if (!$result) {
425 throw new RestException(404, 'email template not found');
426 }
427
428 $newlabel = $label;
429 foreach ($request_data as $field => $value) {
430 if ($field == 'id') {
431 throw new RestException(400, 'Updating with id field is forbidden');
432 }
433 if ($field == 'datec') {
434 throw new RestException(400, 'Updating with datec field is forbidden');
435 }
436
437 if ($field == 'label') {
438 $newlabel = $this->_checkValForAPI($field, $value, $this->email_template);
439 }
440 if ($field === 'caller') {
441 // 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
442 $this->email_template->context['caller'] = sanitizeVal($request_data['caller'], 'aZ09');
443 continue;
444 }
445
446 $this->email_template->$field = $this->_checkValForAPI($field, $value, $this->email_template);
447 }
448
449 if ($this->email_template->update(DolibarrApiAccess::$user) > 0) {
450 return $this->_fetch(0, $newlabel);
451 } else {
452 throw new RestException(500, $this->email_template->error);
453 }
454 }
455
471 private function _fetch($id, $label = '')
472 {
473 global $conf;
474
475 $allowaccess = $this->_checkAccessRights('lire');
476 if (!$allowaccess) {
477 throw new RestException(403, 'denied read access to email templates');
478 }
479
480 $result = $this->email_template->apifetch($id, $label);
481 if ($result > 0) {
482 return $this->_cleanObjectDatas($this->email_template);
483 }
484 if ($result == 0) {
485 if ($id) {
486 throw new RestException(404, 'Email template with id='.((string) $id).' not found in entity='.(int) $conf->entity);
487 }
488 if ($label) {
489 throw new RestException(404, 'Email template with label '.$label.' not found in entity='.(int) $conf->entity);
490 }
491 throw new RestException(404, 'Email Template not found');
492 } else {
493 if (empty($this->email_template->error)) {
494 throw new RestException(400, 'Unknown error in your request');
495 } else {
496 throw new RestException(400, 'Error: '.$this->email_template->error);
497 }
498 }
499 }
500
501 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.PublicUnderscore
514 protected function _cleanObjectDatas($object)
515 {
516 // phpcs:enable
517 $object = parent::_cleanObjectDatas($object);
518 dol_syslog(get_class($this)."::_cleanObjectDatas", LOG_DEBUG);
519
520
521 unset($object->import_key);
522 unset($object->array_languages);
523 unset($object->contacts_ids);
524 unset($object->linkedObjectsIds);
525 unset($object->canvas);
526 unset($object->fk_project);
527 unset($object->contact_id);
528 unset($object->user);
529 unset($object->origin_type);
530 unset($object->origin_id);
531 unset($object->ref);
532 unset($object->ref_ext);
533 unset($object->statut);
534 unset($object->status);
535 unset($object->civility_code);
536 unset($object->country_id);
537 unset($object->country_code);
538 unset($object->state_id);
539 unset($object->region_id);
540 unset($object->barcode_type);
541 unset($object->barcode_type_coder);
542 unset($object->mode_reglement_id);
543 unset($object->cond_reglement_id);
544 unset($object->demand_reason_id);
545 unset($object->transport_mode_id);
546 unset($object->shipping_method_id);
547 unset($object->shipping_method);
548 unset($object->fk_multicurrency);
549 unset($object->multicurrency_code);
550 unset($object->multicurrency_tx);
551 unset($object->multicurrency_total_ht);
552 unset($object->multicurrency_total_tva);
553 unset($object->multicurrency_total_ttc);
554 unset($object->multicurrency_total_localtax1);
555 unset($object->multicurrency_total_localtax2);
556 unset($object->last_main_doc);
557 unset($object->fk_account);
558 unset($object->note_public);
559 unset($object->note_private);
560 unset($object->total_ht);
561 unset($object->total_tva);
562 unset($object->total_localtax1);
563 unset($object->total_localtax2);
564 unset($object->total_ttc);
565 unset($object->lines);
566 unset($object->actiontypecode);
567 unset($object->name);
568 unset($object->lastname);
569 unset($object->firstname);
570 unset($object->civility_id);
571 unset($object->user_author);
572 unset($object->user_creation);
573 unset($object->user_creation_id);
574 unset($object->user_valid);
575 unset($object->user_validation);
576 unset($object->user_validation_id);
577 unset($object->user_closing_id);
578 unset($object->user_modification);
579 unset($object->user_modification_id);
580 unset($object->fk_user_creat);
581 unset($object->fk_user_modif);
582 unset($object->totalpaid);
583 unset($object->product);
584 unset($object->cond_reglement_supplier_id);
585 unset($object->deposit_percent);
586 unset($object->retained_warranty_fk_cond_reglement);
587 unset($object->warehouse_id);
588 unset($object->target);
589 unset($object->array_options);
590 unset($object->extraparams);
591 unset($object->specimen);
592 unset($object->date_validation);
593 unset($object->date_modification);
594 unset($object->date_cloture);
595 unset($object->rowid);
596
597 return $object;
598 }
599
609 private function _validate($data)
610 {
611 $email_template = array();
612 foreach (EmailTemplates::$FIELDS as $field) {
613 if (!isset($data[$field])) {
614 throw new RestException(400, $field." field missing");
615 }
616 $email_template[$field] = $data[$field];
617 }
618 return $email_template;
619 }
620
630 private function _checkAccessRights($accesstype)
631 {
632 // what kind of access management do we need?
633 $allowaccess = false;
634 if (isModEnabled("societe") && DolibarrApiAccess::$user->hasRight('societe', $accesstype)) {
635 $allowaccess = true;
636 }
637 if (isModEnabled('member') && DolibarrApiAccess::$user->hasRight('adherent', $accesstype)) {
638 $allowaccess = true;
639 }
640 if (isModEnabled("propal") && DolibarrApiAccess::$user->hasRight('propal', $accesstype)) {
641 $allowaccess = true;
642 }
643 if (isModEnabled('order') && DolibarrApiAccess::$user->hasRight('commande', $accesstype)) {
644 $allowaccess = true;
645 }
646 if (isModEnabled('invoice') && DolibarrApiAccess::$user->hasRight('facture', $accesstype)) {
647 $allowaccess = true;
648 }
649 if ($allowaccess) {
650 return $allowaccess;
651 } else {
652 throw new RestException(403, 'denied access to email templates');
653 }
654 }
655}
$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.
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.
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.
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.