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