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