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