dolibarr 21.0.0-alpha
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 (!empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to));
807 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
808 try {
809 $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from));
810 } catch (Exception $e) {
811 $this->errors[] = $e->getMessage();
812 }
813 }
814 } else {
815 // Send mail method not correctly defined
816 // --------------------------------------
817 $this->error = 'Bad value for sendmode';
818 }
819 }
820
828 public function sendfile()
829 {
830 global $conf, $db, $langs, $hookmanager;
831
832 $errorlevel = error_reporting();
833 //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings
834
835 $res = false;
836
837 if (!getDolGlobalString('MAIN_DISABLE_ALL_MAILS')) {
838 if (!is_object($hookmanager)) {
839 include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
840 $hookmanager = new HookManager($db);
841 }
842 $hookmanager->initHooks(array('mail'));
843
844 $parameters = array();
845 $action = '';
846 $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
847 if ($reshook < 0) {
848 $this->error = "Error in hook maildao sendMail ".$reshook;
849 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
850
851 return false;
852 }
853 if ($reshook == 1) { // Hook replace standard code
854 dol_syslog("A hook has replaced code to send email", LOG_DEBUG);
855 return true;
856 }
857
858 $sendingmode = $this->sendmode;
859 if ($this->sendcontext == 'emailing' && getDolGlobalString('MAILING_NO_USING_PHPMAIL') && $sendingmode == 'mail') {
860 // List of sending methods
861 $listofmethods = array();
862 $listofmethods['mail'] = 'PHP mail function';
863 //$listofmethods['simplemail']='Simplemail class';
864 $listofmethods['smtps'] = 'SMTP/SMTPS socket library';
865
866 // 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.
867 // You ensure that every user is using its own SMTP server when using the mass emailing module.
868 $linktoadminemailbefore = '<a href="'.DOL_URL_ROOT.'/admin/mails.php">';
869 $linktoadminemailend = '</a>';
870 $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
871 $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
872 $this->error .= '<br>'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
873 $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
874 if (getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS')) {
875 $this->error .= '<br>'.$langs->trans("MailSendSetupIs3", getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
876 $this->errors[] = $langs->trans("MailSendSetupIs3", getDolGlobalString('MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS'));
877 }
878
879 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
880 return false;
881 }
882
883 // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
884 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL')) {
885 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
886 }
887 $tmparray1 = explode(',', $this->addr_to);
888 if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
889 $this->error = 'Too much recipients in to:';
890 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
891 return false;
892 }
893 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL')) {
894 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
895 }
896 $tmparray2 = explode(',', $this->addr_cc);
897 if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
898 $this->error = 'Too much recipients in cc:';
899 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
900 return false;
901 }
902 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL')) {
903 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
904 }
905 $tmparray3 = explode(',', $this->addr_bcc);
906 if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
907 $this->error = 'Too much recipients in bcc:';
908 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
909 return false;
910 }
911 if (!getDolGlobalString('MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL')) {
912 $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
913 }
914 if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
915 $this->error = 'Too much recipients in to:, cc:, bcc:';
916 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
917 return false;
918 }
919
920 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
921 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
922 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
923 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
924 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
925 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
926 $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
927 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
928 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
929 if (!empty($this->sendcontext)) {
930 $smtpContextKey = strtoupper($this->sendcontext);
931 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
932 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
933 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
934 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
935 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
936 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
937 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
938 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
939 $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
940 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
941 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
942 }
943 }
944
945 // Action according to chose sending method
946 if ($this->sendmode == 'mail') {
947 // Use mail php function (default PHP method)
948 // ------------------------------------------
949 dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_NOTICE);
950 //dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
951 //dol_syslog("CMailFile::sendfile message=\n".$message);
952
953 // If Windows, sendmail_from must be defined
954 if (isset($_SERVER["WINDIR"])) {
955 if (empty($this->addr_from)) {
956 $this->addr_from = 'robot@example.com';
957 }
958 @ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
959 }
960
961 // Force parameters
962 //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".getDolGlobalString($keyforsmtpserver)." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG);
963 if (getDolGlobalString($keyforsmtpserver)) {
964 ini_set('SMTP', getDolGlobalString($keyforsmtpserver));
965 }
966 if (getDolGlobalString($keyforsmtpport)) {
967 ini_set('smtp_port', getDolGlobalString($keyforsmtpport));
968 }
969
970 $res = true;
971 if ($res && !$this->subject) {
972 $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
973 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
974 $res = false;
975 }
976 $dest = $this->getValidAddress($this->addr_to, 2);
977 if ($res && !$dest) {
978 $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
979 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
980 $res = false;
981 }
982
983 if ($res) {
984 $additionnalparam = ''; // By default
985 if (getDolGlobalString('MAIN_MAIL_ALLOW_SENDMAIL_F')) {
986 // When using the phpmail function, the mail command may force the from to the user of the login, for example: linuxuser@myserver.mydomain.com
987 // 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.
988 // So forcing using the option -f of sendmail is possible if constant MAIN_MAIL_ALLOW_SENDMAIL_F is defined.
989 // Having this variable defined may create problems with some sendmail (option -f refused)
990 // Having this variable not defined may create problems with some other sendmail (option -f required)
991 $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) : ''));
992 }
993 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
994 $additionnalparam .= ($additionnalparam ? ' ' : '').'-ba';
995 }
996
997 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM')) {
998 $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additional params
999 }
1000
1001 $linuxlike = 1;
1002 if (preg_match('/^win/i', PHP_OS)) {
1003 $linuxlike = 0;
1004 }
1005 if (preg_match('/^mac/i', PHP_OS)) {
1006 $linuxlike = 0;
1007 }
1008
1009 dol_syslog("CMailFile::sendfile: mail start".($linuxlike ? '' : " HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')).", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
1010
1011 $this->message = stripslashes($this->message);
1012
1013 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1014 $this->dump_mail();
1015 }
1016
1017 // Encode subject if required.
1018 $subjecttouse = $this->subject;
1019 if (!ascii_check($subjecttouse)) {
1020 $subjecttouse = $this->encodetorfc2822($subjecttouse);
1021 }
1022
1023 if (!empty($additionnalparam)) {
1024 $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
1025 } else {
1026 $res = mail($dest, $subjecttouse, $this->message, $this->headers);
1027 }
1028
1029 if (!$res) {
1030 $langs->load("errors");
1031 $this->error = "Failed to send mail with php mail";
1032 if (!$linuxlike) {
1033 $this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
1034 }
1035 $this->error .= ".<br>";
1036 $this->error .= $langs->trans("ErrorPhpMailDelivery");
1037 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1038
1039 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1040 $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
1041 }
1042 } else {
1043 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1044 }
1045 }
1046
1047 if (isset($_SERVER["WINDIR"])) {
1048 @ini_restore('sendmail_from');
1049 }
1050
1051 // Restore parameters
1052 if (getDolGlobalString($keyforsmtpserver)) {
1053 ini_restore('SMTP');
1054 }
1055 if (getDolGlobalString($keyforsmtpport)) {
1056 ini_restore('smtp_port');
1057 }
1058 } elseif ($this->sendmode == 'smtps') {
1059 if (!is_object($this->smtps)) {
1060 $this->error = "Failed to send mail with smtps lib<br>Constructor of object CMailFile was not initialized without errors.";
1061 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1062 return false;
1063 }
1064
1065 // Use SMTPS library
1066 // ------------------------------------------
1067 $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
1068
1069 // Clean parameters
1070 if (empty($conf->global->$keyforsmtpserver)) {
1071 $conf->global->$keyforsmtpserver = ini_get('SMTP');
1072 }
1073 if (empty($conf->global->$keyforsmtpport)) {
1074 $conf->global->$keyforsmtpport = ini_get('smtp_port');
1075 }
1076
1077 // If we use SSL/TLS
1078 $server = getDolGlobalString($keyforsmtpserver);
1079 $secure = '';
1080 if (getDolGlobalString($keyfortls) && function_exists('openssl_open')) {
1081 $secure = 'ssl';
1082 }
1083 if (getDolGlobalString($keyforstarttls) && function_exists('openssl_open')) {
1084 $secure = 'tls';
1085 }
1086 $server = ($secure ? $secure.'://' : '').$server;
1087
1088 $port = getDolGlobalInt($keyforsmtpport);
1089
1090 $this->smtps->setHost($server);
1091 $this->smtps->setPort($port); // 25, 465...;
1092
1093 $loginid = '';
1094 $loginpass = '';
1095 if (getDolGlobalString($keyforsmtpid)) {
1096 $loginid = getDolGlobalString($keyforsmtpid);
1097 $this->smtps->setID($loginid);
1098 }
1099 if (getDolGlobalString($keyforsmtppw)) {
1100 $loginpass = getDolGlobalString($keyforsmtppw);
1101 $this->smtps->setPW($loginpass);
1102 }
1103
1104 if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
1105 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
1106
1107 $supportedoauth2array = getSupportedOauth2Array();
1108
1109 $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
1110 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
1111 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
1112 } else {
1113 $keyforprovider = '';
1114 }
1115 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
1116 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
1117
1118 if (!empty($supportedoauth2array)) {
1119 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']));
1120 $nameofservice .= ($keyforprovider ? '-'.$keyforprovider : '');
1121 $OAUTH_SERVICENAME = $nameofservice;
1122 } else {
1123 $OAUTH_SERVICENAME = 'Unknown';
1124 }
1125
1126 $keyforparamtenant = 'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']).($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
1127
1128 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
1129
1130 $storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
1131 try {
1132 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1133
1134 $expire = false;
1135 // Is token expired or will token expire in the next 30 seconds
1136 if (is_object($tokenobj)) {
1137 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1138 }
1139 // Token expired so we refresh it
1140 if (is_object($tokenobj) && $expire) {
1141 $credentials = new Credentials(
1142 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_ID'),
1143 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_SECRET'),
1144 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_URLCALLBACK')
1145 );
1146 $serviceFactory = new \OAuth\ServiceFactory();
1147 $oauthname = explode('-', $OAUTH_SERVICENAME);
1148 // ex service is Google-Emails we need only the first part Google
1149 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1150
1151 // We have to save the refresh token because Google give it only once
1152 $refreshtoken = $tokenobj->getRefreshToken();
1153
1154 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1155 // ServiceInterface does not provide refreshAccessToken, AbstractService does
1156 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1157 $tokenobj->setRefreshToken($refreshtoken); // Restore the refresh token
1158 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1159 }
1160
1161 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1162 }
1163
1164 if (is_object($tokenobj)) {
1165 $this->smtps->setToken($tokenobj->getAccessToken());
1166 } else {
1167 $this->error = "Token not found";
1168 }
1169 } catch (Exception $e) {
1170 // Return an error if token not found
1171 $this->error = $e->getMessage();
1172 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1173 }
1174 }
1175
1176 $res = true;
1177 $from = $this->smtps->getFrom('org');
1178 if ($res && !$from) {
1179 $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Sender address '$from' invalid";
1180 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1181 $res = false;
1182 }
1183 $dest = $this->smtps->getTo();
1184 if ($res && !$dest) {
1185 $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - Recipient address '$dest' invalid";
1186 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1187 $res = false;
1188 }
1189
1190 if ($res) {
1191 dol_syslog("CMailFile::sendfile: sendMsg, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_NOTICE);
1192
1193 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1194 $this->smtps->setDebug(true);
1195 }
1196
1197 $result = $this->smtps->sendMsg();
1198
1199 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1200 $this->dump_mail();
1201 }
1202
1203 $smtperrorcode = 0;
1204 if (! $result) {
1205 $smtperrorcode = $this->smtps->lastretval; // SMTP error code
1206 dol_syslog("CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
1207
1208 if ($smtperrorcode == '421') { // Try later
1209 // TODO Add a delay and try again
1210 /*
1211 dol_syslog("CMailFile::sendfile: Try later error, so we wait and we retry");
1212 sleep(2);
1213
1214 $result = $this->smtps->sendMsg();
1215
1216 if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
1217 $this->dump_mail();
1218 }
1219 */
1220 }
1221 }
1222
1223 $result = $this->smtps->getErrors(); // applicative error code (not SMTP error code)
1224 if (empty($this->error) && empty($result)) {
1225 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1226 $res = true;
1227 } else {
1228 if (empty($this->error)) {
1229 $this->error = $result;
1230 }
1231 dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport)." - ".$this->error, LOG_ERR);
1232 $res = false;
1233
1234 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1235 $this->save_dump_mail_in_err('Mail smtp error '.$smtperrorcode.' with topic '.$this->subject);
1236 }
1237 }
1238 }
1239 } elseif ($this->sendmode == 'swiftmailer') {
1240 // Use Swift Mailer library
1241 // ------------------------------------------
1242 require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
1243
1244 // Clean parameters
1245 if (empty($conf->global->$keyforsmtpserver)) {
1246 $conf->global->$keyforsmtpserver = ini_get('SMTP');
1247 }
1248 if (empty($conf->global->$keyforsmtpport)) {
1249 $conf->global->$keyforsmtpport = ini_get('smtp_port');
1250 }
1251
1252 // If we use SSL/TLS
1253 $server = getDolGlobalString($keyforsmtpserver);
1254 $secure = '';
1255 if (getDolGlobalString($keyfortls) && function_exists('openssl_open')) {
1256 $secure = 'ssl';
1257 }
1258 if (getDolGlobalString($keyforstarttls) && function_exists('openssl_open')) {
1259 $secure = 'tls';
1260 }
1261
1262 $this->transport = new Swift_SmtpTransport($server, getDolGlobalInt($keyforsmtpport), $secure);
1263
1264 if (getDolGlobalString($keyforsmtpid)) {
1265 $this->transport->setUsername(getDolGlobalString($keyforsmtpid));
1266 }
1267 if (getDolGlobalString($keyforsmtppw) && getDolGlobalString($keyforsmtpauthtype) != "XOAUTH2") {
1268 $this->transport->setPassword(getDolGlobalString($keyforsmtppw));
1269 }
1270 if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
1271 require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php';
1272
1273 $supportedoauth2array = getSupportedOauth2Array();
1274
1275 $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
1276 if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
1277 $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
1278 } else {
1279 $keyforprovider = '';
1280 }
1281 $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
1282 $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
1283
1284 if (!empty($supportedoauth2array)) {
1285 $nameofservice = ucfirst(strtolower(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']));
1286 $nameofservice .= ($keyforprovider ? '-'.$keyforprovider : '');
1287 $OAUTH_SERVICENAME = $nameofservice;
1288 } else {
1289 $OAUTH_SERVICENAME = 'Unknown';
1290 }
1291
1292 $keyforparamtenant = 'OAUTH_'.strtoupper(empty($supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['callbackfile']).($keyforprovider ? '-'.$keyforprovider : '').'_TENANT';
1293
1294 require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
1295
1296 $storage = new DoliStorage($db, $conf, $keyforprovider, getDolGlobalString($keyforparamtenant));
1297
1298 try {
1299 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1300
1301 $expire = false;
1302 // Is token expired or will token expire in the next 30 seconds
1303 if (is_object($tokenobj)) {
1304 $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
1305 }
1306 // Token expired so we refresh it
1307 if (is_object($tokenobj) && $expire) {
1308 $credentials = new Credentials(
1309 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_ID'),
1310 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_SECRET'),
1311 getDolGlobalString('OAUTH_'.getDolGlobalString($keyforsmtpoauthservice).'_URLCALLBACK')
1312 );
1313 $serviceFactory = new \OAuth\ServiceFactory();
1314 $oauthname = explode('-', $OAUTH_SERVICENAME);
1315 // ex service is Google-Emails we need only the first part Google
1316 $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
1317 $refreshtoken = $tokenobj->getRefreshToken();
1318
1319 if ($apiService instanceof OAuth\OAuth2\Service\AbstractService || $apiService instanceof OAuth\OAuth1\Service\AbstractService) {
1320 // ServiceInterface does not provide refreshAccessToken, AbstractService does
1321 // We must save the token because Google provides it only once
1322 $tokenobj = $apiService->refreshAccessToken($tokenobj);
1323 $tokenobj->setRefreshToken($refreshtoken);
1324 $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
1325
1326 $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
1327 }
1328 }
1329
1330 if (is_object($tokenobj)) {
1331 $this->transport->setAuthMode('XOAUTH2');
1332 $this->transport->setPassword($tokenobj->getAccessToken());
1333 } else {
1334 $this->errors[] = "Token not found";
1335 }
1336 } catch (Exception $e) {
1337 // Return an error if token not found
1338 $this->errors[] = $e->getMessage();
1339 dol_syslog("CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
1340 }
1341 }
1342 if (getDolGlobalString($keyforsslseflsigned)) {
1343 $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false)));
1344 }
1345 //$smtps->_msgReplyTo = 'reply@web.com';
1346
1347 // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable
1348 $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder();
1349 $this->message->setEncoder($contentEncoderBase64);
1350
1351 // Create the Mailer using your created Transport
1352 $this->mailer = new Swift_Mailer($this->transport);
1353
1354 // DKIM SIGN
1355 if (getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_ENABLED')) {
1356 $privateKey = getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY');
1357 $domainName = getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_DOMAIN');
1358 $selector = getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_SELECTOR');
1359 $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
1360 $this->message->attachSigner($signer->ignoreHeader('Return-Path'));
1361 }
1362
1363 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1364 // To use the ArrayLogger
1365 $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
1366 // Or to use the Echo Logger
1367 //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
1368 $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
1369 }
1370
1371 dol_syslog("CMailFile::sendfile: mailer->send, HOST=".$server.", PORT=" . getDolGlobalString($keyforsmtpport), LOG_NOTICE);
1372
1373 // send mail
1374 $failedRecipients = array();
1375 try {
1376 $result = $this->mailer->send($this->message, $failedRecipients);
1377 } catch (Exception $e) {
1378 $this->errors[] = $e->getMessage();
1379 }
1380 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1381 $this->dump_mail();
1382 }
1383
1384 $res = true;
1385 if (!empty($this->error) || !empty($this->errors) || !$result) {
1386 if (!empty($failedRecipients)) {
1387 $this->error = 'Transport failed for the following addresses: "' . implode('", "', $failedRecipients) . '".';
1388 $this->errors[] = $this->error;
1389 }
1390 dol_syslog("CMailFile::sendfile: mail end error=". implode(' ', $this->errors), LOG_ERR);
1391 $res = false;
1392
1393 if (getDolGlobalString('MAIN_MAIL_DEBUG')) {
1394 $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
1395 }
1396 } else {
1397 dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
1398 }
1399 } else {
1400 // Send mail method not correctly defined
1401 // --------------------------------------
1402
1403 $this->error = 'Bad value for sendmode';
1404 return false;
1405 }
1406
1407 // Now we delete image files that were created dynamically to manage data inline files
1408 /* Note: dol_delete call was disabled, so code commented to not trigger empty if body
1409 foreach ($this->html_images as $val) {
1410 if (!empty($val['type']) && $val['type'] == 'cidfromdata') {
1411 //dol_delete($val['fullpath']);
1412 }
1413 }
1414 */
1415
1416 $parameters = array('sent' => $res);
1417 $action = '';
1418 $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
1419 if ($reshook < 0) {
1420 $this->error = "Error in hook maildao sendMailAfter ".$reshook;
1421 dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
1422
1423 return false;
1424 }
1425 } else {
1426 $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
1427 dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
1428 }
1429
1430 error_reporting($errorlevel); // Reactive niveau erreur origine
1431 return $res;
1432 }
1433
1440 public static function encodetorfc2822($stringtoencode)
1441 {
1442 global $conf;
1443 return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
1444 }
1445
1446 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1453 private function _encode_file($sourcefile)
1454 {
1455 // phpcs:enable
1456 $newsourcefile = dol_osencode($sourcefile);
1457
1458 if (is_readable($newsourcefile)) {
1459 $contents = file_get_contents($newsourcefile); // Need PHP 4.3
1460 $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
1461 return $encoded;
1462 } else {
1463 $this->error = "Error in _encode_file() method: Can't read file '".$sourcefile."'";
1464 dol_syslog("CMailFile::_encode_file: ".$this->error, LOG_ERR);
1465 return -1;
1466 }
1467 }
1468
1469
1470 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1478 public function dump_mail()
1479 {
1480 // phpcs:enable
1481 global $dolibarr_main_data_root;
1482
1483 if (@is_writable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
1484 $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1485 $fp = fopen($outputfile, "w"); // overwrite
1486
1487 if ($this->sendmode == 'mail') {
1488 fwrite($fp, $this->headers);
1489 fwrite($fp, $this->eol); // This eol is added by the mail function, so we add it in log
1490 fwrite($fp, $this->message);
1491 } elseif ($this->sendmode == 'smtps') {
1492 fwrite($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
1493 } elseif ($this->sendmode == 'swiftmailer') {
1494 fwrite($fp, "smtpheader=\n".$this->message->getHeaders()->toString()."\n");
1495 fwrite($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
1496 }
1497
1498 fclose($fp);
1499 dolChmod($outputfile);
1500
1501 // Move dolibarr_mail.log into a dolibarr_mail.log.v123456789
1502 if (getDolGlobalInt('MAIN_MAIL_DEBUG_LOG_WITH_DATE')) {
1503 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1504 archiveOrBackupFile($outputfile, getDolGlobalInt('MAIN_MAIL_DEBUG_LOG_WITH_DATE'));
1505 }
1506 }
1507 }
1508
1509 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1517 public function save_dump_mail_in_err($message = '')
1518 {
1519 global $dolibarr_main_data_root;
1520
1521 if (@is_writable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
1522 $srcfile = $dolibarr_main_data_root."/dolibarr_mail.log";
1523
1524 // Add message to dolibarr_mail.log. We do not use dol_syslog() on purpose,
1525 // to be sure to write into dolibarr_mail.log
1526 if ($message) {
1527 // Test constant SYSLOG_FILE_NO_ERROR (should stay a constant defined with define('SYSLOG_FILE_NO_ERROR',1);
1528 if (defined('SYSLOG_FILE_NO_ERROR')) {
1529 $filefd = @fopen($srcfile, 'a+');
1530 } else {
1531 $filefd = fopen($srcfile, 'a+');
1532 }
1533 if ($filefd) {
1534 fwrite($filefd, $message."\n");
1535 fclose($filefd);
1536 dolChmod($srcfile);
1537 }
1538 }
1539
1540 // Move dolibarr_mail.log into a dolibarr_mail.err or dolibarr_mail.date.err
1541 if (getDolGlobalString('MAIN_MAIL_DEBUG_ERR_WITH_DATE')) {
1542 $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".err";
1543 } else {
1544 $destfile = $dolibarr_main_data_root."/dolibarr_mail.err";
1545 }
1546
1547 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
1548 dol_move($srcfile, $destfile, '0', 1, 0, 0);
1549 }
1550 }
1551
1552
1559 public function checkIfHTML($msg)
1560 {
1561 if (!preg_match('/^[\s\t]*<html/i', $msg)) {
1562 $out = "<html><head><title></title>";
1563 if (!empty($this->styleCSS)) {
1564 $out .= $this->styleCSS;
1565 }
1566 $out .= "</head><body";
1567 if (!empty($this->bodyCSS)) {
1568 $out .= $this->bodyCSS;
1569 }
1570 $out .= ">";
1571 $out .= $msg;
1572 $out .= "</body></html>";
1573 } else {
1574 $out = $msg;
1575 }
1576
1577 return $out;
1578 }
1579
1585 public function buildCSS()
1586 {
1587 if (!empty($this->css)) {
1588 // Style CSS
1589 $this->styleCSS = '<style type="text/css">';
1590 $this->styleCSS .= 'body {';
1591
1592 if ($this->css['bgcolor']) {
1593 $this->styleCSS .= ' background-color: '.$this->css['bgcolor'].';';
1594 $this->bodyCSS .= ' bgcolor="'.$this->css['bgcolor'].'"';
1595 }
1596 if ($this->css['bgimage']) {
1597 // TODO recuperer cid
1598 $this->styleCSS .= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
1599 }
1600 $this->styleCSS .= '}';
1601 $this->styleCSS .= '</style>';
1602 }
1603 }
1604
1605
1606 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1612 public function write_smtpheaders()
1613 {
1614 // phpcs:enable
1615 $out = "";
1616 $host = dol_getprefix('email');
1617
1618 // Sender
1619 //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
1620 $out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
1621 if (getDolGlobalString('MAIN_MAIL_SENDMAIL_FORCE_BA')) {
1622 $out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
1623 }
1624 // Return-Path is important because it is used by SPF. Some MTA does not read Return-Path from header but from command line. See option MAIN_MAIL_ALLOW_SENDMAIL_F for that.
1625 $out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
1626 if (isset($this->reply_to) && $this->reply_to) {
1627 $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
1628 }
1629 if (isset($this->errors_to) && $this->errors_to) {
1630 $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
1631 }
1632
1633 // Receiver
1634 if (isset($this->addr_cc) && $this->addr_cc) {
1635 $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
1636 }
1637 if (isset($this->addr_bcc) && $this->addr_bcc) {
1638 $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 ?
1639 }
1640
1641 // Delivery receipt
1642 if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
1643 $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
1644 }
1645
1646 //$out.= "X-Priority: 3".$this->eol2;
1647
1648 $out .= 'Date: '.date("r").$this->eol2;
1649
1650 $trackid = $this->trackid;
1651 if ($trackid) {
1652 $this->msgid = time().'.phpmail-dolibarr-'.$trackid.'@'.$host;
1653 $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail
1654 $out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2;
1655 } else {
1656 $this->msgid = time().'.phpmail@'.$host;
1657 $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2;
1658 }
1659
1660 // Add 'In-Reply-To:' header with the Message-Id we answer
1661 if (!empty($this->in_reply_to)) {
1662 $out .= 'In-Reply-To: <'.$this->in_reply_to.'>'.$this->eol2;
1663 }
1664 // Add 'References:' header with list of all Message-ID in thread history
1665 if (!empty($this->references)) {
1666 $out .= 'References: '.$this->references.$this->eol2;
1667 }
1668
1669 if (!empty($_SERVER['REMOTE_ADDR'])) {
1670 $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2;
1671 }
1672 $out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2;
1673 $out .= "Mime-Version: 1.0".$this->eol2;
1674
1675 //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
1676
1677 $out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
1678 $out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received.
1679
1680 dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out, LOG_DEBUG);
1681 return $out;
1682 }
1683
1684
1685 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1693 public function write_mimeheaders($filename_list, $mimefilename_list)
1694 {
1695 // phpcs:enable
1696 $mimedone = 0;
1697 $out = "";
1698
1699 if (is_array($filename_list)) {
1700 $filename_list_size = count($filename_list);
1701 for ($i = 0; $i < $filename_list_size; $i++) {
1702 if ($filename_list[$i]) {
1703 if ($mimefilename_list[$i]) {
1704 $filename_list[$i] = $mimefilename_list[$i];
1705 }
1706 $out .= "X-attachments: $filename_list[$i]".$this->eol2;
1707 }
1708 }
1709 }
1710
1711 dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
1712 return $out;
1713 }
1714
1715 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1722 public function write_body($msgtext)
1723 {
1724 // phpcs:enable
1725 global $conf;
1726
1727 $out = '';
1728
1729 $out .= "--".$this->mixed_boundary.$this->eol;
1730
1731 if ($this->atleastoneimage) {
1732 $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1733 $out .= $this->eol;
1734 $out .= "--".$this->alternative_boundary.$this->eol;
1735 }
1736
1737 // Make RFC821 Compliant, replace bare linefeeds
1738 $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext); // PCRE modifier /s means new lines are common chars
1739 if (getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA')) {
1740 $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars
1741 }
1742
1743 $strContentAltText = '';
1744 if ($this->msgishtml) {
1745 // Similar code to forge a text from html is also in smtps.class.php
1746 $strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
1747 // TODO We could replace <img ...> with [Filename.ext] like Gmail do.
1748 $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); // Remove any HTML tags
1749 $strContentAltText = trim(wordwrap($strContentAltText, 75, !getDolGlobalString('MAIN_FIX_FOR_BUGGED_MTA') ? "\r\n" : "\n"));
1750
1751 // Check if html header already in message, if not complete the message
1752 $strContent = $this->checkIfHTML($strContent); // This add a header and a body including custom CSS to the HTML content
1753 }
1754
1755 // Make RFC2045 Compliant, split lines
1756 //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
1757 // TODO Encode main content into base64 and use the chunk_split, or quoted-printable
1758 $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.
1759
1760 if ($this->msgishtml) {
1761 if ($this->atleastoneimage) {
1762 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1763 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1764 $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message
1765 $out .= "--".$this->alternative_boundary.$this->eol;
1766 $out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
1767 $out .= $this->eol;
1768 $out .= "--".$this->related_boundary.$this->eol;
1769 }
1770
1771 if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part before html part
1772 $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
1773 $out .= $this->eol;
1774 $out .= "--".$this->alternative_boundary.$this->eol;
1775 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1776 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1777 $out .= $this->eol.$strContentAltText.$this->eol;
1778 $out .= "--".$this->alternative_boundary.$this->eol;
1779 }
1780
1781 $out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
1782 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64
1783 $out .= $this->eol.$strContent.$this->eol;
1784
1785 if (!$this->atleastoneimage && $strContentAltText && getDolGlobalString('MAIN_MAIL_USE_MULTI_PART')) { // Add plain text message part after html part
1786 $out .= "--".$this->alternative_boundary."--".$this->eol;
1787 }
1788 } else {
1789 $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
1790 //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
1791 $out .= $this->eol.$strContent.$this->eol;
1792 }
1793
1794 $out .= $this->eol;
1795
1796 // Encode images
1797 if ($this->atleastoneimage) {
1798 $out .= $this->write_images($this->images_encoded);
1799 // always end related and end alternative after inline images
1800 $out .= "--".$this->related_boundary."--".$this->eol;
1801 $out .= $this->eol."--".$this->alternative_boundary."--".$this->eol;
1802 $out .= $this->eol;
1803 }
1804
1805 return $out;
1806 }
1807
1808 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1818 private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
1819 {
1820 // phpcs:enable
1821 $out = '';
1822
1823 $filename_list_size = count($filename_list);
1824 for ($i = 0; $i < $filename_list_size; $i++) {
1825 if ($filename_list[$i]) {
1826 dol_syslog("CMailFile::write_files: i=$i ".$filename_list[$i]);
1827 $encoded = $this->_encode_file($filename_list[$i]);
1828 if ($encoded !== -1) {
1829 if ($mimefilename_list[$i]) {
1830 $filename_list[$i] = $mimefilename_list[$i];
1831 }
1832 if (!$mimetype_list[$i]) {
1833 $mimetype_list[$i] = "application/octet-stream";
1834 }
1835
1836 $out .= "--".$this->mixed_boundary.$this->eol;
1837 $out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
1838 $out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol;
1839 $out .= "Content-Transfer-Encoding: base64".$this->eol;
1840 $out .= "Content-Description: ".$filename_list[$i].$this->eol;
1841 if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) {
1842 $out .= "X-Attachment-Id: ".$cidlist[$i].$this->eol;
1843 $out .= "Content-ID: <".$cidlist[$i].'>'.$this->eol;
1844 }
1845 $out .= $this->eol;
1846 $out .= $encoded;
1847 $out .= $this->eol;
1848 //$out.= $this->eol;
1849 } else {
1850 return $encoded;
1851 }
1852 }
1853 }
1854
1855 return $out;
1856 }
1857
1858
1859 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1866 public function write_images($images_list)
1867 {
1868 // phpcs:enable
1869 $out = '';
1870
1871 if (is_array($images_list)) {
1872 foreach ($images_list as $img) {
1873 dol_syslog("CMailFile::write_images: ".$img["name"]);
1874
1875 $out .= "--".$this->related_boundary.$this->eol; // always related for an inline image
1876 $out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol;
1877 $out .= "Content-Transfer-Encoding: base64".$this->eol;
1878 $out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
1879 $out .= "Content-ID: <".$img["cid"].">".$this->eol;
1880 $out .= $this->eol;
1881 $out .= $img["image_encoded"];
1882 $out .= $this->eol;
1883 }
1884 }
1885
1886 return $out;
1887 }
1888
1889
1890 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1898 public function check_server_port($host, $port)
1899 {
1900 // phpcs:enable
1901 global $conf;
1902
1903 $_retVal = 0;
1904 $timeout = 5; // Timeout in seconds
1905
1906 if (function_exists('fsockopen')) {
1907 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
1908 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
1909 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
1910 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
1911 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
1912 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
1913 $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
1914 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
1915 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
1916
1917 if (!empty($this->sendcontext)) {
1918 $smtpContextKey = strtoupper($this->sendcontext);
1919 $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
1920 if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
1921 $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
1922 $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
1923 $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
1924 $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
1925 $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
1926 $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
1927 $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
1928 $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
1929 $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
1930 }
1931 }
1932
1933 // If we use SSL/TLS
1934 if (getDolGlobalString($keyfortls) && function_exists('openssl_open')) {
1935 $host = 'ssl://'.$host;
1936 }
1937 // tls smtp start with no encryption
1938 //if (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
1939
1940 dol_syslog("Try socket connection to host=".$host." port=".$port." timeout=".$timeout);
1941 //See if we can connect to the SMTP server
1942 $errno = 0;
1943 $errstr = '';
1944 if ($socket = @fsockopen(
1945 $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
1946 $port, // which Port number to use
1947 $errno, // actual system level error
1948 $errstr, // and any text that goes with the error
1949 $timeout // timeout for reading/writing data over the socket
1950 )) {
1951 // Windows still does not have support for this timeout function
1952 if (function_exists('stream_set_timeout')) {
1953 stream_set_timeout($socket, $timeout, 0);
1954 }
1955
1956 dol_syslog("Now we wait for answer 220");
1957
1958 // Check response from Server
1959 if ($_retVal = $this->server_parse($socket, "220")) {
1960 $_retVal = $socket;
1961 }
1962 } else {
1963 $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : mb_convert_encoding('Error '.$errno.' - '.$errstr, 'UTF-8', 'ISO-8859-1');
1964 }
1965 }
1966 return $_retVal;
1967 }
1968
1969 // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
1978 public function server_parse($socket, $response)
1979 {
1980 // phpcs:enable
1981 $_retVal = true; // Indicates if Object was created or not
1982 $server_response = '';
1983
1984 while (substr($server_response, 3, 1) != ' ') {
1985 if (!($server_response = fgets($socket, 256))) {
1986 $this->error = "Couldn't get mail server response codes";
1987 return false;
1988 }
1989 }
1990
1991 if (!(substr($server_response, 0, 3) == $response)) {
1992 $this->error = "Ran into problems sending Mail.\r\nResponse: $server_response";
1993 $_retVal = false;
1994 }
1995
1996 return $_retVal;
1997 }
1998
2005 private function findHtmlImages($images_dir)
2006 {
2007 // Build the array of image extensions
2008 $extensions = array_keys($this->image_types);
2009
2010 // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
2011 // For example when:
2012 // <img alt="" src="/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/picture.jpg" style="height:356px; width:1040px" />
2013 $matches = array();
2014 preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
2015
2016 if (!empty($matches) && !empty($matches[1])) {
2017 $i = 0;
2018 // We are interested in $matches[1] only (the second set of parenthesis into regex)
2019 foreach ($matches[1] as $full) {
2020 $regs = array();
2021 if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) { // If xxx is 'file=aaa'
2022 $img = $regs[1];
2023
2024 if (file_exists($images_dir.'/'.$img)) {
2025 // Image path in src
2026 $src = preg_quote($full, '/');
2027 // Image full path
2028 $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
2029 // Image name
2030 $this->html_images[$i]["name"] = $img;
2031 // Content type
2032 $regext = array();
2033 if (preg_match('/^.+\.(\w{3,4})$/', $img, $regext)) {
2034 $ext = strtolower($regext[1]);
2035 $this->html_images[$i]["content_type"] = $this->image_types[$ext];
2036 }
2037 // cid
2038 $this->html_images[$i]["cid"] = dol_hash($this->html_images[$i]["fullpath"], 'md5'); // Force md5 hash (does not contain special chars)
2039 // type
2040 $this->html_images[$i]["type"] = 'cidfromurl';
2041
2042 $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
2043 }
2044 $i++;
2045 }
2046 }
2047
2048 if (!empty($this->html_images)) {
2049 $inline = array();
2050
2051 $i = 0;
2052
2053 foreach ($this->html_images as $img) {
2054 $fullpath = $images_dir.'/'.$img["name"];
2055
2056 // If duplicate images are embedded, they may show up as attachments, so remove them.
2057 if (!in_array($fullpath, $inline)) {
2058 // Read image file
2059 if ($image = file_get_contents($fullpath)) {
2060 // On garde que le nom de l'image
2061 $regs = array();
2062 preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs);
2063 $imgName = $regs[1];
2064 $this->images_encoded[$i]['name'] = $imgName;
2065 $this->images_encoded[$i]['fullpath'] = $fullpath;
2066 $this->images_encoded[$i]['content_type'] = $img["content_type"];
2067 $this->images_encoded[$i]['cid'] = $img["cid"];
2068 // Encodage de l'image
2069 $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
2070 $inline[] = $fullpath;
2071 }
2072 }
2073 $i++;
2074 }
2075 } else {
2076 return -1;
2077 }
2078
2079 return 1;
2080 } else {
2081 return 0;
2082 }
2083 }
2084
2092 private function findHtmlImagesIsSrcData($images_dir)
2093 {
2094 global $conf;
2095
2096 require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
2097
2098 // Build the array of image extensions
2099 $extensions = array_keys($this->image_types);
2100
2101 if (empty($images_dir)) {
2102 //$images_dir = $conf->admin->dir_output.'/temp/'.uniqid('cmailfile');
2103 $images_dir = $conf->admin->dir_output.'/temp/cmailfile';
2104 }
2105
2106 if ($images_dir && !dol_is_dir($images_dir)) {
2107 dol_mkdir($images_dir, DOL_DATA_ROOT);
2108 }
2109
2110 // Uncomment this for debug
2111 /*
2112 global $dolibarr_main_data_root;
2113 $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
2114 $fp = fopen($outputfile, "w+");
2115 fwrite($fp, $this->html);
2116 fclose($fp);
2117 */
2118
2119 // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
2120 // For example when:
2121 // <img alt="" src="/src="data:image....;base64,...." />
2122 $matches = array();
2123 preg_match_all('/src="data:image\/('.implode('|', $extensions).');base64,([^"]+)"/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
2124
2125 if (!empty($matches) && !empty($matches[1])) {
2126 if (empty($images_dir)) {
2127 // No temp directory provided, so we are not able to support conversion of data:image into physical images.
2128 $this->errors[] = 'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
2129 return -1;
2130 }
2131
2132 $i = count($this->html_images);
2133 foreach ($matches[1] as $key => $ext) {
2134 // We save the image to send in disk
2135 $filecontent = $matches[2][$key];
2136
2137 $cid = 'cid000'.dol_hash($filecontent, 'md5'); // The id must not change if image is same
2138
2139 $destfiletmp = $images_dir.'/'.$cid.'.'.$ext;
2140
2141 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)
2142 dol_syslog("write the cid file ".$destfiletmp);
2143 $fhandle = @fopen($destfiletmp, 'w');
2144 if ($fhandle) {
2145 $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
2146 fclose($fhandle);
2147 dolChmod($destfiletmp);
2148 } else {
2149 $this->errors[] = "Failed to open file '".$destfiletmp."' for write";
2150 return -2;
2151 }
2152 }
2153
2154 if (file_exists($destfiletmp)) {
2155 // Image full path
2156 $this->html_images[$i]["fullpath"] = $destfiletmp;
2157 // Image name
2158 $this->html_images[$i]["name"] = basename($destfiletmp);
2159 // Content type
2160 $this->html_images[$i]["content_type"] = $this->image_types[strtolower($ext)];
2161 // cid
2162 $this->html_images[$i]["cid"] = $cid;
2163 // type
2164 $this->html_images[$i]["type"] = 'cidfromdata';
2165
2166 $this->html = str_replace('src="data:image/'.$ext.';base64,'.$filecontent.'"', 'src="cid:'.$this->html_images[$i]["cid"].'"', $this->html);
2167 }
2168 $i++;
2169 }
2170
2171 return 1;
2172 } else {
2173 return 0;
2174 }
2175 }
2176
2192 public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
2193 {
2194 global $conf;
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 }
2237 }
2238
2239 $ret = ($ret ? $ret.',' : '').$newemail;
2240
2241 // Stop if we have too much records
2242 if ($maxnumberofemail && $i >= $maxnumberofemail) {
2243 if (count($arrayaddress) > $maxnumberofemail) {
2244 $ret .= '...';
2245 }
2246 break;
2247 }
2248 }
2249 }
2250
2251 return $ret;
2252 }
2253
2261 public static function getArrayAddress($address)
2262 {
2263 $ret = array();
2264
2265 $arrayaddress = explode(',', $address);
2266
2267 // Boucle sur chaque composant de l'address
2268 foreach ($arrayaddress as $val) {
2269 $regs = array();
2270 if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
2271 $name = trim($regs[1]);
2272 $email = trim($regs[2]);
2273 } else {
2274 $name = null;
2275 $email = trim($val);
2276 }
2277
2278 $ret[$email] = getDolGlobalString('MAIN_MAIL_NO_FULL_EMAIL') ? null : $name;
2279 }
2280
2281 return $ret;
2282 }
2283}
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.
getSupportedOauth2Array()
Return array of tabs to used on pages to setup cron module.
dol_hash($chain, $type='0', $nosalt=0)
Returns a hash (non reversible encryption) of a string.