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