xref: /dokuwiki/lib/exe/js.php (revision 73bea65db81c67139292d26518a078a4fae38f44)
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/helpers.js',
43                DOKU_INC.'lib/scripts/events.js',
44                DOKU_INC.'lib/scripts/cookie.js',
45                DOKU_INC.'lib/scripts/script.js',
46                DOKU_INC.'lib/scripts/tw-sack.js',
47                DOKU_INC.'lib/scripts/ajax.js',
48             );
49    if($edit){
50        if($write){
51            $files[] = DOKU_INC.'lib/scripts/edit.js';
52            if($conf['spellchecker']){
53                $files[] = DOKU_INC.'lib/scripts/spellcheck.js';
54            }
55        }
56        $files[] = DOKU_INC.'lib/scripts/media.js';
57    }
58    $files[] = DOKU_TPLINC.'script.js';
59
60    // get possible plugin scripts
61    $plugins = js_pluginscripts();
62
63    // check cache age & handle conditional request
64    header('Cache-Control: public, max-age=3600');
65    header('Pragma: public');
66    if(js_cacheok($cache,array_merge($files,$plugins))){
67        http_conditionalRequest(filemtime($cache));
68        if($conf['allowdebug']) header("X-CacheUsed: $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        if (@file_exists($plugin)) {
133          echo "\n\n/* XXXXXXXXXX begin of $plugin XXXXXXXXXX */\n\n";
134          @readfile($plugin);
135          echo "\n\n/* XXXXXXXXXX end of $plugin XXXXXXXXXX */\n\n";
136        }
137    }
138
139    // load user script
140    @readfile(DOKU_CONF.'userscript.js');
141
142    // add scroll event and tooltip rewriting
143    js_runonstart('updateAccessKeyTooltip()');
144    js_runonstart('scrollToMarker()');
145    js_runonstart('focusMarker()');
146
147    // end output buffering and get contents
148    $js = ob_get_contents();
149    ob_end_clean();
150
151    // compress whitespace and comments
152    if($conf['compress']){
153        $js = js_compress($js);
154    }
155
156    // save cache file
157    io_saveFile($cache,$js);
158
159    // finally send output
160    print $js;
161}
162
163/**
164 * Checks if a JavaScript Cache file still is valid
165 *
166 * @author Andreas Gohr <andi@splitbrain.org>
167 */
168function js_cacheok($cache,$files){
169    if($_REQUEST['purge']) return false; //support purge request
170
171    $ctime = @filemtime($cache);
172    if(!$ctime) return false; //There is no cache
173
174    // some additional files to check
175    $files[] = DOKU_CONF.'dokuwiki.php';
176    $files[] = DOKU_CONF.'local.php';
177    $files[] = DOKU_CONF.'userscript.js';
178    $files[] = __FILE__;
179
180    // now walk the files
181    foreach($files as $file){
182        if(@filemtime($file) > $ctime){
183            return false;
184        }
185    }
186    return true;
187}
188
189/**
190 * Returns a list of possible Plugin Scripts (no existance check here)
191 *
192 * @author Andreas Gohr <andi@splitbrain.org>
193 */
194function js_pluginscripts(){
195    $list = array();
196    $plugins = plugin_list();
197    foreach ($plugins as $p){
198        $list[] = DOKU_PLUGIN."$p/script.js";
199    }
200    return $list;
201}
202
203/**
204 * Escapes a String to be embedded in a JavaScript call, keeps \n
205 * as newline
206 *
207 * @author Andreas Gohr <andi@splitbrain.org>
208 */
209function js_escape($string){
210    return str_replace('\\\\n','\\n',addslashes($string));
211}
212
213/**
214 * Adds the given JavaScript code to the window.onload() event
215 *
216 * @author Andreas Gohr <andi@splitbrain.org>
217 */
218function js_runonstart($func){
219    echo "addInitEvent(function(){ $func; });".NL;
220}
221
222/**
223 * Strip comments and whitespaces from given JavaScript Code
224 *
225 * This is a port of Nick Galbreath's python tool jsstrip.py which is
226 * released under BSD license. See link for original code.
227 *
228 * @author Nick Galbreath <nickg@modp.com>
229 * @author Andreas Gohr <andi@splitbrain.org>
230 * @link   http://code.google.com/p/jsstrip/
231 */
232function js_compress($s){
233    $s = ltrim($s);     // strip all initial whitespace
234    $s .= "\n";
235    $i = 0;             // char index for input string
236    $j = 0;             // char forward index for input string
237    $line = 0;          // line number of file (close to it anyways)
238    $slen = strlen($s); // size of input string
239    $lch  = '';         // last char added
240    $result = '';       // we store the final result here
241
242    // items that don't need spaces next to them
243    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
244
245    while($i < $slen){
246        // skip all "boring" characters.  This is either
247        // reserved word (e.g. "for", "else", "if") or a
248        // variable/object/method (e.g. "foo.color")
249        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
250            $result .= $s{$i};
251            $i = $i + 1;
252        }
253
254        $ch = $s{$i};
255        // multiline comments (keeping IE conditionals)
256        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
257            $endC = strpos($s,'*/',$i+2);
258            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
259            $i = $endC + 2;
260            continue;
261        }
262
263        // singleline
264        if($ch == '/' && $s{$i+1} == '/'){
265            $endC = strpos($s,"\n",$i+2);
266            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
267            $i = $endC;
268            continue;
269        }
270
271        // tricky.  might be an RE
272        if($ch == '/'){
273            // rewind, skip white space
274            $j = 1;
275            while($s{$i-$j} == ' '){
276                $j = $j + 1;
277            }
278            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
279                // yes, this is an re
280                // now move forward and find the end of it
281                $j = 1;
282                while($s{$i+$j} != '/'){
283                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
284                        $j = $j + 1;
285                    }
286                    if($s{$i+$j} == '\\') $j = $j + 2;
287                }
288                $result .= substr($s,$i,$j+1);
289                $i = $i + $j + 1;
290                continue;
291            }
292        }
293
294        // double quote strings
295        if($ch == '"'){
296            $j = 1;
297            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
298                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
299                    $j += 2;
300                }else{
301                    $j += 1;
302                }
303            }
304            $result .= substr($s,$i,$j+1);
305            $i = $i + $j + 1;
306            continue;
307        }
308
309        // single quote strings
310        if($ch == "'"){
311            $j = 1;
312            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
313                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
314                    $j += 2;
315                }else{
316                    $j += 1;
317                }
318            }
319            $result .= substr($s,$i,$j+1);
320            $i = $i + $j + 1;
321            continue;
322        }
323
324        // whitespaces
325        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
326            // leading spaces
327            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
328                $i = $i + 1;
329                continue;
330            }
331            // trailing spaces
332            //  if this ch is space AND the last char processed
333            //  is special, then skip the space
334            $lch = substr($result,-1);
335            if($lch && (strpos($chars,$lch) !== false)){
336                $i = $i + 1;
337                continue;
338            }
339            // else after all of this convert the "whitespace" to
340            // a single space.  It will get appended below
341            $ch = ' ';
342        }
343
344        // other chars
345        $result .= $ch;
346        $i = $i + 1;
347    }
348
349    return trim($result);
350}
351
352//Setup VIM: ex: et ts=4 enc=utf-8 :
353?>
354