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