Projet

Général

Profil

Paste
Télécharger (25,2 ko) Statistiques
| Branche: | Révision:

root / drupal7 / includes / mail.inc @ 01dfd3b5

1
<?php
2

    
3
/**
4
 * @file
5
 * API functions for processing and sending e-mail.
6
 */
7

    
8
/**
9
 * Auto-detect appropriate line endings for e-mails.
10
 *
11
 * $conf['mail_line_endings'] will override this setting.
12
 */
13
define('MAIL_LINE_ENDINGS', isset($_SERVER['WINDIR']) || (isset($_SERVER['SERVER_SOFTWARE']) && strpos($_SERVER['SERVER_SOFTWARE'], 'Win32') !== FALSE) ? "\r\n" : "\n");
14

    
15

    
16
/**
17
 * Special characters, defined in RFC_2822.
18
 */
19
define('MAIL_RFC_2822_SPECIALS', '()<>[]:;@\,."');
20

    
21
/**
22
 * Composes and optionally sends an e-mail message.
23
 *
24
 * Sending an e-mail works with defining an e-mail template (subject, text
25
 * and possibly e-mail headers) and the replacement values to use in the
26
 * appropriate places in the template. Processed e-mail templates are
27
 * requested from hook_mail() from the module sending the e-mail. Any module
28
 * can modify the composed e-mail message array using hook_mail_alter().
29
 * Finally drupal_mail_system()->mail() sends the e-mail, which can
30
 * be reused if the exact same composed e-mail is to be sent to multiple
31
 * recipients.
32
 *
33
 * Finding out what language to send the e-mail with needs some consideration.
34
 * If you send e-mail to a user, her preferred language should be fine, so
35
 * use user_preferred_language(). If you send email based on form values
36
 * filled on the page, there are two additional choices if you are not
37
 * sending the e-mail to a user on the site. You can either use the language
38
 * used to generate the page ($language global variable) or the site default
39
 * language. See language_default(). The former is good if sending e-mail to
40
 * the person filling the form, the later is good if you send e-mail to an
41
 * address previously set up (like contact addresses in a contact form).
42
 *
43
 * Taking care of always using the proper language is even more important
44
 * when sending e-mails in a row to multiple users. Hook_mail() abstracts
45
 * whether the mail text comes from an administrator setting or is
46
 * static in the source code. It should also deal with common mail tokens,
47
 * only receiving $params which are unique to the actual e-mail at hand.
48
 *
49
 * An example:
50
 *
51
 * @code
52
 *   function example_notify($accounts) {
53
 *     foreach ($accounts as $account) {
54
 *       $params['account'] = $account;
55
 *       // example_mail() will be called based on the first drupal_mail() parameter.
56
 *       drupal_mail('example', 'notice', $account->mail, user_preferred_language($account), $params);
57
 *     }
58
 *   }
59
 *
60
 *   function example_mail($key, &$message, $params) {
61
 *     $data['user'] = $params['account'];
62
 *     $options['language'] = $message['language'];
63
 *     user_mail_tokens($variables, $data, $options);
64
 *     switch($key) {
65
 *       case 'notice':
66
 *         // If the recipient can receive such notices by instant-message, do
67
 *         // not send by email.
68
 *         if (example_im_send($key, $message, $params)) {
69
 *           $message['send'] = FALSE;
70
 *           break;
71
 *         }
72
 *         $langcode = $message['language']->language;
73
 *         $message['subject'] = t('Notification from !site', $variables, array('langcode' => $langcode));
74
 *         $message['body'][] = t("Dear !username\n\nThere is new content available on the site.", $variables, array('langcode' => $langcode));
75
 *         break;
76
 *     }
77
 *   }
78
 * @endcode
79
 *
80
 * Another example, which uses drupal_mail() to format a message for sending
81
 * later:
82
 *
83
 * @code
84
 *   $params = array('current_conditions' => $data);
85
 *   $to = 'user@example.com';
86
 *   $message = drupal_mail('example', 'notice', $to, $language, $params, FALSE);
87
 *   // Only add to the spool if sending was not canceled.
88
 *   if ($message['send']) {
89
 *     example_spool_message($message);
90
 *   }
91
 * @endcode
92
 *
93
 * @param $module
94
 *   A module name to invoke hook_mail() on. The {$module}_mail() hook will be
95
 *   called to complete the $message structure which will already contain common
96
 *   defaults.
97
 * @param $key
98
 *   A key to identify the e-mail sent. The final e-mail id for e-mail altering
99
 *   will be {$module}_{$key}.
100
 * @param $to
101
 *   The e-mail address or addresses where the message will be sent to. The
102
 *   formatting of this string will be validated with the
103
 *   @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
104
 *   Some examples are:
105
 *   - user@example.com
106
 *   - user@example.com, anotheruser@example.com
107
 *   - User <user@example.com>
108
 *   - User <user@example.com>, Another User <anotheruser@example.com>
109
 * @param $language
110
 *   Language object to use to compose the e-mail.
111
 * @param $params
112
 *   Optional parameters to build the e-mail.
113
 * @param $from
114
 *   Sets From to this value, if given.
115
 * @param $send
116
 *   If TRUE, drupal_mail() will call drupal_mail_system()->mail() to deliver
117
 *   the message, and store the result in $message['result']. Modules
118
 *   implementing hook_mail_alter() may cancel sending by setting
119
 *   $message['send'] to FALSE.
120
 *
121
 * @return
122
 *   The $message array structure containing all details of the
123
 *   message. If already sent ($send = TRUE), then the 'result' element
124
 *   will contain the success indicator of the e-mail, failure being already
125
 *   written to the watchdog. (Success means nothing more than the message being
126
 *   accepted at php-level, which still doesn't guarantee it to be delivered.)
127
 */
128
function drupal_mail($module, $key, $to, $language, $params = array(), $from = NULL, $send = TRUE) {
129
  $default_from = variable_get('site_mail', ini_get('sendmail_from'));
130

    
131
  // Bundle up the variables into a structured array for altering.
132
  $message = array(
133
    'id'       => $module . '_' . $key,
134
    'module'   => $module,
135
    'key'      => $key,
136
    'to'       => $to,
137
    'from'     => isset($from) ? $from : $default_from,
138
    'language' => $language,
139
    'params'   => $params,
140
    'send'     => TRUE,
141
    'subject'  => '',
142
    'body'     => array()
143
  );
144

    
145
  // Build the default headers
146
  $headers = array(
147
    'MIME-Version'              => '1.0',
148
    'Content-Type'              => 'text/plain; charset=UTF-8; format=flowed; delsp=yes',
149
    'Content-Transfer-Encoding' => '8Bit',
150
    'X-Mailer'                  => 'Drupal'
151
  );
152
  if ($default_from) {
153
    // To prevent e-mail from looking like spam, the addresses in the Sender and
154
    // Return-Path headers should have a domain authorized to use the originating
155
    // SMTP server.
156
    $headers['From'] = $headers['Sender'] = $headers['Return-Path'] = $default_from;
157

    
158
    if (variable_get('mail_display_name_site_name', FALSE)) {
159
      $display_name = variable_get('site_name', 'Drupal');
160
      $headers['From'] = drupal_mail_format_display_name($display_name) . ' <' . $default_from . '>';
161
    }
162
  }
163
  if ($from && $from != $default_from) {
164
    $headers['From'] = $from;
165
  }
166
  $message['headers'] = $headers;
167

    
168
  // Build the e-mail (get subject and body, allow additional headers) by
169
  // invoking hook_mail() on this module. We cannot use module_invoke() as
170
  // we need to have $message by reference in hook_mail().
171
  if (function_exists($function = $module . '_mail')) {
172
    $function($key, $message, $params);
173
  }
174

    
175
  // Invoke hook_mail_alter() to allow all modules to alter the resulting e-mail.
176
  drupal_alter('mail', $message);
177

    
178
  // Retrieve the responsible implementation for this message.
179
  $system = drupal_mail_system($module, $key);
180

    
181
  // Format the message body.
182
  $message = $system->format($message);
183

    
184
  // Optionally send e-mail.
185
  if ($send) {
186
    // The original caller requested sending. Sending was canceled by one or
187
    // more hook_mail_alter() implementations. We set 'result' to NULL, because
188
    // FALSE indicates an error in sending.
189
    if (empty($message['send'])) {
190
      $message['result'] = NULL;
191
    }
192
    // Sending was originally requested and was not canceled.
193
    else {
194
      $message['result'] = $system->mail($message);
195
      // Log errors.
196
      if (!$message['result']) {
197
        watchdog('mail', 'Error sending e-mail (from %from to %to).', array('%from' => $message['from'], '%to' => $message['to']), WATCHDOG_ERROR);
198
        drupal_set_message(t('Unable to send e-mail. Contact the site administrator if the problem persists.'), 'error');
199
      }
200
    }
201
  }
202

    
203
  return $message;
204
}
205

    
206
/**
207
 * Returns an object that implements the MailSystemInterface interface.
208
 *
209
 * Allows for one or more custom mail backends to format and send mail messages
210
 * composed using drupal_mail().
211
 *
212
 * An implementation needs to implement the following methods:
213
 * - format: Allows to preprocess, format, and postprocess a mail
214
 *   message before it is passed to the sending system. By default, all messages
215
 *   may contain HTML and are converted to plain-text by the DefaultMailSystem
216
 *   implementation. For example, an alternative implementation could override
217
 *   the default implementation and additionally sanitize the HTML for usage in
218
 *   a MIME-encoded e-mail, but still invoking the DefaultMailSystem
219
 *   implementation to generate an alternate plain-text version for sending.
220
 * - mail: Sends a message through a custom mail sending engine.
221
 *   By default, all messages are sent via PHP's mail() function by the
222
 *   DefaultMailSystem implementation.
223
 *
224
 * The selection of a particular implementation is controlled via the variable
225
 * 'mail_system', which is a keyed array.  The default implementation
226
 * is the class whose name is the value of 'default-system' key. A more specific
227
 * match first to key and then to module will be used in preference to the
228
 * default. To specify a different class for all mail sent by one module, set
229
 * the class name as the value for the key corresponding to the module name. To
230
 * specify a class for a particular message sent by one module, set the class
231
 * name as the value for the array key that is the message id, which is
232
 * "${module}_${key}".
233
 *
234
 * For example to debug all mail sent by the user module by logging it to a
235
 * file, you might set the variable as something like:
236
 *
237
 * @code
238
 * array(
239
 *   'default-system' => 'DefaultMailSystem',
240
 *   'user' => 'DevelMailLog',
241
 * );
242
 * @endcode
243
 *
244
 * Finally, a different system can be specified for a specific e-mail ID (see
245
 * the $key param), such as one of the keys used by the contact module:
246
 *
247
 * @code
248
 * array(
249
 *   'default-system' => 'DefaultMailSystem',
250
 *   'user' => 'DevelMailLog',
251
 *   'contact_page_autoreply' => 'DrupalDevNullMailSend',
252
 * );
253
 * @endcode
254
 *
255
 * Other possible uses for system include a mail-sending class that actually
256
 * sends (or duplicates) each message to SMS, Twitter, instant message, etc, or
257
 * a class that queues up a large number of messages for more efficient bulk
258
 * sending or for sending via a remote gateway so as to reduce the load
259
 * on the local server.
260
 *
261
 * @param $module
262
 *   The module name which was used by drupal_mail() to invoke hook_mail().
263
 * @param $key
264
 *   A key to identify the e-mail sent. The final e-mail ID for the e-mail
265
 *   alter hook in drupal_mail() would have been {$module}_{$key}.
266
 *
267
 * @return MailSystemInterface
268
 */
269
function drupal_mail_system($module, $key) {
270
  $instances = &drupal_static(__FUNCTION__, array());
271

    
272
  $id = $module . '_' . $key;
273

    
274
  $configuration = variable_get('mail_system', array('default-system' => 'DefaultMailSystem'));
275

    
276
  // Look for overrides for the default class, starting from the most specific
277
  // id, and falling back to the module name.
278
  if (isset($configuration[$id])) {
279
    $class = $configuration[$id];
280
  }
281
  elseif (isset($configuration[$module])) {
282
    $class = $configuration[$module];
283
  }
284
  else {
285
    $class = $configuration['default-system'];
286
  }
287

    
288
  if (empty($instances[$class])) {
289
    $interfaces = class_implements($class);
290
    if (isset($interfaces['MailSystemInterface'])) {
291
      $instances[$class] = new $class();
292
    }
293
    else {
294
      throw new Exception(t('Class %class does not implement interface %interface', array('%class' => $class, '%interface' => 'MailSystemInterface')));
295
    }
296
  }
297
  return $instances[$class];
298
}
299

    
300
/**
301
 * An interface for pluggable mail back-ends.
302
 */
303
interface MailSystemInterface {
304
  /**
305
   * Format a message composed by drupal_mail() prior sending.
306
   *
307
   * @param $message
308
   *   A message array, as described in hook_mail_alter().
309
   *
310
   * @return
311
   *   The formatted $message.
312
   */
313
   public function format(array $message);
314

    
315
  /**
316
   * Send a message composed by drupal_mail().
317
   *
318
   * @param $message
319
   *   Message array with at least the following elements:
320
   *   - id: A unique identifier of the e-mail type. Examples: 'contact_user_copy',
321
   *     'user_password_reset'.
322
   *   - to: The mail address or addresses where the message will be sent to.
323
   *     The formatting of this string will be validated with the
324
   *     @link http://php.net/manual/filter.filters.validate.php PHP e-mail validation filter. @endlink
325
   *     Some examples are:
326
   *     - user@example.com
327
   *     - user@example.com, anotheruser@example.com
328
   *     - User <user@example.com>
329
   *     - User <user@example.com>, Another User <anotheruser@example.com>
330
   *   - subject: Subject of the e-mail to be sent. This must not contain any
331
   *     newline characters, or the mail may not be sent properly.
332
   *   - body: Message to be sent. Accepts both CRLF and LF line-endings.
333
   *     E-mail bodies must be wrapped. You can use drupal_wrap_mail() for
334
   *     smart plain text wrapping.
335
   *   - headers: Associative array containing all additional mail headers not
336
   *     defined by one of the other parameters.  PHP's mail() looks for Cc and
337
   *     Bcc headers and sends the mail to addresses in these headers too.
338
   *
339
   * @return
340
   *   TRUE if the mail was successfully accepted for delivery, otherwise FALSE.
341
   */
342
   public function mail(array $message);
343
}
344

    
345
/**
346
 * Performs format=flowed soft wrapping for mail (RFC 3676).
347
 *
348
 * We use delsp=yes wrapping, but only break non-spaced languages when
349
 * absolutely necessary to avoid compatibility issues.
350
 *
351
 * We deliberately use LF rather than CRLF, see drupal_mail().
352
 *
353
 * @param string $text
354
 *   The plain text to process.
355
 * @param string $indent (optional)
356
 *   A string to indent the text with. Only '>' characters are repeated on
357
 *   subsequent wrapped lines. Others are replaced by spaces.
358
 *
359
 * @return string
360
 *   The content of the email as a string with formatting applied.
361
 */
362
function drupal_wrap_mail($text, $indent = '') {
363
  // Convert CRLF into LF.
364
  $text = str_replace("\r", '', $text);
365
  // See if soft-wrapping is allowed.
366
  $clean_indent = _drupal_html_to_text_clean($indent);
367
  $soft = strpos($clean_indent, ' ') === FALSE;
368
  // Check if the string has line breaks.
369
  if (strpos($text, "\n") !== FALSE) {
370
    // Remove trailing spaces to make existing breaks hard, but leave signature
371
    // marker untouched (RFC 3676, Section 4.3).
372
    $text = preg_replace('/(?(?<!^--) +\n|  +\n)/m', "\n", $text);
373
    // Wrap each line at the needed width.
374
    $lines = explode("\n", $text);
375
    array_walk($lines, '_drupal_wrap_mail_line', array('soft' => $soft, 'length' => strlen($indent)));
376
    $text = implode("\n", $lines);
377
  }
378
  else {
379
    // Wrap this line.
380
    _drupal_wrap_mail_line($text, 0, array('soft' => $soft, 'length' => strlen($indent)));
381
  }
382
  // Empty lines with nothing but spaces.
383
  $text = preg_replace('/^ +\n/m', "\n", $text);
384
  // Space-stuff special lines.
385
  $text = preg_replace('/^(>| |From)/m', ' $1', $text);
386
  // Apply indentation. We only include non-'>' indentation on the first line.
387
  $text = $indent . substr(preg_replace('/^/m', $clean_indent, $text), strlen($indent));
388

    
389
  return $text;
390
}
391

    
392
/**
393
 * Transforms an HTML string into plain text, preserving its structure.
394
 *
395
 * The output will be suitable for use as 'format=flowed; delsp=yes' text
396
 * (RFC 3676) and can be passed directly to drupal_mail() for sending.
397
 *
398
 * We deliberately use LF rather than CRLF, see drupal_mail().
399
 *
400
 * This function provides suitable alternatives for the following tags:
401
 * <a> <em> <i> <strong> <b> <br> <p> <blockquote> <ul> <ol> <li> <dl> <dt>
402
 * <dd> <h1> <h2> <h3> <h4> <h5> <h6> <hr>
403
 *
404
 * @param $string
405
 *   The string to be transformed.
406
 * @param $allowed_tags (optional)
407
 *   If supplied, a list of tags that will be transformed. If omitted, all
408
 *   all supported tags are transformed.
409
 *
410
 * @return
411
 *   The transformed string.
412
 */
413
function drupal_html_to_text($string, $allowed_tags = NULL) {
414
  // Cache list of supported tags.
415
  static $supported_tags;
416
  if (empty($supported_tags)) {
417
    $supported_tags = array('a', 'em', 'i', 'strong', 'b', 'br', 'p', 'blockquote', 'ul', 'ol', 'li', 'dl', 'dt', 'dd', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr');
418
  }
419

    
420
  // Make sure only supported tags are kept.
421
  $allowed_tags = isset($allowed_tags) ? array_intersect($supported_tags, $allowed_tags) : $supported_tags;
422

    
423
  // Make sure tags, entities and attributes are well-formed and properly nested.
424
  $string = _filter_htmlcorrector(filter_xss($string, $allowed_tags));
425

    
426
  // Apply inline styles.
427
  $string = preg_replace('!</?(em|i)((?> +)[^>]*)?>!i', '/', $string);
428
  $string = preg_replace('!</?(strong|b)((?> +)[^>]*)?>!i', '*', $string);
429

    
430
  // Replace inline <a> tags with the text of link and a footnote.
431
  // 'See <a href="http://drupal.org">the Drupal site</a>' becomes
432
  // 'See the Drupal site [1]' with the URL included as a footnote.
433
  _drupal_html_to_mail_urls(NULL, TRUE);
434
  $pattern = '@(<a[^>]+?href="([^"]*)"[^>]*?>(.+?)</a>)@i';
435
  $string = preg_replace_callback($pattern, '_drupal_html_to_mail_urls', $string);
436
  $urls = _drupal_html_to_mail_urls();
437
  $footnotes = '';
438
  if (count($urls)) {
439
    $footnotes .= "\n";
440
    for ($i = 0, $max = count($urls); $i < $max; $i++) {
441
      $footnotes .= '[' . ($i + 1) . '] ' . $urls[$i] . "\n";
442
    }
443
  }
444

    
445
  // Split tags from text.
446
  $split = preg_split('/<([^>]+?)>/', $string, -1, PREG_SPLIT_DELIM_CAPTURE);
447
  // Note: PHP ensures the array consists of alternating delimiters and literals
448
  // and begins and ends with a literal (inserting $null as required).
449

    
450
  $tag = FALSE; // Odd/even counter (tag or no tag)
451
  $casing = NULL; // Case conversion function
452
  $output = '';
453
  $indent = array(); // All current indentation string chunks
454
  $lists = array(); // Array of counters for opened lists
455
  foreach ($split as $value) {
456
    $chunk = NULL; // Holds a string ready to be formatted and output.
457

    
458
    // Process HTML tags (but don't output any literally).
459
    if ($tag) {
460
      list($tagname) = explode(' ', strtolower($value), 2);
461
      switch ($tagname) {
462
        // List counters
463
        case 'ul':
464
          array_unshift($lists, '*');
465
          break;
466
        case 'ol':
467
          array_unshift($lists, 1);
468
          break;
469
        case '/ul':
470
        case '/ol':
471
          array_shift($lists);
472
          $chunk = ''; // Ensure blank new-line.
473
          break;
474

    
475
        // Quotation/list markers, non-fancy headers
476
        case 'blockquote':
477
          // Format=flowed indentation cannot be mixed with lists.
478
          $indent[] = count($lists) ? ' "' : '>';
479
          break;
480
        case 'li':
481
          $indent[] = isset($lists[0]) && is_numeric($lists[0]) ? ' ' . $lists[0]++ . ') ' : ' * ';
482
          break;
483
        case 'dd':
484
          $indent[] = '    ';
485
          break;
486
        case 'h3':
487
          $indent[] = '.... ';
488
          break;
489
        case 'h4':
490
          $indent[] = '.. ';
491
          break;
492
        case '/blockquote':
493
          if (count($lists)) {
494
            // Append closing quote for inline quotes (immediately).
495
            $output = rtrim($output, "> \n") . "\"\n";
496
            $chunk = ''; // Ensure blank new-line.
497
          }
498
          // Fall-through
499
        case '/li':
500
        case '/dd':
501
          array_pop($indent);
502
          break;
503
        case '/h3':
504
        case '/h4':
505
          array_pop($indent);
506
        case '/h5':
507
        case '/h6':
508
          $chunk = ''; // Ensure blank new-line.
509
          break;
510

    
511
        // Fancy headers
512
        case 'h1':
513
          $indent[] = '======== ';
514
          $casing = 'drupal_strtoupper';
515
          break;
516
        case 'h2':
517
          $indent[] = '-------- ';
518
          $casing = 'drupal_strtoupper';
519
          break;
520
        case '/h1':
521
        case '/h2':
522
          $casing = NULL;
523
          // Pad the line with dashes.
524
          $output = _drupal_html_to_text_pad($output, ($tagname == '/h1') ? '=' : '-', ' ');
525
          array_pop($indent);
526
          $chunk = ''; // Ensure blank new-line.
527
          break;
528

    
529
        // Horizontal rulers
530
        case 'hr':
531
          // Insert immediately.
532
          $output .= drupal_wrap_mail('', implode('', $indent)) . "\n";
533
          $output = _drupal_html_to_text_pad($output, '-');
534
          break;
535

    
536
        // Paragraphs and definition lists
537
        case '/p':
538
        case '/dl':
539
          $chunk = ''; // Ensure blank new-line.
540
          break;
541
      }
542
    }
543
    // Process blocks of text.
544
    else {
545
      // Convert inline HTML text to plain text; not removing line-breaks or
546
      // white-space, since that breaks newlines when sanitizing plain-text.
547
      $value = trim(decode_entities($value));
548
      if (drupal_strlen($value)) {
549
        $chunk = $value;
550
      }
551
    }
552

    
553
    // See if there is something waiting to be output.
554
    if (isset($chunk)) {
555
      // Apply any necessary case conversion.
556
      if (isset($casing)) {
557
        $chunk = $casing($chunk);
558
      }
559
      // Format it and apply the current indentation.
560
      $output .= drupal_wrap_mail($chunk, implode('', $indent)) . MAIL_LINE_ENDINGS;
561
      // Remove non-quotation markers from indentation.
562
      $indent = array_map('_drupal_html_to_text_clean', $indent);
563
    }
564

    
565
    $tag = !$tag;
566
  }
567

    
568
  return $output . $footnotes;
569
}
570

    
571
/**
572
 * Return a RFC-2822 compliant "display-name" component.
573
 *
574
 * The "display-name" component is used in mail header "Originator" fields
575
 * (From, Sender, Reply-to) to give a human-friendly description of the
576
 * address, i.e. From: My Display Name <xyz@example.org>. RFC-822 and
577
 * RFC-2822 define its syntax and rules. This method gets as input a string
578
 * to be used as "display-name" and formats it to be RFC compliant.
579
 *
580
 * @param string $string
581
 *   A string to be used as "display-name".
582
 *
583
 * @return string
584
 *   A RFC compliant version of the string, ready to be used as
585
 *   "display-name" in mail originator header fields.
586
 */
587
function drupal_mail_format_display_name($string) {
588
  // Make sure we don't process html-encoded characters. They may create
589
  // unneeded trouble if left encoded, besides they will be correctly
590
  // processed if decoded.
591
  $string = decode_entities($string);
592

    
593
  // If string contains non-ASCII characters it must be (short) encoded
594
  // according to RFC-2047. The output of a "B" (Base64) encoded-word is
595
  // always safe to be used as display-name.
596
  $safe_display_name = mime_header_encode($string, TRUE);
597

    
598
  // Encoded-words are always safe to be used as display-name because don't
599
  // contain any RFC 2822 "specials" characters. However
600
  // mimeHeaderEncode() encodes a string only if it contains any
601
  // non-ASCII characters, and leaves its value untouched (un-encoded) if
602
  // ASCII only. For this reason in order to produce a valid display-name we
603
  // still need to make sure there are no "specials" characters left.
604
  if (preg_match('/[' . preg_quote(MAIL_RFC_2822_SPECIALS) . ']/', $safe_display_name)) {
605

    
606
    // If string is already quoted, it may or may not be escaped properly, so
607
    // don't trust it and reset.
608
    if (preg_match('/^"(.+)"$/', $safe_display_name, $matches)) {
609
      $safe_display_name = str_replace(array('\\\\', '\\"'), array('\\', '"'), $matches[1]);
610
    }
611

    
612
    // Transform the string in a RFC-2822 "quoted-string" by wrapping it in
613
    // double-quotes. Also make sure '"' and '\' occurrences are escaped.
614
    $safe_display_name = '"' . str_replace(array('\\', '"'), array('\\\\', '\\"'), $safe_display_name) . '"';
615
  }
616

    
617
  return $safe_display_name;
618
}
619

    
620
/**
621
 * Wraps words on a single line.
622
 *
623
 * Callback for array_walk() within drupal_wrap_mail().
624
 */
625
function _drupal_wrap_mail_line(&$line, $key, $values) {
626
  // Use soft-breaks only for purely quoted or unindented text.
627
  $line = wordwrap($line, 77 - $values['length'], $values['soft'] ? " \n" : "\n");
628
  // Break really long words at the maximum width allowed.
629
  $line = wordwrap($line, 996 - $values['length'], $values['soft'] ? " \n" : "\n", TRUE);
630
}
631

    
632
/**
633
 * Keeps track of URLs and replaces them with placeholder tokens.
634
 *
635
 * Callback for preg_replace_callback() within drupal_html_to_text().
636
 */
637
function _drupal_html_to_mail_urls($match = NULL, $reset = FALSE) {
638
  global $base_url, $base_path;
639
  static $urls = array(), $regexp;
640

    
641
  if ($reset) {
642
    // Reset internal URL list.
643
    $urls = array();
644
  }
645
  else {
646
    if (empty($regexp)) {
647
      $regexp = '@^' . preg_quote($base_path, '@') . '@';
648
    }
649
    if ($match) {
650
      list(, , $url, $label) = $match;
651
      // Ensure all URLs are absolute.
652
      $urls[] = strpos($url, '://') ? $url : preg_replace($regexp, $base_url . '/', $url);
653
      return $label . ' [' . count($urls) . ']';
654
    }
655
  }
656
  return $urls;
657
}
658

    
659
/**
660
 * Replaces non-quotation markers from a given piece of indentation with spaces.
661
 *
662
 * Callback for array_map() within drupal_html_to_text().
663
 */
664
function _drupal_html_to_text_clean($indent) {
665
  return preg_replace('/[^>]/', ' ', $indent);
666
}
667

    
668
/**
669
 * Pads the last line with the given character.
670
 *
671
 * @see drupal_html_to_text()
672
 */
673
function _drupal_html_to_text_pad($text, $pad, $prefix = '') {
674
  // Remove last line break.
675
  $text = substr($text, 0, -1);
676
  // Calculate needed padding space and add it.
677
  if (($p = strrpos($text, "\n")) === FALSE) {
678
    $p = -1;
679
  }
680
  $n = max(0, 79 - (strlen($text) - $p) - strlen($prefix));
681
  // Add prefix and padding, and restore linebreak.
682
  return $text . $prefix . str_repeat($pad, $n) . "\n";
683
}