email.class.inc.php 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519
  1. <?php
  2. // Copyright (C) 2010-2016 Combodo SARL
  3. //
  4. // This file is part of iTop.
  5. //
  6. // iTop is free software; you can redistribute it and/or modify
  7. // it under the terms of the GNU Affero General Public License as published by
  8. // the Free Software Foundation, either version 3 of the License, or
  9. // (at your option) any later version.
  10. //
  11. // iTop is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU Affero General Public License for more details.
  15. //
  16. // You should have received a copy of the GNU Affero General Public License
  17. // along with iTop. If not, see <http://www.gnu.org/licenses/>
  18. /**
  19. * Send an email (abstraction for synchronous/asynchronous modes)
  20. *
  21. * @copyright Copyright (C) 2010-2016 Combodo SARL
  22. * @license http://opensource.org/licenses/AGPL-3.0
  23. */
  24. require_once(APPROOT.'/lib/swiftmailer/lib/swift_required.php');
  25. Swift_Preferences::getInstance()->setCharset('UTF-8');
  26. define ('EMAIL_SEND_OK', 0);
  27. define ('EMAIL_SEND_PENDING', 1);
  28. define ('EMAIL_SEND_ERROR', 2);
  29. class EMail
  30. {
  31. // Serialization formats
  32. const ORIGINAL_FORMAT = 1; // Original format, consisting in serializing the whole object, inculding the Swift Mailer's object.
  33. // Did not work with attachements since their binary representation cannot be stored as a valid UTF-8 string
  34. const FORMAT_V2 = 2; // New format, only the raw data are serialized (base64 encoded if needed)
  35. protected static $m_oConfig = null;
  36. protected $m_aData; // For storing data to serialize
  37. public function LoadConfig($sConfigFile = ITOP_DEFAULT_CONFIG_FILE)
  38. {
  39. if (is_null(self::$m_oConfig))
  40. {
  41. self::$m_oConfig = new Config($sConfigFile);
  42. }
  43. }
  44. protected $m_oMessage;
  45. public function __construct()
  46. {
  47. $this->m_aData = array();
  48. $this->m_oMessage = Swift_Message::newInstance();
  49. $oEncoder = new Swift_Mime_ContentEncoder_PlainContentEncoder('8bit');
  50. $this->m_oMessage->setEncoder($oEncoder);
  51. }
  52. /**
  53. * Custom serialization method
  54. * No longer use the brute force "serialize" method since
  55. * 1) It does not work with binary attachments (since they cannot be stored in a UTF-8 text field)
  56. * 2) The size tends to be quite big (sometimes ten times the size of the email)
  57. */
  58. public function SerializeV2()
  59. {
  60. return serialize($this->m_aData);
  61. }
  62. /**
  63. * Custom de-serialization method
  64. * @param string $sSerializedMessage The serialized representation of the message
  65. */
  66. static public function UnSerializeV2($sSerializedMessage)
  67. {
  68. $aData = unserialize($sSerializedMessage);
  69. $oMessage = new Email();
  70. if (array_key_exists('body', $aData))
  71. {
  72. $oMessage->SetBody($aData['body']['body'], $aData['body']['mimeType']);
  73. }
  74. if (array_key_exists('message_id', $aData))
  75. {
  76. $oMessage->SetMessageId($aData['message_id']);
  77. }
  78. if (array_key_exists('bcc', $aData))
  79. {
  80. $oMessage->SetRecipientBCC($aData['bcc']);
  81. }
  82. if (array_key_exists('cc', $aData))
  83. {
  84. $oMessage->SetRecipientCC($aData['cc']);
  85. }
  86. if (array_key_exists('from', $aData))
  87. {
  88. $oMessage->SetRecipientFrom($aData['from']['address'], $aData['from']['label']);
  89. }
  90. if (array_key_exists('reply_to', $aData))
  91. {
  92. $oMessage->SetRecipientReplyTo($aData['reply_to']);
  93. }
  94. if (array_key_exists('to', $aData))
  95. {
  96. $oMessage->SetRecipientTO($aData['to']);
  97. }
  98. if (array_key_exists('subject', $aData))
  99. {
  100. $oMessage->SetSubject($aData['subject']);
  101. }
  102. if (array_key_exists('headers', $aData))
  103. {
  104. foreach($aData['headers'] as $sKey => $sValue)
  105. {
  106. $oMessage->AddToHeader($sKey, $sValue);
  107. }
  108. }
  109. if (array_key_exists('parts', $aData))
  110. {
  111. foreach($aData['parts'] as $aPart)
  112. {
  113. $oMessage->AddPart($aPart['text'], $aPart['mimeType']);
  114. }
  115. }
  116. if (array_key_exists('attachments', $aData))
  117. {
  118. foreach($aData['attachments'] as $aAttachment)
  119. {
  120. $oMessage->AddAttachment(base64_decode($aAttachment['data']), $aAttachment['filename'], $aAttachment['mimeType']);
  121. }
  122. }
  123. return $oMessage;
  124. }
  125. protected function SendAsynchronous(&$aIssues, $oLog = null)
  126. {
  127. try
  128. {
  129. AsyncSendEmail::AddToQueue($this, $oLog);
  130. }
  131. catch(Exception $e)
  132. {
  133. $aIssues = array($e->GetMessage());
  134. return EMAIL_SEND_ERROR;
  135. }
  136. $aIssues = array();
  137. return EMAIL_SEND_PENDING;
  138. }
  139. protected function SendSynchronous(&$aIssues, $oLog = null)
  140. {
  141. // If the body of the message is in HTML, embed all images based on attachments
  142. $this->EmbedInlineImages();
  143. $this->LoadConfig();
  144. $sTransport = self::$m_oConfig->Get('email_transport');
  145. switch ($sTransport)
  146. {
  147. case 'SMTP':
  148. $sHost = self::$m_oConfig->Get('email_transport_smtp.host');
  149. $sPort = self::$m_oConfig->Get('email_transport_smtp.port');
  150. $sEncryption = self::$m_oConfig->Get('email_transport_smtp.encryption');
  151. $sUserName = self::$m_oConfig->Get('email_transport_smtp.username');
  152. $sPassword = self::$m_oConfig->Get('email_transport_smtp.password');
  153. $oTransport = Swift_SmtpTransport::newInstance($sHost, $sPort, $sEncryption);
  154. if (strlen($sUserName) > 0)
  155. {
  156. $oTransport->setUsername($sUserName);
  157. $oTransport->setPassword($sPassword);
  158. }
  159. break;
  160. case 'Null':
  161. $oTransport = Swift_NullTransport::newInstance();
  162. break;
  163. case 'LogFile':
  164. $oTransport = Swift_LogFileTransport::newInstance();
  165. $oTransport->setLogFile(APPROOT.'log/mail.log');
  166. break;
  167. case 'PHPMail':
  168. default:
  169. $oTransport = Swift_MailTransport::newInstance();
  170. }
  171. $oMailer = Swift_Mailer::newInstance($oTransport);
  172. $aFailedRecipients = array();
  173. $iSent = $oMailer->send($this->m_oMessage, $aFailedRecipients);
  174. if ($iSent === 0)
  175. {
  176. // Beware: it seems that $aFailedRecipients sometimes contains the recipients that actually received the message !!!
  177. IssueLog::Warning('Email sending failed: Some recipients were invalid, aFailedRecipients contains: '.implode(', ', $aFailedRecipients));
  178. $aIssues = array('Some recipients were invalid.');
  179. return EMAIL_SEND_ERROR;
  180. }
  181. else
  182. {
  183. $aIssues = array();
  184. return EMAIL_SEND_OK;
  185. }
  186. }
  187. /**
  188. * Reprocess the body of the message (if it is an HTML message)
  189. * to replace the URL of images based on attachments by a link
  190. * to an embedded image (i.e. cid:....)
  191. */
  192. protected function EmbedInlineImages()
  193. {
  194. if ($this->m_aData['body']['mimeType'] == 'text/html')
  195. {
  196. $oDOMDoc = new DOMDocument();
  197. $oDOMDoc->preserveWhitespace = true;
  198. @$oDOMDoc->loadHTML('<?xml encoding="UTF-8"?>'.$this->m_aData['body']['body']); // For loading HTML chunks where the character set is not specified
  199. $oXPath = new DOMXPath($oDOMDoc);
  200. $sXPath = "//img[@data-img-id]";
  201. $oImagesList = $oXPath->query($sXPath);
  202. if ($oImagesList->length != 0)
  203. {
  204. foreach($oImagesList as $oImg)
  205. {
  206. $iAttId = $oImg->getAttribute('data-img-id');
  207. $oAttachment = MetaModel::GetObject('InlineImage', $iAttId, false, true /* Allow All Data */);
  208. if ($oAttachment)
  209. {
  210. $oDoc = $oAttachment->Get('contents');
  211. $oSwiftImage = new Swift_Image($oDoc->GetData(), $oDoc->GetFileName(), $oDoc->GetMimeType());
  212. $sCid = $this->m_oMessage->embed($oSwiftImage);
  213. $oImg->setAttribute('src', $sCid);
  214. }
  215. }
  216. }
  217. $sHtmlBody = $oDOMDoc->saveHTML();
  218. $this->m_oMessage->setBody($sHtmlBody, 'text/html', 'UTF-8');
  219. }
  220. }
  221. public function Send(&$aIssues, $bForceSynchronous = false, $oLog = null)
  222. {
  223. if ($bForceSynchronous)
  224. {
  225. return $this->SendSynchronous($aIssues, $oLog);
  226. }
  227. else
  228. {
  229. $bConfigASYNC = MetaModel::GetConfig()->Get('email_asynchronous');
  230. if ($bConfigASYNC)
  231. {
  232. return $this->SendAsynchronous($aIssues, $oLog);
  233. }
  234. else
  235. {
  236. return $this->SendSynchronous($aIssues, $oLog);
  237. }
  238. }
  239. }
  240. public function AddToHeader($sKey, $sValue)
  241. {
  242. if (!array_key_exists('headers', $this->m_aData))
  243. {
  244. $this->m_aData['headers'] = array();
  245. }
  246. $this->m_aData['headers'][$sKey] = $sValue;
  247. if (strlen($sValue) > 0)
  248. {
  249. $oHeaders = $this->m_oMessage->getHeaders();
  250. switch(strtolower($sKey))
  251. {
  252. default:
  253. $oHeaders->addTextHeader($sKey, $sValue);
  254. }
  255. }
  256. }
  257. public function SetMessageId($sId)
  258. {
  259. $this->m_aData['message_id'] = $sId;
  260. // Note: Swift will add the angle brackets for you
  261. // so let's remove the angle brackets if present, for historical reasons
  262. $sId = str_replace(array('<', '>'), '', $sId);
  263. $oMsgId = $this->m_oMessage->getHeaders()->get('Message-ID');
  264. $oMsgId->SetId($sId);
  265. }
  266. public function SetReferences($sReferences)
  267. {
  268. $this->AddToHeader('References', $sReferences);
  269. }
  270. public function SetBody($sBody, $sMimeType = 'text/html')
  271. {
  272. $this->m_aData['body'] = array('body' => $sBody, 'mimeType' => $sMimeType);
  273. $this->m_oMessage->setBody($sBody, $sMimeType);
  274. }
  275. public function AddPart($sText, $sMimeType = 'text/html')
  276. {
  277. if (!array_key_exists('parts', $this->m_aData))
  278. {
  279. $this->m_aData['parts'] = array();
  280. }
  281. $this->m_aData['parts'][] = array('text' => $sText, 'mimeType' => $sMimeType);
  282. $this->m_oMessage->addPart($sText, $sMimeType);
  283. }
  284. public function AddAttachment($data, $sFileName, $sMimeType)
  285. {
  286. if (!array_key_exists('attachments', $this->m_aData))
  287. {
  288. $this->m_aData['attachments'] = array();
  289. }
  290. $this->m_aData['attachments'][] = array('data' => base64_encode($data), 'filename' => $sFileName, 'mimeType' => $sMimeType);
  291. $this->m_oMessage->attach(Swift_Attachment::newInstance($data, $sFileName, $sMimeType));
  292. }
  293. public function SetSubject($sSubject)
  294. {
  295. $this->m_aData['subject'] = $sSubject;
  296. $this->m_oMessage->setSubject($sSubject);
  297. }
  298. public function GetSubject()
  299. {
  300. return $this->m_oMessage->getSubject();
  301. }
  302. /**
  303. * Helper to transform and sanitize addresses
  304. * - get rid of empty addresses
  305. */
  306. protected function AddressStringToArray($sAddressCSVList)
  307. {
  308. $aAddresses = array();
  309. foreach(explode(',', $sAddressCSVList) as $sAddress)
  310. {
  311. $sAddress = trim($sAddress);
  312. if (strlen($sAddress) > 0)
  313. {
  314. $aAddresses[] = $sAddress;
  315. }
  316. }
  317. return $aAddresses;
  318. }
  319. public function SetRecipientTO($sAddress)
  320. {
  321. $this->m_aData['to'] = $sAddress;
  322. if (!empty($sAddress))
  323. {
  324. $aAddresses = $this->AddressStringToArray($sAddress);
  325. $this->m_oMessage->setTo($aAddresses);
  326. }
  327. }
  328. public function GetRecipientTO($bAsString = false)
  329. {
  330. $aRes = $this->m_oMessage->getTo();
  331. if ($aRes === null)
  332. {
  333. // There is no "To" header field
  334. $aRes = array();
  335. }
  336. if ($bAsString)
  337. {
  338. $aStrings = array();
  339. foreach ($aRes as $sEmail => $sName)
  340. {
  341. if (is_null($sName))
  342. {
  343. $aStrings[] = $sEmail;
  344. }
  345. else
  346. {
  347. $sName = str_replace(array('<', '>'), '', $sName);
  348. $aStrings[] = "$sName <$sEmail>";
  349. }
  350. }
  351. return implode(', ', $aStrings);
  352. }
  353. else
  354. {
  355. return $aRes;
  356. }
  357. }
  358. public function SetRecipientCC($sAddress)
  359. {
  360. $this->m_aData['cc'] = $sAddress;
  361. if (!empty($sAddress))
  362. {
  363. $aAddresses = $this->AddressStringToArray($sAddress);
  364. $this->m_oMessage->setCc($aAddresses);
  365. }
  366. }
  367. public function SetRecipientBCC($sAddress)
  368. {
  369. $this->m_aData['bcc'] = $sAddress;
  370. if (!empty($sAddress))
  371. {
  372. $aAddresses = $this->AddressStringToArray($sAddress);
  373. $this->m_oMessage->setBcc($aAddresses);
  374. }
  375. }
  376. public function SetRecipientFrom($sAddress, $sLabel = '')
  377. {
  378. $this->m_aData['from'] = array('address' => $sAddress, 'label' => $sLabel);
  379. if ($sLabel != '')
  380. {
  381. $this->m_oMessage->setFrom(array($sAddress => $sLabel));
  382. }
  383. else if (!empty($sAddress))
  384. {
  385. $this->m_oMessage->setFrom($sAddress);
  386. }
  387. }
  388. public function SetRecipientReplyTo($sAddress)
  389. {
  390. $this->m_aData['reply_to'] = $sAddress;
  391. if (!empty($sAddress))
  392. {
  393. $this->m_oMessage->setReplyTo($sAddress);
  394. }
  395. }
  396. }
  397. /////////////////////////////////////////////////////////////////////////////////////
  398. /**
  399. * Extension to SwiftMailer: "debug" transport that pretends messages have been sent,
  400. * but just log them to a file.
  401. *
  402. * @package Swift
  403. * @author Denis Flaven
  404. */
  405. class Swift_Transport_LogFileTransport extends Swift_Transport_NullTransport
  406. {
  407. protected $sLogFile;
  408. /**
  409. * Sends the given message.
  410. *
  411. * @param Swift_Mime_Message $message
  412. * @param string[] $failedRecipients An array of failures by-reference
  413. *
  414. * @return int The number of sent emails
  415. */
  416. public function send(Swift_Mime_Message $message, &$failedRecipients = null)
  417. {
  418. $hFile = @fopen($this->sLogFile, 'a');
  419. if ($hFile)
  420. {
  421. $sTxt = "================== ".date('Y-m-d H:i:s')." ==================\n";
  422. $sTxt .= $message->toString()."\n";
  423. @fwrite($hFile, $sTxt);
  424. @fclose($hFile);
  425. }
  426. return parent::send($message, $failedRecipients);
  427. }
  428. public function setLogFile($sFilename)
  429. {
  430. $this->sLogFile = $sFilename;
  431. }
  432. }
  433. /**
  434. * Pretends messages have been sent, but just log them to a file.
  435. *
  436. * @package Swift
  437. * @author Denis Flaven
  438. */
  439. class Swift_LogFileTransport extends Swift_Transport_LogFileTransport
  440. {
  441. /**
  442. * Create a new LogFileTransport.
  443. */
  444. public function __construct()
  445. {
  446. call_user_func_array(
  447. array($this, 'Swift_Transport_LogFileTransport::__construct'),
  448. Swift_DependencyContainer::getInstance()
  449. ->createDependenciesFor('transport.null')
  450. );
  451. }
  452. /**
  453. * Create a new LogFileTransport instance.
  454. *
  455. * @return Swift_LogFileTransport
  456. */
  457. public static function newInstance()
  458. {
  459. return new self();
  460. }
  461. }