PageRenderTime 39ms CodeModel.GetById 14ms RepoModel.GetById 0ms app.codeStats 0ms

/web/core/lib/Drupal/Core/Mail/MailFormatHelper.php

https://gitlab.com/mohamed_hussein/prodt
PHP | 383 lines | 272 code | 23 blank | 88 comment | 9 complexity | b40986a56695299e4bec802541c6f34e MD5 | raw file
  1. <?php
  2. namespace Drupal\Core\Mail;
  3. use Drupal\Component\Utility\Html;
  4. use Drupal\Component\Utility\Xss;
  5. use Drupal\Core\Site\Settings;
  6. /**
  7. * Defines a class containing utility methods for formatting mail messages.
  8. */
  9. class MailFormatHelper {
  10. /**
  11. * Internal array of urls replaced with tokens.
  12. *
  13. * @var array
  14. */
  15. protected static $urls = [];
  16. /**
  17. * Quoted regex expression based on base path.
  18. *
  19. * @var string
  20. */
  21. protected static $regexp;
  22. /**
  23. * Array of tags supported.
  24. *
  25. * @var array
  26. */
  27. protected static $supportedTags = [];
  28. /**
  29. * Performs format=flowed soft wrapping for mail (RFC 3676).
  30. *
  31. * We use delsp=yes wrapping, but only break non-spaced languages when
  32. * absolutely necessary to avoid compatibility issues.
  33. *
  34. * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
  35. *
  36. * @param string $text
  37. * The plain text to process.
  38. * @param string $indent
  39. * (optional) A string to indent the text with. Only '>' characters are
  40. * repeated on subsequent wrapped lines. Others are replaced by spaces.
  41. *
  42. * @return string
  43. * The content of the email as a string with formatting applied.
  44. */
  45. public static function wrapMail($text, $indent = '') {
  46. // Convert CRLF into LF.
  47. $text = str_replace("\r", '', $text);
  48. // See if soft-wrapping is allowed.
  49. $clean_indent = static::htmlToTextClean($indent);
  50. $soft = strpos($clean_indent, ' ') === FALSE;
  51. // Check if the string has line breaks.
  52. if (strpos($text, "\n") !== FALSE) {
  53. // Remove trailing spaces to make existing breaks hard, but leave
  54. // signature marker untouched (RFC 3676, Section 4.3).
  55. $text = preg_replace('/(?(?<!^--) +\n| +\n)/m', "\n", $text);
  56. // Wrap each line at the needed width.
  57. $lines = explode("\n", $text);
  58. array_walk($lines, '\Drupal\Core\Mail\MailFormatHelper::wrapMailLine', ['soft' => $soft, 'length' => strlen($indent)]);
  59. $text = implode("\n", $lines);
  60. }
  61. else {
  62. // Wrap this line.
  63. static::wrapMailLine($text, 0, ['soft' => $soft, 'length' => strlen($indent)]);
  64. }
  65. // Empty lines with nothing but spaces.
  66. $text = preg_replace('/^ +\n/m', "\n", $text);
  67. // Space-stuff special lines.
  68. $text = preg_replace('/^(>| |From)/m', ' $1', $text);
  69. // Apply indentation. We only include non-'>' indentation on the first line.
  70. $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
  71. return $text;
  72. }
  73. /**
  74. * Transforms an HTML string into plain text, preserving its structure.
  75. *
  76. * The output will be suitable for use as 'format=flowed; delsp=yes' text
  77. * (RFC 3676) and can be passed directly to MailManagerInterface::mail() for sending.
  78. *
  79. * We deliberately use LF rather than CRLF, see MailManagerInterface::mail().
  80. *
  81. * This function provides suitable alternatives for the following tags:
  82. * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
  83. * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
  84. *
  85. * @param string $string
  86. * The string to be transformed.
  87. * @param array $allowed_tags
  88. * (optional) If supplied, a list of tags that will be transformed. If
  89. * omitted, all supported tags are transformed.
  90. *
  91. * @return string
  92. * The transformed string.
  93. */
  94. public static function htmlToText($string, $allowed_tags = NULL) {
  95. // Cache list of supported tags.
  96. if (empty(static::$supportedTags)) {
  97. static::$supportedTags = ['a', 'em', 'i', 'strong', 'b', 'br', 'p',
  98. 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3',
  99. 'h4', 'h5', 'h6', 'hr',
  100. ];
  101. }
  102. // Make sure only supported tags are kept.
  103. $allowed_tags = isset($allowed_tags) ? array_intersect(static::$supportedTags, $allowed_tags) : static::$supportedTags;
  104. // Make sure tags, entities and attributes are well-formed and properly
  105. // nested.
  106. $string = Html::normalize(Xss::filter($string, $allowed_tags));
  107. // Apply inline styles.
  108. $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
  109. $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
  110. // Replace inline <a> tags with the text of link and a footnote.
  111. // 'See <a href="https://www.drupal.org">the Drupal site</a>' becomes
  112. // 'See the Drupal site [1]' with the URL included as a footnote.
  113. static::htmlToMailUrls(NULL, TRUE);
  114. $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  115. $string = preg_replace_callback($pattern, 'static::htmlToMailUrls', $string);
  116. $urls = static::htmlToMailUrls();
  117. $footnotes = '';
  118. if (count($urls)) {
  119. $footnotes .= "\n";
  120. for ($i = 0, $max = count($urls); $i < $max; $i++) {
  121. $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
  122. }
  123. }
  124. // Split tags from text.
  125. $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  126. // Note: PHP ensures the array consists of alternating delimiters and
  127. // literals and begins and ends with a literal (inserting $null as
  128. // required).
  129. // Odd/even counter (tag or no tag).
  130. $tag = FALSE;
  131. $output = '';
  132. // All current indentation string chunks.
  133. $indent = [];
  134. // Array of counters for opened lists.
  135. $lists = [];
  136. foreach ($split as $value) {
  137. // Holds a string ready to be formatted and output.
  138. $chunk = NULL;
  139. // Process HTML tags (but don't output any literally).
  140. if ($tag) {
  141. [$tagname] = explode(' ', strtolower($value), 2);
  142. switch ($tagname) {
  143. // List counters.
  144. case 'ul':
  145. array_unshift($lists, '*');
  146. break;
  147. case 'ol':
  148. array_unshift($lists, 1);
  149. break;
  150. case '/ul':
  151. case '/ol':
  152. array_shift($lists);
  153. // Ensure blank new-line.
  154. $chunk = '';
  155. break;
  156. // Quotation/list markers, non-fancy headers.
  157. case 'blockquote':
  158. // Format=flowed indentation cannot be mixed with lists.
  159. $indent[] = count($lists) ? ' "' : '>';
  160. break;
  161. case 'li':
  162. $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
  163. break;
  164. case 'dd':
  165. $indent[] = ' ';
  166. break;
  167. case 'h3':
  168. $indent[] = '.... ';
  169. break;
  170. case 'h4':
  171. $indent[] = '.. ';
  172. break;
  173. case '/blockquote':
  174. if (count($lists)) {
  175. // Append closing quote for inline quotes (immediately).
  176. $output = rtrim($output, "> \n") . "\"\n";
  177. // Ensure blank new-line.
  178. $chunk = '';
  179. }
  180. // Intentional fall-through to the processing for '/li' and '/dd'.
  181. case '/li':
  182. case '/dd':
  183. array_pop($indent);
  184. break;
  185. case '/h3':
  186. case '/h4':
  187. array_pop($indent);
  188. // Intentional fall-through to the processing for '/h5' and '/h6'.
  189. case '/h5':
  190. case '/h6':
  191. // Ensure blank new-line.
  192. $chunk = '';
  193. break;
  194. // Fancy headers.
  195. case 'h1':
  196. $indent[] = '======== ';
  197. break;
  198. case 'h2':
  199. $indent[] = '-------- ';
  200. break;
  201. case '/h1':
  202. case '/h2':
  203. // Pad the line with dashes.
  204. $output = static::htmlToTextPad($output, ($tagname == '/h1') ? '=' : '-', ' ');
  205. array_pop($indent);
  206. // Ensure blank new-line.
  207. $chunk = '';
  208. break;
  209. // Horizontal rulers.
  210. case 'hr':
  211. // Insert immediately.
  212. $output .= static::wrapMail('', implode('', $indent)) . "\n";
  213. $output = static::htmlToTextPad($output, '-');
  214. break;
  215. // Paragraphs and definition lists.
  216. case '/p':
  217. case '/dl':
  218. // Ensure blank new-line.
  219. $chunk = '';
  220. break;
  221. }
  222. }
  223. // Process blocks of text.
  224. else {
  225. // Convert inline HTML text to plain text; not removing line-breaks or
  226. // white-space, since that breaks newlines when sanitizing plain-text.
  227. $value = trim(Html::decodeEntities($value));
  228. if (mb_strlen($value)) {
  229. $chunk = $value;
  230. }
  231. }
  232. // See if there is something waiting to be output.
  233. if (isset($chunk)) {
  234. $line_endings = Settings::get('mail_line_endings', PHP_EOL);
  235. // Format it and apply the current indentation.
  236. $output .= static::wrapMail($chunk, implode('', $indent)) . $line_endings;
  237. // Remove non-quotation markers from indentation.
  238. $indent = array_map('\Drupal\Core\Mail\MailFormatHelper::htmlToTextClean', $indent);
  239. }
  240. $tag = !$tag;
  241. }
  242. return $output . $footnotes;
  243. }
  244. /**
  245. * Wraps words on a single line.
  246. *
  247. * Callback for array_walk() within
  248. * \Drupal\Core\Mail\MailFormatHelper::wrapMail().
  249. *
  250. * Note that we are skipping MIME content header lines, because attached
  251. * files, especially applications, could have long MIME types or long
  252. * filenames which result in line length longer than the 77 characters limit
  253. * and wrapping that line will break the email format. For instance, the
  254. * attached file hello_drupal.docx will produce the following Content-Type:
  255. * @code
  256. * Content-Type:
  257. * application/vnd.openxmlformats-officedocument.wordprocessingml.document;
  258. * name="hello_drupal.docx"
  259. * @endcode
  260. */
  261. protected static function wrapMailLine(&$line, $key, $values) {
  262. $line_is_mime_header = FALSE;
  263. $mime_headers = [
  264. 'Content-Type',
  265. 'Content-Transfer-Encoding',
  266. 'Content-Disposition',
  267. 'Content-Description',
  268. ];
  269. // Do not break MIME headers which could be longer than 77 characters.
  270. foreach ($mime_headers as $header) {
  271. if (strpos($line, $header . ': ') === 0) {
  272. $line_is_mime_header = TRUE;
  273. break;
  274. }
  275. }
  276. if (!$line_is_mime_header) {
  277. // Use soft-breaks only for purely quoted or unindented text.
  278. $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
  279. }
  280. // Break really long words at the maximum width allowed.
  281. $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
  282. }
  283. /**
  284. * Keeps track of URLs and replaces them with placeholder tokens.
  285. *
  286. * Callback for preg_replace_callback() within
  287. * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
  288. */
  289. protected static function htmlToMailUrls($match = NULL, $reset = FALSE) {
  290. // @todo Use request context instead.
  291. global $base_url, $base_path;
  292. if ($reset) {
  293. // Reset internal URL list.
  294. static::$urls = [];
  295. }
  296. else {
  297. if (empty(static::$regexp)) {
  298. static::$regexp = '@^' . preg_quote($base_path, '@') . '@';
  299. }
  300. if ($match) {
  301. [, , $url, $label] = $match;
  302. // Ensure all URLs are absolute.
  303. static::$urls[] = strpos($url, '://') ? $url : preg_replace(static::$regexp, $base_url . '/', $url);
  304. return $label . ' [' . count(static::$urls) . ']';
  305. }
  306. }
  307. return static::$urls;
  308. }
  309. /**
  310. * Replaces non-quotation markers from a piece of indentation with spaces.
  311. *
  312. * Callback for array_map() within
  313. * \Drupal\Core\Mail\MailFormatHelper::htmlToText().
  314. */
  315. protected static function htmlToTextClean($indent) {
  316. return preg_replace('/[^>]/', ' ', $indent);
  317. }
  318. /**
  319. * Pads the last line with the given character.
  320. *
  321. * @param string $text
  322. * The text to pad.
  323. * @param string $pad
  324. * The character to pad the end of the string with.
  325. * @param string $prefix
  326. * (optional) Prefix to add to the string.
  327. *
  328. * @return string
  329. * The padded string.
  330. *
  331. * @see \Drupal\Core\Mail\MailFormatHelper::htmlToText()
  332. */
  333. protected static function htmlToTextPad($text, $pad, $prefix = '') {
  334. // Remove last line break.
  335. $text = substr($text, 0, -1);
  336. // Calculate needed padding space and add it.
  337. if (($p = strrpos($text, "\n")) === FALSE) {
  338. $p = -1;
  339. }
  340. $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
  341. // Add prefix and padding, and restore linebreak.
  342. return $text . $prefix . str_repeat($pad, $n) . "\n";
  343. }
  344. }