xref: /dokuwiki/lib/exe/js.php (revision cd7fd4a2c78ff5083a121a441142649ab5f6acad)
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)
11require_once(DOKU_INC.'inc/init.php');
12require_once(DOKU_INC.'inc/pageutils.php');
13require_once(DOKU_INC.'inc/io.php');
14
15// Main (don't run when UNIT test)
16if(!defined('SIMPLE_TEST')){
17    header('Content-Type: text/javascript; charset=utf-8');
18    js_out();
19}
20
21
22// ---------------------- functions ------------------------------
23
24/**
25 * Output all needed JavaScript
26 *
27 * @author Andreas Gohr <andi@splitbrain.org>
28 */
29function js_out(){
30    global $conf;
31    global $lang;
32    $edit  = (bool) $_REQUEST['edit'];   // edit or preview mode?
33    $write = (bool) $_REQUEST['write'];  // writable?
34
35    // The generated script depends on some dynamic options
36    $cache = getCacheName('scripts'.$edit.$write,'.js');
37
38    // Array of needed files
39    $files = array(
40                DOKU_INC.'lib/scripts/events.js',
41                DOKU_INC.'lib/scripts/script.js',
42                DOKU_INC.'lib/scripts/tw-sack.js',
43                DOKU_INC.'lib/scripts/ajax.js',
44                DOKU_INC.'lib/scripts/domLib.js',
45                DOKU_INC.'lib/scripts/domTT.js',
46             );
47    if($edit && $write){
48        $files[] = DOKU_INC.'lib/scripts/edit.js';
49        if($conf['spellchecker']){
50            $files[] = DOKU_INC.'lib/scripts/spellcheck.js';
51        }
52    }
53    $files[] = DOKU_TPLINC.'script.js';
54
55    // get possible plugin scripts
56    $plugins = js_pluginscripts();
57
58    // check cache age & handle conditional request
59    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
60    header('Pragma: public');
61    if(js_cacheok($cache,array_merge($files,$plugins))){
62        http_conditionalRequest(filemtime($cache));
63        readfile($cache);
64        return;
65    } else {
66        http_conditionalRequest(time());
67    }
68
69    // start output buffering and build the script
70    ob_start();
71
72    // add some translation strings and global variables
73    print "var alertText   = '".js_escape($lang['qb_alert'])."';";
74    print "var notSavedYet = '".js_escape($lang['notsavedyet'])."';";
75    print "var reallyDel   = '".js_escape($lang['del_confirm'])."';";
76    print "var DOKU_BASE   = '".DOKU_BASE."';";
77
78    // load files
79    foreach($files as $file){
80        @readfile($file);
81    }
82
83    // init stuff
84    js_runonstart("ajax_qsearch.init('qsearch__in','qsearch__out')");
85    js_runonstart("addEvent(document,'click',closePopups)");
86    js_runonstart('addTocToggle()');
87
88    if($edit){
89        // size controls
90        js_runonstart("initSizeCtl('size__ctl','wiki__text')");
91
92        if($write){
93            require_once(DOKU_INC.'inc/toolbar.php');
94            toolbar_JSdefines('toolbar');
95            js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)");
96
97            // add pageleave check
98            js_runonstart("initChangeCheck('".js_escape($lang['notsavedyet'])."')");
99
100            // add lock timer
101            js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")");
102
103            // load spell checker
104            if($conf['spellchecker']){
105                js_runonstart("ajax_spell.init('".
106                               js_escape($lang['spell_start'])."','".
107                               js_escape($lang['spell_stop'])."','".
108                               js_escape($lang['spell_wait'])."','".
109                               js_escape($lang['spell_noerr'])."','".
110                               js_escape($lang['spell_nosug'])."','".
111                               js_escape($lang['spell_change'])."')");
112            }
113        }
114    }
115
116    // load plugin scripts (suppress warnings for missing ones)
117    foreach($plugins as $plugin){
118        @readfile($plugin);
119    }
120
121    // load user script
122    @readfile(DOKU_CONF.'userscript.js');
123
124    // add scroll event
125    js_runonstart('scrollToMarker()');
126
127    // initialize init pseudo event
128    echo 'if (document.addEventListener) {';
129    echo '    document.addEventListener("DOMContentLoaded", window.fireoninit, null);';
130    echo '}';
131    echo 'addEvent(window,"load",window.fireoninit);';
132
133    // end output buffering and get contents
134    $js = ob_get_contents();
135    ob_end_clean();
136
137    // compress whitespace and comments
138    if($conf['compress']){
139        $js = js_compress($js);
140    }
141
142    // save cache file
143    io_saveFile($cache,$js);
144
145    // finally send output
146    print $js;
147}
148
149/**
150 * Checks if a JavaScript Cache file still is valid
151 *
152 * @author Andreas Gohr <andi@splitbrain.org>
153 */
154function js_cacheok($cache,$files){
155    $ctime = @filemtime($cache);
156    if(!$ctime) return false; //There is no cache
157
158    // some additional files to check
159    $files[] = DOKU_CONF.'dokuwiki.php';
160    $files[] = DOKU_CONF.'local.php';
161    $files[] = DOKU_CONF.'userscript.js';
162    $files[] = __FILE__;
163
164    // now walk the files
165    foreach($files as $file){
166        if(@filemtime($file) > $ctime){
167            return false;
168        }
169    }
170    return true;
171}
172
173/**
174 * Returns a list of possible Plugin Scripts (no existance check here)
175 *
176 * @author Andreas Gohr <andi@splitbrain.org>
177 */
178function js_pluginscripts(){
179    $list = array();
180    $plugins = plugin_list();
181    foreach ($plugins as $p){
182        $list[] = DOKU_PLUGIN."$p/script.js";
183    }
184    return $list;
185}
186
187/**
188 * Escapes a String to be embedded in a JavaScript call, keeps \n
189 * as newline
190 *
191 * @author Andreas Gohr <andi@splitbrain.org>
192 */
193function js_escape($string){
194    return str_replace('\\\\n','\\n',addslashes($string));
195}
196
197/**
198 * Adds the given JavaScript code to the window.onload() event
199 *
200 * @author Andreas Gohr <andi@splitbrain.org>
201 */
202function js_runonstart($func){
203    echo "addInitEvent(function(){ $func; });\n";
204}
205
206/**
207 * Strip comments and whitespaces from given JavaScript Code
208 *
209 * This is a rewrite of Nick Galbreaths python tool jsstrip.py which is
210 * released under BSD license. See link for original code.
211 *
212 * @author Nick Galbreath <nickg@modp.com>
213 * @author Andreas Gohr <andi@splitbrain.org>
214 * @link http://modp.com/release/jsstrip/
215 */
216function js_compress($s){
217    $i = 0;
218    $line = 0;
219    $s .= "\n";
220    $len = strlen($s);
221
222    // items that don't need spaces next to them
223    $chars = '^&|!+\-*\/%=:;,{}()<>% \t\n\r';
224
225    ob_start();
226    while($i < $len){
227        $ch = $s{$i};
228
229        // multiline comments
230        if($ch == '/' && $s{$i+1} == '*'){
231            $endC = strpos($s,'*/',$i+2);
232            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
233            $i = $endC + 2;
234            continue;
235        }
236
237        // singleline
238        if($ch == '/' && $s{$i+1} == '/'){
239            $endC = strpos($s,"\n",$i+2);
240            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
241            $i = $endC;
242            continue;
243        }
244
245        // tricky.  might be an RE
246        if($ch == '/'){
247            // rewind, skip white space
248            $j = 1;
249            while($s{$i-$j} == ' '){
250                $j = $j + 1;
251            }
252            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
253                // yes, this is an re
254                // now move forward and find the end of it
255                $j = 1;
256                while($s{$i+$j} != '/'){
257                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
258                        $j = $j + 1;
259                    }
260                    if($s{$i+$j} == '\\') $j = $j + 2;
261                }
262                echo substr($s,$i,$j+1);
263                $i = $i + $j + 1;
264                continue;
265            }
266        }
267
268        // double quote strings
269        if($ch == '"'){
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        // single quote strings
283        if($ch == "'"){
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            echo substr($s,$i,$j+1);
292            $i = $i + $j + 1;
293            continue;
294        }
295
296        // newlines
297        if($ch == "\n" || $ch == "\r"){
298            $i = $i+1;
299            continue;
300        }
301
302        // leading spaces
303        if( ( $ch == ' ' ||
304              $ch == "\n" ||
305              $ch == "\t" ) &&
306            !preg_match('/['.$chars.']/',$s{$i+1}) ){
307            $i = $i+1;
308            continue;
309        }
310
311        // trailing spaces
312        if( ( $ch == ' ' ||
313              $ch == "\n" ||
314              $ch == "\t" ) &&
315            !preg_match('/['.$chars.']/',$s{$i-1}) ){
316            $i = $i+1;
317            continue;
318        }
319
320        // other chars
321        echo $ch;
322        $i = $i + 1;
323    }
324
325
326    $out = ob_get_contents();
327    ob_end_clean();
328    return $out;
329}
330
331//Setup VIM: ex: et ts=4 enc=utf-8 :
332?>
333