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