2 use MediaWiki\MediaWikiServices
;
5 * Handles compiling Mustache templates into PHP rendering functions
7 * This program is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 2 of the License, or
10 * (at your option) any later version.
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License along
18 * with this program; if not, write to the Free Software Foundation, Inc.,
19 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
20 * http://www.gnu.org/copyleft/gpl.html
25 class TemplateParser
{
27 * @var string The path to the Mustache templates
29 protected $templateDir;
32 * @var callable[] Array of cached rendering functions
37 * @var bool Always compile template files
39 protected $forceRecompile = false;
42 * @var int Compilation flags passed to LightnCandy
44 protected $compileFlags;
47 * @param string|null $templateDir
48 * @param bool $forceRecompile
50 public function __construct( $templateDir = null, $forceRecompile = false ) {
51 $this->templateDir
= $templateDir ?
: __DIR__
. '/templates';
52 $this->forceRecompile
= $forceRecompile;
54 // Do not add more flags here without discussion.
55 // If you do add more flags, be sure to update unit tests as well.
56 $this->compileFlags
= LightnCandy
::FLAG_ERROR_EXCEPTION | LightnCandy
::FLAG_MUSTACHELOOKUP
;
60 * Enable/disable the use of recursive partials.
63 public function enableRecursivePartials( $enable ) {
65 $this->compileFlags
= $this->compileFlags | LightnCandy
::FLAG_RUNTIMEPARTIAL
;
67 $this->compileFlags
= $this->compileFlags
& ~LightnCandy
::FLAG_RUNTIMEPARTIAL
;
72 * Constructs the location of the source Mustache template
73 * @param string $templateName The name of the template
75 * @throws UnexpectedValueException If $templateName attempts upwards directory traversal
77 protected function getTemplateFilename( $templateName ) {
78 // Prevent path traversal. Based on Language::isValidCode().
79 // This is for paranoia. The $templateName should never come from
82 strcspn( $templateName, ":/\\\000&<>'\"%" ) !== strlen( $templateName )
84 throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
87 return "{$this->templateDir}/{$templateName}.mustache";
91 * Returns a given template function if found, otherwise throws an exception.
92 * @param string $templateName The name of the template (without file suffix)
94 * @throws RuntimeException
96 protected function getTemplate( $templateName ) {
97 $templateKey = $templateName . '|' . $this->compileFlags
;
99 // If a renderer has already been defined for this template, reuse it
100 if ( isset( $this->renderers
[$templateKey] ) &&
101 is_callable( $this->renderers
[$templateKey] )
103 return $this->renderers
[$templateKey];
106 $filename = $this->getTemplateFilename( $templateName );
108 if ( !file_exists( $filename ) ) {
109 throw new RuntimeException( "Could not locate template: {$filename}" );
112 // Read the template file
113 $fileContents = file_get_contents( $filename );
115 // Generate a quick hash for cache invalidation
116 $fastHash = md5( $this->compileFlags
. '|' . $fileContents );
118 // Fetch a secret key for building a keyed hash of the PHP code
119 $config = MediaWikiServices
::getInstance()->getMainConfig();
120 $secretKey = $config->get( 'SecretKey' );
123 // See if the compiled PHP code is stored in cache.
124 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
125 $key = $cache->makeKey( 'template', $templateName, $fastHash );
126 $code = $this->forceRecompile ?
null : $cache->get( $key );
129 // Verify the integrity of the cached PHP code
130 $keyedHash = substr( $code, 0, 64 );
131 $code = substr( $code, 64 );
132 if ( $keyedHash !== hash_hmac( 'sha256', $code, $secretKey ) ) {
133 // If the integrity check fails, don't use the cached code
134 // We'll update the invalid cache below
139 $code = $this->compileForEval( $fileContents, $filename );
141 // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
142 $cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
144 // If there is no secret key available, don't use cache
146 $code = $this->compileForEval( $fileContents, $filename );
149 $renderer = eval( $code );
150 if ( !is_callable( $renderer ) ) {
151 throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
153 $this->renderers
[$templateKey] = $renderer;
158 * Wrapper for compile() function that verifies successful compilation and strips
159 * out the '<?php' part so that the code is ready for eval()
160 * @param string $fileContents Mustache code
161 * @param string $filename Name of the template
162 * @return string PHP code (without '<?php')
163 * @throws RuntimeException
165 protected function compileForEval( $fileContents, $filename ) {
166 // Compile the template into PHP code
167 $code = $this->compile( $fileContents );
170 throw new RuntimeException( "Could not compile template: {$filename}" );
173 // Strip the "<?php" added by lightncandy so that it can be eval()ed
174 if ( substr( $code, 0, 5 ) === '<?php' ) {
175 $code = substr( $code, 5 );
182 * Compile the Mustache code into PHP code using LightnCandy
183 * @param string $code Mustache code
184 * @return string PHP code (with '<?php')
185 * @throws RuntimeException
187 protected function compile( $code ) {
188 if ( !class_exists( 'LightnCandy' ) ) {
189 throw new RuntimeException( 'LightnCandy class not defined' );
191 return LightnCandy
::compile(
194 'flags' => $this->compileFlags
,
195 'basedir' => $this->templateDir
,
196 'fileext' => '.mustache',
202 * Returns HTML for a given template by calling the template function with the given args
205 * echo $templateParser->processTemplate(
208 * 'username' => $user->getName(),
209 * 'message' => 'Hello!'
213 * @param string $templateName The name of the template
214 * @param-taint $templateName exec_misc
216 * @param-taint $args none
217 * @param array $scopes
218 * @param-taint $scopes none
221 public function processTemplate( $templateName, $args, array $scopes = [] ) {
222 $template = $this->getTemplate( $templateName );
223 return call_user_func( $template, $args, $scopes );