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