xref: /dokuwiki/lib/exe/js.php (revision 05ed2c25ea0dc45eef2af0f9f4176c939af41100)
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    js_runonstart("initChangeCheck('".js_escape($lang['notsavedyet'])."')");
111    js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")");
112    js_runonstart('scrollToMarker()');
113    js_runonstart('focusMarker()');
114
115    // end output buffering and get contents
116    $js = ob_get_contents();
117    ob_end_clean();
118
119    // compress whitespace and comments
120    if($conf['compress']){
121        $js = js_compress($js);
122    }
123
124    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
125
126    // save cache file
127    io_saveFile($cache,$js);
128    if(function_exists('gzopen')) io_saveFile("$cache.gz",$js);
129
130    // finally send output
131    if ($conf['gzip_output']) {
132        header('Vary: Accept-Encoding');
133        header('Content-Encoding: gzip');
134        print gzencode($js,9,FORCE_GZIP);
135    } else {
136        print $js;
137    }
138}
139
140/**
141 * Load the given file, handle include calls and print it
142 *
143 * @author Andreas Gohr <andi@splitbrain.org>
144 */
145function js_load($file){
146    if(!@file_exists($file)) return;
147    static $loaded = array();
148
149    $data = io_readFile($file);
150    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
151        $ifile = $match[2];
152
153        // is it a include_once?
154        if($match[1]){
155            $base = basename($ifile);
156            if($loaded[$base]) continue;
157            $loaded[$base] = true;
158        }
159
160        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
161
162        if(@file_exists($ifile)){
163            $idata = io_readFile($ifile);
164        }else{
165            $idata = '';
166        }
167        $data  = str_replace($match[0],$idata,$data);
168    }
169    echo $data;
170}
171
172/**
173 * Checks if a JavaScript Cache file still is valid
174 *
175 * @author Andreas Gohr <andi@splitbrain.org>
176 */
177function js_cacheok($cache,$files){
178    if(isset($_REQUEST['purge'])) return false; //support purge request
179
180    $ctime = @filemtime($cache);
181    if(!$ctime) return false; //There is no cache
182
183    // some additional files to check
184    $files = array_merge($files, getConfigFiles('main'));
185    $files[] = DOKU_CONF.'userscript.js';
186    $files[] = __FILE__;
187
188    // now walk the files
189    foreach($files as $file){
190        if(@filemtime($file) > $ctime){
191            return false;
192        }
193    }
194    return true;
195}
196
197/**
198 * Returns a list of possible Plugin Scripts (no existance check here)
199 *
200 * @author Andreas Gohr <andi@splitbrain.org>
201 */
202function js_pluginscripts(){
203    $list = array();
204    $plugins = plugin_list();
205    foreach ($plugins as $p){
206        $list[] = DOKU_PLUGIN."$p/script.js";
207    }
208    return $list;
209}
210
211/**
212 * Return an two-dimensional array with strings from the language file of each plugin.
213 *
214 * - $lang['js'] must be an array.
215 * - Nothing is returned for plugins without an entry for $lang['js']
216 *
217 * @author Gabriel Birke <birke@d-scribe.de>
218 */
219function js_pluginstrings()
220{
221    global $conf;
222    $pluginstrings = array();
223    $plugins = plugin_list();
224    foreach ($plugins as $p){
225        if (isset($lang)) unset($lang);
226        if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) {
227            include DOKU_PLUGIN."$p/lang/en/lang.php";
228        }
229        if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) {
230            include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php";
231        }
232        if (isset($lang['js'])) {
233            $pluginstrings[$p] = $lang['js'];
234        }
235    }
236    return $pluginstrings;
237}
238
239/**
240 * Escapes a String to be embedded in a JavaScript call, keeps \n
241 * as newline
242 *
243 * @author Andreas Gohr <andi@splitbrain.org>
244 */
245function js_escape($string){
246    return str_replace('\\\\n','\\n',addslashes($string));
247}
248
249/**
250 * Adds the given JavaScript code to the window.onload() event
251 *
252 * @author Andreas Gohr <andi@splitbrain.org>
253 */
254function js_runonstart($func){
255    echo "addInitEvent(function(){ $func; });".NL;
256}
257
258/**
259 * Strip comments and whitespaces from given JavaScript Code
260 *
261 * This is a port of Nick Galbreath's python tool jsstrip.py which is
262 * released under BSD license. See link for original code.
263 *
264 * @author Nick Galbreath <nickg@modp.com>
265 * @author Andreas Gohr <andi@splitbrain.org>
266 * @link   http://code.google.com/p/jsstrip/
267 */
268function js_compress($s){
269    $s = ltrim($s);     // strip all initial whitespace
270    $s .= "\n";
271    $i = 0;             // char index for input string
272    $j = 0;             // char forward index for input string
273    $line = 0;          // line number of file (close to it anyways)
274    $slen = strlen($s); // size of input string
275    $lch  = '';         // last char added
276    $result = '';       // we store the final result here
277
278    // items that don't need spaces next to them
279    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
280
281    $regex_starters = array("(", "=", "[", "," , ":");
282
283    $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B");
284
285    while($i < $slen){
286        // skip all "boring" characters.  This is either
287        // reserved word (e.g. "for", "else", "if") or a
288        // variable/object/method (e.g. "foo.color")
289        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
290            $result .= $s{$i};
291            $i = $i + 1;
292        }
293
294        $ch = $s{$i};
295        // multiline comments (keeping IE conditionals)
296        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
297            $endC = strpos($s,'*/',$i+2);
298            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
299            $i = $endC + 2;
300            continue;
301        }
302
303        // singleline
304        if($ch == '/' && $s{$i+1} == '/'){
305            $endC = strpos($s,"\n",$i+2);
306            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
307            $i = $endC;
308            continue;
309        }
310
311        // tricky.  might be an RE
312        if($ch == '/'){
313            // rewind, skip white space
314            $j = 1;
315            while(in_array($s{$i-$j}, $whitespaces_chars)){
316                $j = $j + 1;
317            }
318            if( in_array($s{$i-$j}, $regex_starters) ){
319                // yes, this is an re
320                // now move forward and find the end of it
321                $j = 1;
322                while($s{$i+$j} != '/'){
323                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
324                        $j = $j + 1;
325                    }
326                    if($s{$i+$j} == '\\') $j = $j + 2;
327                }
328                $result .= substr($s,$i,$j+1);
329                $i = $i + $j + 1;
330                continue;
331            }
332        }
333
334        // double quote strings
335        if($ch == '"'){
336            $j = 1;
337            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
338                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
339                    $j += 2;
340                }else{
341                    $j += 1;
342                }
343            }
344            $result .= substr($s,$i,$j+1);
345            $i = $i + $j + 1;
346            continue;
347        }
348
349        // single quote strings
350        if($ch == "'"){
351            $j = 1;
352            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
353                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
354                    $j += 2;
355                }else{
356                    $j += 1;
357                }
358            }
359            $result .= substr($s,$i,$j+1);
360            $i = $i + $j + 1;
361            continue;
362        }
363
364        // whitespaces
365        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
366            // leading spaces
367            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
368                $i = $i + 1;
369                continue;
370            }
371            // trailing spaces
372            //  if this ch is space AND the last char processed
373            //  is special, then skip the space
374            $lch = substr($result,-1);
375            if($lch && (strpos($chars,$lch) !== false)){
376                $i = $i + 1;
377                continue;
378            }
379            // else after all of this convert the "whitespace" to
380            // a single space.  It will get appended below
381            $ch = ' ';
382        }
383
384        // other chars
385        $result .= $ch;
386        $i = $i + 1;
387    }
388
389    return trim($result);
390}
391
392//Setup VIM: ex: et ts=4 enc=utf-8 :
393