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