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