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