Merge "Fix the Rubocop offense SpaceInsideHashLiteralBraces"
[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 */
22 class TemplateParser {
23 /**
24 * @var string The path to the Mustache templates
25 */
26 protected $templateDir;
27
28 /**
29 * @var callable[] Array of cached rendering functions
30 */
31 protected $renderers;
32
33 /**
34 * @var bool Always compile template files
35 */
36 protected $forceRecompile = false;
37
38 /**
39 * @param string $templateDir
40 * @param boolean $forceRecompile
41 */
42 public function __construct( $templateDir = null, $forceRecompile = false ) {
43 $this->templateDir = $templateDir ? $templateDir : __DIR__.'/templates';
44 $this->forceRecompile = $forceRecompile;
45 }
46
47 /**
48 * Constructs the location of the the source Mustache template
49 * @param string $templateName The name of the template
50 * @return string
51 * @throws Exception Disallows upwards directory traversal via $templateName
52 */
53 public function getTemplateFilename( $templateName ) {
54 // Prevent upwards directory traversal using same methods as Title::secureAndSplit
55 if (
56 strpos( $templateName, '.' ) !== false &&
57 (
58 $templateName === '.' || $templateName === '..' ||
59 strpos( $templateName, './' ) === 0 ||
60 strpos( $templateName, '../' ) === 0 ||
61 strpos( $templateName, '/./' ) !== false ||
62 strpos( $templateName, '/../' ) !== false ||
63 substr( $templateName, -2 ) === '/.' ||
64 substr( $templateName, -3 ) === '/..'
65 )
66 ) {
67 throw new Exception( "Malformed \$templateName: $templateName" );
68 }
69
70 return "{$this->templateDir}/{$templateName}.mustache";
71 }
72
73 /**
74 * Returns a given template function if found, otherwise throws an exception.
75 * @param string $templateName The name of the template (without file suffix)
76 * @return Function
77 * @throws Exception
78 */
79 public function getTemplate( $templateName ) {
80 global $wgSecretKey;
81
82 // If a renderer has already been defined for this template, reuse it
83 if ( isset( $this->renderers[$templateName] ) ) {
84 return $this->renderers[$templateName];
85 }
86
87 $filename = $this->getTemplateFilename( $templateName );
88
89 if ( !file_exists( $filename ) ) {
90 throw new Exception( "Could not locate template: {$filename}" );
91 }
92
93 // Read the template file
94 $fileContents = file_get_contents( $filename );
95
96 // Generate a quick hash for cache invalidation
97 $fastHash = md5( $fileContents );
98
99 // See if the compiled PHP code is stored in cache.
100 // CACHE_ACCEL throws an exception if no suitable object cache is present, so fall
101 // back to CACHE_ANYTHING.
102 try {
103 $cache = wfGetCache( CACHE_ACCEL );
104 } catch ( Exception $e ) {
105 $cache = wfGetCache( CACHE_ANYTHING );
106 }
107 $key = wfMemcKey( 'template', $templateName, $fastHash );
108 $code = $this->forceRecompile ? null : $cache->get( $key );
109
110 if ( !$code ) {
111 // Compile the template into PHP code
112 $code = self::compile( $fileContents );
113
114 if ( !$code ) {
115 throw new Exception( "Could not compile template: {$filename}" );
116 }
117
118 // Strip the "<?php" added by lightncandy so that it can be eval()ed
119 if ( substr( $code, 0, 5 ) === '<?php' ) {
120 $code = substr( $code, 5 );
121 }
122
123 $renderer = eval( $code );
124
125 // Prefix the code with a keyed hash (64 hex chars) as an integrity check
126 $code = hash_hmac( 'sha256', $code, $wgSecretKey ) . $code;
127
128 // Cache the compiled PHP code
129 $cache->set( $key, $code );
130 } else {
131 // Verify the integrity of the cached PHP code
132 $keyedHash = substr( $code, 0, 64 );
133 $code = substr( $code, 64 );
134 if ( $keyedHash === hash_hmac( 'sha256', $code, $wgSecretKey ) ) {
135 $renderer = eval( $code );
136 } else {
137 throw new Exception( "Template failed integrity check: {$filename}" );
138 }
139 }
140
141 return $this->renderers[$templateName] = $renderer;
142 }
143
144 /**
145 * Compile the Mustache code into PHP code using LightnCandy
146 * @param string $code Mustache code
147 * @return string PHP code
148 * @throws Exception
149 */
150 public static function compile( $code ) {
151 if ( !class_exists( 'LightnCandy' ) ) {
152 throw new Exception( 'LightnCandy class not defined' );
153 }
154 return LightnCandy::compile(
155 $code,
156 array(
157 // Do not add more flags here without discussion.
158 // If you do add more flags, be sure to update unit tests as well.
159 'flags' => LightnCandy::FLAG_ERROR_EXCEPTION
160 )
161 );
162 }
163
164 /**
165 * Returns HTML for a given template by calling the template function with the given args
166 * @param string $templateName The name of the template
167 * @param mixed $args
168 * @param array $scopes
169 * @return string
170 */
171 public function processTemplate( $templateName, $args, array $scopes = array() ) {
172 $template = $this->getTemplate( $templateName );
173 return call_user_func( $template, $args, $scopes );
174 }
175 }