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.

mimePart.php 45KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276
  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 and 7
  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 = array();
  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 = array();
  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
  155. * can be 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. foreach ($lines as $idx => $line) {
  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. // exploding quoted strings as well as some regexes below do not
  757. // work properly with some charset e.g. ISO-2022-JP, we'll use UTF-8
  758. $mb = $charset != 'UTF-8' && function_exists('mb_convert_encoding');
  759. // Structured header (make sure addr-spec inside is not encoded)
  760. if (!empty($separator)) {
  761. // Simple e-mail address regexp
  762. $email_regexp = '([^\s<]+|("[^\r\n"]+"))@\S+';
  763. if ($mb) {
  764. $value = mb_convert_encoding($value, 'UTF-8', $charset);
  765. }
  766. $parts = Mail_mimePart::explodeQuotedString("[\t$separator]", $value);
  767. $value = '';
  768. foreach ($parts as $part) {
  769. $part = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $part);
  770. $part = trim($part);
  771. if (!$part) {
  772. continue;
  773. }
  774. if ($value) {
  775. $value .= $separator == ',' ? $separator . ' ' : ' ';
  776. } else {
  777. $value = $name . ': ';
  778. }
  779. // let's find phrase (name) and/or addr-spec
  780. if (preg_match('/^<' . $email_regexp . '>$/', $part)) {
  781. $value .= $part;
  782. } else if (preg_match('/^' . $email_regexp . '$/', $part)) {
  783. // address without brackets and without name
  784. $value .= $part;
  785. } else if (preg_match('/<*' . $email_regexp . '>*$/', $part, $matches)) {
  786. // address with name (handle name)
  787. $address = $matches[0];
  788. $word = str_replace($address, '', $part);
  789. $word = trim($word);
  790. // check if phrase requires quoting
  791. if ($word) {
  792. // non-ASCII: require encoding
  793. if (preg_match('#([^\s\x21-\x7E]){1}#', $word)) {
  794. if ($word[0] == '"' && $word[strlen($word)-1] == '"') {
  795. // de-quote quoted-string, encoding changes
  796. // string to atom
  797. $word = substr($word, 1, -1);
  798. $word = preg_replace('/\\\\([\\\\"])/', '$1', $word);
  799. }
  800. if ($mb) {
  801. $word = mb_convert_encoding($word, $charset, 'UTF-8');
  802. }
  803. // find length of last line
  804. if (($pos = strrpos($value, $eol)) !== false) {
  805. $last_len = strlen($value) - $pos;
  806. } else {
  807. $last_len = strlen($value);
  808. }
  809. $word = Mail_mimePart::encodeHeaderValue(
  810. $word, $charset, $encoding, $last_len, $eol
  811. );
  812. } else if (($word[0] != '"' || $word[strlen($word)-1] != '"')
  813. && preg_match('/[\(\)\<\>\\\.\[\]@,;:"]/', $word)
  814. ) {
  815. // ASCII: quote string if needed
  816. $word = '"'.addcslashes($word, '\\"').'"';
  817. }
  818. }
  819. $value .= $word.' '.$address;
  820. } else {
  821. if ($mb) {
  822. $part = mb_convert_encoding($part, $charset, 'UTF-8');
  823. }
  824. // addr-spec not found, don't encode (?)
  825. $value .= $part;
  826. }
  827. // RFC2822 recommends 78 characters limit, use 76 from RFC2047
  828. $value = wordwrap($value, 76, $eol . ' ');
  829. }
  830. // remove header name prefix (there could be EOL too)
  831. $value = preg_replace(
  832. '/^'.$name.':('.preg_quote($eol, '/').')* /', '', $value
  833. );
  834. } else {
  835. // Unstructured header
  836. // non-ASCII: require encoding
  837. if (preg_match('#([^\s\x21-\x7E]){1}#', $value)) {
  838. if ($value[0] == '"' && $value[strlen($value)-1] == '"') {
  839. if ($mb) {
  840. $value = mb_convert_encoding($value, 'UTF-8', $charset);
  841. }
  842. // de-quote quoted-string, encoding changes
  843. // string to atom
  844. $value = substr($value, 1, -1);
  845. $value = preg_replace('/\\\\([\\\\"])/', '$1', $value);
  846. if ($mb) {
  847. $value = mb_convert_encoding($value, $charset, 'UTF-8');
  848. }
  849. }
  850. $value = Mail_mimePart::encodeHeaderValue(
  851. $value, $charset, $encoding, strlen($name) + 2, $eol
  852. );
  853. } else if (strlen($name.': '.$value) > 78) {
  854. // ASCII: check if header line isn't too long and use folding
  855. $value = preg_replace('/\r?\n[\s\t]*/', $eol . ' ', $value);
  856. $tmp = wordwrap($name . ': ' . $value, 78, $eol . ' ');
  857. $value = preg_replace('/^' . $name . ':\s*/', '', $tmp);
  858. // hard limit 998 (RFC2822)
  859. $value = wordwrap($value, 998, $eol . ' ', true);
  860. }
  861. }
  862. return $value;
  863. }
  864. /**
  865. * Explode quoted string
  866. *
  867. * @param string $delimiter Delimiter expression string for preg_match()
  868. * @param string $string Input string
  869. *
  870. * @return array String tokens array
  871. */
  872. protected static function explodeQuotedString($delimiter, $string)
  873. {
  874. $result = array();
  875. $strlen = strlen($string);
  876. $quoted_string = '"(?:[^"\\\\]|\\\\.)*"';
  877. for ($p=$i=0; $i < $strlen; $i++) {
  878. if ($string[$i] === '"') {
  879. $r = preg_match("/$quoted_string/", $string, $matches, 0, $i);
  880. if (!$r || empty($matches[0])) {
  881. break;
  882. }
  883. $i += strlen($matches[0]) - 1;
  884. } else if (preg_match("/$delimiter/", $string[$i])) {
  885. $result[] = substr($string, $p, $i - $p);
  886. $p = $i + 1;
  887. }
  888. }
  889. $result[] = substr($string, $p);
  890. return $result;
  891. }
  892. /**
  893. * Encodes a header value as per RFC2047
  894. *
  895. * @param string $value The header data to encode
  896. * @param string $charset Character set name
  897. * @param string $encoding Encoding name (base64 or quoted-printable)
  898. * @param int $prefix_len Prefix length. Default: 0
  899. * @param string $eol End-of-line sequence. Default: "\r\n"
  900. *
  901. * @return string Encoded header data
  902. * @since 1.6.1
  903. */
  904. public static function encodeHeaderValue($value, $charset, $encoding, $prefix_len = 0, $eol = "\r\n")
  905. {
  906. // #17311: Use multibyte aware method (requires mbstring extension)
  907. if ($result = Mail_mimePart::encodeMB($value, $charset, $encoding, $prefix_len, $eol)) {
  908. return $result;
  909. }
  910. // Generate the header using the specified params and dynamicly
  911. // determine the maximum length of such strings.
  912. // 75 is the value specified in the RFC.
  913. $encoding = $encoding == 'base64' ? 'B' : 'Q';
  914. $prefix = '=?' . $charset . '?' . $encoding .'?';
  915. $suffix = '?=';
  916. $maxLength = 75 - strlen($prefix . $suffix);
  917. $maxLength1stLine = $maxLength - $prefix_len;
  918. if ($encoding == 'B') {
  919. // Base64 encode the entire string
  920. $value = base64_encode($value);
  921. // We can cut base64 every 4 characters, so the real max
  922. // we can get must be rounded down.
  923. $maxLength = $maxLength - ($maxLength % 4);
  924. $maxLength1stLine = $maxLength1stLine - ($maxLength1stLine % 4);
  925. $cutpoint = $maxLength1stLine;
  926. $output = '';
  927. while ($value) {
  928. // Split translated string at every $maxLength
  929. $part = substr($value, 0, $cutpoint);
  930. $value = substr($value, $cutpoint);
  931. $cutpoint = $maxLength;
  932. // RFC 2047 specifies that any split header should
  933. // be separated by a CRLF SPACE.
  934. if ($output) {
  935. $output .= $eol . ' ';
  936. }
  937. $output .= $prefix . $part . $suffix;
  938. }
  939. $value = $output;
  940. } else {
  941. // quoted-printable encoding has been selected
  942. $value = Mail_mimePart::encodeQP($value);
  943. // This regexp will break QP-encoded text at every $maxLength
  944. // but will not break any encoded letters.
  945. $reg1st = "|(.{0,$maxLength1stLine}[^\=][^\=])|";
  946. $reg2nd = "|(.{0,$maxLength}[^\=][^\=])|";
  947. if (strlen($value) > $maxLength1stLine) {
  948. // Begin with the regexp for the first line.
  949. $reg = $reg1st;
  950. $output = '';
  951. while ($value) {
  952. // Split translated string at every $maxLength
  953. // But make sure not to break any translated chars.
  954. $found = preg_match($reg, $value, $matches);
  955. // After this first line, we need to use a different
  956. // regexp for the first line.
  957. $reg = $reg2nd;
  958. // Save the found part and encapsulate it in the
  959. // prefix & suffix. Then remove the part from the
  960. // $value_out variable.
  961. if ($found) {
  962. $part = $matches[0];
  963. $len = strlen($matches[0]);
  964. $value = substr($value, $len);
  965. } else {
  966. $part = $value;
  967. $value = '';
  968. }
  969. // RFC 2047 specifies that any split header should
  970. // be separated by a CRLF SPACE
  971. if ($output) {
  972. $output .= $eol . ' ';
  973. }
  974. $output .= $prefix . $part . $suffix;
  975. }
  976. $value = $output;
  977. } else {
  978. $value = $prefix . $value . $suffix;
  979. }
  980. }
  981. return $value;
  982. }
  983. /**
  984. * Encodes the given string using quoted-printable
  985. *
  986. * @param string $str String to encode
  987. *
  988. * @return string Encoded string
  989. * @since 1.6.0
  990. */
  991. public static function encodeQP($str)
  992. {
  993. // Bug #17226 RFC 2047 restricts some characters
  994. // if the word is inside a phrase, permitted chars are only:
  995. // ASCII letters, decimal digits, "!", "*", "+", "-", "/", "=", and "_"
  996. // "=", "_", "?" must be encoded
  997. $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
  998. $str = preg_replace_callback(
  999. $regexp, array('Mail_mimePart', 'qpReplaceCallback'), $str
  1000. );
  1001. return str_replace(' ', '_', $str);
  1002. }
  1003. /**
  1004. * Encodes the given string using base64 or quoted-printable.
  1005. * This method makes sure that encoded-word represents an integral
  1006. * number of characters as per RFC2047.
  1007. *
  1008. * @param string $str String to encode
  1009. * @param string $charset Character set name
  1010. * @param string $encoding Encoding name (base64 or quoted-printable)
  1011. * @param int $prefix_len Prefix length. Default: 0
  1012. * @param string $eol End-of-line sequence. Default: "\r\n"
  1013. *
  1014. * @return string Encoded string
  1015. * @since 1.8.0
  1016. */
  1017. public static function encodeMB($str, $charset, $encoding, $prefix_len=0, $eol="\r\n")
  1018. {
  1019. if (!function_exists('mb_substr') || !function_exists('mb_strlen')) {
  1020. return;
  1021. }
  1022. $encoding = $encoding == 'base64' ? 'B' : 'Q';
  1023. // 75 is the value specified in the RFC
  1024. $prefix = '=?' . $charset . '?'.$encoding.'?';
  1025. $suffix = '?=';
  1026. $maxLength = 75 - strlen($prefix . $suffix);
  1027. // A multi-octet character may not be split across adjacent encoded-words
  1028. // So, we'll loop over each character
  1029. // mb_stlen() with wrong charset will generate a warning here and return null
  1030. $length = mb_strlen($str, $charset);
  1031. $result = '';
  1032. $line_length = $prefix_len;
  1033. if ($encoding == 'B') {
  1034. // base64
  1035. $start = 0;
  1036. $prev = '';
  1037. for ($i=1; $i<=$length; $i++) {
  1038. // See #17311
  1039. $chunk = mb_substr($str, $start, $i-$start, $charset);
  1040. $chunk = base64_encode($chunk);
  1041. $chunk_len = strlen($chunk);
  1042. if ($line_length + $chunk_len == $maxLength || $i == $length) {
  1043. if ($result) {
  1044. $result .= "\n";
  1045. }
  1046. $result .= $chunk;
  1047. $line_length = 0;
  1048. $start = $i;
  1049. } else if ($line_length + $chunk_len > $maxLength) {
  1050. if ($result) {
  1051. $result .= "\n";
  1052. }
  1053. if ($prev) {
  1054. $result .= $prev;
  1055. }
  1056. $line_length = 0;
  1057. $start = $i - 1;
  1058. } else {
  1059. $prev = $chunk;
  1060. }
  1061. }
  1062. } else {
  1063. // quoted-printable
  1064. // see encodeQP()
  1065. $regexp = '/([\x22-\x29\x2C\x2E\x3A-\x40\x5B-\x60\x7B-\x7E\x80-\xFF])/';
  1066. for ($i=0; $i<=$length; $i++) {
  1067. $char = mb_substr($str, $i, 1, $charset);
  1068. // RFC recommends underline (instead of =20) in place of the space
  1069. // that's one of the reasons why we're not using iconv_mime_encode()
  1070. if ($char == ' ') {
  1071. $char = '_';
  1072. $char_len = 1;
  1073. } else {
  1074. $char = preg_replace_callback(
  1075. $regexp, array('Mail_mimePart', 'qpReplaceCallback'), $char
  1076. );
  1077. $char_len = strlen($char);
  1078. }
  1079. if ($line_length + $char_len > $maxLength) {
  1080. if ($result) {
  1081. $result .= "\n";
  1082. }
  1083. $line_length = 0;
  1084. }
  1085. $result .= $char;
  1086. $line_length += $char_len;
  1087. }
  1088. }
  1089. if ($result) {
  1090. $result = $prefix
  1091. .str_replace("\n", $suffix.$eol.' '.$prefix, $result).$suffix;
  1092. }
  1093. return $result;
  1094. }
  1095. /**
  1096. * Callback function to replace extended characters (\x80-xFF) with their
  1097. * ASCII values (RFC2047: quoted-printable)
  1098. *
  1099. * @param array $matches Preg_replace's matches array
  1100. *
  1101. * @return string Encoded character string
  1102. */
  1103. protected static function qpReplaceCallback($matches)
  1104. {
  1105. return sprintf('=%02X', ord($matches[1]));
  1106. }
  1107. /**
  1108. * Callback function to replace extended characters (\x80-xFF) with their
  1109. * ASCII values (RFC2231)
  1110. *
  1111. * @param array $matches Preg_replace's matches array
  1112. *
  1113. * @return string Encoded character string
  1114. */
  1115. protected static function encodeReplaceCallback($matches)
  1116. {
  1117. return sprintf('%%%02X', ord($matches[1]));
  1118. }
  1119. /**
  1120. * PEAR::raiseError implementation
  1121. *
  1122. * @param string $message A text error message
  1123. *
  1124. * @return PEAR_Error Instance of PEAR_Error
  1125. */
  1126. public static function raiseError($message)
  1127. {
  1128. // PEAR::raiseError() is not PHP 5.4 compatible
  1129. return new PEAR_Error($message);
  1130. }
  1131. }