Merge "Improve docs for Title::getInternalURL/getCanonicalURL"
[lhc/web/wiklou.git] / includes / TemplateParser.php
1 <?php
2 use MediaWiki\MediaWikiServices;
3
4 /**
5 * Handles compiling Mustache templates into PHP rendering functions
6 *
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.
11 *
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.
16 *
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
21 *
22 * @file
23 * @since 1.25
24 */
25 class TemplateParser {
26 /**
27 * @var string The path to the Mustache templates
28 */
29 protected $templateDir;
30
31 /**
32 * @var callable[] Array of cached rendering functions
33 */
34 protected $renderers;
35
36 /**
37 * @var bool Always compile template files
38 */
39 protected $forceRecompile = false;
40
41 /**
42 * @var int Compilation flags passed to LightnCandy
43 */
44 protected $compileFlags;
45
46 /**
47 * @param string|null $templateDir
48 * @param bool $forceRecompile
49 */
50 public function __construct( $templateDir = null, $forceRecompile = false ) {
51 $this->templateDir = $templateDir ?: __DIR__ . '/templates';
52 $this->forceRecompile = $forceRecompile;
53
54 // Do not add more flags here without discussion.
55 // If you do add more flags, be sure to update unit tests as well.
56 $this->compileFlags = LightnCandy::FLAG_ERROR_EXCEPTION | LightnCandy::FLAG_MUSTACHELOOKUP;
57 }
58
59 /**
60 * Enable/disable the use of recursive partials.
61 * @param bool $enable
62 */
63 public function enableRecursivePartials( $enable ) {
64 if ( $enable ) {
65 $this->compileFlags = $this->compileFlags | LightnCandy::FLAG_RUNTIMEPARTIAL;
66 } else {
67 $this->compileFlags = $this->compileFlags & ~LightnCandy::FLAG_RUNTIMEPARTIAL;
68 }
69 }
70
71 /**
72 * Constructs the location of the source Mustache template
73 * @param string $templateName The name of the template
74 * @return string
75 * @throws UnexpectedValueException If $templateName attempts upwards directory traversal
76 */
77 protected function getTemplateFilename( $templateName ) {
78 // Prevent path traversal. Based on Language::isValidCode().
79 // This is for paranoia. The $templateName should never come from
80 // untrusted input.
81 if (
82 strcspn( $templateName, ":/\\\000&<>'\"%" ) !== strlen( $templateName )
83 ) {
84 throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
85 }
86
87 return "{$this->templateDir}/{$templateName}.mustache";
88 }
89
90 /**
91 * Returns a given template function if found, otherwise throws an exception.
92 * @param string $templateName The name of the template (without file suffix)
93 * @return callable
94 * @throws RuntimeException
95 */
96 protected function getTemplate( $templateName ) {
97 $templateKey = $templateName . '|' . $this->compileFlags;
98
99 // If a renderer has already been defined for this template, reuse it
100 if ( isset( $this->renderers[$templateKey] ) &&
101 is_callable( $this->renderers[$templateKey] )
102 ) {
103 return $this->renderers[$templateKey];
104 }
105
106 $filename = $this->getTemplateFilename( $templateName );
107
108 if ( !file_exists( $filename ) ) {
109 throw new RuntimeException( "Could not locate template: {$filename}" );
110 }
111
112 // Read the template file
113 $fileContents = file_get_contents( $filename );
114
115 // Generate a quick hash for cache invalidation
116 $fastHash = md5( $this->compileFlags . '|' . $fileContents );
117
118 // Fetch a secret key for building a keyed hash of the PHP code
119 $config = MediaWikiServices::getInstance()->getMainConfig();
120 $secretKey = $config->get( 'SecretKey' );
121
122 if ( $secretKey ) {
123 // See if the compiled PHP code is stored in cache.
124 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
125 $key = $cache->makeKey( 'template', $templateName, $fastHash );
126 $code = $this->forceRecompile ? null : $cache->get( $key );
127
128 if ( $code ) {
129 // Verify the integrity of the cached PHP code
130 $keyedHash = substr( $code, 0, 64 );
131 $code = substr( $code, 64 );
132 if ( $keyedHash !== hash_hmac( 'sha256', $code, $secretKey ) ) {
133 // If the integrity check fails, don't use the cached code
134 // We'll update the invalid cache below
135 $code = null;
136 }
137 }
138 if ( !$code ) {
139 $code = $this->compileForEval( $fileContents, $filename );
140
141 // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
142 $cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
143 }
144 // If there is no secret key available, don't use cache
145 } else {
146 $code = $this->compileForEval( $fileContents, $filename );
147 }
148
149 $renderer = eval( $code );
150 if ( !is_callable( $renderer ) ) {
151 throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
152 }
153 $this->renderers[$templateKey] = $renderer;
154 return $renderer;
155 }
156
157 /**
158 * Wrapper for compile() function that verifies successful compilation and strips
159 * out the '<?php' part so that the code is ready for eval()
160 * @param string $fileContents Mustache code
161 * @param string $filename Name of the template
162 * @return string PHP code (without '<?php')
163 * @throws RuntimeException
164 */
165 protected function compileForEval( $fileContents, $filename ) {
166 // Compile the template into PHP code
167 $code = $this->compile( $fileContents );
168
169 if ( !$code ) {
170 throw new RuntimeException( "Could not compile template: {$filename}" );
171 }
172
173 // Strip the "<?php" added by lightncandy so that it can be eval()ed
174 if ( substr( $code, 0, 5 ) === '<?php' ) {
175 $code = substr( $code, 5 );
176 }
177
178 return $code;
179 }
180
181 /**
182 * Compile the Mustache code into PHP code using LightnCandy
183 * @param string $code Mustache code
184 * @return string PHP code (with '<?php')
185 * @throws RuntimeException
186 */
187 protected function compile( $code ) {
188 if ( !class_exists( 'LightnCandy' ) ) {
189 throw new RuntimeException( 'LightnCandy class not defined' );
190 }
191 return LightnCandy::compile(
192 $code,
193 [
194 'flags' => $this->compileFlags,
195 'basedir' => $this->templateDir,
196 'fileext' => '.mustache',
197 ]
198 );
199 }
200
201 /**
202 * Returns HTML for a given template by calling the template function with the given args
203 *
204 * @code
205 * echo $templateParser->processTemplate(
206 * 'ExampleTemplate',
207 * [
208 * 'username' => $user->getName(),
209 * 'message' => 'Hello!'
210 * ]
211 * );
212 * @endcode
213 * @param string $templateName The name of the template
214 * @param-taint $templateName exec_misc
215 * @param mixed $args
216 * @param-taint $args none
217 * @param array $scopes
218 * @param-taint $scopes none
219 * @return string
220 */
221 public function processTemplate( $templateName, $args, array $scopes = [] ) {
222 $template = $this->getTemplate( $templateName );
223 return $template( $args, $scopes );
224 }
225 }