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 // Do not add more flags here without discussion.
45 // If you do add more flags, be sure to update unit tests as well.
46 protected $compileFlags = LightnCandy
::FLAG_ERROR_EXCEPTION
;
49 * @param string $templateDir
50 * @param bool $forceRecompile
52 public function __construct( $templateDir = null, $forceRecompile = false ) {
53 $this->templateDir
= $templateDir ?
: __DIR__
. '/templates';
54 $this->forceRecompile
= $forceRecompile;
58 * Enable/disable the use of recursive partials.
61 public function enableRecursivePartials( $enable ) {
63 $this->compileFlags
= $this->compileFlags | LightnCandy
::FLAG_RUNTIMEPARTIAL
;
65 $this->compileFlags
= $this->compileFlags
& ~LightnCandy
::FLAG_RUNTIMEPARTIAL
;
70 * Constructs the location of the the source Mustache template
71 * @param string $templateName The name of the template
73 * @throws UnexpectedValueException If $templateName attempts upwards directory traversal
75 protected function getTemplateFilename( $templateName ) {
76 // Prevent path traversal. Based on Language::isValidCode().
77 // This is for paranoia. The $templateName should never come from
80 strcspn( $templateName, ":/\\\000&<>'\"%" ) !== strlen( $templateName )
82 throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
85 return "{$this->templateDir}/{$templateName}.mustache";
89 * Returns a given template function if found, otherwise throws an exception.
90 * @param string $templateName The name of the template (without file suffix)
92 * @throws RuntimeException
94 protected function getTemplate( $templateName ) {
95 $templateKey = $templateName . '|' . $this->compileFlags
;
97 // If a renderer has already been defined for this template, reuse it
98 if ( isset( $this->renderers
[$templateKey] ) &&
99 is_callable( $this->renderers
[$templateKey] )
101 return $this->renderers
[$templateKey];
104 $filename = $this->getTemplateFilename( $templateName );
106 if ( !file_exists( $filename ) ) {
107 throw new RuntimeException( "Could not locate template: {$filename}" );
110 // Read the template file
111 $fileContents = file_get_contents( $filename );
113 // Generate a quick hash for cache invalidation
114 $fastHash = md5( $this->compileFlags
. '|' . $fileContents );
116 // Fetch a secret key for building a keyed hash of the PHP code
117 $config = MediaWikiServices
::getInstance()->getMainConfig();
118 $secretKey = $config->get( 'SecretKey' );
121 // See if the compiled PHP code is stored in cache.
122 $cache = ObjectCache
::getLocalServerInstance( CACHE_ANYTHING
);
123 $key = $cache->makeKey( 'template', $templateName, $fastHash );
124 $code = $this->forceRecompile ?
null : $cache->get( $key );
127 // Verify the integrity of the cached PHP code
128 $keyedHash = substr( $code, 0, 64 );
129 $code = substr( $code, 64 );
130 if ( $keyedHash !== hash_hmac( 'sha256', $code, $secretKey ) ) {
131 // If the integrity check fails, don't use the cached code
132 // We'll update the invalid cache below
137 $code = $this->compileForEval( $fileContents, $filename );
139 // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
140 $cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
142 // If there is no secret key available, don't use cache
144 $code = $this->compileForEval( $fileContents, $filename );
147 $renderer = eval( $code );
148 if ( !is_callable( $renderer ) ) {
149 throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
151 $this->renderers
[$templateKey] = $renderer;
156 * Wrapper for compile() function that verifies successful compilation and strips
157 * out the '<?php' part so that the code is ready for eval()
158 * @param string $fileContents Mustache code
159 * @param string $filename Name of the template
160 * @return string PHP code (without '<?php')
161 * @throws RuntimeException
163 protected function compileForEval( $fileContents, $filename ) {
164 // Compile the template into PHP code
165 $code = $this->compile( $fileContents );
168 throw new RuntimeException( "Could not compile template: {$filename}" );
171 // Strip the "<?php" added by lightncandy so that it can be eval()ed
172 if ( substr( $code, 0, 5 ) === '<?php' ) {
173 $code = substr( $code, 5 );
180 * Compile the Mustache code into PHP code using LightnCandy
181 * @param string $code Mustache code
182 * @return string PHP code (with '<?php')
183 * @throws RuntimeException
185 protected function compile( $code ) {
186 if ( !class_exists( 'LightnCandy' ) ) {
187 throw new RuntimeException( 'LightnCandy class not defined' );
189 return LightnCandy
::compile(
192 'flags' => $this->compileFlags
,
193 'basedir' => $this->templateDir
,
194 'fileext' => '.mustache',
200 * Returns HTML for a given template by calling the template function with the given args
203 * echo $templateParser->processTemplate(
206 * 'username' => $user->getName(),
207 * 'message' => 'Hello!'
211 * @param string $templateName The name of the template
213 * @param array $scopes
216 public function processTemplate( $templateName, $args, array $scopes = [] ) {
217 $template = $this->getTemplate( $templateName );
218 return call_user_func( $template, $args, $scopes );