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