From 83b23b86d3e90b7ad54ab869701b2e05362a7df3 Mon Sep 17 00:00:00 2001
From: Shamim Rezaie <shamim@moodle.com>
Date: Fri, 16 Jul 2021 21:08:36 +1000
Subject: [PATCH] MDL-71240 filter_tex: Sanitize the whole latex document

LaTeX documents have a preamble section and admins can use a \newcommand
statement to define new commands there (or to give an alias to another
command). This commit makes sure no blocked command can escape
sanitization by being used in a new seemingly harmless command that is
defined in the LaTeX preamble.
---
 filter/tex/latex.php | 16 ++++++++--------
 1 file changed, 8 insertions(+), 8 deletions(-)

diff --git a/filter/tex/latex.php b/filter/tex/latex.php
index 9e7f897c673..c23170a8785 100644
--- a/filter/tex/latex.php
+++ b/filter/tex/latex.php
@@ -47,23 +47,23 @@
          * @param int $fontsize the font size
          * @return string the latex document
          */
-        function construct_latex_document( $formula, $fontsize=12 ) {
-            global $CFG;
-
-            $formula = filter_tex_sanitize_formula($formula);
-
+        function construct_latex_document($formula, $fontsize = 12) {
             // $fontsize don't affects to formula's size. $density can change size
-            $doc =  "\\documentclass[{$fontsize}pt]{article}\n";
+            $doc = "\\documentclass[{$fontsize}pt]{article}\n";
             $doc .= get_config('filter_tex', 'latexpreamble');
             $doc .= "\\pagestyle{empty}\n";
             $doc .= "\\begin{document}\n";
-//dlnsk            $doc .= "$ {$formula} $\n";
-            if (preg_match("/^[[:space:]]*\\\\begin\\{(gather|align|alignat|multline).?\\}/i",$formula)) {
+            if (preg_match("/^[[:space:]]*\\\\begin\\{(gather|align|alignat|multline).?\\}/i", $formula)) {
                $doc .= "$formula\n";
             } else {
                $doc .= "$ {$formula} $\n";
             }
             $doc .= "\\end{document}\n";
+
+            // Sanitize the whole document (rather than just the formula) to make sure no one can bypass sanitization
+            // by using \newcommand in preamble to give an alias to a blocked command.
+            $doc = filter_tex_sanitize_formula($doc);
+
             return $doc;
         }