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