MediaWiki  1.29.2
TemplateParser.php
Go to the documentation of this file.
1 <?php
3 
25 class TemplateParser {
29  protected $templateDir;
30 
34  protected $renderers;
35 
39  protected $forceRecompile = false;
40 
45  public function __construct( $templateDir = null, $forceRecompile = false ) {
46  $this->templateDir = $templateDir ?: __DIR__ . '/templates';
47  $this->forceRecompile = $forceRecompile;
48  }
49 
56  protected function getTemplateFilename( $templateName ) {
57  // Prevent path traversal. Based on Language::isValidCode().
58  // This is for paranoia. The $templateName should never come from
59  // untrusted input.
60  if (
61  strcspn( $templateName, ":/\\\000&<>'\"%" ) !== strlen( $templateName )
62  ) {
63  throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
64  }
65 
66  return "{$this->templateDir}/{$templateName}.mustache";
67  }
68 
75  protected function getTemplate( $templateName ) {
76  // If a renderer has already been defined for this template, reuse it
77  if ( isset( $this->renderers[$templateName] ) &&
78  is_callable( $this->renderers[$templateName] )
79  ) {
80  return $this->renderers[$templateName];
81  }
82 
83  $filename = $this->getTemplateFilename( $templateName );
84 
85  if ( !file_exists( $filename ) ) {
86  throw new RuntimeException( "Could not locate template: {$filename}" );
87  }
88 
89  // Read the template file
90  $fileContents = file_get_contents( $filename );
91 
92  // Generate a quick hash for cache invalidation
93  $fastHash = md5( $fileContents );
94 
95  // Fetch a secret key for building a keyed hash of the PHP code
96  $config = MediaWikiServices::getInstance()->getMainConfig();
97  $secretKey = $config->get( 'SecretKey' );
98 
99  if ( $secretKey ) {
100  // See if the compiled PHP code is stored in cache.
102  $key = $cache->makeKey( 'template', $templateName, $fastHash );
103  $code = $this->forceRecompile ? null : $cache->get( $key );
104 
105  if ( $code ) {
106  // Verify the integrity of the cached PHP code
107  $keyedHash = substr( $code, 0, 64 );
108  $code = substr( $code, 64 );
109  if ( $keyedHash !== hash_hmac( 'sha256', $code, $secretKey ) ) {
110  // If the integrity check fails, don't use the cached code
111  // We'll update the invalid cache below
112  $code = null;
113  }
114  }
115  if ( !$code ) {
116  $code = $this->compileForEval( $fileContents, $filename );
117 
118  // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
119  $cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
120  }
121  // If there is no secret key available, don't use cache
122  } else {
123  $code = $this->compileForEval( $fileContents, $filename );
124  }
125 
126  $renderer = eval( $code );
127  if ( !is_callable( $renderer ) ) {
128  throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
129  }
130  $this->renderers[$templateName] = $renderer;
131  return $renderer;
132  }
133 
142  protected function compileForEval( $fileContents, $filename ) {
143  // Compile the template into PHP code
144  $code = $this->compile( $fileContents );
145 
146  if ( !$code ) {
147  throw new RuntimeException( "Could not compile template: {$filename}" );
148  }
149 
150  // Strip the "<?php" added by lightncandy so that it can be eval()ed
151  if ( substr( $code, 0, 5 ) === '<?php' ) {
152  $code = substr( $code, 5 );
153  }
154 
155  return $code;
156  }
157 
164  protected function compile( $code ) {
165  if ( !class_exists( 'LightnCandy' ) ) {
166  throw new RuntimeException( 'LightnCandy class not defined' );
167  }
168  return LightnCandy::compile(
169  $code,
170  [
171  // Do not add more flags here without discussion.
172  // If you do add more flags, be sure to update unit tests as well.
173  'flags' => LightnCandy::FLAG_ERROR_EXCEPTION,
174  'basedir' => $this->templateDir,
175  'fileext' => '.mustache',
176  ]
177  );
178  }
179 
197  public function processTemplate( $templateName, $args, array $scopes = [] ) {
198  $template = $this->getTemplate( $templateName );
199  return call_user_func( $template, $args, $scopes );
200  }
201 }
$template
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping $template
Definition: hooks.txt:783
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
CACHE_ANYTHING
const CACHE_ANYTHING
Definition: Defines.php:99
$args
if( $line===false) $args
Definition: cdb.php:63
$cache
$cache
Definition: mcc.php:33
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:783
MediaWikiServices
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
Definition: injection.txt:23
array
the array() calling protocol came about after MediaWiki 1.4rc1.
ObjectCache\getLocalServerInstance
static getLocalServerInstance( $fallback=CACHE_NONE)
Factory function for CACHE_ACCEL (referenced from DefaultSettings.php)
Definition: ObjectCache.php:288