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