CMailFile.class.php 75 KB

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