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