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