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