MDL-62497 javascript: add babel transpiling to Grunt for ES6 support
[moodle.git] / lib / requirejs.php
CommitLineData
adeb96d2
DW
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 is serving optimised JS for RequireJS.
19 *
20 * @package core
21 * @copyright 2015 Damyon Wiese
22 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23 */
24
25// Disable moodle specific debug messages and any errors in output,
26// comment out when debugging or better look into error log!
27define('NO_DEBUG_DISPLAY', true);
28
29// We need just the values from config.php and minlib.php.
30define('ABORT_AFTER_CONFIG', true);
31require('../config.php'); // This stops immediately at the beginning of lib/setup.php.
32require_once("$CFG->dirroot/lib/jslib.php");
33require_once("$CFG->dirroot/lib/classes/requirejs.php");
34
35$slashargument = min_get_slash_argument();
36if (!$slashargument) {
37 // The above call to min_get_slash_argument should always work.
38 die('Invalid request');
39}
40
41$slashargument = ltrim($slashargument, '/');
42if (substr_count($slashargument, '/') < 1) {
43 header('HTTP/1.0 404 not found');
44 die('Slash argument must contain both a revision and a file path');
45}
46// Split into revision and module name.
47list($rev, $file) = explode('/', $slashargument, 2);
48$rev = min_clean_param($rev, 'INT');
49$file = '/' . min_clean_param($file, 'SAFEPATH');
50
51// Only load js files from the js modules folder from the components.
52$jsfiles = array();
53list($unused, $component, $module) = explode('/', $file, 3);
54
55// No subdirs allowed - only flat module structure please.
56if (strpos('/', $module) !== false) {
57 die('Invalid module');
58}
59
60// Some (huge) modules are better loaded lazily (when they are used). If we are requesting
61// one of these modules, only return the one module, not the combo.
62$lazysuffix = "-lazy.js";
63$lazyload = (strpos($module, $lazysuffix) !== false);
64
65if ($lazyload) {
66 // We are lazy loading a single file - so include the component/filename pair in the etag.
67 $etag = sha1($rev . '/' . $component . '/' . $module);
68} else {
69 // We loading all (non-lazy) files - so only the rev makes this request unique.
70 $etag = sha1($rev);
71}
72
73
74// Use the caching only for meaningful revision numbers which prevents future cache poisoning.
75if ($rev > 0 and $rev < (time() + 60 * 60)) {
76 $candidate = $CFG->localcachedir . '/requirejs/' . $etag;
77
78 if (file_exists($candidate)) {
79 if (!empty($_SERVER['HTTP_IF_NONE_MATCH']) || !empty($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
80 // We do not actually need to verify the etag value because our files
81 // never change in cache because we increment the rev parameter.
82 js_send_unmodified(filemtime($candidate), $etag);
83 }
84 js_send_cached($candidate, $etag, 'requirejs.php');
85 exit(0);
86
87 } else {
88 $jsfiles = array();
89 if ($lazyload) {
90 $jsfiles = core_requirejs::find_one_amd_module($component, $module);
91 } else {
92 // Here we respond to the request by returning ALL amd modules. This saves
93 // round trips in production.
94
95 $jsfiles = core_requirejs::find_all_amd_modules();
96 }
97
98 $content = '';
99 foreach ($jsfiles as $modulename => $jsfile) {
39c40ada 100 $js = file_get_contents($jsfile);
d45a6d4f 101 if ($js === false) {
39c40ada 102 error_log('Failed to load JavaScript file ' . $jsfile);
0d8ad3b5
AN
103 $js = "/* Failed to load JavaScript file {$jsfile}. */\n";
104 $content = $js . $content;
105 continue;
39c40ada 106 }
c53f86d4
RW
107 // Remove source map link.
108 $js = preg_replace('~//# sourceMappingURL.*$~s', '', $js);
109 $js = rtrim($js);
39c40ada 110 $js .= "\n";
c53f86d4
RW
111
112 if (preg_match('/define\(\s*\[/', $js)) {
113 // If the JavaScript module has been defined without specifying a name then we'll
114 // add the Moodle module name now.
115 $replace = 'define(\'' . $modulename . '\', ';
116 $search = 'define(';
117 // Replace only the first occurrence.
118 $js = implode($replace, explode($search, $js, 2));
119 }
120
adeb96d2
DW
121 $content .= $js;
122 }
123
124 js_write_cache_file_content($candidate, $content);
125 // Verify nothing failed in cache file creation.
126 clearstatcache();
127 if (file_exists($candidate)) {
128 js_send_cached($candidate, $etag, 'requirejs.php');
129 exit(0);
130 }
131 }
132}
133
c53f86d4
RW
134// Ok, now we need to start normal moodle because we need access to the autoloader.
135define('ABORT_AFTER_CONFIG_CANCEL', true);
136// Session not used here.
137define('NO_MOODLE_COOKIES', true);
138// Ignore upgrade check.
139define('NO_UPGRADE_CHECK', true);
140
141require("$CFG->dirroot/lib/setup.php");
142
adeb96d2 143if ($lazyload) {
c53f86d4 144 $jsfiles = core_requirejs::find_one_amd_module($component, $module, false);
adeb96d2 145} else {
c53f86d4 146 $jsfiles = core_requirejs::find_all_amd_modules(false);
adeb96d2
DW
147}
148
c53f86d4
RW
149// The content of the resulting file.
150$result = [];
151// Sort the files to ensure consistent ordering for source map generation.
152asort($jsfiles);
153
adeb96d2
DW
154foreach ($jsfiles as $modulename => $jsfile) {
155 $shortfilename = str_replace($CFG->dirroot, '', $jsfile);
c53f86d4
RW
156 $mapfile = $jsfile . '.map';
157
158 if (file_exists($mapfile)) {
159 // We've got a a source map file so we can return the minified file here and
160 // the source map will be used by the browser to debug.
161 $js = file_get_contents($jsfile);
162 // Remove source map link from the individual file because we add back a single
163 // source map link to the whole file at the end.
164 $js = preg_replace('~//# sourceMappingURL.*$~s', '', $js);
165 } else {
166 // This file doesn't have a map file. We might be dealing with an older source file from
167 // a plugin or previous version of Moodle so we should just return the full original source
168 // like we used to.
169 $originalsource = str_replace('/amd/build/', '/amd/src/', $jsfile);
170 $originalsource = str_replace('.min.js', '.js', $originalsource);
171 $js = file_get_contents($originalsource);
adeb96d2
DW
172 }
173
c53f86d4
RW
174 $js = rtrim($js);
175
176 if (preg_match('/define\(\s*\[/', $js)) {
177 // If the JavaScript module has been defined without specifying a name then we'll
178 // add the Moodle module name now.
179 $replace = 'define(\'' . $modulename . '\', ';
180
181 // Replace only the first occurrence.
182 $js = implode($replace, explode('define(', $js, 2));
183 } else if (!preg_match('/define\s*\(/', $js)) {
184 debugging('JS file: ' . $shortfilename . ' cannot be loaded, or does not contain a javascript' .
185 ' module in AMD format. "define()" not found.', DEBUG_DEVELOPER);
186 }
187
188 $result[] = $js;
adeb96d2 189}
c53f86d4
RW
190
191$mapdataurl = '//# sourceMappingURL=' . (new \moodle_url('/lib/jssourcemap.php/' . $slashargument))->out();
192$result[] = $mapdataurl;
193$content = implode("\n", $result);
194
d900d617 195js_send_uncached($content, 'requirejs.php');