xref: /dokuwiki/lib/exe/js.php (revision 45be45c58fffce1b3e57942130b69600cc426457)
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} != '"' && ($i+$j < $len)){
290                if( $s{$i+$j} == '\\' && $s{$i+$j+1} == '"' ){
291                    $j += 2;
292                }else{
293                    $j += 1;
294                }
295            }
296            echo substr($s,$i,$j+1);
297            $i = $i + $j + 1;
298            continue;
299        }
300
301        // single quote strings
302        if($ch == "'"){
303            $j = 1;
304            while( $s{$i+$j} != "'" && ($i+$j < $len)){
305                if( $s{$i+$j} == '\\' && $s{$i+$j+1} == "'" ){
306                    $j += 2;
307                }else{
308                    $j += 1;
309                }
310            }
311            echo substr($s,$i,$j+1);
312            $i = $i + $j + 1;
313            continue;
314        }
315
316        // newlines
317        if($ch == "\n" || $ch == "\r"){
318            $i = $i+1;
319            continue;
320        }
321
322        // leading spaces
323        if( ( $ch == ' ' ||
324              $ch == "\n" ||
325              $ch == "\t" ) &&
326            !preg_match('/['.$chars.']/',$s{$i+1}) ){
327            $i = $i+1;
328            continue;
329        }
330
331        // trailing spaces
332        if( ( $ch == ' ' ||
333              $ch == "\n" ||
334              $ch == "\t" ) &&
335            !preg_match('/['.$chars.']/',$s{$i-1}) ){
336            $i = $i+1;
337            continue;
338        }
339
340        // other chars
341        echo $ch;
342        $i = $i + 1;
343    }
344
345
346    $out = ob_get_contents();
347    ob_end_clean();
348    return $out;
349}
350
351//Setup VIM: ex: et ts=4 enc=utf-8 :
352?>
353