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'); 14require_once(DOKU_INC.'inc/pageutils.php'); 15require_once(DOKU_INC.'inc/httputils.php'); 16require_once(DOKU_INC.'inc/io.php'); 17require_once(DOKU_INC.'inc/JSON.php'); 18 19// Main (don't run when UNIT test) 20if(!defined('SIMPLE_TEST')){ 21 header('Content-Type: text/javascript; charset=utf-8'); 22 js_out(); 23} 24 25 26// ---------------------- functions ------------------------------ 27 28/** 29 * Output all needed JavaScript 30 * 31 * @author Andreas Gohr <andi@splitbrain.org> 32 */ 33function js_out(){ 34 global $conf; 35 global $lang; 36 37 // The generated script depends on some dynamic options 38 $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'],'.js'); 39 40 // array of core files 41 $files = array( 42 DOKU_INC.'lib/scripts/helpers.js', 43 DOKU_INC.'lib/scripts/events.js', 44 DOKU_INC.'lib/scripts/delay.js', 45 DOKU_INC.'lib/scripts/cookie.js', 46 DOKU_INC.'lib/scripts/script.js', 47 DOKU_INC.'lib/scripts/tw-sack.js', 48 DOKU_INC.'lib/scripts/ajax.js', 49 DOKU_INC.'lib/scripts/index.js', 50 DOKU_INC.'lib/scripts/drag.js', 51 DOKU_INC.'lib/scripts/textselection.js', 52 DOKU_INC.'lib/scripts/toolbar.js', 53 DOKU_INC.'lib/scripts/edit.js', 54 DOKU_INC.'lib/scripts/linkwiz.js', 55 DOKU_INC.'lib/scripts/media.js', 56 DOKU_INC.'lib/scripts/subscriptions.js', 57 DOKU_TPLINC.'script.js', 58 ); 59 60 // add possible plugin scripts and userscript 61 $files = array_merge($files,js_pluginscripts()); 62 $files[] = DOKU_CONF.'userscript.js'; 63 64 // check cache age & handle conditional request 65 header('Cache-Control: public, max-age=3600'); 66 header('Pragma: public'); 67 if(js_cacheok($cache,$files)){ 68 http_conditionalRequest(filemtime($cache)); 69 if($conf['allowdebug']) header("X-CacheUsed: $cache"); 70 71 // finally send output 72 if ($conf['gzip_output'] && http_gzip_valid($cache)) { 73 header('Vary: Accept-Encoding'); 74 header('Content-Encoding: gzip'); 75 readfile($cache.".gz"); 76 } else { 77 if (!http_sendfile($cache)) readfile($cache); 78 } 79 return; 80 } else { 81 http_conditionalRequest(time()); 82 } 83 84 // start output buffering and build the script 85 ob_start(); 86 87 // add some global variables 88 print "var DOKU_BASE = '".DOKU_BASE."';"; 89 print "var DOKU_TPL = '".DOKU_TPL."';"; 90 print "var DOKU_UHN = ".((int) useHeading('navigation')).";"; 91 print "var DOKU_UHC = ".((int) useHeading('content')).";"; 92 93 // load JS specific translations 94 $json = new JSON(); 95 $lang['js']['plugins'] = js_pluginstrings(); 96 echo 'LANG = '.$json->encode($lang['js']).";\n"; 97 98 // load toolbar 99 require_once(DOKU_INC.'inc/toolbar.php'); 100 toolbar_JSdefines('toolbar'); 101 102 // load files 103 foreach($files as $file){ 104 echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n"; 105 js_load($file); 106 echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n"; 107 } 108 109 110 // init stuff 111 js_runonstart("addEvent(document,'click',closePopups)"); 112 js_runonstart('addTocToggle()'); 113 js_runonstart("initSizeCtl('size__ctl','wiki__text')"); 114 js_runonstart("initToolbar('tool__bar','wiki__text',toolbar)"); 115 js_runonstart("initChangeCheck('".js_escape($lang['notsavedyet'])."')"); 116 js_runonstart("locktimer.init(".($conf['locktime'] - 60).",'".js_escape($lang['willexpire'])."',".$conf['usedraft'].")"); 117 js_runonstart('scrollToMarker()'); 118 js_runonstart('focusMarker()'); 119 120 // end output buffering and get contents 121 $js = ob_get_contents(); 122 ob_end_clean(); 123 124 // compress whitespace and comments 125 if($conf['compress']){ 126 $js = js_compress($js); 127 } 128 129 $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033 130 131 // save cache file 132 io_saveFile($cache,$js); 133 if(function_exists('gzopen')) io_saveFile("$cache.gz",$js); 134 135 // finally send output 136 if ($conf['gzip_output']) { 137 header('Vary: Accept-Encoding'); 138 header('Content-Encoding: gzip'); 139 print gzencode($js,9,FORCE_GZIP); 140 } else { 141 print $js; 142 } 143} 144 145/** 146 * Load the given file, handle include calls and print it 147 * 148 * @author Andreas Gohr <andi@splitbrain.org> 149 */ 150function js_load($file){ 151 if(!@file_exists($file)) return; 152 static $loaded = array(); 153 154 $data = io_readFile($file); 155 while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){ 156 $ifile = $match[2]; 157 158 // is it a include_once? 159 if($match[1]){ 160 $base = basename($ifile); 161 if($loaded[$base]) continue; 162 $loaded[$base] = true; 163 } 164 165 if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile; 166 167 if(@file_exists($ifile)){ 168 $idata = io_readFile($ifile); 169 }else{ 170 $idata = ''; 171 } 172 $data = str_replace($match[0],$idata,$data); 173 } 174 echo $data; 175} 176 177/** 178 * Checks if a JavaScript Cache file still is valid 179 * 180 * @author Andreas Gohr <andi@splitbrain.org> 181 */ 182function js_cacheok($cache,$files){ 183 if(isset($_REQUEST['purge'])) return false; //support purge request 184 185 $ctime = @filemtime($cache); 186 if(!$ctime) return false; //There is no cache 187 188 // some additional files to check 189 $files = array_merge($files, getConfigFiles('main')); 190 $files[] = DOKU_CONF.'userscript.js'; 191 $files[] = __FILE__; 192 193 // now walk the files 194 foreach($files as $file){ 195 if(@filemtime($file) > $ctime){ 196 return false; 197 } 198 } 199 return true; 200} 201 202/** 203 * Returns a list of possible Plugin Scripts (no existance check here) 204 * 205 * @author Andreas Gohr <andi@splitbrain.org> 206 */ 207function js_pluginscripts(){ 208 $list = array(); 209 $plugins = plugin_list(); 210 foreach ($plugins as $p){ 211 $list[] = DOKU_PLUGIN."$p/script.js"; 212 } 213 return $list; 214} 215 216/** 217 * Return an two-dimensional array with strings from the language file of each plugin. 218 * 219 * - $lang['js'] must be an array. 220 * - Nothing is returned for plugins without an entry for $lang['js'] 221 * 222 * @author Gabriel Birke <birke@d-scribe.de> 223 */ 224function js_pluginstrings() 225{ 226 global $conf; 227 $pluginstrings = array(); 228 $plugins = plugin_list(); 229 foreach ($plugins as $p){ 230 if (isset($lang)) unset($lang); 231 if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) { 232 include DOKU_PLUGIN."$p/lang/en/lang.php"; 233 } 234 if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) { 235 include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php"; 236 } 237 if (isset($lang['js'])) { 238 $pluginstrings[$p] = $lang['js']; 239 } 240 } 241 return $pluginstrings; 242} 243 244/** 245 * Escapes a String to be embedded in a JavaScript call, keeps \n 246 * as newline 247 * 248 * @author Andreas Gohr <andi@splitbrain.org> 249 */ 250function js_escape($string){ 251 return str_replace('\\\\n','\\n',addslashes($string)); 252} 253 254/** 255 * Adds the given JavaScript code to the window.onload() event 256 * 257 * @author Andreas Gohr <andi@splitbrain.org> 258 */ 259function js_runonstart($func){ 260 echo "addInitEvent(function(){ $func; });".NL; 261} 262 263/** 264 * Strip comments and whitespaces from given JavaScript Code 265 * 266 * This is a port of Nick Galbreath's python tool jsstrip.py which is 267 * released under BSD license. See link for original code. 268 * 269 * @author Nick Galbreath <nickg@modp.com> 270 * @author Andreas Gohr <andi@splitbrain.org> 271 * @link http://code.google.com/p/jsstrip/ 272 */ 273function js_compress($s){ 274 $s = ltrim($s); // strip all initial whitespace 275 $s .= "\n"; 276 $i = 0; // char index for input string 277 $j = 0; // char forward index for input string 278 $line = 0; // line number of file (close to it anyways) 279 $slen = strlen($s); // size of input string 280 $lch = ''; // last char added 281 $result = ''; // we store the final result here 282 283 // items that don't need spaces next to them 284 $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]"; 285 286 $regex_starters = array("(", "=", "[", "," , ":"); 287 288 $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B"); 289 290 while($i < $slen){ 291 // skip all "boring" characters. This is either 292 // reserved word (e.g. "for", "else", "if") or a 293 // variable/object/method (e.g. "foo.color") 294 while ($i < $slen && (strpos($chars,$s[$i]) === false) ){ 295 $result .= $s{$i}; 296 $i = $i + 1; 297 } 298 299 $ch = $s{$i}; 300 // multiline comments (keeping IE conditionals) 301 if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){ 302 $endC = strpos($s,'*/',$i+2); 303 if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR); 304 $i = $endC + 2; 305 continue; 306 } 307 308 // singleline 309 if($ch == '/' && $s{$i+1} == '/'){ 310 $endC = strpos($s,"\n",$i+2); 311 if($endC === false) trigger_error('Invalid comment', E_USER_ERROR); 312 $i = $endC; 313 continue; 314 } 315 316 // tricky. might be an RE 317 if($ch == '/'){ 318 // rewind, skip white space 319 $j = 1; 320 while(in_array($s{$i-$j}, $whitespaces_chars)){ 321 $j = $j + 1; 322 } 323 if( in_array($s{$i-$j}, $regex_starters) ){ 324 // yes, this is an re 325 // now move forward and find the end of it 326 $j = 1; 327 while($s{$i+$j} != '/'){ 328 while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){ 329 $j = $j + 1; 330 } 331 if($s{$i+$j} == '\\') $j = $j + 2; 332 } 333 $result .= substr($s,$i,$j+1); 334 $i = $i + $j + 1; 335 continue; 336 } 337 } 338 339 // double quote strings 340 if($ch == '"'){ 341 $j = 1; 342 while( $s{$i+$j} != '"' && ($i+$j < $slen)){ 343 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){ 344 $j += 2; 345 }else{ 346 $j += 1; 347 } 348 } 349 $result .= substr($s,$i,$j+1); 350 $i = $i + $j + 1; 351 continue; 352 } 353 354 // single quote strings 355 if($ch == "'"){ 356 $j = 1; 357 while( $s{$i+$j} != "'" && ($i+$j < $slen)){ 358 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){ 359 $j += 2; 360 }else{ 361 $j += 1; 362 } 363 } 364 $result .= substr($s,$i,$j+1); 365 $i = $i + $j + 1; 366 continue; 367 } 368 369 // whitespaces 370 if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){ 371 // leading spaces 372 if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){ 373 $i = $i + 1; 374 continue; 375 } 376 // trailing spaces 377 // if this ch is space AND the last char processed 378 // is special, then skip the space 379 $lch = substr($result,-1); 380 if($lch && (strpos($chars,$lch) !== false)){ 381 $i = $i + 1; 382 continue; 383 } 384 // else after all of this convert the "whitespace" to 385 // a single space. It will get appended below 386 $ch = ' '; 387 } 388 389 // other chars 390 $result .= $ch; 391 $i = $i + 1; 392 } 393 394 return trim($result); 395} 396 397//Setup VIM: ex: et ts=4 enc=utf-8 : 398