dolibarr 24.0.3
html.formmail.class.php
Go to the documentation of this file.
1<?php
2/* Copyright (C) 2005-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3 * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
4 * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
5 * Copyright (C) 2015-2017 Marcos García <marcosgdf@gmail.com>
6 * Copyright (C) 2015-2017 Nicolas ZABOURI <info@inovea-conseil.com>
7 * Copyright (C) 2018-2025 Frédéric France <frederic.france@free.fr>
8 * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
9 * Copyright (C) 2023 Anthony Berton <anthony.berton@bb2a.fr>
10 * Copyright (C) 2024-2026 MDW <mdeweerd@users.noreply.github.com>
11 * Copyright (C) 2026 Nathan Pixodeo <nathan@pixodeo.net>
12 *
13 *
14 * This program is free software; you can redistribute it and/or modify
15 * it under the terms of the GNU General Public License as published by
16 * the Free Software Foundation; either version 3 of the License, or
17 * (at your option) any later version.
18 *
19 * This program is distributed in the hope that it will be useful,
20 * but WITHOUT ANY WARRANTY; without even the implied warranty of
21 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
22 * GNU General Public License for more details.
23 *
24 * You should have received a copy of the GNU General Public License
25 * along with this program. If not, see <https://www.gnu.org/licenses/>.
26 */
27
33require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
34require_once DOL_DOCUMENT_ROOT.'/core/class/cemailtemplate.class.php'; // So the class ModelMail that was defined into this file in old version is still available when including this file
35
36
43class FormMail extends Form
44{
48 public $db;
49
55 public $withform;
56
60 public $fromname;
61
65 public $frommail;
66
70 public $fromtype;
71
75 public $fromid;
76
80 public $fromalsorobot;
81
85 public $totype;
86
90 public $toid;
91
95 public $replytoname;
96
100 public $replytomail;
101
105 public $toname;
106
110 public $tomail;
111
115 public $trackid;
116
120 public $inreplyto;
121
125 public $withsubstit; // Show substitution array
129 public $withfrom;
130
134 public $withto; // Show recipient emails
138 public $withreplyto;
139
145 public $withtofree;
149 public $withtocc;
153 public $withtoccc;
157 public $withtopic;
161 public $witherrorsto;
162
166 public $withfile;
167
171 public $withlayout;
172
176 public $withaiprompt;
177
181 public $withmaindocfile;
185 public $withbody;
186
190 public $withfromreadonly;
194 public $withreplytoreadonly;
198 public $withtoreadonly;
202 public $withtoccreadonly;
206 public $witherrorstoreadonly;
210 public $withtocccreadonly;
214 public $withtopicreadonly;
218 public $withbodyreadonly;
222 public $withfilereadonly;
226 public $withdeliveryreceipt;
230 public $withcancel;
234 public $withdeliveryreceiptreadonly;
238 public $withfckeditor;
239
243 public $ckeditortoolbar;
244
248 public $substit = array();
249
253 public $substit_lines = array();
254
258 public $param = array();
259
263 public $withtouser = array();
267 public $withtoccuser = array();
268
272 public $lines_model;
273
277 public $withoptiononeemailperrecipient;
278
279
285 public function __construct($db)
286 {
287 $this->db = $db;
288
289 $this->withform = 1;
290
291 $this->withfrom = 1;
292 $this->withto = 1;
293 $this->withtofree = 1;
294 $this->withtocc = 1;
295 $this->withtoccc = '0';
296 $this->witherrorsto = 0;
297 $this->withtopic = 1;
298 $this->withfile = 0; // 1=Add section "Attached files". 2=Can add files.
299 $this->withmaindocfile = 0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
300 $this->withbody = 1;
301
302 $this->withfromreadonly = 1;
303 $this->withreplytoreadonly = 1;
304 $this->withtoreadonly = 0;
305 $this->withtoccreadonly = 0;
306 $this->withtocccreadonly = 0;
307 $this->witherrorstoreadonly = 0;
308 $this->withtopicreadonly = 0;
309 $this->withfilereadonly = 0;
310 $this->withbodyreadonly = 0;
311 $this->withdeliveryreceiptreadonly = 0;
312 $this->withfckeditor = -1; // -1 = Auto
313 }
314
315 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
321 public function clear_attached_files()
322 {
323 // phpcs:enable
324 global $conf, $user;
325 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
326
327 // Set tmp user directory
328 $vardir = $conf->user->dir_output."/".$user->id;
329 $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path
330 if (is_dir($upload_dir)) {
331 dol_delete_dir_recursive($upload_dir);
332 }
333
334 $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
335 unset($_SESSION["listofpaths".$keytoavoidconflict]);
336 unset($_SESSION["listofnames".$keytoavoidconflict]);
337 unset($_SESSION["listofmimes".$keytoavoidconflict]);
338 }
339
340 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
349 public function add_attached_files($path, $file = '', $type = '')
350 {
351 // phpcs:enable
352 $listofpaths = array();
353 $listofnames = array();
354 $listofmimes = array();
355
356 if (empty($file)) {
357 $file = basename($path);
358 }
359 if (empty($type)) {
360 $type = dol_mimetype($file);
361 }
362
363 $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
364 if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
365 $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
366 }
367 if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
368 $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
369 }
370 if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
371 $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
372 }
373 if (!in_array($file, $listofnames)) {
374 $listofpaths[] = $path;
375 $listofnames[] = $file;
376 $listofmimes[] = $type;
377 $_SESSION["listofpaths".$keytoavoidconflict] = implode(';', $listofpaths);
378 $_SESSION["listofnames".$keytoavoidconflict] = implode(';', $listofnames);
379 $_SESSION["listofmimes".$keytoavoidconflict] = implode(';', $listofmimes);
380 }
381 }
382
383 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
390 public function remove_attached_files($keytodelete)
391 {
392 // phpcs:enable
393 $listofpaths = array();
394 $listofnames = array();
395 $listofmimes = array();
396
397 $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
398 if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
399 $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
400 }
401 if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
402 $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
403 }
404 if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
405 $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
406 }
407 if ($keytodelete >= 0) {
408 unset($listofpaths[$keytodelete]);
409 unset($listofnames[$keytodelete]);
410 unset($listofmimes[$keytodelete]);
411 $_SESSION["listofpaths".$keytoavoidconflict] = implode(';', $listofpaths);
412 $_SESSION["listofnames".$keytoavoidconflict] = implode(';', $listofnames);
413 $_SESSION["listofmimes".$keytoavoidconflict] = implode(';', $listofmimes);
414 //var_dump($_SESSION['listofpaths']);
415 }
416 }
417
418 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
424 public function get_attached_files()
425 {
426 // phpcs:enable
427 $listofpaths = array();
428 $listofnames = array();
429 $listofmimes = array();
430
431 $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
432 if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
433 $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
434 }
435 if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
436 $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
437 }
438 if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
439 $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
440 }
441 return array('paths' => $listofpaths, 'names' => $listofnames, 'mimes' => $listofmimes);
442 }
443
444 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
455 public function show_form($addfileaction = 'addfile', $removefileaction = 'removefile')
456 {
457 // phpcs:enable
458 print $this->get_form($addfileaction, $removefileaction);
459 }
460
461 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
472 public function get_form($addfileaction = 'addfile', $removefileaction = 'removefile')
473 {
474 // phpcs:enable
475 global $conf, $langs, $user, $hookmanager, $form;
476
477 if (!is_object($form)) {
478 $form = new Form($this->db);
479 }
480
481 // Required to show editor assistants
482 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
483 $formfile = new FormFile($this->db);
484
485 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formai.class.php';
486 $formai = new FormAI($this->db);
487
488 // Load translation files required by the page
489 $langs->loadLangs(array('other', 'mails', 'members'));
490
491 // Clear temp files. Must be done before call of triggers, at beginning (mode = init), or when we select a new template
492 if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelselected') && GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
493 $this->clear_attached_files();
494 }
495
496 // Call hook getFormMail
497 $hookmanager->initHooks(array('formmail'));
498
499 $parameters = array(
500 'addfileaction' => $addfileaction,
501 'removefileaction' => $removefileaction,
502 'trackid' => $this->trackid
503 );
504 $reshook = $hookmanager->executeHooks('getFormMail', $parameters, $this);
505
506 if (!empty($reshook)) {
507 return $hookmanager->resPrint;
508 } else {
509 $out = '';
510
511 $disablebademails = 1;
512
513 // Define output language
514 $outputlangs = $langs;
515 $newlang = '';
516 if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($this->param['langsmodels'])) {
517 $newlang = $this->param['langsmodels'];
518 }
519 if (!empty($newlang)) {
520 $outputlangs = new Translate("", $conf);
521 $outputlangs->setDefaultLang($newlang);
522 // Same files as the language of the recipient in card_presend.tpl.php, so that the __(Key)__ of the templates are translated
523 $outputlangs->loadLangs(array('other', 'commercial', 'bills', 'orders', 'contracts', 'main', 'members', 'propal', 'products', 'supplier_proposal', 'interventions', 'receptions', 'sendings'));
524 }
525
526 // Get message template for $this->param["models"] into c_email_templates
527 $arraydefaultmessage = -1;
528 if ($this->param['models'] != 'none') {
529 $model_id = 0;
530 if (array_key_exists('models_id', $this->param)) {
531 $model_id = $this->param["models_id"];
532 }
533
534 $arraydefaultmessage = $this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id, 1, '', ($model_id > 0 ? -1 : 1)); // If $model_id is empty, preselect the first one
535 }
536
537 // Define list of attached files
538 $listofpaths = array();
539 $listofnames = array();
540 $listofmimes = array();
541 $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
542
543 if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelselected') && GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
544 if (!empty($arraydefaultmessage->joinfiles) && !empty($this->param['fileinit']) && is_array($this->param['fileinit'])) {
545 foreach ($this->param['fileinit'] as $path) {
546 if (!empty($path)) {
547 $this->add_attached_files($path);
548 }
549 }
550 }
551 }
552
553 if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
554 $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
555 }
556 if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
557 $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
558 }
559 if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
560 $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
561 }
562
563
564 $out .= "\n".'<!-- Begin form mail type='.$this->param["models"].' --><div id="mailformdiv"></div>'."\n";
565 if ($this->withform == 1) {
566 $out .= '<form method="POST" name="mailform" id="mailform" enctype="multipart/form-data" action="'.$this->param["returnurl"].'#formmail">'."\n";
567
568 $out .= '<a id="formmail" name="formmail"></a>';
569 $out .= '<input style="display:none" type="submit" id="sendmailhidden" name="sendmail">';
570 $out .= '<input type="hidden" name="token" value="'.newToken().'" />';
571 $out .= '<input type="hidden" name="page_y" value="" />';
572 $out .= '<input type="hidden" name="trackid" value="'.$this->trackid.'" />';
573 $out .= '<input type="hidden" name="inreplyto" value="'.$this->inreplyto.'" />';
574 }
575 if (!empty($this->withfrom)) {
576 if (!empty($this->withfromreadonly)) {
577 $out .= '<input type="hidden" id="fromname" name="fromname" value="'.$this->fromname.'" />';
578 $out .= '<input type="hidden" id="frommail" name="frommail" value="'.$this->frommail.'" />';
579 }
580 }
581 foreach ($this->param as $key => $value) {
582 if (is_array($value)) {
583 $out .= "<!-- param key=".$key." is array, we do not output input field for it -->\n";
584 } else {
585 $out .= '<input type="hidden" id="'.$key.'" name="'.$key.'" value="'.$value.'" />'."\n";
586 }
587 }
588
589 $modelmail_array = array();
590 $break = '';
591 if ($this->param['models'] != 'none') {
592 $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
593 if ($result < 0) {
594 setEventMessages($this->error, $this->errors, 'errors');
595 }
596
597 foreach ($this->lines_model as $line) {
598 $reg = array();
599 if (preg_match('/\‍((.*)\‍)/', $line->label, $reg)) {
600 $labeltouse = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__
601 } else {
602 $labeltouse = $line->label;
603 }
604
605 if ($break != $line->lang) {
606 // New break for a new language, we add the break
607 $s = $line->lang;
608 $shtml = '----- '.$langs->trans("Language_".$line->lang).' -----';
609 $modelmail_array['separator_'.$line->lang] = array('label' => $s, 'data-html' => $shtml, 'disabled' => 'disabled');
610 }
611
612 // We escape the $labeltouse to store it into $modelmail_array.
613 $s = dol_escape_htmltag($labeltouse);
614 $shtml = dol_escape_htmltag($labeltouse);
615 if ($line->lang) {
616 $shtml = picto_from_langcode($line->lang).'</span> '.$shtml;
617 }
618 if ($line->private) {
619 $shtml .= ' - <span class="opacitymedium small">'.dol_escape_htmltag($langs->trans("Private")).'</span>';
620 }
621
622 $modelmail_array[$line->id] = array('label' => $s, 'data-html' => $shtml);
623 }
624 }
625
626 // Zone to select email template
627 if (count($modelmail_array) > 0) {
628 $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOSTINT('modelmailselected') : ($arraydefaultmessage->id > 0 ? $arraydefaultmessage->id : 0);
629
630 // If list of template is filled
631 $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
632
633 $out .= $this->selectarray('modelmailselected', $modelmail_array, $model_mail_selected_id, $langs->trans('SelectMailModel'), 0, 0, '', 0, 0, 0, '', 'minwidth150', 1, '', 0, 1);
634 if ($user->admin) {
635 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
636 }
637
638 // Language selector for predefined message templates (only when multilang is enabled)
639 if (getDolGlobalInt('MAIN_MULTILANGS')) {
640 // This feature is in conflict with the existing one where all templates are show with the language in a flag so user
641 // can choose the template in the correct language.To avoid duplicate and conflict selection, we currently enable this on a hidden constant.
642 // A solution to be compatible would be to wait the user has selected the template, and the combo to select language is shown if no language is forced for the template.
643 if (getDolGlobalInt('MAIN_MULTILANGS_ASK_LANG_IN_SEPARATE_COMBO')) {
644 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formadmin.class.php';
645 $formadmin = new FormAdmin($this->db);
646 $currentlang = (is_object($outputlangs) ? $outputlangs->defaultlang : $langs->defaultlang);
647 $out .= ' &nbsp; ';
648 $out .= $formadmin->select_language($currentlang, 'lang_id', 0, array(), 1, 0, 0, 'maxwidth150');
649 }
650 }
651
652 $out .= '<input type="submit" class="button reposition smallpaddingimp" value="'.$langs->trans('Apply').'" name="modelselected" id="modelselected">';
653 $out .= ' &nbsp; ';
654 $out .= '</div>';
655 } elseif (!empty($this->param['models']) && in_array($this->param['models'], array(
656 'propal_send', 'order_send', 'facture_send',
657 'shipping_send', 'reception_send', 'fichinter_send', 'supplier_proposal_send', 'order_supplier_send',
658 'invoice_supplier_send', 'supplier_payment_send', 'thirdparty', 'contract', 'user', 'recruitmentcandidature_send', 'product_send', 'all'
659 ))) {
660 // If list of template is empty
661 $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
662 $out .= '<span class="opacitymedium">'.$langs->trans('SelectMailModel').':</span> ';
663 $out .= '<select name="modelmailselected" disabled="disabled"><option value="none">'.$langs->trans("NoTemplateDefined").'</option></select>'; // Do not put 'disabled' on 'option' tag, it is already on 'select' and it makes chrome crazy.
664 if ($user->admin) {
665 $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
666 }
667 $out .= ' &nbsp; ';
668 $out .= '<input type="submit" class="button reposition smallpaddingimp" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
669 $out .= ' &nbsp; ';
670 $out .= '</div>';
671 } else {
672 $out .= '<!-- No template available for $this->param["models"] = '.$this->param['models'].' -->';
673 }
674
675
676 $out .= '<table class="tableforemailform boxtablenotop centpercent">'."\n";
677
678 // Substitution array/string
679 $helpforsubstitution = '';
680 if (is_array($this->substit) && count($this->substit)) {
681 $helpforsubstitution .= $langs->trans('AvailableVariables').' :<br><br><span class="small">'."\n";
682 foreach ($this->substit as $key => $val) {
683 // Do not show deprecated variables into the tooltip help of substitution variables
684 if (in_array($key, array('__NEWREF__', '__REFCLIENT__', '__REFSUPPLIER__', '__SUPPLIER_ORDER_DATE_DELIVERY__', '__SUPPLIER_ORDER_DELAY_DELIVERY__'))) {
685 continue;
686 }
687 if (is_array($val)) {
688 $val = implode(', ', $val);
689 } // key __MULTICURRENCY_CODE__ is an array and crashes dolGetFirstLineOfText function which accept only text
690 $helpforsubstitution .= $key.' -> '.$langs->trans(dol_string_nohtmltag(dolGetFirstLineOfText((string) $val))).'<br>';
691 }
692 $helpforsubstitution .= '</span>';
693 }
694
695 /*
696 if (!empty($this->withsubstit)) { // Unset or set ->withsubstit=0 to disable this.
697 $out .= '<tr><td colspan="2" class="right">';
698 if (is_numeric($this->withsubstit)) {
699 $out .= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage
700 } else {
701 $out .= $form->textwithpicto($langs->trans('AvailableVariables'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // New usage
702 }
703 $out .= "</td></tr>\n";
704 }*/
705
706 // From
707 if (!empty($this->withfrom)) {
708 if (!empty($this->withfromreadonly)) {
709 $out .= '<tr><td class="fieldrequired minwidth200">'.$langs->trans("MailFrom").'</td><td>';
710
711 // $this->fromtype is the default value to use to select sender
712 if (!($this->fromtype === 'user' && $this->fromid > 0)
713 && !($this->fromtype === 'company')
714 && !($this->fromtype === 'robot')
715 && !preg_match('/user_aliases/', $this->fromtype)
716 && !preg_match('/global_aliases/', $this->fromtype)
717 && !preg_match('/senderprofile/', $this->fromtype)
718 && !preg_match('/from_template_(\d+)/', $this->fromtype)
719 ) {
720 // Use this->fromname and this->frommail or error if not defined
721 $out .= $this->fromname;
722 if ($this->frommail) {
723 $out .= ' &lt;'.$this->frommail.'&gt;';
724 } else {
725 if ($this->fromtype) {
726 $langs->load('errors');
727 $out .= '<span class="warning"> &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt; </span>';
728 }
729 }
730 } else {
731 $liste = array();
732
733 // Add user email
734 if (empty($user->email)) {
735 $langs->load('errors');
736 $s = $user->getFullName($langs).' &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt;';
737 } else {
738 $s = $user->getFullName($langs).' &lt;'.$user->email.'&gt;';
739 }
740 $liste['user'] = array('label' => $s, 'data-html' => $s);
741
742 // Add also company main email
743 if (getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
744 $s = getDolGlobalString('MAIN_INFO_SOCIETE_NOM', getDolGlobalString('MAIN_INFO_SOCIETE_EMAIL')).' &lt;' . getDolGlobalString('MAIN_INFO_SOCIETE_MAIL').'&gt;';
745 $liste['company'] = array('label' => $s, 'data-html' => $s);
746 }
747
748 // Add also email aliases if there is some
749 $listaliases = array(
750 'global_aliases' => getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'),
751 );
752
753 if (!empty($arraydefaultmessage->email_from) && !empty($arraydefaultmessage->id)) {
754 $templatemailfrom = ' &lt;'.$arraydefaultmessage->email_from.'&gt;';
755 $liste['from_template_'.((int) $arraydefaultmessage->id)] = array('label' => $templatemailfrom, 'data-html' => $templatemailfrom);
756 }
757
758 // Also add robot email
759 if (!empty($this->fromalsorobot)) {
760 if (getDolGlobalString('MAIN_MAIL_EMAIL_FROM') && getDolGlobalString('MAIN_MAIL_EMAIL_FROM') != getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
761 $s = getDolGlobalString('MAIN_MAIL_EMAIL_FROM');
762 if ($this->frommail) {
763 $s .= ' &lt;' . getDolGlobalString('MAIN_MAIL_EMAIL_FROM').'&gt;';
764 }
765 $liste['main_from'] = array('label' => $s, 'data-html' => $s);
766 }
767 }
768
769 // Add also email aliases from the c_email_senderprofile table
770 $sql = "SELECT rowid, label, email FROM ".$this->db->prefix()."c_email_senderprofile";
771 $sql .= " WHERE active = 1 AND (private = 0 OR private = ".((int) $user->id).") AND entity IN (".getEntity('c_email_senderprofile').")";
772 $sql .= " ORDER BY position";
773 $resql = $this->db->query($sql);
774 if ($resql) {
775 $num = $this->db->num_rows($resql);
776 $i = 0;
777 while ($i < $num) {
778 $obj = $this->db->fetch_object($resql);
779 if ($obj) {
780 $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>';
781 }
782 $i++;
783 }
784 } else {
785 dol_print_error($this->db);
786 }
787
788 foreach ($listaliases as $typealias => $listalias) {
789 $posalias = 0;
790 $listaliasarray = explode(',', $listalias);
791 foreach ($listaliasarray as $listaliasval) {
792 $posalias++;
793 $listaliasval = trim($listaliasval);
794 if ($listaliasval) {
795 $listaliasval = preg_replace('/</', '&lt;', $listaliasval);
796 $listaliasval = preg_replace('/>/', '&gt;', $listaliasval);
797 if (!preg_match('/&lt;/', $listaliasval)) {
798 $listaliasval = '&lt;'.$listaliasval.'&gt;';
799 }
800 $liste[$typealias.'_'.$posalias] = array('label' => $listaliasval, 'data-html' => $listaliasval);
801 }
802 }
803 }
804
805 // Using ajaxcombo here make the '<email>' no more visible on list because <emailofuser> is not a valid html tag,
806 // so we transform before each record into $liste to be printable with ajaxcombo by replacing <> into ()
807 // $liste['senderprofile_0_0'] = array('label'=>'rrr', 'data-html'=>'rrr &lt;aaaa&gt;');
808 foreach ($liste as $key => $val) {
809 if (!empty($liste[$key]['data-html'])) {
810 $liste[$key]['data-html'] = str_replace(array('&lt;', '<', '&gt;', '>'), array('__LTCHAR__', '__LTCHAR__', '__GTCHAR__', '__GTCHAR__'), $liste[$key]['data-html']);
811 $liste[$key]['data-html'] = str_replace(array('__LTCHAR__', '__GTCHAR__'), array('<span class="opacitymedium">(', ')</span>'), $liste[$key]['data-html']);
812 }
813 }
814 $out .= ' '.$form->selectarray('fromtype', $liste, (empty($arraydefaultmessage->email_from) || empty($arraydefaultmessage->id)) ? $this->fromtype : 'from_template_'.((int) $arraydefaultmessage->id), 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 1, '', $disablebademails);
815 }
816
817 $out .= "</td></tr>\n";
818 } else {
819 $out .= '<tr><td class="fieldrequired width200">'.$langs->trans("MailFrom")."</td><td>";
820 $out .= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" class="maxwidth200onsmartphone" value="'.$this->fromname.'" />';
821 $out .= '&nbsp; &nbsp; ';
822 $out .= $langs->trans("EMail").':&lt;<input type="text" id="frommail" name="frommail" class="maxwidth200onsmartphone" value="'.$this->frommail.'" />&gt;';
823 $out .= "</td></tr>\n";
824 }
825 }
826
827 // To
828 if (!empty($this->withto) || is_array($this->withto)) {
829 $out .= $this->getHtmlForTo();
830 }
831
832 // To User
833 if (!empty($this->withtouser) && is_array($this->withtouser) && getDolGlobalString('MAIN_MAIL_ENABLED_USER_DEST_SELECT')) {
834 $out .= '<tr><td>';
835 $out .= $langs->trans("MailToUsers");
836 $out .= '</td><td>';
837
838 // multiselect array convert html entities into options tags, even if we don't want this, so we encode them a second time
839 $tmparray = $this->withtouser;
840 foreach ($tmparray as $key => $val) {
841 $tmparray[$key] = dol_htmlentities($tmparray[$key], 0, 'UTF-8', true);
842 }
843 $withtoselected = GETPOST("receiveruser", 'array'); // Array of selected value
844 if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
845 $withtoselected = array_keys($tmparray);
846 }
847 $out .= $form->multiselectarray("receiveruser", $tmparray, $withtoselected, 0, 0, 'inline-block minwidth500', 0, "");
848 $out .= "</td></tr>\n";
849 }
850
851 // With option for one email per recipient
852 if (!empty($this->withoptiononeemailperrecipient)) {
853 if (abs($this->withoptiononeemailperrecipient) == 1) {
854 $out .= '<tr><td class="minwidth200">';
855 $out .= $langs->trans("GroupEmails");
856 $out .= '</td><td>';
857 $out .= ' <input type="checkbox" id="oneemailperrecipient" value="1" name="oneemailperrecipient"'.($this->withoptiononeemailperrecipient > 0 ? ' checked="checked"' : '').'> ';
858 $out .= '<label for="oneemailperrecipient">';
859 $out .= $form->textwithpicto($langs->trans("OneEmailPerRecipient"), $langs->trans("WarningIfYouCheckOneRecipientPerEmail"), 1, 'help');
860 $out .= '</label>';
861 //$out .= '<span class="hideonsmartphone opacitymedium">';
862 //$out .= ' - ';
863 //$out .= $langs->trans("WarningIfYouCheckOneRecipientPerEmail");
864 //$out .= '</span>';
865 if (getDolGlobalString('MASS_ACTION_EMAIL_ON_DIFFERENT_THIRPARTIES_ADD_CUSTOM_EMAIL')) {
866 if (!empty($this->withto) && !is_array($this->withto)) {
867 $out .= ' <span class="opacitymedium">'.$langs->trans("or").'</span> <input type="email" name="emailto" value="">';
868 }
869 }
870 $out .= '</td></tr>';
871 } else {
872 $out .= '<tr><td><input type="hidden" name="oneemailperrecipient" value="1"></td><td></td></tr>';
873 }
874 }
875
876 // CC
877 if (!empty($this->withtocc) || is_array($this->withtocc)) {
878 $out .= $this->getHtmlForCc();
879 }
880
881 // To User cc
882 if (!empty($this->withtoccuser) && is_array($this->withtoccuser) && getDolGlobalString('MAIN_MAIL_ENABLED_USER_DEST_SELECT')) {
883 $out .= '<tr><td>';
884 $out .= $langs->trans("MailToCCUsers");
885 $out .= '</td><td>';
886
887 // multiselect array convert html entities into options tags, even if we don't want this, so we encode them a second time
888 $tmparray = $this->withtoccuser;
889 foreach ($tmparray as $key => $val) {
890 $tmparray[$key] = dol_htmlentities($tmparray[$key], 0, 'UTF-8', true);
891 }
892 $withtoselected = GETPOST("receiverccuser", 'array'); // Array of selected value
893 if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
894 $withtoselected = array_keys($tmparray);
895 }
896 $out .= $form->multiselectarray("receiverccuser", $tmparray, $withtoselected, 0, 0, 'inline-block minwidth500', 0, "");
897 $out .= "</td></tr>\n";
898 }
899
900 // CCC
901 if (!empty($this->withtoccc) || is_array($this->withtoccc)) {
902 $out .= $this->getHtmlForWithCcc();
903 }
904
905 // Replyto
906 if (!empty($this->withreplyto)) {
907 if ($this->withreplytoreadonly) {
908 $out .= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
909 $out .= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
910 $out .= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail ? (" &lt;".$this->replytomail."&gt;") : "");
911 $out .= "</td></tr>\n";
912 }
913 }
914
915 // Errorsto
916 if (!empty($this->witherrorsto)) {
917 $out .= $this->getHtmlForWithErrorsTo();
918 }
919
920 // Ask delivery receipt
921 if (!empty($this->withdeliveryreceipt) && getDolGlobalInt('MAIN_EMAIL_SUPPORT_ACK')) {
922 $out .= $this->getHtmlForDeliveryreceipt();
923 }
924
925 // Topic
926 if (!empty($this->withtopic)) {
927 $out .= $this->getHtmlForTopic($arraydefaultmessage, $helpforsubstitution);
928 }
929
930 // Attached files
931 if (!empty($this->withfile)) {
932 $out .= '<tr>';
933 $out .= '<td class="tdtop">'.$langs->trans("MailFile").'</td>';
934
935 $out .= '<td>';
936
937 if ($this->withmaindocfile) {
938 // withmaindocfile is set to 1 or -1 to show the checkbox (-1 = checked or 1 = not checked)
939 if (GETPOSTISSET('sendmail')) {
940 $this->withmaindocfile = (GETPOST('addmaindocfile', 'alpha') ? -1 : 1);
941 } elseif (is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
942 // If a template was selected, we use setup of template to define if join file checkbox is selected or not.
943 $this->withmaindocfile = ($arraydefaultmessage->joinfiles ? -1 : 1);
944 }
945 }
946
947 if (!empty($this->withmaindocfile)) {
948 if ($this->withmaindocfile == 1) {
949 $out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" />';
950 } elseif ($this->withmaindocfile == -1) {
951 $out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" checked="checked" />';
952 }
953 if (getDolGlobalString('MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND')) {
954 $out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDocOrLastGenerated").'.</label><br>';
955 } else {
956 $out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDoc").'.</label><br>';
957 }
958 }
959
960 if (is_numeric($this->withfile)) {
961 // TODO Trick to have param removedfile containing nb of file to delete. But this does not works without javascript
962 $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
963 $out .= '<script nonce="'.getNonce().'" type="text/javascript">';
964 $out .= 'jQuery(document).ready(function () {';
965 $out .= ' jQuery(".removedfile").click(function() {';
966 $out .= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
967 $out .= ' });';
968 $out .= '})';
969 $out .= '</script>'."\n";
970 if (count($listofpaths)) {
971 foreach ($listofpaths as $key => $val) {
972 $relativepathtofile = substr($val, (strlen(DOL_DATA_ROOT) - strlen($val)));
973
974 $entity = (isset($this->param['object_entity']) ? $this->param['object_entity'] : $conf->entity);
975 if ($entity > 1) {
976 $relativepathtofile = str_replace('/'.$entity.'/', '/', $relativepathtofile);
977 }
978 // Try to extract data from full path
979 $formfile_params = array();
980 preg_match('#^(/)(\w+)(/)(.+)$#', $relativepathtofile, $formfile_params);
981
982 $out .= '<div id="attachfile_'.$key.'">';
983 // Preview of attachment
984 $out .= img_mime($listofnames[$key]).$listofnames[$key];
985
986 $out .= ' '.$formfile->showPreview(array('fullname' => $val,'name' => basename($val)), $formfile_params[2], $formfile_params[4], 0, ($entity == 1 ? '' : 'entity='.((int) $entity)));
987
988 if (!$this->withfilereadonly) {
989 $out .= ' <input type="image" style="border: 0px;" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/delete.png" value="'.($key + 1).'" class="removedfile input-nobottom" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
990 //$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).'&id=removedfile_'.$key.'">'.img_delete($langs->trans("Remove"), 'id="removedfile_'.$key.'" name="removedfile_'.$key.'"', 'removedfile input-nobottom').'</a>';
991 }
992 $out .= '<br></div>';
993 }
994 } /*elseif (empty($this->withmaindocfile)) {
995 //$out .= '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
996 }*/
997 if ($this->withfile == 2) {
998 $maxfilesizearray = getMaxFileSizeArray();
999 $maxmin = $maxfilesizearray['maxmin'];
1000 if ($maxmin > 0) {
1001 $out .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
1002 }
1003 // Can add other files
1004 if (!getDolGlobalString('FROM_MAIL_DONT_USE_INPUT_FILE_MULTIPLE')) {
1005 $out .= '<input type="file" class="flat" id="addedfile" name="addedfile[]" value="'.$langs->trans("Upload").'" multiple />';
1006 } else {
1007 $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
1008 }
1009 $out .= ' ';
1010 $out .= '<input type="submit" class="button smallpaddingimp" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
1011 }
1012 } else {
1013 $out .= $this->withfile;
1014 }
1015
1016 $out .= "</td></tr>\n";
1017 }
1018
1019 // Message (+ Links to choose layout or ai prompt)
1020 if (!empty($this->withbody)) {
1021 $defaultmessage = GETPOST('message', 'restricthtml');
1022 if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
1023 if ($arraydefaultmessage && $arraydefaultmessage->content) {
1024 $defaultmessage = (string) $arraydefaultmessage->content;
1025 } elseif (!is_numeric($this->withbody)) {
1026 $defaultmessage = $this->withbody;
1027 }
1028 }
1029
1030 // Complete substitution array with the url to make online payment
1031 $paymenturl = '';
1032 // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
1033 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
1034 $validpaymentmethod = getValidOnlinePaymentMethods('');
1035
1036 if (empty($this->substit['__REF__'])) { // @phan-suppress-current-line PhanTypeMismatchProperty
1037 $paymenturl = '';
1038 } else {
1039 $langs->loadLangs(array('paypal', 'other'));
1040 $typeforonlinepayment = 'free';
1041 if ($this->param["models"] == 'order' || $this->param["models"] == 'order_send') {
1042 $typeforonlinepayment = 'order'; // TODO use detection on something else than template
1043 }
1044 if ($this->param["models"] == 'invoice' || $this->param["models"] == 'facture_send') {
1045 $typeforonlinepayment = 'invoice'; // TODO use detection on something else than template
1046 }
1047 if ($this->param["models"] == 'member') {
1048 $typeforonlinepayment = 'member'; // TODO use detection on something else than template
1049 }
1050 $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']);
1051 $paymenturl = $url;
1052 }
1053
1054 if (count($validpaymentmethod) > 0 && $paymenturl) {
1055 $langs->load('other');
1056 $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = str_replace('\n', "\n", $langs->transnoentities("PredefinedMailContentLink", $paymenturl));
1057 $this->substit['__ONLINE_PAYMENT_URL__'] = $paymenturl;
1058 } elseif (count($validpaymentmethod) > 0) {
1059 $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '__ONLINE_PAYMENT_TEXT_AND_URL__';
1060 $this->substit['__ONLINE_PAYMENT_URL__'] = '__ONLINE_PAYMENT_URL__';
1061 } else {
1062 $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
1063 $this->substit['__ONLINE_PAYMENT_URL__'] = '';
1064 }
1065
1066 $this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'] = '';
1067
1068 // Generate the string with the template for lines repeated and filled for each line
1069 $lines = '';
1070 $defaultlines = $arraydefaultmessage->content_lines;
1071 if (isset($defaultlines)) {
1072 foreach ($this->substit_lines as $lineid => $substit_line) {
1073 $lines .= make_substitutions($defaultlines, $substit_line, $outputlangs)."\n";
1074 }
1075 }
1076 $this->substit['__LINES__'] = $lines;
1077
1078 $defaultmessage = str_replace('\n', "\n", $defaultmessage);
1079
1080 // Deal with format differences between message and some substitution variables (text / HTML)
1081 $atleastonecomponentishtml = 0;
1082 if (strpos($defaultmessage, '__USER_SIGNATURE__') !== false && dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
1083 $atleastonecomponentishtml++;
1084 }
1085 if (strpos($defaultmessage, '__SENDEREMAIL_SIGNATURE__') !== false && dol_textishtml($this->substit['__SENDEREMAIL_SIGNATURE__'])) {
1086 $atleastonecomponentishtml++;
1087 }
1088 if (strpos($defaultmessage, '__ONLINE_PAYMENT_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
1089 $atleastonecomponentishtml++;
1090 }
1091 if (strpos($defaultmessage, '__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'])) {
1092 $atleastonecomponentishtml++;
1093 }
1094 if (dol_textishtml($defaultmessage)) {
1095 $atleastonecomponentishtml++;
1096 }
1097 if ($atleastonecomponentishtml) {
1098 if (!dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
1099 $this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']);
1100 }
1101 if (!dol_textishtml($this->substit['__SENDEREMAIL_SIGNATURE__'])) {
1102 $this->substit['__SENDEREMAIL_SIGNATURE__'] = dol_nl2br($this->substit['__SENDEREMAIL_SIGNATURE__']);
1103 }
1104 if (!dol_textishtml($this->substit['__LINES__'])) {
1105 $this->substit['__LINES__'] = dol_nl2br($this->substit['__LINES__']);
1106 }
1107 if (!dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
1108 $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = dol_nl2br($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']);
1109 }
1110 if (!dol_textishtml($defaultmessage)) {
1111 $defaultmessage = dol_nl2br($defaultmessage);
1112 }
1113 }
1114
1115 if (GETPOSTISSET("message") && !GETPOST('modelselected')) {
1116 $defaultmessage = GETPOST("message", "restricthtml");
1117 } else {
1118 // Pass $outputlangs so __(TranslationKey)__ in the template body is resolved
1119 // in the language of the selected email template, not the operator's language
1120 // (see issue #34540).
1121 $defaultmessage = make_substitutions($defaultmessage, $this->substit, $outputlangs);
1122 // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
1123 $defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
1124 $defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
1125 }
1126
1127 $out .= '<!-- Message line from get_form -->';
1128 $out .= '<tr>';
1129 $out .= '<td class="tdtop">';
1130 $out .= $form->textwithpicto($langs->trans('MailText'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfrombody');
1131 $out .= '</td>';
1132 $out .= '<td class="tdtop">';
1133
1134 $formmail = $this;
1135 $showlinktolayout = ($formmail->withfckeditor && getDolGlobalInt('MAIN_EMAIL_USE_LAYOUT')) ? $formmail->withlayout : '';
1136 $showlinktolayoutlabel = $langs->trans("FillMessageWithALayout");
1137 $showlinktoai = ($formmail->withaiprompt && isModEnabled('ai')) ? 'textgenerationemail' : '';
1138 $showlinktoailabel = $langs->trans("AIEnhancements");
1139 $formatforouput = '';
1140 $htmlname = 'message';
1141
1142 $formai->substit = $this->substit;
1143 $formai->substit_lines = $this->substit_lines;
1144
1145 // Fill $out
1146 $db = $this->db;
1147 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
1148
1149 $out .= '</td>';
1150 $out .= '</tr>';
1151
1152 $out .= '<tr>';
1153 $out .= '<td colspan="2">';
1154 if ($this->withbodyreadonly) {
1155 $out .= nl2br($defaultmessage);
1156 $out .= '<input type="hidden" id="message" name="message" disabled value="'.$defaultmessage.'" />';
1157 } else {
1158 if (!isset($this->ckeditortoolbar)) {
1159 $this->ckeditortoolbar = 'dolibarr_mailings';
1160 }
1161
1162 // Editor wysiwyg
1163 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1164 if ($this->withfckeditor == -1) {
1165 if (getDolGlobalString('FCKEDITOR_ENABLE_MAIL')) {
1166 $this->withfckeditor = 1;
1167 } else {
1168 $this->withfckeditor = 0;
1169 }
1170 }
1171
1172 $uselocalbrowser = getDolGlobalBool('FCKEDITOR_ENABLE_IMAGE_UPLOAD');
1173 // $uselocalbrowser = true;
1174
1175 $doleditor = new DolEditor('message', $defaultmessage, '', 280, $this->ckeditortoolbar, 'In', true, $uselocalbrowser, $this->withfckeditor, 8, '95%');
1176 $out .= $doleditor->Create(1);
1177 }
1178 $out .= "</td></tr>\n";
1179 }
1180
1181 $out .= '</table>'."\n";
1182
1183 if ($this->withform == 1 || $this->withform == -1) {
1184 $out .= '<div class="center">';
1185 $out .= '<input type="submit" class="button button-add" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
1186 // Add a javascript test to avoid to forget to submit file before sending email
1187 if ($this->withfile == 2 && $conf->use_javascript_ajax) {
1188 $out .= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
1189 }
1190 $out .= ' />';
1191 if ($this->withcancel) {
1192 $out .= '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
1193 }
1194 $out .= '</div>'."\n";
1195 }
1196
1197 if ($this->withform == 1) {
1198 $out .= '</form>'."\n";
1199 }
1200
1201 // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
1202 if (getDolGlobalString('MAIN_MAILFORM_DISABLE_ENTERKEY')) {
1203 $out .= '<script nonce="'.getNonce().'" type="text/javascript">';
1204 $out .= 'jQuery(document).ready(function () {';
1205 $out .= ' $(document).on("keypress", \'#mailform\', function (e) { /* Note this is called at every key pressed ! */
1206 var code = e.keyCode || e.which;
1207 if (code == 13) {
1208 console.log("Enter was intercepted and blocked");
1209 e.preventDefault();
1210 return false;
1211 }
1212 });';
1213 $out .= ' })';
1214 $out .= '</script>';
1215 }
1216
1217 $out .= "<!-- End form mail -->\n";
1218
1219 return $out;
1220 }
1221 }
1222
1228 public function getHtmlForTo()
1229 {
1230 global $langs, $form;
1231 $out = '<tr><td class="fieldrequired">';
1232 if ($this->withtofree) {
1233 $out .= $form->textwithpicto($langs->trans("MailTo"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
1234 } else {
1235 $out .= $langs->trans("MailTo");
1236 }
1237 $out .= '</td><td>';
1238 if ($this->withtoreadonly) {
1239 if (!empty($this->toname) && !empty($this->tomail)) {
1240 $out .= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
1241 $out .= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
1242 if ($this->totype == 'thirdparty') {
1243 $soc = new Societe($this->db);
1244 $soc->fetch($this->toid);
1245 $out .= $soc->getNomUrl(1);
1246 } elseif ($this->totype == 'contact') {
1247 $contact = new Contact($this->db);
1248 $contact->fetch($this->toid);
1249 $out .= $contact->getNomUrl(1);
1250 } else {
1251 $out .= $this->toname;
1252 }
1253 $out .= ' &lt;'.$this->tomail.'&gt;';
1254 if ($this->withtofree) {
1255 $out .= '<br>'.$langs->trans("and").' <input class="minwidth200" id="sendto" name="sendto" spellcheck="false" value="'.(!is_array($this->withto) && !is_numeric($this->withto) ? (GETPOSTISSET("sendto") ? GETPOST("sendto") : $this->withto) : "").'" />';
1256 }
1257 } else {
1258 // Note withto may be a text like 'AllRecipientSelected'
1259 $out .= (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : "";
1260 }
1261 } else {
1262 // The free input of email
1263 if (!empty($this->withtofree)) {
1264 $out .= '<input class="minwidth200" id="sendto" name="sendto" spellcheck="false" value="'.(($this->withtofree && !is_numeric($this->withtofree)) ? $this->withtofree : (!is_array($this->withto) && !is_numeric($this->withto) ? (GETPOSTISSET("sendto") ? GETPOST("sendto") : $this->withto) : "")).'" />';
1265 }
1266 // The select combo
1267 if (!empty($this->withto) && is_array($this->withto)) {
1268 if (!empty($this->withtofree)) {
1269 $out .= ' <span class="opacitymedium">'.$langs->trans("and")."/".$langs->trans("or")."</span> ";
1270 }
1271
1272 $tmparray = $this->withto;
1273 foreach ($tmparray as $key => $val) {
1274 if (is_array($val)) {
1275 $label = $val['label'];
1276 } else {
1277 $label = $val;
1278 }
1279
1280 $tmparray[$key] = array();
1281 $tmparray[$key]['id'] = $key;
1282
1283 $tmparray[$key]['label'] = $label;
1284 $tmparray[$key]['label'] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]['label']);
1285 // multiselect array convert html entities into options tags, even if we don't want this, so we encode them a second time
1286 $tmparray[$key]['label'] = dol_htmlentities($tmparray[$key]['label'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', true);
1287
1288 $tmparray[$key]['labelhtml'] = $label;
1289 $tmparray[$key]['labelhtml'] = str_replace(array('&lt;', '<', '&gt;', '>'), array('__LTCHAR__', '__LTCHAR__', '__GTCHAR__', '__GTCHAR__'), $tmparray[$key]['labelhtml']);
1290 $tmparray[$key]['labelhtml'] = str_replace(array('__LTCHAR__', '__GTCHAR__'), array('<span class="opacitymedium">(', ')</span>'), $tmparray[$key]['labelhtml']);
1291 }
1292
1293 $withtoselected = GETPOST("receiver", 'array'); // Array of selected value
1294 if (!getDolGlobalInt('MAIN_MAIL_NO_WITH_TO_SELECTED')) {
1295 if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
1296 $withtoselected = array_keys($tmparray);
1297 }
1298 }
1299
1300 $out .= $form->multiselectarray("receiver", $tmparray, $withtoselected, 0, 0, 'inline-block minwidth500', 0, 0);
1301 }
1302 }
1303 $out .= "</td></tr>\n";
1304 return $out;
1305 }
1306
1312 public function getHtmlForCc()
1313 {
1314 global $langs, $form;
1315 $out = '<tr><td>';
1316 $out .= $form->textwithpicto($langs->trans("MailCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
1317 $out .= '</td><td>';
1318 if ($this->withtoccreadonly) {
1319 $out .= (!is_array($this->withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : "";
1320 } else {
1321 $out .= '<input class="minwidth200" id="sendtocc" name="sendtocc" value="'.(GETPOST("sendtocc", "alpha") ? GETPOST("sendtocc", "alpha") : ((!is_array($this->withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : '')).'" />';
1322 if (!empty($this->withtocc) && is_array($this->withtocc)) {
1323 $out .= ' <span class="opacitymedium">'.$langs->trans("and")."/".$langs->trans("or")."</span> ";
1324
1325 $tmparray = $this->withtocc;
1326 foreach ($tmparray as $key => $val) {
1327 if (is_array($val)) {
1328 $label = $val['label'];
1329 } else {
1330 $label = $val;
1331 }
1332
1333 $tmparray[$key] = array();
1334 $tmparray[$key]['id'] = $key;
1335
1336 $tmparray[$key]['label'] = $label;
1337 $tmparray[$key]['label'] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]['label']);
1338 // multiselect array convert html entities into options tags, even if we don't want this, so we encode them a second time
1339 $tmparray[$key]['label'] = dol_htmlentities($tmparray[$key]['label'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', true);
1340
1341 $tmparray[$key]['labelhtml'] = $label;
1342 $tmparray[$key]['labelhtml'] = str_replace(array('&lt;', '<', '&gt;', '>'), array('__LTCHAR__', '__LTCHAR__', '__GTCHAR__', '__GTCHAR__'), $tmparray[$key]['labelhtml']);
1343 $tmparray[$key]['labelhtml'] = str_replace(array('__LTCHAR__', '__GTCHAR__'), array('<span class="opacitymedium">(', ')</span>'), $tmparray[$key]['labelhtml']);
1344 }
1345
1346 $withtoccselected = GETPOST("receivercc", 'array'); // Array of selected value
1347
1348 $out .= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, 0, 0, 'inline-block minwidth500', 0, 0);
1349 }
1350 }
1351 $out .= "</td></tr>\n";
1352 return $out;
1353 }
1354
1361 public function getHtmlForWithCcc()
1362 {
1363 global $langs, $form;
1364
1365 $out = '<tr><td>';
1366 $out .= $form->textwithpicto($langs->trans("MailCCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
1367 $out .= '</td><td>';
1368 if (!empty($this->withtocccreadonly)) {
1369 $out .= (!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : "";
1370 } else {
1371 $out .= '<input class="minwidth200" id="sendtoccc" name="sendtoccc" value="'.(GETPOSTISSET("sendtoccc") ? GETPOST("sendtoccc", "alpha") : ((!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : '')).'" />';
1372 if (!empty($this->withtoccc) && is_array($this->withtoccc)) {
1373 $out .= ' <span class="opacitymedium">'.$langs->trans("and")."/".$langs->trans("or")."</span> ";
1374
1375 $tmparray = $this->withtoccc;
1376 foreach ($tmparray as $key => $val) {
1377 if (is_array($val)) {
1378 $label = $val['label'];
1379 } else {
1380 $label = $val;
1381 }
1382 $tmparray[$key] = array();
1383 $tmparray[$key]['id'] = $key;
1384
1385 $tmparray[$key]['label'] = $label;
1386 $tmparray[$key]['label'] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]['label']);
1387 // multiselect array convert html entities into options tags, even if we don't want this, so we encode them a second time
1388 $tmparray[$key]['label'] = dol_htmlentities($tmparray[$key]['label'], ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8', true);
1389
1390 $tmparray[$key]['labelhtml'] = $label;
1391 $tmparray[$key]['labelhtml'] = str_replace(array('&lt;', '<', '&gt;', '>'), array('__LTCHAR__', '__LTCHAR__', '__GTCHAR__', '__GTCHAR__'), $tmparray[$key]['labelhtml']);
1392 $tmparray[$key]['labelhtml'] = str_replace(array('__LTCHAR__', '__GTCHAR__'), array('<span class="opacitymedium">(', ')</span>'), $tmparray[$key]['labelhtml']);
1393 }
1394
1395 $withtocccselected = GETPOST("receiverccc", 'array'); // Array of selected value
1396
1397 $out .= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, 0, 0, 'inline-block minwidth500', 0, 0);
1398 }
1399 }
1400
1401 $showinfobcc = '';
1402 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO') && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
1403 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROPOSAL_TO');
1404 }
1405 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO') && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
1406 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_ORDER_TO');
1407 }
1408 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO') && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
1409 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_INVOICE_TO');
1410 }
1411 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO') && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
1412 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO');
1413 }
1414 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO') && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
1415 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO');
1416 }
1417 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO') && !empty($this->param['models']) && $this->param['models'] == 'invoice_supplier_send') {
1418 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO');
1419 }
1420 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO') && !empty($this->param['models']) && $this->param['models'] == 'project') { // don't know why there is not '_send' at end of this models name.
1421 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_PROJECT_TO');
1422 }
1423 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_SHIPMENT_TO') && !empty($this->param['models']) && $this->param['models'] == 'shipping_send') {
1424 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_SHIPMENT_TO');
1425 }
1426 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_RECEPTION_TO') && !empty($this->param['models']) && $this->param['models'] == 'reception_send') {
1427 $showinfobcc = getDolGlobalString('MAIN_MAIL_AUTOCOPY_RECEPTION_TO');
1428 }
1429 if ($showinfobcc) {
1430 $out .= ' + '.$showinfobcc;
1431 }
1432 $out .= "</td></tr>\n";
1433 return $out;
1434 }
1435
1441 public function getHtmlForWithErrorsTo()
1442 {
1443 global $langs;
1444
1445 //if (! $this->errorstomail) $this->errorstomail=$this->frommail;
1446 $errorstomail = getDolGlobalString('MAIN_MAIL_ERRORS_TO', (!empty($this->errorstomail) ? $this->errorstomail : ''));
1447 if ($this->witherrorstoreadonly) {
1448 $out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
1449 $out .= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
1450 $out .= $errorstomail;
1451 $out .= "</td></tr>\n";
1452 } else {
1453 $out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
1454 $out .= '<input class="minwidth200" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
1455 $out .= "</td></tr>\n";
1456 }
1457 return $out;
1458 }
1459
1465 public function getHtmlForDeliveryreceipt()
1466 {
1467 global $langs;
1468
1469 $out = '<tr><td><label for="deliveryreceipt">'.$langs->trans("DeliveryReceipt").'</label></td><td>';
1470
1471 if (!empty($this->withdeliveryreceiptreadonly)) {
1472 $out .= yn($this->withdeliveryreceipt);
1473 } else {
1474 $defaultvaluefordeliveryreceipt = 0;
1475 if (getDolGlobalString('MAIL_FORCE_DELIVERY_RECEIPT_PROPAL') && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
1476 $defaultvaluefordeliveryreceipt = 1;
1477 }
1478 if (getDolGlobalString('MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL') && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
1479 $defaultvaluefordeliveryreceipt = 1;
1480 }
1481 if (getDolGlobalString('MAIL_FORCE_DELIVERY_RECEIPT_ORDER') && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
1482 $defaultvaluefordeliveryreceipt = 1;
1483 }
1484 if (getDolGlobalString('MAIL_FORCE_DELIVERY_RECEIPT_INVOICE') && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
1485 $defaultvaluefordeliveryreceipt = 1;
1486 }
1487 if (getDolGlobalString('MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_ORDER') && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
1488 $defaultvaluefordeliveryreceipt = 1;
1489 }
1490 //$out .= $form->selectyesno('deliveryreceipt', (GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt), 1);
1491 $out .= '<input type="checkbox" id="deliveryreceipt" name="deliveryreceipt" value="1"'.((GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt) ? ' checked="checked"' : '').'>';
1492 }
1493 $out .= "</td></tr>\n";
1494 return $out;
1495 }
1496
1504 public function getHtmlForTopic($arraydefaultmessage, $helpforsubstitution)
1505 {
1506 global $conf, $langs, $form;
1507
1508 $defaulttopic = GETPOST('subject', 'restricthtml');
1509
1510 if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
1511 if ($arraydefaultmessage && $arraydefaultmessage->topic) {
1512 $defaulttopic = $arraydefaultmessage->topic;
1513 } elseif (!is_numeric($this->withtopic)) {
1514 $defaulttopic = $this->withtopic;
1515 }
1516 }
1517
1518 // Resolve __(TranslationKey)__ in the language of the selected template
1519 // (see issue #34540). Falls back to the caller's language when the template
1520 // has no explicit language pinned.
1521 $outputlangs = $langs;
1522 if (is_object($arraydefaultmessage) && !empty($arraydefaultmessage->lang)) {
1523 $outputlangs = new Translate("", $conf);
1524 $outputlangs->setDefaultLang($arraydefaultmessage->lang);
1525 $outputlangs->loadLangs(array('other', 'commercial', 'bills', 'orders', 'contracts', 'main', 'members', 'propal', 'products', 'supplier_proposal', 'interventions', 'receptions', 'sendings'));
1526 }
1527
1528 $defaulttopic = make_substitutions($defaulttopic, $this->substit, $outputlangs);
1529
1530 $out = '<tr>';
1531 $out .= '<td class="fieldrequired">';
1532 $out .= $form->textwithpicto($langs->trans('MailTopicShort'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfromtopic');
1533 $out .= '</td>';
1534 $out .= '<td>';
1535 if ($this->withtopicreadonly) {
1536 $out .= $defaulttopic;
1537 $out .= '<input type="hidden" class="quatrevingtpercent" id="subject" name="subject" value="'.$defaulttopic.'" spellcheck="false">';
1538 } else {
1539 $out .= '<input type="text" class="quatrevingtpercent" id="subject" name="subject" value="'.((GETPOSTISSET("subject") && !GETPOST('modelselected')) ? GETPOST("subject") : ($defaulttopic ? $defaulttopic : '')).'" spellcheck="false">';
1540 }
1541 $out .= "</td></tr>\n";
1542 return $out;
1543 }
1544
1553 public function getEmailLayoutSelector($htmlContent = 'message', $showlinktolayout = 'email')
1554 {
1555 global $conf, $db, $websitepage, $langs;
1556
1557 require_once DOL_DOCUMENT_ROOT.'/core/lib/emaillayout.lib.php';
1558 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1559 require_once DOL_DOCUMENT_ROOT.'/website/class/website.class.php';
1560 require_once DOL_DOCUMENT_ROOT.'/website/class/websitepage.class.php';
1561
1562 $out = '<div id="template-selector" class="template-selector email-layout-container hidden" style="display:none;">';
1563 $out .= '<div>';
1564
1565 // Define list of email layouts to use
1566 $layouts = array(
1567 'none' => 'None',
1568 );
1569 // Add layouts found on disk in install/doctemplates/maillayout directory
1570 $arrayoflayoutemplates = dol_dir_list(DOL_DOCUMENT_ROOT.'/install/doctemplates/maillayout/', 'files', 0, '\.html$');
1571 foreach ($arrayoflayoutemplates as $layouttemplatefile) {
1572 $layoutname = preg_replace('/\.html$/i', '', $layouttemplatefile['name']);
1573
1574 // Exclude some layouts for some use cases
1575 if ($layoutname == 'news' && (!in_array($showlinktolayout, array('emailing', 'websitepage')) || !isModEnabled('website'))) {
1576 continue;
1577 }
1578 if ($layoutname == 'product' && (!in_array($showlinktolayout, array('emailing', 'websitepage')) || (!isModEnabled('product') && !isModEnabled('service')))) {
1579 continue;
1580 }
1581
1582 $layouts[$layoutname] = ucfirst($layoutname);
1583 }
1584 //}
1585 // TODO Add a hook to allow to complete the list
1586 foreach ($layouts as $layout => $templateFunction) {
1587 $contentHtml = getHtmlOfLayout($layout);
1588
1589 $out .= '<div class="template-option" data-template="'.$layout.'" data-content="'.htmlentities($contentHtml).'">';
1590 $out .= '<img class="maillayout" alt="'.$layout.'" src="'.DOL_URL_ROOT.'/theme/common/maillayout/'.$layout.'.png" />';
1591 $out .= '<span class="template-option-text">'.$langs->trans($templateFunction).'</span>';
1592 $out .= '</div>';
1593 }
1594 $out .= '</div>';
1595
1596 // Prepare the array for multiselect
1597
1598 // Fetch blogs
1599 $blogArray = array();
1600 if (isModEnabled('website')) {
1601 $websitepage = new WebsitePage($this->db);
1602 $arrayofblogs = $websitepage->fetchAll('', 'ASC,DESC', 'fk_website,date_creation', 0, 0, array('type_container' => 'blogpost'));
1603
1604 if (empty($conf->cache['websiteurl'])) {
1605 $conf->cache['websiteurl'] = array();
1606 }
1607
1608 if (!empty($arrayofblogs)) {
1609 foreach ($arrayofblogs as $blog) {
1610 if (!isset($conf->cache['websiteurl'][$blog->id])) {
1611 $tmpwebsite = new Website($db);
1612 $tmpwebsite->fetch($blog->fk_website);
1613 $conf->cache['websiteurl'][$blog->fk_website] = (empty($tmpwebsite->virtualhost) ? $tmpwebsite->ref : $tmpwebsite->virtualhost);
1614 }
1615
1616 $labelwebsite = $conf->cache['websiteurl'][$blog->fk_website];
1617 //$blog->fk_website
1618
1619 $blogArray[$blog->id] = array(
1620 'id' => $blog->id,
1621 'label' => '['.$labelwebsite.' '.$blog->type_container.' '.$blog->id.'] '.dol_trunc($blog->title, 40),
1622 'labelhtml' => '<span class="opacitymedium">['.$labelwebsite.' '.$blog->type_container.' '.$blog->id.']</span> '.dol_trunc($blog->title, 40),
1623 );
1624 }
1625 }
1626 }
1627
1628 // Fetch Product / Services
1629 /* to use with multiselectarray but consume too much memory so replaced
1630 if (in_array('product', array_keys($layouts))) {
1631 $productArray = array();
1632 if (isModEnabled('product') || isModEnabled('service')) {
1633 include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
1634 $form = new Form($this->db);
1635 $arrayofproduct = $form->select_produits_list(0, 'product-select', '', 0, 0, '', 1, 2, 1);
1636 if (!empty($arrayofproduct)) {
1637 foreach ($arrayofproduct as $product) {
1638 $productArray[$product["key"]] = array(
1639 'id' => $product["key"],
1640 'label' => $product["value"].' - '.dol_trunc($product["label2"], 40),
1641 'labelhtml' => $product["value"].' - '.dol_trunc($product["label2"], 40),
1642 );
1643 }
1644 }
1645 }
1646 }
1647 */
1648
1649 // Use the multiselect array function to create the dropdown
1650 if (in_array('news', array_keys($layouts)) && (isModEnabled('product') || isModEnabled('service'))) {
1651 $out .= '<div id="post-dropdown-container" class="email-layout-container hidden" style="margin-top: 8px; display:none;">';
1652 $out .= '<label for="blogpost-select">Select Posts: </label>';
1653 $out .= '<!-- select component for selection of blog posts -->'."\n";
1654 // TODO WARNING: multiselectarray is ok only for very small list
1655 $out .= self::multiselectarray('blogpost-select', $blogArray, array(), 0, 0, 'minwidth200 select-template');
1656 $out .= ' <input type="submit" class="smallpaddingimp button reposition" name="submit" id="post-submit" value="'.dolPrintHTMLForAttribute($langs->trans("Select")).'">';
1657 $out .= '</div>';
1658 }
1659 if (in_array('product', array_keys($layouts)) && (isModEnabled('product') || isModEnabled('service'))) {
1660 include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
1661 $form = new Form($this->db);
1662 $out .= '<div id="product-dropdown-container" class="email-layout-container hidden" style="margin-top: 8px; display:none;">';
1663 $out .= '<label for="product-select">'.img_picto('', 'product', 'class="pictofixedwidth"').$langs->trans("Product").' : </label>';
1664 $out .= '<!-- select component for selection of product -->'."\n";
1665 $out .= $form->select_produits(0, 'product-select', '', 0, 0, -1, 2, '', 0, array(), 0, '1', 0, 'inline-block valignmiddle', 0, '', null, 1);
1666 // TODO multiselectarray is ok only for very small list but is ok for multiselect. We need a multiselect ok with ajax for long list
1667 //$out .= self::multiselectarray('product-select', $productArray, array(), 0, 0, 'minwidth200 select-template');
1668 $out .= ' <input type="submit" class="smallpaddingimp button reposition" name="submit" id="product-submit" value="'.dolPrintHTMLForAttribute($langs->trans("Select")).'">';
1669 $out .= '</div>';
1670 }
1671
1672 $out .= '</div>';
1673
1674 $out .= '<!-- Js code to manage choice of an email layout -->'."\n";
1675 $out .= '<script type="text/javascript">
1676 $(document).ready(function() {
1677 $(".template-option").click(function() {
1678 var template = $(this).data("template");
1679 var subject = jQuery("#subject").val();
1680 var fromtype = jQuery("#fromtype").val();
1681 var sendto = jQuery("#sendto").val();
1682 var sendtocc = jQuery("#sendtocc").val();
1683 var sendtoccc = jQuery("#sendtoccc").val();
1684
1685 console.log("We choose a layout for email template=" + template + ", subject="+subject);
1686
1687 $(".template-option").removeClass("selected");
1688 $(this).addClass("selected");
1689 $(".select-template").val("").trigger("change");
1690
1691 if (template === "news") {
1692 $("#post-dropdown-container").show();
1693 $("#product-dropdown-container").hide();
1694 console.log("Displaying dropdown for news selection");
1695 } else if (template === "product") {
1696 $("#product-dropdown-container").show();
1697 $("#post-dropdown-container").hide();
1698 console.log("Displaying dropdown for product selection");
1699 } else {
1700 $("#post-dropdown-container").hide();
1701 $("#product-dropdown-container").hide();
1702 }
1703
1704 var csrfToken = "' .newToken().'";
1705 $.ajax({
1706 type: "POST",
1707 url: "'.DOL_URL_ROOT.'/core/ajax/mailtemplate.php",
1708 data: {
1709 token: csrfToken,
1710 template: template,
1711 subject: subject,
1712 fromtype: fromtype,
1713 sendto: sendto,
1714 sendtocc: sendtocc,
1715 sendtoccc: sendtoccc,
1716 selectedPosts: "[]"
1717 },
1718 success: function(response) {
1719 jQuery("#'.$htmlContent.'").val(response);
1720 var editorInstance = CKEDITOR.instances["'.$htmlContent.'"];
1721 if (editorInstance) {
1722 editorInstance.setData(response);
1723 }
1724 },
1725 error: function(xhr, status, error) {
1726 console.error("An error occurred: " + xhr.responseText);
1727 }
1728 });
1729 });
1730
1731 $("#blogpost-select").change(function() {
1732 var selectedIds = $(this).val();
1733 var contentHtml = $(".template-option.selected").data("content");
1734
1735 updateSelectedPostsContent(contentHtml, selectedIds);
1736 });
1737 $("#product-select").change(function() {
1738 var selectedIds = $(this).val();
1739 var contentHtml = $(".template-option.selected").data("content");
1740
1741 updateSelectedPostsContent(contentHtml, selectedIds);
1742 });
1743
1744 function updateSelectedPostsContent(contentHtml, selectedIds) {
1745 var csrfToken = "' .newToken().'";
1746 template = $(".template-option.selected").data("template");
1747 var subject = $("#subject").val();
1748 $.ajax({
1749 type: "POST",
1750 url: "'.dol_buildpath('/core/ajax/mailtemplate.php', 1).'",
1751 data: {
1752 token: csrfToken,
1753 template: template,
1754 subject: subject,
1755 selectedPosts: JSON.stringify(selectedIds)
1756 },
1757 success: function(response) {
1758 jQuery("#'.$htmlContent.'").val(response);
1759 var editorInstance = CKEDITOR.instances["'.$htmlContent.'"];
1760 if (editorInstance) {
1761 editorInstance.setData(response);
1762 }
1763 },
1764 error: function(xhr, status, error) {
1765 console.error("An error occurred: " + xhr.responseText);
1766 }
1767 });
1768
1769 }
1770 });
1771 </script>';
1772
1773 return $out;
1774 }
1775
1793 public function getEMailTemplate($dbs, $type_template, $user, $outputlangs, $id = 0, $active = 1, $label = '', $defaultfortype = -1)
1794 {
1795 global $conf;
1796
1797 if ($id == -2 && empty($label)) {
1798 $this->error = 'LabelIsMandatoryWhenIdIs-2or-3';
1799 return -1;
1800 }
1801 if ($type_template === 'societe') {
1802 $type_template = 'thirdparty';
1803 }
1804 $ret = new CEmailTemplate($dbs);
1805
1806 $languagetosearch = (is_object($outputlangs) ? $outputlangs->defaultlang : '');
1807 // Define $languagetosearchmain to fall back on main language (for example to get 'es_ES' for 'es_MX')
1808 $tmparray = explode('_', $languagetosearch);
1809 $languagetosearchmain = $tmparray[0].'_'.strtoupper($tmparray[0]);
1810 if ($languagetosearchmain == $languagetosearch) {
1811 $languagetosearchmain = '';
1812 }
1813
1814 $sql = "SELECT rowid, entity, module, label, type_template, topic, email_from, joinfiles, content, content_lines, lang, email_from, email_to, email_tocc, email_tobcc";
1815 $sql .= " FROM ".$dbs->prefix().'c_email_templates';
1816 $sql .= " WHERE (type_template = '".$dbs->escape($type_template)."' OR type_template = '".$dbs->escape($type_template)."_send' OR type_template = 'all')";
1817 $sql .= " AND entity IN (".getEntity('c_email_templates').")";
1818 $sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // Get all public or private owned
1819 if ($active >= 0) {
1820 $sql .= " AND active = ".((int) $active);
1821 }
1822 if ($defaultfortype >= 0) {
1823 $sql .= " AND defaultfortype = ".((int) $defaultfortype);
1824 }
1825 if ($label) {
1826 $sql .= " AND label = '".$dbs->escape($label)."'";
1827 }
1828 if (!($id > 0) && $languagetosearch) {
1829 $sql .= " AND (lang = '".$dbs->escape($languagetosearch)."'".($languagetosearchmain ? " OR lang = '".$dbs->escape($languagetosearchmain)."'" : "")." OR lang IS NULL OR lang = '')";
1830 }
1831 if ($id > 0) {
1832 $sql .= " AND rowid = ".(int) $id;
1833 }
1834 if ($id == -1) {
1835 $sql .= " AND position = 0";
1836 }
1837 $sql .= " AND entity IN(".getEntity('c_email_templates', 1).")";
1838 if ($languagetosearch) {
1839 $sql .= $dbs->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or ''
1840 } else {
1841 $sql .= $dbs->order("position,lang,label", "ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined
1842 }
1843 //$sql .= $dbs->plimit(1);
1844 //print $sql;
1845
1846 $resql = $dbs->query($sql);
1847 if (!$resql) {
1848 dol_print_error($dbs);
1849 return -1;
1850 }
1851
1852 // Get first found
1853 while (1) {
1854 $obj = $dbs->fetch_object($resql);
1855
1856 if ($obj) {
1857 // If template is for a module, check module is enabled; if not, take next template
1858 if ($obj->module) {
1859 $tempmodulekey = $obj->module;
1860 if (empty($conf->$tempmodulekey) || !isModEnabled($tempmodulekey)) {
1861 continue;
1862 }
1863 }
1864
1865 // If a record was found
1866 $ret->id = (int) $obj->rowid;
1867 $ret->module = (string) $obj->module;
1868 $ret->label = (string) $obj->label;
1869 $ret->lang = $obj->lang;
1870 $ret->topic = $obj->topic;
1871 $ret->content = (string) $obj->content;
1872 $ret->content_lines = (string) $obj->content_lines;
1873 $ret->joinfiles = $obj->joinfiles;
1874 $ret->email_from = (string) $obj->email_from;
1875 $ret->email_tocc = (string) $obj->email_tocc;
1876 $ret->email_tobcc = (string) $obj->email_tobcc;
1877
1878 break;
1879 } else {
1880 // If no record found
1881 if ($id == -2) {
1882 // Not found with the provided label
1883 return -1;
1884 } else {
1885 // If there is no template at all
1886 $defaultmessage = '';
1887
1888 if ($type_template == 'body') {
1889 // Special case to use this->withbody as content
1890 $defaultmessage = (string) $this->withbody;
1891 } elseif ($type_template == 'facture_send' || $type_template == 'facture' || $type_template == 'facture_relance') {
1892 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendInvoice");
1893 } elseif ($type_template == 'propal_send' || $type_template == 'propal') {
1894 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendProposal");
1895 } elseif ($type_template == 'supplier_proposal_send' || $type_template == 'supplier_proposal') {
1896 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendSupplierProposal");
1897 } elseif ($type_template == 'order_send' || $type_template == 'order') {
1898 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendOrder");
1899 } elseif ($type_template == 'order_supplier_send' || $type_template == 'order_supplier') {
1900 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendSupplierOrder");
1901 } elseif ($type_template == 'invoice_supplier_send' || $type_template == 'invoice_supplier') {
1902 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendSupplierInvoice");
1903 } elseif ($type_template == 'shipping_send' || $type_template == 'shipping') {
1904 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendShipping");
1905 } elseif ($type_template == 'reception_send' || $type_template == 'reception') {
1906 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendReception");
1907 } elseif ($type_template == 'fichinter_send' || $type_template == 'fichinter') {
1908 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendFichInter");
1909 } elseif ($type_template == 'actioncomm_send' || $type_template == 'actioncomm') {
1910 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentSendActionComm");
1911 } elseif (!empty($type_template)) {
1912 $defaultmessage = $outputlangs->transnoentitiesnoconv("PredefinedMailContentGeneric");
1913 }
1914
1915 $ret->label = 'default';
1916 $ret->lang = $outputlangs->defaultlang;
1917 $ret->topic = '';
1918 $ret->joinfiles = 1;
1919 $ret->content = $defaultmessage;
1920 $ret->content_lines = '';
1921
1922 break;
1923 }
1924 }
1925 }
1926
1927 $dbs->free($resql);
1928
1929 return $ret;
1930 }
1931
1941 public function isEMailTemplate($type_template, $user, $outputlangs)
1942 {
1943 $sql = "SELECT label, topic, content, lang";
1944 $sql .= " FROM ".$this->db->prefix().'c_email_templates';
1945 $sql .= " WHERE type_template='".$this->db->escape($type_template)."'";
1946 $sql .= " AND entity IN (".getEntity('c_email_templates').")";
1947 $sql .= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".((int) $user->id).")";
1948 if (is_object($outputlangs)) {
1949 $sql .= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')";
1950 }
1951 $sql .= $this->db->order("lang,label", "ASC");
1952 //print $sql;
1953
1954 $resql = $this->db->query($sql);
1955 if ($resql) {
1956 $num = $this->db->num_rows($resql);
1957 $this->db->free($resql);
1958 return $num;
1959 } else {
1960 $this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1961 return -1;
1962 }
1963 }
1964
1975 public function fetchAllEMailTemplate($type_template, $user, $outputlangs, $active = 1)
1976 {
1977 global $db, $conf;
1978
1979 $sql = "SELECT rowid, module, label, topic, content, content_lines, lang, fk_user, private, position";
1980 $sql .= " FROM ".$this->db->prefix().'c_email_templates';
1981 $sql .= " WHERE type_template IN ('".$this->db->escape($type_template)."', 'all')";
1982 $sql .= " AND entity IN (".getEntity('c_email_templates').")";
1983 $sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // See all public templates or templates I own.
1984 if ($active >= 0) {
1985 $sql .= " AND active = ".((int) $active);
1986 }
1987 //if (is_object($outputlangs)) $sql.= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')"; // Return all languages
1988 $sql .= $this->db->order("lang,position,label", "ASC");
1989 //print $sql;
1990
1991 $resql = $this->db->query($sql);
1992 if ($resql) {
1993 $num = $this->db->num_rows($resql);
1994 $this->lines_model = array();
1995 while ($obj = $this->db->fetch_object($resql)) {
1996 // If template is for a module, check module is enabled.
1997 if ($obj->module) {
1998 $tempmodulekey = $obj->module;
1999 if (empty($conf->$tempmodulekey) || !isModEnabled($tempmodulekey)) {
2000 continue;
2001 }
2002 }
2003
2004 $line = new CEmailTemplate($db);
2005 $line->id = (int) $obj->rowid;
2006 $line->label = (string) $obj->label;
2007 $line->lang = $obj->lang;
2008 $line->fk_user = $obj->fk_user;
2009 $line->private = $obj->private;
2010 $line->position = $obj->position;
2011 $line->topic = $obj->topic;
2012 $line->content = $obj->content;
2013 $line->content_lines = $obj->content_lines;
2014
2015 $this->lines_model[] = $line;
2016 }
2017 $this->db->free($resql);
2018 return $num;
2019 } else {
2020 $this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
2021 return -1;
2022 }
2023 }
2024
2030 private static function normalizeTextForComparison($value)
2031 {
2032 $value = dol_string_nohtmltag((string) $value);
2033 $value = preg_replace('/\s+/', ' ', $value);
2034 return trim((string) $value);
2035 }
2036
2042 private static function getLangPrefix($langcode)
2043 {
2044 $langcode = trim((string) $langcode);
2045 if ($langcode === '') {
2046 return '';
2047 }
2048
2049 $prefix = preg_replace('/[_-].*$/', '', $langcode);
2050 $prefix = strtolower((string) $prefix);
2051 return preg_replace('/[^a-z]/', '', $prefix);
2052 }
2053
2061 private static function getBestProductTranslation($multilangs, $langcode)
2062 {
2063 $langcode = trim((string) $langcode);
2064 if ($langcode === '' || !is_array($multilangs) || empty($multilangs)) {
2065 return array('label' => '', 'description' => '');
2066 }
2067
2068 $prefix = self::getLangPrefix($langcode);
2069 $candidates = array($langcode);
2070 if ($prefix !== '' && $prefix !== $langcode) {
2071 $candidates[] = $prefix;
2072 }
2073
2074 foreach ($candidates as $candidate) {
2075 if (empty($multilangs[$candidate]) || !is_array($multilangs[$candidate])) {
2076 continue;
2077 }
2078 $label = trim((string) (isset($multilangs[$candidate]['label']) ? $multilangs[$candidate]['label'] : ''));
2079 $description = trim((string) (isset($multilangs[$candidate]['description']) ? $multilangs[$candidate]['description'] : ''));
2080 if ($label !== '' || $description !== '') {
2081 return array('label' => $label, 'description' => $description);
2082 }
2083 }
2084
2085 if ($prefix !== '') {
2086 foreach ($multilangs as $code => $row) {
2087 if (!is_array($row)) {
2088 continue;
2089 }
2090 if (!(strpos($code, $prefix.'_') === 0 || strpos($code, $prefix.'-') === 0)) {
2091 continue;
2092 }
2093 $label = trim((string) (isset($row['label']) ? $row['label'] : ''));
2094 $description = trim((string) (isset($row['description']) ? $row['description'] : ''));
2095 if ($label !== '' || $description !== '') {
2096 return array('label' => $label, 'description' => $description);
2097 }
2098 }
2099 }
2100
2101 return array('label' => '', 'description' => '');
2102 }
2103
2111 public function setSubstitFromObject($object, $outputlangs)
2112 {
2113 global $extrafields;
2114
2115 $parameters = array();
2116 $tmparray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
2117 complete_substitutions_array($tmparray, $outputlangs, $object, $parameters);
2118
2119 $this->substit = $tmparray;
2120 $targetLang = '';
2121 if (is_object($outputlangs) && !empty($outputlangs->defaultlang)) {
2122 $targetLang = trim((string) $outputlangs->defaultlang);
2123 }
2124
2125 // Fill substit_lines with each object lines content
2126 if (is_array($object->lines)) {
2127 foreach ($object->lines as $line) {
2128 $substit_line = array(
2129 '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '',
2130 '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '',
2131 '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '',
2132 '__LABEL__' => isset($line->label) ? $line->label : '',
2133 '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '',
2134 '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', false, $outputlangs),
2135 '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', false, $outputlangs),
2136 '__QUANTITY__' => $line->qty,
2137 '__SUBPRICE__' => price($line->subprice),
2138 '__AMOUNT__' => price($line->total_ttc),
2139 '__AMOUNT_EXCL_TAX__' => price($line->total_ht)
2140 );
2141
2142 // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__
2143 if (!empty($line->fk_product)) {
2144 if (!is_object($extrafields)) {
2145 $extrafields = new ExtraFields($this->db);
2146 }
2147 $product = new Product($this->db);
2148 $product->fetch($line->fk_product, '', '', '1');
2149 $product->fetch_optionals();
2150
2151 if (getDolGlobalInt('MAIN_MULTILANGS') && $targetLang !== '' && !empty($product->multilangs) && is_array($product->multilangs)) {
2152 $translated = self::getBestProductTranslation($product->multilangs, $targetLang);
2153 $translatedLabel = trim((string) (isset($translated['label']) ? $translated['label'] : ''));
2154 $translatedDescription = trim((string) (isset($translated['description']) ? $translated['description'] : ''));
2155
2156 $currentLabelNorm = self::normalizeTextForComparison($substit_line['__PRODUCT_LABEL__']);
2157 $currentProductDescriptionNorm = self::normalizeTextForComparison($substit_line['__PRODUCT_DESCRIPTION__']);
2158 $currentLineDescriptionNorm = self::normalizeTextForComparison($substit_line['__DESCRIPTION__']);
2159 $productLabelNorm = self::normalizeTextForComparison($product->label);
2160 $productDescriptionNorm = self::normalizeTextForComparison($product->description);
2161
2162 if ($translatedLabel !== '' && ($currentLabelNorm === '' || $currentLabelNorm === $productLabelNorm)) {
2163 $substit_line['__PRODUCT_LABEL__'] = $translatedLabel;
2164 }
2165 if ($translatedDescription !== '' && ($currentProductDescriptionNorm === '' || $currentProductDescriptionNorm === $productDescriptionNorm)) {
2166 $substit_line['__PRODUCT_DESCRIPTION__'] = $translatedDescription;
2167 }
2168 if ($translatedDescription !== '' && ($currentLineDescriptionNorm === '' || $currentLineDescriptionNorm === $productDescriptionNorm || $currentLineDescriptionNorm === $currentProductDescriptionNorm)) {
2169 $substit_line['__DESCRIPTION__'] = $translatedDescription;
2170 }
2171 }
2172
2173 $extrafields->fetch_name_optionals_label($product->table_element, true);
2174
2175 if (!empty($extrafields->attributes[$product->table_element]['label']) && is_array($extrafields->attributes[$product->table_element]['label']) && count($extrafields->attributes[$product->table_element]['label']) > 0) {
2176 foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
2177 $substit_line['__PRODUCT_EXTRAFIELD_'.strtoupper($key).'__'] = isset($product->array_options['options_'.$key]) ? $product->array_options['options_'.$key] : '';
2178 }
2179 }
2180 }
2181
2182 $this->substit_lines[$line->id] = $substit_line; // @phan-suppress-current-line PhanTypeMismatchProperty
2183 }
2184 }
2185 }
2186
2194 public static function getAvailableSubstitKey($mode = 'formemail', $object = null)
2195 {
2196 global $langs;
2197
2198 $tmparray = array();
2199 if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines') {
2200 $parameters = array('mode' => $mode);
2201 $tmparray = getCommonSubstitutionArray($langs, 2, null, $object); // Note: On email template creation, this may be null because it is related to all type of objects
2202 complete_substitutions_array($tmparray, $langs, null, $parameters);
2203
2204 if ($mode == 'formemailwithlines') {
2205 $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function
2206 }
2207 if ($mode == 'formemailforlines') {
2208 $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function
2209 }
2210 }
2211
2212 if ($mode == 'emailing') {
2213 $parameters = array('mode' => $mode);
2214 $tmparray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount'), $object); // Note: On email template creation, this may be null because it is related to all type of objects
2215 complete_substitutions_array($tmparray, $langs, null, $parameters);
2216
2217 // For mass emailing, we have different keys specific to the data into tagerts list
2218 $tmparray['__ID__'] = 'IdRecord';
2219 $tmparray['__EMAIL__'] = 'EMailRecipient';
2220 $tmparray['__LASTNAME__'] = 'Lastname';
2221 $tmparray['__FIRSTNAME__'] = 'Firstname';
2222 $tmparray['__MAILTOEMAIL__'] = 'TagMailtoEmail';
2223 $tmparray['__OTHER1__'] = 'Other1';
2224 $tmparray['__OTHER2__'] = 'Other2';
2225 $tmparray['__OTHER3__'] = 'Other3';
2226 $tmparray['__OTHER4__'] = 'Other4';
2227 $tmparray['__OTHER5__'] = 'Other5';
2228
2229 $tmparray['__THIRDPARTY_CUSTOMER_CODE__'] = 'CustomerCode'; // If source is a thirdparty
2230
2231 $tmparray['__CHECK_READ__'] = $langs->trans('TagCheckMail');
2232 $tmparray['__UNSUBSCRIBE__'] = $langs->trans('TagUnsubscribe');
2233 $tmparray['__UNSUBSCRIBE_URL__'] = $langs->trans('TagUnsubscribe').' (URL)';
2234
2235 $onlinepaymentenabled = 0;
2236 if (isModEnabled('paypal')) {
2237 $onlinepaymentenabled++;
2238 }
2239 if (isModEnabled('stripe')) {
2240 $onlinepaymentenabled++;
2241 }
2242 if ($onlinepaymentenabled && getDolGlobalString('PAYMENT_SECURITY_TOKEN')) {
2243 $tmparray['__SECUREKEYPAYMENT__'] = getDolGlobalString('PAYMENT_SECURITY_TOKEN');
2244 if (isModEnabled('member')) {
2245 $tmparray['__SECUREKEYPAYMENT_MEMBER__'] = 'SecureKeyPAYMENTUniquePerMember';
2246 }
2247 if (isModEnabled('don')) {
2248 $tmparray['__SECUREKEYPAYMENT_DONATION__'] = 'SecureKeyPAYMENTUniquePerDonation';
2249 }
2250 if (isModEnabled('invoice')) {
2251 $tmparray['__SECUREKEYPAYMENT_INVOICE__'] = 'SecureKeyPAYMENTUniquePerInvoice';
2252 }
2253 if (isModEnabled('order')) {
2254 $tmparray['__SECUREKEYPAYMENT_ORDER__'] = 'SecureKeyPAYMENTUniquePerOrder';
2255 }
2256 if (isModEnabled('contract')) {
2257 $tmparray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'SecureKeyPAYMENTUniquePerContractLine';
2258 }
2259
2260 //Online payment link
2261 if (isModEnabled('member')) {
2262 $tmparray['__ONLINEPAYMENTLINK_MEMBER__'] = 'OnlinePaymentLinkUniquePerMember';
2263 }
2264 if (isModEnabled('don')) {
2265 $tmparray['__ONLINEPAYMENTLINK_DONATION__'] = 'OnlinePaymentLinkUniquePerDonation';
2266 }
2267 if (isModEnabled('invoice')) {
2268 $tmparray['__ONLINEPAYMENTLINK_INVOICE__'] = 'OnlinePaymentLinkUniquePerInvoice';
2269 }
2270 if (isModEnabled('order')) {
2271 $tmparray['__ONLINEPAYMENTLINK_ORDER__'] = 'OnlinePaymentLinkUniquePerOrder';
2272 }
2273 if (isModEnabled('contract')) {
2274 $tmparray['__ONLINEPAYMENTLINK_CONTRACTLINE__'] = 'OnlinePaymentLinkUniquePerContractLine';
2275 }
2276 } else {
2277 /* No need to show into tooltip help, option is not enabled
2278 $vars['__SECUREKEYPAYMENT__']='';
2279 $vars['__SECUREKEYPAYMENT_MEMBER__']='';
2280 $vars['__SECUREKEYPAYMENT_INVOICE__']='';
2281 $vars['__SECUREKEYPAYMENT_ORDER__']='';
2282 $vars['__SECUREKEYPAYMENT_CONTRACTLINE__']='';
2283 */
2284 }
2285 if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) {
2286 $tmparray['__PUBLICLINK_NEWMEMBERFORM__'] = 'BlankSubscriptionForm';
2287 }
2288 }
2289
2290 foreach ($tmparray as $key => $val) {
2291 if (empty($val)) {
2292 $tmparray[$key] = $key;
2293 }
2294 }
2295
2296 return $tmparray;
2297 }
2298}
print $object position
Definition edit.php:206
Class to manage a WYSIWYG editor.
Class to generate HTML forms for single email Usage: $formai = new FormAI($db) $formai->proprietes=1 ...
Class to generate html code for admin pages.
Class to offer components to list and upload files.
Class to manage generation of HTML components Only common components must be here.
static selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='minwidth75', $addjscombo=1, $moreparamonempty='', $disablebademail=0, $nohtmlescape=0)
Return a HTML select string, built from an array of key+value.
Class to manage a HTML form to send a unitary email Usage: $formail = new FormMail($db) $formmail->pr...
get_attached_files()
Return list of attached files (stored in SECTION array)
getHtmlForWithErrorsTo()
get Html For WithErrorsTo
getHtmlForTopic($arraydefaultmessage, $helpforsubstitution)
Return Html section for the Topic of message.
clear_attached_files()
Clear list of attached files in send mail form (also stored in session)
fetchAllEMailTemplate($type_template, $user, $outputlangs, $active=1)
Find if template exists and are available for current user, then set them into $this->lines_model.
getHtmlForCc()
get html For CC
getHtmlForTo()
get html For To
add_attached_files($path, $file='', $type='')
Add a file into the list of attached files (stored in SECTION array)
getHtmlForWithCcc()
get html For WithCCC This information is show when MAIN_EMAIL_USECCC is set.
remove_attached_files($keytodelete)
Remove a file from the list of attached files (stored in SECTION array)
__construct($db)
Constructor.
getHtmlForDeliveryreceipt()
get Html For Asking for Delivery Receipt
getEMailTemplate($dbs, $type_template, $user, $outputlangs, $id=0, $active=1, $label='', $defaultfortype=-1)
Return templates of email with type = $type_template or type = 'all'.
show_form($addfileaction='addfile', $removefileaction='removefile')
Show the form to input an email this->withfile: 0=No attaches files, 1=Show attached files,...
get_form($addfileaction='addfile', $removefileaction='removefile')
Get the form to input an email this->withfile: 0=No attaches files, 1=Show attached files,...
Class to manage products or services.
Class to manage translations.
print $script_file $mode $langs defaultlang(is_numeric($duration_value) ? " delay=". $duration_value :"").(is_numeric($duration_value2) ? " after cd cd cd description as p label as s rowid as s nom as s email
Sender: Who sends the email ("Sender" has sent emails on behalf of "From").
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0, $indexdatabase=1, $nolog=0, $level=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories)
setEventMessages($mesg, $mesgs, $style='mesgs', $messagekey='', $noduplicate=0, $attop=0)
Set event messages in dol_events session object.
picto_from_langcode($codelang, $moreatt='', $notitlealt=0)
Return img flag of country for a language code or country code.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return MIME type of a file from its name with extension.
dolGetFirstLineOfText($text, $nboflines=1, $charset='UTF-8')
Return first line of text.
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0, $removedoublespaces=1)
Clean a string from all HTML tags and entities.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
GETPOST($paramname, $check='alphanohtml', $method=0, $filter=null, $options=null, $noreplace=0, $nodefault=0)
Return value of a param into GET or POST supervariable.
dol_htmlentities($string, $flags=ENT_QUOTES|ENT_SUBSTITUTE, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
make_substitutions($text, $substitutionarray, $outputlangs=null, $converttextinhtmlifnecessary=0)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_textishtml($msg, $option=0)
Return if a text is a html content.
GETPOSTINT($paramname, $method=0, $nodefault=0)
Return the value of a $_GET or $_POST supervariable, converted into integer.
getDolGlobalBool($key, $default=false)
Return a Dolibarr global constant boolean value.
dol_print_error($db=null, $error='', $errors=null)
Displays error message system with all the information to facilitate the diagnosis and the escalation...
GETPOSTISSET($paramname)
Return true if we are in a context of submitting the parameter $paramname from a POST of a form.
getDolGlobalString($key, $default='')
Return a Dolibarr global constant string value.
isModEnabled($module)
Is Dolibarr module enabled.
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='hideonsmartphone', $textfordropdown='', $picto='', $textonpictotooltip='', $cssfordropdown='info_admin')
Show information in HTML for admin users or standard users.
getEntity($element, $shared=1, $currentobject=null)
Get list of entity id to use.
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0, $noescapetags='', $escapeonlyhtmltags=0, $cleanalsojavascript=0)
Returns text escaped for inclusion in HTML alt or title or value tags, or into values of HTML input f...
multi select button
0 = Do not include form tag and submit button -1 = Do not include form tag but include submit button
editval_textarea active
print $langs trans("Show") . '< td style="' . $timeColor . '" align="center"> s</td > badge status0 badge status4 badge status3 Error badge status8< td align="center">< span class="badge ' . $badge . '"></span ></td >< td align="center">< a href="#" class="button button-small" onclick="openLogModal(this)" data-req="' . dol_escape_htmltag($reqSafe) . '" data-res="' . dol_escape_htmltag($resSafe) . '" data-err="' . dol_escape_htmltag($errSafe) . '">< span class="fa fa-search-plus"></span ></a ></td ></tr >< tr >< td colspan="' . $colspan . '" class="opacitymedium"></td ></tr ></table ></div ></form > logModal none logModal none s a JSON string
buildzip.php
getMaxFileSizeArray()
Return the max allowed for file upload.