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