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