Merge "Add 3D filetype for STL files"
[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 * @param string $templateDir
43 * @param bool $forceRecompile
44 */
45 public function __construct( $templateDir = null, $forceRecompile = false ) {
46 $this->templateDir = $templateDir ?: __DIR__ . '/templates';
47 $this->forceRecompile = $forceRecompile;
48 }
49
50 /**
51 * Constructs the location of the the source Mustache template
52 * @param string $templateName The name of the template
53 * @return string
54 * @throws UnexpectedValueException If $templateName attempts upwards directory traversal
55 */
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
69 /**
70 * Returns a given template function if found, otherwise throws an exception.
71 * @param string $templateName The name of the template (without file suffix)
72 * @return callable
73 * @throws RuntimeException
74 */
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.
101 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
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
134 /**
135 * Wrapper for compile() function that verifies successful compilation and strips
136 * out the '<?php' part so that the code is ready for eval()
137 * @param string $fileContents Mustache code
138 * @param string $filename Name of the template
139 * @return string PHP code (without '<?php')
140 * @throws RuntimeException
141 */
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
158 /**
159 * Compile the Mustache code into PHP code using LightnCandy
160 * @param string $code Mustache code
161 * @return string PHP code (with '<?php')
162 * @throws RuntimeException
163 */
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
180 /**
181 * Returns HTML for a given template by calling the template function with the given args
182 *
183 * @code
184 * echo $templateParser->processTemplate(
185 * 'ExampleTemplate',
186 * [
187 * 'username' => $user->getName(),
188 * 'message' => 'Hello!'
189 * ]
190 * );
191 * @endcode
192 * @param string $templateName The name of the template
193 * @param mixed $args
194 * @param array $scopes
195 * @return string
196 */
197 public function processTemplate( $templateName, $args, array $scopes = [] ) {
198 $template = $this->getTemplate( $templateName );
199 return call_user_func( $template, $args, $scopes );
200 }
201 }