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