CMailFile.class.php 48 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  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@capnetworks.com>
  9. *
  10. * This program is free software; you can redistribute it and/or modify
  11. * it under the terms of the GNU General Public License as published by
  12. * the Free Software Foundation; either version 3 of the License, or
  13. * (at your option) any later version.
  14. *
  15. * This program is distributed in the hope that it will be useful,
  16. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  17. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  18. * GNU General Public License for more details.
  19. *
  20. * You should have received a copy of the GNU General Public License
  21. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  22. * or see http://www.gnu.org/
  23. *
  24. * Lots of code inspired from Dan Potter's CMailFile class
  25. */
  26. /**
  27. * \file htdocs/core/class/CMailFile.class.php
  28. * \brief File of class to send emails (with attachments or not)
  29. */
  30. /**
  31. * Class to send emails (with attachments or not)
  32. * Usage: $mailfile = new CMailFile($subject,$sendto,$replyto,$message,$filepath,$mimetype,$filename,$cc,$ccc,$deliveryreceipt,$msgishtml,$errors_to,$css,$trackid,$moreinheader,$sendcontext);
  33. * $mailfile->sendfile();
  34. */
  35. class CMailFile
  36. {
  37. public $sendcontext;
  38. public $sendmode;
  39. public $sendsetup;
  40. var $subject; // Topic: Subject of email
  41. var $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).
  42. // Sender: Who send the email ("Sender" has sent emails on behalf of "From").
  43. // 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.
  44. // Return-Path: Email where to send bounds.
  45. var $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)
  46. var $errors_to; // Errors-To: Email where to send errors.
  47. var $addr_to;
  48. var $addr_cc;
  49. var $addr_bcc;
  50. var $trackid;
  51. var $mixed_boundary;
  52. var $related_boundary;
  53. var $alternative_boundary;
  54. var $deliveryreceipt;
  55. var $eol;
  56. var $eol2;
  57. var $error='';
  58. var $smtps; // Contains SMTPs object (if this method is used)
  59. var $phpmailer; // Contains PHPMailer object (if this method is used)
  60. //CSS
  61. var $css;
  62. //! Defined css style for body background
  63. var $styleCSS;
  64. //! Defined background directly in body tag
  65. var $bodyCSS;
  66. var $headers;
  67. var $message;
  68. // Image
  69. var $html;
  70. var $image_boundary;
  71. var $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).
  72. var $html_images=array();
  73. var $images_encoded=array();
  74. var $image_types = array('gif' => 'image/gif',
  75. 'jpg' => 'image/jpeg',
  76. 'jpeg' => 'image/jpeg',
  77. 'jpe' => 'image/jpeg',
  78. 'bmp' => 'image/bmp',
  79. 'png' => 'image/png',
  80. 'tif' => 'image/tiff',
  81. 'tiff' => 'image/tiff');
  82. /**
  83. * CMailFile
  84. *
  85. * @param string $subject Topic/Subject of mail
  86. * @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.
  87. * @param string $from Sender email (RFC 2822: "Name firstname <email>[, ...]" or "email[, ...]" or "<email>[, ...]")
  88. * @param string $msg Message
  89. * @param array $filename_list List of files to attach (full path of filename on file system)
  90. * @param array $mimetype_list List of MIME type of attached files
  91. * @param array $mimefilename_list List of attached file name in message
  92. * @param string $addr_cc Email cc
  93. * @param string $addr_bcc Email bcc (Note: This is autocompleted with MAIN_MAIL_AUTOCOPY_TO if defined)
  94. * @param int $deliveryreceipt Ask a delivery receipt
  95. * @param int $msgishtml 1=String IS already html, 0=String IS NOT html, -1=Unknown make autodetection (with fast mode, not reliable)
  96. * @param string $errors_to Email for errors-to
  97. * @param string $css Css option
  98. * @param string $trackid Tracking string (contains type and id of related element)
  99. * @param string $moreinheader More in header. $moreinheader must contains the "\r\n" (TODO not supported for other MAIL_SEND_MODE different than 'phpmail' and 'smtps' for the moment)
  100. * @param string $sendcontext 'standard', 'emailing', ...
  101. */
  102. 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')
  103. {
  104. global $conf, $dolibarr_main_data_root;
  105. $this->sendcontext = $sendcontext;
  106. $this->sendmode = '';
  107. if ($this->sendcontext == 'emailing') $this->sendmode = $conf->global->EMAILING_MAIL_SENDMODE;
  108. if (empty($this->sendmode)) $this->sendmode=$conf->global->MAIN_MAIL_SENDMODE;
  109. if (empty($this->sendmode)) $this->sendmode='mail';
  110. $this->sendsetup = array();
  111. // We define end of line (RFC 821).
  112. $this->eol="\r\n";
  113. // We define end of line for header fields (RFC 822bis section 2.3 says header must contains \r\n).
  114. $this->eol2="\r\n";
  115. if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
  116. {
  117. $this->eol="\n";
  118. $this->eol2="\n";
  119. $moreinheader = str_replace("\r\n","\n",$moreinheader);
  120. }
  121. // On defini mixed_boundary
  122. $this->mixed_boundary = "multipart_x." . time() . ".x_boundary";
  123. // On defini related_boundary
  124. $this->related_boundary = 'mul_'.dol_hash(uniqid("dolibarr2"), 3); // Force md5 hash (does not contains special chars)
  125. // On defini alternative_boundary
  126. $this->alternative_boundary = 'mul_'.dol_hash(uniqid("dolibarr3"), 3); // Force md5 hash (does not contains special chars)
  127. dol_syslog("CMailFile::CMailfile: sendmode=".$this->sendmode." charset=".$conf->file->character_set_client." from=$from, to=$to, addr_cc=$addr_cc, addr_bcc=$addr_bcc, errors_to=$errors_to, trackid=$trackid sendcontext=$sendcontext", LOG_DEBUG);
  128. dol_syslog("CMailFile::CMailfile: subject=$subject, deliveryreceipt=$deliveryreceipt, msgishtml=$msgishtml", LOG_DEBUG);
  129. if (empty($subject))
  130. {
  131. dol_syslog("CMailFile::CMailfile: Try to send an email with empty subject");
  132. $this->error='ErrorSubjectIsRequired';
  133. return;
  134. }
  135. if (empty($msg))
  136. {
  137. dol_syslog("CMailFile::CMailfile: Try to send an email with empty body");
  138. $msg='.'; // Avoid empty message (with empty message conten show a multipart structure)
  139. }
  140. // Detect if message is HTML (use fast method)
  141. if ($msgishtml == -1)
  142. {
  143. $this->msgishtml = 0;
  144. if (dol_textishtml($msg)) $this->msgishtml = 1;
  145. }
  146. else
  147. {
  148. $this->msgishtml = $msgishtml;
  149. }
  150. if (! empty($conf->global->MAIN_MAIL_FORCE_CONTENT_TYPE_TO_HTML)) $this->msgishtml=1; // To force to send everything with content type html.
  151. // Detect images
  152. if ($this->msgishtml)
  153. {
  154. $this->html = $msg;
  155. if (! empty($conf->global->MAIN_MAIL_ADD_INLINE_IMAGES_IF_IN_MEDIAS))
  156. {
  157. $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias');
  158. }
  159. // Define if there is at least one file
  160. if ($findimg)
  161. {
  162. foreach ($this->html_images as $i => $val)
  163. {
  164. if ($this->html_images[$i])
  165. {
  166. $this->atleastoneimage=1;
  167. dol_syslog("CMailFile::CMailfile: html_images[$i]['name']=".$this->html_images[$i]['name'], LOG_DEBUG);
  168. }
  169. }
  170. }
  171. }
  172. // Define if there is at least one file
  173. foreach ($filename_list as $i => $val)
  174. {
  175. if ($filename_list[$i])
  176. {
  177. $this->atleastonefile=1;
  178. dol_syslog("CMailFile::CMailfile: filename_list[$i]=".$filename_list[$i].", mimetype_list[$i]=".$mimetype_list[$i]." mimefilename_list[$i]=".$mimefilename_list[$i], LOG_DEBUG);
  179. }
  180. }
  181. // Add autocopy to (Note: Adding bcc for specific modules are also done from pages)
  182. if (! empty($conf->global->MAIN_MAIL_AUTOCOPY_TO)) $addr_bcc.=($addr_bcc?', ':'').$conf->global->MAIN_MAIL_AUTOCOPY_TO;
  183. // Action according to choosed sending method
  184. if ($this->sendmode == 'mail')
  185. {
  186. // Use mail php function (default PHP method)
  187. // ------------------------------------------
  188. $smtp_headers = "";
  189. $mime_headers = "";
  190. $text_body = "";
  191. $files_encoded = "";
  192. // Define smtp_headers
  193. $this->subject = $subject;
  194. $this->addr_from = $from;
  195. $this->reply_to = $from; // Set this property after constructor if you want to use another value
  196. $this->errors_to = $errors_to;
  197. $this->addr_to = $to;
  198. $this->addr_cc = $addr_cc;
  199. $this->addr_bcc = $addr_bcc;
  200. $this->deliveryreceipt = $deliveryreceipt;
  201. $this->trackid = $trackid;
  202. $smtp_headers = $this->write_smtpheaders();
  203. if (! empty($moreinheader)) $smtp_headers.=$moreinheader; // $moreinheader contains the \r\n
  204. // Define mime_headers
  205. $mime_headers = $this->write_mimeheaders($filename_list, $mimefilename_list);
  206. if (! empty($this->html))
  207. {
  208. if (!empty($css))
  209. {
  210. $this->css = $css;
  211. $this->buildCSS(); // Build a css style (mode = all) into this->styleCSS and this->bodyCSS
  212. }
  213. $msg = $this->html;
  214. }
  215. // Define body in text_body
  216. $text_body = $this->write_body($msg);
  217. // Add attachments to text_encoded
  218. if ($this->atleastonefile)
  219. {
  220. $files_encoded = $this->write_files($filename_list,$mimetype_list,$mimefilename_list);
  221. }
  222. // We now define $this->headers and $this->message
  223. $this->headers = $smtp_headers . $mime_headers;
  224. // On nettoie le header pour qu'il ne se termine pas par un retour chariot.
  225. // Ceci evite aussi les lignes vides en fin qui peuvent etre interpretees
  226. // comme des injections mail par les serveurs de messagerie.
  227. $this->headers = preg_replace("/([\r\n]+)$/i","",$this->headers);
  228. $this->message = $this->eol.'This is a message with multiple parts in MIME format.'.$this->eol;
  229. $this->message.= $text_body . $files_encoded;
  230. $this->message.= "--" . $this->mixed_boundary . "--" . $this->eol;
  231. }
  232. else if ($this->sendmode == 'smtps')
  233. {
  234. // Use SMTPS library
  235. // ------------------------------------------
  236. require_once DOL_DOCUMENT_ROOT.'/core/class/smtps.class.php';
  237. $smtps = new SMTPs();
  238. $smtps->setCharSet($conf->file->character_set_client);
  239. $smtps->setSubject($this->encodetorfc2822($subject));
  240. $smtps->setTO($this->getValidAddress($to,0,1));
  241. $smtps->setFrom($this->getValidAddress($from,0,1));
  242. $smtps->setTrackId($trackid);
  243. $smtps->setReplyTo($this->getValidAddress($from,0,1)); // Set property with this->smtps->setReplyTo after constructor if you want to use another value than the From
  244. if (! empty($moreinheader)) $smtps->setMoreInHeader($moreinheader);
  245. if (! empty($this->html))
  246. {
  247. if (!empty($css))
  248. {
  249. $this->css = $css;
  250. $this->buildCSS();
  251. }
  252. $msg = $this->html;
  253. $msg = $this->checkIfHTML($msg);
  254. }
  255. if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
  256. else $smtps->setBodyContent($msg,'plain');
  257. if ($this->atleastoneimage)
  258. {
  259. foreach ($this->images_encoded as $img)
  260. {
  261. $smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
  262. }
  263. }
  264. if ($this->atleastonefile)
  265. {
  266. foreach ($filename_list as $i => $val)
  267. {
  268. $content=file_get_contents($filename_list[$i]);
  269. $smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
  270. }
  271. }
  272. $smtps->setCC($addr_cc);
  273. $smtps->setBCC($addr_bcc);
  274. $smtps->setErrorsTo($errors_to);
  275. $smtps->setDeliveryReceipt($deliveryreceipt);
  276. $this->smtps=$smtps;
  277. }
  278. // TODO not stable, in progress
  279. else if ($this->sendmode == 'phpmailer')
  280. {
  281. // Use PHPMailer library
  282. // ------------------------------------------
  283. require_once DOL_DOCUMENT_ROOT.'/includes/phpmailer/class.phpmailer.php';
  284. $this->phpmailer = new PHPMailer();
  285. $this->phpmailer->CharSet = $conf->file->character_set_client;
  286. $this->phpmailer->Subject($this->encodetorfc2822($subject));
  287. $this->phpmailer->setTO($this->getValidAddress($to,0,1));
  288. $this->phpmailer->SetFrom($this->getValidAddress($from,0,1));
  289. $this->phpmailer->SetReplyTo($this->getValidAddress($from,0,1)); // Set property with this->phpmailer->setReplyTo after constructor if you want to use another value than the From
  290. // TODO Add trackid into smtp header
  291. // TODO if (! empty($moreinheader)) ...
  292. if (! empty($this->html))
  293. {
  294. if (!empty($css))
  295. {
  296. $this->css = $css;
  297. $this->buildCSS();
  298. }
  299. $msg = $this->html;
  300. $msg = $this->checkIfHTML($msg);
  301. }
  302. if ($this->msgishtml) $smtps->setBodyContent($msg,'html');
  303. else $smtps->setBodyContent($msg,'plain');
  304. if ($this->atleastoneimage)
  305. {
  306. foreach ($this->images_encoded as $img)
  307. {
  308. $smtps->setImageInline($img['image_encoded'],$img['name'],$img['content_type'],$img['cid']);
  309. }
  310. }
  311. if ($this->atleastonefile)
  312. {
  313. foreach ($filename_list as $i => $val)
  314. {
  315. $content=file_get_contents($filename_list[$i]);
  316. $smtps->setAttachment($content,$mimefilename_list[$i],$mimetype_list[$i]);
  317. }
  318. }
  319. $this->phpmailer->setCC($addr_cc);
  320. $this->phpmailer->setBCC($addr_bcc);
  321. $this->phpmailer->setErrorsTo($errors_to);
  322. $this->phpmailer->setDeliveryReceipt($deliveryreceipt);
  323. }
  324. else if ($this->sendmode == 'swiftmailer')
  325. {
  326. // Use Swift Mailer library
  327. // ------------------------------------------
  328. $host = dol_getprefix('email');
  329. require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
  330. // Create the message
  331. $this->message = Swift_Message::newInstance();
  332. // Adding a trackid header to a message
  333. $headers = $this->message->getHeaders();
  334. $headers->addTextHeader('X-Dolibarr-TRACKID', $trackid);
  335. $headerID = time() . '.swiftmailer-dolibarr-' . $trackid . '@' . $host;
  336. $msgid = $headers->get('Message-ID');
  337. $msgid->setId($headerID);
  338. $headers->addIdHeader('References', $headerID);
  339. // TODO if (! empty($moreinheader)) ...
  340. // Give the message a subject
  341. $this->message->setSubject($this->encodetorfc2822($subject));
  342. // Set the From address with an associative array
  343. //$this->message->setFrom(array('john@doe.com' => 'John Doe'));
  344. if (! empty($from)) $this->message->setFrom($this->getArrayAddress($from));
  345. // Set the To addresses with an associative array
  346. if (! empty($to)) $this->message->setTo($this->getArrayAddress($to));
  347. if (! empty($from)) $this->message->SetReplyTo($this->getArrayAddress($from));
  348. $this->message->setCharSet($conf->file->character_set_client);
  349. if (! empty($this->html))
  350. {
  351. if (!empty($css))
  352. {
  353. $this->css = $css;
  354. $this->buildCSS();
  355. }
  356. $msg = $this->html;
  357. $msg = $this->checkIfHTML($msg);
  358. }
  359. if ($this->atleastoneimage)
  360. {
  361. foreach ($this->images_encoded as $img)
  362. {
  363. //$img['fullpath'],$img['image_encoded'],$img['name'],$img['content_type'],$img['cid']
  364. $attachment = Swift_Image::fromPath($img['fullpath'], $img['content_type']);
  365. // embed image
  366. $imgcid = $this->message->embed($attachment);
  367. // replace cid by the one created by swiftmail in html message
  368. $msg = str_replace("cid:".$img['cid'], $imgcid, $msg);
  369. }
  370. }
  371. if ($this->msgishtml) {
  372. $this->message->setBody($msg,'text/html');
  373. // And optionally an alternative body
  374. //$this->message->addPart('Here is the message itself', 'text/plain');
  375. } else {
  376. $this->message->setBody($msg,'text/plain');
  377. // And optionally an alternative body
  378. //$this->message->addPart('<q>Here is the message itself</q>', 'text/html');
  379. }
  380. if ($this->atleastonefile)
  381. {
  382. foreach ($filename_list as $i => $val)
  383. {
  384. //$this->message->attach(Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]));
  385. $attachment = Swift_Attachment::fromPath($filename_list[$i],$mimetype_list[$i]);
  386. $this->message->attach($attachment);
  387. }
  388. }
  389. if (! empty($addr_cc)) $this->message->setCc($this->getArrayAddress($addr_cc));
  390. if (! empty($addr_bcc)) $this->message->setBcc($this->getArrayAddress($addr_bcc));
  391. //if (! empty($errors_to)) $this->message->setErrorsTo($this->getArrayAddress($errors_to);
  392. if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $this->message->setReadReceiptTo($this->getArrayAddress($from));
  393. }
  394. else
  395. {
  396. // Send mail method not correctly defined
  397. // --------------------------------------
  398. $this->error = 'Bad value for sendmode';
  399. }
  400. }
  401. /**
  402. * Send mail that was prepared by constructor
  403. *
  404. * @return boolean True if mail sent, false otherwise
  405. */
  406. function sendfile()
  407. {
  408. global $conf,$db,$langs;
  409. $errorlevel=error_reporting();
  410. error_reporting($errorlevel ^ E_WARNING); // Desactive warnings
  411. $res=false;
  412. if (empty($conf->global->MAIN_DISABLE_ALL_MAILS))
  413. {
  414. require_once DOL_DOCUMENT_ROOT . '/core/class/hookmanager.class.php';
  415. $hookmanager = new HookManager($db);
  416. $hookmanager->initHooks(array(
  417. 'maildao'
  418. ));
  419. $reshook = $hookmanager->executeHooks('doactions', $parameters, $this, $action); // Note that $action and $object may have been modified by some hooks
  420. if (! empty($reshook))
  421. {
  422. $this->error = "Error in hook maildao doactions " . $reshook;
  423. dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_ERR);
  424. return $reshook;
  425. }
  426. // Check number of recipient is lower or equal than MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL
  427. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL=10;
  428. $tmparray1 = explode(',', $this->addr_to);
  429. if (count($tmparray1) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_TO_IN_SAME_EMAIL)
  430. {
  431. $this->error = 'Too much recipients in to:';
  432. dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
  433. return false;
  434. }
  435. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL=10;
  436. $tmparray2 = explode(',', $this->addr_cc);
  437. if (count($tmparray2) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_CC_IN_SAME_EMAIL)
  438. {
  439. $this->error = 'Too much recipients in cc:';
  440. dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
  441. return false;
  442. }
  443. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL=10;
  444. $tmparray3 = explode(',', $this->addr_bcc);
  445. if (count($tmparray3) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_BCC_IN_SAME_EMAIL)
  446. {
  447. $this->error = 'Too much recipients in bcc:';
  448. dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
  449. return false;
  450. }
  451. if (empty($conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)) $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL=10;
  452. if ((count($tmparray1)+count($tmparray2)+count($tmparray3)) > $conf->global->MAIL_MAX_NB_OF_RECIPIENTS_IN_SAME_EMAIL)
  453. {
  454. $this->error = 'Too much recipients in to:, cc:, bcc:';
  455. dol_syslog("CMailFile::sendfile: mail end error=" . $this->error, LOG_WARNING);
  456. return false;
  457. }
  458. // Action according to choosed sending method
  459. if ($this->sendmode == 'mail')
  460. {
  461. // Use mail php function (default PHP method)
  462. // ------------------------------------------
  463. dol_syslog("CMailFile::sendfile addr_to=".$this->addr_to.", subject=".$this->subject, LOG_DEBUG);
  464. dol_syslog("CMailFile::sendfile header=\n".$this->headers, LOG_DEBUG);
  465. //dol_syslog("CMailFile::sendfile message=\n".$message);
  466. // If Windows, sendmail_from must be defined
  467. if (isset($_SERVER["WINDIR"]))
  468. {
  469. if (empty($this->addr_from)) $this->addr_from = 'robot@example.com';
  470. @ini_set('sendmail_from',$this->getValidAddress($this->addr_from,2));
  471. }
  472. // Forcage parametres
  473. if (! empty($conf->global->MAIN_MAIL_SMTP_SERVER)) ini_set('SMTP',$conf->global->MAIN_MAIL_SMTP_SERVER);
  474. if (! empty($conf->global->MAIN_MAIL_SMTP_PORT)) ini_set('smtp_port',$conf->global->MAIN_MAIL_SMTP_PORT);
  475. $dest=$this->getValidAddress($this->addr_to,2);
  476. if (! $dest)
  477. {
  478. $this->error="Failed to send mail with php mail to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port')."<br>Recipient address '$dest' invalid";
  479. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  480. }
  481. else
  482. {
  483. $additionnalparam = ''; // By default
  484. if (! empty($conf->global->MAIN_MAIL_ALLOW_SENDMAIL_F))
  485. {
  486. // le "Return-Path" (retour des messages bounced) dans les header ne fonctionne pas avec tous les MTA
  487. // Le forcage de la valeur grace à l'option -f de sendmail est donc possible si la constante MAIN_MAIL_ALLOW_SENDMAIL_F est definie.
  488. // Having this variable defined may create problems with some sendmail (option -f refused)
  489. // Having this variable not defined may create problems with some other sendmail (option -f required)
  490. $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) : '') );
  491. }
  492. 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
  493. {
  494. $additionnalparam .= ($additionnalparam?' ':'').'-ba';
  495. }
  496. if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_ADDPARAM)) $additionnalparam .= ($additionnalparam?' ':'').'-U '.$additionnalparam; // Use -U to add additionnal params
  497. dol_syslog("CMailFile::sendfile: mail start HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port').", additionnal_parameters=".$additionnalparam, LOG_DEBUG);
  498. $this->message=stripslashes($this->message);
  499. if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
  500. if (! empty($additionnalparam)) $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers, $additionnalparam);
  501. else $res = mail($dest, $this->encodetorfc2822($this->subject), $this->message, $this->headers);
  502. if (! $res)
  503. {
  504. $this->error="Failed to send mail with php mail";
  505. $linuxlike=1;
  506. if (preg_match('/^win/i',PHP_OS)) $linuxlike=0;
  507. if (preg_match('/^mac/i',PHP_OS)) $linuxlike=0;
  508. if (! $linuxlike)
  509. {
  510. $this->error.=" to HOST=".ini_get('SMTP').", PORT=".ini_get('smtp_port'); // This values are value used only for non linuxlike systems
  511. }
  512. $this->error.=".<br>";
  513. $this->error.=$langs->trans("ErrorPhpMailDelivery");
  514. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  515. }
  516. else
  517. {
  518. dol_syslog("CMailFile::sendfile: mail end success", LOG_DEBUG);
  519. }
  520. }
  521. if (isset($_SERVER["WINDIR"]))
  522. {
  523. @ini_restore('sendmail_from');
  524. }
  525. // Forcage parametres
  526. if (! empty($conf->global->MAIN_MAIL_SMTP_SERVER)) ini_restore('SMTP');
  527. if (! empty($conf->global->MAIN_MAIL_SMTP_PORT)) ini_restore('smtp_port');
  528. }
  529. else if ($this->sendmode == 'smtps')
  530. {
  531. // Use SMTPS library
  532. // ------------------------------------------
  533. $this->smtps->setTransportType(0); // Only this method is coded in SMTPs library
  534. // Clean parameters
  535. if (empty($conf->global->MAIN_MAIL_SMTP_SERVER)) $conf->global->MAIN_MAIL_SMTP_SERVER=ini_get('SMTP');
  536. if (empty($conf->global->MAIN_MAIL_SMTP_PORT)) $conf->global->MAIN_MAIL_SMTP_PORT=ini_get('smtp_port');
  537. // TODO Manage alternative parameters
  538. // If we use SSL/TLS
  539. $server=$conf->global->MAIN_MAIL_SMTP_SERVER;
  540. if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) $server='ssl://'.$server;
  541. $port=$conf->global->MAIN_MAIL_SMTP_PORT;
  542. $this->smtps->setHost($server);
  543. $this->smtps->setPort($port); // 25, 465...;
  544. $loginid=''; $loginpass='';
  545. if (! empty($conf->global->MAIN_MAIL_SMTPS_ID))
  546. {
  547. $loginid = $conf->global->MAIN_MAIL_SMTPS_ID;
  548. $this->smtps->setID($loginid);
  549. }
  550. if (! empty($conf->global->MAIN_MAIL_SMTPS_PW))
  551. {
  552. $loginpass = $conf->global->MAIN_MAIL_SMTPS_PW;
  553. $this->smtps->setPW($loginpass);
  554. }
  555. $res=true;
  556. $from=$this->smtps->getFrom('org');
  557. if (! $from)
  558. {
  559. $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->MAIN_MAIL_SMTP_PORT."<br>Sender address '$from' invalid";
  560. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  561. $res=false;
  562. }
  563. $dest=$this->smtps->getTo();
  564. if (! $dest)
  565. {
  566. $this->error="Failed to send mail with smtps lib to HOST=".$server.", PORT=".$conf->global->MAIN_MAIL_SMTP_PORT."<br>Recipient address '$dest' invalid";
  567. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  568. $res=false;
  569. }
  570. if ($res)
  571. {
  572. if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->smtps->setDebug(true);
  573. $result=$this->smtps->sendMsg();
  574. //print $result;
  575. if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
  576. $result=$this->smtps->getErrors();
  577. if (empty($this->error) && empty($result)) $res=true;
  578. else
  579. {
  580. if (empty($this->error)) $this->error=$result;
  581. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  582. $res=false;
  583. }
  584. }
  585. }
  586. else if ($this->sendmode == 'swiftmailer')
  587. {
  588. // Use Swift Mailer library
  589. // ------------------------------------------
  590. require_once DOL_DOCUMENT_ROOT.'/includes/swiftmailer/lib/swift_required.php';
  591. // Forcage parametres
  592. if (empty($conf->global->MAIN_MAIL_SMTP_SERVER)) $conf->global->MAIN_MAIL_SMTP_SERVER=ini_get('SMTP');
  593. if (empty($conf->global->MAIN_MAIL_SMTP_PORT)) $conf->global->MAIN_MAIL_SMTP_PORT=ini_get('smtp_port');
  594. // If we use SSL/TLS
  595. $server=$conf->global->MAIN_MAIL_SMTP_SERVER;
  596. $secure='';
  597. //var_dump(stream_get_transports());
  598. if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) $secure='ssl';
  599. if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $secure='tls';
  600. $this->transport = Swift_SmtpTransport::newInstance($server, $conf->global->MAIN_MAIL_SMTP_PORT, $secure);
  601. if (! empty($conf->global->MAIN_MAIL_SMTPS_ID)) $this->transport->setUsername($conf->global->MAIN_MAIL_SMTPS_ID);
  602. if (! empty($conf->global->MAIN_MAIL_SMTPS_PW)) $this->transport->setPassword($conf->global->MAIN_MAIL_SMTPS_PW);
  603. //$smtps->_msgReplyTo = 'reply@web.com';
  604. // Create the Mailer using your created Transport
  605. $this->mailer = Swift_Mailer::newInstance($this->transport);
  606. if (! empty($conf->global->MAIN_MAIL_DEBUG)) {
  607. // To use the ArrayLogger
  608. $this->logger = new Swift_Plugins_Loggers_ArrayLogger();
  609. // Or to use the Echo Logger
  610. //$this->logger = new Swift_Plugins_Loggers_EchoLogger();
  611. $this->mailer->registerPlugin(new Swift_Plugins_LoggerPlugin($this->logger));
  612. }
  613. // send mail
  614. try {
  615. $result = $this->mailer->send($this->message);
  616. } catch (Exception $e) {
  617. $this->error = $e->getMessage();
  618. }
  619. if (! empty($conf->global->MAIN_MAIL_DEBUG)) $this->dump_mail();
  620. $res = true;
  621. if (! empty($this->error) && ! $result) {
  622. dol_syslog("CMailFile::sendfile: mail end error=".$this->error, LOG_ERR);
  623. $res=false;
  624. } else {
  625. $this->error = sprintf ("Sent %d messages\n", $result);
  626. }
  627. }
  628. else
  629. {
  630. // Send mail method not correctly defined
  631. // --------------------------------------
  632. return 'Bad value for sendmode';
  633. }
  634. }
  635. else
  636. {
  637. $this->error='No mail sent. Feature is disabled by option MAIN_DISABLE_ALL_MAILS';
  638. dol_syslog("CMailFile::sendfile: ".$this->error, LOG_WARNING);
  639. }
  640. error_reporting($errorlevel); // Reactive niveau erreur origine
  641. return $res;
  642. }
  643. /**
  644. * Encode subject according to RFC 2822 - http://en.wikipedia.org/wiki/MIME#Encoded-Word
  645. *
  646. * @param string $stringtoencode String to encode
  647. * @return string string encoded
  648. */
  649. static function encodetorfc2822($stringtoencode)
  650. {
  651. global $conf;
  652. return '=?'.$conf->file->character_set_client.'?B?'.base64_encode($stringtoencode).'?=';
  653. }
  654. /**
  655. * Read a file on disk and return encoded content for emails (mode = 'mail')
  656. *
  657. * @param string $sourcefile Path to file to encode
  658. * @return int <0 if KO, encoded string if OK
  659. */
  660. function _encode_file($sourcefile)
  661. {
  662. $newsourcefile=dol_osencode($sourcefile);
  663. if (is_readable($newsourcefile))
  664. {
  665. $contents = file_get_contents($newsourcefile); // Need PHP 4.3
  666. $encoded = chunk_split(base64_encode($contents), 76, $this->eol); // 76 max is defined into http://tools.ietf.org/html/rfc2047
  667. return $encoded;
  668. }
  669. else
  670. {
  671. $this->error="Error: Can't read file '".$sourcefile."' into _encode_file";
  672. dol_syslog("CMailFile::encode_file: ".$this->error, LOG_ERR);
  673. return -1;
  674. }
  675. }
  676. /**
  677. * Write content of a SMTP request into a dump file (mode = all)
  678. * Used for debugging.
  679. * Note that to see full SMTP protocol, you can use tcpdump -w /tmp/smtp -s 2000 port 25"
  680. *
  681. * @return void
  682. */
  683. function dump_mail()
  684. {
  685. global $conf,$dolibarr_main_data_root;
  686. if (@is_writeable($dolibarr_main_data_root)) // Avoid fatal error on fopen with open_basedir
  687. {
  688. $outputfile=$dolibarr_main_data_root."/dolibarr_mail.log";
  689. $fp = fopen($outputfile,"w");
  690. if ($this->sendmode == 'mail')
  691. {
  692. fputs($fp, $this->headers);
  693. fputs($fp, $this->eol); // This eol is added by the mail function, so we add it in log
  694. fputs($fp, $this->message);
  695. }
  696. elseif ($this->sendmode == 'smtps')
  697. {
  698. fputs($fp, $this->smtps->log); // this->smtps->log is filled only if MAIN_MAIL_DEBUG was set to on
  699. }
  700. elseif ($this->sendmode == 'swiftmailer')
  701. {
  702. fputs($fp, $this->logger->dump()); // this->logger is filled only if MAIN_MAIL_DEBUG was set to on
  703. }
  704. fclose($fp);
  705. if (! empty($conf->global->MAIN_UMASK))
  706. @chmod($outputfile, octdec($conf->global->MAIN_UMASK));
  707. }
  708. }
  709. /**
  710. * Correct an uncomplete html string
  711. *
  712. * @param string $msg String
  713. * @return string Completed string
  714. */
  715. function checkIfHTML($msg)
  716. {
  717. if (!preg_match('/^[\s\t]*<html/i',$msg))
  718. {
  719. $out = "<html><head><title></title>";
  720. if (!empty($this->styleCSS)) $out.= $this->styleCSS;
  721. $out.= "</head><body";
  722. if (!empty($this->bodyCSS)) $out.= $this->bodyCSS;
  723. $out.= ">";
  724. $out.= $msg;
  725. $out.= "</body></html>";
  726. }
  727. else
  728. {
  729. $out = $msg;
  730. }
  731. return $out;
  732. }
  733. /**
  734. * Build a css style (mode = all) into this->styleCSS and this->bodyCSS
  735. *
  736. * @return css
  737. */
  738. function buildCSS()
  739. {
  740. if (! empty($this->css))
  741. {
  742. // Style CSS
  743. $this->styleCSS = '<style type="text/css">';
  744. $this->styleCSS.= 'body {';
  745. if ($this->css['bgcolor'])
  746. {
  747. $this->styleCSS.= ' background-color: '.$this->css['bgcolor'].';';
  748. $this->bodyCSS.= ' bgcolor="'.$this->css['bgcolor'].'"';
  749. }
  750. if ($this->css['bgimage'])
  751. {
  752. // TODO recuperer cid
  753. $this->styleCSS.= ' background-image: url("cid:'.$this->css['bgimage_cid'].'");';
  754. }
  755. $this->styleCSS.= '}';
  756. $this->styleCSS.= '</style>';
  757. }
  758. }
  759. /**
  760. * Create SMTP headers (mode = 'mail')
  761. *
  762. * @return string headers
  763. */
  764. function write_smtpheaders()
  765. {
  766. global $conf;
  767. $out = "";
  768. $host = dol_getprefix('email');
  769. // Sender
  770. //$out.= "Sender: ".getValidAddress($this->addr_from,2)).$this->eol2;
  771. $out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol2;
  772. if (! empty($conf->global->MAIN_MAIL_SENDMAIL_FORCE_BA))
  773. {
  774. $out.= "To: ".$this->getValidAddress($this->addr_to,0,1).$this->eol2;
  775. }
  776. // 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.
  777. $out.= "Return-Path: ".$this->getValidAddress($this->addr_from,0,1).$this->eol2;
  778. if (isset($this->reply_to) && $this->reply_to) $out.= "Reply-To: ".$this->getValidAddress($this->reply_to,2).$this->eol2;
  779. if (isset($this->errors_to) && $this->errors_to) $out.= "Errors-To: ".$this->getValidAddress($this->errors_to,2).$this->eol2;
  780. // Receiver
  781. if (isset($this->addr_cc) && $this->addr_cc) $out.= "Cc: ".$this->getValidAddress($this->addr_cc,2).$this->eol2;
  782. if (isset($this->addr_bcc) && $this->addr_bcc) $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 ?
  783. // Delivery receipt
  784. if (isset($this->deliveryreceipt) && $this->deliveryreceipt == 1) $out.= "Disposition-Notification-To: ".$this->getValidAddress($this->addr_from,2).$this->eol2;
  785. //$out.= "X-Priority: 3".$this->eol2;
  786. $out.= 'Date: ' . date("r") . $this->eol2;
  787. $trackid = $this->trackid;
  788. if ($trackid)
  789. {
  790. // References is kept in response and Message-ID is returned into In-Reply-To:
  791. $out.= 'Message-ID: <' . time() . '.phpmail-dolibarr-'.$trackid.'@' . $host . ">" . $this->eol2; // Uppercase seems replaced by phpmail
  792. $out.= 'References: <' . time() . '.phpmail-dolibarr-'.$trackid.'@' . $host . ">" . $this->eol2;
  793. $out.= 'X-Dolibarr-TRACKID: '.$trackid. $this->eol2;
  794. }
  795. else
  796. {
  797. $out.= 'Message-ID: <' . time() . '.phpmail@' . $host . ">" . $this->eol2;
  798. }
  799. $out.= "X-Mailer: Dolibarr version " . DOL_VERSION ." (using php mail)".$this->eol2;
  800. $out.= "Mime-Version: 1.0".$this->eol2;
  801. //$out.= "From: ".$this->getValidAddress($this->addr_from,3,1).$this->eol;
  802. $out.= "Content-Type: multipart/mixed; boundary=\"".$this->mixed_boundary."\"".$this->eol2;
  803. $out.= "Content-Transfer-Encoding: 8bit".$this->eol2;
  804. dol_syslog("CMailFile::write_smtpheaders smtp_header=\n".$out);
  805. return $out;
  806. }
  807. /**
  808. * Create header MIME (mode = 'mail')
  809. *
  810. * @param array $filename_list Array of filenames
  811. * @param array $mimefilename_list Array of mime types
  812. * @return string mime headers
  813. */
  814. function write_mimeheaders($filename_list, $mimefilename_list)
  815. {
  816. $mimedone=0;
  817. $out = "";
  818. if ($filename_list)
  819. {
  820. $filename_list_size=count($filename_list);
  821. for($i=0;$i < $filename_list_size;$i++)
  822. {
  823. if ($filename_list[$i])
  824. {
  825. if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
  826. $out.= "X-attachments: $filename_list[$i]".$this->eol2;
  827. }
  828. }
  829. }
  830. dol_syslog("CMailFile::write_mimeheaders mime_header=\n".$out, LOG_DEBUG);
  831. return $out;
  832. }
  833. /**
  834. * Return email content (mode = 'mail')
  835. *
  836. * @param string $msgtext Message string
  837. * @return string String content
  838. */
  839. function write_body($msgtext)
  840. {
  841. global $conf;
  842. $out='';
  843. $out.= "--" . $this->mixed_boundary . $this->eol;
  844. if ($this->atleastoneimage)
  845. {
  846. $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol;
  847. $out.= $this->eol;
  848. $out.= "--" . $this->alternative_boundary . $this->eol;
  849. }
  850. // Make RFC821 Compliant, replace bare linefeeds
  851. $strContent = preg_replace("/(?<!\r)\n/si", "\r\n", $msgtext);
  852. if (! empty($conf->global->MAIN_FIX_FOR_BUGGED_MTA))
  853. {
  854. $strContent = preg_replace("/\r\n/si", "\n", $strContent);
  855. }
  856. $strContentAltText = '';
  857. if ($this->msgishtml)
  858. {
  859. $strContentAltText = html_entity_decode(strip_tags($strContent));
  860. $strContentAltText = rtrim(wordwrap($strContentAltText, 75, "\r\n"));
  861. // Check if html header already in message, if not complete the message
  862. $strContent = $this->checkIfHTML($strContent);
  863. }
  864. // Make RFC2045 Compliant, split lines
  865. //$strContent = rtrim(chunk_split($strContent)); // Function chunck_split seems ko if not used on a base64 content
  866. $strContent = rtrim(wordwrap($strContent)); // TODO Using this method creates unexpected line break on text/plain content.
  867. if ($this->msgishtml)
  868. {
  869. if ($this->atleastoneimage)
  870. {
  871. $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
  872. $out.= $this->eol.($strContentAltText?$strContentAltText:strip_tags($strContent)).$this->eol; // Add plain text message
  873. $out.= "--" . $this->alternative_boundary . $this->eol;
  874. $out.= "Content-Type: multipart/related; boundary=\"".$this->related_boundary."\"".$this->eol;
  875. $out.= $this->eol;
  876. $out.= "--" . $this->related_boundary . $this->eol;
  877. }
  878. if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part before html part
  879. {
  880. $out.= "Content-Type: multipart/alternative; boundary=\"".$this->alternative_boundary."\"".$this->eol;
  881. $out.= $this->eol;
  882. $out.= "--" . $this->alternative_boundary . $this->eol;
  883. $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
  884. $out.= $this->eol.$strContentAltText.$this->eol;
  885. $out.= "--" . $this->alternative_boundary . $this->eol;
  886. }
  887. $out.= "Content-Type: text/html; charset=".$conf->file->character_set_client.$this->eol;
  888. $out.= $this->eol.$strContent.$this->eol;
  889. if (! $this->atleastoneimage && $strContentAltText && ! empty($conf->global->MAIN_MAIL_USE_MULTI_PART)) // Add plain text message part after html part
  890. {
  891. $out.= "--" . $this->alternative_boundary . "--". $this->eol;
  892. }
  893. }
  894. else
  895. {
  896. $out.= "Content-Type: text/plain; charset=".$conf->file->character_set_client.$this->eol;
  897. $out.= $this->eol.$strContent.$this->eol;
  898. }
  899. $out.= $this->eol;
  900. // Encode images
  901. if ($this->atleastoneimage)
  902. {
  903. $out .= $this->write_images($this->images_encoded);
  904. // always end related and end alternative after inline images
  905. $out .= "--" . $this->related_boundary . "--" . $this->eol;
  906. $out .= $this->eol . "--" . $this->alternative_boundary . "--" . $this->eol;
  907. $out .= $this->eol;
  908. }
  909. return $out;
  910. }
  911. /**
  912. * Attach file to email (mode = 'mail')
  913. *
  914. * @param array $filename_list Tableau
  915. * @param array $mimetype_list Tableau
  916. * @param array $mimefilename_list Tableau
  917. * @return string Chaine fichiers encodes
  918. */
  919. function write_files($filename_list,$mimetype_list,$mimefilename_list)
  920. {
  921. $out = '';
  922. $filename_list_size=count($filename_list);
  923. for($i=0;$i < $filename_list_size;$i++)
  924. {
  925. if ($filename_list[$i])
  926. {
  927. dol_syslog("CMailFile::write_files: i=$i");
  928. $encoded = $this->_encode_file($filename_list[$i]);
  929. if ($encoded >= 0)
  930. {
  931. if ($mimefilename_list[$i]) $filename_list[$i] = $mimefilename_list[$i];
  932. if (! $mimetype_list[$i]) {
  933. $mimetype_list[$i] = "application/octet-stream";
  934. }
  935. $out.= "--" . $this->mixed_boundary . $this->eol;
  936. $out.= "Content-Disposition: attachment; filename=\"".$filename_list[$i]."\"".$this->eol;
  937. $out.= "Content-Type: " . $mimetype_list[$i] . "; name=\"".$filename_list[$i]."\"".$this->eol;
  938. $out.= "Content-Transfer-Encoding: base64".$this->eol;
  939. $out.= "Content-Description: File Attachment".$this->eol;
  940. $out.= $this->eol;
  941. $out.= $encoded;
  942. $out.= $this->eol;
  943. //$out.= $this->eol;
  944. }
  945. else
  946. {
  947. return $encoded;
  948. }
  949. }
  950. }
  951. return $out;
  952. }
  953. /**
  954. * Attach an image to email (mode = 'mail')
  955. *
  956. * @param array $images_list Tableau
  957. * @return string Chaine images encodees
  958. */
  959. function write_images($images_list)
  960. {
  961. $out = '';
  962. if ($images_list)
  963. {
  964. foreach ($images_list as $img)
  965. {
  966. dol_syslog("CMailFile::write_images: i=$i");
  967. $out.= "--" . $this->related_boundary . $this->eol; // always related for an inline image
  968. $out.= "Content-Type: " . $img["content_type"] . "; name=\"".$img["name"]."\"".$this->eol;
  969. $out.= "Content-Transfer-Encoding: base64".$this->eol;
  970. $out.= "Content-Disposition: inline; filename=\"".$img["name"]."\"".$this->eol;
  971. $out.= "Content-ID: <".$img["cid"].">".$this->eol;
  972. $out.= $this->eol;
  973. $out.= $img["image_encoded"];
  974. $out.= $this->eol;
  975. }
  976. }
  977. return $out;
  978. }
  979. /**
  980. * Try to create a socket connection
  981. *
  982. * @param string $host Add ssl:// for SSL/TLS.
  983. * @param int $port Example: 25, 465
  984. * @return int Socket id if ok, 0 if KO
  985. */
  986. function check_server_port($host,$port)
  987. {
  988. global $conf;
  989. $_retVal=0;
  990. $timeout=5; // Timeout in seconds
  991. if (function_exists('fsockopen'))
  992. {
  993. // If we use SSL/TLS
  994. if (! empty($conf->global->MAIN_MAIL_EMAIL_TLS) && function_exists('openssl_open')) $host='ssl://'.$host;
  995. // tls smtp start with no encryption
  996. //if (! empty($conf->global->MAIN_MAIL_EMAIL_STARTTLS) && function_exists('openssl_open')) $host='tls://'.$host;
  997. dol_syslog("Try socket connection to host=".$host." port=".$port);
  998. //See if we can connect to the SMTP server
  999. if ($socket = @fsockopen(
  1000. $host, // Host to test, IP or domain. Add ssl:// for SSL/TLS.
  1001. $port, // which Port number to use
  1002. $errno, // actual system level error
  1003. $errstr, // and any text that goes with the error
  1004. $timeout
  1005. )) // timeout for reading/writing data over the socket
  1006. {
  1007. // Windows still does not have support for this timeout function
  1008. if (function_exists('stream_set_timeout')) stream_set_timeout($socket, $timeout, 0);
  1009. dol_syslog("Now we wait for answer 220");
  1010. // Check response from Server
  1011. if ( $_retVal = $this->server_parse($socket, "220") ) $_retVal = $socket;
  1012. }
  1013. else
  1014. {
  1015. $this->error = utf8_check('Error '.$errno.' - '.$errstr)?'Error '.$errno.' - '.$errstr:utf8_encode('Error '.$errno.' - '.$errstr);
  1016. }
  1017. }
  1018. return $_retVal;
  1019. }
  1020. /**
  1021. * This function has been modified as provided by SirSir to allow multiline responses when
  1022. * using SMTP Extensions.
  1023. *
  1024. * @param Socket $socket Socket
  1025. * @param string $response Response string
  1026. * @return boolean true if success
  1027. */
  1028. function server_parse($socket, $response)
  1029. {
  1030. $_retVal = true; // Indicates if Object was created or not
  1031. $server_response = '';
  1032. while (substr($server_response,3,1) != ' ')
  1033. {
  1034. if (! ($server_response = fgets($socket, 256)) )
  1035. {
  1036. $this->error="Couldn't get mail server response codes";
  1037. return false;
  1038. }
  1039. }
  1040. if( !( substr($server_response, 0, 3) == $response ) )
  1041. {
  1042. $this->error="Ran into problems sending Mail.\r\nResponse: $server_response";
  1043. $_retVal = false;
  1044. }
  1045. return $_retVal;
  1046. }
  1047. /**
  1048. * Seearch images into html message and init array this->images_encoded if found
  1049. *
  1050. * @param string $images_dir Location of physical images files
  1051. * @return int >0 if OK, <0 if KO
  1052. */
  1053. function findHtmlImages($images_dir)
  1054. {
  1055. // Build the list of image extensions
  1056. $extensions = array_keys($this->image_types);
  1057. preg_match_all('/(?:"|\')([^"\']+\.('.implode('|', $extensions).'))(?:"|\')/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found
  1058. if ($matches)
  1059. {
  1060. $i=0;
  1061. foreach ($matches[1] as $full)
  1062. {
  1063. if (preg_match('/file=([A-Za-z0-9_\-\/]+[\.]?[A-Za-z0-9]+)?$/i',$full,$regs)) // If xxx is 'file=aaa'
  1064. {
  1065. $img = $regs[1];
  1066. if (file_exists($images_dir.'/'.$img))
  1067. {
  1068. // Image path in src
  1069. $src = preg_quote($full,'/');
  1070. // Image full path
  1071. $this->html_images[$i]["fullpath"] = $images_dir.'/'.$img;
  1072. // Image name
  1073. $this->html_images[$i]["name"] = $img;
  1074. // Content type
  1075. if (preg_match('/^.+\.(\w{3,4})$/', $img, $reg))
  1076. {
  1077. $ext=strtolower($reg[1]);
  1078. $this->html_images[$i]["content_type"] = $this->image_types[$ext];
  1079. }
  1080. // cid
  1081. $this->html_images[$i]["cid"] = dol_hash(uniqid(time()), 3); // Force md5 hash (does not contains special chars)
  1082. $this->html = preg_replace("/src=\"$src\"|src='$src'/i", "src=\"cid:".$this->html_images[$i]["cid"]."\"", $this->html);
  1083. }
  1084. $i++;
  1085. }
  1086. }
  1087. if (!empty($this->html_images))
  1088. {
  1089. $inline = array();
  1090. $i=0;
  1091. foreach ($this->html_images as $img)
  1092. {
  1093. $fullpath = $images_dir.'/'.$img["name"];
  1094. // If duplicate images are embedded, they may show up as attachments, so remove them.
  1095. if (!in_array($fullpath,$inline))
  1096. {
  1097. // Read image file
  1098. if ($image = file_get_contents($fullpath))
  1099. {
  1100. // On garde que le nom de l'image
  1101. preg_match('/([A-Za-z0-9_-]+[\.]?[A-Za-z0-9]+)?$/i',$img["name"],$regs);
  1102. $imgName = $regs[1];
  1103. $this->images_encoded[$i]['name'] = $imgName;
  1104. $this->images_encoded[$i]['fullpath'] = $fullpath;
  1105. $this->images_encoded[$i]['content_type'] = $img["content_type"];
  1106. $this->images_encoded[$i]['cid'] = $img["cid"];
  1107. // Encodage de l'image
  1108. $this->images_encoded[$i]["image_encoded"] = chunk_split(base64_encode($image), 68, $this->eol);
  1109. $inline[] = $fullpath;
  1110. }
  1111. }
  1112. $i++;
  1113. }
  1114. }
  1115. else
  1116. {
  1117. return -1;
  1118. }
  1119. return 1;
  1120. }
  1121. else
  1122. {
  1123. return 0;
  1124. }
  1125. }
  1126. /**
  1127. * Return a formatted address string for SMTP protocol
  1128. *
  1129. * @param string $address Example: 'John Doe <john@doe.com>, Alan Smith <alan@smith.com>' or 'john@doe.com, alan@smith.com'
  1130. * @param int $format 0=auto, 1=emails with <>, 2=emails without <>, 3=auto + label between "
  1131. * @param int $encode 0=No encode name, 1=Encode name to RFC2822
  1132. * @param int $maxnumberofemail 0=No limit. Otherwise, maximum number of emails returned ($address may contains several email separated with ','). Add '...' if there is more.
  1133. * @return string If format 0: '<john@doe.com>' or 'John Doe <john@doe.com>' or '=?UTF-8?B?Sm9obiBEb2U=?= <john@doe.com>'
  1134. * If format 1: '<john@doe.com>'
  1135. * If format 2: 'john@doe.com'
  1136. * If format 3: '<john@doe.com>' or '"John Doe" <john@doe.com>' or '"=?UTF-8?B?Sm9obiBEb2U=?=" <john@doe.com>'
  1137. * If format 4: 'John Doe' or 'john@doe.com' if no label exists
  1138. */
  1139. static function getValidAddress($address,$format,$encode=0,$maxnumberofemail=0)
  1140. {
  1141. global $conf;
  1142. $ret='';
  1143. $arrayaddress=explode(',',$address);
  1144. // Boucle sur chaque composant de l'adresse
  1145. $i=0;
  1146. foreach($arrayaddress as $val)
  1147. {
  1148. if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
  1149. {
  1150. $name = trim($regs[1]);
  1151. $email = trim($regs[2]);
  1152. }
  1153. else
  1154. {
  1155. $name = '';
  1156. $email = trim($val);
  1157. }
  1158. if ($email)
  1159. {
  1160. $i++;
  1161. $newemail='';
  1162. if ($format == 4)
  1163. {
  1164. $newemail = $name?$name:$email;
  1165. }
  1166. if ($format == 2)
  1167. {
  1168. $newemail=$email;
  1169. }
  1170. if ($format == 1 || $format == 3)
  1171. {
  1172. $newemail='<'.$email.'>';
  1173. }
  1174. if ($format == 0 || $format == 3)
  1175. {
  1176. if (! empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)) $newemail='<'.$email.'>';
  1177. elseif (! $name) $newemail='<'.$email.'>';
  1178. else $newemail=($format==3?'"':'').($encode?self::encodetorfc2822($name):$name).($format==3?'"':'').' <'.$email.'>';
  1179. }
  1180. $ret=($ret ? $ret.',' : '').$newemail;
  1181. // Stop if we have too much records
  1182. if ($maxnumberofemail && $i >= $maxnumberofemail)
  1183. {
  1184. if (count($arrayaddress) > $maxnumberofemail) $ret.='...';
  1185. break;
  1186. }
  1187. }
  1188. }
  1189. return $ret;
  1190. }
  1191. /**
  1192. * Return a formatted array of address string for SMTP protocol
  1193. *
  1194. * @param string $address Example: 'John Doe <john@doe.com>, Alan Smith <alan@smith.com>' or 'john@doe.com, alan@smith.com'
  1195. * @return array array of email => name
  1196. */
  1197. function getArrayAddress($address)
  1198. {
  1199. global $conf;
  1200. $ret=array();
  1201. $arrayaddress=explode(',',$address);
  1202. // Boucle sur chaque composant de l'adresse
  1203. foreach($arrayaddress as $val)
  1204. {
  1205. if (preg_match('/^(.*)<(.*)>$/i',trim($val),$regs))
  1206. {
  1207. $name = trim($regs[1]);
  1208. $email = trim($regs[2]);
  1209. }
  1210. else
  1211. {
  1212. $name = null;
  1213. $email = trim($val);
  1214. }
  1215. $ret[$email]=empty($conf->global->MAIN_MAIL_NO_FULL_EMAIL)?$name:null;
  1216. }
  1217. return $ret;
  1218. }
  1219. }