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.');
10 require_once(DOKU_INC
.'inc/io.php');
11 require_once(DOKU_INC
.'inc/changelog.php');
12 require_once(DOKU_INC
.'inc/utf8.php');
13 require_once(DOKU_INC
.'inc/mail.php');
14 require_once(DOKU_INC
.'inc/parserutils.php');
15 require_once(DOKU_INC
.'inc/infoutils.php');
16 require_once DOKU_INC
.'inc/subscription.php';
19 * These constants are used with the recents function
21 define('RECENTS_SKIP_DELETED',2);
22 define('RECENTS_SKIP_MINORS',4);
23 define('RECENTS_SKIP_SUBSPACES',8);
24 define('RECENTS_MEDIA_CHANGES',16);
27 * Wrapper around htmlspecialchars()
29 * @author Andreas Gohr <andi@splitbrain.org>
30 * @see htmlspecialchars()
32 function hsc($string){
33 return htmlspecialchars($string, ENT_QUOTES
, 'UTF-8');
37 * print a newline terminated string
39 * You can give an indention as optional parameter
41 * @author Andreas Gohr <andi@splitbrain.org>
43 function ptln($string,$indent=0){
44 echo str_repeat(' ', $indent)."$string\n";
48 * strips control characters (<32) from the given string
50 * @author Andreas Gohr <andi@splitbrain.org>
52 function stripctl($string){
53 return preg_replace('/[\x00-\x1F]+/s','',$string);
57 * Return a secret token to be used for CSRF attack prevention
59 * @author Andreas Gohr <andi@splitbrain.org>
60 * @link http://en.wikipedia.org/wiki/Cross-site_request_forgery
61 * @link http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
64 function getSecurityToken(){
65 return md5(auth_cookiesalt().session_id());
69 * Check the secret CSRF token
71 function checkSecurityToken($token=null){
72 if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
74 if(is_null($token)) $token = $_REQUEST['sectok'];
75 if(getSecurityToken() != $token){
76 msg('Security Token did not match. Possible CSRF attack.',-1);
83 * Print a hidden form field with a secret CSRF token
85 * @author Andreas Gohr <andi@splitbrain.org>
87 function formSecurityToken($print=true){
88 $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
97 * Return info about the current document as associative
100 * @author Andreas Gohr <andi@splitbrain.org>
110 // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
111 // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
115 // set info about manager/admin status.
116 $info['isadmin'] = false;
117 $info['ismanager'] = false;
118 if(isset($_SERVER['REMOTE_USER'])){
119 $info['userinfo'] = $USERINFO;
120 $info['perm'] = auth_quickaclcheck($ID);
121 $info['subscribed'] = get_info_subscribed();
122 $info['client'] = $_SERVER['REMOTE_USER'];
124 if($info['perm'] == AUTH_ADMIN
){
125 $info['isadmin'] = true;
126 $info['ismanager'] = true;
127 }elseif(auth_ismanager()){
128 $info['ismanager'] = true;
131 // if some outside auth were used only REMOTE_USER is set
132 if(!$info['userinfo']['name']){
133 $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
137 $info['perm'] = auth_aclcheck($ID,'',null);
138 $info['subscribed'] = false;
139 $info['client'] = clientIP(true);
142 $info['namespace'] = getNS($ID);
143 $info['locked'] = checklock($ID);
144 $info['filepath'] = fullpath(wikiFN($ID));
145 $info['exists'] = @file_exists
($info['filepath']);
147 //check if current revision was meant
148 if($info['exists'] && (@filemtime
($info['filepath'])==$REV)){
151 //section editing does not work with old revisions!
154 msg($lang['nosecedit'],0);
156 //really use old revision
157 $info['filepath'] = fullpath(wikiFN($ID,$REV));
158 $info['exists'] = @file_exists
($info['filepath']);
163 $info['writable'] = (is_writable($info['filepath']) &&
164 ($info['perm'] >= AUTH_EDIT
));
166 $info['writable'] = ($info['perm'] >= AUTH_CREATE
);
168 $info['editable'] = ($info['writable'] && empty($info['lock']));
169 $info['lastmod'] = @filemtime
($info['filepath']);
171 //load page meta data
172 $info['meta'] = p_get_metadata($ID);
176 $revinfo = getRevisionInfo($ID, $REV, 1024);
178 if (is_array($info['meta']['last_change'])) {
179 $revinfo = $info['meta']['last_change'];
181 $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
182 // cache most recent changelog line in metadata if missing and still valid
183 if ($revinfo!==false) {
184 $info['meta']['last_change'] = $revinfo;
185 p_set_metadata($ID, array('last_change' => $revinfo));
189 //and check for an external edit
190 if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
191 // cached changelog line no longer valid
193 $info['meta']['last_change'] = $revinfo;
194 p_set_metadata($ID, array('last_change' => $revinfo));
197 $info['ip'] = $revinfo['ip'];
198 $info['user'] = $revinfo['user'];
199 $info['sum'] = $revinfo['sum'];
200 // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
201 // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
203 if($revinfo['user']){
204 $info['editor'] = $revinfo['user'];
206 $info['editor'] = $revinfo['ip'];
210 $draft = getCacheName($info['client'].$ID,'.draft');
211 if(@file_exists
($draft)){
212 if(@filemtime
($draft) < @filemtime
(wikiFN($ID))){
213 // remove stale draft
216 $info['draft'] = $draft;
221 $info['ismobile'] = clientismobile();
227 * Build an string of URL parameters
229 * @author Andreas Gohr
231 function buildURLparams($params, $sep='&'){
234 foreach($params as $key => $val){
235 if($amp) $url .= $sep;
238 $url .= rawurlencode((string)$val);
245 * Build an string of html tag attributes
247 * Skips keys starting with '_', values get HTML encoded
249 * @author Andreas Gohr
251 function buildAttributes($params,$skipempty=false){
253 foreach($params as $key => $val){
254 if($key{0} == '_') continue;
255 if($val === '' && $skipempty) continue;
258 $url .= htmlspecialchars ($val);
266 * This builds the breadcrumb trail and returns it as array
268 * @author Andreas Gohr <andi@splitbrain.org>
270 function breadcrumbs(){
271 // we prepare the breadcrumbs early for quick session closing
272 static $crumbs = null;
273 if($crumbs != null) return $crumbs;
280 $crumbs = isset($_SESSION[DOKU_COOKIE
]['bc']) ?
$_SESSION[DOKU_COOKIE
]['bc'] : array();
281 //we only save on show and existing wiki documents
283 if($ACT != 'show' ||
!@file_exists
($file)){
284 $_SESSION[DOKU_COOKIE
]['bc'] = $crumbs;
289 $name = noNSorNS($ID);
290 if (useHeading('navigation')) {
292 $title = p_get_first_heading($ID,true);
298 //remove ID from array
299 if (isset($crumbs[$ID])) {
304 $crumbs[$ID] = $name;
306 while(count($crumbs) > $conf['breadcrumbs']){
307 array_shift($crumbs);
310 $_SESSION[DOKU_COOKIE
]['bc'] = $crumbs;
315 * Filter for page IDs
317 * This is run on a ID before it is outputted somewhere
318 * currently used to replace the colon with something else
319 * on Windows systems and to have proper URL encoding
321 * Urlencoding is ommitted when the second parameter is false
323 * @author Andreas Gohr <andi@splitbrain.org>
325 function idfilter($id,$ue=true){
327 if ($conf['useslash'] && $conf['userewrite']){
328 $id = strtr($id,':','/');
329 }elseif (strtoupper(substr(PHP_OS
, 0, 3)) === 'WIN' &&
330 $conf['userewrite']) {
331 $id = strtr($id,':',';');
334 $id = rawurlencode($id);
335 $id = str_replace('%3A',':',$id); //keep as colon
336 $id = str_replace('%2F','/',$id); //keep as slash
342 * This builds a link to a wikipage
344 * It handles URL rewriting and adds additional parameter if
347 * @author Andreas Gohr <andi@splitbrain.org>
349 function wl($id='',$more='',$abs=false,$sep='&'){
352 $more = buildURLparams($more,$sep);
354 $more = str_replace(',',$sep,$more);
364 if($conf['userewrite'] == 2){
365 $xlink .= DOKU_SCRIPT
.'/'.$id;
366 if($more) $xlink .= '?'.$more;
367 }elseif($conf['userewrite']){
369 if($more) $xlink .= '?'.$more;
371 $xlink .= DOKU_SCRIPT
.'?id='.$id;
372 if($more) $xlink .= $sep.$more;
374 $xlink .= DOKU_SCRIPT
;
375 if($more) $xlink .= '?'.$more;
382 * This builds a link to an alternate page format
384 * Handles URL rewriting if enabled. Follows the style of wl().
386 * @author Ben Coburn <btcoburn@silicodon.net>
388 function exportlink($id='',$format='raw',$more='',$abs=false,$sep='&'){
391 $more = buildURLparams($more,$sep);
393 $more = str_replace(',',$sep,$more);
396 $format = rawurlencode($format);
404 if($conf['userewrite'] == 2){
405 $xlink .= DOKU_SCRIPT
.'/'.$id.'?do=export_'.$format;
406 if($more) $xlink .= $sep.$more;
407 }elseif($conf['userewrite'] == 1){
408 $xlink .= '_export/'.$format.'/'.$id;
409 if($more) $xlink .= '?'.$more;
411 $xlink .= DOKU_SCRIPT
.'?do=export_'.$format.$sep.'id='.$id;
412 if($more) $xlink .= $sep.$more;
419 * Build a link to a media file
421 * Will return a link to the detail page if $direct is false
423 * The $more parameter should always be given as array, the function then
424 * will strip default parameters to produce even cleaner URLs
426 * @param string $id - the media file id or URL
427 * @param mixed $more - string or array with additional parameters
428 * @param boolean $direct - link to detail page if false
429 * @param string $sep - URL parameter separator
430 * @param boolean $abs - Create an absolute URL
432 function ml($id='',$more='',$direct=true,$sep='&',$abs=false){
435 // strip defaults for shorter URLs
436 if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
437 if(!$more['w']) unset($more['w']);
438 if(!$more['h']) unset($more['h']);
439 if(isset($more['id']) && $direct) unset($more['id']);
440 $more = buildURLparams($more,$sep);
442 $more = str_replace('cache=cache','',$more); //skip default
443 $more = str_replace(',,',',',$more);
444 $more = str_replace(',',$sep,$more);
453 // external URLs are always direct without rewriting
454 if(preg_match('#^(https?|ftp)://#i',$id)){
455 $xlink .= 'lib/exe/fetch.php';
457 $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6);
459 $xlink .= $sep.$more;
460 $xlink .= $sep.'media='.rawurlencode($id);
462 $xlink .= $sep.'media='.rawurlencode($id);
469 // decide on scriptname
471 if($conf['userewrite'] == 1){
474 $script = 'lib/exe/fetch.php';
477 if($conf['userewrite'] == 1){
480 $script = 'lib/exe/detail.php';
484 // build URL based on rewrite mode
485 if($conf['userewrite']){
486 $xlink .= $script.'/'.$id;
487 if($more) $xlink .= '?'.$more;
490 $xlink .= $script.'?'.$more;
491 $xlink .= $sep.'media='.$id;
493 $xlink .= $script.'?media='.$id;
503 * Just builds a link to a script
505 * @todo maybe obsolete
506 * @author Andreas Gohr <andi@splitbrain.org>
508 function script($script='doku.php'){
509 return DOKU_BASE
.DOKU_SCRIPT
;
513 * Spamcheck against wordlist
515 * Checks the wikitext against a list of blocked expressions
516 * returns true if the text contains any bad words
518 * Triggers COMMON_WORDBLOCK_BLOCKED
520 * Action Plugins can use this event to inspect the blocked data
521 * and gain information about the user who was blocked.
524 * data['matches'] - array of matches
525 * data['userinfo'] - information about the blocked user
527 * [user] - username (if logged in)
528 * [mail] - mail address (if logged in)
529 * [name] - real name (if logged in)
531 * @author Andreas Gohr <andi@splitbrain.org>
532 * @author Michael Klier <chi@chimeric.de>
533 * @param string $text - optional text to check, if not given the globals are used
534 * @return bool - true if a spam word was found
536 function checkwordblock($text=''){
543 if(!$conf['usewordblock']) return false;
545 if(!$text) $text = "$PRE $TEXT $SUF";
547 // we prepare the text a tiny bit to prevent spammers circumventing URL checks
548 $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
550 $wordblocks = getWordblocks();
551 // how many lines to read at once (to work around some PCRE limits)
552 if(version_compare(phpversion(),'4.3.0','<')){
553 // old versions of PCRE define a maximum of parenthesises even if no
554 // backreferences are used - the maximum is 99
555 // this is very bad performancewise and may even be too high still
558 // read file in chunks of 200 - this should work around the
559 // MAX_PATTERN_SIZE in modern PCRE
562 while($blocks = array_splice($wordblocks,0,$chunksize)){
564 // build regexp from blocks
565 foreach($blocks as $block){
566 $block = preg_replace('/#.*$/','',$block);
567 $block = trim($block);
568 if(empty($block)) continue;
571 if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
572 // prepare event data
573 $data['matches'] = $matches;
574 $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
575 if($_SERVER['REMOTE_USER']) {
576 $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
577 $data['userinfo']['name'] = $INFO['userinfo']['name'];
578 $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
580 $callback = create_function('', 'return true;');
581 return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
588 * Return the IP of the client
590 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
592 * It returns a comma separated list of IPs if the above mentioned
593 * headers are set. If the single parameter is set, it tries to return
594 * a routable public address, prefering the ones suplied in the X
597 * @param boolean $single If set only a single IP is returned
598 * @author Andreas Gohr <andi@splitbrain.org>
600 function clientIP($single=false){
602 $ip[] = $_SERVER['REMOTE_ADDR'];
603 if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
604 $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
605 if(!empty($_SERVER['HTTP_X_REAL_IP']))
606 $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
608 // some IPv4/v6 regexps borrowed from Feyd
609 // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
610 $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
611 $hex_digit = '[A-Fa-f0-9]';
612 $h16 = "{$hex_digit}{1,4}";
613 $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
614 $ls32 = "(?:$h16:$h16|$IPv4Address)";
616 "(?:(?:{$IPv4Address})|(?:".
617 "(?:$h16:){6}$ls32" .
618 "|::(?:$h16:){5}$ls32" .
619 "|(?:$h16)?::(?:$h16:){4}$ls32" .
620 "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
621 "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
622 "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
623 "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
624 "|(?:(?:$h16:){0,5}$h16)?::$h16" .
625 "|(?:(?:$h16:){0,6}$h16)?::" .
626 ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
628 // remove any non-IP stuff
631 for($i=0; $i<$cnt; $i++
){
632 if(preg_match("/^$IPv4Address$/",$ip[$i],$match) ||
preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
637 if(empty($ip[$i])) unset($ip[$i]);
639 $ip = array_values(array_unique($ip));
640 if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
642 if(!$single) return join(',',$ip);
644 // decide which IP to use, trying to avoid local addresses
645 $ip = array_reverse($ip);
647 if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
653 // still here? just use the first (last) address
658 * Check if the browser is on a mobile device
660 * Adapted from the example code at url below
662 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
664 function clientismobile(){
666 if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
668 if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
670 if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
672 $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';
674 if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
681 * Convert one or more comma separated IPs to hostnames
683 * @author Glen Harris <astfgl@iamnota.org>
684 * @returns a comma separated list of hostnames
686 function gethostsbyaddrs($ips){
688 $ips = explode(',',$ips);
691 foreach($ips as $ip){
692 $hosts[] = gethostbyaddr(trim($ip));
694 return join(',',$hosts);
696 return gethostbyaddr(trim($ips));
701 * Checks if a given page is currently locked.
703 * removes stale lockfiles
705 * @author Andreas Gohr <andi@splitbrain.org>
707 function checklock($id){
709 $lock = wikiLockFN($id);
712 if(!@file_exists
($lock)) return false;
715 if((time() - filemtime($lock)) > $conf['locktime']){
721 $ip = io_readFile($lock);
722 if( ($ip == clientIP()) ||
($ip == $_SERVER['REMOTE_USER']) ){
730 * Lock a page for editing
732 * @author Andreas Gohr <andi@splitbrain.org>
735 $lock = wikiLockFN($id);
736 if($_SERVER['REMOTE_USER']){
737 io_saveFile($lock,$_SERVER['REMOTE_USER']);
739 io_saveFile($lock,clientIP());
744 * Unlock a page if it was locked by the user
746 * @author Andreas Gohr <andi@splitbrain.org>
747 * @return bool true if a lock was removed
749 function unlock($id){
750 $lock = wikiLockFN($id);
751 if(@file_exists
($lock)){
752 $ip = io_readFile($lock);
753 if( ($ip == clientIP()) ||
($ip == $_SERVER['REMOTE_USER']) ){
762 * convert line ending to unix format
764 * @see formText() for 2crlf conversion
765 * @author Andreas Gohr <andi@splitbrain.org>
767 function cleanText($text){
768 $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
773 * Prepares text for print in Webforms by encoding special chars.
774 * It also converts line endings to Windows format which is
775 * pseudo standard for webforms.
777 * @see cleanText() for 2unix conversion
778 * @author Andreas Gohr <andi@splitbrain.org>
780 function formText($text){
781 $text = str_replace("\012","\015\012",$text);
782 return htmlspecialchars($text);
786 * Returns the specified local text in raw format
788 * @author Andreas Gohr <andi@splitbrain.org>
790 function rawLocale($id){
791 return io_readFile(localeFN($id));
795 * Returns the raw WikiText
797 * @author Andreas Gohr <andi@splitbrain.org>
799 function rawWiki($id,$rev=''){
800 return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
804 * Returns the pagetemplate contents for the ID's namespace
806 * @author Andreas Gohr <andi@splitbrain.org>
808 function pageTemplate($data){
812 $path = dirname(wikiFN($id));
814 if(@file_exists
($path.'/_template.txt')){
815 $tpl = io_readFile($path.'/_template.txt');
817 // search upper namespaces for templates
818 $len = strlen(rtrim($conf['datadir'],'/'));
819 while (strlen($path) >= $len){
820 if(@file_exists
($path.'/__template.txt')){
821 $tpl = io_readFile($path.'/__template.txt');
824 $path = substr($path, 0, strrpos($path, '/'));
827 return isset($tpl) ?
parsePageTemplate($tpl, $id) : '';
831 * Performs common page template replacements
833 * @author Andreas Gohr <andi@splitbrain.org>
835 function parsePageTemplate($tpl, $id) {
838 // replace placeholders
840 $page = strtr($file,'_',' ');
842 $tpl = str_replace(array(
862 utf8_strtoupper($file),
866 utf8_strtoupper($page),
867 $_SERVER['REMOTE_USER'],
873 // we need the callback to work around strftime's char limit
874 $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
880 * Returns the raw Wiki Text in three slices.
882 * The range parameter needs to have the form "from-to"
883 * and gives the range of the section in bytes - no
884 * UTF-8 awareness is needed.
885 * The returned order is prefix, section and suffix.
887 * @author Andreas Gohr <andi@splitbrain.org>
889 function rawWikiSlices($range,$id,$rev=''){
890 list($from,$to) = explode('-',$range,2);
891 $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
892 if(!$from) $from = 0;
893 if(!$to) $to = strlen($text)+
1;
895 $slices[0] = substr($text,0,$from-1);
896 $slices[1] = substr($text,$from-1,$to-$from);
897 $slices[2] = substr($text,$to);
903 * Joins wiki text slices
905 * function to join the text slices with correct lineendings again.
906 * When the pretty parameter is set to true it adds additional empty
907 * lines between sections if needed (used on saving).
909 * @author Andreas Gohr <andi@splitbrain.org>
911 function con($pre,$text,$suf,$pretty=false){
913 if($pre && substr($pre,-1) != "\n") $pre .= "\n";
914 if($suf && substr($text,-1) != "\n") $text .= "\n";
917 // Avoid double newline above section when saving section edit
918 //if($pre) $pre .= "\n";
919 if($suf) $text .= "\n";
920 return $pre.$text.$suf;
924 * Saves a wikitext by calling io_writeWikiPage.
925 * Also directs changelog and attic updates.
927 * @author Andreas Gohr <andi@splitbrain.org>
928 * @author Ben Coburn <btcoburn@silicodon.net>
930 function saveWikiText($id,$text,$summary,$minor=false){
931 /* Note to developers:
932 This code is subtle and delicate. Test the behavior of
933 the attic and changelog with dokuwiki and external edits
934 after any changes. External edits change the wiki page
935 directly without using php or dokuwiki.
940 // ignore if no changes were made
941 if($text == rawWiki($id,'')){
946 $old = @filemtime
($file); // from page
947 $wasRemoved = empty($text);
948 $wasCreated = !@file_exists
($file);
949 $wasReverted = ($REV==true);
951 $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
952 $oldRev = (int)(empty($oldRev)?
0:$oldRev[0]);
953 if(!@file_exists
(wikiFN($id, $old)) && @file_exists
($file) && $old>=$oldRev) {
954 // add old revision to the attic if missing
955 saveOldRevision($id);
956 // add a changelog entry if this edit came from outside dokuwiki
958 addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT
, $lang['external_edit'], '', array('ExternalEdit'=>true));
959 // remove soon to be stale instructions
960 $cache = new cache_instructions($id, $file);
961 $cache->removeCache();
966 // Send "update" event with empty data, so plugins can react to page deletion
967 $data = array(array($file, '', false), getNS($id), noNS($id), false);
968 trigger_event('IO_WIKIPAGE_WRITE', $data);
969 // pre-save deleted revision
972 $newRev = saveOldRevision($id);
975 // remove old meta info...
976 $mfiles = metaFiles($id);
977 $changelog = metaFN($id, '.changes');
978 $metadata = metaFN($id, '.meta');
979 foreach ($mfiles as $mfile) {
980 // but keep per-page changelog to preserve page history and keep meta data
981 if (@file_exists
($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink
($mfile); }
984 p_purge_metadata($id);
986 // autoset summary on deletion
987 if(empty($summary)) $summary = $lang['deleted'];
988 // remove empty namespaces
989 io_sweepNS($id, 'datadir');
990 io_sweepNS($id, 'mediadir');
992 // save file (namespace dir is created in io_writeWikiPage)
993 io_writeWikiPage($file, $text, $id);
994 // pre-save the revision, to keep the attic in sync
995 $newRev = saveOldRevision($id);
999 // select changelog line type
1001 $type = DOKU_CHANGE_TYPE_EDIT
;
1003 $type = DOKU_CHANGE_TYPE_REVERT
;
1006 else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE
; }
1007 else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE
; }
1008 else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT
; } //minor edits only for logged in users
1010 addLogEntry($newRev, $id, $type, $summary, $extra);
1011 // send notify mails
1012 notify($id,'admin',$old,$summary,$minor);
1013 notify($id,'subscribers',$old,$summary,$minor);
1015 // update the purgefile (timestamp of the last time anything within the wiki was changed)
1016 io_saveFile($conf['cachedir'].'/purgefile',time());
1018 // if useheading is enabled, purge the cache of all linking pages
1019 if(useHeading('content')){
1020 require_once(DOKU_INC
.'inc/fulltext.php');
1021 $pages = ft_backlinks($id);
1022 foreach ($pages as $page) {
1023 $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1024 $cache->removeCache();
1030 * moves the current version to the attic and returns its
1033 * @author Andreas Gohr <andi@splitbrain.org>
1035 function saveOldRevision($id){
1037 $oldf = wikiFN($id);
1038 if(!@file_exists
($oldf)) return '';
1039 $date = filemtime($oldf);
1040 $newf = wikiFN($id,$date);
1041 io_writeWikiPage($newf, rawWiki($id), $id, $date);
1046 * Sends a notify mail on page change or registration
1048 * @param string $id The changed page
1049 * @param string $who Who to notify (admin|subscribers|register)
1050 * @param int $rev Old page revision
1051 * @param string $summary What changed
1052 * @param boolean $minor Is this a minor edit?
1053 * @param array $replace Additional string substitutions, @KEY@ to be replaced by value
1055 * @author Andreas Gohr <andi@splitbrain.org>
1057 function notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1062 // decide if there is something to do
1063 if($who == 'admin'){
1064 if(empty($conf['notify'])) return; //notify enabled?
1065 $text = rawLocale('mailtext');
1066 $to = $conf['notify'];
1068 }elseif($who == 'subscribers'){
1069 if(!$conf['subscribers']) return; //subscribers enabled?
1070 if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
1071 $data = array('id' => $id, 'addresslist' => '', 'self' => false);
1072 trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data,
1073 'subscription_addresslist');
1074 $bcc = $data['addresslist'];
1075 if(empty($bcc)) return;
1077 $text = rawLocale('subscr_single');
1078 }elseif($who == 'register'){
1079 if(empty($conf['registernotify'])) return;
1080 $text = rawLocale('registermail');
1081 $to = $conf['registernotify'];
1084 return; //just to be safe
1088 $text = str_replace('@DATE@',dformat(),$text);
1089 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
1090 $text = str_replace('@IPADDRESS@',$ip,$text);
1091 $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1092 $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
1093 $text = str_replace('@PAGE@',$id,$text);
1094 $text = str_replace('@TITLE@',$conf['title'],$text);
1095 $text = str_replace('@DOKUWIKIURL@',DOKU_URL
,$text);
1096 $text = str_replace('@SUMMARY@',$summary,$text);
1097 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1099 foreach ($replace as $key => $substitution) {
1100 $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
1103 if($who == 'register'){
1104 $subject = $lang['mail_new_user'].' '.$summary;
1106 $subject = $lang['mail_changed'].' '.$id;
1107 $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1108 require_once(DOKU_INC
.'inc/DifferenceEngine.php');
1109 $df = new Diff(explode("\n",rawWiki($id,$rev)),
1110 explode("\n",rawWiki($id)));
1111 $dformat = new UnifiedDiffFormatter();
1112 $diff = $dformat->format($df);
1114 $subject=$lang['mail_newpage'].' '.$id;
1115 $text = str_replace('@OLDPAGE@','none',$text);
1116 $diff = rawWiki($id);
1118 $text = str_replace('@DIFF@',$diff,$text);
1119 $subject = '['.$conf['title'].'] '.$subject;
1121 $from = $conf['mailfrom'];
1122 $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
1123 $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
1124 $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
1126 mail_send($to,$subject,$text,$from,'',$bcc);
1130 * extracts the query from a search engine referrer
1132 * @author Andreas Gohr <andi@splitbrain.org>
1133 * @author Todd Augsburger <todd@rollerorgans.com>
1135 function getGoogleQuery(){
1136 if (!isset($_SERVER['HTTP_REFERER'])) {
1139 $url = parse_url($_SERVER['HTTP_REFERER']);
1143 // temporary workaround against PHP bug #49733
1144 // see http://bugs.php.net/bug.php?id=49733
1145 if(UTF8_MBSTRING
) $enc = mb_internal_encoding();
1146 parse_str($url['query'],$query);
1147 if(UTF8_MBSTRING
) mb_internal_encoding($enc);
1150 if(isset($query['q']))
1151 $q = $query['q']; // google, live/msn, aol, ask, altavista, alltheweb, gigablast
1152 elseif(isset($query['p']))
1153 $q = $query['p']; // yahoo
1154 elseif(isset($query['query']))
1155 $q = $query['query']; // lycos, netscape, clusty, hotbot
1156 elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1157 $q = urldecode(ltrim($url['path'],'/'));
1159 if($q === '') return '';
1160 $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY
);
1165 * Try to set correct locale
1167 * @deprecated No longer used
1168 * @author Andreas Gohr <andi@splitbrain.org>
1170 function setCorrectLocale(){
1174 $enc = strtoupper($lang['encoding']);
1175 foreach ($lang['locales'] as $loc){
1177 if(@setlocale
(LC_ALL
,$loc)) return;
1178 //try loceale with encoding
1179 if(@setlocale
(LC_ALL
,"$loc.$enc")) return;
1181 //still here? try to set from environment
1182 @setlocale
(LC_ALL
,"");
1186 * Return the human readable size of a file
1188 * @param int $size A file size
1189 * @param int $dec A number of decimal places
1190 * @author Martin Benjamin <b.martin@cybernet.ch>
1191 * @author Aidan Lister <aidan@php.net>
1194 function filesize_h($size, $dec = 1){
1195 $sizes = array('B', 'KB', 'MB', 'GB');
1196 $count = count($sizes);
1199 while ($size >= 1024 && ($i < $count - 1)) {
1204 return round($size, $dec) . ' ' . $sizes[$i];
1208 * Return the given timestamp as human readable, fuzzy age
1210 * @author Andreas Gohr <gohr@cosmocode.de>
1212 function datetime_h($dt){
1215 $ago = time() - $dt;
1216 if($ago > 24*60*60*30*12*2){
1217 return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1219 if($ago > 24*60*60*30*2){
1220 return sprintf($lang['months'], round($ago/(24*60*60*30)));
1222 if($ago > 24*60*60*7*2){
1223 return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1225 if($ago > 24*60*60*2){
1226 return sprintf($lang['days'], round($ago/(24*60*60)));
1229 return sprintf($lang['hours'], round($ago/(60*60)));
1232 return sprintf($lang['minutes'], round($ago/(60)));
1234 return sprintf($lang['seconds'], $ago);
1238 * Wraps around strftime but provides support for fuzzy dates
1240 * The format default to $conf['dformat']. It is passed to
1241 * strftime - %f can be used to get the value from datetime_h()
1244 * @author Andreas Gohr <gohr@cosmocode.de>
1246 function dformat($dt=null,$format=''){
1249 if(is_null($dt)) $dt = time();
1251 if(!$format) $format = $conf['dformat'];
1253 $format = str_replace('%f',datetime_h($dt),$format);
1254 return strftime($format,$dt);
1258 * return an obfuscated email address in line with $conf['mailguard'] setting
1260 * @author Harry Fuecks <hfuecks@gmail.com>
1261 * @author Christopher Smith <chris@jalakai.co.uk>
1263 function obfuscate($email) {
1266 switch ($conf['mailguard']) {
1268 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1269 return strtr($email, $obfuscate);
1273 $len = strlen($email);
1274 for ($x=0; $x < $len; $x++
){
1275 $encode .= '&#x' . bin2hex($email{$x}).';';
1286 * Removes quoting backslashes
1288 * @author Andreas Gohr <andi@splitbrain.org>
1290 function unslash($string,$char="'"){
1291 return str_replace('\\'.$char,$char,$string);
1295 * Convert php.ini shorthands to byte
1297 * @author <gilthans dot NO dot SPAM at gmail dot com>
1298 * @link http://de3.php.net/manual/en/ini.core.php#79564
1300 function php_to_byte($v){
1301 $l = substr($v, -1);
1302 $ret = substr($v, 0, -1);
1303 switch(strtoupper($l)){
1320 * Wrapper around preg_quote adding the default delimiter
1322 function preg_quote_cb($string){
1323 return preg_quote($string,'/');
1327 * Shorten a given string by removing data from the middle
1329 * You can give the string in two parts, the first part $keep
1330 * will never be shortened. The second part $short will be cut
1331 * in the middle to shorten but only if at least $min chars are
1332 * left to display it. Otherwise it will be left off.
1334 * @param string $keep the part to keep
1335 * @param string $short the part to shorten
1336 * @param int $max maximum chars you want for the whole string
1337 * @param int $min minimum number of chars to have left for middle shortening
1338 * @param string $char the shortening character to use
1340 function shorten($keep,$short,$max,$min=9,$char='…'){
1341 $max = $max - utf8_strlen($keep);
1342 if($max < $min) return $keep;
1343 $len = utf8_strlen($short);
1344 if($len <= $max) return $keep.$short;
1345 $half = floor($max/2);
1346 return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1350 * Return the users realname or e-mail address for use
1351 * in page footer and recent changes pages
1353 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1355 function editorinfo($username){
1359 switch($conf['showuseras']){
1363 if($auth) $info = $auth->getUserData($username);
1366 return hsc($username);
1369 if(isset($info) && $info) {
1370 switch($conf['showuseras']){
1372 return hsc($info['name']);
1374 return obfuscate($info['mail']);
1376 $mail=obfuscate($info['mail']);
1377 return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1379 return hsc($username);
1382 return hsc($username);
1387 * Returns the path to a image file for the currently chosen license.
1388 * When no image exists, returns an empty string
1390 * @author Andreas Gohr <andi@splitbrain.org>
1391 * @param string $type - type of image 'badge' or 'button'
1393 function license_img($type){
1396 if(!$conf['license']) return '';
1397 if(!is_array($license[$conf['license']])) return '';
1398 $lic = $license[$conf['license']];
1400 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1401 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1402 if(substr($conf['license'],0,3) == 'cc-'){
1403 $try[] = 'lib/images/license/'.$type.'/cc.png';
1405 foreach($try as $src){
1406 if(@file_exists
(DOKU_INC
.$src)) return $src;
1412 * Checks if the given amount of memory is available
1414 * If the memory_get_usage() function is not available the
1415 * function just assumes $bytes of already allocated memory
1417 * @param int $mem Size of memory you want to allocate in bytes
1418 * @param int $used already allocated memory (see above)
1419 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1420 * @author Andreas Gohr <andi@splitbrain.org>
1422 function is_mem_available($mem,$bytes=1048576){
1423 $limit = trim(ini_get('memory_limit'));
1424 if(empty($limit)) return true; // no limit set!
1426 // parse limit to bytes
1427 $limit = php_to_byte($limit);
1429 // get used memory if possible
1430 if(function_exists('memory_get_usage')){
1431 $used = memory_get_usage();
1436 if($used+
$mem > $limit){
1444 * Send a HTTP redirect to the browser
1446 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1448 * @link http://support.microsoft.com/kb/q176113/
1449 * @author Andreas Gohr <andi@splitbrain.org>
1451 function send_redirect($url){
1452 // always close the session
1453 session_write_close();
1455 // check if running on IIS < 6 with CGI-PHP
1456 if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1457 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1458 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1460 header('Refresh: 0;url='.$url);
1462 header('Location: '.$url);
1468 * Validate a value using a set of valid values
1470 * This function checks whether a specified value is set and in the array
1471 * $valid_values. If not, the function returns a default value or, if no
1472 * default is specified, throws an exception.
1474 * @param string $param The name of the parameter
1475 * @param array $valid_values A set of valid values; Optionally a default may
1476 * be marked by the key “default”.
1477 * @param array $array The array containing the value (typically $_POST
1479 * @param string $exc The text of the raised exception
1481 * @author Adrian Lang <lang@cosmocode.de>
1483 function valid_input_set($param, $valid_values, $array, $exc = '') {
1484 if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
1485 return $array[$param];
1486 } elseif (isset($valid_values['default'])) {
1487 return $valid_values['default'];
1489 throw new Exception($exc);
1493 //Setup VIM: ex: et ts=2 enc=utf-8 :