xref: /dokuwiki/lib/exe/js.php (revision 64159a61e94d0ce680071c8890e144982c3a8cbe)
178a6aeb1SAndreas Gohr<?php
278a6aeb1SAndreas Gohr/**
378a6aeb1SAndreas Gohr * DokuWiki JavaScript creator
478a6aeb1SAndreas Gohr *
578a6aeb1SAndreas Gohr * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
678a6aeb1SAndreas Gohr * @author     Andreas Gohr <andi@splitbrain.org>
778a6aeb1SAndreas Gohr */
878a6aeb1SAndreas Gohr
9d0a27cb0SAndreas Gohrif(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../');
101c2d1019SAndreas Gohrif(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching)
11b1a4fe22SAndreas Gohrif(!defined('NL')) define('NL',"\n");
1298bda4fdSAndreas Gohrif(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here
1378a6aeb1SAndreas Gohrrequire_once(DOKU_INC.'inc/init.php');
1478a6aeb1SAndreas Gohr
1578a6aeb1SAndreas Gohr// Main (don't run when UNIT test)
1678a6aeb1SAndreas Gohrif(!defined('SIMPLE_TEST')){
17138a9500SAndreas Gohr    header('Content-Type: application/javascript; charset=utf-8');
1878a6aeb1SAndreas Gohr    js_out();
1978a6aeb1SAndreas Gohr}
2078a6aeb1SAndreas Gohr
2178a6aeb1SAndreas Gohr
2278a6aeb1SAndreas Gohr// ---------------------- functions ------------------------------
2378a6aeb1SAndreas Gohr
2478a6aeb1SAndreas Gohr/**
2578a6aeb1SAndreas Gohr * Output all needed JavaScript
2678a6aeb1SAndreas Gohr *
2778a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
2878a6aeb1SAndreas Gohr */
2978a6aeb1SAndreas Gohrfunction js_out(){
3078a6aeb1SAndreas Gohr    global $conf;
3178a6aeb1SAndreas Gohr    global $lang;
3209edb711SAndreas Gohr    global $config_cascade;
335fc6f52eSAnika Henke    global $INPUT;
345fc6f52eSAnika Henke
355fc6f52eSAnika Henke    // decide from where to get the template
365fc6f52eSAnika Henke    $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t')));
375fc6f52eSAnika Henke    if(!$tpl) $tpl = $conf['template'];
3878a6aeb1SAndreas Gohr
396392c3b6SAndreas Gohr    // array of core files
4078a6aeb1SAndreas Gohr    $files = array(
41fdfb9c6aSMichal Rezler                DOKU_INC.'lib/scripts/jquery/jquery.cookie.js',
42138bfd16SAndreas Gohr                DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js',
4309063cc6SKate Arzamastseva                DOKU_INC."lib/scripts/fileuploader.js",
448d744859SKate Arzamastseva                DOKU_INC."lib/scripts/fileuploaderextended.js",
4586045fe9Swingedfox                DOKU_INC.'lib/scripts/helpers.js',
4621ed6025SAdrian Lang                DOKU_INC.'lib/scripts/delay.js',
473df72098SAndreas Gohr                DOKU_INC.'lib/scripts/cookie.js',
4878a6aeb1SAndreas Gohr                DOKU_INC.'lib/scripts/script.js',
49c949174aSAdrian Lang                DOKU_INC.'lib/scripts/qsearch.js',
50bb8ef867SMichael Große                DOKU_INC.'lib/scripts/search.js',
51d10c9a74SAdrian Lang                DOKU_INC.'lib/scripts/tree.js',
52a06884abSAndreas Gohr                DOKU_INC.'lib/scripts/index.js',
536392c3b6SAndreas Gohr                DOKU_INC.'lib/scripts/textselection.js',
546392c3b6SAndreas Gohr                DOKU_INC.'lib/scripts/toolbar.js',
556392c3b6SAndreas Gohr                DOKU_INC.'lib/scripts/edit.js',
56ddf8a04fSAndreas Gohr                DOKU_INC.'lib/scripts/editor.js',
5755f92d7eSAndreas Gohr                DOKU_INC.'lib/scripts/locktimer.js',
586392c3b6SAndreas Gohr                DOKU_INC.'lib/scripts/linkwiz.js',
596392c3b6SAndreas Gohr                DOKU_INC.'lib/scripts/media.js',
60767d1669SAndreas Gohr                DOKU_INC.'lib/scripts/compatibility.js',
6187e7175eSAndreas Gohr# disabled for FS#1958                DOKU_INC.'lib/scripts/hotkeys.js',
6217e2e254SAndreas Gohr                DOKU_INC.'lib/scripts/behaviour.js',
63fbedf126SAndreas Gohr                DOKU_INC.'lib/scripts/page.js',
645fc6f52eSAnika Henke                tpl_incdir($tpl).'script.js',
6578a6aeb1SAndreas Gohr            );
6678a6aeb1SAndreas Gohr
676392c3b6SAndreas Gohr    // add possible plugin scripts and userscript
686392c3b6SAndreas Gohr    $files   = array_merge($files,js_pluginscripts());
697b909d5eSGerrit Uitslag    if(!empty($config_cascade['userscript']['default'])) {
707b909d5eSGerrit Uitslag        foreach($config_cascade['userscript']['default'] as $userscript) {
717b909d5eSGerrit Uitslag            $files[] = $userscript;
727b909d5eSGerrit Uitslag        }
7309edb711SAndreas Gohr    }
7478a6aeb1SAndreas Gohr
756d3bebffSGerry Weißbach    // Let plugins decide to either put more scripts here or to remove some
766d3bebffSGerry Weißbach    trigger_event('JS_SCRIPT_LIST', $files);
776d3bebffSGerry Weißbach
786d3bebffSGerry Weißbach    // The generated script depends on some dynamic options
796d3bebffSGerry Weißbach    $cache = new cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].md5(serialize($files)),'.js');
806d3bebffSGerry Weißbach    $cache->_event = 'JS_CACHE_USE';
816d3bebffSGerry Weißbach
826619f42eSAdrian Lang    $cache_files = array_merge($files, getConfigFiles('main'));
836619f42eSAdrian Lang    $cache_files[] = __FILE__;
84ca2b464bSChris Smith
856619f42eSAdrian Lang    // check cache age & handle conditional request
866619f42eSAdrian Lang    // This may exit if a cache can be used
87e67004f5SAndreas Gohr    $cache_ok = $cache->useCache(array('files' => $cache_files));
88e67004f5SAndreas Gohr    http_cached($cache->cache, $cache_ok);
8978a6aeb1SAndreas Gohr
9078a6aeb1SAndreas Gohr    // start output buffering and build the script
9178a6aeb1SAndreas Gohr    ob_start();
9278a6aeb1SAndreas Gohr
93df5d307eSGerrit Uitslag    $json = new JSON();
943df72098SAndreas Gohr    // add some global variables
953df72098SAndreas Gohr    print "var DOKU_BASE   = '".DOKU_BASE."';";
965fc6f52eSAnika Henke    print "var DOKU_TPL    = '".tpl_basedir($tpl)."';";
97df5d307eSGerrit Uitslag    print "var DOKU_COOKIE_PARAM = " . $json->encode(
98df5d307eSGerrit Uitslag            array(
99df5d307eSGerrit Uitslag                 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'],
100df5d307eSGerrit Uitslag                 'secure' => $conf['securecookie'] && is_ssl()
101df5d307eSGerrit Uitslag            )).";";
1025e7a2926SAdrian Lang    // FIXME: Move those to JSINFO
103*64159a61SAndreas Gohr    print "Object.defineProperty(window, 'DOKU_UHN', { get: function() {".
104*64159a61SAndreas Gohr          "console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead');".
105*64159a61SAndreas Gohr          "return JSINFO.useHeadingNavigation; } });";
106*64159a61SAndreas Gohr    print "Object.defineProperty(window, 'DOKU_UHC', { get: function() {".
107*64159a61SAndreas Gohr          "console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead');".
108*64159a61SAndreas Gohr          "return JSINFO.useHeadingContent; } });";
1093df72098SAndreas Gohr
1103df72098SAndreas Gohr    // load JS specific translations
1116392c3b6SAndreas Gohr    $lang['js']['plugins'] = js_pluginstrings();
1125fc6f52eSAnika Henke    $templatestrings = js_templatestrings($tpl);
113acd3eb67SKlap-in    if(!empty($templatestrings)) {
114acd3eb67SKlap-in        $lang['js']['template'] = $templatestrings;
115acd3eb67SKlap-in    }
1163df72098SAndreas Gohr    echo 'LANG = '.$json->encode($lang['js']).";\n";
11778a6aeb1SAndreas Gohr
1186392c3b6SAndreas Gohr    // load toolbar
1196392c3b6SAndreas Gohr    toolbar_JSdefines('toolbar');
1206392c3b6SAndreas Gohr
12178a6aeb1SAndreas Gohr    // load files
12278a6aeb1SAndreas Gohr    foreach($files as $file){
123138bfd16SAndreas Gohr        if(!file_exists($file)) continue;
12480a47290SAndreas Gohr        $ismin = (substr($file,-7) == '.min.js');
1256b0ec830SMichael Hamann        $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0);
12680a47290SAndreas Gohr
12757d846dbSAndreas Gohr        echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n";
12880a47290SAndreas Gohr        if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n";
1296b0ec830SMichael Hamann        if ($debugjs) echo "\ntry {\n";
130176da19bSAndreas Gohr        js_load($file);
1316b0ec830SMichael Hamann        if ($debugjs) echo "\n} catch (e) {\n   logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n";
13280a47290SAndreas Gohr        if($ismin) echo "\n/* END NOCOMPRESS */\n";
13357d846dbSAndreas Gohr        echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n";
13478a6aeb1SAndreas Gohr    }
13578a6aeb1SAndreas Gohr
13678a6aeb1SAndreas Gohr    // init stuff
137544ed901SDaniel Calviño Sánchez    if($conf['locktime'] != 0){
13899e7bfd4SAndreas Gohr        js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")");
139544ed901SDaniel Calviño Sánchez    }
1404062d3d5SMarek Sacha    // init hotkeys - must have been done after init of toolbar
141de32b03eSMichael Hamann# disabled for FS#1958    js_runonstart('initializeHotkeys()');
14200540a38SAndreas Gohr
14378a6aeb1SAndreas Gohr    // end output buffering and get contents
14478a6aeb1SAndreas Gohr    $js = ob_get_contents();
14578a6aeb1SAndreas Gohr    ob_end_clean();
14678a6aeb1SAndreas Gohr
147f8fb2d18SAndreas Gohr    // strip any source maps
148f8fb2d18SAndreas Gohr    stripsourcemaps($js);
149f8fb2d18SAndreas Gohr
15078a6aeb1SAndreas Gohr    // compress whitespace and comments
15178a6aeb1SAndreas Gohr    if($conf['compress']){
15278a6aeb1SAndreas Gohr        $js = js_compress($js);
15378a6aeb1SAndreas Gohr    }
15478a6aeb1SAndreas Gohr
1554d2d451eSAndreas Gohr    $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033
1564d2d451eSAndreas Gohr
1576619f42eSAdrian Lang    http_cached_finish($cache->cache, $js);
158ca2b464bSChris Smith}
15978a6aeb1SAndreas Gohr
16078a6aeb1SAndreas Gohr/**
161176da19bSAndreas Gohr * Load the given file, handle include calls and print it
1623825ddd3SAndreas Gohr *
1633825ddd3SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
164253d4b48SGerrit Uitslag *
165253d4b48SGerrit Uitslag * @param string $file filename path to file
166176da19bSAndreas Gohr */
167176da19bSAndreas Gohrfunction js_load($file){
16879e79377SAndreas Gohr    if(!file_exists($file)) return;
1693825ddd3SAndreas Gohr    static $loaded = array();
170176da19bSAndreas Gohr
171176da19bSAndreas Gohr    $data = io_readFile($file);
17298dba5adSAdrian Lang    while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){
1733825ddd3SAndreas Gohr        $ifile = $match[2];
1743825ddd3SAndreas Gohr
1753825ddd3SAndreas Gohr        // is it a include_once?
1763825ddd3SAndreas Gohr        if($match[1]){
1773009a773SAndreas Gohr            $base = utf8_basename($ifile);
1785c97ad3aSMarius van Witzenburg            if(array_key_exists($base, $loaded) && $loaded[$base] === true){
179969df2f1SAndreas Gohr                $data  = str_replace($match[0], '' ,$data);
180969df2f1SAndreas Gohr                continue;
181969df2f1SAndreas Gohr            }
1823825ddd3SAndreas Gohr            $loaded[$base] = true;
1833825ddd3SAndreas Gohr        }
1843825ddd3SAndreas Gohr
185176da19bSAndreas Gohr        if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile;
186176da19bSAndreas Gohr
18779e79377SAndreas Gohr        if(file_exists($ifile)){
188176da19bSAndreas Gohr            $idata = io_readFile($ifile);
189176da19bSAndreas Gohr        }else{
190176da19bSAndreas Gohr            $idata = '';
191176da19bSAndreas Gohr        }
192176da19bSAndreas Gohr        $data  = str_replace($match[0],$idata,$data);
193176da19bSAndreas Gohr    }
19417582ec6SAndreas Gohr    echo "$data\n";
195176da19bSAndreas Gohr}
196176da19bSAndreas Gohr
197176da19bSAndreas Gohr/**
19878a6aeb1SAndreas Gohr * Returns a list of possible Plugin Scripts (no existance check here)
19978a6aeb1SAndreas Gohr *
20078a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
201253d4b48SGerrit Uitslag *
202253d4b48SGerrit Uitslag * @return array
20378a6aeb1SAndreas Gohr */
20478a6aeb1SAndreas Gohrfunction js_pluginscripts(){
20578a6aeb1SAndreas Gohr    $list = array();
20678a6aeb1SAndreas Gohr    $plugins = plugin_list();
20778a6aeb1SAndreas Gohr    foreach ($plugins as $p){
20878a6aeb1SAndreas Gohr        $list[] = DOKU_PLUGIN."$p/script.js";
20978a6aeb1SAndreas Gohr    }
21078a6aeb1SAndreas Gohr    return $list;
21178a6aeb1SAndreas Gohr}
21278a6aeb1SAndreas Gohr
21378a6aeb1SAndreas Gohr/**
2149f01cf6aSGabriel Birke * Return an two-dimensional array with strings from the language file of each plugin.
2159f01cf6aSGabriel Birke *
2169f01cf6aSGabriel Birke * - $lang['js'] must be an array.
2179f01cf6aSGabriel Birke * - Nothing is returned for plugins without an entry for $lang['js']
2189f01cf6aSGabriel Birke *
2199f01cf6aSGabriel Birke * @author Gabriel Birke <birke@d-scribe.de>
220253d4b48SGerrit Uitslag *
221253d4b48SGerrit Uitslag * @return array
2229f01cf6aSGabriel Birke */
223d91ab76fSMatt Perryfunction js_pluginstrings() {
22419e06537SGerrit Uitslag    global $conf, $config_cascade;
2259f01cf6aSGabriel Birke    $pluginstrings = array();
2269f01cf6aSGabriel Birke    $plugins = plugin_list();
2279f01cf6aSGabriel Birke    foreach($plugins as $p) {
22819e06537SGerrit Uitslag        $path = DOKU_PLUGIN . $p . '/lang/';
22919e06537SGerrit Uitslag
2309f01cf6aSGabriel Birke        if(isset($lang)) unset($lang);
23119e06537SGerrit Uitslag        if(file_exists($path . "en/lang.php")) {
23219e06537SGerrit Uitslag            include $path . "en/lang.php";
2339f01cf6aSGabriel Birke        }
23419e06537SGerrit Uitslag        foreach($config_cascade['lang']['plugin'] as $config_file) {
23519e06537SGerrit Uitslag            if(file_exists($config_file . $p . '/en/lang.php')) {
23619e06537SGerrit Uitslag                include($config_file . $p . '/en/lang.php');
2379f01cf6aSGabriel Birke            }
23819e06537SGerrit Uitslag        }
23919e06537SGerrit Uitslag        if(isset($conf['lang']) && $conf['lang'] != 'en') {
24019e06537SGerrit Uitslag            if(file_exists($path . $conf['lang'] . "/lang.php")) {
24119e06537SGerrit Uitslag                include($path . $conf['lang'] . '/lang.php');
24219e06537SGerrit Uitslag            }
24319e06537SGerrit Uitslag            foreach($config_cascade['lang']['plugin'] as $config_file) {
24419e06537SGerrit Uitslag                if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) {
24519e06537SGerrit Uitslag                    include($config_file . $p . '/' . $conf['lang'] . '/lang.php');
24619e06537SGerrit Uitslag                }
24719e06537SGerrit Uitslag            }
24819e06537SGerrit Uitslag        }
24919e06537SGerrit Uitslag
2509f01cf6aSGabriel Birke        if(isset($lang['js'])) {
2519f01cf6aSGabriel Birke            $pluginstrings[$p] = $lang['js'];
2529f01cf6aSGabriel Birke        }
2539f01cf6aSGabriel Birke    }
2549f01cf6aSGabriel Birke    return $pluginstrings;
2559f01cf6aSGabriel Birke}
2569f01cf6aSGabriel Birke
25756b0b744SGerrit Uitslag/**
25856b0b744SGerrit Uitslag * Return an two-dimensional array with strings from the language file of current active template.
25956b0b744SGerrit Uitslag *
26056b0b744SGerrit Uitslag * - $lang['js'] must be an array.
26156b0b744SGerrit Uitslag * - Nothing is returned for template without an entry for $lang['js']
262253d4b48SGerrit Uitslag *
2635fc6f52eSAnika Henke * @param string $tpl
264253d4b48SGerrit Uitslag * @return array
26556b0b744SGerrit Uitslag */
2665fc6f52eSAnika Henkefunction js_templatestrings($tpl) {
26719e06537SGerrit Uitslag    global $conf, $config_cascade;
26819e06537SGerrit Uitslag
26919e06537SGerrit Uitslag    $path = tpl_incdir() . 'lang/';
27019e06537SGerrit Uitslag
271acd3eb67SKlap-in    $templatestrings = array();
27219e06537SGerrit Uitslag    if(file_exists($path . "en/lang.php")) {
27319e06537SGerrit Uitslag        include $path . "en/lang.php";
274acd3eb67SKlap-in    }
27519e06537SGerrit Uitslag    foreach($config_cascade['lang']['template'] as $config_file) {
27619e06537SGerrit Uitslag        if(file_exists($config_file . $conf['template'] . '/en/lang.php')) {
27719e06537SGerrit Uitslag            include($config_file . $conf['template'] . '/en/lang.php');
278acd3eb67SKlap-in        }
27919e06537SGerrit Uitslag    }
28019e06537SGerrit Uitslag    if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) {
28119e06537SGerrit Uitslag        include $path . $conf['lang'] . "/lang.php";
28219e06537SGerrit Uitslag    }
28319e06537SGerrit Uitslag    if(isset($conf['lang']) && $conf['lang'] != 'en') {
28419e06537SGerrit Uitslag        if(file_exists($path . $conf['lang'] . "/lang.php")) {
28519e06537SGerrit Uitslag            include $path . $conf['lang'] . "/lang.php";
28619e06537SGerrit Uitslag        }
28719e06537SGerrit Uitslag        foreach($config_cascade['lang']['template'] as $config_file) {
28819e06537SGerrit Uitslag            if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) {
28919e06537SGerrit Uitslag                include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php');
29019e06537SGerrit Uitslag            }
29119e06537SGerrit Uitslag        }
29219e06537SGerrit Uitslag    }
29319e06537SGerrit Uitslag
294acd3eb67SKlap-in    if(isset($lang['js'])) {
2955fc6f52eSAnika Henke        $templatestrings[$tpl] = $lang['js'];
296acd3eb67SKlap-in    }
297acd3eb67SKlap-in    return $templatestrings;
298acd3eb67SKlap-in}
299acd3eb67SKlap-in
3009f01cf6aSGabriel Birke/**
30178a6aeb1SAndreas Gohr * Escapes a String to be embedded in a JavaScript call, keeps \n
30278a6aeb1SAndreas Gohr * as newline
30378a6aeb1SAndreas Gohr *
30478a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
305253d4b48SGerrit Uitslag *
306253d4b48SGerrit Uitslag * @param string $string
307253d4b48SGerrit Uitslag * @return string
30878a6aeb1SAndreas Gohr */
30978a6aeb1SAndreas Gohrfunction js_escape($string){
31078a6aeb1SAndreas Gohr    return str_replace('\\\\n','\\n',addslashes($string));
31178a6aeb1SAndreas Gohr}
31278a6aeb1SAndreas Gohr
31378a6aeb1SAndreas Gohr/**
31478a6aeb1SAndreas Gohr * Adds the given JavaScript code to the window.onload() event
31578a6aeb1SAndreas Gohr *
31678a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
317253d4b48SGerrit Uitslag *
318253d4b48SGerrit Uitslag * @param string $func
31978a6aeb1SAndreas Gohr */
32078a6aeb1SAndreas Gohrfunction js_runonstart($func){
3215e7a2926SAdrian Lang    echo "jQuery(function(){ $func; });".NL;
32278a6aeb1SAndreas Gohr}
32378a6aeb1SAndreas Gohr
32478a6aeb1SAndreas Gohr/**
32578a6aeb1SAndreas Gohr * Strip comments and whitespaces from given JavaScript Code
32678a6aeb1SAndreas Gohr *
32773bea65dSAndreas Gohr * This is a port of Nick Galbreath's python tool jsstrip.py which is
32878a6aeb1SAndreas Gohr * released under BSD license. See link for original code.
32978a6aeb1SAndreas Gohr *
33078a6aeb1SAndreas Gohr * @author Nick Galbreath <nickg@modp.com>
33178a6aeb1SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
33273bea65dSAndreas Gohr * @link   http://code.google.com/p/jsstrip/
333253d4b48SGerrit Uitslag *
334253d4b48SGerrit Uitslag * @param string $s
335253d4b48SGerrit Uitslag * @return string
33678a6aeb1SAndreas Gohr */
33778a6aeb1SAndreas Gohrfunction js_compress($s){
33873bea65dSAndreas Gohr    $s = ltrim($s);     // strip all initial whitespace
33978a6aeb1SAndreas Gohr    $s .= "\n";
34073bea65dSAndreas Gohr    $i = 0;             // char index for input string
34173bea65dSAndreas Gohr    $j = 0;             // char forward index for input string
34273bea65dSAndreas Gohr    $line = 0;          // line number of file (close to it anyways)
34373bea65dSAndreas Gohr    $slen = strlen($s); // size of input string
34473bea65dSAndreas Gohr    $lch  = '';         // last char added
34573bea65dSAndreas Gohr    $result = '';       // we store the final result here
34678a6aeb1SAndreas Gohr
34778a6aeb1SAndreas Gohr    // items that don't need spaces next to them
34873bea65dSAndreas Gohr    $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]";
34978a6aeb1SAndreas Gohr
35070daee86SLarsDW223    // items which need a space if the sign before and after whitespace is equal.
35170daee86SLarsDW223    // E.g. '+ ++' may not be compressed to '+++' --> syntax error.
35270daee86SLarsDW223    $ops = "+-";
35370daee86SLarsDW223
3545c5b52fdSLarsDW223    $regex_starters = array("(", "=", "[", "," , ":", "!", "&", "|");
355ef457c67SPierre Paysant-Le Roux
356ef457c67SPierre Paysant-Le Roux    $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B");
357ef457c67SPierre Paysant-Le Roux
35873bea65dSAndreas Gohr    while($i < $slen){
35973bea65dSAndreas Gohr        // skip all "boring" characters.  This is either
36073bea65dSAndreas Gohr        // reserved word (e.g. "for", "else", "if") or a
36173bea65dSAndreas Gohr        // variable/object/method (e.g. "foo.color")
36273bea65dSAndreas Gohr        while ($i < $slen && (strpos($chars,$s[$i]) === false) ){
36373bea65dSAndreas Gohr            $result .= $s{$i};
36473bea65dSAndreas Gohr            $i = $i + 1;
36573bea65dSAndreas Gohr        }
36673bea65dSAndreas Gohr
36778a6aeb1SAndreas Gohr        $ch = $s{$i};
3685cafff96SAndreas Gohr        // multiline comments (keeping IE conditionals)
3695cafff96SAndreas Gohr        if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){
37078a6aeb1SAndreas Gohr            $endC = strpos($s,'*/',$i+2);
37178a6aeb1SAndreas Gohr            if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR);
37280a47290SAndreas Gohr
37380a47290SAndreas Gohr            // check if this is a NOCOMPRESS comment
37480a47290SAndreas Gohr            if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){
37580a47290SAndreas Gohr                $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2);
37680a47290SAndreas Gohr                if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR);
37780a47290SAndreas Gohr
37880a47290SAndreas Gohr                // verbatim copy contents, trimming but putting it on its own line
37980a47290SAndreas Gohr                $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars
38080a47290SAndreas Gohr                $i = $endNC + 20; // END comment = 20 chars
38180a47290SAndreas Gohr            }else{
38278a6aeb1SAndreas Gohr                $i = $endC + 2;
38380a47290SAndreas Gohr            }
38478a6aeb1SAndreas Gohr            continue;
38578a6aeb1SAndreas Gohr        }
38678a6aeb1SAndreas Gohr
38778a6aeb1SAndreas Gohr        // singleline
38878a6aeb1SAndreas Gohr        if($ch == '/' && $s{$i+1} == '/'){
38978a6aeb1SAndreas Gohr            $endC = strpos($s,"\n",$i+2);
39078a6aeb1SAndreas Gohr            if($endC === false) trigger_error('Invalid comment', E_USER_ERROR);
39178a6aeb1SAndreas Gohr            $i = $endC;
39278a6aeb1SAndreas Gohr            continue;
39378a6aeb1SAndreas Gohr        }
39478a6aeb1SAndreas Gohr
39578a6aeb1SAndreas Gohr        // tricky.  might be an RE
39678a6aeb1SAndreas Gohr        if($ch == '/'){
39778a6aeb1SAndreas Gohr            // rewind, skip white space
39878a6aeb1SAndreas Gohr            $j = 1;
399ef457c67SPierre Paysant-Le Roux            while(in_array($s{$i-$j}, $whitespaces_chars)){
40078a6aeb1SAndreas Gohr                $j = $j + 1;
40178a6aeb1SAndreas Gohr            }
402ef457c67SPierre Paysant-Le Roux            if( in_array($s{$i-$j}, $regex_starters) ){
40378a6aeb1SAndreas Gohr                // yes, this is an re
40478a6aeb1SAndreas Gohr                // now move forward and find the end of it
40578a6aeb1SAndreas Gohr                $j = 1;
40678a6aeb1SAndreas Gohr                while($s{$i+$j} != '/'){
40778a6aeb1SAndreas Gohr                    if($s{$i+$j} == '\\') $j = $j + 2;
408e71b260aSMichael Hamann                    else $j++;
40978a6aeb1SAndreas Gohr                }
41073bea65dSAndreas Gohr                $result .= substr($s,$i,$j+1);
41178a6aeb1SAndreas Gohr                $i = $i + $j + 1;
41278a6aeb1SAndreas Gohr                continue;
41378a6aeb1SAndreas Gohr            }
41478a6aeb1SAndreas Gohr        }
41578a6aeb1SAndreas Gohr
41678a6aeb1SAndreas Gohr        // double quote strings
41778a6aeb1SAndreas Gohr        if($ch == '"'){
41878a6aeb1SAndreas Gohr            $j = 1;
41973bea65dSAndreas Gohr            while( $s{$i+$j} != '"' && ($i+$j < $slen)){
420e5cafda0SAndreas Gohr                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){
42145be45c5SAndreas Gohr                    $j += 2;
42245be45c5SAndreas Gohr                }else{
42345be45c5SAndreas Gohr                    $j += 1;
42478a6aeb1SAndreas Gohr                }
42578a6aeb1SAndreas Gohr            }
426ca53ac98SAndreas Gohr            $string  = substr($s,$i,$j+1);
427ca53ac98SAndreas Gohr            // remove multiline markers:
428ca53ac98SAndreas Gohr            $string  = str_replace("\\\n",'',$string);
429ca53ac98SAndreas Gohr            $result .= $string;
43078a6aeb1SAndreas Gohr            $i = $i + $j + 1;
43178a6aeb1SAndreas Gohr            continue;
43278a6aeb1SAndreas Gohr        }
43378a6aeb1SAndreas Gohr
43478a6aeb1SAndreas Gohr        // single quote strings
43578a6aeb1SAndreas Gohr        if($ch == "'"){
43678a6aeb1SAndreas Gohr            $j = 1;
43773bea65dSAndreas Gohr            while( $s{$i+$j} != "'" && ($i+$j < $slen)){
438e5cafda0SAndreas Gohr                if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){
43945be45c5SAndreas Gohr                    $j += 2;
44045be45c5SAndreas Gohr                }else{
44145be45c5SAndreas Gohr                    $j += 1;
44278a6aeb1SAndreas Gohr                }
44378a6aeb1SAndreas Gohr            }
444ca53ac98SAndreas Gohr            $string = substr($s,$i,$j+1);
445ca53ac98SAndreas Gohr            // remove multiline markers:
446ca53ac98SAndreas Gohr            $string  = str_replace("\\\n",'',$string);
447ca53ac98SAndreas Gohr            $result .= $string;
44878a6aeb1SAndreas Gohr            $i = $i + $j + 1;
44978a6aeb1SAndreas Gohr            continue;
45078a6aeb1SAndreas Gohr        }
45178a6aeb1SAndreas Gohr
45273bea65dSAndreas Gohr        // whitespaces
45373bea65dSAndreas Gohr        if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){
45470daee86SLarsDW223            $lch = substr($result,-1);
45570daee86SLarsDW223
45670daee86SLarsDW223            // Only consider deleting whitespace if the signs before and after
45770daee86SLarsDW223            // are not equal and are not an operator which may not follow itself.
458a8cf30efSMarius van Witzenburg            if ($i+1 < $slen && ((!$lch || $s[$i+1] == ' ')
45970daee86SLarsDW223                || $lch != $s[$i+1]
4605c97ad3aSMarius van Witzenburg                || strpos($ops,$s[$i+1]) === false)) {
46178a6aeb1SAndreas Gohr                // leading spaces
46273bea65dSAndreas Gohr                if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){
46378a6aeb1SAndreas Gohr                    $i = $i + 1;
46478a6aeb1SAndreas Gohr                    continue;
46578a6aeb1SAndreas Gohr                }
46678a6aeb1SAndreas Gohr                // trailing spaces
46773bea65dSAndreas Gohr                //  if this ch is space AND the last char processed
46873bea65dSAndreas Gohr                //  is special, then skip the space
46973bea65dSAndreas Gohr                if($lch && (strpos($chars,$lch) !== false)){
47078a6aeb1SAndreas Gohr                    $i = $i + 1;
47178a6aeb1SAndreas Gohr                    continue;
47278a6aeb1SAndreas Gohr                }
47370daee86SLarsDW223            }
47470daee86SLarsDW223
47573bea65dSAndreas Gohr            // else after all of this convert the "whitespace" to
47673bea65dSAndreas Gohr            // a single space.  It will get appended below
47773bea65dSAndreas Gohr            $ch = ' ';
47873bea65dSAndreas Gohr        }
47978a6aeb1SAndreas Gohr
48078a6aeb1SAndreas Gohr        // other chars
48173bea65dSAndreas Gohr        $result .= $ch;
48278a6aeb1SAndreas Gohr        $i = $i + 1;
48378a6aeb1SAndreas Gohr    }
48478a6aeb1SAndreas Gohr
48573bea65dSAndreas Gohr    return trim($result);
48678a6aeb1SAndreas Gohr}
48778a6aeb1SAndreas Gohr
488e3776c06SMichael Hamann//Setup VIM: ex: et ts=4 :
489