From a16cb528dc66dc3a9fcddabc990702d4ff030252 Mon Sep 17 00:00:00 2001 From: Ryan Cramer Date: Wed, 31 Mar 2021 10:13:18 -0400 Subject: [PATCH] Update TemplateFile class with a clearAll() static method and update ProcessPageView to use it when a 404 is thrown. This ensures that a 404 thrown after some output has already been sent can't get interpreted as a non-404 by the client --- wire/core/TemplateFile.php | 29 ++++++++++++++++++++- wire/modules/Process/ProcessPageView.module | 1 + 2 files changed, 29 insertions(+), 1 deletion(-) diff --git a/wire/core/TemplateFile.php b/wire/core/TemplateFile.php index 6962fb6e..574ac1ea 100644 --- a/wire/core/TemplateFile.php +++ b/wire/core/TemplateFile.php @@ -138,7 +138,15 @@ class TemplateFile extends WireData { * DEPRECATED: Variables that will be applied globally to this and all other TemplateFile instances * */ - static protected $globals = array(); + static protected $globals = array(); + + /** + * Output buffer starting level, set by first TemplateFile instance that gets created + * + * @var null|int + * + */ + static protected $obStartLevel = null; /** * Construct the template file @@ -147,6 +155,7 @@ class TemplateFile extends WireData { * */ public function __construct($filename = '') { + if(self::$obStartLevel === null) self::$obStartLevel = ob_get_level(); if($filename) $this->setFilename($filename); } @@ -561,6 +570,24 @@ class TemplateFile extends WireData { return self::$renderStack; } + /** + * Clear out all pending output buffers + * + * @since 3.0.175 + * @return int Number of output buffers cleaned + * + */ + public static function clearAll() { + $n = 0; + if(self::$obStartLevel !== null) { + while(ob_get_level() > self::$obStartLevel) { + ob_end_clean(); + $n++; + } + } + return $n; + } + /** * The string value of a TemplateFile is its PHP template filename OR its class name if no filename is set * diff --git a/wire/modules/Process/ProcessPageView.module b/wire/modules/Process/ProcessPageView.module index 0716d313..b1b7ca47 100644 --- a/wire/modules/Process/ProcessPageView.module +++ b/wire/modules/Process/ProcessPageView.module @@ -227,6 +227,7 @@ class ProcessPageView extends Process { } catch(Wire404Exception $e) { // 404 exception + TemplateFile::clearAll(); return $this->renderNoPage(array( 'reason404' => '404 thrown during page render', 'exception404' => $e,