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