dolibarr 19.0.3
CMailFile.class.php
Go to the documentation of this file.
1<?php
33use OAuth\Common\Storage\DoliStorage;
34use OAuth\Common\Consumer\Credentials;
35
36
43{
44 public $sendcontext;
45 public $sendmode;
46 public $sendsetup;
47
51 public $subject;
52 public $addr_from; // From: Label and EMail of sender (must include '<>'). For example '<myemail@example.com>' or 'John Doe <myemail@example.com>' or '<myemail+trackingid@example.com>'). Note that with gmail smtps, value here is forced by google to account (but not the reply-to).
53 // Sender: Who send the email ("Sender" has sent emails on behalf of "From").
54 // Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
55 // Return-Path: Email where to send bounds.
56 public $reply_to; // Reply-To: Email where to send replies from mailer software (mailer use From if reply-to not defined, Gmail use gmail account if reply-to not defined)
57 public $errors_to; // Errors-To: Email where to send errors.
58 public $addr_to;
59 public $addr_cc;
60 public $addr_bcc;
61 public $trackid;
62
63 public $mixed_boundary;
64 public $related_boundary;
65 public $alternative_boundary;
66 public $deliveryreceipt;
67
68 public $atleastonefile;
69
70 public $msg;
71 public $eol;
72 public $eol2;
73
77 public $error = '';
78
82 public $errors = array();
83
84
88 public $smtps;
92 public $mailer;
93
97 public $transport;
101 public $logger;
102
106 public $css;
108 public $styleCSS;
110 public $bodyCSS;
111
115 public $msgid;
116 public $headers;
117 public $message;
118
122 public $filename_list = array();
126 public $mimetype_list = array();
130 public $mimefilename_list = array();
134 public $cid_list = array();
135
136 // Image
137 public $html;
138 public $msgishtml;
139 public $image_boundary;
140 public $atleastoneimage = 0; // at least one image file with file=xxx.ext into content (TODO Debug this. How can this case be tested. Remove if not used).
141 public $html_images = array();
142 public $images_encoded = array();
143 public $image_types = array(
144 'gif' => 'image/gif',
145 'jpg' => 'image/jpeg',
146 'jpeg' => 'image/jpeg',
147 'jpe' => 'image/jpeg',
148 'bmp' => 'image/bmp',
149 'png' => 'image/png',
150 'tif' => 'image/tiff',
151 'tiff' => 'image/tiff',
152 );
153
154
177 public function __construct($subject, $to, $from, $msg, $filename_list = array(), $mimetype_list = array(), $mimefilename_list = array(), $addr_cc = "", $addr_bcc = "", $deliveryreceipt = 0, $msgishtml = 0, $errors_to = '', $css = '', $trackid = '', $moreinheader = '', $sendcontext = 'standard', $replyto = '', $upload_dir_tmp = '')
178 {
179 global $conf, $dolibarr_main_data_root, $user;
180
181 dol_syslog("CMailFile::CMailfile: charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, replyto=$replyto trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
182 dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
183
184
185 // Clean values of $mimefilename_list
186 if (is_array($mimefilename_list)) {
187 foreach ($mimefilename_list as $key => $val) {
188 $mimefilename_list[$key] = dol_string_unaccent($mimefilename_list[$key]);
189 }
190 }
191
192 $cid_list = array();
193
194 $this->sendcontext = $sendcontext;
195
196 // Define this->sendmode ('mail', 'smtps', 'swiftmailer', ...) according to $sendcontext ('standard', 'emailing', 'ticket', 'password')
197 $this->sendmode = '';
198 if (!empty($this->sendcontext)) {
199 $smtpContextKey = strtoupper($this->sendcontext);
200 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
201 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
202 $this->sendmode = $smtpContextSendMode;
203 }
204 }
205 if (empty($this->sendmode)) {
206 $this->sendmode = (getDolGlobalString('MAIN_MAIL_SENDMODE') ? $conf->global->MAIN_MAIL_SENDMODE : 'mail');
207 }
208
209 // We define end of line (RFC 821).
210 $this->eol = "\r\n";
211 // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
212 $this->eol2 = "\r\n";
213 if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) {
214 $this->eol = "\n";
215 $this->eol2 = "\n";
216 $moreinheader = str_replace("\r\n", "\n", $moreinheader);
217 }
218
219 // On defini mixed_boundary
220 $this->mixed_boundary = "multipart_x.".time().".x_boundary";
221
222 // On defini related_boundary
223 $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contain special chars)
224
225 // On defini alternative_boundary
226 $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contain special chars)
227
228 if (empty($subject)) {
229 dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
230 $this->error = 'ErrorSubjectIsRequired';
231 return;
232 }
233 if (empty($msg)) {
234 dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
235 $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure)
236 }
237
238 // Detect if message is HTML (use fast method)
239 if ($msgishtml == -1) {
240 $this->msgishtml = 0;
241 if (dol_textishtml($msg)) {
242 $this->msgishtml = 1;
243 }
244 } else {
245 $this->msgishtml = $msgishtml;
246 }
247
248 global $dolibarr_main_url_root;
249
250 // Define $urlwithroot
251 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
252 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
253 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
254
255 // Replace relative /viewimage to absolute path
256 $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1);
257
258 if (getDolGlobalString('MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML')) {
259 $this->msgishtml = 1; // To force to send everything with content type html.
260 }
261
262 // Detect images
263 if ($this->msgishtml) {
264 $this->html = $msg;
265
266 $findimg = 0;
267 if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS')) { // Off by default
268 // Search into the body for <img tags of links in medias files to replace them with an embedded file
269 // Note because media links are public, this should be useless, except avoid blocking images with email browser.
270 // This convert an embedd file with src="/viewimage.php?modulepart... into a cid link
271 // TODO Exclude viewimage used for the read tracker ?
272 $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
273 if ($findimg<0) {
274 dol_syslog("CMailFile::CMailfile: Error on findHtmlImages");
275 $this->error = 'ErrorInAddAttachementsImageBaseOnMedia';
276 return;
277 }
278 }
279
280 if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA')) {
281 // Search into the body for <img src="data:image/ext;base64,..." to replace them with an embedded file
282 // This convert an embedded file with src="data:image... into a cid link + attached file
283 $resultImageData = $this->findHtmlImagesIsSrcData($upload_dir_tmp);
284 if ($resultImageData < 0) {
285 dol_syslog("CMailFile::CMailfile: Error on findHtmlImagesInSrcData code=".$resultImageData." upload_dir_tmp=".$upload_dir_tmp);
286 dol_syslog("CMailFile::CMailfile: ".implode(',', $this->errors)); // Output errors set by findHtmlImagesInSrcData
287 $this->error = 'ErrorInAddAttachementsImageBaseOnMedia';
288 return;
289 }
290 $findimg += $resultImageData;
291 }
292
293 // Set atleastoneimage if there is at least one embedded file (into ->html_images)
294 if ($findimg > 0) {
295 foreach ($this->html_images as $i => $val) {
296 if ($this->html_images[$i]) {
297 $this->atleastoneimage = 1;
298 if ($this->html_images[$i]['type'] == 'cidfromdata') {
299 if (!in_array($this->html_images[$i]['fullpath'], $filename_list)) {
300 // If this file path is not already into the $filename_list, we add it.
301 $posindice = count($filename_list);
302 $filename_list[$posindice] = $this->html_images[$i]['fullpath'];
303 $mimetype_list[$posindice] = $this->html_images[$i]['content_type'];
304 $mimefilename_list[$posindice] = $this->html_images[$i]['name'];
305 } else {
306 $posindice = array_search($this->html_images[$i]['fullpath'], $filename_list);
307 }
308 // We complete the array of cid_list
309 $cid_list[$posindice] = $this->html_images[$i]['cid'];
310 }
311 dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
312 }
313 }
314 }
315 }
316 //var_dump($filename_list);
317 //var_dump($cid_list);exit;
318
319 // Set atleastoneimage if there is at least one file (into $filename_list array)
320 if (is_array($filename_list)) {
321 foreach ($filename_list as $i => $val) {
322 if ($filename_list[$i]) {
323 $this->atleastonefile = 1;
324 dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i]." cid_list[$i]=".$cid_list[$i], LOG_DEBUG);
325 }
326 }
327 }
328
329 // Add auto copy to if not already in $to (Note: Adding bcc for specific modules are also done from pages)
330 // For example MAIN_MAIL_AUTOCOPY_TO can be 'email@example.com, __USER_EMAIL__, ...'
331 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')) {
332 $listofemailstoadd = explode(',', getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO'));
333 foreach ($listofemailstoadd as $key => $val) {
334 $emailtoadd = $listofemailstoadd[$key];
335 if (trim($emailtoadd) == '__USER_EMAIL__') {
336 if (!empty($user) && !empty($user->email)) {
337 $emailtoadd = $user->email;
338 } else {
339 $emailtoadd = '';
340 }
341 }
342 if ($emailtoadd && preg_match('/'.preg_quote($emailtoadd, '/').'/i', $to)) {
343 $emailtoadd = ''; // Email already in the "To"
344 }
345 if ($emailtoadd) {
346 $listofemailstoadd[$key] = $emailtoadd;
347 } else {
348 unset($listofemailstoadd[$key]);
349 }
350 }
351 if (!empty($listofemailstoadd)) {
352 $addr_bcc .= ($addr_bcc ? ', ' : '').join(', ', $listofemailstoadd);
353 }
354 }
355
356 // We always use a replyto
357 if (empty($replyto)) {
358 $replyto = dol_sanitizeEmail($from);
359 }
360 // We can force the from
361 if (getDolGlobalString('MAIN_MAIL_FORCE_FROM')) {
362 $from = getDolGlobalString('MAIN_MAIL_FORCE_FROM');
363 }
364
365 $this->subject = $subject;
366 $this->addr_to = dol_sanitizeEmail($to);
367 $this->addr_from = dol_sanitizeEmail($from);
368 $this->msg = $msg;
369 $this->addr_cc = dol_sanitizeEmail($addr_cc);
370 $this->addr_bcc = dol_sanitizeEmail($addr_bcc);
371 $this->deliveryreceipt = $deliveryreceipt;
372 $this->reply_to = dol_sanitizeEmail($replyto);
373 $this->errors_to = dol_sanitizeEmail($errors_to);
374 $this->trackid = $trackid;
375 // Set arrays with attached files info
376 $this->filename_list = $filename_list;
377 $this->mimetype_list = $mimetype_list;
378 $this->mimefilename_list = $mimefilename_list;
379 $this->cid_list = $cid_list;
380
381 if (getDolGlobalString('MAIN_MAIL_FORCE_SENDTO')) {
382 $this->addr_to = dol_sanitizeEmail(getDolGlobalString('MAIN_MAIL_FORCE_SENDTO'));
383 $this->addr_cc = '';
384 $this->addr_bcc = '';
385 }
386
387 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
388 if (!empty($this->sendcontext)) {
389 $smtpContextKey = strtoupper($this->sendcontext);
390 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
391 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
392 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
393 }
394 }
395
396 dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
397
398 // We set all data according to choosed sending method.
399 // We also set a value for ->msgid
400 if ($this->sendmode == 'mail') {
401 // Use mail php function (default PHP method)
402 // ------------------------------------------
403
404 $smtp_headers = "";
405 $mime_headers = "";
406 $text_body = "";
407 $files_encoded = "";
408
409 // Define smtp_headers (this also set ->msgid)
410 $smtp_headers = $this->write_smtpheaders();
411 if (!empty($moreinheader)) {
412 $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n
413 }
414
415 // Define mime_headers
416 $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
417
418 if (!empty($this->html)) {
419 if (!empty($css)) {
420 $this->css = $css;
421 $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
422 }
423
424 $msg = $this->html;
425 }
426
427 // Define body in text_body
428 $text_body = $this->write_body($msg);
429
430 // Add attachments to text_encoded
431 if (!empty($this->atleastonefile)) {
432 $files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
433 }
434
435 // We now define $this->headers and $this->message
436 $this->headers = $smtp_headers.$mime_headers;
437 // On nettoie le header pour qu'il ne se termine pas par un retour chariot.
438 // This avoid also empty lines at end that can be interpreted as mail injection by email servers.
439 $this->headers = preg_replace("/([\r\n]+)$/i", "", $this->headers);
440
441 //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
442 $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
443 $this->message .= $text_body.$files_encoded;
444 $this->message .= "--".$this->mixed_boundary."--".$this->eol;
445 } elseif ($this->sendmode == 'smtps') {
446 // Use SMTPS library
447 // ------------------------------------------
448
449 require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
450 $smtps = new SMTPs();
451 $smtps->setCharSet($conf->file->character_set_client);
452
453 // Encode subject if required.
454 $subjecttouse = $this->subject;
455 if (!ascii_check($subjecttouse)) {
456 $subjecttouse = $this->encodetorfc2822($subjecttouse);
457 }
458
459 $smtps->setSubject($subjecttouse);
460 $smtps->setTO($this->getValidAddress($this->addr_to, 0, 1));
461 $smtps->setFrom($this->getValidAddress($this->addr_from, 0, 1));
462 $smtps->setTrackId($this->trackid);
463 $smtps->setReplyTo($this->getValidAddress($this->reply_to, 0, 1));
464
465 if (!empty($moreinheader)) {
466 $smtps->setMoreInHeader($moreinheader);
467 }
468
469 if (!empty($this->html)) {
470 if (!empty($css)) {
471 $this->css = $css;
472 $this->buildCSS();
473 }
474 $msg = $this->html;
475 $msg = $this->checkIfHTML($msg); // This add a header and a body including custom CSS to the HTML content
476 }
477
478 // Replace . alone on a new line with .. to avoid to have SMTP interpret this as end of message
479 $msg = preg_replace('/(\r|\n)\.(\r|\n)/ims', '\1..\2', $msg);
480
481 if ($this->msgishtml) {
482 $smtps->setBodyContent($msg, 'html');
483 } else {
484 $smtps->setBodyContent($msg, 'plain');
485 }
486
487 if ($this->atleastoneimage) {
488 foreach ($this->images_encoded as $img) {
489 $smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']);
490 }
491 }
492
493 if (!empty($this->atleastonefile)) {
494 foreach ($filename_list as $i => $val) {
495 $content = file_get_contents($filename_list[$i]);
496 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
497 }
498 }
499
500 $smtps->setCC($this->addr_cc);
501 $smtps->setBCC($this->addr_bcc);
502 $smtps->setErrorsTo($this->errors_to);
503 $smtps->setDeliveryReceipt($this->deliveryreceipt);
504 if (!empty($conf->global->$keyforsslseflsigned)) {
505 $smtps->setOptions(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
506 }
507
508 $host = dol_getprefix('email');
509 $this->msgid = time().'.SMTPs-dolibarr-'.$this->trackid.'@'.$host;
510
511 $this->smtps = $smtps;
512 } elseif ($this->sendmode == 'swiftmailer') {
513 // Use Swift Mailer library
514 $host = dol_getprefix('email');
515
516 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
517
518 // egulias autoloader lib
519 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php';
520
521 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
522
523 // Create the message
524 //$this->message = Swift_Message::newInstance();
525 $this->message = new Swift_Message();
526 //$this->message = new Swift_SignedMessage();
527 // Adding a trackid header to a message
528 $headers = $this->message->getHeaders();
529
530 $headers->addTextHeader('X-Dolibarr-TRACKID', $this->trackid.'@'.$host);
531 $this->msgid = time().'.swiftmailer-dolibarr-'.$this->trackid.'@'.$host;
532 $headerID = $this->msgid;
533 $msgid = $headers->get('Message-ID');
534 $msgid->setId($headerID);
535
536 // Add 'References:' header
537 //$headers->addIdHeader('References', $headerID);
538
539 // Give the message a subject
540 try {
541 $this->message->setSubject($this->subject);
542 } catch (Exception $e) {
543 $this->errors[] = $e->getMessage();
544 }
545
546 // Set the From address with an associative array
547 //$this->message->setFrom(array('john@doe.com' => 'John Doe'));
548 if (!empty($this->addr_from)) {
549 try {
550 if (getDolGlobalString('MAIN_FORCE_DISABLE_MAIL_SPOOFING')) {
551 // Prevent email spoofing for smtp server with a strict configuration
552 $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string
553 $adressEmailFrom = array();
554 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
555 $adressEmailFrom = reset($adressEmailFrom);
556 if ($emailMatchs !== false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
557 $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
558 } else {
559 $this->message->setFrom($this->getArrayAddress($this->addr_from));
560 }
561 } else {
562 $this->message->setFrom($this->getArrayAddress($this->addr_from));
563 }
564 } catch (Exception $e) {
565 $this->errors[] = $e->getMessage();
566 }
567 }
568
569 // Set the To addresses with an associative array
570 if (!empty($this->addr_to)) {
571 try {
572 $this->message->setTo($this->getArrayAddress($this->addr_to));
573 } catch (Exception $e) {
574 $this->errors[] = $e->getMessage();
575 }
576 }
577
578 if (!empty($this->reply_to)) {
579 try {
580 $this->message->SetReplyTo($this->getArrayAddress($this->reply_to));
581 } catch (Exception $e) {
582 $this->errors[] = $e->getMessage();
583 }
584 }
585
586 if (!empty($this->errors_to)) {
587 try {
588 $headers->addTextHeader('Errors-To', $this->getArrayAddress($this->errors_to));
589 } catch (Exception $e) {
590 $this->errors[] = $e->getMessage();
591 }
592 }
593
594 try {
595 $this->message->setCharSet($conf->file->character_set_client);
596 } catch (Exception $e) {
597 $this->errors[] = $e->getMessage();
598 }
599
600 if (!empty($this->html)) {
601 if (!empty($css)) {
602 $this->css = $css;
603 $this->buildCSS();
604 }
605 $msg = $this->html;
606 $msg = $this->checkIfHTML($msg); // This add a header and a body including custom CSS to the HTML content
607 }
608
609 if ($this->atleastoneimage) {
610 foreach ($this->images_encoded as $img) {
611 //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
612 $attachment = Swift_Image::fromPath($img['fullpath']);
613 // embed image
614 $imgcid = $this->message->embed($attachment);
615 // replace cid by the one created by swiftmail in html message
616 $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
617 }
618 }
619
620 if ($this->msgishtml) {
621 $this->message->setBody($msg, 'text/html');
622 // And optionally an alternative body
623 $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
624 } else {
625 $this->message->setBody($msg, 'text/plain');
626 // And optionally an alternative body
627 $this->message->addPart(dol_nl2br($msg), 'text/html');
628 }
629
630 if (!empty($this->atleastonefile)) {
631 foreach ($filename_list as $i => $val) {
632 //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
633 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
634 if (!empty($mimefilename_list[$i])) {
635 $attachment->setFilename($mimefilename_list[$i]);
636 }
637 $this->message->attach($attachment);
638 }
639 }
640
641 if (!empty($this->addr_cc)) {
642 try {
643 $this->message->setCc($this->getArrayAddress($this->addr_cc));
644 } catch (Exception $e) {
645 $this->errors[] = $e->getMessage();
646 }
647 }
648 if (!empty($this->addr_bcc)) {
649 try {
650 $this->message->setBcc($this->getArrayAddress($this->addr_bcc));
651 } catch (Exception $e) {
652 $this->errors[] = $e->getMessage();
653 }
654 }
655 //if (!empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to));
656 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
657 try {
658 $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from));
659 } catch (Exception $e) {
660 $this->errors[] = $e->getMessage();
661 }
662 }
663 } else {
664 // Send mail method not correctly defined
665 // --------------------------------------
666 $this->error = 'Bad value for sendmode';
667 }
668 }
669
675 public function sendfile()
676 {
677 global $conf, $db, $langs, $hookmanager;
678
679 $errorlevel = error_reporting();
680 //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings
681
682 $res = false;
683
684 if (!getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
685 if (!is_object($hookmanager)) {
686 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
687 $hookmanager = new HookManager($db);
688 }
689 $hookmanager->initHooks(array('mail'));
690
691 $parameters = array();
692 $action = '';
693 $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
694 if ($reshook < 0) {
695 $this->error = "Error in hook maildao sendMail ".$reshook;
696 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
697
698 return $reshook;
699 }
700 if ($reshook == 1) { // Hook replace standard code
701 return true;
702 }
703
704 $sendingmode = $this->sendmode;
705 if ($this->sendcontext == 'emailing' && getDolGlobalString('MAILING_NO_USING_PHPMAIL') && $sendingmode == 'mail') {
706 // List of sending methods
707 $listofmethods = array();
708 $listofmethods['mail'] = 'PHP mail function';
709 //$listofmethods['simplemail']='Simplemail class';
710 $listofmethods['smtps'] = 'SMTP/SMTPS socket library';
711
712 // 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.
713 // You ensure that every user is using its own SMTP server when using the mass emailing module.
714 $linktoadminemailbefore = '<a href="'.DOL_URL_ROOT.'/admin/mails.php">';
715 $linktoadminemailend = '</a>';
716 $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
717 $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
718 $this->error .= '<br>'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
719 $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
720 if (getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS')) {
721 $this->error .= '<br>'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
722 $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
723 }
724
725 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
726 return false;
727 }
728
729 // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
730 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL')) {
731 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
732 }
733 $tmparray1 = explode(',', $this->addr_to);
734 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
735 $this->error = 'Too much recipients in to:';
736 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
737 return false;
738 }
739 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL')) {
740 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
741 }
742 $tmparray2 = explode(',', $this->addr_cc);
743 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
744 $this->error = 'Too much recipients in cc:';
745 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
746 return false;
747 }
748 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL')) {
749 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
750 }
751 $tmparray3 = explode(',', $this->addr_bcc);
752 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
753 $this->error = 'Too much recipients in bcc:';
754 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
755 return false;
756 }
757 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL')) {
758 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
759 }
760 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
761 $this->error = 'Too much recipients in to:, cc:, bcc:';
762 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
763 return false;
764 }
765
766 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
767 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
768 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
769 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
770 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
771 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
772 $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
773 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
774 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
775 if (!empty($this->sendcontext)) {
776 $smtpContextKey = strtoupper($this->sendcontext);
777 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
778 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
779 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
780 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
781 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
782 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
783 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
784 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
785 $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
786 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
787 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
788 }
789 }
790
791 // Action according to choosed sending method
792 if ($this->sendmode == 'mail') {
793 // Use mail php function (default PHP method)
794 // ------------------------------------------
795 dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
796 //dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
797 //dol_syslog("CMailFile::sendfile message=\n".$message);
798
799 // If Windows, sendmail_from must be defined
800 if (isset($_SERVER["WINDIR"])) {
801 if (empty($this->addr_from)) {
802 $this->addr_from = 'robot@example.com';
803 }
804 @ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
805 }
806
807 // Force parameters
808 //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".getDolGlobalString($keyforsmtpserver)." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG);
809 if (getDolGlobalString($keyforsmtpserver)) {
810 ini_set('SMTP', getDolGlobalString($keyforsmtpserver));
811 }
812 if (getDolGlobalString($keyforsmtpport)) {
813 ini_set('smtp_port', getDolGlobalString($keyforsmtpport));
814 }
815
816 $res = true;
817 if ($res && !$this->subject) {
818 $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
819 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
820 $res = false;
821 }
822 $dest = $this->getValidAddress($this->addr_to, 2);
823 if ($res && !$dest) {
824 $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
825 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
826 $res = false;
827 }
828
829 if ($res) {
830 $additionnalparam = ''; // By default
831 if (getDolGlobalString('MAIN_MAIL_ALLOW_SENDMAIL_F')) {
832 // When using the phpmail function, the mail command may force the from to the user of the login, for example: linuxuser@myserver.mydomain.com
833 // You can try to set this option to have the command use the From. if it does not work, you can also try the MAIN_MAIL_SENDMAIL_FORCE_BA.
834 // So forcing using the option -f of sendmail is possible if constant MAIN_MAIL_ALLOW_SENDMAIL_F is defined.
835 // Having this variable defined may create problems with some sendmail (option -f refused)
836 // Having this variable not defined may create problems with some other sendmail (option -f required)
837 $additionnalparam .= ($additionnalparam ? ' ' : '').(getDolGlobalString('MAIN_MAIL_ERRORS_TO') ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : ''));
838 }
839 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_BA')) { // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
840 $additionnalparam .= ($additionnalparam ? ' ' : '').'-ba';
841 }
842
843 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM')) {
844 $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params
845 }
846
847 $linuxlike = 1;
848 if (preg_match('/^win/i', PHP_OS)) {
849 $linuxlike = 0;
850 }
851 if (preg_match('/^mac/i', PHP_OS)) {
852 $linuxlike = 0;
853 }
854
855 dol_syslog("CMailFile::sendfile: mail start".($linuxlike ? '' : " HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')).", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
856
857 $this->message = stripslashes($this->message);
858
859 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
860 $this->dump_mail();
861 }
862
863 // Encode subject if required.
864 $subjecttouse = $this->subject;
865 if (!ascii_check($subjecttouse)) {
866 $subjecttouse = $this->encodetorfc2822($subjecttouse);
867 }
868
869 if (!empty($additionnalparam)) {
870 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
871 } else {
872 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
873 }
874
875 if (!$res) {
876 $langs->load("errors");
877 $this->error = "Failed to send mail with php mail";
878 if (!$linuxlike) {
879 $this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
880 }
881 $this->error .= ".<br>";
882 $this->error .= $langs->trans("ErrorPhpMailDelivery");
883 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
884
885 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
886 $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
887 }
888 } else {
889 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
890 }
891 }
892
893 if (isset($_SERVER["WINDIR"])) {
894 @ini_restore('sendmail_from');
895 }
896
897 // Restore parameters
898 if (getDolGlobalString($keyforsmtpserver)) {
899 ini_restore('SMTP');
900 }
901 if (getDolGlobalString($keyforsmtpport)) {
902 ini_restore('smtp_port');
903 }
904 } elseif ($this->sendmode == 'smtps') {
905 if (!is_object($this->smtps)) {
906 $this->error = "Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
907 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
908 return false;
909 }
910
911 // Use SMTPS library
912 // ------------------------------------------
913 $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
914
915 // Clean parameters
916 if (empty($conf->global->$keyforsmtpserver)) {
917 $conf->global->$keyforsmtpserver = ini_get('SMTP');
918 }
919 if (empty($conf->global->$keyforsmtpport)) {
920 $conf->global->$keyforsmtpport = ini_get('smtp_port');
921 }
922
923 // If we use SSL/TLS
924 $server = getDolGlobalString($keyforsmtpserver);
925 $secure = '';
926 if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
927 $secure = 'ssl';
928 }
929 if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
930 $secure = 'tls';
931 }
932 $server = ($secure ? $secure.'://' : '').$server;
933
934 $port = getDolGlobalInt($keyforsmtpport);
935
936 $this->smtps->setHost($server);
937 $this->smtps->setPort($port); // 25, 465...;
938
939 $loginid = '';
940 $loginpass = '';
941 if (!empty($conf->global->$keyforsmtpid)) {
942 $loginid = $conf->global->$keyforsmtpid;
943 $this->smtps->setID($loginid);
944 }
945 if (!empty($conf->global->$keyforsmtppw)) {
946 $loginpass = $conf->global->$keyforsmtppw;
947 $this->smtps->setPW($loginpass);
948 }
949
950 if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
951 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
952
953 $supportedoauth2array = getSupportedOauth2Array();
954
955 $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
956 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
957 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
958 } else {
959 $keyforprovider = '';
960 }
961 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
962 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
963
964 if (!empty($supportedoauth2array)) {
965 $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
966 } else {
967 $OAUTH_SERVICENAME = 'Unknown';
968 }
969
970 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
971
972 $storage = new DoliStorage($db, $conf, $keyforprovider);
973 try {
974 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
975 $expire = false;
976 // Is token expired or will token expire in the next 30 seconds
977 if (is_object($tokenobj)) {
978 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
979 }
980 // Token expired so we refresh it
981 if (is_object($tokenobj) && $expire) {
982 $credentials = new Credentials(
983 getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_ID'),
984 getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_SECRET'),
985 getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_URLAUTHORIZE')
986 );
987 $serviceFactory = new \OAuth\ServiceFactory();
988 $oauthname = explode('-', $OAUTH_SERVICENAME);
989 // ex service is Google-Emails we need only the first part Google
990 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
991 // We have to save the token because Google give it only once
992 $refreshtoken = $tokenobj->getRefreshToken();
993 $tokenobj = $apiService->refreshAccessToken($tokenobj);
994 $tokenobj->setRefreshToken($refreshtoken);
995 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
996 }
997
998 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
999 if (is_object($tokenobj)) {
1000 $this->smtps->setToken($tokenobj->getAccessToken());
1001 } else {
1002 $this->error = "Token not found";
1003 }
1004 } catch (Exception $e) {
1005 // Return an error if token not found
1006 $this->error = $e->getMessage();
1007 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1008 }
1009 }
1010
1011 $res = true;
1012 $from = $this->smtps->getFrom('org');
1013 if ($res && !$from) {
1014 $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Sender address '$from' invalid";
1015 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1016 $res = false;
1017 }
1018 $dest = $this->smtps->getTo();
1019 if ($res && !$dest) {
1020 $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Recipient address '$dest' invalid";
1021 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1022 $res = false;
1023 }
1024
1025 if ($res) {
1026 dol_syslog("CMailFile::sendfile: sendMsg, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_DEBUG);
1027
1028 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1029 $this->smtps->setDebug(true);
1030 }
1031
1032 $result = $this->smtps->sendMsg();
1033
1034 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1035 $this->dump_mail();
1036 }
1037
1038 $smtperrorcode = 0;
1039 if (! $result) {
1040 $smtperrorcode = $this->smtps->lastretval; // SMTP error code
1041 dol_syslog("CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1042
1043 if ($smtperrorcode == '421') { // Try later
1044 // TODO Add a delay and try again
1045 /*
1046 dol_syslog("CMailFile::sendfile: Try later error, so we wait and we retry");
1047 sleep(2);
1048
1049 $result = $this->smtps->sendMsg();
1050
1051 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1052 $this->dump_mail();
1053 }
1054 */
1055 }
1056 }
1057
1058 $result = $this->smtps->getErrors(); // applicative error code (not SMTP error code)
1059 if (empty($this->error) && empty($result)) {
1060 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1061 $res = true;
1062 } else {
1063 if (empty($this->error)) {
1064 $this->error = $result;
1065 }
1066 dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - ".$this->error, LOG_ERR);
1067 $res = false;
1068
1069 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1070 $this->save_dump_mail_in_err('Mail smtp error '.$smtperrorcode.' with topic '.$this->subject);
1071 }
1072 }
1073 }
1074 } elseif ($this->sendmode == 'swiftmailer') {
1075 // Use Swift Mailer library
1076 // ------------------------------------------
1077 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
1078
1079 // Clean parameters
1080 if (empty($conf->global->$keyforsmtpserver)) {
1081 $conf->global->$keyforsmtpserver = ini_get('SMTP');
1082 }
1083 if (empty($conf->global->$keyforsmtpport)) {
1084 $conf->global->$keyforsmtpport = ini_get('smtp_port');
1085 }
1086
1087 // If we use SSL/TLS
1088 $server = getDolGlobalString($keyforsmtpserver);
1089 $secure = '';
1090 if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
1091 $secure = 'ssl';
1092 }
1093 if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
1094 $secure = 'tls';
1095 }
1096
1097 $this->transport = new Swift_SmtpTransport($server, getDolGlobalString($keyforsmtpport), $secure);
1098
1099 if (!empty($conf->global->$keyforsmtpid)) {
1100 $this->transport->setUsername($conf->global->$keyforsmtpid);
1101 }
1102 if (!empty($conf->global->$keyforsmtppw) && getDolGlobalString($keyforsmtpauthtype) != "XOAUTH2") {
1103 $this->transport->setPassword($conf->global->$keyforsmtppw);
1104 }
1105 if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
1106 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php';
1107
1108 $supportedoauth2array = getSupportedOauth2Array();
1109
1110 $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
1111 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
1112 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
1113 } else {
1114 $keyforprovider = '';
1115 }
1116 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
1117 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
1118
1119 $OAUTH_SERVICENAME = 'Unknown';
1120 if (array_key_exists($keyforsupportedoauth2array, $supportedoauth2array)
1121 && array_key_exists('name', $supportedoauth2array[$keyforsupportedoauth2array])
1122 && !empty($supportedoauth2array[$keyforsupportedoauth2array]['name'])) {
1123 $OAUTH_SERVICENAME = $supportedoauth2array[$keyforsupportedoauth2array]['name'].(!empty($keyforprovider) ? '-'.$keyforprovider : '');
1124 }
1125
1126 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
1127
1128 $storage = new DoliStorage($db, $conf, $keyforprovider);
1129
1130 try {
1131 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1132 $expire = false;
1133 // Is token expired or will token expire in the next 30 seconds
1134 if (is_object($tokenobj)) {
1135 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1136 }
1137 // Token expired so we refresh it
1138 if (is_object($tokenobj) && $expire) {
1139 $credentials = new Credentials(
1140 getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_ID'),
1141 getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_SECRET'),
1142 getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_URLAUTHORIZE')
1143 );
1144 $serviceFactory = new \OAuth\ServiceFactory();
1145 $oauthname = explode('-', $OAUTH_SERVICENAME);
1146 // ex service is Google-Emails we need only the first part Google
1147 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1148 // We have to save the token because Google give it only once
1149 $refreshtoken = $tokenobj->getRefreshToken();
1150 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1151 $tokenobj->setRefreshToken($refreshtoken);
1152 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1153 }
1154 if (is_object($tokenobj)) {
1155 $this->transport->setAuthMode('XOAUTH2');
1156 $this->transport->setPassword($tokenobj->getAccessToken());
1157 } else {
1158 $this->errors[] = "Token not found";
1159 }
1160 } catch (Exception $e) {
1161 // Return an error if token not found
1162 $this->errors[] = $e->getMessage();
1163 dol_syslog("CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1164 }
1165 }
1166 if (getDolGlobalString($keyforsslseflsigned)) {
1167 $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false)));
1168 }
1169 //$smtps->_msgReplyTo = 'reply@web.com';
1170
1171 // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable
1172 $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1173 $this->message->setEncoder($contentEncoderBase64);
1174
1175 // Create the Mailer using your created Transport
1176 $this->mailer = new Swift_Mailer($this->transport);
1177
1178 // DKIM SIGN
1179 if (getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_ENABLED')) {
1180 $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
1181 $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
1182 $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
1183 $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1184 $this->message->attachSigner($signer->ignoreHeader('Return-Path'));
1185 }
1186
1187 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1188 // To use the ArrayLogger
1189 $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
1190 // Or to use the Echo Logger
1191 //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
1192 $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
1193 }
1194
1195 dol_syslog("CMailFile::sendfile: mailer->send, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_DEBUG);
1196
1197 // send mail
1198 $failedRecipients = array();
1199 try {
1200 $result = $this->mailer->send($this->message, $failedRecipients);
1201 } catch (Exception $e) {
1202 $this->errors[] = $e->getMessage();
1203 }
1204 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1205 $this->dump_mail();
1206 }
1207
1208 $res = true;
1209 if (!empty($this->error) || !empty($this->errors) || !$result) {
1210 if (!empty($failedRecipients)) {
1211 $this->error = 'Transport failed for the following addresses: "' . join('", "', $failedRecipients) . '".';
1212 $this->errors[] = $this->error;
1213 }
1214 dol_syslog("CMailFile::sendfile: mail end error=". join(' ', $this->errors), LOG_ERR);
1215 $res = false;
1216
1217 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1218 $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
1219 }
1220 } else {
1221 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1222 }
1223 } else {
1224 // Send mail method not correctly defined
1225 // --------------------------------------
1226
1227 return 'Bad value for sendmode';
1228 }
1229
1230 // Now we delete image files that were created dynamically to manage data inline files
1231 foreach ($this->html_images as $val) {
1232 if (!empty($val['type']) && $val['type'] == 'cidfromdata') {
1233 //dol_delete($val['fullpath']);
1234 }
1235 }
1236
1237 $parameters = array('sent' => $res);
1238 $action = '';
1239 $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1240 if ($reshook < 0) {
1241 $this->error = "Error in hook maildao sendMailAfter ".$reshook;
1242 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1243
1244 return $reshook;
1245 }
1246 } else {
1247 $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1248 dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
1249 }
1250
1251 error_reporting($errorlevel); // Reactive niveau erreur origine
1252 return $res;
1253 }
1254
1261 public static function encodetorfc2822($stringtoencode)
1262 {
1263 global $conf;
1264 return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
1265 }
1266
1267 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1274 private function _encode_file($sourcefile)
1275 {
1276 // phpcs:enable
1277 $newsourcefile = dol_osencode($sourcefile);
1278
1279 if (is_readable($newsourcefile)) {
1280 $contents = file_get_contents($newsourcefile); // Need PHP 4.3
1281 $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
1282 return $encoded;
1283 } else {
1284 $this->error = "Error in _encode_file() method: Can't read file '".$sourcefile."'";
1285 dol_syslog("CMailFile::_encode_file: ".$this->error, LOG_ERR);
1286 return -1;
1287 }
1288 }
1289
1290
1291 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1299 public function dump_mail()
1300 {
1301 // phpcs:enable
1302 global $conf, $dolibarr_main_data_root;
1303
1304 if (@is_writeable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
1305 $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1306 $fp = fopen($outputfile, "w"); // overwrite
1307
1308 if ($this->sendmode == 'mail') {
1309 fputs($fp, $this->headers);
1310 fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log
1311 fputs($fp, $this->message);
1312 } elseif ($this->sendmode == 'smtps') {
1313 fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
1314 } elseif ($this->sendmode == 'swiftmailer') {
1315 fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
1316 }
1317
1318 fclose($fp);
1319 dolChmod($outputfile);
1320
1321 // Move dolibarr_mail.log into a dolibarr_mail.YYYYMMDD.log
1322 if (getDolGlobalString('MAIN_MAIL_DEBUG_LOG_WITH_DATE')) {
1323 $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".log";
1324
1325 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1326 dol_move($outputfile, $destfile, 0, 1, 0, 0);
1327 }
1328 }
1329 }
1330
1331 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1339 public function save_dump_mail_in_err($message = '')
1340 {
1341 global $dolibarr_main_data_root;
1342
1343 if (@is_writeable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
1344 $srcfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1345
1346 // Add message to dolibarr_mail.log. We do not use dol_syslog() on purpose,
1347 // to be sure to write into dolibarr_mail.log
1348 if ($message) {
1349 // Test constant SYSLOG_FILE_NO_ERROR (should stay a constant defined with define('SYSLOG_FILE_NO_ERROR',1);
1350 if (defined('SYSLOG_FILE_NO_ERROR')) {
1351 $filefd = @fopen($srcfile, 'a+');
1352 } else {
1353 $filefd = fopen($srcfile, 'a+');
1354 }
1355 if ($filefd) {
1356 fwrite($filefd, $message."\n");
1357 fclose($filefd);
1358 dolChmod($srcfile);
1359 }
1360 }
1361
1362 // Move dolibarr_mail.log into a dolibarr_mail.err or dolibarr_mail.date.err
1363 if (getDolGlobalString('MAIN_MAIL_DEBUG_ERR_WITH_DATE')) {
1364 $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".err";
1365 } else {
1366 $destfile = $dolibarr_main_data_root."/dolibarr_mail.err";
1367 }
1368
1369 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1370 dol_move($srcfile, $destfile, 0, 1, 0, 0);
1371 }
1372 }
1373
1374
1381 public function checkIfHTML($msg)
1382 {
1383 if (!preg_match('/^[\s\t]*<html/i', $msg)) {
1384 $out = "<html><head><title></title>";
1385 if (!empty($this->styleCSS)) {
1386 $out .= $this->styleCSS;
1387 }
1388 $out .= "</head><body";
1389 if (!empty($this->bodyCSS)) {
1390 $out .= $this->bodyCSS;
1391 }
1392 $out .= ">";
1393 $out .= $msg;
1394 $out .= "</body></html>";
1395 } else {
1396 $out = $msg;
1397 }
1398
1399 return $out;
1400 }
1401
1407 public function buildCSS()
1408 {
1409 if (!empty($this->css)) {
1410 // Style CSS
1411 $this->styleCSS = '<style type="text/css">';
1412 $this->styleCSS .= 'body {';
1413
1414 if ($this->css['bgcolor']) {
1415 $this->styleCSS .= ' background-color: '.$this->css['bgcolor'].';';
1416 $this->bodyCSS .= ' bgcolor="'.$this->css['bgcolor'].'"';
1417 }
1418 if ($this->css['bgimage']) {
1419 // TODO recuperer cid
1420 $this->styleCSS .= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
1421 }
1422 $this->styleCSS .= '}';
1423 $this->styleCSS .= '</style>';
1424 }
1425 }
1426
1427
1428 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1434 public function write_smtpheaders()
1435 {
1436 // phpcs:enable
1437 global $conf;
1438 $out = "";
1439
1440 $host = dol_getprefix('email');
1441
1442 // Sender
1443 //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
1444 $out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
1445 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_BA')) {
1446 $out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
1447 }
1448 // Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
1449 $out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
1450 if (isset($this->reply_to) && $this->reply_to) {
1451 $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
1452 }
1453 if (isset($this->errors_to) && $this->errors_to) {
1454 $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1455 }
1456
1457 // Receiver
1458 if (isset($this->addr_cc) && $this->addr_cc) {
1459 $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1460 }
1461 if (isset($this->addr_bcc) && $this->addr_bcc) {
1462 $out .= "Bcc: ".$this->getValidAddress($this->addr_bcc, 2).$this->eol2; // TODO Question: bcc must not be into header, only into SMTP command "RCPT TO". Does php mail support this ?
1463 }
1464
1465 // Delivery receipt
1466 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1467 $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1468 }
1469
1470 //$out.= "X-Priority: 3".$this->eol2;
1471
1472 $out .= 'Date: '.date("r").$this->eol2;
1473
1474 $trackid = $this->trackid;
1475 if ($trackid) {
1476 // References is kept in response and Message-ID is returned into In-Reply-To:
1477 $this->msgid = time().'.phpmail-dolibarr-'.$trackid.'@'.$host;
1478 $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail
1479 //$out .= 'References: <'.$this->msgid.">".$this->eol2;
1480 $out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2;
1481 } else {
1482 $this->msgid = time().'.phpmail@'.$host;
1483 $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2;
1484 }
1485
1486 if (!empty($_SERVER['REMOTE_ADDR'])) {
1487 $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2;
1488 }
1489 $out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2;
1490 $out .= "Mime-Version: 1.0".$this->eol2;
1491
1492 //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1493
1494 $out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1495 $out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received.
1496
1497 dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
1498 return $out;
1499 }
1500
1501
1502 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1510 public function write_mimeheaders($filename_list, $mimefilename_list)
1511 {
1512 // phpcs:enable
1513 $mimedone = 0;
1514 $out = "";
1515
1516 if (is_array($filename_list)) {
1517 $filename_list_size = count($filename_list);
1518 for ($i = 0; $i < $filename_list_size; $i++) {
1519 if ($filename_list[$i]) {
1520 if ($mimefilename_list[$i]) {
1521 $filename_list[$i] = $mimefilename_list[$i];
1522 }
1523 $out .= "X-attachments: $filename_list[$i]".$this->eol2;
1524 }
1525 }
1526 }
1527
1528 dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1529 return $out;
1530 }
1531
1532 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1539 public function write_body($msgtext)
1540 {
1541 // phpcs:enable
1542 global $conf;
1543
1544 $out = '';
1545
1546 $out .= "--".$this->mixed_boundary.$this->eol;
1547
1548 if ($this->atleastoneimage) {
1549 $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1550 $out .= $this->eol;
1551 $out .= "--".$this->alternative_boundary.$this->eol;
1552 }
1553
1554 // Make RFC821 Compliant, replace bare linefeeds
1555 $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext); // PCRE modifier /s means new lines are common chars
1556 if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) {
1557 $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars
1558 }
1559
1560 $strContentAltText = '';
1561 if ($this->msgishtml) {
1562 // Similar code to forge a text from html is also in smtps.class.php
1563 $strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
1564 // TODO We could replace <img ...> with [Filename.ext] like Gmail do.
1565 $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); // Remove any HTML tags
1566 $strContentAltText = trim(wordwrap($strContentAltText, 75, !getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA') ? "\r\n" : "\n"));
1567
1568 // Check if html header already in message, if not complete the message
1569 $strContent = $this->checkIfHTML($strContent); // This add a header and a body including custom CSS to the HTML content
1570 }
1571
1572 // Make RFC2045 Compliant, split lines
1573 //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
1574 // TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1575 $strContent = rtrim(wordwrap($strContent, 75, !getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA') ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content.
1576
1577 if ($this->msgishtml) {
1578 if ($this->atleastoneimage) {
1579 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1580 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1581 $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message
1582 $out .= "--".$this->alternative_boundary.$this->eol;
1583 $out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1584 $out .= $this->eol;
1585 $out .= "--".$this->related_boundary.$this->eol;
1586 }
1587
1588 if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part before html part
1589 $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1590 $out .= $this->eol;
1591 $out .= "--".$this->alternative_boundary.$this->eol;
1592 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1593 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1594 $out .= $this->eol.$strContentAltText.$this->eol;
1595 $out .= "--".$this->alternative_boundary.$this->eol;
1596 }
1597
1598 $out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1599 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64
1600 $out .= $this->eol.$strContent.$this->eol;
1601
1602 if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part after html part
1603 $out .= "--".$this->alternative_boundary."--".$this->eol;
1604 }
1605 } else {
1606 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1607 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1608 $out .= $this->eol.$strContent.$this->eol;
1609 }
1610
1611 $out .= $this->eol;
1612
1613 // Encode images
1614 if ($this->atleastoneimage) {
1615 $out .= $this->write_images($this->images_encoded);
1616 // always end related and end alternative after inline images
1617 $out .= "--".$this->related_boundary."--".$this->eol;
1618 $out .= $this->eol."--".$this->alternative_boundary."--".$this->eol;
1619 $out .= $this->eol;
1620 }
1621
1622 return $out;
1623 }
1624
1625 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1635 private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
1636 {
1637 // phpcs:enable
1638 $out = '';
1639
1640 $filename_list_size = count($filename_list);
1641 for ($i = 0; $i < $filename_list_size; $i++) {
1642 if ($filename_list[$i]) {
1643 dol_syslog("CMailFile::write_files: i=$i ".$filename_list[$i]);
1644 $encoded = $this->_encode_file($filename_list[$i]);
1645 if ($encoded !== -1) {
1646 if ($mimefilename_list[$i]) {
1647 $filename_list[$i] = $mimefilename_list[$i];
1648 }
1649 if (!$mimetype_list[$i]) {
1650 $mimetype_list[$i] = "application/octet-stream";
1651 }
1652
1653 $out .= "--".$this->mixed_boundary.$this->eol;
1654 $out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1655 $out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol;
1656 $out .= "Content-Transfer-Encoding: base64".$this->eol;
1657 $out .= "Content-Description: ".$filename_list[$i].$this->eol;
1658 if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) {
1659 $out .= "X-Attachment-Id: ".$cidlist[$i].$this->eol;
1660 $out .= "Content-ID: <".$cidlist[$i].'>'.$this->eol;
1661 }
1662 $out .= $this->eol;
1663 $out .= $encoded;
1664 $out .= $this->eol;
1665 //$out.= $this->eol;
1666 } else {
1667 return $encoded;
1668 }
1669 }
1670 }
1671
1672 return $out;
1673 }
1674
1675
1676 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1683 public function write_images($images_list)
1684 {
1685 // phpcs:enable
1686 $out = '';
1687
1688 if (is_array($images_list)) {
1689 foreach ($images_list as $img) {
1690 dol_syslog("CMailFile::write_images: ".$img["name"]);
1691
1692 $out .= "--".$this->related_boundary.$this->eol; // always related for an inline image
1693 $out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol;
1694 $out .= "Content-Transfer-Encoding: base64".$this->eol;
1695 $out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1696 $out .= "Content-ID: <".$img["cid"].">".$this->eol;
1697 $out .= $this->eol;
1698 $out .= $img["image_encoded"];
1699 $out .= $this->eol;
1700 }
1701 }
1702
1703 return $out;
1704 }
1705
1706
1707 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1715 public function check_server_port($host, $port)
1716 {
1717 // phpcs:enable
1718 global $conf;
1719
1720 $_retVal = 0;
1721 $timeout = 5; // Timeout in seconds
1722
1723 if (function_exists('fsockopen')) {
1724 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
1725 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
1726 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
1727 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
1728 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
1729 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
1730 $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
1731 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
1732 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
1733
1734 if (!empty($this->sendcontext)) {
1735 $smtpContextKey = strtoupper($this->sendcontext);
1736 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
1737 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
1738 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
1739 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
1740 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
1741 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
1742 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
1743 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
1744 $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
1745 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
1746 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
1747 }
1748 }
1749
1750 // If we use SSL/TLS
1751 if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
1752 $host = 'ssl://'.$host;
1753 }
1754 // tls smtp start with no encryption
1755 //if (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1756
1757 dol_syslog("Try socket connection to host=".$host." port=".$port." timeout=".$timeout);
1758 //See if we can connect to the SMTP server
1759 $errno = 0;
1760 $errstr = '';
1761 if ($socket = @fsockopen(
1762 $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1763 $port, // which Port number to use
1764 $errno, // actual system level error
1765 $errstr, // and any text that goes with the error
1766 $timeout // timeout for reading/writing data over the socket
1767 )) {
1768 // Windows still does not have support for this timeout function
1769 if (function_exists('stream_set_timeout')) {
1770 stream_set_timeout($socket, $timeout, 0);
1771 }
1772
1773 dol_syslog("Now we wait for answer 220");
1774
1775 // Check response from Server
1776 if ($_retVal = $this->server_parse($socket, "220")) {
1777 $_retVal = $socket;
1778 }
1779 } else {
1780 $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : mb_convert_encoding('Error '.$errno.' - '.$errstr, 'UTF-8', 'ISO-8859-1');
1781 }
1782 }
1783 return $_retVal;
1784 }
1785
1786 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1795 public function server_parse($socket, $response)
1796 {
1797 // phpcs:enable
1798 $_retVal = true; // Indicates if Object was created or not
1799 $server_response = '';
1800
1801 while (substr($server_response, 3, 1) != ' ') {
1802 if (!($server_response = fgets($socket, 256))) {
1803 $this->error = "Couldn't get mail server response codes";
1804 return false;
1805 }
1806 }
1807
1808 if (!(substr($server_response, 0, 3) == $response)) {
1809 $this->error = "Ran into problems sending Mail.\r\nResponse: $server_response";
1810 $_retVal = false;
1811 }
1812
1813 return $_retVal;
1814 }
1815
1822 private function findHtmlImages($images_dir)
1823 {
1824 // Build the array of image extensions
1825 $extensions = array_keys($this->image_types);
1826
1827 // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
1828 // For example when:
1829 // <img alt="" src="/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/picture.jpg" style="height:356px; width:1040px" />
1830 $matches = array();
1831 preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
1832
1833 if (!empty($matches) && !empty($matches[1])) {
1834 $i = 0;
1835 // We are interested in $matches[1] only (the second set of parenthesis into regex)
1836 foreach ($matches[1] as $full) {
1837 $regs = array();
1838 if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) { // If xxx is 'file=aaa'
1839 $img = $regs[1];
1840
1841 if (file_exists($images_dir.'/'.$img)) {
1842 // Image path in src
1843 $src = preg_quote($full, '/');
1844 // Image full path
1845 $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
1846 // Image name
1847 $this->html_images[$i]["name"] = $img;
1848 // Content type
1849 $regext = array();
1850 if (preg_match('/^.+\.(\w{3,4})$/', $img, $regext)) {
1851 $ext = strtolower($regext[1]);
1852 $this->html_images[$i]["content_type"] = $this->image_types[$ext];
1853 }
1854 // cid
1855 $this->html_images[$i]["cid"] = dol_hash($this->html_images[$i]["fullpath"], 'md5'); // Force md5 hash (does not contain special chars)
1856 // type
1857 $this->html_images[$i]["type"] = 'cidfromurl';
1858
1859 $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
1860 }
1861 $i++;
1862 }
1863 }
1864
1865 if (!empty($this->html_images)) {
1866 $inline = array();
1867
1868 $i = 0;
1869
1870 foreach ($this->html_images as $img) {
1871 $fullpath = $images_dir.'/'.$img["name"];
1872
1873 // If duplicate images are embedded, they may show up as attachments, so remove them.
1874 if (!in_array($fullpath, $inline)) {
1875 // Read image file
1876 if ($image = file_get_contents($fullpath)) {
1877 // On garde que le nom de l'image
1878 $regs = array();
1879 preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs);
1880 $imgName = $regs[1];
1881
1882 $this->images_encoded[$i]['name'] = $imgName;
1883 $this->images_encoded[$i]['fullpath'] = $fullpath;
1884 $this->images_encoded[$i]['content_type'] = $img["content_type"];
1885 $this->images_encoded[$i]['cid'] = $img["cid"];
1886 // Encodage de l'image
1887 $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
1888 $inline[] = $fullpath;
1889 }
1890 }
1891 $i++;
1892 }
1893 } else {
1894 return -1;
1895 }
1896
1897 return 1;
1898 } else {
1899 return 0;
1900 }
1901 }
1902
1910 private function findHtmlImagesIsSrcData($images_dir)
1911 {
1912 global $conf;
1913
1914 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1915
1916 // Build the array of image extensions
1917 $extensions = array_keys($this->image_types);
1918
1919 if (empty($images_dir)) {
1920 //$images_dir = $conf->admin->dir_output.'/temp/'.uniqid('cmailfile');
1921 $images_dir = $conf->admin->dir_output.'/temp/cmailfile';
1922 }
1923
1924 if ($images_dir && !dol_is_dir($images_dir)) {
1925 dol_mkdir($images_dir, DOL_DATA_ROOT);
1926 }
1927
1928 // Uncomment this for debug
1929 /*
1930 global $dolibarr_main_data_root;
1931 $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1932 $fp = fopen($outputfile, "w+");
1933 fwrite($fp, $this->html);
1934 fclose($fp);
1935 */
1936
1937 // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
1938 // For example when:
1939 // <img alt="" src="/src="data:image....;base64,...." />
1940 $matches = array();
1941 preg_match_all('/src="data:image\/('.implode('|', $extensions).');base64,([^"]+)"/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
1942
1943 if (!empty($matches) && !empty($matches[1])) {
1944 if (empty($images_dir)) {
1945 // No temp directory provided, so we are not able to support convertion of data:image into physical images.
1946 $this->errors[] = 'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
1947 return -1;
1948 }
1949
1950 $i = count($this->html_images);
1951 foreach ($matches[1] as $key => $ext) {
1952 // We save the image to send in disk
1953 $filecontent = $matches[2][$key];
1954
1955 $cid = 'cid000'.dol_hash($filecontent, 'md5'); // The id must not change if image is same
1956
1957 $destfiletmp = $images_dir.'/'.$cid.'.'.$ext;
1958
1959 if (!dol_is_file($destfiletmp)) { // If file does not exist yet (this is the case for the first email sent with a data:image inside)
1960 dol_syslog("write the cid file ".$destfiletmp);
1961 $fhandle = @fopen($destfiletmp, 'w');
1962 if ($fhandle) {
1963 $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
1964 fclose($fhandle);
1965 dolChmod($destfiletmp);
1966 } else {
1967 $this->errors[] = "Failed to open file '".$destfiletmp."' for write";
1968 return -2;
1969 }
1970 }
1971
1972 if (file_exists($destfiletmp)) {
1973 // Image full path
1974 $this->html_images[$i]["fullpath"] = $destfiletmp;
1975 // Image name
1976 $this->html_images[$i]["name"] = basename($destfiletmp);
1977 // Content type
1978 $this->html_images[$i]["content_type"] = $this->image_types[strtolower($ext)];
1979 // cid
1980 $this->html_images[$i]["cid"] = $cid;
1981 // type
1982 $this->html_images[$i]["type"] = 'cidfromdata';
1983
1984 $this->html = str_replace('src="data:image/'.$ext.';base64,'.$filecontent.'"', 'src="cid:'.$this->html_images[$i]["cid"].'"', $this->html);
1985 }
1986 $i++;
1987 }
1988
1989 return 1;
1990 } else {
1991 return 0;
1992 }
1993 }
1994
2010 public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
2011 {
2012 global $conf;
2013
2014 $ret = '';
2015
2016 $arrayaddress = explode(',', $address);
2017
2018 // Boucle sur chaque composant de l'adresse
2019 $i = 0;
2020 foreach ($arrayaddress as $val) {
2021 $regs = array();
2022 if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
2023 $name = trim($regs[1]);
2024 $email = trim($regs[2]);
2025 } else {
2026 $name = '';
2027 $email = trim($val);
2028 }
2029
2030 if ($email) {
2031 $i++;
2032
2033 $newemail = '';
2034 if ($format == 5) {
2035 $newemail = $name ? $name : $email;
2036 $newemail = '<a href="mailto:'.$email.'">'.$newemail.'</a>';
2037 }
2038 if ($format == 4) {
2039 $newemail = $name ? $name : $email;
2040 }
2041 if ($format == 2) {
2042 $newemail = $email;
2043 }
2044 if ($format == 1 || $format == 3) {
2045 $newemail = '<'.$email.'>';
2046 }
2047 if ($format == 0 || $format == 3) {
2048 if (getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL')) {
2049 $newemail = '<'.$email.'>';
2050 } elseif (!$name) {
2051 $newemail = '<'.$email.'>';
2052 } else {
2053 $newemail = ($format == 3 ? '"' : '').($encode ? self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>';
2054 }
2055 }
2056
2057 $ret = ($ret ? $ret.',' : '').$newemail;
2058
2059 // Stop if we have too much records
2060 if ($maxnumberofemail && $i >= $maxnumberofemail) {
2061 if (count($arrayaddress) > $maxnumberofemail) {
2062 $ret .= '...';
2063 }
2064 break;
2065 }
2066 }
2067 }
2068
2069 return $ret;
2070 }
2071
2079 public static function getArrayAddress($address)
2080 {
2081 global $conf;
2082
2083 $ret = array();
2084
2085 $arrayaddress = explode(',', $address);
2086
2087 // Boucle sur chaque composant de l'adresse
2088 foreach ($arrayaddress as $val) {
2089 if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
2090 $name = trim($regs[1]);
2091 $email = trim($regs[2]);
2092 } else {
2093 $name = null;
2094 $email = trim($val);
2095 }
2096
2097 $ret[$email] = !getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL') ? $name : null;
2098 }
2099
2100 return $ret;
2101 }
2102}
Class to send emails (with attachments or not) Usage: $mailfile = new CMailFile($subject,...
_encode_file($sourcefile)
Read a file on disk and return encoded content for emails (mode = 'mail')
write_body($msgtext)
Return email content (mode = 'mail')
$bodyCSS
Defined background directly in body tag.
dump_mail()
Write content of a SMTP request into a dump file (mode = all) Used for debugging.
sendfile()
Send mail that was prepared by constructor.
save_dump_mail_in_err($message='')
Save content if mail is in error Used for debugging.
static encodetorfc2822($stringtoencode)
Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word.
checkIfHTML($msg)
Correct an uncomplete html string.
static getValidAddress($address, $format, $encode=0, $maxnumberofemail=0)
Return a formatted address string for SMTP protocol.
write_images($images_list)
Attach an image to email (mode = 'mail')
server_parse($socket, $response)
This function has been modified as provided by SirSir to allow multiline responses when using SMTP Ex...
__construct($subject, $to, $from, $msg, $filename_list=array(), $mimetype_list=array(), $mimefilename_list=array(), $addr_cc="", $addr_bcc="", $deliveryreceipt=0, $msgishtml=0, $errors_to='', $css='', $trackid='', $moreinheader='', $sendcontext='standard', $replyto='', $upload_dir_tmp='')
CMailFile.
write_smtpheaders()
Create SMTP headers (mode = 'mail')
findHtmlImagesIsSrcData($images_dir)
Seearch images with data:image format into html message.
$styleCSS
Defined css style for body background.
write_mimeheaders($filename_list, $mimefilename_list)
Create header MIME (mode = 'mail')
check_server_port($host, $port)
Try to create a socket connection.
buildCSS()
Build a css style (mode = all) into this->styleCSS and this->bodyCSS.
write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
Attach file to email (mode = 'mail')
static getArrayAddress($address)
Return a formatted array of address string for SMTP protocol.
findHtmlImages($images_dir)
Search images into html message and init array this->images_encoded if found.
Class to manage hooks.
Class to construct and send SMTP compliant email, even to a secure SMTP server, regardless of platfor...
dol_move($srcfile, $destfile, $newmask=0, $overwriteifexists=1, $testvirus=0, $indexdatabase=1, $moreinfo=array())
Move a file into another name.
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_osencode($str)
Return a string encoded into OS filesystem encoding.
dol_nl2br($stringtoencode, $nl2brmode=0, $forxml=false)
Replace CRLF in string with a HTML BR tag.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs='', $encodetooutput=false)
Output date in a string format according to outputlangs (or langs if not defined).
dolChmod($filepath, $newmask='')
Change mod of a file.
dol_now($mode='auto')
Return date for now.
getDolGlobalInt($key, $default=0)
Return a Dolibarr global constant int value.
dol_string_unaccent($str)
Clean a string from all accent characters to be used as ref, login or by dol_sanitizeFileName.
ascii_check($str)
Check if a string is in ASCII.
dol_textishtml($msg, $option=0)
Return if a text is a html content.
getDolGlobalString($key, $default='')
Return dolibarr global constant string value.
utf8_check($str)
Check if a string is in UTF8.
dol_syslog($message, $level=LOG_INFO, $ident=0, $suffixinfilename='', $restricttologhandler='', $logcontext=null)
Write log message into outputs.
dol_mkdir($dir, $dataroot='', $newmask='')
Creation of a directory (this can create recursive subdir)
dol_sanitizeEmail($stringtoclean)
Clean a string to use it as an Email.
getSupportedOauth2Array()
Return array of tabs to used on pages to setup cron module.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.