xref: /dokuwiki/lib/exe/js.php (revision 137ce95a340b36e962f90c44c9f6414dc2e0d1e4)
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',dirname(__FILE__).'/../../');
10if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching)
11if(!defined('NL')) define('NL',"\n");
12require_once(DOKU_INC.'inc/init.php');
13require_once(DOKU_INC.'inc/pageutils.php');
14require_once(DOKU_INC.'inc/io.php');
15require_once(DOKU_INC.'inc/JSON.php');
16
17// Main (don't run when UNIT test)
18if(!defined('SIMPLE_TEST')){
19    header('Content-Type: text/javascript; charset=utf-8');
20    js_out();
21}
22
23
24// ---------------------- functions ------------------------------
25
26/**
27 * Output all needed JavaScript
28 *
29 * @author Andreas Gohr <andi@splitbrain.org>
30 */
31function js_out(){
32    global $conf;
33    global $lang;
34    $edit  = (bool) $_REQUEST['edit'];   // edit or preview mode?
35    $write = (bool) $_REQUEST['write'];  // writable?
36
37    // The generated script depends on some dynamic options
38    $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].$edit.'x'.$write,'.js');
39
40    // Array of needed files
41    $files = array(
42                DOKU_INC.'lib/scripts/helpers.js',
43                DOKU_INC.'lib/scripts/events.js',
44                DOKU_INC.'lib/scripts/cookie.js',
45                DOKU_INC.'lib/scripts/script.js',
46                DOKU_INC.'lib/scripts/tw-sack.js',
47                DOKU_INC.'lib/scripts/ajax.js',
48                DOKU_INC.'lib/scripts/index.js',
49             );
50    if($edit){
51        if($write){
52            $files[] = DOKU_INC.'lib/scripts/edit.js';
53        }
54        $files[] = DOKU_INC.'lib/scripts/media.js';
55    }
56    $files[] = DOKU_TPLINC.'script.js';
57
58    // get possible plugin scripts
59    $plugins = js_pluginscripts();
60
61    // check cache age & handle conditional request
62    header('Cache-Control: public, max-age=3600');
63    header('Pragma: public');
64    if(js_cacheok($cache,array_merge($files,$plugins))){
65        http_conditionalRequest(filemtime($cache));
66        if($conf['allowdebug']) header("X-CacheUsed: $cache");
67        readfile($cache);
68        return;
69    } else {
70        http_conditionalRequest(time());
71    }
72
73    // start output buffering and build the script
74    ob_start();
75
76    // add some global variables
77    print "var DOKU_BASE   = '".DOKU_BASE."';";
78    print "var DOKU_TPL    = '".DOKU_TPL."';";
79
80    //FIXME: move thes into LANG
81    print "var alertText   = '".js_escape($lang['qb_alert'])."';";
82    print "var notSavedYet = '".js_escape($lang['notsavedyet'])."';";
83    print "var reallyDel   = '".js_escape($lang['del_confirm'])."';";
84
85    // load JS strings form plugins
86    $lang['js']['plugins'] = js_pluginstrings();
87
88    // load JS specific translations
89    $json = new JSON();
90    echo 'LANG = '.$json->encode($lang['js']).";\n";
91
92    // load files
93    foreach($files as $file){
94        echo "\n\n/* XXXXXXXXXX begin of $file XXXXXXXXXX */\n\n";
95        js_load($file);
96        echo "\n\n/* XXXXXXXXXX end of $file XXXXXXXXXX */\n\n";
97    }
98
99    // init stuff
100    js_runonstart("ajax_qsearch.init('qsearch__in','qsearch__out')");
101    js_runonstart("addEvent(document,'click',closePopups)");
102    js_runonstart('addTocToggle()');
103
104    if($edit){
105        // size controls
106        js_runonstart("initSizeCtl('size__ctl','wiki__text')");
107
108        if($write){
109            require_once(DOKU_INC.'inc/toolbar.php');
110            toolbar_JSdefines('toolbar');
111            js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)");
112
113            // add pageleave check
114            js_runonstart("initChangeCheck('".js_escape($lang['notsavedyet'])."')");
115
116            // add lock timer
117            js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")");
118        }
119    }
120
121    // load plugin scripts (suppress warnings for missing ones)
122    foreach($plugins as $plugin){
123        if (@file_exists($plugin)) {
124          echo "\n\n/* XXXXXXXXXX begin of $plugin XXXXXXXXXX */\n\n";
125          js_load($plugin);
126          echo "\n\n/* XXXXXXXXXX end of $plugin XXXXXXXXXX */\n\n";
127        }
128    }
129
130    // load user script
131    @readfile(DOKU_CONF.'userscript.js');
132
133    // add scroll event and tooltip rewriting
134    js_runonstart('scrollToMarker()');
135    js_runonstart('focusMarker()');
136
137    // end output buffering and get contents
138    $js = ob_get_contents();
139    ob_end_clean();
140
141    // compress whitespace and comments
142    if($conf['compress']){
143        $js = js_compress($js);
144    }
145
146    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
147
148    // save cache file
149    io_saveFile($cache,$js);
150
151    // finally send output
152    print $js;
153}
154
155/**
156 * Load the given file, handle include calls and print it
157 *
158 * @author Andreas Gohr <andi@splitbrain.org>
159 */
160function js_load($file){
161    if(!@file_exists($file)) return;
162    static $loaded = array();
163
164    $data = io_readFile($file);
165    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\./]+)\s*\*/#',$data,$match)){
166        $ifile = $match[2];
167
168        // is it a include_once?
169        if($match[1]){
170            $base = basename($ifile);
171            if($loaded[$base]) continue;
172            $loaded[$base] = true;
173        }
174
175        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
176
177        if(@file_exists($ifile)){
178            $idata = io_readFile($ifile);
179        }else{
180            $idata = '';
181        }
182        $data  = str_replace($match[0],$idata,$data);
183    }
184    echo $data;
185}
186
187/**
188 * Checks if a JavaScript Cache file still is valid
189 *
190 * @author Andreas Gohr <andi@splitbrain.org>
191 */
192function js_cacheok($cache,$files){
193    if($_REQUEST['purge']) return false; //support purge request
194
195    $ctime = @filemtime($cache);
196    if(!$ctime) return false; //There is no cache
197
198    // some additional files to check
199    $files[] = DOKU_CONF.'dokuwiki.php';
200    $files[] = DOKU_CONF.'local.php';
201    $files[] = DOKU_CONF.'userscript.js';
202    $files[] = __FILE__;
203
204    // now walk the files
205    foreach($files as $file){
206        if(@filemtime($file) > $ctime){
207            return false;
208        }
209    }
210    return true;
211}
212
213/**
214 * Returns a list of possible Plugin Scripts (no existance check here)
215 *
216 * @author Andreas Gohr <andi@splitbrain.org>
217 */
218function js_pluginscripts(){
219    $list = array();
220    $plugins = plugin_list();
221    foreach ($plugins as $p){
222        $list[] = DOKU_PLUGIN."$p/script.js";
223    }
224    return $list;
225}
226
227/**
228 * Return an two-dimensional array with strings from the language file of each plugin.
229 *
230 * - $lang['js'] must be an array.
231 * - Nothing is returned for plugins without an entry for $lang['js']
232 *
233 * @author Gabriel Birke <birke@d-scribe.de>
234 */
235function js_pluginstrings()
236{
237    global $conf;
238    $pluginstrings = array();
239    $plugins = plugin_list();
240    foreach ($plugins as $p){
241        if (isset($lang)) unset($lang);
242        if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) {
243            include DOKU_PLUGIN."$p/lang/en/lang.php";
244        }
245        if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) {
246            include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php";
247        }
248        if (isset($lang['js'])) {
249            $pluginstrings[$p] = $lang['js'];
250        }
251    }
252    return $pluginstrings;
253}
254
255/**
256 * Escapes a String to be embedded in a JavaScript call, keeps \n
257 * as newline
258 *
259 * @author Andreas Gohr <andi@splitbrain.org>
260 */
261function js_escape($string){
262    return str_replace('\\\\n','\\n',addslashes($string));
263}
264
265/**
266 * Adds the given JavaScript code to the window.onload() event
267 *
268 * @author Andreas Gohr <andi@splitbrain.org>
269 */
270function js_runonstart($func){
271    echo "addInitEvent(function(){ $func; });".NL;
272}
273
274/**
275 * Strip comments and whitespaces from given JavaScript Code
276 *
277 * This is a port of Nick Galbreath's python tool jsstrip.py which is
278 * released under BSD license. See link for original code.
279 *
280 * @author Nick Galbreath <nickg@modp.com>
281 * @author Andreas Gohr <andi@splitbrain.org>
282 * @link   http://code.google.com/p/jsstrip/
283 */
284function js_compress($s){
285    $s = ltrim($s);     // strip all initial whitespace
286    $s .= "\n";
287    $i = 0;             // char index for input string
288    $j = 0;             // char forward index for input string
289    $line = 0;          // line number of file (close to it anyways)
290    $slen = strlen($s); // size of input string
291    $lch  = '';         // last char added
292    $result = '';       // we store the final result here
293
294    // items that don't need spaces next to them
295    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
296
297    while($i < $slen){
298        // skip all "boring" characters.  This is either
299        // reserved word (e.g. "for", "else", "if") or a
300        // variable/object/method (e.g. "foo.color")
301        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
302            $result .= $s{$i};
303            $i = $i + 1;
304        }
305
306        $ch = $s{$i};
307        // multiline comments (keeping IE conditionals)
308        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
309            $endC = strpos($s,'*/',$i+2);
310            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
311            $i = $endC + 2;
312            continue;
313        }
314
315        // singleline
316        if($ch == '/' && $s{$i+1} == '/'){
317            $endC = strpos($s,"\n",$i+2);
318            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
319            $i = $endC;
320            continue;
321        }
322
323        // tricky.  might be an RE
324        if($ch == '/'){
325            // rewind, skip white space
326            $j = 1;
327            while($s{$i-$j} == ' '){
328                $j = $j + 1;
329            }
330            if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){
331                // yes, this is an re
332                // now move forward and find the end of it
333                $j = 1;
334                while($s{$i+$j} != '/'){
335                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
336                        $j = $j + 1;
337                    }
338                    if($s{$i+$j} == '\\') $j = $j + 2;
339                }
340                $result .= substr($s,$i,$j+1);
341                $i = $i + $j + 1;
342                continue;
343            }
344        }
345
346        // double quote strings
347        if($ch == '"'){
348            $j = 1;
349            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
350                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
351                    $j += 2;
352                }else{
353                    $j += 1;
354                }
355            }
356            $result .= substr($s,$i,$j+1);
357            $i = $i + $j + 1;
358            continue;
359        }
360
361        // single quote strings
362        if($ch == "'"){
363            $j = 1;
364            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
365                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
366                    $j += 2;
367                }else{
368                    $j += 1;
369                }
370            }
371            $result .= substr($s,$i,$j+1);
372            $i = $i + $j + 1;
373            continue;
374        }
375
376        // whitespaces
377        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
378            // leading spaces
379            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
380                $i = $i + 1;
381                continue;
382            }
383            // trailing spaces
384            //  if this ch is space AND the last char processed
385            //  is special, then skip the space
386            $lch = substr($result,-1);
387            if($lch && (strpos($chars,$lch) !== false)){
388                $i = $i + 1;
389                continue;
390            }
391            // else after all of this convert the "whitespace" to
392            // a single space.  It will get appended below
393            $ch = ' ';
394        }
395
396        // other chars
397        $result .= $ch;
398        $i = $i + 1;
399    }
400
401    return trim($result);
402}
403
404//Setup VIM: ex: et ts=4 enc=utf-8 :
405?>
406