PageRenderTime 32ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

/myproj/class.phpmailer.php

http://jcuecafe.googlecode.com/
PHP | 2057 lines | 1499 code | 203 blank | 355 comment | 230 complexity | c988160bbe1165de1d661dfd06b327f2 MD5 | raw file

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. // *****************
  3. //
  4. //Programmer : Ms. Mihika Jain
  5. //Student ID : 12526075
  6. //Contact email : mihika.jain@my.jcu.edu.au
  7. //
  8. // *****************
  9. if (version_compare(PHP_VERSION, '5.0.0', '<') ) exit("Sorry, this version of PHPMailer will only run on PHP version 5 or greater!\n");
  10. class PHPMailer {
  11. public $Priority = 3;
  12. public $CharSet = 'iso-8859-1';
  13. public $ContentType = 'text/plain';
  14. public $Encoding = '8bit';
  15. public $ErrorInfo = '';
  16. public $From = 'root@localhost';
  17. public $FromName = 'Root User';
  18. public $Sender = '';
  19. public $Subject = '';
  20. public $Body = '';
  21. public $AltBody = '';
  22. protected $MIMEBody = '';
  23. protected $MIMEHeader = '';
  24. public $WordWrap = 0;
  25. public $Mailer = 'mail';
  26. public $Sendmail = '/usr/sbin/sendmail';
  27. public $PluginDir = '';
  28. public $ConfirmReadingTo = '';
  29. public $Hostname = '';
  30. public $MessageID = '';
  31. public $Host = 'localhost';
  32. public $Port = 25;
  33. public $Helo = '';
  34. public $SMTPSecure = '';
  35. public $SMTPAuth = false;
  36. public $Username = '';
  37. public $Password = '';
  38. public $Timeout = 10;
  39. public $SMTPDebug = false;
  40. public $SMTPKeepAlive = false;
  41. public $SingleTo = false;
  42. public $SingleToArray = array();
  43. public $LE = "\n";
  44. public $DKIM_selector = 'phpmailer';
  45. public $DKIM_identity = '';
  46. public $DKIM_passphrase = '';
  47. public $DKIM_domain = '';
  48. public $DKIM_private = '';
  49. public $action_function = ''; //'callbackAction';
  50. public $Version = '5.2';
  51. public $XMailer = '';
  52. protected $smtp = NULL;
  53. protected $to = array();
  54. protected $cc = array();
  55. protected $bcc = array();
  56. protected $ReplyTo = array();
  57. protected $all_recipients = array();
  58. protected $attachment = array();
  59. protected $CustomHeader = array();
  60. protected $message_type = '';
  61. protected $boundary = array();
  62. protected $language = array();
  63. protected $error_count = 0;
  64. protected $sign_cert_file = '';
  65. protected $sign_key_file = '';
  66. protected $sign_key_pass = '';
  67. protected $exceptions = false;
  68. const STOP_MESSAGE = 0; // message only, continue processing
  69. const STOP_CONTINUE = 1; // message?, likely ok to continue processing
  70. const STOP_CRITICAL = 2; // message, plus full stop, critical error reached
  71. /////////////////////////////////////////////////
  72. // METHODS, VARIABLES
  73. /////////////////////////////////////////////////
  74. /**
  75. * Constructor
  76. * @param boolean $exceptions Should we throw external exceptions?
  77. */
  78. public function __construct($exceptions = false) {
  79. $this->exceptions = ($exceptions == true);
  80. }
  81. /**
  82. * Sets message type to HTML.
  83. * @param bool $ishtml
  84. * @return void
  85. */
  86. public function IsHTML($ishtml = true) {
  87. if ($ishtml) {
  88. $this->ContentType = 'text/html';
  89. } else {
  90. $this->ContentType = 'text/plain';
  91. }
  92. }
  93. /**
  94. * Sets Mailer to send message using SMTP.
  95. * @return void
  96. */
  97. public function IsSMTP() {
  98. $this->Mailer = 'smtp';
  99. }
  100. /**
  101. * Sets Mailer to send message using PHP mail() function.
  102. * @return void
  103. */
  104. public function IsMail() {
  105. $this->Mailer = 'mail';
  106. }
  107. /**
  108. * Sets Mailer to send message using the $Sendmail program.
  109. * @return void
  110. */
  111. public function IsSendmail() {
  112. if (!stristr(ini_get('sendmail_path'), 'sendmail')) {
  113. $this->Sendmail = '/var/qmail/bin/sendmail';
  114. }
  115. $this->Mailer = 'sendmail';
  116. }
  117. /**
  118. * Sets Mailer to send message using the qmail MTA.
  119. * @return void
  120. */
  121. public function IsQmail() {
  122. if (stristr(ini_get('sendmail_path'), 'qmail')) {
  123. $this->Sendmail = '/var/qmail/bin/sendmail';
  124. }
  125. $this->Mailer = 'sendmail';
  126. }
  127. /////////////////////////////////////////////////
  128. // METHODS, RECIPIENTS
  129. /////////////////////////////////////////////////
  130. /**
  131. * Adds a "To" address.
  132. * @param string $address
  133. * @param string $name
  134. * @return boolean true on success, false if address already used
  135. */
  136. public function AddAddress($address, $name = '') {
  137. return $this->AddAnAddress('to', $address, $name);
  138. }
  139. /**
  140. * Adds a "Cc" address.
  141. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  142. * @param string $address
  143. * @param string $name
  144. * @return boolean true on success, false if address already used
  145. */
  146. public function AddCC($address, $name = '') {
  147. return $this->AddAnAddress('cc', $address, $name);
  148. }
  149. /**
  150. * Adds a "Bcc" address.
  151. * Note: this function works with the SMTP mailer on win32, not with the "mail" mailer.
  152. * @param string $address
  153. * @param string $name
  154. * @return boolean true on success, false if address already used
  155. */
  156. public function AddBCC($address, $name = '') {
  157. return $this->AddAnAddress('bcc', $address, $name);
  158. }
  159. /**
  160. * Adds a "Reply-to" address.
  161. * @param string $address
  162. * @param string $name
  163. * @return boolean
  164. */
  165. public function AddReplyTo($address, $name = '') {
  166. return $this->AddAnAddress('ReplyTo', $address, $name);
  167. }
  168. /**
  169. * Adds an address to one of the recipient arrays
  170. * Addresses that have been added already return false, but do not throw exceptions
  171. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  172. * @param string $address The email address to send to
  173. * @param string $name
  174. * @return boolean true on success, false if address already used or invalid in some way
  175. * @access protected
  176. */
  177. protected function AddAnAddress($kind, $address, $name = '') {
  178. if (!preg_match('/^(to|cc|bcc|ReplyTo)$/', $kind)) {
  179. $this->SetError($this->Lang('Invalid recipient array').': '.$kind);
  180. if ($this->exceptions) {
  181. throw new phpmailerException('Invalid recipient array: ' . $kind);
  182. }
  183. echo $this->Lang('Invalid recipient array').': '.$kind;
  184. return false;
  185. }
  186. $address = trim($address);
  187. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  188. if (!self::ValidateAddress($address)) {
  189. $this->SetError($this->Lang('invalid_address').': '. $address);
  190. if ($this->exceptions) {
  191. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  192. }
  193. echo $this->Lang('invalid_address').': '.$address;
  194. return false;
  195. }
  196. if ($kind != 'ReplyTo') {
  197. if (!isset($this->all_recipients[strtolower($address)])) {
  198. array_push($this->$kind, array($address, $name));
  199. $this->all_recipients[strtolower($address)] = true;
  200. return true;
  201. }
  202. } else {
  203. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  204. $this->ReplyTo[strtolower($address)] = array($address, $name);
  205. return true;
  206. }
  207. }
  208. return false;
  209. }
  210. /**
  211. * Set the From and FromName properties
  212. * @param string $address
  213. * @param string $name
  214. * @return boolean
  215. */
  216. public function SetFrom($address, $name = '', $auto = 1) {
  217. $address = trim($address);
  218. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  219. if (!self::ValidateAddress($address)) {
  220. $this->SetError($this->Lang('invalid_address').': '. $address);
  221. if ($this->exceptions) {
  222. throw new phpmailerException($this->Lang('invalid_address').': '.$address);
  223. }
  224. echo $this->Lang('invalid_address').': '.$address;
  225. return false;
  226. }
  227. $this->From = $address;
  228. $this->FromName = $name;
  229. if ($auto) {
  230. if (empty($this->ReplyTo)) {
  231. $this->AddAnAddress('ReplyTo', $address, $name);
  232. }
  233. if (empty($this->Sender)) {
  234. $this->Sender = $address;
  235. }
  236. }
  237. return true;
  238. }
  239. /**
  240. * Check that a string looks roughly like an email address should
  241. * Static so it can be used without instantiation
  242. * Tries to use PHP built-in validator in the filter extension (from PHP 5.2), falls back to a reasonably competent regex validator
  243. * Conforms approximately to RFC2822
  244. * @link http://www.hexillion.com/samples/#Regex Original pattern found here
  245. * @param string $address The email address to check
  246. * @return boolean
  247. * @static
  248. * @access public
  249. */
  250. public static function ValidateAddress($address) {
  251. if (function_exists('filter_var')) { //Introduced in PHP 5.2
  252. if(filter_var($address, FILTER_VALIDATE_EMAIL) === FALSE) {
  253. return false;
  254. } else {
  255. return true;
  256. }
  257. } else {
  258. return preg_match('/^(?:[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+\.)*[\w\!\#\$\%\&\'\*\+\-\/\=\?\^\`\{\|\}\~]+@(?:(?:(?:[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!\.)){0,61}[a-zA-Z0-9_-]?\.)+[a-zA-Z0-9_](?:[a-zA-Z0-9_\-](?!$)){0,61}[a-zA-Z0-9_]?)|(?:\[(?:(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\.){3}(?:[01]?\d{1,2}|2[0-4]\d|25[0-5])\]))$/', $address);
  259. }
  260. }
  261. /////////////////////////////////////////////////
  262. // METHODS, MAIL SENDING
  263. /////////////////////////////////////////////////
  264. /**
  265. * Creates message and assigns Mailer. If the message is
  266. * not sent successfully then it returns false. Use the ErrorInfo
  267. * variable to view description of the error.
  268. * @return bool
  269. */
  270. public function Send() {
  271. try {
  272. if(!$this->PreSend()) return false;
  273. return $this->PostSend();
  274. } catch (phpmailerException $e) {
  275. $this->SetError($e->getMessage());
  276. if ($this->exceptions) {
  277. throw $e;
  278. }
  279. return false;
  280. }
  281. }
  282. protected function PreSend() {
  283. try {
  284. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  285. throw new phpmailerException($this->Lang('provide_address'), self::STOP_CRITICAL);
  286. }
  287. // Set whether the message is multipart/alternative
  288. if(!empty($this->AltBody)) {
  289. $this->ContentType = 'multipart/alternative';
  290. }
  291. $this->error_count = 0; // reset errors
  292. $this->SetMessageType();
  293. //Refuse to send an empty message
  294. if (empty($this->Body)) {
  295. throw new phpmailerException($this->Lang('empty_message'), self::STOP_CRITICAL);
  296. }
  297. $this->MIMEHeader = $this->CreateHeader();
  298. $this->MIMEBody = $this->CreateBody();
  299. // digitally sign with DKIM if enabled
  300. if ($this->DKIM_domain && $this->DKIM_private) {
  301. $header_dkim = $this->DKIM_Add($this->MIMEHeader, $this->EncodeHeader($this->SecureHeader($this->Subject)), $this->MIMEBody);
  302. $this->MIMEHeader = str_replace("\r\n", "\n", $header_dkim) . $this->MIMEHeader;
  303. }
  304. return true;
  305. } catch (phpmailerException $e) {
  306. $this->SetError($e->getMessage());
  307. if ($this->exceptions) {
  308. throw $e;
  309. }
  310. return false;
  311. }
  312. }
  313. protected function PostSend() {
  314. try {
  315. // Choose the mailer and send through it
  316. switch($this->Mailer) {
  317. case 'sendmail':
  318. return $this->SendmailSend($this->MIMEHeader, $this->MIMEBody);
  319. case 'smtp':
  320. return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  321. default:
  322. return $this->MailSend($this->MIMEHeader, $this->MIMEBody);
  323. }
  324. } catch (phpmailerException $e) {
  325. $this->SetError($e->getMessage());
  326. if ($this->exceptions) {
  327. throw $e;
  328. }
  329. echo $e->getMessage()."\n";
  330. return false;
  331. }
  332. }
  333. /**
  334. * Sends mail using the $Sendmail program.
  335. * @param string $header The message headers
  336. * @param string $body The message body
  337. * @access protected
  338. * @return bool
  339. */
  340. protected function SendmailSend($header, $body) {
  341. if ($this->Sender != '') {
  342. $sendmail = sprintf("%s -oi -f %s -t", escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  343. } else {
  344. $sendmail = sprintf("%s -oi -t", escapeshellcmd($this->Sendmail));
  345. }
  346. if ($this->SingleTo === true) {
  347. foreach ($this->SingleToArray as $key => $val) {
  348. if(!@$mail = popen($sendmail, 'w')) {
  349. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  350. }
  351. fputs($mail, "To: " . $val . "\n");
  352. fputs($mail, $header);
  353. fputs($mail, $body);
  354. $result = pclose($mail);
  355. // implement call back function if it exists
  356. $isSent = ($result == 0) ? 1 : 0;
  357. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  358. if($result != 0) {
  359. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  360. }
  361. }
  362. } else {
  363. if(!@$mail = popen($sendmail, 'w')) {
  364. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  365. }
  366. fputs($mail, $header);
  367. fputs($mail, $body);
  368. $result = pclose($mail);
  369. // implement call back function if it exists
  370. $isSent = ($result == 0) ? 1 : 0;
  371. $this->doCallback($isSent, $this->to, $this->cc, $this->bcc, $this->Subject, $body);
  372. if($result != 0) {
  373. throw new phpmailerException($this->Lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  374. }
  375. }
  376. return true;
  377. }
  378. /**
  379. * Sends mail using the PHP mail() function.
  380. * @param string $header The message headers
  381. * @param string $body The message body
  382. * @access protected
  383. * @return bool
  384. */
  385. protected function MailSend($header, $body) {
  386. $toArr = array();
  387. foreach($this->to as $t) {
  388. $toArr[] = $this->AddrFormat($t);
  389. }
  390. $to = implode(', ', $toArr);
  391. if (empty($this->Sender)) {
  392. $params = "-oi -f %s";
  393. } else {
  394. $params = sprintf("-oi -f %s", $this->Sender);
  395. }
  396. if ($this->Sender != '' and !ini_get('safe_mode')) {
  397. $old_from = ini_get('sendmail_from');
  398. ini_set('sendmail_from', $this->Sender);
  399. if ($this->SingleTo === true && count($toArr) > 1) {
  400. foreach ($toArr as $key => $val) {
  401. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  402. // implement call back function if it exists
  403. $isSent = ($rt == 1) ? 1 : 0;
  404. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  405. }
  406. } else {
  407. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  408. // implement call back function if it exists
  409. $isSent = ($rt == 1) ? 1 : 0;
  410. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  411. }
  412. } else {
  413. if ($this->SingleTo === true && count($toArr) > 1) {
  414. foreach ($toArr as $key => $val) {
  415. $rt = @mail($val, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header, $params);
  416. // implement call back function if it exists
  417. $isSent = ($rt == 1) ? 1 : 0;
  418. $this->doCallback($isSent, $val, $this->cc, $this->bcc, $this->Subject, $body);
  419. }
  420. } else {
  421. $rt = @mail($to, $this->EncodeHeader($this->SecureHeader($this->Subject)), $body, $header);
  422. // implement call back function if it exists
  423. $isSent = ($rt == 1) ? 1 : 0;
  424. $this->doCallback($isSent, $to, $this->cc, $this->bcc, $this->Subject, $body);
  425. }
  426. }
  427. if (isset($old_from)) {
  428. ini_set('sendmail_from', $old_from);
  429. }
  430. if(!$rt) {
  431. throw new phpmailerException($this->Lang('instantiate'), self::STOP_CRITICAL);
  432. }
  433. return true;
  434. }
  435. /**
  436. * Sends mail via SMTP using PhpSMTP
  437. * Returns false if there is a bad MAIL FROM, RCPT, or DATA input.
  438. * @param string $header The message headers
  439. * @param string $body The message body
  440. * @uses SMTP
  441. * @access protected
  442. * @return bool
  443. */
  444. protected function SmtpSend($header, $body) {
  445. require_once $this->PluginDir . 'class.smtp.php';
  446. $bad_rcpt = array();
  447. if(!$this->SmtpConnect()) {
  448. throw new phpmailerException($this->Lang('smtp_connect_failed'), self::STOP_CRITICAL);
  449. }
  450. $smtp_from = ($this->Sender == '') ? $this->From : $this->Sender;
  451. if(!$this->smtp->Mail($smtp_from)) {
  452. throw new phpmailerException($this->Lang('from_failed') . $smtp_from, self::STOP_CRITICAL);
  453. }
  454. // Attempt to send attach all recipients
  455. foreach($this->to as $to) {
  456. if (!$this->smtp->Recipient($to[0])) {
  457. $bad_rcpt[] = $to[0];
  458. // implement call back function if it exists
  459. $isSent = 0;
  460. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  461. } else {
  462. // implement call back function if it exists
  463. $isSent = 1;
  464. $this->doCallback($isSent, $to[0], '', '', $this->Subject, $body);
  465. }
  466. }
  467. foreach($this->cc as $cc) {
  468. if (!$this->smtp->Recipient($cc[0])) {
  469. $bad_rcpt[] = $cc[0];
  470. // implement call back function if it exists
  471. $isSent = 0;
  472. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  473. } else {
  474. // implement call back function if it exists
  475. $isSent = 1;
  476. $this->doCallback($isSent, '', $cc[0], '', $this->Subject, $body);
  477. }
  478. }
  479. foreach($this->bcc as $bcc) {
  480. if (!$this->smtp->Recipient($bcc[0])) {
  481. $bad_rcpt[] = $bcc[0];
  482. // implement call back function if it exists
  483. $isSent = 0;
  484. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  485. } else {
  486. // implement call back function if it exists
  487. $isSent = 1;
  488. $this->doCallback($isSent, '', '', $bcc[0], $this->Subject, $body);
  489. }
  490. }
  491. if (count($bad_rcpt) > 0 ) { //Create error message for any bad addresses
  492. $badaddresses = implode(', ', $bad_rcpt);
  493. throw new phpmailerException($this->Lang('recipients_failed') . $badaddresses);
  494. }
  495. if(!$this->smtp->Data($header . $body)) {
  496. throw new phpmailerException($this->Lang('data_not_accepted'), self::STOP_CRITICAL);
  497. }
  498. if($this->SMTPKeepAlive == true) {
  499. $this->smtp->Reset();
  500. }
  501. return true;
  502. }
  503. /**
  504. * Initiates a connection to an SMTP server.
  505. * Returns false if the operation failed.
  506. * @uses SMTP
  507. * @access public
  508. * @return bool
  509. */
  510. public function SmtpConnect() {
  511. if(is_null($this->smtp)) {
  512. $this->smtp = new SMTP();
  513. }
  514. $this->smtp->do_debug = $this->SMTPDebug;
  515. $hosts = explode(';', $this->Host);
  516. $index = 0;
  517. $connection = $this->smtp->Connected();
  518. // Retry while there is no connection
  519. try {
  520. while($index < count($hosts) && !$connection) {
  521. $hostinfo = array();
  522. if (preg_match('/^(.+):([0-9]+)$/', $hosts[$index], $hostinfo)) {
  523. $host = $hostinfo[1];
  524. $port = $hostinfo[2];
  525. } else {
  526. $host = $hosts[$index];
  527. $port = $this->Port;
  528. }
  529. $tls = ($this->SMTPSecure == 'tls');
  530. $ssl = ($this->SMTPSecure == 'ssl');
  531. if ($this->smtp->Connect(($ssl ? 'ssl://':'').$host, $port, $this->Timeout)) {
  532. $hello = ($this->Helo != '' ? $this->Helo : $this->ServerHostname());
  533. $this->smtp->Hello($hello);
  534. if ($tls) {
  535. if (!$this->smtp->StartTLS()) {
  536. throw new phpmailerException($this->Lang('tls'));
  537. }
  538. //We must resend HELO after tls negotiation
  539. $this->smtp->Hello($hello);
  540. }
  541. $connection = true;
  542. if ($this->SMTPAuth) {
  543. if (!$this->smtp->Authenticate($this->Username, $this->Password)) {
  544. throw new phpmailerException($this->Lang('authenticate'));
  545. }
  546. }
  547. }
  548. $index++;
  549. if (!$connection) {
  550. throw new phpmailerException($this->Lang('connect_host'));
  551. }
  552. }
  553. } catch (phpmailerException $e) {
  554. $this->smtp->Reset();
  555. throw $e;
  556. }
  557. return true;
  558. }
  559. /**
  560. * Closes the active SMTP session if one exists.
  561. * @return void
  562. */
  563. public function SmtpClose() {
  564. if(!is_null($this->smtp)) {
  565. if($this->smtp->Connected()) {
  566. $this->smtp->Quit();
  567. $this->smtp->Close();
  568. }
  569. }
  570. }
  571. /**
  572. * Sets the language for all class error messages.
  573. * Returns false if it cannot load the language file. The default language is English.
  574. * @param string $langcode ISO 639-1 2-character language code (e.g. Portuguese: "br")
  575. * @param string $lang_path Path to the language file directory
  576. * @access public
  577. */
  578. function SetLanguage($langcode = 'en', $lang_path = 'language/') {
  579. //Define full set of translatable strings
  580. $PHPMAILER_LANG = array(
  581. 'provide_address' => 'You must provide at least one recipient email address.',
  582. 'mailer_not_supported' => ' mailer is not supported.',
  583. 'execute' => 'Could not execute: ',
  584. 'instantiate' => 'Could not instantiate mail function.',
  585. 'authenticate' => 'SMTP Error: Could not authenticate.',
  586. 'from_failed' => 'The following From address failed: ',
  587. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  588. 'data_not_accepted' => 'SMTP Error: Data not accepted.',
  589. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  590. 'file_access' => 'Could not access file: ',
  591. 'file_open' => 'File Error: Could not open file: ',
  592. 'encoding' => 'Unknown encoding: ',
  593. 'signing' => 'Signing Error: ',
  594. 'smtp_error' => 'SMTP server error: ',
  595. 'empty_message' => 'Message body empty',
  596. 'invalid_address' => 'Invalid address',
  597. 'variable_set' => 'Cannot set or reset variable: '
  598. );
  599. //Overwrite language-specific strings. This way we'll never have missing translations - no more "language string failed to load"!
  600. $l = true;
  601. if ($langcode != 'en') { //There is no English translation file
  602. $l = @include $lang_path.'phpmailer.lang-'.$langcode.'.php';
  603. }
  604. $this->language = $PHPMAILER_LANG;
  605. return ($l == true); //Returns false if language not found
  606. }
  607. /**
  608. * Return the current array of language strings
  609. * @return array
  610. */
  611. public function GetTranslations() {
  612. return $this->language;
  613. }
  614. /////////////////////////////////////////////////
  615. // METHODS, MESSAGE CREATION
  616. /////////////////////////////////////////////////
  617. /**
  618. * Creates recipient headers.
  619. * @access public
  620. * @return string
  621. */
  622. public function AddrAppend($type, $addr) {
  623. $addr_str = $type . ': ';
  624. $addresses = array();
  625. foreach ($addr as $a) {
  626. $addresses[] = $this->AddrFormat($a);
  627. }
  628. $addr_str .= implode(', ', $addresses);
  629. $addr_str .= $this->LE;
  630. return $addr_str;
  631. }
  632. /**
  633. * Formats an address correctly.
  634. * @access public
  635. * @return string
  636. */
  637. public function AddrFormat($addr) {
  638. if (empty($addr[1])) {
  639. return $this->SecureHeader($addr[0]);
  640. } else {
  641. return $this->EncodeHeader($this->SecureHeader($addr[1]), 'phrase') . " <" . $this->SecureHeader($addr[0]) . ">";
  642. }
  643. }
  644. /**
  645. * Wraps message for use with mailers that do not
  646. * automatically perform wrapping and for quoted-printable.
  647. * Original written by philippe.
  648. * @param string $message The message to wrap
  649. * @param integer $length The line length to wrap to
  650. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  651. * @access public
  652. * @return string
  653. */
  654. public function WrapText($message, $length, $qp_mode = false) {
  655. $soft_break = ($qp_mode) ? sprintf(" =%s", $this->LE) : $this->LE;
  656. // If utf-8 encoding is used, we will need to make sure we don't
  657. // split multibyte characters when we wrap
  658. $is_utf8 = (strtolower($this->CharSet) == "utf-8");
  659. $message = $this->FixEOL($message);
  660. if (substr($message, -1) == $this->LE) {
  661. $message = substr($message, 0, -1);
  662. }
  663. $line = explode($this->LE, $message);
  664. $message = '';
  665. for ($i = 0 ;$i < count($line); $i++) {
  666. $line_part = explode(' ', $line[$i]);
  667. $buf = '';
  668. for ($e = 0; $e<count($line_part); $e++) {
  669. $word = $line_part[$e];
  670. if ($qp_mode and (strlen($word) > $length)) {
  671. $space_left = $length - strlen($buf) - 1;
  672. if ($e != 0) {
  673. if ($space_left > 20) {
  674. $len = $space_left;
  675. if ($is_utf8) {
  676. $len = $this->UTF8CharBoundary($word, $len);
  677. } elseif (substr($word, $len - 1, 1) == "=") {
  678. $len--;
  679. } elseif (substr($word, $len - 2, 1) == "=") {
  680. $len -= 2;
  681. }
  682. $part = substr($word, 0, $len);
  683. $word = substr($word, $len);
  684. $buf .= ' ' . $part;
  685. $message .= $buf . sprintf("=%s", $this->LE);
  686. } else {
  687. $message .= $buf . $soft_break;
  688. }
  689. $buf = '';
  690. }
  691. while (strlen($word) > 0) {
  692. $len = $length;
  693. if ($is_utf8) {
  694. $len = $this->UTF8CharBoundary($word, $len);
  695. } elseif (substr($word, $len - 1, 1) == "=") {
  696. $len--;
  697. } elseif (substr($word, $len - 2, 1) == "=") {
  698. $len -= 2;
  699. }
  700. $part = substr($word, 0, $len);
  701. $word = substr($word, $len);
  702. if (strlen($word) > 0) {
  703. $message .= $part . sprintf("=%s", $this->LE);
  704. } else {
  705. $buf = $part;
  706. }
  707. }
  708. } else {
  709. $buf_o = $buf;
  710. $buf .= ($e == 0) ? $word : (' ' . $word);
  711. if (strlen($buf) > $length and $buf_o != '') {
  712. $message .= $buf_o . $soft_break;
  713. $buf = $word;
  714. }
  715. }
  716. }
  717. $message .= $buf . $this->LE;
  718. }
  719. return $message;
  720. }
  721. /**
  722. * Finds last character boundary prior to maxLength in a utf-8
  723. * quoted (printable) encoded string.
  724. * Original written by Colin Brown.
  725. * @access public
  726. * @param string $encodedText utf-8 QP text
  727. * @param int $maxLength find last character boundary prior to this length
  728. * @return int
  729. */
  730. public function UTF8CharBoundary($encodedText, $maxLength) {
  731. $foundSplitPos = false;
  732. $lookBack = 3;
  733. while (!$foundSplitPos) {
  734. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  735. $encodedCharPos = strpos($lastChunk, "=");
  736. if ($encodedCharPos !== false) {
  737. // Found start of encoded character byte within $lookBack block.
  738. // Check the encoded byte value (the 2 chars after the '=')
  739. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  740. $dec = hexdec($hex);
  741. if ($dec < 128) { // Single byte character.
  742. // If the encoded char was found at pos 0, it will fit
  743. // otherwise reduce maxLength to start of the encoded char
  744. $maxLength = ($encodedCharPos == 0) ? $maxLength :
  745. $maxLength - ($lookBack - $encodedCharPos);
  746. $foundSplitPos = true;
  747. } elseif ($dec >= 192) { // First byte of a multi byte character
  748. // Reduce maxLength to split at start of character
  749. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  750. $foundSplitPos = true;
  751. } elseif ($dec < 192) { // Middle byte of a multi byte character, look further back
  752. $lookBack += 3;
  753. }
  754. } else {
  755. // No encoded character found
  756. $foundSplitPos = true;
  757. }
  758. }
  759. return $maxLength;
  760. }
  761. /**
  762. * Set the body wrapping.
  763. * @access public
  764. * @return void
  765. */
  766. public function SetWordWrap() {
  767. if($this->WordWrap < 1) {
  768. return;
  769. }
  770. switch($this->message_type) {
  771. case 'alt':
  772. case 'alt_inline':
  773. case 'alt_attach':
  774. case 'alt_inline_attach':
  775. $this->AltBody = $this->WrapText($this->AltBody, $this->WordWrap);
  776. break;
  777. default:
  778. $this->Body = $this->WrapText($this->Body, $this->WordWrap);
  779. break;
  780. }
  781. }
  782. /**
  783. * Assembles message header.
  784. * @access public
  785. * @return string The assembled header
  786. */
  787. public function CreateHeader() {
  788. $result = '';
  789. // Set the boundaries
  790. $uniq_id = md5(uniqid(time()));
  791. $this->boundary[1] = 'b1_' . $uniq_id;
  792. $this->boundary[2] = 'b2_' . $uniq_id;
  793. $this->boundary[3] = 'b3_' . $uniq_id;
  794. $result .= $this->HeaderLine('Date', self::RFCDate());
  795. if($this->Sender == '') {
  796. $result .= $this->HeaderLine('Return-Path', trim($this->From));
  797. } else {
  798. $result .= $this->HeaderLine('Return-Path', trim($this->Sender));
  799. }
  800. // To be created automatically by mail()
  801. if($this->Mailer != 'mail') {
  802. if ($this->SingleTo === true) {
  803. foreach($this->to as $t) {
  804. $this->SingleToArray[] = $this->AddrFormat($t);
  805. }
  806. } else {
  807. if(count($this->to) > 0) {
  808. $result .= $this->AddrAppend('To', $this->to);
  809. } elseif (count($this->cc) == 0) {
  810. $result .= $this->HeaderLine('To', 'undisclosed-recipients:;');
  811. }
  812. }
  813. }
  814. $from = array();
  815. $from[0][0] = trim($this->From);
  816. $from[0][1] = $this->FromName;
  817. $result .= $this->AddrAppend('From', $from);
  818. // sendmail and mail() extract Cc from the header before sending
  819. if(count($this->cc) > 0) {
  820. $result .= $this->AddrAppend('Cc', $this->cc);
  821. }
  822. // sendmail and mail() extract Bcc from the header before sending
  823. if((($this->Mailer == 'sendmail') || ($this->Mailer == 'mail')) && (count($this->bcc) > 0)) {
  824. $result .= $this->AddrAppend('Bcc', $this->bcc);
  825. }
  826. if(count($this->ReplyTo) > 0) {
  827. $result .= $this->AddrAppend('Reply-to', $this->ReplyTo);
  828. }
  829. // mail() sets the subject itself
  830. if($this->Mailer != 'mail') {
  831. $result .= $this->HeaderLine('Subject', $this->EncodeHeader($this->SecureHeader($this->Subject)));
  832. }
  833. if($this->MessageID != '') {
  834. $result .= $this->HeaderLine('Message-ID', $this->MessageID);
  835. } else {
  836. $result .= sprintf("Message-ID: <%s@%s>%s", $uniq_id, $this->ServerHostname(), $this->LE);
  837. }
  838. $result .= $this->HeaderLine('X-Priority', $this->Priority);
  839. if($this->XMailer) {
  840. $result .= $this->HeaderLine('X-Mailer', $this->XMailer);
  841. } else {
  842. $result .= $this->HeaderLine('X-Mailer', 'PHPMailer '.$this->Version.' (http://code.google.com/a/apache-extras.org/p/phpmailer/)');
  843. }
  844. if($this->ConfirmReadingTo != '') {
  845. $result .= $this->HeaderLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  846. }
  847. // Add custom headers
  848. for($index = 0; $index < count($this->CustomHeader); $index++) {
  849. $result .= $this->HeaderLine(trim($this->CustomHeader[$index][0]), $this->EncodeHeader(trim($this->CustomHeader[$index][1])));
  850. }
  851. if (!$this->sign_key_file) {
  852. $result .= $this->HeaderLine('MIME-Version', '1.0');
  853. $result .= $this->GetMailMIME();
  854. }
  855. return $result;
  856. }
  857. /**
  858. * Returns the message MIME.
  859. * @access public
  860. * @return string
  861. */
  862. public function GetMailMIME() {
  863. $result = '';
  864. switch($this->message_type) {
  865. case 'plain':
  866. $result .= $this->HeaderLine('Content-Transfer-Encoding', $this->Encoding);
  867. $result .= $this->TextLine('Content-Type: '.$this->ContentType.'; charset="'.$this->CharSet.'"');
  868. break;
  869. case 'inline':
  870. $result .= $this->HeaderLine('Content-Type', 'multipart/related;');
  871. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  872. break;
  873. case 'attach':
  874. case 'inline_attach':
  875. case 'alt_attach':
  876. case 'alt_inline_attach':
  877. $result .= $this->HeaderLine('Content-Type', 'multipart/mixed;');
  878. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  879. break;
  880. case 'alt':
  881. case 'alt_inline':
  882. $result .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  883. $result .= $this->TextLine("\tboundary=\"" . $this->boundary[1] . '"');
  884. break;
  885. }
  886. if($this->Mailer != 'mail') {
  887. $result .= $this->LE.$this->LE;
  888. }
  889. return $result;
  890. }
  891. /**
  892. * Assembles the message body. Returns an empty string on failure.
  893. * @access public
  894. * @return string The assembled message body
  895. */
  896. public function CreateBody() {
  897. $body = '';
  898. if ($this->sign_key_file) {
  899. $body .= $this->GetMailMIME();
  900. }
  901. $this->SetWordWrap();
  902. switch($this->message_type) {
  903. case 'plain':
  904. $body .= $this->EncodeString($this->Body, $this->Encoding);
  905. break;
  906. case 'inline':
  907. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  908. $body .= $this->EncodeString($this->Body, $this->Encoding);
  909. $body .= $this->LE.$this->LE;
  910. $body .= $this->AttachAll("inline", $this->boundary[1]);
  911. break;
  912. case 'attach':
  913. $body .= $this->GetBoundary($this->boundary[1], '', '', '');
  914. $body .= $this->EncodeString($this->Body, $this->Encoding);
  915. $body .= $this->LE.$this->LE;
  916. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  917. break;
  918. case 'inline_attach':
  919. $body .= $this->TextLine("--" . $this->boundary[1]);
  920. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  921. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  922. $body .= $this->LE;
  923. $body .= $this->GetBoundary($this->boundary[2], '', '', '');
  924. $body .= $this->EncodeString($this->Body, $this->Encoding);
  925. $body .= $this->LE.$this->LE;
  926. $body .= $this->AttachAll("inline", $this->boundary[2]);
  927. $body .= $this->LE;
  928. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  929. break;
  930. case 'alt':
  931. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  932. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  933. $body .= $this->LE.$this->LE;
  934. $body .= $this->GetBoundary($this->boundary[1], '', 'text/html', '');
  935. $body .= $this->EncodeString($this->Body, $this->Encoding);
  936. $body .= $this->LE.$this->LE;
  937. $body .= $this->EndBoundary($this->boundary[1]);
  938. break;
  939. case 'alt_inline':
  940. $body .= $this->GetBoundary($this->boundary[1], '', 'text/plain', '');
  941. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  942. $body .= $this->LE.$this->LE;
  943. $body .= $this->TextLine("--" . $this->boundary[1]);
  944. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  945. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  946. $body .= $this->LE;
  947. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  948. $body .= $this->EncodeString($this->Body, $this->Encoding);
  949. $body .= $this->LE.$this->LE;
  950. $body .= $this->AttachAll("inline", $this->boundary[2]);
  951. $body .= $this->LE;
  952. $body .= $this->EndBoundary($this->boundary[1]);
  953. break;
  954. case 'alt_attach':
  955. $body .= $this->TextLine("--" . $this->boundary[1]);
  956. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  957. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  958. $body .= $this->LE;
  959. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  960. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  961. $body .= $this->LE.$this->LE;
  962. $body .= $this->GetBoundary($this->boundary[2], '', 'text/html', '');
  963. $body .= $this->EncodeString($this->Body, $this->Encoding);
  964. $body .= $this->LE.$this->LE;
  965. $body .= $this->EndBoundary($this->boundary[2]);
  966. $body .= $this->LE;
  967. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  968. break;
  969. case 'alt_inline_attach':
  970. $body .= $this->TextLine("--" . $this->boundary[1]);
  971. $body .= $this->HeaderLine('Content-Type', 'multipart/alternative;');
  972. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[2] . '"');
  973. $body .= $this->LE;
  974. $body .= $this->GetBoundary($this->boundary[2], '', 'text/plain', '');
  975. $body .= $this->EncodeString($this->AltBody, $this->Encoding);
  976. $body .= $this->LE.$this->LE;
  977. $body .= $this->TextLine("--" . $this->boundary[2]);
  978. $body .= $this->HeaderLine('Content-Type', 'multipart/related;');
  979. $body .= $this->TextLine("\tboundary=\"" . $this->boundary[3] . '"');
  980. $body .= $this->LE;
  981. $body .= $this->GetBoundary($this->boundary[3], '', 'text/html', '');
  982. $body .= $this->EncodeString($this->Body, $this->Encoding);
  983. $body .= $this->LE.$this->LE;
  984. $body .= $this->AttachAll("inline", $this->boundary[3]);
  985. $body .= $this->LE;
  986. $body .= $this->EndBoundary($this->boundary[2]);
  987. $body .= $this->LE;
  988. $body .= $this->AttachAll("attachment", $this->boundary[1]);
  989. break;
  990. }
  991. if ($this->IsError()) {
  992. $body = '';
  993. } elseif ($this->sign_key_file) {
  994. try {
  995. $file = tempnam('', 'mail');
  996. file_put_contents($file, $body); //TODO check this worked
  997. $signed = tempnam("", "signed");
  998. if (@openssl_pkcs7_sign($file, $signed, "file://".$this->sign_cert_file, array("file://".$this->sign_key_file, $this->sign_key_pass), NULL)) {
  999. @unlink($file);
  1000. @unlink($signed);
  1001. $body = file_get_contents($signed);
  1002. } else {
  1003. @unlink($file);
  1004. @unlink($signed);
  1005. throw new phpmailerException($this->Lang("signing").openssl_error_string());
  1006. }
  1007. } catch (phpmailerException $e) {
  1008. $body = '';
  1009. if ($this->exceptions) {
  1010. throw $e;
  1011. }
  1012. }
  1013. }
  1014. return $body;
  1015. }
  1016. /**
  1017. * Returns the start of a message boundary.
  1018. * @access protected
  1019. * @return string
  1020. */
  1021. protected function GetBoundary($boundary, $charSet, $contentType, $encoding) {
  1022. $result = '';
  1023. if($charSet == '') {
  1024. $charSet = $this->CharSet;
  1025. }
  1026. if($contentType == '') {
  1027. $contentType = $this->ContentType;
  1028. }
  1029. if($encoding == '') {
  1030. $encoding = $this->Encoding;
  1031. }
  1032. $result .= $this->TextLine('--' . $boundary);
  1033. $result .= sprintf("Content-Type: %s; charset=\"%s\"", $contentType, $charSet);
  1034. $result .= $this->LE;
  1035. $result .= $this->HeaderLine('Content-Transfer-Encoding', $encoding);
  1036. $result .= $this->LE;
  1037. return $result;
  1038. }
  1039. /**
  1040. * Returns the end of a message boundary.
  1041. * @access protected
  1042. * @return string
  1043. */
  1044. protected function EndBoundary($boundary) {
  1045. return $this->LE . '--' . $boundary . '--' . $this->LE;
  1046. }
  1047. /**
  1048. * Sets the message type.
  1049. * @access protected
  1050. * @return void
  1051. */
  1052. protected function SetMessageType() {
  1053. $this->message_type = array();
  1054. if($this->AlternativeExists()) $this->message_type[] = "alt";
  1055. if($this->InlineImageExists()) $this->message_type[] = "inline";
  1056. if($this->AttachmentExists()) $this->message_type[] = "attach";
  1057. $this->message_type = implode("_", $this->message_type);
  1058. if($this->message_type == "") $this->message_type = "plain";
  1059. }
  1060. /**
  1061. * Returns a formatted header line.
  1062. * @access public
  1063. * @return string
  1064. */
  1065. public function HeaderLine($name, $value) {
  1066. return $name . ': ' . $value . $this->LE;
  1067. }
  1068. /**
  1069. * Returns a formatted mail line.
  1070. * @access public
  1071. * @return string
  1072. */
  1073. public function TextLine($value) {
  1074. return $value . $this->LE;
  1075. }
  1076. /////////////////////////////////////////////////
  1077. // CLASS METHODS, ATTACHMENTS
  1078. /////////////////////////////////////////////////
  1079. /**
  1080. * Adds an attachment from a path on the filesystem.
  1081. * Returns false if the file could not be found
  1082. * or accessed.
  1083. * @param string $path Path to the attachment.
  1084. * @param string $name Overrides the attachment name.
  1085. * @param string $encoding File encoding (see $Encoding).
  1086. * @param string $type File extension (MIME) type.
  1087. * @return bool
  1088. */
  1089. public function AddAttachment($path, $name = '', $encoding = 'base64', $type = 'application/octet-stream') {
  1090. try {
  1091. if ( !@is_file($path) ) {
  1092. throw new phpmailerException($this->Lang('file_access') . $path, self::STOP_CONTINUE);
  1093. }
  1094. $filename = basename($path);
  1095. if ( $name == '' ) {
  1096. $name = $filename;
  1097. }
  1098. $this->attachment[] = array(
  1099. 0 => $path,
  1100. 1 => $filename,
  1101. 2 => $name,
  1102. 3 => $encoding,
  1103. 4 => $type,
  1104. 5 => false, // isStringAttachment
  1105. 6 => 'attachment',
  1106. 7 => 0
  1107. );
  1108. } catch (phpmailerException $e) {
  1109. $this->SetError($e->getMessage());
  1110. if ($this->exceptions) {
  1111. throw $e;
  1112. }
  1113. echo $e->getMessage()."\n";
  1114. if ( $e->getCode() == self::STOP_CRITICAL ) {
  1115. return false;
  1116. }
  1117. }
  1118. return true;
  1119. }
  1120. /**
  1121. * Return the current array of attachments
  1122. * @return array
  1123. */
  1124. public function GetAttachments() {
  1125. return $this->attachment;
  1126. }
  1127. /**
  1128. * Attaches all fs, string, and binary attachments to the message.
  1129. * Returns an empty string on failure.
  1130. * @access protected
  1131. * @return string
  1132. */
  1133. protected function AttachAll($disposition_type, $boundary) {
  1134. // Return text of body
  1135. $mime = array();
  1136. $cidUniq = array();
  1137. $incl = array();
  1138. // Add all attachments
  1139. foreach ($this->attachment as $attachment) {
  1140. // CHECK IF IT IS A VALID DISPOSITION_FILTER
  1141. if($attachment[6] == $disposition_type) {
  1142. // Check for string attachment
  1143. $bString = $attachment[5];
  1144. if ($bString) {
  1145. $string = $attachment[0];
  1146. } else {
  1147. $path = $attachment[0];
  1148. }
  1149. $inclhash = md5(serialize($attachment));
  1150. if (in_array($inclhash, $incl)) { continue; }
  1151. $incl[] = $inclhash;
  1152. $filename = $attachment[1];
  1153. $name = $attachment[2];
  1154. $encoding = $attachment[3];
  1155. $type = $attachment[4];
  1156. $disposition = $attachment[6];
  1157. $cid = $attachment[7];
  1158. if ( $disposition == 'inline' && isset($cidUniq[$cid]) ) { continue; }
  1159. $cidUniq[$cid] = true;
  1160. $mime[] = sprintf("--%s%s", $boundary, $this->LE);
  1161. $mime[] = sprintf("Content-Type: %s; name=\"%s\"%s", $type, $this->EncodeHeader($this->SecureHeader($name)), $this->LE);
  1162. $mime[] = sprintf("Content-Transfer-Encoding: %s%s", $encoding, $this->LE);
  1163. if($disposition == 'inline') {
  1164. $mime[] = sprintf("Content-ID: <%s>%s", $cid, $this->LE);
  1165. }
  1166. $mime[] = sprintf("Content-Disposition: %s; filename=\"%s\"%s", $disposition, $this->EncodeHeader($this->SecureHeader($name)), $this->LE.$this->LE);
  1167. // Encode as string attachment
  1168. if($bString) {
  1169. $mime[] = $this->EncodeString($string, $encoding);
  1170. if($this->IsError()) {
  1171. return '';
  1172. }
  1173. $mime[] = $this->LE.$this->LE;
  1174. } else {
  1175. $mime[] = $this->EncodeFile($path, $encoding);
  1176. if($this->IsError()) {
  1177. return '';
  1178. }
  1179. $mime[] = $this->LE.$this->LE;
  1180. }
  1181. }
  1182. }
  1183. $mime[] = sprintf("--%s--%s", $boundary, $this->LE);
  1184. return implode("", $mime);
  1185. }
  1186. /**
  1187. * Encodes attachment in requested format.
  1188. * Returns an empty string on failure.
  1189. * @param string $path The full path to the file
  1190. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1191. * @see EncodeFile()
  1192. * @access protected
  1193. * @return string
  1194. */
  1195. protected function EncodeFile($path, $encoding = 'base64') {
  1196. try {
  1197. if (!is_readable($path)) {
  1198. throw new phpmailerException($this->Lang('file_open') . $path, self::STOP_CONTINUE);
  1199. }
  1200. if (function_exists('get_magic_quotes')) {
  1201. function get_magic_quotes() {
  1202. return false;
  1203. }
  1204. }
  1205. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1206. $magic_quotes = get_magic_quotes_runtime();
  1207. set_magic_quotes_runtime(0);
  1208. }
  1209. $file_buffer = file_get_contents($path);
  1210. $file_buffer = $this->EncodeString($file_buffer, $encoding);
  1211. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  1212. set_magic_quotes_runtime($magic_quotes);
  1213. }
  1214. return $file_buffer;
  1215. } catch (Exception $e) {
  1216. $this->SetError($e->getMessage());
  1217. return '';
  1218. }
  1219. }
  1220. /**
  1221. * Encodes string to requested format.
  1222. * Returns an empty string on failure.
  1223. * @param string $str The text to encode
  1224. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  1225. * @access public
  1226. * @return string
  1227. */
  1228. public function EncodeString($str, $encoding = 'base64') {
  1229. $encoded = '';
  1230. switch(strtolower($encoding)) {
  1231. case 'base64':
  1232. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  1233. break;
  1234. case '7bit':
  1235. case '8bit':
  1236. $encoded = $this->FixEOL($str);
  1237. //Make sure it ends with a line break
  1238. if (substr($encoded, -(strlen($this->LE))) != $this->LE)
  1239. $encoded .= $this->LE;
  1240. break;
  1241. case 'binary':
  1242. $encoded = $str;
  1243. break;
  1244. case 'quoted-printable':
  1245. $encoded = $this->EncodeQP($str);
  1246. break;
  1247. default:
  1248. $this->SetError($this->Lang('encoding') . $encoding);
  1249. break;
  1250. }
  1251. return $encoded;
  1252. }
  1253. /**
  1254. * Encode a header string to best (shortest) of Q, B, quoted or none.
  1255. * @access public
  1256. * @return string
  1257. */
  1258. public function EncodeHeader($str, $position = 'text') {
  1259. $x = 0;
  1260. switch (strtolower($position)) {
  1261. case 'phrase':
  1262. if (!preg_match('/[\200-\377]/', $str)) {
  1263. // Can't use addslashes as we don't know what value has magic_quotes_sybase
  1264. $encoded = addcslashes($str, "\0..\37\177\\\"");
  1265. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  1266. return ($encoded);
  1267. } else {
  1268. return ("\"$encoded\"");
  1269. }
  1270. }
  1271. $x = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  1272. break;
  1273. case 'comment':
  1274. $x = preg_match_all('/[()"]/', $str, $matches);
  1275. // Fall-through
  1276. case 'text':
  1277. default:
  1278. $x += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  1279. break;
  1280. }
  1281. if ($x == 0) {
  1282. return ($str);
  1283. }
  1284. $maxlen = 75 - 7 - strlen($this->CharSet);
  1285. // Try to select the encoding which should produce the shortest output
  1286. if (strlen($str)/3 < $x) {
  1287. $encoding = 'B';
  1288. if (function_exists('mb_strlen') && $this->HasMultiBytes($str)) {
  1289. // Use a custom function which correctly encodes and wraps long
  1290. // multibyte strings without breaking lines within a character
  1291. $encoded = $this->Base64EncodeWrapMB($str);
  1292. } else {
  1293. $encoded = base64_encode($str);
  1294. $maxlen -= $maxlen % 4;
  1295. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  1296. }
  1297. } else {
  1298. $encoding = 'Q';
  1299. $encoded = $this->EncodeQ($str, $position);
  1300. $encoded = $this->WrapText($encoded, $maxlen, true);
  1301. $encoded = str_replace('='.$this->LE, "\n", trim($encoded));
  1302. }
  1303. $encoded = preg_replace('/^(.*)$/m', " =?".$this->CharSet."?$encoding?\\1?=", $encoded);
  1304. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  1305. return $encoded;
  1306. }
  1307. /**
  1308. * Checks if a string contains multibyte characters.
  1309. * @access public
  1310. * @param string $str multi-byte text to wrap encode
  1311. * @return bool
  1312. */
  1313. public function HasMultiBytes($str) {
  1314. if (function_exists('mb_strlen')) {
  1315. return (strlen($str) > mb_strlen($str, $this->CharSet));
  1316. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  1317. return false;
  1318. }
  1319. }
  1320. /**
  1321. * Correctly encodes and wraps long multibyte strings for mail headers
  1322. * without breaking lines within a character.
  1323. * Adapted from a function by paravoid at http://uk.php.net/manual/en/function.mb-encode-mimeheader.php
  1324. * @access public
  1325. * @param string $str multi-byte text to wrap encode
  1326. * @return string
  1327. */
  1328. public function Base64EncodeWrapMB($str) {
  1329. $start = "=?".$this->CharSet."?B?";
  1330. $end = "?=";
  1331. $encoded = "";
  1332. $mb_length = mb_strlen($str, $this->CharSet);
  1333. // Each line must have length <= 75, including $start and $end
  1334. $length = 75 - strlen($start) - strlen($end);
  1335. // Average multi-byte ratio
  1336. $ratio = $mb_length / strlen($str);
  1337. // Base64 has a 4:3 ratio
  1338. $offset = $avgLength = floor($length * $ratio * .75);
  1339. for ($i = 0; $i < $mb_length; $i += $offset) {
  1340. $lookBack = 0;
  1341. do {
  1342. $offset = $avgLength - $lookBack;
  1343. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  1344. $chunk = base64_encode($chunk);
  1345. $lookBack++;
  1346. }
  1347. while (strlen($chunk) > $length);
  1348. $encoded .= $chunk . $this->LE;
  1349. }
  1350. // Chomp the last linefeed
  1351. $encoded = substr($encoded, 0, -strlen($this->LE));
  1352. return $encoded;
  1353. }
  1354. /**
  1355. * Encode string to quoted-printable.
  1356. * Only uses standard PHP, slow, but will always work
  1357. * @access public
  1358. * @param string $string the text to encode
  1359. * @param integer $line_max Number of chars allowed on a line before wrapping
  1360. * @return string
  1361. */
  1362. public function EncodeQPphp( $input = '', $line_max = 76, $space_conv = false) {
  1363. $hex = array('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F');
  1364. $lines = preg_split('/(?:\r\n|\r|\n)/', $input);
  1365. $eol =

Large files files are truncated, but you can click here to view the full file