js.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  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. use dokuwiki\Cache\Cache;
  9. use dokuwiki\Extension\Event;
  10. use splitbrain\JSStrip\Exception as JSStripException;
  11. use splitbrain\JSStrip\JSStrip;
  12. if(!defined('DOKU_INC')) define('DOKU_INC', __DIR__ .'/../../');
  13. if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching)
  14. if(!defined('NL')) define('NL',"\n");
  15. if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here
  16. require_once(DOKU_INC.'inc/init.php');
  17. // Main (don't run when UNIT test)
  18. if(!defined('SIMPLE_TEST')){
  19. header('Content-Type: application/javascript; charset=utf-8');
  20. js_out();
  21. }
  22. // ---------------------- functions ------------------------------
  23. /**
  24. * Output all needed JavaScript
  25. *
  26. * @author Andreas Gohr <andi@splitbrain.org>
  27. */
  28. function js_out(){
  29. global $conf;
  30. global $lang;
  31. global $config_cascade;
  32. global $INPUT;
  33. // decide from where to get the template
  34. $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t')));
  35. if(!$tpl) $tpl = $conf['template'];
  36. // array of core files
  37. $files = array(
  38. DOKU_INC.'lib/scripts/jquery/jquery.cookie.js',
  39. DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js',
  40. DOKU_INC."lib/scripts/fileuploader.js",
  41. DOKU_INC."lib/scripts/fileuploaderextended.js",
  42. DOKU_INC.'lib/scripts/helpers.js',
  43. DOKU_INC.'lib/scripts/delay.js',
  44. DOKU_INC.'lib/scripts/cookie.js',
  45. DOKU_INC.'lib/scripts/script.js',
  46. DOKU_INC.'lib/scripts/qsearch.js',
  47. DOKU_INC.'lib/scripts/search.js',
  48. DOKU_INC.'lib/scripts/tree.js',
  49. DOKU_INC.'lib/scripts/index.js',
  50. DOKU_INC.'lib/scripts/textselection.js',
  51. DOKU_INC.'lib/scripts/toolbar.js',
  52. DOKU_INC.'lib/scripts/edit.js',
  53. DOKU_INC.'lib/scripts/editor.js',
  54. DOKU_INC.'lib/scripts/locktimer.js',
  55. DOKU_INC.'lib/scripts/linkwiz.js',
  56. DOKU_INC.'lib/scripts/media.js',
  57. DOKU_INC.'lib/scripts/compatibility.js',
  58. # disabled for FS#1958 DOKU_INC.'lib/scripts/hotkeys.js',
  59. DOKU_INC.'lib/scripts/behaviour.js',
  60. DOKU_INC.'lib/scripts/page.js',
  61. tpl_incdir($tpl).'script.js',
  62. );
  63. // add possible plugin scripts and userscript
  64. $files = array_merge($files,js_pluginscripts());
  65. if(is_array($config_cascade['userscript']['default'])) {
  66. foreach($config_cascade['userscript']['default'] as $userscript) {
  67. $files[] = $userscript;
  68. }
  69. }
  70. // Let plugins decide to either put more scripts here or to remove some
  71. Event::createAndTrigger('JS_SCRIPT_LIST', $files);
  72. // The generated script depends on some dynamic options
  73. $cache = new Cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].md5(serialize($files)),'.js');
  74. $cache->setEvent('JS_CACHE_USE');
  75. $cache_files = array_merge($files, getConfigFiles('main'));
  76. $cache_files[] = __FILE__;
  77. // check cache age & handle conditional request
  78. // This may exit if a cache can be used
  79. $cache_ok = $cache->useCache(array('files' => $cache_files));
  80. http_cached($cache->cache, $cache_ok);
  81. // start output buffering and build the script
  82. ob_start();
  83. // add some global variables
  84. print "var DOKU_BASE = '".DOKU_BASE."';";
  85. print "var DOKU_TPL = '".tpl_basedir($tpl)."';";
  86. print "var DOKU_COOKIE_PARAM = " . json_encode(
  87. array(
  88. 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'],
  89. 'secure' => $conf['securecookie'] && is_ssl()
  90. )).";";
  91. // FIXME: Move those to JSINFO
  92. print "Object.defineProperty(window, 'DOKU_UHN', { get: function() {".
  93. "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');".
  94. "return JSINFO.useHeadingNavigation; } });";
  95. print "Object.defineProperty(window, 'DOKU_UHC', { get: function() {".
  96. "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');".
  97. "return JSINFO.useHeadingContent; } });";
  98. // load JS specific translations
  99. $lang['js']['plugins'] = js_pluginstrings();
  100. $templatestrings = js_templatestrings($tpl);
  101. if(!empty($templatestrings)) {
  102. $lang['js']['template'] = $templatestrings;
  103. }
  104. echo 'LANG = '.json_encode($lang['js']).";\n";
  105. // load toolbar
  106. toolbar_JSdefines('toolbar');
  107. // load files
  108. foreach($files as $file){
  109. if(!file_exists($file)) continue;
  110. $ismin = (substr($file,-7) == '.min.js');
  111. $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0);
  112. echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
  113. if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
  114. if ($debugjs) echo "\ntry {\n";
  115. js_load($file);
  116. if ($debugjs) echo "\n} catch (e) {\n logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n";
  117. if($ismin) echo "\n/* END NOCOMPRESS */\n";
  118. echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
  119. }
  120. // init stuff
  121. if($conf['locktime'] != 0){
  122. js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")");
  123. }
  124. // init hotkeys - must have been done after init of toolbar
  125. # disabled for FS#1958 js_runonstart('initializeHotkeys()');
  126. // end output buffering and get contents
  127. $js = ob_get_contents();
  128. ob_end_clean();
  129. // strip any source maps
  130. stripsourcemaps($js);
  131. // compress whitespace and comments
  132. if($conf['compress']){
  133. try {
  134. $js = (new JSStrip())->compress($js);
  135. } catch (JSStripException $e) {
  136. $js .= "\nconsole.error(".json_encode($e->getMessage()).");\n";
  137. }
  138. }
  139. $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
  140. http_cached_finish($cache->cache, $js);
  141. }
  142. /**
  143. * Load the given file, handle include calls and print it
  144. *
  145. * @author Andreas Gohr <andi@splitbrain.org>
  146. *
  147. * @param string $file filename path to file
  148. */
  149. function js_load($file){
  150. if(!file_exists($file)) return;
  151. static $loaded = array();
  152. $data = io_readFile($file);
  153. while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
  154. $ifile = $match[2];
  155. // is it a include_once?
  156. if($match[1]){
  157. $base = \dokuwiki\Utf8\PhpString::basename($ifile);
  158. if(array_key_exists($base, $loaded) && $loaded[$base] === true){
  159. $data = str_replace($match[0], '' ,$data);
  160. continue;
  161. }
  162. $loaded[$base] = true;
  163. }
  164. if($ifile[0] != '/') $ifile = dirname($file).'/'.$ifile;
  165. $idata = '';
  166. if (file_exists($ifile)) {
  167. $ismin = (substr($ifile, -7) == '.min.js');;
  168. if ($ismin) $idata .= "\n/* BEGIN NOCOMPRESS */\n";
  169. $idata .= io_readFile($ifile);
  170. if ($ismin) $idata .= "\n/* END NOCOMPRESS */\n";
  171. }
  172. $data = str_replace($match[0],$idata,$data);
  173. }
  174. echo "$data\n";
  175. }
  176. /**
  177. * Returns a list of possible Plugin Scripts (no existance check here)
  178. *
  179. * @author Andreas Gohr <andi@splitbrain.org>
  180. *
  181. * @return array
  182. */
  183. function js_pluginscripts(){
  184. $list = array();
  185. $plugins = plugin_list();
  186. foreach ($plugins as $p){
  187. $list[] = DOKU_PLUGIN."$p/script.js";
  188. }
  189. return $list;
  190. }
  191. /**
  192. * Return an two-dimensional array with strings from the language file of each plugin.
  193. *
  194. * - $lang['js'] must be an array.
  195. * - Nothing is returned for plugins without an entry for $lang['js']
  196. *
  197. * @author Gabriel Birke <birke@d-scribe.de>
  198. *
  199. * @return array
  200. */
  201. function js_pluginstrings() {
  202. global $conf, $config_cascade;
  203. $pluginstrings = array();
  204. $plugins = plugin_list();
  205. foreach($plugins as $p) {
  206. $path = DOKU_PLUGIN . $p . '/lang/';
  207. if(isset($lang)) unset($lang);
  208. if(file_exists($path . "en/lang.php")) {
  209. include $path . "en/lang.php";
  210. }
  211. foreach($config_cascade['lang']['plugin'] as $config_file) {
  212. if(file_exists($config_file . $p . '/en/lang.php')) {
  213. include($config_file . $p . '/en/lang.php');
  214. }
  215. }
  216. if(isset($conf['lang']) && $conf['lang'] != 'en') {
  217. if(file_exists($path . $conf['lang'] . "/lang.php")) {
  218. include($path . $conf['lang'] . '/lang.php');
  219. }
  220. foreach($config_cascade['lang']['plugin'] as $config_file) {
  221. if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) {
  222. include($config_file . $p . '/' . $conf['lang'] . '/lang.php');
  223. }
  224. }
  225. }
  226. if(isset($lang['js'])) {
  227. $pluginstrings[$p] = $lang['js'];
  228. }
  229. }
  230. return $pluginstrings;
  231. }
  232. /**
  233. * Return an two-dimensional array with strings from the language file of current active template.
  234. *
  235. * - $lang['js'] must be an array.
  236. * - Nothing is returned for template without an entry for $lang['js']
  237. *
  238. * @param string $tpl
  239. * @return array
  240. */
  241. function js_templatestrings($tpl) {
  242. global $conf, $config_cascade;
  243. $path = tpl_incdir() . 'lang/';
  244. $templatestrings = array();
  245. if(file_exists($path . "en/lang.php")) {
  246. include $path . "en/lang.php";
  247. }
  248. foreach($config_cascade['lang']['template'] as $config_file) {
  249. if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
  250. include($config_file . $conf['template'] . '/en/lang.php');
  251. }
  252. }
  253. if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) {
  254. include $path . $conf['lang'] . "/lang.php";
  255. }
  256. if(isset($conf['lang']) && $conf['lang'] != 'en') {
  257. if(file_exists($path . $conf['lang'] . "/lang.php")) {
  258. include $path . $conf['lang'] . "/lang.php";
  259. }
  260. foreach($config_cascade['lang']['template'] as $config_file) {
  261. if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
  262. include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
  263. }
  264. }
  265. }
  266. if(isset($lang['js'])) {
  267. $templatestrings[$tpl] = $lang['js'];
  268. }
  269. return $templatestrings;
  270. }
  271. /**
  272. * Escapes a String to be embedded in a JavaScript call, keeps \n
  273. * as newline
  274. *
  275. * @author Andreas Gohr <andi@splitbrain.org>
  276. *
  277. * @param string $string
  278. * @return string
  279. */
  280. function js_escape($string){
  281. return str_replace('\\\\n','\\n',addslashes($string));
  282. }
  283. /**
  284. * Adds the given JavaScript code to the window.onload() event
  285. *
  286. * @author Andreas Gohr <andi@splitbrain.org>
  287. *
  288. * @param string $func
  289. */
  290. function js_runonstart($func){
  291. echo "jQuery(function(){ $func; });".NL;
  292. }