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