html.formmail.class.php 67 KB

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