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