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