3 * Common DokuWiki functions
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
9 if(!defined('DOKU_INC')) die('meh.');
12 * These constants are used with the recents function
14 define('RECENTS_SKIP_DELETED',2);
15 define('RECENTS_SKIP_MINORS',4);
16 define('RECENTS_SKIP_SUBSPACES',8);
17 define('RECENTS_MEDIA_CHANGES',16);
18 define('RECENTS_MEDIA_PAGES_MIXED',32);
21 * Wrapper around htmlspecialchars()
23 * @author Andreas Gohr <andi@splitbrain.org>
24 * @see htmlspecialchars()
26 function hsc($string){
27 return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
31 * print a newline terminated string
33 * You can give an indention as optional parameter
35 * @author Andreas Gohr <andi@splitbrain.org>
37 function ptln($string,$indent=0){
38 echo str_repeat(' ', $indent)."$string\n";
42 * strips control characters (<32) from the given string
44 * @author Andreas Gohr <andi@splitbrain.org>
46 function stripctl($string){
47 return preg_replace('/[\x00-\x1F]+/s','',$string);
51 * Return a secret token to be used for CSRF attack prevention
53 * @author Andreas Gohr <andi@splitbrain.org>
54 * @link http://en.wikipedia.org/wiki/Cross-site_request_forgery
55 * @link http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
58 function getSecurityToken(){
59 return md5(auth_cookiesalt().session_id().$_SERVER['REMOTE_USER']);
63 * Check the secret CSRF token
65 function checkSecurityToken($token=null){
66 if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
68 if(is_null($token)) $token = $_REQUEST['sectok'];
69 if(getSecurityToken() != $token){
70 msg('Security Token did not match. Possible CSRF attack.',-1);
77 * Print a hidden form field with a secret CSRF token
79 * @author Andreas Gohr <andi@splitbrain.org>
81 function formSecurityToken($print=true){
82 $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
91 * Return info about the current document as associative
94 * @author Andreas Gohr <andi@splitbrain.org>
103 // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
104 // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
108 // set info about manager/admin status.
109 $info['isadmin'] = false;
110 $info['ismanager'] = false;
111 if(isset($_SERVER['REMOTE_USER'])){
112 $info['userinfo'] = $USERINFO;
113 $info['perm'] = auth_quickaclcheck($ID);
114 $info['subscribed'] = get_info_subscribed();
115 $info['client'] = $_SERVER['REMOTE_USER'];
117 if($info['perm'] == AUTH_ADMIN){
118 $info['isadmin'] = true;
119 $info['ismanager'] = true;
120 }elseif(auth_ismanager()){
121 $info['ismanager'] = true;
124 // if some outside auth were used only REMOTE_USER is set
125 if(!$info['userinfo']['name']){
126 $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
130 $info['perm'] = auth_aclcheck($ID,'',null);
131 $info['subscribed'] = false;
132 $info['client'] = clientIP(true);
135 $info['namespace'] = getNS($ID);
136 $info['locked'] = checklock($ID);
137 $info['filepath'] = fullpath(wikiFN($ID));
138 $info['exists'] = @file_exists($info['filepath']);
140 //check if current revision was meant
141 if($info['exists'] && (@filemtime($info['filepath'])==$REV)){
144 //section editing does not work with old revisions!
147 msg($lang['nosecedit'],0);
149 //really use old revision
150 $info['filepath'] = fullpath(wikiFN($ID,$REV));
151 $info['exists'] = @file_exists($info['filepath']);
156 $info['writable'] = (is_writable($info['filepath']) &&
157 ($info['perm'] >= AUTH_EDIT));
159 $info['writable'] = ($info['perm'] >= AUTH_CREATE);
161 $info['editable'] = ($info['writable'] && empty($info['locked']));
162 $info['lastmod'] = @filemtime($info['filepath']);
164 //load page meta data
165 $info['meta'] = p_get_metadata($ID);
169 $revinfo = getRevisionInfo($ID, $REV, 1024);
171 if (is_array($info['meta']['last_change'])) {
172 $revinfo = $info['meta']['last_change'];
174 $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
175 // cache most recent changelog line in metadata if missing and still valid
176 if ($revinfo!==false) {
177 $info['meta']['last_change'] = $revinfo;
178 p_set_metadata($ID, array('last_change' => $revinfo));
182 //and check for an external edit
183 if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
184 // cached changelog line no longer valid
186 $info['meta']['last_change'] = $revinfo;
187 p_set_metadata($ID, array('last_change' => $revinfo));
190 $info['ip'] = $revinfo['ip'];
191 $info['user'] = $revinfo['user'];
192 $info['sum'] = $revinfo['sum'];
193 // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
194 // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
196 if($revinfo['user']){
197 $info['editor'] = $revinfo['user'];
199 $info['editor'] = $revinfo['ip'];
203 $draft = getCacheName($info['client'].$ID,'.draft');
204 if(@file_exists($draft)){
205 if(@filemtime($draft) < @filemtime(wikiFN($ID))){
206 // remove stale draft
209 $info['draft'] = $draft;
214 $info['ismobile'] = clientismobile();
220 * Build an string of URL parameters
222 * @author Andreas Gohr
224 function buildURLparams($params, $sep='&'){
227 foreach($params as $key => $val){
228 if($amp) $url .= $sep;
230 $url .= rawurlencode($key).'=';
231 $url .= rawurlencode((string)$val);
238 * Build an string of html tag attributes
240 * Skips keys starting with '_', values get HTML encoded
242 * @author Andreas Gohr
244 function buildAttributes($params,$skipempty=false){
247 foreach($params as $key => $val){
248 if($key{0} == '_') continue;
249 if($val === '' && $skipempty) continue;
250 if($white) $url .= ' ';
253 $url .= htmlspecialchars ($val);
262 * This builds the breadcrumb trail and returns it as array
264 * @author Andreas Gohr <andi@splitbrain.org>
266 function breadcrumbs(){
267 // we prepare the breadcrumbs early for quick session closing
268 static $crumbs = null;
269 if($crumbs != null) return $crumbs;
276 $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
277 //we only save on show and existing wiki documents
279 if($ACT != 'show' || !@file_exists($file)){
280 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
285 $name = noNSorNS($ID);
286 if (useHeading('navigation')) {
288 $title = p_get_first_heading($ID,METADATA_RENDER_USING_SIMPLE_CACHE);
294 //remove ID from array
295 if (isset($crumbs[$ID])) {
300 $crumbs[$ID] = $name;
302 while(count($crumbs) > $conf['breadcrumbs']){
303 array_shift($crumbs);
306 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
311 * Filter for page IDs
313 * This is run on a ID before it is outputted somewhere
314 * currently used to replace the colon with something else
315 * on Windows systems and to have proper URL encoding
317 * Urlencoding is ommitted when the second parameter is false
319 * @author Andreas Gohr <andi@splitbrain.org>
321 function idfilter($id,$ue=true){
323 if ($conf['useslash'] && $conf['userewrite']){
324 $id = strtr($id,':','/');
325 }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
326 $conf['userewrite']) {
327 $id = strtr($id,':',';');
330 $id = rawurlencode($id);
331 $id = str_replace('%3A',':',$id); //keep as colon
332 $id = str_replace('%2F','/',$id); //keep as slash
338 * This builds a link to a wikipage
340 * It handles URL rewriting and adds additional parameter if
343 * @author Andreas Gohr <andi@splitbrain.org>
345 function wl($id='',$more='',$abs=false,$sep='&'){
348 $more = buildURLparams($more,$sep);
350 $more = str_replace(',',$sep,$more);
360 if($conf['userewrite'] == 2){
361 $xlink .= DOKU_SCRIPT.'/'.$id;
362 if($more) $xlink .= '?'.$more;
363 }elseif($conf['userewrite']){
365 if($more) $xlink .= '?'.$more;
367 $xlink .= DOKU_SCRIPT.'?id='.$id;
368 if($more) $xlink .= $sep.$more;
370 $xlink .= DOKU_SCRIPT;
371 if($more) $xlink .= '?'.$more;
378 * This builds a link to an alternate page format
380 * Handles URL rewriting if enabled. Follows the style of wl().
382 * @author Ben Coburn <btcoburn@silicodon.net>
384 function exportlink($id='',$format='raw',$more='',$abs=false,$sep='&'){
387 $more = buildURLparams($more,$sep);
389 $more = str_replace(',',$sep,$more);
392 $format = rawurlencode($format);
400 if($conf['userewrite'] == 2){
401 $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
402 if($more) $xlink .= $sep.$more;
403 }elseif($conf['userewrite'] == 1){
404 $xlink .= '_export/'.$format.'/'.$id;
405 if($more) $xlink .= '?'.$more;
407 $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
408 if($more) $xlink .= $sep.$more;
415 * Build a link to a media file
417 * Will return a link to the detail page if $direct is false
419 * The $more parameter should always be given as array, the function then
420 * will strip default parameters to produce even cleaner URLs
422 * @param string $id - the media file id or URL
423 * @param mixed $more - string or array with additional parameters
424 * @param boolean $direct - link to detail page if false
425 * @param string $sep - URL parameter separator
426 * @param boolean $abs - Create an absolute URL
428 function ml($id='',$more='',$direct=true,$sep='&',$abs=false){
431 // strip defaults for shorter URLs
432 if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
433 if(!$more['w']) unset($more['w']);
434 if(!$more['h']) unset($more['h']);
435 if(isset($more['id']) && $direct) unset($more['id']);
436 $more = buildURLparams($more,$sep);
438 $more = str_replace('cache=cache','',$more); //skip default
439 $more = str_replace(',,',',',$more);
440 $more = str_replace(',',$sep,$more);
449 // external URLs are always direct without rewriting
450 if(preg_match('#^(https?|ftp)://#i',$id)){
451 $xlink .= 'lib/exe/fetch.php';
453 $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6);
455 $xlink .= $sep.$more;
456 $xlink .= $sep.'media='.rawurlencode($id);
458 $xlink .= $sep.'media='.rawurlencode($id);
465 // decide on scriptname
467 if($conf['userewrite'] == 1){
470 $script = 'lib/exe/fetch.php';
473 if($conf['userewrite'] == 1){
476 $script = 'lib/exe/detail.php';
480 // build URL based on rewrite mode
481 if($conf['userewrite']){
482 $xlink .= $script.'/'.$id;
483 if($more) $xlink .= '?'.$more;
486 $xlink .= $script.'?'.$more;
487 $xlink .= $sep.'media='.$id;
489 $xlink .= $script.'?media='.$id;
499 * Just builds a link to a script
501 * @todo maybe obsolete
502 * @author Andreas Gohr <andi@splitbrain.org>
504 function script($script='doku.php'){
505 return DOKU_BASE.DOKU_SCRIPT;
509 * Spamcheck against wordlist
511 * Checks the wikitext against a list of blocked expressions
512 * returns true if the text contains any bad words
514 * Triggers COMMON_WORDBLOCK_BLOCKED
516 * Action Plugins can use this event to inspect the blocked data
517 * and gain information about the user who was blocked.
520 * data['matches'] - array of matches
521 * data['userinfo'] - information about the blocked user
523 * [user] - username (if logged in)
524 * [mail] - mail address (if logged in)
525 * [name] - real name (if logged in)
527 * @author Andreas Gohr <andi@splitbrain.org>
528 * @author Michael Klier <chi@chimeric.de>
529 * @param string $text - optional text to check, if not given the globals are used
530 * @return bool - true if a spam word was found
532 function checkwordblock($text=''){
539 if(!$conf['usewordblock']) return false;
541 if(!$text) $text = "$PRE $TEXT $SUF";
543 // we prepare the text a tiny bit to prevent spammers circumventing URL checks
544 $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
546 $wordblocks = getWordblocks();
547 // how many lines to read at once (to work around some PCRE limits)
548 if(version_compare(phpversion(),'4.3.0','<')){
549 // old versions of PCRE define a maximum of parenthesises even if no
550 // backreferences are used - the maximum is 99
551 // this is very bad performancewise and may even be too high still
554 // read file in chunks of 200 - this should work around the
555 // MAX_PATTERN_SIZE in modern PCRE
558 while($blocks = array_splice($wordblocks,0,$chunksize)){
560 // build regexp from blocks
561 foreach($blocks as $block){
562 $block = preg_replace('/#.*$/','',$block);
563 $block = trim($block);
564 if(empty($block)) continue;
567 if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
568 // prepare event data
569 $data['matches'] = $matches;
570 $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
571 if($_SERVER['REMOTE_USER']) {
572 $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
573 $data['userinfo']['name'] = $INFO['userinfo']['name'];
574 $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
576 $callback = create_function('', 'return true;');
577 return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
584 * Return the IP of the client
586 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
588 * It returns a comma separated list of IPs if the above mentioned
589 * headers are set. If the single parameter is set, it tries to return
590 * a routable public address, prefering the ones suplied in the X
593 * @param boolean $single If set only a single IP is returned
594 * @author Andreas Gohr <andi@splitbrain.org>
596 function clientIP($single=false){
598 $ip[] = $_SERVER['REMOTE_ADDR'];
599 if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
600 $ip = array_merge($ip,explode(',',str_replace(' ','',$_SERVER['HTTP_X_FORWARDED_FOR'])));
601 if(!empty($_SERVER['HTTP_X_REAL_IP']))
602 $ip = array_merge($ip,explode(',',str_replace(' ','',$_SERVER['HTTP_X_REAL_IP'])));
604 // some IPv4/v6 regexps borrowed from Feyd
605 // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
606 $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
607 $hex_digit = '[A-Fa-f0-9]';
608 $h16 = "{$hex_digit}{1,4}";
609 $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
610 $ls32 = "(?:$h16:$h16|$IPv4Address)";
612 "(?:(?:{$IPv4Address})|(?:".
613 "(?:$h16:){6}$ls32" .
614 "|::(?:$h16:){5}$ls32" .
615 "|(?:$h16)?::(?:$h16:){4}$ls32" .
616 "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
617 "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
618 "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
619 "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
620 "|(?:(?:$h16:){0,5}$h16)?::$h16" .
621 "|(?:(?:$h16:){0,6}$h16)?::" .
622 ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
624 // remove any non-IP stuff
627 for($i=0; $i<$cnt; $i++){
628 if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
633 if(empty($ip[$i])) unset($ip[$i]);
635 $ip = array_values(array_unique($ip));
636 if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
638 if(!$single) return join(',',$ip);
640 // decide which IP to use, trying to avoid local addresses
641 $ip = array_reverse($ip);
643 if(preg_match('/^(::1|[fF][eE]80:|127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
649 // still here? just use the first (last) address
654 * Check if the browser is on a mobile device
656 * Adapted from the example code at url below
658 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
660 function clientismobile(){
662 if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
664 if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
666 if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
668 $uamatches = 'midp|j2me|avantg|docomo|novarra|palmos|palmsource|240x320|opwv|chtml|pda|windows ce|mmp\/|blackberry|mib\/|symbian|wireless|nokia|hand|mobi|phone|cdm|up\.b|audio|SIE\-|SEC\-|samsung|HTC|mot\-|mitsu|sagem|sony|alcatel|lg|erics|vx|NEC|philips|mmm|xx|panasonic|sharp|wap|sch|rover|pocket|benq|java|pt|pg|vox|amoi|bird|compal|kg|voda|sany|kdd|dbt|sendo|sgh|gradi|jb|\d\d\di|moto';
670 if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
677 * Convert one or more comma separated IPs to hostnames
679 * @author Glen Harris <astfgl@iamnota.org>
680 * @returns a comma separated list of hostnames
682 function gethostsbyaddrs($ips){
684 $ips = explode(',',$ips);
687 foreach($ips as $ip){
688 $hosts[] = gethostbyaddr(trim($ip));
690 return join(',',$hosts);
692 return gethostbyaddr(trim($ips));
697 * Checks if a given page is currently locked.
699 * removes stale lockfiles
701 * @author Andreas Gohr <andi@splitbrain.org>
703 function checklock($id){
705 $lock = wikiLockFN($id);
708 if(!@file_exists($lock)) return false;
711 if((time() - filemtime($lock)) > $conf['locktime']){
717 list($ip,$session) = explode("\n",io_readFile($lock));
718 if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()){
726 * Lock a page for editing
728 * @author Andreas Gohr <andi@splitbrain.org>
733 if($conf['locktime'] == 0){
737 $lock = wikiLockFN($id);
738 if($_SERVER['REMOTE_USER']){
739 io_saveFile($lock,$_SERVER['REMOTE_USER']);
741 io_saveFile($lock,clientIP()."\n".session_id());
746 * Unlock a page if it was locked by the user
748 * @author Andreas Gohr <andi@splitbrain.org>
749 * @return bool true if a lock was removed
751 function unlock($id){
752 $lock = wikiLockFN($id);
753 if(@file_exists($lock)){
754 list($ip,$session) = explode("\n",io_readFile($lock));
755 if($ip == $_SERVER['REMOTE_USER'] || $ip == clientIP() || $session == session_id()){
764 * convert line ending to unix format
766 * @see formText() for 2crlf conversion
767 * @author Andreas Gohr <andi@splitbrain.org>
769 function cleanText($text){
770 $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
775 * Prepares text for print in Webforms by encoding special chars.
776 * It also converts line endings to Windows format which is
777 * pseudo standard for webforms.
779 * @see cleanText() for 2unix conversion
780 * @author Andreas Gohr <andi@splitbrain.org>
782 function formText($text){
783 $text = str_replace("\012","\015\012",$text);
784 return htmlspecialchars($text);
788 * Returns the specified local text in raw format
790 * @author Andreas Gohr <andi@splitbrain.org>
792 function rawLocale($id){
793 return io_readFile(localeFN($id));
797 * Returns the raw WikiText
799 * @author Andreas Gohr <andi@splitbrain.org>
801 function rawWiki($id,$rev=''){
802 return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
806 * Returns the pagetemplate contents for the ID's namespace
808 * @triggers COMMON_PAGETPL_LOAD
809 * @author Andreas Gohr <andi@splitbrain.org>
811 function pageTemplate($id){
814 if (is_array($id)) $id = $id[0];
816 // prepare initial event data
818 'id' => $id, // the id of the page to be created
819 'tpl' => '', // the text used as template
820 'tplfile' => '', // the file above text was/should be loaded from
821 'doreplace' => true // should wildcard replacements be done on the text?
824 $evt = new Doku_Event('COMMON_PAGETPL_LOAD',$data);
825 if($evt->advise_before(true)){
826 // the before event might have loaded the content already
827 if(empty($data['tpl'])){
828 // if the before event did not set a template file, try to find one
829 if(empty($data['tplfile'])){
830 $path = dirname(wikiFN($id));
832 if(@file_exists($path.'/_template.txt')){
833 $data['tplfile'] = $path.'/_template.txt';
835 // search upper namespaces for templates
836 $len = strlen(rtrim($conf['datadir'],'/'));
837 while (strlen($path) >= $len){
838 if(@file_exists($path.'/__template.txt')){
839 $data['tplfile'] = $path.'/__template.txt';
842 $path = substr($path, 0, strrpos($path, '/'));
847 $data['tpl'] = io_readFile($data['tplfile']);
849 if($data['doreplace']) parsePageTemplate($data);
851 $evt->advise_after();
858 * Performs common page template replacements
859 * This works on data from COMMON_PAGETPL_LOAD
861 * @author Andreas Gohr <andi@splitbrain.org>
863 function parsePageTemplate(&$data) {
869 // replace placeholders
871 $page = strtr($file, $conf['sepchar'], ' ');
873 $tpl = str_replace(array(
893 utf8_strtoupper($file),
897 utf8_strtoupper($page),
898 $_SERVER['REMOTE_USER'],
904 // we need the callback to work around strftime's char limit
905 $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
911 * Returns the raw Wiki Text in three slices.
913 * The range parameter needs to have the form "from-to"
914 * and gives the range of the section in bytes - no
915 * UTF-8 awareness is needed.
916 * The returned order is prefix, section and suffix.
918 * @author Andreas Gohr <andi@splitbrain.org>
920 function rawWikiSlices($range,$id,$rev=''){
921 $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
924 list($from,$to) = explode('-',$range,2);
925 // Make range zero-based, use defaults if marker is missing
926 $from = !$from ? 0 : ($from - 1);
927 $to = !$to ? strlen($text) : ($to - 1);
929 $slices[0] = substr($text, 0, $from);
930 $slices[1] = substr($text, $from, $to-$from);
931 $slices[2] = substr($text, $to);
936 * Joins wiki text slices
938 * function to join the text slices.
939 * When the pretty parameter is set to true it adds additional empty
940 * lines between sections if needed (used on saving).
942 * @author Andreas Gohr <andi@splitbrain.org>
944 function con($pre,$text,$suf,$pretty=false){
946 if ($pre !== '' && substr($pre, -1) !== "\n" &&
947 substr($text, 0, 1) !== "\n") {
950 if ($suf !== '' && substr($text, -1) !== "\n" &&
951 substr($suf, 0, 1) !== "\n") {
956 return $pre.$text.$suf;
960 * Saves a wikitext by calling io_writeWikiPage.
961 * Also directs changelog and attic updates.
963 * @author Andreas Gohr <andi@splitbrain.org>
964 * @author Ben Coburn <btcoburn@silicodon.net>
966 function saveWikiText($id,$text,$summary,$minor=false){
967 /* Note to developers:
968 This code is subtle and delicate. Test the behavior of
969 the attic and changelog with dokuwiki and external edits
970 after any changes. External edits change the wiki page
971 directly without using php or dokuwiki.
976 // ignore if no changes were made
977 if($text == rawWiki($id,'')){
982 $old = @filemtime($file); // from page
983 $wasRemoved = (trim($text) == ''); // check for empty or whitespace only
984 $wasCreated = !@file_exists($file);
985 $wasReverted = ($REV==true);
987 $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
988 $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
989 if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
990 // add old revision to the attic if missing
991 saveOldRevision($id);
992 // add a changelog entry if this edit came from outside dokuwiki
994 addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
995 // remove soon to be stale instructions
996 $cache = new cache_instructions($id, $file);
997 $cache->removeCache();
1002 // Send "update" event with empty data, so plugins can react to page deletion
1003 $data = array(array($file, '', false), getNS($id), noNS($id), false);
1004 trigger_event('IO_WIKIPAGE_WRITE', $data);
1005 // pre-save deleted revision
1008 $newRev = saveOldRevision($id);
1009 // remove empty file
1011 // don't remove old meta info as it should be saved, plugins can use IO_WIKIPAGE_WRITE for removing their metadata...
1012 // purge non-persistant meta data
1013 p_purge_metadata($id);
1015 // autoset summary on deletion
1016 if(empty($summary)) $summary = $lang['deleted'];
1017 // remove empty namespaces
1018 io_sweepNS($id, 'datadir');
1019 io_sweepNS($id, 'mediadir');
1021 // save file (namespace dir is created in io_writeWikiPage)
1022 io_writeWikiPage($file, $text, $id);
1023 // pre-save the revision, to keep the attic in sync
1024 $newRev = saveOldRevision($id);
1028 // select changelog line type
1030 $type = DOKU_CHANGE_TYPE_EDIT;
1032 $type = DOKU_CHANGE_TYPE_REVERT;
1035 else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
1036 else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
1037 else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
1039 addLogEntry($newRev, $id, $type, $summary, $extra);
1040 // send notify mails
1041 notify($id,'admin',$old,$summary,$minor);
1042 notify($id,'subscribers',$old,$summary,$minor);
1044 // update the purgefile (timestamp of the last time anything within the wiki was changed)
1045 io_saveFile($conf['cachedir'].'/purgefile',time());
1047 // if useheading is enabled, purge the cache of all linking pages
1048 if(useHeading('content')){
1049 $pages = ft_backlinks($id);
1050 foreach ($pages as $page) {
1051 $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1052 $cache->removeCache();
1058 * moves the current version to the attic and returns its
1061 * @author Andreas Gohr <andi@splitbrain.org>
1063 function saveOldRevision($id){
1065 $oldf = wikiFN($id);
1066 if(!@file_exists($oldf)) return '';
1067 $date = filemtime($oldf);
1068 $newf = wikiFN($id,$date);
1069 io_writeWikiPage($newf, rawWiki($id), $id, $date);
1074 * Sends a notify mail on page change or registration
1076 * @param string $id The changed page
1077 * @param string $who Who to notify (admin|subscribers|register)
1078 * @param int $rev Old page revision
1079 * @param string $summary What changed
1080 * @param boolean $minor Is this a minor edit?
1081 * @param array $replace Additional string substitutions, @KEY@ to be replaced by value
1083 * @author Andreas Gohr <andi@splitbrain.org>
1085 function notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1090 // decide if there is something to do
1091 if($who == 'admin'){
1092 if(empty($conf['notify'])) return; //notify enabled?
1093 $text = rawLocale('mailtext');
1094 $to = $conf['notify'];
1096 }elseif($who == 'subscribers'){
1097 if(!$conf['subscribers']) return; //subscribers enabled?
1098 if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
1099 $data = array('id' => $id, 'addresslist' => '', 'self' => false);
1100 trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data,
1101 'subscription_addresslist');
1102 $bcc = $data['addresslist'];
1103 if(empty($bcc)) return;
1105 $text = rawLocale('subscr_single');
1106 }elseif($who == 'register'){
1107 if(empty($conf['registernotify'])) return;
1108 $text = rawLocale('registermail');
1109 $to = $conf['registernotify'];
1112 return; //just to be safe
1116 $text = str_replace('@DATE@',dformat(),$text);
1117 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
1118 $text = str_replace('@IPADDRESS@',$ip,$text);
1119 $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1120 $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
1121 $text = str_replace('@PAGE@',$id,$text);
1122 $text = str_replace('@TITLE@',$conf['title'],$text);
1123 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1124 $text = str_replace('@SUMMARY@',$summary,$text);
1125 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1126 $text = str_replace('@NAME@',$INFO['userinfo']['name'],$text);
1127 $text = str_replace('@MAIL@',$INFO['userinfo']['mail'],$text);
1129 foreach ($replace as $key => $substitution) {
1130 $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
1133 if($who == 'register'){
1134 $subject = $lang['mail_new_user'].' '.$summary;
1136 $subject = $lang['mail_changed'].' '.$id;
1137 $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1138 $df = new Diff(explode("\n",rawWiki($id,$rev)),
1139 explode("\n",rawWiki($id)));
1140 $dformat = new UnifiedDiffFormatter();
1141 $diff = $dformat->format($df);
1143 $subject=$lang['mail_newpage'].' '.$id;
1144 $text = str_replace('@OLDPAGE@','none',$text);
1145 $diff = rawWiki($id);
1147 $text = str_replace('@DIFF@',$diff,$text);
1148 if(empty($conf['mailprefix'])) {
1149 if(utf8_strlen($conf['title']) < 20) {
1150 $subject = '['.$conf['title'].'] '.$subject;
1152 $subject = '['.utf8_substr($conf['title'], 0, 20).'...] '.$subject;
1155 $subject = '['.$conf['mailprefix'].'] '.$subject;
1157 mail_send($to,$subject,$text,$conf['mailfrom'],'',$bcc);
1161 * extracts the query from a search engine referrer
1163 * @author Andreas Gohr <andi@splitbrain.org>
1164 * @author Todd Augsburger <todd@rollerorgans.com>
1166 function getGoogleQuery(){
1167 if (!isset($_SERVER['HTTP_REFERER'])) {
1170 $url = parse_url($_SERVER['HTTP_REFERER']);
1174 // temporary workaround against PHP bug #49733
1175 // see http://bugs.php.net/bug.php?id=49733
1176 if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1177 parse_str($url['query'],$query);
1178 if(UTF8_MBSTRING) mb_internal_encoding($enc);
1181 if(isset($query['q']))
1182 $q = $query['q']; // google, live/msn, aol, ask, altavista, alltheweb, gigablast
1183 elseif(isset($query['p']))
1184 $q = $query['p']; // yahoo
1185 elseif(isset($query['query']))
1186 $q = $query['query']; // lycos, netscape, clusty, hotbot
1187 elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1188 $q = urldecode(ltrim($url['path'],'/'));
1190 if($q === '') return '';
1191 $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1196 * Try to set correct locale
1198 * @deprecated No longer used
1199 * @author Andreas Gohr <andi@splitbrain.org>
1201 function setCorrectLocale(){
1205 $enc = strtoupper($lang['encoding']);
1206 foreach ($lang['locales'] as $loc){
1208 if(@setlocale(LC_ALL,$loc)) return;
1209 //try loceale with encoding
1210 if(@setlocale(LC_ALL,"$loc.$enc")) return;
1212 //still here? try to set from environment
1213 @setlocale(LC_ALL,"");
1217 * Return the human readable size of a file
1219 * @param int $size A file size
1220 * @param int $dec A number of decimal places
1221 * @author Martin Benjamin <b.martin@cybernet.ch>
1222 * @author Aidan Lister <aidan@php.net>
1225 function filesize_h($size, $dec = 1){
1226 $sizes = array('B', 'KB', 'MB', 'GB');
1227 $count = count($sizes);
1230 while ($size >= 1024 && ($i < $count - 1)) {
1235 return round($size, $dec) . ' ' . $sizes[$i];
1239 * Return the given timestamp as human readable, fuzzy age
1241 * @author Andreas Gohr <gohr@cosmocode.de>
1243 function datetime_h($dt){
1246 $ago = time() - $dt;
1247 if($ago > 24*60*60*30*12*2){
1248 return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1250 if($ago > 24*60*60*30*2){
1251 return sprintf($lang['months'], round($ago/(24*60*60*30)));
1253 if($ago > 24*60*60*7*2){
1254 return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1256 if($ago > 24*60*60*2){
1257 return sprintf($lang['days'], round($ago/(24*60*60)));
1260 return sprintf($lang['hours'], round($ago/(60*60)));
1263 return sprintf($lang['minutes'], round($ago/(60)));
1265 return sprintf($lang['seconds'], $ago);
1269 * Wraps around strftime but provides support for fuzzy dates
1271 * The format default to $conf['dformat']. It is passed to
1272 * strftime - %f can be used to get the value from datetime_h()
1275 * @author Andreas Gohr <gohr@cosmocode.de>
1277 function dformat($dt=null,$format=''){
1280 if(is_null($dt)) $dt = time();
1282 if(!$format) $format = $conf['dformat'];
1284 $format = str_replace('%f',datetime_h($dt),$format);
1285 return strftime($format,$dt);
1289 * Formats a timestamp as ISO 8601 date
1291 * @author <ungu at terong dot com>
1292 * @link http://www.php.net/manual/en/function.date.php#54072
1294 function date_iso8601($int_date) {
1295 //$int_date: current date in UNIX timestamp
1296 $date_mod = date('Y-m-d\TH:i:s', $int_date);
1297 $pre_timezone = date('O', $int_date);
1298 $time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1299 $date_mod .= $time_zone;
1304 * return an obfuscated email address in line with $conf['mailguard'] setting
1306 * @author Harry Fuecks <hfuecks@gmail.com>
1307 * @author Christopher Smith <chris@jalakai.co.uk>
1309 function obfuscate($email) {
1312 switch ($conf['mailguard']) {
1314 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1315 return strtr($email, $obfuscate);
1319 $len = strlen($email);
1320 for ($x=0; $x < $len; $x++){
1321 $encode .= '&#x' . bin2hex($email{$x}).';';
1332 * Removes quoting backslashes
1334 * @author Andreas Gohr <andi@splitbrain.org>
1336 function unslash($string,$char="'"){
1337 return str_replace('\\'.$char,$char,$string);
1341 * Convert php.ini shorthands to byte
1343 * @author <gilthans dot NO dot SPAM at gmail dot com>
1344 * @link http://de3.php.net/manual/en/ini.core.php#79564
1346 function php_to_byte($v){
1347 $l = substr($v, -1);
1348 $ret = substr($v, 0, -1);
1349 switch(strtoupper($l)){
1369 * Wrapper around preg_quote adding the default delimiter
1371 function preg_quote_cb($string){
1372 return preg_quote($string,'/');
1376 * Shorten a given string by removing data from the middle
1378 * You can give the string in two parts, the first part $keep
1379 * will never be shortened. The second part $short will be cut
1380 * in the middle to shorten but only if at least $min chars are
1381 * left to display it. Otherwise it will be left off.
1383 * @param string $keep the part to keep
1384 * @param string $short the part to shorten
1385 * @param int $max maximum chars you want for the whole string
1386 * @param int $min minimum number of chars to have left for middle shortening
1387 * @param string $char the shortening character to use
1389 function shorten($keep,$short,$max,$min=9,$char='…'){
1390 $max = $max - utf8_strlen($keep);
1391 if($max < $min) return $keep;
1392 $len = utf8_strlen($short);
1393 if($len <= $max) return $keep.$short;
1394 $half = floor($max/2);
1395 return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1399 * Return the users realname or e-mail address for use
1400 * in page footer and recent changes pages
1402 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1404 function editorinfo($username){
1408 switch($conf['showuseras']){
1412 if($auth) $info = $auth->getUserData($username);
1415 return hsc($username);
1418 if(isset($info) && $info) {
1419 switch($conf['showuseras']){
1421 return hsc($info['name']);
1423 return obfuscate($info['mail']);
1425 $mail=obfuscate($info['mail']);
1426 return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1428 return hsc($username);
1431 return hsc($username);
1436 * Returns the path to a image file for the currently chosen license.
1437 * When no image exists, returns an empty string
1439 * @author Andreas Gohr <andi@splitbrain.org>
1440 * @param string $type - type of image 'badge' or 'button'
1442 function license_img($type){
1445 if(!$conf['license']) return '';
1446 if(!is_array($license[$conf['license']])) return '';
1447 $lic = $license[$conf['license']];
1449 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1450 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1451 if(substr($conf['license'],0,3) == 'cc-'){
1452 $try[] = 'lib/images/license/'.$type.'/cc.png';
1454 foreach($try as $src){
1455 if(@file_exists(DOKU_INC.$src)) return $src;
1461 * Checks if the given amount of memory is available
1463 * If the memory_get_usage() function is not available the
1464 * function just assumes $bytes of already allocated memory
1466 * @param int $mem Size of memory you want to allocate in bytes
1467 * @param int $used already allocated memory (see above)
1468 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1469 * @author Andreas Gohr <andi@splitbrain.org>
1471 function is_mem_available($mem,$bytes=1048576){
1472 $limit = trim(ini_get('memory_limit'));
1473 if(empty($limit)) return true; // no limit set!
1475 // parse limit to bytes
1476 $limit = php_to_byte($limit);
1478 // get used memory if possible
1479 if(function_exists('memory_get_usage')){
1480 $used = memory_get_usage();
1485 if($used+$mem > $limit){
1493 * Send a HTTP redirect to the browser
1495 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1497 * @link http://support.microsoft.com/kb/q176113/
1498 * @author Andreas Gohr <andi@splitbrain.org>
1500 function send_redirect($url){
1501 //are there any undisplayed messages? keep them in session for display
1503 if (isset($MSG) && count($MSG) && !defined('NOSESSION')){
1504 //reopen session, store data and close session again
1506 $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1509 // always close the session
1510 session_write_close();
1512 // work around IE bug
1513 // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1514 list($url,$hash) = explode('#',$url);
1516 if(strpos($url,'?')){
1517 $url = $url.'&#'.$hash;
1519 $url = $url.'?&#'.$hash;
1523 // check if running on IIS < 6 with CGI-PHP
1524 if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1525 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1526 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1528 header('Refresh: 0;url='.$url);
1530 header('Location: '.$url);
1536 * Validate a value using a set of valid values
1538 * This function checks whether a specified value is set and in the array
1539 * $valid_values. If not, the function returns a default value or, if no
1540 * default is specified, throws an exception.
1542 * @param string $param The name of the parameter
1543 * @param array $valid_values A set of valid values; Optionally a default may
1544 * be marked by the key “default”.
1545 * @param array $array The array containing the value (typically $_POST
1547 * @param string $exc The text of the raised exception
1549 * @author Adrian Lang <lang@cosmocode.de>
1551 function valid_input_set($param, $valid_values, $array, $exc = '') {
1552 if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
1553 return $array[$param];
1554 } elseif (isset($valid_values['default'])) {
1555 return $valid_values['default'];
1557 throw new Exception($exc);
1561 function get_doku_pref($pref, $default) {
1562 if (strpos($_COOKIE['DOKU_PREFS'], $pref) !== false) {
1563 $parts = explode('#', $_COOKIE['DOKU_PREFS']);
1564 for ($i = 0; $i < count($parts); $i+=2){
1565 if ($parts[$i] == $pref) {
1566 return $parts[$i+1];
1573 //Setup VIM: ex: et ts=2 :