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