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