diff options
Diffstat (limited to 'wiki/lib/exe')
-rw-r--r-- | wiki/lib/exe/ajax.php | 25 | ||||
-rw-r--r-- | wiki/lib/exe/css.php | 635 | ||||
-rw-r--r-- | wiki/lib/exe/detail.php | 53 | ||||
-rw-r--r-- | wiki/lib/exe/fetch.php | 99 | ||||
-rw-r--r-- | wiki/lib/exe/index.html | 11 | ||||
-rw-r--r-- | wiki/lib/exe/indexer.php | 209 | ||||
-rw-r--r-- | wiki/lib/exe/jquery.php | 43 | ||||
-rw-r--r-- | wiki/lib/exe/js.php | 484 | ||||
-rw-r--r-- | wiki/lib/exe/manifest.php | 14 | ||||
-rw-r--r-- | wiki/lib/exe/mediamanager.php | 126 | ||||
-rw-r--r-- | wiki/lib/exe/opensearch.php | 38 | ||||
-rw-r--r-- | wiki/lib/exe/xmlrpc.php | 67 |
12 files changed, 1804 insertions, 0 deletions
diff --git a/wiki/lib/exe/ajax.php b/wiki/lib/exe/ajax.php new file mode 100644 index 0000000..55f1c87 --- /dev/null +++ b/wiki/lib/exe/ajax.php @@ -0,0 +1,25 @@ +<?php +/** + * DokuWiki AJAX call handler + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + */ + +if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../'); +require_once(DOKU_INC . 'inc/init.php'); + +//close session +session_write_close(); + +// default header, ajax call may overwrite it later +header('Content-Type: text/html; charset=utf-8'); + +//call the requested function +global $INPUT; +if($INPUT->has('call')) { + $call = $INPUT->filter('utf8_stripspecials')->str('call'); + new \dokuwiki\Ajax($call); +} else { + http_status(404); +} diff --git a/wiki/lib/exe/css.php b/wiki/lib/exe/css.php new file mode 100644 index 0000000..40eaf99 --- /dev/null +++ b/wiki/lib/exe/css.php @@ -0,0 +1,635 @@ +<?php +/** + * DokuWiki StyleSheet creator + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + */ + +if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); +if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) +if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here +if(!defined('NL')) define('NL',"\n"); +require_once(DOKU_INC.'inc/init.php'); + +// Main (don't run when UNIT test) +if(!defined('SIMPLE_TEST')){ + header('Content-Type: text/css; charset=utf-8'); + css_out(); +} + + +// ---------------------- functions ------------------------------ + +/** + * Output all needed Styles + * + * @author Andreas Gohr <andi@splitbrain.org> + */ +function css_out(){ + global $conf; + global $lang; + global $config_cascade; + global $INPUT; + + if ($INPUT->str('s') == 'feed') { + $mediatypes = array('feed'); + $type = 'feed'; + } else { + $mediatypes = array('screen', 'all', 'print', 'speech'); + $type = ''; + } + + // decide from where to get the template + $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); + if(!$tpl) $tpl = $conf['template']; + + // load style.ini + $styleUtil = new \dokuwiki\StyleUtils(); + $styleini = $styleUtil->cssStyleini($tpl, $INPUT->bool('preview')); + + // cache influencers + $tplinc = tpl_incdir($tpl); + $cache_files = getConfigFiles('main'); + $cache_files[] = $tplinc.'style.ini'; + $cache_files[] = DOKU_CONF."tpl/$tpl/style.ini"; + $cache_files[] = __FILE__; + if($INPUT->bool('preview')) $cache_files[] = $conf['cachedir'].'/preview.ini'; + + // Array of needed files and their web locations, the latter ones + // are needed to fix relative paths in the stylesheets + $media_files = array(); + foreach($mediatypes as $mediatype) { + $files = array(); + + // load core styles + $files[DOKU_INC.'lib/styles/'.$mediatype.'.css'] = DOKU_BASE.'lib/styles/'; + + // load jQuery-UI theme + if ($mediatype == 'screen') { + $files[DOKU_INC.'lib/scripts/jquery/jquery-ui-theme/smoothness.css'] = DOKU_BASE.'lib/scripts/jquery/jquery-ui-theme/'; + } + // load plugin styles + $files = array_merge($files, css_pluginstyles($mediatype)); + // load template styles + if (isset($styleini['stylesheets'][$mediatype])) { + $files = array_merge($files, $styleini['stylesheets'][$mediatype]); + } + // load user styles + if(!empty($config_cascade['userstyle'][$mediatype])) { + foreach($config_cascade['userstyle'][$mediatype] as $userstyle) { + $files[$userstyle] = DOKU_BASE; + } + } + + // Let plugins decide to either put more styles here or to remove some + $media_files[$mediatype] = css_filewrapper($mediatype, $files); + $CSSEvt = new Doku_Event('CSS_STYLES_INCLUDED', $media_files[$mediatype]); + + // Make it preventable. + if ( $CSSEvt->advise_before() ) { + $cache_files = array_merge($cache_files, array_keys($media_files[$mediatype]['files'])); + } else { + // unset if prevented. Nothing will be printed for this mediatype. + unset($media_files[$mediatype]); + } + + // finish event. + $CSSEvt->advise_after(); + } + + // The generated script depends on some dynamic options + $cache = new cache('styles'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].$INPUT->bool('preview').DOKU_BASE.$tpl.$type,'.css'); + $cache->_event = 'CSS_CACHE_USE'; + + // check cache age & handle conditional request + // This may exit if a cache can be used + $cache_ok = $cache->useCache(array('files' => $cache_files)); + http_cached($cache->cache, $cache_ok); + + // start output buffering + ob_start(); + + // Fire CSS_STYLES_INCLUDED for one last time to let the + // plugins decide whether to include the DW default styles. + // This can be done by preventing the Default. + $media_files['DW_DEFAULT'] = css_filewrapper('DW_DEFAULT'); + trigger_event('CSS_STYLES_INCLUDED', $media_files['DW_DEFAULT'], 'css_defaultstyles'); + + // build the stylesheet + foreach ($mediatypes as $mediatype) { + + // Check if there is a wrapper set for this type. + if ( !isset($media_files[$mediatype]) ) { + continue; + } + + $cssData = $media_files[$mediatype]; + + // Print the styles. + print NL; + if ( $cssData['encapsulate'] === true ) print $cssData['encapsulationPrefix'] . ' {'; + print '/* START '.$cssData['mediatype'].' styles */'.NL; + + // load files + foreach($cssData['files'] as $file => $location){ + $display = str_replace(fullpath(DOKU_INC), '', fullpath($file)); + print "\n/* XXXXXXXXX $display XXXXXXXXX */\n"; + print css_loadfile($file, $location); + } + + print NL; + if ( $cssData['encapsulate'] === true ) print '} /* /@media '; + else print '/*'; + print ' END '.$cssData['mediatype'].' styles */'.NL; + } + + // end output buffering and get contents + $css = ob_get_contents(); + ob_end_clean(); + + // strip any source maps + stripsourcemaps($css); + + // apply style replacements + $css = css_applystyle($css, $styleini['replacements']); + + // parse less + $css = css_parseless($css); + + // compress whitespace and comments + if($conf['compress']){ + $css = css_compress($css); + } + + // embed small images right into the stylesheet + if($conf['cssdatauri']){ + $base = preg_quote(DOKU_BASE,'#'); + $css = preg_replace_callback('#(url\([ \'"]*)('.$base.')(.*?(?:\.(png|gif)))#i','css_datauri',$css); + } + + http_cached_finish($cache->cache, $css); +} + +/** + * Uses phpless to parse LESS in our CSS + * + * most of this function is error handling to show a nice useful error when + * LESS compilation fails + * + * @param string $css + * @return string + */ +function css_parseless($css) { + global $conf; + + $less = new lessc(); + $less->importDir = array(DOKU_INC); + $less->setPreserveComments(!$conf['compress']); + + if (defined('DOKU_UNITTEST')){ + $less->importDir[] = TMP_DIR; + } + + try { + return $less->compile($css); + } catch(Exception $e) { + // get exception message + $msg = str_replace(array("\n", "\r", "'"), array(), $e->getMessage()); + + // try to use line number to find affected file + if(preg_match('/line: (\d+)$/', $msg, $m)){ + $msg = substr($msg, 0, -1* strlen($m[0])); //remove useless linenumber + $lno = $m[1]; + + // walk upwards to last include + $lines = explode("\n", $css); + for($i=$lno-1; $i>=0; $i--){ + if(preg_match('/\/(\* XXXXXXXXX )(.*?)( XXXXXXXXX \*)\//', $lines[$i], $m)){ + // we found it, add info to message + $msg .= ' in '.$m[2].' at line '.($lno-$i); + break; + } + } + } + + // something went wrong + $error = 'A fatal error occured during compilation of the CSS files. '. + 'If you recently installed a new plugin or template it '. + 'might be broken and you should try disabling it again. ['.$msg.']'; + + echo ".dokuwiki:before { + content: '$error'; + background-color: red; + display: block; + background-color: #fcc; + border-color: #ebb; + color: #000; + padding: 0.5em; + }"; + + exit; + } +} + +/** + * Does placeholder replacements in the style according to + * the ones defined in a templates style.ini file + * + * This also adds the ini defined placeholders as less variables + * (sans the surrounding __ and with a ini_ prefix) + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $css + * @param array $replacements array(placeholder => value) + * @return string + */ +function css_applystyle($css, $replacements) { + // we convert ini replacements to LESS variable names + // and build a list of variable: value; pairs + $less = ''; + foreach((array) $replacements as $key => $value) { + $lkey = trim($key, '_'); + $lkey = '@ini_'.$lkey; + $less .= "$lkey: $value;\n"; + + $replacements[$key] = $lkey; + } + + // we now replace all old ini replacements with LESS variables + $css = strtr($css, $replacements); + + // now prepend the list of LESS variables as the very first thing + $css = $less.$css; + return $css; +} + +/** + * Wrapper for the files, content and mediatype for the event CSS_STYLES_INCLUDED + * + * @author Gerry Weißbach <gerry.w@gammaproduction.de> + * + * @param string $mediatype type ofthe current media files/content set + * @param array $files set of files that define the current mediatype + * @return array + */ +function css_filewrapper($mediatype, $files=array()){ + return array( + 'files' => $files, + 'mediatype' => $mediatype, + 'encapsulate' => $mediatype != 'all', + 'encapsulationPrefix' => '@media '.$mediatype + ); +} + +/** + * Prints the @media encapsulated default styles of DokuWiki + * + * @author Gerry Weißbach <gerry.w@gammaproduction.de> + * + * This function is being called by a CSS_STYLES_INCLUDED event + * The event can be distinguished by the mediatype which is: + * DW_DEFAULT + */ +function css_defaultstyles(){ + // print the default classes for interwiki links and file downloads + print '@media screen {'; + css_interwiki(); + css_filetypes(); + print '}'; +} + +/** + * Prints classes for interwikilinks + * + * Interwiki links have two classes: 'interwiki' and 'iw_$name>' where + * $name is the identifier given in the config. All Interwiki links get + * an default style with a default icon. If a special icon is available + * for an interwiki URL it is set in it's own class. Both classes can be + * overwritten in the template or userstyles. + * + * @author Andreas Gohr <andi@splitbrain.org> + */ +function css_interwiki(){ + + // default style + echo 'a.interwiki {'; + echo ' background: transparent url('.DOKU_BASE.'lib/images/interwiki.png) 0px 1px no-repeat;'; + echo ' padding: 1px 0px 1px 16px;'; + echo '}'; + + // additional styles when icon available + $iwlinks = getInterwiki(); + foreach(array_keys($iwlinks) as $iw){ + $class = preg_replace('/[^_\-a-z0-9]+/i','_',$iw); + if(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.png')){ + echo "a.iw_$class {"; + echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.png)'; + echo '}'; + }elseif(file_exists(DOKU_INC.'lib/images/interwiki/'.$iw.'.gif')){ + echo "a.iw_$class {"; + echo ' background-image: url('.DOKU_BASE.'lib/images/interwiki/'.$iw.'.gif)'; + echo '}'; + } + } +} + +/** + * Prints classes for file download links + * + * @author Andreas Gohr <andi@splitbrain.org> + */ +function css_filetypes(){ + + // default style + echo '.mediafile {'; + echo ' background: transparent url('.DOKU_BASE.'lib/images/fileicons/file.png) 0px 1px no-repeat;'; + echo ' padding-left: 18px;'; + echo ' padding-bottom: 1px;'; + echo '}'; + + // additional styles when icon available + // scan directory for all icons + $exts = array(); + if($dh = opendir(DOKU_INC.'lib/images/fileicons')){ + while(false !== ($file = readdir($dh))){ + if(preg_match('/([_\-a-z0-9]+(?:\.[_\-a-z0-9]+)*?)\.(png|gif)/i',$file,$match)){ + $ext = strtolower($match[1]); + $type = '.'.strtolower($match[2]); + if($ext!='file' && (!isset($exts[$ext]) || $type=='.png')){ + $exts[$ext] = $type; + } + } + } + closedir($dh); + } + foreach($exts as $ext=>$type){ + $class = preg_replace('/[^_\-a-z0-9]+/','_',$ext); + echo ".mf_$class {"; + echo ' background-image: url('.DOKU_BASE.'lib/images/fileicons/'.$ext.$type.')'; + echo '}'; + } +} + +/** + * Loads a given file and fixes relative URLs with the + * given location prefix + * + * @param string $file file system path + * @param string $location + * @return string + */ +function css_loadfile($file,$location=''){ + $css_file = new DokuCssFile($file); + return $css_file->load($location); +} + +/** + * Helper class to abstract loading of css/less files + * + * @author Chris Smith <chris@jalakai.co.uk> + */ +class DokuCssFile { + + protected $filepath; // file system path to the CSS/Less file + protected $location; // base url location of the CSS/Less file + protected $relative_path = null; + + public function __construct($file) { + $this->filepath = $file; + } + + /** + * Load the contents of the css/less file and adjust any relative paths/urls (relative to this file) to be + * relative to the dokuwiki root: the web root (DOKU_BASE) for most files; the file system root (DOKU_INC) + * for less files. + * + * @param string $location base url for this file + * @return string the CSS/Less contents of the file + */ + public function load($location='') { + if (!file_exists($this->filepath)) return ''; + + $css = io_readFile($this->filepath); + if (!$location) return $css; + + $this->location = $location; + + $css = preg_replace_callback('#(url\( *)([\'"]?)(.*?)(\2)( *\))#',array($this,'replacements'),$css); + $css = preg_replace_callback('#(@import\s+)([\'"])(.*?)(\2)#',array($this,'replacements'),$css); + + return $css; + } + + /** + * Get the relative file system path of this file, relative to dokuwiki's root folder, DOKU_INC + * + * @return string relative file system path + */ + protected function getRelativePath(){ + + if (is_null($this->relative_path)) { + $basedir = array(DOKU_INC); + + // during testing, files may be found relative to a second base dir, TMP_DIR + if (defined('DOKU_UNITTEST')) { + $basedir[] = realpath(TMP_DIR); + } + + $basedir = array_map('preg_quote_cb', $basedir); + $regex = '/^('.join('|',$basedir).')/'; + $this->relative_path = preg_replace($regex, '', dirname($this->filepath)); + } + + return $this->relative_path; + } + + /** + * preg_replace callback to adjust relative urls from relative to this file to relative + * to the appropriate dokuwiki root location as described in the code + * + * @param array see http://php.net/preg_replace_callback + * @return string see http://php.net/preg_replace_callback + */ + public function replacements($match) { + + // not a relative url? - no adjustment required + if (preg_match('#^(/|data:|https?://)#',$match[3])) { + return $match[0]; + } + // a less file import? - requires a file system location + else if (substr($match[3],-5) == '.less') { + if ($match[3]{0} != '/') { + $match[3] = $this->getRelativePath() . '/' . $match[3]; + } + } + // everything else requires a url adjustment + else { + $match[3] = $this->location . $match[3]; + } + + return join('',array_slice($match,1)); + } +} + +/** + * Convert local image URLs to data URLs if the filesize is small + * + * Callback for preg_replace_callback + * + * @param array $match + * @return string + */ +function css_datauri($match){ + global $conf; + + $pre = unslash($match[1]); + $base = unslash($match[2]); + $url = unslash($match[3]); + $ext = unslash($match[4]); + + $local = DOKU_INC.$url; + $size = @filesize($local); + if($size && $size < $conf['cssdatauri']){ + $data = base64_encode(file_get_contents($local)); + } + if (!empty($data)){ + $url = 'data:image/'.$ext.';base64,'.$data; + }else{ + $url = $base.$url; + } + return $pre.$url; +} + + +/** + * Returns a list of possible Plugin Styles (no existance check here) + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $mediatype + * @return array + */ +function css_pluginstyles($mediatype='screen'){ + $list = array(); + $plugins = plugin_list(); + foreach ($plugins as $p){ + $list[DOKU_PLUGIN."$p/$mediatype.css"] = DOKU_BASE."lib/plugins/$p/"; + $list[DOKU_PLUGIN."$p/$mediatype.less"] = DOKU_BASE."lib/plugins/$p/"; + // alternative for screen.css + if ($mediatype=='screen') { + $list[DOKU_PLUGIN."$p/style.css"] = DOKU_BASE."lib/plugins/$p/"; + $list[DOKU_PLUGIN."$p/style.less"] = DOKU_BASE."lib/plugins/$p/"; + } + } + return $list; +} + +/** + * Very simple CSS optimizer + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $css + * @return string + */ +function css_compress($css){ + //strip comments through a callback + $css = preg_replace_callback('#(/\*)(.*?)(\*/)#s','css_comment_cb',$css); + + //strip (incorrect but common) one line comments + $css = preg_replace_callback('/^.*\/\/.*$/m','css_onelinecomment_cb',$css); + + // strip whitespaces + $css = preg_replace('![\r\n\t ]+!',' ',$css); + $css = preg_replace('/ ?([;,{}\/]) ?/','\\1',$css); + $css = preg_replace('/ ?: /',':',$css); + + // number compression + $css = preg_replace('/([: ])0+(\.\d+?)0*((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2$3', $css); // "0.1em" to ".1em", "1.10em" to "1.1em" + $css = preg_replace('/([: ])\.(0)+((?:pt|pc|in|mm|cm|em|ex|px)\b|%)(?=[^\{]*[;\}])/', '$1$2', $css); // ".0em" to "0" + $css = preg_replace('/([: ]0)0*(\.0*)?((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1', $css); // "0.0em" to "0" + $css = preg_replace('/([: ]\d+)(\.0*)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$3', $css); // "1.0em" to "1em" + $css = preg_replace('/([: ])0+(\d+|\d*\.\d+)((?:pt|pc|in|mm|cm|em|ex|px)(?=[^\{]*[;\}])\b|%)/', '$1$2$3', $css); // "001em" to "1em" + + // shorten attributes (1em 1em 1em 1em -> 1em) + $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width|radius)):)([\w\.]+)( \2)+(?=[;\}]| !)/', '$1$2', $css); // "1em 1em 1em 1em" to "1em" + $css = preg_replace('/(?<![\w\-])((?:margin|padding|border|border-(?:width)):)([\w\.]+) ([\w\.]+) \2 \3(?=[;\}]| !)/', '$1$2 $3', $css); // "1em 2em 1em 2em" to "1em 2em" + + // shorten colors + $css = preg_replace("/#([0-9a-fA-F]{1})\\1([0-9a-fA-F]{1})\\2([0-9a-fA-F]{1})\\3(?=[^\{]*[;\}])/", "#\\1\\2\\3", $css); + + return $css; +} + +/** + * Callback for css_compress() + * + * Keeps short comments (< 5 chars) to maintain typical browser hacks + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param array $matches + * @return string + */ +function css_comment_cb($matches){ + if(strlen($matches[2]) > 4) return ''; + return $matches[0]; +} + +/** + * Callback for css_compress() + * + * Strips one line comments but makes sure it will not destroy url() constructs with slashes + * + * @param array $matches + * @return string + */ +function css_onelinecomment_cb($matches) { + $line = $matches[0]; + + $i = 0; + $len = strlen($line); + + while ($i< $len){ + $nextcom = strpos($line, '//', $i); + $nexturl = stripos($line, 'url(', $i); + + if($nextcom === false) { + // no more comments, we're done + $i = $len; + break; + } + + // keep any quoted string that starts before a comment + $nextsqt = strpos($line, "'", $i); + $nextdqt = strpos($line, '"', $i); + if(min($nextsqt, $nextdqt) < $nextcom) { + $skipto = false; + if($nextsqt !== false && ($nextdqt === false || $nextsqt < $nextdqt)) { + $skipto = strpos($line, "'", $nextsqt+1) +1; + } else if ($nextdqt !== false) { + $skipto = strpos($line, '"', $nextdqt+1) +1; + } + + if($skipto !== false) { + $i = $skipto; + continue; + } + } + + if($nexturl === false || $nextcom < $nexturl) { + // no url anymore, strip comment and be done + $i = $nextcom; + break; + } + + // we have an upcoming url + $i = strpos($line, ')', $nexturl); + } + + return substr($line, 0, $i); +} + +//Setup VIM: ex: et ts=4 : diff --git a/wiki/lib/exe/detail.php b/wiki/lib/exe/detail.php new file mode 100644 index 0000000..ec1a9b8 --- /dev/null +++ b/wiki/lib/exe/detail.php @@ -0,0 +1,53 @@ +<?php +if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); +define('DOKU_MEDIADETAIL',1); +require_once(DOKU_INC.'inc/init.php'); + +$IMG = getID('media'); +$ID = cleanID($INPUT->str('id')); +$REV = $INPUT->int('rev'); + +// this makes some general info available as well as the info about the +// "parent" page +$INFO = array_merge(pageinfo(),mediainfo()); + +$tmp = array(); +trigger_event('DETAIL_STARTED', $tmp); + +//close session +session_write_close(); + +if($conf['allowdebug'] && $INPUT->has('debug')){ + print '<pre>'; + foreach(explode(' ','basedir userewrite baseurl useslash') as $x){ + print '$'."conf['$x'] = '".$conf[$x]."';\n"; + } + foreach(explode(' ','DOCUMENT_ROOT HTTP_HOST SCRIPT_FILENAME PHP_SELF '. + 'REQUEST_URI SCRIPT_NAME PATH_INFO PATH_TRANSLATED') as $x){ + print '$'."_SERVER['$x'] = '".$_SERVER[$x]."';\n"; + } + print "getID('media'): ".getID('media')."\n"; + print "getID('media',false): ".getID('media',false)."\n"; + print '</pre>'; +} + +$ERROR = false; +// check image permissions +$AUTH = auth_quickaclcheck($IMG); +if($AUTH >= AUTH_READ){ + // check if image exists + $SRC = mediaFN($IMG,$REV); + if(!file_exists($SRC)){ + //doesn't exist! + http_status(404); + $ERROR = 'File not found'; + } +}else{ + // no auth + $ERROR = p_locale_xhtml('denied'); +} + +//start output and load template +header('Content-Type: text/html; charset=utf-8'); +include(template('detail.php')); + diff --git a/wiki/lib/exe/fetch.php b/wiki/lib/exe/fetch.php new file mode 100644 index 0000000..933367e --- /dev/null +++ b/wiki/lib/exe/fetch.php @@ -0,0 +1,99 @@ +<?php +/** + * DokuWiki media passthrough file + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + */ + +if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__).'/../../'); +if (!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); +require_once(DOKU_INC.'inc/init.php'); +session_write_close(); //close session + +require_once(DOKU_INC.'inc/fetch.functions.php'); + +if (defined('SIMPLE_TEST')) { + $INPUT = new Input(); +} + +// BEGIN main + $mimetypes = getMimeTypes(); + + //get input + $MEDIA = stripctl(getID('media', false)); // no cleaning except control chars - maybe external + $CACHE = calc_cache($INPUT->str('cache')); + $WIDTH = $INPUT->int('w'); + $HEIGHT = $INPUT->int('h'); + $REV = & $INPUT->ref('rev'); + //sanitize revision + $REV = preg_replace('/[^0-9]/', '', $REV); + + list($EXT, $MIME, $DL) = mimetype($MEDIA, false); + if($EXT === false) { + $EXT = 'unknown'; + $MIME = 'application/octet-stream'; + $DL = true; + } + + // check for permissions, preconditions and cache external files + list($STATUS, $STATUSMESSAGE) = checkFileStatus($MEDIA, $FILE, $REV, $WIDTH, $HEIGHT); + + // prepare data for plugin events + $data = array( + 'media' => $MEDIA, + 'file' => $FILE, + 'orig' => $FILE, + 'mime' => $MIME, + 'download' => $DL, + 'cache' => $CACHE, + 'ext' => $EXT, + 'width' => $WIDTH, + 'height' => $HEIGHT, + 'status' => $STATUS, + 'statusmessage' => $STATUSMESSAGE, + 'ispublic' => media_ispublic($MEDIA), + ); + + // handle the file status + $evt = new Doku_Event('FETCH_MEDIA_STATUS', $data); + if($evt->advise_before()) { + // redirects + if($data['status'] > 300 && $data['status'] <= 304) { + if (defined('SIMPLE_TEST')) return; //TestResponse doesn't recognize redirects + send_redirect($data['statusmessage']); + } + // send any non 200 status + if($data['status'] != 200) { + http_status($data['status'], $data['statusmessage']); + } + // die on errors + if($data['status'] > 203) { + print $data['statusmessage']; + if (defined('SIMPLE_TEST')) return; + exit; + } + } + $evt->advise_after(); + unset($evt); + + //handle image resizing/cropping + if((substr($MIME, 0, 5) == 'image') && ($WIDTH || $HEIGHT)) { + if($HEIGHT && $WIDTH) { + $data['file'] = $FILE = media_crop_image($data['file'], $EXT, $WIDTH, $HEIGHT); + } else { + $data['file'] = $FILE = media_resize_image($data['file'], $EXT, $WIDTH, $HEIGHT); + } + } + + // finally send the file to the client + $evt = new Doku_Event('MEDIA_SENDFILE', $data); + if($evt->advise_before()) { + sendFile($data['file'], $data['mime'], $data['download'], $data['cache'], $data['ispublic'], $data['orig']); + } + // Do something after the download finished. + $evt->advise_after(); // will not be emitted on 304 or x-sendfile + +// END DO main + +//Setup VIM: ex: et ts=2 : diff --git a/wiki/lib/exe/index.html b/wiki/lib/exe/index.html new file mode 100644 index 0000000..977f90e --- /dev/null +++ b/wiki/lib/exe/index.html @@ -0,0 +1,11 @@ +<!DOCTYPE html> +<html> +<head> +<meta http-equiv="refresh" content="0; URL=../../" /> +<meta name="robots" content="noindex" /> +<title>nothing here...</title> +</head> +<body> +<!-- this is just here to prevent directory browsing --> +</body> +</html> diff --git a/wiki/lib/exe/indexer.php b/wiki/lib/exe/indexer.php new file mode 100644 index 0000000..4f60f16 --- /dev/null +++ b/wiki/lib/exe/indexer.php @@ -0,0 +1,209 @@ +<?php +/** + * DokuWiki indexer + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + */ +if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); +define('DOKU_DISABLE_GZIP_OUTPUT',1); +require_once(DOKU_INC.'inc/init.php'); +session_write_close(); //close session +if(!defined('NL')) define('NL',"\n"); + +// keep running after browser closes connection +@ignore_user_abort(true); + +// check if user abort worked, if yes send output early +$defer = !@ignore_user_abort() || $conf['broken_iua']; +$output = $INPUT->has('debug') && $conf['allowdebug']; +if(!$defer && !$output){ + sendGIF(); // send gif +} + +$ID = cleanID($INPUT->str('id')); + +// Catch any possible output (e.g. errors) +if(!$output) ob_start(); +else header('Content-Type: text/plain'); + +// run one of the jobs +$tmp = array(); // No event data +$evt = new Doku_Event('INDEXER_TASKS_RUN', $tmp); +if ($evt->advise_before()) { + runIndexer() or + runSitemapper() or + sendDigest() or + runTrimRecentChanges() or + runTrimRecentChanges(true) or + $evt->advise_after(); +} + +if(!$output) { + ob_end_clean(); + if($defer) sendGIF(); +} + +exit; + +// -------------------------------------------------------------------- + +/** + * Trims the recent changes cache (or imports the old changelog) as needed. + * + * @param bool $media_changes If the media changelog shall be trimmed instead of + * the page changelog + * @return bool + * + * @author Ben Coburn <btcoburn@silicodon.net> + */ +function runTrimRecentChanges($media_changes = false) { + global $conf; + + echo "runTrimRecentChanges($media_changes): started".NL; + + $fn = ($media_changes ? $conf['media_changelog'] : $conf['changelog']); + + // Trim the Recent Changes + // Trims the recent changes cache to the last $conf['changes_days'] recent + // changes or $conf['recent'] items, which ever is larger. + // The trimming is only done once a day. + if (file_exists($fn) && + (@filemtime($fn.'.trimmed')+86400)<time() && + !file_exists($fn.'_tmp')) { + @touch($fn.'.trimmed'); + io_lock($fn); + $lines = file($fn); + if (count($lines)<=$conf['recent']) { + // nothing to trim + io_unlock($fn); + echo "runTrimRecentChanges($media_changes): finished".NL; + return false; + } + + io_saveFile($fn.'_tmp', ''); // presave tmp as 2nd lock + $trim_time = time() - $conf['recent_days']*86400; + $out_lines = array(); + $old_lines = array(); + for ($i=0; $i<count($lines); $i++) { + $log = parseChangelogLine($lines[$i]); + if ($log === false) continue; // discard junk + if ($log['date'] < $trim_time) { + $old_lines[$log['date'].".$i"] = $lines[$i]; // keep old lines for now (append .$i to prevent key collisions) + } else { + $out_lines[$log['date'].".$i"] = $lines[$i]; // definitely keep these lines + } + } + + if (count($lines)==count($out_lines)) { + // nothing to trim + @unlink($fn.'_tmp'); + io_unlock($fn); + echo "runTrimRecentChanges($media_changes): finished".NL; + return false; + } + + // sort the final result, it shouldn't be necessary, + // however the extra robustness in making the changelog cache self-correcting is worth it + ksort($out_lines); + $extra = $conf['recent'] - count($out_lines); // do we need extra lines do bring us up to minimum + if ($extra > 0) { + ksort($old_lines); + $out_lines = array_merge(array_slice($old_lines,-$extra),$out_lines); + } + + // save trimmed changelog + io_saveFile($fn.'_tmp', implode('', $out_lines)); + @unlink($fn); + if (!rename($fn.'_tmp', $fn)) { + // rename failed so try another way... + io_unlock($fn); + io_saveFile($fn, implode('', $out_lines)); + @unlink($fn.'_tmp'); + } else { + io_unlock($fn); + } + echo "runTrimRecentChanges($media_changes): finished".NL; + return true; + } + + // nothing done + echo "runTrimRecentChanges($media_changes): finished".NL; + return false; +} + +/** + * Runs the indexer for the current page + * + * @author Andreas Gohr <andi@splitbrain.org> + */ +function runIndexer(){ + global $ID; + global $conf; + print "runIndexer(): started".NL; + + if(!$ID) return false; + + // do the work + return idx_addPage($ID, true); +} + +/** + * Builds a Google Sitemap of all public pages known to the indexer + * + * The map is placed in the root directory named sitemap.xml.gz - This + * file needs to be writable! + * + * @author Andreas Gohr + * @link https://www.google.com/webmasters/sitemaps/docs/en/about.html + */ +function runSitemapper(){ + print "runSitemapper(): started".NL; + $result = Sitemapper::generate() && Sitemapper::pingSearchEngines(); + print 'runSitemapper(): finished'.NL; + return $result; +} + +/** + * Send digest and list mails for all subscriptions which are in effect for the + * current page + * + * @author Adrian Lang <lang@cosmocode.de> + */ +function sendDigest() { + global $conf; + global $ID; + + echo 'sendDigest(): started'.NL; + if(!actionOK('subscribe')) { + echo 'sendDigest(): disabled'.NL; + return false; + } + $sub = new Subscription(); + $sent = $sub->send_bulk($ID); + + echo "sendDigest(): sent $sent mails".NL; + echo 'sendDigest(): finished'.NL; + return (bool) $sent; +} + +/** + * Just send a 1x1 pixel blank gif to the browser + * + * @author Andreas Gohr <andi@splitbrain.org> + * @author Harry Fuecks <fuecks@gmail.com> + */ +function sendGIF(){ + $img = base64_decode('R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAEALAAAAAABAAEAAAIBTAA7'); + header('Content-Type: image/gif'); + header('Content-Length: '.strlen($img)); + header('Connection: Close'); + print $img; + tpl_flush(); + // Browser should drop connection after this + // Thinks it's got the whole image +} + +//Setup VIM: ex: et ts=4 : +// No trailing PHP closing tag - no output please! +// See Note at http://php.net/manual/en/language.basic-syntax.instruction-separation.php diff --git a/wiki/lib/exe/jquery.php b/wiki/lib/exe/jquery.php new file mode 100644 index 0000000..f32aef7 --- /dev/null +++ b/wiki/lib/exe/jquery.php @@ -0,0 +1,43 @@ +<?php + +if(!defined('DOKU_INC')) define('DOKU_INC', dirname(__FILE__) . '/../../'); +if(!defined('NOSESSION')) define('NOSESSION', true); // we do not use a session or authentication here (better caching) +if(!defined('NL')) define('NL', "\n"); +if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT', 1); // we gzip ourself here +require_once(DOKU_INC . 'inc/init.php'); + +// MAIN +header('Content-Type: application/javascript; charset=utf-8'); +jquery_out(); + +/** + * Delivers the jQuery JavaScript + * + * We do absolutely nothing fancy here but concatenating the different files + * and handling conditional and gzipped requests + * + * uses cache or fills it + */ +function jquery_out() { + $cache = new cache('jquery', '.js'); + $files = array( + DOKU_INC . 'lib/scripts/jquery/jquery.min.js', + DOKU_INC . 'lib/scripts/jquery/jquery-ui.min.js', + DOKU_INC . 'lib/scripts/jquery/jquery-migrate.min.js', + ); + $cache_files = $files; + $cache_files[] = __FILE__; + + // check cache age & handle conditional request + // This may exit if a cache can be used + $cache_ok = $cache->useCache(array('files' => $cache_files)); + http_cached($cache->cache, $cache_ok); + + $js = ''; + foreach($files as $file) { + $js .= file_get_contents($file)."\n"; + } + stripsourcemaps($js); + + http_cached_finish($cache->cache, $js); +} diff --git a/wiki/lib/exe/js.php b/wiki/lib/exe/js.php new file mode 100644 index 0000000..7b76efa --- /dev/null +++ b/wiki/lib/exe/js.php @@ -0,0 +1,484 @@ +<?php +/** + * DokuWiki JavaScript creator + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @author Andreas Gohr <andi@splitbrain.org> + */ + +if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); +if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) +if(!defined('NL')) define('NL',"\n"); +if(!defined('DOKU_DISABLE_GZIP_OUTPUT')) define('DOKU_DISABLE_GZIP_OUTPUT',1); // we gzip ourself here +require_once(DOKU_INC.'inc/init.php'); + +// Main (don't run when UNIT test) +if(!defined('SIMPLE_TEST')){ + header('Content-Type: application/javascript; charset=utf-8'); + js_out(); +} + + +// ---------------------- functions ------------------------------ + +/** + * Output all needed JavaScript + * + * @author Andreas Gohr <andi@splitbrain.org> + */ +function js_out(){ + global $conf; + global $lang; + global $config_cascade; + global $INPUT; + + // decide from where to get the template + $tpl = trim(preg_replace('/[^\w-]+/','',$INPUT->str('t'))); + if(!$tpl) $tpl = $conf['template']; + + // array of core files + $files = array( + DOKU_INC.'lib/scripts/jquery/jquery.cookie.js', + DOKU_INC.'inc/lang/'.$conf['lang'].'/jquery.ui.datepicker.js', + DOKU_INC."lib/scripts/fileuploader.js", + DOKU_INC."lib/scripts/fileuploaderextended.js", + DOKU_INC.'lib/scripts/helpers.js', + DOKU_INC.'lib/scripts/delay.js', + DOKU_INC.'lib/scripts/cookie.js', + DOKU_INC.'lib/scripts/script.js', + DOKU_INC.'lib/scripts/qsearch.js', + DOKU_INC.'lib/scripts/search.js', + DOKU_INC.'lib/scripts/tree.js', + DOKU_INC.'lib/scripts/index.js', + DOKU_INC.'lib/scripts/textselection.js', + DOKU_INC.'lib/scripts/toolbar.js', + DOKU_INC.'lib/scripts/edit.js', + DOKU_INC.'lib/scripts/editor.js', + DOKU_INC.'lib/scripts/locktimer.js', + DOKU_INC.'lib/scripts/linkwiz.js', + DOKU_INC.'lib/scripts/media.js', + DOKU_INC.'lib/scripts/compatibility.js', +# disabled for FS#1958 DOKU_INC.'lib/scripts/hotkeys.js', + DOKU_INC.'lib/scripts/behaviour.js', + DOKU_INC.'lib/scripts/page.js', + tpl_incdir($tpl).'script.js', + ); + + // add possible plugin scripts and userscript + $files = array_merge($files,js_pluginscripts()); + if(!empty($config_cascade['userscript']['default'])) { + foreach($config_cascade['userscript']['default'] as $userscript) { + $files[] = $userscript; + } + } + + // Let plugins decide to either put more scripts here or to remove some + trigger_event('JS_SCRIPT_LIST', $files); + + // The generated script depends on some dynamic options + $cache = new cache('scripts'.$_SERVER['HTTP_HOST'].$_SERVER['SERVER_PORT'].md5(serialize($files)),'.js'); + $cache->_event = 'JS_CACHE_USE'; + + $cache_files = array_merge($files, getConfigFiles('main')); + $cache_files[] = __FILE__; + + // check cache age & handle conditional request + // This may exit if a cache can be used + $cache_ok = $cache->useCache(array('files' => $cache_files)); + http_cached($cache->cache, $cache_ok); + + // start output buffering and build the script + ob_start(); + + $json = new JSON(); + // add some global variables + print "var DOKU_BASE = '".DOKU_BASE."';"; + print "var DOKU_TPL = '".tpl_basedir($tpl)."';"; + print "var DOKU_COOKIE_PARAM = " . $json->encode( + array( + 'path' => empty($conf['cookiedir']) ? DOKU_REL : $conf['cookiedir'], + 'secure' => $conf['securecookie'] && is_ssl() + )).";"; + // FIXME: Move those to JSINFO + print "Object.defineProperty(window, 'DOKU_UHN', { get: function() { console.warn('Using DOKU_UHN is deprecated. Please use JSINFO.useHeadingNavigation instead'); return JSINFO.useHeadingNavigation; } });"; + print "Object.defineProperty(window, 'DOKU_UHC', { get: function() { console.warn('Using DOKU_UHC is deprecated. Please use JSINFO.useHeadingContent instead'); return JSINFO.useHeadingContent; } });"; + + // load JS specific translations + $lang['js']['plugins'] = js_pluginstrings(); + $templatestrings = js_templatestrings($tpl); + if(!empty($templatestrings)) { + $lang['js']['template'] = $templatestrings; + } + echo 'LANG = '.$json->encode($lang['js']).";\n"; + + // load toolbar + toolbar_JSdefines('toolbar'); + + // load files + foreach($files as $file){ + if(!file_exists($file)) continue; + $ismin = (substr($file,-7) == '.min.js'); + $debugjs = ($conf['allowdebug'] && strpos($file, DOKU_INC.'lib/scripts/') !== 0); + + echo "\n\n/* XXXXXXXXXX begin of ".str_replace(DOKU_INC, '', $file) ." XXXXXXXXXX */\n\n"; + if($ismin) echo "\n/* BEGIN NOCOMPRESS */\n"; + if ($debugjs) echo "\ntry {\n"; + js_load($file); + if ($debugjs) echo "\n} catch (e) {\n logError(e, '".str_replace(DOKU_INC, '', $file)."');\n}\n"; + if($ismin) echo "\n/* END NOCOMPRESS */\n"; + echo "\n\n/* XXXXXXXXXX end of " . str_replace(DOKU_INC, '', $file) . " XXXXXXXXXX */\n\n"; + } + + // init stuff + if($conf['locktime'] != 0){ + js_runonstart("dw_locktimer.init(".($conf['locktime'] - 60).",".$conf['usedraft'].")"); + } + // init hotkeys - must have been done after init of toolbar +# disabled for FS#1958 js_runonstart('initializeHotkeys()'); + + // end output buffering and get contents + $js = ob_get_contents(); + ob_end_clean(); + + // strip any source maps + stripsourcemaps($js); + + // compress whitespace and comments + if($conf['compress']){ + $js = js_compress($js); + } + + $js .= "\n"; // https://bugzilla.mozilla.org/show_bug.cgi?id=316033 + + http_cached_finish($cache->cache, $js); +} + +/** + * Load the given file, handle include calls and print it + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $file filename path to file + */ +function js_load($file){ + if(!file_exists($file)) return; + static $loaded = array(); + + $data = io_readFile($file); + while(preg_match('#/\*\s*DOKUWIKI:include(_once)?\s+([\w\.\-_/]+)\s*\*/#',$data,$match)){ + $ifile = $match[2]; + + // is it a include_once? + if($match[1]){ + $base = utf8_basename($ifile); + if(array_key_exists($base, $loaded) && $loaded[$base] === true){ + $data = str_replace($match[0], '' ,$data); + continue; + } + $loaded[$base] = true; + } + + if($ifile{0} != '/') $ifile = dirname($file).'/'.$ifile; + + if(file_exists($ifile)){ + $idata = io_readFile($ifile); + }else{ + $idata = ''; + } + $data = str_replace($match[0],$idata,$data); + } + echo "$data\n"; +} + +/** + * Returns a list of possible Plugin Scripts (no existance check here) + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @return array + */ +function js_pluginscripts(){ + $list = array(); + $plugins = plugin_list(); + foreach ($plugins as $p){ + $list[] = DOKU_PLUGIN."$p/script.js"; + } + return $list; +} + +/** + * Return an two-dimensional array with strings from the language file of each plugin. + * + * - $lang['js'] must be an array. + * - Nothing is returned for plugins without an entry for $lang['js'] + * + * @author Gabriel Birke <birke@d-scribe.de> + * + * @return array + */ +function js_pluginstrings() { + global $conf, $config_cascade; + $pluginstrings = array(); + $plugins = plugin_list(); + foreach($plugins as $p) { + $path = DOKU_PLUGIN . $p . '/lang/'; + + if(isset($lang)) unset($lang); + if(file_exists($path . "en/lang.php")) { + include $path . "en/lang.php"; + } + foreach($config_cascade['lang']['plugin'] as $config_file) { + if(file_exists($config_file . $p . '/en/lang.php')) { + include($config_file . $p . '/en/lang.php'); + } + } + if(isset($conf['lang']) && $conf['lang'] != 'en') { + if(file_exists($path . $conf['lang'] . "/lang.php")) { + include($path . $conf['lang'] . '/lang.php'); + } + foreach($config_cascade['lang']['plugin'] as $config_file) { + if(file_exists($config_file . $p . '/' . $conf['lang'] . '/lang.php')) { + include($config_file . $p . '/' . $conf['lang'] . '/lang.php'); + } + } + } + + if(isset($lang['js'])) { + $pluginstrings[$p] = $lang['js']; + } + } + return $pluginstrings; +} + +/** + * Return an two-dimensional array with strings from the language file of current active template. + * + * - $lang['js'] must be an array. + * - Nothing is returned for template without an entry for $lang['js'] + * + * @param string $tpl + * @return array + */ +function js_templatestrings($tpl) { + global $conf, $config_cascade; + + $path = tpl_incdir() . 'lang/'; + + $templatestrings = array(); + if(file_exists($path . "en/lang.php")) { + include $path . "en/lang.php"; + } + foreach($config_cascade['lang']['template'] as $config_file) { + if(file_exists($config_file . $conf['template'] . '/en/lang.php')) { + include($config_file . $conf['template'] . '/en/lang.php'); + } + } + if(isset($conf['lang']) && $conf['lang'] != 'en' && file_exists($path . $conf['lang'] . "/lang.php")) { + include $path . $conf['lang'] . "/lang.php"; + } + if(isset($conf['lang']) && $conf['lang'] != 'en') { + if(file_exists($path . $conf['lang'] . "/lang.php")) { + include $path . $conf['lang'] . "/lang.php"; + } + foreach($config_cascade['lang']['template'] as $config_file) { + if(file_exists($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php')) { + include($config_file . $conf['template'] . '/' . $conf['lang'] . '/lang.php'); + } + } + } + + if(isset($lang['js'])) { + $templatestrings[$tpl] = $lang['js']; + } + return $templatestrings; +} + +/** + * Escapes a String to be embedded in a JavaScript call, keeps \n + * as newline + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $string + * @return string + */ +function js_escape($string){ + return str_replace('\\\\n','\\n',addslashes($string)); +} + +/** + * Adds the given JavaScript code to the window.onload() event + * + * @author Andreas Gohr <andi@splitbrain.org> + * + * @param string $func + */ +function js_runonstart($func){ + echo "jQuery(function(){ $func; });".NL; +} + +/** + * Strip comments and whitespaces from given JavaScript Code + * + * This is a port of Nick Galbreath's python tool jsstrip.py which is + * released under BSD license. See link for original code. + * + * @author Nick Galbreath <nickg@modp.com> + * @author Andreas Gohr <andi@splitbrain.org> + * @link http://code.google.com/p/jsstrip/ + * + * @param string $s + * @return string + */ +function js_compress($s){ + $s = ltrim($s); // strip all initial whitespace + $s .= "\n"; + $i = 0; // char index for input string + $j = 0; // char forward index for input string + $line = 0; // line number of file (close to it anyways) + $slen = strlen($s); // size of input string + $lch = ''; // last char added + $result = ''; // we store the final result here + + // items that don't need spaces next to them + $chars = "^&|!+\-*\/%=\?:;,{}()<>% \t\n\r'\"[]"; + + // items which need a space if the sign before and after whitespace is equal. + // E.g. '+ ++' may not be compressed to '+++' --> syntax error. + $ops = "+-"; + + $regex_starters = array("(", "=", "[", "," , ":", "!", "&", "|"); + + $whitespaces_chars = array(" ", "\t", "\n", "\r", "\0", "\x0B"); + + while($i < $slen){ + // skip all "boring" characters. This is either + // reserved word (e.g. "for", "else", "if") or a + // variable/object/method (e.g. "foo.color") + while ($i < $slen && (strpos($chars,$s[$i]) === false) ){ + $result .= $s{$i}; + $i = $i + 1; + } + + $ch = $s{$i}; + // multiline comments (keeping IE conditionals) + if($ch == '/' && $s{$i+1} == '*' && $s{$i+2} != '@'){ + $endC = strpos($s,'*/',$i+2); + if($endC === false) trigger_error('Found invalid /*..*/ comment', E_USER_ERROR); + + // check if this is a NOCOMPRESS comment + if(substr($s, $i, $endC+2-$i) == '/* BEGIN NOCOMPRESS */'){ + $endNC = strpos($s, '/* END NOCOMPRESS */', $endC+2); + if($endNC === false) trigger_error('Found invalid NOCOMPRESS comment', E_USER_ERROR); + + // verbatim copy contents, trimming but putting it on its own line + $result .= "\n".trim(substr($s, $i + 22, $endNC - ($i + 22)))."\n"; // BEGIN comment = 22 chars + $i = $endNC + 20; // END comment = 20 chars + }else{ + $i = $endC + 2; + } + continue; + } + + // singleline + if($ch == '/' && $s{$i+1} == '/'){ + $endC = strpos($s,"\n",$i+2); + if($endC === false) trigger_error('Invalid comment', E_USER_ERROR); + $i = $endC; + continue; + } + + // tricky. might be an RE + if($ch == '/'){ + // rewind, skip white space + $j = 1; + while(in_array($s{$i-$j}, $whitespaces_chars)){ + $j = $j + 1; + } + if( in_array($s{$i-$j}, $regex_starters) ){ + // yes, this is an re + // now move forward and find the end of it + $j = 1; + while($s{$i+$j} != '/'){ + if($s{$i+$j} == '\\') $j = $j + 2; + else $j++; + } + $result .= substr($s,$i,$j+1); + $i = $i + $j + 1; + continue; + } + } + + // double quote strings + if($ch == '"'){ + $j = 1; + while( $s{$i+$j} != '"' && ($i+$j < $slen)){ + if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == '"' || $s{$i+$j+1} == '\\') ){ + $j += 2; + }else{ + $j += 1; + } + } + $string = substr($s,$i,$j+1); + // remove multiline markers: + $string = str_replace("\\\n",'',$string); + $result .= $string; + $i = $i + $j + 1; + continue; + } + + // single quote strings + if($ch == "'"){ + $j = 1; + while( $s{$i+$j} != "'" && ($i+$j < $slen)){ + if( $s{$i+$j} == '\\' && ($s{$i+$j+1} == "'" || $s{$i+$j+1} == '\\') ){ + $j += 2; + }else{ + $j += 1; + } + } + $string = substr($s,$i,$j+1); + // remove multiline markers: + $string = str_replace("\\\n",'',$string); + $result .= $string; + $i = $i + $j + 1; + continue; + } + + // whitespaces + if( $ch == ' ' || $ch == "\r" || $ch == "\n" || $ch == "\t" ){ + $lch = substr($result,-1); + + // Only consider deleting whitespace if the signs before and after + // are not equal and are not an operator which may not follow itself. + if ($i+1 < $slen && ((!$lch || $s[$i+1] == ' ') + || $lch != $s[$i+1] + || strpos($ops,$s[$i+1]) === false)) { + // leading spaces + if($i+1 < $slen && (strpos($chars,$s[$i+1]) !== false)){ + $i = $i + 1; + continue; + } + // trailing spaces + // if this ch is space AND the last char processed + // is special, then skip the space + if($lch && (strpos($chars,$lch) !== false)){ + $i = $i + 1; + continue; + } + } + + // else after all of this convert the "whitespace" to + // a single space. It will get appended below + $ch = ' '; + } + + // other chars + $result .= $ch; + $i = $i + 1; + } + + return trim($result); +} + +//Setup VIM: ex: et ts=4 : diff --git a/wiki/lib/exe/manifest.php b/wiki/lib/exe/manifest.php new file mode 100644 index 0000000..e9a3528 --- /dev/null +++ b/wiki/lib/exe/manifest.php @@ -0,0 +1,14 @@ +<?php + +if (!defined('DOKU_INC')) { + define('DOKU_INC', __DIR__ . '/../../'); +} +require_once(DOKU_INC . 'inc/init.php'); + +if (!actionOK('manifest')) { + http_status(404, 'Manifest has been disabled in DokuWiki configuration.'); + exit(); +} + +$manifest = new \dokuwiki\Manifest(); +$manifest->sendManifest(); diff --git a/wiki/lib/exe/mediamanager.php b/wiki/lib/exe/mediamanager.php new file mode 100644 index 0000000..7222544 --- /dev/null +++ b/wiki/lib/exe/mediamanager.php @@ -0,0 +1,126 @@ +<?php + if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); + define('DOKU_MEDIAMANAGER',1); + + // for multi uploader: + @ini_set('session.use_only_cookies',0); + + require_once(DOKU_INC.'inc/init.php'); + + global $INPUT; + global $lang; + global $conf; + // handle passed message + if($INPUT->str('msg1')) msg(hsc($INPUT->str('msg1')),1); + if($INPUT->str('err')) msg(hsc($INPUT->str('err')),-1); + + global $DEL; + // get namespace to display (either direct or from deletion order) + if($INPUT->str('delete')){ + $DEL = cleanID($INPUT->str('delete')); + $IMG = $DEL; + $NS = getNS($DEL); + }elseif($INPUT->str('edit')){ + $IMG = cleanID($INPUT->str('edit')); + $NS = getNS($IMG); + }elseif($INPUT->str('img')){ + $IMG = cleanID($INPUT->str('img')); + $NS = getNS($IMG); + }else{ + $NS = cleanID($INPUT->str('ns')); + $IMG = null; + } + + global $INFO, $JSINFO; + $INFO = !empty($INFO) ? array_merge($INFO, mediainfo()) : mediainfo(); + $JSINFO['id'] = ''; + $JSINFO['namespace'] = ''; + $AUTH = $INFO['perm']; // shortcut for historical reasons + + $tmp = array(); + trigger_event('MEDIAMANAGER_STARTED', $tmp); + session_write_close(); //close session + + // do not display the manager if user does not have read access + if($AUTH < AUTH_READ && !$fullscreen) { + http_status(403); + die($lang['accessdenied']); + } + + // handle flash upload + if(isset($_FILES['Filedata'])){ + $_FILES['upload'] =& $_FILES['Filedata']; + $JUMPTO = media_upload($NS,$AUTH); + if($JUMPTO == false){ + http_status(400); + echo 'Upload failed'; + } + echo 'ok'; + exit; + } + + // give info on PHP caught upload errors + if(!empty($_FILES['upload']['error'])){ + switch($_FILES['upload']['error']){ + case 1: + case 2: + msg(sprintf($lang['uploadsize'], + filesize_h(php_to_byte(ini_get('upload_max_filesize')))),-1); + break; + default: + msg($lang['uploadfail'].' ('.$_FILES['upload']['error'].')',-1); + } + unset($_FILES['upload']); + } + + // handle upload + if(!empty($_FILES['upload']['tmp_name'])){ + $JUMPTO = media_upload($NS,$AUTH); + if($JUMPTO) $NS = getNS($JUMPTO); + } + + // handle meta saving + if($IMG && @array_key_exists('save', $INPUT->arr('do'))){ + $JUMPTO = media_metasave($IMG,$AUTH,$INPUT->arr('meta')); + } + + if($IMG && ($INPUT->str('mediado') == 'save' || @array_key_exists('save', $INPUT->arr('mediado')))) { + $JUMPTO = media_metasave($IMG,$AUTH,$INPUT->arr('meta')); + } + + if ($INPUT->int('rev') && $conf['mediarevisions']) $REV = $INPUT->int('rev'); + + if($INPUT->str('mediado') == 'restore' && $conf['mediarevisions']){ + $JUMPTO = media_restore($INPUT->str('image'), $REV, $AUTH); + } + + // handle deletion + if($DEL) { + $res = 0; + if(checkSecurityToken()) { + $res = media_delete($DEL,$AUTH); + } + if ($res & DOKU_MEDIA_DELETED) { + $msg = sprintf($lang['deletesucc'], noNS($DEL)); + if ($res & DOKU_MEDIA_EMPTY_NS && !$fullscreen) { + // current namespace was removed. redirecting to root ns passing msg along + send_redirect(DOKU_URL.'lib/exe/mediamanager.php?msg1='. + rawurlencode($msg).'&edid='.$INPUT->str('edid')); + } + msg($msg,1); + } elseif ($res & DOKU_MEDIA_INUSE) { + if(!$conf['refshow']) { + msg(sprintf($lang['mediainuse'],noNS($DEL)),0); + } + } else { + msg(sprintf($lang['deletefail'],noNS($DEL)),-1); + } + } + // finished - start output + + if (!$fullscreen) { + header('Content-Type: text/html; charset=utf-8'); + include(template('mediamanager.php')); + } + +/* vim: set expandtab tabstop=4 shiftwidth=4 softtabstop=4: */ diff --git a/wiki/lib/exe/opensearch.php b/wiki/lib/exe/opensearch.php new file mode 100644 index 0000000..b00b2b7 --- /dev/null +++ b/wiki/lib/exe/opensearch.php @@ -0,0 +1,38 @@ +<?php +/** + * DokuWiki OpenSearch creator + * + * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) + * @link http://www.opensearch.org/ + * @author Mike Frysinger <vapier@gentoo.org> + * @author Andreas Gohr <andi@splitbrain.org> + */ + +if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); +if(!defined('NOSESSION')) define('NOSESSION',true); // we do not use a session or authentication here (better caching) +if(!defined('NL')) define('NL',"\n"); +require_once(DOKU_INC.'inc/init.php'); + +// try to be clever about the favicon location +if(file_exists(DOKU_INC.'favicon.ico')){ + $ico = DOKU_URL.'favicon.ico'; +}elseif(file_exists(tpl_incdir().'images/favicon.ico')){ + $ico = DOKU_URL.'lib/tpl/'.$conf['template'].'/images/favicon.ico'; +}elseif(file_exists(tpl_incdir().'favicon.ico')){ + $ico = DOKU_URL.'lib/tpl/'.$conf['template'].'/favicon.ico'; +}else{ + $ico = DOKU_URL.'lib/tpl/dokuwiki/images/favicon.ico'; +} + +// output +header('Content-Type: application/opensearchdescription+xml; charset=utf-8'); +echo '<?xml version="1.0"?>'.NL; +echo '<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">'.NL; +echo ' <ShortName>'.hsc($conf['title']).'</ShortName>'.NL; +echo ' <Image width="16" height="16" type="image/x-icon">'.$ico.'</Image>'.NL; +echo ' <Url type="text/html" template="'.DOKU_URL.DOKU_SCRIPT.'?do=search&id={searchTerms}" />'.NL; +echo ' <Url type="application/x-suggestions+json" template="'. + DOKU_URL.'lib/exe/ajax.php?call=suggestions&q={searchTerms}" />'.NL; +echo '</OpenSearchDescription>'.NL; + +//Setup VIM: ex: et ts=4 : diff --git a/wiki/lib/exe/xmlrpc.php b/wiki/lib/exe/xmlrpc.php new file mode 100644 index 0000000..3046f47 --- /dev/null +++ b/wiki/lib/exe/xmlrpc.php @@ -0,0 +1,67 @@ +<?php +if(!defined('DOKU_INC')) define('DOKU_INC',dirname(__FILE__).'/../../'); + +require_once(DOKU_INC.'inc/init.php'); +session_write_close(); //close session + +if(!$conf['remote']) die((new IXR_Error(-32605, "XML-RPC server not enabled."))->getXml()); + +/** + * Contains needed wrapper functions and registers all available + * XMLRPC functions. + */ +class dokuwiki_xmlrpc_server extends IXR_Server { + protected $remote; + + /** + * Constructor. Register methods and run Server + */ + public function __construct(){ + $this->remote = new RemoteAPI(); + $this->remote->setDateTransformation(array($this, 'toDate')); + $this->remote->setFileTransformation(array($this, 'toFile')); + parent::__construct(); + } + + /** + * @param string $methodname + * @param array $args + * @return IXR_Error|mixed + */ + public function call($methodname, $args){ + try { + $result = $this->remote->call($methodname, $args); + return $result; + } catch (RemoteAccessDeniedException $e) { + if (!isset($_SERVER['REMOTE_USER'])) { + http_status(401); + return new IXR_Error(-32603, "server error. not authorized to call method $methodname"); + } else { + http_status(403); + return new IXR_Error(-32604, "server error. forbidden to call the method $methodname"); + } + } catch (RemoteException $e) { + return new IXR_Error($e->getCode(), $e->getMessage()); + } + } + + /** + * @param string|int $data iso date(yyyy[-]mm[-]dd[ hh:mm[:ss]]) or timestamp + * @return IXR_Date + */ + public function toDate($data) { + return new IXR_Date($data); + } + + /** + * @param string $data + * @return IXR_Base64 + */ + public function toFile($data) { + return new IXR_Base64($data); + } +} + +$server = new dokuwiki_xmlrpc_server(); + +// vim:ts=4:sw=4:et: |