dolibarr 21.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@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 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', 'aZ09');
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", 'alpha'), GETPOST("clone_receivers", 'alpha'));
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 if ($obj->source_type == "thirdparty") {
261 $result = $thirdpartystatic->fetch($obj->source_id);
262
263 if ($result > 0) {
264 $substitutionarray['__THIRDPARTY_CUSTOMER_CODE__'] = $thirdpartystatic->code_client;
265 } else {
266 $substitutionarray['__THIRDPARTY_CUSTOMER_CODE__'] = '';
267 }
268 }
269 $substitutionarray['__EMAIL__'] = $obj->email;
270 $substitutionarray['__LASTNAME__'] = $obj->lastname;
271 $substitutionarray['__FIRSTNAME__'] = $obj->firstname;
272 $substitutionarray['__MAILTOEMAIL__'] = '<a href="mailto:'.$obj->email.'">'.$obj->email.'</a>';
273 $substitutionarray['__OTHER1__'] = $other1;
274 $substitutionarray['__OTHER2__'] = $other2;
275 $substitutionarray['__OTHER3__'] = $other3;
276 $substitutionarray['__OTHER4__'] = $other4;
277 $substitutionarray['__OTHER5__'] = $other5;
278 $substitutionarray['__USER_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter)
279 $substitutionarray['__SENDEREMAIL_SIGNATURE__'] = $signature; // Signature is empty when ran from command line or taken from user in parameter)
280 $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"/>';
281 $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>';
282 $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);
283
284 $onlinepaymentenabled = 0;
285 if (isModEnabled('paypal')) {
286 $onlinepaymentenabled++;
287 }
288 if (isModEnabled('paybox')) {
289 $onlinepaymentenabled++;
290 }
291 if (isModEnabled('stripe')) {
292 $onlinepaymentenabled++;
293 }
294 if ($onlinepaymentenabled && getDolGlobalString('PAYMENT_SECURITY_TOKEN')) {
295 require_once DOL_DOCUMENT_ROOT.'/core/lib/payments.lib.php';
296 $substitutionarray['__ONLINEPAYMENTLINK_MEMBER__'] = getHtmlOnlinePaymentLink('member', $obj->source_id);
297 $substitutionarray['__ONLINEPAYMENTLINK_DONATION__'] = getHtmlOnlinePaymentLink('donation', $obj->source_id);
298 $substitutionarray['__ONLINEPAYMENTLINK_ORDER__'] = getHtmlOnlinePaymentLink('order', $obj->source_id);
299 $substitutionarray['__ONLINEPAYMENTLINK_INVOICE__'] = getHtmlOnlinePaymentLink('invoice', $obj->source_id);
300 $substitutionarray['__ONLINEPAYMENTLINK_CONTRACTLINE__'] = getHtmlOnlinePaymentLink('contractline', $obj->source_id);
301
302 $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), '2');
303 if (!getDolGlobalString('PAYMENT_SECURITY_TOKEN_UNIQUE')) {
304 $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), '2');
305 $substitutionarray['__SECUREKEYPAYMENT_DONATION__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), '2');
306 $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), '2');
307 $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), '2');
308 $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), '2');
309 } else {
310 $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'member'.$obj->source_id, '2');
311 $substitutionarray['__SECUREKEYPAYMENT_DONATION__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'donation'.$obj->source_id, '2');
312 $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'order'.$obj->source_id, '2');
313 $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'invoice'.$obj->source_id, '2');
314 $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'contractline'.$obj->source_id, '2');
315 }
316 }
317 if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) {
318 $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>';
319 }
320 /* For backward compatibility, deprecated */
321 if (isModEnabled('paypal') && getDolGlobalString('PAYPAL_SECURITY_TOKEN')) {
322 $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), '2');
323
324 if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) {
325 $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), '2');
326 } else {
327 $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'membersubscription'.$obj->source_id, '2');
328 }
329
330 if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) {
331 $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), '2');
332 } else {
333 $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'order'.$obj->source_id, '2');
334 }
335
336 if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) {
337 $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), '2');
338 } else {
339 $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'invoice'.$obj->source_id, '2');
340 }
341
342 if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) {
343 $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), '2');
344 } else {
345 $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'contractline'.$obj->source_id, '2');
346 }
347 }
348 //$substitutionisok=true;
349
350 complete_substitutions_array($substitutionarray, $langs);
351 $newsubject = make_substitutions($subject, $substitutionarray);
352 $newmessage = make_substitutions($message, $substitutionarray, null, 0);
353
354 $moreinheader = '';
355 if (preg_match('/__UNSUBSCRIBE_(_|URL_)/', $message)) {
356 $moreinheader = "List-Unsubscribe: <__UNSUBSCRIBE_URL__>\n";
357 $moreinheader = make_substitutions($moreinheader, $substitutionarray);
358 }
359
360 $arr_file = array();
361 $arr_mime = array();
362 $arr_name = array();
363 $arr_css = array();
364
365 $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0);
366 if (count($listofpaths)) {
367 foreach ($listofpaths as $key => $val) {
368 $arr_file[] = $listofpaths[$key]['fullname'];
369 $arr_mime[] = dol_mimetype($listofpaths[$key]['name']);
370 $arr_name[] = $listofpaths[$key]['name'];
371 }
372 }
373
374 // Mail making
375 $trackid = 'emailing-'.$obj->fk_mailing.'-'.$obj->rowid;
376 $upload_dir_tmp = $upload_dir;
377 $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);
378
379 if ($mail->error) {
380 $res = 0;
381 }
382 /*if (! $substitutionisok)
383 {
384 $mail->error='Some substitution failed';
385 $res=0;
386 }*/
387
388 // Send mail
389 if ($res) {
390 $res = $mail->sendfile();
391 }
392
393 if ($res) {
394 // Mail successful
395 $nbok++;
396
397 dol_syslog("comm/mailing/card.php: ok for #".$iforemailloop.($mail->error ? ' - '.$mail->error : ''), LOG_DEBUG);
398
399 $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
400 $sql .= " SET statut=1, date_envoi = '".$db->idate($now)."' WHERE rowid=".((int) $obj->rowid);
401 $resql2 = $db->query($sql);
402 if (!$resql2) {
403 dol_print_error($db);
404 } else {
405 //if check read is use then update prospect contact status
406 if (strpos($message, '__CHECK_READ__') !== false) {
407 //Update status communication of thirdparty prospect
408 $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).")";
409 dol_syslog("card.php: set prospect thirdparty status", LOG_DEBUG);
410 $resql2 = $db->query($sql);
411 if (!$resql2) {
412 dol_print_error($db);
413 }
414
415 //Update status communication of contact prospect
416 $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)";
417 dol_syslog("card.php: set prospect contact status", LOG_DEBUG);
418
419 $resql2 = $db->query($sql);
420 if (!$resql2) {
421 dol_print_error($db);
422 }
423 }
424 }
425
426 if (getDolGlobalString('MAILING_DELAY')) {
427 dol_syslog("Wait a delay of MAILING_DELAY=".((float) $conf->global->MAILING_DELAY));
428 usleep((int) ((float) $conf->global->MAILING_DELAY * 1000000));
429 }
430
431 //test if CHECK READ change statut prospect contact
432 } else {
433 // Mail failed
434 $nbko++;
435
436 dol_syslog("comm/mailing/card.php: error for #".$iforemailloop.($mail->error ? ' - '.$mail->error : ''), LOG_WARNING);
437
438 $sql = "UPDATE ".MAIN_DB_PREFIX."mailing_cibles";
439 $sql .= " SET statut=-1, error_text='".$db->escape(dol_trunc($mail->error, 250))."', date_envoi='".$db->idate($now)."' WHERE rowid=".((int) $obj->rowid);
440 $resql2 = $db->query($sql);
441 if (!$resql2) {
442 dol_print_error($db);
443 }
444 }
445
446 $iforemailloop++;
447 }
448 } else {
449 setEventMessages($langs->transnoentitiesnoconv("NoMoreRecipientToSendTo"), null, 'mesgs');
450 }
451
452 // Loop finished, set global statut of mail
453 if ($nbko > 0) {
454 $statut = 2; // Status 'sent partially' (because at least one error)
455 setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs');
456 } else {
457 if ($nbok >= $num) {
458 $statut = 3; // Send to everybody
459 } else {
460 $statut = 2; // Status 'sent partially' (because not send to everybody)
461 }
462 setEventMessages($langs->transnoentitiesnoconv("EMailSentToNRecipients", $nbok), null, 'mesgs');
463 }
464
465 $sql = "UPDATE ".MAIN_DB_PREFIX."mailing SET statut=".((int) $statut)." WHERE rowid = ".((int) $object->id);
466 dol_syslog("comm/mailing/card.php: update global status", LOG_DEBUG);
467 $resql2 = $db->query($sql);
468 if (!$resql2) {
469 dol_print_error($db);
470 }
471 } else {
472 dol_syslog($db->error());
473 dol_print_error($db);
474 }
475 $object->fetch($id);
476 $action = '';
477 }
478 }
479
480 // Action send test emailing
481 if ($action == 'send' && ! $cancel && $permissiontovalidatesend) {
482 $error = 0;
483
484 $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing');
485
486 $object->sendto = GETPOST("sendto", 'alphawithlgt');
487 if (!$object->sendto) {
488 setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv("MailTo")), null, 'errors');
489 $error++;
490 }
491
492 if (!$error) {
493 // Is the message in html
494 $msgishtml = -1; // Unknown = autodetect by default
495 if (preg_match('/[\s\t]*<html>/i', $object->body)) {
496 $msgishtml = 1;
497 }
498
499 $signature = ((!empty($user->signature) && !getDolGlobalString('MAIN_MAIL_DO_NOT_USE_SIGN')) ? $user->signature : '');
500
501 $parameters = array('mode' => 'emailing');
502 $substitutionarray = getCommonSubstitutionArray($langs, 0, array('object', 'objectamount'), $targetobject); // Note: On mass emailing, this is null because be don't know object
503
504 // other are set at begin of page
505 $substitutionarray['__EMAIL__'] = $object->sendto;
506 $substitutionarray['__MAILTOEMAIL__'] = '<a href="mailto:'.$object->sendto.'">'.$object->sendto.'</a>';
507 $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"/>';
508 $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>';
509 $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';
510
511 // Subject and message substitutions
512 complete_substitutions_array($substitutionarray, $langs, $targetobject);
513
514 $tmpsujet = make_substitutions($object->sujet, $substitutionarray);
515 $tmpbody = make_substitutions($object->body, $substitutionarray);
516
517 $arr_file = array();
518 $arr_mime = array();
519 $arr_name = array();
520 $arr_css = array();
521
522 // Add CSS
523 if (!empty($object->bgcolor)) {
524 $arr_css['bgcolor'] = (preg_match('/^#/', $object->bgcolor) ? '' : '#').$object->bgcolor;
525 }
526 if (!empty($object->bgimage)) {
527 $arr_css['bgimage'] = $object->bgimage;
528 }
529
530 // Attached files
531 $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0);
532 if (count($listofpaths)) {
533 foreach ($listofpaths as $key => $val) {
534 $arr_file[] = $listofpaths[$key]['fullname'];
535 $arr_mime[] = dol_mimetype($listofpaths[$key]['name']);
536 $arr_name[] = $listofpaths[$key]['name'];
537 }
538 }
539
540 $trackid = 'emailing-test';
541 $upload_dir_tmp = $upload_dir;
542 $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);
543
544 $result = $mailfile->sendfile();
545 if ($result) {
546 setEventMessages($langs->trans("MailSuccessfulySent", $mailfile->getValidAddress($object->email_from, 2), $mailfile->getValidAddress($object->sendto, 2)), null, 'mesgs');
547 $action = '';
548 } else {
549 setEventMessages($langs->trans("ResultKo").'<br>'.$mailfile->error.' '.json_encode($result), null, 'errors');
550 $action = 'test';
551 }
552 }
553 }
554
555 $mesgs = array();
556 // Action add emailing
557 if ($action == 'add' && $permissiontocreate) {
558 $object->messtype = (string) GETPOST("messtype");
559 if ($object->messtype == 'sms') {
560 $object->email_from = (string) GETPOST("from_phone", 'alphawithlgt'); // Must allow 'name <email>'
561 } else {
562 $object->email_from = (string) GETPOST("from", 'alphawithlgt'); // Must allow 'name <email>'
563 }
564 $object->email_replyto = (string) GETPOST("replyto", 'alphawithlgt'); // Must allow 'name <email>'
565 $object->email_errorsto = (string) GETPOST("errorsto", 'alphawithlgt'); // Must allow 'name <email>'
566 $object->title = (string) GETPOST("title");
567 $object->sujet = (string) GETPOST("sujet");
568 $object->body = (string) GETPOST("bodyemail", 'restricthtml');
569 $object->bgcolor = preg_replace('/^#/', '', (string) GETPOST("bgcolor"));
570 $object->bgimage = (string) GETPOST("bgimage");
571
572 if (!$object->title) {
573 $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTitle"));
574 }
575 if ($object->messtype != 'sms' && !$object->sujet) {
576 $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTopic"));
577 }
578 if (!$object->body) {
579 $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailMessage"));
580 }
581
582 if (!count($mesgs)) {
583 if ($object->create($user) >= 0) {
584 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
585 exit;
586 }
587 $mesgs[] = $object->error;
588 $mesgs = array_merge($mesgs, $object->errors);
589 }
590
591 setEventMessages('', $mesgs, 'errors');
592 $action = "create";
593 }
594
595 // Action update description of emailing
596 if (($action == 'settitle' || $action == 'setemail_from' || $action == 'setemail_replyto' || $action == 'setreplyto' || $action == 'setemail_errorsto' || $action == 'setevenunsubscribe') && $permissiontovalidatesend) {
597 $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing');
598
599 if ($action == 'settitle') { // Test on permission already done
600 $object->title = trim(GETPOST('title', 'alpha'));
601 } elseif ($action == 'setemail_from') { // Test on permission already done
602 $object->email_from = trim(GETPOST('email_from', 'alphawithlgt')); // Must allow 'name <email>'
603 } elseif ($action == 'setemail_replyto') { // Test on permission already done
604 $object->email_replyto = trim(GETPOST('email_replyto', 'alphawithlgt')); // Must allow 'name <email>'
605 } elseif ($action == 'setemail_errorsto') { // Test on permission already done
606 $object->email_errorsto = trim(GETPOST('email_errorsto', 'alphawithlgt')); // Must allow 'name <email>'
607 } elseif ($action == 'settitle' && empty($object->title)) { // Test on permission already done
608 $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTitle"));
609 } elseif ($action == 'setfrom' && empty($object->email_from)) { // Test on permission already done
610 $mesg = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailFrom"));
611 } elseif ($action == 'setevenunsubscribe') { // Test on permission already done
612 $object->evenunsubscribe = (GETPOST('evenunsubscribe') ? 1 : 0);
613 }
614
615 if (!$mesg) {
616 $result = $object->update($user);
617 if ($result >= 0) {
618 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
619 exit;
620 }
621 $mesg = $object->error;
622 }
623
624 setEventMessages($mesg, $mesgs, 'errors');
625 $action = "";
626 }
627
628 /*
629 * Action of adding a file in email form
630 */
631 if (GETPOST('addfile') && $permissiontocreate) {
632 $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing');
633
634 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
635
636 // Set tmp user directory
637 dol_add_file_process($upload_dir, 0, 0, 'addedfile', '', null, '', 0);
638
639 $action = "edit";
640 }
641
642 // Action of file remove
643 if (GETPOST("removedfile") && $permissiontocreate) {
644 $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing');
645
646 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
647
648 dol_remove_file_process(GETPOST('removedfile'), 0, 0); // We really delete file linked to mailing
649
650 $action = "edit";
651 }
652
653 // Action of emailing update
654 if ($action == 'update' && !GETPOST("removedfile") && !$cancel && $permissiontocreate) {
655 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
656
657 $isupload = 0;
658
659 if (!$isupload) {
660 $mesgs = array();
661
662 //$object->messtype = (string) GETPOST("messtype"); // We must not be able to change the messtype
663 $object->sujet = (string) GETPOST("sujet");
664 $object->body = (string) GETPOST("bodyemail", 'restricthtml');
665 $object->bgcolor = preg_replace('/^#/', '', (string) GETPOST("bgcolor"));
666 $object->bgimage = (string) GETPOST("bgimage");
667
668 if ($object->messtype != 'sms' && !$object->sujet) {
669 $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailTopic"));
670 }
671 if (!$object->body) {
672 $mesgs[] = $langs->trans("ErrorFieldRequired", $langs->transnoentities("MailMessage"));
673 }
674
675 if (!count($mesgs)) {
676 if ($object->update($user) >= 0) {
677 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
678 exit;
679 }
680 $mesgs[] = $object->error;
681 $mesgs = array_merge($mesgs, $object->errors);
682 }
683
684 setEventMessages('', $mesgs, 'errors');
685 $action = "edit";
686 } else {
687 $action = "edit";
688 }
689 }
690
691 // Action of validation confirmation
692 if ($action == 'confirm_valid' && $confirm == 'yes' && $permissiontovalidatesend) {
693 if ($object->id > 0) {
694 $object->valid($user);
695 setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs');
696 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
697 exit;
698 } else {
699 dol_print_error($db);
700 }
701 }
702
703 // Action of validation confirmation
704 if ($action == 'confirm_settodraft' && $confirm == 'yes' && $permissiontocreate) {
705 if ($object->id > 0) {
706 $result = $object->setStatut(0);
707 if ($result > 0) {
708 //setEventMessages($langs->trans("MailingSuccessfullyValidated"), null, 'mesgs');
709 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
710 exit;
711 } else {
712 setEventMessages($object->error, $object->errors, 'errors');
713 }
714 } else {
715 dol_print_error($db);
716 }
717 }
718
719 // Resend
720 if ($action == 'confirm_reset' && $confirm == 'yes' && $permissiontocreate) {
721 if ($object->id > 0) {
722 $db->begin();
723
724 $result = $object->valid($user);
725 if ($result > 0) {
726 $result = $object->reset_targets_status($user);
727 }
728
729 if ($result > 0) {
730 $db->commit();
731 header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id);
732 exit;
733 } else {
734 setEventMessages($object->error, $object->errors, 'errors');
735 $db->rollback();
736 }
737 } else {
738 dol_print_error($db);
739 }
740 }
741
742 // Action of delete confirmation
743 if ($action == 'confirm_delete' && $confirm == 'yes' && $permissiontodelete) {
744 if ($object->delete($user)) {
745 $url = (!empty($urlfrom) ? $urlfrom : 'list.php');
746 header("Location: ".$url);
747 exit;
748 }
749 }
750
751 if ($cancel) {
752 $action = '';
753 }
754}
755
756
757/*
758 * View
759 */
760
761$form = new Form($db);
762$htmlother = new FormOther($db);
763
764$help_url = 'EN:Module_EMailing|FR:Module_Mailing|ES:M&oacute;dulo_Mailing';
766 '',
767 $langs->trans("Mailing"),
768 $help_url,
769 '',
770 0,
771 0,
772 array(
773 '/includes/ace/src/ace.js',
774 '/includes/ace/src/ext-statusbar.js',
775 '/includes/ace/src/ext-language_tools.js',
776 //'/includes/ace/src/ext-chromevox.js'
777 ),
778 array()
779);
780
781
782if ($action == 'create') { // aaa
783 // EMailing in creation mode
784 print '<form name="new_mailing" action="'.$_SERVER['PHP_SELF'].'" method="POST">'."\n";
785 print '<input type="hidden" name="token" value="'.newToken().'">';
786 print '<input type="hidden" name="action" value="add">';
787
788 $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br><br><span class="small">';
789 foreach ($object->substitutionarray as $key => $val) {
790 $htmltext .= $key.' = '.$langs->trans($val).'<br>';
791 }
792 $htmltext .= '</span></i>';
793
794
795 $availablelink = $form->textwithpicto('<span class="opacitymedium hideonsmartphone">'.$langs->trans("AvailableVariables").'</span>', $htmltext, 1, 'helpclickable', '', 0, 2, 'availvar');
796 //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>';
797
798
799 // Print mail form
800 print load_fiche_titre($langs->trans("NewMailing"), $availablelink, 'object_email');
801
802 print dol_get_fiche_head(array(), '', '', 0, '', 0, '', '');
803
804 print '<table class="border centpercent">';
805
806 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>';
807
808 if (getDolGlobalInt('EMAILINGS_SUPPORT_ALSO_SMS')) {
809 $arrayoftypes = array("email" => "Email", "sms" => "SMS");
810 print '<tr><td class="fieldrequired titlefieldcreate">'.$langs->trans("Type").'</td><td>';
811 print $form->selectarray('messtype', $arrayoftypes, (GETPOSTISSET('messtype') ? GETPOST('messtype') : 'email'), 0, 0);
812
813 print '<script>
814 $( document ).ready(function() {
815 jQuery("#messtype").on("change", function() {
816 console.log("We change the message ttpe");
817 if (jQuery("#messtype").val() == "email") {
818 jQuery(".fieldsforsms").hide();
819 jQuery(".fieldsforemail").show();
820 }
821 if (jQuery("#messtype").val() == "sms") {
822 jQuery(".fieldsforsms").show();
823 jQuery(".fieldsforemail").hide();
824 }
825 });
826 jQuery("#messtype").change();
827 })
828 </script>';
829
830 print '</td></tr>';
831 }
832 print '</table>';
833
834 print '<br>';
835
836 print '<table class="border centpercent">';
837
838 print '<tr class="fieldsforemail"><td class="fieldrequired titlefieldcreate">'.$langs->trans("MailFrom").'</td>';
839 print '<td>'.img_picto('', 'email', 'class="pictofixedwidth"').'<input class="flat minwidth200" name="from" value="'.(GETPOSTISSET('from') ? GETPOST('from') : getDolGlobalString('MAILING_EMAIL_FROM')).'"></td></tr>';
840
841 print '<tr class="fieldsforsms hidden"><td class="fieldrequired titlefieldcreate">'.$langs->trans("PhoneFrom").'</td>';
842 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>';
843
844 print '<tr class="fieldsforemail"><td>'.$langs->trans("MailErrorsTo").'</td>';
845 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>';
846
847 print '<tr class="fieldsforemail"><td>'.$langs->trans("MailReply").'</td>';
848 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>';
849
850 // Other attributes
851 $parameters = array();
852 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
853 print $hookmanager->resPrint;
854 if (empty($reshook)) {
855 print $object->showOptionals($extrafields, 'create');
856 }
857
858 print '</table>';
859
860 print '<br>';
861
862 print '<table class="border centpercent">';
863 print '<tr class="fieldsforemail"><td class="fieldrequired titlefieldcreate">'.$langs->trans("MailTopic").'</td><td><input id="sujet" class="flat minwidth200 quatrevingtpercent" name="sujet" value="'.dol_escape_htmltag(GETPOST('sujet', 'alphanohtml')).'"></td></tr>';
864 print '<tr class="fieldsforemail"><td>'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
865 print $htmlother->selectColor(GETPOST('bgcolor'), 'bgcolor', '', 0);
866 print '</td></tr>';
867
868 $formmail = new FormMail($db);
869 $formmail->withfckeditor = 1;
870 $formmail->withlayout = 'emailing';
871 $formmail->withaiprompt = 'html';
872
873 print '<tr class="fieldsforemail"><td></td><td class="tdtop"></td></tr>';
874
875 print '<tr class="fieldsforemail"><td class="tdtop" colspan="2">';
876
877 $out = '';
878 $showlinktolayout = ($formmail->withfckeditor ? $formmail->withlayout : '');
879 $showlinktolayoutlabel = $langs->trans("FillMessageWithALayout");
880 $showlinktoai = ($formmail->withaiprompt && isModEnabled('ai')) ? 'textgenerationemail' : '';
881 $showlinktoailabel = $langs->trans("FillMessageWithAIContent");
882 $formatforouput = 'html';
883 $htmlname = 'bodyemail';
884
885 // Fill $out
886 include DOL_DOCUMENT_ROOT.'/core/tpl/formlayoutai.tpl.php';
887
888 print $out;
889
890 print '</td></tr>';
891 print '</table>';
892
893
894 print '<div style="padding-top: 10px">';
895 // wysiwyg editor
896 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
897 $doleditor = new DolEditor('bodyemail', GETPOST('bodyemail', 'restricthtmlallowunvalid'), '', 600, 'dolibarr_mailings', '', true, -1, getDolGlobalInt('FCKEDITOR_ENABLE_MAILING'), 20, '100%');
898 $doleditor->Create();
899 print '</div>';
900
901 print dol_get_fiche_end();
902
903 print $form->buttonsSaveCancel("Create", 'Cancel');
904
905 print '</form>';
906} else {
907 if ($object->id > 0) {
908 $upload_dir = $conf->mailing->dir_output."/".get_exdir($object->id, 2, 0, 1, $object, 'mailing');
909
911
912 if ($action == 'settodraft') {
913 // Confirmation back to draft
914 print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("SetToDraft"), $langs->trans("ConfirmUnvalidateEmailing"), "confirm_settodraft", '', '', 1);
915 } elseif ($action == 'valid') {
916 // Confirmation of mailing validation
917 print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("ValidMailing"), $langs->trans("ConfirmValidMailing"), "confirm_valid", '', '', 1);
918 } elseif ($action == 'reset') {
919 // Confirm reset
920 print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id, $langs->trans("ResetMailing"), $langs->trans("ConfirmResetMailing", $object->ref), "confirm_reset", '', '', 2);
921 } elseif ($action == 'delete') {
922 // Confirm delete
923 print $form->formconfirm($_SERVER["PHP_SELF"]."?id=".$object->id.(!empty($urlfrom) ? '&urlfrom='.urlencode($urlfrom) : ''), $langs->trans("DeleteMailing"), $langs->trans("ConfirmDeleteMailing"), "confirm_delete", '', '', 1);
924 }
925
926 if ($action != 'edit' && $action != 'edittxt' && $action != 'edithtml') {
927 print dol_get_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email');
928
929 // View mode mailing
930 if ($action == 'sendall') {
931 // Define message to recommend from command line
932 $sendingmode = getDolGlobalString('EMAILING_MAIL_SENDMODE');
933 if (empty($sendingmode)) {
934 $sendingmode = getDolGlobalString('MAIN_MAIL_SENDMODE');
935 }
936 if (empty($sendingmode)) {
937 $sendingmode = 'mail'; // If not defined, we use php mail function
938 }
939
940 // MAILING_NO_USING_PHPMAIL may be defined or not.
941 // MAILING_LIMIT_SENDBYWEB is always defined to something != 0 (-1=forbidden).
942 // MAILING_LIMIT_SENDBYCLI may be defined or not (-1=forbidden, 0 or undefined=no limit).
943 // MAILING_LIMIT_SENDBYDAY may be defined or not (0 or undefined=no limit).
944 if (getDolGlobalString('MAILING_NO_USING_PHPMAIL') && $sendingmode == 'mail') {
945 // 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.
946 // You ensure that every user is using its own SMTP server when using the mass emailing module.
947 $linktoadminemailbefore = '<a href="'.DOL_URL_ROOT.'/admin/mails_emailing.php">';
948 $linktoadminemailend = '</a>';
949 setEventMessages($langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]), null, 'warnings');
950 $messagetoshow = $langs->trans("MailSendSetupIs2", '{s1}', '{s2}', '{s3}', '{s4}');
951 $messagetoshow = str_replace('{s1}', $linktoadminemailbefore, $messagetoshow);
952 $messagetoshow = str_replace('{s2}', $linktoadminemailend, $messagetoshow);
953 $messagetoshow = str_replace('{s3}', $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $messagetoshow);
954 $messagetoshow = str_replace('{s4}', $listofmethods['smtps'], $messagetoshow);
955 setEventMessages($messagetoshow, null, 'warnings');
956
957 if (getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS')) {
958 setEventMessages($langs->trans("MailSendSetupIs3", getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS')), null, 'warnings');
959 }
960 $action = '';
961 } elseif (getDolGlobalInt('MAILING_LIMIT_SENDBYWEB') < 0) {
962 if (getDolGlobalString('MAILING_LIMIT_WARNING_PHPMAIL') && $sendingmode == 'mail') {
963 setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings');
964 }
965 if (getDolGlobalString('MAILING_LIMIT_WARNING_NOPHPMAIL') && $sendingmode != 'mail') {
966 setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings');
967 }
968
969 // The feature is forbidden from GUI, we show just message to use from command line.
970 setEventMessages($langs->trans("MailingNeedCommand"), null, 'warnings');
971 setEventMessages('<textarea cols="60" rows="'.ROWS_1.'" wrap="soft">php ./scripts/emailings/mailing-send.php '.$object->id.'</textarea>', null, 'warnings');
972 if ($conf->file->mailing_limit_sendbyweb != '-1') { // MAILING_LIMIT_SENDBYWEB was set to -1 in database, but it is allowed to increase it.
973 setEventMessages($langs->trans("MailingNeedCommand2"), null, 'warnings'); // You can send online with constant...
974 }
975 $action = '';
976 } else {
977 if (getDolGlobalString('MAILING_LIMIT_WARNING_PHPMAIL') && $sendingmode == 'mail') {
978 setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_PHPMAIL), null, 'warnings');
979 }
980 if (getDolGlobalString('MAILING_LIMIT_WARNING_NOPHPMAIL') && $sendingmode != 'mail') {
981 setEventMessages($langs->transnoentitiesnoconv($conf->global->MAILING_LIMIT_WARNING_NOPHPMAIL), null, 'warnings');
982 }
983
984 $text = '';
985
986 if (getDolGlobalInt('MAILING_LIMIT_SENDBYDAY') > 0) {
987 $text .= $langs->trans('WarningLimitSendByDay', getDolGlobalInt('MAILING_LIMIT_SENDBYDAY'));
988 $text .= '<br><br>';
989 }
990 $text .= $langs->trans('ConfirmSendingEmailing').'<br>';
991 $text .= $langs->trans('LimitSendingEmailing', getDolGlobalString('MAILING_LIMIT_SENDBYWEB'));
992
993 if (!isset($conf->global->MAILING_LIMIT_SENDBYCLI) || getDolGlobalInt('MAILING_LIMIT_SENDBYCLI') >= 0) {
994 $text .= '<br><br>';
995 $text .= '<u>'.$langs->trans("AdvancedAlternative").':</u> '.$langs->trans("MailingNeedCommand");
996 $text .= '<br><textarea class="quatrevingtpercent" rows="'.ROWS_2.'" wrap="soft" disabled>php ./scripts/emailings/mailing-send.php '.$object->id.' '.$user->login.'</textarea>';
997 }
998
999 print $form->formconfirm($_SERVER['PHP_SELF'].'?id='.$object->id, $langs->trans('SendMailing'), $text, 'sendallconfirmed', '', '', 1, 380, 660, 0, $langs->trans("Confirm"), $langs->trans("Cancel"));
1000 }
1001 }
1002
1003 $linkback = '<a href="'.DOL_URL_ROOT.'/comm/mailing/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1004
1005 $morehtmlref = '<div class="refidno">';
1006 // Ref customer
1007 $morehtmlref .= $form->editfieldkey("", 'title', $object->title, $object, $user->hasRight('mailing', 'creer'), 'string', '', 0, 1);
1008 $morehtmlref .= $form->editfieldval("", 'title', $object->title, $object, $user->hasRight('mailing', 'creer'), 'string', '', null, null, '', 1);
1009 $morehtmlref .= '</div>';
1010
1011 $morehtmlstatus = '';
1012 $nbtry = $nbok = 0;
1013 if ($object->status == 2 || $object->status == 3) {
1014 $nbtry = $object->countNbOfTargets('alreadysent');
1015 $nbko = $object->countNbOfTargets('alreadysentko');
1016
1017 $morehtmlstatus .= ' ('.$nbtry.'/'.$object->nbemail;
1018 if ($nbko) {
1019 $morehtmlstatus .= ' - '.$nbko.' '.$langs->trans("Error");
1020 }
1021 $morehtmlstatus .= ') &nbsp; ';
1022 }
1023
1024 dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlstatus);
1025
1026 print '<div class="fichecenter">';
1027 print '<div class="fichehalfleft">';
1028 print '<div class="underbanner clearboth"></div>';
1029 print '<table class="border centpercent tableforfield">'."\n";
1030
1031 // From
1032 print '<tr><td class="titlefield">';
1033 print $form->editfieldkey("MailFrom", 'email_from', $object->email_from, $object, $user->hasRight('mailing', 'creer') && $object->status < $object::STATUS_SENTCOMPLETELY, 'string');
1034 print '</td><td>';
1035 print $form->editfieldval("MailFrom", 'email_from', $object->email_from, $object, $user->hasRight('mailing', 'creer') && $object->status < $object::STATUS_SENTCOMPLETELY, 'string');
1036 $email = CMailFile::getValidAddress($object->email_from, 2);
1037 if ($email && !isValidEmail($email)) {
1038 $langs->load("errors");
1039 print img_warning($langs->trans("ErrorBadEMail", $email));
1040 } elseif ($email && !isValidMailDomain($email)) {
1041 $langs->load("errors");
1042 print img_warning($langs->trans("ErrorBadMXDomain", $email));
1043 }
1044
1045 print '</td></tr>';
1046
1047 // Errors to
1048 if ($object->messtype != 'sms') {
1049 print '<tr><td>';
1050 print $form->editfieldkey("MailErrorsTo", 'email_errorsto', $object->email_errorsto, $object, $user->hasRight('mailing', 'creer') && $object->status < $object::STATUS_SENTCOMPLETELY, 'string');
1051 print '</td><td>';
1052 print $form->editfieldval("MailErrorsTo", 'email_errorsto', $object->email_errorsto, $object, $user->hasRight('mailing', 'creer') && $object->status < $object::STATUS_SENTCOMPLETELY, 'string');
1053 $emailarray = CMailFile::getArrayAddress($object->email_errorsto);
1054 foreach ($emailarray as $email => $name) {
1055 if ($name != $email) {
1056 print dol_escape_htmltag($name).' &lt;'.$email;
1057 print '&gt;';
1058 if ($email && !isValidEmail($email)) {
1059 $langs->load("errors");
1060 print img_warning($langs->trans("ErrorBadEMail", $email));
1061 } elseif ($email && !isValidMailDomain($email)) {
1062 $langs->load("errors");
1063 print img_warning($langs->trans("ErrorBadMXDomain", $email));
1064 }
1065 } else {
1066 print dol_print_email($object->email_errorsto, 0, 0, 0, 0, 1);
1067 }
1068 }
1069 print '</td></tr>';
1070 }
1071
1072 // Reply to
1073 if ($object->messtype != 'sms') {
1074 print '<tr><td>';
1075 print $form->editfieldkey("MailReply", 'email_replyto', $object->email_replyto, $object, $user->hasRight('mailing', 'creer') && $object->status < $object::STATUS_SENTCOMPLETELY, 'string');
1076 print '</td><td>';
1077 print $form->editfieldval("MailReply", 'email_replyto', $object->email_replyto, $object, $user->hasRight('mailing', 'creer') && $object->status < $object::STATUS_SENTCOMPLETELY, 'string');
1078 $email = CMailFile::getValidAddress($object->email_replyto, 2);
1079 if ($action != 'editemail_replyto') {
1080 if ($email && !isValidEmail($email)) {
1081 $langs->load("errors");
1082 print img_warning($langs->trans("ErrorBadEMail", $email));
1083 } elseif ($email && !isValidMailDomain($email)) {
1084 $langs->load("errors");
1085 print img_warning($langs->trans("ErrorBadMXDomain", $email));
1086 }
1087 }
1088 print '</td></tr>';
1089 }
1090
1091 print '</table>';
1092 print '</div>';
1093
1094 print '<div class="fichehalfright">';
1095 print '<div class="underbanner clearboth"></div>';
1096
1097 print '<table class="border centpercent tableforfield">';
1098
1099 // Number of distinct emails
1100 print '<tr><td>';
1101 print $langs->trans("TotalNbOfDistinctRecipients");
1102 print '</td><td>';
1103 $nbemail = ($object->nbemail ? $object->nbemail : 0);
1104 if (is_numeric($nbemail)) {
1105 $text = '';
1106 if ((getDolGlobalString('MAILING_LIMIT_SENDBYWEB') && getDolGlobalInt('MAILING_LIMIT_SENDBYWEB') < $nbemail) && ($object->status == 1 || ($object->status == 2 && $nbtry < $nbemail))) {
1107 if (getDolGlobalInt('MAILING_LIMIT_SENDBYWEB') > 0) {
1108 $text .= $langs->trans('LimitSendingEmailing', getDolGlobalString('MAILING_LIMIT_SENDBYWEB'));
1109 } else {
1110 $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed');
1111 }
1112 }
1113 if (empty($nbemail)) {
1114 $nbemail .= ' '.img_warning('').' <span class="warning">'.$langs->trans("NoTargetYet").'</span>';
1115 }
1116 if ($text) {
1117 print $form->textwithpicto($nbemail, $text, 1, 'warning');
1118 } else {
1119 print $nbemail;
1120 }
1121 }
1122 print '</td></tr>';
1123
1124 print '<tr><td>';
1125 print $langs->trans("MAIN_MAIL_SENDMODE");
1126 print '</td><td>';
1127 if ($object->messtype != 'sms') {
1128 if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'default') {
1129 $text = $listofmethods[getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING')];
1130 } elseif (getDolGlobalString('MAIN_MAIL_SENDMODE')) {
1131 $text = $listofmethods[getDolGlobalString('MAIN_MAIL_SENDMODE')];
1132 } else {
1133 $text = $listofmethods['mail'];
1134 }
1135 print $text;
1136 if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'default') {
1137 if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'mail') {
1138 print ' <span class="opacitymedium">('.getDolGlobalString('MAIN_MAIL_SMTP_SERVER_EMAILING', getDolGlobalString('MAIN_MAIL_SMTP_SERVER')).')</span>';
1139 }
1140 } elseif (getDolGlobalString('MAIN_MAIL_SENDMODE') != 'mail' && getDolGlobalString('MAIN_MAIL_SMTP_SERVER')) {
1141 print ' <span class="opacitymedium">('.getDolGlobalString('MAIN_MAIL_SMTP_SERVER').')</span>';
1142 }
1143 } else {
1144 print 'SMS ';
1145 print ' <span class="opacitymedium">('.getDolGlobalString('MAIN_MAIL_SMTP_SERVER').')</span>';
1146 }
1147 print '</td></tr>';
1148
1149 // Other attributes. Fields from hook formObjectOptions and Extrafields.
1150 include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_view.tpl.php';
1151
1152 print '</table>';
1153 print '</div>';
1154 print '</div>';
1155
1156 print '<div class="clearboth"></div>';
1157
1158 print dol_get_fiche_end();
1159
1160
1161 // Clone confirmation
1162 if ($action == 'clone') {
1163 // Create an array for form
1164 $formquestion = array(
1165 'text' => $langs->trans("ConfirmClone"),
1166 0 => array('type' => 'checkbox', 'name' => 'clone_content', 'label' => $langs->trans("CloneContent"), 'value' => 1),
1167 1 => array('type' => 'checkbox', 'name' => 'clone_receivers', 'label' => $langs->trans("CloneReceivers"), 'value' => 0)
1168 );
1169 // Incomplete payment. On demande si motif = escompte ou autre
1170 print $form->formconfirm($_SERVER["PHP_SELF"].'?id='.$object->id, $langs->trans('ToClone'), $langs->trans('ConfirmCloneEMailing', $object->ref), 'confirm_clone', $formquestion, 'yes', 2, 240);
1171 }
1172
1173 // Actions Buttons
1174 if (GETPOST('cancel', 'alpha') || $confirm == 'no' || $action == '' || in_array($action, array('settodraft', 'valid', 'delete', 'sendall', 'clone', 'test', 'editevenunsubscribe'))) {
1175 print "\n\n<div class=\"tabsAction\">\n";
1176
1177 if (($object->status == 1) && ($user->hasRight('mailing', 'valider') || $object->user_validation_id == $user->id)) {
1178 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=settodraft&token='.newToken().'&id='.$object->id.'">'.$langs->trans("SetToDraft").'</a>';
1179 }
1180
1181 if (($object->status == 0 || $object->status == 1 || $object->status == 2) && $user->hasRight('mailing', 'creer')) {
1182 if (isModEnabled('fckeditor') && getDolGlobalInt('FCKEDITOR_ENABLE_MAILING') && $object->messtype != 'sms') {
1183 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edit&token='.newToken().'&id='.$object->id.'">'.$langs->trans("Edit").'</a>';
1184 } else {
1185 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edittxt&token='.newToken().'&id='.$object->id.'">'.$langs->trans("EditWithTextEditor").'</a>';
1186 }
1187
1188 if (!getDolGlobalInt('EMAILINGS_SUPPORT_ALSO_SMS')) {
1189 if (!empty($conf->use_javascript_ajax)) {
1190 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=edithtml&token='.newToken().'&id='.$object->id.'">'.$langs->trans("EditHTMLSource").'</a>';
1191 }
1192 }
1193 }
1194
1195 //print '<a class="butAction" href="card.php?action=test&amp;id='.$object->id.'">'.$langs->trans("PreviewMailing").'</a>';
1196
1197 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('mailing', 'mailing_advance', 'send')) {
1198 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("TestMailing").'</a>';
1199 } else {
1200 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=test&token='.newToken().'&id='.$object->id.'">'.$langs->trans("TestMailing").'</a>';
1201 }
1202
1203 if ($object->status == 0) {
1204 if ($object->nbemail <= 0) {
1205 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NoTargetYet")).'">'.$langs->trans("Validate").'</a>';
1206 } elseif (!$user->hasRight('mailing', 'valider')) {
1207 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("Validate").'</a>';
1208 } else {
1209 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=valid&amp;id='.$object->id.'">'.$langs->trans("Validate").'</a>';
1210 }
1211 }
1212
1213 if (($object->status == 1 || $object->status == 2) && $object->nbemail > 0 && $user->hasRight('mailing', 'valider')) {
1214 if (getDolGlobalInt('MAILING_LIMIT_SENDBYWEB') < 0) {
1215 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("SendingFromWebInterfaceIsNotAllowed")).'">'.$langs->trans("SendMailing").'</a>';
1216 } elseif (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('mailing', 'mailing_advance', 'send')) {
1217 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("SendMailing").'</a>';
1218 } else {
1219 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=sendall&amp;id='.$object->id.'">'.$langs->trans("SendMailing").'</a>';
1220 }
1221 }
1222
1223 if ($user->hasRight('mailing', 'creer')) {
1224 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=clone&amp;object=emailing&amp;id='.$object->id.'">'.$langs->trans("ToClone").'</a>';
1225 }
1226
1227 if (($object->status == 2 || $object->status == 3) && $user->hasRight('mailing', 'valider')) {
1228 if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('mailing', 'mailing_advance', 'send')) {
1229 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("ResetMailing").'</a>';
1230 } else {
1231 print '<a class="butAction" href="'.$_SERVER['PHP_SELF'].'?action=reset&amp;id='.$object->id.'">'.$langs->trans("ResetMailing").'</a>';
1232 }
1233 }
1234
1235 if (($object->status <= 1 && $user->hasRight('mailing', 'creer')) || $user->hasRight('mailing', 'supprimer')) {
1236 if ($object->status > 0 && (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && !$user->hasRight('mailing', 'mailing_advance', 'delete'))) {
1237 print '<a class="butActionRefused classfortooltip" href="#" title="'.dol_escape_htmltag($langs->transnoentitiesnoconv("NotEnoughPermissions")).'">'.$langs->trans("Delete").'</a>';
1238 } else {
1239 print '<a class="butActionDelete" href="'.$_SERVER['PHP_SELF'].'?action=delete&token='.newToken().'&id='.$object->id.(!empty($urlfrom) ? '&urlfrom='.$urlfrom : '').'">'.$langs->trans("Delete").'</a>';
1240 }
1241 }
1242
1243 print '</div>';
1244 }
1245
1246 // Display of the TEST form
1247 if ($action == 'test') {
1248 print '<div id="formmailbeforetitle" name="formmailbeforetitle"></div>';
1249 print load_fiche_titre($langs->trans("TestMailing"));
1250
1251 print dol_get_fiche_head([], '', '', -1);
1252
1253 // Create mail form object
1254 include_once DOL_DOCUMENT_ROOT.'/core/class/html.formmail.class.php';
1255 $formmail = new FormMail($db);
1256 $formmail->fromname = $object->email_from;
1257 $formmail->frommail = $object->email_from;
1258 $formmail->withsubstit = 0;
1259 $formmail->withfrom = 0;
1260 $formmail->withto = $user->email ? $user->email : 1;
1261 $formmail->withtocc = 0;
1262 $formmail->withtoccc = getDolGlobalString('MAIN_EMAIL_USECCC');
1263 $formmail->withtopic = 0;
1264 $formmail->withtopicreadonly = 1;
1265 $formmail->withfile = 0;
1266 $formmail->withlayout = '';
1267 $formmail->withaiprompt = '';
1268 $formmail->withbody = 0;
1269 $formmail->withbodyreadonly = 1;
1270 $formmail->withcancel = 1;
1271 $formmail->withdeliveryreceipt = 0;
1272 // Table of substitutions
1273 $formmail->substit = $object->substitutionarrayfortest;
1274 // Table of post's complementary params
1275 $formmail->param["action"] = "send";
1276 $formmail->param["models"] = 'none';
1277 $formmail->param["mailid"] = $object->id;
1278 $formmail->param["returnurl"] = $_SERVER['PHP_SELF']."?id=".$object->id;
1279
1280 print $formmail->get_form();
1281
1282 print '<br>';
1283
1284 print dol_get_fiche_end();
1285
1286 dol_set_focus('#sendto');
1287 }
1288
1289
1290 $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br><br><span class="small">';
1291 foreach ($object->substitutionarray as $key => $val) {
1292 $htmltext .= $key.' = '.$langs->trans($val).'<br>';
1293 }
1294 $htmltext .= '</span></i>';
1295
1296 // Print mail content
1297 print load_fiche_titre($langs->trans("EMail"), $form->textwithpicto('<span class="opacitymedium hideonsmartphone">'.$langs->trans("AvailableVariables").'</span>', $htmltext, 1, 'helpclickable', '', 0, 3, 'emailsubstitionhelp'), 'generic');
1298
1299 print dol_get_fiche_head([], '', '', -1);
1300
1301 print '<table class="bordernooddeven tableforfield centpercent">';
1302
1303 // Subject
1304 if ($object->messtype != 'sms') {
1305 print '<tr><td class="titlefield">'.$langs->trans("MailTopic").'</td><td colspan="3">'.$object->sujet.'</td></tr>';
1306 }
1307
1308 // Joined files
1309 if ($object->messtype != 'sms') {
1310 print '<tr><td>'.$langs->trans("MailFile").'</td><td colspan="3">';
1311 // List of files
1312 $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0);
1313 if (count($listofpaths)) {
1314 foreach ($listofpaths as $key => $val) {
1315 print img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name'];
1316 print '<br>';
1317 }
1318 } else {
1319 print '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
1320 }
1321 print '</td></tr>';
1322 }
1323
1324 // Background color
1325 /*print '<tr><td width="15%">'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
1326 print $htmlother->selectColor($object->bgcolor,'bgcolor','',0);
1327 print '</td></tr>';*/
1328
1329 print '</table>';
1330
1331 // Message
1332 print '<div style="padding-top: 10px; background: '.($object->bgcolor ? (preg_match('/^#/', $object->bgcolor) ? '' : '#').$object->bgcolor : 'white').'">';
1333 if (empty($object->bgcolor) || strtolower($object->bgcolor) == 'ffffff') { // CKEditor does not apply the color of the div into its content area
1334 $readonly = 1;
1335 // wysiwyg editor
1336 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1337 $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', false, -1, getDolGlobalInt('FCKEDITOR_ENABLE_MAILING'), 20, '100%', $readonly);
1338 $doleditor->Create();
1339 } else {
1340 print dol_htmlentitiesbr($object->body);
1341 }
1342 print '</div>';
1343
1344 print dol_get_fiche_end();
1345 } else {
1346 /*
1347 * Edition mode mailing (CKeditor or HTML source)
1348 */
1349
1350 print dol_get_fiche_head($head, 'card', $langs->trans("Mailing"), -1, 'email');
1351
1352 $linkback = '<a href="'.DOL_URL_ROOT.'/comm/mailing/list.php?restore_lastsearch_values=1">'.$langs->trans("BackToList").'</a>';
1353
1354 $morehtmlref = '<div class="refidno">';
1355 // Ref customer
1356 $morehtmlref .= $form->editfieldkey("", 'title', $object->title, $object, $user->hasRight('mailing', 'creer'), 'string', '', 0, 1);
1357 $morehtmlref .= $form->editfieldval("", 'title', $object->title, $object, $user->hasRight('mailing', 'creer'), 'string', '', null, null, '', 1);
1358 $morehtmlref .= '</div>';
1359
1360 $morehtmlstatus = '';
1361 $nbtry = $nbok = 0;
1362 if ($object->status == 2 || $object->status == 3) {
1363 $nbtry = $object->countNbOfTargets('alreadysent');
1364 $nbko = $object->countNbOfTargets('alreadysentko');
1365
1366 $morehtmlstatus .= ' ('.$nbtry.'/'.$object->nbemail;
1367 if ($nbko) {
1368 $morehtmlstatus .= ' - '.$nbko.' '.$langs->trans("Error");
1369 }
1370 $morehtmlstatus .= ') &nbsp; ';
1371 }
1372
1373 dol_banner_tab($object, 'id', $linkback, 1, 'rowid', 'ref', $morehtmlref, '', 0, '', $morehtmlstatus);
1374
1375 print '<div class="fichecenter">';
1376 print '<div class="fichehalfleft">';
1377 print '<div class="underbanner clearboth"></div>';
1378
1379 print '<table class="border centpercent tableforfield">';
1380
1381 /*
1382 print '<tr><td class="titlefield">'.$langs->trans("Ref").'</td>';
1383 print '<td colspan="3">';
1384 print $form->showrefnav($object,'id', $linkback);
1385 print '</td></tr>';
1386 */
1387
1388 // From
1389 print '<tr><td class="titlefield">';
1390 print $langs->trans("MailFrom");
1391 print '</td><td>'.dol_print_email($object->email_from, 0, 0, 0, 0, 1).'</td></tr>';
1392 // To
1393 if ($object->messtype != 'sms') {
1394 print '<tr><td>'.$langs->trans("MailErrorsTo").'</td><td>'.dol_print_email($object->email_errorsto, 0, 0, 0, 0, 1).'</td></tr>';
1395 print '<tr><td>'.$langs->trans("MailReply").'</td><td>'.dol_print_email($object->email_replyto, 0, 0, 0, 0, 1).'</td></tr>';
1396 }
1397
1398 print '</table>';
1399 print '</div>';
1400
1401
1402 print '<div class="fichehalfright">';
1403 print '<div class="underbanner clearboth"></div>';
1404
1405 print '<table class="border centpercent tableforfield">';
1406
1407 // Number of distinct emails
1408 print '<tr><td>';
1409 print $langs->trans("TotalNbOfDistinctRecipients");
1410 print '</td><td>';
1411 $nbemail = ($object->nbemail ? $object->nbemail : 0);
1412 if (is_numeric($nbemail)) {
1413 $text = '';
1414 if ((getDolGlobalString('MAILING_LIMIT_SENDBYWEB') && $conf->global->MAILING_LIMIT_SENDBYWEB < $nbemail) && ($object->status == 1 || $object->status == 2)) {
1415 if (getDolGlobalInt('MAILING_LIMIT_SENDBYWEB') > 0) {
1416 $text .= $langs->trans('LimitSendingEmailing', getDolGlobalString('MAILING_LIMIT_SENDBYWEB'));
1417 } else {
1418 $text .= $langs->trans('SendingFromWebInterfaceIsNotAllowed');
1419 }
1420 }
1421 if (empty($nbemail)) {
1422 $nbemail .= ' '.img_warning('').' <span class="warning">'.$langs->trans("NoTargetYet").'</span>';
1423 }
1424 if ($text) {
1425 print $form->textwithpicto($nbemail, $text, 1, 'warning');
1426 } else {
1427 print $nbemail;
1428 }
1429 }
1430 print '</td></tr>';
1431
1432 print '<tr><td>';
1433 print $langs->trans("MAIN_MAIL_SENDMODE");
1434 print '</td><td>';
1435 if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'default') {
1436 $text = $listofmethods[getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING')];
1437 } elseif (getDolGlobalString('MAIN_MAIL_SENDMODE')) {
1438 $text = $listofmethods[getDolGlobalString('MAIN_MAIL_SENDMODE')];
1439 } else {
1440 $text = $listofmethods['mail'];
1441 }
1442 print $text;
1443 if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'default') {
1444 if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'mail') {
1445 print ' <span class="opacitymedium">('.getDolGlobalString('MAIN_MAIL_SMTP_SERVER_EMAILING').')</span>';
1446 }
1447 } elseif (getDolGlobalString('MAIN_MAIL_SENDMODE') != 'mail' && getDolGlobalString('MAIN_MAIL_SMTP_SERVER')) {
1448 print ' <span class="opacitymedium">('.getDolGlobalString('MAIN_MAIL_SMTP_SERVER').')</span>';
1449 }
1450 print '</td></tr>';
1451
1452
1453 // Other attributes
1454 $parameters = array();
1455 $reshook = $hookmanager->executeHooks('formObjectOptions', $parameters, $object, $action); // Note that $action and $object may have been modified by hook
1456 print $hookmanager->resPrint;
1457 if (empty($reshook)) {
1458 print $object->showOptionals($extrafields, 'edit', $parameters);
1459 }
1460
1461 print '</table>';
1462 print '</div>';
1463 print '</div>';
1464
1465 print '<div class="clearboth"></div>';
1466
1467 print dol_get_fiche_end();
1468
1469
1470 print "<br><br>\n";
1471
1472 print '<form name="edit_mailing" action="card.php" method="post" enctype="multipart/form-data">'."\n";
1473 print '<input type="hidden" name="token" value="'.newToken().'">';
1474 print '<input type="hidden" name="action" value="update">';
1475 print '<input type="hidden" name="id" value="'.$object->id.'">';
1476
1477 $htmltext = '<i>'.$langs->trans("FollowingConstantsWillBeSubstituted").':<br><br><span class="small">';
1478 foreach ($object->substitutionarray as $key => $val) {
1479 $htmltext .= $key.' = '.$langs->trans($val).'<br>';
1480 }
1481 $htmltext .= '</span></i>';
1482
1483 // Print mail content
1484 print load_fiche_titre($langs->trans("EMail"), '<span class="opacitymedium">'.$form->textwithpicto($langs->trans("AvailableVariables").'</span>', $htmltext, 1, 'help', '', 0, 2, 'emailsubstitionhelp'), 'generic');
1485
1486 print dol_get_fiche_head([], '', '', -1);
1487
1488 print '<table class="bordernooddeven centpercent">';
1489
1490 // Subject
1491 if ($object->messtype != 'sms') {
1492 print '<tr><td class="fieldrequired titlefield">';
1493 print $langs->trans("MailTopic");
1494 print '</td><td colspan="3"><input class="flat quatrevingtpercent" type="text" name="sujet" value="'.$object->sujet.'"></td></tr>';
1495 }
1496
1497 $trackid = ''; // TODO To avoid conflicts with 2 mass emailing, we should set a trackid here, even if we use another one into email header.
1498 dol_init_file_process($upload_dir, $trackid);
1499
1500 // Joined files
1501 if ($object->messtype != 'sms') {
1502 $addfileaction = 'addfile';
1503 print '<tr><td>'.$langs->trans("MailFile").'</td>';
1504 print '<td colspan="3">';
1505 // List of files
1506 $listofpaths = dol_dir_list($upload_dir, 'all', 0, '', '', 'name', SORT_ASC, 0);
1507 $out = '';
1508
1509 // TODO Trick to have param removedfile containing nb of image to delete. But this does not works without javascript
1510 $out .= '<input type="hidden" class="removedfilehidden" name="removedfile" value="">'."\n";
1511 $out .= '<script type="text/javascript">';
1512 $out .= 'jQuery(document).ready(function () {';
1513 $out .= ' jQuery(".removedfile").click(function() {';
1514 $out .= ' jQuery(".removedfilehidden").val(jQuery(this).val());';
1515 $out .= ' });';
1516 $out .= '})';
1517 $out .= '</script>'."\n";
1518 if (count($listofpaths)) {
1519 foreach ($listofpaths as $key => $val) {
1520 $out .= '<div id="attachfile_'.$key.'">';
1521 $out .= img_mime($listofpaths[$key]['name']).' '.$listofpaths[$key]['name'];
1522 $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.'" />';
1523 $out .= '<br></div>';
1524 }
1525 } else {
1526 //$out .= '<span class="opacitymedium">'.$langs->trans("NoAttachedFiles").'</span><br>';
1527 }
1528
1529 // Add link to add file
1530 $maxfilesizearray = getMaxFileSizeArray();
1531 $maxmin = $maxfilesizearray['maxmin'];
1532 if ($maxmin > 0) {
1533 $out .= '<input type="hidden" name="MAX_FILE_SIZE" value="'.($maxmin * 1024).'">'; // MAX_FILE_SIZE must precede the field type=file
1534 }
1535 $out .= '<input type="file" class="flat" id="addedfile" name="addedfile" value="'.$langs->trans("Upload").'" />';
1536 $out .= ' ';
1537 $out .= '<input type="submit" class="button smallpaddingimp" id="'.$addfileaction.'" name="'.$addfileaction.'" value="'.$langs->trans("MailingAddFile").'" />';
1538 print $out;
1539 print '</td></tr>';
1540
1541 // Background color
1542 print '<tr><td>'.$langs->trans("BackgroundColorByDefault").'</td><td colspan="3">';
1543 print $htmlother->selectColor($object->bgcolor, 'bgcolor', '', 0);
1544 print '</td></tr>';
1545 }
1546
1547 print '</table>';
1548
1549
1550 // Message
1551 print '<div style="padding-top: 10px">';
1552
1553 if ($action == 'edit') {
1554 // wysiwyg editor
1555 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1556 $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, -1, getDolGlobalInt('FCKEDITOR_ENABLE_MAILING'), 20, '100%');
1557 $doleditor->Create();
1558 }
1559 if ($action == 'edittxt') {
1560 // wysiwyg editor
1561 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1562 $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, -1, 0, 20, '100%');
1563 $doleditor->Create();
1564 }
1565 if ($action == 'edithtml') {
1566 // HTML source editor
1567 require_once DOL_DOCUMENT_ROOT.'/core/class/doleditor.class.php';
1568 $doleditor = new DolEditor('bodyemail', $object->body, '', 600, 'dolibarr_mailings', '', true, -1, 'ace', 20, '100%');
1569 $doleditor->Create(0, '', false, 'HTML Source', 'php');
1570 }
1571
1572 print '</div>';
1573
1574
1575 print dol_get_fiche_end();
1576
1577 print '<div class="center">';
1578 print '<input type="submit" class="button buttonforacesave button-save" value="'.$langs->trans("Save").'" name="save">';
1579 print '&nbsp; &nbsp; &nbsp;';
1580 print '<input type="submit" class="button button-cancel" value="'.$langs->trans("Cancel").'" name="cancel">';
1581 print '</div>';
1582
1583 print '</form>';
1584 print '<br>';
1585 }
1586 } else {
1587 dol_print_error($db, $object->error);
1588 }
1589}
1590
1591// End of page
1592llxFooter();
1593$db->close();
$id
Definition account.php:48
if( $user->socid > 0) if(! $user->hasRight('accounting', 'chartofaccount')) $object
Definition card.php:66
llxFooter($comment='', $zone='private', $disabledoutputofmessages=0)
Empty footer.
Definition wrapper.php:87
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:71
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, $varfiles='addedfile', $savingdocmask='', $link=null, $trackid='', $generatethumbs=1, $object=null, $forceFullTestIndexation='')
Get and save an upload file (for example after submitting a new file 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)
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...
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 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.