xref: /dokuwiki/lib/exe/js.php (revision d443762bafe99b9292cee141f99fbe818e8d2f16)
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
9if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../');
10if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching)
11if(!defined('NL')) define('NL',"\n");
12if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here
13require_once(DOKU_INC.'inc/init.php');
14
15// Main (don't run when UNIT test)
16if(!defined('SIMPLE_TEST')){
17    header('Content-Type: application/javascript; charset=utf-8');
18    js_out();
19}
20
21
22// ---------------------- functions ------------------------------
23
24/**
25 * Output all needed JavaScript
26 *
27 * @author Andreas Gohr <andi@splitbrain.org>
28 */
29function js_out(){
30    global $conf;
31    global $lang;
32    global $config_cascade;
33    global $INPUT;
34
35    // decide from where to get the template
36    $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t')));
37    if(!$tpl) $tpl = $conf['template'];
38
39    // array of core files
40    $files = array(
41                DOKU_INC.'lib/scripts/jquery/jquery.cookie.js',
42                DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js',
43                DOKU_INC."lib/scripts/fileuploader.js",
44                DOKU_INC."lib/scripts/fileuploaderextended.js",
45                DOKU_INC.'lib/scripts/helpers.js',
46                DOKU_INC.'lib/scripts/delay.js',
47                DOKU_INC.'lib/scripts/cookie.js',
48                DOKU_INC.'lib/scripts/script.js',
49                DOKU_INC.'lib/scripts/qsearch.js',
50                DOKU_INC.'lib/scripts/search.js',
51                DOKU_INC.'lib/scripts/tree.js',
52                DOKU_INC.'lib/scripts/index.js',
53                DOKU_INC.'lib/scripts/textselection.js',
54                DOKU_INC.'lib/scripts/toolbar.js',
55                DOKU_INC.'lib/scripts/edit.js',
56                DOKU_INC.'lib/scripts/editor.js',
57                DOKU_INC.'lib/scripts/locktimer.js',
58                DOKU_INC.'lib/scripts/linkwiz.js',
59                DOKU_INC.'lib/scripts/media.js',
60                DOKU_INC.'lib/scripts/compatibility.js',
61# disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
62                DOKU_INC.'lib/scripts/behaviour.js',
63                DOKU_INC.'lib/scripts/page.js',
64                tpl_incdir($tpl).'script.js',
65            );
66
67    // add possible plugin scripts and userscript
68    $files   = array_merge($files,js_pluginscripts());
69    if(!empty($config_cascade['userscript']['default'])) {
70        foreach($config_cascade['userscript']['default'] as $userscript) {
71            $files[] = $userscript;
72        }
73    }
74
75    // Let plugins decide to either put more scripts here or to remove some
76    trigger_event('JS_SCRIPT_LIST', $files);
77
78    // The generated script depends on some dynamic options
79    $cache = new cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].md5(serialize($files)),'.js');
80    $cache->_event = 'JS_CACHE_USE';
81
82    $cache_files = array_merge($files, getConfigFiles('main'));
83    $cache_files[] = __FILE__;
84
85    // check cache age & handle conditional request
86    // This may exit if a cache can be used
87    $cache_ok = $cache->useCache(array('files' => $cache_files));
88    http_cached($cache->cache, $cache_ok);
89
90    // start output buffering and build the script
91    ob_start();
92
93    // add some global variables
94    print "var DOKU_BASE   = '".DOKU_BASE."';";
95    print "var DOKU_TPL    = '".tpl_basedir($tpl)."';";
96    print "var DOKU_COOKIE_PARAM = " . json_encode(
97            array(
98                 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'],
99                 'secure' => $conf['securecookie'] && is_ssl()
100            )).";";
101    // FIXME: Move those to JSINFO
102    print "Object.defineProperty(window, 'DOKU_UHN', { get: function() {".
103          "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');".
104          "return JSINFO.useHeadingNavigation; } });";
105    print "Object.defineProperty(window, 'DOKU_UHC', { get: function() {".
106          "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');".
107          "return JSINFO.useHeadingContent; } });";
108
109    // load JS specific translations
110    $lang['js']['plugins'] = js_pluginstrings();
111    $templatestrings = js_templatestrings($tpl);
112    if(!empty($templatestrings)) {
113        $lang['js']['template'] = $templatestrings;
114    }
115    echo 'LANG = '.json_encode($lang['js']).";\n";
116
117    // load toolbar
118    toolbar_JSdefines('toolbar');
119
120    // load files
121    foreach($files as $file){
122        if(!file_exists($file)) continue;
123        $ismin = (substr($file,-7) == '.min.js');
124        $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0);
125
126        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
127        if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
128        if ($debugjs) echo "\ntry {\n";
129        js_load($file);
130        if ($debugjs) echo "\n} catch (e) {\n   logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n";
131        if($ismin) echo "\n/* END NOCOMPRESS */\n";
132        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
133    }
134
135    // init stuff
136    if($conf['locktime'] != 0){
137        js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")");
138    }
139    // init hotkeys - must have been done after init of toolbar
140# disabled for FS#1958    js_runonstart('initializeHotkeys()');
141
142    // end output buffering and get contents
143    $js = ob_get_contents();
144    ob_end_clean();
145
146    // strip any source maps
147    stripsourcemaps($js);
148
149    // compress whitespace and comments
150    if($conf['compress']){
151        $js = js_compress($js);
152    }
153
154    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
155
156    http_cached_finish($cache->cache, $js);
157}
158
159/**
160 * Load the given file, handle include calls and print it
161 *
162 * @author Andreas Gohr <andi@splitbrain.org>
163 *
164 * @param string $file filename path to file
165 */
166function js_load($file){
167    if(!file_exists($file)) return;
168    static $loaded = array();
169
170    $data = io_readFile($file);
171    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
172        $ifile = $match[2];
173
174        // is it a include_once?
175        if($match[1]){
176            $base = utf8_basename($ifile);
177            if(array_key_exists($base, $loaded) && $loaded[$base] === true){
178                $data  = str_replace($match[0], '' ,$data);
179                continue;
180            }
181            $loaded[$base] = true;
182        }
183
184        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
185
186        if(file_exists($ifile)){
187            $idata = io_readFile($ifile);
188        }else{
189            $idata = '';
190        }
191        $data  = str_replace($match[0],$idata,$data);
192    }
193    echo "$data\n";
194}
195
196/**
197 * Returns a list of possible Plugin Scripts (no existance check here)
198 *
199 * @author Andreas Gohr <andi@splitbrain.org>
200 *
201 * @return array
202 */
203function js_pluginscripts(){
204    $list = array();
205    $plugins = plugin_list();
206    foreach ($plugins as $p){
207        $list[] = DOKU_PLUGIN."$p/script.js";
208    }
209    return $list;
210}
211
212/**
213 * Return an two-dimensional array with strings from the language file of each plugin.
214 *
215 * - $lang['js'] must be an array.
216 * - Nothing is returned for plugins without an entry for $lang['js']
217 *
218 * @author Gabriel Birke <birke@d-scribe.de>
219 *
220 * @return array
221 */
222function js_pluginstrings() {
223    global $conf, $config_cascade;
224    $pluginstrings = array();
225    $plugins = plugin_list();
226    foreach($plugins as $p) {
227        $path = DOKU_PLUGIN . $p . '/lang/';
228
229        if(isset($lang)) unset($lang);
230        if(file_exists($path . "en/lang.php")) {
231            include $path . "en/lang.php";
232        }
233        foreach($config_cascade['lang']['plugin'] as $config_file) {
234            if(file_exists($config_file . $p . '/en/lang.php')) {
235                include($config_file . $p . '/en/lang.php');
236            }
237        }
238        if(isset($conf['lang']) && $conf['lang'] != 'en') {
239            if(file_exists($path . $conf['lang'] . "/lang.php")) {
240                include($path . $conf['lang'] . '/lang.php');
241            }
242            foreach($config_cascade['lang']['plugin'] as $config_file) {
243                if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) {
244                    include($config_file . $p . '/' . $conf['lang'] . '/lang.php');
245                }
246            }
247        }
248
249        if(isset($lang['js'])) {
250            $pluginstrings[$p] = $lang['js'];
251        }
252    }
253    return $pluginstrings;
254}
255
256/**
257 * Return an two-dimensional array with strings from the language file of current active template.
258 *
259 * - $lang['js'] must be an array.
260 * - Nothing is returned for template without an entry for $lang['js']
261 *
262 * @param string $tpl
263 * @return array
264 */
265function js_templatestrings($tpl) {
266    global $conf, $config_cascade;
267
268    $path = tpl_incdir() . 'lang/';
269
270    $templatestrings = array();
271    if(file_exists($path . "en/lang.php")) {
272        include $path . "en/lang.php";
273    }
274    foreach($config_cascade['lang']['template'] as $config_file) {
275        if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
276            include($config_file . $conf['template'] . '/en/lang.php');
277        }
278    }
279    if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) {
280        include $path . $conf['lang'] . "/lang.php";
281    }
282    if(isset($conf['lang']) && $conf['lang'] != 'en') {
283        if(file_exists($path . $conf['lang'] . "/lang.php")) {
284            include $path . $conf['lang'] . "/lang.php";
285        }
286        foreach($config_cascade['lang']['template'] as $config_file) {
287            if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
288                include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
289            }
290        }
291    }
292
293    if(isset($lang['js'])) {
294        $templatestrings[$tpl] = $lang['js'];
295    }
296    return $templatestrings;
297}
298
299/**
300 * Escapes a String to be embedded in a JavaScript call, keeps \n
301 * as newline
302 *
303 * @author Andreas Gohr <andi@splitbrain.org>
304 *
305 * @param string $string
306 * @return string
307 */
308function js_escape($string){
309    return str_replace('\\\\n','\\n',addslashes($string));
310}
311
312/**
313 * Adds the given JavaScript code to the window.onload() event
314 *
315 * @author Andreas Gohr <andi@splitbrain.org>
316 *
317 * @param string $func
318 */
319function js_runonstart($func){
320    echo "jQuery(function(){ $func; });".NL;
321}
322
323/**
324 * Strip comments and whitespaces from given JavaScript Code
325 *
326 * This is a port of Nick Galbreath's python tool jsstrip.py which is
327 * released under BSD license. See link for original code.
328 *
329 * @author Nick Galbreath <nickg@modp.com>
330 * @author Andreas Gohr <andi@splitbrain.org>
331 * @link   http://code.google.com/p/jsstrip/
332 *
333 * @param string $s
334 * @return string
335 */
336function js_compress($s){
337    $s = ltrim($s);     // strip all initial whitespace
338    $s .= "\n";
339    $i = 0;             // char index for input string
340    $j = 0;             // char forward index for input string
341    $line = 0;          // line number of file (close to it anyways)
342    $slen = strlen($s); // size of input string
343    $lch  = '';         // last char added
344    $result = '';       // we store the final result here
345
346    // items that don't need spaces next to them
347    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
348
349    // items which need a space if the sign before and after whitespace is equal.
350    // E.g. '+ ++' may not be compressed to '+++' --> syntax error.
351    $ops = "+-";
352
353    $regex_starters = array("(", "=", "[", "," , ":", "!", "&", "|");
354
355    $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B");
356
357    while($i < $slen){
358        // skip all "boring" characters.  This is either
359        // reserved word (e.g. "for", "else", "if") or a
360        // variable/object/method (e.g. "foo.color")
361        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
362            $result .= $s{$i};
363            $i = $i + 1;
364        }
365
366        $ch = $s{$i};
367        // multiline comments (keeping IE conditionals)
368        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
369            $endC = strpos($s,'*/',$i+2);
370            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
371
372            // check if this is a NOCOMPRESS comment
373            if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){
374                $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2);
375                if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR);
376
377                // verbatim copy contents, trimming but putting it on its own line
378                $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars
379                $i = $endNC + 20; // END comment = 20 chars
380            }else{
381                $i = $endC + 2;
382            }
383            continue;
384        }
385
386        // singleline
387        if($ch == '/' && $s{$i+1} == '/'){
388            $endC = strpos($s,"\n",$i+2);
389            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
390            $i = $endC;
391            continue;
392        }
393
394        // tricky.  might be an RE
395        if($ch == '/'){
396            // rewind, skip white space
397            $j = 1;
398            while(in_array($s{$i-$j}, $whitespaces_chars)){
399                $j = $j + 1;
400            }
401            if( in_array($s{$i-$j}, $regex_starters) ){
402                // yes, this is an re
403                // now move forward and find the end of it
404                $j = 1;
405                while($s{$i+$j} != '/'){
406                    if($s{$i+$j} == '\\') $j = $j + 2;
407                    else $j++;
408                }
409                $result .= substr($s,$i,$j+1);
410                $i = $i + $j + 1;
411                continue;
412            }
413        }
414
415        // double quote strings
416        if($ch == '"'){
417            $j = 1;
418            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
419                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
420                    $j += 2;
421                }else{
422                    $j += 1;
423                }
424            }
425            $string  = substr($s,$i,$j+1);
426            // remove multiline markers:
427            $string  = str_replace("\\\n",'',$string);
428            $result .= $string;
429            $i = $i + $j + 1;
430            continue;
431        }
432
433        // single quote strings
434        if($ch == "'"){
435            $j = 1;
436            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
437                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
438                    $j += 2;
439                }else{
440                    $j += 1;
441                }
442            }
443            $string = substr($s,$i,$j+1);
444            // remove multiline markers:
445            $string  = str_replace("\\\n",'',$string);
446            $result .= $string;
447            $i = $i + $j + 1;
448            continue;
449        }
450
451        // whitespaces
452        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
453            $lch = substr($result,-1);
454
455            // Only consider deleting whitespace if the signs before and after
456            // are not equal and are not an operator which may not follow itself.
457            if ($i+1 < $slen && ((!$lch || $s[$i+1] == ' ')
458                || $lch != $s[$i+1]
459                || strpos($ops,$s[$i+1]) === false)) {
460                // leading spaces
461                if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
462                    $i = $i + 1;
463                    continue;
464                }
465                // trailing spaces
466                //  if this ch is space AND the last char processed
467                //  is special, then skip the space
468                if($lch && (strpos($chars,$lch) !== false)){
469                    $i = $i + 1;
470                    continue;
471                }
472            }
473
474            // else after all of this convert the "whitespace" to
475            // a single space.  It will get appended below
476            $ch = ' ';
477        }
478
479        // other chars
480        $result .= $ch;
481        $i = $i + 1;
482    }
483
484    return trim($result);
485}
486
487//Setup VIM: ex: et ts=4 :
488