diff --git a/modules/system/ServiceProvider.php b/modules/system/ServiceProvider.php index 3ca790061..bab3911db 100644 --- a/modules/system/ServiceProvider.php +++ b/modules/system/ServiceProvider.php @@ -14,6 +14,7 @@ use System\Classes\SettingsManager; use System\Twig\Engine as TwigEngine; use System\Twig\Loader as TwigLoader; use System\Models\EmailSettings; +use System\Models\EmailTemplate; use Backend\Classes\WidgetManager; use October\Rain\Support\ModuleServiceProvider; @@ -68,22 +69,38 @@ class ServiceProvider extends ModuleServiceProvider return $handler->handleException($exception, $httpCode, $isConsole); }); + /* + * Register basic twig + */ + App::bindShared('twig', function($app) { + return new Twig_Environment(new TwigLoader(), ['auto_reload' => true]); + }); + /* * Register .htm extension for Twig views */ App::make('view')->addExtension('htm', 'twig', function() { - $twigEnvironment = new Twig_Environment(new TwigLoader(), ['auto_reload' => true]); - return new TwigEngine($twigEnvironment); + return new TwigEngine(App::make('twig')); }); /* * Override system email with email settings */ - Event::listen('mailer.register', function() { + Event::listen('mailer.beforeRegister', function() { if (EmailSettings::isConfigured()) EmailSettings::applyConfigValues(); }); + /* + * Override standard Mailer content with template + */ + Event::listen('mailer.register', function() { + App::make('mailer')->bindEvent('content.beforeAdd', function($message, $view, $plain, $data){ + if (EmailTemplate::addContentToMailer($message, $view, $data)) + return false; + }); + }); + /* * Register other module providers */ diff --git a/modules/system/models/EmailTemplate.php b/modules/system/models/EmailTemplate.php index cd89ad7f7..5e914d467 100644 --- a/modules/system/models/EmailTemplate.php +++ b/modules/system/models/EmailTemplate.php @@ -1,5 +1,6 @@ ['System\Models\EmailLayout'] ]; + /** + * @var array A cache of customised email templates. + */ + protected static $cache = []; + /** * @var array Cache of registration callbacks. */ @@ -82,6 +88,33 @@ class EmailTemplate extends Model return MailParser::parse(File::get(View::make($code)->getPath())); } + public static function addContentToMailer($message, $code, $data) + { + if (!isset(self::$cache[$code])) { + if (!$template = self::where('is_custom', true)->whereCode($code)->first()) + return false; + + self::$cache[$code] = $template; + } + else + $template = self::$cache[$code]; + + /* + * Set Twig to load from a string + */ + $twig = App::make('twig'); + $oldLoader = $twig->getLoader(); + $twig->setLoader(new \Twig_Loader_String); + + $message->subject($twig->render($template->subject, $data)); + $message->setBody($twig->render($template->content_html, $data), 'text/html'); + if (strlen($template->content_text)) + $message->addPart($twig->render($template->content_text, $data), 'text/plain'); + + $twig->setLoader($oldLoader); + return true; + } + // // Registration //