xref: /dokuwiki/lib/exe/js.php (revision 9a3288d64bca5fe18d3c72e8a6a73d064ac15e43)
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',realpath(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.$write,'.js');
39
40    // Array of needed files
41    $files = array(
42                DOKU_INC.'lib/scripts/events.js',
43                DOKU_INC.'lib/scripts/cookie.js',
44                DOKU_INC.'lib/scripts/script.js',
45                DOKU_INC.'lib/scripts/tw-sack.js',
46                DOKU_INC.'lib/scripts/ajax.js',
47                DOKU_INC.'lib/scripts/domLib.js',
48                DOKU_INC.'lib/scripts/domTT.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        readfile($cache);
70        return;
71    } else {
72        http_conditionalRequest(time());
73    }
74
75    // start output buffering and build the script
76    ob_start();
77
78    // add some global variables
79    print "var DOKU_BASE   = '".DOKU_BASE."';";
80
81    //FIXME: move thes into LANG
82    print "var alertText   = '".js_escape($lang['qb_alert'])."';";
83    print "var notSavedYet = '".js_escape($lang['notsavedyet'])."';";
84    print "var reallyDel   = '".js_escape($lang['del_confirm'])."';";
85
86    // load JS specific translations
87    $json = new JSON();
88    echo 'LANG = '.$json->encode($lang['js']).";\n";
89
90    // load files
91    foreach($files as $file){
92        echo "\n\n/* XXXXXXXXXX begin of $file XXXXXXXXXX */\n\n";
93        @readfile($file);
94        echo "\n\n/* XXXXXXXXXX end of $file XXXXXXXXXX */\n\n";
95    }
96
97    // init stuff
98    js_runonstart("ajax_qsearch.init('qsearch__in','qsearch__out')");
99    js_runonstart("addEvent(document,'click',closePopups)");
100    js_runonstart('addTocToggle()');
101
102    if($edit){
103        // size controls
104        js_runonstart("initSizeCtl('size__ctl','wiki__text')");
105
106        if($write){
107            require_once(DOKU_INC.'inc/toolbar.php');
108            toolbar_JSdefines('toolbar');
109            js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)");
110
111            // add pageleave check
112            js_runonstart("initChangeCheck('".js_escape($lang['notsavedyet'])."')");
113
114            // add lock timer
115            js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")");
116
117            // load spell checker
118            if($conf['spellchecker']){
119                js_runonstart("ajax_spell.init('".
120                               js_escape($lang['spell_start'])."','".
121                               js_escape($lang['spell_stop'])."','".
122                               js_escape($lang['spell_wait'])."','".
123                               js_escape($lang['spell_noerr'])."','".
124                               js_escape($lang['spell_nosug'])."','".
125                               js_escape($lang['spell_change'])."')");
126            }
127        }
128    }
129
130    // load plugin scripts (suppress warnings for missing ones)
131    foreach($plugins as $plugin){
132        echo "\n\n/* XXXXXXXXXX begin of $file XXXXXXXXXX */\n\n";
133        @readfile($plugin);
134        echo "\n\n/* XXXXXXXXXX end of $file XXXXXXXXXX */\n\n";
135    }
136
137    // load user script
138    @readfile(DOKU_CONF.'userscript.js');
139
140    // add scroll event and tooltip rewriting
141    js_runonstart('updateAccessKeyTooltip()');
142    js_runonstart('scrollToMarker()');
143
144    // initialize init pseudo event
145    echo 'if (document.addEventListener) {'.NL;
146    echo '    document.addEventListener("DOMContentLoaded", window.fireoninit, null);'.NL;
147    echo '}'.NL;
148    echo 'addEvent(window,"load",window.fireoninit);'.NL;
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    // save cache file
160    io_saveFile($cache,$js);
161
162    // finally send output
163    print $js;
164}
165
166/**
167 * Checks if a JavaScript Cache file still is valid
168 *
169 * @author Andreas Gohr <andi@splitbrain.org>
170 */
171function js_cacheok($cache,$files){
172    $ctime = @filemtime($cache);
173    if(!$ctime) return false; //There is no cache
174
175    // some additional files to check
176    $files[] = DOKU_CONF.'dokuwiki.php';
177    $files[] = DOKU_CONF.'local.php';
178    $files[] = DOKU_CONF.'userscript.js';
179    $files[] = __FILE__;
180
181    // now walk the files
182    foreach($files as $file){
183        if(@filemtime($file) > $ctime){
184            return false;
185        }
186    }
187    return true;
188}
189
190/**
191 * Returns a list of possible Plugin Scripts (no existance check here)
192 *
193 * @author Andreas Gohr <andi@splitbrain.org>
194 */
195function js_pluginscripts(){
196    $list = array();
197    $plugins = plugin_list();
198    foreach ($plugins as $p){
199        $list[] = DOKU_PLUGIN."$p/script.js";
200    }
201    return $list;
202}
203
204/**
205 * Escapes a String to be embedded in a JavaScript call, keeps \n
206 * as newline
207 *
208 * @author Andreas Gohr <andi@splitbrain.org>
209 */
210function js_escape($string){
211    return str_replace('\\\\n','\\n',addslashes($string));
212}
213
214/**
215 * Adds the given JavaScript code to the window.onload() event
216 *
217 * @author Andreas Gohr <andi@splitbrain.org>
218 */
219function js_runonstart($func){
220    echo "addInitEvent(function(){ $func; });".NL;
221}
222
223/**
224 * Strip comments and whitespaces from given JavaScript Code
225 *
226 * This is a rewrite of Nick Galbreaths python tool jsstrip.py which is
227 * released under BSD license. See link for original code.
228 *
229 * @author Nick Galbreath <nickg@modp.com>
230 * @author Andreas Gohr <andi@splitbrain.org>
231 * @link http://modp.com/release/jsstrip/
232 */
233function js_compress($s){
234    $i = 0;
235    $line = 0;
236    $s .= "\n";
237    $len = strlen($s);
238
239    // items that don't need spaces next to them
240    $chars = '^&|!+\-*\/%=:;,{}()<>% \t\n\r';
241
242    ob_start();
243    while($i < $len){
244        $ch = $s{$i};
245
246        // multiline comments
247        if($ch == '/' && $s{$i+1} == '*'){
248            $endC = strpos($s,'*/',$i+2);
249            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
250            $i = $endC + 2;
251            continue;
252        }
253
254        // singleline
255        if($ch == '/' && $s{$i+1} == '/'){
256            $endC = strpos($s,"\n",$i+2);
257            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
258            $i = $endC;
259            continue;
260        }
261
262        // tricky.  might be an RE
263        if($ch == '/'){
264            // rewind, skip white space
265            $j = 1;
266            while($s{$i-$j} == ' '){
267                $j = $j + 1;
268            }
269            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
270                // yes, this is an re
271                // now move forward and find the end of it
272                $j = 1;
273                while($s{$i+$j} != '/'){
274                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
275                        $j = $j + 1;
276                    }
277                    if($s{$i+$j} == '\\') $j = $j + 2;
278                }
279                echo substr($s,$i,$j+1);
280                $i = $i + $j + 1;
281                continue;
282            }
283        }
284
285        // double quote strings
286        if($ch == '"'){
287            $j = 1;
288            while( $s{$i+$j} != '"' ){
289                while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '"') ){
290                    $j = $j + 1;
291                }
292                if($s{$i+$j} == '\\') $j = $j + 2;
293            }
294            echo substr($s,$i,$j+1);
295            $i = $i + $j + 1;
296            continue;
297        }
298
299        // single quote strings
300        if($ch == "'"){
301            $j = 1;
302            while( $s{$i+$j} != "'" ){
303                while( ($s{$i+$j} != '\\') && ($s{$i+$j} != "'") ){
304                    $j = $j + 1;
305                }
306                if ($s{$i+$j} == '\\') $j = $j + 2;
307            }
308            echo substr($s,$i,$j+1);
309            $i = $i + $j + 1;
310            continue;
311        }
312
313        // newlines
314        if($ch == "\n" || $ch == "\r"){
315            $i = $i+1;
316            continue;
317        }
318
319        // leading spaces
320        if( ( $ch == ' ' ||
321              $ch == "\n" ||
322              $ch == "\t" ) &&
323            !preg_match('/['.$chars.']/',$s{$i+1}) ){
324            $i = $i+1;
325            continue;
326        }
327
328        // trailing spaces
329        if( ( $ch == ' ' ||
330              $ch == "\n" ||
331              $ch == "\t" ) &&
332            !preg_match('/['.$chars.']/',$s{$i-1}) ){
333            $i = $i+1;
334            continue;
335        }
336
337        // other chars
338        echo $ch;
339        $i = $i + 1;
340    }
341
342
343    $out = ob_get_contents();
344    ob_end_clean();
345    return $out;
346}
347
348//Setup VIM: ex: et ts=4 enc=utf-8 :
349?>
350