dolibarr 25.0.0-alpha
CMailFile.class.php
Go to the documentation of this file.
1<?php
35use OAuth\Common\Storage\DoliStorage;
36use OAuth\Common\Consumer\Credentials;
37
44{
46 public $sendcontext;
48 public $sendmode;
53 public $sendsetup;
54
58 public $subject;
65 public $addr_from;
66
67 // Return-Path: Email where to send bounds.
68
70 public $reply_to;
72 public $errors_to;
74 public $addr_to;
76 public $addr_cc;
78 public $addr_bcc;
80 public $trackid;
81
83 public $mixed_boundary;
85 public $related_boundary;
87 public $alternative_boundary;
89 public $deliveryreceipt;
90
92 public $atleastonefile;
93
95 public $msg;
97 public $eol;
99 public $eol2;
100
104 public $error = '';
105
109 public $errors = array();
110
114 public $smtps;
118 public $mailer;
119
123 public $transport;
127 public $logger;
128
132 public $css;
134 public $styleCSS;
136 public $bodyCSS;
137
141 public $msgid;
142
146 public $in_reply_to;
147
151 public $references;
152
156 public $headers;
157
161 public $message;
162
166 public $filename_list = array();
170 public $mimetype_list = array();
174 public $mimefilename_list = array();
178 public $cid_list = array();
179
181 public $html;
183 public $msgishtml;
185 public $image_boundary;
187 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).
189 public $html_images = array();
191 public $images_encoded = array();
193 public $image_types = array(
194 'gif' => 'image/gif',
195 'jpg' => 'image/jpeg',
196 'jpeg' => 'image/jpeg',
197 'jpe' => 'image/jpeg',
198 'bmp' => 'image/bmp',
199 'png' => 'image/png',
200 'tif' => 'image/tiff',
201 'tiff' => 'image/tiff',
202 'webp' => 'image/webp',
203 );
204
229 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 = '', $in_reply_to = '', $references = '')
230 {
231 global $conf, $dolibarr_main_data_root, $user;
232
233 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");
234 dol_syslog("CMailFile::CMailFile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
235
236 // Clean values of $mimefilename_list
237 if (is_array($mimefilename_list)) {
238 foreach ($mimefilename_list as $key => $val) {
239 $mimefilename_list[$key] = dol_string_unaccent($mimefilename_list[$key]);
240 }
241 }
242
243 $cid_list = array();
244
245 $this->sendcontext = $sendcontext;
246
247 // Define this->sendmode ('mail', 'smtps', 'swiftmailer', ...) according to $sendcontext ('standard', 'emailing', 'ticket', 'passwordreset')
248 $this->sendmode = '';
249 if (!empty($this->sendcontext)) {
250 $smtpContextKey = strtoupper($this->sendcontext);
251 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
252 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
253 $this->sendmode = $smtpContextSendMode;
254 }
255 }
256 if (empty($this->sendmode)) {
257 $this->sendmode = getDolGlobalString('MAIN_MAIL_SENDMODE', 'mail');
258 }
259
260 // Add a Feedback-ID. Must be used for stats on spam report only.
261 if ($trackid) {
262 //Examples:
263 // LinkedIn – Feedback-ID: accept_invite_04:linkedin
264 // Twitter – Feedback-ID: 0040162518f58f41d1f0:15491f3b2ee48656f8e7fb2fac:none:twitterESP
265 // Amazon.com : Feedback-ID: 1.eu-west-1.kjoQSiqb8G+7lWWiDVsxjM2m0ynYd4I6yEFlfoox6aY=:AmazonSES
266 $moreinheader .= "Feedback-ID: ".$trackid.':'.dol_getprefix('email').":dolib\r\n";
267 }
268
269 // We define end of line (RFC 821).
270 $this->eol = "\r\n";
271 // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
272 $this->eol2 = "\r\n";
273 if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) {
274 $this->eol = "\n";
275 $this->eol2 = "\n";
276 $moreinheader = str_replace("\r\n", "\n", $moreinheader);
277 }
278
279 // On defini mixed_boundary
280 $this->mixed_boundary = "multipart_x.".time().".x_boundary";
281
282 // On defini related_boundary
283 $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), '3'); // Force md5 hash (does not contain special chars)
284
285 // On defini alternative_boundary
286 $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), '3'); // Force md5 hash (does not contain special chars)
287
288 if (empty($subject)) {
289 dol_syslog("CMailFile::CMailFile: Try to send an email with empty subject");
290 $this->error = 'ErrorSubjectIsRequired';
291 return;
292 }
293 if (empty($msg)) {
294 dol_syslog("CMailFile::CMailFile: Try to send an email with empty body");
295 $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure)
296 }
297
298 // Detect if message is HTML (use fast method)
299 if ($msgishtml == -1) {
300 $this->msgishtml = 0;
301 if (dol_textishtml($msg)) {
302 $this->msgishtml = 1;
303 }
304 } else {
305 $this->msgishtml = $msgishtml;
306 }
307
309
310 // Define $urlwithroot
311 $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
312 $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
313 //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
314
315 // Replace relative /viewimage to absolute path
316 $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1);
317
318 if (getDolGlobalString('MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML')) {
319 $this->msgishtml = 1; // To force to send everything with content type html.
320 }
321 dol_syslog("CMailFile::CMailFile: msgishtml=".$this->msgishtml, LOG_DEBUG);
322
323 // Detect images
324 if ($this->msgishtml) {
325 $this->html = $msg;
326
327 $findimg = 0;
328 if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS')) { // Off by default
329 // Search into the body for <img tags of links in medias files to replace them with an embedded file
330 // Note because media links are public, this should be useless, except avoid blocking images with email browser.
331 // This converts an embed file with src="/viewimage.php?modulepart... into a cid link
332 // TODO Exclude viewimage used for the read tracker ?
333 $dolibarr_main_data_root_images = $dolibarr_main_data_root;
334 if ((int) $conf->entity !== 1) {
335 $dolibarr_main_data_root_images .= '/'.$conf->entity.'/';
336 }
337 $findimg = $this->findHtmlImages($dolibarr_main_data_root_images.'/medias');
338 if ($findimg < 0) {
339 dol_syslog("CMailFile::CMailFile: Error on findHtmlImages");
340 $this->error = 'ErrorInAddAttachmentsImageBaseOnMedia';
341 return;
342 }
343 }
344
345 if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA')) { // On by default because Gmail does not support src="data:image..."
346 // Search into the body for <img src="data:image/ext;base64,..." to replace them with an embedded file
347 // This convert an embedded file with src="data:image... into a cid link + attached file.
348 // It modifies ->html and complete ->html_images
349 $resultImageData = $this->findHtmlImagesIsSrcData($upload_dir_tmp);
350 if ($resultImageData < 0) {
351 dol_syslog("CMailFile::CMailFile: Error on findHtmlImagesInSrcData code=".$resultImageData." upload_dir_tmp=".$upload_dir_tmp);
352 $this->error = 'ErrorInAddAttachmentsImageBaseIsSrcData';
353 return;
354 }
355 $findimg += $resultImageData;
356 }
357
358 // Set atleastoneimage if there is at least one embedded file (into ->html_images)
359 if ($findimg > 0) {
360 foreach ($this->html_images as $i => $val) {
361 if ($this->html_images[$i]) {
362 $this->atleastoneimage = 1;
363 if ($this->html_images[$i]['type'] == 'cidfromdata') {
364 if (!in_array($this->html_images[$i]['fullpath'], $filename_list)) {
365 // If this file path is not already into the $filename_list, we append it at end of array
366 $posindice = count($filename_list);
367 $filename_list[$posindice] = $this->html_images[$i]['fullpath'];
368 $mimetype_list[$posindice] = $this->html_images[$i]['content_type'];
369 $mimefilename_list[$posindice] = $this->html_images[$i]['name'];
370 } else {
371 $posindice = array_search($this->html_images[$i]['fullpath'], $filename_list);
372 }
373 // We complete the array of cid_list
374 $cid_list[$posindice] = $this->html_images[$i]['cid'];
375 }
376 dol_syslog("CMailFile::CMailFile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
377 }
378 }
379 }
380 }
381 //var_dump($filename_list);
382 //var_dump($cid_list);exit;
383
384 // Set atleastoneimage if there is at least one file (into $filename_list array)
385 if (is_array($filename_list)) {
386 foreach ($filename_list as $i => $val) {
387 if ($filename_list[$i]) {
388 $this->atleastonefile = 1;
389 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]=".(empty($cid_list[$i]) ? '' : $cid_list[$i]), LOG_DEBUG);
390 }
391 }
392 }
393
394 // Add auto copy to if not already in $to (Note: Adding bcc for specific modules are also done from pages)
395 // For example MAIN_MAIL_AUTOCOPY_TO can be 'email@example.com, __USER_EMAIL__, ...'
396 if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')) {
397 $listofemailstoadd = explode(',', getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO'));
398 foreach ($listofemailstoadd as $key => $val) {
399 $emailtoadd = $listofemailstoadd[$key];
400 if (trim($emailtoadd) == '__USER_EMAIL__') {
401 if (!empty($user) && !empty($user->email)) {
402 $emailtoadd = $user->email;
403 } else {
404 $emailtoadd = '';
405 }
406 }
407 if ($emailtoadd && preg_match('/'.preg_quote($emailtoadd, '/').'/i', $to)) {
408 $emailtoadd = ''; // Email already in the "To"
409 }
410 if ($emailtoadd) {
411 $listofemailstoadd[$key] = $emailtoadd;
412 } else {
413 unset($listofemailstoadd[$key]);
414 }
415 }
416 if (!empty($listofemailstoadd)) {
417 $addr_bcc .= ($addr_bcc ? ', ' : '').implode(', ', $listofemailstoadd);
418 }
419 }
420
421 // Verify if $to, $addr_cc and addr_bcc have unwanted addresses
422 if (getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO')) {
423 // Parse to, cc and bcc to remove MAIN_MAIL_FORCE_NOT_SENDING_TO
424 $listofemailstonotsendto = explode(',', getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO'));
425
426 //Verify for $to
427 $replaceto = false;
428 $tabto = explode(",", $to);
429 foreach ($tabto as $key => $addrto) {
430 $addrto = array_keys($this->getArrayAddress($addrto));
431 if (in_array($addrto[0], $listofemailstonotsendto)) {
432 unset($tabto[$key]);
433 $replaceto = true;
434 }
435 }
436 if ($replaceto && getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO_REPLACE')) {
437 $tabto[] = getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO_REPLACE');
438 }
439 $to = implode(',', $tabto);
440
441 //Verify for $addr_cc
442 $replacecc = false;
443 $tabcc = explode(',', $addr_cc);
444 foreach ($tabcc as $key => $cc) {
445 $cc = array_keys($this->getArrayAddress($cc));
446 if (in_array($cc[0], $listofemailstonotsendto)) {
447 unset($tabcc[$key]);
448 $replacecc = true;
449 }
450 }
451 if ($replacecc && getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO_REPLACE')) {
452 $tabcc[] = getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO_REPLACE');
453 }
454 $addr_cc = implode(',', $tabcc);
455
456 //Verify for $addr_bcc
457 $replacebcc = false;
458 $tabbcc = explode(',', $addr_bcc);
459 foreach ($tabbcc as $key => $bcc) {
460 $bcc = array_keys($this->getArrayAddress($bcc));
461 if (in_array($bcc[0], $listofemailstonotsendto)) {
462 unset($tabbcc[$key]);
463 $replacebcc = true;
464 }
465 }
466 if ($replacebcc && getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO_REPLACE')) {
467 $tabbcc[] = getDolGlobalString('MAIN_MAIL_FORCE_NOT_SENDING_TO_REPLACE');
468 }
469 $addr_bcc = implode(',', $tabbcc);
470 }
471
472 // We always use a replyto
473 if (empty($replyto)) {
474 $replyto = dol_sanitizeEmail($from);
475 }
476 // We can force the from
477 if (getDolGlobalString('MAIN_MAIL_FORCE_FROM')) {
478 $from = getDolGlobalString('MAIN_MAIL_FORCE_FROM');
479 }
480
481 $this->subject = $subject;
482 $this->addr_to = dol_sanitizeEmail($to);
483 $this->addr_from = dol_sanitizeEmail($from);
484 $this->msg = $msg;
485 $this->addr_cc = dol_sanitizeEmail($addr_cc);
486 $this->addr_bcc = dol_sanitizeEmail($addr_bcc);
487 $this->deliveryreceipt = $deliveryreceipt;
488 $this->reply_to = dol_sanitizeEmail($replyto);
489 $this->errors_to = dol_sanitizeEmail($errors_to);
490 $this->trackid = $trackid;
491 $this->in_reply_to = $in_reply_to;
492 $this->references = $references;
493 // Set arrays with attached files info
494 $this->filename_list = $filename_list;
495 $this->mimetype_list = $mimetype_list;
496 $this->mimefilename_list = $mimefilename_list;
497 $this->cid_list = $cid_list;
498
499 if (getDolGlobalString('MAIN_MAIL_FORCE_SENDTO')) {
500 $this->addr_to = dol_sanitizeEmail(getDolGlobalString('MAIN_MAIL_FORCE_SENDTO'));
501 $this->addr_cc = '';
502 $this->addr_bcc = '';
503 }
504
505 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
506 if (!empty($this->sendcontext)) {
507 $smtpContextKey = strtoupper($this->sendcontext);
508 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
509 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
510 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
511 }
512 }
513
514 dol_syslog("CMailFile::CMailFile: sendmode=".$this->sendmode." addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
515
516 // We set all data according to chose sending method.
517 // We also set a value for ->msgid
518 if ($this->sendmode == 'mail') {
519 // Use mail php function (default PHP method)
520 // ------------------------------------------
521
522 $smtp_headers = "";
523 $mime_headers = "";
524 $text_body = "";
525 $files_encoded = "";
526
527 // Define smtp_headers (this also set SMTP headers from ->in_reply_to and ->references and set the property ->msgid)
528 $smtp_headers = $this->write_smtpheaders();
529 if (!empty($moreinheader)) {
530 $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n
531 }
532
533 // Define mime_headers
534 $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
535
536 if (!empty($this->html)) {
537 if (!empty($css)) {
538 $this->css = $css;
539 $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
540 }
541
542 $msg = $this->html;
543 }
544
545 // Define body in text_body
546 $text_body = $this->write_body($msg);
547
548 // Add attachments to text_encoded
549 if (!empty($this->atleastonefile) && $filename_list !== null && $mimetype_list !== null && $mimefilename_list !== null) {
550 $files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
551 }
552
553 // We now define $this->headers and $this->message
554 $this->headers = $smtp_headers.$mime_headers;
555 // Clean the header to avoid that it terminates with a CR character.
556 // This avoid also empty lines at end that can be interpreted as mail injection by email servers.
557 $this->headers = preg_replace("/([\r\n]+)$/i", "", $this->headers);
558
559 //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
560 $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
561 $this->message .= $text_body.$files_encoded;
562 $this->message .= "--".$this->mixed_boundary."--".$this->eol;
563 } elseif ($this->sendmode == 'smtps') {
564 // Use SMTPS library
565 // ------------------------------------------
566 $host = dol_getprefix('email');
567
568 require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
569 $smtps = new SMTPs();
570 $smtps->setCharSet($conf->file->character_set_client);
571
572 // Encode subject if required.
573 $subjecttouse = $this->subject;
574 if (!ascii_check($subjecttouse)) {
575 $subjecttouse = $this->encodetorfc2822($subjecttouse);
576 }
577
578 $smtps->setSubject($subjecttouse);
579 $smtps->setTO($this->getValidAddress($this->addr_to, 0, 1));
580 $smtps->setFrom($this->getValidAddress($this->addr_from, 0, 1));
581 $smtps->setReplyTo($this->getValidAddress($this->reply_to, 0, 1));
582
583 $smtps->setTrackId($this->trackid);
584
585 if (!empty($this->in_reply_to)) {
586 $smtps->setInReplyTo($this->in_reply_to);
587 }
588 if (!empty($this->references)) {
589 // SMTPs expects the list of Message-IDs as an array
590 $smtps->setReferences(preg_split('/[\s,]+/', trim($this->references), -1, PREG_SPLIT_NO_EMPTY));
591 }
592
593 if (!empty($moreinheader)) {
594 $smtps->setMoreInHeader($moreinheader);
595 }
596
597 //X-Dolibarr-TRACKID, In-Reply-To, References and $moreinheader will be added to header inside the smtps->getHeader
598
599 if (!empty($this->html)) {
600 if (!empty($css)) {
601 $this->css = $css;
602 $this->buildCSS();
603 }
604 $msg = $this->html;
605 $msg = $this->checkIfHTML($msg); // This add a header and a body including custom CSS to the HTML content
606 }
607
608 // Note: lines starting with a "." are escaped by SMTPs::sendMsg() (dot-stuffing)
609
610 if ($this->msgishtml) {
611 $smtps->setBodyContent($msg, 'html');
612 } else {
613 $smtps->setBodyContent($msg, 'plain');
614 }
615
616 if (!empty($this->atleastoneimage)) {
617 foreach ($this->images_encoded as $img) {
618 $smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']);
619 }
620 }
621
622 if (!empty($this->atleastonefile)) {
623 foreach ($filename_list as $i => $val) {
624 $content = file_get_contents($filename_list[$i]);
625 if (empty($cid_list[$i])) {
626 $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], (empty($cid_list[$i]) ? '' : $cid_list[$i]));
627 }
628 }
629 }
630
631 $smtps->setCC($this->addr_cc);
632 $smtps->setBCC($this->addr_bcc);
633 $smtps->setErrorsTo($this->errors_to);
634 $smtps->setDeliveryReceipt($this->deliveryreceipt);
635
636 $options = array();
637 if (getDolGlobalString($keyforsslseflsigned)) {
638 $options = array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true));
639 }
640 if (getDolGlobalString('SMTPS_CAPTURE_PEER_CERT')) {
641 $options = array_merge($options, array('ssl' => array('capture_peer_cert' => true, 'capture_peer_cert_chain' => true)));
642 // Adding this will allow the code to retrieve information about the TLS certificate by doing
643 // $cert = stream_context_get_params($this->socket)['options']['ssl']['peer_certificate'];
644 // echo "Server Certificate Information:\n";
645 // echo "Subject: " . openssl_x509_parse($cert)['subject']['CN'] . "\n";
646 // echo "Issuer: " . openssl_x509_parse($cert)['issuer']['CN'] . "\n";
647 // echo "Valid From: " . date('Y-m-d H:i:s', openssl_x509_parse($cert)['validFrom_time_t']) . "\n";
648 // echo "Valid To: " . date('Y-m-d H:i:s', openssl_x509_parse($cert)['validTo_time_t']) . "\n";
649 }
650 if (getDolGlobalString('SMTPS_FORCE_IP_V4')) {
651 $options = array_merge($options, array('socket' => ['bindto' => '0.0.0.0:0'])); // Forces IPv4 (IPv6 would be '::0')
652 }
653 if (!empty($options)) {
654 $smtps->setOptions($options);
655 }
656
657 $this->msgid = uniqid('', true).'.SMTPs-dolibarr-'.$this->trackid.'@'.$host;
658
659 $smtps->setMessageID($this->msgid);
660
661 $this->smtps = $smtps;
662 } elseif ($this->sendmode == 'swiftmailer') {
663 // Use Swift Mailer library
664 // ------------------------------------------
665 $host = dol_getprefix('email');
666
667 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
668
669 // egulias autoloader lib
670 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php';
671
672 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
673
674 // Create the message
675 //$this->message = Swift_Message::newInstance();
676 $this->message = new Swift_Message();
677 //$this->message = new Swift_SignedMessage();
678 // Adding a trackid header to a message
679 $headers = $this->message->getHeaders();
680
681 $headers->addTextHeader('X-Dolibarr-TRACKID', $this->trackid.'@'.$host);
682 $this->msgid = uniqid('', true).'.swiftmailer-dolibarr-'.$this->trackid.'@'.$host;
683 $headerID = $this->msgid;
684 $msgid = $headers->get('Message-ID');
685 if ($msgid instanceof Swift_Mime_Headers_IdentificationHeader) {
686 $msgid->setId($headerID);
687 }
688
689 // Add 'In-Reply-To:' header
690 // Swift adds the angle brackets itself and rejects an id that still has them
691 if (!empty($this->in_reply_to)) {
692 $headers->addIdHeader('In-Reply-To', trim($this->in_reply_to, " \t<>"));
693 }
694 // Add 'References:' header
695 if (!empty($this->references)) {
696 $references = array();
697 foreach (preg_split('/[\s,]+/', trim($this->references), -1, PREG_SPLIT_NO_EMPTY) as $reference) {
698 $references[] = trim($reference, '<>');
699 }
700 $headers->addIdHeader('References', $references);
701 }
702
703 if (!empty($moreinheader)) {
704 $moreinheaderarray = preg_split('/[\r\n]+/', $moreinheader);
705 foreach ($moreinheaderarray as $moreinheaderval) {
706 $moreinheadervaltmp = explode(':', $moreinheaderval, 2);
707 if (!empty($moreinheadervaltmp[0]) && !empty($moreinheadervaltmp[1])) {
708 $headers->addTextHeader($moreinheadervaltmp[0], $moreinheadervaltmp[1]);
709 }
710 }
711 }
712
713 // Give the message a subject
714 try {
715 $this->message->setSubject($this->subject);
716 } catch (Exception $e) {
717 $this->errors[] = $e->getMessage();
718 }
719
720 // Set the From address with an associative array
721 // $this->message->setFrom(array('john@doe.com' => 'John Doe'));
722 if (!empty($this->addr_from)) {
723 try {
724 if (getDolGlobalString('MAIN_FORCE_DISABLE_MAIL_SPOOFING')) {
725 // Prevent email spoofing for smtp server with a strict configuration
726 $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string
727 $adressEmailFrom = array();
728 $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
729 $adressEmailFrom = reset($adressEmailFrom);
730 if ($emailMatchs !== false && filter_var(getDolGlobalString('MAIN_MAIL_SMTPS_ID'), FILTER_VALIDATE_EMAIL) && getDolGlobalString('MAIN_MAIL_SMTPS_ID') !== $adressEmailFrom[0]) {
731 $this->message->setFrom(getDolGlobalString('MAIN_MAIL_SMTPS_ID'));
732 } else {
733 $this->message->setFrom($this->getArrayAddress($this->addr_from));
734 }
735 } else {
736 $this->message->setFrom($this->getArrayAddress($this->addr_from));
737 }
738 } catch (Exception $e) {
739 $this->errors[] = $e->getMessage();
740 }
741 }
742
743 // Set the To addresses with an associative array
744 if (!empty($this->addr_to)) {
745 try {
746 $this->message->setTo($this->getArrayAddress($this->addr_to));
747 } catch (Exception $e) {
748 $this->errors[] = $e->getMessage();
749 }
750 }
751
752 if (!empty($this->reply_to)) {
753 try {
754 $this->message->SetReplyTo($this->getArrayAddress($this->reply_to));
755 } catch (Exception $e) {
756 $this->errors[] = $e->getMessage();
757 }
758 }
759
760 if (!empty($this->errors_to)) {
761 try {
762 $headers->addMailboxHeader('Errors-To', $this->getArrayAddress($this->errors_to));
763 } catch (Exception $e) {
764 $this->errors[] = $e->getMessage();
765 }
766 }
767
768 try {
769 $this->message->setCharSet($conf->file->character_set_client);
770 } catch (Exception $e) {
771 $this->errors[] = $e->getMessage();
772 }
773
774 if (!empty($this->html)) {
775 if (!empty($css)) {
776 $this->css = $css;
777 $this->buildCSS();
778 }
779 $msg = $this->html;
780 $msg = $this->checkIfHTML($msg); // This add a header and a body including custom CSS to the HTML content
781 }
782
783 if ($this->atleastoneimage) {
784 foreach ($this->html_images as $img) {
785 // $img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
786 $attachment = Swift_Image::fromPath($img['fullpath']);
787 // embed image
788 $imgcid = $this->message->embed($attachment);
789 // replace cid by the one created by swiftmail in html message
790 $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
791 }
792 foreach ($this->images_encoded as $img) {
793 //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
794 $attachment = Swift_Image::fromPath($img['fullpath']);
795 // embed image
796 $imgcid = $this->message->embed($attachment);
797 // replace cid by the one created by swiftmail in html message
798 $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
799 }
800 }
801
802 if ($this->msgishtml) {
803 $this->message->setBody($msg, 'text/html');
804 // And optionally an alternative body
805 $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
806 } else {
807 $this->message->setBody($msg, 'text/plain');
808 // And optionally an alternative body
809 $this->message->addPart(dol_nl2br($msg), 'text/html');
810 }
811
812 if (!empty($this->atleastonefile)) {
813 foreach ($filename_list as $i => $val) {
814 //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
815 $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
816 if (!empty($mimefilename_list[$i])) {
817 $attachment->setFilename($mimefilename_list[$i]);
818 }
819 $this->message->attach($attachment);
820 }
821 }
822
823 if (!empty($this->addr_cc)) {
824 try {
825 $this->message->setCc($this->getArrayAddress($this->addr_cc));
826 } catch (Exception $e) {
827 $this->errors[] = $e->getMessage();
828 }
829 }
830 if (!empty($this->addr_bcc)) {
831 try {
832 $this->message->setBcc($this->getArrayAddress($this->addr_bcc));
833 } catch (Exception $e) {
834 $this->errors[] = $e->getMessage();
835 }
836 }
837 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
838 try {
839 $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from));
840 } catch (Exception $e) {
841 $this->errors[] = $e->getMessage();
842 }
843 }
844 } else {
845 // Send mail method not correctly defined
846 // --------------------------------------
847 $this->error = 'Bad value for sendmode';
848 }
849 }
850
858 public function sendfile()
859 {
860 global $conf, $db, $langs, $hookmanager;
861
862 $errorlevel = error_reporting();
863 //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings
864
865 $res = false;
866
867 if (!getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
868 if (!is_object($hookmanager)) {
869 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
870 $hookmanager = new HookManager($db);
871 }
872 $hookmanager->initHooks(array('mail'));
873
874 $parameters = array();
875 $action = '';
876 $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
877 if ($reshook < 0) {
878 $this->error = "Error in hook maildao sendMail ".$reshook;
879 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
880
881 return false;
882 }
883 if ($reshook == 1) { // Hook replace standard code
884 dol_syslog("A hook has replaced code to send email", LOG_DEBUG);
885 return true;
886 }
887
888 $sendingmode = $this->sendmode;
889 if ($this->sendcontext == 'emailing' && getDolGlobalString('MAILING_NO_USING_PHPMAIL') && $sendingmode == 'mail') {
890 // List of sending methods
891 $listofmethods = array();
892 $listofmethods['mail'] = 'PHP mail function';
893 //$listofmethods['simplemail']='Simplemail class';
894 $listofmethods['smtps'] = 'SMTP/SMTPS socket library';
895
896 // 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.
897 // You ensure that every user is using its own SMTP server when using the mass emailing module.
898 $linktoadminemailbefore = '<a href="'.DOL_URL_ROOT.'/admin/mails.php">';
899 $linktoadminemailend = '</a>';
900 $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
901 $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
902 $this->error .= '<br>'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
903 $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
904 if (getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS')) {
905 $this->error .= '<br>'.$langs->trans("MailSendSetupIs3", getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
906 $this->errors[] = $langs->trans("MailSendSetupIs3", getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
907 }
908
909 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
910 return false;
911 }
912
913 // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
914 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL')) {
915 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
916 }
917 $tmparray1 = explode(',', $this->addr_to);
918 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
919 $this->error = 'Too much recipients in to:';
920 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
921 return false;
922 }
923 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL')) {
924 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
925 }
926 $tmparray2 = explode(',', $this->addr_cc);
927 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
928 $this->error = 'Too much recipients in cc:';
929 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
930 return false;
931 }
932 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL')) {
933 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
934 }
935 $tmparray3 = explode(',', $this->addr_bcc);
936 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
937 $this->error = 'Too much recipients in bcc:';
938 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
939 return false;
940 }
941 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL')) {
942 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
943 }
944 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
945 $this->error = 'Too much recipients in to:, cc:, bcc:';
946 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
947 return false;
948 }
949
950 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
951 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
952 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
953 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
954 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
955 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
956 $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
957 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
958 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
959 if (!empty($this->sendcontext)) {
960 $smtpContextKey = strtoupper($this->sendcontext);
961 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
962 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
963 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
964 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
965 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
966 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
967 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
968 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
969 $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
970 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
971 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
972 }
973 }
974
975 // Action according to chose sending method
976 if ($this->sendmode == 'mail') {
977 // Use mail php function (default PHP method)
978 // ------------------------------------------
979 dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_NOTICE);
980 //dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
981 //dol_syslog("CMailFile::sendfile message=\n".$message);
982
983 // If Windows, sendmail_from must be defined
984 if (isset($_SERVER["WINDIR"])) {
985 if (empty($this->addr_from)) {
986 $this->addr_from = 'robot@example.com';
987 }
988 @ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
989 }
990
991 // Force parameters
992 //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".getDolGlobalString($keyforsmtpserver)." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG);
993 if (getDolGlobalString($keyforsmtpserver)) {
994 ini_set('SMTP', getDolGlobalString($keyforsmtpserver));
995 }
996 if (getDolGlobalString($keyforsmtpport)) {
997 ini_set('smtp_port', getDolGlobalString($keyforsmtpport));
998 }
999
1000 $res = true;
1001 if ($res && !$this->subject) {
1002 $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
1003 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1004 $res = false;
1005 }
1006 $dest = $this->getValidAddress($this->addr_to, 2);
1007 if ($res && !$dest) {
1008 $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
1009 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1010 $res = false;
1011 }
1012
1013 if ($res) {
1014 $additionnalparam = ''; // By default
1015 if (getDolGlobalString('MAIN_MAIL_ALLOW_SENDMAIL_F')) {
1016 // When using the phpmail function, the mail command may force the from to the user of the login, for example: linuxuser@myserver.mydomain.com
1017 // 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.
1018 // So forcing using the option -f of sendmail is possible if constant MAIN_MAIL_ALLOW_SENDMAIL_F is defined.
1019 // Having this variable defined may create problems with some sendmail (option -f refused)
1020 // Having this variable not defined may create problems with some other sendmail (option -f required)
1021 $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) : ''));
1022 }
1023 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
1024 $additionnalparam .= ($additionnalparam ? ' ' : '').'-ba';
1025 }
1026
1027 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM')) {
1028 $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additional params
1029 }
1030
1031 $linuxlike = 1;
1032 if (preg_match('/^win/i', PHP_OS)) {
1033 $linuxlike = 0;
1034 }
1035 if (preg_match('/^mac/i', PHP_OS)) {
1036 $linuxlike = 0;
1037 }
1038
1039 dol_syslog("CMailFile::sendfile: mail start".($linuxlike ? '' : " HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')).", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
1040
1041 $this->message = stripslashes($this->message);
1042
1043 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1044 $this->dump_mail();
1045 }
1046
1047 // Encode subject if required.
1048 $subjecttouse = $this->subject;
1049 if (!ascii_check($subjecttouse)) {
1050 $subjecttouse = $this->encodetorfc2822($subjecttouse);
1051 }
1052
1053 if (!empty($additionnalparam)) {
1054 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
1055 } else {
1056 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
1057 }
1058
1059 if (!$res) {
1060 $langs->load("errors");
1061 $this->error = "Failed to send mail with php mail";
1062 if (!$linuxlike) {
1063 $this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
1064 }
1065 $this->error .= ".<br>";
1066 $this->error .= $langs->trans("ErrorPhpMailDelivery");
1067 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1068
1069 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1070 $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
1071 }
1072 } else {
1073 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1074 }
1075 }
1076
1077 if (isset($_SERVER["WINDIR"])) {
1078 @ini_restore('sendmail_from');
1079 }
1080
1081 // Restore parameters
1082 if (getDolGlobalString($keyforsmtpserver)) {
1083 ini_restore('SMTP');
1084 }
1085 if (getDolGlobalString($keyforsmtpport)) {
1086 ini_restore('smtp_port');
1087 }
1088 } elseif ($this->sendmode == 'smtps') {
1089 if (!is_object($this->smtps)) {
1090 $this->error = "Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1091 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1092 return false;
1093 }
1094
1095 // Use SMTPS library
1096 // ------------------------------------------
1097 $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
1098
1099 // Clean parameters
1100 if (empty($conf->global->$keyforsmtpserver)) {
1101 $conf->global->$keyforsmtpserver = ini_get('SMTP');
1102 }
1103 if (empty($conf->global->$keyforsmtpport)) {
1104 $conf->global->$keyforsmtpport = ini_get('smtp_port');
1105 }
1106
1107 // If we use SSL/TLS
1108 $server = getDolGlobalString($keyforsmtpserver);
1109 $secure = '';
1110 if (getDolGlobalString($keyfortls) && function_exists('openssl_open')) {
1111 $secure = 'ssl';
1112 }
1113 if (getDolGlobalString($keyforstarttls) && function_exists('openssl_open')) {
1114 $secure = 'tls';
1115 }
1116 $server = ($secure ? $secure.'://' : '').$server;
1117
1118 $port = getDolGlobalInt($keyforsmtpport);
1119
1120 $tmpresult = $this->checkSmtpTargetAllowed($server, $port);
1121 if ($tmpresult) {
1122 $this->error = $tmpresult;
1123 $this->errors[] = $this->error;
1124 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
1125 return false;
1126 }
1127
1128 $this->smtps->setHost($server);
1129 $this->smtps->setPort($port); // 25, 465...;
1130
1131 $loginid = '';
1132 $loginpass = '';
1133 if (getDolGlobalString($keyforsmtpid)) {
1134 $loginid = getDolGlobalString($keyforsmtpid);
1135 $this->smtps->setID($loginid);
1136 }
1137 if (getDolGlobalString($keyforsmtppw)) {
1138 $loginpass = getDolGlobalString($keyforsmtppw);
1139 $this->smtps->setPW($loginpass);
1140 }
1141 // Authentication method of the send context (MAIN_MAIL_SMTPS_AUTH_TYPE_xxx when the context has its own setup)
1142 $this->smtps->setAuthType(getDolGlobalString($keyforsmtpauthtype));
1143
1144 if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
1145 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
1146
1147 $supportedoauth2array = getSupportedOauth2Array();
1148
1149 $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
1150 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
1151 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
1152 } else {
1153 $keyforprovider = '';
1154 }
1155 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
1156 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
1157
1158 if (!empty($supportedoauth2array)) {
1159 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']));
1160 $nameofservice .= ($keyforprovider ? '-'.$keyforprovider : '');
1161 $OAUTH_SERVICENAME = $nameofservice;
1162 } else {
1163 $OAUTH_SERVICENAME = 'Unknown';
1164 }
1165
1166 $keyforparamtenant = 'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']).($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
1167
1168 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
1169
1170 $storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
1171 try {
1172 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1173
1174 $expire = false;
1175 // Is token expired or will token expire in the next 30 seconds
1176 if (is_object($tokenobj)) {
1177 // time() is used in tokenobj @phan-suppress-next-line DolibarrForbiddenFunctionPlugin
1178 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1179 }
1180 // Token expired so we refresh it
1181 if (is_object($tokenobj) && $expire) {
1182 $credentials = new Credentials(
1183 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_ID'),
1184 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_SECRET'),
1185 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_URLCALLBACK')
1186 );
1187 $serviceFactory = new \OAuth\ServiceFactory();
1188
1189 // Force the curl client, the default stream one uses file_get_contents() which
1190 // fails to reach the token endpoint on many setups, so the token is never refreshed.
1191 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
1192 $serviceFactory->setHttpClient($httpClient);
1193 $oauthname = explode('-', $OAUTH_SERVICENAME);
1194 // Recreate the service with its configured scopes.
1195 // This matters for some providers (Microsoft v2 token endpoint) where scope may be required on refresh.
1196 $oauthScopes = array();
1197 $oauthScopesStr = getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_SCOPE');
1198 if (!empty($oauthScopesStr)) {
1199 $oauthScopes = preg_split('/\s*,\s*/', $oauthScopesStr);
1200 if (!is_array($oauthScopes)) {
1201 $oauthScopes = array();
1202 }
1203 }
1204
1205 // ex service is Google-Emails we need only the first part Google
1206 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $oauthScopes);
1207
1208 // Some providers (like Google) return a refresh token only once.
1209 // If the refreshed token does not contain one, keep the previous refresh token.
1210 $refreshtoken = $tokenobj->getRefreshToken();
1211
1212 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1213 // ServiceInterface does not provide refreshAccessToken, AbstractService does
1214 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1215 if (empty($tokenobj->getRefreshToken())) {
1216 $tokenobj->setRefreshToken($refreshtoken);
1217 }
1218 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1219 }
1220
1221 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1222 }
1223
1224 if (is_object($tokenobj)) {
1225 $this->smtps->setToken($tokenobj->getAccessToken());
1226 } else {
1227 $this->error = "OAuth2 token not found for service '".$OAUTH_SERVICENAME."' (setup constant ".$keyforsmtpoauthservice.", send context '".$this->sendcontext."'). Compare it with the service column of llx_oauth_token.";
1228 dol_syslog("CMailFile::sendfile: ".$this->error, LOG_ERR);
1229 }
1230 } catch (Exception $e) {
1231 // Return an error if token not found
1232 $this->error = $e->getMessage();
1233 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1234 }
1235 }
1236
1237 $res = true;
1238 $from = $this->smtps->getFrom('org');
1239 if ($res && !$from) {
1240 $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Sender address '$from' invalid";
1241 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1242 $res = false;
1243 }
1244 $dest = $this->smtps->getTo();
1245 if ($res && !$dest) {
1246 $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Recipient address '$dest' invalid";
1247 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1248 $res = false;
1249 }
1250
1251 if ($res) {
1252 dol_syslog("CMailFile::sendfile: sendMsg, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_NOTICE);
1253
1254 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1255 $this->smtps->setDebug(true);
1256 }
1257
1258 $result = $this->smtps->sendMsg();
1259
1260 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1261 $this->dump_mail(); // Create file dolibarr_mail.log or dolibarr_mail.log.vXXX if option for archive is on
1262 }
1263
1264 $smtperrorcode = 0;
1265 if (! $result) {
1266 $smtperrorcode = $this->smtps->lastretval; // SMTP error code
1267 dol_syslog("CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1268
1269 if ($smtperrorcode == '421') { // Try later
1270 // TODO Add a delay and try again
1271 /*
1272 dol_syslog("CMailFile::sendfile: Try later error, so we wait and we retry");
1273 sleep(2);
1274
1275 $result = $this->smtps->sendMsg();
1276
1277 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1278 $this->dump_mail();
1279 }
1280 */
1281 }
1282 } else {
1283 dol_syslog("CMailFile::sendfile: mail SMTP sendMsg is success", LOG_DEBUG);
1284 }
1285
1286 $result = $this->smtps->getErrors(); // applicative error code (not SMTP error code)
1287
1288 if (empty($this->error) && empty($result)) {
1289 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1290 $res = true;
1291 } else {
1292 if (empty($this->error)) {
1293 $this->error = $result;
1294 }
1295 dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - ".$this->error, LOG_ERR);
1296 $res = false;
1297
1298 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1299 $this->save_dump_mail_in_err('Mail smtp error '.$smtperrorcode.' with topic '.$this->subject.' - '.$this->error);
1300 }
1301 }
1302 }
1303 } elseif ($this->sendmode == 'swiftmailer') {
1304 // Use Swift Mailer library
1305 // ------------------------------------------
1306 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
1307
1308 // Clean parameters
1309 if (empty($conf->global->$keyforsmtpserver)) {
1310 $conf->global->$keyforsmtpserver = ini_get('SMTP');
1311 }
1312 if (empty($conf->global->$keyforsmtpport)) {
1313 $conf->global->$keyforsmtpport = ini_get('smtp_port');
1314 }
1315
1316 // If we use SSL/TLS
1317 $server = getDolGlobalString($keyforsmtpserver);
1318 $secure = '';
1319 if (getDolGlobalString($keyfortls) && function_exists('openssl_open')) {
1320 $secure = 'ssl';
1321 }
1322 if (getDolGlobalString($keyforstarttls) && function_exists('openssl_open')) {
1323 $secure = 'tls';
1324 }
1325
1326 $tmpresult = $this->checkSmtpTargetAllowed($server, getDolGlobalInt($keyforsmtpport));
1327 if ($tmpresult) {
1328 $this->error = $tmpresult;
1329 $this->errors[] = $this->error;
1330 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
1331 return false;
1332 }
1333
1334 $this->transport = new Swift_SmtpTransport($server, getDolGlobalInt($keyforsmtpport), $secure);
1335
1336 if (getDolGlobalString($keyforsmtpid)) {
1337 $this->transport->setUsername(getDolGlobalString($keyforsmtpid));
1338 }
1339 if (getDolGlobalString($keyforsmtppw) && getDolGlobalString($keyforsmtpauthtype) != "XOAUTH2") {
1340 $this->transport->setPassword(getDolGlobalString($keyforsmtppw));
1341 }
1342 if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
1343 $this->transport->setAuthMode('XOAUTH2');
1344 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php';
1345
1346 $supportedoauth2array = getSupportedOauth2Array();
1347
1348 $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
1349 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
1350 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
1351 } else {
1352 $keyforprovider = '';
1353 }
1354 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
1355 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
1356
1357 if (!empty($supportedoauth2array)) {
1358 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']));
1359 $nameofservice .= ($keyforprovider ? '-'.$keyforprovider : '');
1360 $OAUTH_SERVICENAME = $nameofservice;
1361 } else {
1362 $OAUTH_SERVICENAME = 'Unknown';
1363 }
1364
1365 $keyforparamtenant = 'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']).($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
1366
1367 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
1368
1369 $storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
1370
1371 try {
1372 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1373
1374 $expire = false;
1375 // Is token expired or will token expire in the next 30 seconds
1376 if (is_object($tokenobj)) {
1377 // time() is used in tokenobj @phan-suppress-next-line DolibarrForbiddenFunctionPlugin
1378 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1379 }
1380 // Token expired so we refresh it
1381 if (is_object($tokenobj) && $expire) {
1382 $credentials = new Credentials(
1383 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_ID'),
1384 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_SECRET'),
1385 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_URLCALLBACK')
1386 );
1387 $serviceFactory = new \OAuth\ServiceFactory();
1388
1389 // Force the curl client, the default stream one uses file_get_contents() which
1390 // fails to reach the token endpoint on many setups, so the token is never refreshed.
1391 $httpClient = new \OAuth\Common\Http\Client\CurlClient();
1392 $serviceFactory->setHttpClient($httpClient);
1393 $oauthname = explode('-', $OAUTH_SERVICENAME);
1394 // Recreate the service with its configured scopes.
1395 // This matters for some providers (Microsoft v2 token endpoint) where scope may be required on refresh.
1396 $oauthScopes = array();
1397 $oauthScopesStr = getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_SCOPE');
1398 if (!empty($oauthScopesStr)) {
1399 $oauthScopes = preg_split('/\s*,\s*/', $oauthScopesStr);
1400 if (!is_array($oauthScopes)) {
1401 $oauthScopes = array();
1402 }
1403 }
1404
1405 // ex service is Google-Emails we need only the first part Google
1406 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, $oauthScopes);
1407 $refreshtoken = $tokenobj->getRefreshToken();
1408
1409 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1410 // ServiceInterface does not provide refreshAccessToken, AbstractService does
1411 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1412 if (empty($tokenobj->getRefreshToken())) {
1413 $tokenobj->setRefreshToken($refreshtoken);
1414 }
1415 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1416
1417 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1418 }
1419 }
1420
1421 if (is_object($tokenobj)) {
1422 $this->transport->setAuthMode('XOAUTH2');
1423 $this->transport->setPassword($tokenobj->getAccessToken());
1424 } else {
1425 $this->errors[] = "OAuth2 token not found for service '".$OAUTH_SERVICENAME."' (setup constant ".$keyforsmtpoauthservice.", send context '".$this->sendcontext."'). Compare it with the service column of llx_oauth_token.";
1426 dol_syslog("CMailFile::sendfile: ".end($this->errors), LOG_ERR);
1427 }
1428 } catch (Exception $e) {
1429 // Return an error if token not found
1430 $this->errors[] = $e->getMessage();
1431 dol_syslog("CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1432 }
1433 }
1434 if (getDolGlobalString($keyforsslseflsigned)) {
1435 $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false)));
1436 }
1437 //$smtps->_msgReplyTo = 'reply@web.com';
1438
1439 // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable
1440 $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1441 $this->message->setEncoder($contentEncoderBase64);
1442
1443 // Create the Mailer using your created Transport
1444 $this->mailer = new Swift_Mailer($this->transport);
1445
1446 // DKIM SIGN
1447 if (getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_ENABLED')) {
1448 $privateKey = getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY');
1449 $domainName = getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_DOMAIN');
1450 $selector = getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_SELECTOR');
1451 $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1452 $this->message->attachSigner($signer->ignoreHeader('Return-Path'));
1453 }
1454
1455 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1456 // To use the ArrayLogger
1457 $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
1458 // Or to use the Echo Logger
1459 //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
1460 $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
1461 }
1462
1463 dol_syslog("CMailFile::sendfile: mailer->send, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_NOTICE);
1464
1465 // send mail
1466 $failedRecipients = array();
1467
1468 $result = false;
1469 try {
1470 $result = $this->mailer->send($this->message, $failedRecipients);
1471 } catch (Exception $e) {
1472 $this->errors[] = $e->getMessage();
1473 }
1474 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1475 $this->dump_mail();
1476 }
1477
1478 $res = true;
1479 if (!empty($this->error) || !empty($this->errors) || !$result) {
1480 if (!empty($failedRecipients)) {
1481 $this->error = 'Transport failed for the following addresses: "' . implode('", "', $failedRecipients) . '".';
1482 $this->errors[] = $this->error;
1483 }
1484 dol_syslog("CMailFile::sendfile: mail end error=". implode(' ', $this->errors), LOG_ERR);
1485 $res = false;
1486
1487 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1488 $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
1489 }
1490 } else {
1491 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1492 }
1493 } else {
1494 // Send mail method not correctly defined
1495 // --------------------------------------
1496
1497 $this->error = 'Bad value for sendmode';
1498 return false;
1499 }
1500
1501 // Now we delete image files that were created dynamically to manage data inline files
1502 /* Note: dol_delete call was disabled, so code commented to not trigger empty if body
1503 foreach ($this->html_images as $val) {
1504 if (!empty($val['type']) && $val['type'] == 'cidfromdata') {
1505 //dol_delete($val['fullpath']);
1506 }
1507 }
1508 */
1509
1510 $parameters = array('sent' => $res);
1511 $action = '';
1512 $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1513 if ($reshook < 0) {
1514 $this->error = "Error in hook maildao sendMailAfter ".$reshook;
1515 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1516
1517 return false;
1518 }
1519 } else {
1520 $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1521 dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
1522 }
1523
1524 error_reporting($errorlevel); // Reactive original error level
1525 return $res;
1526 }
1527
1534 public static function encodetorfc2822($stringtoencode)
1535 {
1536 global $conf;
1537 return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
1538 }
1539
1540 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1547 private function _encode_file($sourcefile)
1548 {
1549 // phpcs:enable
1550 $newsourcefile = dol_osencode($sourcefile);
1551
1552 if (is_readable($newsourcefile)) {
1553 $contents = file_get_contents($newsourcefile); // Need PHP 4.3
1554 $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
1555 return $encoded;
1556 } else {
1557 $this->error = "Error in _encode_file() method: Can't read file '".$sourcefile."'";
1558 dol_syslog("CMailFile::_encode_file: ".$this->error, LOG_ERR);
1559 return -1;
1560 }
1561 }
1562
1563 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1571 public function dump_mail()
1572 {
1573 // phpcs:enable
1574 global $dolibarr_main_data_root;
1575
1576 if (@is_writable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
1577 $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1578 $fp = fopen($outputfile, "w"); // overwrite
1579
1580 if ($fp) {
1581 if ($this->sendmode == 'mail') {
1582 fwrite($fp, 'Param 1 (dest) for mail(): Not yet available in dump');
1583 fwrite($fp, $this->eol); // This eol is added by the mail function, so we add it in log
1584 fwrite($fp, 'Param 2 (topic) for mail(): '.$this->subject);
1585 fwrite($fp, $this->eol); // This eol is added by the mail function, so we add it in log
1586 fwrite($fp, 'Param 4 (headers) for mail():'."\n");
1587 fwrite($fp, $this->headers);
1588 fwrite($fp, $this->eol); // This eol is added by the mail function, so we add it in log
1589 fwrite($fp, 'Param 3 (message) for mail():'."\n");
1590 fwrite($fp, $this->message);
1591 } elseif ($this->sendmode == 'smtps') {
1592 fwrite($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
1593 } elseif ($this->sendmode == 'swiftmailer') {
1594 fwrite($fp, "smtpheader=\n".$this->message->getHeaders()->toString()."\n");
1595 fwrite($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
1596 }
1597
1598 fclose($fp);
1599 dolChmod($outputfile);
1600
1601 // Move dolibarr_mail.log into a dolibarr_mail.log.v123456789
1602 if (getDolGlobalInt('MAIN_MAIL_DEBUG_LOG_WITH_DATE')) {
1603 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1604 archiveOrBackupFile($outputfile, getDolGlobalInt('MAIN_MAIL_DEBUG_LOG_WITH_DATE'));
1605 }
1606 }
1607 }
1608 }
1609
1610 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1618 public function save_dump_mail_in_err($message = '')
1619 {
1620 global $dolibarr_main_data_root;
1621
1622 if (@is_writable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
1623 $srcfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1624
1625 // Add message to dolibarr_mail.log. We do not use dol_syslog() on purpose,
1626 // to be sure to write into dolibarr_mail.log
1627 if ($message) {
1628 // Test constant SYSLOG_FILE_NO_ERROR (should stay a constant defined with define('SYSLOG_FILE_NO_ERROR',1);
1629 if (defined('SYSLOG_FILE_NO_ERROR')) {
1630 $filefd = @fopen($srcfile, 'a+');
1631 } else {
1632 $filefd = fopen($srcfile, 'a+');
1633 }
1634 if ($filefd) {
1635 fwrite($filefd, $message."\n");
1636 fclose($filefd);
1637 dolChmod($srcfile);
1638 }
1639 }
1640
1641 // Move dolibarr_mail.log into a dolibarr_mail.err or dolibarr_mail.date.err
1642 if (getDolGlobalString('MAIN_MAIL_DEBUG_ERR_WITH_DATE')) {
1643 $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".err";
1644 } else {
1645 $destfile = $dolibarr_main_data_root."/dolibarr_mail.err";
1646 }
1647
1648 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1649 dol_move($srcfile, $destfile, '0', 1, 0, 0);
1650 }
1651 }
1652
1659 public function checkIfHTML($msg)
1660 {
1661 if (!preg_match('/^[\s\t]*<html/i', $msg)) {
1662 $out = "<html><head><title></title>";
1663 if (!empty($this->styleCSS)) {
1664 $out .= $this->styleCSS;
1665 }
1666 $out .= "</head><body";
1667 if (!empty($this->bodyCSS)) {
1668 $out .= $this->bodyCSS;
1669 }
1670 $out .= ">";
1671 $out .= $msg;
1672 $out .= "</body></html>";
1673 } else {
1674 $out = $msg;
1675 }
1676
1677 return $out;
1678 }
1679
1685 public function buildCSS()
1686 {
1687 if (!empty($this->css)) {
1688 // Style CSS
1689 $this->styleCSS = '<style type="text/css">';
1690 $this->styleCSS .= 'body {';
1691
1692 if ($this->css['bgcolor']) {
1693 $this->styleCSS .= ' background-color: '.$this->css['bgcolor'].';';
1694 $this->bodyCSS .= ' bgcolor="'.$this->css['bgcolor'].'"';
1695 }
1696 if ($this->css['bgimage']) {
1697 // TODO recuperer cid
1698 $this->styleCSS .= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
1699 }
1700 $this->styleCSS .= '}';
1701 $this->styleCSS .= '</style>';
1702 }
1703 }
1704
1705 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1711 public function write_smtpheaders()
1712 {
1713 // phpcs:enable
1714 $out = "";
1715 $host = dol_getprefix('email');
1716
1717 // Sender
1718 //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
1719 $out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
1720 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_BA')) {
1721 $out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
1722 }
1723 if (!getDolGlobalString('MAIN_MAIL_NO_RETURN_PATH_FOR_MODE_MAIL')) {
1724 // Return-Path is important because it is used by SPF. Some command line MTA overwrites the Return-Path, even if already in the
1725 // SMTP header, with a value guessed by command line tool. See option MAIN_MAIL_ALLOW_SENDMAIL_F to provide email to the command line tool.
1726 // Return-Path is used for bounced emails. If not set (most cases), the From is used.
1727 $out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 1, 1).$this->eol2;
1728 }
1729 if (isset($this->reply_to) && $this->reply_to) {
1730 $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
1731 }
1732 if (isset($this->errors_to) && $this->errors_to) {
1733 $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1734 }
1735
1736 // Receiver
1737 if (isset($this->addr_cc) && $this->addr_cc) {
1738 $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1739 }
1740 if (isset($this->addr_bcc) && $this->addr_bcc) {
1741 $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 ?
1742 }
1743
1744 // Delivery receipt
1745 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1746 $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1747 }
1748
1749 //$out.= "X-Priority: 3".$this->eol2;
1750 $out .= 'Date: '.date("r").$this->eol2;
1751
1752 $trackid = $this->trackid;
1753 if ($trackid) {
1754 $this->msgid = uniqid('', true).'.phpmail-dolibarr-'.$trackid.'@'.$host;
1755 $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail
1756 $out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2;
1757 } else {
1758 $this->msgid = uniqid('', true).'.phpmail@'.$host;
1759 $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2;
1760 }
1761
1762 // Add 'In-Reply-To:' header with the Message-Id we answer
1763 if (!empty($this->in_reply_to)) {
1764 $out .= 'In-Reply-To: <'.$this->in_reply_to.'>'.$this->eol2;
1765 }
1766 // Add 'References:' header with list of all Message-ID in thread history
1767 if (!empty($this->references)) {
1768 $out .= 'References: '.$this->references.$this->eol2;
1769 }
1770
1771 if (!empty($_SERVER['REMOTE_ADDR'])) {
1772 $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2;
1773 }
1774 $out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2;
1775 $out .= "Mime-Version: 1.0".$this->eol2;
1776
1777 //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1778
1779 $out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1780 if (!getDolGlobalString("MAIN_EMAIL_DISABLE_ADD_CONTENT_ENCODING_8BIT")) {
1781 $out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received.
1782 }
1783
1784 dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out, LOG_DEBUG);
1785 return $out;
1786 }
1787
1788 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1796 public function write_mimeheaders($filename_list, $mimefilename_list)
1797 {
1798 // phpcs:enable
1799 $out = "";
1800
1801 if (is_array($filename_list) && is_array($mimefilename_list)) {
1802 $filename_list_size = count($filename_list);
1803 for ($i = 0; $i < $filename_list_size; $i++) {
1804 if ($filename_list[$i]) {
1805 if ($mimefilename_list[$i]) {
1806 $filename_list[$i] = $mimefilename_list[$i];
1807 }
1808 $out .= "X-attachments: $filename_list[$i]".$this->eol2;
1809 }
1810 }
1811 }
1812
1813 dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1814 return $out;
1815 }
1816
1817 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1824 public function write_body($msgtext)
1825 {
1826 // phpcs:enable
1827 global $conf;
1828
1829 $out = '';
1830
1831 $out .= "--".$this->mixed_boundary.$this->eol;
1832
1833 if ($this->atleastoneimage) {
1834 $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1835 $out .= $this->eol;
1836 $out .= "--".$this->alternative_boundary.$this->eol;
1837 }
1838
1839 // Make RFC821 Compliant, replace bare linefeeds
1840 $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext); // PCRE modifier /s means new lines are common chars
1841 if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) {
1842 $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars
1843 }
1844
1845 $strContentAltText = '';
1846 if ($this->msgishtml) {
1847 // Similar code to forge a text from html is also in smtps.class.php
1848 $strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
1849 // TODO We could replace <img ...> with [Filename.ext] like Gmail do.
1850 $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); // Remove any HTML tags
1851 $strContentAltText = trim(wordwrap($strContentAltText, 75, !getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA') ? "\r\n" : "\n"));
1852
1853 // Check if html header already in message, if not complete the message
1854 $strContent = $this->checkIfHTML($strContent); // This add a header and a body including custom CSS to the HTML content
1855 }
1856
1857 // Make RFC2045 Compliant, split lines
1858 //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
1859 // TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1860 $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.
1861
1862 if ($this->msgishtml) {
1863 if ($this->atleastoneimage) {
1864 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1865 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1866 $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message
1867 $out .= "--".$this->alternative_boundary.$this->eol;
1868 $out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1869 $out .= $this->eol;
1870 $out .= "--".$this->related_boundary.$this->eol;
1871 }
1872
1873 if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part before html part
1874 $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1875 $out .= $this->eol;
1876 $out .= "--".$this->alternative_boundary.$this->eol;
1877 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1878 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1879 $out .= $this->eol.$strContentAltText.$this->eol;
1880 $out .= "--".$this->alternative_boundary.$this->eol;
1881 }
1882
1883 $out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1884 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64
1885 $out .= $this->eol.$strContent.$this->eol;
1886
1887 if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part after html part
1888 $out .= "--".$this->alternative_boundary."--".$this->eol;
1889 }
1890 } else {
1891 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1892 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1893 $out .= $this->eol.$strContent.$this->eol;
1894 }
1895
1896 $out .= $this->eol;
1897
1898 // Encode images
1899 if ($this->atleastoneimage) {
1900 $out .= $this->write_images($this->images_encoded);
1901 // always end related and end alternative after inline images
1902 $out .= "--".$this->related_boundary."--".$this->eol;
1903 $out .= $this->eol."--".$this->alternative_boundary."--".$this->eol;
1904 $out .= $this->eol;
1905 }
1906
1907 return $out;
1908 }
1909
1910 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1920 private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
1921 {
1922 // phpcs:enable
1923 $out = '';
1924
1925 $filename_list_size = count($filename_list);
1926 for ($i = 0; $i < $filename_list_size; $i++) {
1927 if ($filename_list[$i]) {
1928 dol_syslog("CMailFile::write_files: i=$i ".$filename_list[$i]);
1929 $encoded = $this->_encode_file($filename_list[$i]);
1930 if ($encoded !== -1) {
1931 if ($mimefilename_list[$i]) {
1932 $filename_list[$i] = $mimefilename_list[$i];
1933 }
1934 if (!$mimetype_list[$i]) {
1935 $mimetype_list[$i] = "application/octet-stream";
1936 }
1937
1938 // Skip files that have a CID (they will be added as inline images instead)
1939 // @phpstan-ignore-next-line
1940 if (!empty($cidlist) && is_array($cidlist) && isset($cidlist[$i]) && $cidlist[$i] !== null && $cidlist[$i] !== '') {
1941 continue; // Skip this file as it will be processed as inline image
1942 }
1943
1944 $out .= "--".$this->mixed_boundary.$this->eol;
1945
1946 $out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1947 $out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol;
1948 $out .= "Content-Transfer-Encoding: base64".$this->eol;
1949 $out .= "Content-Description: ".$filename_list[$i].$this->eol;
1950 $out .= $this->eol;
1951 $out .= $encoded;
1952 $out .= $this->eol;
1953 //$out.= $this->eol;
1954 } else {
1955 return $encoded;
1956 }
1957 }
1958 }
1959
1960 return $out;
1961 }
1962
1963 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1970 public function write_images($images_list)
1971 {
1972 // phpcs:enable
1973 $out = '';
1974
1975 if (is_array($images_list)) {
1976 foreach ($images_list as $img) {
1977 dol_syslog("CMailFile::write_images: ".$img["name"]);
1978
1979 $out .= "--".$this->related_boundary.$this->eol; // always related for an inline image
1980 $out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol;
1981 $out .= "Content-Transfer-Encoding: base64".$this->eol;
1982 $out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1983 $out .= "Content-ID: <".$img["cid"].">".$this->eol;
1984 $out .= $this->eol;
1985 $out .= $img["image_encoded"];
1986 $out .= $this->eol;
1987 }
1988 }
1989
1990 return $out;
1991 }
1992
2004 public function checkSmtpTargetAllowed($host, $port)
2005 {
2006 include_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php';
2007
2008 global $dolibarr_mail_allow_unrestricted_smtp_target;
2009
2010 if (!empty($dolibarr_mail_allow_unrestricted_smtp_target)) {
2011 return '';
2012 }
2013
2014 $listofallowedports = array('25', '465', '587', '2525');
2015 if ($host && !in_array((string) $port, $listofallowedports)) {
2016 return 'Error bad SMTP port. Only ports '.implode(', ', $listofallowedports).' are allowed. You can set the parameter dolibarr_mail_allow_unrestricted_smtp_target into the conf.php file to remove this restriction.';
2017 }
2018
2019 // Parse $host
2020 $newUrlArray = parse_url((string) $host);
2021 $hosttocheck = $newUrlArray['host'] ?? ($newUrlArray['path'] ?? '');
2022 $hosttocheck = str_replace(array('[', ']'), '', $hosttocheck); // Remove brackets of IPv6
2023
2024 if (empty($hosttocheck)) {
2025 return '';
2026 }
2027
2028 // Deny some reserved host names
2029 if (in_array($hosttocheck, array('metadata.google.internal'))) {
2030 return 'Error bad hostname '.$hosttocheck.' (Used by Google metadata). This value for hostname is not allowed.';
2031 }
2032
2033 // Clean host name $hosttocheck to convert it into an IP $iptocheck
2034 if (in_array($hosttocheck, array('localhost', 'localhost.domain'))) {
2035 $iptocheck = '127.0.0.1';
2036 } elseif (in_array($hosttocheck, array('ip6-localhost', 'ip6-loopback'))) {
2037 $iptocheck = '::1';
2038 } else {
2039 // Resolve $hosttocheck to get the IP $iptocheck
2040 $iptocheck = resolveDns($hosttocheck);
2041 }
2042
2043 // Check $iptocheck is an IP (v4 or v6), if not clear value.
2044 if (!filter_var($iptocheck, FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 | FILTER_FLAG_IPV6)) { // This is not an IP, we clean data
2045 $iptocheck = '0'; // will disabled check on IP
2046 }
2047
2048 if ($iptocheck && !in_array($iptocheck, array('127.0.0.1', '::1'))) {
2049 $localurl = 0;
2050 $tmpresult = isIPAllowed($iptocheck, $localurl);
2051
2052 if ($tmpresult) {
2053 return $tmpresult;
2054 }
2055 }
2056
2057 return '';
2058 }
2059
2060 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2068 public function check_server_port($host, $port)
2069 {
2070 // phpcs:enable
2071 $_retVal = 0;
2072 $timeout = 5; // Timeout in seconds
2073
2074 $tmpresult = $this->checkSmtpTargetAllowed((string) $host, (int) $port);
2075 if ($tmpresult) {
2076 $info = array();
2077 $info['http_code'] = 400;
2078 $info['content'] = $tmpresult;
2079 return $info;
2080 }
2081
2082 if (function_exists('fsockopen')) {
2083 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
2084 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
2085 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
2086 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
2087 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
2088 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
2089 $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
2090 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
2091 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
2092
2093 if (!empty($this->sendcontext)) {
2094 $smtpContextKey = strtoupper($this->sendcontext);
2095 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
2096 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
2097 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
2098 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
2099 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
2100 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
2101 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
2102 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
2103 $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
2104 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
2105 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
2106 }
2107 }
2108
2109 // If we use SSL/TLS
2110 if (getDolGlobalString($keyfortls) && function_exists('openssl_open')) {
2111 $host = 'ssl://'.$host;
2112 }
2113 // tls smtp start with no encryption
2114 //if (getDolGlobalString('MAIN_MAIL_EMAIL_STARTTLS') && function_exists('openssl_open')) $host='tls://'.$host;
2115
2116 dol_syslog("Try socket connection to host=".$host." port=".$port." timeout=".$timeout);
2117 //See if we can connect to the SMTP server
2118 $errno = 0;
2119 $errstr = '';
2120 if ($socket = @fsockopen(
2121 $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
2122 $port, // which Port number to use
2123 $errno, // actual system level error
2124 $errstr, // and any text that goes with the error
2125 $timeout // timeout for reading/writing data over the socket
2126 )) {
2127 // Windows still does not have support for this timeout function
2128 if (function_exists('stream_set_timeout')) {
2129 stream_set_timeout($socket, $timeout, 0);
2130 }
2131
2132 dol_syslog("Now we wait for answer 220");
2133
2134 // Check response from Server
2135 if ($_retVal = $this->server_parse($socket, "220")) {
2136 $_retVal = $socket;
2137 } else {
2138 $this->error = ($this->error ? $this->error." - " : "")."Succeed in opening socket but answer 220 not received";
2139 }
2140 } else {
2141 $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : mb_convert_encoding('Error '.$errno.' - '.$errstr, 'UTF-8', 'ISO-8859-1');
2142 }
2143 }
2144
2145 sleep(1);
2146
2147 return $_retVal;
2148 }
2149
2150 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
2159 public function server_parse($socket, $response)
2160 {
2161 // phpcs:enable
2162 $_retVal = true; // Indicates if Object was created or not
2163 $server_response = '';
2164
2165 while (substr($server_response, 3, 1) != ' ') {
2166 if (!($server_response = fgets($socket, 256))) {
2167 $this->error = "Couldn't get mail server response codes";
2168 return false;
2169 }
2170 }
2171
2172 if (!(substr($server_response, 0, 3) == $response)) {
2173 $this->error = "Ran into problems sending Mail.\r\nResponse: $server_response";
2174 $_retVal = false;
2175 }
2176
2177 return $_retVal;
2178 }
2179
2187 private function findHtmlImages($images_dir)
2188 {
2189 // Build the array of image extensions
2190 $extensions = array_keys($this->image_types);
2191
2192 // We search (into mail body this->html), if we find some strings like "... .imgext" or '... .imgext' to detect strings like "...file=xxx.img"
2193 // For example to detect:
2194 // <img alt="" src="/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/picture.jpg" style="height:356px; width:1040px" />
2195 $matches = array();
2196 preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
2197
2198 if (!empty($matches) && !empty($matches[1])) {
2199 $i = 0;
2200 // We are interested in $matches[1] only (the second set of parenthesis into regex)
2201 foreach ($matches[1] as $full) {
2202 $full = urldecode($full);
2203
2204 $regs = array();
2205 if (preg_match('/file=([A-Za-z0-9_\-\/ ]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) { // If xxx is 'file=aaa'
2206 $img = $regs[1];
2207
2208 if (file_exists($images_dir.'/'.$img)) {
2209 // Image path in src
2210 $src = preg_quote($full, '/');
2211 // Image full path
2212 $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
2213 // Image name
2214 $this->html_images[$i]["name"] = $img;
2215 // Content type
2216 $regext = array();
2217 if (preg_match('/^.+\.(\w{3,4})$/', $img, $regext)) {
2218 $ext = strtolower($regext[1]);
2219 $this->html_images[$i]["content_type"] = $this->image_types[$ext];
2220 }
2221 // cid
2222 $this->html_images[$i]["cid"] = dol_hash($this->html_images[$i]["fullpath"], 'md5'); // Force md5 hash (does not contain special chars)
2223 // type
2224 $this->html_images[$i]["type"] = 'cidfromurl';
2225
2226 $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
2227 }
2228 $i++;
2229 }
2230 }
2231
2232 if (!empty($this->html_images)) {
2233 $inline = array();
2234
2235 $i = 0;
2236
2237 foreach ($this->html_images as $img) {
2238 $fullpath = $images_dir.'/'.$img["name"];
2239
2240 // If referenced image is found on disk (src link), it may show up as attachments, so we remove it by storing it into images_encoded
2241 if (!in_array($fullpath, $inline)) {
2242 // Read image file
2243 if ($image = file_get_contents($fullpath)) {
2244 // Keep only the image name
2245 $regs = array();
2246 preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs);
2247 $imgName = $regs[1];
2248 $this->images_encoded[$i]['name'] = $imgName;
2249 $this->images_encoded[$i]['fullpath'] = $fullpath;
2250 $this->images_encoded[$i]['content_type'] = $img["content_type"];
2251 $this->images_encoded[$i]['cid'] = $img["cid"];
2252 // Encodage de l'image
2253 $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
2254 $inline[] = $fullpath;
2255 }
2256 }
2257 $i++;
2258 }
2259 } else {
2260 return -1;
2261 }
2262
2263 return 1;
2264 } else {
2265 return 0;
2266 }
2267 }
2268
2277 private function findHtmlImagesIsSrcData($images_dir)
2278 {
2279 global $conf;
2280
2281 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2282
2283 // Build the array of image extensions
2284 $extensions = array_keys($this->image_types);
2285
2286 if (empty($images_dir)) {
2287 //$images_dir = $conf->admin->dir_output.'/temp/'.uniqid('cmailfile');
2288 $images_dir = $conf->admin->dir_output.'/temp/cmailfile';
2289 }
2290
2291 if ($images_dir && !dol_is_dir($images_dir)) {
2292 dol_mkdir($images_dir, DOL_DATA_ROOT);
2293 }
2294
2295 // Uncomment this for debug
2296 /*
2297 global $dolibarr_main_data_root;
2298 $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
2299 $fp = fopen($outputfile, "w+");
2300 fwrite($fp, $this->html);
2301 fclose($fp);
2302 */
2303
2304 // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
2305 // For example when:
2306 // <img alt="" src="/src="data:image....;base64,...." />
2307 $matches = array();
2308 preg_match_all('/src="data:image\/('.implode('|', $extensions).');base64,([^"]+)"/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
2309
2310 if (!empty($matches) && !empty($matches[1])) {
2311 if (empty($images_dir)) {
2312 // No temp directory provided, so we are not able to support conversion of data:image into physical images.
2313 $this->errors[] = 'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
2314 return -1;
2315 }
2316
2317 $i = count($this->html_images);
2318 foreach ($matches[1] as $key => $ext) {
2319 // We save the image to send in disk
2320 $filecontent = $matches[2][$key];
2321
2322 $cid = 'cid000'.dol_hash($filecontent, 'md5'); // The id must not change if image is same
2323
2324 $destfiletmp = $images_dir.'/'.$cid.'.'.$ext;
2325
2326 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)
2327 dol_syslog("write the cid file ".$destfiletmp);
2328 $fhandle = @fopen($destfiletmp, 'w');
2329 if ($fhandle) {
2330 $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
2331 fclose($fhandle);
2332 dolChmod($destfiletmp);
2333 } else {
2334 $this->errors[] = "Failed to open file '".$destfiletmp."' for write";
2335 return -2;
2336 }
2337 }
2338
2339 if (file_exists($destfiletmp)) {
2340 // Image full path
2341 $this->html_images[$i]["fullpath"] = $destfiletmp;
2342 // Image name
2343 $this->html_images[$i]["name"] = basename($destfiletmp);
2344 // Content type
2345 $this->html_images[$i]["content_type"] = $this->image_types[strtolower($ext)];
2346 // cid
2347 $this->html_images[$i]["cid"] = $cid;
2348 // type
2349 $this->html_images[$i]["type"] = 'cidfromdata';
2350
2351 $this->html = str_replace('src="data:image/'.$ext.';base64,'.$filecontent.'"', 'src="cid:'.$this->html_images[$i]["cid"].'"', $this->html);
2352 }
2353 $i++;
2354 }
2355
2356 // Also add cidfromdata images to images_encoded array so they are sent as inline images
2357 foreach ($this->html_images as $img) {
2358 if ($img['type'] == 'cidfromdata') {
2359 $image_content = file_get_contents($img['fullpath']);
2360 if ($image_content !== false) {
2361 $idx = count($this->images_encoded);
2362 $this->images_encoded[$idx]['name'] = $img['name'];
2363 $this->images_encoded[$idx]['fullpath'] = $img['fullpath'];
2364 $this->images_encoded[$idx]['content_type'] = $img['content_type'];
2365 $this->images_encoded[$idx]['cid'] = $img['cid'];
2366 $this->images_encoded[$idx]['type'] = 'cidfromdata';
2367 $this->images_encoded[$idx]['image_encoded'] = chunk_split(base64_encode($image_content), 68, $this->eol);
2368 }
2369 }
2370 }
2371
2372 return 1;
2373 } else {
2374 return 0;
2375 }
2376 }
2377
2393 public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
2394 {
2395 $ret = '';
2396
2397 $address = trim(str_replace(array("\r", "\n", "\0"), '', $address));
2398 $arrayaddress = (!empty($address) ? explode(',', $address) : array());
2399
2400 // Loop over every component of the address
2401 $i = 0;
2402 foreach ($arrayaddress as $val) {
2403 $regs = array();
2404 if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
2405 $name = trim($regs[1]);
2406 $email = trim($regs[2]);
2407 } else {
2408 $name = '';
2409 $email = trim($val);
2410 }
2411
2412 if ($email) {
2413 $i++;
2414
2415 $newemail = '';
2416 if ($format == 5) {
2417 $newemail = $name ? $name : $email;
2418 $newemail = '<a href="mailto:'.$email.'">'.$newemail.'</a>';
2419 }
2420 if ($format == 4) {
2421 $newemail = $name ? $name : $email;
2422 }
2423 if ($format == 2) {
2424 $newemail = $email;
2425 }
2426 if ($format == 1 || $format == 3) {
2427 $newemail = '<'.$email.'>';
2428 }
2429 if ($format == 0 || $format == 3) {
2430 if (getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL')) {
2431 $newemail = '<'.$email.'>';
2432 } elseif (!$name) {
2433 $newemail = '<'.$email.'>';
2434 } else {
2435 $newemail = ($format == 3 ? '"' : '').($encode ? self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>';
2436 //$newemail = (($format == 3 && !$encode) ? '"' : '').($encode ? self::encodetorfc2822($name) : $name).(($format == 3 && !$encode) ? '"' : '').' <'.$email.'>';
2437 }
2438 }
2439
2440 $ret = ($ret ? $ret.',' : '').$newemail;
2441
2442 // Stop if we have too much records
2443 if ($maxnumberofemail && $i >= $maxnumberofemail) {
2444 if (count($arrayaddress) > $maxnumberofemail) {
2445 $ret .= '...';
2446 }
2447 break;
2448 }
2449 }
2450 }
2451
2452 return $ret;
2453 }
2454
2462 public static function getArrayAddress($address)
2463 {
2464 $ret = array();
2465
2466 $arrayaddress = explode(',', $address);
2467
2468 // Loop over every component of the address
2469 foreach ($arrayaddress as $val) {
2470 $regs = array();
2471 if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
2472 $name = trim($regs[1]);
2473 $email = trim($regs[2]);
2474 } else {
2475 $name = null;
2476 $email = trim($val);
2477 }
2478
2479 $ret[$email] = getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL') ? null : $name;
2480 }
2481
2482 return $ret;
2483 }
2484}
global $dolibarr_main_url_root
if(!isModEnabled('ai')||!getDolGlobalString('AI_ASSISTANT_ENABLED')) global $conf
The main.inc.php has been included so the following variable are now defined:
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')
__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='', $in_reply_to='', $references='')
CMailFile.
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.
checkSmtpTargetAllowed($host, $port)
Check that the SMTP target (host and port) is allowed.
static encodetorfc2822($stringtoencode)
Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word.
checkIfHTML($msg)
Correct an incomplete 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...
write_smtpheaders()
Create SMTP headers (mode = 'mail')
findHtmlImagesIsSrcData($images_dir)
Search images with src="data:image..." format into html message.
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 This is called in the CM...
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(), $entity=null)
Move a file into another name.
archiveOrBackupFile($srcfile, $max_versions=5, $archivedir='', $suffix="v", $moveorcopy='move')
Manage backup versions for a given file, ensuring only a maximum number of versions are kept.
dol_is_file($pathoffile)
Return if path is a file.
dol_is_dir($folder)
Test if filename is a directory.
dol_now($mode='gmt')
Return date for now.
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.
dolChmod($filepath, $newmask='')
Change mod of a file.
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.
dol_print_date($time, $format='', $tzoutput='auto', $outputlangs=null, $encodetooutput=false, $decorate=0)
Output date in a string format according to outputlangs (or langs if not defined).
getDolGlobalString($key, $default='')
Return a 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.
isIPAllowed($iptocheck, $localurl)
Is IP allowed.
resolveDns($hosttocheck)
Resolve a hostname into its IP.
getSupportedOauth2Array()
Return array of tabs to use on pages to setup cron module.
dol_hash($chain, $type='0', $nosalt=0, $mode=0)
Returns a hash (non reversible encryption) of a string.