xref: /dokuwiki/lib/exe/js.php (revision 9399c87e10527bd9270ac34f45432bcff3a2b473)
1<?php
2
3/**
4 * DokuWiki JavaScript creator
5 *
6 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
7 * @author     Andreas Gohr <andi@splitbrain.org>
8 */
9
10use dokuwiki\Ip;
11use dokuwiki\Utf8\PhpString;
12use dokuwiki\Cache\Cache;
13use dokuwiki\Extension\Event;
14use splitbrain\JSStrip\Exception as JSStripException;
15use splitbrain\JSStrip\JSStrip;
16
17if (!defined('DOKU_INC')) define('DOKU_INC', __DIR__ . '/../../');
18if (!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching)
19if (!defined('NL')) define('NL', "\n");
20if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here
21require_once(DOKU_INC . 'inc/init.php');
22
23// Main (don't run when UNIT test)
24if (!defined('SIMPLE_TEST')) {
25    header('Content-Type: application/javascript; charset=utf-8');
26    js_out();
27}
28
29
30// ---------------------- functions ------------------------------
31
32/**
33 * Output all needed JavaScript
34 *
35 * @author Andreas Gohr <andi@splitbrain.org>
36 */
37function js_out()
38{
39    global $conf;
40    global $lang;
41    global $config_cascade;
42    global $INPUT;
43
44    // decide from where to get the template
45    $tpl = trim(preg_replace('/[^\w-]+/', '', $INPUT->str('t')));
46    if (!$tpl) $tpl = $conf['template'];
47
48    // array of core files
49    $files = [
50        DOKU_INC . 'lib/scripts/jquery/jquery.cookie.js',
51        DOKU_INC . 'inc/lang/' . $conf['lang'] . '/jquery.ui.datepicker.js',
52        DOKU_INC . "lib/scripts/fileuploader.js",
53        DOKU_INC . "lib/scripts/fileuploaderextended.js",
54        DOKU_INC . 'lib/scripts/helpers.js',
55        DOKU_INC . 'lib/scripts/delay.js',
56        DOKU_INC . 'lib/scripts/cookie.js',
57        DOKU_INC . 'lib/scripts/script.js',
58        DOKU_INC . 'lib/scripts/qsearch.js',
59        DOKU_INC . 'lib/scripts/search.js',
60        DOKU_INC . 'lib/scripts/tree.js',
61        DOKU_INC . 'lib/scripts/index.js',
62        DOKU_INC . 'lib/scripts/textselection.js',
63        DOKU_INC . 'lib/scripts/toolbar.js',
64        DOKU_INC . 'lib/scripts/edit.js',
65        DOKU_INC . 'lib/scripts/editor.js',
66        DOKU_INC . 'lib/scripts/locktimer.js',
67        DOKU_INC . 'lib/scripts/linkwiz.js',
68        DOKU_INC . 'lib/scripts/media.js',
69        DOKU_INC . 'lib/scripts/compatibility.js',
70        # disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
71        DOKU_INC . 'lib/scripts/behaviour.js',
72        DOKU_INC . 'lib/scripts/page.js',
73        tpl_incdir($tpl) . 'script.js',
74    ];
75
76    // add possible plugin scripts and userscript
77    $files = array_merge($files, js_pluginscripts());
78    if (is_array($config_cascade['userscript']['default'])) {
79        foreach ($config_cascade['userscript']['default'] as $userscript) {
80            $files[] = $userscript;
81        }
82    }
83
84    // Let plugins decide to either put more scripts here or to remove some
85    Event::createAndTrigger('JS_SCRIPT_LIST', $files);
86
87    // The generated script depends on some dynamic options
88    $cache = new Cache('scripts' . $_SERVER['HTTP_HOST'] . $_SERVER['SERVER_PORT'] . md5(serialize($files)), '.js');
89    $cache->setEvent('JS_CACHE_USE');
90
91    $cache_files = array_merge($files, getConfigFiles('main'));
92    $cache_files[] = __FILE__;
93
94    // check cache age & handle conditional request
95    // This may exit if a cache can be used
96    $cache_ok = $cache->useCache(['files' => $cache_files]);
97    http_cached($cache->cache, $cache_ok);
98
99    // start output buffering and build the script
100    ob_start();
101
102    // add some global variables
103    echo "var DOKU_BASE   = '" . DOKU_BASE . "';";
104    echo "var DOKU_TPL    = '" . tpl_basedir($tpl) . "';";
105    echo "var DOKU_COOKIE_PARAM = " . json_encode([
106            'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'],
107            'secure' => $conf['securecookie'] && Ip::isSsl(),
108        ], JSON_THROW_ON_ERROR) . ";";
109    // FIXME: Move those to JSINFO
110    echo "Object.defineProperty(window, 'DOKU_UHN', { get: function() {" .
111        "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');" .
112        "return JSINFO.useHeadingNavigation; } });";
113    echo "Object.defineProperty(window, 'DOKU_UHC', { get: function() {" .
114        "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');" .
115        "return JSINFO.useHeadingContent; } });";
116
117    // load JS specific translations
118    $lang['js']['plugins'] = js_pluginstrings();
119    $templatestrings = js_templatestrings($tpl);
120    if (!empty($templatestrings)) {
121        $lang['js']['template'] = $templatestrings;
122    }
123    echo 'LANG = ' . json_encode($lang['js'], JSON_THROW_ON_ERROR) . ";\n";
124
125    // load toolbar
126    toolbar_JSdefines('toolbar');
127
128    // load files
129    foreach ($files as $file) {
130        if (!file_exists($file)) continue;
131        $ismin = str_ends_with($file, '.min.js');
132        $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC . 'lib/scripts/') !== 0);
133
134        echo "\n\n/* XXXXXXXXXX begin of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
135        if ($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
136        if ($debugjs) echo "\ntry {\n";
137        js_load($file);
138        if ($debugjs) echo "\n} catch (e) {\n   logError(e, '" . str_replace(DOKU_INC, '', $file) . "');\n}\n";
139        if ($ismin) echo "\n/* END NOCOMPRESS */\n";
140        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
141    }
142
143    // init stuff
144    if ($conf['locktime'] != 0) {
145        js_runonstart("dw_locktimer.init(" . ($conf['locktime'] - 60) . "," . $conf['usedraft'] . ")");
146    }
147    // init hotkeys - must have been done after init of toolbar
148    # disabled for FS#1958    js_runonstart('initializeHotkeys()');
149
150    // end output buffering and get contents
151    $js = ob_get_contents();
152    ob_end_clean();
153
154    // strip any source maps
155    stripsourcemaps($js);
156
157    // compress whitespace and comments
158    if ($conf['compress']) {
159        try {
160            $js = (new JSStrip())->compress($js);
161        } catch (JSStripException $e) {
162            $js .= "\nconsole.error(" . json_encode($e->getMessage(), JSON_THROW_ON_ERROR) . ");\n";
163        }
164    }
165
166    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
167
168    http_cached_finish($cache->cache, $js);
169}
170
171/**
172 * Load the given file, handle include calls and print it
173 *
174 * @param string $file filename path to file
175 *
176 * @author Andreas Gohr <andi@splitbrain.org>
177 */
178function js_load($file)
179{
180    if (!file_exists($file)) return;
181    static $loaded = [];
182
183    $data = io_readFile($file);
184    while (preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#', $data, $match)) {
185        $ifile = $match[2];
186
187        // is it a include_once?
188        if ($match[1]) {
189            $base = PhpString::basename($ifile);
190            if (array_key_exists($base, $loaded) && $loaded[$base] === true) {
191                $data = str_replace($match[0], '', $data);
192                continue;
193            }
194            $loaded[$base] = true;
195        }
196
197        if ($ifile[0] != '/') $ifile = dirname($file) . '/' . $ifile;
198
199        $idata = '';
200        if (file_exists($ifile)) {
201            $ismin = str_ends_with($ifile, '.min.js');
202            if ($ismin) $idata .= "\n/* BEGIN NOCOMPRESS */\n";
203            $idata .= io_readFile($ifile);
204            if ($ismin) $idata .= "\n/* END NOCOMPRESS */\n";
205        }
206        $data = str_replace($match[0], $idata, $data);
207    }
208    echo "$data\n";
209}
210
211/**
212 * Returns a list of possible Plugin Scripts (no existance check here)
213 *
214 * @return array
215 *
216 * @author Andreas Gohr <andi@splitbrain.org>
217 */
218function js_pluginscripts()
219{
220    $list = [];
221    $plugins = plugin_list();
222    foreach ($plugins as $p) {
223        $list[] = DOKU_PLUGIN . "$p/script.js";
224    }
225    return $list;
226}
227
228/**
229 * Return an two-dimensional array with strings from the language file of each plugin.
230 *
231 * - $lang['js'] must be an array.
232 * - Nothing is returned for plugins without an entry for $lang['js']
233 *
234 * @return array
235 * @author Gabriel Birke <birke@d-scribe.de>
236 *
237 */
238function js_pluginstrings()
239{
240    global $conf, $config_cascade;
241    $pluginstrings = [];
242    $plugins = plugin_list();
243    foreach ($plugins as $p) {
244        $path = DOKU_PLUGIN . $p . '/lang/';
245
246        if (isset($lang)) unset($lang);
247        if (file_exists($path . "en/lang.php")) {
248            include $path . "en/lang.php";
249        }
250        foreach ($config_cascade['lang']['plugin'] as $config_file) {
251            if (file_exists($config_file . $p . '/en/lang.php')) {
252                include($config_file . $p . '/en/lang.php');
253            }
254        }
255        if (isset($conf['lang']) && $conf['lang'] != 'en') {
256            if (file_exists($path . $conf['lang'] . "/lang.php")) {
257                include($path . $conf['lang'] . '/lang.php');
258            }
259            foreach ($config_cascade['lang']['plugin'] as $config_file) {
260                if (file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) {
261                    include($config_file . $p . '/' . $conf['lang'] . '/lang.php');
262                }
263            }
264        }
265
266        if (isset($lang['js'])) {
267            $pluginstrings[$p] = $lang['js'];
268        }
269    }
270    return $pluginstrings;
271}
272
273/**
274 * Return an two-dimensional array with strings from the language file of current active template.
275 *
276 * - $lang['js'] must be an array.
277 * - Nothing is returned for template without an entry for $lang['js']
278 *
279 * @param string $tpl
280 * @return array
281 */
282function js_templatestrings($tpl)
283{
284    global $conf, $config_cascade;
285
286    $path = tpl_incdir() . 'lang/';
287
288    $templatestrings = [];
289    if (file_exists($path . "en/lang.php")) {
290        include $path . "en/lang.php";
291    }
292    foreach ($config_cascade['lang']['template'] as $config_file) {
293        if (file_exists($config_file . $conf['template'] . '/en/lang.php')) {
294            include($config_file . $conf['template'] . '/en/lang.php');
295        }
296    }
297    if (isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) {
298        include $path . $conf['lang'] . "/lang.php";
299    }
300    if (isset($conf['lang']) && $conf['lang'] != 'en') {
301        if (file_exists($path . $conf['lang'] . "/lang.php")) {
302            include $path . $conf['lang'] . "/lang.php";
303        }
304        foreach ($config_cascade['lang']['template'] as $config_file) {
305            if (file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
306                include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
307            }
308        }
309    }
310
311    if (isset($lang['js'])) {
312        $templatestrings[$tpl] = $lang['js'];
313    }
314    return $templatestrings;
315}
316
317/**
318 * Escapes a String to be embedded in a JavaScript call, keeps \n
319 * as newline
320 *
321 * @param string $string
322 * @return string
323 *
324 * @author Andreas Gohr <andi@splitbrain.org>
325 */
326function js_escape($string)
327{
328    return str_replace('\\\\n', '\\n', addslashes($string));
329}
330
331/**
332 * Adds the given JavaScript code to the window.onload() event
333 *
334 * @param string $func
335 *
336 * @author Andreas Gohr <andi@splitbrain.org>
337 */
338function js_runonstart($func)
339{
340    echo "jQuery(function(){ $func; });" . NL;
341}
342