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