mail.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622
  1. <?php
  2. /**
  3. * @file
  4. * API functions for processing and sending e-mail.
  5. */
  6. /**
  7. * Auto-detect appropriate line endings for e-mails.
  8. *
  9. * $conf['mail_line_endings'] will override this setting.
  10. */
  11. define('MAIL_LINE_ENDINGS', isset($_SERVER['WINDIR']) || strpos($_SERVER['SERVER_SOFTWARE'], 'Win32') !== FALSE ? "\r\n" : "\n");
  12. /**
  13. * Composes and optionally sends an e-mail message.
  14. *
  15. * Sending an e-mail works with defining an e-mail template (subject, text
  16. * and possibly e-mail headers) and the replacement values to use in the
  17. * appropriate places in the template. Processed e-mail templates are
  18. * requested from hook_mail() from the module sending the e-mail. Any module
  19. * can modify the composed e-mail message array using hook_mail_alter().
  20. * Finally drupal_mail_system()->mail() sends the e-mail, which can
  21. * be reused if the exact same composed e-mail is to be sent to multiple
  22. * recipients.
  23. *
  24. * Finding out what language to send the e-mail with needs some consideration.
  25. * If you send e-mail to a user, her preferred language should be fine, so
  26. * use user_preferred_language(). If you send email based on form values
  27. * filled on the page, there are two additional choices if you are not
  28. * sending the e-mail to a user on the site. You can either use the language
  29. * used to generate the page ($language global variable) or the site default
  30. * language. See language_default(). The former is good if sending e-mail to
  31. * the person filling the form, the later is good if you send e-mail to an
  32. * address previously set up (like contact addresses in a contact form).
  33. *
  34. * Taking care of always using the proper language is even more important
  35. * when sending e-mails in a row to multiple users. Hook_mail() abstracts
  36. * whether the mail text comes from an administrator setting or is
  37. * static in the source code. It should also deal with common mail tokens,
  38. * only receiving $params which are unique to the actual e-mail at hand.
  39. *
  40. * An example:
  41. *
  42. * @code
  43. * function example_notify($accounts) {
  44. * foreach ($accounts as $account) {
  45. * $params['account'] = $account;
  46. * // example_mail() will be called based on the first drupal_mail() parameter.
  47. * drupal_mail('example', 'notice', $account->mail, user_preferred_language($account), $params);
  48. * }
  49. * }
  50. *
  51. * function example_mail($key, &$message, $params) {
  52. * $data['user'] = $params['account'];
  53. * $options['language'] = $message['language'];
  54. * user_mail_tokens($variables, $data, $options);
  55. * switch($key) {
  56. * case 'notice':
  57. * // If the recipient can receive such notices by instant-message, do
  58. * // not send by email.
  59. * if (example_im_send($key, $message, $params)) {
  60. * $message['send'] = FALSE;
  61. * break;
  62. * }
  63. * $langcode = $message['language']->language;
  64. * $message['subject'] = t('Notification from !site', $variables, array('langcode' => $langcode));
  65. * $message['body'][] = t("Dear !username\n\nThere is new content available on the site.", $variables, array('langcode' => $langcode));
  66. * break;
  67. * }
  68. * }
  69. * @endcode
  70. *
  71. * Another example, which uses drupal_mail() to format a message for sending
  72. * later:
  73. *
  74. * @code
  75. * $params = array('current_conditions' => $data);
  76. * $to = 'user@example.com';
  77. * $message = drupal_mail('example', 'notice', $to, $language, $params, FALSE);
  78. * // Only add to the spool if sending was not canceled.
  79. * if ($message['send']) {
  80. * example_spool_message($message);
  81. * }
  82. * @endcode
  83. *
  84. * @param $module
  85. * A module name to invoke hook_mail() on. The {$module}_mail() hook will be
  86. * called to complete the $message structure which will already contain common
  87. * defaults.
  88. * @param $key
  89. * A key to identify the e-mail sent. The final e-mail id for e-mail altering
  90. * will be {$module}_{$key}.
  91. * @param $to
  92. * The e-mail address or addresses where the message will be sent to. The
  93. * formatting of this string will be validated with the
  94. * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
  95. * Some examples are:
  96. * - user@example.com
  97. * - user@example.com, anotheruser@example.com
  98. * - User <user@example.com>
  99. * - User <user@example.com>, Another User <anotheruser@example.com>
  100. * @param $language
  101. * Language object to use to compose the e-mail.
  102. * @param $params
  103. * Optional parameters to build the e-mail.
  104. * @param $from
  105. * Sets From to this value, if given.
  106. * @param $send
  107. * If TRUE, drupal_mail() will call drupal_mail_system()->mail() to deliver
  108. * the message, and store the result in $message['result']. Modules
  109. * implementing hook_mail_alter() may cancel sending by setting
  110. * $message['send'] to FALSE.
  111. *
  112. * @return
  113. * The $message array structure containing all details of the
  114. * message. If already sent ($send = TRUE), then the 'result' element
  115. * will contain the success indicator of the e-mail, failure being already
  116. * written to the watchdog. (Success means nothing more than the message being
  117. * accepted at php-level, which still doesn't guarantee it to be delivered.)
  118. */
  119. function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
  120. $default_from = variable_get('site_mail', ini_get('sendmail_from'));
  121. // Bundle up the variables into a structured array for altering.
  122. $message = array(
  123. 'id' => $module . '_' . $key,
  124. 'module' => $module,
  125. 'key' => $key,
  126. 'to' => $to,
  127. 'from' => isset($from) ? $from : $default_from,
  128. 'language' => $language,
  129. 'params' => $params,
  130. 'send' => TRUE,
  131. 'subject' => '',
  132. 'body' => array()
  133. );
  134. // Build the default headers
  135. $headers = array(
  136. 'MIME-Version' => '1.0',
  137. 'Content-Type' => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
  138. 'Content-Transfer-Encoding' => '8Bit',
  139. 'X-Mailer' => 'Drupal'
  140. );
  141. if ($default_from) {
  142. // To prevent e-mail from looking like spam, the addresses in the Sender and
  143. // Return-Path headers should have a domain authorized to use the originating
  144. // SMTP server.
  145. $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $default_from;
  146. }
  147. if ($from) {
  148. $headers['From'] = $from;
  149. }
  150. $message['headers'] = $headers;
  151. // Build the e-mail (get subject and body, allow additional headers) by
  152. // invoking hook_mail() on this module. We cannot use module_invoke() as
  153. // we need to have $message by reference in hook_mail().
  154. if (function_exists($function = $module . '_mail')) {
  155. $function($key, $message, $params);
  156. }
  157. // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
  158. drupal_alter('mail', $message);
  159. // Retrieve the responsible implementation for this message.
  160. $system = drupal_mail_system($module, $key);
  161. // Format the message body.
  162. $message = $system->format($message);
  163. // Optionally send e-mail.
  164. if ($send) {
  165. // The original caller requested sending. Sending was canceled by one or
  166. // more hook_mail_alter() implementations. We set 'result' to NULL, because
  167. // FALSE indicates an error in sending.
  168. if (empty($message['send'])) {
  169. $message['result'] = NULL;
  170. }
  171. // Sending was originally requested and was not canceled.
  172. else {
  173. $message['result'] = $system->mail($message);
  174. // Log errors.
  175. if (!$message['result']) {
  176. watchdog('mail', 'Error sending e-mail (from %from to %to).', array('%from' => $message['from'], '%to' => $message['to']), WATCHDOG_ERROR);
  177. drupal_set_message(t('Unable to send e-mail. Contact the site administrator if the problem persists.'), 'error');
  178. }
  179. }
  180. }
  181. return $message;
  182. }
  183. /**
  184. * Returns an object that implements the MailSystemInterface interface.
  185. *
  186. * Allows for one or more custom mail backends to format and send mail messages
  187. * composed using drupal_mail().
  188. *
  189. * An implementation needs to implement the following methods:
  190. * - format: Allows to preprocess, format, and postprocess a mail
  191. * message before it is passed to the sending system. By default, all messages
  192. * may contain HTML and are converted to plain-text by the DefaultMailSystem
  193. * implementation. For example, an alternative implementation could override
  194. * the default implementation and additionally sanitize the HTML for usage in
  195. * a MIME-encoded e-mail, but still invoking the DefaultMailSystem
  196. * implementation to generate an alternate plain-text version for sending.
  197. * - mail: Sends a message through a custom mail sending engine.
  198. * By default, all messages are sent via PHP's mail() function by the
  199. * DefaultMailSystem implementation.
  200. *
  201. * The selection of a particular implementation is controlled via the variable
  202. * 'mail_system', which is a keyed array. The default implementation
  203. * is the class whose name is the value of 'default-system' key. A more specific
  204. * match first to key and then to module will be used in preference to the
  205. * default. To specify a different class for all mail sent by one module, set
  206. * the class name as the value for the key corresponding to the module name. To
  207. * specify a class for a particular message sent by one module, set the class
  208. * name as the value for the array key that is the message id, which is
  209. * "${module}_${key}".
  210. *
  211. * For example to debug all mail sent by the user module by logging it to a
  212. * file, you might set the variable as something like:
  213. *
  214. * @code
  215. * array(
  216. * 'default-system' => 'DefaultMailSystem',
  217. * 'user' => 'DevelMailLog',
  218. * );
  219. * @endcode
  220. *
  221. * Finally, a different system can be specified for a specific e-mail ID (see
  222. * the $key param), such as one of the keys used by the contact module:
  223. *
  224. * @code
  225. * array(
  226. * 'default-system' => 'DefaultMailSystem',
  227. * 'user' => 'DevelMailLog',
  228. * 'contact_page_autoreply' => 'DrupalDevNullMailSend',
  229. * );
  230. * @endcode
  231. *
  232. * Other possible uses for system include a mail-sending class that actually
  233. * sends (or duplicates) each message to SMS, Twitter, instant message, etc, or
  234. * a class that queues up a large number of messages for more efficient bulk
  235. * sending or for sending via a remote gateway so as to reduce the load
  236. * on the local server.
  237. *
  238. * @param $module
  239. * The module name which was used by drupal_mail() to invoke hook_mail().
  240. * @param $key
  241. * A key to identify the e-mail sent. The final e-mail ID for the e-mail
  242. * alter hook in drupal_mail() would have been {$module}_{$key}.
  243. *
  244. * @return MailSystemInterface
  245. */
  246. function drupal_mail_system($module, $key) {
  247. $instances = &drupal_static(__FUNCTION__, array());
  248. $id = $module . '_' . $key;
  249. $configuration = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
  250. // Look for overrides for the default class, starting from the most specific
  251. // id, and falling back to the module name.
  252. if (isset($configuration[$id])) {
  253. $class = $configuration[$id];
  254. }
  255. elseif (isset($configuration[$module])) {
  256. $class = $configuration[$module];
  257. }
  258. else {
  259. $class = $configuration['default-system'];
  260. }
  261. if (empty($instances[$class])) {
  262. $interfaces = class_implements($class);
  263. if (isset($interfaces['MailSystemInterface'])) {
  264. $instances[$class] = new $class();
  265. }
  266. else {
  267. throw new Exception(t('Class %class does not implement interface %interface', array('%class' => $class, '%interface' => 'MailSystemInterface')));
  268. }
  269. }
  270. return $instances[$class];
  271. }
  272. /**
  273. * An interface for pluggable mail back-ends.
  274. */
  275. interface MailSystemInterface {
  276. /**
  277. * Format a message composed by drupal_mail() prior sending.
  278. *
  279. * @param $message
  280. * A message array, as described in hook_mail_alter().
  281. *
  282. * @return
  283. * The formatted $message.
  284. */
  285. public function format(array $message);
  286. /**
  287. * Send a message composed by drupal_mail().
  288. *
  289. * @param $message
  290. * Message array with at least the following elements:
  291. * - id: A unique identifier of the e-mail type. Examples: 'contact_user_copy',
  292. * 'user_password_reset'.
  293. * - to: The mail address or addresses where the message will be sent to.
  294. * The formatting of this string will be validated with the
  295. * @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
  296. * Some examples are:
  297. * - user@example.com
  298. * - user@example.com, anotheruser@example.com
  299. * - User <user@example.com>
  300. * - User <user@example.com>, Another User <anotheruser@example.com>
  301. * - subject: Subject of the e-mail to be sent. This must not contain any
  302. * newline characters, or the mail may not be sent properly.
  303. * - body: Message to be sent. Accepts both CRLF and LF line-endings.
  304. * E-mail bodies must be wrapped. You can use drupal_wrap_mail() for
  305. * smart plain text wrapping.
  306. * - headers: Associative array containing all additional mail headers not
  307. * defined by one of the other parameters. PHP's mail() looks for Cc and
  308. * Bcc headers and sends the mail to addresses in these headers too.
  309. *
  310. * @return
  311. * TRUE if the mail was successfully accepted for delivery, otherwise FALSE.
  312. */
  313. public function mail(array $message);
  314. }
  315. /**
  316. * Performs format=flowed soft wrapping for mail (RFC 3676).
  317. *
  318. * We use delsp=yes wrapping, but only break non-spaced languages when
  319. * absolutely necessary to avoid compatibility issues.
  320. *
  321. * We deliberately use LF rather than CRLF, see drupal_mail().
  322. *
  323. * @param $text
  324. * The plain text to process.
  325. * @param $indent (optional)
  326. * A string to indent the text with. Only '>' characters are repeated on
  327. * subsequent wrapped lines. Others are replaced by spaces.
  328. *
  329. * @return
  330. * The content of the email as a string with formatting applied.
  331. */
  332. function drupal_wrap_mail($text, $indent = '') {
  333. // Convert CRLF into LF.
  334. $text = str_replace("\r", '', $text);
  335. // See if soft-wrapping is allowed.
  336. $clean_indent = _drupal_html_to_text_clean($indent);
  337. $soft = strpos($clean_indent, ' ') === FALSE;
  338. // Check if the string has line breaks.
  339. if (strpos($text, "\n") !== FALSE) {
  340. // Remove trailing spaces to make existing breaks hard.
  341. $text = preg_replace('/ +\n/m', "\n", $text);
  342. // Wrap each line at the needed width.
  343. $lines = explode("\n", $text);
  344. array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent)));
  345. $text = implode("\n", $lines);
  346. }
  347. else {
  348. // Wrap this line.
  349. _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => strlen($indent)));
  350. }
  351. // Empty lines with nothing but spaces.
  352. $text = preg_replace('/^ +\n/m', "\n", $text);
  353. // Space-stuff special lines.
  354. $text = preg_replace('/^(>| |From)/m', ' $1', $text);
  355. // Apply indentation. We only include non-'>' indentation on the first line.
  356. $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
  357. return $text;
  358. }
  359. /**
  360. * Transforms an HTML string into plain text, preserving its structure.
  361. *
  362. * The output will be suitable for use as 'format=flowed; delsp=yes' text
  363. * (RFC 3676) and can be passed directly to drupal_mail() for sending.
  364. *
  365. * We deliberately use LF rather than CRLF, see drupal_mail().
  366. *
  367. * This function provides suitable alternatives for the following tags:
  368. * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
  369. * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
  370. *
  371. * @param $string
  372. * The string to be transformed.
  373. * @param $allowed_tags (optional)
  374. * If supplied, a list of tags that will be transformed. If omitted, all
  375. * all supported tags are transformed.
  376. *
  377. * @return
  378. * The transformed string.
  379. */
  380. function drupal_html_to_text($string, $allowed_tags = NULL) {
  381. // Cache list of supported tags.
  382. static $supported_tags;
  383. if (empty($supported_tags)) {
  384. $supported_tags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p', 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr');
  385. }
  386. // Make sure only supported tags are kept.
  387. $allowed_tags = isset($allowed_tags) ? array_intersect($supported_tags, $allowed_tags) : $supported_tags;
  388. // Make sure tags, entities and attributes are well-formed and properly nested.
  389. $string = _filter_htmlcorrector(filter_xss($string, $allowed_tags));
  390. // Apply inline styles.
  391. $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
  392. $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
  393. // Replace inline <a> tags with the text of link and a footnote.
  394. // 'See <a href="http://drupal.org">the Drupal site</a>' becomes
  395. // 'See the Drupal site [1]' with the URL included as a footnote.
  396. _drupal_html_to_mail_urls(NULL, TRUE);
  397. $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  398. $string = preg_replace_callback($pattern, '_drupal_html_to_mail_urls', $string);
  399. $urls = _drupal_html_to_mail_urls();
  400. $footnotes = '';
  401. if (count($urls)) {
  402. $footnotes .= "\n";
  403. for ($i = 0, $max = count($urls); $i < $max; $i++) {
  404. $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
  405. }
  406. }
  407. // Split tags from text.
  408. $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  409. // Note: PHP ensures the array consists of alternating delimiters and literals
  410. // and begins and ends with a literal (inserting $null as required).
  411. $tag = FALSE; // Odd/even counter (tag or no tag)
  412. $casing = NULL; // Case conversion function
  413. $output = '';
  414. $indent = array(); // All current indentation string chunks
  415. $lists = array(); // Array of counters for opened lists
  416. foreach ($split as $value) {
  417. $chunk = NULL; // Holds a string ready to be formatted and output.
  418. // Process HTML tags (but don't output any literally).
  419. if ($tag) {
  420. list($tagname) = explode(' ', strtolower($value), 2);
  421. switch ($tagname) {
  422. // List counters
  423. case 'ul':
  424. array_unshift($lists, '*');
  425. break;
  426. case 'ol':
  427. array_unshift($lists, 1);
  428. break;
  429. case '/ul':
  430. case '/ol':
  431. array_shift($lists);
  432. $chunk = ''; // Ensure blank new-line.
  433. break;
  434. // Quotation/list markers, non-fancy headers
  435. case 'blockquote':
  436. // Format=flowed indentation cannot be mixed with lists.
  437. $indent[] = count($lists) ? ' "' : '>';
  438. break;
  439. case 'li':
  440. $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
  441. break;
  442. case 'dd':
  443. $indent[] = ' ';
  444. break;
  445. case 'h3':
  446. $indent[] = '.... ';
  447. break;
  448. case 'h4':
  449. $indent[] = '.. ';
  450. break;
  451. case '/blockquote':
  452. if (count($lists)) {
  453. // Append closing quote for inline quotes (immediately).
  454. $output = rtrim($output, "> \n") . "\"\n";
  455. $chunk = ''; // Ensure blank new-line.
  456. }
  457. // Fall-through
  458. case '/li':
  459. case '/dd':
  460. array_pop($indent);
  461. break;
  462. case '/h3':
  463. case '/h4':
  464. array_pop($indent);
  465. case '/h5':
  466. case '/h6':
  467. $chunk = ''; // Ensure blank new-line.
  468. break;
  469. // Fancy headers
  470. case 'h1':
  471. $indent[] = '======== ';
  472. $casing = 'drupal_strtoupper';
  473. break;
  474. case 'h2':
  475. $indent[] = '-------- ';
  476. $casing = 'drupal_strtoupper';
  477. break;
  478. case '/h1':
  479. case '/h2':
  480. $casing = NULL;
  481. // Pad the line with dashes.
  482. $output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' ');
  483. array_pop($indent);
  484. $chunk = ''; // Ensure blank new-line.
  485. break;
  486. // Horizontal rulers
  487. case 'hr':
  488. // Insert immediately.
  489. $output .= drupal_wrap_mail('', implode('', $indent)) . "\n";
  490. $output = _drupal_html_to_text_pad($output, '-');
  491. break;
  492. // Paragraphs and definition lists
  493. case '/p':
  494. case '/dl':
  495. $chunk = ''; // Ensure blank new-line.
  496. break;
  497. }
  498. }
  499. // Process blocks of text.
  500. else {
  501. // Convert inline HTML text to plain text; not removing line-breaks or
  502. // white-space, since that breaks newlines when sanitizing plain-text.
  503. $value = trim(decode_entities($value));
  504. if (drupal_strlen($value)) {
  505. $chunk = $value;
  506. }
  507. }
  508. // See if there is something waiting to be output.
  509. if (isset($chunk)) {
  510. // Apply any necessary case conversion.
  511. if (isset($casing)) {
  512. $chunk = $casing($chunk);
  513. }
  514. // Format it and apply the current indentation.
  515. $output .= drupal_wrap_mail($chunk, implode('', $indent)) . MAIL_LINE_ENDINGS;
  516. // Remove non-quotation markers from indentation.
  517. $indent = array_map('_drupal_html_to_text_clean', $indent);
  518. }
  519. $tag = !$tag;
  520. }
  521. return $output . $footnotes;
  522. }
  523. /**
  524. * Wraps words on a single line.
  525. *
  526. * Callback for array_walk() winthin drupal_wrap_mail().
  527. */
  528. function _drupal_wrap_mail_line(&$line, $key, $values) {
  529. // Use soft-breaks only for purely quoted or unindented text.
  530. $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
  531. // Break really long words at the maximum width allowed.
  532. $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n");
  533. }
  534. /**
  535. * Keeps track of URLs and replaces them with placeholder tokens.
  536. *
  537. * Callback for preg_replace_callback() within drupal_html_to_text().
  538. */
  539. function _drupal_html_to_mail_urls($match = NULL, $reset = FALSE) {
  540. global $base_url, $base_path;
  541. static $urls = array(), $regexp;
  542. if ($reset) {
  543. // Reset internal URL list.
  544. $urls = array();
  545. }
  546. else {
  547. if (empty($regexp)) {
  548. $regexp = '@^' . preg_quote($base_path, '@') . '@';
  549. }
  550. if ($match) {
  551. list(, , $url, $label) = $match;
  552. // Ensure all URLs are absolute.
  553. $urls[] = strpos($url, '://') ? $url : preg_replace($regexp, $base_url . '/', $url);
  554. return $label . ' [' . count($urls) . ']';
  555. }
  556. }
  557. return $urls;
  558. }
  559. /**
  560. * Replaces non-quotation markers from a given piece of indentation with spaces.
  561. *
  562. * Callback for array_map() within drupal_html_to_text().
  563. */
  564. function _drupal_html_to_text_clean($indent) {
  565. return preg_replace('/[^>]/', ' ', $indent);
  566. }
  567. /**
  568. * Pads the last line with the given character.
  569. *
  570. * @see drupal_html_to_text()
  571. */
  572. function _drupal_html_to_text_pad($text, $pad, $prefix = '') {
  573. // Remove last line break.
  574. $text = substr($text, 0, -1);
  575. // Calculate needed padding space and add it.
  576. if (($p = strrpos($text, "\n")) === FALSE) {
  577. $p = -1;
  578. }
  579. $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
  580. // Add prefix and padding, and restore linebreak.
  581. return $text . $prefix . str_repeat($pad, $n) . "\n";
  582. }