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