Completed
Branch develop (5b8006)
by
unknown
43:45
created

FormMail::add_attached_files()   C

Complexity

Conditions 8
Paths 128

Size

Total Lines 23
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 17
nc 128
nop 3
dl 0
loc 23
rs 5.3846
c 0
b 0
f 0
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      Marcos García        <[email protected]>
6
 *
7
 * This program is free software; you can redistribute it and/or modify
8
 * it under the terms of the GNU General Public License as published by
9
 * the Free Software Foundation; either version 3 of the License, or
10
 * (at your option) any later version.
11
 *
12
 * This program is distributed in the hope that it will be useful,
13
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15
 * GNU General Public License for more details.
16
 *
17
 * You should have received a copy of the GNU General Public License
18
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
19
 */
20
21
/**
22
 *       \file       htdocs/core/class/html.formmail.class.php
23
 *       \ingroup    core
24
 *       \brief      Fichier de la classe permettant la generation du formulaire html d'envoi de mail unitaire
25
 */
26
require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
27
28
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
	var $db;
38
39
	var $withform;				// 1=Include HTML form tag and show submit button, 0=Do not include form tag and submit button, -1=Do not include form tag but include submit button
40
41
	var $fromname;
42
	var $frommail;
43
	var $replytoname;
44
	var $replytomail;
45
	var $toname;
46
	var $tomail;
47
	var $trackid;
48
49
	var $withsubstit;			// Show substitution array
50
	var $withfrom;
51
	/**
52
	 * @var int
53
	 * @deprecated Fill withto with array before calling method.
54
	 * @see withto
55
	 */
56
	public $withtosocid;
57
	/**
58
	 * @var int|int[]
59
	 */
60
	public $withto;				// Show recipient emails
61
	var $withtofree;			// Show free text for recipient emails
62
	var $withtocc;
63
	var $withtoccc;
64
	var $withtopic;
65
	var $withfile;				// 0=No attaches files, 1=Show attached files, 2=Can add new attached files
66
	var $withmaindocfile;		// 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
67
	var $withbody;
68
69
	var $withfromreadonly;
70
	var $withreplytoreadonly;
71
	var $withtoreadonly;
72
	var $withtoccreadonly;
73
	var $withtocccreadonly;
74
	var $withtopicreadonly;
75
	var $withfilereadonly;
76
	var $withdeliveryreceipt;
77
	var $withcancel;
78
	var $withfckeditor;
79
80
	var $substit=array();
81
	var $substit_lines=array();
82
	var $param=array();
83
84
	var $error;
85
86
	public $lines_model;
87
88
89
	/**
90
	 *	Constructor
91
	 *
92
	 *  @param	DoliDB	$db      Database handler
93
	 */
94
	function __construct($db)
95
	{
96
		$this->db = $db;
97
98
		$this->withform=1;
99
100
		$this->withfrom=1;
101
		$this->withto=1;
102
		$this->withtofree=1;
103
		$this->withtocc=1;
104
		$this->withtoccc=0;
105
		$this->witherrorsto=0;
106
		$this->withtopic=1;
107
		$this->withfile=0;			// 1=Add section "Attached files". 2=Can add files.
108
		$this->withmaindocfile=0;	// 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
109
		$this->withbody=1;
110
111
		$this->withfromreadonly=1;
112
		$this->withreplytoreadonly=1;
113
		$this->withtoreadonly=0;
114
		$this->withtoccreadonly=0;
115
		$this->withtocccreadonly=0;
116
		$this->witherrorstoreadonly=0;
117
		$this->withtopicreadonly=0;
118
		$this->withfilereadonly=0;
119
		$this->withbodyreadonly=0;
120
		$this->withdeliveryreceiptreadonly=0;
121
		$this->withfckeditor=-1;	// -1 = Auto
122
123
		return 1;
0 ignored issues
show
Bug introduced by
Constructors do not have meaningful return values, anything that is returned from here is discarded. Are you sure this is correct?
Loading history...
124
	}
125
126
	/**
127
	 * Clear list of attached files in send mail form (also stored in session)
128
	 *
129
	 * @return	void
130
	 */
131
	function clear_attached_files()
132
	{
133
		global $conf,$user;
134
		require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
135
136
		// Set tmp user directory
137
		$vardir=$conf->user->dir_output."/".$user->id;
138
		$upload_dir = $vardir.'/temp/';                     // TODO Add $keytoavoidconflict in upload_dir path
139
		if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir);
140
141
		$keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
142
		unset($_SESSION["listofpaths".$keytoavoidconflict]);
143
		unset($_SESSION["listofnames".$keytoavoidconflict]);
144
		unset($_SESSION["listofmimes".$keytoavoidconflict]);
145
	}
146
147
	/**
148
	 * Add a file into the list of attached files (stored in SECTION array)
149
	 *
150
	 * @param 	string   $path   Full absolute path on filesystem of file, including file name
151
	 * @param 	string   $file   Only filename (can be basename($path))
152
	 * @param 	string   $type   Mime type (can be dol_mimetype($file))
153
	 * @return	void
154
	 */
155
	function add_attached_files($path, $file='', $type='')
156
	{
157
		$listofpaths=array();
158
		$listofnames=array();
159
		$listofmimes=array();
160
161
		if (empty($file)) $file=basename($path);
162
		if (empty($type)) $type=dol_mimetype($file);
163
164
		$keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
165
		if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
166
		if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
167
		if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
168
		if (! in_array($file,$listofnames))
169
		{
170
			$listofpaths[]=$path;
171
			$listofnames[]=$file;
172
			$listofmimes[]=$type;
173
			$_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
174
			$_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
175
			$_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
176
		}
177
	}
178
179
	/**
180
	 * Remove a file from the list of attached files (stored in SECTION array)
181
	 *
182
	 * @param  	string	$keytodelete     Key in file array (0, 1, 2, ...)
183
	 * @return	void
184
	 */
185
	function remove_attached_files($keytodelete)
186
	{
187
		$listofpaths=array();
188
		$listofnames=array();
189
		$listofmimes=array();
190
191
		$keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
192
		if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
193
		if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
194
		if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
195
		if ($keytodelete >= 0)
196
		{
197
			unset ($listofpaths[$keytodelete]);
198
			unset ($listofnames[$keytodelete]);
199
			unset ($listofmimes[$keytodelete]);
200
			$_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
201
			$_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
202
			$_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
203
			//var_dump($_SESSION['listofpaths']);
204
		}
205
	}
206
207
	/**
208
	 * Return list of attached files (stored in SECTION array)
209
	 *
210
	 * @return	array       array('paths'=> ,'names'=>, 'mimes'=> )
211
	 */
212
	function get_attached_files()
213
	{
214
		$listofpaths=array();
215
		$listofnames=array();
216
		$listofmimes=array();
217
218
		$keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
219
		if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
220
		if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
221
		if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
222
		return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes);
223
	}
224
225
	/**
226
	 *	Show the form to input an email
227
	 *  this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
228
	 *  this->withmaindocfile
229
	 *
230
	 *	@param	string	$addfileaction		Name of action when posting file attachments
231
	 *	@param	string	$removefileaction	Name of action when removing file attachments
232
	 *	@return	void
233
	 */
234
	function show_form($addfileaction='addfile',$removefileaction='removefile')
235
	{
236
		print $this->get_form($addfileaction,$removefileaction);
237
	}
238
239
	/**
240
	 *	Get the form to input an email
241
	 *  this->withfile: 0=No attaches files, 1=Show attached files, 2=Can add new attached files
242
	 *  this->withfile
243
	 *  this->param:	Contains more parameteres like email templates info
244
	 *
245
	 *	@param	string	$addfileaction		Name of action when posting file attachments
246
	 *	@param	string	$removefileaction	Name of action when removing file attachments
247
	 *	@return string						Form to show
248
	 */
249
	function get_form($addfileaction='addfile',$removefileaction='removefile')
0 ignored issues
show
Coding Style introduced by
get_form uses the super-global variable $_REQUEST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
250
	{
251
		global $conf, $langs, $user, $hookmanager, $form;
252
253
		if (! is_object($form)) $form=new Form($this->db);
254
255
		$langs->load("other");
256
		$langs->load("mails");
257
258
259
		// Clear temp files. Must be done at beginning, before call of triggers
260
		if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1'))
261
		{
262
			$this->clear_attached_files();
263
		}
264
265
		// Call hook getFormMail
266
		$hookmanager->initHooks(array('formmail'));
267
268
		$parameters=array(
269
			'addfileaction' => $addfileaction,
270
			'removefileaction'=> $removefileaction,
271
			'trackid'=> $this->trackid
272
		);
273
		$reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this);
274
275
		if (!empty($reshook))
276
		{
277
			return $hookmanager->resPrint;
278
		}
279
		else
280
		{
281
			$out='';
282
283
			$disablebademails=1;
284
285
	   		// Define output language
286
			$outputlangs = $langs;
287
			$newlang = '';
288
			if ($conf->global->MAIN_MULTILANGS && empty($newlang))	$newlang = $this->param['langsmodels'];
289
			if (! empty($newlang))
290
			{
291
				$outputlangs = new Translate("", $conf);
292
				$outputlangs->setDefaultLang($newlang);
293
				$outputlangs->load('other');
294
			}
295
296
			// Get message template for $this->param["models"] into c_email_templates
297
			$arraydefaultmessage=array();
298
			if ($this->param['models'] != 'none')
299
			{
300
				$model_id=0;
301
				if (array_key_exists('models_id',$this->param))
302
				{
303
					$model_id=$this->param["models_id"];
304
				}
305
				$arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, ($model_id ? $model_id : -1));		// we set -1 if model_id empty
306
			}
307
			//var_dump($this->param["models"]);
308
			//var_dump($model_id);
309
			//var_dump($arraydefaultmessage);
310
311
312
			// Define list of attached files
313
			$listofpaths=array();
314
			$listofnames=array();
315
			$listofmimes=array();
316
			$keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid;   // this->trackid must be defined
317
318
			if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1'))
319
			{
320
				if (! empty($arraydefaultmessage['joinfiles']) && is_array($this->param['fileinit']))
321
				{
322
					foreach($this->param['fileinit'] as $file)
323
					{
324
						$this->add_attached_files($file, basename($file), dol_mimetype($file));
325
					}
326
				}
327
			}
328
329
	   		if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
330
	   		if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
331
	   		if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
332
333
334
			$out.= "\n".'<!-- Begin form mail type='.$this->param["models"].' --><div id="mailformdiv"></div>'."\n";
335
			if ($this->withform == 1)
336
			{
337
				$out.= '<form method="POST" name="mailform" id="mailform" enctype="multipart/form-data" action="'.$this->param["returnurl"].'#formmail">'."\n";
338
339
				$out.= '<a id="formmail" name="formmail"></a>';
340
				$out.= '<input style="display:none" type="submit" id="sendmail" name="sendmail">';
341
				$out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'" />';
342
				$out.= '<input type="hidden" name="trackid" value="'.$this->trackid.'" />';
343
			}
344
			if (! empty($this->withfrom))
345
			{
346
				if (! empty($this->withfromreadonly))
347
				{
348
					$out.= '<input type="hidden" id="fromname" name="fromname" value="'.$this->fromname.'" />';
349
					$out.= '<input type="hidden" id="frommail" name="frommail" value="'.$this->frommail.'" />';
350
				}
351
			}
352
			foreach ($this->param as $key=>$value)
353
			{
354
				$out.= '<input type="hidden" id="'.$key.'" name="'.$key.'" value="'.$value.'" />'."\n";
355
			}
356
357
			$modelmail_array=array();
358
			if ($this->param['models'] != 'none')
359
			{
360
				$result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
361
				if ($result < 0)
362
				{
363
					setEventMessages($this->error, $this->errors, 'errors');
364
				}
365
				foreach($this->lines_model as $line)
366
				{
367
					$langs->trans("members");
368
					if (preg_match('/\((.*)\)/', $line->label, $reg))
369
					{
370
						$modelmail_array[$line->id]=$langs->trans($reg[1]);		// langs->trans when label is __(xxx)__
371
					}
372
					else
373
					{
374
						$modelmail_array[$line->id]=$line->label;
375
					}
376
					if ($line->lang) $modelmail_array[$line->id].=' ('.$line->lang.')';
377
					if ($line->private) $modelmail_array[$line->id].=' - '.$langs->trans("Private");
378
					//if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' ';
379
				}
380
			}
381
382
			// Zone to select email template
383
			if (count($modelmail_array)>0)
384
			{
385
				// If list of template is filled
386
				$out.= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
387
				$out.= '<span class="opacitymedium">'.$langs->trans('SelectMailModel').':</span> '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100');
388
				if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1);
389
				$out.= ' &nbsp; ';
390
				$out.= '<input class="button" type="submit" value="'.$langs->trans('Apply').'" name="modelselected" id="modelselected">';
391
				$out.= ' &nbsp; ';
392
				$out.= '</div>';
393
			}
394
			elseif (! empty($this->param['models']) && in_array($this->param['models'], array(
395
					'propal_send','order_send','facture_send',
396
					'shipping_send','fichinter_send','supplier_proposal_send','order_supplier_send',
397
					'invoice_supplier_send','thirdparty','contract','user','all'
398
		   		)))
399
			{
400
				// If list of template is empty
401
				$out.= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
402
				$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.
403
				if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1);
404
				$out.= ' &nbsp; ';
405
				$out.= '<input class="button" type="submit" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
406
				$out.= ' &nbsp; ';
407
				$out.= '</div>';
408
			}
409
410
411
412
			$out.= '<table class="tableforemailform boxtablenotop" width="100%">'."\n";
413
414
			// Substitution array
415
			if (! empty($this->withsubstit))		// Unset or set ->withsubstit=0 to disable this.
416
			{
417
				$out.= '<tr><td colspan="2" align="right">';
418
				//$out.='<div class="floatright">';
419
				$help="";
420
				foreach($this->substit as $key => $val)
421
				{
422
					$help.=$key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'<br>';
423
				}
424
				if (is_numeric($this->withsubstit)) $out.= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $help, 1, 'help', '', 0, 2, 'substittooltip');	// Old usage
425
				else $out.= $form->textwithpicto($langs->trans('AvailableVariables'), $help, 1, 'help', '', 0, 2, 'substittooltip');															// New usage
426
				$out.= "</td></tr>\n";
427
				//$out.='</div>';
428
			}
429
430
			/*var_dump(! empty($this->withfromreadonly));
431
			var_dump($this->withfrom);
432
			var_dump($this->fromtype);
433
			var_dump($this->fromname);*/
434
435
			// From
436
			if (! empty($this->withfrom))
437
			{
438
				if (! empty($this->withfromreadonly))
439
				{
440
					$out.= '<tr><td class="fieldrequired minwidth200">'.$langs->trans("MailFrom").'</td><td>';
441
442
					// $this->fromtype is the default value to use to select sender
443
					if (! ($this->fromtype === 'user' && $this->fromid > 0)
444
						&& ! ($this->fromtype === 'company')
445
						&& ! ($this->fromtype === 'robot')
446
						&& ! preg_match('/user_aliases/', $this->fromtype)
447
						&& ! preg_match('/global_aliases/', $this->fromtype)
448
						&& ! preg_match('/senderprofile/', $this->fromtype)
449
						)
450
					{
451
						// Use this->fromname and this->frommail or error if not defined
452
						$out.= $this->fromname;
453
						if ($this->frommail)
454
						{
455
							$out.= ' &lt;'.$this->frommail.'&gt;';
456
						}
457
						else
458
						{
459
							if ($this->fromtype)
460
							{
461
								$langs->load('errors');
462
								$out.= '<span class="warning"> &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt; </span>';
463
							}
464
						}
465
					} else {
466
						$liste = array();
467
468
						// Add user email
469
						if (empty($user->email))
470
						{
471
							$langs->load('errors');
472
							$liste['user'] = $user->getFullName($langs) . ' &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt;';
473
						}
474
						else
475
						{
476
							$liste['user'] = $user->getFullName($langs) .' &lt;'.$user->email.'&gt;';
477
						}
478
479
						// Add also company main email
480
						$liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' &lt;'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'&gt;';
481
482
						// Add also email aliases if there is some
483
						$listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
484
485
						// Also add robot email
486
						if (! empty($this->fromalsorobot))
487
						{
488
							if (! empty($conf->global->MAIN_MAIL_EMAIL_FROM) && $conf->global->MAIN_MAIL_EMAIL_FROM != $conf->global->MAIN_INFO_SOCIETE_MAIL)
489
							{
490
								$liste['robot'] = $conf->global->MAIN_MAIL_EMAIL_FROM;
491
								if ($this->frommail)
492
								{
493
									$liste['robot'] .= ' &lt;'.$conf->global->MAIN_MAIL_EMAIL_FROM.'&gt;';
494
								}
495
							}
496
						}
497
498
						// Add also email aliases from the c_email_senderprofile table
499
						$sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1 ORDER BY position';
500
						$resql = $this->db->query($sql);
501
						if ($resql)
502
						{
503
							$num = $this->db->num_rows($resql);
504
							$i=0;
505
							while($i < $num)
506
							{
507
								$obj = $this->db->fetch_object($resql);
508
								if ($obj)
509
								{
510
									$listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>';
511
								}
512
								$i++;
513
							}
514
						}
515
						else dol_print_error($this->db);
516
517
						foreach($listaliases as $typealias => $listalias)
518
						{
519
							$posalias=0;
520
							$listaliasarray=explode(',', $listalias);
521
							foreach ($listaliasarray as $listaliasval)
522
							{
523
								$posalias++;
524
								$listaliasval=trim($listaliasval);
525
								if ($listaliasval)
526
								{
527
									$listaliasval=preg_replace('/</', '&lt;', $listaliasval);
528
									$listaliasval=preg_replace('/>/', '&gt;', $listaliasval);
529
									if (! preg_match('/&lt;/', $listaliasval)) $listaliasval='&lt;'.$listaliasval.'&gt;';
530
									$liste[$typealias.'_'.$posalias]=$listaliasval;
531
								}
532
							}
533
						}
534
535
						// Set the default "From"
536
						$defaultfrom='';
537
						$reshook=$hookmanager->executeHooks('getDefaultFromEmail', $parameters, $this);
538
						if (empty($reshook))
539
						{
540
							$defaultfrom = $this->fromtype;
541
						}
542
						if (! empty($hookmanager->resArray['defaultfrom'])) $defaultfrom=$hookmanager->resArray['defaultfrom'];
543
544
						// Using combo here make the '<email>' no more visible on list.
545
						//$out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 1, '', $disablebademails);
546
						$out.= ' '.$form->selectarray('fromtype', $liste, $defaultfrom, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 0, '', $disablebademails);
547
					}
548
549
					$out.= "</td></tr>\n";
550
				}
551
				else
552
				{
553
					$out.= '<tr><td class="fieldrequired width200">'.$langs->trans("MailFrom")."</td><td>";
554
					$out.= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" class="maxwidth200onsmartphone" value="'.$this->fromname.'" />';
555
					$out.= '&nbsp; &nbsp; ';
556
					$out.= $langs->trans("EMail").':&lt;<input type="text" id="frommail" name="frommail" class="maxwidth200onsmartphone" value="'.$this->frommail.'" />&gt;';
557
					$out.= "</td></tr>\n";
558
				}
559
			}
560
561
			// To
562
			if (! empty($this->withto) || is_array($this->withto))
563
			{
564
				$out.= '<tr><td class="fieldrequired">';
565
				if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
566
				else $out.= $langs->trans("MailTo");
567
				$out.= '</td><td>';
568
				if ($this->withtoreadonly)
569
				{
570
					if (! empty($this->toname) && ! empty($this->tomail))
571
					{
572
						$out.= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
573
						$out.= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
574
						if ($this->totype == 'thirdparty')
575
						{
576
							$soc=new Societe($this->db);
577
							$soc->fetch($this->toid);
578
							$out.= $soc->getNomUrl(1);
579
						}
580
						else if ($this->totype == 'contact')
581
						{
582
							$contact=new Contact($this->db);
583
							$contact->fetch($this->toid);
584
							$out.= $contact->getNomUrl(1);
585
						}
586
						else
587
						{
588
							$out.= $this->toname;
589
						}
590
						$out.= ' &lt;'.$this->tomail.'&gt;';
591
						if ($this->withtofree)
592
						{
593
							$out.= '<br>'.$langs->trans("and").' <input class="minwidth200" id="sendto" name="sendto" value="'.(! is_array($this->withto) && ! is_numeric($this->withto)? (isset($_REQUEST["sendto"])?$_REQUEST["sendto"]:$this->withto) :"").'" />';
594
						}
595
					}
596
					else
597
					{
598
						// Note withto may be a text like 'AllRecipientSelected'
599
						$out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:"";
600
					}
601
				}
602
				else
603
				{
604
					if (! empty($this->withtofree))
605
					{
606
						$out.= '<input class="minwidth200" id="sendto" name="sendto" value="'.(! is_array($this->withto) && ! is_numeric($this->withto)? (isset($_REQUEST["sendto"])?$_REQUEST["sendto"]:$this->withto) :"").'" />';
607
					}
608
					if (! empty($this->withto) && is_array($this->withto))
609
					{
610
						if (! empty($this->withtofree)) $out.= " ".$langs->trans("and")."/".$langs->trans("or")." ";
611
						// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
612
						$tmparray = $this->withto;
613
						foreach($tmparray as $key => $val)
614
						{
615
							$tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
616
						}
617
						$withtoselected=GETPOST("receiver",'none');     // Array of selected value
618
						if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend')
619
						{
620
							$withtoselected = array_keys($tmparray);
621
						}
622
						$out.= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
623
					}
624
				}
625
				$out.= "</td></tr>\n";
626
			}
627
628
			// withoptiononeemailperrecipient
629
			if (! empty($this->withoptiononeemailperrecipient))
630
			{
631
				$out.= '<tr><td class="minwidth200">';
632
				$out.= $langs->trans("GroupEmails");
633
				$out.= '</td><td>';
634
				$out.=' <input type="checkbox" name="oneemailperrecipient"'.($this->withoptiononeemailperrecipient > 0?' checked="checked"':'').'> ';
635
				$out.= $langs->trans("OneEmailPerRecipient");
636
				$out.='<span class="hideonsmartphone">';
637
				$out.=' - ';
638
				$out.= $langs->trans("WarningIfYouCheckOneRecipientPerEmail");
639
				$out.='</span>';
640
				$out.= '</td></tr>';
641
			}
642
643
			// CC
644
			if (! empty($this->withtocc) || is_array($this->withtocc))
645
			{
646
				$out.= '<tr><td>';
647
				$out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
648
				$out.= '</td><td>';
649
				if ($this->withtoccreadonly)
650
				{
651
					$out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:"";
652
				}
653
				else
654
				{
655
					$out.= '<input class="minwidth200" id="sendtocc" name="sendtocc" value="'.((! is_array($this->withtocc) && ! is_numeric($this->withtocc))? (isset($_POST["sendtocc"])?$_POST["sendtocc"]:$this->withtocc) : (isset($_POST["sendtocc"])?$_POST["sendtocc"]:"") ).'" />';
656
					if (! empty($this->withtocc) && is_array($this->withtocc))
657
					{
658
						$out.= " ".$langs->trans("and")."/".$langs->trans("or")." ";
659
						// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
660
						$tmparray = $this->withtocc;
661
						foreach($tmparray as $key => $val)
662
						{
663
							$tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
664
						}
665
						$withtoccselected=GETPOST("receivercc");     // Array of selected value
666
						$out.= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500',null, "");
667
					}
668
				}
669
				$out.= "</td></tr>\n";
670
			}
671
672
			// CCC
673
			if (! empty($this->withtoccc) || is_array($this->withtoccc))
674
			{
675
				$out.= '<tr><td>';
676
				$out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
677
				$out.= '</td><td>';
678
				if (! empty($this->withtocccreadonly))
679
				{
680
					$out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:"";
681
				}
682
				else
683
				{
684
					$out.= '<input class="minwidth200" id="sendtoccc" name="sendtoccc" value="'.((! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))? (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:$this->withtoccc) : (isset($_POST["sendtoccc"])?$_POST["sendtoccc"]:"") ).'" />';
685
					if (! empty($this->withtoccc) && is_array($this->withtoccc))
686
					{
687
						$out.= " ".$langs->trans("and")."/".$langs->trans("or")." ";
688
						// multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
689
						$tmparray = $this->withtoccc;
690
						foreach($tmparray as $key => $val)
691
						{
692
							$tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
693
						}
694
						$withtocccselected=GETPOST("receiverccc");     // Array of selected value
695
						$out.= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null,null, "90%");
696
					}
697
				}
698
699
				$showinfobcc='';
700
				if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_PROPOSAL_TO;
701
				if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_SUPPLIER_PROPOSAL_TO;
702
				if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_ORDER_TO;
703
				if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $showinfobcc=$conf->global->MAIN_MAIL_AUTOCOPY_INVOICE_TO;
704
				if ($showinfobcc) $out.=' + '.$showinfobcc;
705
				$out.= "</td></tr>\n";
706
			}
707
708
			// Replyto
709
			if (! empty($this->withreplyto))
710
			{
711
				if ($this->withreplytoreadonly)
712
				{
713
					$out.= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
714
					$out.= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
715
					$out.= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail?(" &lt;".$this->replytomail."&gt;"):"");
716
					$out.= "</td></tr>\n";
717
				}
718
			}
719
720
			// Errorsto
721
			if (! empty($this->witherrorsto))
722
			{
723
				//if (! $this->errorstomail) $this->errorstomail=$this->frommail;
724
				$errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail);
725
				if ($this->witherrorstoreadonly)
726
				{
727
					$out.= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
728
					$out.= '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
729
					$out.= $errorstomail;
730
					$out.= "</td></tr>\n";
731
				}
732
				else
733
				{
734
					$out.= '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
735
					$out.= '<input size="30" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
736
					$out.= "</td></tr>\n";
737
				}
738
			}
739
740
			// Ask delivery receipt
741
			if (! empty($this->withdeliveryreceipt))
742
			{
743
				$out.= '<tr><td>'.$langs->trans("DeliveryReceipt").'</td><td>';
744
745
				if (! empty($this->withdeliveryreceiptreadonly))
746
				{
747
					$out.= yn($this->withdeliveryreceipt);
748
				}
749
				else
750
				{
751
					$defaultvaluefordeliveryreceipt=0;
752
					if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $defaultvaluefordeliveryreceipt=1;
753
					if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt=1;
754
					if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt=1;
755
					if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt=1;
756
					$out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:$defaultvaluefordeliveryreceipt), 1);
757
				}
758
759
				$out.= "</td></tr>\n";
760
			}
761
762
			// Topic
763
			if (! empty($this->withtopic))
764
			{
765
				$defaulttopic=GETPOST('subject','none');
766
				if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1')
767
				{
768
					if (is_array($arraydefaultmessage) && count($arraydefaultmessage) > 0 && $arraydefaultmessage['topic']) $defaulttopic=$arraydefaultmessage['topic'];
769
					elseif (! is_numeric($this->withtopic))	 $defaulttopic=$this->withtopic;
770
				}
771
772
				$defaulttopic=make_substitutions($defaulttopic,$this->substit);
773
774
				$out.= '<tr>';
775
				$out.= '<td class="fieldrequired">'.$langs->trans("MailTopic").'</td>';
776
				$out.= '<td>';
777
				if ($this->withtopicreadonly)
778
				{
779
					$out.= $defaulttopic;
780
					$out.= '<input type="hidden" class="quatrevingtpercent" id="subject" name="subject" value="'.$defaulttopic.'" />';
781
				}
782
				else
783
				{
784
					$out.= '<input type="text" class="quatrevingtpercent" id="subject" name="subject" value="'. ((isset($_POST["subject"]) && ! $_POST['modelselected'])?$_POST["subject"]:($defaulttopic?$defaulttopic:'')) .'" />';
785
				}
786
				$out.= "</td></tr>\n";
787
			}
788
789
			// Attached files
790
			if (! empty($this->withfile))
791
			{
792
				$out.= '<tr>';
793
				$out.= '<td>'.$langs->trans("MailFile").'</td>';
794
795
				$out.= '<td>';
796
				if (! empty($this->withmaindocfile))
797
				{
798
					if ($this->withmaindocfile == 1)
799
					{
800
						$out.='<input type="checkbox" name="addmaindocfile" value="1" />';
801
					}
802
					if ($this->withmaindocfile == -1)
803
					{
804
						$out.='<input type="checkbox" name="addmaindocfile" checked="checked" />';
805
					}
806
					$out.=' '.$langs->trans("JoinMainDoc").'.<br>';
807
				}
808
809
				if (is_numeric($this->withfile))
810
				{
811
					// TODO Trick to have param removedfile containing nb of file to delete. But this does not works without javascript
812
					$out.= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
813
					$out.= '<script type="text/javascript" language="javascript">';
814
					$out.= 'jQuery(document).ready(function () {';
815
					$out.= '    jQuery(".removedfile").click(function() {';
816
					$out.= '        jQuery(".removedfilehidden").val(jQuery(this).val());';
817
					$out.= '    });';
818
					$out.= '})';
819
					$out.= '</script>'."\n";
820
					if (count($listofpaths))
821
					{
822
						foreach($listofpaths as $key => $val)
823
						{
824
							$out.= '<div id="attachfile_'.$key.'">';
825
							$out.= img_mime($listofnames[$key]).' '.$listofnames[$key];
826
							if (! $this->withfilereadonly)
827
							{
828
								$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.'" />';
829
								//$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
830
							}
831
							$out.= '<br></div>';
832
						}
833
					}
834
					else if (empty($this->withmaindocfile))		// Do not show message if we asked to show the checkbox
835
					{
836
						$out.= $langs->trans("NoAttachedFiles").'<br>';
837
					}
838
					if ($this->withfile == 2)	// Can add other files
839
					{
840
						if (!empty($conf->global->FROM_MAIL_USE_INPUT_FILE_MULTIPLE)) $out.= '<input type="file" class="flat" id="addedfile" name="addedfile[]" value="'.$langs->trans("Upload").'" multiple />';
841
						else $out.= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
842
						$out.= ' ';
843
						$out.= '<input class="button" type="submit" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
844
					}
845
				}
846
				else
847
				{
848
					$out.=$this->withfile;
849
				}
850
851
				$out.= "</td></tr>\n";
852
			}
853
854
			// Message
855
			if (! empty($this->withbody))
856
			{
857
				$defaultmessage=GETPOST('message','none');
858
				if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1')
859
				{
860
					if (count($arraydefaultmessage) > 0 && $arraydefaultmessage['content']) $defaultmessage=$arraydefaultmessage['content'];
861
	   				elseif (! is_numeric($this->withbody))	$defaultmessage=$this->withbody;
862
				}
863
864
				// Complete substitution array
865
				$paymenturl='';
866
				if (empty($this->substit['__REF__']))
867
				{
868
					$paymenturl='';
869
				}
870
				else
871
				{
872
					// Set the online payment url link into __ONLINE_PAYMENT_URL__ key
873
					require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
874
					$langs->load('paypal');
875
					$typeforonlinepayment='free';
876
					if ($this->param["models"]=='order_send')   $typeforonlinepayment='order';		// TODO use detection on something else than template
877
					if ($this->param["models"]=='facture_send') $typeforonlinepayment='invoice';	// TODO use detection on something else than template
878
					if ($this->param["models"]=='member_send')  $typeforonlinepayment='member';		// TODO use detection on something else than template
879
					$url=getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']);
880
		   			$paymenturl=$url;
881
				}
882
883
				$this->substit['__ONLINE_PAYMENT_URL__']=$paymenturl;
884
885
				//Add lines substitution key from each line
886
				$lines = '';
887
				$defaultlines = $arraydefaultmessage['content_lines'];
888
				if (isset($defaultlines))
889
				{
890
					foreach ($this->substit_lines as $substit_line)
891
					{
892
						$lines .= make_substitutions($defaultlines,$substit_line)."\n";
893
					}
894
				}
895
				$this->substit['__LINES__']=$lines;
896
897
				$defaultmessage=str_replace('\n',"\n",$defaultmessage);
898
899
				// Deal with format differences between message and signature (text / HTML)
900
				if(dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
901
					$this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']);
902
				} else if(!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
903
					$defaultmessage = dol_nl2br($defaultmessage);
904
				}
905
906
				if (isset($_POST["message"]) && ! $_POST['modelselected']) $defaultmessage=$_POST["message"];
907
				else
908
				{
909
					$defaultmessage=make_substitutions($defaultmessage,$this->substit);
910
					// Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
911
					$defaultmessage=preg_replace("/^(<br>)+/","",$defaultmessage);
912
					$defaultmessage=preg_replace("/^\n+/","",$defaultmessage);
913
				}
914
915
				$out.= '<tr>';
916
				$out.= '<td valign="top">'.$langs->trans("MailText").'</td>';
917
				$out.= '<td>';
918
				if ($this->withbodyreadonly)
919
				{
920
					$out.= nl2br($defaultmessage);
921
					$out.= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />';
922
				}
923
				else
924
				{
925
					if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes';
926
927
					// Editor wysiwyg
928
					require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
929
					if ($this->withfckeditor == -1)
930
					{
931
						if (! empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $this->withfckeditor=1;
932
						else $this->withfckeditor=0;
933
					}
934
935
					$doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,'95%');
936
					$out.= $doleditor->Create(1);
937
				}
938
				$out.= "</td></tr>\n";
939
			}
940
941
			$out.= '</table>'."\n";
942
943
			if ($this->withform == 1 || $this->withform == -1)
944
			{
945
				$out.= '<br><div class="center">';
946
				$out.= '<input class="button" type="submit" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
947
				// Add a javascript test to avoid to forget to submit file before sending email
948
				if ($this->withfile == 2 && $conf->use_javascript_ajax)
949
				{
950
					$out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
951
				}
952
				$out.= ' />';
953
				if ($this->withcancel)
954
				{
955
					$out.= ' &nbsp; &nbsp; ';
956
					$out.= '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
957
				}
958
				$out.= '</div>'."\n";
959
			}
960
961
			if ($this->withform == 1) $out.= '</form>'."\n";
962
963
			// Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
964
			if (! empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY))
965
			{
966
				$out.= '<script type="text/javascript" language="javascript">';
967
				$out.= 'jQuery(document).ready(function () {';
968
				$out.= '	$(document).on("keypress", \'#mailform\', function (e) {		/* Note this is called at every key pressed ! */
969
	    						var code = e.keyCode || e.which;
970
	    						if (code == 13) {
971
	        						e.preventDefault();
972
	        						return false;
973
	    						}
974
							});';
975
				$out.='		})';
976
				$out.= '</script>';
977
			}
978
979
			$out.= "<!-- End form mail -->\n";
980
981
			return $out;
982
		}
983
	}
984
985
986
987
	/**
988
	 *      Return templates of email with type = $type_template or type = 'all'.
989
	 *      This search into table c_email_templates. Used by the get_form function.
990
	 *
991
	 * 		@param	DoliDB		$db				Database handler
992
	 * 		@param	string		$type_template	Get message for type=$type_template, type='all' also included.
993
	 *      @param	string		$user			Use template public or limited to this user
994
	 *      @param	Translate	$outputlangs	Output lang object
995
	 *      @param	int			$id				Id of template to find, or -1 for first found with lower position, or 0 for first found whatever is position
996
	 *      @param  int         $active         1=Only active template, 0=Only disabled, -1=All
997
	 *      @param	string		$label			Label of template
998
	 *      @return array						array('topic'=>,'content'=>,..)
999
	 */
1000
	public function getEMailTemplate($db, $type_template, $user, $outputlangs, $id=0, $active=1, $label='')
1001
	{
1002
		$ret=array();
1003
1004
		$sql = "SELECT label, topic, joinfiles, content, content_lines, lang";
1005
		$sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
1006
		$sql.= " WHERE (type_template='".$db->escape($type_template)."' OR type_template='all')";
1007
		$sql.= " AND entity IN (".getEntity('c_email_templates').")";
1008
		$sql.= " AND (private = 0 OR fk_user = ".$user->id.")";				// Get all public or private owned
1009
		if ($active >= 0) $sql.=" AND active = ".$active;
1010
		if ($label) $sql.=" AND label ='".$this->db->escape($label)."'";
1011
		if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')";
1012
		if ($id > 0)   $sql.= " AND rowid=".$id;
1013
		if ($id == -1) $sql.= " AND position=0";
1014
		if (is_object($outputlangs)) $sql.= $db->order("position,lang,label","ASC,DESC,ASC");		// We want line with lang set first, then with lang null or ''
1015
		else $sql.= $db->order("position,lang,label","ASC,ASC,ASC");		// If no language provided, we give priority to lang not defined
1016
		$sql.= $db->plimit(1);
1017
		//print $sql;
1018
1019
		$resql = $db->query($sql);
1020
		if ($resql)
1021
		{
1022
			$obj = $db->fetch_object($resql);	// Get first found
1023
			if ($obj)
1024
			{
1025
				$ret['label']=$obj->label;
1026
				$ret['lang']=$obj->lang;
1027
				$ret['topic']=$obj->topic;
1028
				$ret['joinfiles']=$obj->joinfiles;
1029
				$ret['content']=$obj->content;
1030
				$ret['content_lines']=$obj->content_lines;
1031
			}
1032
			else								// If there is no template at all
1033
			{
1034
				$defaultmessage='';
1035
				if     ($type_template=='facture_send')	            { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoice"); }
1036
				elseif ($type_template=='facture_relance')			{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); }
1037
				elseif ($type_template=='propal_send')				{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); }
1038
				elseif ($type_template=='supplier_proposal_send')	{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); }
1039
				elseif ($type_template=='order_send')				{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); }
1040
				elseif ($type_template=='order_supplier_send')		{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); }
1041
				elseif ($type_template=='invoice_supplier_send')	{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); }
1042
				elseif ($type_template=='shipping_send')			{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); }
1043
				elseif ($type_template=='fichinter_send')			{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); }
1044
				elseif ($type_template=='thirdparty')				{ $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); }
1045
				elseif ($type_template=='user')				        { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); }
1046
1047
				$ret['label']='default';
1048
				$ret['lang']=$outputlangs->defaultlang;
1049
				$ret['topic']='';
1050
				$ret['joinfiles']=1;
1051
				$ret['content']=$defaultmessage;
1052
				$ret['content_lines']='';
1053
			}
1054
1055
			$db->free($resql);
1056
			return $ret;
1057
		}
1058
		else
1059
		{
1060
			dol_print_error($db);
1061
			return -1;
1062
		}
1063
	}
1064
1065
	/**
1066
	 *      Find if template exists
1067
	 *      Search into table c_email_templates
1068
	 *
1069
	 * 		@param	string		$type_template	Get message for key module
1070
	 *      @param	string		$user			Use template public or limited to this user
1071
	 *      @param	Translate	$outputlangs	Output lang object
1072
	 *      @return	int		<0 if KO,
1073
	 */
1074
	public function isEMailTemplate($type_template, $user, $outputlangs)
1075
	{
1076
		$ret=array();
1077
1078
		$sql = "SELECT label, topic, content, lang";
1079
		$sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
1080
		$sql.= " WHERE type_template='".$this->db->escape($type_template)."'";
1081
		$sql.= " AND entity IN (".getEntity('c_email_templates').")";
1082
		$sql.= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".$user->id.")";
1083
		if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')";
1084
		$sql.= $this->db->order("lang,label","ASC");
1085
		//print $sql;
1086
1087
		$resql = $this->db->query($sql);
1088
		if ($resql)
1089
		{
1090
			$num= $this->db->num_rows($resql);
1091
			$this->db->free($resql);
1092
			return $num;
1093
		}
1094
		else
1095
		{
1096
			$this->error=get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1097
			return -1;
1098
		}
1099
	}
1100
1101
	/**
1102
	 *      Find if template exists and are available for current user, then set them into $this->lines_module.
1103
	 *      Search into table c_email_templates
1104
	 *
1105
	 * 		@param	string		$type_template	Get message for key module
1106
	 *      @param	string		$user			Use template public or limited to this user
1107
	 *      @param	Translate	$outputlangs	Output lang object
1108
	 *      @param  int         $active         1=Only active template, 0=Only disabled, -1=All
1109
	 *      @return	int		                    <0 if KO, nb of records found if OK
1110
	 */
1111
	public function fetchAllEMailTemplate($type_template, $user, $outputlangs, $active=1)
1112
	{
1113
		$ret=array();
1114
1115
		$sql = "SELECT rowid, label, topic, content, content_lines, lang, fk_user, private, position";
1116
		$sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
1117
		$sql.= " WHERE type_template IN ('".$this->db->escape($type_template)."', 'all')";
1118
		$sql.= " AND entity IN (".getEntity('c_email_templates').")";
1119
		$sql.= " AND (private = 0 OR fk_user = ".$user->id.")";		// See all public templates or templates I own.
1120
		if ($active >= 0) $sql.=" AND active = ".$active;
1121
		//if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')";	// Return all languages
1122
		$sql.= $this->db->order("position,lang,label","ASC");
1123
		//print $sql;
1124
1125
		$resql = $this->db->query($sql);
1126
		if ($resql)
1127
		{
1128
			$num=$this->db->num_rows($resql);
1129
			$this->lines_model=array();
1130
			while ($obj = $this->db->fetch_object($resql))
1131
			{
1132
				$line = new ModelMail();
1133
				$line->id=$obj->rowid;
1134
				$line->label=$obj->label;
1135
				$line->lang=$obj->lang;
1136
				$line->fk_user=$obj->fk_user;
1137
				$line->private=$obj->private;
1138
				$line->position=$obj->position;
1139
				$line->topic=$obj->topic;
1140
				$line->content=$obj->content;
1141
				$line->content_lines=$obj->content_lines;
1142
				$this->lines_model[]=$line;
1143
			}
1144
			$this->db->free($resql);
1145
			return $num;
1146
		}
1147
		else
1148
		{
1149
			$this->error=get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1150
			return -1;
1151
		}
1152
	}
1153
1154
1155
1156
	/**
1157
	 * Set substit array from object. This is call when suggesting the email template into forms before sending email.
1158
	 *
1159
	 * @param	CommonObject	$object		   Object to use
1160
	 * @param   Translate  		$outputlangs   Object lang
1161
	 * @return	void
1162
	 * @see getCommonSubstitutionArray
1163
	 */
1164
	function setSubstitFromObject($object, $outputlangs)
1165
	{
1166
		global $conf, $user;
1167
1168
		$parameters=array();
1169
		$tmparray=getCommonSubstitutionArray($outputlangs, 0, null, $object);
1170
		complete_substitutions_array($tmparray, $outputlangs, null, $parameters);
1171
1172
		$this->substit=$tmparray;
1173
1174
		// Fill substit_lines with each object lines content
1175
		if (is_array($object->lines))
1176
		{
1177
			foreach ($object->lines as $line)
1178
			{
1179
				$substit_line = array(
1180
					'__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '',
1181
					'__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '',
1182
					'__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '',
1183
					'__LABEL__' => isset($line->label) ? $line->label : '',
1184
					'__DESCRIPTION__' => isset($line->desc) ? $line->desc : '',
1185
					'__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs),
1186
					'__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs),
1187
					'__QUANTITY__' => $line->qty,
1188
					'__SUBPRICE__' => price($line->subprice),
1189
					'__AMOUNT__' => price($line->total_ttc),
1190
					'__AMOUNT_EXCL_TAX__' => price($line->total_ht),
1191
					//'__PRODUCT_EXTRAFIELD_FIELD__' Done dinamically just after
1192
				);
1193
1194
				// Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__
1195
				if (!empty($line->fk_product))
1196
				{
1197
					$extrafields = new ExtraFields($this->db);
1198
					$extralabels = $extrafields->fetch_name_optionals_label('product', true);
1199
					$product = new Product($this->db);
1200
					$product->fetch($line->fk_product, '', '', 1);
1201
					$product->fetch_optionals();
1202
					foreach ($extrafields->attribute_label as $key => $label) {
1203
						$substit_line['__PRODUCT_EXTRAFIELD_' . strtoupper($key) . '__'] = $product->array_options['options_' . $key];
1204
					}
1205
				}
1206
				$this->substit_lines[] = $substit_line;
1207
			}
1208
		}
1209
	}
1210
1211
	/**
1212
	 * Get list of substitution keys available for emails. This is used for tooltips help.
1213
	 * This include the complete_substitutions_array.
1214
	 *
1215
	 * @param	string	$mode		'formemail', 'formemailwithlines', 'formemailforlines', 'emailing', ...
1216
	 * @param	Object	$object		Object if applicable
1217
	 * @return	array               Array of substitution values for emails.
1218
	 */
1219
	static function getAvailableSubstitKey($mode='formemail', $object=null)
1220
	{
1221
		global $conf, $langs;
1222
1223
		$tmparray=array();
1224
		if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines')
1225
		{
1226
			$parameters=array('mode'=>$mode);
1227
			$tmparray=getCommonSubstitutionArray($langs, 2, null, $object);			// Note: On email templated edition, this is null because it is related to all type of objects
1228
			complete_substitutions_array($tmparray, $langs, null, $parameters);
1229
1230
			if ($mode == 'formwithlines')
1231
			{
1232
				$tmparray['__LINES__'] = '__LINES__';      // Will be set by the get_form function
1233
			}
1234
			if ($mode == 'formforlines')
1235
			{
1236
				$tmparray['__QUANTITY__'] = '__QUANTITY__';   // Will be set by the get_form function
1237
			}
1238
		}
1239
1240
		if ($mode == 'emailing')
1241
		{
1242
			$parameters=array('mode'=>$mode);
1243
			$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
1244
			complete_substitutions_array($tmparray, $langs, null, $parameters);
1245
1246
			// For mass emailing, we have different keys
1247
			$tmparray['__ID__'] = 'IdRecord';
1248
			$tmparray['__EMAIL__'] = 'EMailRecipient';
1249
			$tmparray['__LASTNAME__'] = 'Lastname';
1250
			$tmparray['__FIRSTNAME__'] = 'Firstname';
1251
			$tmparray['__MAILTOEMAIL__'] = 'TagMailtoEmail';
1252
			$tmparray['__OTHER1__'] = 'Other1';
1253
			$tmparray['__OTHER2__'] = 'Other2';
1254
			$tmparray['__OTHER3__'] = 'Other3';
1255
			$tmparray['__OTHER4__'] = 'Other4';
1256
			$tmparray['__OTHER5__'] = 'Other5';
1257
			$tmparray['__USER_SIGNATURE__'] = 'TagSignature';
1258
			$tmparray['__CHECK_READ__'] = 'TagCheckMail';
1259
			$tmparray['__UNSUBSCRIBE__'] = 'TagUnsubscribe';
1260
				//,'__PERSONALIZED__' => 'Personalized'	// Hidden because not used yet in mass emailing
1261
1262
			$onlinepaymentenabled = 0;
1263
			if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++;
1264
			if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++;
1265
			if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++;
1266
			if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN))
1267
			{
1268
				$tmparray['__SECUREKEYPAYMENT__']=$conf->global->PAYMENT_SECURITY_TOKEN;
1269
				if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
1270
				{
1271
					if ($conf->adherent->enabled) $tmparray['__SECUREKEYPAYMENT_MEMBER__']='SecureKeyPAYMENTUniquePerMember';
1272
					if ($conf->facture->enabled)  $tmparray['__SECUREKEYPAYMENT_INVOICE__']='SecureKeyPAYMENTUniquePerInvoice';
1273
					if ($conf->commande->enabled) $tmparray['__SECUREKEYPAYMENT_ORDER__']='SecureKeyPAYMENTUniquePerOrder';
1274
					if ($conf->contrat->enabled)  $tmparray['__SECUREKEYPAYMENT_CONTRACTLINE__']='SecureKeyPAYMENTUniquePerContractLine';
1275
				}
1276
			}
1277
			else
1278
			{
1279
				/* No need to show into tooltip help, option is not enabled
1280
				$vars['__SECUREKEYPAYMENT__']='';
1281
				$vars['__SECUREKEYPAYMENT_MEMBER__']='';
1282
				$vars['__SECUREKEYPAYMENT_INVOICE__']='';
1283
				$vars['__SECUREKEYPAYMENT_ORDER__']='';
1284
				$vars['__SECUREKEYPAYMENT_CONTRACTLINE__']='';
1285
				*/
1286
			}
1287
		}
1288
1289
		$tmparray['__(AnyTranslationKey)__']="Translation";
1290
1291
		foreach($tmparray as $key => $val)
1292
		{
1293
			if (empty($val)) $tmparray[$key]=$key;
1294
		}
1295
1296
		return $tmparray;
1297
	}
1298
1299
}
1300
1301
1302
/**
1303
 * ModelMail
1304
 */
1305
class ModelMail
1306
{
1307
	public $id;
1308
	public $label;
1309
	public $topic;
1310
	public $content;
1311
	public $content_lines;
1312
	public $lang;
1313
}
1314