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 // load minified version for some files 44 $min = $conf['compress'] ? '.min' : ''; 45 46 // array of core files 47 $files = array( 48 DOKU_INC."lib/scripts/jquery/jquery$min.js", 49 DOKU_INC.'lib/scripts/jquery/jquery.cookie.js', 50 DOKU_INC."lib/scripts/jquery/jquery-ui$min.js", 51 DOKU_INC."lib/scripts/jquery/jquery-migrate$min.js", 52 DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js', 53 DOKU_INC."lib/scripts/fileuploader.js", 54 DOKU_INC."lib/scripts/fileuploaderextended.js", 55 DOKU_INC.'lib/scripts/helpers.js', 56 DOKU_INC.'lib/scripts/delay.js', 57 DOKU_INC.'lib/scripts/cookie.js', 58 DOKU_INC.'lib/scripts/script.js', 59 DOKU_INC.'lib/scripts/tw-sack.js', 60 DOKU_INC.'lib/scripts/qsearch.js', 61 DOKU_INC.'lib/scripts/tree.js', 62 DOKU_INC.'lib/scripts/index.js', 63 DOKU_INC.'lib/scripts/drag.js', 64 DOKU_INC.'lib/scripts/textselection.js', 65 DOKU_INC.'lib/scripts/toolbar.js', 66 DOKU_INC.'lib/scripts/edit.js', 67 DOKU_INC.'lib/scripts/editor.js', 68 DOKU_INC.'lib/scripts/locktimer.js', 69 DOKU_INC.'lib/scripts/linkwiz.js', 70 DOKU_INC.'lib/scripts/media.js', 71# deprecated DOKU_INC.'lib/scripts/compatibility.js', 72# disabled for FS#1958 DOKU_INC.'lib/scripts/hotkeys.js', 73 DOKU_INC.'lib/scripts/behaviour.js', 74 DOKU_INC.'lib/scripts/page.js', 75 tpl_incdir($tpl).'script.js', 76 ); 77 78 // add possible plugin scripts and userscript 79 $files = array_merge($files,js_pluginscripts()); 80 if(!empty($config_cascade['userscript']['default'])) { 81 foreach($config_cascade['userscript']['default'] as $userscript) { 82 $files[] = $userscript; 83 } 84 } 85 86 $cache_files = array_merge($files, getConfigFiles('main')); 87 $cache_files[] = __FILE__; 88 89 // check cache age & handle conditional request 90 // This may exit if a cache can be used 91 $cache_ok = $cache->useCache(array('files' => $cache_files)); 92 http_cached($cache->cache, $cache_ok); 93 94 // start output buffering and build the script 95 ob_start(); 96 97 $json = new JSON(); 98 // add some global variables 99 print "var DOKU_BASE = '".DOKU_BASE."';"; 100 print "var DOKU_TPL = '".tpl_basedir($tpl)."';"; 101 print "var DOKU_COOKIE_PARAM = " . $json->encode( 102 array( 103 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'], 104 'secure' => $conf['securecookie'] && is_ssl() 105 )).";"; 106 // FIXME: Move those to JSINFO 107 print "var DOKU_UHN = ".((int) useHeading('navigation')).";"; 108 print "var DOKU_UHC = ".((int) useHeading('content')).";"; 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($loaded[$base]){ 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; 225 $pluginstrings = array(); 226 $plugins = plugin_list(); 227 foreach ($plugins as $p){ 228 if (isset($lang)) unset($lang); 229 if (file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) { 230 include DOKU_PLUGIN."$p/lang/en/lang.php"; 231 } 232 if (isset($conf['lang']) && $conf['lang']!='en' && file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) { 233 include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php"; 234 } 235 if (isset($lang['js'])) { 236 $pluginstrings[$p] = $lang['js']; 237 } 238 } 239 return $pluginstrings; 240} 241 242/** 243 * Return an two-dimensional array with strings from the language file of current active template. 244 * 245 * - $lang['js'] must be an array. 246 * - Nothing is returned for template without an entry for $lang['js'] 247 * 248 * @param string $tpl 249 * @return array 250 */ 251function js_templatestrings($tpl) { 252 global $conf; 253 $templatestrings = array(); 254 if (file_exists(tpl_incdir($tpl)."lang/en/lang.php")) { 255 include tpl_incdir($tpl)."lang/en/lang.php"; 256 } 257 if (isset($conf['lang']) && $conf['lang']!='en' && file_exists(tpl_incdir($tpl)."lang/".$conf['lang']."/lang.php")) { 258 include tpl_incdir($tpl)."lang/".$conf['lang']."/lang.php"; 259 } 260 if (isset($lang['js'])) { 261 $templatestrings[$tpl] = $lang['js']; 262 } 263 return $templatestrings; 264} 265 266/** 267 * Escapes a String to be embedded in a JavaScript call, keeps \n 268 * as newline 269 * 270 * @author Andreas Gohr <andi@splitbrain.org> 271 * 272 * @param string $string 273 * @return string 274 */ 275function js_escape($string){ 276 return str_replace('\\\\n','\\n',addslashes($string)); 277} 278 279/** 280 * Adds the given JavaScript code to the window.onload() event 281 * 282 * @author Andreas Gohr <andi@splitbrain.org> 283 * 284 * @param string $func 285 */ 286function js_runonstart($func){ 287 echo "jQuery(function(){ $func; });".NL; 288} 289 290/** 291 * Strip comments and whitespaces from given JavaScript Code 292 * 293 * This is a port of Nick Galbreath's python tool jsstrip.py which is 294 * released under BSD license. See link for original code. 295 * 296 * @author Nick Galbreath <nickg@modp.com> 297 * @author Andreas Gohr <andi@splitbrain.org> 298 * @link http://code.google.com/p/jsstrip/ 299 * 300 * @param string $s 301 * @return string 302 */ 303function js_compress($s){ 304 $s = ltrim($s); // strip all initial whitespace 305 $s .= "\n"; 306 $i = 0; // char index for input string 307 $j = 0; // char forward index for input string 308 $line = 0; // line number of file (close to it anyways) 309 $slen = strlen($s); // size of input string 310 $lch = ''; // last char added 311 $result = ''; // we store the final result here 312 313 // items that don't need spaces next to them 314 $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]"; 315 316 // items which need a space if the sign before and after whitespace is equal. 317 // E.g. '+ ++' may not be compressed to '+++' --> syntax error. 318 $ops = "+-"; 319 320 $regex_starters = array("(", "=", "[", "," , ":", "!", "&", "|"); 321 322 $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B"); 323 324 while($i < $slen){ 325 // skip all "boring" characters. This is either 326 // reserved word (e.g. "for", "else", "if") or a 327 // variable/object/method (e.g. "foo.color") 328 while ($i < $slen && (strpos($chars,$s[$i]) === false) ){ 329 $result .= $s{$i}; 330 $i = $i + 1; 331 } 332 333 $ch = $s{$i}; 334 // multiline comments (keeping IE conditionals) 335 if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){ 336 $endC = strpos($s,'*/',$i+2); 337 if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR); 338 339 // check if this is a NOCOMPRESS comment 340 if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){ 341 $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2); 342 if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR); 343 344 // verbatim copy contents, trimming but putting it on its own line 345 $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars 346 $i = $endNC + 20; // END comment = 20 chars 347 }else{ 348 $i = $endC + 2; 349 } 350 continue; 351 } 352 353 // singleline 354 if($ch == '/' && $s{$i+1} == '/'){ 355 $endC = strpos($s,"\n",$i+2); 356 if($endC === false) trigger_error('Invalid comment', E_USER_ERROR); 357 $i = $endC; 358 continue; 359 } 360 361 // tricky. might be an RE 362 if($ch == '/'){ 363 // rewind, skip white space 364 $j = 1; 365 while(in_array($s{$i-$j}, $whitespaces_chars)){ 366 $j = $j + 1; 367 } 368 if( in_array($s{$i-$j}, $regex_starters) ){ 369 // yes, this is an re 370 // now move forward and find the end of it 371 $j = 1; 372 while($s{$i+$j} != '/'){ 373 if($s{$i+$j} == '\\') $j = $j + 2; 374 else $j++; 375 } 376 $result .= substr($s,$i,$j+1); 377 $i = $i + $j + 1; 378 continue; 379 } 380 } 381 382 // double quote strings 383 if($ch == '"'){ 384 $j = 1; 385 while( $s{$i+$j} != '"' && ($i+$j < $slen)){ 386 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){ 387 $j += 2; 388 }else{ 389 $j += 1; 390 } 391 } 392 $string = substr($s,$i,$j+1); 393 // remove multiline markers: 394 $string = str_replace("\\\n",'',$string); 395 $result .= $string; 396 $i = $i + $j + 1; 397 continue; 398 } 399 400 // single quote strings 401 if($ch == "'"){ 402 $j = 1; 403 while( $s{$i+$j} != "'" && ($i+$j < $slen)){ 404 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){ 405 $j += 2; 406 }else{ 407 $j += 1; 408 } 409 } 410 $string = substr($s,$i,$j+1); 411 // remove multiline markers: 412 $string = str_replace("\\\n",'',$string); 413 $result .= $string; 414 $i = $i + $j + 1; 415 continue; 416 } 417 418 // whitespaces 419 if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){ 420 $lch = substr($result,-1); 421 422 // Only consider deleting whitespace if the signs before and after 423 // are not equal and are not an operator which may not follow itself. 424 if ((!$lch || $s[$i+1] == ' ') 425 || $lch != $s[$i+1] 426 || strpos($ops,$s[$i+1]) === false) { 427 // leading spaces 428 if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){ 429 $i = $i + 1; 430 continue; 431 } 432 // trailing spaces 433 // if this ch is space AND the last char processed 434 // is special, then skip the space 435 if($lch && (strpos($chars,$lch) !== false)){ 436 $i = $i + 1; 437 continue; 438 } 439 } 440 441 // else after all of this convert the "whitespace" to 442 // a single space. It will get appended below 443 $ch = ' '; 444 } 445 446 // other chars 447 $result .= $ch; 448 $i = $i + 1; 449 } 450 451 return trim($result); 452} 453 454//Setup VIM: ex: et ts=4 : 455