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