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