MDL-40889 prevent 304 when minimising JS
[moodle.git] / lib / jslib.php
CommitLineData
8ab29743
PS
1<?php
2// This file is part of Moodle - http://moodle.org/
3//
4// Moodle is free software: you can redistribute it and/or modify
5// it under the terms of the GNU General Public License as published by
6// the Free Software Foundation, either version 3 of the License, or
7// (at your option) any later version.
8//
9// Moodle is distributed in the hope that it will be useful,
10// but WITHOUT ANY WARRANTY; without even the implied warranty of
11// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12// GNU General Public License for more details.
13//
14// You should have received a copy of the GNU General Public License
15// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
16
17/**
18 * This file contains various javascript related functions,
19 * all functions here are self contained and can be used in ABORT_AFTER_CONFIG scripts.
20 *
21 * @package core_lib
22 * @copyright 2012 Petr Skoda (skodak) {@link http://skodak.org}
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24 */
25
26//NOTE: do not verify MOODLE_INTERNAL here, this is used from themes too
27
28/**
29 * Send javascript file content with as much caching as possible
30 * @param string $jspath
31 * @param string $etag
32 * @param string $filename
33 */
34function js_send_cached($jspath, $etag, $filename = 'javascript.php') {
35 require(__DIR__ . '/xsendfilelib.php');
36
37 $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
38
16b143ef 39 header('Etag: "'.$etag.'"');
8ab29743
PS
40 header('Content-Disposition: inline; filename="'.$filename.'"');
41 header('Last-Modified: '. gmdate('D, d M Y H:i:s', filemtime($jspath)) .' GMT');
42 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
43 header('Pragma: ');
44 header('Cache-Control: public, max-age='.$lifetime);
45 header('Accept-Ranges: none');
46 header('Content-Type: application/javascript; charset=utf-8');
47
48 if (xsendfile($jspath)) {
49 die;
50 }
51
52 if (!min_enable_zlib_compression()) {
53 header('Content-Length: '.filesize($jspath));
54 }
55
56 readfile($jspath);
57 die;
58}
59
60/**
61 * Send javascript without any caching
62 * @param string $js
63 * @param string $filename
64 */
65function js_send_uncached($js, $filename = 'javascript.php') {
66 header('Content-Disposition: inline; filename="'.$filename.'"');
67 header('Last-Modified: '. gmdate('D, d M Y H:i:s', time()) .' GMT');
68 header('Expires: '. gmdate('D, d M Y H:i:s', time() + 2) .' GMT');
69 header('Pragma: ');
70 header('Accept-Ranges: none');
71 header('Content-Type: application/javascript; charset=utf-8');
72 header('Content-Length: '.strlen($js));
73
74 echo $js;
75 die;
76}
77
78/**
79 * Send file not modified headers
80 * @param int $lastmodified
81 * @param string $etag
82 */
83function js_send_unmodified($lastmodified, $etag) {
84 $lifetime = 60*60*24*60; // 60 days only - the revision may get incremented quite often
85 header('HTTP/1.1 304 Not Modified');
86 header('Expires: '. gmdate('D, d M Y H:i:s', time() + $lifetime) .' GMT');
87 header('Cache-Control: public, max-age='.$lifetime);
88 header('Content-Type: application/javascript; charset=utf-8');
16b143ef 89 header('Etag: "'.$etag.'"');
8ab29743
PS
90 if ($lastmodified) {
91 header('Last-Modified: '. gmdate('D, d M Y H:i:s', $lastmodified) .' GMT');
92 }
93 die;
94}
95
96/**
97 * Minify javascript files
98 * @param array $files
99 * @return string
100 */
101function js_minify($files) {
102 // setup include path
103 set_include_path(__DIR__ . '/minify/lib' . PATH_SEPARATOR . get_include_path());
104 require_once('Minify.php');
105
106 if (empty($files)) {
107 return '';
108 }
109
ef7c73d5
PS
110 // We do not really want any 304 here!
111 // There does not seem to be any better way to prevent them here.
112 unset($_SERVER['HTTP_IF_NONE_MATCH']);
113 unset($_SERVER['HTTP_IF_MODIFIED_SINCE']);
114
8ab29743
PS
115 if (0 === stripos(PHP_OS, 'win')) {
116 Minify::setDocRoot(); // IIS may need help
117 }
118 // disable all caching, we do it in moodle
119 Minify::setCache(null, false);
120
121 $options = array(
122 'bubbleCssImports' => false,
123 // Don't gzip content we just want text for storage
124 'encodeOutput' => false,
125 // Maximum age to cache, not used but required
126 'maxAge' => 1800,
127 // The files to minify
128 'files' => $files,
129 // Turn orr URI rewriting
130 'rewriteCssUris' => false,
131 // This returns the CSS rather than echoing it for display
132 'quiet' => true
133 );
134
135 $error = 'unknown';
136 try {
137 $result = Minify::serve('Files', $options);
ef7c73d5 138 if ($result['success'] and $result['statusCode'] == 200) {
8ab29743
PS
139 return $result['content'];
140 }
141 } catch (Exception $e) {
142 $error = $e->getMessage();
143 $error = str_replace("\r", ' ', $error);
144 $error = str_replace("\n", ' ', $error);
145 }
146
147 // minification failed - try to inform the theme developer and include the non-minified version
148 $js = <<<EOD
149try {console.log('Error: Minimisation of javascript failed!');} catch (e) {}
150
151// Error: $error
152// Problem detected during javascript minimisation, please review the following code
153// =================================================================================
154
155
156EOD;
157 foreach ($files as $jsfile) {
158 $js .= file_get_contents($jsfile)."\n";
159 }
160 return $js;
161}
979d3207
PS
162
163/**
164 * Create cache file for JS content
165 * @param string $file full file path to cache file
166 * @param string $content JS code
167 */
168function js_write_cache_file_content($file, $content) {
169 global $CFG;
170
171 clearstatcache();
172 if (!file_exists(dirname($file))) {
173 @mkdir(dirname($file), $CFG->directorypermissions, true);
174 }
175
176 // Prevent serving of incomplete file from concurrent request,
177 // the rename() should be more atomic than fwrite().
178 ignore_user_abort(true);
179 if ($fp = fopen($file.'.tmp', 'xb')) {
180 fwrite($fp, $content);
181 fclose($fp);
182 rename($file.'.tmp', $file);
183 @chmod($file, $CFG->filepermissions);
184 @unlink($file.'.tmp'); // just in case anything fails
185 }
186 ignore_user_abort(false);
187 if (connection_aborted()) {
188 die;
189 }
190}
191
192/**
193 * Sends a 404 message about CSS not being found.
194 */
195function js_send_css_not_found() {
196 header('HTTP/1.0 404 not found');
197 die('JS was not found, sorry.');
198}