devel.mail.inc 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. <?php
  2. /**
  3. * @file
  4. * MailSystemInterface for logging mails to the filesystem.
  5. *
  6. * To enable, save a variable in settings.php (or otherwise) whose value
  7. * can be as simple as:
  8. *
  9. * $conf['mail_system'] = array(
  10. * 'default-system' => 'DevelMailLog',
  11. *);
  12. *
  13. * Saves to temporary://devel-mails dir by default. Can be changed using
  14. * 'devel_debug_mail_directory' variable. Filename pattern controlled by
  15. * 'devel_debug_mail_file_format' variable.
  16. *
  17. */
  18. class DevelMailLog extends DefaultMailSystem {
  19. public function composeMessage($message) {
  20. $mimeheaders = array();
  21. $message['headers']['To'] = $message['to'];
  22. foreach ($message['headers'] as $name => $value) {
  23. $mimeheaders[] = $name . ': ' . mime_header_encode($value);
  24. }
  25. $line_endings = variable_get('mail_line_endings', MAIL_LINE_ENDINGS);
  26. $output = join($line_endings, $mimeheaders) . $line_endings;
  27. $output .= $message['subject'] . $line_endings;
  28. $output .= preg_replace('@\r?\n@', $line_endings, $message['body']);
  29. return $output;
  30. }
  31. public function getFileName($message) {
  32. $output_directory = $this->getOutputDirectory();
  33. $this->makeOutputDirectory($output_directory);
  34. $output_file_format = variable_get('devel_debug_mail_file_format', '%to-%subject-%datetime.mail.txt');
  35. $tokens = array(
  36. '%to' => $message['to'],
  37. '%subject' => $message['subject'],
  38. '%datetime' => date('y-m-d_his'),
  39. );
  40. return $output_directory . '/' . $this->dirify(str_replace(array_keys($tokens), array_values($tokens), $output_file_format));
  41. }
  42. private function dirify($string) {
  43. return preg_replace('/[^a-zA-Z0-9_\-\.@]/', '_', $string);
  44. }
  45. /**
  46. * Save an e-mail message to a file, using Drupal variables and default settings.
  47. *
  48. * @see http://php.net/manual/en/function.mail.php
  49. * @see drupal_mail()
  50. *
  51. * @param $message
  52. * A message array, as described in hook_mail_alter().
  53. * @return
  54. * TRUE if the mail was successfully accepted, otherwise FALSE.
  55. */
  56. public function mail(array $message) {
  57. $output = $this->composeMessage($message);
  58. $output_file = $this->getFileName($message);
  59. return file_put_contents($output_file, $output);
  60. }
  61. protected function makeOutputDirectory($output_directory) {
  62. if (!file_prepare_directory($output_directory, FILE_CREATE_DIRECTORY)) {
  63. throw new Exception("Unable to continue sending mail, $output_directory is not writable");
  64. }
  65. }
  66. public function getOutputDirectory() {
  67. return variable_get('devel_debug_mail_directory', 'temporary://devel-mails');
  68. }
  69. }
  70. ?>