Merge "Add CollationFa"
[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 upwards directory traversal using same methods as Title::secureAndSplit
58 if (
59 strpos( $templateName, '.' ) !== false &&
60 (
61 $templateName === '.' || $templateName === '..' ||
62 strpos( $templateName, './' ) === 0 ||
63 strpos( $templateName, '../' ) === 0 ||
64 strpos( $templateName, '/./' ) !== false ||
65 strpos( $templateName, '/../' ) !== false ||
66 substr( $templateName, -2 ) === '/.' ||
67 substr( $templateName, -3 ) === '/..'
68 )
69 ) {
70 throw new UnexpectedValueException( "Malformed \$templateName: $templateName" );
71 }
72
73 return "{$this->templateDir}/{$templateName}.mustache";
74 }
75
76 /**
77 * Returns a given template function if found, otherwise throws an exception.
78 * @param string $templateName The name of the template (without file suffix)
79 * @return callable
80 * @throws RuntimeException
81 */
82 protected function getTemplate( $templateName ) {
83 // If a renderer has already been defined for this template, reuse it
84 if ( isset( $this->renderers[$templateName] ) &&
85 is_callable( $this->renderers[$templateName] )
86 ) {
87 return $this->renderers[$templateName];
88 }
89
90 $filename = $this->getTemplateFilename( $templateName );
91
92 if ( !file_exists( $filename ) ) {
93 throw new RuntimeException( "Could not locate template: {$filename}" );
94 }
95
96 // Read the template file
97 $fileContents = file_get_contents( $filename );
98
99 // Generate a quick hash for cache invalidation
100 $fastHash = md5( $fileContents );
101
102 // Fetch a secret key for building a keyed hash of the PHP code
103 $config = MediaWikiServices::getInstance()->getMainConfig();
104 $secretKey = $config->get( 'SecretKey' );
105
106 if ( $secretKey ) {
107 // See if the compiled PHP code is stored in cache.
108 $cache = ObjectCache::getLocalServerInstance( CACHE_ANYTHING );
109 $key = $cache->makeKey( 'template', $templateName, $fastHash );
110 $code = $this->forceRecompile ? null : $cache->get( $key );
111
112 if ( !$code ) {
113 $code = $this->compileForEval( $fileContents, $filename );
114
115 // Prefix the cached code with a keyed hash (64 hex chars) as an integrity check
116 $cache->set( $key, hash_hmac( 'sha256', $code, $secretKey ) . $code );
117 } else {
118 // Verify the integrity of the cached PHP code
119 $keyedHash = substr( $code, 0, 64 );
120 $code = substr( $code, 64 );
121 if ( $keyedHash !== hash_hmac( 'sha256', $code, $secretKey ) ) {
122 // Generate a notice if integrity check fails
123 trigger_error( "Template failed integrity check: {$filename}" );
124 }
125 }
126 // If there is no secret key available, don't use cache
127 } else {
128 $code = $this->compileForEval( $fileContents, $filename );
129 }
130
131 $renderer = eval( $code );
132 if ( !is_callable( $renderer ) ) {
133 throw new RuntimeException( "Requested template, {$templateName}, is not callable" );
134 }
135 $this->renderers[$templateName] = $renderer;
136 return $renderer;
137 }
138
139 /**
140 * Wrapper for compile() function that verifies successful compilation and strips
141 * out the '<?php' part so that the code is ready for eval()
142 * @param string $fileContents Mustache code
143 * @param string $filename Name of the template
144 * @return string PHP code (without '<?php')
145 * @throws RuntimeException
146 */
147 protected function compileForEval( $fileContents, $filename ) {
148 // Compile the template into PHP code
149 $code = $this->compile( $fileContents );
150
151 if ( !$code ) {
152 throw new RuntimeException( "Could not compile template: {$filename}" );
153 }
154
155 // Strip the "<?php" added by lightncandy so that it can be eval()ed
156 if ( substr( $code, 0, 5 ) === '<?php' ) {
157 $code = substr( $code, 5 );
158 }
159
160 return $code;
161 }
162
163 /**
164 * Compile the Mustache code into PHP code using LightnCandy
165 * @param string $code Mustache code
166 * @return string PHP code (with '<?php')
167 * @throws RuntimeException
168 */
169 protected function compile( $code ) {
170 if ( !class_exists( 'LightnCandy' ) ) {
171 throw new RuntimeException( 'LightnCandy class not defined' );
172 }
173 return LightnCandy::compile(
174 $code,
175 [
176 // Do not add more flags here without discussion.
177 // If you do add more flags, be sure to update unit tests as well.
178 'flags' => LightnCandy::FLAG_ERROR_EXCEPTION,
179 'basedir' => $this->templateDir,
180 'fileext' => '.mustache',
181 ]
182 );
183 }
184
185 /**
186 * Returns HTML for a given template by calling the template function with the given args
187 *
188 * @code
189 * echo $templateParser->processTemplate(
190 * 'ExampleTemplate',
191 * [
192 * 'username' => $user->getName(),
193 * 'message' => 'Hello!'
194 * ]
195 * );
196 * @endcode
197 * @param string $templateName The name of the template
198 * @param mixed $args
199 * @param array $scopes
200 * @return string
201 */
202 public function processTemplate( $templateName, $args, array $scopes = [] ) {
203 $template = $this->getTemplate( $templateName );
204 return call_user_func( $template, $args, $scopes );
205 }
206 }