You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249
  1. <?php
  2. /**
  3. * The Mail_mimePart class is used to create MIME E-mail messages
  4. *
  5. * This class enables you to manipulate and build a mime email
  6. * from the ground up. The Mail_Mime class is a userfriendly api
  7. * to this class for people who aren't interested in the internals
  8. * of mime mail.
  9. * This class however allows full control over the email.
  10. *
  11. * Compatible with PHP version 5
  12. *
  13. * LICENSE: This LICENSE is in the BSD license style.
  14. * Copyright (c) 2002-2003, Richard Heyes <richard@phpguru.org>
  15. * Copyright (c) 2003-2006, PEAR <pear-group@php.net>
  16. * All rights reserved.
  17. *
  18. * Redistribution and use in source and binary forms, with or
  19. * without modification, are permitted provided that the following
  20. * conditions are met:
  21. *
  22. * - Redistributions of source code must retain the above copyright
  23. * notice, this list of conditions and the following disclaimer.
  24. * - Redistributions in binary form must reproduce the above copyright
  25. * notice, this list of conditions and the following disclaimer in the
  26. * documentation and/or other materials provided with the distribution.
  27. * - Neither the name of the authors, nor the names of its contributors
  28. * may be used to endorse or promote products derived from this
  29. * software without specific prior written permission.
  30. *
  31. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  32. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  33. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  34. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  35. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  36. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  37. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  38. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  39. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  40. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
  41. * THE POSSIBILITY OF SUCH DAMAGE.
  42. *
  43. * @category Mail
  44. * @package Mail_Mime
  45. * @author Richard Heyes <richard@phpguru.org>
  46. * @author Cipriano Groenendal <cipri@php.net>
  47. * @author Sean Coates <sean@php.net>
  48. * @author Aleksander Machniak <alec@php.net>
  49. * @copyright 2003-2006 PEAR <pear-group@php.net>
  50. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  51. * @version Release: @package_version@
  52. * @link http://pear.php.net/package/Mail_mime
  53. */
  54. /**
  55. * require PEAR
  56. *
  57. * This package depends on PEAR to raise errors.
  58. */
  59. require_once 'PEAR.php';
  60. /**
  61. * The Mail_mimePart class is used to create MIME E-mail messages
  62. *
  63. * This class enables you to manipulate and build a mime email
  64. * from the ground up. The Mail_Mime class is a userfriendly api
  65. * to this class for people who aren't interested in the internals
  66. * of mime mail.
  67. * This class however allows full control over the email.
  68. *
  69. * @category Mail
  70. * @package Mail_Mime
  71. * @author Richard Heyes <richard@phpguru.org>
  72. * @author Cipriano Groenendal <cipri@php.net>
  73. * @author Sean Coates <sean@php.net>
  74. * @author Aleksander Machniak <alec@php.net>
  75. * @copyright 2003-2006 PEAR <pear-group@php.net>
  76. * @license http://www.opensource.org/licenses/bsd-license.php BSD License
  77. * @version Release: @package_version@
  78. * @link http://pear.php.net/package/Mail_mime
  79. */
  80. class Mail_mimePart
  81. {
  82. /**
  83. * The encoding type of this part
  84. *
  85. * @var string
  86. */
  87. protected $encoding;
  88. /**
  89. * An array of subparts
  90. *
  91. * @var array
  92. */
  93. protected $subparts;
  94. /**
  95. * The output of this part after being built
  96. *
  97. * @var string
  98. */
  99. protected $encoded;
  100. /**
  101. * Headers for this part
  102. *
  103. * @var array
  104. */
  105. protected $headers;
  106. /**
  107. * The body of this part (not encoded)
  108. *
  109. * @var string
  110. */
  111. protected $body;
  112. /**
  113. * The location of file with body of this part (not encoded)
  114. *
  115. * @var string
  116. */
  117. protected $body_file;
  118. /**
  119. * The short text of multipart part preamble (RFC2046 5.1.1)
  120. *
  121. * @var string
  122. */
  123. protected $preamble;
  124. /**
  125. * The end-of-line sequence
  126. *
  127. * @var string
  128. */
  129. protected $eol = "\r\n";
  130. /**
  131. * Constructor.
  132. *
  133. * Sets up the object.
  134. *
  135. * @param string $body The body of the mime part if any.
  136. * @param array $params An associative array of optional parameters:
  137. * content_type - The content type for this part eg multipart/mixed
  138. * encoding - The encoding to use, 7bit, 8bit,
  139. * base64, or quoted-printable
  140. * charset - Content character set
  141. * cid - Content ID to apply
  142. * disposition - Content disposition, inline or attachment
  143. * filename - Filename parameter for content disposition
  144. * description - Content description
  145. * name_encoding - Encoding of the attachment name (Content-Type)
  146. * By default filenames are encoded using RFC2231
  147. * Here you can set RFC2047 encoding (quoted-printable
  148. * or base64) instead
  149. * filename_encoding - Encoding of the attachment filename (Content-Disposition)
  150. * See 'name_encoding'
  151. * headers_charset - Charset of the headers e.g. filename, description.
  152. * If not set, 'charset' will be used
  153. * eol - End of line sequence. Default: "\r\n"
  154. * headers - Hash array with additional part headers. Array keys can be
  155. * in form of <header_name>:<parameter_name>
  156. * body_file - Location of file with part's body (instead of $body)
  157. * preamble - short text of multipart part preamble (RFC2046 5.1.1)
  158. */
  159. public function __construct($body = '', $params = array())
  160. {
  161. if (!empty($params['eol'])) {
  162. $this->eol = $params['eol'];
  163. } else if (defined('MAIL_MIMEPART_CRLF')) { // backward-copat.
  164. $this->eol = MAIL_MIMEPART_CRLF;
  165. }
  166. // Additional part headers
  167. if (!empty($params['headers']) && is_array($params['headers'])) {
  168. $headers = $params['headers'];
  169. }
  170. foreach ($params as $key => $value) {
  171. switch ($key) {
  172. case 'encoding':
  173. $this->encoding = $value;
  174. $headers['Content-Transfer-Encoding'] = $value;
  175. break;
  176. case 'cid':
  177. $headers['Content-ID'] = '<' . $value . '>';
  178. break;
  179. case 'location':
  180. $headers['Content-Location'] = $value;
  181. break;
  182. case 'body_file':
  183. $this->body_file = $value;
  184. break;
  185. case 'preamble':
  186. $this->preamble = $value;
  187. break;
  188. // for backward compatibility
  189. case 'dfilename':
  190. $params['filename'] = $value;
  191. break;
  192. }
  193. }
  194. // Default content-type
  195. if (empty($params['content_type'])) {
  196. $params['content_type'] = 'text/plain';
  197. }
  198. // Content-Type
  199. $headers['Content-Type'] = $params['content_type'];
  200. if (!empty($params['charset'])) {
  201. $charset = "charset={$params['charset']}";
  202. // place charset parameter in the same line, if possible
  203. if ((strlen($headers['Content-Type']) + strlen($charset) + 16) <= 76) {
  204. $headers['Content-Type'] .= '; ';
  205. } else {
  206. $headers['Content-Type'] .= ';' . $this->eol . ' ';
  207. }
  208. $headers['Content-Type'] .= $charset;
  209. // Default headers charset
  210. if (!isset($params['headers_charset'])) {
  211. $params['headers_charset'] = $params['charset'];
  212. }
  213. }
  214. // header values encoding parameters
  215. $h_charset = !empty($params['headers_charset']) ? $params['headers_charset'] : 'US-ASCII';
  216. $h_language = !empty($params['language']) ? $params['language'] : null;
  217. $h_encoding = !empty($params['name_encoding']) ? $params['name_encoding'] : null;
  218. if (!empty($params['filename'])) {
  219. $headers['Content-Type'] .= ';' . $this->eol;
  220. $headers['Content-Type'] .= $this->buildHeaderParam(
  221. 'name', $params['filename'], $h_charset, $h_language, $h_encoding
  222. );
  223. }
  224. // Content-Disposition
  225. if (!empty($params['disposition'])) {
  226. $headers['Content-Disposition'] = $params['disposition'];
  227. if (!empty($params['filename'])) {
  228. $headers['Content-Disposition'] .= ';' . $this->eol;
  229. $headers['Content-Disposition'] .= $this->buildHeaderParam(
  230. 'filename', $params['filename'], $h_charset, $h_language,
  231. !empty($params['filename_encoding']) ? $params['filename_encoding'] : null
  232. );
  233. }
  234. // add attachment size
  235. $size = $this->body_file ? filesize($this->body_file) : strlen($body);
  236. if ($size) {
  237. $headers['Content-Disposition'] .= ';' . $this->eol . ' size=' . $size;
  238. }
  239. }
  240. if (!empty($params['description'])) {
  241. $headers['Content-Description'] = $this->encodeHeader(
  242. 'Content-Description', $params['description'], $h_charset, $h_encoding,
  243. $this->eol
  244. );
  245. }
  246. // Search and add existing headers' parameters
  247. foreach ($headers as $key => $value) {
  248. $items = explode(':', $key);
  249. if (count($items) == 2) {
  250. $header = $items[0];
  251. $param = $items[1];
  252. if (isset($headers[$header])) {
  253. $headers[$header] .= ';' . $this->eol;
  254. }
  255. $headers[$header] .= $this->buildHeaderParam(
  256. $param, $value, $h_charset, $h_language, $h_encoding
  257. );
  258. unset($headers[$key]);
  259. }
  260. }
  261. // Default encoding
  262. if (!isset($this->encoding)) {
  263. $this->encoding = '7bit';
  264. }
  265. // Assign stuff to member variables
  266. $this->encoded = array();
  267. $this->headers = $headers;
  268. $this->body = $body;
  269. }
  270. /**
  271. * Encodes and returns the email. Also stores
  272. * it in the encoded member variable
  273. *
  274. * @param string $boundary Pre-defined boundary string
  275. *
  276. * @return An associative array containing two elements,
  277. * body and headers. The headers element is itself
  278. * an indexed array. On error returns PEAR error object.
  279. */
  280. public function encode($boundary=null)
  281. {
  282. $encoded =& $this->encoded;
  283. if (count($this->subparts)) {
  284. $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
  285. $eol = $this->eol;
  286. $this->headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
  287. $encoded['body'] = '';
  288. if ($this->preamble) {
  289. $encoded['body'] .= $this->preamble . $eol . $eol;
  290. }
  291. for ($i = 0; $i < count($this->subparts); $i++) {
  292. $encoded['body'] .= '--' . $boundary . $eol;
  293. $tmp = $this->subparts[$i]->encode();
  294. if (is_a($tmp, 'PEAR_Error')) {
  295. return $tmp;
  296. }
  297. foreach ($tmp['headers'] as $key => $value) {
  298. $encoded['body'] .= $key . ': ' . $value . $eol;
  299. }
  300. $encoded['body'] .= $eol . $tmp['body'] . $eol;
  301. }
  302. $encoded['body'] .= '--' . $boundary . '--' . $eol;
  303. } else if ($this->body) {
  304. $encoded['body'] = $this->getEncodedData($this->body, $this->encoding);
  305. } else if ($this->body_file) {
  306. // Temporarily reset magic_quotes_runtime for file reads and writes
  307. if ($magic_quote_setting = get_magic_quotes_runtime()) {
  308. @ini_set('magic_quotes_runtime', 0);
  309. }
  310. $body = $this->getEncodedDataFromFile($this->body_file, $this->encoding);
  311. if ($magic_quote_setting) {
  312. @ini_set('magic_quotes_runtime', $magic_quote_setting);
  313. }
  314. if (is_a($body, 'PEAR_Error')) {
  315. return $body;
  316. }
  317. $encoded['body'] = $body;
  318. } else {
  319. $encoded['body'] = '';
  320. }
  321. // Add headers to $encoded
  322. $encoded['headers'] =& $this->headers;
  323. return $encoded;
  324. }
  325. /**
  326. * Encodes and saves the email into file or stream.
  327. * Data will be appended to the file/stream.
  328. *
  329. * @param mixed $filename Existing file location
  330. * or file pointer resource
  331. * @param string $boundary Pre-defined boundary string
  332. * @param boolean $skip_head True if you don't want to save headers
  333. *
  334. * @return array An associative array containing message headers
  335. * or PEAR error object
  336. * @since 1.6.0
  337. */
  338. public function encodeToFile($filename, $boundary = null, $skip_head = false)
  339. {
  340. if (!is_resource($filename)) {
  341. if (file_exists($filename) && !is_writable($filename)) {
  342. $err = self::raiseError('File is not writeable: ' . $filename);
  343. return $err;
  344. }
  345. if (!($fh = fopen($filename, 'ab'))) {
  346. $err = self::raiseError('Unable to open file: ' . $filename);
  347. return $err;
  348. }
  349. } else {
  350. $fh = $filename;
  351. }
  352. // Temporarily reset magic_quotes_runtime for file reads and writes
  353. if ($magic_quote_setting = get_magic_quotes_runtime()) {
  354. @ini_set('magic_quotes_runtime', 0);
  355. }
  356. $res = $this->encodePartToFile($fh, $boundary, $skip_head);
  357. if (!is_resource($filename)) {
  358. fclose($fh);
  359. }
  360. if ($magic_quote_setting) {
  361. @ini_set('magic_quotes_runtime', $magic_quote_setting);
  362. }
  363. return is_a($res, 'PEAR_Error') ? $res : $this->headers;
  364. }
  365. /**
  366. * Encodes given email part into file
  367. *
  368. * @param string $fh Output file handle
  369. * @param string $boundary Pre-defined boundary string
  370. * @param boolean $skip_head True if you don't want to save headers
  371. *
  372. * @return array True on sucess or PEAR error object
  373. */
  374. protected function encodePartToFile($fh, $boundary = null, $skip_head = false)
  375. {
  376. $eol = $this->eol;
  377. if (count($this->subparts)) {
  378. $boundary = $boundary ? $boundary : '=_' . md5(rand() . microtime());
  379. $this->headers['Content-Type'] .= ";$eol boundary=\"$boundary\"";
  380. }
  381. if (!$skip_head) {
  382. foreach ($this->headers as $key => $value) {
  383. fwrite($fh, $key . ': ' . $value . $eol);
  384. }
  385. $f_eol = $eol;
  386. } else {
  387. $f_eol = '';
  388. }
  389. if (count($this->subparts)) {
  390. if ($this->preamble) {
  391. fwrite($fh, $f_eol . $this->preamble . $eol);
  392. $f_eol = $eol;
  393. }
  394. for ($i = 0; $i < count($this->subparts); $i++) {
  395. fwrite($fh, $f_eol . '--' . $boundary . $eol);
  396. $res = $this->subparts[$i]->encodePartToFile($fh);
  397. if (is_a($res, 'PEAR_Error')) {
  398. return $res;
  399. }
  400. $f_eol = $eol;
  401. }
  402. fwrite($fh, $eol . '--' . $boundary . '--' . $eol);
  403. } else if ($this->body) {
  404. fwrite($fh, $f_eol);
  405. fwrite($fh, $this->getEncodedData($this->body, $this->encoding));
  406. } else if ($this->body_file) {
  407. fwrite($fh, $f_eol);
  408. $res = $this->getEncodedDataFromFile(
  409. $this->body_file, $this->encoding, $fh
  410. );
  411. if (is_a($res, 'PEAR_Error')) {
  412. return $res;
  413. }
  414. }
  415. return true;
  416. }
  417. /**
  418. * Adds a subpart to current mime part and returns
  419. * a reference to it
  420. *
  421. * @param mixed $body The body of the subpart or Mail_mimePart object
  422. * @param array $params The parameters for the subpart, same
  423. * as the $params argument for constructor
  424. *
  425. * @return Mail_mimePart A reference to the part you just added.
  426. */
  427. public function addSubpart($body, $params = null)
  428. {
  429. if ($body instanceof Mail_mimePart) {
  430. $part = $body;
  431. } else {
  432. $part = new Mail_mimePart($body, $params);
  433. }
  434. $this->subparts[] = $part;
  435. return $part;
  436. }
  437. /**
  438. * Returns encoded data based upon encoding passed to it
  439. *
  440. * @param string $data The data to encode.
  441. * @param string $encoding The encoding type to use, 7bit, base64,
  442. * or quoted-printable.
  443. *
  444. * @return string Encoded data string
  445. */
  446. protected function getEncodedData($data, $encoding)
  447. {
  448. switch ($encoding) {
  449. case 'quoted-printable':
  450. return self::quotedPrintableEncode($data, 76, $this->eol);
  451. break;
  452. case 'base64':
  453. return rtrim(chunk_split(base64_encode($data), 76, $this->eol));
  454. break;
  455. case '8bit':
  456. case '7bit':
  457. default:
  458. return $data;
  459. }
  460. }
  461. /**
  462. * Returns encoded data based upon encoding passed to it
  463. *
  464. * @param string $filename Data file location
  465. * @param string $encoding The encoding type to use, 7bit, base64,
  466. * or quoted-printable.
  467. * @param resource $fh Output file handle. If set, data will be
  468. * stored into it instead of returning it
  469. *
  470. * @return string Encoded data or PEAR error object
  471. */
  472. protected function getEncodedDataFromFile($filename, $encoding, $fh = null)
  473. {
  474. if (!is_readable($filename)) {
  475. $err = self::raiseError('Unable to read file: ' . $filename);
  476. return $err;
  477. }
  478. if (!($fd = fopen($filename, 'rb'))) {
  479. $err = self::raiseError('Could not open file: ' . $filename);
  480. return $err;
  481. }
  482. $data = '';
  483. switch ($encoding) {
  484. case 'quoted-printable':
  485. while (!feof($fd)) {
  486. $buffer = self::quotedPrintableEncode(fgets($fd), 76, $this->eol);
  487. if ($fh) {
  488. fwrite($fh, $buffer);
  489. } else {
  490. $data .= $buffer;
  491. }
  492. }
  493. break;
  494. case 'base64':
  495. while (!feof($fd)) {
  496. // Should read in a multiple of 57 bytes so that
  497. // the output is 76 bytes per line. Don't use big chunks
  498. // because base64 encoding is memory expensive
  499. $buffer = fread($fd, 57 * 9198); // ca. 0.5 MB
  500. $buffer = base64_encode($buffer);
  501. $buffer = chunk_split($buffer, 76, $this->eol);
  502. if (feof($fd)) {
  503. $buffer = rtrim($buffer);
  504. }
  505. if ($fh) {
  506. fwrite($fh, $buffer);
  507. } else {
  508. $data .= $buffer;
  509. }
  510. }
  511. break;
  512. case '8bit':
  513. case '7bit':
  514. default:
  515. while (!feof($fd)) {
  516. $buffer = fread($fd, 1048576); // 1 MB
  517. if ($fh) {
  518. fwrite($fh, $buffer);
  519. } else {
  520. $data .= $buffer;
  521. }
  522. }
  523. }
  524. fclose($fd);
  525. if (!$fh) {
  526. return $data;
  527. }
  528. }
  529. /**
  530. * Encodes data to quoted-printable standard.
  531. *
  532. * @param string $input The data to encode
  533. * @param int $line_max Optional max line length. Should
  534. * not be more than 76 chars
  535. * @param string $eol End-of-line sequence. Default: "\r\n"
  536. *
  537. * @return string Encoded data
  538. */
  539. public static function quotedPrintableEncode($input , $line_max = 76, $eol = "\r\n")
  540. {
  541. /*
  542. // imap_8bit() is extremely fast, but doesn't handle properly some characters
  543. if (function_exists('imap_8bit') && $line_max == 76) {
  544. $input = preg_replace('/\r?\n/', "\r\n", $input);
  545. $input = imap_8bit($input);
  546. if ($eol != "\r\n") {
  547. $input = str_replace("\r\n", $eol, $input);
  548. }
  549. return $input;
  550. }
  551. */
  552. $lines = preg_split("/\r?\n/", $input);
  553. $escape = '=';
  554. $output = '';
  555. while (list($idx, $line) = each($lines)) {
  556. $newline = '';
  557. $i = 0;
  558. while (isset($line[$i])) {
  559. $char = $line[$i];
  560. $dec = ord($char);
  561. $i++;
  562. if (($dec == 32) && (!isset($line[$i]))) {
  563. // convert space at eol only
  564. $char = '=20';
  565. } elseif ($dec == 9 && isset($line[$i])) {
  566. ; // Do nothing if a TAB is not on eol
  567. } elseif (($dec == 61) || ($dec < 32) || ($dec > 126)) {
  568. $char = $escape . sprintf('%02X', $dec);
  569. } elseif (($dec == 46) && (($newline == '')
  570. || ((strlen($newline) + strlen("=2E")) >= $line_max))
  571. ) {
  572. // Bug #9722: convert full-stop at bol,
  573. // some Windows servers need this, won't break anything (cipri)
  574. // Bug #11731: full-stop at bol also needs to be encoded
  575. // if this line would push us over the line_max limit.
  576. $char = '=2E';
  577. }
  578. // Note, when changing this line, also change the ($dec == 46)
  579. // check line, as it mimics this line due to Bug #11731
  580. // EOL is not counted
  581. if ((strlen($newline) + strlen($char)) >= $line_max) {
  582. // soft line break; " =\r\n" is okay
  583. $output .= $newline . $escape . $eol;
  584. $newline = '';
  585. }
  586. $newline .= $char;
  587. } // end of for
  588. $output .= $newline . $eol;
  589. unset($lines[$idx]);
  590. }
  591. // Don't want last crlf
  592. $output = substr($output, 0, -1 * strlen($eol));
  593. return $output;
  594. }
  595. /**
  596. * Encodes the parameter of a header.
  597. *
  598. * @param string $name The name of the header-parameter
  599. * @param string $value The value of the paramter
  600. * @param string $charset The characterset of $value
  601. * @param string $language The language used in $value
  602. * @param string $encoding Parameter encoding. If not set, parameter value
  603. * is encoded according to RFC2231
  604. * @param int $maxLength The maximum length of a line. Defauls to 75
  605. *
  606. * @return string
  607. */
  608. protected function buildHeaderParam($name, $value, $charset = null,
  609. $language = null, $encoding = null, $maxLength = 75
  610. ) {
  611. // RFC 2045:
  612. // value needs encoding if contains non-ASCII chars or is longer than 78 chars
  613. if (!preg_match('#[^\x20-\x7E]#', $value)) {
  614. $token_regexp = '#([^\x21\x23-\x27\x2A\x2B\x2D'
  615. . '\x2E\x30-\x39\x41-\x5A\x5E-\x7E])#';
  616. if (!preg_match($token_regexp, $value)) {
  617. // token
  618. if (strlen($name) + strlen($value) + 3 <= $maxLength) {
  619. return " {$name}={$value}";
  620. }
  621. } else {
  622. // quoted-string
  623. $quoted = addcslashes($value, '\\"');
  624. if (strlen($name) + strlen($quoted) + 5 <= $maxLength) {
  625. return " {$name}=\"{$quoted}\"";
  626. }
  627. }
  628. }
  629. // RFC2047: use quoted-printable/base64 encoding
  630. if ($encoding == 'quoted-printable' || $encoding == 'base64') {
  631. return $this->buildRFC2047Param($name, $value, $charset, $encoding);
  632. }
  633. // RFC2231:
  634. $encValue = preg_replace_callback(
  635. '/([^\x21\x23\x24\x26\x2B\x2D\x2E\x30-\x39\x41-\x5A\x5E-\x7E])/',
  636. array($this, 'encodeReplaceCallback'), $value
  637. );
  638. $value = "$charset'$language'$encValue";
  639. $header = " {$name}*={$value}";
  640. if (strlen($header) <= $maxLength) {
  641. return $header;
  642. }
  643. $preLength = strlen(" {$name}*0*=");
  644. $maxLength = max(16, $maxLength - $preLength - 3);
  645. $maxLengthReg = "|(.{0,$maxLength}[^\%][^\%])|";
  646. $headers = array();
  647. $headCount = 0;
  648. while ($value) {
  649. $matches = array();
  650. $found = preg_match($maxLengthReg, $value, $matches);
  651. if ($found) {
  652. $headers[] = " {$name}*{$headCount}*={$matches[0]}";
  653. $value = substr($value, strlen($matches[0]));
  654. } else {
  655. $headers[] = " {$name}*{$headCount}*={$value}";
  656. $value = '';
  657. }
  658. $headCount++;
  659. }
  660. $headers = implode(';' . $this->eol, $headers);
  661. return $headers;
  662. }
  663. /**
  664. * Encodes header parameter as per RFC2047 if needed
  665. *
  666. * @param string $name The parameter name
  667. * @param string $value The parameter value
  668. * @param string $charset The parameter charset
  669. * @param string $encoding Encoding type (quoted-printable or base64)
  670. * @param int $maxLength Encoded parameter max length. Default: 76
  671. *
  672. * @return string Parameter line
  673. */
  674. protected function buildRFC2047Param($name, $value, $charset,
  675. $encoding = 'quoted-printable', $maxLength = 76
  676. ) {
  677. // WARNING: RFC 2047 says: "An 'encoded-word' MUST NOT be used in
  678. // parameter of a MIME Content-Type or Content-Disposition field",
  679. // but... it's supported by many clients/servers
  680. $quoted = '';
  681. if ($encoding == 'base64') {
  682. $value = base64_encode($value);
  683. $prefix = '=?' . $charset . '?B?';
  684. $suffix = '?=';
  685. // 2 x SPACE, 2 x '"', '=', ';'
  686. $add_len = strlen($prefix . $suffix) + strlen($name) + 6;
  687. $len = $add_len + strlen($value);
  688. while ($len > $maxLength) {
  689. // We can cut base64-encoded string every 4 characters
  690. $real_len = floor(($maxLength - $add_len) / 4) * 4;
  691. $_quote = substr($value, 0, $real_len);
  692. $value = substr($value, $real_len);
  693. $quoted .= $prefix . $_quote . $suffix . $this->eol . ' ';
  694. $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
  695. $len = strlen($value) + $add_len;
  696. }
  697. $quoted .= $prefix . $value . $suffix;
  698. } else {
  699. // quoted-printable
  700. $value = $this->encodeQP($value);
  701. $prefix = '=?' . $charset . '?Q?';
  702. $suffix = '?=';
  703. // 2 x SPACE, 2 x '"', '=', ';'
  704. $add_len = strlen($prefix . $suffix) + strlen($name) + 6;
  705. $len = $add_len + strlen($value);
  706. while ($len > $maxLength) {
  707. $length = $maxLength - $add_len;
  708. // don't break any encoded letters
  709. if (preg_match("/^(.{0,$length}[^\=][^\=])/", $value, $matches)) {
  710. $_quote = $matches[1];
  711. }
  712. $quoted .= $prefix . $_quote . $suffix . $this->eol . ' ';
  713. $value = substr($value, strlen($_quote));
  714. $add_len = strlen($prefix . $suffix) + 4; // 2 x SPACE, '"', ';'
  715. $len = strlen($value) + $add_len;
  716. }
  717. $quoted .= $prefix . $value . $suffix;
  718. }
  719. return " {$name}=\"{$quoted}\"";
  720. }
  721. /**
  722. * Encodes a header as per RFC2047
  723. *
  724. * @param string $name The header name
  725. * @param string $value The header data to encode
  726. * @param string $charset Character set name
  727. * @param string $encoding Encoding name (base64 or quoted-printable)
  728. * @param string $eol End-of-line sequence. Default: "\r\n"
  729. *
  730. * @return string Encoded header data (without a name)
  731. * @since 1.6.1
  732. */
  733. public static function encodeHeader($name, $value, $charset = 'ISO-8859-1',
  734. $encoding = 'quoted-printable', $eol = "\r\n"
  735. ) {
  736. // Structured headers
  737. $comma_headers = array(
  738. 'from', 'to', 'cc', 'bcc', 'sender', 'reply-to',
  739. 'resent-from', 'resent-to', 'resent-cc', 'resent-bcc',
  740. 'resent-sender', 'resent-reply-to',
  741. 'mail-reply-to', 'mail-followup-to',
  742. 'return-receipt-to', 'disposition-notification-to',
  743. );
  744. $other_headers = array(
  745. 'references', 'in-reply-to', 'message-id', 'resent-message-id',
  746. );
  747. $name = strtolower($name);
  748. if (in_array($name, $comma_headers)) {
  749. $separator = ',';
  750. } else if (in_array($name, $other_headers)) {
  751. $separator = ' ';
  752. }
  753. if (!$charset) {
  754. $charset = 'ISO-8859-1';
  755. }
  756. // Structured header (make sure addr-spec inside is not encoded)
  757. if (!empty($separator)) {
  758. // Simple e-mail address regexp
  759. $email_regexp = '([^\s<]+|("[^\r\n"]+"))@\S+';
  760. $parts = Mail_mimePart::explodeQuotedString("[\t$separator]", $value);
  761. $value = '';
  762. foreach ($parts as $part) {
  763. $part = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $part);
  764. $part = trim($part);
  765. if (!$part) {
  766. continue;
  767. }
  768. if ($value) {
  769. $value .= $separator == ',' ? $separator . ' ' : ' ';
  770. } else {
  771. $value = $name . ': ';
  772. }
  773. // let's find phrase (name) and/or addr-spec
  774. if (preg_match('/^<' . $email_regexp . '>$/', $part)) {
  775. $value .= $part;
  776. } else if (preg_match('/^' . $email_regexp . '$/', $part)) {
  777. // address without brackets and without name
  778. $value .= $part;
  779. } else if (preg_match('/<*' . $email_regexp . '>*$/', $part, $matches)) {
  780. // address with name (handle name)
  781. $address = $matches[0];
  782. $word = str_replace($address, '', $part);
  783. $word = trim($word);
  784. // check if phrase requires quoting
  785. if ($word) {
  786. // non-ASCII: require encoding
  787. if (preg_match('#([^\s\x21-\x7E]){1}#', $word)) {
  788. if ($word[0] == '"' && $word[strlen($word)-1] == '"') {
  789. // de-quote quoted-string, encoding changes
  790. // string to atom
  791. $search = array("\\\"", "\\\\");
  792. $replace = array("\"", "\\");
  793. $word = str_replace($search, $replace, $word);
  794. $word = substr($word, 1, -1);
  795. }
  796. // find length of last line
  797. if (($pos = strrpos($value, $eol)) !== false) {
  798. $last_len = strlen($value) - $pos;
  799. } else {
  800. $last_len = strlen($value);
  801. }
  802. $word = Mail_mimePart::encodeHeaderValue(
  803. $word, $charset, $encoding, $last_len, $eol
  804. );
  805. } else if (($word[0] != '"' || $word[strlen($word)-1] != '"')
  806. && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $word)
  807. ) {
  808. // ASCII: quote string if needed
  809. $word = '"'.addcslashes($word, '\\"').'"';
  810. }
  811. }
  812. $value .= $word.' '.$address;
  813. } else {
  814. // addr-spec not found, don't encode (?)
  815. $value .= $part;
  816. }
  817. // RFC2822 recommends 78 characters limit, use 76 from RFC2047
  818. $value = wordwrap($value, 76, $eol . ' ');
  819. }
  820. // remove header name prefix (there could be EOL too)
  821. $value = preg_replace(
  822. '/^'.$name.':('.preg_quote($eol, '/').')* /', '', $value
  823. );
  824. } else {
  825. // Unstructured header
  826. // non-ASCII: require encoding
  827. if (preg_match('#([^\s\x21-\x7E]){1}#', $value)) {
  828. if ($value[0] == '"' && $value[strlen($value)-1] == '"') {
  829. // de-quote quoted-string, encoding changes
  830. // string to atom
  831. $search = array("\\\"", "\\\\");
  832. $replace = array("\"", "\\");
  833. $value = str_replace($search, $replace, $value);
  834. $value = substr($value, 1, -1);
  835. }
  836. $value = Mail_mimePart::encodeHeaderValue(
  837. $value, $charset, $encoding, strlen($name) + 2, $eol
  838. );
  839. } else if (strlen($name.': '.$value) > 78) {
  840. // ASCII: check if header line isn't too long and use folding
  841. $value = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $value);
  842. $tmp = wordwrap($name.': '.$value, 78, $eol . ' ');
  843. $value = preg_replace('/^'.$name.':\s*/', '', $tmp);
  844. // hard limit 998 (RFC2822)
  845. $value = wordwrap($value, 998, $eol . ' ', true);
  846. }
  847. }
  848. return $value;
  849. }
  850. /**
  851. * Explode quoted string
  852. *
  853. * @param string $delimiter Delimiter expression string for preg_match()
  854. * @param string $string Input string
  855. *
  856. * @return array String tokens array
  857. */
  858. protected static function explodeQuotedString($delimiter, $string)
  859. {
  860. $result = array();
  861. $strlen = strlen($string);
  862. for ($q=$p=$i=0; $i < $strlen; $i++) {
  863. if ($string[$i] == "\""
  864. && (empty($string[$i-1]) || $string[$i-1] != "\\")
  865. ) {
  866. $q = $q ? false : true;
  867. } else if (!$q && preg_match("/$delimiter/", $string[$i])) {
  868. $result[] = substr($string, $p, $i - $p);
  869. $p = $i + 1;
  870. }
  871. }
  872. $result[] = substr($string, $p);
  873. return $result;
  874. }
  875. /**
  876. * Encodes a header value as per RFC2047
  877. *
  878. * @param string $value The header data to encode
  879. * @param string $charset Character set name
  880. * @param string $encoding Encoding name (base64 or quoted-printable)
  881. * @param int $prefix_len Prefix length. Default: 0
  882. * @param string $eol End-of-line sequence. Default: "\r\n"
  883. *
  884. * @return string Encoded header data
  885. * @since 1.6.1
  886. */
  887. public static function encodeHeaderValue($value, $charset, $encoding, $prefix_len = 0, $eol = "\r\n")
  888. {
  889. // #17311: Use multibyte aware method (requires mbstring extension)
  890. if ($result = Mail_mimePart::encodeMB($value, $charset, $encoding, $prefix_len, $eol)) {
  891. return $result;
  892. }
  893. // Generate the header using the specified params and dynamicly
  894. // determine the maximum length of such strings.
  895. // 75 is the value specified in the RFC.
  896. $encoding = $encoding == 'base64' ? 'B' : 'Q';
  897. $prefix = '=?' . $charset . '?' . $encoding .'?';
  898. $suffix = '?=';
  899. $maxLength = 75 - strlen($prefix . $suffix);
  900. $maxLength1stLine = $maxLength - $prefix_len;
  901. if ($encoding == 'B') {
  902. // Base64 encode the entire string
  903. $value = base64_encode($value);
  904. // We can cut base64 every 4 characters, so the real max
  905. // we can get must be rounded down.
  906. $maxLength = $maxLength - ($maxLength % 4);
  907. $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
  908. $cutpoint = $maxLength1stLine;
  909. $output = '';
  910. while ($value) {
  911. // Split translated string at every $maxLength
  912. $part = substr($value, 0, $cutpoint);
  913. $value = substr($value, $cutpoint);
  914. $cutpoint = $maxLength;
  915. // RFC 2047 specifies that any split header should
  916. // be separated by a CRLF SPACE.
  917. if ($output) {
  918. $output .= $eol . ' ';
  919. }
  920. $output .= $prefix . $part . $suffix;
  921. }
  922. $value = $output;
  923. } else {
  924. // quoted-printable encoding has been selected
  925. $value = Mail_mimePart::encodeQP($value);
  926. // This regexp will break QP-encoded text at every $maxLength
  927. // but will not break any encoded letters.
  928. $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
  929. $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
  930. if (strlen($value) > $maxLength1stLine) {
  931. // Begin with the regexp for the first line.
  932. $reg = $reg1st;
  933. $output = '';
  934. while ($value) {
  935. // Split translated string at every $maxLength
  936. // But make sure not to break any translated chars.
  937. $found = preg_match($reg, $value, $matches);
  938. // After this first line, we need to use a different
  939. // regexp for the first line.
  940. $reg = $reg2nd;
  941. // Save the found part and encapsulate it in the
  942. // prefix & suffix. Then remove the part from the
  943. // $value_out variable.
  944. if ($found) {
  945. $part = $matches[0];
  946. $len = strlen($matches[0]);
  947. $value = substr($value, $len);
  948. } else {
  949. $part = $value;
  950. $value = '';
  951. }
  952. // RFC 2047 specifies that any split header should
  953. // be separated by a CRLF SPACE
  954. if ($output) {
  955. $output .= $eol . ' ';
  956. }
  957. $output .= $prefix . $part . $suffix;
  958. }
  959. $value = $output;
  960. } else {
  961. $value = $prefix . $value . $suffix;
  962. }
  963. }
  964. return $value;
  965. }
  966. /**
  967. * Encodes the given string using quoted-printable
  968. *
  969. * @param string $str String to encode
  970. *
  971. * @return string Encoded string
  972. * @since 1.6.0
  973. */
  974. public static function encodeQP($str)
  975. {
  976. // Bug #17226 RFC 2047 restricts some characters
  977. // if the word is inside a phrase, permitted chars are only:
  978. // ASCII letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
  979. // "=", "_", "?" must be encoded
  980. $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
  981. $str = preg_replace_callback(
  982. $regexp, array('Mail_mimePart', 'qpReplaceCallback'), $str
  983. );
  984. return str_replace(' ', '_', $str);
  985. }
  986. /**
  987. * Encodes the given string using base64 or quoted-printable.
  988. * This method makes sure that encoded-word represents an integral
  989. * number of characters as per RFC2047.
  990. *
  991. * @param string $str String to encode
  992. * @param string $charset Character set name
  993. * @param string $encoding Encoding name (base64 or quoted-printable)
  994. * @param int $prefix_len Prefix length. Default: 0
  995. * @param string $eol End-of-line sequence. Default: "\r\n"
  996. *
  997. * @return string Encoded string
  998. * @since 1.8.0
  999. */
  1000. public static function encodeMB($str, $charset, $encoding, $prefix_len=0, $eol="\r\n")
  1001. {
  1002. if (!function_exists('mb_substr') || !function_exists('mb_strlen')) {
  1003. return;
  1004. }
  1005. $encoding = $encoding == 'base64' ? 'B' : 'Q';
  1006. // 75 is the value specified in the RFC
  1007. $prefix = '=?' . $charset . '?'.$encoding.'?';
  1008. $suffix = '?=';
  1009. $maxLength = 75 - strlen($prefix . $suffix);
  1010. // A multi-octet character may not be split across adjacent encoded-words
  1011. // So, we'll loop over each character
  1012. // mb_stlen() with wrong charset will generate a warning here and return null
  1013. $length = mb_strlen($str, $charset);
  1014. $result = '';
  1015. $line_length = $prefix_len;
  1016. if ($encoding == 'B') {
  1017. // base64
  1018. $start = 0;
  1019. $prev = '';
  1020. for ($i=1; $i<=$length; $i++) {
  1021. // See #17311
  1022. $chunk = mb_substr($str, $start, $i-$start, $charset);
  1023. $chunk = base64_encode($chunk);
  1024. $chunk_len = strlen($chunk);
  1025. if ($line_length + $chunk_len == $maxLength || $i == $length) {
  1026. if ($result) {
  1027. $result .= "\n";
  1028. }
  1029. $result .= $chunk;
  1030. $line_length = 0;
  1031. $start = $i;
  1032. } else if ($line_length + $chunk_len > $maxLength) {
  1033. if ($result) {
  1034. $result .= "\n";
  1035. }
  1036. if ($prev) {
  1037. $result .= $prev;
  1038. }
  1039. $line_length = 0;
  1040. $start = $i - 1;
  1041. } else {
  1042. $prev = $chunk;
  1043. }
  1044. }
  1045. } else {
  1046. // quoted-printable
  1047. // see encodeQP()
  1048. $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
  1049. for ($i=0; $i<=$length; $i++) {
  1050. $char = mb_substr($str, $i, 1, $charset);
  1051. // RFC recommends underline (instead of =20) in place of the space
  1052. // that's one of the reasons why we're not using iconv_mime_encode()
  1053. if ($char == ' ') {
  1054. $char = '_';
  1055. $char_len = 1;
  1056. } else {
  1057. $char = preg_replace_callback(
  1058. $regexp, array('Mail_mimePart', 'qpReplaceCallback'), $char
  1059. );
  1060. $char_len = strlen($char);
  1061. }
  1062. if ($line_length + $char_len > $maxLength) {
  1063. if ($result) {
  1064. $result .= "\n";
  1065. }
  1066. $line_length = 0;
  1067. }
  1068. $result .= $char;
  1069. $line_length += $char_len;
  1070. }
  1071. }
  1072. if ($result) {
  1073. $result = $prefix
  1074. .str_replace("\n", $suffix.$eol.' '.$prefix, $result).$suffix;
  1075. }
  1076. return $result;
  1077. }
  1078. /**
  1079. * Callback function to replace extended characters (\x80-xFF) with their
  1080. * ASCII values (RFC2047: quoted-printable)
  1081. *
  1082. * @param array $matches Preg_replace's matches array
  1083. *
  1084. * @return string Encoded character string
  1085. */
  1086. protected static function qpReplaceCallback($matches)
  1087. {
  1088. return sprintf('=%02X', ord($matches[1]));
  1089. }
  1090. /**
  1091. * Callback function to replace extended characters (\x80-xFF) with their
  1092. * ASCII values (RFC2231)
  1093. *
  1094. * @param array $matches Preg_replace's matches array
  1095. *
  1096. * @return string Encoded character string
  1097. */
  1098. protected static function encodeReplaceCallback($matches)
  1099. {
  1100. return sprintf('%%%02X', ord($matches[1]));
  1101. }
  1102. /**
  1103. * PEAR::raiseError implementation
  1104. *
  1105. * @param string $message A text error message
  1106. *
  1107. * @return PEAR_Error Instance of PEAR_Error
  1108. */
  1109. public static function raiseError($message)
  1110. {
  1111. // PEAR::raiseError() is not PHP 5.4 compatible
  1112. return new PEAR_Error($message);
  1113. }
  1114. }