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