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