dolibarr  9.0.0
html.formmail.class.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2005-2012 Laurent Destailleur <eldy@users.sourceforge.net>
3  * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
4  * Copyright (C) 2010-2011 Juanjo Menent <jmenent@2byte.es>
5  * Copyright (C) 2015-2017 Marcos García <marcosgdf@gmail.com>
6  * Copyright (C) 2015-2017 Nicolas ZABOURI <info@inovea-conseil.com>
7  * Copyright (C) 2018 Frédéric France <frederic.france@netlogic.fr>
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 <http://www.gnu.org/licenses/>.
21  */
22 
28 require_once DOL_DOCUMENT_ROOT .'/core/class/html.form.class.php';
29 
30 
37 class FormMail extends Form
38 {
42  public $db;
43 
44  public $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
45 
46  public $fromname;
47  public $frommail;
48 
52  public $fromtype;
53 
57  public $fromid;
58 
62  public $totype;
63 
67  public $toid;
68 
69  public $replytoname;
70  public $replytomail;
71  public $toname;
72  public $tomail;
73  public $trackid;
74 
75  public $withsubstit; // Show substitution array
76  public $withfrom;
77 
83  public $withtosocid;
84 
88  public $withto; // Show recipient emails
89 
90  public $withtofree; // Show free text for recipient emails
91  public $withtocc;
92  public $withtoccc;
93  public $withtopic;
94  public $withfile; // 0=No attaches files, 1=Show attached files, 2=Can add new attached files
95  public $withmaindocfile; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
96  public $withbody;
97 
98  public $withfromreadonly;
99  public $withreplytoreadonly;
100  public $withtoreadonly;
101  public $withtoccreadonly;
102  public $withtocccreadonly;
103  public $withtopicreadonly;
104  public $withfilereadonly;
105  public $withdeliveryreceipt;
106  public $withcancel;
107  public $withfckeditor;
108 
109  public $substit=array();
110  public $substit_lines=array();
111  public $param=array();
112 
113  public $withtouser=array();
114  public $withtoccuser=array();
115 
116  public $lines_model;
117 
118 
124  function __construct($db)
125  {
126  $this->db = $db;
127 
128  $this->withform=1;
129 
130  $this->withfrom=1;
131  $this->withto=1;
132  $this->withtofree=1;
133  $this->withtocc=1;
134  $this->withtoccc=0;
135  $this->witherrorsto=0;
136  $this->withtopic=1;
137  $this->withfile=0; // 1=Add section "Attached files". 2=Can add files.
138  $this->withmaindocfile=0; // 1=Add a checkbox "Attach also main document" for mass actions (checked by default), -1=Add checkbox (not checked by default)
139  $this->withbody=1;
140 
141  $this->withfromreadonly=1;
142  $this->withreplytoreadonly=1;
143  $this->withtoreadonly=0;
144  $this->withtoccreadonly=0;
145  $this->withtocccreadonly=0;
146  $this->witherrorstoreadonly=0;
147  $this->withtopicreadonly=0;
148  $this->withfilereadonly=0;
149  $this->withbodyreadonly=0;
150  $this->withdeliveryreceiptreadonly=0;
151  $this->withfckeditor=-1; // -1 = Auto
152  }
153 
154  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
161  {
162  // phpcs:enable
163  global $conf,$user;
164  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
165 
166  // Set tmp user directory
167  $vardir=$conf->user->dir_output."/".$user->id;
168  $upload_dir = $vardir.'/temp/'; // TODO Add $keytoavoidconflict in upload_dir path
169  if (is_dir($upload_dir)) dol_delete_dir_recursive($upload_dir);
170 
171  $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined
172  unset($_SESSION["listofpaths".$keytoavoidconflict]);
173  unset($_SESSION["listofnames".$keytoavoidconflict]);
174  unset($_SESSION["listofmimes".$keytoavoidconflict]);
175  }
176 
177  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
186  function add_attached_files($path, $file='', $type='')
187  {
188  // phpcs:enable
189  $listofpaths=array();
190  $listofnames=array();
191  $listofmimes=array();
192 
193  if (empty($file)) $file=basename($path);
194  if (empty($type)) $type=dol_mimetype($file);
195 
196  $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined
197  if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
198  if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
199  if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
200  if (! in_array($file,$listofnames))
201  {
202  $listofpaths[]=$path;
203  $listofnames[]=$file;
204  $listofmimes[]=$type;
205  $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
206  $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
207  $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
208  }
209  }
210 
211  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
218  function remove_attached_files($keytodelete)
219  {
220  // phpcs:enable
221  $listofpaths=array();
222  $listofnames=array();
223  $listofmimes=array();
224 
225  $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined
226  if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
227  if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
228  if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
229  if ($keytodelete >= 0)
230  {
231  unset ($listofpaths[$keytodelete]);
232  unset ($listofnames[$keytodelete]);
233  unset ($listofmimes[$keytodelete]);
234  $_SESSION["listofpaths".$keytoavoidconflict]=join(';',$listofpaths);
235  $_SESSION["listofnames".$keytoavoidconflict]=join(';',$listofnames);
236  $_SESSION["listofmimes".$keytoavoidconflict]=join(';',$listofmimes);
237  //var_dump($_SESSION['listofpaths']);
238  }
239  }
240 
241  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
248  {
249  // phpcs:enable
250  $listofpaths=array();
251  $listofnames=array();
252  $listofmimes=array();
253 
254  $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined
255  if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
256  if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
257  if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
258  return array('paths'=>$listofpaths, 'names'=>$listofnames, 'mimes'=>$listofmimes);
259  }
260 
261  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
271  function show_form($addfileaction='addfile',$removefileaction='removefile')
272  {
273  // phpcs:enable
274  print $this->get_form($addfileaction,$removefileaction);
275  }
276 
277  // phpcs:disable PEAR.NamingConventions.ValidFunctionName.NotCamelCaps
288  function get_form($addfileaction='addfile', $removefileaction='removefile')
289  {
290  // phpcs:enable
291  global $conf, $langs, $user, $hookmanager, $form;
292 
293  if (! is_object($form)) $form=new Form($this->db);
294 
295  // Load translation files required by the page
296  $langs->loadLangs(array('other', 'mails'));
297 
298  // Clear temp files. Must be done at beginning, before call of triggers
299  if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1'))
300  {
301  $this->clear_attached_files();
302  }
303 
304  // Call hook getFormMail
305  $hookmanager->initHooks(array('formmail'));
306 
307  $parameters=array(
308  'addfileaction' => $addfileaction,
309  'removefileaction'=> $removefileaction,
310  'trackid'=> $this->trackid
311  );
312  $reshook=$hookmanager->executeHooks('getFormMail', $parameters, $this);
313 
314  if (!empty($reshook))
315  {
316  return $hookmanager->resPrint;
317  }
318  else
319  {
320  $out='';
321 
322  $disablebademails=1;
323 
324  // Define output language
325  $outputlangs = $langs;
326  $newlang = '';
327  if ($conf->global->MAIN_MULTILANGS && empty($newlang)) $newlang = $this->param['langsmodels'];
328  if (! empty($newlang))
329  {
330  $outputlangs = new Translate("", $conf);
331  $outputlangs->setDefaultLang($newlang);
332  $outputlangs->load('other');
333  }
334 
335  // Get message template for $this->param["models"] into c_email_templates
336  $arraydefaultmessage = -1;
337  if ($this->param['models'] != 'none')
338  {
339  $model_id=0;
340  if (array_key_exists('models_id',$this->param))
341  {
342  $model_id=$this->param["models_id"];
343  }
344 
345  $arraydefaultmessage=$this->getEMailTemplate($this->db, $this->param["models"], $user, $outputlangs, $model_id); // If $model_id is empty, preselect the first one
346  }
347 
348  // Define list of attached files
349  $listofpaths=array();
350  $listofnames=array();
351  $listofmimes=array();
352  $keytoavoidconflict = empty($this->trackid)?'':'-'.$this->trackid; // this->trackid must be defined
353 
354  if (GETPOST('mode','alpha') == 'init' || (GETPOST('modelmailselected','alpha') && GETPOST('modelmailselected','alpha') != '-1'))
355  {
356  if (! empty($arraydefaultmessage->joinfiles) && is_array($this->param['fileinit']))
357  {
358  foreach($this->param['fileinit'] as $file)
359  {
360  $this->add_attached_files($file, basename($file), dol_mimetype($file));
361  }
362  }
363  }
364 
365  if (! empty($_SESSION["listofpaths".$keytoavoidconflict])) $listofpaths=explode(';',$_SESSION["listofpaths".$keytoavoidconflict]);
366  if (! empty($_SESSION["listofnames".$keytoavoidconflict])) $listofnames=explode(';',$_SESSION["listofnames".$keytoavoidconflict]);
367  if (! empty($_SESSION["listofmimes".$keytoavoidconflict])) $listofmimes=explode(';',$_SESSION["listofmimes".$keytoavoidconflict]);
368 
369 
370  $out.= "\n".'<!-- Begin form mail type='.$this->param["models"].' --><div id="mailformdiv"></div>'."\n";
371  if ($this->withform == 1)
372  {
373  $out.= '<form method="POST" name="mailform" id="mailform" enctype="multipart/form-data" action="'.$this->param["returnurl"].'#formmail">'."\n";
374 
375  $out.= '<a id="formmail" name="formmail"></a>';
376  $out.= '<input style="display:none" type="submit" id="sendmail" name="sendmail">';
377  $out.= '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'" />';
378  $out.= '<input type="hidden" name="trackid" value="'.$this->trackid.'" />';
379  }
380  if (! empty($this->withfrom))
381  {
382  if (! empty($this->withfromreadonly))
383  {
384  $out.= '<input type="hidden" id="fromname" name="fromname" value="'.$this->fromname.'" />';
385  $out.= '<input type="hidden" id="frommail" name="frommail" value="'.$this->frommail.'" />';
386  }
387  }
388  foreach ($this->param as $key=>$value)
389  {
390  $out.= '<input type="hidden" id="'.$key.'" name="'.$key.'" value="'.$value.'" />'."\n";
391  }
392 
393  $modelmail_array=array();
394  if ($this->param['models'] != 'none')
395  {
396  $result = $this->fetchAllEMailTemplate($this->param["models"], $user, $outputlangs);
397  if ($result < 0)
398  {
399  setEventMessages($this->error, $this->errors, 'errors');
400  }
401  foreach($this->lines_model as $line)
402  {
403  $langs->trans("members");
404  if (preg_match('/\((.*)\)/', $line->label, $reg))
405  {
406  $modelmail_array[$line->id]=$langs->trans($reg[1]); // langs->trans when label is __(xxx)__
407  }
408  else
409  {
410  $modelmail_array[$line->id]=$line->label;
411  }
412  if ($line->lang) $modelmail_array[$line->id].=' ('.$line->lang.')';
413  if ($line->private) $modelmail_array[$line->id].=' - '.$langs->trans("Private");
414  //if ($line->fk_user != $user->id) $modelmail_array[$line->id].=' - '.$langs->trans("By").' ';
415  }
416  }
417 
418  // Zone to select email template
419  if (count($modelmail_array)>0)
420  {
421  // If list of template is filled
422  $out.= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
423  $out.= '<span class="opacitymedium">'.$langs->trans('SelectMailModel').':</span> '.$this->selectarray('modelmailselected', $modelmail_array, 0, 1, 0, 0, '', 0, 0, 0, '', 'minwidth100');
424  if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1);
425  $out.= ' &nbsp; ';
426  $out.= '<input class="button" type="submit" value="'.$langs->trans('Apply').'" name="modelselected" id="modelselected">';
427  $out.= ' &nbsp; ';
428  $out.= '</div>';
429  }
430  elseif (! empty($this->param['models']) && in_array($this->param['models'], array(
431  'propal_send','order_send','facture_send',
432  'shipping_send','fichinter_send','supplier_proposal_send','order_supplier_send',
433  'invoice_supplier_send','thirdparty','contract','user','all'
434  )))
435  {
436  // If list of template is empty
437  $out.= '<div class="center" style="padding: 0px 0 12px 0">'."\n";
438  $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.
439  if ($user->admin) $out.= info_admin($langs->trans("YouCanChangeValuesForThisListFrom", $langs->transnoentitiesnoconv('Setup').' - '.$langs->transnoentitiesnoconv('EMails')),1);
440  $out.= ' &nbsp; ';
441  $out.= '<input class="button" type="submit" value="'.$langs->trans('Apply').'" name="modelselected" disabled="disabled" id="modelselected">';
442  $out.= ' &nbsp; ';
443  $out.= '</div>';
444  }
445 
446 
447 
448  $out.= '<table class="tableforemailform boxtablenotop" width="100%">'."\n";
449 
450  // Substitution array/string
451  $helpforsubstitution='';
452  if (is_array($this->substit) && count($this->substit)) $helpforsubstitution.=$langs->trans('AvailableVariables').' :<br>'."\n";
453  foreach($this->substit as $key => $val)
454  {
455  $helpforsubstitution.=$key.' -> '.$langs->trans(dol_string_nohtmltag($val)).'<br>';
456  }
457  if (! empty($this->withsubstit)) // Unset or set ->withsubstit=0 to disable this.
458  {
459  $out.= '<tr><td colspan="2" align="right">';
460  //$out.='<div class="floatright">';
461  if (is_numeric($this->withsubstit)) $out.= $form->textwithpicto($langs->trans("EMailTestSubstitutionReplacedByGenericValues"), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // Old usage
462  else $out.= $form->textwithpicto($langs->trans('AvailableVariables'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltip'); // New usage
463  $out.= "</td></tr>\n";
464  //$out.='</div>';
465  }
466 
467  /*var_dump(! empty($this->withfromreadonly));
468  var_dump($this->withfrom);
469  var_dump($this->fromtype);
470  var_dump($this->fromname);*/
471 
472  // From
473  if (! empty($this->withfrom))
474  {
475  if (! empty($this->withfromreadonly))
476  {
477  $out.= '<tr><td class="fieldrequired minwidth200">'.$langs->trans("MailFrom").'</td><td>';
478 
479  // $this->fromtype is the default value to use to select sender
480  if (! ($this->fromtype === 'user' && $this->fromid > 0)
481  && ! ($this->fromtype === 'company')
482  && ! ($this->fromtype === 'robot')
483  && ! preg_match('/user_aliases/', $this->fromtype)
484  && ! preg_match('/global_aliases/', $this->fromtype)
485  && ! preg_match('/senderprofile/', $this->fromtype)
486  )
487  {
488  // Use this->fromname and this->frommail or error if not defined
489  $out.= $this->fromname;
490  if ($this->frommail)
491  {
492  $out.= ' &lt;'.$this->frommail.'&gt;';
493  }
494  else
495  {
496  if ($this->fromtype)
497  {
498  $langs->load('errors');
499  $out.= '<span class="warning"> &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt; </span>';
500  }
501  }
502  } else {
503  $liste = array();
504 
505  // Add user email
506  if (empty($user->email))
507  {
508  $langs->load('errors');
509  $liste['user'] = $user->getFullName($langs) . ' &lt;'.$langs->trans('ErrorNoMailDefinedForThisUser').'&gt;';
510  }
511  else
512  {
513  $liste['user'] = $user->getFullName($langs) .' &lt;'.$user->email.'&gt;';
514  }
515 
516  // Add also company main email
517  $liste['company'] = $conf->global->MAIN_INFO_SOCIETE_NOM .' &lt;'.$conf->global->MAIN_INFO_SOCIETE_MAIL.'&gt;';
518 
519  // Add also email aliases if there is some
520  $listaliases=array('user_aliases'=>$user->email_aliases, 'global_aliases'=>$conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES);
521 
522  // Also add robot email
523  if (! empty($this->fromalsorobot))
524  {
525  if (! empty($conf->global->MAIN_MAIL_EMAIL_FROM) && $conf->global->MAIN_MAIL_EMAIL_FROM != $conf->global->MAIN_INFO_SOCIETE_MAIL)
526  {
527  $liste['robot'] = $conf->global->MAIN_MAIL_EMAIL_FROM;
528  if ($this->frommail)
529  {
530  $liste['robot'] .= ' &lt;'.$conf->global->MAIN_MAIL_EMAIL_FROM.'&gt;';
531  }
532  }
533  }
534 
535  // Add also email aliases from the c_email_senderprofile table
536  $sql='SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile WHERE active = 1 ORDER BY position';
537  $resql = $this->db->query($sql);
538  if ($resql)
539  {
540  $num = $this->db->num_rows($resql);
541  $i=0;
542  while($i < $num)
543  {
544  $obj = $this->db->fetch_object($resql);
545  if ($obj)
546  {
547  $listaliases['senderprofile_'.$obj->rowid] = $obj->label.' <'.$obj->email.'>';
548  }
549  $i++;
550  }
551  }
552  else dol_print_error($this->db);
553 
554  foreach($listaliases as $typealias => $listalias)
555  {
556  $posalias=0;
557  $listaliasarray=explode(',', $listalias);
558  foreach ($listaliasarray as $listaliasval)
559  {
560  $posalias++;
561  $listaliasval=trim($listaliasval);
562  if ($listaliasval)
563  {
564  $listaliasval=preg_replace('/</', '&lt;', $listaliasval);
565  $listaliasval=preg_replace('/>/', '&gt;', $listaliasval);
566  if (! preg_match('/&lt;/', $listaliasval)) $listaliasval='&lt;'.$listaliasval.'&gt;';
567  $liste[$typealias.'_'.$posalias]=$listaliasval;
568  }
569  }
570  }
571 
572  // Set the default "From"
573  $defaultfrom='';
574  $reshook=$hookmanager->executeHooks('getDefaultFromEmail', $parameters, $this);
575  if (empty($reshook))
576  {
577  $defaultfrom = $this->fromtype;
578  }
579  if (! empty($hookmanager->resArray['defaultfrom'])) $defaultfrom=$hookmanager->resArray['defaultfrom'];
580 
581  // Using combo here make the '<email>' no more visible on list.
582  //$out.= ' '.$form->selectarray('fromtype', $liste, $this->fromtype, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 1, '', $disablebademails);
583  $out.= ' '.$form->selectarray('fromtype', $liste, $defaultfrom, 0, 0, 0, '', 0, 0, 0, '', 'fromforsendingprofile maxwidth200onsmartphone', 0, '', $disablebademails);
584  }
585 
586  $out.= "</td></tr>\n";
587  }
588  else
589  {
590  $out.= '<tr><td class="fieldrequired width200">'.$langs->trans("MailFrom")."</td><td>";
591  $out.= $langs->trans("Name").':<input type="text" id="fromname" name="fromname" class="maxwidth200onsmartphone" value="'.$this->fromname.'" />';
592  $out.= '&nbsp; &nbsp; ';
593  $out.= $langs->trans("EMail").':&lt;<input type="text" id="frommail" name="frommail" class="maxwidth200onsmartphone" value="'.$this->frommail.'" />&gt;';
594  $out.= "</td></tr>\n";
595  }
596  }
597 
598  // To
599  if (! empty($this->withto) || is_array($this->withto))
600  {
601  $out.= '<tr><td class="fieldrequired">';
602  if ($this->withtofree) $out.= $form->textwithpicto($langs->trans("MailTo"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
603  else $out.= $langs->trans("MailTo");
604  $out.= '</td><td>';
605  if ($this->withtoreadonly)
606  {
607  if (! empty($this->toname) && ! empty($this->tomail))
608  {
609  $out.= '<input type="hidden" id="toname" name="toname" value="'.$this->toname.'" />';
610  $out.= '<input type="hidden" id="tomail" name="tomail" value="'.$this->tomail.'" />';
611  if ($this->totype == 'thirdparty')
612  {
613  $soc=new Societe($this->db);
614  $soc->fetch($this->toid);
615  $out.= $soc->getNomUrl(1);
616  }
617  else if ($this->totype == 'contact')
618  {
619  $contact=new Contact($this->db);
620  $contact->fetch($this->toid);
621  $out.= $contact->getNomUrl(1);
622  }
623  else
624  {
625  $out.= $this->toname;
626  }
627  $out.= ' &lt;'.$this->tomail.'&gt;';
628  if ($this->withtofree)
629  {
630  $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) :"").'" />';
631  }
632  }
633  else
634  {
635  // Note withto may be a text like 'AllRecipientSelected'
636  $out.= (! is_array($this->withto) && ! is_numeric($this->withto))?$this->withto:"";
637  }
638  }
639  else
640  {
641  if (! empty($this->withtofree))
642  {
643  $out.= '<input class="minwidth200" id="sendto" name="sendto" value="'.(! is_array($this->withto) && ! is_numeric($this->withto)? (isset($_REQUEST["sendto"])?$_REQUEST["sendto"]:$this->withto) :"").'" />';
644  }
645  if (! empty($this->withto) && is_array($this->withto))
646  {
647  if (! empty($this->withtofree)) $out.= " ".$langs->trans("and")."/".$langs->trans("or")." ";
648  // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
649  $tmparray = $this->withto;
650  foreach($tmparray as $key => $val)
651  {
652  $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
653  }
654  $withtoselected=GETPOST("receiver",'none'); // Array of selected value
655  if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend')
656  {
657  $withtoselected = array_keys($tmparray);
658  }
659  $out.= $form->multiselectarray("receiver", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
660  }
661  }
662  $out.= "</td></tr>\n";
663  }
664 
665  // To User
666  if (! empty($this->withtouser) && is_array($this->withtouser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT))
667  {
668  $out.= '<tr><td>';
669  $out.= $langs->trans("MailToUsers");
670  $out.= '</td><td>';
671 
672  // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
673  $tmparray = $this->withtouser;
674  foreach($tmparray as $key => $val)
675  {
676  $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
677  }
678  $withtoselected=GETPOST("receiveruser",'none'); // Array of selected value
679  if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend')
680  {
681  $withtoselected = array_keys($tmparray);
682  }
683  $out.= $form->multiselectarray("receiveruser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
684  $out.= "</td></tr>\n";
685  }
686 
687  // withoptiononeemailperrecipient
688  if (! empty($this->withoptiononeemailperrecipient))
689  {
690  $out.= '<tr><td class="minwidth200">';
691  $out.= $langs->trans("GroupEmails");
692  $out.= '</td><td>';
693  $out.=' <input type="checkbox" name="oneemailperrecipient"'.($this->withoptiononeemailperrecipient > 0?' checked="checked"':'').'> ';
694  $out.= $langs->trans("OneEmailPerRecipient");
695  $out.='<span class="hideonsmartphone">';
696  $out.=' - ';
697  $out.= $langs->trans("WarningIfYouCheckOneRecipientPerEmail");
698  $out.='</span>';
699  $out.= '</td></tr>';
700  }
701 
702  // CC
703  if (! empty($this->withtocc) || is_array($this->withtocc))
704  {
705  $out.= '<tr><td>';
706  $out.= $form->textwithpicto($langs->trans("MailCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
707  $out.= '</td><td>';
708  if ($this->withtoccreadonly)
709  {
710  $out.= (! is_array($this->withtocc) && ! is_numeric($this->withtocc))?$this->withtocc:"";
711  }
712  else
713  {
714  $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"]:"") ).'" />';
715  if (! empty($this->withtocc) && is_array($this->withtocc))
716  {
717  $out.= " ".$langs->trans("and")."/".$langs->trans("or")." ";
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->withtocc;
720  foreach($tmparray as $key => $val)
721  {
722  $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
723  }
724  $withtoccselected=GETPOST("receivercc"); // Array of selected value
725  $out.= $form->multiselectarray("receivercc", $tmparray, $withtoccselected, null, null, 'inline-block minwidth500',null, "");
726  }
727  }
728  $out.= "</td></tr>\n";
729  }
730 
731  // To User cc
732  if (! empty($this->withtoccuser) && is_array($this->withtoccuser) && !empty($conf->global->MAIN_MAIL_ENABLED_USER_DEST_SELECT))
733  {
734  $out.= '<tr><td>';
735  $out.= $langs->trans("MailToCCUsers");
736  $out.= '</td><td>';
737 
738  // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
739  $tmparray = $this->withtoccuser;
740  foreach($tmparray as $key => $val)
741  {
742  $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
743  }
744  $withtoselected=GETPOST("receiverccuser",'none'); // Array of selected value
745  if (empty($withtoselected) && count($tmparray) == 1 && GETPOST('action','aZ09') == 'presend')
746  {
747  $withtoselected = array_keys($tmparray);
748  }
749  $out.= $form->multiselectarray("receiverccuser", $tmparray, $withtoselected, null, null, 'inline-block minwidth500', null, "");
750  $out.= "</td></tr>\n";
751  }
752 
753  // CCC
754  if (! empty($this->withtoccc) || is_array($this->withtoccc))
755  {
756  $out.= '<tr><td>';
757  $out.= $form->textwithpicto($langs->trans("MailCCC"),$langs->trans("YouCanUseCommaSeparatorForSeveralRecipients"));
758  $out.= '</td><td>';
759  if (! empty($this->withtocccreadonly))
760  {
761  $out.= (! is_array($this->withtoccc) && ! is_numeric($this->withtoccc))?$this->withtoccc:"";
762  }
763  else
764  {
765  $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"]:"") ).'" />';
766  if (! empty($this->withtoccc) && is_array($this->withtoccc))
767  {
768  $out.= " ".$langs->trans("and")."/".$langs->trans("or")." ";
769  // multiselect array convert html entities into options tags, even if we dont want this, so we encode them a second time
770  $tmparray = $this->withtoccc;
771  foreach($tmparray as $key => $val)
772  {
773  $tmparray[$key]=dol_htmlentities($tmparray[$key], null, 'UTF-8', true);
774  }
775  $withtocccselected=GETPOST("receiverccc"); // Array of selected value
776  $out.= $form->multiselectarray("receiverccc", $tmparray, $withtocccselected, null, null, null,null, "90%");
777  }
778  }
779 
780  $showinfobcc='';
781  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;
782  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;
783  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;
784  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;
785  if ($showinfobcc) $out.=' + '.$showinfobcc;
786  $out.= "</td></tr>\n";
787  }
788 
789  // Replyto
790  if (! empty($this->withreplyto))
791  {
792  if ($this->withreplytoreadonly)
793  {
794  $out.= '<input type="hidden" id="replyname" name="replyname" value="'.$this->replytoname.'" />';
795  $out.= '<input type="hidden" id="replymail" name="replymail" value="'.$this->replytomail.'" />';
796  $out.= "<tr><td>".$langs->trans("MailReply")."</td><td>".$this->replytoname.($this->replytomail?(" &lt;".$this->replytomail."&gt;"):"");
797  $out.= "</td></tr>\n";
798  }
799  }
800 
801  // Errorsto
802  if (! empty($this->witherrorsto))
803  {
804  //if (! $this->errorstomail) $this->errorstomail=$this->frommail;
805  $errorstomail = (! empty($conf->global->MAIN_MAIL_ERRORS_TO) ? $conf->global->MAIN_MAIL_ERRORS_TO : $this->errorstomail);
806  if ($this->witherrorstoreadonly)
807  {
808  $out.= '<input type="hidden" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
809  $out.= '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
810  $out.= $errorstomail;
811  $out.= "</td></tr>\n";
812  }
813  else
814  {
815  $out.= '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>';
816  $out.= '<input size="30" id="errorstomail" name="errorstomail" value="'.$errorstomail.'" />';
817  $out.= "</td></tr>\n";
818  }
819  }
820 
821  // Ask delivery receipt
822  if (! empty($this->withdeliveryreceipt))
823  {
824  $out.= '<tr><td>'.$langs->trans("DeliveryReceipt").'</td><td>';
825 
826  if (! empty($this->withdeliveryreceiptreadonly))
827  {
828  $out.= yn($this->withdeliveryreceipt);
829  }
830  else
831  {
832  $defaultvaluefordeliveryreceipt=0;
833  if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_PROPAL) && ! empty($this->param['models']) && $this->param['models'] == 'propal_send') $defaultvaluefordeliveryreceipt=1;
834  if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_SUPPLIER_PROPOSAL) && ! empty($this->param['models']) && $this->param['models'] == 'supplier_proposal_send') $defaultvaluefordeliveryreceipt=1;
835  if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_ORDER) && ! empty($this->param['models']) && $this->param['models'] == 'order_send') $defaultvaluefordeliveryreceipt=1;
836  if (! empty($conf->global->MAIL_FORCE_DELIVERY_RECEIPT_INVOICE) && ! empty($this->param['models']) && $this->param['models'] == 'facture_send') $defaultvaluefordeliveryreceipt=1;
837  $out.= $form->selectyesno('deliveryreceipt', (isset($_POST["deliveryreceipt"])?$_POST["deliveryreceipt"]:$defaultvaluefordeliveryreceipt), 1);
838  }
839 
840  $out.= "</td></tr>\n";
841  }
842 
843  // Topic
844  if (! empty($this->withtopic))
845  {
846  $defaulttopic=GETPOST('subject','none');
847  if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1')
848  {
849  if ($arraydefaultmessage && $arraydefaultmessage->topic) {
850  $defaulttopic = $arraydefaultmessage->topic;
851  } elseif (! is_numeric($this->withtopic)) {
852  $defaulttopic = $this->withtopic;
853  }
854  }
855 
856  $defaulttopic=make_substitutions($defaulttopic,$this->substit);
857 
858  $out.= '<tr>';
859  $out.= '<td class="fieldrequired">';
860  $out.=$form->textwithpicto($langs->trans('MailTopic'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfromtopic');
861  $out.='</td>';
862  $out.= '<td>';
863  if ($this->withtopicreadonly)
864  {
865  $out.= $defaulttopic;
866  $out.= '<input type="hidden" class="quatrevingtpercent" id="subject" name="subject" value="'.$defaulttopic.'" />';
867  }
868  else
869  {
870  $out.= '<input type="text" class="quatrevingtpercent" id="subject" name="subject" value="'. ((isset($_POST["subject"]) && ! $_POST['modelselected'])?$_POST["subject"]:($defaulttopic?$defaulttopic:'')) .'" />';
871  }
872  $out.= "</td></tr>\n";
873  }
874 
875  // Attached files
876  if (! empty($this->withfile))
877  {
878  $out.= '<tr>';
879  $out.= '<td>'.$langs->trans("MailFile").'</td>';
880 
881  $out.= '<td>';
882 
883  if ($this->withmaindocfile) // withmaindocfile is set to 1 or -1 to show the checkbox (-1 = checked or 1 = not checked)
884  {
885  if (GETPOSTISSET('sendmail'))
886  {
887  $this->withmaindocfile = (GETPOST('addmaindocfile', 'alpha') ? -1 : 1);
888  }
889  // If a template was selected, we use setup of template to define if join file checkbox is selected or not.
890  elseif (is_object($arraydefaultmessage) && $arraydefaultmessage->id > 0)
891  {
892  $this->withmaindocfile = ($arraydefaultmessage->joinfiles ? -1 : 1);
893  }
894  }
895 
896  if (! empty($this->withmaindocfile))
897  {
898  if ($this->withmaindocfile == 1)
899  {
900  $out.='<input type="checkbox" name="addmaindocfile" value="1" />';
901  }
902  if ($this->withmaindocfile == -1)
903  {
904  $out.='<input type="checkbox" name="addmaindocfile" value="1" checked="checked" />';
905  }
906  $out.=' '.$langs->trans("JoinMainDoc").'.<br>';
907  }
908 
909  if (is_numeric($this->withfile))
910  {
911  // TODO Trick to have param removedfile containing nb of file to delete. But this does not works without javascript
912  $out.= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
913  $out.= '<script type="text/javascript" language="javascript">';
914  $out.= 'jQuery(document).ready(function () {';
915  $out.= ' jQuery(".removedfile").click(function() {';
916  $out.= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
917  $out.= ' });';
918  $out.= '})';
919  $out.= '</script>'."\n";
920  if (count($listofpaths))
921  {
922  foreach($listofpaths as $key => $val)
923  {
924  $out.= '<div id="attachfile_'.$key.'">';
925  $out.= img_mime($listofnames[$key]).' '.$listofnames[$key];
926  if (! $this->withfilereadonly)
927  {
928  $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.'" />';
929  //$out.= ' <a href="'.$_SERVER["PHP_SELF"].'?removedfile='.($key+1).' id="removedfile_'.$key.'">'.img_delete($langs->trans("Delete").'</a>';
930  }
931  $out.= '<br></div>';
932  }
933  }
934  else if (empty($this->withmaindocfile)) // Do not show message if we asked to show the checkbox
935  {
936  $out.= $langs->trans("NoAttachedFiles").'<br>';
937  }
938  if ($this->withfile == 2) // Can add other files
939  {
940  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 />';
941  else $out.= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
942  $out.= ' ';
943  $out.= '<input class="button" type="submit" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
944  }
945  }
946  else
947  {
948  $out.=$this->withfile;
949  }
950 
951  $out.= "</td></tr>\n";
952  }
953 
954  // Message
955  if (! empty($this->withbody))
956  {
957  $defaultmessage=GETPOST('message','none');
958  if (! GETPOST('modelselected','alpha') || GETPOST('modelmailselected') != '-1')
959  {
960  if ($arraydefaultmessage && $arraydefaultmessage->content) {
961  $defaultmessage = $arraydefaultmessage->content;
962  } elseif (! is_numeric($this->withbody)) {
963  $defaultmessage = $this->withbody;
964  }
965  }
966 
967  // Complete substitution array with the url to make online payment
968  $paymenturl=''; $validpaymentmethod=array();
969  if (empty($this->substit['__REF__']))
970  {
971  $paymenturl='';
972  }
973  else
974  {
975  // Set the online payment url link into __ONLINE_PAYMENT_URL__ key
976  require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
977  $langs->loadLangs(array('paypal','other'));
978  $typeforonlinepayment='free';
979  if ($this->param["models"]=='order' || $this->param["models"]=='order_send') $typeforonlinepayment='order'; // TODO use detection on something else than template
980  if ($this->param["models"]=='invoice' || $this->param["models"]=='facture_send') $typeforonlinepayment='invoice'; // TODO use detection on something else than template
981  if ($this->param["models"]=='member') $typeforonlinepayment='member'; // TODO use detection on something else than template
982  $url=getOnlinePaymentUrl(0, $typeforonlinepayment, $this->substit['__REF__']);
983  $paymenturl=$url;
984 
985  $validpaymentmethod = getValidOnlinePaymentMethods('');
986  }
987 
988  if (count($validpaymentmethod) > 0 && $paymenturl)
989  {
990  $langs->load('other');
991  $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']=str_replace('\n', "\n", $langs->transnoentities("PredefinedMailContentLink", $paymenturl));
992  $this->substit['__ONLINE_PAYMENT_URL__']=$paymenturl;
993  }
994  else
995  {
996  $this->substit['__ONLINE_PAYMENT_TEXT_AND_URL__']='';
997  $this->substit['__ONLINE_PAYMENT_URL__']='';
998  }
999 
1000  //Add lines substitution key from each line
1001  $lines = '';
1002  $defaultlines = $arraydefaultmessage->content_lines;
1003  if (isset($defaultlines))
1004  {
1005  foreach ($this->substit_lines as $substit_line)
1006  {
1007  $lines .= make_substitutions($defaultlines,$substit_line)."\n";
1008  }
1009  }
1010  $this->substit['__LINES__']=$lines;
1011 
1012  $defaultmessage=str_replace('\n',"\n",$defaultmessage);
1013 
1014  // Deal with format differences between message and signature (text / HTML)
1015  if (dol_textishtml($defaultmessage) && !dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
1016  $this->substit['__USER_SIGNATURE__'] = dol_nl2br($this->substit['__USER_SIGNATURE__']);
1017  } else if(!dol_textishtml($defaultmessage) && dol_textishtml($this->substit['__USER_SIGNATURE__'])) {
1018  $defaultmessage = dol_nl2br($defaultmessage);
1019  }
1020 
1021  if (isset($_POST["message"]) && ! $_POST['modelselected']) $defaultmessage=$_POST["message"];
1022  else
1023  {
1024  $defaultmessage=make_substitutions($defaultmessage,$this->substit);
1025  // Clean first \n and br (to avoid empty line when CONTACTCIVNAME is empty)
1026  $defaultmessage=preg_replace("/^(<br>)+/","",$defaultmessage);
1027  $defaultmessage=preg_replace("/^\n+/","",$defaultmessage);
1028  }
1029 
1030  $out.= '<tr>';
1031  $out.= '<td valign="top">';
1032  $out.=$form->textwithpicto($langs->trans('MailText'), $helpforsubstitution, 1, 'help', '', 0, 2, 'substittooltipfrombody');
1033  $out.='</td>';
1034  $out.= '<td>';
1035  if ($this->withbodyreadonly)
1036  {
1037  $out.= nl2br($defaultmessage);
1038  $out.= '<input type="hidden" id="message" name="message" value="'.$defaultmessage.'" />';
1039  }
1040  else
1041  {
1042  if (! isset($this->ckeditortoolbar)) $this->ckeditortoolbar = 'dolibarr_notes';
1043 
1044  // Editor wysiwyg
1045  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1046  if ($this->withfckeditor == -1)
1047  {
1048  if (! empty($conf->global->FCKEDITOR_ENABLE_MAIL)) $this->withfckeditor=1;
1049  else $this->withfckeditor=0;
1050  }
1051 
1052  $doleditor=new DolEditor('message',$defaultmessage,'',280,$this->ckeditortoolbar,'In',true,true,$this->withfckeditor,8,'95%');
1053  $out.= $doleditor->Create(1);
1054  }
1055  $out.= "</td></tr>\n";
1056  }
1057 
1058  $out.= '</table>'."\n";
1059 
1060  if ($this->withform == 1 || $this->withform == -1)
1061  {
1062  $out.= '<br><div class="center">';
1063  $out.= '<input class="button" type="submit" id="sendmail" name="sendmail" value="'.$langs->trans("SendMail").'"';
1064  // Add a javascript test to avoid to forget to submit file before sending email
1065  if ($this->withfile == 2 && $conf->use_javascript_ajax)
1066  {
1067  $out.= ' onClick="if (document.mailform.addedfile.value != \'\') { alert(\''.dol_escape_js($langs->trans("FileWasNotUploaded")).'\'); return false; } else { return true; }"';
1068  }
1069  $out.= ' />';
1070  if ($this->withcancel)
1071  {
1072  $out.= ' &nbsp; &nbsp; ';
1073  $out.= '<input class="button" type="submit" id="cancel" name="cancel" value="'.$langs->trans("Cancel").'" />';
1074  }
1075  $out.= '</div>'."\n";
1076  }
1077 
1078  if ($this->withform == 1) $out.= '</form>'."\n";
1079 
1080  // Disable enter key if option MAIN_MAILFORM_DISABLE_ENTERKEY is set
1081  if (! empty($conf->global->MAIN_MAILFORM_DISABLE_ENTERKEY))
1082  {
1083  $out.= '<script type="text/javascript" language="javascript">';
1084  $out.= 'jQuery(document).ready(function () {';
1085  $out.= ' $(document).on("keypress", \'#mailform\', function (e) { /* Note this is called at every key pressed ! */
1086  var code = e.keyCode || e.which;
1087  if (code == 13) {
1088  e.preventDefault();
1089  return false;
1090  }
1091  });';
1092  $out.=' })';
1093  $out.= '</script>';
1094  }
1095 
1096  $out.= "<!-- End form mail -->\n";
1097 
1098  return $out;
1099  }
1100  }
1101 
1102 
1103 
1117  public function getEMailTemplate($db, $type_template, $user, $outputlangs, $id=0, $active=1, $label='')
1118  {
1119  $ret = new ModelMail();
1120 
1121  if ($id == -2 && empty($label))
1122  {
1123  $this->error = 'LabelIsMandatoryWhenIdIs-2';
1124  return -1;
1125  }
1126 
1127  $sql = "SELECT rowid, label, topic, joinfiles, content, content_lines, lang";
1128  $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
1129  $sql.= " WHERE (type_template='".$db->escape($type_template)."' OR type_template='all')";
1130  $sql.= " AND entity IN (".getEntity('c_email_templates').")";
1131  $sql.= " AND (private = 0 OR fk_user = ".$user->id.")"; // Get all public or private owned
1132  if ($active >= 0) $sql.=" AND active = ".$active;
1133  if ($label) $sql.=" AND label ='".$db->escape($label)."'";
1134  if (! ($id > 0) && is_object($outputlangs)) $sql.= " AND (lang = '".$db->escape($outputlangs->defaultlang)."' OR lang IS NULL OR lang = '')";
1135  if ($id > 0) $sql.= " AND rowid=".$id;
1136  if ($id == -1) $sql.= " AND position=0";
1137  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 ''
1138  else $sql.= $db->order("position,lang,label","ASC,ASC,ASC"); // If no language provided, we give priority to lang not defined
1139  $sql.= $db->plimit(1);
1140  //print $sql;
1141 
1142  $resql = $db->query($sql);
1143  if ($resql)
1144  {
1145  // Get first found
1146  $obj = $db->fetch_object($resql);
1147 
1148  if ($obj) {
1149  $ret->id = $obj->rowid;
1150  $ret->label = $obj->label;
1151  $ret->lang = $obj->lang;
1152  $ret->topic = $obj->topic;
1153  $ret->content = $obj->content;
1154  $ret->content_lines = $obj->content_lines;
1155  $ret->joinfiles = $obj->joinfiles;
1156  }
1157  elseif($id == -2) {
1158  // Not found with the provided label
1159  return -1;
1160  }
1161  else { // If there is no template at all
1162  $defaultmessage='';
1163  if ($type_template=='body') { $defaultmessage=$this->withbody; } // Special case to use this->withbody as content
1164  elseif ($type_template=='facture_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoice"); }
1165  elseif ($type_template=='facture_relance') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendInvoiceReminder"); }
1166  elseif ($type_template=='propal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendProposal"); }
1167  elseif ($type_template=='supplier_proposal_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierProposal"); }
1168  elseif ($type_template=='order_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendOrder"); }
1169  elseif ($type_template=='order_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierOrder"); }
1170  elseif ($type_template=='invoice_supplier_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendSupplierInvoice"); }
1171  elseif ($type_template=='shipping_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendShipping"); }
1172  elseif ($type_template=='fichinter_send') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentSendFichInter"); }
1173  elseif ($type_template=='thirdparty') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentThirdparty"); }
1174  elseif ($type_template=='user') { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContentUser"); }
1175  elseif (!empty($type_template)) { $defaultmessage=$outputlangs->transnoentities("PredefinedMailContent".ucfirst($type_template)); }
1176 
1177  $ret->label = 'default';
1178  $ret->lang = $outputlangs->defaultlang;
1179  $ret->topic = '';
1180  $ret->joinfiles = 1;
1181  $ret->content = $defaultmessage;
1182  $ret->content_lines ='';
1183  }
1184 
1185  $db->free($resql);
1186  return $ret;
1187  }
1188  else
1189  {
1190  dol_print_error($db);
1191  return -1;
1192  }
1193  }
1194 
1204  public function isEMailTemplate($type_template, $user, $outputlangs)
1205  {
1206  $ret=array();
1207 
1208  $sql = "SELECT label, topic, content, lang";
1209  $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
1210  $sql.= " WHERE type_template='".$this->db->escape($type_template)."'";
1211  $sql.= " AND entity IN (".getEntity('c_email_templates').")";
1212  $sql.= " AND (fk_user is NULL or fk_user = 0 or fk_user = ".$user->id.")";
1213  if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')";
1214  $sql.= $this->db->order("lang,label","ASC");
1215  //print $sql;
1216 
1217  $resql = $this->db->query($sql);
1218  if ($resql)
1219  {
1220  $num= $this->db->num_rows($resql);
1221  $this->db->free($resql);
1222  return $num;
1223  }
1224  else
1225  {
1226  $this->error=get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1227  return -1;
1228  }
1229  }
1230 
1241  public function fetchAllEMailTemplate($type_template, $user, $outputlangs, $active=1)
1242  {
1243  $ret=array();
1244 
1245  $sql = "SELECT rowid, label, topic, content, content_lines, lang, fk_user, private, position";
1246  $sql.= " FROM ".MAIN_DB_PREFIX.'c_email_templates';
1247  $sql.= " WHERE type_template IN ('".$this->db->escape($type_template)."', 'all')";
1248  $sql.= " AND entity IN (".getEntity('c_email_templates').")";
1249  $sql.= " AND (private = 0 OR fk_user = ".$user->id.")"; // See all public templates or templates I own.
1250  if ($active >= 0) $sql.=" AND active = ".$active;
1251  //if (is_object($outputlangs)) $sql.= " AND (lang = '".$outputlangs->defaultlang."' OR lang IS NULL OR lang = '')"; // Return all languages
1252  $sql.= $this->db->order("position,lang,label","ASC");
1253  //print $sql;
1254 
1255  $resql = $this->db->query($sql);
1256  if ($resql)
1257  {
1258  $num=$this->db->num_rows($resql);
1259  $this->lines_model=array();
1260  while ($obj = $this->db->fetch_object($resql))
1261  {
1262  $line = new ModelMail();
1263  $line->id=$obj->rowid;
1264  $line->label=$obj->label;
1265  $line->lang=$obj->lang;
1266  $line->fk_user=$obj->fk_user;
1267  $line->private=$obj->private;
1268  $line->position=$obj->position;
1269  $line->topic=$obj->topic;
1270  $line->content=$obj->content;
1271  $line->content_lines=$obj->content_lines;
1272 
1273  $this->lines_model[]=$line;
1274  }
1275  $this->db->free($resql);
1276  return $num;
1277  }
1278  else
1279  {
1280  $this->error=get_class($this).' '.__METHOD__.' ERROR:'.$this->db->lasterror();
1281  return -1;
1282  }
1283  }
1284 
1285 
1286 
1295  function setSubstitFromObject($object, $outputlangs)
1296  {
1297  global $conf, $user;
1298 
1299  $parameters=array();
1300  $tmparray=getCommonSubstitutionArray($outputlangs, 0, null, $object);
1301  complete_substitutions_array($tmparray, $outputlangs, null, $parameters);
1302 
1303  $this->substit=$tmparray;
1304 
1305  // Fill substit_lines with each object lines content
1306  if (is_array($object->lines))
1307  {
1308  foreach ($object->lines as $line)
1309  {
1310  $substit_line = array(
1311  '__PRODUCT_REF__' => isset($line->product_ref) ? $line->product_ref : '',
1312  '__PRODUCT_LABEL__' => isset($line->product_label) ? $line->product_label : '',
1313  '__PRODUCT_DESCRIPTION__' => isset($line->product_desc) ? $line->product_desc : '',
1314  '__LABEL__' => isset($line->label) ? $line->label : '',
1315  '__DESCRIPTION__' => isset($line->desc) ? $line->desc : '',
1316  '__DATE_START_YMD__' => dol_print_date($line->date_start, 'day', 0, $outputlangs),
1317  '__DATE_END_YMD__' => dol_print_date($line->date_end, 'day', 0, $outputlangs),
1318  '__QUANTITY__' => $line->qty,
1319  '__SUBPRICE__' => price($line->subprice),
1320  '__AMOUNT__' => price($line->total_ttc),
1321  '__AMOUNT_EXCL_TAX__' => price($line->total_ht)
1322  );
1323 
1324  // Create dynamic tags for __PRODUCT_EXTRAFIELD_FIELD__
1325  if (!empty($line->fk_product))
1326  {
1327  if (! is_object($extrafields)) $extrafields = new ExtraFields($this->db);
1328  $extrafields->fetch_name_optionals_label('product', true);
1329  $product = new Product($this->db);
1330  $product->fetch($line->fk_product, '', '', 1);
1331  $product->fetch_optionals();
1332  if (is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label']) > 0)
1333  {
1334  foreach ($extrafields->attributes[$product->table_element]['label'] as $key => $label) {
1335  $substit_line['__PRODUCT_EXTRAFIELD_' . strtoupper($key) . '__'] = $product->array_options['options_' . $key];
1336  }
1337  }
1338  }
1339  $this->substit_lines[] = $substit_line;
1340  }
1341  }
1342  }
1343 
1352  static function getAvailableSubstitKey($mode='formemail', $object=null)
1353  {
1354  global $conf, $langs;
1355 
1356  $tmparray=array();
1357  if ($mode == 'formemail' || $mode == 'formemailwithlines' || $mode == 'formemailforlines')
1358  {
1359  $parameters=array('mode'=>$mode);
1360  $tmparray=getCommonSubstitutionArray($langs, 2, null, $object); // Note: On email templated edition, this is null because it is related to all type of objects
1361  complete_substitutions_array($tmparray, $langs, null, $parameters);
1362 
1363  if ($mode == 'formwithlines')
1364  {
1365  $tmparray['__LINES__'] = '__LINES__'; // Will be set by the get_form function
1366  }
1367  if ($mode == 'formforlines')
1368  {
1369  $tmparray['__QUANTITY__'] = '__QUANTITY__'; // Will be set by the get_form function
1370  }
1371  }
1372 
1373  if ($mode == 'emailing')
1374  {
1375  $parameters=array('mode'=>$mode);
1376  $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
1377  complete_substitutions_array($tmparray, $langs, null, $parameters);
1378 
1379  // For mass emailing, we have different keys
1380  $tmparray['__ID__'] = 'IdRecord';
1381  $tmparray['__EMAIL__'] = 'EMailRecipient';
1382  $tmparray['__LASTNAME__'] = 'Lastname';
1383  $tmparray['__FIRSTNAME__'] = 'Firstname';
1384  $tmparray['__MAILTOEMAIL__'] = 'TagMailtoEmail';
1385  $tmparray['__OTHER1__'] = 'Other1';
1386  $tmparray['__OTHER2__'] = 'Other2';
1387  $tmparray['__OTHER3__'] = 'Other3';
1388  $tmparray['__OTHER4__'] = 'Other4';
1389  $tmparray['__OTHER5__'] = 'Other5';
1390  $tmparray['__USER_SIGNATURE__'] = 'TagSignature';
1391  $tmparray['__CHECK_READ__'] = 'TagCheckMail';
1392  $tmparray['__UNSUBSCRIBE__'] = 'TagUnsubscribe';
1393  //,'__PERSONALIZED__' => 'Personalized' // Hidden because not used yet in mass emailing
1394 
1395  $onlinepaymentenabled = 0;
1396  if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++;
1397  if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++;
1398  if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++;
1399  if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN))
1400  {
1401  $tmparray['__SECUREKEYPAYMENT__']=$conf->global->PAYMENT_SECURITY_TOKEN;
1402  if (! empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
1403  {
1404  if ($conf->adherent->enabled) $tmparray['__SECUREKEYPAYMENT_MEMBER__']='SecureKeyPAYMENTUniquePerMember';
1405  if ($conf->facture->enabled) $tmparray['__SECUREKEYPAYMENT_INVOICE__']='SecureKeyPAYMENTUniquePerInvoice';
1406  if ($conf->commande->enabled) $tmparray['__SECUREKEYPAYMENT_ORDER__']='SecureKeyPAYMENTUniquePerOrder';
1407  if ($conf->contrat->enabled) $tmparray['__SECUREKEYPAYMENT_CONTRACTLINE__']='SecureKeyPAYMENTUniquePerContractLine';
1408  }
1409  }
1410  else
1411  {
1412  /* No need to show into tooltip help, option is not enabled
1413  $vars['__SECUREKEYPAYMENT__']='';
1414  $vars['__SECUREKEYPAYMENT_MEMBER__']='';
1415  $vars['__SECUREKEYPAYMENT_INVOICE__']='';
1416  $vars['__SECUREKEYPAYMENT_ORDER__']='';
1417  $vars['__SECUREKEYPAYMENT_CONTRACTLINE__']='';
1418  */
1419  }
1420  }
1421 
1422  foreach($tmparray as $key => $val)
1423  {
1424  if (empty($val)) $tmparray[$key]=$key;
1425  }
1426 
1427  return $tmparray;
1428  }
1429 }
1430 
1431 
1435 class ModelMail
1436 {
1440  public $id;
1441 
1445  public $label;
1446 
1447  public $topic;
1448  public $content;
1449  public $content_lines;
1450  public $lang;
1451  public $joinfiles;
1452 }
print $object label
hash of file content (md5_file(dol_osencode($destfull))
Definition: edit.php:153
GETPOST($paramname, $check='none', $method=0, $filter=null, $options=null, $noreplace=0)
Return value of a param into GET or POST supervariable.
Classe permettant la generation du formulaire html d&#39;envoi de mail unitaire Usage: $formail = new For...
yn($yesno, $case=1, $color=0)
Return yes or no in current language.
print
Draft customers invoices.
Definition: index.php:91
setEventMessages($mesg, $mesgs, $style='mesgs')
Set event messages in dol_events session object.
if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) if(! empty($conf->don->enabled) && $user->rights->societe->lire) if(! empty($conf->tax->enabled) && $user->rights->tax->charges->lire) if(! empty($conf->facture->enabled) &&! empty($conf->commande->enabled) && $user->rights->commande->lire &&empty($conf->global->WORKFLOW_DISABLE_CREATE_INVOICE_FROM_ORDER)) if(! empty($conf->facture->enabled) && $user->rights->facture->lire) if(! empty($conf->fournisseur->enabled) && $user->rights->fournisseur->facture->lire) $resql
Social contributions to pay.
Definition: index.php:1053
__construct($db)
Constructor.
get_form($addfileaction='addfile', $removefileaction='removefile')
Get the form to input an email this->withfile: 0=No attaches files, 1=Show attached files...
Class to manage contact/addresses.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return mime type of a file.
getEMailTemplate($db, $type_template, $user, $outputlangs, $id=0, $active=1, $label='')
Return templates of email with type = $type_template or type = &#39;all&#39;.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
show_form($addfileaction='addfile', $removefileaction='removefile')
Show the form to input an email this->withfile: 0=No attaches files, 1=Show attached files...
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
static selectarray($htmlname, $array, $id='', $show_empty=0, $key_in_label=0, $value_as_key=0, $moreparam='', $translate=0, $maxlen=0, $disabled=0, $sort='', $morecss='', $addjscombo=0, $moreparamonempty='', $disablebademail=0, $nohtmlescape=0)
Return a HTML select string, built from an array of key+value.
Class to manage generation of HTML components Only common components must be here.
GETPOSTISSET($paramname)
Return true if we are in a context of submitting a parameter.
Class to manage third parties objects (customers, suppliers, prospects...)
info_admin($text, $infoonimgalt=0, $nodiv=0, $admin='1', $morecss='')
Show information for admin users or standard users.
dol_delete_dir_recursive($dir, $count=0, $nophperrors=0, $onlysub=0, &$countdeleted=0)
Remove a directory $dir and its subdirectories (or only files and subdirectories) ...
Definition: files.lib.php:1273
fetchAllEMailTemplate($type_template, $user, $outputlangs, $active=1)
Find if template exists and are available for current user, then set them into $this->lines_module.
Class to manage translations.
add_attached_files($path, $file='', $type='')
Add a file into the list of attached files (stored in SECTION array)
remove_attached_files($keytodelete)
Remove a file from the list of attached files (stored in SECTION array)
get_attached_files()
Return list of attached files (stored in SECTION array)
dol_string_nohtmltag($stringtoclean, $removelinefeed=1, $pagecodeto='UTF-8', $strip_tags=0)
Clean a string from all HTML tags and entities.
clear_attached_files()
Clear list of attached files in send mail form (also stored in session)
Class to manage a WYSIWYG editor.
make_substitutions($text, $substitutionarray, $outputlangs=null)
Make substitution into a text string, replacing keys with vals from $substitutionarray (oldval=>newva...
dol_htmlentities($string, $flags=null, $encoding='UTF-8', $double_encode=false)
Replace htmlentities functions.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
dol_textishtml($msg, $option=0)
Return if a text is a html content.