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