3 use MediaWiki\MediaWikiServices
;
6 * Handles compiling Mustache templates into PHP rendering functions
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 class TemplateParser
{
28 * @var string The path to the Mustache templates
30 protected $templateDir;
33 * @var callable[] Array of cached rendering functions
38 * @var bool Always compile template files
40 protected $forceRecompile = false;
43 * @var int Compilation flags passed to LightnCandy
45 protected $compileFlags;
48 * @param string|null $templateDir
49 * @param bool $forceRecompile
51 public function __construct( $templateDir = null, $forceRecompile = false ) {
52 $this->templateDir
= $templateDir ?
: __DIR__
. '/templates';
53 $this->forceRecompile
= $forceRecompile;
55 // Do not add more flags here without discussion.
56 // If you do add more flags, be sure to update unit tests as well.
57 $this->compileFlags
= LightnCandy
::FLAG_ERROR_EXCEPTION | LightnCandy
::FLAG_MUSTACHELOOKUP
;
61 * Enable/disable the use of recursive partials.
64 public function enableRecursivePartials( $enable ) {
66 $this->compileFlags |
= LightnCandy
::FLAG_RUNTIMEPARTIAL
;
68 $this->compileFlags
&= ~LightnCandy
::FLAG_RUNTIMEPARTIAL
;
73 * Constructs the location of the source Mustache template
74 * @param string $templateName The name of the template
76 * @throws UnexpectedValueException If $templateName attempts upwards directory traversal
78 protected function getTemplateFilename( $templateName ) {
79 // Prevent path traversal. Based on Language::isValidCode().
80 // This is for paranoia. The $templateName should never come from
83 strcspn( $templateName, ":/\\\000&<>'\"%" ) !== strlen( $templateName )
85 throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
88 return "{$this->templateDir}/{$templateName}.mustache";
92 * Returns a given template function if found, otherwise throws an exception.
93 * @param string $templateName The name of the template (without file suffix)
95 * @throws RuntimeException
97 protected function getTemplate( $templateName ) {
98 $templateKey = $templateName . '|' . $this->compileFlags
;
100 // If a renderer has already been defined for this template, reuse it
101 if ( isset( $this->renderers
[$templateKey] ) &&
102 is_callable( $this->renderers
[$templateKey] )
104 return $this->renderers
[$templateKey];
107 $filename = $this->getTemplateFilename( $templateName );
109 if ( !file_exists( $filename ) ) {
110 throw new RuntimeException( "Could not locate template: {$filename}" );
113 // Read the template file
114 $fileContents = file_get_contents( $filename );
116 // Generate a quick hash for cache invalidation
117 $fastHash = md5( $this->compileFlags
. '|' . $fileContents );
119 // Fetch a secret key for building a keyed hash of the PHP code
120 $config = MediaWikiServices
::getInstance()->getMainConfig();
121 $secretKey = $config->get( 'SecretKey' );
124 // See if the compiled PHP code is stored in cache.
125 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
126 $key = $cache->makeKey( 'template', $templateName, $fastHash );
127 $code = $this->forceRecompile ?
null : $cache->get( $key );
130 // Verify the integrity of the cached PHP code
131 $keyedHash = substr( $code, 0, 64 );
132 $code = substr( $code, 64 );
133 if ( $keyedHash !== hash_hmac( 'sha256', $code, $secretKey ) ) {
134 // If the integrity check fails, don't use the cached code
135 // We'll update the invalid cache below
140 $code = $this->compileForEval( $fileContents, $filename );
142 // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
143 $cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
145 // If there is no secret key available, don't use cache
147 $code = $this->compileForEval( $fileContents, $filename );
150 $renderer = eval( $code );
151 if ( !is_callable( $renderer ) ) {
152 throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
154 $this->renderers
[$templateKey] = $renderer;
159 * Wrapper for compile() function that verifies successful compilation and strips
160 * out the '<?php' part so that the code is ready for eval()
161 * @param string $fileContents Mustache code
162 * @param string $filename Name of the template
163 * @return string PHP code (without '<?php')
164 * @throws RuntimeException
166 protected function compileForEval( $fileContents, $filename ) {
167 // Compile the template into PHP code
168 $code = $this->compile( $fileContents );
171 throw new RuntimeException( "Could not compile template: {$filename}" );
174 // Strip the "<?php" added by lightncandy so that it can be eval()ed
175 if ( substr( $code, 0, 5 ) === '<?php' ) {
176 $code = substr( $code, 5 );
183 * Compile the Mustache code into PHP code using LightnCandy
184 * @param string $code Mustache code
185 * @return string PHP code (with '<?php')
186 * @throws RuntimeException
188 protected function compile( $code ) {
189 if ( !class_exists( 'LightnCandy' ) ) {
190 throw new RuntimeException( 'LightnCandy class not defined' );
192 return LightnCandy
::compile(
195 'flags' => $this->compileFlags
,
196 'basedir' => $this->templateDir
,
197 'fileext' => '.mustache',
203 * Returns HTML for a given template by calling the template function with the given args
206 * echo $templateParser->processTemplate(
209 * 'username' => $user->getName(),
210 * 'message' => 'Hello!'
214 * @param string $templateName The name of the template
215 * @param-taint $templateName exec_misc
217 * @param-taint $args none
218 * @param array $scopes
219 * @param-taint $scopes none
222 public function processTemplate( $templateName, $args, array $scopes = [] ) {
223 $template = $this->getTemplate( $templateName );
224 return $template( $args, $scopes );