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 $edit = (bool) $_REQUEST['edit']; // edit or preview mode? 37 $write = (bool) $_REQUEST['write']; // writable? 38 39 // The generated script depends on some dynamic options 40 $cache = getCacheName('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].$edit.'x'.$write,'.js'); 41 42 // Array of needed files 43 $files = array( 44 DOKU_INC.'lib/scripts/helpers.js', 45 DOKU_INC.'lib/scripts/events.js', 46 DOKU_INC.'lib/scripts/cookie.js', 47 DOKU_INC.'lib/scripts/script.js', 48 DOKU_INC.'lib/scripts/tw-sack.js', 49 DOKU_INC.'lib/scripts/ajax.js', 50 DOKU_INC.'lib/scripts/index.js', 51 ); 52 if($edit){ 53 if($write){ 54 $files[] = DOKU_INC.'lib/scripts/textselection.js'; 55 $files[] = DOKU_INC.'lib/scripts/toolbar.js'; 56 $files[] = DOKU_INC.'lib/scripts/edit.js'; 57 } 58 $files[] = DOKU_INC.'lib/scripts/media.js'; 59 } 60 $files[] = DOKU_TPLINC.'script.js'; 61 62 // get possible plugin scripts 63 $plugins = js_pluginscripts(); 64 65 // check cache age & handle conditional request 66 header('Cache-Control: public, max-age=3600'); 67 header('Pragma: public'); 68 if(js_cacheok($cache,array_merge($files,$plugins))){ 69 http_conditionalRequest(filemtime($cache)); 70 if($conf['allowdebug']) header("X-CacheUsed: $cache"); 71 72 // finally send output 73 if ($conf['gzip_output'] && http_gzip_valid($cache)) { 74 header('Vary: Accept-Encoding'); 75 header('Content-Encoding: gzip'); 76 readfile($cache.".gz"); 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 ($conf['gzip_output']) { 167 header('Vary: Accept-Encoding'); 168 header('Content-Encoding: gzip'); 169 print gzencode($js,9,FORCE_GZIP); 170 } else { 171 print $js; 172 } 173} 174 175/** 176 * Load the given file, handle include calls and print it 177 * 178 * @author Andreas Gohr <andi@splitbrain.org> 179 */ 180function js_load($file){ 181 if(!@file_exists($file)) return; 182 static $loaded = array(); 183 184 $data = io_readFile($file); 185 while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\./]+)\s*\*/#',$data,$match)){ 186 $ifile = $match[2]; 187 188 // is it a include_once? 189 if($match[1]){ 190 $base = basename($ifile); 191 if($loaded[$base]) continue; 192 $loaded[$base] = true; 193 } 194 195 if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile; 196 197 if(@file_exists($ifile)){ 198 $idata = io_readFile($ifile); 199 }else{ 200 $idata = ''; 201 } 202 $data = str_replace($match[0],$idata,$data); 203 } 204 echo $data; 205} 206 207/** 208 * Checks if a JavaScript Cache file still is valid 209 * 210 * @author Andreas Gohr <andi@splitbrain.org> 211 */ 212function js_cacheok($cache,$files){ 213 if($_REQUEST['purge']) return false; //support purge request 214 215 $ctime = @filemtime($cache); 216 if(!$ctime) return false; //There is no cache 217 218 // some additional files to check 219 $files = array_merge($files, getConfigFiles('main')); 220 $files[] = DOKU_CONF.'userscript.js'; 221 $files[] = __FILE__; 222 223 // now walk the files 224 foreach($files as $file){ 225 if(@filemtime($file) > $ctime){ 226 return false; 227 } 228 } 229 return true; 230} 231 232/** 233 * Returns a list of possible Plugin Scripts (no existance check here) 234 * 235 * @author Andreas Gohr <andi@splitbrain.org> 236 */ 237function js_pluginscripts(){ 238 $list = array(); 239 $plugins = plugin_list(); 240 foreach ($plugins as $p){ 241 $list[] = DOKU_PLUGIN."$p/script.js"; 242 } 243 return $list; 244} 245 246/** 247 * Return an two-dimensional array with strings from the language file of each plugin. 248 * 249 * - $lang['js'] must be an array. 250 * - Nothing is returned for plugins without an entry for $lang['js'] 251 * 252 * @author Gabriel Birke <birke@d-scribe.de> 253 */ 254function js_pluginstrings() 255{ 256 global $conf; 257 $pluginstrings = array(); 258 $plugins = plugin_list(); 259 foreach ($plugins as $p){ 260 if (isset($lang)) unset($lang); 261 if (@file_exists(DOKU_PLUGIN."$p/lang/en/lang.php")) { 262 include DOKU_PLUGIN."$p/lang/en/lang.php"; 263 } 264 if (isset($conf['lang']) && $conf['lang']!='en' && @file_exists(DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php")) { 265 include DOKU_PLUGIN."$p/lang/".$conf['lang']."/lang.php"; 266 } 267 if (isset($lang['js'])) { 268 $pluginstrings[$p] = $lang['js']; 269 } 270 } 271 return $pluginstrings; 272} 273 274/** 275 * Escapes a String to be embedded in a JavaScript call, keeps \n 276 * as newline 277 * 278 * @author Andreas Gohr <andi@splitbrain.org> 279 */ 280function js_escape($string){ 281 return str_replace('\\\\n','\\n',addslashes($string)); 282} 283 284/** 285 * Adds the given JavaScript code to the window.onload() event 286 * 287 * @author Andreas Gohr <andi@splitbrain.org> 288 */ 289function js_runonstart($func){ 290 echo "addInitEvent(function(){ $func; });".NL; 291} 292 293/** 294 * Strip comments and whitespaces from given JavaScript Code 295 * 296 * This is a port of Nick Galbreath's python tool jsstrip.py which is 297 * released under BSD license. See link for original code. 298 * 299 * @author Nick Galbreath <nickg@modp.com> 300 * @author Andreas Gohr <andi@splitbrain.org> 301 * @link http://code.google.com/p/jsstrip/ 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 while($i < $slen){ 317 // skip all "boring" characters. This is either 318 // reserved word (e.g. "for", "else", "if") or a 319 // variable/object/method (e.g. "foo.color") 320 while ($i < $slen && (strpos($chars,$s[$i]) === false) ){ 321 $result .= $s{$i}; 322 $i = $i + 1; 323 } 324 325 $ch = $s{$i}; 326 // multiline comments (keeping IE conditionals) 327 if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){ 328 $endC = strpos($s,'*/',$i+2); 329 if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR); 330 $i = $endC + 2; 331 continue; 332 } 333 334 // singleline 335 if($ch == '/' && $s{$i+1} == '/'){ 336 $endC = strpos($s,"\n",$i+2); 337 if($endC === false) trigger_error('Invalid comment', E_USER_ERROR); 338 $i = $endC; 339 continue; 340 } 341 342 // tricky. might be an RE 343 if($ch == '/'){ 344 // rewind, skip white space 345 $j = 1; 346 while($s{$i-$j} == ' '){ 347 $j = $j + 1; 348 } 349 if( ($s{$i-$j} == '=') || ($s{$i-$j} == '(') ){ 350 // yes, this is an re 351 // now move forward and find the end of it 352 $j = 1; 353 while($s{$i+$j} != '/'){ 354 while( ($s{$i+$j} != '\\') && ($s{$i+$j} != '/')){ 355 $j = $j + 1; 356 } 357 if($s{$i+$j} == '\\') $j = $j + 2; 358 } 359 $result .= substr($s,$i,$j+1); 360 $i = $i + $j + 1; 361 continue; 362 } 363 } 364 365 // double quote strings 366 if($ch == '"'){ 367 $j = 1; 368 while( $s{$i+$j} != '"' && ($i+$j < $slen)){ 369 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){ 370 $j += 2; 371 }else{ 372 $j += 1; 373 } 374 } 375 $result .= substr($s,$i,$j+1); 376 $i = $i + $j + 1; 377 continue; 378 } 379 380 // single quote strings 381 if($ch == "'"){ 382 $j = 1; 383 while( $s{$i+$j} != "'" && ($i+$j < $slen)){ 384 if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){ 385 $j += 2; 386 }else{ 387 $j += 1; 388 } 389 } 390 $result .= substr($s,$i,$j+1); 391 $i = $i + $j + 1; 392 continue; 393 } 394 395 // whitespaces 396 if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){ 397 // leading spaces 398 if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){ 399 $i = $i + 1; 400 continue; 401 } 402 // trailing spaces 403 // if this ch is space AND the last char processed 404 // is special, then skip the space 405 $lch = substr($result,-1); 406 if($lch && (strpos($chars,$lch) !== false)){ 407 $i = $i + 1; 408 continue; 409 } 410 // else after all of this convert the "whitespace" to 411 // a single space. It will get appended below 412 $ch = ' '; 413 } 414 415 // other chars 416 $result .= $ch; 417 $i = $i + 1; 418 } 419 420 return trim($result); 421} 422 423//Setup VIM: ex: et ts=4 enc=utf-8 : 424?> 425