xref: /dokuwiki/lib/exe/js.php (revision c499bfe13cc054e1a85ba63045d722c713ca8da4)
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'],'.js');
36    $cache->_event = 'JS_CACHE_USE';
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/jquery/jquery.mb.browser.js",
47                DOKU_INC."lib/scripts/jquery/jquery-migrate.js",
48                DOKU_INC."lib/scripts/fileuploader.js",
49                DOKU_INC."lib/scripts/fileuploaderextended.js",
50                DOKU_INC.'lib/scripts/helpers.js',
51                DOKU_INC.'lib/scripts/delay.js',
52                DOKU_INC.'lib/scripts/cookie.js',
53                DOKU_INC.'lib/scripts/script.js',
54                DOKU_INC.'lib/scripts/tw-sack.js',
55                DOKU_INC.'lib/scripts/qsearch.js',
56                DOKU_INC.'lib/scripts/tree.js',
57                DOKU_INC.'lib/scripts/index.js',
58                DOKU_INC.'lib/scripts/drag.js',
59                DOKU_INC.'lib/scripts/textselection.js',
60                DOKU_INC.'lib/scripts/toolbar.js',
61                DOKU_INC.'lib/scripts/edit.js',
62                DOKU_INC.'lib/scripts/editor.js',
63                DOKU_INC.'lib/scripts/locktimer.js',
64                DOKU_INC.'lib/scripts/linkwiz.js',
65                DOKU_INC.'lib/scripts/media.js',
66                DOKU_INC.'lib/scripts/compatibility.js',
67# disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
68                DOKU_INC.'lib/scripts/behaviour.js',
69                DOKU_INC.'lib/scripts/page.js',
70                tpl_incdir().'script.js',
71            );
72
73    // add possible plugin scripts and userscript
74    $files   = array_merge($files,js_pluginscripts());
75    if(isset($config_cascade['userscript']['default'])){
76        $files[] = $config_cascade['userscript']['default'];
77    }
78
79    $cache_files = array_merge($files, getConfigFiles('main'));
80    $cache_files[] = __FILE__;
81
82    // check cache age & handle conditional request
83    // This may exit if a cache can be used
84    $cache_ok = $cache->useCache(array('files' => $cache_files));
85    http_cached($cache->cache, $cache_ok);
86
87    // start output buffering and build the script
88    ob_start();
89
90    // add some global variables
91    print "var DOKU_BASE   = '".DOKU_BASE."';";
92    print "var DOKU_TPL    = '".tpl_basedir()."';";
93    // FIXME: Move those to JSINFO
94    print "var DOKU_UHN    = ".((int) useHeading('navigation')).";";
95    print "var DOKU_UHC    = ".((int) useHeading('content')).";";
96
97    // load JS specific translations
98    $json = new JSON();
99    $lang['js']['plugins'] = js_pluginstrings();
100    echo 'LANG = '.$json->encode($lang['js']).";\n";
101
102    // load toolbar
103    toolbar_JSdefines('toolbar');
104
105    // load files
106    foreach($files as $file){
107        $ismin = (substr($file,-7) == '.min.js');
108
109        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
110        if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
111        js_load($file);
112        if($ismin) echo "\n/* END NOCOMPRESS */\n";
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 = utf8_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
272            // check if this is a NOCOMPRESS comment
273            if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){
274                $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2);
275                if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR);
276
277                // verbatim copy contents, trimming but putting it on its own line
278                $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars
279                $i = $endNC + 20; // END comment = 20 chars
280            }else{
281                $i = $endC + 2;
282            }
283            continue;
284        }
285
286        // singleline
287        if($ch == '/' && $s{$i+1} == '/'){
288            $endC = strpos($s,"\n",$i+2);
289            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
290            $i = $endC;
291            continue;
292        }
293
294        // tricky.  might be an RE
295        if($ch == '/'){
296            // rewind, skip white space
297            $j = 1;
298            while(in_array($s{$i-$j}, $whitespaces_chars)){
299                $j = $j + 1;
300            }
301            if( in_array($s{$i-$j}, $regex_starters) ){
302                // yes, this is an re
303                // now move forward and find the end of it
304                $j = 1;
305                while($s{$i+$j} != '/'){
306                    if($s{$i+$j} == '\\') $j = $j + 2;
307                    else $j++;
308                }
309                $result .= substr($s,$i,$j+1);
310                $i = $i + $j + 1;
311                continue;
312            }
313        }
314
315        // double quote strings
316        if($ch == '"'){
317            $j = 1;
318            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
319                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
320                    $j += 2;
321                }else{
322                    $j += 1;
323                }
324            }
325            $string  = substr($s,$i,$j+1);
326            // remove multiline markers:
327            $string  = str_replace("\\\n",'',$string);
328            $result .= $string;
329            $i = $i + $j + 1;
330            continue;
331        }
332
333        // single quote strings
334        if($ch == "'"){
335            $j = 1;
336            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
337                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
338                    $j += 2;
339                }else{
340                    $j += 1;
341                }
342            }
343            $string = substr($s,$i,$j+1);
344            // remove multiline markers:
345            $string  = str_replace("\\\n",'',$string);
346            $result .= $string;
347            $i = $i + $j + 1;
348            continue;
349        }
350
351        // whitespaces
352        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
353            // leading spaces
354            if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
355                $i = $i + 1;
356                continue;
357            }
358            // trailing spaces
359            //  if this ch is space AND the last char processed
360            //  is special, then skip the space
361            $lch = substr($result,-1);
362            if($lch && (strpos($chars,$lch) !== false)){
363                $i = $i + 1;
364                continue;
365            }
366            // else after all of this convert the "whitespace" to
367            // a single space.  It will get appended below
368            $ch = ' ';
369        }
370
371        // other chars
372        $result .= $ch;
373        $i = $i + 1;
374    }
375
376    return trim($result);
377}
378
379//Setup VIM: ex: et ts=4 :
380