Allow a prefix for subject of sent mails (Close FS#2021)
[dokuwiki.git] / inc / common.php
blob6ea6d56d8e0f5b30deab4250aa9bb44e778eba27
1 <?php
2 /**
3 * Common DokuWiki functions
5 * @license GPL 2 (http://www.gnu.org/licenses/gpl.html)
6 * @author Andreas Gohr <andi@splitbrain.org>
7 */
9 if(!defined('DOKU_INC')) die('meh.');
11 /**
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);
19 /**
20 * Wrapper around htmlspecialchars()
22 * @author Andreas Gohr <andi@splitbrain.org>
23 * @see htmlspecialchars()
25 function hsc($string){
26 return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
29 /**
30 * print a newline terminated string
32 * You can give an indention as optional parameter
34 * @author Andreas Gohr <andi@splitbrain.org>
36 function ptln($string,$indent=0){
37 echo str_repeat(' ', $indent)."$string\n";
40 /**
41 * strips control characters (<32) from the given string
43 * @author Andreas Gohr <andi@splitbrain.org>
45 function stripctl($string){
46 return preg_replace('/[\x00-\x1F]+/s','',$string);
49 /**
50 * Return a secret token to be used for CSRF attack prevention
52 * @author Andreas Gohr <andi@splitbrain.org>
53 * @link http://en.wikipedia.org/wiki/Cross-site_request_forgery
54 * @link http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
55 * @return string
57 function getSecurityToken(){
58 return md5(auth_cookiesalt().session_id());
61 /**
62 * Check the secret CSRF token
64 function checkSecurityToken($token=null){
65 if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
67 if(is_null($token)) $token = $_REQUEST['sectok'];
68 if(getSecurityToken() != $token){
69 msg('Security Token did not match. Possible CSRF attack.',-1);
70 return false;
72 return true;
75 /**
76 * Print a hidden form field with a secret CSRF token
78 * @author Andreas Gohr <andi@splitbrain.org>
80 function formSecurityToken($print=true){
81 $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
82 if($print){
83 echo $ret;
84 }else{
85 return $ret;
89 /**
90 * Return info about the current document as associative
91 * array.
93 * @author Andreas Gohr <andi@splitbrain.org>
95 function pageinfo(){
96 global $ID;
97 global $REV;
98 global $RANGE;
99 global $USERINFO;
100 global $lang;
102 // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
103 // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
104 $info['id'] = $ID;
105 $info['rev'] = $REV;
107 // set info about manager/admin status.
108 $info['isadmin'] = false;
109 $info['ismanager'] = false;
110 if(isset($_SERVER['REMOTE_USER'])){
111 $info['userinfo'] = $USERINFO;
112 $info['perm'] = auth_quickaclcheck($ID);
113 $info['subscribed'] = get_info_subscribed();
114 $info['client'] = $_SERVER['REMOTE_USER'];
116 if($info['perm'] == AUTH_ADMIN){
117 $info['isadmin'] = true;
118 $info['ismanager'] = true;
119 }elseif(auth_ismanager()){
120 $info['ismanager'] = true;
123 // if some outside auth were used only REMOTE_USER is set
124 if(!$info['userinfo']['name']){
125 $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
128 }else{
129 $info['perm'] = auth_aclcheck($ID,'',null);
130 $info['subscribed'] = false;
131 $info['client'] = clientIP(true);
134 $info['namespace'] = getNS($ID);
135 $info['locked'] = checklock($ID);
136 $info['filepath'] = fullpath(wikiFN($ID));
137 $info['exists'] = @file_exists($info['filepath']);
138 if($REV){
139 //check if current revision was meant
140 if($info['exists'] && (@filemtime($info['filepath'])==$REV)){
141 $REV = '';
142 }elseif($RANGE){
143 //section editing does not work with old revisions!
144 $REV = '';
145 $RANGE = '';
146 msg($lang['nosecedit'],0);
147 }else{
148 //really use old revision
149 $info['filepath'] = fullpath(wikiFN($ID,$REV));
150 $info['exists'] = @file_exists($info['filepath']);
153 $info['rev'] = $REV;
154 if($info['exists']){
155 $info['writable'] = (is_writable($info['filepath']) &&
156 ($info['perm'] >= AUTH_EDIT));
157 }else{
158 $info['writable'] = ($info['perm'] >= AUTH_CREATE);
160 $info['editable'] = ($info['writable'] && empty($info['locked']));
161 $info['lastmod'] = @filemtime($info['filepath']);
163 //load page meta data
164 $info['meta'] = p_get_metadata($ID);
166 //who's the editor
167 if($REV){
168 $revinfo = getRevisionInfo($ID, $REV, 1024);
169 }else{
170 if (is_array($info['meta']['last_change'])) {
171 $revinfo = $info['meta']['last_change'];
172 } else {
173 $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
174 // cache most recent changelog line in metadata if missing and still valid
175 if ($revinfo!==false) {
176 $info['meta']['last_change'] = $revinfo;
177 p_set_metadata($ID, array('last_change' => $revinfo));
181 //and check for an external edit
182 if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
183 // cached changelog line no longer valid
184 $revinfo = false;
185 $info['meta']['last_change'] = $revinfo;
186 p_set_metadata($ID, array('last_change' => $revinfo));
189 $info['ip'] = $revinfo['ip'];
190 $info['user'] = $revinfo['user'];
191 $info['sum'] = $revinfo['sum'];
192 // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
193 // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
195 if($revinfo['user']){
196 $info['editor'] = $revinfo['user'];
197 }else{
198 $info['editor'] = $revinfo['ip'];
201 // draft
202 $draft = getCacheName($info['client'].$ID,'.draft');
203 if(@file_exists($draft)){
204 if(@filemtime($draft) < @filemtime(wikiFN($ID))){
205 // remove stale draft
206 @unlink($draft);
207 }else{
208 $info['draft'] = $draft;
212 // mobile detection
213 $info['ismobile'] = clientismobile();
215 return $info;
219 * Build an string of URL parameters
221 * @author Andreas Gohr
223 function buildURLparams($params, $sep='&amp;'){
224 $url = '';
225 $amp = false;
226 foreach($params as $key => $val){
227 if($amp) $url .= $sep;
229 $url .= rawurlencode($key).'=';
230 $url .= rawurlencode((string)$val);
231 $amp = true;
233 return $url;
237 * Build an string of html tag attributes
239 * Skips keys starting with '_', values get HTML encoded
241 * @author Andreas Gohr
243 function buildAttributes($params,$skipempty=false){
244 $url = '';
245 foreach($params as $key => $val){
246 if($key{0} == '_') continue;
247 if($val === '' && $skipempty) continue;
249 $url .= $key.'="';
250 $url .= htmlspecialchars ($val);
251 $url .= '" ';
253 return $url;
258 * This builds the breadcrumb trail and returns it as array
260 * @author Andreas Gohr <andi@splitbrain.org>
262 function breadcrumbs(){
263 // we prepare the breadcrumbs early for quick session closing
264 static $crumbs = null;
265 if($crumbs != null) return $crumbs;
267 global $ID;
268 global $ACT;
269 global $conf;
271 //first visit?
272 $crumbs = isset($_SESSION[DOKU_COOKIE]['bc']) ? $_SESSION[DOKU_COOKIE]['bc'] : array();
273 //we only save on show and existing wiki documents
274 $file = wikiFN($ID);
275 if($ACT != 'show' || !@file_exists($file)){
276 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
277 return $crumbs;
280 // page names
281 $name = noNSorNS($ID);
282 if (useHeading('navigation')) {
283 // get page title
284 $title = p_get_first_heading($ID,true);
285 if ($title) {
286 $name = $title;
290 //remove ID from array
291 if (isset($crumbs[$ID])) {
292 unset($crumbs[$ID]);
295 //add to array
296 $crumbs[$ID] = $name;
297 //reduce size
298 while(count($crumbs) > $conf['breadcrumbs']){
299 array_shift($crumbs);
301 //save to session
302 $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
303 return $crumbs;
307 * Filter for page IDs
309 * This is run on a ID before it is outputted somewhere
310 * currently used to replace the colon with something else
311 * on Windows systems and to have proper URL encoding
313 * Urlencoding is ommitted when the second parameter is false
315 * @author Andreas Gohr <andi@splitbrain.org>
317 function idfilter($id,$ue=true){
318 global $conf;
319 if ($conf['useslash'] && $conf['userewrite']){
320 $id = strtr($id,':','/');
321 }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
322 $conf['userewrite']) {
323 $id = strtr($id,':',';');
325 if($ue){
326 $id = rawurlencode($id);
327 $id = str_replace('%3A',':',$id); //keep as colon
328 $id = str_replace('%2F','/',$id); //keep as slash
330 return $id;
334 * This builds a link to a wikipage
336 * It handles URL rewriting and adds additional parameter if
337 * given in $more
339 * @author Andreas Gohr <andi@splitbrain.org>
341 function wl($id='',$more='',$abs=false,$sep='&amp;'){
342 global $conf;
343 if(is_array($more)){
344 $more = buildURLparams($more,$sep);
345 }else{
346 $more = str_replace(',',$sep,$more);
349 $id = idfilter($id);
350 if($abs){
351 $xlink = DOKU_URL;
352 }else{
353 $xlink = DOKU_BASE;
356 if($conf['userewrite'] == 2){
357 $xlink .= DOKU_SCRIPT.'/'.$id;
358 if($more) $xlink .= '?'.$more;
359 }elseif($conf['userewrite']){
360 $xlink .= $id;
361 if($more) $xlink .= '?'.$more;
362 }elseif($id){
363 $xlink .= DOKU_SCRIPT.'?id='.$id;
364 if($more) $xlink .= $sep.$more;
365 }else{
366 $xlink .= DOKU_SCRIPT;
367 if($more) $xlink .= '?'.$more;
370 return $xlink;
374 * This builds a link to an alternate page format
376 * Handles URL rewriting if enabled. Follows the style of wl().
378 * @author Ben Coburn <btcoburn@silicodon.net>
380 function exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
381 global $conf;
382 if(is_array($more)){
383 $more = buildURLparams($more,$sep);
384 }else{
385 $more = str_replace(',',$sep,$more);
388 $format = rawurlencode($format);
389 $id = idfilter($id);
390 if($abs){
391 $xlink = DOKU_URL;
392 }else{
393 $xlink = DOKU_BASE;
396 if($conf['userewrite'] == 2){
397 $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
398 if($more) $xlink .= $sep.$more;
399 }elseif($conf['userewrite'] == 1){
400 $xlink .= '_export/'.$format.'/'.$id;
401 if($more) $xlink .= '?'.$more;
402 }else{
403 $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
404 if($more) $xlink .= $sep.$more;
407 return $xlink;
411 * Build a link to a media file
413 * Will return a link to the detail page if $direct is false
415 * The $more parameter should always be given as array, the function then
416 * will strip default parameters to produce even cleaner URLs
418 * @param string $id - the media file id or URL
419 * @param mixed $more - string or array with additional parameters
420 * @param boolean $direct - link to detail page if false
421 * @param string $sep - URL parameter separator
422 * @param boolean $abs - Create an absolute URL
424 function ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
425 global $conf;
426 if(is_array($more)){
427 // strip defaults for shorter URLs
428 if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
429 if(!$more['w']) unset($more['w']);
430 if(!$more['h']) unset($more['h']);
431 if(isset($more['id']) && $direct) unset($more['id']);
432 $more = buildURLparams($more,$sep);
433 }else{
434 $more = str_replace('cache=cache','',$more); //skip default
435 $more = str_replace(',,',',',$more);
436 $more = str_replace(',',$sep,$more);
439 if($abs){
440 $xlink = DOKU_URL;
441 }else{
442 $xlink = DOKU_BASE;
445 // external URLs are always direct without rewriting
446 if(preg_match('#^(https?|ftp)://#i',$id)){
447 $xlink .= 'lib/exe/fetch.php';
448 // add hash:
449 $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6);
450 if($more){
451 $xlink .= $sep.$more;
452 $xlink .= $sep.'media='.rawurlencode($id);
453 }else{
454 $xlink .= $sep.'media='.rawurlencode($id);
456 return $xlink;
459 $id = idfilter($id);
461 // decide on scriptname
462 if($direct){
463 if($conf['userewrite'] == 1){
464 $script = '_media';
465 }else{
466 $script = 'lib/exe/fetch.php';
468 }else{
469 if($conf['userewrite'] == 1){
470 $script = '_detail';
471 }else{
472 $script = 'lib/exe/detail.php';
476 // build URL based on rewrite mode
477 if($conf['userewrite']){
478 $xlink .= $script.'/'.$id;
479 if($more) $xlink .= '?'.$more;
480 }else{
481 if($more){
482 $xlink .= $script.'?'.$more;
483 $xlink .= $sep.'media='.$id;
484 }else{
485 $xlink .= $script.'?media='.$id;
489 return $xlink;
495 * Just builds a link to a script
497 * @todo maybe obsolete
498 * @author Andreas Gohr <andi@splitbrain.org>
500 function script($script='doku.php'){
501 return DOKU_BASE.DOKU_SCRIPT;
505 * Spamcheck against wordlist
507 * Checks the wikitext against a list of blocked expressions
508 * returns true if the text contains any bad words
510 * Triggers COMMON_WORDBLOCK_BLOCKED
512 * Action Plugins can use this event to inspect the blocked data
513 * and gain information about the user who was blocked.
515 * Event data:
516 * data['matches'] - array of matches
517 * data['userinfo'] - information about the blocked user
518 * [ip] - ip address
519 * [user] - username (if logged in)
520 * [mail] - mail address (if logged in)
521 * [name] - real name (if logged in)
523 * @author Andreas Gohr <andi@splitbrain.org>
524 * @author Michael Klier <chi@chimeric.de>
525 * @param string $text - optional text to check, if not given the globals are used
526 * @return bool - true if a spam word was found
528 function checkwordblock($text=''){
529 global $TEXT;
530 global $PRE;
531 global $SUF;
532 global $conf;
533 global $INFO;
535 if(!$conf['usewordblock']) return false;
537 if(!$text) $text = "$PRE $TEXT $SUF";
539 // we prepare the text a tiny bit to prevent spammers circumventing URL checks
540 $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
542 $wordblocks = getWordblocks();
543 // how many lines to read at once (to work around some PCRE limits)
544 if(version_compare(phpversion(),'4.3.0','<')){
545 // old versions of PCRE define a maximum of parenthesises even if no
546 // backreferences are used - the maximum is 99
547 // this is very bad performancewise and may even be too high still
548 $chunksize = 40;
549 }else{
550 // read file in chunks of 200 - this should work around the
551 // MAX_PATTERN_SIZE in modern PCRE
552 $chunksize = 200;
554 while($blocks = array_splice($wordblocks,0,$chunksize)){
555 $re = array();
556 // build regexp from blocks
557 foreach($blocks as $block){
558 $block = preg_replace('/#.*$/','',$block);
559 $block = trim($block);
560 if(empty($block)) continue;
561 $re[] = $block;
563 if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
564 // prepare event data
565 $data['matches'] = $matches;
566 $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
567 if($_SERVER['REMOTE_USER']) {
568 $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
569 $data['userinfo']['name'] = $INFO['userinfo']['name'];
570 $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
572 $callback = create_function('', 'return true;');
573 return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
576 return false;
580 * Return the IP of the client
582 * Honours X-Forwarded-For and X-Real-IP Proxy Headers
584 * It returns a comma separated list of IPs if the above mentioned
585 * headers are set. If the single parameter is set, it tries to return
586 * a routable public address, prefering the ones suplied in the X
587 * headers
589 * @param boolean $single If set only a single IP is returned
590 * @author Andreas Gohr <andi@splitbrain.org>
592 function clientIP($single=false){
593 $ip = array();
594 $ip[] = $_SERVER['REMOTE_ADDR'];
595 if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
596 $ip = array_merge($ip,explode(',',str_replace(' ','',$_SERVER['HTTP_X_FORWARDED_FOR'])));
597 if(!empty($_SERVER['HTTP_X_REAL_IP']))
598 $ip = array_merge($ip,explode(',',str_replace(' ','',$_SERVER['HTTP_X_REAL_IP'])));
600 // some IPv4/v6 regexps borrowed from Feyd
601 // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
602 $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
603 $hex_digit = '[A-Fa-f0-9]';
604 $h16 = "{$hex_digit}{1,4}";
605 $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
606 $ls32 = "(?:$h16:$h16|$IPv4Address)";
607 $IPv6Address =
608 "(?:(?:{$IPv4Address})|(?:".
609 "(?:$h16:){6}$ls32" .
610 "|::(?:$h16:){5}$ls32" .
611 "|(?:$h16)?::(?:$h16:){4}$ls32" .
612 "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
613 "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
614 "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
615 "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
616 "|(?:(?:$h16:){0,5}$h16)?::$h16" .
617 "|(?:(?:$h16:){0,6}$h16)?::" .
618 ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
620 // remove any non-IP stuff
621 $cnt = count($ip);
622 $match = array();
623 for($i=0; $i<$cnt; $i++){
624 if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
625 $ip[$i] = $match[0];
626 } else {
627 $ip[$i] = '';
629 if(empty($ip[$i])) unset($ip[$i]);
631 $ip = array_values(array_unique($ip));
632 if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
634 if(!$single) return join(',',$ip);
636 // decide which IP to use, trying to avoid local addresses
637 $ip = array_reverse($ip);
638 foreach($ip as $i){
639 if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
640 continue;
641 }else{
642 return $i;
645 // still here? just use the first (last) address
646 return $ip[0];
650 * Check if the browser is on a mobile device
652 * Adapted from the example code at url below
654 * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
656 function clientismobile(){
658 if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
660 if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
662 if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
664 $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';
666 if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
668 return false;
673 * Convert one or more comma separated IPs to hostnames
675 * @author Glen Harris <astfgl@iamnota.org>
676 * @returns a comma separated list of hostnames
678 function gethostsbyaddrs($ips){
679 $hosts = array();
680 $ips = explode(',',$ips);
682 if(is_array($ips)) {
683 foreach($ips as $ip){
684 $hosts[] = gethostbyaddr(trim($ip));
686 return join(',',$hosts);
687 } else {
688 return gethostbyaddr(trim($ips));
693 * Checks if a given page is currently locked.
695 * removes stale lockfiles
697 * @author Andreas Gohr <andi@splitbrain.org>
699 function checklock($id){
700 global $conf;
701 $lock = wikiLockFN($id);
703 //no lockfile
704 if(!@file_exists($lock)) return false;
706 //lockfile expired
707 if((time() - filemtime($lock)) > $conf['locktime']){
708 @unlink($lock);
709 return false;
712 //my own lock
713 $ip = io_readFile($lock);
714 if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
715 return false;
718 return $ip;
722 * Lock a page for editing
724 * @author Andreas Gohr <andi@splitbrain.org>
726 function lock($id){
727 global $conf;
729 if($conf['locktime'] == 0){
730 return;
733 $lock = wikiLockFN($id);
734 if($_SERVER['REMOTE_USER']){
735 io_saveFile($lock,$_SERVER['REMOTE_USER']);
736 }else{
737 io_saveFile($lock,clientIP());
742 * Unlock a page if it was locked by the user
744 * @author Andreas Gohr <andi@splitbrain.org>
745 * @return bool true if a lock was removed
747 function unlock($id){
748 $lock = wikiLockFN($id);
749 if(@file_exists($lock)){
750 $ip = io_readFile($lock);
751 if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
752 @unlink($lock);
753 return true;
756 return false;
760 * convert line ending to unix format
762 * @see formText() for 2crlf conversion
763 * @author Andreas Gohr <andi@splitbrain.org>
765 function cleanText($text){
766 $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
767 return $text;
771 * Prepares text for print in Webforms by encoding special chars.
772 * It also converts line endings to Windows format which is
773 * pseudo standard for webforms.
775 * @see cleanText() for 2unix conversion
776 * @author Andreas Gohr <andi@splitbrain.org>
778 function formText($text){
779 $text = str_replace("\012","\015\012",$text);
780 return htmlspecialchars($text);
784 * Returns the specified local text in raw format
786 * @author Andreas Gohr <andi@splitbrain.org>
788 function rawLocale($id){
789 return io_readFile(localeFN($id));
793 * Returns the raw WikiText
795 * @author Andreas Gohr <andi@splitbrain.org>
797 function rawWiki($id,$rev=''){
798 return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
802 * Returns the pagetemplate contents for the ID's namespace
804 * @triggers COMMON_PAGE_FROMTEMPLATE
805 * @author Andreas Gohr <andi@splitbrain.org>
807 function pageTemplate($id){
808 global $conf;
810 if (is_array($id)) $id = $id[0];
812 $path = dirname(wikiFN($id));
813 $tpl = '';
814 if(@file_exists($path.'/_template.txt')){
815 $tpl = io_readFile($path.'/_template.txt');
816 }else{
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');
822 break;
824 $path = substr($path, 0, strrpos($path, '/'));
827 $data = compact('tpl', 'id');
828 trigger_event('COMMON_PAGE_FROMTEMPLATE', $data, 'parsePageTemplate', true);
829 return $data['tpl'];
833 * Performs common page template replacements
834 * This is the default action for COMMON_PAGE_FROMTEMPLATE
836 * @author Andreas Gohr <andi@splitbrain.org>
838 function parsePageTemplate(&$data) {
839 extract($data);
841 global $USERINFO;
842 global $conf;
844 // replace placeholders
845 $file = noNS($id);
846 $page = strtr($file, $conf['sepchar'], ' ');
848 $tpl = str_replace(array(
849 '@ID@',
850 '@NS@',
851 '@FILE@',
852 '@!FILE@',
853 '@!FILE!@',
854 '@PAGE@',
855 '@!PAGE@',
856 '@!!PAGE@',
857 '@!PAGE!@',
858 '@USER@',
859 '@NAME@',
860 '@MAIL@',
861 '@DATE@',
863 array(
864 $id,
865 getNS($id),
866 $file,
867 utf8_ucfirst($file),
868 utf8_strtoupper($file),
869 $page,
870 utf8_ucfirst($page),
871 utf8_ucwords($page),
872 utf8_strtoupper($page),
873 $_SERVER['REMOTE_USER'],
874 $USERINFO['name'],
875 $USERINFO['mail'],
876 $conf['dformat'],
877 ), $tpl);
879 // we need the callback to work around strftime's char limit
880 $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
881 $data['tpl'] = $tpl;
882 return $tpl;
886 * Returns the raw Wiki Text in three slices.
888 * The range parameter needs to have the form "from-to"
889 * and gives the range of the section in bytes - no
890 * UTF-8 awareness is needed.
891 * The returned order is prefix, section and suffix.
893 * @author Andreas Gohr <andi@splitbrain.org>
895 function rawWikiSlices($range,$id,$rev=''){
896 $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
898 // Parse range
899 list($from,$to) = explode('-',$range,2);
900 // Make range zero-based, use defaults if marker is missing
901 $from = !$from ? 0 : ($from - 1);
902 $to = !$to ? strlen($text) : ($to - 1);
904 $slices[0] = substr($text, 0, $from);
905 $slices[1] = substr($text, $from, $to-$from);
906 $slices[2] = substr($text, $to);
907 return $slices;
911 * Joins wiki text slices
913 * function to join the text slices.
914 * When the pretty parameter is set to true it adds additional empty
915 * lines between sections if needed (used on saving).
917 * @author Andreas Gohr <andi@splitbrain.org>
919 function con($pre,$text,$suf,$pretty=false){
920 if($pretty){
921 if ($pre !== '' && substr($pre, -1) !== "\n" &&
922 substr($text, 0, 1) !== "\n") {
923 $pre .= "\n";
925 if ($suf !== '' && substr($text, -1) !== "\n" &&
926 substr($suf, 0, 1) !== "\n") {
927 $text .= "\n";
931 return $pre.$text.$suf;
935 * Saves a wikitext by calling io_writeWikiPage.
936 * Also directs changelog and attic updates.
938 * @author Andreas Gohr <andi@splitbrain.org>
939 * @author Ben Coburn <btcoburn@silicodon.net>
941 function saveWikiText($id,$text,$summary,$minor=false){
942 /* Note to developers:
943 This code is subtle and delicate. Test the behavior of
944 the attic and changelog with dokuwiki and external edits
945 after any changes. External edits change the wiki page
946 directly without using php or dokuwiki.
948 global $conf;
949 global $lang;
950 global $REV;
951 // ignore if no changes were made
952 if($text == rawWiki($id,'')){
953 return;
956 $file = wikiFN($id);
957 $old = @filemtime($file); // from page
958 $wasRemoved = empty($text);
959 $wasCreated = !@file_exists($file);
960 $wasReverted = ($REV==true);
961 $newRev = false;
962 $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
963 $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
964 if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
965 // add old revision to the attic if missing
966 saveOldRevision($id);
967 // add a changelog entry if this edit came from outside dokuwiki
968 if ($old>$oldRev) {
969 addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
970 // remove soon to be stale instructions
971 $cache = new cache_instructions($id, $file);
972 $cache->removeCache();
976 if ($wasRemoved){
977 // Send "update" event with empty data, so plugins can react to page deletion
978 $data = array(array($file, '', false), getNS($id), noNS($id), false);
979 trigger_event('IO_WIKIPAGE_WRITE', $data);
980 // pre-save deleted revision
981 @touch($file);
982 clearstatcache();
983 $newRev = saveOldRevision($id);
984 // remove empty file
985 @unlink($file);
986 // remove old meta info...
987 $mfiles = metaFiles($id);
988 $changelog = metaFN($id, '.changes');
989 $metadata = metaFN($id, '.meta');
990 $subscribers = metaFN($id, '.mlist');
991 foreach ($mfiles as $mfile) {
992 // but keep per-page changelog to preserve page history, keep subscriber list and keep meta data
993 if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata && $mfile!==$subscribers) { @unlink($mfile); }
995 // purge meta data
996 p_purge_metadata($id);
997 $del = true;
998 // autoset summary on deletion
999 if(empty($summary)) $summary = $lang['deleted'];
1000 // remove empty namespaces
1001 io_sweepNS($id, 'datadir');
1002 io_sweepNS($id, 'mediadir');
1003 }else{
1004 // save file (namespace dir is created in io_writeWikiPage)
1005 io_writeWikiPage($file, $text, $id);
1006 // pre-save the revision, to keep the attic in sync
1007 $newRev = saveOldRevision($id);
1008 $del = false;
1011 // select changelog line type
1012 $extra = '';
1013 $type = DOKU_CHANGE_TYPE_EDIT;
1014 if ($wasReverted) {
1015 $type = DOKU_CHANGE_TYPE_REVERT;
1016 $extra = $REV;
1018 else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
1019 else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
1020 else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
1022 addLogEntry($newRev, $id, $type, $summary, $extra);
1023 // send notify mails
1024 notify($id,'admin',$old,$summary,$minor);
1025 notify($id,'subscribers',$old,$summary,$minor);
1027 // update the purgefile (timestamp of the last time anything within the wiki was changed)
1028 io_saveFile($conf['cachedir'].'/purgefile',time());
1030 // if useheading is enabled, purge the cache of all linking pages
1031 if(useHeading('content')){
1032 $pages = ft_backlinks($id);
1033 foreach ($pages as $page) {
1034 $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
1035 $cache->removeCache();
1041 * moves the current version to the attic and returns its
1042 * revision date
1044 * @author Andreas Gohr <andi@splitbrain.org>
1046 function saveOldRevision($id){
1047 global $conf;
1048 $oldf = wikiFN($id);
1049 if(!@file_exists($oldf)) return '';
1050 $date = filemtime($oldf);
1051 $newf = wikiFN($id,$date);
1052 io_writeWikiPage($newf, rawWiki($id), $id, $date);
1053 return $date;
1057 * Sends a notify mail on page change or registration
1059 * @param string $id The changed page
1060 * @param string $who Who to notify (admin|subscribers|register)
1061 * @param int $rev Old page revision
1062 * @param string $summary What changed
1063 * @param boolean $minor Is this a minor edit?
1064 * @param array $replace Additional string substitutions, @KEY@ to be replaced by value
1066 * @author Andreas Gohr <andi@splitbrain.org>
1068 function notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1069 global $lang;
1070 global $conf;
1071 global $INFO;
1073 // decide if there is something to do
1074 if($who == 'admin'){
1075 if(empty($conf['notify'])) return; //notify enabled?
1076 $text = rawLocale('mailtext');
1077 $to = $conf['notify'];
1078 $bcc = '';
1079 }elseif($who == 'subscribers'){
1080 if(!$conf['subscribers']) return; //subscribers enabled?
1081 if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
1082 $data = array('id' => $id, 'addresslist' => '', 'self' => false);
1083 trigger_event('COMMON_NOTIFY_ADDRESSLIST', $data,
1084 'subscription_addresslist');
1085 $bcc = $data['addresslist'];
1086 if(empty($bcc)) return;
1087 $to = '';
1088 $text = rawLocale('subscr_single');
1089 }elseif($who == 'register'){
1090 if(empty($conf['registernotify'])) return;
1091 $text = rawLocale('registermail');
1092 $to = $conf['registernotify'];
1093 $bcc = '';
1094 }else{
1095 return; //just to be safe
1098 $ip = clientIP();
1099 $text = str_replace('@DATE@',dformat(),$text);
1100 $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
1101 $text = str_replace('@IPADDRESS@',$ip,$text);
1102 $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1103 $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
1104 $text = str_replace('@PAGE@',$id,$text);
1105 $text = str_replace('@TITLE@',$conf['title'],$text);
1106 $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1107 $text = str_replace('@SUMMARY@',$summary,$text);
1108 $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1109 $text = str_replace('@NAME@',$INFO['userinfo']['name'],$text);
1110 $text = str_replace('@MAIL@',$INFO['userinfo']['mail'],$text);
1112 foreach ($replace as $key => $substitution) {
1113 $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
1116 if($who == 'register'){
1117 $subject = $lang['mail_new_user'].' '.$summary;
1118 }elseif($rev){
1119 $subject = $lang['mail_changed'].' '.$id;
1120 $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1121 $df = new Diff(explode("\n",rawWiki($id,$rev)),
1122 explode("\n",rawWiki($id)));
1123 $dformat = new UnifiedDiffFormatter();
1124 $diff = $dformat->format($df);
1125 }else{
1126 $subject=$lang['mail_newpage'].' '.$id;
1127 $text = str_replace('@OLDPAGE@','none',$text);
1128 $diff = rawWiki($id);
1130 $text = str_replace('@DIFF@',$diff,$text);
1131 if(empty($conf['mailprefix'])) {
1132 if(utf8_strlen($conf['title']) < 20) {
1133 $subject = '['.$conf['title'].'] '.$subject;
1134 }else{
1135 $subject = '['.utf8_substr($conf['title'], 0, 20).'...] '.$subject;
1137 }else{
1138 $subject = '['.$conf['mailprefix'].'] '.$subject;
1140 mail_send($to,$subject,$text,$conf['mailfrom'],'',$bcc);
1144 * extracts the query from a search engine referrer
1146 * @author Andreas Gohr <andi@splitbrain.org>
1147 * @author Todd Augsburger <todd@rollerorgans.com>
1149 function getGoogleQuery(){
1150 if (!isset($_SERVER['HTTP_REFERER'])) {
1151 return '';
1153 $url = parse_url($_SERVER['HTTP_REFERER']);
1155 $query = array();
1157 // temporary workaround against PHP bug #49733
1158 // see http://bugs.php.net/bug.php?id=49733
1159 if(UTF8_MBSTRING) $enc = mb_internal_encoding();
1160 parse_str($url['query'],$query);
1161 if(UTF8_MBSTRING) mb_internal_encoding($enc);
1163 $q = '';
1164 if(isset($query['q']))
1165 $q = $query['q']; // google, live/msn, aol, ask, altavista, alltheweb, gigablast
1166 elseif(isset($query['p']))
1167 $q = $query['p']; // yahoo
1168 elseif(isset($query['query']))
1169 $q = $query['query']; // lycos, netscape, clusty, hotbot
1170 elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1171 $q = urldecode(ltrim($url['path'],'/'));
1173 if($q === '') return '';
1174 $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1175 return $q;
1179 * Try to set correct locale
1181 * @deprecated No longer used
1182 * @author Andreas Gohr <andi@splitbrain.org>
1184 function setCorrectLocale(){
1185 global $conf;
1186 global $lang;
1188 $enc = strtoupper($lang['encoding']);
1189 foreach ($lang['locales'] as $loc){
1190 //try locale
1191 if(@setlocale(LC_ALL,$loc)) return;
1192 //try loceale with encoding
1193 if(@setlocale(LC_ALL,"$loc.$enc")) return;
1195 //still here? try to set from environment
1196 @setlocale(LC_ALL,"");
1200 * Return the human readable size of a file
1202 * @param int $size A file size
1203 * @param int $dec A number of decimal places
1204 * @author Martin Benjamin <b.martin@cybernet.ch>
1205 * @author Aidan Lister <aidan@php.net>
1206 * @version 1.0.0
1208 function filesize_h($size, $dec = 1){
1209 $sizes = array('B', 'KB', 'MB', 'GB');
1210 $count = count($sizes);
1211 $i = 0;
1213 while ($size >= 1024 && ($i < $count - 1)) {
1214 $size /= 1024;
1215 $i++;
1218 return round($size, $dec) . ' ' . $sizes[$i];
1222 * Return the given timestamp as human readable, fuzzy age
1224 * @author Andreas Gohr <gohr@cosmocode.de>
1226 function datetime_h($dt){
1227 global $lang;
1229 $ago = time() - $dt;
1230 if($ago > 24*60*60*30*12*2){
1231 return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1233 if($ago > 24*60*60*30*2){
1234 return sprintf($lang['months'], round($ago/(24*60*60*30)));
1236 if($ago > 24*60*60*7*2){
1237 return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1239 if($ago > 24*60*60*2){
1240 return sprintf($lang['days'], round($ago/(24*60*60)));
1242 if($ago > 60*60*2){
1243 return sprintf($lang['hours'], round($ago/(60*60)));
1245 if($ago > 60*2){
1246 return sprintf($lang['minutes'], round($ago/(60)));
1248 return sprintf($lang['seconds'], $ago);
1252 * Wraps around strftime but provides support for fuzzy dates
1254 * The format default to $conf['dformat']. It is passed to
1255 * strftime - %f can be used to get the value from datetime_h()
1257 * @see datetime_h
1258 * @author Andreas Gohr <gohr@cosmocode.de>
1260 function dformat($dt=null,$format=''){
1261 global $conf;
1263 if(is_null($dt)) $dt = time();
1264 $dt = (int) $dt;
1265 if(!$format) $format = $conf['dformat'];
1267 $format = str_replace('%f',datetime_h($dt),$format);
1268 return strftime($format,$dt);
1272 * Formats a timestamp as ISO 8601 date
1274 * @author <ungu at terong dot com>
1275 * @link http://www.php.net/manual/en/function.date.php#54072
1277 function date_iso8601($int_date) {
1278 //$int_date: current date in UNIX timestamp
1279 $date_mod = date('Y-m-d\TH:i:s', $int_date);
1280 $pre_timezone = date('O', $int_date);
1281 $time_zone = substr($pre_timezone, 0, 3).":".substr($pre_timezone, 3, 2);
1282 $date_mod .= $time_zone;
1283 return $date_mod;
1287 * return an obfuscated email address in line with $conf['mailguard'] setting
1289 * @author Harry Fuecks <hfuecks@gmail.com>
1290 * @author Christopher Smith <chris@jalakai.co.uk>
1292 function obfuscate($email) {
1293 global $conf;
1295 switch ($conf['mailguard']) {
1296 case 'visible' :
1297 $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
1298 return strtr($email, $obfuscate);
1300 case 'hex' :
1301 $encode = '';
1302 $len = strlen($email);
1303 for ($x=0; $x < $len; $x++){
1304 $encode .= '&#x' . bin2hex($email{$x}).';';
1306 return $encode;
1308 case 'none' :
1309 default :
1310 return $email;
1315 * Removes quoting backslashes
1317 * @author Andreas Gohr <andi@splitbrain.org>
1319 function unslash($string,$char="'"){
1320 return str_replace('\\'.$char,$char,$string);
1324 * Convert php.ini shorthands to byte
1326 * @author <gilthans dot NO dot SPAM at gmail dot com>
1327 * @link http://de3.php.net/manual/en/ini.core.php#79564
1329 function php_to_byte($v){
1330 $l = substr($v, -1);
1331 $ret = substr($v, 0, -1);
1332 switch(strtoupper($l)){
1333 case 'P':
1334 $ret *= 1024;
1335 case 'T':
1336 $ret *= 1024;
1337 case 'G':
1338 $ret *= 1024;
1339 case 'M':
1340 $ret *= 1024;
1341 case 'K':
1342 $ret *= 1024;
1343 break;
1344 default;
1345 $ret *= 10;
1346 break;
1348 return $ret;
1352 * Wrapper around preg_quote adding the default delimiter
1354 function preg_quote_cb($string){
1355 return preg_quote($string,'/');
1359 * Shorten a given string by removing data from the middle
1361 * You can give the string in two parts, the first part $keep
1362 * will never be shortened. The second part $short will be cut
1363 * in the middle to shorten but only if at least $min chars are
1364 * left to display it. Otherwise it will be left off.
1366 * @param string $keep the part to keep
1367 * @param string $short the part to shorten
1368 * @param int $max maximum chars you want for the whole string
1369 * @param int $min minimum number of chars to have left for middle shortening
1370 * @param string $char the shortening character to use
1372 function shorten($keep,$short,$max,$min=9,$char='…'){
1373 $max = $max - utf8_strlen($keep);
1374 if($max < $min) return $keep;
1375 $len = utf8_strlen($short);
1376 if($len <= $max) return $keep.$short;
1377 $half = floor($max/2);
1378 return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1382 * Return the users realname or e-mail address for use
1383 * in page footer and recent changes pages
1385 * @author Andy Webber <dokuwiki AT andywebber DOT com>
1387 function editorinfo($username){
1388 global $conf;
1389 global $auth;
1391 switch($conf['showuseras']){
1392 case 'username':
1393 case 'email':
1394 case 'email_link':
1395 if($auth) $info = $auth->getUserData($username);
1396 break;
1397 default:
1398 return hsc($username);
1401 if(isset($info) && $info) {
1402 switch($conf['showuseras']){
1403 case 'username':
1404 return hsc($info['name']);
1405 case 'email':
1406 return obfuscate($info['mail']);
1407 case 'email_link':
1408 $mail=obfuscate($info['mail']);
1409 return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1410 default:
1411 return hsc($username);
1413 } else {
1414 return hsc($username);
1419 * Returns the path to a image file for the currently chosen license.
1420 * When no image exists, returns an empty string
1422 * @author Andreas Gohr <andi@splitbrain.org>
1423 * @param string $type - type of image 'badge' or 'button'
1425 function license_img($type){
1426 global $license;
1427 global $conf;
1428 if(!$conf['license']) return '';
1429 if(!is_array($license[$conf['license']])) return '';
1430 $lic = $license[$conf['license']];
1431 $try = array();
1432 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1433 $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1434 if(substr($conf['license'],0,3) == 'cc-'){
1435 $try[] = 'lib/images/license/'.$type.'/cc.png';
1437 foreach($try as $src){
1438 if(@file_exists(DOKU_INC.$src)) return $src;
1440 return '';
1444 * Checks if the given amount of memory is available
1446 * If the memory_get_usage() function is not available the
1447 * function just assumes $bytes of already allocated memory
1449 * @param int $mem Size of memory you want to allocate in bytes
1450 * @param int $used already allocated memory (see above)
1451 * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
1452 * @author Andreas Gohr <andi@splitbrain.org>
1454 function is_mem_available($mem,$bytes=1048576){
1455 $limit = trim(ini_get('memory_limit'));
1456 if(empty($limit)) return true; // no limit set!
1458 // parse limit to bytes
1459 $limit = php_to_byte($limit);
1461 // get used memory if possible
1462 if(function_exists('memory_get_usage')){
1463 $used = memory_get_usage();
1464 }else{
1465 $used = $bytes;
1468 if($used+$mem > $limit){
1469 return false;
1472 return true;
1476 * Send a HTTP redirect to the browser
1478 * Works arround Microsoft IIS cookie sending bug. Exits the script.
1480 * @link http://support.microsoft.com/kb/q176113/
1481 * @author Andreas Gohr <andi@splitbrain.org>
1483 function send_redirect($url){
1484 //are there any undisplayed messages? keep them in session for display
1485 global $MSG;
1486 if (isset($MSG) && count($MSG) && !defined('NOSESSION')){
1487 //reopen session, store data and close session again
1488 @session_start();
1489 $_SESSION[DOKU_COOKIE]['msg'] = $MSG;
1492 // always close the session
1493 session_write_close();
1495 // work around IE bug
1496 // http://www.ianhoar.com/2008/11/16/internet-explorer-6-and-redirected-anchor-links/
1497 list($url,$hash) = explode('#',$url);
1498 if($hash){
1499 if(strpos($url,'?')){
1500 $url = $url.'&#'.$hash;
1501 }else{
1502 $url = $url.'?&#'.$hash;
1506 // check if running on IIS < 6 with CGI-PHP
1507 if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1508 (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1509 (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1510 $matches[1] < 6 ){
1511 header('Refresh: 0;url='.$url);
1512 }else{
1513 header('Location: '.$url);
1515 exit;
1519 * Validate a value using a set of valid values
1521 * This function checks whether a specified value is set and in the array
1522 * $valid_values. If not, the function returns a default value or, if no
1523 * default is specified, throws an exception.
1525 * @param string $param The name of the parameter
1526 * @param array $valid_values A set of valid values; Optionally a default may
1527 * be marked by the key “default”.
1528 * @param array $array The array containing the value (typically $_POST
1529 * or $_GET)
1530 * @param string $exc The text of the raised exception
1532 * @author Adrian Lang <lang@cosmocode.de>
1534 function valid_input_set($param, $valid_values, $array, $exc = '') {
1535 if (isset($array[$param]) && in_array($array[$param], $valid_values)) {
1536 return $array[$param];
1537 } elseif (isset($valid_values['default'])) {
1538 return $valid_values['default'];
1539 } else {
1540 throw new Exception($exc);
1544 //Setup VIM: ex: et ts=2 :