xref: /dokuwiki/lib/exe/js.php (revision 54637c3d2b8a7f1cba60f230703d3c65141b0a24)
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    print "var DOKU_TPL    = '".DOKU_TPL."';";
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        js_load($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          js_load($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    // end output buffering and get contents
149    $js = ob_get_contents();
150    ob_end_clean();
151
152    // compress whitespace and comments
153    if($conf['compress']){
154        $js = js_compress($js);
155    }
156
157    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
158
159    // save cache file
160    io_saveFile($cache,$js);
161
162    // finally send output
163    print $js;
164}
165
166/**
167 * Load the given file, handle include calls and print it
168 */
169function js_load($file){
170    if(!@file_exists($file)) return;
171
172    $data = io_readFile($file);
173    while(preg_match('#/\*\s*!!include\s+([\w\./]+)\s*\*/#',$data,$match)){
174        $ifile = $match[1];
175        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
176
177        if(@file_exists($ifile)){
178            $idata = io_readFile($ifile);
179        }else{
180            $idata = '';
181        }
182        $data  = str_replace($match[0],$idata,$data);
183    }
184    echo $data;
185}
186
187/**
188 * Checks if a JavaScript Cache file still is valid
189 *
190 * @author Andreas Gohr <andi@splitbrain.org>
191 */
192function js_cacheok($cache,$files){
193    if($_REQUEST['purge']) return false; //support purge request
194
195    $ctime = @filemtime($cache);
196    if(!$ctime) return false; //There is no cache
197
198    // some additional files to check
199    $files[] = DOKU_CONF.'dokuwiki.php';
200    $files[] = DOKU_CONF.'local.php';
201    $files[] = DOKU_CONF.'userscript.js';
202    $files[] = __FILE__;
203
204    // now walk the files
205    foreach($files as $file){
206        if(@filemtime($file) > $ctime){
207            return false;
208        }
209    }
210    return true;
211}
212
213/**
214 * Returns a list of possible Plugin Scripts (no existance check here)
215 *
216 * @author Andreas Gohr <andi@splitbrain.org>
217 */
218function js_pluginscripts(){
219    $list = array();
220    $plugins = plugin_list();
221    foreach ($plugins as $p){
222        $list[] = DOKU_PLUGIN."$p/script.js";
223    }
224    return $list;
225}
226
227/**
228 * Escapes a String to be embedded in a JavaScript call, keeps \n
229 * as newline
230 *
231 * @author Andreas Gohr <andi@splitbrain.org>
232 */
233function js_escape($string){
234    return str_replace('\\\\n','\\n',addslashes($string));
235}
236
237/**
238 * Adds the given JavaScript code to the window.onload() event
239 *
240 * @author Andreas Gohr <andi@splitbrain.org>
241 */
242function js_runonstart($func){
243    echo "addInitEvent(function(){ $func; });".NL;
244}
245
246/**
247 * Strip comments and whitespaces from given JavaScript Code
248 *
249 * This is a port of Nick Galbreath's python tool jsstrip.py which is
250 * released under BSD license. See link for original code.
251 *
252 * @author Nick Galbreath <nickg@modp.com>
253 * @author Andreas Gohr <andi@splitbrain.org>
254 * @link   http://code.google.com/p/jsstrip/
255 */
256function js_compress($s){
257    $s = ltrim($s);     // strip all initial whitespace
258    $s .= "\n";
259    $i = 0;             // char index for input string
260    $j = 0;             // char forward index for input string
261    $line = 0;          // line number of file (close to it anyways)
262    $slen = strlen($s); // size of input string
263    $lch  = '';         // last char added
264    $result = '';       // we store the final result here
265
266    // items that don't need spaces next to them
267    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
268
269    while($i < $slen){
270        // skip all "boring" characters.  This is either
271        // reserved word (e.g. "for", "else", "if") or a
272        // variable/object/method (e.g. "foo.color")
273        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
274            $result .= $s{$i};
275            $i = $i + 1;
276        }
277
278        $ch = $s{$i};
279        // multiline comments (keeping IE conditionals)
280        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
281            $endC = strpos($s,'*/',$i+2);
282            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
283            $i = $endC + 2;
284            continue;
285        }
286
287        // singleline
288        if($ch == '/' && $s{$i+1} == '/'){
289            $endC = strpos($s,"\n",$i+2);
290            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
291            $i = $endC;
292            continue;
293        }
294
295        // tricky.  might be an RE
296        if($ch == '/'){
297            // rewind, skip white space
298            $j = 1;
299            while($s{$i-$j} == ' '){
300                $j = $j + 1;
301            }
302            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
303                // yes, this is an re
304                // now move forward and find the end of it
305                $j = 1;
306                while($s{$i+$j} != '/'){
307                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
308                        $j = $j + 1;
309                    }
310                    if($s{$i+$j} == '\\') $j = $j + 2;
311                }
312                $result .= substr($s,$i,$j+1);
313                $i = $i + $j + 1;
314                continue;
315            }
316        }
317
318        // double quote strings
319        if($ch == '"'){
320            $j = 1;
321            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
322                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
323                    $j += 2;
324                }else{
325                    $j += 1;
326                }
327            }
328            $result .= substr($s,$i,$j+1);
329            $i = $i + $j + 1;
330            continue;
331        }
332
333        // single quote strings
334        if($ch == "'"){
335            $j = 1;
336            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
337                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
338                    $j += 2;
339                }else{
340                    $j += 1;
341                }
342            }
343            $result .= substr($s,$i,$j+1);
344            $i = $i + $j + 1;
345            continue;
346        }
347
348        // whitespaces
349        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
350            // leading spaces
351            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
352                $i = $i + 1;
353                continue;
354            }
355            // trailing spaces
356            //  if this ch is space AND the last char processed
357            //  is special, then skip the space
358            $lch = substr($result,-1);
359            if($lch && (strpos($chars,$lch) !== false)){
360                $i = $i + 1;
361                continue;
362            }
363            // else after all of this convert the "whitespace" to
364            // a single space.  It will get appended below
365            $ch = ' ';
366        }
367
368        // other chars
369        $result .= $ch;
370        $i = $i + 1;
371    }
372
373    return trim($result);
374}
375
376//Setup VIM: ex: et ts=4 enc=utf-8 :
377?>
378