CMailFile.class.php 77 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050
  1. <?php
  2. /**
  3. * Copyright (C) Dan Potter
  4. * Copyright (C) Eric Seigne
  5. * Copyright (C) 2000-2005 Rodolphe Quiedeville <rodolphe@quiedeville.org>
  6. * Copyright (C) 2003 Jean-Louis Bergamo <jlb@j1b.org>
  7. * Copyright (C) 2004-2015 Laurent Destailleur <eldy@users.sourceforge.net>
  8. * Copyright (C) 2005-2012 Regis Houssin <regis.houssin@inodbox.com>
  9. * Copyright (C) 2019-2023 Frédéric France <frederic.france@netlogic.fr>
  10. *
  11. * This program is free software; you can redistribute it and/or modify
  12. * it under the terms of the GNU General Public License as published by
  13. * the Free Software Foundation; either version 3 of the License, or
  14. * (at your option) any later version.
  15. *
  16. * This program is distributed in the hope that it will be useful,
  17. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. * GNU General Public License for more details.
  20. *
  21. * You should have received a copy of the GNU General Public License
  22. * along with this program. If not, see <https://www.gnu.org/licenses/>.
  23. * or see https://www.gnu.org/
  24. *
  25. * Lots of code inspired from Dan Potter's CMailFile class
  26. */
  27. /**
  28. * \file htdocs/core/class/CMailFile.class.php
  29. * \brief File of class to send emails (with attachments or not)
  30. */
  31. use OAuth\Common\Storage\DoliStorage;
  32. use OAuth\Common\Consumer\Credentials;
  33. /**
  34. * Class to send emails (with attachments or not)
  35. * Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext,$replyto);
  36. * $mailfile->sendfile();
  37. */
  38. class CMailFile
  39. {
  40. public $sendcontext;
  41. public $sendmode;
  42. public $sendsetup;
  43. /**
  44. * @var string Subject of email
  45. */
  46. public $subject;
  47. 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).
  48. // Sender: Who send the email ("Sender" has sent emails on behalf of "From").
  49. // Use it when the "From" is an email of a domain that is a SPF protected domain, and sending smtp server is not this domain. In such case, add Sender field with an email of the protected domain.
  50. // Return-Path: Email where to send bounds.
  51. 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)
  52. public $errors_to; // Errors-To: Email where to send errors.
  53. public $addr_to;
  54. public $addr_cc;
  55. public $addr_bcc;
  56. public $trackid;
  57. public $mixed_boundary;
  58. public $related_boundary;
  59. public $alternative_boundary;
  60. public $deliveryreceipt;
  61. public $atleastonefile;
  62. public $msg;
  63. public $eol;
  64. public $eol2;
  65. /**
  66. * @var string Error code (or message)
  67. */
  68. public $error = '';
  69. /**
  70. * @var string[] Array of Error code (or message)
  71. */
  72. public $errors = array();
  73. public $smtps; // Contains SMTPs object (if this method is used)
  74. public $phpmailer; // Contains PHPMailer object (if this method is used)
  75. /**
  76. * @var Swift_SmtpTransport
  77. */
  78. public $transport;
  79. /**
  80. * @var Swift_Mailer
  81. */
  82. public $mailer;
  83. /**
  84. * @var Swift_Plugins_Loggers_ArrayLogger
  85. */
  86. public $logger;
  87. /**
  88. * @var string CSS
  89. */
  90. public $css;
  91. //! Defined css style for body background
  92. public $styleCSS;
  93. //! Defined background directly in body tag
  94. public $bodyCSS;
  95. public $msgid;
  96. public $headers;
  97. public $message;
  98. /**
  99. * @var array fullfilenames list (full path of filename on file system)
  100. */
  101. public $filename_list = array();
  102. /**
  103. * @var array mimetypes of files list (List of MIME type of attached files)
  104. */
  105. public $mimetype_list = array();
  106. /**
  107. * @var array filenames list (List of attached file name in message)
  108. */
  109. public $mimefilename_list = array();
  110. /**
  111. * @var array filenames cid
  112. */
  113. public $cid_list = array();
  114. // Image
  115. public $html;
  116. public $msgishtml;
  117. public $image_boundary;
  118. 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).
  119. public $html_images = array();
  120. public $images_encoded = array();
  121. public $image_types = array(
  122. 'gif' => 'image/gif',
  123. 'jpg' => 'image/jpeg',
  124. 'jpeg' => 'image/jpeg',
  125. 'jpe' => 'image/jpeg',
  126. 'bmp' => 'image/bmp',
  127. 'png' => 'image/png',
  128. 'tif' => 'image/tiff',
  129. 'tiff' => 'image/tiff',
  130. );
  131. /**
  132. * CMailFile
  133. *
  134. * @param string $subject Topic/Subject of mail
  135. * @param string $to Recipients emails (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]"). Note: the keyword '__SUPERVISOREMAIL__' is not allowed here and must be replaced by caller.
  136. * @param string $from Sender email (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]")
  137. * @param string $msg Message
  138. * @param array $filename_list List of files to attach (full path of filename on file system)
  139. * @param array $mimetype_list List of MIME type of attached files
  140. * @param array $mimefilename_list List of attached file name in message
  141. * @param string $addr_cc Email cc (Example: 'abc@def.com, ghk@lmn.com')
  142. * @param string $addr_bcc Email bcc (Note: This is autocompleted with MAIN_MAIL_AUTOCOPY_TO if defined)
  143. * @param int $deliveryreceipt Ask a delivery receipt
  144. * @param int $msgishtml 1=String IS already html, 0=String IS NOT html, -1=Unknown make autodetection (with fast mode, not reliable)
  145. * @param string $errors_to Email for errors-to
  146. * @param string $css Css option
  147. * @param string $trackid Tracking string (contains type and id of related element)
  148. * @param string $moreinheader More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'mail' and 'smtps' for the moment)
  149. * @param string $sendcontext 'standard', 'emailing', 'ticket', 'password', ... (used to define which sending mode and parameters to use)
  150. * @param string $replyto Reply-to email (will be set to same value than From by default if not provided)
  151. * @param string $upload_dir_tmp Temporary directory (used to convert images embedded as img src=data:image)
  152. */
  153. 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 = '')
  154. {
  155. global $conf, $dolibarr_main_data_root, $user;
  156. dol_syslog("CMailFile::CMailfile: charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, replyto=$replyto trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
  157. dol_syslog("CMailFile::CMailfile: subject=".$subject.", deliveryreceipt=".$deliveryreceipt.", msgishtml=".$msgishtml, LOG_DEBUG);
  158. // Clean values of $mimefilename_list
  159. if (is_array($mimefilename_list)) {
  160. foreach ($mimefilename_list as $key => $val) {
  161. $mimefilename_list[$key] = dol_string_unaccent($mimefilename_list[$key]);
  162. }
  163. }
  164. $cid_list = array();
  165. $this->sendcontext = $sendcontext;
  166. // Define this->sendmode ('mail', 'smtps', 'swiftmailer', ...) according to $sendcontext ('standard', 'emailing', 'ticket', 'password')
  167. $this->sendmode = '';
  168. if (!empty($this->sendcontext)) {
  169. $smtpContextKey = strtoupper($this->sendcontext);
  170. $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
  171. if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
  172. $this->sendmode = $smtpContextSendMode;
  173. }
  174. }
  175. if (empty($this->sendmode)) {
  176. $this->sendmode = (!empty($conf->global->MAIN_MAIL_SENDMODE) ? $conf->global->MAIN_MAIL_SENDMODE : 'mail');
  177. }
  178. // We define end of line (RFC 821).
  179. $this->eol = "\r\n";
  180. // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
  181. $this->eol2 = "\r\n";
  182. if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
  183. $this->eol = "\n";
  184. $this->eol2 = "\n";
  185. $moreinheader = str_replace("\r\n", "\n", $moreinheader);
  186. }
  187. // On defini mixed_boundary
  188. $this->mixed_boundary = "multipart_x.".time().".x_boundary";
  189. // On defini related_boundary
  190. $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contain special chars)
  191. // On defini alternative_boundary
  192. $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contain special chars)
  193. if (empty($subject)) {
  194. dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
  195. $this->error = 'ErrorSubjectIsRequired';
  196. return;
  197. }
  198. if (empty($msg)) {
  199. dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
  200. $msg = '.'; // Avoid empty message (with empty message content, you will see a multipart structure)
  201. }
  202. // Detect if message is HTML (use fast method)
  203. if ($msgishtml == -1) {
  204. $this->msgishtml = 0;
  205. if (dol_textishtml($msg)) {
  206. $this->msgishtml = 1;
  207. }
  208. } else {
  209. $this->msgishtml = $msgishtml;
  210. }
  211. global $dolibarr_main_url_root;
  212. // Define $urlwithroot
  213. $urlwithouturlroot = preg_replace('/'.preg_quote(DOL_URL_ROOT, '/').'$/i', '', trim($dolibarr_main_url_root));
  214. $urlwithroot = $urlwithouturlroot.DOL_URL_ROOT; // This is to use external domain name found into config file
  215. //$urlwithroot=DOL_MAIN_URL_ROOT; // This is to use same domain name than current
  216. // Replace relative /viewimage to absolute path
  217. $msg = preg_replace('/src="'.preg_quote(DOL_URL_ROOT, '/').'\/viewimage\.php/ims', 'src="'.$urlwithroot.'/viewimage.php', $msg, -1);
  218. if (!empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) {
  219. $this->msgishtml = 1; // To force to send everything with content type html.
  220. }
  221. // Detect images
  222. if ($this->msgishtml) {
  223. $this->html = $msg;
  224. $findimg = 0;
  225. if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS)) { // Off by default
  226. // Search into the body for <img tags of links in medias files to replace them with an embedded file
  227. // Note because media links are public, this should be useless, except avoid blocking images with email browser.
  228. // This convert an embedd file with src="/viewimage.php?modulepart... into a cid link
  229. // TODO Exclude viewimage used for the read tracker ?
  230. $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
  231. }
  232. if (!empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA)) {
  233. // Search into the body for <img src="data:image/ext;base64,..." to replace them with an embedded file
  234. // This convert an embedded file with src="data:image... into a cid link + attached file
  235. $findimg = $this->findHtmlImagesIsSrcData($upload_dir_tmp);
  236. }
  237. // Set atleastoneimage if there is at least one embedded file (into ->html_images)
  238. if ($findimg > 0) {
  239. foreach ($this->html_images as $i => $val) {
  240. if ($this->html_images[$i]) {
  241. $this->atleastoneimage = 1;
  242. if ($this->html_images[$i]['type'] == 'cidfromdata') {
  243. if (!in_array($this->html_images[$i]['fullpath'], $filename_list)) {
  244. // If this file path is not already into the $filename_list, we add it.
  245. $posindice = count($filename_list);
  246. $filename_list[$posindice] = $this->html_images[$i]['fullpath'];
  247. $mimetype_list[$posindice] = $this->html_images[$i]['content_type'];
  248. $mimefilename_list[$posindice] = $this->html_images[$i]['name'];
  249. } else {
  250. $posindice = array_search($this->html_images[$i]['fullpath'], $filename_list);
  251. }
  252. // We complete the array of cid_list
  253. $cid_list[$posindice] = $this->html_images[$i]['cid'];
  254. }
  255. dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
  256. }
  257. }
  258. }
  259. }
  260. //var_dump($filename_list);
  261. //var_dump($cid_list);exit;
  262. // Set atleastoneimage if there is at least one file (into $filename_list array)
  263. if (is_array($filename_list)) {
  264. foreach ($filename_list as $i => $val) {
  265. if ($filename_list[$i]) {
  266. $this->atleastonefile = 1;
  267. 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]=".$cid_list[$i], LOG_DEBUG);
  268. }
  269. }
  270. }
  271. // Add auto copy to if not already in $to (Note: Adding bcc for specific modules are also done from pages)
  272. // For example MAIN_MAIL_AUTOCOPY_TO can be 'email@example.com, __USER_EMAIL__, ...'
  273. if (!empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) {
  274. $listofemailstoadd = explode(',', $conf->global->MAIN_MAIL_AUTOCOPY_TO);
  275. foreach ($listofemailstoadd as $key => $val) {
  276. $emailtoadd = $listofemailstoadd[$key];
  277. if (trim($emailtoadd) == '__USER_EMAIL__') {
  278. if (!empty($user) && !empty($user->email)) {
  279. $emailtoadd = $user->email;
  280. } else {
  281. $emailtoadd = '';
  282. }
  283. }
  284. if ($emailtoadd && preg_match('/'.preg_quote($emailtoadd, '/').'/i', $to)) {
  285. $emailtoadd = ''; // Email already in the "To"
  286. }
  287. if ($emailtoadd) {
  288. $listofemailstoadd[$key] = $emailtoadd;
  289. } else {
  290. unset($listofemailstoadd[$key]);
  291. }
  292. }
  293. if (!empty($listofemailstoadd)) {
  294. $addr_bcc .= ($addr_bcc ? ', ' : '').join(', ', $listofemailstoadd);
  295. }
  296. }
  297. $this->subject = $subject;
  298. $this->addr_to = dol_sanitizeEmail($to);
  299. $this->addr_from = dol_sanitizeEmail($from);
  300. $this->msg = $msg;
  301. $this->addr_cc = dol_sanitizeEmail($addr_cc);
  302. $this->addr_bcc = dol_sanitizeEmail($addr_bcc);
  303. $this->deliveryreceipt = $deliveryreceipt;
  304. if (empty($replyto)) {
  305. $replyto = dol_sanitizeEmail($from);
  306. }
  307. $this->reply_to = dol_sanitizeEmail($replyto);
  308. $this->errors_to = dol_sanitizeEmail($errors_to);
  309. $this->trackid = $trackid;
  310. // Set arrays with attached files info
  311. $this->filename_list = $filename_list;
  312. $this->mimetype_list = $mimetype_list;
  313. $this->mimefilename_list = $mimefilename_list;
  314. $this->cid_list = $cid_list;
  315. if (!empty($conf->global->MAIN_MAIL_FORCE_SENDTO)) {
  316. $this->addr_to = dol_sanitizeEmail($conf->global->MAIN_MAIL_FORCE_SENDTO);
  317. $this->addr_cc = '';
  318. $this->addr_bcc = '';
  319. }
  320. $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
  321. if (!empty($this->sendcontext)) {
  322. $smtpContextKey = strtoupper($this->sendcontext);
  323. $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
  324. if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
  325. $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
  326. }
  327. }
  328. dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." addr_bcc=$addr_bcc, replyto=$replyto", LOG_DEBUG);
  329. // We set all data according to choosed sending method.
  330. // We also set a value for ->msgid
  331. if ($this->sendmode == 'mail') {
  332. // Use mail php function (default PHP method)
  333. // ------------------------------------------
  334. $smtp_headers = "";
  335. $mime_headers = "";
  336. $text_body = "";
  337. $files_encoded = "";
  338. // Define smtp_headers (this also set ->msgid)
  339. $smtp_headers = $this->write_smtpheaders();
  340. if (!empty($moreinheader)) {
  341. $smtp_headers .= $moreinheader; // $moreinheader contains the \r\n
  342. }
  343. // Define mime_headers
  344. $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
  345. if (!empty($this->html)) {
  346. if (!empty($css)) {
  347. $this->css = $css;
  348. $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
  349. }
  350. $msg = $this->html;
  351. }
  352. // Define body in text_body
  353. $text_body = $this->write_body($msg);
  354. // Add attachments to text_encoded
  355. if (!empty($this->atleastonefile)) {
  356. $files_encoded = $this->write_files($filename_list, $mimetype_list, $mimefilename_list, $cid_list);
  357. }
  358. // We now define $this->headers and $this->message
  359. $this->headers = $smtp_headers.$mime_headers;
  360. // On nettoie le header pour qu'il ne se termine pas par un retour chariot.
  361. // This avoid also empty lines at end that can be interpreted as mail injection by email servers.
  362. $this->headers = preg_replace("/([\r\n]+)$/i", "", $this->headers);
  363. //$this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
  364. $this->message = 'This is a message with multiple parts in MIME format.'.$this->eol;
  365. $this->message .= $text_body.$files_encoded;
  366. $this->message .= "--".$this->mixed_boundary."--".$this->eol;
  367. } elseif ($this->sendmode == 'smtps') {
  368. // Use SMTPS library
  369. // ------------------------------------------
  370. require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
  371. $smtps = new SMTPs();
  372. $smtps->setCharSet($conf->file->character_set_client);
  373. // Encode subject if required.
  374. $subjecttouse = $this->subject;
  375. if (!ascii_check($subjecttouse)) {
  376. $subjecttouse = $this->encodetorfc2822($subjecttouse);
  377. }
  378. $smtps->setSubject($subjecttouse);
  379. $smtps->setTO($this->getValidAddress($this->addr_to, 0, 1));
  380. $smtps->setFrom($this->getValidAddress($this->addr_from, 0, 1));
  381. $smtps->setTrackId($this->trackid);
  382. $smtps->setReplyTo($this->getValidAddress($this->reply_to, 0, 1));
  383. if (!empty($moreinheader)) {
  384. $smtps->setMoreInHeader($moreinheader);
  385. }
  386. if (!empty($this->html)) {
  387. if (!empty($css)) {
  388. $this->css = $css;
  389. $this->buildCSS();
  390. }
  391. $msg = $this->html;
  392. $msg = $this->checkIfHTML($msg);
  393. }
  394. // Replace . alone on a new line with .. to avoid to have SMTP interpret this as end of message
  395. $msg = preg_replace('/(\r|\n)\.(\r|\n)/ims', '\1..\2', $msg);
  396. if ($this->msgishtml) {
  397. $smtps->setBodyContent($msg, 'html');
  398. } else {
  399. $smtps->setBodyContent($msg, 'plain');
  400. }
  401. if ($this->atleastoneimage) {
  402. foreach ($this->images_encoded as $img) {
  403. $smtps->setImageInline($img['image_encoded'], $img['name'], $img['content_type'], $img['cid']);
  404. }
  405. }
  406. if (!empty($this->atleastonefile)) {
  407. foreach ($filename_list as $i => $val) {
  408. $content = file_get_contents($filename_list[$i]);
  409. $smtps->setAttachment($content, $mimefilename_list[$i], $mimetype_list[$i], $cid_list[$i]);
  410. }
  411. }
  412. $smtps->setCC($this->addr_cc);
  413. $smtps->setBCC($this->addr_bcc);
  414. $smtps->setErrorsTo($this->errors_to);
  415. $smtps->setDeliveryReceipt($this->deliveryreceipt);
  416. if (!empty($conf->global->$keyforsslseflsigned)) {
  417. $smtps->setOptions(array('ssl' => array('verify_peer' => false, 'verify_peer_name' => false, 'allow_self_signed' => true)));
  418. }
  419. $host = dol_getprefix('email');
  420. $this->msgid = time().'.SMTPs-dolibarr-'.$this->trackid.'@'.$host;
  421. $this->smtps = $smtps;
  422. } elseif ($this->sendmode == 'swiftmailer') {
  423. // Use Swift Mailer library
  424. $host = dol_getprefix('email');
  425. require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lexer/lib/Doctrine/Common/Lexer/AbstractLexer.php';
  426. // egulias autoloader lib
  427. require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/autoload.php';
  428. require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
  429. // Create the message
  430. //$this->message = Swift_Message::newInstance();
  431. $this->message = new Swift_Message();
  432. //$this->message = new Swift_SignedMessage();
  433. // Adding a trackid header to a message
  434. $headers = $this->message->getHeaders();
  435. $headers->addTextHeader('X-Dolibarr-TRACKID', $this->trackid.'@'.$host);
  436. $this->msgid = time().'.swiftmailer-dolibarr-'.$this->trackid.'@'.$host;
  437. $headerID = $this->msgid;
  438. $msgid = $headers->get('Message-ID');
  439. $msgid->setId($headerID);
  440. $headers->addIdHeader('References', $headerID);
  441. // TODO if (!empty($moreinheader)) ...
  442. // Give the message a subject
  443. try {
  444. $this->message->setSubject($this->subject);
  445. } catch (Exception $e) {
  446. $this->errors[] = $e->getMessage();
  447. }
  448. // Set the From address with an associative array
  449. //$this->message->setFrom(array('john@doe.com' => 'John Doe'));
  450. if (!empty($this->addr_from)) {
  451. try {
  452. if (!empty($conf->global->MAIN_FORCE_DISABLE_MAIL_SPOOFING)) {
  453. // Prevent email spoofing for smtp server with a strict configuration
  454. $regexp = '/([a-z0-9_\.\-\+])+\@(([a-z0-9\-])+\.)+([a-z0-9]{2,4})+/i'; // This regular expression extracts all emails from a string
  455. $adressEmailFrom = array();
  456. $emailMatchs = preg_match_all($regexp, $from, $adressEmailFrom);
  457. $adressEmailFrom = reset($adressEmailFrom);
  458. if ($emailMatchs !== false && filter_var($conf->global->MAIN_MAIL_SMTPS_ID, FILTER_VALIDATE_EMAIL) && $conf->global->MAIN_MAIL_SMTPS_ID !== $adressEmailFrom) {
  459. $this->message->setFrom($conf->global->MAIN_MAIL_SMTPS_ID);
  460. } else {
  461. $this->message->setFrom($this->getArrayAddress($this->addr_from));
  462. }
  463. } else {
  464. $this->message->setFrom($this->getArrayAddress($this->addr_from));
  465. }
  466. } catch (Exception $e) {
  467. $this->errors[] = $e->getMessage();
  468. }
  469. }
  470. // Set the To addresses with an associative array
  471. if (!empty($this->addr_to)) {
  472. try {
  473. $this->message->setTo($this->getArrayAddress($this->addr_to));
  474. } catch (Exception $e) {
  475. $this->errors[] = $e->getMessage();
  476. }
  477. }
  478. if (!empty($this->reply_to)) {
  479. try {
  480. $this->message->SetReplyTo($this->getArrayAddress($this->reply_to));
  481. } catch (Exception $e) {
  482. $this->errors[] = $e->getMessage();
  483. }
  484. }
  485. if (!empty($this->errors_to)) {
  486. try {
  487. $headers->addTextHeader('Errors-To', $this->getArrayAddress($this->errors_to));
  488. } catch (Exception $e) {
  489. $this->errors[] = $e->getMessage();
  490. }
  491. }
  492. try {
  493. $this->message->setCharSet($conf->file->character_set_client);
  494. } catch (Exception $e) {
  495. $this->errors[] = $e->getMessage();
  496. }
  497. if (!empty($this->html)) {
  498. if (!empty($css)) {
  499. $this->css = $css;
  500. $this->buildCSS();
  501. }
  502. $msg = $this->html;
  503. $msg = $this->checkIfHTML($msg);
  504. }
  505. if ($this->atleastoneimage) {
  506. foreach ($this->images_encoded as $img) {
  507. //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
  508. $attachment = Swift_Image::fromPath($img['fullpath']);
  509. // embed image
  510. $imgcid = $this->message->embed($attachment);
  511. // replace cid by the one created by swiftmail in html message
  512. $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
  513. }
  514. }
  515. if ($this->msgishtml) {
  516. $this->message->setBody($msg, 'text/html');
  517. // And optionally an alternative body
  518. $this->message->addPart(html_entity_decode(strip_tags($msg)), 'text/plain');
  519. } else {
  520. $this->message->setBody($msg, 'text/plain');
  521. // And optionally an alternative body
  522. $this->message->addPart(dol_nl2br($msg), 'text/html');
  523. }
  524. if (!empty($this->atleastonefile)) {
  525. foreach ($filename_list as $i => $val) {
  526. //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
  527. $attachment = Swift_Attachment::fromPath($filename_list[$i], $mimetype_list[$i]);
  528. if (!empty($mimefilename_list[$i])) {
  529. $attachment->setFilename($mimefilename_list[$i]);
  530. }
  531. $this->message->attach($attachment);
  532. }
  533. }
  534. if (!empty($this->addr_cc)) {
  535. try {
  536. $this->message->setCc($this->getArrayAddress($this->addr_cc));
  537. } catch (Exception $e) {
  538. $this->errors[] = $e->getMessage();
  539. }
  540. }
  541. if (!empty($this->addr_bcc)) {
  542. try {
  543. $this->message->setBcc($this->getArrayAddress($this->addr_bcc));
  544. } catch (Exception $e) {
  545. $this->errors[] = $e->getMessage();
  546. }
  547. }
  548. //if (!empty($this->errors_to)) $this->message->setErrorsTo($this->getArrayAddress($this->errors_to));
  549. if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
  550. try {
  551. $this->message->setReadReceiptTo($this->getArrayAddress($this->addr_from));
  552. } catch (Exception $e) {
  553. $this->errors[] = $e->getMessage();
  554. }
  555. }
  556. } else {
  557. // Send mail method not correctly defined
  558. // --------------------------------------
  559. $this->error = 'Bad value for sendmode';
  560. }
  561. }
  562. /**
  563. * Send mail that was prepared by constructor.
  564. *
  565. * @return boolean True if mail sent, false otherwise
  566. */
  567. public function sendfile()
  568. {
  569. global $conf, $db, $langs, $hookmanager;
  570. $errorlevel = error_reporting();
  571. //error_reporting($errorlevel ^ E_WARNING); // Desactive warnings
  572. $res = false;
  573. if (empty($conf->global->MAIN_DISABLE_ALL_MAILS)) {
  574. if (!is_object($hookmanager)) {
  575. include_once DOL_DOCUMENT_ROOT.'/core/class/hookmanager.class.php';
  576. $hookmanager = new HookManager($db);
  577. }
  578. $hookmanager->initHooks(array('mail'));
  579. $parameters = array();
  580. $action = '';
  581. $reshook = $hookmanager->executeHooks('sendMail', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  582. if ($reshook < 0) {
  583. $this->error = "Error in hook maildao sendMail ".$reshook;
  584. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  585. return $reshook;
  586. }
  587. if ($reshook == 1) { // Hook replace standard code
  588. return true;
  589. }
  590. $sendingmode = $this->sendmode;
  591. if ($this->sendcontext == 'emailing' && !empty($conf->global->MAILING_NO_USING_PHPMAIL) && $sendingmode == 'mail') {
  592. // List of sending methods
  593. $listofmethods = array();
  594. $listofmethods['mail'] = 'PHP mail function';
  595. //$listofmethods['simplemail']='Simplemail class';
  596. $listofmethods['smtps'] = 'SMTP/SMTPS socket library';
  597. // 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.
  598. // You ensure that every user is using its own SMTP server when using the mass emailing module.
  599. $linktoadminemailbefore = '<a href="'.DOL_URL_ROOT.'/admin/mails.php">';
  600. $linktoadminemailend = '</a>';
  601. $this->error = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
  602. $this->errors[] = $langs->trans("MailSendSetupIs", $listofmethods[$sendingmode]);
  603. $this->error .= '<br>'.$langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
  604. $this->errors[] = $langs->trans("MailSendSetupIs2", $linktoadminemailbefore, $linktoadminemailend, $langs->transnoentitiesnoconv("MAIN_MAIL_SENDMODE"), $listofmethods['smtps']);
  605. if (!empty($conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS)) {
  606. $this->error .= '<br>'.$langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
  607. $this->errors[] = $langs->trans("MailSendSetupIs3", $conf->global->MAILING_SMTP_SETUP_EMAILS_FOR_QUESTIONS);
  608. }
  609. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
  610. return false;
  611. }
  612. // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
  613. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) {
  614. $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL = 10;
  615. }
  616. $tmparray1 = explode(',', $this->addr_to);
  617. if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL) {
  618. $this->error = 'Too much recipients in to:';
  619. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
  620. return false;
  621. }
  622. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) {
  623. $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL = 10;
  624. }
  625. $tmparray2 = explode(',', $this->addr_cc);
  626. if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL) {
  627. $this->error = 'Too much recipients in cc:';
  628. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
  629. return false;
  630. }
  631. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) {
  632. $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL = 10;
  633. }
  634. $tmparray3 = explode(',', $this->addr_bcc);
  635. if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL) {
  636. $this->error = 'Too much recipients in bcc:';
  637. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
  638. return false;
  639. }
  640. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) {
  641. $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL = 10;
  642. }
  643. if ((count($tmparray1) + count($tmparray2) + count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL) {
  644. $this->error = 'Too much recipients in to:, cc:, bcc:';
  645. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_WARNING);
  646. return false;
  647. }
  648. $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
  649. $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
  650. $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
  651. $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
  652. $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
  653. $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
  654. $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
  655. $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
  656. $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
  657. if (!empty($this->sendcontext)) {
  658. $smtpContextKey = strtoupper($this->sendcontext);
  659. $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
  660. if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
  661. $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
  662. $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
  663. $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
  664. $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
  665. $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
  666. $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
  667. $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
  668. $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
  669. $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
  670. }
  671. }
  672. // Action according to choosed sending method
  673. if ($this->sendmode == 'mail') {
  674. // Use mail php function (default PHP method)
  675. // ------------------------------------------
  676. dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
  677. //dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
  678. //dol_syslog("CMailFile::sendfile message=\n".$message);
  679. // If Windows, sendmail_from must be defined
  680. if (isset($_SERVER["WINDIR"])) {
  681. if (empty($this->addr_from)) {
  682. $this->addr_from = 'robot@example.com';
  683. }
  684. @ini_set('sendmail_from', $this->getValidAddress($this->addr_from, 2));
  685. }
  686. // Force parameters
  687. //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".$conf->global->$keyforsmtpserver." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG);
  688. if (!empty($conf->global->$keyforsmtpserver)) {
  689. ini_set('SMTP', $conf->global->$keyforsmtpserver);
  690. }
  691. if (!empty($conf->global->$keyforsmtpport)) {
  692. ini_set('smtp_port', $conf->global->$keyforsmtpport);
  693. }
  694. $res = true;
  695. if ($res && !$this->subject) {
  696. $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Subject is empty";
  697. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  698. $res = false;
  699. }
  700. $dest = $this->getValidAddress($this->addr_to, 2);
  701. if ($res && !$dest) {
  702. $this->error = "Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
  703. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  704. $res = false;
  705. }
  706. if ($res) {
  707. $additionnalparam = ''; // By default
  708. if (!empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F)) {
  709. // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
  710. // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
  711. // Having this variable defined may create problems with some sendmail (option -f refused)
  712. // Having this variable not defined may create problems with some other sendmail (option -f required)
  713. $additionnalparam .= ($additionnalparam ? ' ' : '').(!empty($conf->global->MAIN_MAIL_ERRORS_TO) ? '-f'.$this->getValidAddress($conf->global->MAIN_MAIL_ERRORS_TO, 2) : ($this->addr_from != '' ? '-f'.$this->getValidAddress($this->addr_from, 2) : ''));
  714. }
  715. if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) { // To force usage of -ba option. This option tells sendmail to read From: or Sender: to setup sender
  716. $additionnalparam .= ($additionnalparam ? ' ' : '').'-ba';
  717. }
  718. if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) {
  719. $additionnalparam .= ($additionnalparam ? ' ' : '').'-U '.$additionnalparam; // Use -U to add additionnal params
  720. }
  721. $linuxlike = 1;
  722. if (preg_match('/^win/i', PHP_OS)) {
  723. $linuxlike = 0;
  724. }
  725. if (preg_match('/^mac/i', PHP_OS)) {
  726. $linuxlike = 0;
  727. }
  728. dol_syslog("CMailFile::sendfile: mail start".($linuxlike ? '' : " HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')).", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
  729. $this->message = stripslashes($this->message);
  730. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  731. $this->dump_mail();
  732. }
  733. // Encode subject if required.
  734. $subjecttouse = $this->subject;
  735. if (!ascii_check($subjecttouse)) {
  736. $subjecttouse = $this->encodetorfc2822($subjecttouse);
  737. }
  738. if (!empty($additionnalparam)) {
  739. $res = mail($dest, $subjecttouse, $this->message, $this->headers, $additionnalparam);
  740. } else {
  741. $res = mail($dest, $subjecttouse, $this->message, $this->headers);
  742. }
  743. if (!$res) {
  744. $langs->load("errors");
  745. $this->error = "Failed to send mail with php mail";
  746. if (!$linuxlike) {
  747. $this->error .= " to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
  748. }
  749. $this->error .= ".<br>";
  750. $this->error .= $langs->trans("ErrorPhpMailDelivery");
  751. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  752. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  753. $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
  754. }
  755. } else {
  756. dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
  757. }
  758. }
  759. if (isset($_SERVER["WINDIR"])) {
  760. @ini_restore('sendmail_from');
  761. }
  762. // Restore parameters
  763. if (!empty($conf->global->$keyforsmtpserver)) {
  764. ini_restore('SMTP');
  765. }
  766. if (!empty($conf->global->$keyforsmtpport)) {
  767. ini_restore('smtp_port');
  768. }
  769. } elseif ($this->sendmode == 'smtps') {
  770. if (!is_object($this->smtps)) {
  771. $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport."<br>Constructor of object CMailFile was not initialized without errors.";
  772. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  773. return false;
  774. }
  775. // Use SMTPS library
  776. // ------------------------------------------
  777. $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
  778. // Clean parameters
  779. if (empty($conf->global->$keyforsmtpserver)) {
  780. $conf->global->$keyforsmtpserver = ini_get('SMTP');
  781. }
  782. if (empty($conf->global->$keyforsmtpport)) {
  783. $conf->global->$keyforsmtpport = ini_get('smtp_port');
  784. }
  785. // If we use SSL/TLS
  786. $server = $conf->global->$keyforsmtpserver;
  787. $secure = '';
  788. if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
  789. $secure = 'ssl';
  790. }
  791. if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
  792. $secure = 'tls';
  793. }
  794. $server = ($secure ? $secure.'://' : '').$server;
  795. $port = $conf->global->$keyforsmtpport;
  796. $this->smtps->setHost($server);
  797. $this->smtps->setPort($port); // 25, 465...;
  798. $loginid = '';
  799. $loginpass = '';
  800. if (!empty($conf->global->$keyforsmtpid)) {
  801. $loginid = $conf->global->$keyforsmtpid;
  802. $this->smtps->setID($loginid);
  803. }
  804. if (!empty($conf->global->$keyforsmtppw)) {
  805. $loginpass = $conf->global->$keyforsmtppw;
  806. $this->smtps->setPW($loginpass);
  807. }
  808. if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
  809. require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
  810. $keyforsupportedoauth2array = $conf->global->$keyforsmtpoauthservice;
  811. if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
  812. $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
  813. } else {
  814. $keyforprovider = '';
  815. }
  816. $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
  817. $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
  818. if (isset($supportedoauth2array)) {
  819. $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
  820. } else {
  821. $OAUTH_SERVICENAME = 'Unknown';
  822. }
  823. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  824. $storage = new DoliStorage($db, $conf, $keyforprovider);
  825. try {
  826. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  827. $expire = false;
  828. // Is token expired or will token expire in the next 30 seconds
  829. if (is_object($tokenobj)) {
  830. $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
  831. }
  832. // Token expired so we refresh it
  833. if (is_object($tokenobj) && $expire) {
  834. $credentials = new Credentials(
  835. getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_ID'),
  836. getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_SECRET'),
  837. getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_URLAUTHORIZE')
  838. );
  839. $serviceFactory = new \OAuth\ServiceFactory();
  840. $oauthname = explode('-', $OAUTH_SERVICENAME);
  841. // ex service is Google-Emails we need only the first part Google
  842. $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
  843. // We have to save the token because Google give it only once
  844. $refreshtoken = $tokenobj->getRefreshToken();
  845. $tokenobj = $apiService->refreshAccessToken($tokenobj);
  846. $tokenobj->setRefreshToken($refreshtoken);
  847. $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
  848. }
  849. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  850. if (is_object($tokenobj)) {
  851. $this->smtps->setToken($tokenobj->getAccessToken());
  852. } else {
  853. $this->error = "Token not found";
  854. }
  855. } catch (Exception $e) {
  856. // Return an error if token not found
  857. $this->error = $e->getMessage();
  858. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  859. }
  860. }
  861. $res = true;
  862. $from = $this->smtps->getFrom('org');
  863. if ($res && !$from) {
  864. $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - Sender address '$from' invalid";
  865. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  866. $res = false;
  867. }
  868. $dest = $this->smtps->getTo();
  869. if ($res && !$dest) {
  870. $this->error = "Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - Recipient address '$dest' invalid";
  871. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  872. $res = false;
  873. }
  874. if ($res) {
  875. dol_syslog("CMailFile::sendfile: sendMsg, HOST=".$server.", PORT=".$conf->global->$keyforsmtpport, LOG_DEBUG);
  876. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  877. $this->smtps->setDebug(true);
  878. }
  879. $result = $this->smtps->sendMsg();
  880. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  881. $this->dump_mail();
  882. }
  883. if (! $result) {
  884. $smtperrorcode = $this->smtps->lastretval; // SMTP error code
  885. dol_syslog("CMailFile::sendfile: mail SMTP error code ".$smtperrorcode, LOG_WARNING);
  886. if ($smtperrorcode == '421') { // Try later
  887. // TODO Add a delay and try again
  888. /*
  889. dol_syslog("CMailFile::sendfile: Try later error, so we wait and we retry");
  890. sleep(2);
  891. $result = $this->smtps->sendMsg();
  892. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  893. $this->dump_mail();
  894. }
  895. */
  896. }
  897. }
  898. $result = $this->smtps->getErrors(); // applicative error code (not SMTP error code)
  899. if (empty($this->error) && empty($result)) {
  900. dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
  901. $res = true;
  902. } else {
  903. if (empty($this->error)) {
  904. $this->error = $result;
  905. }
  906. dol_syslog("CMailFile::sendfile: mail end error with smtps lib to HOST=".$server.", PORT=".$conf->global->$keyforsmtpport." - ".$this->error, LOG_ERR);
  907. $res = false;
  908. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  909. $this->save_dump_mail_in_err('Mail smtp error '.$smtperrorcode.' with topic '.$this->subject);
  910. }
  911. }
  912. }
  913. } elseif ($this->sendmode == 'swiftmailer') {
  914. // Use Swift Mailer library
  915. // ------------------------------------------
  916. require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
  917. // Clean parameters
  918. if (empty($conf->global->$keyforsmtpserver)) {
  919. $conf->global->$keyforsmtpserver = ini_get('SMTP');
  920. }
  921. if (empty($conf->global->$keyforsmtpport)) {
  922. $conf->global->$keyforsmtpport = ini_get('smtp_port');
  923. }
  924. // If we use SSL/TLS
  925. $server = $conf->global->$keyforsmtpserver;
  926. $secure = '';
  927. if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
  928. $secure = 'ssl';
  929. }
  930. if (!empty($conf->global->$keyforstarttls) && function_exists('openssl_open')) {
  931. $secure = 'tls';
  932. }
  933. $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure);
  934. if (!empty($conf->global->$keyforsmtpid)) {
  935. $this->transport->setUsername($conf->global->$keyforsmtpid);
  936. }
  937. if (!empty($conf->global->$keyforsmtppw) && getDolGlobalString($keyforsmtpauthtype) != "XOAUTH2") {
  938. $this->transport->setPassword($conf->global->$keyforsmtppw);
  939. }
  940. if (getDolGlobalString($keyforsmtpauthtype) === "XOAUTH2") {
  941. require_once DOL_DOCUMENT_ROOT.'/core/lib/oauth.lib.php'; // define $supportedoauth2array
  942. $keyforsupportedoauth2array = getDolGlobalString($keyforsmtpoauthservice);
  943. if (preg_match('/^.*-/', $keyforsupportedoauth2array)) {
  944. $keyforprovider = preg_replace('/^.*-/', '', $keyforsupportedoauth2array);
  945. } else {
  946. $keyforprovider = '';
  947. }
  948. $keyforsupportedoauth2array = preg_replace('/-.*$/', '', $keyforsupportedoauth2array);
  949. $keyforsupportedoauth2array = 'OAUTH_'.$keyforsupportedoauth2array.'_NAME';
  950. $OAUTH_SERVICENAME = (empty($supportedoauth2array[$keyforsupportedoauth2array]['name']) ? 'Unknown' : $supportedoauth2array[$keyforsupportedoauth2array]['name'].($keyforprovider ? '-'.$keyforprovider : ''));
  951. require_once DOL_DOCUMENT_ROOT.'/includes/OAuth/bootstrap.php';
  952. $storage = new DoliStorage($db, $conf, $keyforprovider);
  953. try {
  954. $tokenobj = $storage->retrieveAccessToken($OAUTH_SERVICENAME);
  955. $expire = false;
  956. // Is token expired or will token expire in the next 30 seconds
  957. if (is_object($tokenobj)) {
  958. $expire = ($tokenobj->getEndOfLife() !== -9002 && $tokenobj->getEndOfLife() !== -9001 && time() > ($tokenobj->getEndOfLife() - 30));
  959. }
  960. // Token expired so we refresh it
  961. if (is_object($tokenobj) && $expire) {
  962. $credentials = new Credentials(
  963. getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_ID'),
  964. getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_SECRET'),
  965. getDolGlobalString('OAUTH_'.getDolGlobalString('MAIN_MAIL_SMTPS_OAUTH_SERVICE').'_URLAUTHORIZE')
  966. );
  967. $serviceFactory = new \OAuth\ServiceFactory();
  968. $oauthname = explode('-', $OAUTH_SERVICENAME);
  969. // ex service is Google-Emails we need only the first part Google
  970. $apiService = $serviceFactory->createService($oauthname[0], $credentials, $storage, array());
  971. // We have to save the token because Google give it only once
  972. $refreshtoken = $tokenobj->getRefreshToken();
  973. $tokenobj = $apiService->refreshAccessToken($tokenobj);
  974. $tokenobj->setRefreshToken($refreshtoken);
  975. $storage->storeAccessToken($OAUTH_SERVICENAME, $tokenobj);
  976. }
  977. if (is_object($tokenobj)) {
  978. $this->transport->setAuthMode('XOAUTH2');
  979. $this->transport->setPassword($tokenobj->getAccessToken());
  980. } else {
  981. $this->errors[] = "Token not found";
  982. }
  983. } catch (Exception $e) {
  984. // Return an error if token not found
  985. $this->errors[] = $e->getMessage();
  986. dol_syslog("CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR);
  987. }
  988. }
  989. if (!empty($conf->global->$keyforsslseflsigned)) {
  990. $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false)));
  991. }
  992. //$smtps->_msgReplyTo = 'reply@web.com';
  993. // Switch content encoding to base64 - avoid the doubledot issue with quoted-printable
  994. $contentEncoderBase64 = new Swift_Mime_ContentEncoder_Base64ContentEncoder();
  995. $this->message->setEncoder($contentEncoderBase64);
  996. // Create the Mailer using your created Transport
  997. $this->mailer = new Swift_Mailer($this->transport);
  998. // DKIM SIGN
  999. if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) {
  1000. $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY;
  1001. $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN;
  1002. $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR;
  1003. $signer = new Swift_Signers_DKIMSigner($privateKey, $domainName, $selector);
  1004. $this->message->attachSigner($signer->ignoreHeader('Return-Path'));
  1005. }
  1006. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  1007. // To use the ArrayLogger
  1008. $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
  1009. // Or to use the Echo Logger
  1010. //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
  1011. $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
  1012. }
  1013. dol_syslog("CMailFile::sendfile: mailer->send, HOST=".$server.", PORT=".$conf->global->$keyforsmtpport, LOG_DEBUG);
  1014. // send mail
  1015. $failedRecipients = array();
  1016. try {
  1017. $result = $this->mailer->send($this->message, $failedRecipients);
  1018. } catch (Exception $e) {
  1019. $this->errors[] = $e->getMessage();
  1020. }
  1021. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  1022. $this->dump_mail();
  1023. }
  1024. $res = true;
  1025. if (!empty($this->error) || !empty($this->errors) || !$result) {
  1026. if (!empty($failedRecipients)) {
  1027. $this->errors[] = 'Transport failed for the following addresses: "' . join('", "', $failedRecipients) . '".';
  1028. }
  1029. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  1030. $res = false;
  1031. if (!empty($conf->global->MAIN_MAIL_DEBUG)) {
  1032. $this->save_dump_mail_in_err('Mail with topic '.$this->subject);
  1033. }
  1034. } else {
  1035. dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
  1036. }
  1037. } else {
  1038. // Send mail method not correctly defined
  1039. // --------------------------------------
  1040. return 'Bad value for sendmode';
  1041. }
  1042. // Now we delete image files that were created dynamically to manage data inline files
  1043. foreach ($this->html_images as $val) {
  1044. if (!empty($val['type']) && $val['type'] == 'cidfromdata') {
  1045. //dol_delete($val['fullpath']);
  1046. }
  1047. }
  1048. $parameters = array('sent' => $res);
  1049. $action = '';
  1050. $reshook = $hookmanager->executeHooks('sendMailAfter', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  1051. if ($reshook < 0) {
  1052. $this->error = "Error in hook maildao sendMailAfter ".$reshook;
  1053. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  1054. return $reshook;
  1055. }
  1056. } else {
  1057. $this->error = 'No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
  1058. dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
  1059. }
  1060. error_reporting($errorlevel); // Reactive niveau erreur origine
  1061. return $res;
  1062. }
  1063. /**
  1064. * Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word
  1065. *
  1066. * @param string $stringtoencode String to encode
  1067. * @return string string encoded
  1068. */
  1069. public static function encodetorfc2822($stringtoencode)
  1070. {
  1071. global $conf;
  1072. return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
  1073. }
  1074. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1075. /**
  1076. * Read a file on disk and return encoded content for emails (mode = 'mail')
  1077. *
  1078. * @param string $sourcefile Path to file to encode
  1079. * @return int|string <0 if KO, encoded string if OK
  1080. */
  1081. private function _encode_file($sourcefile)
  1082. {
  1083. // phpcs:enable
  1084. $newsourcefile = dol_osencode($sourcefile);
  1085. if (is_readable($newsourcefile)) {
  1086. $contents = file_get_contents($newsourcefile); // Need PHP 4.3
  1087. $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
  1088. return $encoded;
  1089. } else {
  1090. $this->error = "Error in _encode_file() method: Can't read file '".$sourcefile."'";
  1091. dol_syslog("CMailFile::_encode_file: ".$this->error, LOG_ERR);
  1092. return -1;
  1093. }
  1094. }
  1095. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1096. /**
  1097. * Write content of a SMTP request into a dump file (mode = all)
  1098. * Used for debugging.
  1099. * Note that to see full SMTP protocol, you can use tcpdump -w /tmp/smtp -s 2000 port 25"
  1100. *
  1101. * @return void
  1102. */
  1103. public function dump_mail()
  1104. {
  1105. // phpcs:enable
  1106. global $conf, $dolibarr_main_data_root;
  1107. if (@is_writeable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
  1108. $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
  1109. $fp = fopen($outputfile, "w"); // overwrite
  1110. if ($this->sendmode == 'mail') {
  1111. fputs($fp, $this->headers);
  1112. fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log
  1113. fputs($fp, $this->message);
  1114. } elseif ($this->sendmode == 'smtps') {
  1115. fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
  1116. } elseif ($this->sendmode == 'swiftmailer') {
  1117. fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
  1118. }
  1119. fclose($fp);
  1120. dolChmod($outputfile);
  1121. }
  1122. }
  1123. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1124. /**
  1125. * Save content if mail is in error
  1126. * Used for debugging.
  1127. *
  1128. * @param string $message Add also a message
  1129. * @return void
  1130. */
  1131. public function save_dump_mail_in_err($message = '')
  1132. {
  1133. global $dolibarr_main_data_root;
  1134. if (@is_writeable($dolibarr_main_data_root)) { // Avoid fatal error on fopen with open_basedir
  1135. $srcfile = $dolibarr_main_data_root."/dolibarr_mail.log";
  1136. // Add message to dolibarr_mail.log. We do not use dol_syslog() on purpose,
  1137. // to be sure to write into dolibarr_mail.log
  1138. if ($message) {
  1139. // Test constant SYSLOG_FILE_NO_ERROR (should stay a constant defined with define('SYSLOG_FILE_NO_ERROR',1);
  1140. if (defined('SYSLOG_FILE_NO_ERROR')) {
  1141. $filefd = @fopen($srcfile, 'a+');
  1142. } else {
  1143. $filefd = fopen($srcfile, 'a+');
  1144. }
  1145. if ($filefd) {
  1146. fwrite($filefd, $message."\n");
  1147. fclose($filefd);
  1148. dolChmod($srcfile);
  1149. }
  1150. }
  1151. // Move dolibarr_mail.log into a dolibarr_mail.err or dolibarr_mail.date.err
  1152. if (getDolGlobalString('MAIN_MAIL_DEBUG_ERR_WITH_DATE')) {
  1153. $destfile = $dolibarr_main_data_root."/dolibarr_mail.".dol_print_date(dol_now(), 'dayhourlog', 'gmt').".err";
  1154. } else {
  1155. $destfile = $dolibarr_main_data_root."/dolibarr_mail.err";
  1156. }
  1157. require_once DOL_DOCUMENT_ROOT.'/core/lib/files.lib.php';
  1158. dol_move($srcfile, $destfile, 0, 1, 0, 0);
  1159. }
  1160. }
  1161. /**
  1162. * Correct an uncomplete html string
  1163. *
  1164. * @param string $msg String
  1165. * @return string Completed string
  1166. */
  1167. public function checkIfHTML($msg)
  1168. {
  1169. if (!preg_match('/^[\s\t]*<html/i', $msg)) {
  1170. $out = "<html><head><title></title>";
  1171. if (!empty($this->styleCSS)) {
  1172. $out .= $this->styleCSS;
  1173. }
  1174. $out .= "</head><body";
  1175. if (!empty($this->bodyCSS)) {
  1176. $out .= $this->bodyCSS;
  1177. }
  1178. $out .= ">";
  1179. $out .= $msg;
  1180. $out .= "</body></html>";
  1181. } else {
  1182. $out = $msg;
  1183. }
  1184. return $out;
  1185. }
  1186. /**
  1187. * Build a css style (mode = all) into this->styleCSS and this->bodyCSS
  1188. *
  1189. * @return void
  1190. */
  1191. public function buildCSS()
  1192. {
  1193. if (!empty($this->css)) {
  1194. // Style CSS
  1195. $this->styleCSS = '<style type="text/css">';
  1196. $this->styleCSS .= 'body {';
  1197. if ($this->css['bgcolor']) {
  1198. $this->styleCSS .= ' background-color: '.$this->css['bgcolor'].';';
  1199. $this->bodyCSS .= ' bgcolor="'.$this->css['bgcolor'].'"';
  1200. }
  1201. if ($this->css['bgimage']) {
  1202. // TODO recuperer cid
  1203. $this->styleCSS .= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
  1204. }
  1205. $this->styleCSS .= '}';
  1206. $this->styleCSS .= '</style>';
  1207. }
  1208. }
  1209. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1210. /**
  1211. * Create SMTP headers (mode = 'mail')
  1212. *
  1213. * @return string headers
  1214. */
  1215. public function write_smtpheaders()
  1216. {
  1217. // phpcs:enable
  1218. global $conf;
  1219. $out = "";
  1220. $host = dol_getprefix('email');
  1221. // Sender
  1222. //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
  1223. $out .= "From: ".$this->getValidAddress($this->addr_from, 3, 1).$this->eol2;
  1224. if (!empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA)) {
  1225. $out .= "To: ".$this->getValidAddress($this->addr_to, 0, 1).$this->eol2;
  1226. }
  1227. // 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.
  1228. $out .= "Return-Path: ".$this->getValidAddress($this->addr_from, 0, 1).$this->eol2;
  1229. if (isset($this->reply_to) && $this->reply_to) {
  1230. $out .= "Reply-To: ".$this->getValidAddress($this->reply_to, 2).$this->eol2;
  1231. }
  1232. if (isset($this->errors_to) && $this->errors_to) {
  1233. $out .= "Errors-To: ".$this->getValidAddress($this->errors_to, 2).$this->eol2;
  1234. }
  1235. // Receiver
  1236. if (isset($this->addr_cc) && $this->addr_cc) {
  1237. $out .= "Cc: ".$this->getValidAddress($this->addr_cc, 2).$this->eol2;
  1238. }
  1239. if (isset($this->addr_bcc) && $this->addr_bcc) {
  1240. $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 ?
  1241. }
  1242. // Delivery receipt
  1243. if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) {
  1244. $out .= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from, 2).$this->eol2;
  1245. }
  1246. //$out.= "X-Priority: 3".$this->eol2;
  1247. $out .= 'Date: '.date("r").$this->eol2;
  1248. $trackid = $this->trackid;
  1249. if ($trackid) {
  1250. // References is kept in response and Message-ID is returned into In-Reply-To:
  1251. $this->msgid = time().'.phpmail-dolibarr-'.$trackid.'@'.$host;
  1252. $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2; // Uppercase seems replaced by phpmail
  1253. $out .= 'References: <'.$this->msgid.">".$this->eol2;
  1254. $out .= 'X-Dolibarr-TRACKID: '.$trackid.'@'.$host.$this->eol2;
  1255. } else {
  1256. $this->msgid = time().'.phpmail@'.$host;
  1257. $out .= 'Message-ID: <'.$this->msgid.">".$this->eol2;
  1258. }
  1259. if (!empty($_SERVER['REMOTE_ADDR'])) {
  1260. $out .= "X-RemoteAddr: ".$_SERVER['REMOTE_ADDR'].$this->eol2;
  1261. }
  1262. $out .= "X-Mailer: Dolibarr version ".DOL_VERSION." (using php mail)".$this->eol2;
  1263. $out .= "Mime-Version: 1.0".$this->eol2;
  1264. //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
  1265. $out .= "Content-Type: multipart/mixed;".$this->eol2." boundary=\"".$this->mixed_boundary."\"".$this->eol2;
  1266. $out .= "Content-Transfer-Encoding: 8bit".$this->eol2; // TODO Seems to be ignored. Header is 7bit once received.
  1267. dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
  1268. return $out;
  1269. }
  1270. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1271. /**
  1272. * Create header MIME (mode = 'mail')
  1273. *
  1274. * @param array $filename_list Array of filenames
  1275. * @param array $mimefilename_list Array of mime types
  1276. * @return string mime headers
  1277. */
  1278. public function write_mimeheaders($filename_list, $mimefilename_list)
  1279. {
  1280. // phpcs:enable
  1281. $mimedone = 0;
  1282. $out = "";
  1283. if (is_array($filename_list)) {
  1284. $filename_list_size = count($filename_list);
  1285. for ($i = 0; $i < $filename_list_size; $i++) {
  1286. if ($filename_list[$i]) {
  1287. if ($mimefilename_list[$i]) {
  1288. $filename_list[$i] = $mimefilename_list[$i];
  1289. }
  1290. $out .= "X-attachments: $filename_list[$i]".$this->eol2;
  1291. }
  1292. }
  1293. }
  1294. dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
  1295. return $out;
  1296. }
  1297. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1298. /**
  1299. * Return email content (mode = 'mail')
  1300. *
  1301. * @param string $msgtext Message string
  1302. * @return string String content
  1303. */
  1304. public function write_body($msgtext)
  1305. {
  1306. // phpcs:enable
  1307. global $conf;
  1308. $out = '';
  1309. $out .= "--".$this->mixed_boundary.$this->eol;
  1310. if ($this->atleastoneimage) {
  1311. $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
  1312. $out .= $this->eol;
  1313. $out .= "--".$this->alternative_boundary.$this->eol;
  1314. }
  1315. // Make RFC821 Compliant, replace bare linefeeds
  1316. $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext); // PCRE modifier /s means new lines are common chars
  1317. if (!empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA)) {
  1318. $strContent = preg_replace("/\r\n/si", "\n", $strContent); // PCRE modifier /s means new lines are common chars
  1319. }
  1320. $strContentAltText = '';
  1321. if ($this->msgishtml) {
  1322. // Similar code to forge a text from html is also in smtps.class.php
  1323. $strContentAltText = preg_replace("/<br\s*[^>]*>/", " ", $strContent);
  1324. // TODO We could replace <img ...> with [Filename.ext] like Gmail do.
  1325. $strContentAltText = html_entity_decode(strip_tags($strContentAltText)); // Remove any HTML tags
  1326. $strContentAltText = trim(wordwrap($strContentAltText, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n"));
  1327. // Check if html header already in message, if not complete the message
  1328. $strContent = $this->checkIfHTML($strContent);
  1329. }
  1330. // Make RFC2045 Compliant, split lines
  1331. //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
  1332. // TODO Encode main content into base64 and use the chunk_split, or quoted-printable
  1333. $strContent = rtrim(wordwrap($strContent, 75, empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA) ? "\r\n" : "\n")); // TODO Using this method creates unexpected line break on text/plain content.
  1334. if ($this->msgishtml) {
  1335. if ($this->atleastoneimage) {
  1336. $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
  1337. //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
  1338. $out .= $this->eol.($strContentAltText ? $strContentAltText : strip_tags($strContent)).$this->eol; // Add plain text message
  1339. $out .= "--".$this->alternative_boundary.$this->eol;
  1340. $out .= "Content-Type: multipart/related;".$this->eol." boundary=\"".$this->related_boundary."\"".$this->eol;
  1341. $out .= $this->eol;
  1342. $out .= "--".$this->related_boundary.$this->eol;
  1343. }
  1344. if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Add plain text message part before html part
  1345. $out .= "Content-Type: multipart/alternative;".$this->eol." boundary=\"".$this->alternative_boundary."\"".$this->eol;
  1346. $out .= $this->eol;
  1347. $out .= "--".$this->alternative_boundary.$this->eol;
  1348. $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
  1349. //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
  1350. $out .= $this->eol.$strContentAltText.$this->eol;
  1351. $out .= "--".$this->alternative_boundary.$this->eol;
  1352. }
  1353. $out .= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
  1354. //$out.= "Content-Transfer-Encoding: 7bit".$this->eol; // TODO Use base64
  1355. $out .= $this->eol.$strContent.$this->eol;
  1356. if (!$this->atleastoneimage && $strContentAltText && !empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) { // Add plain text message part after html part
  1357. $out .= "--".$this->alternative_boundary."--".$this->eol;
  1358. }
  1359. } else {
  1360. $out .= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
  1361. //$out.= "Content-Transfer-Encoding: 7bit".$this->eol;
  1362. $out .= $this->eol.$strContent.$this->eol;
  1363. }
  1364. $out .= $this->eol;
  1365. // Encode images
  1366. if ($this->atleastoneimage) {
  1367. $out .= $this->write_images($this->images_encoded);
  1368. // always end related and end alternative after inline images
  1369. $out .= "--".$this->related_boundary."--".$this->eol;
  1370. $out .= $this->eol."--".$this->alternative_boundary."--".$this->eol;
  1371. $out .= $this->eol;
  1372. }
  1373. return $out;
  1374. }
  1375. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1376. /**
  1377. * Attach file to email (mode = 'mail')
  1378. *
  1379. * @param array $filename_list Tableau
  1380. * @param array $mimetype_list Tableau
  1381. * @param array $mimefilename_list Tableau
  1382. * @param array $cidlist Array of CID if file must be completed with CID code
  1383. * @return string String with files encoded
  1384. */
  1385. private function write_files($filename_list, $mimetype_list, $mimefilename_list, $cidlist)
  1386. {
  1387. // phpcs:enable
  1388. $out = '';
  1389. $filename_list_size = count($filename_list);
  1390. for ($i = 0; $i < $filename_list_size; $i++) {
  1391. if ($filename_list[$i]) {
  1392. dol_syslog("CMailFile::write_files: i=$i");
  1393. $encoded = $this->_encode_file($filename_list[$i]);
  1394. if ($encoded >= 0) {
  1395. if ($mimefilename_list[$i]) {
  1396. $filename_list[$i] = $mimefilename_list[$i];
  1397. }
  1398. if (!$mimetype_list[$i]) {
  1399. $mimetype_list[$i] = "application/octet-stream";
  1400. }
  1401. $out .= "--".$this->mixed_boundary.$this->eol;
  1402. $out .= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
  1403. $out .= "Content-Type: ".$mimetype_list[$i]."; name=\"".$filename_list[$i]."\"".$this->eol;
  1404. $out .= "Content-Transfer-Encoding: base64".$this->eol;
  1405. $out .= "Content-Description: ".$filename_list[$i].$this->eol;
  1406. if (!empty($cidlist) && is_array($cidlist) && $cidlist[$i]) {
  1407. $out .= "X-Attachment-Id: ".$cidlist[$i].$this->eol;
  1408. $out .= "Content-ID: <".$cidlist[$i].'>'.$this->eol;
  1409. }
  1410. $out .= $this->eol;
  1411. $out .= $encoded;
  1412. $out .= $this->eol;
  1413. //$out.= $this->eol;
  1414. } else {
  1415. return $encoded;
  1416. }
  1417. }
  1418. }
  1419. return $out;
  1420. }
  1421. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1422. /**
  1423. * Attach an image to email (mode = 'mail')
  1424. *
  1425. * @param array $images_list Array of array image
  1426. * @return string Chaine images encodees
  1427. */
  1428. public function write_images($images_list)
  1429. {
  1430. // phpcs:enable
  1431. $out = '';
  1432. if (is_array($images_list)) {
  1433. foreach ($images_list as $img) {
  1434. dol_syslog("CMailFile::write_images: ".$img["name"]);
  1435. $out .= "--".$this->related_boundary.$this->eol; // always related for an inline image
  1436. $out .= "Content-Type: ".$img["content_type"]."; name=\"".$img["name"]."\"".$this->eol;
  1437. $out .= "Content-Transfer-Encoding: base64".$this->eol;
  1438. $out .= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
  1439. $out .= "Content-ID: <".$img["cid"].">".$this->eol;
  1440. $out .= $this->eol;
  1441. $out .= $img["image_encoded"];
  1442. $out .= $this->eol;
  1443. }
  1444. }
  1445. return $out;
  1446. }
  1447. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1448. /**
  1449. * Try to create a socket connection
  1450. *
  1451. * @param string $host Add ssl:// for SSL/TLS.
  1452. * @param int $port Example: 25, 465
  1453. * @return int Socket id if ok, 0 if KO
  1454. */
  1455. public function check_server_port($host, $port)
  1456. {
  1457. // phpcs:enable
  1458. global $conf;
  1459. $_retVal = 0;
  1460. $timeout = 5; // Timeout in seconds
  1461. if (function_exists('fsockopen')) {
  1462. $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER';
  1463. $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT';
  1464. $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID';
  1465. $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW';
  1466. $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE';
  1467. $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE';
  1468. $keyfortls = 'MAIN_MAIL_EMAIL_TLS';
  1469. $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS';
  1470. $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED';
  1471. if (!empty($this->sendcontext)) {
  1472. $smtpContextKey = strtoupper($this->sendcontext);
  1473. $smtpContextSendMode = getDolGlobalString('MAIN_MAIL_SENDMODE_'.$smtpContextKey);
  1474. if (!empty($smtpContextSendMode) && $smtpContextSendMode != 'default') {
  1475. $keyforsmtpserver = 'MAIN_MAIL_SMTP_SERVER_'.$smtpContextKey;
  1476. $keyforsmtpport = 'MAIN_MAIL_SMTP_PORT_'.$smtpContextKey;
  1477. $keyforsmtpid = 'MAIN_MAIL_SMTPS_ID_'.$smtpContextKey;
  1478. $keyforsmtppw = 'MAIN_MAIL_SMTPS_PW_'.$smtpContextKey;
  1479. $keyforsmtpauthtype = 'MAIN_MAIL_SMTPS_AUTH_TYPE_'.$smtpContextKey;
  1480. $keyforsmtpoauthservice = 'MAIN_MAIL_SMTPS_OAUTH_SERVICE_'.$smtpContextKey;
  1481. $keyfortls = 'MAIN_MAIL_EMAIL_TLS_'.$smtpContextKey;
  1482. $keyforstarttls = 'MAIN_MAIL_EMAIL_STARTTLS_'.$smtpContextKey;
  1483. $keyforsslseflsigned = 'MAIN_MAIL_EMAIL_SMTP_ALLOW_SELF_SIGNED_'.$smtpContextKey;
  1484. }
  1485. }
  1486. // If we use SSL/TLS
  1487. if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) {
  1488. $host = 'ssl://'.$host;
  1489. }
  1490. // tls smtp start with no encryption
  1491. //if (!empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
  1492. dol_syslog("Try socket connection to host=".$host." port=".$port);
  1493. //See if we can connect to the SMTP server
  1494. $errno = 0; $errstr = '';
  1495. if ($socket = @fsockopen(
  1496. $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
  1497. $port, // which Port number to use
  1498. $errno, // actual system level error
  1499. $errstr, // and any text that goes with the error
  1500. $timeout // timeout for reading/writing data over the socket
  1501. )) {
  1502. // Windows still does not have support for this timeout function
  1503. if (function_exists('stream_set_timeout')) {
  1504. stream_set_timeout($socket, $timeout, 0);
  1505. }
  1506. dol_syslog("Now we wait for answer 220");
  1507. // Check response from Server
  1508. if ($_retVal = $this->server_parse($socket, "220")) {
  1509. $_retVal = $socket;
  1510. }
  1511. } else {
  1512. $this->error = utf8_check('Error '.$errno.' - '.$errstr) ? 'Error '.$errno.' - '.$errstr : utf8_encode('Error '.$errno.' - '.$errstr);
  1513. }
  1514. }
  1515. return $_retVal;
  1516. }
  1517. // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps
  1518. /**
  1519. * This function has been modified as provided by SirSir to allow multiline responses when
  1520. * using SMTP Extensions.
  1521. *
  1522. * @param resource $socket Socket
  1523. * @param string $response Response string
  1524. * @return boolean true if success
  1525. */
  1526. public function server_parse($socket, $response)
  1527. {
  1528. // phpcs:enable
  1529. $_retVal = true; // Indicates if Object was created or not
  1530. $server_response = '';
  1531. while (substr($server_response, 3, 1) != ' ') {
  1532. if (!($server_response = fgets($socket, 256))) {
  1533. $this->error = "Couldn't get mail server response codes";
  1534. return false;
  1535. }
  1536. }
  1537. if (!(substr($server_response, 0, 3) == $response)) {
  1538. $this->error = "Ran into problems sending Mail.\r\nResponse: $server_response";
  1539. $_retVal = false;
  1540. }
  1541. return $_retVal;
  1542. }
  1543. /**
  1544. * Search images into html message and init array this->images_encoded if found
  1545. *
  1546. * @param string $images_dir Location of physical images files. For example $dolibarr_main_data_root.'/medias'
  1547. * @return int >0 if OK, <0 if KO
  1548. */
  1549. private function findHtmlImages($images_dir)
  1550. {
  1551. // Build the array of image extensions
  1552. $extensions = array_keys($this->image_types);
  1553. // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
  1554. // For example when:
  1555. // <img alt="" src="/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/picture.jpg" style="height:356px; width:1040px" />
  1556. $matches = array();
  1557. preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
  1558. if (!empty($matches)) {
  1559. $i = 0;
  1560. // We are interested in $matches[1] only (the second set of parenthesis into regex)
  1561. foreach ($matches[1] as $full) {
  1562. $regs = array();
  1563. if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i', $full, $regs)) { // If xxx is 'file=aaa'
  1564. $img = $regs[1];
  1565. if (file_exists($images_dir.'/'.$img)) {
  1566. // Image path in src
  1567. $src = preg_quote($full, '/');
  1568. // Image full path
  1569. $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
  1570. // Image name
  1571. $this->html_images[$i]["name"] = $img;
  1572. // Content type
  1573. $regext = array();
  1574. if (preg_match('/^.+\.(\w{3,4})$/', $img, $regext)) {
  1575. $ext = strtolower($regext[1]);
  1576. $this->html_images[$i]["content_type"] = $this->image_types[$ext];
  1577. }
  1578. // cid
  1579. $this->html_images[$i]["cid"] = dol_hash($this->html_images[$i]["fullpath"], 'md5'); // Force md5 hash (does not contain special chars)
  1580. // type
  1581. $this->html_images[$i]["type"] = 'cidfromurl';
  1582. $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
  1583. }
  1584. $i++;
  1585. }
  1586. }
  1587. if (!empty($this->html_images)) {
  1588. $inline = array();
  1589. $i = 0;
  1590. foreach ($this->html_images as $img) {
  1591. $fullpath = $images_dir.'/'.$img["name"];
  1592. // If duplicate images are embedded, they may show up as attachments, so remove them.
  1593. if (!in_array($fullpath, $inline)) {
  1594. // Read image file
  1595. if ($image = file_get_contents($fullpath)) {
  1596. // On garde que le nom de l'image
  1597. $regs = array();
  1598. preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i', $img["name"], $regs);
  1599. $imgName = $regs[1];
  1600. $this->images_encoded[$i]['name'] = $imgName;
  1601. $this->images_encoded[$i]['fullpath'] = $fullpath;
  1602. $this->images_encoded[$i]['content_type'] = $img["content_type"];
  1603. $this->images_encoded[$i]['cid'] = $img["cid"];
  1604. // Encodage de l'image
  1605. $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
  1606. $inline[] = $fullpath;
  1607. }
  1608. }
  1609. $i++;
  1610. }
  1611. } else {
  1612. return -1;
  1613. }
  1614. return 1;
  1615. } else {
  1616. return 0;
  1617. }
  1618. }
  1619. /**
  1620. * Seearch images with data:image format into html message.
  1621. * If we find some, we create it on disk.
  1622. *
  1623. * @param string $images_dir Location of where to store physicaly images files. For example $dolibarr_main_data_root.'/medias'
  1624. * @return int >0 if OK, <0 if KO
  1625. */
  1626. private function findHtmlImagesIsSrcData($images_dir)
  1627. {
  1628. global $conf;
  1629. // Build the array of image extensions
  1630. $extensions = array_keys($this->image_types);
  1631. if ($images_dir && !dol_is_dir($images_dir)) {
  1632. dol_mkdir($images_dir, DOL_DATA_ROOT);
  1633. }
  1634. // Uncomment this for debug
  1635. /*
  1636. global $dolibarr_main_data_root;
  1637. $outputfile = $dolibarr_main_data_root."/dolibarr_mail.log";
  1638. $fp = fopen($outputfile, "w+");
  1639. fwrite($fp, $this->html);
  1640. fclose($fp);
  1641. */
  1642. // We search (into mail body this->html), if we find some strings like "... file=xxx.img"
  1643. // For example when:
  1644. // <img alt="" src="/viewimage.php?modulepart=medias&amp;entity=1&amp;file=image/picture.jpg" style="height:356px; width:1040px" />
  1645. $matches = array();
  1646. preg_match_all('/src="data:image\/('.implode('|', $extensions).');base64,([^"]+)"/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
  1647. if (!empty($matches) && !empty($matches[1])) {
  1648. if (empty($images_dir)) {
  1649. // No temp directory provided, so we are not able to support convertion of data:image into physical images.
  1650. $this->error = 'NoTempDirProvidedInCMailConstructorSoCantConvertDataImgOnDisk';
  1651. return -1;
  1652. }
  1653. $i = 0;
  1654. foreach ($matches[1] as $key => $ext) {
  1655. // We save the image to send in disk
  1656. $filecontent = $matches[2][$key];
  1657. $cid = 'cid000'.dol_hash($filecontent, 'md5'); // The id must not change if image is same
  1658. $destfiletmp = $images_dir.'/'.$cid.'.'.$ext;
  1659. 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)
  1660. dol_syslog("write the cid file ".$destfiletmp);
  1661. $fhandle = @fopen($destfiletmp, 'w');
  1662. if ($fhandle) {
  1663. $nbofbyteswrote = fwrite($fhandle, base64_decode($filecontent));
  1664. fclose($fhandle);
  1665. dolChmod($destfiletmp);
  1666. } else {
  1667. $this->errors[] = "Failed to open file '".$destfiletmp."' for write";
  1668. return -1;
  1669. }
  1670. }
  1671. if (file_exists($destfiletmp)) {
  1672. // Image full path
  1673. $this->html_images[$i]["fullpath"] = $destfiletmp;
  1674. // Image name
  1675. $this->html_images[$i]["name"] = basename($destfiletmp);
  1676. // Content type
  1677. $this->html_images[$i]["content_type"] = $this->image_types[strtolower($ext)];
  1678. // cid
  1679. $this->html_images[$i]["cid"] = $cid;
  1680. // type
  1681. $this->html_images[$i]["type"] = 'cidfromdata';
  1682. $this->html = str_replace('src="data:image/'.$ext.';base64,'.$filecontent.'"', 'src="cid:'.$this->html_images[$i]["cid"].'"', $this->html);
  1683. }
  1684. $i++;
  1685. }
  1686. return 1;
  1687. } else {
  1688. return 0;
  1689. }
  1690. }
  1691. /**
  1692. * Return a formatted address string for SMTP protocol
  1693. *
  1694. * @param string $address Example: 'John Doe <john@doe.com>, Alan Smith <alan@smith.com>' or 'john@doe.com, alan@smith.com'
  1695. * @param int $format 0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between ", 4 label or email, 5 mailto link
  1696. * @param int $encode 0=No encode name, 1=Encode name to RFC2822
  1697. * @param int $maxnumberofemail 0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more.
  1698. * @return string If format 0: '<john@doe.com>' or 'John Doe <john@doe.com>' or '=?UTF-8?B?Sm9obiBEb2U=?= <john@doe.com>'
  1699. * If format 1: '<john@doe.com>'
  1700. * If format 2: 'john@doe.com'
  1701. * If format 3: '<john@doe.com>' or '"John Doe" <john@doe.com>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <john@doe.com>'
  1702. * If format 4: 'John Doe' or 'john@doe.com' if no label exists
  1703. * If format 5: <a href="mailto:john@doe.com">John Doe</a> or <a href="mailto:john@doe.com">john@doe.com</a> if no label exists
  1704. * @see getArrayAddress()
  1705. */
  1706. public static function getValidAddress($address, $format, $encode = 0, $maxnumberofemail = 0)
  1707. {
  1708. global $conf;
  1709. $ret = '';
  1710. $arrayaddress = explode(',', $address);
  1711. // Boucle sur chaque composant de l'adresse
  1712. $i = 0;
  1713. foreach ($arrayaddress as $val) {
  1714. $regs = array();
  1715. if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
  1716. $name = trim($regs[1]);
  1717. $email = trim($regs[2]);
  1718. } else {
  1719. $name = '';
  1720. $email = trim($val);
  1721. }
  1722. if ($email) {
  1723. $i++;
  1724. $newemail = '';
  1725. if ($format == 5) {
  1726. $newemail = $name ? $name : $email;
  1727. $newemail = '<a href="mailto:'.$email.'">'.$newemail.'</a>';
  1728. }
  1729. if ($format == 4) {
  1730. $newemail = $name ? $name : $email;
  1731. }
  1732. if ($format == 2) {
  1733. $newemail = $email;
  1734. }
  1735. if ($format == 1 || $format == 3) {
  1736. $newemail = '<'.$email.'>';
  1737. }
  1738. if ($format == 0 || $format == 3) {
  1739. if (!empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) {
  1740. $newemail = '<'.$email.'>';
  1741. } elseif (!$name) {
  1742. $newemail = '<'.$email.'>';
  1743. } else {
  1744. $newemail = ($format == 3 ? '"' : '').($encode ?self::encodetorfc2822($name) : $name).($format == 3 ? '"' : '').' <'.$email.'>';
  1745. }
  1746. }
  1747. $ret = ($ret ? $ret.',' : '').$newemail;
  1748. // Stop if we have too much records
  1749. if ($maxnumberofemail && $i >= $maxnumberofemail) {
  1750. if (count($arrayaddress) > $maxnumberofemail) {
  1751. $ret .= '...';
  1752. }
  1753. break;
  1754. }
  1755. }
  1756. }
  1757. return $ret;
  1758. }
  1759. /**
  1760. * Return a formatted array of address string for SMTP protocol
  1761. *
  1762. * @param string $address Example: 'John Doe <john@doe.com>, Alan Smith <alan@smith.com>' or 'john@doe.com, alan@smith.com'
  1763. * @return array array of email => name
  1764. * @see getValidAddress()
  1765. */
  1766. public static function getArrayAddress($address)
  1767. {
  1768. global $conf;
  1769. $ret = array();
  1770. $arrayaddress = explode(',', $address);
  1771. // Boucle sur chaque composant de l'adresse
  1772. foreach ($arrayaddress as $val) {
  1773. if (preg_match('/^(.*)<(.*)>$/i', trim($val), $regs)) {
  1774. $name = trim($regs[1]);
  1775. $email = trim($regs[2]);
  1776. } else {
  1777. $name = null;
  1778. $email = trim($val);
  1779. }
  1780. $ret[$email] = empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL) ? $name : null;
  1781. }
  1782. return $ret;
  1783. }
  1784. }