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: application/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 global $INPUT; 34 35 // decide from where to get the template 36 $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); 37 if(!$tpl) $tpl = $conf['template']; 38 39 // The generated script depends on some dynamic options 40 $cache = new cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].DOKU_BASE.$tpl,'.js'); 41 $cache->_event = 'JS_CACHE_USE'; 42 43 // array of core files 44 $files = array( 45 DOKU_INC.'lib/scripts/jquery/jquery.cookie.js', 46 DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js', 47 DOKU_INC."lib/scripts/fileuploader.js", 48 DOKU_INC."lib/scripts/fileuploaderextended.js", 49 DOKU_INC.'lib/scripts/helpers.js', 50 DOKU_INC.'lib/scripts/delay.js', 51 DOKU_INC.'lib/scripts/cookie.js', 52 DOKU_INC.'lib/scripts/script.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/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/compatibility.js', 64# disabled for FS#1958 DOKU_INC.'lib/scripts/hotkeys.js', 65 DOKU_INC.'lib/scripts/behaviour.js', 66 DOKU_INC.'lib/scripts/page.js', 67 tpl_incdir($tpl).'script.js', 68 ); 69 70 // add possible plugin scripts and userscript 71 $files = array_merge($files,js_pluginscripts()); 72 if(!empty($config_cascade['userscript']['default'])) { 73 foreach($config_cascade['userscript']['default'] as $userscript) { 74 $files[] = $userscript; 75 } 76 } 77 78 $cache_files = array_merge($files, getConfigFiles('main')); 79 $cache_files[] = __FILE__; 80 81 // check cache age & handle conditional request 82 // This may exit if a cache can be used 83 $cache_ok = $cache->useCache(array('files' => $cache_files)); 84 http_cached($cache->cache, $cache_ok); 85 86 // start output buffering and build the script 87 ob_start(); 88 89 $json = new JSON(); 90 // add some global variables 91 print "var DOKU_BASE = '".DOKU_BASE."';"; 92 print "var DOKU_TPL = '".tpl_basedir($tpl)."';"; 93 print "var DOKU_COOKIE_PARAM = " . $json->encode( 94 array( 95 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'], 96 'secure' => $conf['securecookie'] && is_ssl() 97 )).";"; 98 // FIXME: Move those to JSINFO 99 print "var DOKU_UHN = ".((int) useHeading('navigation')).";"; 100 print "var DOKU_UHC = ".((int) useHeading('content')).";"; 101 102 // load JS specific translations 103 $lang['js']['plugins'] = js_pluginstrings(); 104 $templatestrings = js_templatestrings($tpl); 105 if(!empty($templatestrings)) { 106 $lang['js']['template'] = $templatestrings; 107 } 108 echo 'LANG = '.$json->encode($lang['js']).";\n"; 109 110 // load toolbar 111 toolbar_JSdefines('toolbar'); 112 113 // load files 114 foreach($files as $file){ 115 if(!file_exists($file)) continue; 116 $ismin = (substr($file,-7) == '.min.js'); 117 $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0); 118 119 echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n"; 120 if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n"; 121 if ($debugjs) echo "\ntry {\n"; 122 js_load($file); 123 if ($debugjs) echo "\n} catch (e) {\n logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n"; 124 if($ismin) echo "\n/* END NOCOMPRESS */\n"; 125 echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n"; 126 } 127 128 // init stuff 129 if($conf['locktime'] != 0){ 130 js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")"); 131 } 132 // init hotkeys - must have been done after init of toolbar 133# disabled for FS#1958 js_runonstart('initializeHotkeys()'); 134 135 // end output buffering and get contents 136 $js = ob_get_contents(); 137 ob_end_clean(); 138 139 // strip any source maps 140 stripsourcemaps($js); 141 142 // compress whitespace and comments 143 if($conf['compress']){ 144 $js = js_compress($js); 145 } 146 147 $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033 148 149 http_cached_finish($cache->cache, $js); 150} 151 152/** 153 * Load the given file, handle include calls and print it 154 * 155 * @author Andreas Gohr <andi@splitbrain.org> 156 * 157 * @param string $file filename path to file 158 */ 159function js_load($file){ 160 if(!file_exists($file)) return; 161 static $loaded = array(); 162 163 $data = io_readFile($file); 164 while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){ 165 $ifile = $match[2]; 166 167 // is it a include_once? 168 if($match[1]){ 169 $base = utf8_basename($ifile); 170 if(array_key_exists($base, $loaded) && $loaded[$base] === true){ 171 $data = str_replace($match[0], '' ,$data); 172 continue; 173 } 174 $loaded[$base] = true; 175 } 176 177 if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile; 178 179 if(file_exists($ifile)){ 180 $idata = io_readFile($ifile); 181 }else{ 182 $idata = ''; 183 } 184 $data = str_replace($match[0],$idata,$data); 185 } 186 echo "$data\n"; 187} 188 189/** 190 * Returns a list of possible Plugin Scripts (no existance check here) 191 * 192 * @author Andreas Gohr <andi@splitbrain.org> 193 * 194 * @return array 195 */ 196function js_pluginscripts(){ 197 $list = array(); 198 $plugins = plugin_list(); 199 foreach ($plugins as $p){ 200 $list[] = DOKU_PLUGIN."$p/script.js"; 201 } 202 return $list; 203} 204 205/** 206 * Return an two-dimensional array with strings from the language file of each plugin. 207 * 208 * - $lang['js'] must be an array. 209 * - Nothing is returned for plugins without an entry for $lang['js'] 210 * 211 * @author Gabriel Birke <birke@d-scribe.de> 212 * 213 * @return array 214 */ 215function js_pluginstrings() { 216 global $conf, $config_cascade; 217 $pluginstrings = array(); 218 $plugins = plugin_list(); 219 foreach($plugins as $p) { 220 $path = DOKU_PLUGIN . $p . '/lang/'; 221 222 if(isset($lang)) unset($lang); 223 if(file_exists($path . "en/lang.php")) { 224 include $path . "en/lang.php"; 225 } 226 foreach($config_cascade['lang']['plugin'] as $config_file) { 227 if(file_exists($config_file . $p . '/en/lang.php')) { 228 include($config_file . $p . '/en/lang.php'); 229 } 230 } 231 if(isset($conf['lang']) && $conf['lang'] != 'en') { 232 if(file_exists($path . $conf['lang'] . "/lang.php")) { 233 include($path . $conf['lang'] . '/lang.php'); 234 } 235 foreach($config_cascade['lang']['plugin'] as $config_file) { 236 if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) { 237 include($config_file . $p . '/' . $conf['lang'] . '/lang.php'); 238 } 239 } 240 } 241 242 if(isset($lang['js'])) { 243 $pluginstrings[$p] = $lang['js']; 244 } 245 } 246 return $pluginstrings; 247} 248 249/** 250 * Return an two-dimensional array with strings from the language file of current active template. 251 * 252 * - $lang['js'] must be an array. 253 * - Nothing is returned for template without an entry for $lang['js'] 254 * 255 * @param string $tpl 256 * @return array 257 */ 258function js_templatestrings($tpl) { 259 global $conf, $config_cascade; 260 261 $path = tpl_incdir() . 'lang/'; 262 263 $templatestrings = array(); 264 if(file_exists($path . "en/lang.php")) { 265 include $path . "en/lang.php"; 266 } 267 foreach($config_cascade['lang']['template'] as $config_file) { 268 if(file_exists($config_file . $conf['template'] . '/en/lang.php')) { 269 include($config_file . $conf['template'] . '/en/lang.php'); 270 } 271 } 272 if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) { 273 include $path . $conf['lang'] . "/lang.php"; 274 } 275 if(isset($conf['lang']) && $conf['lang'] != 'en') { 276 if(file_exists($path . $conf['lang'] . "/lang.php")) { 277 include $path . $conf['lang'] . "/lang.php"; 278 } 279 foreach($config_cascade['lang']['template'] as $config_file) { 280 if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) { 281 include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php'); 282 } 283 } 284 } 285 286 if(isset($lang['js'])) { 287 $templatestrings[$tpl] = $lang['js']; 288 } 289 return $templatestrings; 290} 291 292/** 293 * Escapes a String to be embedded in a JavaScript call, keeps \n 294 * as newline 295 * 296 * @author Andreas Gohr <andi@splitbrain.org> 297 * 298 * @param string $string 299 * @return string 300 */ 301function js_escape($string){ 302 return str_replace('\\\\n','\\n',addslashes($string)); 303} 304 305/** 306 * Adds the given JavaScript code to the window.onload() event 307 * 308 * @author Andreas Gohr <andi@splitbrain.org> 309 * 310 * @param string $func 311 */ 312function js_runonstart($func){ 313 echo "jQuery(function(){ $func; });".NL; 314} 315 316/** 317 * Strip comments and whitespaces from given JavaScript Code 318 * 319 * This is a port of Nick Galbreath's python tool jsstrip.py which is 320 * released under BSD license. See link for original code. 321 * 322 * @author Nick Galbreath <nickg@modp.com> 323 * @author Andreas Gohr <andi@splitbrain.org> 324 * @link http://code.google.com/p/jsstrip/ 325 * 326 * @param string $s 327 * @return string 328 */ 329function js_compress($s){ 330 $s = ltrim($s); // strip all initial whitespace 331 $s .= "\n"; 332 $i = 0; // char index for input string 333 $j = 0; // char forward index for input string 334 $line = 0; // line number of file (close to it anyways) 335 $slen = strlen($s); // size of input string 336 $lch = ''; // last char added 337 $result = ''; // we store the final result here 338 339 // items that don't need spaces next to them 340 $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]"; 341 342 // items which need a space if the sign before and after whitespace is equal. 343 // E.g. '+ ++' may not be compressed to '+++' --> syntax error. 344 $ops = "+-"; 345 346 $regex_starters = array("(", "=", "[", "," , ":", "!", "&", "|"); 347 348 $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B"); 349 350 while($i < $slen){ 351 // skip all "boring" characters. This is either 352 // reserved word (e.g. "for", "else", "if") or a 353 // variable/object/method (e.g. "foo.color") 354 while ($i < $slen && (strpos($chars,$s[$i]) === false) ){ 355 $result .= $s{$i}; 356 $i = $i + 1; 357 } 358 359 $ch = $s{$i}; 360 // multiline comments (keeping IE conditionals) 361 if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){ 362 $endC = strpos($s,'*/',$i+2); 363 if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR); 364 365 // check if this is a NOCOMPRESS comment 366 if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){ 367 $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2); 368 if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR); 369 370 // verbatim copy contents, trimming but putting it on its own line 371 $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars 372 $i = $endNC + 20; // END comment = 20 chars 373 }else{ 374 $i = $endC + 2; 375 } 376 continue; 377 } 378 379 // singleline 380 if($ch == '/' && $s{$i+1} == '/'){ 381 $endC = strpos($s,"\n",$i+2); 382 if($endC === false) trigger_error('Invalid comment', E_USER_ERROR); 383 $i = $endC; 384 continue; 385 } 386 387 // tricky. might be an RE 388 if($ch == '/'){ 389 // rewind, skip white space 390 $j = 1; 391 while(in_array($s{$i-$j}, $whitespaces_chars)){ 392 $j = $j + 1; 393 } 394 if( in_array($s{$i-$j}, $regex_starters) ){ 395 // yes, this is an re 396 // now move forward and find the end of it 397 $j = 1; 398 while($s{$i+$j} != '/'){ 399 if($s{$i+$j} == '\\') $j = $j + 2; 400 else $j++; 401 } 402 $result .= substr($s,$i,$j+1); 403 $i = $i + $j + 1; 404 continue; 405 } 406 } 407 408 // double quote strings 409 if($ch == '"'){ 410 $j = 1; 411 while( $s{$i+$j} != '"' && ($i+$j < $slen)){ 412 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){ 413 $j += 2; 414 }else{ 415 $j += 1; 416 } 417 } 418 $string = substr($s,$i,$j+1); 419 // remove multiline markers: 420 $string = str_replace("\\\n",'',$string); 421 $result .= $string; 422 $i = $i + $j + 1; 423 continue; 424 } 425 426 // single quote strings 427 if($ch == "'"){ 428 $j = 1; 429 while( $s{$i+$j} != "'" && ($i+$j < $slen)){ 430 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){ 431 $j += 2; 432 }else{ 433 $j += 1; 434 } 435 } 436 $string = substr($s,$i,$j+1); 437 // remove multiline markers: 438 $string = str_replace("\\\n",'',$string); 439 $result .= $string; 440 $i = $i + $j + 1; 441 continue; 442 } 443 444 // whitespaces 445 if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){ 446 $lch = substr($result,-1); 447 448 // Only consider deleting whitespace if the signs before and after 449 // are not equal and are not an operator which may not follow itself. 450 if ($i+1 < $slen && ((!$lch || $s[$i+1] == ' ') 451 || $lch != $s[$i+1] 452 || strpos($ops,$s[$i+1]) === false)) { 453 // leading spaces 454 if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){ 455 $i = $i + 1; 456 continue; 457 } 458 // trailing spaces 459 // if this ch is space AND the last char processed 460 // is special, then skip the space 461 if($lch && (strpos($chars,$lch) !== false)){ 462 $i = $i + 1; 463 continue; 464 } 465 } 466 467 // else after all of this convert the "whitespace" to 468 // a single space. It will get appended below 469 $ch = ' '; 470 } 471 472 // other chars 473 $result .= $ch; 474 $i = $i + 1; 475 } 476 477 return trim($result); 478} 479 480//Setup VIM: ex: et ts=4 : 481