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