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