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