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