xref: /dokuwiki/lib/exe/js.php (revision 22064dd98283bc61e1b444e45707c1c51230eb92)
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");
12if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here
13require_once(DOKU_INC.'inc/init.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    global $config_cascade;
33
34    // The generated script depends on some dynamic options
35    $cache = new cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.js');
36    $cache->_event = 'JS_CACHE_USE';
37
38    // load minified version for some files
39    $min = $conf['compress'] ? '.min' : '';
40
41    // array of core files
42    $files = array(
43                DOKU_INC."lib/scripts/jquery/jquery$min.js",
44                DOKU_INC.'lib/scripts/jquery/jquery.cookie.js',
45                DOKU_INC."lib/scripts/jquery/jquery-ui$min.js",
46                DOKU_INC."lib/scripts/jquery/jquery-migrate$min.js",
47                DOKU_INC."lib/scripts/fileuploader.js",
48                DOKU_INC."lib/scripts/fileuploaderextended.js",
49                DOKU_INC.'lib/scripts/helpers.js',
50                DOKU_INC.'lib/scripts/delay.js',
51                DOKU_INC.'lib/scripts/cookie.js',
52                DOKU_INC.'lib/scripts/script.js',
53                DOKU_INC.'lib/scripts/tw-sack.js',
54                DOKU_INC.'lib/scripts/qsearch.js',
55                DOKU_INC.'lib/scripts/tree.js',
56                DOKU_INC.'lib/scripts/index.js',
57                DOKU_INC.'lib/scripts/drag.js',
58                DOKU_INC.'lib/scripts/textselection.js',
59                DOKU_INC.'lib/scripts/toolbar.js',
60                DOKU_INC.'lib/scripts/edit.js',
61                DOKU_INC.'lib/scripts/editor.js',
62                DOKU_INC.'lib/scripts/locktimer.js',
63                DOKU_INC.'lib/scripts/linkwiz.js',
64                DOKU_INC.'lib/scripts/media.js',
65# deprecated                DOKU_INC.'lib/scripts/compatibility.js',
66# disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
67                DOKU_INC.'lib/scripts/behaviour.js',
68                DOKU_INC.'lib/scripts/page.js',
69                tpl_incdir().'script.js',
70            );
71
72    // add possible plugin scripts and userscript
73    $files   = array_merge($files,js_pluginscripts());
74    if(isset($config_cascade['userscript']['default'])){
75        $files[] = $config_cascade['userscript']['default'];
76    }
77
78    $cache_files = array_merge($files, getConfigFiles('main'));
79    $cache_files[] = __FILE__;
80
81    // check cache age & handle conditional request
82    // This may exit if a cache can be used
83    $cache_ok = $cache->useCache(array('files' => $cache_files));
84    http_cached($cache->cache, $cache_ok);
85
86    // start output buffering and build the script
87    ob_start();
88
89    // add some global variables
90    print "var DOKU_BASE   = '".DOKU_BASE."';";
91    print "var DOKU_TPL    = '".tpl_basedir()."';";
92    // FIXME: Move those to JSINFO
93    print "var DOKU_UHN    = ".((int) useHeading('navigation')).";";
94    print "var DOKU_UHC    = ".((int) useHeading('content')).";";
95
96    // load JS specific translations
97    $json = new JSON();
98    $lang['js']['plugins'] = js_pluginstrings();
99    echo 'LANG = '.$json->encode($lang['js']).";\n";
100
101    // load toolbar
102    toolbar_JSdefines('toolbar');
103
104    // load files
105    foreach($files as $file){
106        $ismin = (substr($file,-7) == '.min.js');
107
108        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
109        if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
110        js_load($file);
111        if($ismin) echo "\n/* END NOCOMPRESS */\n";
112        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
113    }
114
115    // init stuff
116    if($conf['locktime'] != 0){
117        js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")");
118    }
119    // init hotkeys - must have been done after init of toolbar
120# disabled for FS#1958    js_runonstart('initializeHotkeys()');
121
122    // end output buffering and get contents
123    $js = ob_get_contents();
124    ob_end_clean();
125
126    // compress whitespace and comments
127    if($conf['compress']){
128        $js = js_compress($js);
129    }
130
131    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
132
133    http_cached_finish($cache->cache, $js);
134}
135
136/**
137 * Load the given file, handle include calls and print it
138 *
139 * @author Andreas Gohr <andi@splitbrain.org>
140 */
141function js_load($file){
142    if(!@file_exists($file)) return;
143    static $loaded = array();
144
145    $data = io_readFile($file);
146    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
147        $ifile = $match[2];
148
149        // is it a include_once?
150        if($match[1]){
151            $base = utf8_basename($ifile);
152            if($loaded[$base]) continue;
153            $loaded[$base] = true;
154        }
155
156        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
157
158        if(@file_exists($ifile)){
159            $idata = io_readFile($ifile);
160        }else{
161            $idata = '';
162        }
163        $data  = str_replace($match[0],$idata,$data);
164    }
165    echo "$data\n";
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 * Return an two-dimensional array with strings from the language file of each plugin.
184 *
185 * - $lang['js'] must be an array.
186 * - Nothing is returned for plugins without an entry for $lang['js']
187 *
188 * @author Gabriel Birke <birke@d-scribe.de>
189 */
190function js_pluginstrings()
191{
192    global $conf;
193    $pluginstrings = array();
194    $plugins = plugin_list();
195    foreach ($plugins as $p){
196        if (isset($lang)) unset($lang);
197        if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) {
198            include DOKU_PLUGIN."$p/lang/en/lang.php";
199        }
200        if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) {
201            include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php";
202        }
203        if (isset($lang['js'])) {
204            $pluginstrings[$p] = $lang['js'];
205        }
206    }
207    return $pluginstrings;
208}
209
210/**
211 * Escapes a String to be embedded in a JavaScript call, keeps \n
212 * as newline
213 *
214 * @author Andreas Gohr <andi@splitbrain.org>
215 */
216function js_escape($string){
217    return str_replace('\\\\n','\\n',addslashes($string));
218}
219
220/**
221 * Adds the given JavaScript code to the window.onload() event
222 *
223 * @author Andreas Gohr <andi@splitbrain.org>
224 */
225function js_runonstart($func){
226    echo "jQuery(function(){ $func; });".NL;
227}
228
229/**
230 * Strip comments and whitespaces from given JavaScript Code
231 *
232 * This is a port of Nick Galbreath's python tool jsstrip.py which is
233 * released under BSD license. See link for original code.
234 *
235 * @author Nick Galbreath <nickg@modp.com>
236 * @author Andreas Gohr <andi@splitbrain.org>
237 * @link   http://code.google.com/p/jsstrip/
238 */
239function js_compress($s){
240    $s = ltrim($s);     // strip all initial whitespace
241    $s .= "\n";
242    $i = 0;             // char index for input string
243    $j = 0;             // char forward index for input string
244    $line = 0;          // line number of file (close to it anyways)
245    $slen = strlen($s); // size of input string
246    $lch  = '';         // last char added
247    $result = '';       // we store the final result here
248
249    // items that don't need spaces next to them
250    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
251
252    $regex_starters = array("(", "=", "[", "," , ":", "!");
253
254    $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B");
255
256    while($i < $slen){
257        // skip all "boring" characters.  This is either
258        // reserved word (e.g. "for", "else", "if") or a
259        // variable/object/method (e.g. "foo.color")
260        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
261            $result .= $s{$i};
262            $i = $i + 1;
263        }
264
265        $ch = $s{$i};
266        // multiline comments (keeping IE conditionals)
267        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
268            $endC = strpos($s,'*/',$i+2);
269            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
270
271            // check if this is a NOCOMPRESS comment
272            if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){
273                $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2);
274                if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR);
275
276                // verbatim copy contents, trimming but putting it on its own line
277                $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars
278                $i = $endNC + 20; // END comment = 20 chars
279            }else{
280                $i = $endC + 2;
281            }
282            continue;
283        }
284
285        // singleline
286        if($ch == '/' && $s{$i+1} == '/'){
287            $endC = strpos($s,"\n",$i+2);
288            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
289            $i = $endC;
290            continue;
291        }
292
293        // tricky.  might be an RE
294        if($ch == '/'){
295            // rewind, skip white space
296            $j = 1;
297            while(in_array($s{$i-$j}, $whitespaces_chars)){
298                $j = $j + 1;
299            }
300            if( in_array($s{$i-$j}, $regex_starters) ){
301                // yes, this is an re
302                // now move forward and find the end of it
303                $j = 1;
304                while($s{$i+$j} != '/'){
305                    if($s{$i+$j} == '\\') $j = $j + 2;
306                    else $j++;
307                }
308                $result .= substr($s,$i,$j+1);
309                $i = $i + $j + 1;
310                continue;
311            }
312        }
313
314        // double quote strings
315        if($ch == '"'){
316            $j = 1;
317            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
318                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
319                    $j += 2;
320                }else{
321                    $j += 1;
322                }
323            }
324            $string  = substr($s,$i,$j+1);
325            // remove multiline markers:
326            $string  = str_replace("\\\n",'',$string);
327            $result .= $string;
328            $i = $i + $j + 1;
329            continue;
330        }
331
332        // single quote strings
333        if($ch == "'"){
334            $j = 1;
335            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
336                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
337                    $j += 2;
338                }else{
339                    $j += 1;
340                }
341            }
342            $string = substr($s,$i,$j+1);
343            // remove multiline markers:
344            $string  = str_replace("\\\n",'',$string);
345            $result .= $string;
346            $i = $i + $j + 1;
347            continue;
348        }
349
350        // whitespaces
351        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
352            // leading spaces
353            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
354                $i = $i + 1;
355                continue;
356            }
357            // trailing spaces
358            //  if this ch is space AND the last char processed
359            //  is special, then skip the space
360            $lch = substr($result,-1);
361            if($lch && (strpos($chars,$lch) !== false)){
362                $i = $i + 1;
363                continue;
364            }
365            // else after all of this convert the "whitespace" to
366            // a single space.  It will get appended below
367            $ch = ' ';
368        }
369
370        // other chars
371        $result .= $ch;
372        $i = $i + 1;
373    }
374
375    return trim($result);
376}
377
378//Setup VIM: ex: et ts=4 :
379