xref: /dokuwiki/lib/exe/js.php (revision 73f799f0aa6144ef07d0af5a050b845a88ba991d)
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 = getCacheName('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.js');
36
37    // array of core files
38    $files = array(
39                DOKU_INC.'lib/scripts/helpers.js',
40                DOKU_INC.'lib/scripts/events.js',
41                DOKU_INC.'lib/scripts/delay.js',
42                DOKU_INC.'lib/scripts/cookie.js',
43                DOKU_INC.'lib/scripts/script.js',
44                DOKU_INC.'lib/scripts/tw-sack.js',
45                DOKU_INC.'lib/scripts/ajax.js',
46                DOKU_INC.'lib/scripts/index.js',
47                DOKU_INC.'lib/scripts/drag.js',
48                DOKU_INC.'lib/scripts/textselection.js',
49                DOKU_INC.'lib/scripts/toolbar.js',
50                DOKU_INC.'lib/scripts/edit.js',
51                DOKU_INC.'lib/scripts/linkwiz.js',
52                DOKU_INC.'lib/scripts/media.js',
53                DOKU_INC.'lib/scripts/subscriptions.js',
54# disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
55                DOKU_TPLINC.'script.js',
56            );
57
58    // add possible plugin scripts and userscript
59    $files   = array_merge($files,js_pluginscripts());
60    if(isset($config_cascade['userscript']['default'])){
61        $files[] = $config_cascade['userscript']['default'];
62    }
63
64    // check cache age & handle conditional request
65    header('Cache-Control: public, max-age=3600');
66    header('Pragma: public');
67    if(js_cacheok($cache,$files)){
68        http_conditionalRequest(filemtime($cache));
69        if($conf['allowdebug']) header("X-CacheUsed: $cache");
70
71        // finally send output
72        if ($conf['gzip_output'] && http_gzip_valid($cache)) {
73            header('Vary: Accept-Encoding');
74            header('Content-Encoding: gzip');
75            readfile($cache.".gz");
76        } else {
77            if (!http_sendfile($cache)) readfile($cache);
78        }
79        return;
80    } else {
81        http_conditionalRequest(time());
82    }
83
84    // start output buffering and build the script
85    ob_start();
86
87    // add some global variables
88    print "var DOKU_BASE   = '".DOKU_BASE."';";
89    print "var DOKU_TPL    = '".DOKU_TPL."';";
90    print "var DOKU_UHN    = ".((int) useHeading('navigation')).";";
91    print "var DOKU_UHC    = ".((int) useHeading('content')).";";
92
93    // load JS specific translations
94    $json = new JSON();
95    $lang['js']['plugins'] = js_pluginstrings();
96    echo 'LANG = '.$json->encode($lang['js']).";\n";
97
98    // load toolbar
99    toolbar_JSdefines('toolbar');
100
101    // load files
102    foreach($files as $file){
103        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
104        js_load($file);
105        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
106    }
107
108
109    // init stuff
110    js_runonstart("addEvent(document,'click',closePopups)");
111    js_runonstart('addTocToggle()');
112    js_runonstart("initSizeCtl('size__ctl','wiki__text')");
113    js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)");
114    if($conf['locktime'] != 0){
115        js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")");
116    }
117    js_runonstart('scrollToMarker()');
118    js_runonstart('focusMarker()');
119    // init hotkeys - must have been done after init of toolbar
120# disabled for FS#1958    js_runonstart('initializeHotkeys()');
121
122    // end output buffering and get contents
123    $js = ob_get_contents();
124    ob_end_clean();
125
126    // compress whitespace and comments
127    if($conf['compress']){
128        $js = js_compress($js);
129    }
130
131    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
132
133    // save cache file
134    io_saveFile($cache,$js);
135    if(function_exists('gzopen')) io_saveFile("$cache.gz",$js);
136
137    // finally send output
138    if ($conf['gzip_output']) {
139        header('Vary: Accept-Encoding');
140        header('Content-Encoding: gzip');
141        print gzencode($js,9,FORCE_GZIP);
142    } else {
143        print $js;
144    }
145}
146
147/**
148 * Load the given file, handle include calls and print it
149 *
150 * @author Andreas Gohr <andi@splitbrain.org>
151 */
152function js_load($file){
153    if(!@file_exists($file)) return;
154    static $loaded = array();
155
156    $data = io_readFile($file);
157    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
158        $ifile = $match[2];
159
160        // is it a include_once?
161        if($match[1]){
162            $base = basename($ifile);
163            if($loaded[$base]) continue;
164            $loaded[$base] = true;
165        }
166
167        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
168
169        if(@file_exists($ifile)){
170            $idata = io_readFile($ifile);
171        }else{
172            $idata = '';
173        }
174        $data  = str_replace($match[0],$idata,$data);
175    }
176    echo $data;
177}
178
179/**
180 * Checks if a JavaScript Cache file still is valid
181 *
182 * @author Andreas Gohr <andi@splitbrain.org>
183 */
184function js_cacheok($cache,$files){
185    if(isset($_REQUEST['purge'])) return false; //support purge request
186
187    $ctime = @filemtime($cache);
188    if(!$ctime) return false; //There is no cache
189
190    // some additional files to check
191    $files = array_merge($files, getConfigFiles('main'));
192    $files[] = DOKU_CONF.'userscript.js';
193    $files[] = __FILE__;
194
195    // now walk the files
196    foreach($files as $file){
197        if(@filemtime($file) > $ctime){
198            return false;
199        }
200    }
201    return true;
202}
203
204/**
205 * Returns a list of possible Plugin Scripts (no existance check here)
206 *
207 * @author Andreas Gohr <andi@splitbrain.org>
208 */
209function js_pluginscripts(){
210    $list = array();
211    $plugins = plugin_list();
212    foreach ($plugins as $p){
213        $list[] = DOKU_PLUGIN."$p/script.js";
214    }
215    return $list;
216}
217
218/**
219 * Return an two-dimensional array with strings from the language file of each plugin.
220 *
221 * - $lang['js'] must be an array.
222 * - Nothing is returned for plugins without an entry for $lang['js']
223 *
224 * @author Gabriel Birke <birke@d-scribe.de>
225 */
226function js_pluginstrings()
227{
228    global $conf;
229    $pluginstrings = array();
230    $plugins = plugin_list();
231    foreach ($plugins as $p){
232        if (isset($lang)) unset($lang);
233        if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) {
234            include DOKU_PLUGIN."$p/lang/en/lang.php";
235        }
236        if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) {
237            include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php";
238        }
239        if (isset($lang['js'])) {
240            $pluginstrings[$p] = $lang['js'];
241        }
242    }
243    return $pluginstrings;
244}
245
246/**
247 * Escapes a String to be embedded in a JavaScript call, keeps \n
248 * as newline
249 *
250 * @author Andreas Gohr <andi@splitbrain.org>
251 */
252function js_escape($string){
253    return str_replace('\\\\n','\\n',addslashes($string));
254}
255
256/**
257 * Adds the given JavaScript code to the window.onload() event
258 *
259 * @author Andreas Gohr <andi@splitbrain.org>
260 */
261function js_runonstart($func){
262    echo "addInitEvent(function(){ $func; });".NL;
263}
264
265/**
266 * Strip comments and whitespaces from given JavaScript Code
267 *
268 * This is a port of Nick Galbreath's python tool jsstrip.py which is
269 * released under BSD license. See link for original code.
270 *
271 * @author Nick Galbreath <nickg@modp.com>
272 * @author Andreas Gohr <andi@splitbrain.org>
273 * @link   http://code.google.com/p/jsstrip/
274 */
275function js_compress($s){
276    $s = ltrim($s);     // strip all initial whitespace
277    $s .= "\n";
278    $i = 0;             // char index for input string
279    $j = 0;             // char forward index for input string
280    $line = 0;          // line number of file (close to it anyways)
281    $slen = strlen($s); // size of input string
282    $lch  = '';         // last char added
283    $result = '';       // we store the final result here
284
285    // items that don't need spaces next to them
286    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
287
288    $regex_starters = array("(", "=", "[", "," , ":");
289
290    $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B");
291
292    while($i < $slen){
293        // skip all "boring" characters.  This is either
294        // reserved word (e.g. "for", "else", "if") or a
295        // variable/object/method (e.g. "foo.color")
296        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
297            $result .= $s{$i};
298            $i = $i + 1;
299        }
300
301        $ch = $s{$i};
302        // multiline comments (keeping IE conditionals)
303        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
304            $endC = strpos($s,'*/',$i+2);
305            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
306            $i = $endC + 2;
307            continue;
308        }
309
310        // singleline
311        if($ch == '/' && $s{$i+1} == '/'){
312            $endC = strpos($s,"\n",$i+2);
313            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
314            $i = $endC;
315            continue;
316        }
317
318        // tricky.  might be an RE
319        if($ch == '/'){
320            // rewind, skip white space
321            $j = 1;
322            while(in_array($s{$i-$j}, $whitespaces_chars)){
323                $j = $j + 1;
324            }
325            if( in_array($s{$i-$j}, $regex_starters) ){
326                // yes, this is an re
327                // now move forward and find the end of it
328                $j = 1;
329                while($s{$i+$j} != '/'){
330                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
331                        $j = $j + 1;
332                    }
333                    if($s{$i+$j} == '\\') $j = $j + 2;
334                }
335                $result .= substr($s,$i,$j+1);
336                $i = $i + $j + 1;
337                continue;
338            }
339        }
340
341        // double quote strings
342        if($ch == '"'){
343            $j = 1;
344            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
345                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
346                    $j += 2;
347                }else{
348                    $j += 1;
349                }
350            }
351            $result .= substr($s,$i,$j+1);
352            $i = $i + $j + 1;
353            continue;
354        }
355
356        // single quote strings
357        if($ch == "'"){
358            $j = 1;
359            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
360                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
361                    $j += 2;
362                }else{
363                    $j += 1;
364                }
365            }
366            $result .= substr($s,$i,$j+1);
367            $i = $i + $j + 1;
368            continue;
369        }
370
371        // whitespaces
372        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
373            // leading spaces
374            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
375                $i = $i + 1;
376                continue;
377            }
378            // trailing spaces
379            //  if this ch is space AND the last char processed
380            //  is special, then skip the space
381            $lch = substr($result,-1);
382            if($lch && (strpos($chars,$lch) !== false)){
383                $i = $i + 1;
384                continue;
385            }
386            // else after all of this convert the "whitespace" to
387            // a single space.  It will get appended below
388            $ch = ' ';
389        }
390
391        // other chars
392        $result .= $ch;
393        $i = $i + 1;
394    }
395
396    return trim($result);
397}
398
399//Setup VIM: ex: et ts=4 :
400