/admin/mailout-debugger.php

https://github.com/markn86/moodle · PHP · 77 lines · 27 code · 9 blank · 41 comment · 5 complexity · b51a9945aec73621e823fb15fb674efb MD5 · raw file

  1. #!/usr/bin/php
  2. <?php
  3. /*
  4. * Utility to debug mailouts - will save the content of emails to a
  5. * logfile instead of sending them out. Use it as a sendmail
  6. * "stand-in" when testing mailouts.
  7. *
  8. * It is not Moodle specific - use it anywhere by setting the php
  9. * "sendmail_path" setting to this file with a logfile parameter.
  10. *
  11. * - Set in php.ini (not settable in config.php):
  12. * sendmail_path=/path-to-moodle/admin/mailout-debugger.php');
  13. * Or from the commandline
  14. * php -d sendmail_path='/path-to-moodle/admin/mailout-debugger.php' /path/to/cron.php
  15. *
  16. * - Create a file in admin called mailout-debugger.enable
  17. * (this is a security check to prevent execution in prod environments)
  18. * touch /path/to/moodle/admin/mailout-debugger.enable
  19. *
  20. * - Mark as executable: chmod ugo+rx mailout-debugger.php
  21. *
  22. * - Run your admin/cron.php
  23. *
  24. * - Read /tmp/moodle-mailout.log
  25. *
  26. *
  27. * This script will create logfiles in /tmp/ or in $TMPDIR if set.
  28. * On windows, use php -r 'print sys_get_temp_dir()' to see where the file is saved.
  29. */
  30. // Security check.
  31. if (!file_exists(__DIR__.'/mailout-debugger.enable')) {
  32. mdie("Disabled.");
  33. }
  34. $tmpdir=sys_get_temp_dir(); // default
  35. if (isset($_SERVER['REMOTE_ADDR'])) {
  36. mdie("should not be called from web server!");
  37. }
  38. if (isset($_ENV['TMPDIR']) && is_dir($_ENV['TMPDIR'])) {
  39. $tmpdir = $_ENV['TMPDIR'];
  40. }
  41. $tmpfile = $tmpdir . '/moodle-mailout.log';
  42. $fh = fopen($tmpfile, 'a+', false)
  43. or mdie("Error openning $tmpfile on append\n");
  44. fwrite($fh, "==== ".strftime("%a %b %e %H:%M:%S %Y", time())." ====\n");
  45. fwrite($fh, "==== Commandline: " . implode(' ',$argv) . "\n");
  46. $stdin = fopen('php://stdin', 'r');
  47. while ($line = fgets($stdin)) {
  48. fwrite($fh, $line);
  49. }
  50. fwrite($fh, "\n");
  51. fclose($fh);
  52. fclose($stdin);
  53. /**
  54. * Print an error to STDOUT and exit with a non-zero code. For commandline scripts.
  55. * Default errorcode is 1.
  56. *
  57. * Very useful for perl-like error-handling:
  58. *
  59. * do_something() or mdie("Something went wrong");
  60. *
  61. * @param string $msg Error message
  62. * @param integer $errorcode Error code to emit
  63. *
  64. */
  65. function mdie($msg='', $errorcode=1) {
  66. trigger_error($msg);
  67. exit($errorcode);
  68. }