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