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