xref: /dokuwiki/lib/exe/js.php (revision af28745a55598899ff91b5048e6acff9cd2ed1d8)
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 */
8
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 = array(
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(array('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            array(
103                 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'],
104                 'secure' => $conf['securecookie'] && is_ssl()
105            )).";";
106    // FIXME: Move those to JSINFO
107    print "Object.defineProperty(window, 'DOKU_UHN', { get: function() {".
108          "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');".
109          "return JSINFO.useHeadingNavigation; } });";
110    print "Object.defineProperty(window, 'DOKU_UHC', { get: function() {".
111          "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');".
112          "return JSINFO.useHeadingContent; } });";
113
114    // load JS specific translations
115    $lang['js']['plugins'] = js_pluginstrings();
116    $templatestrings = js_templatestrings($tpl);
117    if(!empty($templatestrings)) {
118        $lang['js']['template'] = $templatestrings;
119    }
120    echo 'LANG = '.json_encode($lang['js']).";\n";
121
122    // load toolbar
123    toolbar_JSdefines('toolbar');
124
125    // load files
126    foreach($files as $file){
127        if(!file_exists($file)) continue;
128        $ismin = (substr($file,-7) == '.min.js');
129        $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0);
130
131        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
132        if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
133        if ($debugjs) echo "\ntry {\n";
134        js_load($file);
135        if ($debugjs) echo "\n} catch (e) {\n   logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n";
136        if($ismin) echo "\n/* END NOCOMPRESS */\n";
137        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
138    }
139
140    // init stuff
141    if($conf['locktime'] != 0){
142        js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")");
143    }
144    // init hotkeys - must have been done after init of toolbar
145# disabled for FS#1958    js_runonstart('initializeHotkeys()');
146
147    // end output buffering and get contents
148    $js = ob_get_contents();
149    ob_end_clean();
150
151    // strip any source maps
152    stripsourcemaps($js);
153
154    // compress whitespace and comments
155    if($conf['compress']){
156        try {
157            $js = (new JSStrip())->compress($js);
158        } catch (JSStripException $e) {
159            $js .= "\nconsole.error(".json_encode($e->getMessage()).");\n";
160        }
161    }
162
163    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
164
165    http_cached_finish($cache->cache, $js);
166}
167
168/**
169 * Load the given file, handle include calls and print it
170 *
171 * @author Andreas Gohr <andi@splitbrain.org>
172 *
173 * @param string $file filename path to file
174 */
175function js_load($file){
176    if(!file_exists($file)) return;
177    static $loaded = array();
178
179    $data = io_readFile($file);
180    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
181        $ifile = $match[2];
182
183        // is it a include_once?
184        if($match[1]){
185            $base = \dokuwiki\Utf8\PhpString::basename($ifile);
186            if(array_key_exists($base, $loaded) && $loaded[$base] === true){
187                $data  = str_replace($match[0], '' ,$data);
188                continue;
189            }
190            $loaded[$base] = true;
191        }
192
193        if($ifile[0] != '/') $ifile = dirname($file).'/'.$ifile;
194
195        if(file_exists($ifile)){
196            $idata = io_readFile($ifile);
197        }else{
198            $idata = '';
199        }
200        $data  = str_replace($match[0],$idata,$data);
201    }
202    echo "$data\n";
203}
204
205/**
206 * Returns a list of possible Plugin Scripts (no existance check here)
207 *
208 * @author Andreas Gohr <andi@splitbrain.org>
209 *
210 * @return array
211 */
212function js_pluginscripts(){
213    $list = array();
214    $plugins = plugin_list();
215    foreach ($plugins as $p){
216        $list[] = DOKU_PLUGIN."$p/script.js";
217    }
218    return $list;
219}
220
221/**
222 * Return an two-dimensional array with strings from the language file of each plugin.
223 *
224 * - $lang['js'] must be an array.
225 * - Nothing is returned for plugins without an entry for $lang['js']
226 *
227 * @author Gabriel Birke <birke@d-scribe.de>
228 *
229 * @return array
230 */
231function js_pluginstrings() {
232    global $conf, $config_cascade;
233    $pluginstrings = array();
234    $plugins = plugin_list();
235    foreach($plugins as $p) {
236        $path = DOKU_PLUGIN . $p . '/lang/';
237
238        if(isset($lang)) unset($lang);
239        if(file_exists($path . "en/lang.php")) {
240            include $path . "en/lang.php";
241        }
242        foreach($config_cascade['lang']['plugin'] as $config_file) {
243            if(file_exists($config_file . $p . '/en/lang.php')) {
244                include($config_file . $p . '/en/lang.php');
245            }
246        }
247        if(isset($conf['lang']) && $conf['lang'] != 'en') {
248            if(file_exists($path . $conf['lang'] . "/lang.php")) {
249                include($path . $conf['lang'] . '/lang.php');
250            }
251            foreach($config_cascade['lang']['plugin'] as $config_file) {
252                if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) {
253                    include($config_file . $p . '/' . $conf['lang'] . '/lang.php');
254                }
255            }
256        }
257
258        if(isset($lang['js'])) {
259            $pluginstrings[$p] = $lang['js'];
260        }
261    }
262    return $pluginstrings;
263}
264
265/**
266 * Return an two-dimensional array with strings from the language file of current active template.
267 *
268 * - $lang['js'] must be an array.
269 * - Nothing is returned for template without an entry for $lang['js']
270 *
271 * @param string $tpl
272 * @return array
273 */
274function js_templatestrings($tpl) {
275    global $conf, $config_cascade;
276
277    $path = tpl_incdir() . 'lang/';
278
279    $templatestrings = array();
280    if(file_exists($path . "en/lang.php")) {
281        include $path . "en/lang.php";
282    }
283    foreach($config_cascade['lang']['template'] as $config_file) {
284        if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
285            include($config_file . $conf['template'] . '/en/lang.php');
286        }
287    }
288    if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) {
289        include $path . $conf['lang'] . "/lang.php";
290    }
291    if(isset($conf['lang']) && $conf['lang'] != 'en') {
292        if(file_exists($path . $conf['lang'] . "/lang.php")) {
293            include $path . $conf['lang'] . "/lang.php";
294        }
295        foreach($config_cascade['lang']['template'] as $config_file) {
296            if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
297                include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
298            }
299        }
300    }
301
302    if(isset($lang['js'])) {
303        $templatestrings[$tpl] = $lang['js'];
304    }
305    return $templatestrings;
306}
307
308/**
309 * Escapes a String to be embedded in a JavaScript call, keeps \n
310 * as newline
311 *
312 * @author Andreas Gohr <andi@splitbrain.org>
313 *
314 * @param string $string
315 * @return string
316 */
317function js_escape($string){
318    return str_replace('\\\\n','\\n',addslashes($string));
319}
320
321/**
322 * Adds the given JavaScript code to the window.onload() event
323 *
324 * @author Andreas Gohr <andi@splitbrain.org>
325 *
326 * @param string $func
327 */
328function js_runonstart($func){
329    echo "jQuery(function(){ $func; });".NL;
330}
331