mail.inc 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623
  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 string $text
  324. * The plain text to process.
  325. * @param string $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 string
  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, but leave signature
  341. // marker untouched (RFC 3676, Section 4.3).
  342. $text = preg_replace('/(?(?<!^--) +\n| +\n)/m', "\n", $text);
  343. // Wrap each line at the needed width.
  344. $lines = explode("\n", $text);
  345. array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent)));
  346. $text = implode("\n", $lines);
  347. }
  348. else {
  349. // Wrap this line.
  350. _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => strlen($indent)));
  351. }
  352. // Empty lines with nothing but spaces.
  353. $text = preg_replace('/^ +\n/m', "\n", $text);
  354. // Space-stuff special lines.
  355. $text = preg_replace('/^(>| |From)/m', ' $1', $text);
  356. // Apply indentation. We only include non-'>' indentation on the first line.
  357. $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
  358. return $text;
  359. }
  360. /**
  361. * Transforms an HTML string into plain text, preserving its structure.
  362. *
  363. * The output will be suitable for use as 'format=flowed; delsp=yes' text
  364. * (RFC 3676) and can be passed directly to drupal_mail() for sending.
  365. *
  366. * We deliberately use LF rather than CRLF, see drupal_mail().
  367. *
  368. * This function provides suitable alternatives for the following tags:
  369. * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
  370. * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
  371. *
  372. * @param $string
  373. * The string to be transformed.
  374. * @param $allowed_tags (optional)
  375. * If supplied, a list of tags that will be transformed. If omitted, all
  376. * all supported tags are transformed.
  377. *
  378. * @return
  379. * The transformed string.
  380. */
  381. function drupal_html_to_text($string, $allowed_tags = NULL) {
  382. // Cache list of supported tags.
  383. static $supported_tags;
  384. if (empty($supported_tags)) {
  385. $supported_tags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p', 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr');
  386. }
  387. // Make sure only supported tags are kept.
  388. $allowed_tags = isset($allowed_tags) ? array_intersect($supported_tags, $allowed_tags) : $supported_tags;
  389. // Make sure tags, entities and attributes are well-formed and properly nested.
  390. $string = _filter_htmlcorrector(filter_xss($string, $allowed_tags));
  391. // Apply inline styles.
  392. $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
  393. $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
  394. // Replace inline <a> tags with the text of link and a footnote.
  395. // 'See <a href="http://drupal.org">the Drupal site</a>' becomes
  396. // 'See the Drupal site [1]' with the URL included as a footnote.
  397. _drupal_html_to_mail_urls(NULL, TRUE);
  398. $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
  399. $string = preg_replace_callback($pattern, '_drupal_html_to_mail_urls', $string);
  400. $urls = _drupal_html_to_mail_urls();
  401. $footnotes = '';
  402. if (count($urls)) {
  403. $footnotes .= "\n";
  404. for ($i = 0, $max = count($urls); $i < $max; $i++) {
  405. $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
  406. }
  407. }
  408. // Split tags from text.
  409. $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
  410. // Note: PHP ensures the array consists of alternating delimiters and literals
  411. // and begins and ends with a literal (inserting $null as required).
  412. $tag = FALSE; // Odd/even counter (tag or no tag)
  413. $casing = NULL; // Case conversion function
  414. $output = '';
  415. $indent = array(); // All current indentation string chunks
  416. $lists = array(); // Array of counters for opened lists
  417. foreach ($split as $value) {
  418. $chunk = NULL; // Holds a string ready to be formatted and output.
  419. // Process HTML tags (but don't output any literally).
  420. if ($tag) {
  421. list($tagname) = explode(' ', strtolower($value), 2);
  422. switch ($tagname) {
  423. // List counters
  424. case 'ul':
  425. array_unshift($lists, '*');
  426. break;
  427. case 'ol':
  428. array_unshift($lists, 1);
  429. break;
  430. case '/ul':
  431. case '/ol':
  432. array_shift($lists);
  433. $chunk = ''; // Ensure blank new-line.
  434. break;
  435. // Quotation/list markers, non-fancy headers
  436. case 'blockquote':
  437. // Format=flowed indentation cannot be mixed with lists.
  438. $indent[] = count($lists) ? ' "' : '>';
  439. break;
  440. case 'li':
  441. $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
  442. break;
  443. case 'dd':
  444. $indent[] = ' ';
  445. break;
  446. case 'h3':
  447. $indent[] = '.... ';
  448. break;
  449. case 'h4':
  450. $indent[] = '.. ';
  451. break;
  452. case '/blockquote':
  453. if (count($lists)) {
  454. // Append closing quote for inline quotes (immediately).
  455. $output = rtrim($output, "> \n") . "\"\n";
  456. $chunk = ''; // Ensure blank new-line.
  457. }
  458. // Fall-through
  459. case '/li':
  460. case '/dd':
  461. array_pop($indent);
  462. break;
  463. case '/h3':
  464. case '/h4':
  465. array_pop($indent);
  466. case '/h5':
  467. case '/h6':
  468. $chunk = ''; // Ensure blank new-line.
  469. break;
  470. // Fancy headers
  471. case 'h1':
  472. $indent[] = '======== ';
  473. $casing = 'drupal_strtoupper';
  474. break;
  475. case 'h2':
  476. $indent[] = '-------- ';
  477. $casing = 'drupal_strtoupper';
  478. break;
  479. case '/h1':
  480. case '/h2':
  481. $casing = NULL;
  482. // Pad the line with dashes.
  483. $output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' ');
  484. array_pop($indent);
  485. $chunk = ''; // Ensure blank new-line.
  486. break;
  487. // Horizontal rulers
  488. case 'hr':
  489. // Insert immediately.
  490. $output .= drupal_wrap_mail('', implode('', $indent)) . "\n";
  491. $output = _drupal_html_to_text_pad($output, '-');
  492. break;
  493. // Paragraphs and definition lists
  494. case '/p':
  495. case '/dl':
  496. $chunk = ''; // Ensure blank new-line.
  497. break;
  498. }
  499. }
  500. // Process blocks of text.
  501. else {
  502. // Convert inline HTML text to plain text; not removing line-breaks or
  503. // white-space, since that breaks newlines when sanitizing plain-text.
  504. $value = trim(decode_entities($value));
  505. if (drupal_strlen($value)) {
  506. $chunk = $value;
  507. }
  508. }
  509. // See if there is something waiting to be output.
  510. if (isset($chunk)) {
  511. // Apply any necessary case conversion.
  512. if (isset($casing)) {
  513. $chunk = $casing($chunk);
  514. }
  515. // Format it and apply the current indentation.
  516. $output .= drupal_wrap_mail($chunk, implode('', $indent)) . MAIL_LINE_ENDINGS;
  517. // Remove non-quotation markers from indentation.
  518. $indent = array_map('_drupal_html_to_text_clean', $indent);
  519. }
  520. $tag = !$tag;
  521. }
  522. return $output . $footnotes;
  523. }
  524. /**
  525. * Wraps words on a single line.
  526. *
  527. * Callback for array_walk() winthin drupal_wrap_mail().
  528. */
  529. function _drupal_wrap_mail_line(&$line, $key, $values) {
  530. // Use soft-breaks only for purely quoted or unindented text.
  531. $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
  532. // Break really long words at the maximum width allowed.
  533. $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n");
  534. }
  535. /**
  536. * Keeps track of URLs and replaces them with placeholder tokens.
  537. *
  538. * Callback for preg_replace_callback() within drupal_html_to_text().
  539. */
  540. function _drupal_html_to_mail_urls($match = NULL, $reset = FALSE) {
  541. global $base_url, $base_path;
  542. static $urls = array(), $regexp;
  543. if ($reset) {
  544. // Reset internal URL list.
  545. $urls = array();
  546. }
  547. else {
  548. if (empty($regexp)) {
  549. $regexp = '@^' . preg_quote($base_path, '@') . '@';
  550. }
  551. if ($match) {
  552. list(, , $url, $label) = $match;
  553. // Ensure all URLs are absolute.
  554. $urls[] = strpos($url, '://') ? $url : preg_replace($regexp, $base_url . '/', $url);
  555. return $label . ' [' . count($urls) . ']';
  556. }
  557. }
  558. return $urls;
  559. }
  560. /**
  561. * Replaces non-quotation markers from a given piece of indentation with spaces.
  562. *
  563. * Callback for array_map() within drupal_html_to_text().
  564. */
  565. function _drupal_html_to_text_clean($indent) {
  566. return preg_replace('/[^>]/', ' ', $indent);
  567. }
  568. /**
  569. * Pads the last line with the given character.
  570. *
  571. * @see drupal_html_to_text()
  572. */
  573. function _drupal_html_to_text_pad($text, $pad, $prefix = '') {
  574. // Remove last line break.
  575. $text = substr($text, 0, -1);
  576. // Calculate needed padding space and add it.
  577. if (($p = strrpos($text, "\n")) === FALSE) {
  578. $p = -1;
  579. }
  580. $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
  581. // Add prefix and padding, and restore linebreak.
  582. return $text . $prefix . str_repeat($pad, $n) . "\n";
  583. }