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