dolibarr 25.0.0-alpha
actions_sendmails.inc.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2013 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
4 * Copyright (C) 2024-2026 Frédéric France <frederic.france@free.fr>
5* Copyright (C) 2013 Juanjo Menent <jmenent@2byte.es>
6*
7* This program is free software; you can redistribute it and/or modify
8* it under the terms of the GNU General Public License as published by
9* the Free Software Foundation; either version 3 of the License, or
10* (at your option) any later version.
11*
12* This program is distributed in the hope that it will be useful,
13* but WITHOUT ANY WARRANTY; without even the implied warranty of
14* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15* GNU General Public License for more details.
16*
17* You should have received a copy of the GNU General Public License
18* along with this program. If not, see <https://www.gnu.org/licenses/>.
19* or see https://www.gnu.org/
20*/
21
48'
49@phan-var-force Societe $mysoc
50@phan-var-force CommonObject $object
51@phan-var-force int $error
52';
53
54
55/*
56 * Add file in email form
57 */
58if (GETPOST('addfile', 'alpha')) {
59 $trackid = GETPOST('trackid', 'aZ09');
60
61 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
62
63 // Set tmp user directory
64 $vardir = $conf->user->dir_output."/".$user->id;
65 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
66
67 dol_add_file_process($upload_dir_tmp, 1, 0, 'addedfile', '', null, $trackid, 0);
68 $action = 'presend';
69}
70
71/*
72 * Remove file in email form
73 */
74if (GETPOST('removedfile') && !GETPOST('removeAll')) {
75 $trackid = GETPOST('trackid', 'aZ09');
76
77 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
78
79 // Set tmp user directory
80 $vardir = $conf->user->dir_output."/".$user->id;
81 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
82
83 // TODO Delete only files that was uploaded from email form. This can be addressed by adding the trackid into the temp path then changing donotdeletefile to 2 instead of 1 to say "delete only if into temp dir"
84 // GETPOST('removedfile','alpha') is position of file into $_SESSION["listofpaths"...] array.
85 dol_remove_file_process(GETPOSTINT('removedfile'), 0, 1, $trackid); // We do not delete because if file is the official PDF of doc, we don't want to remove it physically
86 $action = 'presend';
87}
88
89/*
90 * Remove all files in email form
91 */
92if (GETPOST('removeAll', 'alpha')) {
93 $trackid = GETPOST('trackid', 'aZ09');
94
95 $listofpaths = array();
96 $listofnames = array();
97 $listofmimes = array();
98 $keytoavoidconflict = empty($trackid) ? '' : '-'.$trackid;
99 if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
100 $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
101 }
102 if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
103 $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
104 }
105 if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
106 $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
107 }
108
109 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
110 $formmail = new FormMail($db);
111 $formmail->trackid = $trackid;
112
113 foreach ($listofpaths as $key => $value) {
114 $pathtodelete = $value;
115 $filetodelete = $listofnames[$key];
116 $result = dol_delete_file($pathtodelete, 1); // Delete uploaded Files
117
118 $langs->load("other");
119 setEventMessages($langs->trans("FileWasRemoved", $filetodelete), null, 'mesgs');
120
121 $formmail->remove_attached_files($key); // Update Session
122 }
123}
124
125/*
126 * Send mail
127 */
128if (($action == 'send' || $action == 'relance') && !GETPOST('addfile') && !GETPOST('removeAll') && !GETPOST('removedfile') && !GETPOST('cancel') && !GETPOST('modelselected')) {
129 if (empty($trackid)) {
130 $trackid = GETPOST('trackid', 'aZ09');
131 }
132
133 // Set tmp user directory (used to convert images embedded as img src=data:image)
134 $vardir = $conf->user->dir_output."/".$user->id;
135 $upload_dir_tmp = $vardir.'/temp'; // TODO Add $keytoavoidconflict in upload_dir path
136
137 $subject = '';
138 //$actionmsg = '';
139 $actionmsg2 = '';
140 $thirdparty = null;
141 $contact = null;
142 $result = 0;
143
144 $langs->load('mails');
145
146 $sendtosocid = 0; // Id of related thirdparty
147
148 if (is_object($object)) {
149 $result = $object->fetch($id);
150
151 if (method_exists($object, "fetch_thirdparty") && !in_array($object->element, array('member', 'user', 'expensereport', 'societe', 'contact'))) {
152 $object->fetch_thirdparty();
153 $thirdparty = $object->thirdparty;
154 if (is_object($thirdparty)) {
155 $sendtosocid = $thirdparty->id;
156 }
157 } elseif ($object->element == 'member' || $object->element == 'user') {
158 '@phan-var-force Adherent|User $object';
159 $thirdparty = $object;
160 if ($object->socid > 0) {
161 $sendtosocid = $object->socid;
162 }
163 } elseif ($object->element == 'expensereport') {
164 '@phan-var-force ExpenseReport $object';
165 $tmpuser = new User($db);
166 $tmpuser->fetch($object->fk_user_author);
167 $thirdparty = $tmpuser;
168 } elseif ($object->element == 'societe') {
169 '@phan-var-force Societe $object';
170 $thirdparty = $object;
171 if (is_object($thirdparty) && $thirdparty->id > 0) {
172 $sendtosocid = $thirdparty->id;
173 }
174 } elseif ($object->element == 'contact') {
175 '@phan-var-force Contact $object';
176 $contact = $object;
177 if ($contact->id > 0) {
178 $contact->fetch_thirdparty();
179 $thirdparty = $contact->thirdparty;
180 if (is_object($thirdparty) && $thirdparty->id > 0) {
181 $sendtosocid = $thirdparty->id;
182 }
183 }
184 } else {
185 dol_print_error(null, "Use actions_sendmails.in.php for an element/object '".$object->element."' that is not supported");
186 }
187
188 if (is_object($hookmanager)) {
189 $parameters = array();
190 $reshook = $hookmanager->executeHooks('initSendToSocid', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks
191 }
192 } else {
193 $thirdparty = $mysoc;
194 $result = 1; // No object to fetch (e.g. Setup -> Emails -> send test email): consider OK
195 }
196
197 if ($result > 0) {
198 $email_from = '';
199 $sendto = '';
200 $sendtocc = '';
201 $sendtobcc = '';
202 $sendtoid = array();
203 $sendtouserid = array();
204 $sendtoccuserid = array();
205
206 // Define $sendto
207 $receiver = GETPOST('receiver', 'alphawithlgt');
208 if (!is_array($receiver)) {
209 if ($receiver == '-1') {
210 $receiver = array();
211 } else {
212 $receiver = array($receiver);
213 }
214 }
215
216 $tmparray = array();
217 if (trim(GETPOST('sendto', 'alphawithlgt'))) {
218 // Recipients are provided into free text field
219 $tmparray[] = trim(GETPOST('sendto', 'alphawithlgt'));
220 }
221
222 if (trim(GETPOST('tomail', 'alphawithlgt'))) {
223 // Recipients are provided into free hidden text field
224 $tmparray[] = trim(GETPOST('tomail', 'alphawithlgt'));
225 }
226
227 if (count($receiver) > 0) {
228 // Recipient was provided from combo list
229 foreach ($receiver as $key => $val) {
230 if ($val == 'thirdparty') { // Key selected means current third party ('thirdparty' may be used for current member or current user too)
231 $thirdpartyEmail = (is_object($thirdparty) && !empty($thirdparty->email)) ? (string) $thirdparty->email : '';
232 if ($thirdpartyEmail !== '') {
233 $thirdpartyLabel = '';
234 if (is_object($thirdparty)) {
235 if (method_exists($thirdparty, 'getFullName')) {
236 $thirdpartyLabel = (string) $thirdparty->getFullName($langs);
237 } elseif (!empty($thirdparty->name)) {
238 $thirdpartyLabel = (string) $thirdparty->name;
239 } elseif (!empty($thirdparty->nom)) {
240 $thirdpartyLabel = (string) $thirdparty->nom;
241 }
242 }
243 if ($thirdpartyLabel !== '') {
244 $tmparray[] = dol_string_nospecial($thirdpartyLabel, ' ', array(",")).' <'.$thirdpartyEmail.'>';
245 } else {
246 $tmparray[] = $thirdpartyEmail;
247 }
248 }
249 } elseif ($val == 'contact') { // Key selected means current contact
250 $tmparray[] = dol_string_nospecial($contact->getFullName($langs), ' ', array(",")).' <'.$contact->email.'>';
251 $sendtoid[] = $contact->id;
252 } elseif ($val && $object->element == 'project' && empty($object->socid)) { // $val is the Id of a contact
253 $contact = new Contact($db);
254 $ret = $contact->fetch((int) $val);
255 if ($ret > 0 && !empty($contact->socid)) {
256 $thirdparty = new Societe($db);
257 $thirdparty->fetch($contact->socid);
258 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
259 $sendtoid[] = ((int) $val);
260 }
261 } elseif (is_numeric($val) && $val > 0) { // $val is the Id of a contact
262 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
263 $sendtoid[] = ((int) $val);
264 } elseif ($val !== '') { // $val is a free-typed "Name <email>" or "email" tag
265 $tmparray[] = sanitizeVal($val, 'alphawithlgt');
266 }
267 }
268 }
269
270 if (getDolGlobalString('MAIN_MAIL_ENABLED_USER_DEST_SELECT')) {
271 $receiveruser = GETPOST('receiveruser', 'alphawithlgt');
272 if (is_array($receiveruser) && count($receiveruser) > 0) {
273 $fuserdest = new User($db);
274 foreach ($receiveruser as $key => $val) {
275 $tmparray[] = $fuserdest->user_get_property($val, 'email');
276 $sendtouserid[] = $val;
277 }
278 }
279 }
280
281 $sendto = implode(',', $tmparray);
282
283 // Define $sendtocc
284 $receivercc = GETPOST('receivercc', 'alphawithlgt');
285 if (!is_array($receivercc)) {
286 if ($receivercc == '-1') {
287 $receivercc = array();
288 } else {
289 $receivercc = array($receivercc);
290 }
291 }
292 $tmparray = array();
293 if (trim(GETPOST('sendtocc', 'alphawithlgt'))) {
294 $tmparray[] = trim(GETPOST('sendtocc', 'alphawithlgt'));
295 }
296 if (count($receivercc) > 0) {
297 foreach ($receivercc as $key => $val) {
298 if ($val == 'thirdparty') { // Key selected means current thirdparty (may be usd for current member or current user too)
299 // Recipient was provided from combo list
300 $tmparray[] = dol_string_nospecial((string) $thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>';
301 } elseif ($val == 'contact') { // Key selected means current contact
302 // Recipient was provided from combo list
303 $tmparray[] = dol_string_nospecial((string) $contact->name, ' ', array(",")).' <'.$contact->email.'>';
304 //$sendtoid[] = $contact->id; TODO Add also id of contact in CC ?
305 } elseif (is_numeric($val) && $val > 0) { // $val is the Id of a contact
306 $tmparray[] = $thirdparty->contact_get_property((int) $val, 'email');
307 //$sendtoid[] = ((int) $val); TODO Add also id of contact in CC ?
308 } elseif ($val !== '') { // $val is a free-typed "Name <email>" or "email" tag
309 $tmparray[] = sanitizeVal($val, 'alphawithlgt');
310 }
311 }
312 }
313 if (getDolGlobalString('MAIN_MAIL_ENABLED_USER_DEST_SELECT')) {
314 $receiverccuser = GETPOST('receiverccuser', 'alphawithlgt');
315
316 if (is_array($receiverccuser) && count($receiverccuser) > 0) {
317 $fuserdest = new User($db);
318 foreach ($receiverccuser as $key => $val) {
319 $tmparray[] = $fuserdest->user_get_property($val, 'email');
320 $sendtoccuserid[] = $val;
321 }
322 }
323 }
324 $sendtocc = implode(',', $tmparray);
325
326 if (dol_strlen($sendto)) {
327 // Define $urlwithroot
328 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
329 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
330 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
331
332 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
333
334 $langs->load("commercial");
335
336 $reg = array();
337 $fromtype = GETPOST('fromtype', 'alpha');
338 $emailsendersignature = '';
339 if ($fromtype === 'robot') {
340 $email_from = dol_string_nospecial(getDolGlobalString('MAIN_MAIL_EMAIL_FROM'), ' ', array(",")).' <' . getDolGlobalString('MAIN_MAIL_EMAIL_FROM').'>';
341 } elseif ($fromtype === 'user') {
342 $email_from = dol_string_nospecial($user->getFullName($langs), ' ', array(",")).' <'.$user->email.'>';
343 } elseif ($fromtype === 'company') {
344 $email_from = dol_string_nospecial(getDolGlobalString('MAIN_INFO_SOCIETE_NOM'), ' ', array(",")).' <' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'>';
345 } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) {
346 $tmp = explode(',', getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'));
347 $email_from = trim($tmp[((int) $reg[1] - 1)]);
348 } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) {
349 $sql = "SELECT rowid, label, email, signature FROM ".MAIN_DB_PREFIX."c_email_senderprofile";
350 $sql .= " WHERE rowid = ".(int) $reg[1];
351 $resql = $db->query($sql);
352 $obj = $db->fetch_object($resql);
353 if ($obj) {
354 $email_from = dol_string_nospecial($obj->label, ' ', array(",")).' <'.$obj->email.'>';
355 $emailsendersignature = $obj->signature;
356 }
357 } elseif (preg_match('/from_template_(\d+)/', $fromtype, $reg)) {
358 $sql = "SELECT rowid, email_from FROM ".MAIN_DB_PREFIX."c_email_templates";
359 $sql .= " WHERE rowid = ".(int) $reg[1];
360 $resql = $db->query($sql);
361 $obj = $db->fetch_object($resql);
362 if ($obj) {
363 $email_from = $obj->email_from;
364 }
365 } else {
366 $email_from = dol_string_nospecial(GETPOST('fromname'), ' ', array(",")).' <'.GETPOST('frommail').'>';
367 }
368
369 $replyto = '';
370 if (GETPOST('replytomail')) {
371 $replyto = dol_string_nospecial(GETPOST('replytoname'), ' ', array(","));
372 $replyto .= ($replyto ? ' ' : '').'<'.GETPOST('replytomail').'>';
373 }
374
375 $message = GETPOST('message', 'restricthtml');
376 $subject = GETPOST('subject', 'restricthtml');
377
378 // Make a change into HTML code to allow to include images from medias directory with an external reabable URL.
379 // <img alt="" src="/dolibarr_dev/htdocs/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
380 // become
381 // <img alt="" src="'.$urlwithroot.'viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/ldestailleur_166x166.jpg" style="height:166px; width:166px" />
382 $message = preg_replace('/(<img.*src=")[^\"]*viewimage\.php([^\"]*)modulepart=medias([^\"]*)file=([^\"]*)("[^\/]*\/>)/', '\1'.$urlwithroot.'/viewimage.php\2modulepart=medias\3file=\4\5', $message);
383
384 $tmparrayccc = array();
385 if (trim(GETPOST('sendtoccc', 'alphawithlgt'))) {
386 $tmparrayccc[] = trim(GETPOST('sendtoccc', 'alphawithlgt'));
387 }
388 $receiverccc = GETPOST('receiverccc', 'alphawithlgt');
389 if (!is_array($receiverccc)) {
390 $receiverccc = ($receiverccc && $receiverccc != '-1') ? array($receiverccc) : array();
391 }
392 foreach ($receiverccc as $val) {
393 if ($val == 'thirdparty') { // Key selected means current thirdparty
394 $tmparrayccc[] = dol_string_nospecial((string) $thirdparty->name, ' ', array(",")).' <'.$thirdparty->email.'>';
395 } elseif ($val == 'contact') { // Key selected means current contact
396 $tmparrayccc[] = dol_string_nospecial((string) $contact->name, ' ', array(",")).' <'.$contact->email.'>';
397 } elseif (is_numeric($val) && $val > 0) { // $val is the Id of a contact
398 $tmparrayccc[] = $thirdparty->contact_get_property((int) $val, 'email');
399 } elseif ($val !== '') { // $val is a free-typed "Name <email>" or "email" tag
400 $tmparrayccc[] = sanitizeVal($val, 'alphawithlgt');
401 }
402 }
403 $sendtobcc = implode(',', $tmparrayccc);
404 // Autocomplete the $sendtobcc
405 // $autocopy can be MAIN_MAIL_AUTOCOPY_PROPOSAL_TO, MAIN_MAIL_AUTOCOPY_ORDER_TO, MAIN_MAIL_AUTOCOPY_INVOICE_TO, MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO...
406 if (!empty($autocopy)) {
407 $sendtobcc .= (getDolGlobalString($autocopy) ? (($sendtobcc ? ", " : "") . getDolGlobalString($autocopy)) : '');
408 }
409
410 $deliveryreceipt = GETPOSTINT('deliveryreceipt') ? 1 : 0;
411
412 if ($action == 'send' || $action == 'relance') {
413 $actionmsg2 = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($email_from, 4, 0, 1), CMailFile::getValidAddress($sendto, 4, 0, 1));
414 /*if ($message) {
415 $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($email_from);
416 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto));
417 if ($sendtocc) {
418 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('Bcc').": ".dol_escape_htmltag($sendtocc));
419 }
420 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTopic').": ".$subject);
421 $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('TextUsedInTheMessageBody').":");
422 $actionmsg = dol_concatdesc($actionmsg, $message);
423 }*/
424 }
425
426 // Create form object
427 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
428 $formmail = new FormMail($db);
429 $formmail->trackid = $trackid; // $trackid must be defined
430
431 $attachedfiles = $formmail->get_attached_files();
432 $filepath = $attachedfiles['paths'];
433 $filename = $attachedfiles['names'];
434 $mimetype = $attachedfiles['mimes'];
435
436 // Make substitution in email content
437 $substitutionarray = getCommonSubstitutionArray($langs, 0, null, $object);
438
439 $substitutionarray['__SENDEREMAIL_SIGNATURE__'] = (empty($emailsendersignature) ? $user->signature : $emailsendersignature);
440 $substitutionarray['__EMAIL__'] = $sendto;
441 $substitutionarray['__CHECK_READ__'] = (is_object($object) && is_object($object->thirdparty)) ? '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag=undefined&securitykey='.dol_hash(getDolGlobalString('MAILING_EMAIL_UNSUBSCRIBE_KEY')."-undefined", 'md5').'" width="1" height="1" style="width:1px;height:1px" border="0"/>' : '';
442
443 $parameters = array('mode' => 'formemail');
444 complete_substitutions_array($substitutionarray, $langs, $object, $parameters);
445
446 $subject = make_substitutions($subject, $substitutionarray);
447 $message = make_substitutions($message, $substitutionarray);
448
449 if (is_object($object) && method_exists($object, 'makeSubstitution')) {
450 $subject = $object->makeSubstitution($subject);
451 $message = $object->makeSubstitution($message);
452 }
453
454 // Send mail (substitutionarray must be done just before this)
455 if (empty($sendcontext)) {
456 $sendcontext = 'standard';
457 }
458 $mailfile = new CMailFile($subject, $sendto, $email_from, $message, $filepath, $mimetype, $filename, $sendtocc, $sendtobcc, $deliveryreceipt, -1, '', '', $trackid, '', $sendcontext, $replyto, $upload_dir_tmp);
459
460 if (!empty($mailfile->error) || !empty($mailfile->errors)) {
461 setEventMessages($mailfile->error, $mailfile->errors, 'errors');
462 $action = 'presend';
463 } else {
464 $result = $mailfile->sendfile();
465 if ($result) {
466 // Initialisation of datas of object to call trigger
467 if (is_object($object)) {
468 $db->begin(); // Transaction for post action must start after sending email to avoid lock when sending email that may be long
469
470 if (empty($actiontypecode)) {
471 $actiontypecode = 'AC_EMAIL'; // Event inserted into agenda automatically
472 }
473
474 $object->socid = $sendtosocid; // To link to a company
475 $object->sendtoid = $sendtoid; // To link to contact-addresses. This is an array.
476 $object->actiontypecode = $actiontypecode; // Type of event ('AC_OTH', 'AC_OTH_AUTO', 'AC_XXX'...)
477 $object->actionmsg = $message; // Long text
478 $object->actionmsg2 = $actionmsg2; // Short text ($langs->transnoentities('MailSentByTo')...);
479 if (getDolGlobalString('MAIN_MAIL_REPLACE_EVENT_TITLE_BY_EMAIL_SUBJECT')) {
480 $object->actionmsg2 = $subject; // Short text
481 }
482
483 $object->trackid = $trackid;
484 $object->fk_element = $object->id;
485 $object->elementtype = $object->element;
486 if (is_array($attachedfiles) && count($attachedfiles) > 0) {
487 $object->attachedfiles = $attachedfiles;
488 }
489 if (is_array($sendtouserid) && count($sendtouserid) > 0 && getDolGlobalString('MAIN_MAIL_ENABLED_USER_DEST_SELECT')) {
490 $object->sendtouserid = $sendtouserid;
491 }
492
493 // TODO Fix this: Such properties does not exists on all objects
494 $object->context['email_msgid'] = $mailfile->msgid;
495 $object->context['email_from'] = $email_from;
496 $object->context['email_subject'] = $subject;
497 $object->context['email_to'] = $sendto;
498 $object->context['email_tocc'] = $sendtocc;
499 $object->context['email_tobcc'] = $sendtobcc;
500
501 $object->email_msgid = $mailfile->msgid; // @todo Set msgid into $mailfile after sending
502 $object->email_from = $email_from;
503 $object->email_subject = $subject;
504 $object->email_to = $sendto;
505 $object->email_tocc = $sendtocc;
506 $object->email_tobcc = $sendtobcc;
507
508 // Call of triggers (you should have set $triggersendname to execute trigger.
509 if (!empty($triggersendname)) {
510 if ($triggersendname == 'BILL_SENTBYMAIL' && $object instanceof Facture) {
511 /* @var Facture $object */
512
513 // If sending email for invoice, we increase the counter of invoices sent by email
514 $sql = "UPDATE ".MAIN_DB_PREFIX."facture SET email_sent_counter = email_sent_counter + 1";
515 $sql .= " WHERE rowid = ".((int) $object->id);
516
517 $resql = $db->query($sql);
518 if ($resql) {
519 $object->email_sent_counter += 1;
520 }
521 }
522
523 $result = $object->call_trigger($triggersendname, $user); // @phan-suppress-current-line PhanPossiblyUndeclaredGlobalVariable
524 if ($result < 0) {
525 $error++;
526 }
527 if ($error) {
528 setEventMessages($object->error, $object->errors, 'errors');
529 }
530 }
531 // End call of triggers
532
533 if (!$error) {
534 $db->commit();
535 } else {
536 $db->rollback();
537 }
538 }
539
540 // Redirect here
541 // This avoid sending mail twice if going out and then back to page
542 $mesg = $langs->trans('MailSuccessfulySent', $mailfile->getValidAddress($email_from, 2), $mailfile->getValidAddress($sendto, 2));
543 setEventMessages($mesg, null, 'mesgs');
544
545 header('Location: '.$_SERVER["PHP_SELF"].'?'.($paramname ?? 'id').'='.(is_object($object) ? $object->id : ''));
546 exit;
547 } else {
548 $langs->load("other");
549 $mesg = '<div class="error">';
550 if (!empty($mailfile->error) || !empty($mailfile->errors)) {
551 $mesg .= $langs->transnoentities('ErrorFailedToSendMail', dol_escape_htmltag($email_from), dol_escape_htmltag($sendto));
552 if (!empty($mailfile->error)) {
553 $mesg .= '<br>'.$mailfile->error;
554 }
555 if (!empty($mailfile->errors) && is_array($mailfile->errors)) {
556 $mesg .= '<br>'.implode('<br>', $mailfile->errors);
557 }
558 } else {
559 $mesg .= $langs->transnoentities('ErrorFailedToSendMail', dol_escape_htmltag($email_from), dol_escape_htmltag($sendto));
560 if (getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
561 $mesg .= '<br>Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
562 } else {
563 $mesg .= '<br>Unknown Error, please refer to your administrator';
564 }
565 }
566 $mesg .= '</div>';
567
568 setEventMessages($mesg, null, 'warnings');
569 $action = 'presend';
570 }
571 }
572 } else {
573 $langs->load("errors");
574 setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentitiesnoconv("MailTo")), null, 'warnings');
575 dol_syslog('Try to send email with no recipient defined', LOG_WARNING);
576 $action = 'presend';
577 }
578 } else {
579 $langs->load("errors");
580 setEventMessages($langs->trans('ErrorFailedToReadObject', $object->element), null, 'errors');
581 dol_syslog('Failed to read data of object id='.$object->id.' element='.$object->element);
582 $action = 'presend';
583 }
584}
$id
Support class for third parties, contacts, members, users or resources.
Definition account.php:47
if(! $sortfield) if(! $sortorder) $object
Definition account.php:100
global $dolibarr_main_url_root
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
Class to manage contact/addresses.
Class to manage invoices.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
Class to manage third parties objects (customers, suppliers, prospects...)
Class to manage Dolibarr users.
global $mysoc
dol_add_file_process($upload_dir, $allowoverwrite=0, $updatesessionordb=0, $keyforsourcefile='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null, $forceFullTextIndexation='', $mode=0)
Get and save an upload file (for example after submitting a new file in a mail form).
dol_delete_file($file, $disableglob=0, $nophperrors=0, $nohook=0, $object=null, $allowdotdot=false, $indexdatabase=1, $nolog=0)
Remove a file or several files with a mask.
dol_remove_file_process($filenb, $donotupdatesession=0, $donotdeletefile=1, $trackid='')
Remove an uploaded file (for example after submitting a new file a mail form).
dol_strlen($string, $stringencoding='UTF-8', $binarycount=0)
Make a strlen call.
dol_string_nospecial($str, $newstr='_', $badcharstoreplace='', $badcharstoremove='', $keepspaces=0)
Clean a string from all punctuation characters to use it as a ref or login.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
sanitizeVal($out='', $check='alphanohtml', $filter=null, $options=null)
Return a sanitized or empty value after checking value against a rule.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Definition html.lib.php:183
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.