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