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