xref: /dokuwiki/lib/exe/js.php (revision 9de3b5710719658ef75740c0bd930423cc7c209c)
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'],
36                       '.js');
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/events.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                DOKU_INC.'lib/scripts/subscriptions.js',
66                DOKU_INC.'lib/scripts/compatibility.js',
67# disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
68                DOKU_TPLINC.'script.js',
69                DOKU_INC.'lib/scripts/behaviour.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    http_cached($cache->cache,
84                $cache->useCache(array('files' => $cache_files)));
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    = '".DOKU_TPL."';";
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
111    // init stuff
112    js_runonstart("addEvent(document,'click',closePopups)");
113    js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)");
114    if($conf['locktime'] != 0){
115        js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].", 'wiki__text')");
116    }
117    // init hotkeys - must have been done after init of toolbar
118# disabled for FS#1958    js_runonstart('initializeHotkeys()');
119
120    // end output buffering and get contents
121    $js = ob_get_contents();
122    ob_end_clean();
123
124    // compress whitespace and comments
125    if($conf['compress']){
126        $js = js_compress($js);
127    }
128
129    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
130
131    http_cached_finish($cache->cache, $js);
132}
133
134/**
135 * Load the given file, handle include calls and print it
136 *
137 * @author Andreas Gohr <andi@splitbrain.org>
138 */
139function js_load($file){
140    if(!@file_exists($file)) return;
141    static $loaded = array();
142
143    $data = io_readFile($file);
144    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
145        $ifile = $match[2];
146
147        // is it a include_once?
148        if($match[1]){
149            $base = basename($ifile);
150            if($loaded[$base]) continue;
151            $loaded[$base] = true;
152        }
153
154        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
155
156        if(@file_exists($ifile)){
157            $idata = io_readFile($ifile);
158        }else{
159            $idata = '';
160        }
161        $data  = str_replace($match[0],$idata,$data);
162    }
163    echo "$data\n";
164}
165
166/**
167 * Returns a list of possible Plugin Scripts (no existance check here)
168 *
169 * @author Andreas Gohr <andi@splitbrain.org>
170 */
171function js_pluginscripts(){
172    $list = array();
173    $plugins = plugin_list();
174    foreach ($plugins as $p){
175        $list[] = DOKU_PLUGIN."$p/script.js";
176    }
177    return $list;
178}
179
180/**
181 * Return an two-dimensional array with strings from the language file of each plugin.
182 *
183 * - $lang['js'] must be an array.
184 * - Nothing is returned for plugins without an entry for $lang['js']
185 *
186 * @author Gabriel Birke <birke@d-scribe.de>
187 */
188function js_pluginstrings()
189{
190    global $conf;
191    $pluginstrings = array();
192    $plugins = plugin_list();
193    foreach ($plugins as $p){
194        if (isset($lang)) unset($lang);
195        if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) {
196            include DOKU_PLUGIN."$p/lang/en/lang.php";
197        }
198        if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) {
199            include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php";
200        }
201        if (isset($lang['js'])) {
202            $pluginstrings[$p] = $lang['js'];
203        }
204    }
205    return $pluginstrings;
206}
207
208/**
209 * Escapes a String to be embedded in a JavaScript call, keeps \n
210 * as newline
211 *
212 * @author Andreas Gohr <andi@splitbrain.org>
213 */
214function js_escape($string){
215    return str_replace('\\\\n','\\n',addslashes($string));
216}
217
218/**
219 * Adds the given JavaScript code to the window.onload() event
220 *
221 * @author Andreas Gohr <andi@splitbrain.org>
222 */
223function js_runonstart($func){
224    echo "addInitEvent(function(){ $func; });".NL;
225}
226
227/**
228 * Strip comments and whitespaces from given JavaScript Code
229 *
230 * This is a port of Nick Galbreath's python tool jsstrip.py which is
231 * released under BSD license. See link for original code.
232 *
233 * @author Nick Galbreath <nickg@modp.com>
234 * @author Andreas Gohr <andi@splitbrain.org>
235 * @link   http://code.google.com/p/jsstrip/
236 */
237function js_compress($s){
238    $s = ltrim($s);     // strip all initial whitespace
239    $s .= "\n";
240    $i = 0;             // char index for input string
241    $j = 0;             // char forward index for input string
242    $line = 0;          // line number of file (close to it anyways)
243    $slen = strlen($s); // size of input string
244    $lch  = '';         // last char added
245    $result = '';       // we store the final result here
246
247    // items that don't need spaces next to them
248    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
249
250    $regex_starters = array("(", "=", "[", "," , ":", "!");
251
252    $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B");
253
254    while($i < $slen){
255        // skip all "boring" characters.  This is either
256        // reserved word (e.g. "for", "else", "if") or a
257        // variable/object/method (e.g. "foo.color")
258        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
259            $result .= $s{$i};
260            $i = $i + 1;
261        }
262
263        $ch = $s{$i};
264        // multiline comments (keeping IE conditionals)
265        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
266            $endC = strpos($s,'*/',$i+2);
267            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
268            $i = $endC + 2;
269            continue;
270        }
271
272        // singleline
273        if($ch == '/' && $s{$i+1} == '/'){
274            $endC = strpos($s,"\n",$i+2);
275            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
276            $i = $endC;
277            continue;
278        }
279
280        // tricky.  might be an RE
281        if($ch == '/'){
282            // rewind, skip white space
283            $j = 1;
284            while(in_array($s{$i-$j}, $whitespaces_chars)){
285                $j = $j + 1;
286            }
287            if( in_array($s{$i-$j}, $regex_starters) ){
288                // yes, this is an re
289                // now move forward and find the end of it
290                $j = 1;
291                while($s{$i+$j} != '/'){
292                    while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){
293                        $j = $j + 1;
294                    }
295                    if($s{$i+$j} == '\\') $j = $j + 2;
296                }
297                $result .= substr($s,$i,$j+1);
298                $i = $i + $j + 1;
299                continue;
300            }
301        }
302
303        // double quote strings
304        if($ch == '"'){
305            $j = 1;
306            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
307                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
308                    $j += 2;
309                }else{
310                    $j += 1;
311                }
312            }
313            $result .= substr($s,$i,$j+1);
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            $result .= substr($s,$i,$j+1);
329            $i = $i + $j + 1;
330            continue;
331        }
332
333        // whitespaces
334        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
335            // leading spaces
336            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
337                $i = $i + 1;
338                continue;
339            }
340            // trailing spaces
341            //  if this ch is space AND the last char processed
342            //  is special, then skip the space
343            $lch = substr($result,-1);
344            if($lch && (strpos($chars,$lch) !== false)){
345                $i = $i + 1;
346                continue;
347            }
348            // else after all of this convert the "whitespace" to
349            // a single space.  It will get appended below
350            $ch = ' ';
351        }
352
353        // other chars
354        $result .= $ch;
355        $i = $i + 1;
356    }
357
358    return trim($result);
359}
360
361//Setup VIM: ex: et ts=4 :
362