xref: /dokuwiki/lib/exe/js.php (revision 5aa52fafe8be8e728c0d2c9ff12c999e80766127)
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             );
48    if($edit){
49        if($write){
50            $files[] = DOKU_INC.'lib/scripts/edit.js';
51            if($conf['spellchecker']){
52                $files[] = DOKU_INC.'lib/scripts/spellcheck.js';
53            }
54        }
55        $files[] = DOKU_INC.'lib/scripts/media.js';
56    }
57    $files[] = DOKU_TPLINC.'script.js';
58
59    // get possible plugin scripts
60    $plugins = js_pluginscripts();
61
62    // check cache age & handle conditional request
63    header('Cache-Control: public, max-age=3600');
64    header('Pragma: public');
65    if(js_cacheok($cache,array_merge($files,$plugins))){
66        http_conditionalRequest(filemtime($cache));
67        if($conf['allowdebug']) header("X-CacheUsed: $cache");
68        readfile($cache);
69        return;
70    } else {
71        http_conditionalRequest(time());
72    }
73
74    // start output buffering and build the script
75    ob_start();
76
77    // add some global variables
78    print "var DOKU_BASE   = '".DOKU_BASE."';";
79
80    //FIXME: move thes into LANG
81    print "var alertText   = '".js_escape($lang['qb_alert'])."';";
82    print "var notSavedYet = '".js_escape($lang['notsavedyet'])."';";
83    print "var reallyDel   = '".js_escape($lang['del_confirm'])."';";
84
85    // load JS specific translations
86    $json = new JSON();
87    echo 'LANG = '.$json->encode($lang['js']).";\n";
88
89    // load files
90    foreach($files as $file){
91        echo "\n\n/* XXXXXXXXXX begin of $file XXXXXXXXXX */\n\n";
92        @readfile($file);
93        echo "\n\n/* XXXXXXXXXX end of $file XXXXXXXXXX */\n\n";
94    }
95
96    // init stuff
97    js_runonstart("ajax_qsearch.init('qsearch__in','qsearch__out')");
98    js_runonstart("addEvent(document,'click',closePopups)");
99    js_runonstart('addTocToggle()');
100
101    if($edit){
102        // size controls
103        js_runonstart("initSizeCtl('size__ctl','wiki__text')");
104
105        if($write){
106            require_once(DOKU_INC.'inc/toolbar.php');
107            toolbar_JSdefines('toolbar');
108            js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)");
109
110            // add pageleave check
111            js_runonstart("initChangeCheck('".js_escape($lang['notsavedyet'])."')");
112
113            // add lock timer
114            js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")");
115
116            // load spell checker
117            if($conf['spellchecker']){
118                js_runonstart("ajax_spell.init('".
119                               js_escape($lang['spell_start'])."','".
120                               js_escape($lang['spell_stop'])."','".
121                               js_escape($lang['spell_wait'])."','".
122                               js_escape($lang['spell_noerr'])."','".
123                               js_escape($lang['spell_nosug'])."','".
124                               js_escape($lang['spell_change'])."')");
125            }
126        }
127    }
128
129    // load plugin scripts (suppress warnings for missing ones)
130    foreach($plugins as $plugin){
131        if (@file_exists($plugin)) {
132          echo "\n\n/* XXXXXXXXXX begin of $plugin XXXXXXXXXX */\n\n";
133          @readfile($plugin);
134          echo "\n\n/* XXXXXXXXXX end of $plugin XXXXXXXXXX */\n\n";
135        }
136    }
137
138    // load user script
139    @readfile(DOKU_CONF.'userscript.js');
140
141    // add scroll event and tooltip rewriting
142    js_runonstart('updateAccessKeyTooltip()');
143    js_runonstart('scrollToMarker()');
144    js_runonstart('focusMarker()');
145
146    // end output buffering and get contents
147    $js = ob_get_contents();
148    ob_end_clean();
149
150    // compress whitespace and comments
151    if($conf['compress']){
152        $js = js_compress($js);
153    }
154
155    // save cache file
156    io_saveFile($cache,$js);
157
158    // finally send output
159    print $js;
160}
161
162/**
163 * Checks if a JavaScript Cache file still is valid
164 *
165 * @author Andreas Gohr <andi@splitbrain.org>
166 */
167function js_cacheok($cache,$files){
168    if($_REQUEST['purge']) return false; //support purge request
169
170    $ctime = @filemtime($cache);
171    if(!$ctime) return false; //There is no cache
172
173    // some additional files to check
174    $files[] = DOKU_CONF.'dokuwiki.php';
175    $files[] = DOKU_CONF.'local.php';
176    $files[] = DOKU_CONF.'userscript.js';
177    $files[] = __FILE__;
178
179    // now walk the files
180    foreach($files as $file){
181        if(@filemtime($file) > $ctime){
182            return false;
183        }
184    }
185    return true;
186}
187
188/**
189 * Returns a list of possible Plugin Scripts (no existance check here)
190 *
191 * @author Andreas Gohr <andi@splitbrain.org>
192 */
193function js_pluginscripts(){
194    $list = array();
195    $plugins = plugin_list();
196    foreach ($plugins as $p){
197        $list[] = DOKU_PLUGIN."$p/script.js";
198    }
199    return $list;
200}
201
202/**
203 * Escapes a String to be embedded in a JavaScript call, keeps \n
204 * as newline
205 *
206 * @author Andreas Gohr <andi@splitbrain.org>
207 */
208function js_escape($string){
209    return str_replace('\\\\n','\\n',addslashes($string));
210}
211
212/**
213 * Adds the given JavaScript code to the window.onload() event
214 *
215 * @author Andreas Gohr <andi@splitbrain.org>
216 */
217function js_runonstart($func){
218    echo "addInitEvent(function(){ $func; });".NL;
219}
220
221/**
222 * Strip comments and whitespaces from given JavaScript Code
223 *
224 * This is a rewrite of Nick Galbreaths python tool jsstrip.py which is
225 * released under BSD license. See link for original code.
226 *
227 * @author Nick Galbreath <nickg@modp.com>
228 * @author Andreas Gohr <andi@splitbrain.org>
229 * @link http://modp.com/release/jsstrip/
230 */
231function js_compress($s){
232    $i = 0;
233    $line = 0;
234    $s .= "\n";
235    $len = strlen($s);
236
237    // items that don't need spaces next to them
238    $chars = '^&|!+\-*\/%=\?:;,{}()<>% \t\n\r';
239
240    ob_start();
241    while($i < $len){
242        $ch = $s{$i};
243
244        // multiline comments (keeping IE conditionals)
245        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
246            $endC = strpos($s,'*/',$i+2);
247            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
248            $i = $endC + 2;
249            continue;
250        }
251
252        // singleline
253        if($ch == '/' && $s{$i+1} == '/'){
254            $endC = strpos($s,"\n",$i+2);
255            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
256            $i = $endC;
257            continue;
258        }
259
260        // tricky.  might be an RE
261        if($ch == '/'){
262            // rewind, skip white space
263            $j = 1;
264            while($s{$i-$j} == ' '){
265                $j = $j + 1;
266            }
267            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
268                // yes, this is an re
269                // now move forward and find the end of it
270                $j = 1;
271                while($s{$i+$j} != '/'){
272                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
273                        $j = $j + 1;
274                    }
275                    if($s{$i+$j} == '\\') $j = $j + 2;
276                }
277                echo substr($s,$i,$j+1);
278                $i = $i + $j + 1;
279                continue;
280            }
281        }
282
283        // double quote strings
284        if($ch == '"'){
285            $j = 1;
286            while( $s{$i+$j} != '"' && ($i+$j < $len)){
287                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
288                    $j += 2;
289                }else{
290                    $j += 1;
291                }
292            }
293            echo substr($s,$i,$j+1);
294            $i = $i + $j + 1;
295            continue;
296        }
297
298        // single quote strings
299        if($ch == "'"){
300            $j = 1;
301            while( $s{$i+$j} != "'" && ($i+$j < $len)){
302                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
303                    $j += 2;
304                }else{
305                    $j += 1;
306                }
307            }
308            echo substr($s,$i,$j+1);
309            $i = $i + $j + 1;
310            continue;
311        }
312
313        // newlines
314        if($ch == "\n" || $ch == "\r"){
315            $i = $i+1;
316            continue;
317        }
318
319        // leading spaces
320        if( ( $ch == ' ' ||
321              $ch == "\n" ||
322              $ch == "\t" ) &&
323            !preg_match('/['.$chars.']/',$s{$i+1}) ){
324            $i = $i+1;
325            continue;
326        }
327
328        // trailing spaces
329        if( ( $ch == ' ' ||
330              $ch == "\n" ||
331              $ch == "\t" ) &&
332            !preg_match('/['.$chars.']/',$s{$i-1}) ){
333            $i = $i+1;
334            continue;
335        }
336
337        // other chars
338        echo $ch;
339        $i = $i + 1;
340    }
341
342
343    $out = ob_get_contents();
344    ob_end_clean();
345    return $out;
346}
347
348//Setup VIM: ex: et ts=4 enc=utf-8 :
349?>
350