html.formmail.class.php 66 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740
  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 (!empty($conf->global->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 .= $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.
  456. if ($user->admin) {
  457. $out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
  458. }
  459. $out .= ' &nbsp; ';
  460. $out .= '<input type="submit" class="button" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
  461. $out .= ' &nbsp; ';
  462. $out .= '</div>';
  463. } else {
  464. $out .= '<!-- No template available for $this->param["models"] = '.$this->param['models'].' -->';
  465. }
  466. $out .= '<table class="tableforemailform boxtablenotop centpercent">'."\n";
  467. // Substitution array/string
  468. $helpforsubstitution = '';
  469. if (is_array($this->substit) && count($this->substit)) {
  470. $helpforsubstitution .= $langs->trans('AvailableVariables').' :<br>'."\n";
  471. }
  472. foreach ($this->substit as $key => $val) {
  473. $helpforsubstitution .= $key.' -> '.$langs->trans(dol_string_nohtmltag(dolGetFirstLineOfText($val))).'<br>';
  474. }
  475. if (!empty($this->withsubstit)) { // Unset or set ->withsubstit=0 to disable this.
  476. $out .= '<tr><td colspan="2" class="right">';
  477. //$out.='<div class="floatright">';
  478. if (is_numeric($this->withsubstit)) {
  479. $out .= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage
  480. } else {
  481. $out .= $form->textwithpicto($langs->trans('AvailableVariables'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // New usage
  482. }
  483. $out .= "</td></tr>\n";
  484. //$out.='</div>';
  485. }
  486. // From
  487. if (!empty($this->withfrom)) {
  488. if (!empty($this->withfromreadonly)) {
  489. $out .= '<tr><td class="fieldrequired minwidth200">'.$langs->trans("MailFrom").'</td><td>';
  490. // $this->fromtype is the default value to use to select sender
  491. if (!($this->fromtype === 'user' && $this->fromid > 0)
  492. && !($this->fromtype === 'company')
  493. && !($this->fromtype === 'robot')
  494. && !preg_match('/user_aliases/', $this->fromtype)
  495. && !preg_match('/global_aliases/', $this->fromtype)
  496. && !preg_match('/senderprofile/', $this->fromtype)
  497. ) {
  498. // Use this->fromname and this->frommail or error if not defined
  499. $out .= $this->fromname;
  500. if ($this->frommail) {
  501. $out .= ' &lt;'.$this->frommail.'&gt;';
  502. } else {
  503. if ($this->fromtype) {
  504. $langs->load('errors');
  505. $out .= '<span class="warning"> &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt; </span>';
  506. }
  507. }
  508. } else {
  509. $liste = array();
  510. // Add user email
  511. if (empty($user->email)) {
  512. $langs->load('errors');
  513. $liste['user'] = $user->getFullName($langs).' &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt;';
  514. } else {
  515. $liste['user'] = $user->getFullName($langs).' &lt;'.$user->email.'&gt;';
  516. }
  517. // Add also company main email
  518. if (!empty($conf->global->MAIN_INFO_SOCIETE_MAIL)) {
  519. $liste['company'] = !empty($conf->global->MAIN_INFO_SOCIETE_NOM)?$conf->global->MAIN_INFO_SOCIETE_NOM:$conf->global->MAIN_INFO_SOCIETE_MAIL;
  520. $liste['company'].=' &lt;'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'&gt;';
  521. }
  522. // Add also email aliases if there is some
  523. $listaliases = array(
  524. 'user_aliases' => (empty($user->email_aliases) ? '' : $user->email_aliases),
  525. 'global_aliases' => getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'),
  526. );
  527. // Also add robot email
  528. if (!empty($this->fromalsorobot)) {
  529. if (!empty($conf->global->MAIN_MAIL_EMAIL_FROM) && getDolGlobalString('MAIN_MAIL_EMAIL_FROM') != getDolGlobalString('MAIN_INFO_SOCIETE_MAIL')) {
  530. $liste['robot'] = $conf->global->MAIN_MAIL_EMAIL_FROM;
  531. if ($this->frommail) {
  532. $liste['robot'] .= ' &lt;'.$conf->global->MAIN_MAIL_EMAIL_FROM.'&gt;';
  533. }
  534. }
  535. }
  536. // Add also email aliases from the c_email_senderprofile table
  537. $sql = "SELECT rowid, label, email FROM ".$this->db->prefix()."c_email_senderprofile";
  538. $sql .= " WHERE active = 1 AND (private = 0 OR private = ".((int) $user->id).")";
  539. $sql .= " ORDER BY position";
  540. $resql = $this->db->query($sql);
  541. if ($resql) {
  542. $num = $this->db->num_rows($resql);
  543. $i = 0;
  544. while ($i < $num) {
  545. $obj = $this->db->fetch_object($resql);
  546. if ($obj) {
  547. $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>';
  548. }
  549. $i++;
  550. }
  551. } else {
  552. dol_print_error($this->db);
  553. }
  554. foreach ($listaliases as $typealias => $listalias) {
  555. $posalias = 0;
  556. $listaliasarray = explode(',', $listalias);
  557. foreach ($listaliasarray as $listaliasval) {
  558. $posalias++;
  559. $listaliasval = trim($listaliasval);
  560. if ($listaliasval) {
  561. $listaliasval = preg_replace('/</', '&lt;', $listaliasval);
  562. $listaliasval = preg_replace('/>/', '&gt;', $listaliasval);
  563. if (!preg_match('/&lt;/', $listaliasval)) {
  564. $listaliasval = '&lt;'.$listaliasval.'&gt;';
  565. }
  566. $liste[$typealias.'_'.$posalias] = $listaliasval;
  567. }
  568. }
  569. }
  570. // Using combo here make the '<email>' no more visible on list.
  571. //$out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 1, '', $disablebademails);
  572. $out .= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 0, '', $disablebademails);
  573. }
  574. $out .= "</td></tr>\n";
  575. } else {
  576. $out .= '<tr><td class="fieldrequired width200">'.$langs->trans("MailFrom")."</td><td>";
  577. $out .= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" class="maxwidth200onsmartphone" value="'.$this->fromname.'" />';
  578. $out .= '&nbsp; &nbsp; ';
  579. $out .= $langs->trans("EMail").':&lt;<input type="text" id="frommail" name="frommail" class="maxwidth200onsmartphone" value="'.$this->frommail.'" />&gt;';
  580. $out .= "</td></tr>\n";
  581. }
  582. }
  583. // To
  584. if (!empty($this->withto) || is_array($this->withto)) {
  585. $out .= $this->getHtmlForTo();
  586. }
  587. // To User
  588. if (!empty($this->withtouser) && is_array($this->withtouser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
  589. $out .= '<tr><td>';
  590. $out .= $langs->trans("MailToUsers");
  591. $out .= '</td><td>';
  592. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  593. $tmparray = $this->withtouser;
  594. foreach ($tmparray as $key => $val) {
  595. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  596. }
  597. $withtoselected = GETPOST("receiveruser", 'array'); // Array of selected value
  598. if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
  599. $withtoselected = array_keys($tmparray);
  600. }
  601. $out .= $form->multiselectarray("receiveruser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
  602. $out .= "</td></tr>\n";
  603. }
  604. // With option one email per recipient
  605. if (!empty($this->withoptiononeemailperrecipient)) {
  606. if (abs($this->withoptiononeemailperrecipient) == 1) {
  607. $out .= '<tr><td class="minwidth200">';
  608. $out .= $langs->trans("GroupEmails");
  609. $out .= '</td><td>';
  610. $out .= ' <input type="checkbox" id="oneemailperrecipient" value="1" name="oneemailperrecipient"'.($this->withoptiononeemailperrecipient > 0 ? ' checked="checked"' : '').'> ';
  611. $out .= '<label for="oneemailperrecipient">'.$langs->trans("OneEmailPerRecipient").'</label>';
  612. $out .= '<span class="hideonsmartphone opacitymedium">';
  613. $out .= ' - ';
  614. $out .= $langs->trans("WarningIfYouCheckOneRecipientPerEmail");
  615. $out .= '</span>';
  616. $out .= '</td></tr>';
  617. } else {
  618. $out .= '<tr><td><input type="hidden" name="oneemailperrecipient" value="1"></td><td></td></tr>';
  619. }
  620. }
  621. // CC
  622. if (!empty($this->withtocc) || is_array($this->withtocc)) {
  623. $out .= $this->getHtmlForCc();
  624. }
  625. // To User cc
  626. if (!empty($this->withtoccuser) && is_array($this->withtoccuser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
  627. $out .= '<tr><td>';
  628. $out .= $langs->trans("MailToCCUsers");
  629. $out .= '</td><td>';
  630. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  631. $tmparray = $this->withtoccuser;
  632. foreach ($tmparray as $key => $val) {
  633. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  634. }
  635. $withtoselected = GETPOST("receiverccuser", 'array'); // Array of selected value
  636. if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
  637. $withtoselected = array_keys($tmparray);
  638. }
  639. $out .= $form->multiselectarray("receiverccuser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
  640. $out .= "</td></tr>\n";
  641. }
  642. // CCC
  643. if (!empty($this->withtoccc) || is_array($this->withtoccc)) {
  644. $out .= $this->getHtmlForWithCcc();
  645. }
  646. // Replyto
  647. if (!empty($this->withreplyto)) {
  648. if ($this->withreplytoreadonly) {
  649. $out .= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
  650. $out .= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
  651. $out .= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail ? (" &lt;".$this->replytomail."&gt;") : "");
  652. $out .= "</td></tr>\n";
  653. }
  654. }
  655. // Errorsto
  656. if (!empty($this->witherrorsto)) {
  657. $out .= $this->getHtmlForWithErrorsTo();
  658. }
  659. // Ask delivery receipt
  660. if (!empty($this->withdeliveryreceipt)) {
  661. $out .= $this->getHtmlForDeliveryReceipt();
  662. }
  663. // Topic
  664. if (!empty($this->withtopic)) {
  665. $out .= $this->getHtmlForTopic($arraydefaultmessage, $helpforsubstitution);
  666. }
  667. // Attached files
  668. if (!empty($this->withfile)) {
  669. $out .= '<tr>';
  670. $out .= '<td>'.$langs->trans("MailFile").'</td>';
  671. $out .= '<td>';
  672. if ($this->withmaindocfile) {
  673. // withmaindocfile is set to 1 or -1 to show the checkbox (-1 = checked or 1 = not checked)
  674. if (GETPOSTISSET('sendmail')) {
  675. $this->withmaindocfile = (GETPOST('addmaindocfile', 'alpha') ? -1 : 1);
  676. } elseif (is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
  677. // If a template was selected, we use setup of template to define if join file checkbox is selected or not.
  678. $this->withmaindocfile = ($arraydefaultmessage->joinfiles ? -1 : 1);
  679. }
  680. }
  681. if (!empty($this->withmaindocfile)) {
  682. if ($this->withmaindocfile == 1) {
  683. $out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" />';
  684. } elseif ($this->withmaindocfile == -1) {
  685. $out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" checked="checked" />';
  686. }
  687. if (!empty($conf->global->MAIL_MASS_ACTION_ADD_LAST_IF_MAIN_DOC_NOT_FOUND)) {
  688. $out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDocOrLastGenerated").'.</label><br>';
  689. } else {
  690. $out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDoc").'.</label><br>';
  691. }
  692. }
  693. if (is_numeric($this->withfile)) {
  694. // TODO Trick to have param removedfile containing nb of file to delete. But this does not works without javascript
  695. $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
  696. $out .= '<script type="text/javascript">';
  697. $out .= 'jQuery(document).ready(function () {';
  698. $out .= ' jQuery(".removedfile").click(function() {';
  699. $out .= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
  700. $out .= ' });';
  701. $out .= '})';
  702. $out .= '</script>'."\n";
  703. if (count($listofpaths)) {
  704. foreach ($listofpaths as $key => $val) {
  705. $relativepathtofile = substr($val, (strlen(DOL_DATA_ROOT) - strlen($val)));
  706. if ($conf->entity > 1) {
  707. $relativepathtofile = str_replace($conf->entity.'/', '', $relativepathtofile);
  708. }
  709. // Try to extract data from full path
  710. $formfile_params = array();
  711. preg_match('#^(/)(\w+)(/)(.+)$#', $relativepathtofile, $formfile_params);
  712. $out .= '<div id="attachfile_'.$key.'">';
  713. // Preview of attachment
  714. $out .= img_mime($listofnames[$key]).' '.$listofnames[$key];
  715. $out .= $formfile->showPreview(array(), $formfile_params[2], $formfile_params[4]);
  716. if (!$this->withfilereadonly) {
  717. $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.'" />';
  718. //$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
  719. }
  720. $out .= '<br></div>';
  721. }
  722. } elseif (empty($this->withmaindocfile)) {
  723. //$out .= '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
  724. }
  725. if ($this->withfile == 2) {
  726. $maxfilesizearray = getMaxFileSizeArray();
  727. $maxmin = $maxfilesizearray['maxmin'];
  728. if ($maxmin > 0) {
  729. $out .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
  730. }
  731. // Can add other files
  732. if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) {
  733. $out .= '<input type="file" class="flat" id="addedfile" name="addedfile[]" value="'.$langs->trans("Upload").'" multiple />';
  734. } else {
  735. $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
  736. }
  737. $out .= ' ';
  738. $out .= '<input type="submit" class="button smallpaddingimp" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
  739. }
  740. } else {
  741. $out .= $this->withfile;
  742. }
  743. $out .= "</td></tr>\n";
  744. }
  745. // Message
  746. if (!empty($this->withbody)) {
  747. $defaultmessage = GETPOST('message', 'restricthtml');
  748. if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
  749. if ($arraydefaultmessage && $arraydefaultmessage->content) {
  750. $defaultmessage = $arraydefaultmessage->content;
  751. } elseif (!is_numeric($this->withbody)) {
  752. $defaultmessage = $this->withbody;
  753. }
  754. }
  755. // Complete substitution array with the url to make online payment
  756. $paymenturl = '';
  757. $validpaymentmethod = array();
  758. if (empty($this->substit['__REF__'])) {
  759. $paymenturl = '';
  760. } else {
  761. // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
  762. require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
  763. $langs->loadLangs(array('paypal', 'other'));
  764. $typeforonlinepayment = 'free';
  765. if ($this->param["models"] == 'order' || $this->param["models"] == 'order_send') {
  766. $typeforonlinepayment = 'order'; // TODO use detection on something else than template
  767. }
  768. if ($this->param["models"] == 'invoice' || $this->param["models"] == 'facture_send') {
  769. $typeforonlinepayment = 'invoice'; // TODO use detection on something else than template
  770. }
  771. if ($this->param["models"] == 'member') {
  772. $typeforonlinepayment = 'member'; // TODO use detection on something else than template
  773. }
  774. $url = getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']);
  775. $paymenturl = $url;
  776. $validpaymentmethod = getValidOnlinePaymentMethods('');
  777. }
  778. if (count($validpaymentmethod) > 0 && $paymenturl) {
  779. $langs->load('other');
  780. $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = str_replace('\n', "\n", $langs->transnoentities("PredefinedMailContentLink", $paymenturl));
  781. $this->substit['__ONLINE_PAYMENT_URL__'] = $paymenturl;
  782. } else {
  783. $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
  784. $this->substit['__ONLINE_PAYMENT_URL__'] = '';
  785. }
  786. $this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'] = '';
  787. // Add lines substitution key from each line
  788. $lines = '';
  789. $defaultlines = $arraydefaultmessage->content_lines;
  790. if (isset($defaultlines)) {
  791. foreach ($this->substit_lines as $substit_line) {
  792. $lines .= make_substitutions($defaultlines, $substit_line)."\n";
  793. }
  794. }
  795. $this->substit['__LINES__'] = $lines;
  796. $defaultmessage = str_replace('\n', "\n", $defaultmessage);
  797. // Deal with format differences between message and some substitution variables (text / HTML)
  798. $atleastonecomponentishtml = 0;
  799. if (strpos($defaultmessage, '__USER_SIGNATURE__') !== false && dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
  800. $atleastonecomponentishtml++;
  801. }
  802. if (strpos($defaultmessage, '__SENDEREMAIL_SIGNATURE__') !== false && dol_textishtml($this->substit['__SENDEREMAIL_SIGNATURE__'])) {
  803. $atleastonecomponentishtml++;
  804. }
  805. if (strpos($defaultmessage, '__ONLINE_PAYMENT_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
  806. $atleastonecomponentishtml++;
  807. }
  808. if (strpos($defaultmessage, '__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'])) {
  809. $atleastonecomponentishtml++;
  810. }
  811. if (dol_textishtml($defaultmessage)) {
  812. $atleastonecomponentishtml++;
  813. }
  814. if ($atleastonecomponentishtml) {
  815. if (!dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
  816. $this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']);
  817. }
  818. if (!dol_textishtml($this->substit['__SENDEREMAIL_SIGNATURE__'])) {
  819. $this->substit['__SENDEREMAIL_SIGNATURE__'] = dol_nl2br($this->substit['__SENDEREMAIL_SIGNATURE__']);
  820. }
  821. if (!dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
  822. $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = dol_nl2br($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']);
  823. }
  824. if (!dol_textishtml($defaultmessage)) {
  825. $defaultmessage = dol_nl2br($defaultmessage);
  826. }
  827. }
  828. if (GETPOSTISSET("message") && !GETPOST('modelselected')) {
  829. $defaultmessage = GETPOST("message", "restricthtml");
  830. } else {
  831. $defaultmessage = make_substitutions($defaultmessage, $this->substit);
  832. // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
  833. $defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
  834. $defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
  835. }
  836. $out .= '<tr>';
  837. $out .= '<td colspan="2">';
  838. $out .= $form->textwithpicto($langs->trans('MailText'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfrombody');
  839. $out .= '</td>';
  840. $out .= '</tr>';
  841. $out .= '<tr>';
  842. $out .= '<td colspan="2">';
  843. if ($this->withbodyreadonly) {
  844. $out .= nl2br($defaultmessage);
  845. $out .= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />';
  846. } else {
  847. if (!isset($this->ckeditortoolbar)) {
  848. $this->ckeditortoolbar = 'dolibarr_mailings';
  849. }
  850. // Editor wysiwyg
  851. require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
  852. if ($this->withfckeditor == -1) {
  853. if (!empty($conf->global->FCKEDITOR_ENABLE_MAIL)) {
  854. $this->withfckeditor = 1;
  855. } else {
  856. $this->withfckeditor = 0;
  857. }
  858. }
  859. $doleditor = new DolEditor('message', $defaultmessage, '', 280, $this->ckeditortoolbar, 'In', true, true, $this->withfckeditor, 8, '95%');
  860. $out .= $doleditor->Create(1);
  861. }
  862. $out .= "</td></tr>\n";
  863. }
  864. $out .= '</table>'."\n";
  865. if ($this->withform == 1 || $this->withform == -1) {
  866. $out .= '<div class="center">';
  867. $out .= '<input type="submit" class="button button-add" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
  868. // Add a javascript test to avoid to forget to submit file before sending email
  869. if ($this->withfile == 2 && $conf->use_javascript_ajax) {
  870. $out .= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
  871. }
  872. $out .= ' />';
  873. if ($this->withcancel) {
  874. $out .= '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
  875. }
  876. $out .= '</div>'."\n";
  877. }
  878. if ($this->withform == 1) {
  879. $out .= '</form>'."\n";
  880. }
  881. // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
  882. if (!empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) {
  883. $out .= '<script type="text/javascript">';
  884. $out .= 'jQuery(document).ready(function () {';
  885. $out .= ' $(document).on("keypress", \'#mailform\', function (e) { /* Note this is called at every key pressed ! */
  886. var code = e.keyCode || e.which;
  887. if (code == 13) {
  888. console.log("Enter was intercepted and blocked");
  889. e.preventDefault();
  890. return false;
  891. }
  892. });';
  893. $out .= ' })';
  894. $out .= '</script>';
  895. }
  896. $out .= "<!-- End form mail -->\n";
  897. return $out;
  898. }
  899. }
  900. /**
  901. * get html For To
  902. *
  903. * @return string html
  904. */
  905. public function getHtmlForTo()
  906. {
  907. global $langs, $form;
  908. $out = '<tr><td class="fieldrequired">';
  909. if ($this->withtofree) {
  910. $out .= $form->textwithpicto($langs->trans("MailTo"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
  911. } else {
  912. $out .= $langs->trans("MailTo");
  913. }
  914. $out .= '</td><td>';
  915. if ($this->withtoreadonly) {
  916. if (!empty($this->toname) && !empty($this->tomail)) {
  917. $out .= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
  918. $out .= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
  919. if ($this->totype == 'thirdparty') {
  920. $soc = new Societe($this->db);
  921. $soc->fetch($this->toid);
  922. $out .= $soc->getNomUrl(1);
  923. } elseif ($this->totype == 'contact') {
  924. $contact = new Contact($this->db);
  925. $contact->fetch($this->toid);
  926. $out .= $contact->getNomUrl(1);
  927. } else {
  928. $out .= $this->toname;
  929. }
  930. $out .= ' &lt;'.$this->tomail.'&gt;';
  931. if ($this->withtofree) {
  932. $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) : "").'" />';
  933. }
  934. } else {
  935. // Note withto may be a text like 'AllRecipientSelected'
  936. $out .= (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : "";
  937. }
  938. } else {
  939. // The free input of email
  940. if (!empty($this->withtofree)) {
  941. $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) : "")).'" />';
  942. }
  943. // The select combo
  944. if (!empty($this->withto) && is_array($this->withto)) {
  945. if (!empty($this->withtofree)) {
  946. $out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
  947. }
  948. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  949. $tmparray = $this->withto;
  950. foreach ($tmparray as $key => $val) {
  951. $tmparray[$key] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]);
  952. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  953. }
  954. $withtoselected = GETPOST("receiver", 'array'); // Array of selected value
  955. if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
  956. $withtoselected = array_keys($tmparray);
  957. }
  958. $out .= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
  959. }
  960. }
  961. $out .= "</td></tr>\n";
  962. return $out;
  963. }
  964. /**
  965. * get html For CC
  966. *
  967. * @return string html
  968. */
  969. public function getHtmlForCc()
  970. {
  971. global $langs, $form;
  972. $out = '<tr><td>';
  973. $out .= $form->textwithpicto($langs->trans("MailCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
  974. $out .= '</td><td>';
  975. if ($this->withtoccreadonly) {
  976. $out .= (!is_array($this->withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : "";
  977. } else {
  978. $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 : '')).'" />';
  979. if (!empty($this->withtocc) && is_array($this->withtocc)) {
  980. $out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
  981. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  982. $tmparray = $this->withtocc;
  983. foreach ($tmparray as $key => $val) {
  984. $tmparray[$key] = str_replace(array('<', '>'), array('(', ')'), $tmparray[$key]);
  985. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  986. }
  987. $withtoccselected = GETPOST("receivercc", 'array'); // Array of selected value
  988. $out .= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500', null, "");
  989. }
  990. }
  991. $out .= "</td></tr>\n";
  992. return $out;
  993. }
  994. /**
  995. * get html For WithCCC
  996. *
  997. * @return string html
  998. */
  999. public function getHtmlForWithCcc()
  1000. {
  1001. global $conf, $langs, $form;
  1002. $out = '<tr><td>';
  1003. $out .= $form->textwithpicto($langs->trans("MailCCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
  1004. $out .= '</td><td>';
  1005. if (!empty($this->withtocccreadonly)) {
  1006. $out .= (!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : "";
  1007. } else {
  1008. $out .= '<input class="minwidth200" id="sendtoccc" name="sendtoccc" value="'.(GETPOSTISSET("sendtoccc") ? GETPOST("sendtoccc", "alpha") : ((!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : '')).'" />';
  1009. if (!empty($this->withtoccc) && is_array($this->withtoccc)) {
  1010. $out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
  1011. // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
  1012. $tmparray = $this->withtoccc;
  1013. foreach ($tmparray as $key => $val) {
  1014. $tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
  1015. }
  1016. $withtocccselected = GETPOST("receiverccc", 'array'); // Array of selected value
  1017. $out .= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null, null, "90%");
  1018. }
  1019. }
  1020. $showinfobcc = '';
  1021. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
  1022. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO;
  1023. }
  1024. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
  1025. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO;
  1026. }
  1027. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
  1028. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO;
  1029. }
  1030. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
  1031. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO;
  1032. }
  1033. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
  1034. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO;
  1035. }
  1036. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'invoice_supplier_send') {
  1037. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO;
  1038. }
  1039. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) && !empty($this->param['models']) && $this->param['models'] == 'project') {
  1040. $showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO;
  1041. }
  1042. if ($showinfobcc) {
  1043. $out .= ' + '.$showinfobcc;
  1044. }
  1045. $out .= "</td></tr>\n";
  1046. return $out;
  1047. }
  1048. /**
  1049. * get Html For WithErrorsTo
  1050. *
  1051. * @return string html
  1052. */
  1053. public function getHtmlForWithErrorsTo()
  1054. {
  1055. global $conf, $langs;
  1056. //if (! $this->errorstomail) $this->errorstomail=$this->frommail;
  1057. $errorstomail = getDolGlobalString('MAIN_MAIL_ERRORS_TO', (!empty($this->errorstomail) ? $this->errorstomail : ''));
  1058. if ($this->witherrorstoreadonly) {
  1059. $out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
  1060. $out .= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
  1061. $out .= $errorstomail;
  1062. $out .= "</td></tr>\n";
  1063. } else {
  1064. $out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
  1065. $out .= '<input size="30" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
  1066. $out .= "</td></tr>\n";
  1067. }
  1068. return $out;
  1069. }
  1070. /**
  1071. * get Html For Asking for Delivery Receipt
  1072. *
  1073. * @return string html
  1074. */
  1075. public function getHtmlForDeliveryreceipt()
  1076. {
  1077. global $conf, $langs, $form;
  1078. $out = '<tr><td>'.$langs->trans("DeliveryReceipt").'</td><td>';
  1079. if (!empty($this->withdeliveryreceiptreadonly)) {
  1080. $out .= yn($this->withdeliveryreceipt);
  1081. } else {
  1082. $defaultvaluefordeliveryreceipt = 0;
  1083. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
  1084. $defaultvaluefordeliveryreceipt = 1;
  1085. }
  1086. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
  1087. $defaultvaluefordeliveryreceipt = 1;
  1088. }
  1089. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
  1090. $defaultvaluefordeliveryreceipt = 1;
  1091. }
  1092. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
  1093. $defaultvaluefordeliveryreceipt = 1;
  1094. }
  1095. if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
  1096. $defaultvaluefordeliveryreceipt = 1;
  1097. }
  1098. $out .= $form->selectyesno('deliveryreceipt', (GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt), 1);
  1099. }
  1100. $out .= "</td></tr>\n";
  1101. return $out;
  1102. }
  1103. /**
  1104. * get Html For Topic of message
  1105. *
  1106. * @param array $arraydefaultmessage Array with message template content
  1107. * @param string $helpforsubstitution Help string for substitution
  1108. * @return string Text for topic
  1109. */
  1110. public function getHtmlForTopic($arraydefaultmessage, $helpforsubstitution)
  1111. {
  1112. global $conf, $langs, $form;
  1113. $defaulttopic = GETPOST('subject', 'restricthtml');
  1114. if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
  1115. if ($arraydefaultmessage && $arraydefaultmessage->topic) {
  1116. $defaulttopic = $arraydefaultmessage->topic;
  1117. } elseif (!is_numeric($this->withtopic)) {
  1118. $defaulttopic = $this->withtopic;
  1119. }
  1120. }
  1121. $defaulttopic = make_substitutions($defaulttopic, $this->substit);
  1122. $out = '<tr>';
  1123. $out .= '<td class="fieldrequired">';
  1124. $out .= $form->textwithpicto($langs->trans('MailTopic'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfromtopic');
  1125. $out .= '</td>';
  1126. $out .= '<td>';
  1127. if ($this->withtopicreadonly) {
  1128. $out .= $defaulttopic;
  1129. $out .= '<input type="hidden" class="quatrevingtpercent" id="subject" name="subject" value="'.$defaulttopic.'" />';
  1130. } else {
  1131. $out .= '<input type="text" class="quatrevingtpercent" id="subject" name="subject" value="'.((GETPOSTISSET("subject") && !GETPOST('modelselected')) ? GETPOST("subject") : ($defaulttopic ? $defaulttopic : '')).'" />';
  1132. }
  1133. $out .= "</td></tr>\n";
  1134. return $out;
  1135. }
  1136. /**
  1137. * Return templates of email with type = $type_template or type = 'all'.
  1138. * This search into table c_email_templates. Used by the get_form function.
  1139. *
  1140. * @param DoliDB $dbs Database handler
  1141. * @param string $type_template Get message for model/type=$type_template, type='all' also included.
  1142. * @param User $user Get template public or limited to this user
  1143. * @param Translate $outputlangs Output lang object
  1144. * @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)
  1145. * @param int $active 1=Only active template, 0=Only disabled, -1=All
  1146. * @param string $label Label of template to get
  1147. * @return ModelMail|integer One instance of ModelMail or -1 if error
  1148. */
  1149. public function getEMailTemplate($dbs, $type_template, $user, $outputlangs, $id = 0, $active = 1, $label = '')
  1150. {
  1151. global $conf, $langs;
  1152. $ret = new ModelMail();
  1153. if ($id == -2 && empty($label)) {
  1154. $this->error = 'LabelIsMandatoryWhenIdIs-2';
  1155. return -1;
  1156. }
  1157. $languagetosearch = (is_object($outputlangs) ? $outputlangs->defaultlang : '');
  1158. // Define $languagetosearchmain to fall back on main language (for example to get 'es_ES' for 'es_MX')
  1159. $tmparray = explode('_', $languagetosearch);
  1160. $languagetosearchmain = $tmparray[0].'_'.strtoupper($tmparray[0]);
  1161. if ($languagetosearchmain == $languagetosearch) {
  1162. $languagetosearchmain = '';
  1163. }
  1164. $sql = "SELECT rowid, module, label, type_template, topic, joinfiles, content, content_lines, lang";
  1165. $sql .= " FROM ".$dbs->prefix().'c_email_templates';
  1166. $sql .= " WHERE (type_template='".$dbs->escape($type_template)."' OR type_template='all')";
  1167. $sql .= " AND entity IN (".getEntity('c_email_templates').")";
  1168. $sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // Get all public or private owned
  1169. if ($active >= 0) {
  1170. $sql .= " AND active = ".((int) $active);
  1171. }
  1172. if ($label) {
  1173. $sql .= " AND label = '".$dbs->escape($label)."'";
  1174. }
  1175. if (!($id > 0) && $languagetosearch) {
  1176. $sql .= " AND (lang = '".$dbs->escape($languagetosearch)."'".($languagetosearchmain ? " OR lang = '".$dbs->escape($languagetosearchmain)."'" : "")." OR lang IS NULL OR lang = '')";
  1177. }
  1178. if ($id > 0) {
  1179. $sql .= " AND rowid=".(int) $id;
  1180. }
  1181. if ($id == -1) {
  1182. $sql .= " AND position=0";
  1183. }
  1184. if ($languagetosearch) {
  1185. $sql .= $dbs->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or ''
  1186. } else {
  1187. $sql .= $dbs->order("position,lang,label", "ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined
  1188. }
  1189. //$sql .= $dbs->plimit(1);
  1190. //print $sql;
  1191. $resql = $dbs->query($sql);
  1192. if (!$resql) {
  1193. dol_print_error($dbs);
  1194. return -1;
  1195. }
  1196. // Get first found
  1197. while (1) {
  1198. $obj = $dbs->fetch_object($resql);
  1199. if ($obj) {
  1200. // If template is for a module, check module is enabled; if not, take next template
  1201. if ($obj->module) {
  1202. $tempmodulekey = $obj->module;
  1203. if (empty($conf->$tempmodulekey) || empty($conf->$tempmodulekey->enabled)) {
  1204. continue;
  1205. }
  1206. }
  1207. // If a record was found
  1208. $ret->id = $obj->rowid;
  1209. $ret->module = $obj->module;
  1210. $ret->label = $obj->label;
  1211. $ret->lang = $obj->lang;
  1212. $ret->topic = $obj->topic;
  1213. $ret->content = $obj->content;
  1214. $ret->content_lines = $obj->content_lines;
  1215. $ret->joinfiles = $obj->joinfiles;
  1216. break;
  1217. } else {
  1218. // If no record found
  1219. if ($id == -2) {
  1220. // Not found with the provided label
  1221. return -1;
  1222. } else {
  1223. // If there is no template at all
  1224. $defaultmessage = '';
  1225. if ($type_template == 'body') {
  1226. // Special case to use this->withbody as content
  1227. $defaultmessage = $this->withbody;
  1228. } elseif ($type_template == 'facture_send') {
  1229. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoice");
  1230. } elseif ($type_template == 'facture_relance') {
  1231. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder");
  1232. } elseif ($type_template == 'propal_send') {
  1233. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendProposal");
  1234. } elseif ($type_template == 'supplier_proposal_send') {
  1235. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal");
  1236. } elseif ($type_template == 'order_send') {
  1237. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendOrder");
  1238. } elseif ($type_template == 'order_supplier_send') {
  1239. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder");
  1240. } elseif ($type_template == 'invoice_supplier_send') {
  1241. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice");
  1242. } elseif ($type_template == 'shipping_send') {
  1243. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendShipping");
  1244. } elseif ($type_template == 'fichinter_send') {
  1245. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendFichInter");
  1246. } elseif ($type_template == 'actioncomm_send') {
  1247. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendActionComm");
  1248. } elseif ($type_template == 'thirdparty') {
  1249. $defaultmessage = $outputlangs->transnoentities("PredefinedMailContentThirdparty");
  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 (!empty($conf->paypal->enabled)) {
  1448. $onlinepaymentenabled++;
  1449. }
  1450. if (!empty($conf->paybox->enabled)) {
  1451. $onlinepaymentenabled++;
  1452. }
  1453. if (!empty($conf->stripe->enabled)) {
  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 (!empty($conf->don->enabled)) {
  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 payement link
  1475. if (isModEnabled('adherent')) {
  1476. $tmparray['__ONLINEPAYMENTLINK_MEMBER__'] = 'OnlinePaymentLinkUniquePerMember';
  1477. }
  1478. if (!empty($conf->don->enabled)) {
  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. /**
  1547. * @var string Module the template is dedicated for
  1548. */
  1549. public $module;
  1550. /**
  1551. * @var int Position of template in a combo list
  1552. */
  1553. public $position;
  1554. }