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