Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.2.x will end 22 April 2024 (12 months).
  • Bug fixes for security issues in 4.2.x will end 7 October 2024 (18 months).
  • PHP version: minimum PHP 8.0.0 Note: minimum PHP version has increased since Moodle 4.1. PHP 8.1.x is supported too.

Differences Between: [Versions 310 and 402] [Versions 311 and 402] [Versions 39 and 402] [Versions 400 and 402] [Versions 401 and 402]

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * Customised version of phpmailer for Moodle
  19   *
  20   * @package    core
  21   * @author     Dan Poltawski <talktodan@gmail.com>
  22   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  23   */
  24  
  25  defined('MOODLE_INTERNAL') || die();
  26  
  27  // PLEASE NOTE: we use the phpmailer class _unmodified_
  28  // through the joys of OO. Distros are free to use their stock
  29  // version of this file.
  30  
  31  /**
  32   * Moodle Customised version of the PHPMailer class
  33   *
  34   * This class extends the stock PHPMailer class
  35   * in order to make sensible configuration choices,
  36   * and behave in a way which is friendly to moodle.
  37   *
  38   * @copyright 2009 Dan Poltawski <talktodan@gmail.com>
  39   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  40   * @since     Moodle 2.0
  41   */
  42  class moodle_phpmailer extends \PHPMailer\PHPMailer\PHPMailer {
  43  
  44      /**
  45       * Constructor - creates an instance of the PHPMailer class
  46       * with Moodle defaults.
  47       */
  48      public function __construct(){
  49          global $CFG;
  50          $this->CharSet   = 'UTF-8';
  51          // MDL-52637: Disable the automatic TLS encryption added in v5.2.10 (9da56fc1328a72aa124b35b738966315c41ef5c6).
  52          $this->SMTPAutoTLS = false;
  53  
  54          if (!empty($CFG->smtpauthtype)) {
  55              $this->AuthType = $CFG->smtpauthtype;
  56  
  57              if ($this->AuthType == 'XOAUTH2') {
  58                  $this->process_oauth();
  59              }
  60          }
  61  
  62          // Some MTAs may do double conversion of LF if CRLF used, CRLF is required line ending in RFC 822bis.
  63          if (isset($CFG->mailnewline) and $CFG->mailnewline == 'CRLF') {
  64              parent::setLE("\r\n");
  65          } else {
  66              parent::setLE("\n");
  67          }
  68      }
  69  
  70      /**
  71       * Extended AddCustomHeader function in order to stop duplicate
  72       * message-ids
  73       * http://tracker.moodle.org/browse/MDL-3681
  74       */
  75      public function addCustomHeader($custom_header, $value = null) {
  76          if ($value === null and preg_match('/message-id:(.*)/i', $custom_header, $matches)) {
  77              $this->MessageID = trim($matches[1]);
  78              return true;
  79          } else if ($value !== null and strcasecmp($custom_header, 'message-id') === 0) {
  80              $this->MessageID = trim($value);
  81              return true;
  82          } else {
  83              return parent::addCustomHeader($custom_header, $value);
  84          }
  85      }
  86  
  87      /**
  88       * Use internal moodles own core_text to encode mimeheaders.
  89       * Fall back to phpmailers inbuilt functions if not
  90       */
  91      public function encodeHeader($str, $position = 'text') {
  92          $encoded = core_text::encode_mimeheader($str, $this->CharSet);
  93          if ($encoded !== false) {
  94              if ($position === 'phrase') {
  95                  // Escape special symbols in each line in the encoded string, join back together and enclose in quotes.
  96                  $chunks = preg_split("/\\n/", $encoded);
  97                  $chunks = array_map(function($chunk) {
  98                      return addcslashes($chunk, "\0..\37\177\\\"");
  99                  }, $chunks);
 100                  return '"' . join(parent::getLE(), $chunks) . '"';
 101              }
 102              return str_replace("\n", parent::getLE(), $encoded);
 103          }
 104  
 105          return parent::encodeHeader($str, $position);
 106      }
 107  
 108      /**
 109       * Replaced function to fix tz bug:
 110       * http://tracker.moodle.org/browse/MDL-12596
 111       */
 112      public static function rfcDate() {
 113          $tz = date('Z');
 114          $tzs = ($tz < 0) ? '-' : '+';
 115          $tz = abs($tz);
 116          $tz = (($tz - ($tz%3600) )/3600)*100 + ($tz%3600)/60; // fixed tz bug
 117          $result = sprintf("%s %s%04d", date('D, j M Y H:i:s'), $tzs, $tz);
 118  
 119          return $result;
 120      }
 121  
 122      /**
 123       * Sends this mail.
 124       *
 125       * This function has been overridden to facilitate unit testing.
 126       *
 127       * @return bool
 128       */
 129      public function postSend() {
 130          // Now ask phpunit if it wants to catch this message.
 131          if (PHPUNIT_TEST) {
 132              if (!phpunit_util::is_redirecting_phpmailer()) {
 133                  debugging('Unit tests must not send real emails! Use $this->redirectEmails()');
 134                  return true;
 135              }
 136              $mail = new stdClass();
 137              $mail->header = $this->MIMEHeader;
 138              $mail->body = $this->MIMEBody;
 139              $mail->subject = $this->Subject;
 140              $mail->from = $this->From;
 141              $mail->to = $this->to[0][0];
 142              phpunit_util::phpmailer_sent($mail);
 143              return true;
 144          } else {
 145              return parent::postSend();
 146          }
 147      }
 148  
 149      /**
 150       * Config the PHPMailer to use OAUTH if necessary.
 151       */
 152      private function process_oauth(): void {
 153          global $CFG;
 154  
 155          require_once($CFG->libdir . '/phpmailer/moodle_phpmailer_oauth.php');
 156          if (!empty($CFG->smtpoauthservice)) {
 157              // Get the issuer.
 158              $issuer = \core\oauth2\api::get_issuer($CFG->smtpoauthservice);
 159              // Validate the issuer and check if it is enabled or not.
 160              if ($issuer && $issuer->get('enabled')) {
 161                  // Get the OAuth Client.
 162                  if ($oauthclient = \core\oauth2\api::get_system_oauth_client($issuer)) {
 163                      $oauth = new moodle_phpmailer_oauth([
 164                          'provider' => $oauthclient,
 165                          'clientId' => $oauthclient->get_clientid(),
 166                          'clientSecret' => $oauthclient->get_clientsecret(),
 167                          'refreshToken' => $oauthclient->get_refresh_token(),
 168                          'userName' => $CFG->smtpuser,
 169                      ]);
 170                      // Set the OAuth.
 171                      $this->setOAuth($oauth);
 172                  }
 173              }
 174          }
 175      }
 176  }