Merge "Explicitly mark HTMLCacheUpdateJob jobs that are recursive for clarity"
[lhc/web/wiklou.git] / includes / TemplateParser.php
1 <?php
2 /**
3 * Handles compiling Mustache templates into PHP rendering functions
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @since 1.25
22 */
23 class TemplateParser {
24 /**
25 * @var string The path to the Mustache templates
26 */
27 protected $templateDir;
28
29 /**
30 * @var callable[] Array of cached rendering functions
31 */
32 protected $renderers;
33
34 /**
35 * @var bool Always compile template files
36 */
37 protected $forceRecompile = false;
38
39 /**
40 * @param string $templateDir
41 * @param boolean $forceRecompile
42 */
43 public function __construct( $templateDir = null, $forceRecompile = false ) {
44 $this->templateDir = $templateDir ? $templateDir : __DIR__ . '/templates';
45 $this->forceRecompile = $forceRecompile;
46 }
47
48 /**
49 * Constructs the location of the the source Mustache template
50 * @param string $templateName The name of the template
51 * @return string
52 * @throws Exception Disallows upwards directory traversal via $templateName
53 */
54 public function getTemplateFilename( $templateName ) {
55 // Prevent upwards directory traversal using same methods as Title::secureAndSplit
56 if (
57 strpos( $templateName, '.' ) !== false &&
58 (
59 $templateName === '.' || $templateName === '..' ||
60 strpos( $templateName, './' ) === 0 ||
61 strpos( $templateName, '../' ) === 0 ||
62 strpos( $templateName, '/./' ) !== false ||
63 strpos( $templateName, '/../' ) !== false ||
64 substr( $templateName, -2 ) === '/.' ||
65 substr( $templateName, -3 ) === '/..'
66 )
67 ) {
68 throw new Exception( "Malformed \$templateName: $templateName" );
69 }
70
71 return "{$this->templateDir}/{$templateName}.mustache";
72 }
73
74 /**
75 * Returns a given template function if found, otherwise throws an exception.
76 * @param string $templateName The name of the template (without file suffix)
77 * @return Function
78 * @throws Exception
79 */
80 public function getTemplate( $templateName ) {
81 // If a renderer has already been defined for this template, reuse it
82 if ( isset( $this->renderers[$templateName] ) ) {
83 return $this->renderers[$templateName];
84 }
85
86 $filename = $this->getTemplateFilename( $templateName );
87
88 if ( !file_exists( $filename ) ) {
89 throw new Exception( "Could not locate template: {$filename}" );
90 }
91
92 // Read the template file
93 $fileContents = file_get_contents( $filename );
94
95 // Generate a quick hash for cache invalidation
96 $fastHash = md5( $fileContents );
97
98 // Fetch a secret key for building a keyed hash of the PHP code
99 $config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
100 $secretKey = $config->get( 'SecretKey' );
101
102 // See if the compiled PHP code is stored in cache.
103 // CACHE_ACCEL throws an exception if no suitable object cache is present, so fall
104 // back to CACHE_ANYTHING.
105 try {
106 $cache = wfGetCache( CACHE_ACCEL );
107 } catch ( Exception $e ) {
108 $cache = wfGetCache( CACHE_ANYTHING );
109 }
110 $key = wfMemcKey( 'template', $templateName, $fastHash );
111 $code = $this->forceRecompile ? null : $cache->get( $key );
112
113 if ( !$code ) {
114 // Compile the template into PHP code
115 $code = self::compile( $fileContents );
116
117 if ( !$code ) {
118 throw new Exception( "Could not compile template: {$filename}" );
119 }
120
121 // Strip the "<?php" added by lightncandy so that it can be eval()ed
122 if ( substr( $code, 0, 5 ) === '<?php' ) {
123 $code = substr( $code, 5 );
124 }
125
126 $renderer = eval( $code );
127
128 // Prefix the code with a keyed hash (64 hex chars) as an integrity check
129 $code = hash_hmac( 'sha256', $code, $secretKey ) . $code;
130
131 // Cache the compiled PHP code
132 $cache->set( $key, $code );
133 } else {
134 // Verify the integrity of the cached PHP code
135 $keyedHash = substr( $code, 0, 64 );
136 $code = substr( $code, 64 );
137 if ( $keyedHash === hash_hmac( 'sha256', $code, $secretKey ) ) {
138 $renderer = eval( $code );
139 } else {
140 throw new Exception( "Template failed integrity check: {$filename}" );
141 }
142 }
143
144 return $this->renderers[$templateName] = $renderer;
145 }
146
147 /**
148 * Compile the Mustache code into PHP code using LightnCandy
149 * @param string $code Mustache code
150 * @return string PHP code
151 * @throws Exception
152 */
153 public static function compile( $code ) {
154 if ( !class_exists( 'LightnCandy' ) ) {
155 throw new Exception( 'LightnCandy class not defined' );
156 }
157 return LightnCandy::compile(
158 $code,
159 array(
160 // Do not add more flags here without discussion.
161 // If you do add more flags, be sure to update unit tests as well.
162 'flags' => LightnCandy::FLAG_ERROR_EXCEPTION
163 )
164 );
165 }
166
167 /**
168 * Returns HTML for a given template by calling the template function with the given args
169 *
170 * @code
171 * echo $templateParser->processTemplate(
172 * 'ExampleTemplate',
173 * array(
174 * 'username' => $user->getName(),
175 * 'message' => 'Hello!'
176 * )
177 * );
178 * @endcode
179 * @param string $templateName The name of the template
180 * @param mixed $args
181 * @param array $scopes
182 * @return string
183 */
184 public function processTemplate( $templateName, $args, array $scopes = array() ) {
185 $template = $this->getTemplate( $templateName );
186 return call_user_func( $template, $args, $scopes );
187 }
188 }