xref: /dokuwiki/lib/exe/js.php (revision 8dbc24f23699c45b6e3e9cb3edf765187b82f89b)
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        if (@file_exists($plugin)) {
134          echo "\n\n/* XXXXXXXXXX begin of $plugin XXXXXXXXXX */\n\n";
135          @readfile($plugin);
136          echo "\n\n/* XXXXXXXXXX end of $plugin XXXXXXXXXX */\n\n";
137        }
138    }
139
140    // load user script
141    @readfile(DOKU_CONF.'userscript.js');
142
143    // add scroll event and tooltip rewriting
144    js_runonstart('updateAccessKeyTooltip()');
145    js_runonstart('scrollToMarker()');
146    js_runonstart('focusMarker()');
147
148/*    // initialize init pseudo event
149    echo 'if (document.addEventListener) {'.NL;
150    echo '    document.addEventListener("DOMContentLoaded", window.fireoninit, null);'.NL;
151    echo '}'.NL;
152    echo 'addEvent(window,"load",window.fireoninit);'.NL;*/
153
154    // end output buffering and get contents
155    $js = ob_get_contents();
156    ob_end_clean();
157
158    // compress whitespace and comments
159    if($conf['compress']){
160        $js = js_compress($js);
161    }
162
163    // save cache file
164    io_saveFile($cache,$js);
165
166    // finally send output
167    print $js;
168}
169
170/**
171 * Checks if a JavaScript Cache file still is valid
172 *
173 * @author Andreas Gohr <andi@splitbrain.org>
174 */
175function js_cacheok($cache,$files){
176    $ctime = @filemtime($cache);
177    if(!$ctime) return false; //There is no cache
178
179    // some additional files to check
180    $files[] = DOKU_CONF.'dokuwiki.php';
181    $files[] = DOKU_CONF.'local.php';
182    $files[] = DOKU_CONF.'userscript.js';
183    $files[] = __FILE__;
184
185    // now walk the files
186    foreach($files as $file){
187        if(@filemtime($file) > $ctime){
188            return false;
189        }
190    }
191    return true;
192}
193
194/**
195 * Returns a list of possible Plugin Scripts (no existance check here)
196 *
197 * @author Andreas Gohr <andi@splitbrain.org>
198 */
199function js_pluginscripts(){
200    $list = array();
201    $plugins = plugin_list();
202    foreach ($plugins as $p){
203        $list[] = DOKU_PLUGIN."$p/script.js";
204    }
205    return $list;
206}
207
208/**
209 * Escapes a String to be embedded in a JavaScript call, keeps \n
210 * as newline
211 *
212 * @author Andreas Gohr <andi@splitbrain.org>
213 */
214function js_escape($string){
215    return str_replace('\\\\n','\\n',addslashes($string));
216}
217
218/**
219 * Adds the given JavaScript code to the window.onload() event
220 *
221 * @author Andreas Gohr <andi@splitbrain.org>
222 */
223function js_runonstart($func){
224    echo "addInitEvent(function(){ $func; });".NL;
225}
226
227/**
228 * Strip comments and whitespaces from given JavaScript Code
229 *
230 * This is a rewrite of Nick Galbreaths python tool jsstrip.py which is
231 * released under BSD license. See link for original code.
232 *
233 * @author Nick Galbreath <nickg@modp.com>
234 * @author Andreas Gohr <andi@splitbrain.org>
235 * @link http://modp.com/release/jsstrip/
236 */
237function js_compress($s){
238    $i = 0;
239    $line = 0;
240    $s .= "\n";
241    $len = strlen($s);
242
243    // items that don't need spaces next to them
244    $chars = '^&|!+\-*\/%=\?:;,{}()<>% \t\n\r';
245
246    ob_start();
247    while($i < $len){
248        $ch = $s{$i};
249
250        // multiline comments (keeping IE conditionals)
251        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
252            $endC = strpos($s,'*/',$i+2);
253            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
254            $i = $endC + 2;
255            continue;
256        }
257
258        // singleline
259        if($ch == '/' && $s{$i+1} == '/'){
260            $endC = strpos($s,"\n",$i+2);
261            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
262            $i = $endC;
263            continue;
264        }
265
266        // tricky.  might be an RE
267        if($ch == '/'){
268            // rewind, skip white space
269            $j = 1;
270            while($s{$i-$j} == ' '){
271                $j = $j + 1;
272            }
273            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
274                // yes, this is an re
275                // now move forward and find the end of it
276                $j = 1;
277                while($s{$i+$j} != '/'){
278                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
279                        $j = $j + 1;
280                    }
281                    if($s{$i+$j} == '\\') $j = $j + 2;
282                }
283                echo substr($s,$i,$j+1);
284                $i = $i + $j + 1;
285                continue;
286            }
287        }
288
289        // double quote strings
290        if($ch == '"'){
291            $j = 1;
292            while( $s{$i+$j} != '"' && ($i+$j < $len)){
293                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
294                    $j += 2;
295                }else{
296                    $j += 1;
297                }
298            }
299            echo substr($s,$i,$j+1);
300            $i = $i + $j + 1;
301            continue;
302        }
303
304        // single quote strings
305        if($ch == "'"){
306            $j = 1;
307            while( $s{$i+$j} != "'" && ($i+$j < $len)){
308                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
309                    $j += 2;
310                }else{
311                    $j += 1;
312                }
313            }
314            echo substr($s,$i,$j+1);
315            $i = $i + $j + 1;
316            continue;
317        }
318
319        // newlines
320        if($ch == "\n" || $ch == "\r"){
321            $i = $i+1;
322            continue;
323        }
324
325        // leading spaces
326        if( ( $ch == ' ' ||
327              $ch == "\n" ||
328              $ch == "\t" ) &&
329            !preg_match('/['.$chars.']/',$s{$i+1}) ){
330            $i = $i+1;
331            continue;
332        }
333
334        // trailing spaces
335        if( ( $ch == ' ' ||
336              $ch == "\n" ||
337              $ch == "\t" ) &&
338            !preg_match('/['.$chars.']/',$s{$i-1}) ){
339            $i = $i+1;
340            continue;
341        }
342
343        // other chars
344        echo $ch;
345        $i = $i + 1;
346    }
347
348
349    $out = ob_get_contents();
350    ob_end_clean();
351    return $out;
352}
353
354//Setup VIM: ex: et ts=4 enc=utf-8 :
355?>
356