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