Merge "maintenance: Script to rename titles for Unicode uppercasing changes"
[lhc/web/wiklou.git] / includes / TemplateParser.php
1 <?php
2
3 use MediaWiki\MediaWikiServices;
4
5 /**
6 * Handles compiling Mustache templates into PHP rendering functions
7 *
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.
12 *
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.
17 *
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
22 *
23 * @file
24 * @since 1.25
25 */
26 class TemplateParser {
27 /**
28 * @var string The path to the Mustache templates
29 */
30 protected $templateDir;
31
32 /**
33 * @var callable[] Array of cached rendering functions
34 */
35 protected $renderers;
36
37 /**
38 * @var bool Always compile template files
39 */
40 protected $forceRecompile = false;
41
42 /**
43 * @var int Compilation flags passed to LightnCandy
44 */
45 protected $compileFlags;
46
47 /**
48 * @param string|null $templateDir
49 * @param bool $forceRecompile
50 */
51 public function __construct( $templateDir = null, $forceRecompile = false ) {
52 $this->templateDir = $templateDir ?: __DIR__ . '/templates';
53 $this->forceRecompile = $forceRecompile;
54
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;
58 }
59
60 /**
61 * Enable/disable the use of recursive partials.
62 * @param bool $enable
63 */
64 public function enableRecursivePartials( $enable ) {
65 if ( $enable ) {
66 $this->compileFlags |= LightnCandy::FLAG_RUNTIMEPARTIAL;
67 } else {
68 $this->compileFlags &= ~LightnCandy::FLAG_RUNTIMEPARTIAL;
69 }
70 }
71
72 /**
73 * Constructs the location of the source Mustache template
74 * @param string $templateName The name of the template
75 * @return string
76 * @throws UnexpectedValueException If $templateName attempts upwards directory traversal
77 */
78 protected function getTemplateFilename( $templateName ) {
79 // Prevent path traversal. Based on Language::isValidCode().
80 // This is for paranoia. The $templateName should never come from
81 // untrusted input.
82 if (
83 strcspn( $templateName, ":/\\\000&<>'\"%" ) !== strlen( $templateName )
84 ) {
85 throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
86 }
87
88 return "{$this->templateDir}/{$templateName}.mustache";
89 }
90
91 /**
92 * Returns a given template function if found, otherwise throws an exception.
93 * @param string $templateName The name of the template (without file suffix)
94 * @return callable
95 * @throws RuntimeException
96 */
97 protected function getTemplate( $templateName ) {
98 $templateKey = $templateName . '|' . $this->compileFlags;
99
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] )
103 ) {
104 return $this->renderers[$templateKey];
105 }
106
107 $filename = $this->getTemplateFilename( $templateName );
108
109 if ( !file_exists( $filename ) ) {
110 throw new RuntimeException( "Could not locate template: {$filename}" );
111 }
112
113 // Read the template file
114 $fileContents = file_get_contents( $filename );
115
116 // Generate a quick hash for cache invalidation
117 $fastHash = md5( $this->compileFlags . '|' . $fileContents );
118
119 // Fetch a secret key for building a keyed hash of the PHP code
120 $config = MediaWikiServices::getInstance()->getMainConfig();
121 $secretKey = $config->get( 'SecretKey' );
122
123 if ( $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 );
128
129 if ( $code ) {
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
136 $code = null;
137 }
138 }
139 if ( !$code ) {
140 $code = $this->compileForEval( $fileContents, $filename );
141
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 );
144 }
145 // If there is no secret key available, don't use cache
146 } else {
147 $code = $this->compileForEval( $fileContents, $filename );
148 }
149
150 $renderer = eval( $code );
151 if ( !is_callable( $renderer ) ) {
152 throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
153 }
154 $this->renderers[$templateKey] = $renderer;
155 return $renderer;
156 }
157
158 /**
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
165 */
166 protected function compileForEval( $fileContents, $filename ) {
167 // Compile the template into PHP code
168 $code = $this->compile( $fileContents );
169
170 if ( !$code ) {
171 throw new RuntimeException( "Could not compile template: {$filename}" );
172 }
173
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 );
177 }
178
179 return $code;
180 }
181
182 /**
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
187 */
188 protected function compile( $code ) {
189 if ( !class_exists( 'LightnCandy' ) ) {
190 throw new RuntimeException( 'LightnCandy class not defined' );
191 }
192 return LightnCandy::compile(
193 $code,
194 [
195 'flags' => $this->compileFlags,
196 'basedir' => $this->templateDir,
197 'fileext' => '.mustache',
198 ]
199 );
200 }
201
202 /**
203 * Returns HTML for a given template by calling the template function with the given args
204 *
205 * @code
206 * echo $templateParser->processTemplate(
207 * 'ExampleTemplate',
208 * [
209 * 'username' => $user->getName(),
210 * 'message' => 'Hello!'
211 * ]
212 * );
213 * @endcode
214 * @param string $templateName The name of the template
215 * @param-taint $templateName exec_misc
216 * @param mixed $args
217 * @param-taint $args none
218 * @param array $scopes
219 * @param-taint $scopes none
220 * @return string
221 */
222 public function processTemplate( $templateName, $args, array $scopes = [] ) {
223 $template = $this->getTemplate( $templateName );
224 return $template( $args, $scopes );
225 }
226 }