html.formmail.class.php 66 KB

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