dolibarr  9.0.0
card.php
Go to the documentation of this file.
1 <?php
2 /* Copyright (C) 2004 Rodolphe Quiedeville <rodolphe@quiedeville.org>
3  * Copyright (C) 2005-2016 Laurent Destailleur <eldy@uers.sourceforge.net>
4  * Copyright (C) 2005-2016 Regis Houssin <regis.houssin@inodbox.com>
5  *
6  * This program is free software; you can redistribute it and/or modify
7  * it under the terms of the GNU General Public License as published by
8  * the Free Software Foundation; either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14  * GNU General Public License for more details.
15  *
16  * You should have received a copy of the GNU General Public License
17  * along with this program. If not, see <http://www.gnu.org/licenses/>.
18  */
19 
26 if (! defined('NOSTYLECHECK')) define('NOSTYLECHECK','1');
27 
28 require '../../main.inc.php';
29 require_once DOL_DOCUMENT_ROOT.'/core/lib/emailing.lib.php';
30 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
31 require_once DOL_DOCUMENT_ROOT.'/core/class/CMailFile.class.php';
32 require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php';
33 require_once DOL_DOCUMENT_ROOT.'/comm/mailing/class/mailing.class.php';
34 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formother.class.php';
35 require_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
36 require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php';
37 
38 // Load translation files required by the page
39 $langs->load("mails");
40 
41 if (! $user->rights->mailing->lire || (empty($conf->global->EXTERNAL_USERS_ARE_AUTHORIZED) && $user->societe_id > 0)) accessforbidden();
42 
43 $id=(GETPOST('mailid','int') ? GETPOST('mailid','int') : GETPOST('id','int'));
44 $action=GETPOST('action','alpha');
45 $confirm=GETPOST('confirm','alpha');
46 $urlfrom=GETPOST('urlfrom');
47 
48 $object=new Mailing($db);
49 $result=$object->fetch($id);
50 
51 $extrafields = new ExtraFields($db);
52 
53 // fetch optionals attributes and labels
54 $extralabels=$extrafields->fetch_name_optionals_label($object->table_element);
55 
56 // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context
57 $hookmanager->initHooks(array('mailingcard','globalcard'));
58 
59 // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
60 $object->substitutionarray=FormMail::getAvailableSubstitKey('emailing');
61 
62 
63 // Set $object->substitutionarrayfortest
64 $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:'');
65 
66 $targetobject = null; // Not defined with mass emailing
67 
68 $parameters=array('mode'=>'emailing');
69 $substitutionarray=FormMail::getAvailableSubstitKey('emailing', $targetobject);
70 
71 $object->substitutionarrayfortest = $substitutionarray;
72 
73 // List of sending methods
74 $listofmethods=array();
75 $listofmethods['mail']='PHP mail function';
76 //$listofmethods['simplemail']='Simplemail class';
77 $listofmethods['smtps']='SMTP/SMTPS socket library';
78 
79 
80 
81 /*
82  * Actions
83  */
84 
85 $parameters=array();
86 $reshook=$hookmanager->executeHooks('doActions',$parameters,$object,$action); // Note that $action and $object may have been modified by some hooks
87 if ($reshook < 0) setEventMessages($hookmanager->error, $hookmanager->errors, 'errors');
88 
89 if (empty($reshook))
90 {
91  // Action clone object
92  if ($action == 'confirm_clone' && $confirm == 'yes')
93  {
94  if (empty($_REQUEST["clone_content"]) && empty($_REQUEST["clone_receivers"]))
95  {
96  setEventMessages($langs->trans("NoCloneOptionsSpecified"), null, 'errors');
97  }
98  else
99  {
100  $result=$object->createFromClone($object->id,$_REQUEST["clone_content"],$_REQUEST["clone_receivers"]);
101  if ($result > 0)
102  {
103  header("Location: ".$_SERVER['PHP_SELF'].'?id='.$result);
104  exit;
105  }
106  else
107  {
108  setEventMessages($object->error, $object->errors, 'errors');
109  }
110  }
111  $action='';
112  }
113 
114  // Action send emailing for everybody
115  if ($action == 'sendallconfirmed' && $confirm == 'yes')
116  {
117  if (empty($conf->global->MAILING_LIMIT_SENDBYWEB))
118  {
119  // As security measure, we don't allow send from the GUI
120  setEventMessages($langs->trans("MailingNeedCommand"), null, 'warnings');
121  setEventMessages('<textarea cols="70" rows="'.ROWS_2.'" wrap="soft">php ./scripts/emailings/mailing-send.php '.$object->id.'</textarea>', null, 'warnings');
122  setEventMessages($langs->trans("MailingNeedCommand2"), null, 'warnings');
123  $action='';
124  }
125  else if ($conf->global->MAILING_LIMIT_SENDBYWEB < 0)
126  {
127  setEventMessages($langs->trans("NotEnoughPermissions"), null, 'warnings');
128  $action='';
129  }
130  else
131  {
132  $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
133 
134  if ($object->statut == 0)
135  {
136  dol_print_error('','ErrorMailIsNotValidated');
137  exit;
138  }
139 
140  $id = $object->id;
141  $subject = $object->sujet;
142  $message = $object->body;
143  $from = $object->email_from;
144  $replyto = $object->email_replyto;
145  $errorsto = $object->email_errorsto;
146  // Le message est-il en html
147  $msgishtml=-1; // Unknown by default
148  if (preg_match('/[\s\t]*<html>/i',$message)) $msgishtml=1;
149 
150  // Warning, we must not use begin-commit transaction here
151  // because we want to save update for each mail sent.
152 
153  $nbok=0; $nbko=0;
154 
155  // On choisit les mails non deja envoyes pour ce mailing (statut=0)
156  // ou envoyes en erreur (statut=-1)
157  $sql = "SELECT mc.rowid, mc.fk_mailing, mc.lastname, mc.firstname, mc.email, mc.other, mc.source_url, mc.source_id, mc.source_type, mc.tag";
158  $sql .= " FROM ".MAIN_DB_PREFIX."mailing_cibles as mc";
159  $sql .= " WHERE mc.statut < 1 AND mc.fk_mailing = ".$object->id;
160  $sql .= " ORDER BY mc.statut DESC"; // first status 0, then status -1
161 
162  dol_syslog("card.php: select targets", LOG_DEBUG);
163  $resql=$db->query($sql);
164  if ($resql)
165  {
166  $num = $db->num_rows($resql); // nb of possible recipients
167 
168  if ($num)
169  {
170  dol_syslog("comm/mailing/card.php: nb of targets = ".$num, LOG_DEBUG);
171 
172  $now=dol_now();
173 
174  // Positionne date debut envoi
175  $sql="UPDATE ".MAIN_DB_PREFIX."mailing SET date_envoi='".$db->idate($now)."' WHERE rowid=".$object->id;
176  $resql2=$db->query($sql);
177  if (! $resql2)
178  {
179  dol_print_error($db);
180  }
181 
182  // Loop on each email and send it
183  $i = 0;
184 
185  while ($i < $num && $i < $conf->global->MAILING_LIMIT_SENDBYWEB)
186  {
187  // Here code is common with same loop ino mailing-send.php
188  $res=1;
189  $now=dol_now();
190 
191  $obj = $db->fetch_object($resql);
192 
193  // sendto en RFC2822
194  $sendto = str_replace(',',' ',dolGetFirstLastname($obj->firstname, $obj->lastname))." <".$obj->email.">";
195 
196  // Make substitutions on topic and body. From (AA=YY;BB=CC;...) we keep YY, CC, ...
197  $other=explode(';',$obj->other);
198  $tmpfield=explode('=',$other[0],2); $other1=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
199  $tmpfield=explode('=',$other[1],2); $other2=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
200  $tmpfield=explode('=',$other[2],2); $other3=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
201  $tmpfield=explode('=',$other[3],2); $other4=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
202  $tmpfield=explode('=',$other[4],2); $other5=(isset($tmpfield[1])?$tmpfield[1]:$tmpfield[0]);
203 
204  $signature = ((!empty($user->signature) && empty($conf->global->MAIN_MAIL_DO_NOT_USE_SIGN))?$user->signature:'');
205 
206  $targetobject = null; // Not defined with mass emailing
207  $parameters=array('mode'=>'emailing');
208  $substitutionarray=getCommonSubstitutionArray($langs, 0, array('object','objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object
209 
210  // Array of possible substitutions (See also file mailing-send.php that should manage same substitutions)
211  $substitutionarray['__ID__'] = $obj->source_id;
212  $substitutionarray['__EMAIL__'] = $obj->email;
213  $substitutionarray['__LASTNAME__'] = $obj->lastname;
214  $substitutionarray['__FIRSTNAME__'] = $obj->firstname;
215  $substitutionarray['__MAILTOEMAIL__'] = '<a href="mailto:'.$obj->email.'">'.$obj->email.'</a>';
216  $substitutionarray['__OTHER1__'] = $other1;
217  $substitutionarray['__OTHER2__'] = $other2;
218  $substitutionarray['__OTHER3__'] = $other3;
219  $substitutionarray['__OTHER4__'] = $other4;
220  $substitutionarray['__OTHER5__'] = $other5;
221  $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter)
222  $substitutionarray['__SIGNATURE__'] = $signature; // For backward compatibility
223  $substitutionarray['__CHECK_READ__'] = '<img src="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-read.php?tag='.$obj->tag.'&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" width="1" height="1" style="width:1px;height:1px" border="0"/>';
224  $substitutionarray['__UNSUBSCRIBE__'] = '<a href="'.DOL_MAIN_URL_ROOT.'/public/emailing/mailing-unsubscribe.php?tag='.$obj->tag.'&unsuscrib=1&securitykey='.urlencode($conf->global->MAILING_EMAIL_UNSUBSCRIBE_KEY).'" target="_blank">'.$langs->trans("MailUnsubcribe").'</a>';
225 
226  $onlinepaymentenabled = 0;
227  if (! empty($conf->paypal->enabled)) $onlinepaymentenabled++;
228  if (! empty($conf->paybox->enabled)) $onlinepaymentenabled++;
229  if (! empty($conf->stripe->enabled)) $onlinepaymentenabled++;
230  if ($onlinepaymentenabled && ! empty($conf->global->PAYMENT_SECURITY_TOKEN))
231  {
232  $substitutionarray['__SECUREKEYPAYMENT__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
233  if (empty($conf->global->PAYMENT_SECURITY_TOKEN_UNIQUE))
234  {
235  $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
236  $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
237  $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
238  $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2);
239  }
240  else
241  {
242  $substitutionarray['__SECUREKEYPAYMENT_MEMBER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2);
243  $substitutionarray['__SECUREKEYPAYMENT_ORDER__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'order' . $obj->source_id, 2);
244  $substitutionarray['__SECUREKEYPAYMENT_INVOICE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2);
245  $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__']=dol_hash($conf->global->PAYMENT_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
246  }
247  }
248  /* For backward compatibility, deprecated */
249  if (! empty($conf->paypal->enabled) && ! empty($conf->global->PAYPAL_SECURITY_TOKEN))
250  {
251  $substitutionarray['__SECUREKEYPAYPAL__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
252 
253  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
254  else $substitutionarray['__SECUREKEYPAYPAL_MEMBER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'membersubscription' . $obj->source_id, 2);
255 
256  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
257  else $substitutionarray['__SECUREKEYPAYPAL_ORDER__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'order' . $obj->source_id, 2);
258 
259  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
260  else $substitutionarray['__SECUREKEYPAYPAL_INVOICE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'invoice' . $obj->source_id, 2);
261 
262  if (empty($conf->global->PAYPAL_SECURITY_TOKEN_UNIQUE)) $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2);
263  else $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__']=dol_hash($conf->global->PAYPAL_SECURITY_TOKEN . 'contractline' . $obj->source_id, 2);
264  }
265  //$substitutionisok=true;
266 
267  complete_substitutions_array($substitutionarray, $langs);
268  $newsubject=make_substitutions($subject,$substitutionarray);
269  $newmessage=make_substitutions($message,$substitutionarray);
270 
271  $arr_file = array();
272  $arr_mime = array();
273  $arr_name = array();
274  $arr_css = array();
275 
276  $listofpaths=dol_dir_list($upload_dir,'all',0,'','','name',SORT_ASC,0);
277  if (count($listofpaths))
278  {
279  foreach($listofpaths as $key => $val)
280  {
281  $arr_file[]=$listofpaths[$key]['fullname'];
282  $arr_mime[]=dol_mimetype($listofpaths[$key]['name']);
283  $arr_name[]=$listofpaths[$key]['name'];
284  }
285  }
286 
287  // Fabrication du mail
288  $trackid='emailing-'.$obj->fk_mailing.'-'.$obj->rowid;
289  $mail = new CMailFile($newsubject, $sendto, $from, $newmessage, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $errorsto, $arr_css, $trackid, '', 'emailing');
290 
291  if ($mail->error)
292  {
293  $res=0;
294  }
295  /*if (! $substitutionisok)
296  {
297  $mail->error='Some substitution failed';
298  $res=0;
299  }*/
300 
301  // Send mail
302  if ($res)
303  {
304  $res=$mail->sendfile();
305  }
306 
307  if ($res)
308  {
309  // Mail successful
310  $nbok++;
311 
312  dol_syslog("comm/mailing/card.php: ok for #".$i.($mail->error?' - '.$mail->error:''), LOG_DEBUG);
313 
314  $sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
315  $sql.=" SET statut=1, date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid;
316  $resql2=$db->query($sql);
317  if (! $resql2)
318  {
319  dol_print_error($db);
320  }
321  else
322  {
323  //if cheack read is use then update prospect contact status
324  if (strpos($message, '__CHECK_READ__') !== false)
325  {
326  //Update status communication of thirdparty prospect
327  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT source_id FROM ".MAIN_DB_PREFIX."mailing_cibles WHERE rowid=".$obj->rowid.")";
328  dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG);
329  $resql2=$db->query($sql);
330  if (! $resql2)
331  {
332  dol_print_error($db);
333  }
334 
335  //Update status communication of contact prospect
336  $sql = "UPDATE ".MAIN_DB_PREFIX."societe SET fk_stcomm=2 WHERE rowid IN (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."socpeople AS sc INNER JOIN ".MAIN_DB_PREFIX."mailing_cibles AS mc ON mc.rowid=".$obj->rowid." AND mc.source_type = 'contact' AND mc.source_id = sc.rowid)";
337  dol_syslog("card.php: set prospect contact status", LOG_DEBUG);
338 
339  $resql2=$db->query($sql);
340  if (! $resql2)
341  {
342  dol_print_error($db);
343  }
344  }
345  }
346 
347  if (!empty($conf->global->MAILING_DELAY))
348  {
349  sleep($conf->global->MAILING_DELAY);
350  }
351 
352  //test if CHECK READ change statut prospect contact
353  }
354  else
355  {
356  // Mail failed
357  $nbko++;
358 
359  dol_syslog("comm/mailing/card.php: error for #".$i.($mail->error?' - '.$mail->error:''), LOG_WARNING);
360 
361  $sql="UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
362  $sql.=" SET statut=-1, error_text='".$db->escape($mail->error)."', date_envoi='".$db->idate($now)."' WHERE rowid=".$obj->rowid;
363  $resql2=$db->query($sql);
364  if (! $resql2)
365  {
366  dol_print_error($db);
367  }
368  }
369 
370  $i++;
371  }
372  }
373  else
374  {
375  setEventMessages($langs->transnoentitiesnoconv("NoMoreRecipientToSendTo"), null, 'mesgs');
376  }
377 
378  // Loop finished, set global statut of mail
379  if ($nbko > 0)
380  {
381  $statut=2; // Status 'sent partially' (because at least one error)
382  if ($nbok > 0) setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients",$nbok), null, 'mesgs');
383  else setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients",$nbok), null, 'mesgs');
384  }
385  else
386  {
387  if ($nbok >= $num)
388  {
389  $statut=3; // Send to everybody
390  setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients",$nbok), null, 'mesgs');
391  }
392  else
393  {
394  $statut=2; // Status 'sent partially' (because not send to everybody)
395  setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients",$nbok), null, 'mesgs');
396  }
397  }
398 
399  $sql="UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".$statut." WHERE rowid=".$object->id;
400  dol_syslog("comm/mailing/card.php: update global status", LOG_DEBUG);
401  $resql2=$db->query($sql);
402  if (! $resql2)
403  {
404  dol_print_error($db);
405  }
406  }
407  else
408  {
409  dol_syslog($db->error());
410  dol_print_error($db);
411  }
412 
413  $action = '';
414  }
415  }
416 
417  // Action send test emailing
418  if ($action == 'send' && empty($_POST["cancel"]))
419  {
420  $error=0;
421 
422  $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
423 
424  $object->sendto = $_POST["sendto"];
425  if (! $object->sendto)
426  {
427  setEventMessages($langs->trans("ErrorFieldRequired", $langs->trans("MailTo")), null, 'errors');
428  $error++;
429  }
430 
431  if (! $error)
432  {
433  // Le message est-il en html
434  $msgishtml=-1; // Inconnu par defaut
435  if (preg_match('/[\s\t]*<html>/i',$object->body)) $msgishtml=1;
436 
437  // other are set at begin of page
438  $object->substitutionarrayfortest['__EMAIL__'] = $object->sendto;
439  $object->substitutionarrayfortest['__MAILTOEMAIL__'] = '<a href="mailto:'.$object->sendto.'">'.$object->sendto.'</a>';
440 
441  // Pratique les substitutions sur le sujet et message
442  complete_substitutions_array($object->substitutionarrayfortest, $langs);
443  $tmpsujet=make_substitutions($object->sujet,$object->substitutionarrayfortest);
444  $tmpbody=make_substitutions($object->body,$object->substitutionarrayfortest);
445 
446  $arr_file = array();
447  $arr_mime = array();
448  $arr_name = array();
449  $arr_css = array();
450 
451  // Ajout CSS
452  if (!empty($object->bgcolor)) $arr_css['bgcolor'] = (preg_match('/^#/',$object->bgcolor)?'':'#').$object->bgcolor;
453  if (!empty($object->bgimage)) $arr_css['bgimage'] = $object->bgimage;
454 
455  // Attached files
456  $listofpaths=dol_dir_list($upload_dir,'all',0,'','','name',SORT_ASC,0);
457  if (count($listofpaths))
458  {
459  foreach($listofpaths as $key => $val)
460  {
461  $arr_file[]=$listofpaths[$key]['fullname'];
462  $arr_mime[]=dol_mimetype($listofpaths[$key]['name']);
463  $arr_name[]=$listofpaths[$key]['name'];
464  }
465  }
466 
467  $trackid='emailingtest';
468  $mailfile = new CMailFile($tmpsujet, $object->sendto, $object->email_from, $tmpbody, $arr_file, $arr_mime, $arr_name, '', '', 0, $msgishtml, $object->email_errorsto, $arr_css, $trackid, '', 'emailing');
469 
470  $result=$mailfile->sendfile();
471  if ($result)
472  {
473  setEventMessages($langs->trans("MailSuccessfulySent",$mailfile->getValidAddress($object->email_from,2),$mailfile->getValidAddress($object->sendto,2)), null, 'mesgs');
474  }
475  else
476  {
477  setEventMessages($langs->trans("ResultKo").'<br>'.$mailfile->error.' '.$result, null, 'errors');
478  }
479 
480  $action='';
481  }
482  }
483 
484  // Action add emailing
485  if ($action == 'add')
486  {
487  $mesgs = array();
488 
489  $object->email_from = trim($_POST["from"]);
490  $object->email_replyto = trim($_POST["replyto"]);
491  $object->email_errorsto = trim($_POST["errorsto"]);
492  $object->titre = trim($_POST["titre"]);
493  $object->sujet = trim($_POST["sujet"]);
494  $object->body = trim($_POST["bodyemail"]);
495  $object->bgcolor = trim($_POST["bgcolor"]);
496  $object->bgimage = trim($_POST["bgimage"]);
497 
498  if (! $object->titre) {
499  $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTitle"));
500  }
501  if (! $object->sujet) {
502  $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTopic"));
503  }
504  if (! $object->body) {
505  $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailMessage"));
506  }
507 
508  if (!count($mesgs))
509  {
510  if ($object->create($user) >= 0)
511  {
512  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
513  exit;
514  }
515  $mesgs[] = $object->error;
516  }
517 
518  setEventMessages($mesg, $mesgs, 'errors');
519  $action="create";
520  }
521 
522  // Action update description of emailing
523  if ($action == 'settitre' || $action == 'setemail_from' || $action == 'setreplyto' || $action == 'setemail_errorsto')
524  {
525  $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
526 
527  if ($action == 'settitre') $object->titre = trim(GETPOST('titre','alpha'));
528  else if ($action == 'setemail_from') $object->email_from = trim(GETPOST('email_from','alpha'));
529  else if ($action == 'setemail_replyto') $object->email_replyto = trim(GETPOST('email_replyto','alpha'));
530  else if ($action == 'setemail_errorsto') $object->email_errorsto = trim(GETPOST('email_errorsto','alpha'));
531  else if ($action == 'settitre' && empty($object->titre)) {
532  $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTitle"));
533  }
534  else if ($action == 'setfrom' && empty($object->email_from)) {
535  $mesg = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailFrom"));
536  }
537 
538  if (! $mesg)
539  {
540  if ($object->update($user) >= 0)
541  {
542  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
543  exit;
544  }
545  $mesg = $object->error;
546  }
547 
548  setEventMessages($mesg, $mesgs, 'errors');
549  $action="";
550  }
551 
552  /*
553  * Add file in email form
554  */
555  if (! empty($_POST['addfile']))
556  {
557  $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
558 
559  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
560 
561  // Set tmp user directory
562  dol_add_file_process($upload_dir,0,0);
563 
564  $action="edit";
565  }
566 
567  // Action remove file
568  if (! empty($_POST["removedfile"]))
569  {
570  $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
571 
572  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
573 
574  dol_remove_file_process($_POST['removedfile'],0,0); // We really delete file linked to mailing
575 
576  $action="edit";
577  }
578 
579  // Action update emailing
580  if ($action == 'update' && empty($_POST["removedfile"]) && empty($_POST["cancel"]))
581  {
582  require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
583 
584  $isupload=0;
585 
586  if (! $isupload)
587  {
588  $mesgs = array();
589 
590  $object->sujet = trim($_POST["sujet"]);
591  $object->body = trim($_POST["bodyemail"]);
592  $object->bgcolor = trim($_POST["bgcolor"]);
593  $object->bgimage = trim($_POST["bgimage"]);
594 
595  if (! $object->sujet) {
596  $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailTopic"));
597  }
598  if (! $object->body) {
599  $mesgs[] = $langs->trans("ErrorFieldRequired",$langs->transnoentities("MailMessage"));
600  }
601 
602  if (!count($mesgs))
603  {
604  if ($object->update($user) >= 0)
605  {
606  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
607  exit;
608  }
609  $mesgs[] =$object->error;
610  }
611 
612  setEventMessages($mesg, $mesgs, 'errors');
613  $action="edit";
614  }
615  else
616  {
617  $action="edit";
618  }
619  }
620 
621  // Action confirmation validation
622  if ($action == 'confirm_valid' && $confirm == 'yes')
623  {
624  if ($object->id > 0)
625  {
626  $object->valid($user);
627  setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs');
628  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
629  exit;
630  }
631  else
632  {
633  dol_print_error($db);
634  }
635  }
636 
637  // Action confirmation validation
638  if ($action == 'confirm_settodraft' && $confirm == 'yes')
639  {
640  if ($object->id > 0)
641  {
642  $result = $object->setStatut(0);
643  if ($result > 0)
644  {
645  //setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs');
646  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
647  exit;
648  }
649  else
650  {
651  setEventMessages($object->error, $object->errors, 'errors');
652  }
653  }
654  else
655  {
656  dol_print_error($db);
657  }
658  }
659 
660  // Resend
661  if ($action == 'confirm_reset' && $confirm == 'yes')
662  {
663  if ($object->id > 0)
664  {
665  $db->begin();
666 
667  $result=$object->valid($user);
668  if ($result > 0)
669  {
670  $result=$object->reset_targets_status($user);
671  }
672 
673  if ($result > 0)
674  {
675  $db->commit();
676  header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
677  exit;
678  }
679  else
680  {
681  setEventMessages($object->error, $object->errors, 'errors');
682  $db->rollback();
683  }
684  }
685  else
686  {
687  dol_print_error($db);
688  }
689  }
690 
691  // Action confirmation suppression
692  if ($action == 'confirm_delete' && $confirm == 'yes')
693  {
694  if ($object->delete($object->id))
695  {
696  $url= (! empty($urlfrom) ? $urlfrom : 'list.php');
697  header("Location: ".$url);
698  exit;
699  }
700  }
701 
702  if (! empty($_POST["cancel"]))
703  {
704  $action = '';
705  }
706 }
707 
708 
709 /*
710  * View
711  */
712 
713 $form = new Form($db);
714 $htmlother = new FormOther($db);
715 
716 $help_url='EN:Module_EMailing|FR:Module_Mailing|ES:M&oacute;dulo_Mailing';
717 llxHeader('', $langs->trans("Mailing"), $help_url, '', 0, 0,
718  array(
719  '/includes/ace/ace.js',
720  '/includes/ace/ext-statusbar.js',
721  '/includes/ace/ext-language_tools.js',
722  //'/includes/ace/ext-chromevox.js'
723  ), array());
724 
725 if ($action == 'create')
726 {
727  // EMailing in creation mode
728  print '<form name="new_mailing" action="'.$_SERVER['PHP_SELF'].'" method="POST">'."\n";
729  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
730  print '<input type="hidden" name="action" value="add">';
731 
732  $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
733  foreach($object->substitutionarray as $key => $val)
734  {
735  $htmltext.=$key.' = '.$langs->trans($val).'<br>';
736  }
737  $htmltext.='</i>';
738 
739 
740  $availablelink=$form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'availvar');
741  //print '<a href="javascript:document_preview(\''.DOL_URL_ROOT.'/admin/modulehelp.php?id='.$objMod->numero.'\',\'text/html\',\''.dol_escape_js($langs->trans("Module")).'\')">'.img_picto($langs->trans("ClickToShowDescription"), $imginfo).'</a>';
742 
743 
744  // Print mail form
745  print load_fiche_titre($langs->trans("NewMailing"), $availablelink, 'title_generic');
746 
747  dol_fiche_head();
748 
749  print '<table class="border" width="100%">';
750  print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("MailTitle").'</td><td><input class="flat minwidth300" name="titre" value="'.dol_escape_htmltag(GETPOST('titre')).'" autofocus="autofocus"></td></tr>';
751  print '<tr><td class="fieldrequired">'.$langs->trans("MailFrom").'</td><td><input class="flat minwidth200" name="from" value="'.$conf->global->MAILING_EMAIL_FROM.'"></td></tr>';
752  print '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td><input class="flat minwidth200" name="errorsto" value="'.(!empty($conf->global->MAILING_EMAIL_ERRORSTO)?$conf->global->MAILING_EMAIL_ERRORSTO:$conf->global->MAIN_MAIL_ERRORS_TO).'"></td></tr>';
753 
754  // Other attributes
755  $parameters=array();
756  $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
757  print $hookmanager->resPrint;
758  if (empty($reshook))
759  {
760  print $object->showOptionals($extrafields,'edit');
761  }
762 
763  print '</table>';
764  print '</br><br>';
765 
766  print '<table class="border" width="100%">';
767  print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("MailTopic").'</td><td><input class="flat minwidth200 quatrevingtpercent" name="sujet" value="'.dol_escape_htmltag(GETPOST('sujet')).'"></td></tr>';
768  print '<tr><td>'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
769  print $htmlother->selectColor($_POST['bgcolor'],'bgcolor','',0);
770  print '</td></tr>';
771 
772  print '</table>';
773 
774  print '<div style="padding-top: 10px">';
775  // Editeur wysiwyg
776  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
777  $doleditor=new DolEditor('bodyemail',GETPOST('bodyemail','none'),'',600,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%');
778  $doleditor->Create();
779  print '</div>';
780 
781  dol_fiche_end();
782 
783  print '<div class="center"><input type="submit" class="button" value="'.$langs->trans("CreateMailing").'"></div>';
784 
785  print '</form>';
786 }
787 else
788 {
789  if ($object->id > 0)
790  {
791  $upload_dir = $conf->mailing->dir_output . "/" . get_exdir($object->id,2,0,1,$object,'mailing');
792 
793  $head = emailing_prepare_head($object);
794 
795  // Confirmation back to draft
796  if ($action == 'settodraft')
797  {
798  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id,$langs->trans("SetToDraft"),$langs->trans("ConfirmUnvalidateEmailing"),"confirm_settodraft",'','',1);
799  }
800  // Confirmation validation of mailing
801  if ($action == 'valid')
802  {
803  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id,$langs->trans("ValidMailing"),$langs->trans("ConfirmValidMailing"),"confirm_valid",'','',1);
804  }
805  // Confirm reset
806  else if ($action == 'reset')
807  {
808  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id,$langs->trans("ResetMailing"),$langs->trans("ConfirmResetMailing",$object->ref),"confirm_reset",'','',2);
809  }
810  // Confirm delete
811  else if ($action == 'delete')
812  {
813  print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id.(! empty($urlfrom) ? '&urlfrom='.urlencode($urlfrom) : ''),$langs->trans("DeleteAMailing"),$langs->trans("ConfirmDeleteMailing"),"confirm_delete",'','',1);
814  }
815 
816 
817  if ($action != 'edit' && $action != 'edithtml')
818  {
819  dol_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email');
820 
821  /*
822  * Mailing en mode visu
823  */
824  if ($action == 'sendall')
825  {
826  // Define message to recommand from command line
827  $sendingmode=$conf->global->EMAILING_MAIL_SENDMODE;
828  if (empty($sendingmode)) $sendingmode=$conf->global->MAIN_MAIL_SENDMODE;
829  if (empty($sendingmode)) $sendingmode='mail'; // If not defined, we use php mail function
830 
831  // MAILING_NO_USING_PHPMAIL may be defined or not.
832  // MAILING_LIMIT_SENDBYWEB is always defined to something != 0 (-1=forbidden).
833  // MAILING_LIMIT_SENDBYCLI may be defined ot not (-1=forbidden, 0 or undefined=no limit).
834  if (! empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail')
835  {
836  // EMailing feature may be a spam problem, so when you host several users/instance, having this option may force each user to use their own SMTP agent.
837  // You ensure that every user is using its own SMTP server when using the mass emailing module.
838  $linktoadminemailbefore='<a href="'.DOL_URL_ROOT.'/admin/mails.php">';
839  $linktoadminemailend='</a>';
840  setEventMessages($langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]), null, 'warnings');
841  setEventMessages($langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']), null, 'warnings');
842  if (! empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) setEventMessages($langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS), null, 'warnings');
843  $_GET["action"]='';
844  }
845  else if ($conf->global->MAILING_LIMIT_SENDBYWEB < 0)
846  {
847  if (! empty($conf->global->MAILING_LIMIT_WARNING_PHPMAIL) && $sendingmode == 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings');
848  if (! empty($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL) && $sendingmode != 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings');
849 
850  // The feature is forbidden from GUI, we show just message to use from command line.
851  setEventMessages($langs->trans("MailingNeedCommand"), null, 'warnings');
852  setEventMessages('<textarea cols="60" rows="'.ROWS_1.'" wrap="soft">php ./scripts/emailings/mailing-send.php '.$object->id.'</textarea>', null, 'warnings');
853  if ($conf->file->mailing_limit_sendbyweb != '-1') // MAILING_LIMIT_SENDBYWEB was set to -1 in database, but it is allowed ot increase it.
854  {
855  setEventMessages($langs->trans("MailingNeedCommand2"), null, 'warnings'); // You can send online with constant...
856  }
857  $_GET["action"]='';
858  }
859  else
860  {
861  if (! empty($conf->global->MAILING_LIMIT_WARNING_PHPMAIL) && $sendingmode == 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings');
862  if (! empty($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL) && $sendingmode != 'mail') setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings');
863 
864  $text='';
865  if ($conf->global->MAILING_LIMIT_SENDBYCLI >= 0)
866  {
867  $text.=$langs->trans("MailingNeedCommand");
868  $text.='<br><textarea cols="60" rows="'.ROWS_2.'" wrap="soft">php ./scripts/emailings/mailing-send.php '.$object->id.' '.$user->login.'</textarea>';
869  $text.='<br><br>';
870  }
871  $text.=$langs->trans('ConfirmSendingEmailing').'<br>';
872  $text.=$langs->trans('LimitSendingEmailing',$conf->global->MAILING_LIMIT_SENDBYWEB);
873  print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id,$langs->trans('SendMailing'),$text,'sendallconfirmed',$formquestion,'',1,300);
874  }
875  }
876 
877  $linkback = '<a href="'.DOL_URL_ROOT.'/comm/mailing/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
878 
879  $morehtmlright='';
880  $nbtry = $nbok = 0;
881  if ($object->statut == 2 || $object->statut == 3)
882  {
883  $nbtry = $object->countNbOfTargets('alreadysent');
884  $nbko = $object->countNbOfTargets('alreadysentko');
885 
886  $morehtmlright.=' ('.$nbtry.'/'.$object->nbemail;
887  if ($nbko) $morehtmlright.=' - '.$nbko.' '.$langs->trans("Error");
888  $morehtmlright.=') &nbsp; ';
889  }
890 
891  dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', '', '', 0, '', $morehtmlright);
892 
893  print '<div class="fichecenter">';
894  print '<div class="underbanner clearboth"></div>';
895 
896  print '<table class="border" width="100%">';
897 
898  // Description
899  print '<tr><td class="titlefield">'.$form->editfieldkey("MailTitle",'titre',$object->titre,$object,$user->rights->mailing->creer && $object->statut < 3,'string').'</td><td colspan="3">';
900  print $form->editfieldval("MailTitle",'titre',$object->titre,$object,$user->rights->mailing->creer && $object->statut < 3,'string');
901  print '</td></tr>';
902 
903  // From
904  print '<tr><td>'.$form->editfieldkey("MailFrom",'email_from',$object->email_from,$object,$user->rights->mailing->creer && $object->statut < 3,'string').'</td><td colspan="3">';
905  print $form->editfieldval("MailFrom",'email_from',$object->email_from,$object,$user->rights->mailing->creer && $object->statut < 3,'string');
906  print '</td></tr>';
907 
908  // Errors to
909  print '<tr><td>'.$form->editfieldkey("MailErrorsTo",'email_errorsto',$object->email_errorsto,$object,$user->rights->mailing->creer && $object->statut < 3,'string').'</td><td colspan="3">';
910  print $form->editfieldval("MailErrorsTo",'email_errorsto',$object->email_errorsto,$object,$user->rights->mailing->creer && $object->statut < 3,'string');
911  print '</td></tr>';
912 
913  // Nb of distinct emails
914  print '<tr><td>';
915  print $langs->trans("TotalNbOfDistinctRecipients");
916  print '</td><td colspan="3">';
917  $nbemail = ($object->nbemail?$object->nbemail:0);
918  if (is_numeric($nbemail))
919  {
920  $text='';
921  if ((! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || ($object->statut == 2 && $nbtry < $nbemail)))
922  {
923  if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0)
924  {
925  $text.=$langs->trans('LimitSendingEmailing',$conf->global->MAILING_LIMIT_SENDBYWEB);
926  }
927  else
928  {
929  $text.=$langs->trans('SendingFromWebInterfaceIsNotAllowed');
930  }
931  }
932  if (empty($nbemail)) $nbemail.=' '.img_warning('').' <font class="warning">'.$langs->trans("NoTargetYet").'</font>';
933  if ($text)
934  {
935  print $form->textwithpicto($nbemail,$text,1,'warning');
936  }
937  else
938  {
939  print $nbemail;
940  }
941  }
942  print '</td></tr>';
943 
944  // Other attributes
945  include DOL_DOCUMENT_ROOT . '/core/tpl/extrafields_view.tpl.php';
946 
947  print '</table>';
948 
949  print "</div>";
950 
951  dol_fiche_end();
952 
953 
954  // Clone confirmation
955  if ($action == 'clone')
956  {
957  // Create an array for form
958  $formquestion=array(
959  'text' => $langs->trans("ConfirmClone"),
960  array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneContent"), 'value' => 1),
961  array('type' => 'checkbox', 'name' => 'clone_receivers', 'label' => $langs->trans("CloneReceivers"), 'value' => 0)
962  );
963  // Paiement incomplet. On demande si motif = escompte ou autre
964  print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id,$langs->trans('CloneEMailing'),$langs->trans('ConfirmCloneEMailing',$object->ref),'confirm_clone',$formquestion,'yes',2,240);
965  }
966 
967  /*
968  * Boutons d'action
969  */
970 
971  if (GETPOST('cancel','alpha') || $confirm=='no' || $action == '' || in_array($action,array('settodraft','valid','delete','sendall','clone','test')))
972  {
973  print "\n\n<div class=\"tabsAction\">\n";
974 
975  if (($object->statut == 1) && ($user->rights->mailing->valider || $object->fk_user_valid == $user->id))
976  {
977  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=settodraft&amp;id='.$object->id.'">'.$langs->trans("SetToDraft").'</a>';
978  }
979 
980  if (($object->statut == 0 || $object->statut == 1) && $user->rights->mailing->creer)
981  {
982  if (! empty($conf->fckeditor->enabled) && ! empty($conf->global->FCKEDITOR_ENABLE_MAILING))
983  {
984  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("EditWithEditor").'</a>';
985  }
986  else
987  {
988  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&amp;id='.$object->id.'">'.$langs->trans("EditWithTextEditor").'</a>';
989  }
990 
991  if (! empty($conf->use_javascript_ajax)) print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edithtml&amp;id='.$object->id.'">'.$langs->trans("EditHTMLSource").'</a>';
992  }
993 
994  //print '<a class="butAction" href="card.php?action=test&amp;id='.$object->id.'">'.$langs->trans("PreviewMailing").'</a>';
995 
996  if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send)
997  {
998  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("TestMailing").'</a>';
999  }
1000  else
1001  {
1002  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=test&amp;id='.$object->id.'">'.$langs->trans("TestMailing").'</a>';
1003  }
1004 
1005  if ($object->statut == 0)
1006  {
1007  if ($object->nbemail <= 0)
1008  {
1009  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NoTargetYet")).'">'.$langs->trans("ValidMailing").'</a>';
1010  }
1011  else if (empty($user->rights->mailing->valider))
1012  {
1013  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("ValidMailing").'</a>';
1014  }
1015  else
1016  {
1017  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=valid&amp;id='.$object->id.'">'.$langs->trans("ValidMailing").'</a>';
1018  }
1019  }
1020 
1021  if (($object->statut == 1 || $object->statut == 2) && $object->nbemail > 0 && $user->rights->mailing->valider)
1022  {
1023  if ($conf->global->MAILING_LIMIT_SENDBYWEB < 0)
1024  {
1025  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("SendingFromWebInterfaceIsNotAllowed")).'">'.$langs->trans("SendMailing").'</a>';
1026  }
1027  else if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send)
1028  {
1029  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("SendMailing").'</a>';
1030  }
1031  else
1032  {
1033  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=sendall&amp;id='.$object->id.'">'.$langs->trans("SendMailing").'</a>';
1034  }
1035  }
1036 
1037  if ($user->rights->mailing->creer)
1038  {
1039  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=clone&amp;object=emailing&amp;id='.$object->id.'">'.$langs->trans("ToClone").'</a>';
1040  }
1041 
1042  if (($object->statut == 2 || $object->statut == 3) && $user->rights->mailing->valider)
1043  {
1044  if (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->send)
1045  {
1046  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("ResetMailing").'</a>';
1047  }
1048  else
1049  {
1050  print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=reset&amp;id='.$object->id.'">'.$langs->trans("ResetMailing").'</a>';
1051  }
1052  }
1053 
1054  if (($object->statut <= 1 && $user->rights->mailing->creer) || $user->rights->mailing->supprimer)
1055  {
1056  if ($object->statut > 0 && (! empty($conf->global->MAIN_USE_ADVANCED_PERMS) && ! $user->rights->mailing->mailing_advance->delete))
1057  {
1058  print '<a class="butActionRefused" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("DeleteMailing").'</a>';
1059  }
1060  else
1061  {
1062  print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=delete&amp;id='.$object->id.(! empty($urlfrom) ? '&urlfrom='.$urlfrom : '').'">'.$langs->trans("DeleteMailing").'</a>';
1063  }
1064  }
1065 
1066  print '</div>';
1067  }
1068 
1069  // Affichage formulaire de TEST
1070  if ($action == 'test')
1071  {
1072  print '<div id="formmailbeforetitle" name="formmailbeforetitle"></div>';
1073  print load_fiche_titre($langs->trans("TestMailing"));
1074 
1075  dol_fiche_head(null, '', '', -1);
1076 
1077  // Create l'objet formulaire mail
1078  include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1079  $formmail = new FormMail($db);
1080  $formmail->fromname = $object->email_from;
1081  $formmail->frommail = $object->email_from;
1082  $formmail->withsubstit=1;
1083  $formmail->withfrom=0;
1084  $formmail->withto=$user->email?$user->email:1;
1085  $formmail->withtocc=0;
1086  $formmail->withtoccc=$conf->global->MAIN_EMAIL_USECCC;
1087  $formmail->withtopic=0;
1088  $formmail->withtopicreadonly=1;
1089  $formmail->withfile=0;
1090  $formmail->withbody=0;
1091  $formmail->withbodyreadonly=1;
1092  $formmail->withcancel=1;
1093  $formmail->withdeliveryreceipt=0;
1094  // Tableau des substitutions
1095  $formmail->substit=$object->substitutionarrayfortest;
1096  // Tableau des parametres complementaires du post
1097  $formmail->param["action"]="send";
1098  $formmail->param["models"]='none';
1099  $formmail->param["mailid"]=$object->id;
1100  $formmail->param["returnurl"]=$_SERVER['PHP_SELF']."?id=".$object->id;
1101 
1102  print $formmail->get_form();
1103 
1104  print '<br>';
1105 
1106  dol_fiche_end();
1107 
1108  print dol_set_focus('#sendto');
1109  }
1110 
1111 
1112  $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
1113  foreach($object->substitutionarray as $key => $val)
1114  {
1115  $htmltext.=$key.' = '.$langs->trans($val).'<br>';
1116  }
1117  $htmltext.='</i>';
1118 
1119  // Print mail content
1120  print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto('<span class="hideonsmartphone">'.$langs->trans("AvailableVariables").'</span>', $htmltext, 1, 'help', '', 0, 2, 'emailsubstitionhelp'), 'title_generic');
1121 
1122  dol_fiche_head('', '', '', -1);
1123 
1124  print '<table class="bordernooddeven" width="100%">';
1125 
1126  // Subject
1127  print '<tr><td class="titlefield">'.$langs->trans("MailTopic").'</td><td colspan="3">'.$object->sujet.'</td></tr>';
1128 
1129  // Joined files
1130  print '<tr><td>'.$langs->trans("MailFile").'</td><td colspan="3">';
1131  // List of files
1132  $listofpaths=dol_dir_list($upload_dir,'all',0,'','','name',SORT_ASC,0);
1133  if (count($listofpaths))
1134  {
1135  foreach($listofpaths as $key => $val)
1136  {
1137  print img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name'];
1138  print '<br>';
1139  }
1140  }
1141  else
1142  {
1143  print '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
1144  }
1145  print '</td></tr>';
1146 
1147  // Background color
1148  /*print '<tr><td width="15%">'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
1149  print $htmlother->selectColor($object->bgcolor,'bgcolor','',0);
1150  print '</td></tr>';*/
1151 
1152  print '</table>';
1153 
1154  // Message
1155  print '<div style="padding-top: 10px; background: '.($object->bgcolor?(preg_match('/^#/',$object->bgcolor)?'':'#').$object->bgcolor:'white').'">';
1156  if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') // CKEditor does not apply the color of the div into its content area
1157  {
1158  $readonly=1;
1159  // Editeur wysiwyg
1160  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1161  $doleditor=new DolEditor('bodyemail',$object->body,'',600,'dolibarr_mailings','',false,true,empty($conf->global->FCKEDITOR_ENABLE_MAILING)?0:1,20,'90%',$readonly);
1162  $doleditor->Create();
1163  }
1164  else print dol_htmlentitiesbr($object->body);
1165  print '</div>';
1166 
1167  dol_fiche_end();
1168  }
1169  else
1170  {
1171  /*
1172  * Mailing en mode edition (CKeditor or HTML source)
1173  */
1174 
1175  dol_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email');
1176 
1177  $linkback = '<a href="'.DOL_URL_ROOT.'/comm/mailing/list.php">'.$langs->trans("BackToList").'</a>';
1178 
1179  $morehtmlright='';
1180  if ($object->statut == 2) $morehtmlright.=' ('.$object->countNbOfTargets('alreadysent').'/'.$object->nbemail.') ';
1181 
1182  dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', '', '', 0, '', $morehtmlright);
1183 
1184  print '<div class="fichecenter">';
1185  print '<div class="underbanner clearboth"></div>';
1186 
1187  print '<table class="border" width="100%">';
1188 
1189  /*
1190  print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td>';
1191  print '<td colspan="3">';
1192  print $form->showrefnav($object,'id', $linkback);
1193  print '</td></tr>';
1194  */
1195 
1196  // Topic
1197  print '<tr><td class="titlefield">'.$langs->trans("MailTitle").'</td><td colspan="3">'.$object->titre.'</td></tr>';
1198  // From
1199  print '<tr><td class="titlefield">'.$langs->trans("MailFrom").'</td><td colspan="3">'.dol_print_email($object->email_from,0,0,0,0,1).'</td></tr>';
1200  // To
1201  print '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td colspan="3">'.dol_print_email($object->email_errorsto,0,0,0,0,1).'</td></tr>';
1202 
1203  // Nb of distinct emails
1204  print '<tr><td>';
1205  print $langs->trans("TotalNbOfDistinctRecipients");
1206  print '</td><td colspan="3">';
1207  $nbemail = ($object->nbemail?$object->nbemail:0);
1208  if (is_numeric($nbemail))
1209  {
1210  $text='';
1211  if ((! empty($conf->global->MAILING_LIMIT_SENDBYWEB) && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->statut == 1 || $object->statut == 2))
1212  {
1213  if ($conf->global->MAILING_LIMIT_SENDBYWEB > 0)
1214  {
1215  $text.=$langs->trans('LimitSendingEmailing',$conf->global->MAILING_LIMIT_SENDBYWEB);
1216  }
1217  else
1218  {
1219  $text.=$langs->trans('SendingFromWebInterfaceIsNotAllowed');
1220  }
1221  }
1222  if (empty($nbemail)) $nbemail.=' '.img_warning('').' <font class="warning">'.$langs->trans("NoTargetYet").'</font>';
1223  if ($text)
1224  {
1225  print $form->textwithpicto($nbemail,$text,1,'warning');
1226  }
1227  else
1228  {
1229  print $nbemail;
1230  }
1231  }
1232  print '</td></tr>';
1233 
1234  // Other attributes
1235  $parameters=array();
1236  $reshook=$hookmanager->executeHooks('formObjectOptions',$parameters,$object,$action); // Note that $action and $object may have been modified by hook
1237  print $hookmanager->resPrint;
1238  if (empty($reshook))
1239  {
1240  print $object->showOptionals($extrafields,'edit');
1241  }
1242 
1243  print '</table>';
1244  print '</div>';
1245 
1246  dol_fiche_end();
1247 
1248 
1249 
1250  print "<br>\n";
1251 
1252  print '<form name="edit_mailing" action="card.php" method="post" enctype="multipart/form-data">'."\n";
1253  print '<input type="hidden" name="token" value="'.$_SESSION['newtoken'].'">';
1254  print '<input type="hidden" name="action" value="update">';
1255  print '<input type="hidden" name="id" value="'.$object->id.'">';
1256 
1257  $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br>';
1258  foreach($object->substitutionarray as $key => $val)
1259  {
1260  $htmltext.=$key.' = '.$langs->trans($val).'<br>';
1261  }
1262  $htmltext.='</i>';
1263 
1264  // Print mail content
1265  print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto($langs->trans("AvailableVariables"), $htmltext, 1, 'help', '', 0, 2, 'emailsubstitionhelp'), 'title_generic');
1266 
1267  dol_fiche_head(null, '', '', -1);
1268 
1269  print '<table class="bordernooddeven" width="100%">';
1270 
1271  // Subject
1272  print '<tr><td class="fieldrequired titlefield">'.$langs->trans("MailTopic").'</td><td colspan="3"><input class="flat quatrevingtpercent" type="text" name="sujet" value="'.$object->sujet.'"></td></tr>';
1273 
1274  $trackid=''; // TODO To avoid conflicts with 2 mass emailing, we should set a trackid here, even if we use another one into email header.
1275  dol_init_file_process($upload_dir, $trackid);
1276 
1277  // Joined files
1278  $addfileaction='addfile';
1279  print '<tr><td>'.$langs->trans("MailFile").'</td>';
1280  print '<td colspan="3">';
1281  // List of files
1282  $listofpaths=dol_dir_list($upload_dir,'all',0,'','','name',SORT_ASC,0);
1283 
1284  // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
1285  $out.= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
1286  $out.= '<script type="text/javascript" language="javascript">';
1287  $out.= 'jQuery(document).ready(function () {';
1288  $out.= ' jQuery(".removedfile").click(function() {';
1289  $out.= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
1290  $out.= ' });';
1291  $out.= '})';
1292  $out.= '</script>'."\n";
1293  if (count($listofpaths))
1294  {
1295  foreach($listofpaths as $key => $val)
1296  {
1297  $out.= '<div id="attachfile_'.$key.'">';
1298  $out.= img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name'];
1299  $out.= ' <input type="image" style="border: 0px;" src="'.img_picto($langs->trans("Search"),'delete.png','','',1).'" value="'.($key+1).'" class="removedfile" id="removedfile_'.$key.'" name="removedfile_'.$key.'" />';
1300  $out.= '<br></div>';
1301  }
1302  }
1303  else
1304  {
1305  $out.= $langs->trans("NoAttachedFiles").'<br>';
1306  }
1307  // Add link to add file
1308  $out.= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
1309  $out.= ' ';
1310  $out.= '<input type="submit" class="button" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
1311  print $out;
1312  print '</td></tr>';
1313 
1314  // Background color
1315  print '<tr><td>'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
1316  print $htmlother->selectColor($object->bgcolor,'bgcolor','',0);
1317  print '</td></tr>';
1318 
1319  print '</table>';
1320 
1321  // Message
1322  print '<div style="padding-top: 10px">';
1323 
1324  if ($action == 'edit')
1325  {
1326  // Editeur wysiwyg
1327  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1328  $doleditor=new DolEditor('bodyemail',$object->body,'',600,'dolibarr_mailings','',true,true,$conf->global->FCKEDITOR_ENABLE_MAILING,20,'90%');
1329  $doleditor->Create();
1330  }
1331  if ($action == 'edithtml')
1332  {
1333  // Editor HTML source
1334  require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1335  $doleditor=new DolEditor('bodyemail',$object->body,'',600,'dolibarr_mailings','',true,true,'ace',20,'90%');
1336  $doleditor->Create(0, '', false, 'HTML Source', 'php');
1337  }
1338 
1339  print '</div>';
1340 
1341 
1342  dol_fiche_end();
1343 
1344  print '<div class="center">';
1345  print '<input type="submit" class="button buttonforacesave" value="'.$langs->trans("Save").'" name="save">';
1346  print '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
1347  print '<input type="submit" class="button" value="'.$langs->trans("Cancel").'" name="cancel">';
1348  print '</div>';
1349 
1350  print '</form>';
1351  print '<br>';
1352  }
1353  }
1354  else
1355  {
1356  dol_print_error($db,$object->error);
1357  }
1358 }
1359 
1360 // End of page
1361 llxFooter();
1362 $db->close();
llxFooter()
Empty footer.
Definition: wrapper.php:56
load_fiche_titre($titre, $morehtmlright='', $picto='title_generic.png', $pictoisfullpath=0, $id='', $morecssontable='', $morehtmlcenter='')
Load a title with picto.
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...
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
get_exdir($num, $level, $alpha, $withoutslash, $object, $modulepart)
Return a path to have a the directory according to object where files are stored. ...
dol_banner_tab($object, $paramid, $morehtml='', $shownav=1, $fieldid='rowid', $fieldref='ref', $morehtmlref='', $moreparam='', $nodbprefix=0, $morehtmlleft='', $morehtmlstatus='', $onlybanner=0, $morehtmlright='')
Show tab footer of a card.
dol_mimetype($file, $default='application/octet-stream', $mode=0)
Return mime type of a file.
dol_remove_file_process($filenb, $donotupdatesession=0, $donotdeletefile=1, $trackid='')
Remove an uploaded file (for example after submitting a new file a mail form).
Definition: files.lib.php:1663
dol_print_error($db='', $error='', $errors=null)
Affiche message erreur system avec toutes les informations pour faciliter le diagnostic et la remonte...
dol_escape_htmltag($stringtoescape, $keepb=0, $keepn=0)
Returns text escaped for inclusion in HTML alt or title tags, or into values of HTML input fields...
getCommonSubstitutionArray($outputlangs, $onlykey=0, $exclude=null, $object=null)
Return array of possible common substitutions.
accessforbidden($message='', $printheader=1, $printfooter=1, $showonlymessage=0)
Show a message to say access is forbidden and stop program Calling this function terminate execution ...
Class to manage standard extra fields.
Class to manage generation of HTML components Only common components must be here.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='')
Write log message into outputs.
emailing_prepare_head(Mailing $object)
Prepare array with list of tabs.
dol_add_file_process($upload_dir, $allowoverwrite=0, $donotupdatesession=0, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1)
Get and save an upload file (for example after submitting a new file a mail form).
Definition: files.lib.php:1519
dol_fiche_end($notab=0)
Show tab footer of a card.
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext); $mailfile->sendfile();.
Classe permettant la generation de composants html autre Only common components are here...
llxHeader()
Empty header.
Definition: wrapper.php:44
if(GETPOST('cancel', 'alpha')) if(! GETPOST( 'confirmmassaction', 'alpha') &&$massaction !='presend' &&$massaction !='confirm_presend')
Draft customers invoices.
Definition: list.php:156
dol_dir_list($path, $types="all", $recursive=0, $filter="", $excludefilter=null, $sortcriteria="name", $sortorder=SORT_ASC, $mode=0, $nohook=0, $relativename="", $donotfollowsymlinks=0)
Scan a directory and return a list of files/directories.
Definition: files.lib.php:59
Class to manage emailings module.
dol_now($mode='gmt')
Return date for now.
if($_POST["cancel"]==$langs->trans("Cancel") &&! $id) if($action=='add' && $_POST["cancel"]<> $langs->trans("Cancel")) if($action=='delete') if($id) $form
Actions.
Definition: card.php:153
dol_init_file_process($pathtoscan='', $trackid='')
Scan a directory and init $_SESSION to manage uploaded files with list of all found files...
Definition: files.lib.php:1481
dol_print_email($email, $cid=0, $socid=0, $addlink=0, $max=64, $showinvalid=1, $withpicto=0)
Show EMail link.
static getAvailableSubstitKey($mode='formemail', $object=null)
Get list of substitution keys available for emails.
dol_htmlentitiesbr($stringtoencode, $nl2brmode=0, $pagecodefrom='UTF-8', $removelasteolbr=1)
This function is called to encode a string into a HTML string but differs from htmlentities because a...
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_hash($chain, $type='0')
Returns a hash of a string.
img_mime($file, $titlealt='', $morecss='')
Show MIME img of a file.
dol_set_focus($selector)
Set focus onto field with selector (similar behaviour of &#39;autofocus&#39; HTML5 tag)
dol_fiche_head($links=array(), $active='0', $title='', $notab=0, $picto='', $pictoisfullpath=0, $morehtmlright='', $morecss='')
Show tab header of a card.
$parameters
Actions.
Definition: card.php:114
dolGetFirstLastname($firstname, $lastname, $nameorder=-1)
Return firstname and lastname in correct order.
complete_substitutions_array(&$substitutionarray, $outputlangs, $object=null, $parameters=null, $callfunc="completesubstitutionarray")
Complete the $substitutionarray with more entries coming from external module that had set the "subst...