xref: /dokuwiki/lib/exe/js.php (revision e3c3abf1ebade68a06abb03d098d58afda87b317)
178a6aeb1SAndreas Gohr<?php
278a6aeb1SAndreas Gohr/**
378a6aeb1SAndreas Gohr * DokuWiki JavaScript creator
478a6aeb1SAndreas Gohr *
578a6aeb1SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
678a6aeb1SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
778a6aeb1SAndreas Gohr */
8*e3c3abf1SAndreas Gohruse dokuwiki\Utf8\PhpString;
90db5771eSMichael Großeuse dokuwiki\Cache\Cache;
10cbb44eabSAndreas Gohruse dokuwiki\Extension\Event;
11af28745aSAndreas Gohruse splitbrain\JSStrip\Exception as JSStripException;
12af28745aSAndreas Gohruse splitbrain\JSStrip\JSStrip;
130db5771eSMichael Große
14cbb44eabSAndreas Gohrif(!defined('DOKU_INC')) define('DOKU_INC', __DIR__ .'/../../');
151c2d1019SAndreas Gohrif(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching)
16b1a4fe22SAndreas Gohrif(!defined('NL')) define('NL',"\n");
1798bda4fdSAndreas Gohrif(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here
1878a6aeb1SAndreas Gohrrequire_once(DOKU_INC.'inc/init.php');
1978a6aeb1SAndreas Gohr
2078a6aeb1SAndreas Gohr// Main (don't run when UNIT test)
2178a6aeb1SAndreas Gohrif(!defined('SIMPLE_TEST')){
22138a9500SAndreas Gohr    header('Content-Type: application/javascript; charset=utf-8');
2378a6aeb1SAndreas Gohr    js_out();
2478a6aeb1SAndreas Gohr}
2578a6aeb1SAndreas Gohr
2678a6aeb1SAndreas Gohr
2778a6aeb1SAndreas Gohr// ---------------------- functions ------------------------------
2878a6aeb1SAndreas Gohr
2978a6aeb1SAndreas Gohr/**
3078a6aeb1SAndreas Gohr * Output all needed JavaScript
3178a6aeb1SAndreas Gohr *
3278a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
3378a6aeb1SAndreas Gohr */
3478a6aeb1SAndreas Gohrfunction js_out(){
3578a6aeb1SAndreas Gohr    global $conf;
3678a6aeb1SAndreas Gohr    global $lang;
3709edb711SAndreas Gohr    global $config_cascade;
385fc6f52eSAnika Henke    global $INPUT;
395fc6f52eSAnika Henke
405fc6f52eSAnika Henke    // decide from where to get the template
415fc6f52eSAnika Henke    $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t')));
425fc6f52eSAnika Henke    if(!$tpl) $tpl = $conf['template'];
4378a6aeb1SAndreas Gohr
446392c3b6SAndreas Gohr    // array of core files
45*e3c3abf1SAndreas Gohr    $files = [
46fdfb9c6aSMichal Rezler        DOKU_INC.'lib/scripts/jquery/jquery.cookie.js',
47138bfd16SAndreas Gohr        DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js',
4809063cc6SKate Arzamastseva        DOKU_INC."lib/scripts/fileuploader.js",
498d744859SKate Arzamastseva        DOKU_INC."lib/scripts/fileuploaderextended.js",
5086045fe9Swingedfox        DOKU_INC.'lib/scripts/helpers.js',
5121ed6025SAdrian Lang        DOKU_INC.'lib/scripts/delay.js',
523df72098SAndreas Gohr        DOKU_INC.'lib/scripts/cookie.js',
5378a6aeb1SAndreas Gohr        DOKU_INC.'lib/scripts/script.js',
54c949174aSAdrian Lang        DOKU_INC.'lib/scripts/qsearch.js',
55bb8ef867SMichael Große        DOKU_INC.'lib/scripts/search.js',
56d10c9a74SAdrian Lang        DOKU_INC.'lib/scripts/tree.js',
57a06884abSAndreas Gohr        DOKU_INC.'lib/scripts/index.js',
586392c3b6SAndreas Gohr        DOKU_INC.'lib/scripts/textselection.js',
596392c3b6SAndreas Gohr        DOKU_INC.'lib/scripts/toolbar.js',
606392c3b6SAndreas Gohr        DOKU_INC.'lib/scripts/edit.js',
61ddf8a04fSAndreas Gohr        DOKU_INC.'lib/scripts/editor.js',
6255f92d7eSAndreas Gohr        DOKU_INC.'lib/scripts/locktimer.js',
636392c3b6SAndreas Gohr        DOKU_INC.'lib/scripts/linkwiz.js',
646392c3b6SAndreas Gohr        DOKU_INC.'lib/scripts/media.js',
65767d1669SAndreas Gohr        DOKU_INC.'lib/scripts/compatibility.js',
6687e7175eSAndreas Gohr        # disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
6717e2e254SAndreas Gohr        DOKU_INC.'lib/scripts/behaviour.js',
68fbedf126SAndreas Gohr        DOKU_INC.'lib/scripts/page.js',
695fc6f52eSAnika Henke        tpl_incdir($tpl).'script.js',
70*e3c3abf1SAndreas Gohr    ];
7178a6aeb1SAndreas Gohr
726392c3b6SAndreas Gohr    // add possible plugin scripts and userscript
736392c3b6SAndreas Gohr    $files   = array_merge($files,js_pluginscripts());
7460764596SAndreas Gohr    if(is_array($config_cascade['userscript']['default'])) {
757b909d5eSGerrit Uitslag        foreach($config_cascade['userscript']['default'] as $userscript) {
767b909d5eSGerrit Uitslag            $files[] = $userscript;
777b909d5eSGerrit Uitslag        }
7809edb711SAndreas Gohr    }
7978a6aeb1SAndreas Gohr
806d3bebffSGerry Weißbach    // Let plugins decide to either put more scripts here or to remove some
81cbb44eabSAndreas Gohr    Event::createAndTrigger('JS_SCRIPT_LIST', $files);
826d3bebffSGerry Weißbach
836d3bebffSGerry Weißbach    // The generated script depends on some dynamic options
840db5771eSMichael Große    $cache = new Cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].md5(serialize($files)),'.js');
85dc7da772SMichael Große    $cache->setEvent('JS_CACHE_USE');
866d3bebffSGerry Weißbach
876619f42eSAdrian Lang    $cache_files = array_merge($files, getConfigFiles('main'));
886619f42eSAdrian Lang    $cache_files[] = __FILE__;
89ca2b464bSChris Smith
906619f42eSAdrian Lang    // check cache age & handle conditional request
916619f42eSAdrian Lang    // This may exit if a cache can be used
92*e3c3abf1SAndreas Gohr    $cache_ok = $cache->useCache(['files' => $cache_files]);
93e67004f5SAndreas Gohr    http_cached($cache->cache, $cache_ok);
9478a6aeb1SAndreas Gohr
9578a6aeb1SAndreas Gohr    // start output buffering and build the script
9678a6aeb1SAndreas Gohr    ob_start();
9778a6aeb1SAndreas Gohr
983df72098SAndreas Gohr    // add some global variables
993df72098SAndreas Gohr    print "var DOKU_BASE   = '".DOKU_BASE."';";
1005fc6f52eSAnika Henke    print "var DOKU_TPL    = '".tpl_basedir($tpl)."';";
101*e3c3abf1SAndreas Gohr    print "var DOKU_COOKIE_PARAM = " . json_encode([
102df5d307eSGerrit Uitslag            'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'],
103df5d307eSGerrit Uitslag            'secure' => $conf['securecookie'] && is_ssl()
104*e3c3abf1SAndreas Gohr        ], JSON_THROW_ON_ERROR) . ";";
1055e7a2926SAdrian Lang    // FIXME: Move those to JSINFO
10664159a61SAndreas Gohr    print "Object.defineProperty(window, 'DOKU_UHN', { get: function() {".
10764159a61SAndreas Gohr          "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');".
10864159a61SAndreas Gohr          "return JSINFO.useHeadingNavigation; } });";
10964159a61SAndreas Gohr    print "Object.defineProperty(window, 'DOKU_UHC', { get: function() {".
11064159a61SAndreas Gohr          "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');".
11164159a61SAndreas Gohr          "return JSINFO.useHeadingContent; } });";
1123df72098SAndreas Gohr
1133df72098SAndreas Gohr    // load JS specific translations
1146392c3b6SAndreas Gohr    $lang['js']['plugins'] = js_pluginstrings();
1155fc6f52eSAnika Henke    $templatestrings = js_templatestrings($tpl);
116acd3eb67SKlap-in    if(!empty($templatestrings)) {
117acd3eb67SKlap-in        $lang['js']['template'] = $templatestrings;
118acd3eb67SKlap-in    }
119*e3c3abf1SAndreas Gohr    echo 'LANG = '.json_encode($lang['js'], JSON_THROW_ON_ERROR).";\n";
12078a6aeb1SAndreas Gohr
1216392c3b6SAndreas Gohr    // load toolbar
1226392c3b6SAndreas Gohr    toolbar_JSdefines('toolbar');
1236392c3b6SAndreas Gohr
12478a6aeb1SAndreas Gohr    // load files
12578a6aeb1SAndreas Gohr    foreach($files as $file){
126138bfd16SAndreas Gohr        if(!file_exists($file)) continue;
12780a47290SAndreas Gohr        $ismin = (substr($file,-7) == '.min.js');
1286b0ec830SMichael Hamann        $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0);
12980a47290SAndreas Gohr
13057d846dbSAndreas Gohr        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
13180a47290SAndreas Gohr        if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
1326b0ec830SMichael Hamann        if ($debugjs) echo "\ntry {\n";
133176da19bSAndreas Gohr        js_load($file);
1346b0ec830SMichael Hamann        if ($debugjs) echo "\n} catch (e) {\n   logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n";
13580a47290SAndreas Gohr        if($ismin) echo "\n/* END NOCOMPRESS */\n";
13657d846dbSAndreas Gohr        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
13778a6aeb1SAndreas Gohr    }
13878a6aeb1SAndreas Gohr
13978a6aeb1SAndreas Gohr    // init stuff
140544ed901SDaniel Calviño Sánchez    if($conf['locktime'] != 0){
14199e7bfd4SAndreas Gohr        js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")");
142544ed901SDaniel Calviño Sánchez    }
1434062d3d5SMarek Sacha    // init hotkeys - must have been done after init of toolbar
144de32b03eSMichael Hamann    # disabled for FS#1958    js_runonstart('initializeHotkeys()');
14500540a38SAndreas Gohr
14678a6aeb1SAndreas Gohr    // end output buffering and get contents
14778a6aeb1SAndreas Gohr    $js = ob_get_contents();
14878a6aeb1SAndreas Gohr    ob_end_clean();
14978a6aeb1SAndreas Gohr
150f8fb2d18SAndreas Gohr    // strip any source maps
151f8fb2d18SAndreas Gohr    stripsourcemaps($js);
152f8fb2d18SAndreas Gohr
15378a6aeb1SAndreas Gohr    // compress whitespace and comments
15478a6aeb1SAndreas Gohr    if($conf['compress']){
155af28745aSAndreas Gohr        try {
156af28745aSAndreas Gohr            $js = (new JSStrip())->compress($js);
157af28745aSAndreas Gohr        } catch (JSStripException $e) {
158*e3c3abf1SAndreas Gohr            $js .= "\nconsole.error(".json_encode($e->getMessage(), JSON_THROW_ON_ERROR).");\n";
159af28745aSAndreas Gohr        }
16078a6aeb1SAndreas Gohr    }
16178a6aeb1SAndreas Gohr
1624d2d451eSAndreas Gohr    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
1634d2d451eSAndreas Gohr
1646619f42eSAdrian Lang    http_cached_finish($cache->cache, $js);
165ca2b464bSChris Smith}
16678a6aeb1SAndreas Gohr
16778a6aeb1SAndreas Gohr/**
168176da19bSAndreas Gohr * Load the given file, handle include calls and print it
1693825ddd3SAndreas Gohr *
1703825ddd3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
171253d4b48SGerrit Uitslag *
172253d4b48SGerrit Uitslag * @param string $file filename path to file
173176da19bSAndreas Gohr */
174176da19bSAndreas Gohrfunction js_load($file){
17579e79377SAndreas Gohr    if(!file_exists($file)) return;
176*e3c3abf1SAndreas Gohr    static $loaded = [];
177176da19bSAndreas Gohr
178176da19bSAndreas Gohr    $data = io_readFile($file);
17998dba5adSAdrian Lang    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
1803825ddd3SAndreas Gohr        $ifile = $match[2];
1813825ddd3SAndreas Gohr
1823825ddd3SAndreas Gohr        // is it a include_once?
1833825ddd3SAndreas Gohr        if($match[1]){
184*e3c3abf1SAndreas Gohr            $base = PhpString::basename($ifile);
1855c97ad3aSMarius van Witzenburg            if(array_key_exists($base, $loaded) && $loaded[$base] === true){
186969df2f1SAndreas Gohr                $data  = str_replace($match[0], '' ,$data);
187969df2f1SAndreas Gohr                continue;
188969df2f1SAndreas Gohr            }
1893825ddd3SAndreas Gohr            $loaded[$base] = true;
1903825ddd3SAndreas Gohr        }
1913825ddd3SAndreas Gohr
1925312cb0bSSyntaxseed        if($ifile[0] != '/') $ifile = dirname($file).'/'.$ifile;
193176da19bSAndreas Gohr
194176da19bSAndreas Gohr        $idata = '';
195b4af56dcSMoritz Raguschat        if (file_exists($ifile)) {
196b4af56dcSMoritz Raguschat            $ismin = (substr($ifile, -7) == '.min.js');;
197b4af56dcSMoritz Raguschat            if ($ismin) $idata .= "\n/* BEGIN NOCOMPRESS */\n";
198b4af56dcSMoritz Raguschat            $idata .= io_readFile($ifile);
199b4af56dcSMoritz Raguschat            if ($ismin) $idata .= "\n/* END NOCOMPRESS */\n";
200176da19bSAndreas Gohr        }
201176da19bSAndreas Gohr        $data  = str_replace($match[0],$idata,$data);
202176da19bSAndreas Gohr    }
20317582ec6SAndreas Gohr    echo "$data\n";
204176da19bSAndreas Gohr}
205176da19bSAndreas Gohr
206176da19bSAndreas Gohr/**
20778a6aeb1SAndreas Gohr * Returns a list of possible Plugin Scripts (no existance check here)
20878a6aeb1SAndreas Gohr *
20978a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
210253d4b48SGerrit Uitslag *
211253d4b48SGerrit Uitslag * @return array
21278a6aeb1SAndreas Gohr */
21378a6aeb1SAndreas Gohrfunction js_pluginscripts(){
214*e3c3abf1SAndreas Gohr    $list = [];
21578a6aeb1SAndreas Gohr    $plugins = plugin_list();
21678a6aeb1SAndreas Gohr    foreach ($plugins as $p){
21778a6aeb1SAndreas Gohr        $list[] = DOKU_PLUGIN."$p/script.js";
21878a6aeb1SAndreas Gohr    }
21978a6aeb1SAndreas Gohr    return $list;
22078a6aeb1SAndreas Gohr}
22178a6aeb1SAndreas Gohr
22278a6aeb1SAndreas Gohr/**
2239f01cf6aSGabriel Birke * Return an two-dimensional array with strings from the language file of each plugin.
2249f01cf6aSGabriel Birke *
2259f01cf6aSGabriel Birke * - $lang['js'] must be an array.
2269f01cf6aSGabriel Birke * - Nothing is returned for plugins without an entry for $lang['js']
2279f01cf6aSGabriel Birke *
2289f01cf6aSGabriel Birke * @author Gabriel Birke <birke@d-scribe.de>
229253d4b48SGerrit Uitslag *
230253d4b48SGerrit Uitslag * @return array
2319f01cf6aSGabriel Birke */
232d91ab76fSMatt Perryfunction js_pluginstrings() {
23319e06537SGerrit Uitslag    global $conf, $config_cascade;
234*e3c3abf1SAndreas Gohr    $pluginstrings = [];
2359f01cf6aSGabriel Birke    $plugins = plugin_list();
2369f01cf6aSGabriel Birke    foreach($plugins as $p) {
23719e06537SGerrit Uitslag        $path = DOKU_PLUGIN . $p . '/lang/';
23819e06537SGerrit Uitslag
2399f01cf6aSGabriel Birke        if(isset($lang)) unset($lang);
24019e06537SGerrit Uitslag        if(file_exists($path . "en/lang.php")) {
24119e06537SGerrit Uitslag            include $path . "en/lang.php";
2429f01cf6aSGabriel Birke        }
24319e06537SGerrit Uitslag        foreach($config_cascade['lang']['plugin'] as $config_file) {
24419e06537SGerrit Uitslag            if(file_exists($config_file . $p . '/en/lang.php')) {
24519e06537SGerrit Uitslag                include($config_file . $p . '/en/lang.php');
2469f01cf6aSGabriel Birke            }
24719e06537SGerrit Uitslag        }
24819e06537SGerrit Uitslag        if(isset($conf['lang']) && $conf['lang'] != 'en') {
24919e06537SGerrit Uitslag            if(file_exists($path . $conf['lang'] . "/lang.php")) {
25019e06537SGerrit Uitslag                include($path . $conf['lang'] . '/lang.php');
25119e06537SGerrit Uitslag            }
25219e06537SGerrit Uitslag            foreach($config_cascade['lang']['plugin'] as $config_file) {
25319e06537SGerrit Uitslag                if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) {
25419e06537SGerrit Uitslag                    include($config_file . $p . '/' . $conf['lang'] . '/lang.php');
25519e06537SGerrit Uitslag                }
25619e06537SGerrit Uitslag            }
25719e06537SGerrit Uitslag        }
25819e06537SGerrit Uitslag
2599f01cf6aSGabriel Birke        if(isset($lang['js'])) {
2609f01cf6aSGabriel Birke            $pluginstrings[$p] = $lang['js'];
2619f01cf6aSGabriel Birke        }
2629f01cf6aSGabriel Birke    }
2639f01cf6aSGabriel Birke    return $pluginstrings;
2649f01cf6aSGabriel Birke}
2659f01cf6aSGabriel Birke
26656b0b744SGerrit Uitslag/**
26756b0b744SGerrit Uitslag * Return an two-dimensional array with strings from the language file of current active template.
26856b0b744SGerrit Uitslag *
26956b0b744SGerrit Uitslag * - $lang['js'] must be an array.
27056b0b744SGerrit Uitslag * - Nothing is returned for template without an entry for $lang['js']
271253d4b48SGerrit Uitslag *
2725fc6f52eSAnika Henke * @param string $tpl
273253d4b48SGerrit Uitslag * @return array
27456b0b744SGerrit Uitslag */
2755fc6f52eSAnika Henkefunction js_templatestrings($tpl) {
27619e06537SGerrit Uitslag    global $conf, $config_cascade;
27719e06537SGerrit Uitslag
27819e06537SGerrit Uitslag    $path = tpl_incdir() . 'lang/';
27919e06537SGerrit Uitslag
280*e3c3abf1SAndreas Gohr    $templatestrings = [];
28119e06537SGerrit Uitslag    if(file_exists($path . "en/lang.php")) {
28219e06537SGerrit Uitslag        include $path . "en/lang.php";
283acd3eb67SKlap-in    }
28419e06537SGerrit Uitslag    foreach($config_cascade['lang']['template'] as $config_file) {
28519e06537SGerrit Uitslag        if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
28619e06537SGerrit Uitslag            include($config_file . $conf['template'] . '/en/lang.php');
287acd3eb67SKlap-in        }
28819e06537SGerrit Uitslag    }
28919e06537SGerrit Uitslag    if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) {
29019e06537SGerrit Uitslag        include $path . $conf['lang'] . "/lang.php";
29119e06537SGerrit Uitslag    }
29219e06537SGerrit Uitslag    if(isset($conf['lang']) && $conf['lang'] != 'en') {
29319e06537SGerrit Uitslag        if(file_exists($path . $conf['lang'] . "/lang.php")) {
29419e06537SGerrit Uitslag            include $path . $conf['lang'] . "/lang.php";
29519e06537SGerrit Uitslag        }
29619e06537SGerrit Uitslag        foreach($config_cascade['lang']['template'] as $config_file) {
29719e06537SGerrit Uitslag            if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
29819e06537SGerrit Uitslag                include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
29919e06537SGerrit Uitslag            }
30019e06537SGerrit Uitslag        }
30119e06537SGerrit Uitslag    }
30219e06537SGerrit Uitslag
303acd3eb67SKlap-in    if(isset($lang['js'])) {
3045fc6f52eSAnika Henke        $templatestrings[$tpl] = $lang['js'];
305acd3eb67SKlap-in    }
306acd3eb67SKlap-in    return $templatestrings;
307acd3eb67SKlap-in}
308acd3eb67SKlap-in
3099f01cf6aSGabriel Birke/**
31078a6aeb1SAndreas Gohr * Escapes a String to be embedded in a JavaScript call, keeps \n
31178a6aeb1SAndreas Gohr * as newline
31278a6aeb1SAndreas Gohr *
31378a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
314253d4b48SGerrit Uitslag *
315253d4b48SGerrit Uitslag * @param string $string
316253d4b48SGerrit Uitslag * @return string
31778a6aeb1SAndreas Gohr */
31878a6aeb1SAndreas Gohrfunction js_escape($string){
31978a6aeb1SAndreas Gohr    return str_replace('\\\\n','\\n',addslashes($string));
32078a6aeb1SAndreas Gohr}
32178a6aeb1SAndreas Gohr
32278a6aeb1SAndreas Gohr/**
32378a6aeb1SAndreas Gohr * Adds the given JavaScript code to the window.onload() event
32478a6aeb1SAndreas Gohr *
32578a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
326253d4b48SGerrit Uitslag *
327253d4b48SGerrit Uitslag * @param string $func
32878a6aeb1SAndreas Gohr */
32978a6aeb1SAndreas Gohrfunction js_runonstart($func){
3305e7a2926SAdrian Lang    echo "jQuery(function(){ $func; });".NL;
33178a6aeb1SAndreas Gohr}
332