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