html.formmail.class.php 68 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768
  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-2022 Frédéric France <frederic.france@netlogic.fr>
  8. * Copyright (C) 2022 Charlene Benke <charlene@patas-monkey.com>
  9. * Copyright (C) 2023 Anthony Berton <anthony.berton@bb2a.fr>
  10. *
  11. *
  12. * This program is free software; you can redistribute it and/or modify
  13. * it under the terms of the GNU General Public License as published by
  14. * the Free Software Foundation; either version 3 of the License, or
  15. * (at your option) any later version.
  16. *
  17. * This program is distributed in the hope that it will be useful,
  18. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  19. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  20. * GNU General Public License for more details.
  21. *
  22. * You should have received a copy of the GNU General Public License
  23. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  24. */
  25. /**
  26. * \file htdocs/core/class/html.formmail.class.php
  27. * \ingroup core
  28. * \brief Fichier de la classe permettant la generation du formulaire html d'envoi de mail unitaire
  29. */
  30. require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php';
  31. /**
  32. * Classe permettant la generation du formulaire html d'envoi de mail unitaire
  33. * Usage: $formail = new FormMail($db)
  34. * $formmail->proprietes=1 ou chaine ou tableau de valeurs
  35. * $formmail->show_form() affiche le formulaire
  36. */
  37. class FormMail extends Form
  38. {
  39. /**
  40. * @var DoliDB Database handler.
  41. */
  42. public $db;
  43. /**
  44. * @var int 1 = Include HTML form tag and show submit button
  45. * 0 = Do not include form tag and submit button
  46. * -1 = Do not include form tag but include submit button
  47. */
  48. public $withform;
  49. /**
  50. * @var string name from
  51. */
  52. public $fromname;
  53. /**
  54. * @var string email from
  55. */
  56. public $frommail;
  57. /**
  58. * @var string user, company, robot
  59. */
  60. public $fromtype;
  61. /**
  62. * @var int from ID
  63. */
  64. public $fromid;
  65. /**
  66. * @var int also from robot
  67. */
  68. public $fromalsorobot;
  69. /**
  70. * @var string thirdparty etc
  71. */
  72. public $totype;
  73. /**
  74. * @var int ID
  75. */
  76. public $toid;
  77. /**
  78. * @var string Reply-to name
  79. */
  80. public $replytoname;
  81. /**
  82. * @var string replyto email
  83. */
  84. public $replytomail;
  85. /**
  86. * @var string To name
  87. */
  88. public $toname;
  89. /**
  90. * @var string To email
  91. */
  92. public $tomail;
  93. /**
  94. * @var string Track id
  95. */
  96. public $trackid;
  97. /**
  98. * @var string If you know a MSGID of an email and want to send the email in reply to it. Will be added into header as In-Reply-To: <...>
  99. */
  100. public $inreplyto;
  101. public $withsubstit; // Show substitution array
  102. public $withfrom;
  103. /**
  104. * @var int|string|array
  105. */
  106. public $withto; // Show recipient emails
  107. public $withreplyto;
  108. /**
  109. * @var int|string 0 = Do not Show free text for recipient emails
  110. * 1 = Show free text for recipient emails
  111. * or a free email
  112. */
  113. public $withtofree;
  114. public $withtocc;
  115. public $withtoccc;
  116. public $withtopic;
  117. /**
  118. * @var int 0=No attaches files, 1=Show attached files, 2=Can add new attached files
  119. */
  120. public $withfile;
  121. /**
  122. * @var int 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
  123. */
  124. public $withmaindocfile;
  125. public $withbody;
  126. public $withfromreadonly;
  127. public $withreplytoreadonly;
  128. public $withtoreadonly;
  129. public $withtoccreadonly;
  130. public $withtocccreadonly;
  131. public $withtopicreadonly;
  132. public $withfilereadonly;
  133. public $withdeliveryreceipt;
  134. public $withcancel;
  135. public $withfckeditor;
  136. public $substit = array();
  137. public $substit_lines = array();
  138. public $param = array();
  139. public $withtouser = array();
  140. public $withtoccuser = array();
  141. public $lines_model;
  142. // -1 suggest the checkbox 'one email per recipient' not checked, 0 = no suggestion, 1 = suggest and checked
  143. public $withoptiononeemailperrecipient;
  144. /**
  145. * Constructor
  146. *
  147. * @param DoliDB $db Database handler
  148. */
  149. public function __construct($db)
  150. {
  151. $this->db = $db;
  152. $this->withform = 1;
  153. $this->withfrom = 1;
  154. $this->withto = 1;
  155. $this->withtofree = 1;
  156. $this->withtocc = 1;
  157. $this->withtoccc = 0;
  158. $this->witherrorsto = 0;
  159. $this->withtopic = 1;
  160. $this->withfile = 0; // 1=Add section "Attached files". 2=Can add files.
  161. $this->withmaindocfile = 0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
  162. $this->withbody = 1;
  163. $this->withfromreadonly = 1;
  164. $this->withreplytoreadonly = 1;
  165. $this->withtoreadonly = 0;
  166. $this->withtoccreadonly = 0;
  167. $this->withtocccreadonly = 0;
  168. $this->witherrorstoreadonly = 0;
  169. $this->withtopicreadonly = 0;
  170. $this->withfilereadonly = 0;
  171. $this->withbodyreadonly = 0;
  172. $this->withdeliveryreceiptreadonly = 0;
  173. $this->withfckeditor = -1; // -1 = Auto
  174. }
  175. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  176. /**
  177. * Clear list of attached files in send mail form (also stored in session)
  178. *
  179. * @return void
  180. */
  181. public function clear_attached_files()
  182. {
  183. // phpcs:enable
  184. global $conf, $user;
  185. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  186. // Set tmp user directory
  187. $vardir = $conf->user->dir_output."/".$user->id;
  188. $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path
  189. if (is_dir($upload_dir)) {
  190. dol_delete_dir_recursive($upload_dir);
  191. }
  192. $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
  193. unset($_SESSION["listofpaths".$keytoavoidconflict]);
  194. unset($_SESSION["listofnames".$keytoavoidconflict]);
  195. unset($_SESSION["listofmimes".$keytoavoidconflict]);
  196. }
  197. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  198. /**
  199. * Add a file into the list of attached files (stored in SECTION array)
  200. *
  201. * @param string $path Full absolute path on filesystem of file, including file name
  202. * @param string $file Only filename (can be basename($path))
  203. * @param string $type Mime type (can be dol_mimetype($file))
  204. * @return void
  205. */
  206. public function add_attached_files($path, $file = '', $type = '')
  207. {
  208. // phpcs:enable
  209. $listofpaths = array();
  210. $listofnames = array();
  211. $listofmimes = array();
  212. if (empty($file)) {
  213. $file = basename($path);
  214. }
  215. if (empty($type)) {
  216. $type = dol_mimetype($file);
  217. }
  218. $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
  219. if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
  220. $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
  221. }
  222. if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
  223. $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
  224. }
  225. if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
  226. $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
  227. }
  228. if (!in_array($file, $listofnames)) {
  229. $listofpaths[] = $path;
  230. $listofnames[] = $file;
  231. $listofmimes[] = $type;
  232. $_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
  233. $_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
  234. $_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
  235. }
  236. }
  237. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  238. /**
  239. * Remove a file from the list of attached files (stored in SECTION array)
  240. *
  241. * @param string $keytodelete Key index in file array (0, 1, 2, ...)
  242. * @return void
  243. */
  244. public function remove_attached_files($keytodelete)
  245. {
  246. // phpcs:enable
  247. $listofpaths = array();
  248. $listofnames = array();
  249. $listofmimes = array();
  250. $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
  251. if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
  252. $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
  253. }
  254. if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
  255. $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
  256. }
  257. if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
  258. $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
  259. }
  260. if ($keytodelete >= 0) {
  261. unset($listofpaths[$keytodelete]);
  262. unset($listofnames[$keytodelete]);
  263. unset($listofmimes[$keytodelete]);
  264. $_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
  265. $_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
  266. $_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
  267. //var_dump($_SESSION['listofpaths']);
  268. }
  269. }
  270. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  271. /**
  272. * Return list of attached files (stored in SECTION array)
  273. *
  274. * @return array array('paths'=> ,'names'=>, 'mimes'=> )
  275. */
  276. public function get_attached_files()
  277. {
  278. // phpcs:enable
  279. $listofpaths = array();
  280. $listofnames = array();
  281. $listofmimes = array();
  282. $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
  283. if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
  284. $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
  285. }
  286. if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
  287. $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
  288. }
  289. if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
  290. $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
  291. }
  292. return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes);
  293. }
  294. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  295. /**
  296. * Show the form to input an email
  297. * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
  298. * this->withmaindocfile
  299. *
  300. * @param string $addfileaction Name of action when posting file attachments
  301. * @param string $removefileaction Name of action when removing file attachments
  302. * @return void
  303. * @deprecated
  304. */
  305. public function show_form($addfileaction = 'addfile', $removefileaction = 'removefile')
  306. {
  307. // phpcs:enable
  308. print $this->get_form($addfileaction, $removefileaction);
  309. }
  310. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  311. /**
  312. * Get the form to input an email
  313. * this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
  314. * this->param: Contains more parameters like email templates info
  315. * this->withfckeditor: 1=We use an advanced editor, so we switch content into HTML
  316. *
  317. * @param string $addfileaction Name of action when posting file attachments
  318. * @param string $removefileaction Name of action when removing file attachments
  319. * @return string Form to show
  320. */
  321. public function get_form($addfileaction = 'addfile', $removefileaction = 'removefile')
  322. {
  323. // phpcs:enable
  324. global $conf, $langs, $user, $hookmanager, $form;
  325. // Required to show preview wof mail attachments
  326. require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
  327. $formfile = new Formfile($this->db);
  328. if (!is_object($form)) {
  329. $form = new Form($this->db);
  330. }
  331. // Load translation files required by the page
  332. $langs->loadLangs(array('other', 'mails', 'members'));
  333. // Clear temp files. Must be done before call of triggers, at beginning (mode = init), or when we select a new template
  334. if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelselected') && GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
  335. $this->clear_attached_files();
  336. }
  337. // Call hook getFormMail
  338. $hookmanager->initHooks(array('formmail'));
  339. $parameters = array(
  340. 'addfileaction' => $addfileaction,
  341. 'removefileaction'=> $removefileaction,
  342. 'trackid'=> $this->trackid
  343. );
  344. $reshook = $hookmanager->executeHooks('getFormMail', $parameters, $this);
  345. if (!empty($reshook)) {
  346. return $hookmanager->resPrint;
  347. } else {
  348. $out = '';
  349. $disablebademails = 1;
  350. // Define output language
  351. $outputlangs = $langs;
  352. $newlang = '';
  353. if (getDolGlobalInt('MAIN_MULTILANGS') && !empty($this->param['langsmodels'])) {
  354. $newlang = $this->param['langsmodels'];
  355. }
  356. if (!empty($newlang)) {
  357. $outputlangs = new Translate("", $conf);
  358. $outputlangs->setDefaultLang($newlang);
  359. $outputlangs->load('other');
  360. }
  361. // Get message template for $this->param["models"] into c_email_templates
  362. $arraydefaultmessage = -1;
  363. if ($this->param['models'] != 'none') {
  364. $model_id = 0;
  365. if (array_key_exists('models_id', $this->param)) {
  366. $model_id = $this->param["models_id"];
  367. }
  368. $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
  369. }
  370. // Define list of attached files
  371. $listofpaths = array();
  372. $listofnames = array();
  373. $listofmimes = array();
  374. $keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
  375. if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelselected') && GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
  376. if (!empty($arraydefaultmessage->joinfiles) && !empty($this->param['fileinit']) && is_array($this->param['fileinit'])) {
  377. foreach ($this->param['fileinit'] as $file) {
  378. if (!empty($file)) {
  379. $this->add_attached_files($file, basename($file), dol_mimetype($file));
  380. }
  381. }
  382. }
  383. }
  384. if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
  385. $listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
  386. }
  387. if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
  388. $listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
  389. }
  390. if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
  391. $listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
  392. }
  393. $out .= "\n".'<!-- Begin form mail type='.$this->param["models"].' --><div id="mailformdiv"></div>'."\n";
  394. if ($this->withform == 1) {
  395. $out .= '<form method="POST" name="mailform" id="mailform" enctype="multipart/form-data" action="'.$this->param["returnurl"].'#formmail">'."\n";
  396. $out .= '<a id="formmail" name="formmail"></a>';
  397. $out .= '<input style="display:none" type="submit" id="sendmailhidden" name="sendmail">';
  398. $out .= '<input type="hidden" name="token" value="'.newToken().'" />';
  399. $out .= '<input type="hidden" name="trackid" value="'.$this->trackid.'" />';
  400. $out .= '<input type="hidden" name="inreplyto" value="'.$this->inreplyto.'" />';
  401. }
  402. if (!empty($this->withfrom)) {
  403. if (!empty($this->withfromreadonly)) {
  404. $out .= '<input type="hidden" id="fromname" name="fromname" value="'.$this->fromname.'" />';
  405. $out .= '<input type="hidden" id="frommail" name="frommail" value="'.$this->frommail.'" />';
  406. }
  407. }
  408. foreach ($this->param as $key => $value) {
  409. if (is_array($value)) {
  410. $out .= "<!-- param key=".$key." is array, we do not output input field for it -->\n";
  411. } else {
  412. $out .= '<input type="hidden" id="'.$key.'" name="'.$key.'" value="'.$value.'" />'."\n";
  413. }
  414. }
  415. $modelmail_array = array();
  416. if ($this->param['models'] != 'none') {
  417. $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
  418. if ($result < 0) {
  419. setEventMessages($this->error, $this->errors, 'errors');
  420. }
  421. foreach ($this->lines_model as $line) {
  422. $reg = array();
  423. if (preg_match('/\((.*)\)/', $line->label, $reg)) {
  424. $labeltouse = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__
  425. } else {
  426. $labeltouse = $line->label;
  427. }
  428. // We escape the $labeltouse to store it into $modelmail_array.
  429. $modelmail_array[$line->id] = dol_escape_htmltag($labeltouse);
  430. if ($line->lang) {
  431. $modelmail_array[$line->id] .= ' '.picto_from_langcode($line->lang);
  432. }
  433. if ($line->private) {
  434. $modelmail_array[$line->id] .= ' - <span class="opacitymedium">'.dol_escape_htmltag($langs->trans("Private")).'</span>';
  435. }
  436. }
  437. }
  438. // Zone to select email template
  439. if (count($modelmail_array) > 0) {
  440. $model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ($arraydefaultmessage->id > 0 ? $arraydefaultmessage->id : 0);
  441. // If list of template is filled
  442. $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
  443. $out .= '<span class="opacitymedium">'.$langs->trans('SelectMailModel').':</span> ';
  444. $out .= $this->selectarray('modelmailselected', $modelmail_array, $model_mail_selected_id, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100', 1, '', 0, 1);
  445. if ($user->admin) {
  446. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
  447. }
  448. $out .= ' &nbsp; ';
  449. $out .= '<input type="submit" class="button reposition smallpaddingimp" value="'.$langs->trans('Apply').'" name="modelselected" id="modelselected">';
  450. $out .= ' &nbsp; ';
  451. $out .= '</div>';
  452. } elseif (!empty($this->param['models']) && in_array($this->param['models'], array(
  453. 'propal_send', 'order_send', 'facture_send',
  454. 'shipping_send', 'fichinter_send', 'supplier_proposal_send', 'order_supplier_send',
  455. 'invoice_supplier_send', 'thirdparty', 'contract', 'user', 'recruitmentcandidature_send', 'all'
  456. ))) {
  457. // If list of template is empty
  458. $out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
  459. $out .= '<span class="opacitymedium">'.$langs->trans('SelectMailModel').':</span> ';
  460. $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.
  461. if ($user->admin) {
  462. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
  463. }
  464. $out .= ' &nbsp; ';
  465. $out .= '<input type="submit" class="button" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
  466. $out .= ' &nbsp; ';
  467. $out .= '</div>';
  468. } else {
  469. $out .= '<!-- No template available for $this->param["models"] = '.$this->param['models'].' -->';
  470. }
  471. $out .= '<table class="tableforemailform boxtablenotop centpercent">'."\n";
  472. // Substitution array/string
  473. $helpforsubstitution = '';
  474. if (is_array($this->substit) && count($this->substit)) {
  475. $helpforsubstitution .= $langs->trans('AvailableVariables').' :<br><br><span class="small">'."\n";
  476. }
  477. foreach ($this->substit as $key => $val) {
  478. // Do not show deprecated variables into the tooltip help of substitution variables
  479. if (in_array($key, array('__NEWREF__', '__REFCLIENT__', '__REFSUPPLIER__', '__SUPPLIER_ORDER_DATE_DELIVERY__', '__SUPPLIER_ORDER_DELAY_DELIVERY__'))) {
  480. continue;
  481. }
  482. $helpforsubstitution .= $key.' -> '.$langs->trans(dol_string_nohtmltag(dolGetFirstLineOfText($val))).'<br>';
  483. }
  484. if (is_array($this->substit) && count($this->substit)) {
  485. $helpforsubstitution .= '</span>';
  486. }
  487. if (!empty($this->withsubstit)) { // Unset or set ->withsubstit=0 to disable this.
  488. $out .= '<tr><td colspan="2" class="right">';
  489. if (is_numeric($this->withsubstit)) {
  490. $out .= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage
  491. } else {
  492. $out .= $form->textwithpicto($langs->trans('AvailableVariables'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // New usage
  493. }
  494. $out .= "</td></tr>\n";
  495. }
  496. // From
  497. if (!empty($this->withfrom)) {
  498. if (!empty($this->withfromreadonly)) {
  499. $out .= '<tr><td class="fieldrequired minwidth200">'.$langs->trans("MailFrom").'</td><td>';
  500. // $this->fromtype is the default value to use to select sender
  501. if (!($this->fromtype === 'user' && $this->fromid > 0)
  502. && !($this->fromtype === 'company')
  503. && !($this->fromtype === 'robot')
  504. && !preg_match('/user_aliases/', $this->fromtype)
  505. && !preg_match('/global_aliases/', $this->fromtype)
  506. && !preg_match('/senderprofile/', $this->fromtype)
  507. ) {
  508. // Use this->fromname and this->frommail or error if not defined
  509. $out .= $this->fromname;
  510. if ($this->frommail) {
  511. $out .= ' &lt;'.$this->frommail.'&gt;';
  512. } else {
  513. if ($this->fromtype) {
  514. $langs->load('errors');
  515. $out .= '<span class="warning"> &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt; </span>';
  516. }
  517. }
  518. } else {
  519. $liste = array();
  520. // Add user email
  521. if (empty($user->email)) {
  522. $langs->load('errors');
  523. $s = $user->getFullName($langs).' &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt;';
  524. } else {
  525. $s = $user->getFullName($langs).' &lt;'.$user->email.'&gt;';
  526. }
  527. $liste['user'] = array('label' => $s, 'data-html' => $s);
  528. // Add also company main email
  529. if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) {
  530. $s = (empty($conf->global->MAIN_INFO_SOCIETE_NOM)?$conf->global->MAIN_INFO_SOCIETE_EMAIL:$conf->global->MAIN_INFO_SOCIETE_NOM).' &lt;'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'&gt;';
  531. $liste['company'] = array('label' => $s, 'data-html' => $s);
  532. }
  533. // Add also email aliases if there is some
  534. $listaliases = array(
  535. 'user_aliases' => (empty($user->email_aliases) ? '' : $user->email_aliases),
  536. 'global_aliases' => getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'),
  537. );
  538. // Also add robot email
  539. if (!empty($this->fromalsorobot)) {
  540. if (!empty($conf->global->MAIN_MAIL_EMAIL_FROM) && getDolGlobalString('MAIN_MAIL_EMAIL_FROM') != getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
  541. $s = $conf->global->MAIN_MAIL_EMAIL_FROM;
  542. if ($this->frommail) {
  543. $s .= ' &lt;'.$conf->global->MAIN_MAIL_EMAIL_FROM.'&gt;';
  544. }
  545. array('label' => $s, 'data-html' => $s);
  546. }
  547. }
  548. // Add also email aliases from the c_email_senderprofile table
  549. $sql = "SELECT rowid, label, email FROM ".$this->db->prefix()."c_email_senderprofile";
  550. $sql .= " WHERE active = 1 AND (private = 0 OR private = ".((int) $user->id).")";
  551. $sql .= " ORDER BY position";
  552. $resql = $this->db->query($sql);
  553. if ($resql) {
  554. $num = $this->db->num_rows($resql);
  555. $i = 0;
  556. while ($i < $num) {
  557. $obj = $this->db->fetch_object($resql);
  558. if ($obj) {
  559. $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>';
  560. }
  561. $i++;
  562. }
  563. } else {
  564. dol_print_error($this->db);
  565. }
  566. foreach ($listaliases as $typealias => $listalias) {
  567. $posalias = 0;
  568. $listaliasarray = explode(',', $listalias);
  569. foreach ($listaliasarray as $listaliasval) {
  570. $posalias++;
  571. $listaliasval = trim($listaliasval);
  572. if ($listaliasval) {
  573. $listaliasval = preg_replace('/</', '&lt;', $listaliasval);
  574. $listaliasval = preg_replace('/>/', '&gt;', $listaliasval);
  575. if (!preg_match('/&lt;/', $listaliasval)) {
  576. $listaliasval = '&lt;'.$listaliasval.'&gt;';
  577. }
  578. $liste[$typealias.'_'.$posalias] = array('label' => $listaliasval, 'data-html' => $listaliasval);
  579. }
  580. }
  581. }
  582. // Using combo here make the '<email>' no more visible on list.
  583. //$out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 1, '', $disablebademails);
  584. $out .= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 0, '', $disablebademails);
  585. }
  586. $out .= "</td></tr>\n";
  587. } else {
  588. $out .= '<tr><td class="fieldrequired width200">'.$langs->trans("MailFrom")."</td><td>";
  589. $out .= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" class="maxwidth200onsmartphone" value="'.$this->fromname.'" />';
  590. $out .= '&nbsp; &nbsp; ';
  591. $out .= $langs->trans("EMail").':&lt;<input type="text" id="frommail" name="frommail" class="maxwidth200onsmartphone" value="'.$this->frommail.'" />&gt;';
  592. $out .= "</td></tr>\n";
  593. }
  594. }
  595. // To
  596. if (!empty($this->withto) || is_array($this->withto)) {
  597. $out .= $this->getHtmlForTo();
  598. }
  599. // To User
  600. if (!empty($this->withtouser) && is_array($this->withtouser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
  601. $out .= '<tr><td>';
  602. $out .= $langs->trans("MailToUsers");
  603. $out .= '</td><td>';
  604. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  605. $tmparray = $this->withtouser;
  606. foreach ($tmparray as $key => $val) {
  607. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  608. }
  609. $withtoselected = GETPOST("receiveruser", 'array'); // Array of selected value
  610. if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
  611. $withtoselected = array_keys($tmparray);
  612. }
  613. $out .= $form->multiselectarray("receiveruser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
  614. $out .= "</td></tr>\n";
  615. }
  616. // With option for one email per recipient
  617. if (!empty($this->withoptiononeemailperrecipient)) {
  618. if (abs($this->withoptiononeemailperrecipient) == 1) {
  619. $out .= '<tr><td class="minwidth200">';
  620. $out .= $langs->trans("GroupEmails");
  621. $out .= '</td><td>';
  622. $out .= ' <input type="checkbox" id="oneemailperrecipient" value="1" name="oneemailperrecipient"'.($this->withoptiononeemailperrecipient > 0 ? ' checked="checked"' : '').'> ';
  623. $out .= '<label for="oneemailperrecipient">';
  624. $out .= $form->textwithpicto($langs->trans("OneEmailPerRecipient"), $langs->trans("WarningIfYouCheckOneRecipientPerEmail"), 1, 'help');
  625. $out .= '</label>';
  626. //$out .= '<span class="hideonsmartphone opacitymedium">';
  627. //$out .= ' - ';
  628. //$out .= $langs->trans("WarningIfYouCheckOneRecipientPerEmail");
  629. //$out .= '</span>';
  630. if (getDolGlobalString('MASS_ACTION_EMAIL_ON_DIFFERENT_THIRPARTIES_ADD_CUSTOM_EMAIL')) {
  631. if (!empty($this->withto) && !is_array($this->withto)) {
  632. $out .= ' '.$langs->trans("or").' <input type="email" name="emailto" value="">';
  633. }
  634. }
  635. $out .= '</td></tr>';
  636. } else {
  637. $out .= '<tr><td><input type="hidden" name="oneemailperrecipient" value="1"></td><td></td></tr>';
  638. }
  639. }
  640. // CC
  641. if (!empty($this->withtocc) || is_array($this->withtocc)) {
  642. $out .= $this->getHtmlForCc();
  643. }
  644. // To User cc
  645. if (!empty($this->withtoccuser) && is_array($this->withtoccuser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
  646. $out .= '<tr><td>';
  647. $out .= $langs->trans("MailToCCUsers");
  648. $out .= '</td><td>';
  649. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  650. $tmparray = $this->withtoccuser;
  651. foreach ($tmparray as $key => $val) {
  652. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  653. }
  654. $withtoselected = GETPOST("receiverccuser", 'array'); // Array of selected value
  655. if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
  656. $withtoselected = array_keys($tmparray);
  657. }
  658. $out .= $form->multiselectarray("receiverccuser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
  659. $out .= "</td></tr>\n";
  660. }
  661. // CCC
  662. if (!empty($this->withtoccc) || is_array($this->withtoccc)) {
  663. $out .= $this->getHtmlForWithCcc();
  664. }
  665. // Replyto
  666. if (!empty($this->withreplyto)) {
  667. if ($this->withreplytoreadonly) {
  668. $out .= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
  669. $out .= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
  670. $out .= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail ? (" &lt;".$this->replytomail."&gt;") : "");
  671. $out .= "</td></tr>\n";
  672. }
  673. }
  674. // Errorsto
  675. if (!empty($this->witherrorsto)) {
  676. $out .= $this->getHtmlForWithErrorsTo();
  677. }
  678. // Ask delivery receipt
  679. if (!empty($this->withdeliveryreceipt) && getDolGlobalInt('MAIN_EMAIL_SUPPORT_ACK')) {
  680. $out .= $this->getHtmlForDeliveryReceipt();
  681. }
  682. // Topic
  683. if (!empty($this->withtopic)) {
  684. $out .= $this->getHtmlForTopic($arraydefaultmessage, $helpforsubstitution);
  685. }
  686. // Attached files
  687. if (!empty($this->withfile)) {
  688. $out .= '<tr>';
  689. $out .= '<td>'.$langs->trans("MailFile").'</td>';
  690. $out .= '<td>';
  691. if ($this->withmaindocfile) {
  692. // withmaindocfile is set to 1 or -1 to show the checkbox (-1 = checked or 1 = not checked)
  693. if (GETPOSTISSET('sendmail')) {
  694. $this->withmaindocfile = (GETPOST('addmaindocfile', 'alpha') ? -1 : 1);
  695. } elseif (is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  696. // If a template was selected, we use setup of template to define if join file checkbox is selected or not.
  697. $this->withmaindocfile = ($arraydefaultmessage->joinfiles ? -1 : 1);
  698. }
  699. }
  700. if (!empty($this->withmaindocfile)) {
  701. if ($this->withmaindocfile == 1) {
  702. $out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" />';
  703. } elseif ($this->withmaindocfile == -1) {
  704. $out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" checked="checked" />';
  705. }
  706. if (!empty($conf->global->MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND)) {
  707. $out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDocOrLastGenerated").'.</label><br>';
  708. } else {
  709. $out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDoc").'.</label><br>';
  710. }
  711. }
  712. if (is_numeric($this->withfile)) {
  713. // TODO Trick to have param removedfile containing nb of file to delete. But this does not works without javascript
  714. $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
  715. $out .= '<script nonce="'.getNonce().'" type="text/javascript">';
  716. $out .= 'jQuery(document).ready(function () {';
  717. $out .= ' jQuery(".removedfile").click(function() {';
  718. $out .= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
  719. $out .= ' });';
  720. $out .= '})';
  721. $out .= '</script>'."\n";
  722. if (count($listofpaths)) {
  723. foreach ($listofpaths as $key => $val) {
  724. $relativepathtofile = substr($val, (strlen(DOL_DATA_ROOT) - strlen($val)));
  725. if ($conf->entity > 1) {
  726. $relativepathtofile = str_replace($conf->entity.'/', '', $relativepathtofile);
  727. }
  728. // Try to extract data from full path
  729. $formfile_params = array();
  730. preg_match('#^(/)(\w+)(/)(.+)$#', $relativepathtofile, $formfile_params);
  731. $out .= '<div id="attachfile_'.$key.'">';
  732. // Preview of attachment
  733. $out .= img_mime($listofnames[$key]).' '.$listofnames[$key];
  734. $out .= $formfile->showPreview(array(), $formfile_params[2], $formfile_params[4]);
  735. if (!$this->withfilereadonly) {
  736. $out .= ' <input type="image" style="border: 0px;" src="'.DOL_URL_ROOT.'/theme/'.$conf->theme.'/img/delete.png" value="'.($key + 1).'" class="removedfile" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
  737. //$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
  738. }
  739. $out .= '<br></div>';
  740. }
  741. } elseif (empty($this->withmaindocfile)) {
  742. //$out .= '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
  743. }
  744. if ($this->withfile == 2) {
  745. $maxfilesizearray = getMaxFileSizeArray();
  746. $maxmin = $maxfilesizearray['maxmin'];
  747. if ($maxmin > 0) {
  748. $out .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
  749. }
  750. // Can add other files
  751. if (empty($conf->global->FROM_MAIL_DONT_USE_INPUT_FILE_MULTIPLE)) {
  752. $out .= '<input type="file" class="flat" id="addedfile" name="addedfile[]" value="'.$langs->trans("Upload").'" multiple />';
  753. } else {
  754. $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
  755. }
  756. $out .= ' ';
  757. $out .= '<input type="submit" class="button smallpaddingimp" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
  758. }
  759. } else {
  760. $out .= $this->withfile;
  761. }
  762. $out .= "</td></tr>\n";
  763. }
  764. // Message
  765. if (!empty($this->withbody)) {
  766. $defaultmessage = GETPOST('message', 'restricthtml');
  767. if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
  768. if ($arraydefaultmessage && $arraydefaultmessage->content) {
  769. $defaultmessage = $arraydefaultmessage->content;
  770. } elseif (!is_numeric($this->withbody)) {
  771. $defaultmessage = $this->withbody;
  772. }
  773. }
  774. // Complete substitution array with the url to make online payment
  775. $paymenturl = '';
  776. $validpaymentmethod = array();
  777. if (empty($this->substit['__REF__'])) {
  778. $paymenturl = '';
  779. } else {
  780. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  781. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  782. $langs->loadLangs(array('paypal', 'other'));
  783. $typeforonlinepayment = 'free';
  784. if ($this->param["models"] == 'order' || $this->param["models"] == 'order_send') {
  785. $typeforonlinepayment = 'order'; // TODO use detection on something else than template
  786. }
  787. if ($this->param["models"] == 'invoice' || $this->param["models"] == 'facture_send') {
  788. $typeforonlinepayment = 'invoice'; // TODO use detection on something else than template
  789. }
  790. if ($this->param["models"] == 'member') {
  791. $typeforonlinepayment = 'member'; // TODO use detection on something else than template
  792. }
  793. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']);
  794. $paymenturl = $url;
  795. $validpaymentmethod = getValidOnlinePaymentMethods('');
  796. }
  797. if (count($validpaymentmethod) > 0 && $paymenturl) {
  798. $langs->load('other');
  799. $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = str_replace('\n', "\n", $langs->transnoentities("PredefinedMailContentLink", $paymenturl));
  800. $this->substit['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  801. } else {
  802. $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
  803. $this->substit['__ONLINE_PAYMENT_URL__'] = '';
  804. }
  805. $this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'] = '';
  806. // Add lines substitution key from each line
  807. $lines = '';
  808. $defaultlines = $arraydefaultmessage->content_lines;
  809. if (isset($defaultlines)) {
  810. foreach ($this->substit_lines as $substit_line) {
  811. $lines .= make_substitutions($defaultlines, $substit_line)."\n";
  812. }
  813. }
  814. $this->substit['__LINES__'] = $lines;
  815. $defaultmessage = str_replace('\n', "\n", $defaultmessage);
  816. // Deal with format differences between message and some substitution variables (text / HTML)
  817. $atleastonecomponentishtml = 0;
  818. if (strpos($defaultmessage, '__USER_SIGNATURE__') !== false && dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
  819. $atleastonecomponentishtml++;
  820. }
  821. if (strpos($defaultmessage, '__SENDEREMAIL_SIGNATURE__') !== false && dol_textishtml($this->substit['__SENDEREMAIL_SIGNATURE__'])) {
  822. $atleastonecomponentishtml++;
  823. }
  824. if (strpos($defaultmessage, '__ONLINE_PAYMENT_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
  825. $atleastonecomponentishtml++;
  826. }
  827. if (strpos($defaultmessage, '__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'])) {
  828. $atleastonecomponentishtml++;
  829. }
  830. if (dol_textishtml($defaultmessage)) {
  831. $atleastonecomponentishtml++;
  832. }
  833. if ($atleastonecomponentishtml) {
  834. if (!dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
  835. $this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']);
  836. }
  837. if (!dol_textishtml($this->substit['__SENDEREMAIL_SIGNATURE__'])) {
  838. $this->substit['__SENDEREMAIL_SIGNATURE__'] = dol_nl2br($this->substit['__SENDEREMAIL_SIGNATURE__']);
  839. }
  840. if (!dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
  841. $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = dol_nl2br($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']);
  842. }
  843. if (!dol_textishtml($defaultmessage)) {
  844. $defaultmessage = dol_nl2br($defaultmessage);
  845. }
  846. }
  847. if (GETPOSTISSET("message") && !GETPOST('modelselected')) {
  848. $defaultmessage = GETPOST("message", "restricthtml");
  849. } else {
  850. $defaultmessage = make_substitutions($defaultmessage, $this->substit);
  851. // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
  852. $defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
  853. $defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
  854. }
  855. $out .= '<tr>';
  856. $out .= '<td colspan="2">';
  857. $out .= $form->textwithpicto($langs->trans('MailText'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfrombody');
  858. $out .= '</td>';
  859. $out .= '</tr>';
  860. $out .= '<tr>';
  861. $out .= '<td colspan="2">';
  862. if ($this->withbodyreadonly) {
  863. $out .= nl2br($defaultmessage);
  864. $out .= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />';
  865. } else {
  866. if (!isset($this->ckeditortoolbar)) {
  867. $this->ckeditortoolbar = 'dolibarr_mailings';
  868. }
  869. // Editor wysiwyg
  870. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  871. if ($this->withfckeditor == -1) {
  872. if (!empty($conf->global->FCKEDITOR_ENABLE_MAIL)) {
  873. $this->withfckeditor = 1;
  874. } else {
  875. $this->withfckeditor = 0;
  876. }
  877. }
  878. $doleditor = new DolEditor('message', $defaultmessage, '', 280, $this->ckeditortoolbar, 'In', true, true, $this->withfckeditor, 8, '95%');
  879. $out .= $doleditor->Create(1);
  880. }
  881. $out .= "</td></tr>\n";
  882. }
  883. $out .= '</table>'."\n";
  884. if ($this->withform == 1 || $this->withform == -1) {
  885. $out .= '<div class="center">';
  886. $out .= '<input type="submit" class="button button-add" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
  887. // Add a javascript test to avoid to forget to submit file before sending email
  888. if ($this->withfile == 2 && $conf->use_javascript_ajax) {
  889. $out .= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
  890. }
  891. $out .= ' />';
  892. if ($this->withcancel) {
  893. $out .= '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
  894. }
  895. $out .= '</div>'."\n";
  896. }
  897. if ($this->withform == 1) {
  898. $out .= '</form>'."\n";
  899. }
  900. // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
  901. if (!empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) {
  902. $out .= '<script nonce="'.getNonce().'" type="text/javascript">';
  903. $out .= 'jQuery(document).ready(function () {';
  904. $out .= ' $(document).on("keypress", \'#mailform\', function (e) { /* Note this is called at every key pressed ! */
  905. var code = e.keyCode || e.which;
  906. if (code == 13) {
  907. console.log("Enter was intercepted and blocked");
  908. e.preventDefault();
  909. return false;
  910. }
  911. });';
  912. $out .= ' })';
  913. $out .= '</script>';
  914. }
  915. $out .= "<!-- End form mail -->\n";
  916. return $out;
  917. }
  918. }
  919. /**
  920. * get html For To
  921. *
  922. * @return string html
  923. */
  924. public function getHtmlForTo()
  925. {
  926. global $langs, $form;
  927. $out = '<tr><td class="fieldrequired">';
  928. if ($this->withtofree) {
  929. $out .= $form->textwithpicto($langs->trans("MailTo"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
  930. } else {
  931. $out .= $langs->trans("MailTo");
  932. }
  933. $out .= '</td><td>';
  934. if ($this->withtoreadonly) {
  935. if (!empty($this->toname) && !empty($this->tomail)) {
  936. $out .= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
  937. $out .= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
  938. if ($this->totype == 'thirdparty') {
  939. $soc = new Societe($this->db);
  940. $soc->fetch($this->toid);
  941. $out .= $soc->getNomUrl(1);
  942. } elseif ($this->totype == 'contact') {
  943. $contact = new Contact($this->db);
  944. $contact->fetch($this->toid);
  945. $out .= $contact->getNomUrl(1);
  946. } else {
  947. $out .= $this->toname;
  948. }
  949. $out .= ' &lt;'.$this->tomail.'&gt;';
  950. if ($this->withtofree) {
  951. $out .= '<br>'.$langs->trans("and").' <input class="minwidth200" id="sendto" name="sendto" value="'.(!is_array($this->withto) && !is_numeric($this->withto) ? (GETPOSTISSET("sendto") ? GETPOST("sendto") : $this->withto) : "").'" />';
  952. }
  953. } else {
  954. // Note withto may be a text like 'AllRecipientSelected'
  955. $out .= (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : "";
  956. }
  957. } else {
  958. // The free input of email
  959. if (!empty($this->withtofree)) {
  960. $out .= '<input class="minwidth200" id="sendto" name="sendto" value="'.(($this->withtofree && !is_numeric($this->withtofree)) ? $this->withtofree : (!is_array($this->withto) && !is_numeric($this->withto) ? (GETPOSTISSET("sendto") ? GETPOST("sendto") : $this->withto) : "")).'" />';
  961. }
  962. // The select combo
  963. if (!empty($this->withto) && is_array($this->withto)) {
  964. if (!empty($this->withtofree)) {
  965. $out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
  966. }
  967. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  968. $tmparray = $this->withto;
  969. foreach ($tmparray as $key => $val) {
  970. $tmparray[$key] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]);
  971. $tmparray[$key] = dol_htmlentities($tmparray[$key], ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8', true);
  972. }
  973. $withtoselected = GETPOST("receiver", 'array'); // Array of selected value
  974. if (!getDolGlobalInt('MAIN_MAIL_NO_WITH_TO_SELECTED')) {
  975. if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
  976. $withtoselected = array_keys($tmparray);
  977. }
  978. }
  979. $out .= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
  980. }
  981. }
  982. $out .= "</td></tr>\n";
  983. return $out;
  984. }
  985. /**
  986. * get html For CC
  987. *
  988. * @return string html
  989. */
  990. public function getHtmlForCc()
  991. {
  992. global $langs, $form;
  993. $out = '<tr><td>';
  994. $out .= $form->textwithpicto($langs->trans("MailCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
  995. $out .= '</td><td>';
  996. if ($this->withtoccreadonly) {
  997. $out .= (!is_array($this->withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : "";
  998. } else {
  999. $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 : '')).'" />';
  1000. if (!empty($this->withtocc) && is_array($this->withtocc)) {
  1001. $out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
  1002. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  1003. $tmparray = $this->withtocc;
  1004. foreach ($tmparray as $key => $val) {
  1005. $tmparray[$key] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]);
  1006. $tmparray[$key] = dol_htmlentities($tmparray[$key], ENT_QUOTES|ENT_SUBSTITUTE, 'UTF-8', true);
  1007. }
  1008. $withtoccselected = GETPOST("receivercc", 'array'); // Array of selected value
  1009. $out .= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500', null, "");
  1010. }
  1011. }
  1012. $out .= "</td></tr>\n";
  1013. return $out;
  1014. }
  1015. /**
  1016. * get html For WithCCC
  1017. *
  1018. * @return string html
  1019. */
  1020. public function getHtmlForWithCcc()
  1021. {
  1022. global $conf, $langs, $form;
  1023. $out = '<tr><td>';
  1024. $out .= $form->textwithpicto($langs->trans("MailCCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
  1025. $out .= '</td><td>';
  1026. if (!empty($this->withtocccreadonly)) {
  1027. $out .= (!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : "";
  1028. } else {
  1029. $out .= '<input class="minwidth200" id="sendtoccc" name="sendtoccc" value="'.(GETPOSTISSET("sendtoccc") ? GETPOST("sendtoccc", "alpha") : ((!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : '')).'" />';
  1030. if (!empty($this->withtoccc) && is_array($this->withtoccc)) {
  1031. $out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
  1032. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  1033. $tmparray = $this->withtoccc;
  1034. foreach ($tmparray as $key => $val) {
  1035. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  1036. }
  1037. $withtocccselected = GETPOST("receiverccc", 'array'); // Array of selected value
  1038. $out .= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null, null, "90%");
  1039. }
  1040. }
  1041. $showinfobcc = '';
  1042. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
  1043. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO;
  1044. }
  1045. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
  1046. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO;
  1047. }
  1048. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
  1049. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO;
  1050. }
  1051. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
  1052. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO;
  1053. }
  1054. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
  1055. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO;
  1056. }
  1057. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'invoice_supplier_send') {
  1058. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO;
  1059. }
  1060. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) && !empty($this->param['models']) && $this->param['models'] == 'project') {
  1061. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO;
  1062. }
  1063. if ($showinfobcc) {
  1064. $out .= ' + '.$showinfobcc;
  1065. }
  1066. $out .= "</td></tr>\n";
  1067. return $out;
  1068. }
  1069. /**
  1070. * get Html For WithErrorsTo
  1071. *
  1072. * @return string html
  1073. */
  1074. public function getHtmlForWithErrorsTo()
  1075. {
  1076. global $conf, $langs;
  1077. //if (! $this->errorstomail) $this->errorstomail=$this->frommail;
  1078. $errorstomail = getDolGlobalString('MAIN_MAIL_ERRORS_TO', (!empty($this->errorstomail) ? $this->errorstomail : ''));
  1079. if ($this->witherrorstoreadonly) {
  1080. $out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
  1081. $out .= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
  1082. $out .= $errorstomail;
  1083. $out .= "</td></tr>\n";
  1084. } else {
  1085. $out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
  1086. $out .= '<input class="minwidth200" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
  1087. $out .= "</td></tr>\n";
  1088. }
  1089. return $out;
  1090. }
  1091. /**
  1092. * get Html For Asking for Delivery Receipt
  1093. *
  1094. * @return string html
  1095. */
  1096. public function getHtmlForDeliveryreceipt()
  1097. {
  1098. global $conf, $langs;
  1099. $out = '<tr><td><label for="deliveryreceipt">'.$langs->trans("DeliveryReceipt").'</label></td><td>';
  1100. if (!empty($this->withdeliveryreceiptreadonly)) {
  1101. $out .= yn($this->withdeliveryreceipt);
  1102. } else {
  1103. $defaultvaluefordeliveryreceipt = 0;
  1104. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
  1105. $defaultvaluefordeliveryreceipt = 1;
  1106. }
  1107. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
  1108. $defaultvaluefordeliveryreceipt = 1;
  1109. }
  1110. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
  1111. $defaultvaluefordeliveryreceipt = 1;
  1112. }
  1113. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
  1114. $defaultvaluefordeliveryreceipt = 1;
  1115. }
  1116. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
  1117. $defaultvaluefordeliveryreceipt = 1;
  1118. }
  1119. //$out .= $form->selectyesno('deliveryreceipt', (GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt), 1);
  1120. $out .= '<input type="checkbox" id="deliveryreceipt" name="deliveryreceipt" value="1"'.((GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt) ? ' checked="checked"' : '').'>';
  1121. }
  1122. $out .= "</td></tr>\n";
  1123. return $out;
  1124. }
  1125. /**
  1126. * get Html For Topic of message
  1127. *
  1128. * @param array $arraydefaultmessage Array with message template content
  1129. * @param string $helpforsubstitution Help string for substitution
  1130. * @return string Text for topic
  1131. */
  1132. public function getHtmlForTopic($arraydefaultmessage, $helpforsubstitution)
  1133. {
  1134. global $conf, $langs, $form;
  1135. $defaulttopic = GETPOST('subject', 'restricthtml');
  1136. if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
  1137. if ($arraydefaultmessage && $arraydefaultmessage->topic) {
  1138. $defaulttopic = $arraydefaultmessage->topic;
  1139. } elseif (!is_numeric($this->withtopic)) {
  1140. $defaulttopic = $this->withtopic;
  1141. }
  1142. }
  1143. $defaulttopic = make_substitutions($defaulttopic, $this->substit);
  1144. $out = '<tr>';
  1145. $out .= '<td class="fieldrequired">';
  1146. $out .= $form->textwithpicto($langs->trans('MailTopic'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfromtopic');
  1147. $out .= '</td>';
  1148. $out .= '<td>';
  1149. if ($this->withtopicreadonly) {
  1150. $out .= $defaulttopic;
  1151. $out .= '<input type="hidden" class="quatrevingtpercent" id="subject" name="subject" value="'.$defaulttopic.'" />';
  1152. } else {
  1153. $out .= '<input type="text" class="quatrevingtpercent" id="subject" name="subject" value="'.((GETPOSTISSET("subject") && !GETPOST('modelselected')) ? GETPOST("subject") : ($defaulttopic ? $defaulttopic : '')).'" />';
  1154. }
  1155. $out .= "</td></tr>\n";
  1156. return $out;
  1157. }
  1158. /**
  1159. * Return templates of email with type = $type_template or type = 'all'.
  1160. * This search into table c_email_templates. Used by the get_form function.
  1161. *
  1162. * @param DoliDB $dbs Database handler
  1163. * @param string $type_template Get message for model/type=$type_template, type='all' also included.
  1164. * @param User $user Get templates public + limited to this user
  1165. * @param Translate $outputlangs Output lang object
  1166. * @param int $id Id of template to get, or
  1167. * -1 for first found with position 0, or
  1168. * 0 for first found whatever is position (priority order depends on lang provided or not) or
  1169. * -2 for exact match with label (no answer if not found)
  1170. * @param int $active 1=Only active template, 0=Only disabled, -1=All
  1171. * @param string $label Label of template to get
  1172. * @param int $defaultfortype 1=Only default templates, 0=Only not default, -1=All
  1173. * @return ModelMail|integer One instance of ModelMail or < 0 if error
  1174. */
  1175. public function getEMailTemplate($dbs, $type_template, $user, $outputlangs, $id = 0, $active = 1, $label = '', $defaultfortype = -1)
  1176. {
  1177. global $conf;
  1178. if ($id == -2 && empty($label)) {
  1179. $this->error = 'LabelIsMandatoryWhenIdIs-2or-3';
  1180. return -1;
  1181. }
  1182. $ret = new ModelMail();
  1183. $languagetosearch = (is_object($outputlangs) ? $outputlangs->defaultlang : '');
  1184. // Define $languagetosearchmain to fall back on main language (for example to get 'es_ES' for 'es_MX')
  1185. $tmparray = explode('_', $languagetosearch);
  1186. $languagetosearchmain = $tmparray[0].'_'.strtoupper($tmparray[0]);
  1187. if ($languagetosearchmain == $languagetosearch) {
  1188. $languagetosearchmain = '';
  1189. }
  1190. $sql = "SELECT rowid, module, label, type_template, topic, joinfiles, content, content_lines, lang, email_from, email_to, email_tocc, email_tobcc";
  1191. $sql .= " FROM ".$dbs->prefix().'c_email_templates';
  1192. $sql .= " WHERE (type_template = '".$dbs->escape($type_template)."' OR type_template = 'all')";
  1193. $sql .= " AND entity IN (".getEntity('c_email_templates').")";
  1194. $sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // Get all public or private owned
  1195. if ($active >= 0) {
  1196. $sql .= " AND active = ".((int) $active);
  1197. }
  1198. if ($defaultfortype >= 0) {
  1199. $sql .= " AND defaultfortype = ".((int) $defaultfortype);
  1200. }
  1201. if ($label) {
  1202. $sql .= " AND label = '".$dbs->escape($label)."'";
  1203. }
  1204. if (!($id > 0) && $languagetosearch) {
  1205. $sql .= " AND (lang = '".$dbs->escape($languagetosearch)."'".($languagetosearchmain ? " OR lang = '".$dbs->escape($languagetosearchmain)."'" : "")." OR lang IS NULL OR lang = '')";
  1206. }
  1207. if ($id > 0) {
  1208. $sql .= " AND rowid = ".(int) $id;
  1209. }
  1210. if ($id == -1) {
  1211. $sql .= " AND position = 0";
  1212. }
  1213. if ($languagetosearch) {
  1214. $sql .= $dbs->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or ''
  1215. } else {
  1216. $sql .= $dbs->order("position,lang,label", "ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined
  1217. }
  1218. //$sql .= $dbs->plimit(1);
  1219. //print $sql;
  1220. $resql = $dbs->query($sql);
  1221. if (!$resql) {
  1222. dol_print_error($dbs);
  1223. return -1;
  1224. }
  1225. // Get first found
  1226. while (1) {
  1227. $obj = $dbs->fetch_object($resql);
  1228. if ($obj) {
  1229. // If template is for a module, check module is enabled; if not, take next template
  1230. if ($obj->module) {
  1231. $tempmodulekey = $obj->module;
  1232. if (empty($conf->$tempmodulekey) || !isModEnabled($tempmodulekey)) {
  1233. continue;
  1234. }
  1235. }
  1236. // If a record was found
  1237. $ret->id = $obj->rowid;
  1238. $ret->module = $obj->module;
  1239. $ret->label = $obj->label;
  1240. $ret->lang = $obj->lang;
  1241. $ret->topic = $obj->topic;
  1242. $ret->content = $obj->content;
  1243. $ret->content_lines = $obj->content_lines;
  1244. $ret->joinfiles = $obj->joinfiles;
  1245. break;
  1246. } else {
  1247. // If no record found
  1248. if ($id == -2) {
  1249. // Not found with the provided label
  1250. return -1;
  1251. } else {
  1252. // If there is no template at all
  1253. $defaultmessage = '';
  1254. if ($type_template == 'body') {
  1255. // Special case to use this->withbody as content
  1256. $defaultmessage = $this->withbody;
  1257. } elseif ($type_template == 'facture_send') {
  1258. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoice");
  1259. } elseif ($type_template == 'facture_relance') {
  1260. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder");
  1261. } elseif ($type_template == 'propal_send') {
  1262. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendProposal");
  1263. } elseif ($type_template == 'supplier_proposal_send') {
  1264. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal");
  1265. } elseif ($type_template == 'order_send') {
  1266. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendOrder");
  1267. } elseif ($type_template == 'order_supplier_send') {
  1268. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder");
  1269. } elseif ($type_template == 'invoice_supplier_send') {
  1270. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice");
  1271. } elseif ($type_template == 'shipping_send') {
  1272. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendShipping");
  1273. } elseif ($type_template == 'fichinter_send') {
  1274. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendFichInter");
  1275. } elseif ($type_template == 'actioncomm_send') {
  1276. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendActionComm");
  1277. } elseif (!empty($type_template)) {
  1278. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentGeneric");
  1279. }
  1280. $ret->label = 'default';
  1281. $ret->lang = $outputlangs->defaultlang;
  1282. $ret->topic = '';
  1283. $ret->joinfiles = 1;
  1284. $ret->content = $defaultmessage;
  1285. $ret->content_lines = '';
  1286. break;
  1287. }
  1288. }
  1289. }
  1290. $dbs->free($resql);
  1291. return $ret;
  1292. }
  1293. /**
  1294. * Find if template exists
  1295. * Search into table c_email_templates
  1296. *
  1297. * @param string $type_template Get message for key module
  1298. * @param User $user Use template public or limited to this user
  1299. * @param Translate $outputlangs Output lang object
  1300. * @return int <0 if KO,
  1301. */
  1302. public function isEMailTemplate($type_template, $user, $outputlangs)
  1303. {
  1304. $sql = "SELECT label, topic, content, lang";
  1305. $sql .= " FROM ".$this->db->prefix().'c_email_templates';
  1306. $sql .= " WHERE type_template='".$this->db->escape($type_template)."'";
  1307. $sql .= " AND entity IN (".getEntity('c_email_templates').")";
  1308. $sql .= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".((int) $user->id).")";
  1309. if (is_object($outputlangs)) {
  1310. $sql .= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')";
  1311. }
  1312. $sql .= $this->db->order("lang,label", "ASC");
  1313. //print $sql;
  1314. $resql = $this->db->query($sql);
  1315. if ($resql) {
  1316. $num = $this->db->num_rows($resql);
  1317. $this->db->free($resql);
  1318. return $num;
  1319. } else {
  1320. $this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
  1321. return -1;
  1322. }
  1323. }
  1324. /**
  1325. * Find if template exists and are available for current user, then set them into $this->lines_module.
  1326. * Search into table c_email_templates
  1327. *
  1328. * @param string $type_template Get message for key module
  1329. * @param User $user Use template public or limited to this user
  1330. * @param Translate $outputlangs Output lang object
  1331. * @param int $active 1=Only active template, 0=Only disabled, -1=All
  1332. * @return int <0 if KO, nb of records found if OK
  1333. */
  1334. public function fetchAllEMailTemplate($type_template, $user, $outputlangs, $active = 1)
  1335. {
  1336. global $conf;
  1337. $sql = "SELECT rowid, module, label, topic, content, content_lines, lang, fk_user, private, position";
  1338. $sql .= " FROM ".$this->db->prefix().'c_email_templates';
  1339. $sql .= " WHERE type_template IN ('".$this->db->escape($type_template)."', 'all')";
  1340. $sql .= " AND entity IN (".getEntity('c_email_templates').")";
  1341. $sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // See all public templates or templates I own.
  1342. if ($active >= 0) {
  1343. $sql .= " AND active = ".((int) $active);
  1344. }
  1345. //if (is_object($outputlangs)) $sql.= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')"; // Return all languages
  1346. $sql .= $this->db->order("position,lang,label", "ASC");
  1347. //print $sql;
  1348. $resql = $this->db->query($sql);
  1349. if ($resql) {
  1350. $num = $this->db->num_rows($resql);
  1351. $this->lines_model = array();
  1352. while ($obj = $this->db->fetch_object($resql)) {
  1353. // If template is for a module, check module is enabled.
  1354. if ($obj->module) {
  1355. $tempmodulekey = $obj->module;
  1356. if (empty($conf->$tempmodulekey) || !isModEnabled($tempmodulekey)) {
  1357. continue;
  1358. }
  1359. }
  1360. $line = new ModelMail();
  1361. $line->id = $obj->rowid;
  1362. $line->label = $obj->label;
  1363. $line->lang = $obj->lang;
  1364. $line->fk_user = $obj->fk_user;
  1365. $line->private = $obj->private;
  1366. $line->position = $obj->position;
  1367. $line->topic = $obj->topic;
  1368. $line->content = $obj->content;
  1369. $line->content_lines = $obj->content_lines;
  1370. $this->lines_model[] = $line;
  1371. }
  1372. $this->db->free($resql);
  1373. return $num;
  1374. } else {
  1375. $this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
  1376. return -1;
  1377. }
  1378. }
  1379. /**
  1380. * Set ->substit (and ->substit_line) array from object. This is call when suggesting the email template into forms before sending email.
  1381. *
  1382. * @param CommonObject $object Object to use
  1383. * @param Translate $outputlangs Object lang
  1384. * @return void
  1385. * @see getCommonSubstitutionArray()
  1386. */
  1387. public function setSubstitFromObject($object, $outputlangs)
  1388. {
  1389. global $conf, $user, $extrafields;
  1390. $parameters = array();
  1391. $tmparray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
  1392. complete_substitutions_array($tmparray, $outputlangs, null, $parameters);
  1393. $this->substit = $tmparray;
  1394. // Fill substit_lines with each object lines content
  1395. if (is_array($object->lines)) {
  1396. foreach ($object->lines as $line) {
  1397. $substit_line = array(
  1398. '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '',
  1399. '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '',
  1400. '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '',
  1401. '__LABEL__' => isset($line->label) ? $line->label : '',
  1402. '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '',
  1403. '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs),
  1404. '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs),
  1405. '__QUANTITY__' => $line->qty,
  1406. '__SUBPRICE__' => price($line->subprice),
  1407. '__AMOUNT__' => price($line->total_ttc),
  1408. '__AMOUNT_EXCL_TAX__' => price($line->total_ht)
  1409. );
  1410. // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__
  1411. if (!empty($line->fk_product)) {
  1412. if (!is_object($extrafields)) {
  1413. $extrafields = new ExtraFields($this->db);
  1414. }
  1415. $product = new Product($this->db);
  1416. $product->fetch($line->fk_product, '', '', 1);
  1417. $product->fetch_optionals();
  1418. $extrafields->fetch_name_optionals_label($product->table_element, true);
  1419. if (!empty($extrafields->attributes[$product->table_element]['label']) && is_array($extrafields->attributes[$product->table_element]['label']) && count($extrafields->attributes[$product->table_element]['label']) > 0) {
  1420. foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
  1421. $substit_line['__PRODUCT_EXTRAFIELD_'.strtoupper($key).'__'] = isset($product->array_options['options_'.$key]) ? $product->array_options['options_'.$key] : '';
  1422. }
  1423. }
  1424. }
  1425. $this->substit_lines[] = $substit_line;
  1426. }
  1427. }
  1428. }
  1429. /**
  1430. * Get list of substitution keys available for emails. This is used for tooltips help.
  1431. * This include the complete_substitutions_array.
  1432. *
  1433. * @param string $mode 'formemail', 'formemailwithlines', 'formemailforlines', 'emailing', ...
  1434. * @param Object $object Object if applicable
  1435. * @return array Array of substitution values for emails.
  1436. */
  1437. public static function getAvailableSubstitKey($mode = 'formemail', $object = null)
  1438. {
  1439. global $conf, $langs;
  1440. $tmparray = array();
  1441. if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines') {
  1442. $parameters = array('mode'=>$mode);
  1443. $tmparray = getCommonSubstitutionArray($langs, 2, null, $object); // Note: On email templated edition, this is null because it is related to all type of objects
  1444. complete_substitutions_array($tmparray, $langs, null, $parameters);
  1445. if ($mode == 'formwithlines') {
  1446. $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function
  1447. }
  1448. if ($mode == 'formforlines') {
  1449. $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function
  1450. }
  1451. }
  1452. if ($mode == 'emailing') {
  1453. $parameters = array('mode'=>$mode);
  1454. $tmparray = getCommonSubstitutionArray($langs, 2, array('object', 'objectamount'), $object); // Note: On email templated edition, this is null because it is related to all type of objects
  1455. complete_substitutions_array($tmparray, $langs, null, $parameters);
  1456. // For mass emailing, we have different keys specific to the data into tagerts list
  1457. $tmparray['__ID__'] = 'IdRecord';
  1458. $tmparray['__THIRDPARTY_CUSTOMER_CODE__'] = 'CustomerCode';
  1459. $tmparray['__EMAIL__'] = 'EMailRecipient';
  1460. $tmparray['__LASTNAME__'] = 'Lastname';
  1461. $tmparray['__FIRSTNAME__'] = 'Firstname';
  1462. $tmparray['__MAILTOEMAIL__'] = 'TagMailtoEmail';
  1463. $tmparray['__OTHER1__'] = 'Other1';
  1464. $tmparray['__OTHER2__'] = 'Other2';
  1465. $tmparray['__OTHER3__'] = 'Other3';
  1466. $tmparray['__OTHER4__'] = 'Other4';
  1467. $tmparray['__OTHER5__'] = 'Other5';
  1468. //,'__PERSONALIZED__' => 'Personalized' // Hidden because not used yet in mass emailing
  1469. $onlinepaymentenabled = 0;
  1470. if (isModEnabled('paypal')) {
  1471. $onlinepaymentenabled++;
  1472. }
  1473. if (isModEnabled('paybox')) {
  1474. $onlinepaymentenabled++;
  1475. }
  1476. if (isModEnabled('stripe')) {
  1477. $onlinepaymentenabled++;
  1478. }
  1479. if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
  1480. $tmparray['__SECUREKEYPAYMENT__'] = $conf->global->PAYMENT_SECURITY_TOKEN;
  1481. if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
  1482. if (isModEnabled('adherent')) {
  1483. $tmparray['__SECUREKEYPAYMENT_MEMBER__'] = 'SecureKeyPAYMENTUniquePerMember';
  1484. }
  1485. if (isModEnabled('don')) {
  1486. $tmparray['__SECUREKEYPAYMENT_DONATION__'] = 'SecureKeyPAYMENTUniquePerDonation';
  1487. }
  1488. if (isModEnabled('facture')) {
  1489. $tmparray['__SECUREKEYPAYMENT_INVOICE__'] = 'SecureKeyPAYMENTUniquePerInvoice';
  1490. }
  1491. if (isModEnabled('commande')) {
  1492. $tmparray['__SECUREKEYPAYMENT_ORDER__'] = 'SecureKeyPAYMENTUniquePerOrder';
  1493. }
  1494. if (isModEnabled('contrat')) {
  1495. $tmparray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'SecureKeyPAYMENTUniquePerContractLine';
  1496. }
  1497. //Online payment link
  1498. if (isModEnabled('adherent')) {
  1499. $tmparray['__ONLINEPAYMENTLINK_MEMBER__'] = 'OnlinePaymentLinkUniquePerMember';
  1500. }
  1501. if (isModEnabled('don')) {
  1502. $tmparray['__ONLINEPAYMENTLINK_DONATION__'] = 'OnlinePaymentLinkUniquePerDonation';
  1503. }
  1504. if (isModEnabled('facture')) {
  1505. $tmparray['__ONLINEPAYMENTLINK_INVOICE__'] = 'OnlinePaymentLinkUniquePerInvoice';
  1506. }
  1507. if (isModEnabled('commande')) {
  1508. $tmparray['__ONLINEPAYMENTLINK_ORDER__'] = 'OnlinePaymentLinkUniquePerOrder';
  1509. }
  1510. if (isModEnabled('contrat')) {
  1511. $tmparray['__ONLINEPAYMENTLINK_CONTRACTLINE__'] = 'OnlinePaymentLinkUniquePerContractLine';
  1512. }
  1513. }
  1514. } else {
  1515. /* No need to show into tooltip help, option is not enabled
  1516. $vars['__SECUREKEYPAYMENT__']='';
  1517. $vars['__SECUREKEYPAYMENT_MEMBER__']='';
  1518. $vars['__SECUREKEYPAYMENT_INVOICE__']='';
  1519. $vars['__SECUREKEYPAYMENT_ORDER__']='';
  1520. $vars['__SECUREKEYPAYMENT_CONTRACTLINE__']='';
  1521. */
  1522. }
  1523. if (!empty($conf->global->MEMBER_ENABLE_PUBLIC)) {
  1524. $substitutionarray['__PUBLICLINK_NEWMEMBERFORM__'] = 'BlankSubscriptionForm';
  1525. }
  1526. }
  1527. foreach ($tmparray as $key => $val) {
  1528. if (empty($val)) {
  1529. $tmparray[$key] = $key;
  1530. }
  1531. }
  1532. return $tmparray;
  1533. }
  1534. }
  1535. /**
  1536. * ModelMail
  1537. *
  1538. * Object of table llx_c_email_templates
  1539. */
  1540. class ModelMail
  1541. {
  1542. /**
  1543. * @var int ID
  1544. */
  1545. public $id;
  1546. /**
  1547. * @var string Model mail label
  1548. */
  1549. public $label;
  1550. /**
  1551. * @var int Owner of email template
  1552. */
  1553. public $fk_user;
  1554. /**
  1555. * @var int Is template private
  1556. */
  1557. public $private;
  1558. /**
  1559. * @var string Model mail topic
  1560. */
  1561. public $topic;
  1562. /**
  1563. * @var string Model mail content
  1564. */
  1565. public $content;
  1566. public $content_lines;
  1567. public $lang;
  1568. public $joinfiles;
  1569. public $email_from;
  1570. public $email_to;
  1571. public $email_tocc;
  1572. public $email_tobcc;
  1573. /**
  1574. * @var string Module the template is dedicated for
  1575. */
  1576. public $module;
  1577. /**
  1578. * @var int Position of template in a combo list
  1579. */
  1580. public $position;
  1581. }