25 class TemplateParser {
29 protected $templateDir;
39 protected $forceRecompile =
false;
44 protected $compileFlags;
50 public function __construct( $templateDir =
null, $forceRecompile =
false ) {
51 $this->templateDir = $templateDir ?: __DIR__ .
'/templates';
52 $this->forceRecompile = $forceRecompile;
56 $this->compileFlags = LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_MUSTACHELOOKUP;
63 public function enableRecursivePartials( $enable ) {
65 $this->compileFlags = $this->compileFlags | LightnCandy::FLAG_RUNTIMEPARTIAL;
67 $this->compileFlags = $this->compileFlags & ~LightnCandy::FLAG_RUNTIMEPARTIAL;
77 protected function getTemplateFilename( $templateName ) {
82 strcspn( $templateName,
":/\\\000&<>'\"%" ) !== strlen( $templateName )
84 throw new UnexpectedValueException(
"Malformed \$templateName: $templateName" );
87 return "{$this->templateDir}/{$templateName}.mustache";
96 protected function getTemplate( $templateName ) {
97 $templateKey = $templateName .
'|' . $this->compileFlags;
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}" );
113 $fileContents = file_get_contents( $filename );
116 $fastHash = md5( $this->compileFlags .
'|' . $fileContents );
119 $config = MediaWikiServices::getInstance()->getMainConfig();
120 $secretKey = $config->get(
'SecretKey' );
125 $key =
$cache->makeKey(
'template', $templateName, $fastHash );
130 $keyedHash = substr(
$code, 0, 64 );
132 if ( $keyedHash !== hash_hmac(
'sha256',
$code, $secretKey ) ) {
139 $code = $this->compileForEval( $fileContents, $filename );
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;
165 protected function compileForEval( $fileContents, $filename ) {
167 $code = $this->compile( $fileContents );
170 throw new RuntimeException(
"Could not compile template: {$filename}" );
174 if ( substr(
$code, 0, 5 ) ===
'<?php' ) {
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',
221 public function processTemplate( $templateName,
$args,
array $scopes = [] ) {
222 $template = $this->getTemplate( $templateName );