Passed
Branch develop (e2bf59)
by
unknown
29:11
created

FormMail::getHtmlForDeliveryreceipt()   D

Complexity

Conditions 18
Paths 33

Size

Total Lines 28
Code Lines 19

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 18
eloc 19
c 1
b 0
f 0
nop 0
dl 0
loc 28
rs 4.8666
nc 33

How to fix   Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
/* Copyright (C) 2005-2012 Laurent Destailleur  <[email protected]>
3
 * Copyright (C) 2005-2012 Regis Houssin	    <[email protected]>
4
 * Copyright (C) 2010-2011 Juanjo Menent	    <[email protected]>
5
 * Copyright (C) 2015-2017 Marcos García        <[email protected]>
6
 * Copyright (C) 2015-2017 Nicolas ZABOURI      <[email protected]>
7
 * Copyright (C) 2018-2021  Frédéric France     <[email protected]>
8
 *
9
 * This program is free software; you can redistribute it and/or modify
10
 * it under the terms of the GNU General Public License as published by
11
 * the Free Software Foundation; either version 3 of the License, or
12
 * (at your option) any later version.
13
 *
14
 * This program is distributed in the hope that it will be useful,
15
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17
 * GNU General Public License for more details.
18
 *
19
 * You should have received a copy of the GNU General Public License
20
 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21
 */
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
31
/**
32
 *      Classe permettant la generation du formulaire html d'envoi de mail unitaire
33
 *      Usage: $formail = new FormMail($db)
34
 *             $formmail->proprietes=1 ou chaine ou tableau de valeurs
35
 *             $formmail->show_form() affiche le formulaire
36
 */
37
class FormMail extends Form
38
{
39
	/**
40
	 * @var DoliDB Database handler.
41
	 */
42
	public $db;
43
44
	/**
45
	 * @var int 1 = Include HTML form tag and show submit button
46
	 *          0 = Do not include form tag and submit button
47
	 *          -1 = Do not include form tag but include submit button
48
	 */
49
	public $withform;
50
51
	/**
52
	 * @var string name from
53
	 */
54
	public $fromname;
55
56
	/**
57
	 * @var string email from
58
	 */
59
	public $frommail;
60
61
	/**
62
	 * @var string user, company, robot
63
	 */
64
	public $fromtype;
65
66
	/**
67
	 * @var int from ID
68
	 */
69
	public $fromid;
70
71
	/**
72
	 * @var int also from robot
73
	 */
74
	public $fromalsorobot;
75
76
	/**
77
	 * @var string thirdparty etc
78
	 */
79
	public $totype;
80
81
	/**
82
	 * @var int ID
83
	 */
84
	public $toid;
85
86
	/**
87
	 * @var string replyto name
88
	 */
89
	public $replytoname;
90
91
	/**
92
	 * @var string replyto email
93
	 */
94
	public $replytomail;
95
96
	/**
97
	 * @var string to name
98
	 */
99
	public $toname;
100
101
	/**
102
	 * @var string to email
103
	 */
104
	public $tomail;
105
106
	/**
107
	 * @var string trackid
108
	 */
109
	public $trackid;
110
111
	public $withsubstit; // Show substitution array
112
	public $withfrom;
113
114
	/**
115
	 * @var int|string|array
116
	 */
117
	public $withto; // Show recipient emails
118
119
	/**
120
	 * @var int|string 0 = Do not Show free text for recipient emails
121
	 *                 1 = Show free text for recipient emails
122
	 *                 or a free email
123
	 */
124
	public $withtofree;
125
	public $withtocc;
126
	public $withtoccc;
127
	public $withtopic;
128
129
	/**
130
	 * @var int 0=No attaches files, 1=Show attached files, 2=Can add new attached files
131
	 */
132
	public $withfile;
133
134
	/**
135
	 * @var int 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
136
	 */
137
	public $withmaindocfile;
138
	public $withbody;
139
140
	public $withfromreadonly;
141
	public $withreplytoreadonly;
142
	public $withtoreadonly;
143
	public $withtoccreadonly;
144
	public $withtocccreadonly;
145
	public $withtopicreadonly;
146
	public $withfilereadonly;
147
	public $withdeliveryreceipt;
148
	public $withcancel;
149
	public $withfckeditor;
150
151
	public $substit = array();
152
	public $substit_lines = array();
153
	public $param = array();
154
155
	public $withtouser = array();
156
	public $withtoccuser = array();
157
158
	public $lines_model;
159
160
	// -1 suggest the checkbox 'one email per recipient' not checked, 0 = no suggestion, 1 = suggest and checked
161
	public $withoptiononeemailperrecipient;
162
163
164
	/**
165
	 *	Constructor
166
	 *
167
	 *  @param	DoliDB	$db      Database handler
168
	 */
169
	public function __construct($db)
170
	{
171
		$this->db = $db;
172
173
		$this->withform = 1;
174
175
		$this->withfrom = 1;
176
		$this->withto = 1;
177
		$this->withtofree = 1;
178
		$this->withtocc = 1;
179
		$this->withtoccc = 0;
180
		$this->witherrorsto = 0;
181
		$this->withtopic = 1;
182
		$this->withfile = 0; // 1=Add section "Attached files". 2=Can add files.
183
		$this->withmaindocfile = 0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
184
		$this->withbody = 1;
185
186
		$this->withfromreadonly = 1;
187
		$this->withreplytoreadonly = 1;
188
		$this->withtoreadonly = 0;
189
		$this->withtoccreadonly = 0;
190
		$this->withtocccreadonly = 0;
191
		$this->witherrorstoreadonly = 0;
192
		$this->withtopicreadonly = 0;
193
		$this->withfilereadonly = 0;
194
		$this->withbodyreadonly = 0;
195
		$this->withdeliveryreceiptreadonly = 0;
196
		$this->withfckeditor = -1; // -1 = Auto
197
	}
198
199
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
200
	/**
201
	 * Clear list of attached files in send mail form (also stored in session)
202
	 *
203
	 * @return	void
204
	 */
205
	public function clear_attached_files()
206
	{
207
		// phpcs:enable
208
		global $conf, $user;
209
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
210
211
		// Set tmp user directory
212
		$vardir = $conf->user->dir_output."/".$user->id;
213
		$upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path
214
		if (is_dir($upload_dir)) {
215
			dol_delete_dir_recursive($upload_dir);
216
		}
217
218
		$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
219
		unset($_SESSION["listofpaths".$keytoavoidconflict]);
220
		unset($_SESSION["listofnames".$keytoavoidconflict]);
221
		unset($_SESSION["listofmimes".$keytoavoidconflict]);
222
	}
223
224
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
225
	/**
226
	 * Add a file into the list of attached files (stored in SECTION array)
227
	 *
228
	 * @param 	string   $path   Full absolute path on filesystem of file, including file name
229
	 * @param 	string   $file   Only filename (can be basename($path))
230
	 * @param 	string   $type   Mime type (can be dol_mimetype($file))
231
	 * @return	void
232
	 */
233
	public function add_attached_files($path, $file = '', $type = '')
234
	{
235
		// phpcs:enable
236
		$listofpaths = array();
237
		$listofnames = array();
238
		$listofmimes = array();
239
240
		if (empty($file)) {
241
			$file = basename($path);
242
		}
243
		if (empty($type)) {
244
			$type = dol_mimetype($file);
245
		}
246
247
		$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
248
		if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
249
			$listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
250
		}
251
		if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
252
			$listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
253
		}
254
		if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
255
			$listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
256
		}
257
		if (!in_array($file, $listofnames)) {
258
			$listofpaths[] = $path;
259
			$listofnames[] = $file;
260
			$listofmimes[] = $type;
261
			$_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
262
			$_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
263
			$_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
264
		}
265
	}
266
267
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
268
	/**
269
	 * Remove a file from the list of attached files (stored in SECTION array)
270
	 *
271
	 * @param  	string	$keytodelete     Key index in file array (0, 1, 2, ...)
272
	 * @return	void
273
	 */
274
	public function remove_attached_files($keytodelete)
275
	{
276
		// phpcs:enable
277
		$listofpaths = array();
278
		$listofnames = array();
279
		$listofmimes = array();
280
281
		$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
282
		if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
283
			$listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
284
		}
285
		if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
286
			$listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
287
		}
288
		if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
289
			$listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
290
		}
291
		if ($keytodelete >= 0) {
292
			unset($listofpaths[$keytodelete]);
293
			unset($listofnames[$keytodelete]);
294
			unset($listofmimes[$keytodelete]);
295
			$_SESSION["listofpaths".$keytoavoidconflict] = join(';', $listofpaths);
296
			$_SESSION["listofnames".$keytoavoidconflict] = join(';', $listofnames);
297
			$_SESSION["listofmimes".$keytoavoidconflict] = join(';', $listofmimes);
298
			//var_dump($_SESSION['listofpaths']);
299
		}
300
	}
301
302
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
303
	/**
304
	 * Return list of attached files (stored in SECTION array)
305
	 *
306
	 * @return	array       array('paths'=> ,'names'=>, 'mimes'=> )
307
	 */
308
	public function get_attached_files()
309
	{
310
		// phpcs:enable
311
		$listofpaths = array();
312
		$listofnames = array();
313
		$listofmimes = array();
314
315
		$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
316
		if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
317
			$listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
318
		}
319
		if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
320
			$listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
321
		}
322
		if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
323
			$listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
324
		}
325
		return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes);
326
	}
327
328
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
329
	/**
330
	 *	Show the form to input an email
331
	 *  this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
332
	 *  this->withmaindocfile
333
	 *
334
	 *	@param	string	$addfileaction		Name of action when posting file attachments
335
	 *	@param	string	$removefileaction	Name of action when removing file attachments
336
	 *	@return	void
337
	 *  @deprecated
338
	 */
339
	public function show_form($addfileaction = 'addfile', $removefileaction = 'removefile')
340
	{
341
		// phpcs:enable
342
		print $this->get_form($addfileaction, $removefileaction);
343
	}
344
345
	// phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
346
	/**
347
	 *	Get the form to input an email
348
	 *  this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
349
	 *  this->param:	Contains more parameters like email templates info
350
	 *  this->withfckeditor: 1=We use an advanced editor, so we switch content into HTML
351
	 *
352
	 *	@param	string	$addfileaction		Name of action when posting file attachments
353
	 *	@param	string	$removefileaction	Name of action when removing file attachments
354
	 *	@return string						Form to show
355
	 */
356
	public function get_form($addfileaction = 'addfile', $removefileaction = 'removefile')
357
	{
358
		// phpcs:enable
359
		global $conf, $langs, $user, $hookmanager, $form;
360
361
		// Required to show preview wof mail attachments
362
		require_once DOL_DOCUMENT_ROOT.'/core/class/html.formfile.class.php';
363
		$formfile = new Formfile($this->db);
364
365
		if (!is_object($form)) {
366
			$form = new Form($this->db);
367
		}
368
369
		// Load translation files required by the page
370
		$langs->loadLangs(array('other', 'mails', 'members'));
371
372
		// Clear temp files. Must be done before call of triggers, at beginning (mode = init), or when we select a new template
373
		if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelselected') && GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
374
			$this->clear_attached_files();
375
		}
376
377
		// Call hook getFormMail
378
		$hookmanager->initHooks(array('formmail'));
379
380
		$parameters = array(
381
			'addfileaction' => $addfileaction,
382
			'removefileaction'=> $removefileaction,
383
			'trackid'=> $this->trackid
384
		);
385
		$reshook = $hookmanager->executeHooks('getFormMail', $parameters, $this);
386
387
		if (!empty($reshook)) {
388
			return $hookmanager->resPrint;
389
		} else {
390
			$out = '';
391
392
			$disablebademails = 1;
393
394
			// Define output language
395
			$outputlangs = $langs;
396
			$newlang = '';
397
			if ($conf->global->MAIN_MULTILANGS && empty($newlang)) {
398
				$newlang = $this->param['langsmodels'];
399
			}
400
			if (!empty($newlang)) {
401
				$outputlangs = new Translate("", $conf);
402
				$outputlangs->setDefaultLang($newlang);
403
				$outputlangs->load('other');
404
			}
405
406
			// Get message template for $this->param["models"] into c_email_templates
407
			$arraydefaultmessage = -1;
408
			if ($this->param['models'] != 'none') {
409
				$model_id = 0;
410
				if (array_key_exists('models_id', $this->param)) {
411
					$model_id = $this->param["models_id"];
412
				}
413
414
				$arraydefaultmessage = $this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id); // If $model_id is empty, preselect the first one
415
			}
416
417
			// Define list of attached files
418
			$listofpaths = array();
419
			$listofnames = array();
420
			$listofmimes = array();
421
			$keytoavoidconflict = empty($this->trackid) ? '' : '-'.$this->trackid; // this->trackid must be defined
422
423
			if (GETPOST('mode', 'alpha') == 'init' || (GETPOST('modelselected') && GETPOST('modelmailselected', 'alpha') && GETPOST('modelmailselected', 'alpha') != '-1')) {
424
				if (!empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit'])) {
425
					foreach ($this->param['fileinit'] as $file) {
426
						$this->add_attached_files($file, basename($file), dol_mimetype($file));
427
					}
428
				}
429
			}
430
431
			if (!empty($_SESSION["listofpaths".$keytoavoidconflict])) {
432
				$listofpaths = explode(';', $_SESSION["listofpaths".$keytoavoidconflict]);
433
			}
434
			if (!empty($_SESSION["listofnames".$keytoavoidconflict])) {
435
				$listofnames = explode(';', $_SESSION["listofnames".$keytoavoidconflict]);
436
			}
437
			if (!empty($_SESSION["listofmimes".$keytoavoidconflict])) {
438
				$listofmimes = explode(';', $_SESSION["listofmimes".$keytoavoidconflict]);
439
			}
440
441
442
			$out .= "\n".'<!-- Begin form mail type='.$this->param["models"].' --><div id="mailformdiv"></div>'."\n";
443
			if ($this->withform == 1) {
444
				$out .= '<form method="POST" name="mailform" id="mailform" enctype="multipart/form-data" action="'.$this->param["returnurl"].'#formmail">'."\n";
445
446
				$out .= '<a id="formmail" name="formmail"></a>';
447
				$out .= '<input style="display:none" type="submit" id="sendmailhidden" name="sendmail">';
448
				$out .= '<input type="hidden" name="token" value="'.newToken().'" />';
449
				$out .= '<input type="hidden" name="trackid" value="'.$this->trackid.'" />';
450
			}
451
			if (!empty($this->withfrom)) {
452
				if (!empty($this->withfromreadonly)) {
453
					$out .= '<input type="hidden" id="fromname" name="fromname" value="'.$this->fromname.'" />';
454
					$out .= '<input type="hidden" id="frommail" name="frommail" value="'.$this->frommail.'" />';
455
				}
456
			}
457
			foreach ($this->param as $key => $value) {
458
				if (is_array($value)) {
459
					$out .= "<!-- param key=".$key." is array, we do not output input filed for it -->\n";
460
				} else {
461
					$out .= '<input type="hidden" id="'.$key.'" name="'.$key.'" value="'.$value.'" />'."\n";
462
				}
463
			}
464
465
			$modelmail_array = array();
466
			if ($this->param['models'] != 'none') {
467
				$result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
468
				if ($result < 0) {
469
					setEventMessages($this->error, $this->errors, 'errors');
470
				}
471
472
				foreach ($this->lines_model as $line) {
473
					$reg = array();
474
					if (preg_match('/\((.*)\)/', $line->label, $reg)) {
475
						$labeltouse = $langs->trans($reg[1]); // langs->trans when label is __(xxx)__
476
					} else {
477
						$labeltouse = $line->label;
478
					}
479
480
					// We escape the $labeltouse to store it into $modelmail_array.
481
					$modelmail_array[$line->id] = dol_escape_htmltag($labeltouse);
482
					if ($line->lang) {
483
						$modelmail_array[$line->id] .= ' '.picto_from_langcode($line->lang);
484
					}
485
					if ($line->private) {
486
						$modelmail_array[$line->id] .= ' - <span class="opacitymedium">'.dol_escape_htmltag($langs->trans("Private")).'</span>';
487
					}
488
				}
489
			}
490
491
			// Zone to select email template
492
			if (count($modelmail_array) > 0) {
493
				$model_mail_selected_id = GETPOSTISSET('modelmailselected') ? GETPOST('modelmailselected', 'int') : ($arraydefaultmessage->id > 0 ? $arraydefaultmessage->id : 0);
494
495
				// If list of template is filled
496
				$out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
497
498
				$out .= '<span class="opacitymedium">'.$langs->trans('SelectMailModel').':</span> ';
499
500
				$out .= $this->selectarray('modelmailselected', $modelmail_array, $model_mail_selected_id, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100', 1, '', 0, 1);
501
				if ($user->admin) {
502
					$out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
503
				}
504
505
				$out .= ' &nbsp; ';
506
				$out .= '<input type="submit" class="button reposition" value="'.$langs->trans('Apply').'" name="modelselected" id="modelselected">';
507
				$out .= ' &nbsp; ';
508
				$out .= '</div>';
509
			} elseif (!empty($this->param['models']) && in_array($this->param['models'], array(
510
					'propal_send', 'order_send', 'facture_send',
511
					'shipping_send', 'fichinter_send', 'supplier_proposal_send', 'order_supplier_send',
512
					'invoice_supplier_send', 'thirdparty', 'contract', 'user', 'recruitmentcandidature_send', 'all'
513
				))) {
514
				// If list of template is empty
515
				$out .= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
516
				$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.
517
				if ($user->admin) {
518
					$out .= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')), 1);
519
				}
520
				$out .= ' &nbsp; ';
521
				$out .= '<input type="submit" class="button" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
522
				$out .= ' &nbsp; ';
523
				$out .= '</div>';
524
			} else {
525
				$out .= '<!-- No template available for $this->param["models"] = '.$this->param['models'].' -->';
526
			}
527
528
529
			$out .= '<table class="tableforemailform boxtablenotop centpercent">'."\n";
530
531
			// Substitution array/string
532
			$helpforsubstitution = '';
533
			if (is_array($this->substit) && count($this->substit)) {
534
				$helpforsubstitution .= $langs->trans('AvailableVariables').' :<br>'."\n";
535
			}
536
			foreach ($this->substit as $key => $val) {
537
				$helpforsubstitution .= $key.' -> '.$langs->trans(dol_string_nohtmltag(dolGetFirstLineOfText($val))).'<br>';
538
			}
539
			if (!empty($this->withsubstit)) {	// Unset or set ->withsubstit=0 to disable this.
540
				$out .= '<tr><td colspan="2" class="right">';
541
				//$out.='<div class="floatright">';
542
				if (is_numeric($this->withsubstit)) {
543
					$out .= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage
544
				} else {
545
					$out .= $form->textwithpicto($langs->trans('AvailableVariables'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // New usage
546
				}
547
				$out .= "</td></tr>\n";
548
				//$out.='</div>';
549
			}
550
551
			// From
552
			if (!empty($this->withfrom)) {
553
				if (!empty($this->withfromreadonly)) {
554
					$out .= '<tr><td class="fieldrequired minwidth200">'.$langs->trans("MailFrom").'</td><td>';
555
556
					// $this->fromtype is the default value to use to select sender
557
					if (!($this->fromtype === 'user' && $this->fromid > 0)
558
						&& !($this->fromtype === 'company')
559
						&& !($this->fromtype === 'robot')
560
						&& !preg_match('/user_aliases/', $this->fromtype)
561
						&& !preg_match('/global_aliases/', $this->fromtype)
562
						&& !preg_match('/senderprofile/', $this->fromtype)
563
						) {
564
						// Use this->fromname and this->frommail or error if not defined
565
						$out .= $this->fromname;
566
						if ($this->frommail) {
567
							$out .= ' &lt;'.$this->frommail.'&gt;';
568
						} else {
569
							if ($this->fromtype) {
570
								$langs->load('errors');
571
								$out .= '<span class="warning"> &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt; </span>';
572
							}
573
						}
574
					} else {
575
						$liste = array();
576
577
						// Add user email
578
						if (empty($user->email)) {
579
							$langs->load('errors');
580
							$liste['user'] = $user->getFullName($langs).' &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt;';
581
						} else {
582
							$liste['user'] = $user->getFullName($langs).' &lt;'.$user->email.'&gt;';
583
						}
584
585
						// Add also company main email
586
						$liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM.' &lt;'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'&gt;';
587
588
						// Add also email aliases if there is some
589
						$listaliases = array(
590
							'user_aliases' => (empty($user->email_aliases) ? '' : $user->email_aliases),
591
							'global_aliases' => getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES'),
592
						);
593
594
						// Also add robot email
595
						if (!empty($this->fromalsorobot)) {
596
							if (!empty($conf->global->MAIN_MAIL_EMAIL_FROM) && $conf->global->MAIN_MAIL_EMAIL_FROM != $conf->global->MAIN_INFO_SOCIETE_MAIL) {
597
								$liste['robot'] = $conf->global->MAIN_MAIL_EMAIL_FROM;
598
								if ($this->frommail) {
599
									$liste['robot'] .= ' &lt;'.$conf->global->MAIN_MAIL_EMAIL_FROM.'&gt;';
600
								}
601
							}
602
						}
603
604
						// Add also email aliases from the c_email_senderprofile table
605
						$sql = "SELECT rowid, label, email FROM ".$this->db->prefix()."c_email_senderprofile";
606
						$sql .= " WHERE active = 1 AND (private = 0 OR private = ".((int) $user->id).")";
607
						$sql .= " ORDER BY position";
608
						$resql = $this->db->query($sql);
609
						if ($resql) {
610
							$num = $this->db->num_rows($resql);
611
							$i = 0;
612
							while ($i < $num) {
613
								$obj = $this->db->fetch_object($resql);
614
								if ($obj) {
615
									$listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>';
616
								}
617
								$i++;
618
							}
619
						} else {
620
							dol_print_error($this->db);
621
						}
622
623
						foreach ($listaliases as $typealias => $listalias) {
624
							$posalias = 0;
625
							$listaliasarray = explode(',', $listalias);
626
							foreach ($listaliasarray as $listaliasval) {
627
								$posalias++;
628
								$listaliasval = trim($listaliasval);
629
								if ($listaliasval) {
630
									$listaliasval = preg_replace('/</', '&lt;', $listaliasval);
631
									$listaliasval = preg_replace('/>/', '&gt;', $listaliasval);
632
									if (!preg_match('/&lt;/', $listaliasval)) {
633
										$listaliasval = '&lt;'.$listaliasval.'&gt;';
634
									}
635
									$liste[$typealias.'_'.$posalias] = $listaliasval;
636
								}
637
							}
638
						}
639
640
						// Set the default "From"
641
						$defaultfrom = '';
642
						$reshook = $hookmanager->executeHooks('getDefaultFromEmail', $parameters, $this);
643
						if (empty($reshook)) {
644
							$defaultfrom = $this->fromtype;
645
						}
646
						if (!empty($hookmanager->resArray['defaultfrom'])) {
647
							$defaultfrom = $hookmanager->resArray['defaultfrom'];
648
						}
649
650
						// Using combo here make the '<email>' no more visible on list.
651
						//$out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 1, '', $disablebademails);
652
						$out .= ' '.$form->selectarray('fromtype', $liste, $defaultfrom, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 0, '', $disablebademails);
653
					}
654
655
					$out .= "</td></tr>\n";
656
				} else {
657
					$out .= '<tr><td class="fieldrequired width200">'.$langs->trans("MailFrom")."</td><td>";
658
					$out .= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" class="maxwidth200onsmartphone" value="'.$this->fromname.'" />';
659
					$out .= '&nbsp; &nbsp; ';
660
					$out .= $langs->trans("EMail").':&lt;<input type="text" id="frommail" name="frommail" class="maxwidth200onsmartphone" value="'.$this->frommail.'" />&gt;';
661
					$out .= "</td></tr>\n";
662
				}
663
			}
664
665
			// To
666
			if (!empty($this->withto) || is_array($this->withto)) {
667
				$out .= $this->getHtmlForTo();
668
			}
669
670
			// To User
671
			if (!empty($this->withtouser) && is_array($this->withtouser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
672
				$out .= '<tr><td>';
673
				$out .= $langs->trans("MailToUsers");
674
				$out .= '</td><td>';
675
676
				// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
677
				$tmparray = $this->withtouser;
678
				foreach ($tmparray as $key => $val) {
679
					$tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
680
				}
681
				$withtoselected = GETPOST("receiveruser", 'array'); // Array of selected value
682
				if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
683
					$withtoselected = array_keys($tmparray);
684
				}
685
				$out .= $form->multiselectarray("receiveruser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
686
				$out .= "</td></tr>\n";
687
			}
688
689
			// With option one email per recipient
690
			if (!empty($this->withoptiononeemailperrecipient)) {
691
				if (abs($this->withoptiononeemailperrecipient) == 1) {
692
					$out .= '<tr><td class="minwidth200">';
693
					$out .= $langs->trans("GroupEmails");
694
					$out .= '</td><td>';
695
					$out .= ' <input type="checkbox" id="oneemailperrecipient" value="1" name="oneemailperrecipient"'.($this->withoptiononeemailperrecipient > 0 ? ' checked="checked"' : '').'> ';
696
					$out .= '<label for="oneemailperrecipient">'.$langs->trans("OneEmailPerRecipient").'</label>';
697
					$out .= '<span class="hideonsmartphone opacitymedium">';
698
					$out .= ' - ';
699
					$out .= $langs->trans("WarningIfYouCheckOneRecipientPerEmail");
700
					$out .= '</span>';
701
					$out .= '</td></tr>';
702
				} else {
703
					$out .= '<tr><td><input type="hidden" name="oneemailperrecipient" value="1"></td><td></td></tr>';
704
				}
705
			}
706
707
			// CC
708
			if (!empty($this->withtocc) || is_array($this->withtocc)) {
709
				$out .= $this->getHtmlForCc();
710
			}
711
712
			// To User cc
713
			if (!empty($this->withtoccuser) && is_array($this->withtoccuser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT)) {
714
				$out .= '<tr><td>';
715
				$out .= $langs->trans("MailToCCUsers");
716
				$out .= '</td><td>';
717
718
				// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
719
				$tmparray = $this->withtoccuser;
720
				foreach ($tmparray as $key => $val) {
721
					$tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
722
				}
723
				$withtoselected = GETPOST("receiverccuser", 'array'); // Array of selected value
724
				if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
725
					$withtoselected = array_keys($tmparray);
726
				}
727
				$out .= $form->multiselectarray("receiverccuser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
728
				$out .= "</td></tr>\n";
729
			}
730
731
			// CCC
732
			if (!empty($this->withtoccc) || is_array($this->withtoccc)) {
733
				$out .= $this->getHtmlForWithCcc();
734
			}
735
736
			// Replyto
737
			if (!empty($this->withreplyto)) {
0 ignored issues
show
Bug introduced by
The property withreplyto does not exist on FormMail. Did you mean withreplytoreadonly?
Loading history...
738
				if ($this->withreplytoreadonly) {
739
					$out .= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
740
					$out .= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
741
					$out .= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail ? (" &lt;".$this->replytomail."&gt;") : "");
742
					$out .= "</td></tr>\n";
743
				}
744
			}
745
746
			// Errorsto
747
			if (!empty($this->witherrorsto)) {
748
				$out .= $this->getHtmlForWithErrorsTo();
749
			}
750
751
			// Ask delivery receipt
752
			if (!empty($this->withdeliveryreceipt)) {
753
				$out .= $this->getHtmlForDeliveryReceipt();
754
			}
755
756
			// Topic
757
			if (!empty($this->withtopic)) {
758
				$out .= $this->getHtmlForTopic($arraydefaultmessage, $helpforsubstitution);
759
			}
760
761
			// Attached files
762
			if (!empty($this->withfile)) {
763
				$out .= '<tr>';
764
				$out .= '<td>'.$langs->trans("MailFile").'</td>';
765
766
				$out .= '<td>';
767
768
				if ($this->withmaindocfile) {
769
					// withmaindocfile is set to 1 or -1 to show the checkbox (-1 = checked or 1 = not checked)
770
					if (GETPOSTISSET('sendmail')) {
771
						$this->withmaindocfile = (GETPOST('addmaindocfile', 'alpha') ? -1 : 1);
772
					} elseif (is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0) {
773
						// If a template was selected, we use setup of template to define if join file checkbox is selected or not.
774
						$this->withmaindocfile = ($arraydefaultmessage->joinfiles ? -1 : 1);
775
					}
776
				}
777
778
				if (!empty($this->withmaindocfile)) {
779
					if ($this->withmaindocfile == 1) {
780
						$out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" />';
781
					} elseif ($this->withmaindocfile == -1) {
782
						$out .= '<input type="checkbox" id="addmaindocfile" name="addmaindocfile" value="1" checked="checked" />';
783
					}
784
					$out .= ' <label for="addmaindocfile">'.$langs->trans("JoinMainDoc").'.</label><br>';
785
				}
786
787
				if (is_numeric($this->withfile)) {
788
					// TODO Trick to have param removedfile containing nb of file to delete. But this does not works without javascript
789
					$out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
790
					$out .= '<script type="text/javascript">';
791
					$out .= 'jQuery(document).ready(function () {';
792
					$out .= '    jQuery(".removedfile").click(function() {';
793
					$out .= '        jQuery(".removedfilehidden").val(jQuery(this).val());';
794
					$out .= '    });';
795
					$out .= '})';
796
					$out .= '</script>'."\n";
797
					if (count($listofpaths)) {
798
						foreach ($listofpaths as $key => $val) {
799
							$relativepathtofile = substr($val, (strlen(DOL_DATA_ROOT) - strlen($val)));
800
801
							if ($conf->entity > 1) {
802
								$relativepathtofile = str_replace($conf->entity.'/', '', $relativepathtofile);
803
							}
804
							// Try to extract data from full path
805
							$formfile_params = array();
806
							preg_match('#^(/)(\w+)(/)(.+)$#', $relativepathtofile, $formfile_params);
807
808
							$out .= '<div id="attachfile_'.$key.'">';
809
							// Preview of attachment
810
							$out .= img_mime($listofnames[$key]).' '.$listofnames[$key];
811
812
							$out .= $formfile->showPreview(array(), $formfile_params[2], $formfile_params[4]);
813
							if (!$this->withfilereadonly) {
814
								$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.'" />';
815
								//$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
816
							}
817
							$out .= '<br></div>';
818
						}
819
					} elseif (empty($this->withmaindocfile)) {
820
						$out .= '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
821
					}
822
					if ($this->withfile == 2) {
823
						// Can add other files
824
						if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) {
825
							$out .= '<input type="file" class="flat" id="addedfile" name="addedfile[]" value="'.$langs->trans("Upload").'" multiple />';
826
						} else {
827
							$out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
828
						}
829
						$out .= ' ';
830
						$out .= '<input type="submit" class="button" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
831
					}
832
				} else {
833
					$out .= $this->withfile;
834
				}
835
836
				$out .= "</td></tr>\n";
837
			}
838
839
			// Message
840
			if (!empty($this->withbody)) {
841
				$defaultmessage = GETPOST('message', 'restricthtml');
842
				if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
843
					if ($arraydefaultmessage && $arraydefaultmessage->content) {
844
						$defaultmessage = $arraydefaultmessage->content;
845
					} elseif (!is_numeric($this->withbody)) {
846
						$defaultmessage = $this->withbody;
847
					}
848
				}
849
850
				// Complete substitution array with the url to make online payment
851
				$paymenturl = '';
852
				$validpaymentmethod = array();
853
				if (empty($this->substit['__REF__'])) {
854
					$paymenturl = '';
855
				} else {
856
					// Set the online payment url link into __ONLINE_PAYMENT_URL__ key
857
					require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
858
					$langs->loadLangs(array('paypal', 'other'));
859
					$typeforonlinepayment = 'free';
860
					if ($this->param["models"] == 'order' || $this->param["models"] == 'order_send') {
861
						$typeforonlinepayment = 'order'; // TODO use detection on something else than template
862
					}
863
					if ($this->param["models"] == 'invoice' || $this->param["models"] == 'facture_send') {
864
						$typeforonlinepayment = 'invoice'; // TODO use detection on something else than template
865
					}
866
					if ($this->param["models"] == 'member') {
867
						$typeforonlinepayment = 'member'; // TODO use detection on something else than template
868
					}
869
					$url = getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']);
870
					$paymenturl = $url;
871
872
					$validpaymentmethod = getValidOnlinePaymentMethods('');
873
				}
874
875
				if (count($validpaymentmethod) > 0 && $paymenturl) {
876
					$langs->load('other');
877
					$this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = str_replace('\n', "\n", $langs->transnoentities("PredefinedMailContentLink", $paymenturl));
878
					$this->substit['__ONLINE_PAYMENT_URL__'] = $paymenturl;
879
				} else {
880
					$this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = '';
881
					$this->substit['__ONLINE_PAYMENT_URL__'] = '';
882
				}
883
884
				$this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'] = '';
885
886
				// Add lines substitution key from each line
887
				$lines = '';
888
				$defaultlines = $arraydefaultmessage->content_lines;
889
				if (isset($defaultlines)) {
890
					foreach ($this->substit_lines as $substit_line) {
891
						$lines .= make_substitutions($defaultlines, $substit_line)."\n";
892
					}
893
				}
894
				$this->substit['__LINES__'] = $lines;
895
896
				$defaultmessage = str_replace('\n', "\n", $defaultmessage);
897
898
				// Deal with format differences between message and some substitution variables (text / HTML)
899
				$atleastonecomponentishtml = 0;
900
				if (strpos($defaultmessage, '__USER_SIGNATURE__') !== false && dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
901
					$atleastonecomponentishtml++;
902
				}
903
				if (strpos($defaultmessage, '__ONLINE_PAYMENT_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
904
					$atleastonecomponentishtml++;
905
				}
906
				if (strpos($defaultmessage, '__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__') !== false && dol_textishtml($this->substit['__ONLINE_INTERVIEW_SCHEDULER_TEXT_AND_URL__'])) {
907
					$atleastonecomponentishtml++;
908
				}
909
				if (dol_textishtml($defaultmessage)) {
910
					$atleastonecomponentishtml++;
911
				}
912
				if ($atleastonecomponentishtml) {
913
					if (!dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
914
						$this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']);
915
					}
916
					if (!dol_textishtml($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'])) {
917
						$this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__'] = dol_nl2br($this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']);
918
					}
919
					if (!dol_textishtml($defaultmessage)) {
920
						$defaultmessage = dol_nl2br($defaultmessage);
921
					}
922
				}
923
924
				if (GETPOSTISSET("message") && !GETPOST('modelselected')) {
925
					$defaultmessage = GETPOST("message", "restricthtml");
926
				} else {
927
					$defaultmessage = make_substitutions($defaultmessage, $this->substit);
928
					// Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
929
					$defaultmessage = preg_replace("/^(<br>)+/", "", $defaultmessage);
930
					$defaultmessage = preg_replace("/^\n+/", "", $defaultmessage);
931
				}
932
933
				$out .= '<tr>';
934
				$out .= '<td class="tdtop">';
935
				$out .= $form->textwithpicto($langs->trans('MailText'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfrombody');
936
				$out .= '</td>';
937
				$out .= '<td>';
938
				if ($this->withbodyreadonly) {
939
					$out .= nl2br($defaultmessage);
940
					$out .= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />';
941
				} else {
942
					if (!isset($this->ckeditortoolbar)) {
943
						$this->ckeditortoolbar = 'dolibarr_notes';
944
					}
945
946
					// Editor wysiwyg
947
					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
948
					if ($this->withfckeditor == -1) {
949
						if (!empty($conf->global->FCKEDITOR_ENABLE_MAIL)) {
950
							$this->withfckeditor = 1;
951
						} else {
952
							$this->withfckeditor = 0;
953
						}
954
					}
955
956
					$doleditor = new DolEditor('message', $defaultmessage, '', 280, $this->ckeditortoolbar, 'In', true, true, $this->withfckeditor, 8, '95%');
957
					$out .= $doleditor->Create(1);
958
				}
959
				$out .= "</td></tr>\n";
960
			}
961
962
			$out .= '</table>'."\n";
963
964
			if ($this->withform == 1 || $this->withform == -1) {
965
				$out .= '<div class="center">';
966
				$out .= '<input type="submit" class="button button-add" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
967
				// Add a javascript test to avoid to forget to submit file before sending email
968
				if ($this->withfile == 2 && $conf->use_javascript_ajax) {
969
					$out .= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
970
				}
971
				$out .= ' />';
972
				if ($this->withcancel) {
973
					$out .= '<input class="button button-cancel" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
974
				}
975
				$out .= '</div>'."\n";
976
			}
977
978
			if ($this->withform == 1) {
979
				$out .= '</form>'."\n";
980
			}
981
982
			// Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
983
			if (!empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY)) {
984
				$out .= '<script type="text/javascript">';
985
				$out .= 'jQuery(document).ready(function () {';
986
				$out .= '	$(document).on("keypress", \'#mailform\', function (e) {		/* Note this is called at every key pressed ! */
987
	    						var code = e.keyCode || e.which;
988
	    						if (code == 13) {
989
									console.log("Enter was intercepted and blocked");
990
	        						e.preventDefault();
991
	        						return false;
992
	    						}
993
							});';
994
				$out .= '		})';
995
				$out .= '</script>';
996
			}
997
998
			$out .= "<!-- End form mail -->\n";
999
1000
			return $out;
1001
		}
1002
	}
1003
1004
	/**
1005
	 * get html For To
1006
	 *
1007
	 * @return string html
1008
	 */
1009
	public function getHtmlForTo()
1010
	{
1011
		global $langs, $form;
1012
		$out = '<tr><td class="fieldrequired">';
1013
		if ($this->withtofree) {
1014
			$out .= $form->textwithpicto($langs->trans("MailTo"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
1015
		} else {
1016
			$out .= $langs->trans("MailTo");
1017
		}
1018
		$out .= '</td><td>';
1019
		if ($this->withtoreadonly) {
1020
			if (!empty($this->toname) && !empty($this->tomail)) {
1021
				$out .= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
1022
				$out .= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
1023
				if ($this->totype == 'thirdparty') {
1024
					$soc = new Societe($this->db);
1025
					$soc->fetch($this->toid);
1026
					$out .= $soc->getNomUrl(1);
1027
				} elseif ($this->totype == 'contact') {
1028
					$contact = new Contact($this->db);
1029
					$contact->fetch($this->toid);
1030
					$out .= $contact->getNomUrl(1);
1031
				} else {
1032
					$out .= $this->toname;
1033
				}
1034
				$out .= ' &lt;'.$this->tomail.'&gt;';
1035
				if ($this->withtofree) {
1036
					$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) : "").'" />';
1037
				}
1038
			} else {
1039
				// Note withto may be a text like 'AllRecipientSelected'
1040
				$out .= (!is_array($this->withto) && !is_numeric($this->withto)) ? $this->withto : "";
1041
			}
1042
		} else {
1043
			// The free input of email
1044
			if (!empty($this->withtofree)) {
1045
				$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) : "")).'" />';
1046
			}
1047
			// The select combo
1048
			if (!empty($this->withto) && is_array($this->withto)) {
1049
				if (!empty($this->withtofree)) {
1050
					$out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
1051
				}
1052
				// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
1053
				$tmparray = $this->withto;
1054
				foreach ($tmparray as $key => $val) {
1055
					$tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
1056
				}
1057
1058
				$withtoselected = GETPOST("receiver", 'array'); // Array of selected value
1059
1060
				if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action', 'aZ09') == 'presend') {
1061
					$withtoselected = array_keys($tmparray);
1062
				}
1063
				$out .= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
1064
			}
1065
		}
1066
		$out .= "</td></tr>\n";
1067
		return $out;
1068
	}
1069
1070
	/**
1071
	 * get html For CC
1072
	 *
1073
	 * @return string html
1074
	 */
1075
	public function getHtmlForCc()
1076
	{
1077
		global $langs, $form;
1078
		$out = '<tr><td>';
1079
		$out .= $form->textwithpicto($langs->trans("MailCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
1080
		$out .= '</td><td>';
1081
		if ($this->withtoccreadonly) {
1082
			$out .= (!is_array($this->withtocc) && !is_numeric($this->withtocc)) ? $this->withtocc : "";
1083
		} else {
1084
			$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 : '')).'" />';
1085
			if (!empty($this->withtocc) && is_array($this->withtocc)) {
0 ignored issues
show
introduced by
The condition is_array($this->withtocc) is always false.
Loading history...
1086
				$out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
1087
				// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
1088
				$tmparray = $this->withtocc;
1089
				foreach ($tmparray as $key => $val) {
1090
					$tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
1091
				}
1092
				$withtoccselected = GETPOST("receivercc", 'array'); // Array of selected value
1093
				$out .= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500', null, "");
1094
			}
1095
		}
1096
		$out .= "</td></tr>\n";
1097
		return $out;
1098
	}
1099
1100
	/**
1101
	 * get html For WithCCC
1102
	 *
1103
	 * @return string html
1104
	 */
1105
	public function getHtmlForWithCcc()
1106
	{
1107
		global $conf, $langs, $form;
1108
		$out = '<tr><td>';
1109
		$out .= $form->textwithpicto($langs->trans("MailCCC"), $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
1110
		$out .= '</td><td>';
1111
		if (!empty($this->withtocccreadonly)) {
1112
			$out .= (!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : "";
1113
		} else {
1114
			$out .= '<input class="minwidth200" id="sendtoccc" name="sendtoccc" value="'.(GETPOSTISSET("sendtoccc") ? GETPOST("sendtoccc", "alpha") : ((!is_array($this->withtoccc) && !is_numeric($this->withtoccc)) ? $this->withtoccc : '')).'" />';
1115
			if (!empty($this->withtoccc) && is_array($this->withtoccc)) {
0 ignored issues
show
introduced by
The condition is_array($this->withtoccc) is always false.
Loading history...
1116
				$out .= " ".$langs->trans("and")."/".$langs->trans("or")." ";
1117
				// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
1118
				$tmparray = $this->withtoccc;
1119
				foreach ($tmparray as $key => $val) {
1120
					$tmparray[$key] = dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
1121
				}
1122
				$withtocccselected = GETPOST("receiverccc", 'array'); // Array of selected value
1123
				$out .= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null, null, "90%");
1124
			}
1125
		}
1126
1127
		$showinfobcc = '';
1128
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
1129
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO;
1130
		}
1131
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
1132
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO;
1133
		}
1134
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
1135
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO;
1136
		}
1137
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
1138
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO;
1139
		}
1140
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO) && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
1141
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_ORDER_TO;
1142
		}
1143
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO) && !empty($this->param['models']) && $this->param['models'] == 'invoice_supplier_send') {
1144
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_INVOICE_TO;
1145
		}
1146
		if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO) && !empty($this->param['models']) && $this->param['models'] == 'project') {
1147
			$showinfobcc = $conf->global->MAIN_MAIL_AUTOCOPY_PROJECT_TO;
1148
		}
1149
		if ($showinfobcc) {
1150
			$out .= ' + '.$showinfobcc;
1151
		}
1152
		$out .= "</td></tr>\n";
1153
		return $out;
1154
	}
1155
1156
	/**
1157
	 * get Html For WithErrorsTo
1158
	 *
1159
	 * @return string html
1160
	 */
1161
	public function getHtmlForWithErrorsTo()
1162
	{
1163
		global $conf, $langs;
1164
		//if (! $this->errorstomail) $this->errorstomail=$this->frommail;
1165
		$errorstomail = (!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail);
0 ignored issues
show
Bug introduced by
The property errorstomail does not exist on FormMail. Did you mean errors?
Loading history...
1166
		if ($this->witherrorstoreadonly) {
1167
			$out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
1168
			$out .= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
1169
			$out .= $errorstomail;
1170
			$out .= "</td></tr>\n";
1171
		} else {
1172
			$out = '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
1173
			$out .= '<input size="30" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
1174
			$out .= "</td></tr>\n";
1175
		}
1176
		return $out;
1177
	}
1178
1179
	/**
1180
	 * get Html For Asking for Delivery Receipt
1181
	 *
1182
	 * @return string html
1183
	 */
1184
	public function getHtmlForDeliveryreceipt()
1185
	{
1186
		global $conf, $langs, $form;
1187
		$out = '<tr><td>'.$langs->trans("DeliveryReceipt").'</td><td>';
1188
1189
		if (!empty($this->withdeliveryreceiptreadonly)) {
1190
			$out .= yn($this->withdeliveryreceipt);
1191
		} else {
1192
			$defaultvaluefordeliveryreceipt = 0;
1193
			if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && !empty($this->param['models']) && $this->param['models'] == 'propal_send') {
1194
				$defaultvaluefordeliveryreceipt = 1;
1195
			}
1196
			if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && !empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') {
1197
				$defaultvaluefordeliveryreceipt = 1;
1198
			}
1199
			if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_send') {
1200
				$defaultvaluefordeliveryreceipt = 1;
1201
			}
1202
			if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && !empty($this->param['models']) && $this->param['models'] == 'facture_send') {
1203
				$defaultvaluefordeliveryreceipt = 1;
1204
			}
1205
			if (!empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_ORDER) && !empty($this->param['models']) && $this->param['models'] == 'order_supplier_send') {
1206
				$defaultvaluefordeliveryreceipt = 1;
1207
			}
1208
			$out .= $form->selectyesno('deliveryreceipt', (GETPOSTISSET("deliveryreceipt") ? GETPOST("deliveryreceipt") : $defaultvaluefordeliveryreceipt), 1);
1209
		}
1210
		$out .= "</td></tr>\n";
1211
		return $out;
1212
	}
1213
1214
	/**
1215
	 * get Html For Topic of message
1216
	 *
1217
	 * @param	array	$arraydefaultmessage		Array with message template content
1218
	 * @param	string	$helpforsubstitution		Help string for substitution
1219
	 * @return 	string 								Text for topic
1220
	 */
1221
	public function getHtmlForTopic($arraydefaultmessage, $helpforsubstitution)
1222
	{
1223
		global $conf, $langs, $form;
1224
1225
		$defaulttopic = GETPOST('subject', 'restricthtml');
1226
1227
		if (!GETPOST('modelselected', 'alpha') || GETPOST('modelmailselected') != '-1') {
1228
			if ($arraydefaultmessage && $arraydefaultmessage->topic) {
0 ignored issues
show
Bug Best Practice introduced by
The expression $arraydefaultmessage of type array is implicitly converted to a boolean; are you sure this is intended? If so, consider using ! empty($expr) instead to make it clear that you intend to check for an array without elements.

This check marks implicit conversions of arrays to boolean values in a comparison. While in PHP an empty array is considered to be equal (but not identical) to false, this is not always apparent.

Consider making the comparison explicit by using empty(..) or ! empty(...) instead.

Loading history...
1229
				$defaulttopic = $arraydefaultmessage->topic;
1230
			} elseif (!is_numeric($this->withtopic)) {
1231
				$defaulttopic = $this->withtopic;
1232
			}
1233
		}
1234
1235
		$defaulttopic = make_substitutions($defaulttopic, $this->substit);
1236
1237
		$out = '<tr>';
1238
		$out .= '<td class="fieldrequired">';
1239
		$out .= $form->textwithpicto($langs->trans('MailTopic'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfromtopic');
1240
		$out .= '</td>';
1241
		$out .= '<td>';
1242
		if ($this->withtopicreadonly) {
1243
			$out .= $defaulttopic;
1244
			$out .= '<input type="hidden" class="quatrevingtpercent" id="subject" name="subject" value="'.$defaulttopic.'" />';
1245
		} else {
1246
			$out .= '<input type="text" class="quatrevingtpercent" id="subject" name="subject" value="'.((GETPOSTISSET("subject") && !GETPOST('modelselected')) ? GETPOST("subject") : ($defaulttopic ? $defaulttopic : '')).'" />';
1247
		}
1248
		$out .= "</td></tr>\n";
1249
		return $out;
1250
	}
1251
1252
	/**
1253
	 *  Return templates of email with type = $type_template or type = 'all'.
1254
	 *  This search into table c_email_templates. Used by the get_form function.
1255
	 *
1256
	 *  @param	DoliDB		$dbs			Database handler
1257
	 *  @param	string		$type_template	Get message for model/type=$type_template, type='all' also included.
1258
	 *  @param	User		$user			Get template public or limited to this user
1259
	 *  @param	Translate	$outputlangs	Output lang object
1260
	 *  @param	int			$id				Id of template to find, 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)
1261
	 *  @param  int         $active         1=Only active template, 0=Only disabled, -1=All
1262
	 *  @param	string		$label			Label of template
1263
	 *  @return ModelMail|integer			One instance of ModelMail or -1 if error
1264
	 */
1265
	public function getEMailTemplate($dbs, $type_template, $user, $outputlangs, $id = 0, $active = 1, $label = '')
1266
	{
1267
		global $conf, $langs;
1268
1269
		$ret = new ModelMail();
1270
1271
		if ($id == -2 && empty($label)) {
1272
			$this->error = 'LabelIsMandatoryWhenIdIs-2';
1273
			return -1;
1274
		}
1275
1276
		$languagetosearch = (is_object($outputlangs) ? $outputlangs->defaultlang : '');
1277
		// Define $languagetosearchmain to fall back on main language (for example to get 'es_ES' for 'es_MX')
1278
		$tmparray = explode('_', $languagetosearch);
1279
		$languagetosearchmain = $tmparray[0].'_'.strtoupper($tmparray[0]);
1280
		if ($languagetosearchmain == $languagetosearch) {
1281
			$languagetosearchmain = '';
1282
		}
1283
1284
		$sql = "SELECT rowid, module, label, type_template, topic, joinfiles, content, content_lines, lang";
1285
		$sql .= " FROM ".$dbs->prefix().'c_email_templates';
1286
		$sql .= " WHERE (type_template='".$dbs->escape($type_template)."' OR type_template='all')";
1287
		$sql .= " AND entity IN (".getEntity('c_email_templates').")";
1288
		$sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // Get all public or private owned
1289
		if ($active >= 0) {
1290
			$sql .= " AND active = ".((int) $active);
1291
		}
1292
		if ($label) {
1293
			$sql .= " AND label = '".$dbs->escape($label)."'";
1294
		}
1295
		if (!($id > 0) && $languagetosearch) {
1296
			$sql .= " AND (lang = '".$dbs->escape($languagetosearch)."'".($languagetosearchmain ? " OR lang = '".$dbs->escape($languagetosearchmain)."'" : "")." OR lang IS NULL OR lang = '')";
1297
		}
1298
		if ($id > 0) {
1299
			$sql .= " AND rowid=".(int) $id;
1300
		}
1301
		if ($id == -1) {
1302
			$sql .= " AND position=0";
1303
		}
1304
		if ($languagetosearch) {
1305
			$sql .= $dbs->order("position,lang,label", "ASC,DESC,ASC"); // We want line with lang set first, then with lang null or ''
1306
		} else {
1307
			$sql .= $dbs->order("position,lang,label", "ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined
1308
		}
1309
		//$sql .= $dbs->plimit(1);
1310
		//print $sql;
1311
1312
		$resql = $dbs->query($sql);
1313
		if (!$resql) {
1314
			dol_print_error($dbs);
1315
			return -1;
1316
		}
1317
1318
		// Get first found
1319
		while (1) {
1320
			$obj = $dbs->fetch_object($resql);
1321
1322
			if ($obj) {
1323
				// If template is for a module, check module is enabled; if not, take next template
1324
				if ($obj->module) {
1325
					$tempmodulekey = $obj->module;
1326
					if (empty($conf->$tempmodulekey) || empty($conf->$tempmodulekey->enabled)) {
1327
						continue;
1328
					}
1329
				}
1330
1331
				// If a record was found
1332
				$ret->id = $obj->rowid;
1333
				$ret->module = $obj->module;
0 ignored issues
show
Bug introduced by
The property module does not seem to exist on ModelMail.
Loading history...
1334
				$ret->label = $obj->label;
1335
				$ret->lang = $obj->lang;
1336
				$ret->topic = $obj->topic;
1337
				$ret->content = $obj->content;
1338
				$ret->content_lines = $obj->content_lines;
1339
				$ret->joinfiles = $obj->joinfiles;
1340
1341
				break;
1342
			} else {
1343
				// If no record found
1344
				if ($id == -2) {
1345
					// Not found with the provided label
1346
					return -1;
1347
				} else {
1348
					// If there is no template at all
1349
					$defaultmessage = '';
1350
1351
					if ($type_template == 'body') {
1352
						// Special case to use this->withbody as content
1353
						$defaultmessage = $this->withbody;
1354
					} elseif ($type_template == 'facture_send') {
1355
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoice");
1356
					} elseif ($type_template == 'facture_relance') {
1357
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder");
1358
					} elseif ($type_template == 'propal_send') {
1359
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendProposal");
1360
					} elseif ($type_template == 'supplier_proposal_send') {
1361
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal");
1362
					} elseif ($type_template == 'order_send') {
1363
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendOrder");
1364
					} elseif ($type_template == 'order_supplier_send') {
1365
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder");
1366
					} elseif ($type_template == 'invoice_supplier_send') {
1367
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice");
1368
					} elseif ($type_template == 'shipping_send') {
1369
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendShipping");
1370
					} elseif ($type_template == 'fichinter_send') {
1371
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendFichInter");
1372
					} elseif ($type_template == 'actioncomm_send') {
1373
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentSendActionComm");
1374
					} elseif ($type_template == 'thirdparty') {
1375
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentThirdparty");
1376
					} elseif (!empty($type_template)) {
1377
						$defaultmessage = $outputlangs->transnoentities("PredefinedMailContentGeneric");
1378
					}
1379
1380
					$ret->label = 'default';
1381
					$ret->lang = $outputlangs->defaultlang;
1382
					$ret->topic = '';
1383
					$ret->joinfiles = 1;
1384
					$ret->content = $defaultmessage;
1385
					$ret->content_lines = '';
1386
1387
					break;
1388
				}
1389
			}
1390
		}
1391
1392
		$dbs->free($resql);
1393
1394
		return $ret;
1395
	}
1396
1397
	/**
1398
	 *      Find if template exists
1399
	 *      Search into table c_email_templates
1400
	 *
1401
	 * 		@param	string		$type_template	Get message for key module
1402
	 *      @param	User		$user			Use template public or limited to this user
1403
	 *      @param	Translate	$outputlangs	Output lang object
1404
	 *      @return	int		<0 if KO,
1405
	 */
1406
	public function isEMailTemplate($type_template, $user, $outputlangs)
1407
	{
1408
		$sql = "SELECT label, topic, content, lang";
1409
		$sql .= " FROM ".$this->db->prefix().'c_email_templates';
1410
		$sql .= " WHERE type_template='".$this->db->escape($type_template)."'";
1411
		$sql .= " AND entity IN (".getEntity('c_email_templates').")";
1412
		$sql .= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".((int) $user->id).")";
1413
		if (is_object($outputlangs)) {
1414
			$sql .= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')";
1415
		}
1416
		$sql .= $this->db->order("lang,label", "ASC");
1417
		//print $sql;
1418
1419
		$resql = $this->db->query($sql);
1420
		if ($resql) {
1421
			$num = $this->db->num_rows($resql);
1422
			$this->db->free($resql);
1423
			return $num;
1424
		} else {
1425
			$this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1426
			return -1;
1427
		}
1428
	}
1429
1430
	/**
1431
	 *      Find if template exists and are available for current user, then set them into $this->lines_module.
1432
	 *      Search into table c_email_templates
1433
	 *
1434
	 * 		@param	string		$type_template	Get message for key module
1435
	 *      @param	User		$user			Use template public or limited to this user
1436
	 *      @param	Translate	$outputlangs	Output lang object
1437
	 *      @param  int         $active         1=Only active template, 0=Only disabled, -1=All
1438
	 *      @return	int		                    <0 if KO, nb of records found if OK
1439
	 */
1440
	public function fetchAllEMailTemplate($type_template, $user, $outputlangs, $active = 1)
1441
	{
1442
		global $conf;
1443
1444
		$sql = "SELECT rowid, module, label, topic, content, content_lines, lang, fk_user, private, position";
1445
		$sql .= " FROM ".$this->db->prefix().'c_email_templates';
1446
		$sql .= " WHERE type_template IN ('".$this->db->escape($type_template)."', 'all')";
1447
		$sql .= " AND entity IN (".getEntity('c_email_templates').")";
1448
		$sql .= " AND (private = 0 OR fk_user = ".((int) $user->id).")"; // See all public templates or templates I own.
1449
		if ($active >= 0) {
1450
			$sql .= " AND active = ".((int) $active);
1451
		}
1452
		//if (is_object($outputlangs)) $sql.= " AND (lang = '".$this->db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')";	// Return all languages
1453
		$sql .= $this->db->order("position,lang,label", "ASC");
1454
		//print $sql;
1455
1456
		$resql = $this->db->query($sql);
1457
		if ($resql) {
1458
			$num = $this->db->num_rows($resql);
1459
			$this->lines_model = array();
1460
			while ($obj = $this->db->fetch_object($resql)) {
1461
				// If template is for a module, check module is enabled.
1462
				if ($obj->module) {
1463
					$tempmodulekey = $obj->module;
1464
					if (empty($conf->$tempmodulekey) || empty($conf->$tempmodulekey->enabled)) {
1465
						continue;
1466
					}
1467
				}
1468
1469
				$line = new ModelMail();
1470
				$line->id = $obj->rowid;
1471
				$line->label = $obj->label;
1472
				$line->lang = $obj->lang;
1473
				$line->fk_user = $obj->fk_user;
0 ignored issues
show
Bug introduced by
The property fk_user does not seem to exist on ModelMail.
Loading history...
1474
				$line->private = $obj->private;
0 ignored issues
show
Bug introduced by
The property private does not seem to exist on ModelMail.
Loading history...
1475
				$line->position = $obj->position;
0 ignored issues
show
Bug introduced by
The property position does not seem to exist on ModelMail.
Loading history...
1476
				$line->topic = $obj->topic;
1477
				$line->content = $obj->content;
1478
				$line->content_lines = $obj->content_lines;
1479
1480
				$this->lines_model[] = $line;
1481
			}
1482
			$this->db->free($resql);
1483
			return $num;
1484
		} else {
1485
			$this->error = get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1486
			return -1;
1487
		}
1488
	}
1489
1490
1491
1492
	/**
1493
	 * Set substit array from object. This is call when suggesting the email template into forms before sending email.
1494
	 *
1495
	 * @param	CommonObject	$object		   Object to use
1496
	 * @param   Translate  		$outputlangs   Object lang
1497
	 * @return	void
1498
	 * @see getCommonSubstitutionArray()
1499
	 */
1500
	public function setSubstitFromObject($object, $outputlangs)
1501
	{
1502
		global $conf, $user, $extrafields;
1503
1504
		$parameters = array();
1505
		$tmparray = getCommonSubstitutionArray($outputlangs, 0, null, $object);
1506
		complete_substitutions_array($tmparray, $outputlangs, null, $parameters);
1507
1508
		$this->substit = $tmparray;
1509
1510
		// Fill substit_lines with each object lines content
1511
		if (is_array($object->lines)) {
1512
			foreach ($object->lines as $line) {
1513
				$substit_line = array(
1514
					'__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '',
1515
					'__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '',
1516
					'__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '',
1517
					'__LABEL__' => isset($line->label) ? $line->label : '',
1518
					'__DESCRIPTION__' => isset($line->desc) ? $line->desc : '',
1519
					'__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs),
1520
					'__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs),
1521
					'__QUANTITY__' => $line->qty,
1522
					'__SUBPRICE__' => price($line->subprice),
1523
					'__AMOUNT__' => price($line->total_ttc),
1524
					'__AMOUNT_EXCL_TAX__' => price($line->total_ht)
1525
				);
1526
1527
				// Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__
1528
				if (!empty($line->fk_product)) {
1529
					if (!is_object($extrafields)) {
1530
						$extrafields = new ExtraFields($this->db);
1531
					}
1532
					$extrafields->fetch_name_optionals_label('product', true);
1533
					$product = new Product($this->db);
1534
					$product->fetch($line->fk_product, '', '', 1);
1535
					$product->fetch_optionals();
1536
					if (is_array($extrafields->attributes[$product->table_element]['label']) && count($extrafields->attributes[$product->table_element]['label']) > 0) {
1537
						foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
1538
							$substit_line['__PRODUCT_EXTRAFIELD_'.strtoupper($key).'__'] = $product->array_options['options_'.$key];
1539
						}
1540
					}
1541
				}
1542
				$this->substit_lines[] = $substit_line;
1543
			}
1544
		}
1545
	}
1546
1547
	/**
1548
	 * Get list of substitution keys available for emails. This is used for tooltips help.
1549
	 * This include the complete_substitutions_array.
1550
	 *
1551
	 * @param	string	$mode		'formemail', 'formemailwithlines', 'formemailforlines', 'emailing', ...
1552
	 * @param	Object	$object		Object if applicable
1553
	 * @return	array               Array of substitution values for emails.
1554
	 */
1555
	public static function getAvailableSubstitKey($mode = 'formemail', $object = null)
1556
	{
1557
		global $conf, $langs;
1558
1559
		$tmparray = array();
1560
		if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines') {
1561
			$parameters = array('mode'=>$mode);
1562
			$tmparray = getCommonSubstitutionArray($langs, 2, null, $object); // Note: On email templated edition, this is null because it is related to all type of objects
1563
			complete_substitutions_array($tmparray, $langs, null, $parameters);
1564
1565
			if ($mode == 'formwithlines') {
1566
				$tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function
1567
			}
1568
			if ($mode == 'formforlines') {
1569
				$tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function
1570
			}
1571
		}
1572
1573
		if ($mode == 'emailing') {
1574
			$parameters = array('mode'=>$mode);
1575
			$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
1576
			complete_substitutions_array($tmparray, $langs, null, $parameters);
1577
1578
			// For mass emailing, we have different keys
1579
			$tmparray['__ID__'] = 'IdRecord';
1580
			$tmparray['__THIRDPARTY_CUSTOMER_CODE__'] = 'CustomerCode';
1581
			$tmparray['__EMAIL__'] = 'EMailRecipient';
1582
			$tmparray['__LASTNAME__'] = 'Lastname';
1583
			$tmparray['__FIRSTNAME__'] = 'Firstname';
1584
			$tmparray['__MAILTOEMAIL__'] = 'TagMailtoEmail';
1585
			$tmparray['__OTHER1__'] = 'Other1';
1586
			$tmparray['__OTHER2__'] = 'Other2';
1587
			$tmparray['__OTHER3__'] = 'Other3';
1588
			$tmparray['__OTHER4__'] = 'Other4';
1589
			$tmparray['__OTHER5__'] = 'Other5';
1590
			$tmparray['__USER_SIGNATURE__'] = 'TagSignature';
1591
			$tmparray['__CHECK_READ__'] = 'TagCheckMail';
1592
			$tmparray['__UNSUBSCRIBE__'] = 'TagUnsubscribe';
1593
			//,'__PERSONALIZED__' => 'Personalized'	// Hidden because not used yet in mass emailing
1594
1595
			$onlinepaymentenabled = 0;
1596
			if (!empty($conf->paypal->enabled)) {
1597
				$onlinepaymentenabled++;
1598
			}
1599
			if (!empty($conf->paybox->enabled)) {
1600
				$onlinepaymentenabled++;
1601
			}
1602
			if (!empty($conf->stripe->enabled)) {
1603
				$onlinepaymentenabled++;
1604
			}
1605
			if ($onlinepaymentenabled && !empty($conf->global->PAYMENT_SECURITY_TOKEN)) {
1606
				$tmparray['__SECUREKEYPAYMENT__'] = $conf->global->PAYMENT_SECURITY_TOKEN;
1607
				if (!empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE)) {
1608
					if ($conf->adherent->enabled) {
1609
						$tmparray['__SECUREKEYPAYMENT_MEMBER__'] = 'SecureKeyPAYMENTUniquePerMember';
1610
					}
1611
					if ($conf->donation->enabled) {
1612
						$tmparray['__SECUREKEYPAYMENT_DONATION__'] = 'SecureKeyPAYMENTUniquePerDonation';
1613
					}
1614
					if ($conf->facture->enabled) {
1615
						$tmparray['__SECUREKEYPAYMENT_INVOICE__'] = 'SecureKeyPAYMENTUniquePerInvoice';
1616
					}
1617
					if ($conf->commande->enabled) {
1618
						$tmparray['__SECUREKEYPAYMENT_ORDER__'] = 'SecureKeyPAYMENTUniquePerOrder';
1619
					}
1620
					if ($conf->contrat->enabled) {
1621
						$tmparray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = 'SecureKeyPAYMENTUniquePerContractLine';
1622
					}
1623
1624
					//Online payement link
1625
					if ($conf->adherent->enabled) {
1626
						$tmparray['__ONLINEPAYMENTLINK_MEMBER__'] = 'OnlinePaymentLinkUniquePerMember';
1627
					}
1628
					if ($conf->donation->enabled) {
1629
						$tmparray['__ONLINEPAYMENTLINK_DONATION__'] = 'OnlinePaymentLinkUniquePerDonation';
1630
					}
1631
					if ($conf->facture->enabled) {
1632
						$tmparray['__ONLINEPAYMENTLINK_INVOICE__'] = 'OnlinePaymentLinkUniquePerInvoice';
1633
					}
1634
					if ($conf->commande->enabled) {
1635
						$tmparray['__ONLINEPAYMENTLINK_ORDER__'] = 'OnlinePaymentLinkUniquePerOrder';
1636
					}
1637
					if ($conf->contrat->enabled) {
1638
						$tmparray['__ONLINEPAYMENTLINK_CONTRACTLINE__'] = 'OnlinePaymentLinkUniquePerContractLine';
1639
					}
1640
				}
1641
			} else {
1642
				/* No need to show into tooltip help, option is not enabled
1643
				$vars['__SECUREKEYPAYMENT__']='';
1644
				$vars['__SECUREKEYPAYMENT_MEMBER__']='';
1645
				$vars['__SECUREKEYPAYMENT_INVOICE__']='';
1646
				$vars['__SECUREKEYPAYMENT_ORDER__']='';
1647
				$vars['__SECUREKEYPAYMENT_CONTRACTLINE__']='';
1648
				*/
1649
			}
1650
			if (!empty($conf->global->MEMBER_ENABLE_PUBLIC)) {
1651
				$substitutionarray['__PUBLICLINK_NEWMEMBERFORM__'] = 'BlankSubscriptionForm';
0 ignored issues
show
Comprehensibility Best Practice introduced by
$substitutionarray was never initialized. Although not strictly required by PHP, it is generally a good practice to add $substitutionarray = array(); before regardless.
Loading history...
1652
			}
1653
		}
1654
1655
		foreach ($tmparray as $key => $val) {
1656
			if (empty($val)) {
1657
				$tmparray[$key] = $key;
1658
			}
1659
		}
1660
1661
		return $tmparray;
1662
	}
1663
}
1664
1665
1666
/**
1667
 * ModelMail
1668
 */
1669
class ModelMail
1670
{
1671
	/**
1672
	 * @var int ID
1673
	 */
1674
	public $id;
1675
1676
	/**
1677
	 * @var string Model mail label
1678
	 */
1679
	public $label;
1680
1681
	/**
1682
	 * @var string Model mail topic
1683
	 */
1684
	public $topic;
1685
1686
	/**
1687
	 * @var string Model mail content
1688
	 */
1689
	public $content;
1690
	public $content_lines;
1691
	public $lang;
1692
	public $joinfiles;
1693
}
1694