xref: /dokuwiki/inc/common.php (revision f22635779b10fe3735a11bc1af5c88653e580534)
1ed7b5f09Sandi<?php
215fae107Sandi/**
315fae107Sandi * Common DokuWiki functions
415fae107Sandi *
515fae107Sandi * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
715fae107Sandi */
815fae107Sandi
9fa8adffeSAndreas Gohrif(!defined('DOKU_INC')) die('meh.');
10ed7b5f09Sandirequire_once(DOKU_INC.'inc/io.php');
117d559c7fSBen Coburnrequire_once(DOKU_INC.'inc/changelog.php');
12ed7b5f09Sandirequire_once(DOKU_INC.'inc/utf8.php');
13ed7b5f09Sandirequire_once(DOKU_INC.'inc/mail.php');
14c112d578Sandirequire_once(DOKU_INC.'inc/parserutils.php');
15c29dc6e4SAndreas Gohrrequire_once(DOKU_INC.'inc/infoutils.php');
16f3f0262cSandi
17f3f0262cSandi/**
18b6912aeaSAndreas Gohr * These constants are used with the recents function
19b6912aeaSAndreas Gohr */
20b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_DELETED',2);
21b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_MINORS',4);
22b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_SUBSPACES',8);
2399c8d7f2Smichaeldefine('RECENTS_MEDIA_CHANGES',16);
24b6912aeaSAndreas Gohr
25b6912aeaSAndreas Gohr/**
26d5197206Schris * Wrapper around htmlspecialchars()
27d5197206Schris *
28d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
29d5197206Schris * @see    htmlspecialchars()
30d5197206Schris */
31d5197206Schrisfunction hsc($string){
32d5197206Schris  return htmlspecialchars($string, ENT_QUOTES, 'UTF-8');
33d5197206Schris}
34d5197206Schris
35d5197206Schris/**
36d5197206Schris * print a newline terminated string
37d5197206Schris *
38d5197206Schris * You can give an indention as optional parameter
39d5197206Schris *
40d5197206Schris * @author Andreas Gohr <andi@splitbrain.org>
41d5197206Schris */
4225ec097bSChris Smithfunction ptln($string,$indent=0){
4325ec097bSChris Smith  echo str_repeat(' ', $indent)."$string\n";
4402b0b681SAndreas Gohr}
4502b0b681SAndreas Gohr
4602b0b681SAndreas Gohr/**
4702b0b681SAndreas Gohr * strips control characters (<32) from the given string
4802b0b681SAndreas Gohr *
4902b0b681SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
5002b0b681SAndreas Gohr */
5102b0b681SAndreas Gohrfunction stripctl($string){
5202b0b681SAndreas Gohr  return preg_replace('/[\x00-\x1F]+/s','',$string);
53d5197206Schris}
54d5197206Schris
55d5197206Schris/**
56634d7150SAndreas Gohr * Return a secret token to be used for CSRF attack prevention
57634d7150SAndreas Gohr *
58634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
59634d7150SAndreas Gohr * @link    http://en.wikipedia.org/wiki/Cross-site_request_forgery
60634d7150SAndreas Gohr * @link    http://christ1an.blogspot.com/2007/04/preventing-csrf-efficiently.html
61634d7150SAndreas Gohr * @return  string
62634d7150SAndreas Gohr */
63634d7150SAndreas Gohrfunction getSecurityToken(){
64634d7150SAndreas Gohr  return md5(auth_cookiesalt().session_id());
65634d7150SAndreas Gohr}
66634d7150SAndreas Gohr
67634d7150SAndreas Gohr/**
68634d7150SAndreas Gohr * Check the secret CSRF token
69634d7150SAndreas Gohr */
70634d7150SAndreas Gohrfunction checkSecurityToken($token=null){
71df97eaacSAndreas Gohr  if(!$_SERVER['REMOTE_USER']) return true; // no logged in user, no need for a check
72df97eaacSAndreas Gohr
73634d7150SAndreas Gohr  if(is_null($token)) $token = $_REQUEST['sectok'];
74634d7150SAndreas Gohr  if(getSecurityToken() != $token){
75634d7150SAndreas Gohr    msg('Security Token did not match. Possible CSRF attack.',-1);
76634d7150SAndreas Gohr    return false;
77634d7150SAndreas Gohr  }
78634d7150SAndreas Gohr  return true;
79634d7150SAndreas Gohr}
80634d7150SAndreas Gohr
81634d7150SAndreas Gohr/**
82634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
83634d7150SAndreas Gohr *
84634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
85634d7150SAndreas Gohr */
86634d7150SAndreas Gohrfunction formSecurityToken($print=true){
872404d0edSAnika Henke  $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
88634d7150SAndreas Gohr  if($print){
89634d7150SAndreas Gohr    echo $ret;
90634d7150SAndreas Gohr  }else{
91634d7150SAndreas Gohr    return $ret;
92634d7150SAndreas Gohr  }
93634d7150SAndreas Gohr}
94634d7150SAndreas Gohr
95634d7150SAndreas Gohr/**
9615fae107Sandi * Return info about the current document as associative
97f3f0262cSandi * array.
9815fae107Sandi *
9915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
100f3f0262cSandi */
101f3f0262cSandifunction pageinfo(){
102f3f0262cSandi  global $ID;
103f3f0262cSandi  global $REV;
1047b3a6803SAndreas Gohr  global $RANGE;
105f3f0262cSandi  global $USERINFO;
106f3f0262cSandi  global $conf;
1077b3a6803SAndreas Gohr  global $lang;
108f3f0262cSandi
1096afe8dcaSchris  // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1106afe8dcaSchris  // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1116afe8dcaSchris  $info['id'] = $ID;
1126afe8dcaSchris  $info['rev'] = $REV;
1136afe8dcaSchris
114f3f0262cSandi  if($_SERVER['REMOTE_USER']){
115f3f0262cSandi    $info['userinfo']     = $USERINFO;
116f3f0262cSandi    $info['perm']         = auth_quickaclcheck($ID);
11752b0dd67SGuy Brand    $info['subscribed']   = is_subscribed($ID,$_SERVER['REMOTE_USER'],false);
11852b0dd67SGuy Brand    $info['subscribedns'] = is_subscribed($ID,$_SERVER['REMOTE_USER'],true);
119ee4c4a1bSAndreas Gohr    $info['client']       = $_SERVER['REMOTE_USER'];
12017ee7f66SAndreas Gohr
121f8cc712eSAndreas Gohr    // set info about manager/admin status
122f8cc712eSAndreas Gohr    $info['isadmin']   = false;
123f8cc712eSAndreas Gohr    $info['ismanager'] = false;
124f8cc712eSAndreas Gohr    if($info['perm'] == AUTH_ADMIN){
125f8cc712eSAndreas Gohr      $info['isadmin']   = true;
126f8cc712eSAndreas Gohr      $info['ismanager'] = true;
127f8cc712eSAndreas Gohr    }elseif(auth_ismanager()){
128f8cc712eSAndreas Gohr      $info['ismanager'] = true;
129f8cc712eSAndreas Gohr    }
130f8cc712eSAndreas Gohr
13117ee7f66SAndreas Gohr    // if some outside auth were used only REMOTE_USER is set
13217ee7f66SAndreas Gohr    if(!$info['userinfo']['name']){
13317ee7f66SAndreas Gohr      $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
13417ee7f66SAndreas Gohr    }
135ee4c4a1bSAndreas Gohr
136f3f0262cSandi  }else{
137f3f0262cSandi    $info['perm']       = auth_aclcheck($ID,'',null);
1381380fc45SAndreas Gohr    $info['subscribed'] = false;
139ee4c4a1bSAndreas Gohr    $info['client']     = clientIP(true);
140f3f0262cSandi  }
141f3f0262cSandi
142f3f0262cSandi  $info['namespace'] = getNS($ID);
143f3f0262cSandi  $info['locked']    = checklock($ID);
14400976812SAndreas Gohr  $info['filepath']  = fullpath(wikiFN($ID));
1452ca9d91cSBen Coburn  $info['exists']    = @file_exists($info['filepath']);
1462ca9d91cSBen Coburn  if($REV){
1472ca9d91cSBen Coburn    //check if current revision was meant
1482ca9d91cSBen Coburn    if($info['exists'] && (@filemtime($info['filepath'])==$REV)){
1492ca9d91cSBen Coburn      $REV = '';
1507b3a6803SAndreas Gohr    }elseif($RANGE){
1517b3a6803SAndreas Gohr      //section editing does not work with old revisions!
1527b3a6803SAndreas Gohr      $REV   = '';
1537b3a6803SAndreas Gohr      $RANGE = '';
1547b3a6803SAndreas Gohr      msg($lang['nosecedit'],0);
1552ca9d91cSBen Coburn    }else{
1562ca9d91cSBen Coburn      //really use old revision
15700976812SAndreas Gohr      $info['filepath'] = fullpath(wikiFN($ID,$REV));
158f3f0262cSandi      $info['exists']   = @file_exists($info['filepath']);
159f3f0262cSandi    }
160f3f0262cSandi  }
161c112d578Sandi  $info['rev'] = $REV;
162f3f0262cSandi  if($info['exists']){
163f3f0262cSandi    $info['writable'] = (is_writable($info['filepath']) &&
164f3f0262cSandi                         ($info['perm'] >= AUTH_EDIT));
165f3f0262cSandi  }else{
166f3f0262cSandi    $info['writable'] = ($info['perm'] >= AUTH_CREATE);
167f3f0262cSandi  }
168f3f0262cSandi  $info['editable']  = ($info['writable'] && empty($info['lock']));
169f3f0262cSandi  $info['lastmod']   = @filemtime($info['filepath']);
170f3f0262cSandi
17171726d78SBen Coburn  //load page meta data
17271726d78SBen Coburn  $info['meta'] = p_get_metadata($ID);
17371726d78SBen Coburn
174652610a2Sandi  //who's the editor
175652610a2Sandi  if($REV){
17671726d78SBen Coburn    $revinfo = getRevisionInfo($ID, $REV, 1024);
177652610a2Sandi  }else{
178aa27cf05SAndreas Gohr    if (is_array($info['meta']['last_change'])) {
179aa27cf05SAndreas Gohr       $revinfo = $info['meta']['last_change'];
180aa27cf05SAndreas Gohr    } else {
181cd00a034SBen Coburn      $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
182cd00a034SBen Coburn      // cache most recent changelog line in metadata if missing and still valid
183cd00a034SBen Coburn      if ($revinfo!==false) {
184cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
185cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
186cd00a034SBen Coburn      }
187cd00a034SBen Coburn    }
188cd00a034SBen Coburn  }
189cd00a034SBen Coburn  //and check for an external edit
190cd00a034SBen Coburn  if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
191cd00a034SBen Coburn    // cached changelog line no longer valid
192cd00a034SBen Coburn    $revinfo = false;
193cd00a034SBen Coburn    $info['meta']['last_change'] = $revinfo;
194cd00a034SBen Coburn    p_set_metadata($ID, array('last_change' => $revinfo));
195652610a2Sandi  }
196bb4866bdSchris
197652610a2Sandi  $info['ip']     = $revinfo['ip'];
198652610a2Sandi  $info['user']   = $revinfo['user'];
199652610a2Sandi  $info['sum']    = $revinfo['sum'];
20071726d78SBen Coburn  // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
201ebf1501fSBen Coburn  // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
20259f257aeSchris
20388f522e9Sandi  if($revinfo['user']){
20488f522e9Sandi    $info['editor'] = $revinfo['user'];
20588f522e9Sandi  }else{
20688f522e9Sandi    $info['editor'] = $revinfo['ip'];
20788f522e9Sandi  }
208652610a2Sandi
209ee4c4a1bSAndreas Gohr  // draft
210ee4c4a1bSAndreas Gohr  $draft = getCacheName($info['client'].$ID,'.draft');
211ee4c4a1bSAndreas Gohr  if(@file_exists($draft)){
212ee4c4a1bSAndreas Gohr    if(@filemtime($draft) < @filemtime(wikiFN($ID))){
213ee4c4a1bSAndreas Gohr      // remove stale draft
214ee4c4a1bSAndreas Gohr      @unlink($draft);
215ee4c4a1bSAndreas Gohr    }else{
216ee4c4a1bSAndreas Gohr      $info['draft'] = $draft;
217ee4c4a1bSAndreas Gohr    }
218ee4c4a1bSAndreas Gohr  }
219ee4c4a1bSAndreas Gohr
2201c548ebeSAndreas Gohr  // mobile detection
2211c548ebeSAndreas Gohr  $info['ismobile'] = clientismobile();
2221c548ebeSAndreas Gohr
223f3f0262cSandi  return $info;
224f3f0262cSandi}
225f3f0262cSandi
226f3f0262cSandi/**
2272684e50aSAndreas Gohr * Build an string of URL parameters
2282684e50aSAndreas Gohr *
2292684e50aSAndreas Gohr * @author Andreas Gohr
2302684e50aSAndreas Gohr */
231b174aeaeSchrisfunction buildURLparams($params, $sep='&amp;'){
2322684e50aSAndreas Gohr  $url = '';
2332684e50aSAndreas Gohr  $amp = false;
2342684e50aSAndreas Gohr  foreach($params as $key => $val){
235b174aeaeSchris    if($amp) $url .= $sep;
2362684e50aSAndreas Gohr
2372684e50aSAndreas Gohr    $url .= $key.'=';
2383a50618cSgweissbach    $url .= rawurlencode((string)$val);
2392684e50aSAndreas Gohr    $amp = true;
2402684e50aSAndreas Gohr  }
2412684e50aSAndreas Gohr  return $url;
2422684e50aSAndreas Gohr}
2432684e50aSAndreas Gohr
2442684e50aSAndreas Gohr/**
2452684e50aSAndreas Gohr * Build an string of html tag attributes
2462684e50aSAndreas Gohr *
2477bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2487bff22c0SAndreas Gohr *
2492684e50aSAndreas Gohr * @author Andreas Gohr
2502684e50aSAndreas Gohr */
2514b030ce7SAndreas Gohrfunction buildAttributes($params,$skipempty=false){
2522684e50aSAndreas Gohr  $url = '';
2532684e50aSAndreas Gohr  foreach($params as $key => $val){
2547bff22c0SAndreas Gohr    if($key{0} == '_') continue;
255b1c94f1dSAndreas Gohr    if($val === '' && $skipempty) continue;
2567bff22c0SAndreas Gohr
2572684e50aSAndreas Gohr    $url .= $key.'="';
2582684e50aSAndreas Gohr    $url .= htmlspecialchars ($val);
2592684e50aSAndreas Gohr    $url .= '" ';
2602684e50aSAndreas Gohr  }
2612684e50aSAndreas Gohr  return $url;
2622684e50aSAndreas Gohr}
2632684e50aSAndreas Gohr
2642684e50aSAndreas Gohr
2652684e50aSAndreas Gohr/**
26615fae107Sandi * This builds the breadcrumb trail and returns it as array
26715fae107Sandi *
26815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
269f3f0262cSandi */
270f3f0262cSandifunction breadcrumbs(){
2718746e727Sandi  // we prepare the breadcrumbs early for quick session closing
2728746e727Sandi  static $crumbs = null;
2738746e727Sandi  if($crumbs != null) return $crumbs;
2748746e727Sandi
275f3f0262cSandi  global $ID;
276f3f0262cSandi  global $ACT;
277f3f0262cSandi  global $conf;
278e71ce681SAndreas Gohr  $crumbs = $_SESSION[DOKU_COOKIE]['bc'];
279f3f0262cSandi
280f3f0262cSandi  //first visit?
281f3f0262cSandi  if (!is_array($crumbs)){
282f3f0262cSandi    $crumbs = array();
283f3f0262cSandi  }
284f3f0262cSandi  //we only save on show and existing wiki documents
285a77f5846Sjan  $file = wikiFN($ID);
286a77f5846Sjan  if($ACT != 'show' || !@file_exists($file)){
287e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
288f3f0262cSandi    return $crumbs;
289f3f0262cSandi  }
290a77f5846Sjan
291a77f5846Sjan  // page names
2921a84a0f3SAnika Henke  $name = noNSorNS($ID);
293fe9ec250SChris Smith  if (useHeading('navigation')) {
294a77f5846Sjan    // get page title
295955cd091SChris Smith    $title = p_get_first_heading($ID,true);
296a77f5846Sjan    if ($title) {
297a77f5846Sjan      $name = $title;
298a77f5846Sjan    }
299a77f5846Sjan  }
300a77f5846Sjan
301f3f0262cSandi  //remove ID from array
302a77f5846Sjan  if (isset($crumbs[$ID])) {
303a77f5846Sjan    unset($crumbs[$ID]);
304f3f0262cSandi  }
305f3f0262cSandi
306f3f0262cSandi  //add to array
307a77f5846Sjan  $crumbs[$ID] = $name;
308f3f0262cSandi  //reduce size
309f3f0262cSandi  while(count($crumbs) > $conf['breadcrumbs']){
310f3f0262cSandi    array_shift($crumbs);
311f3f0262cSandi  }
312f3f0262cSandi  //save to session
313e71ce681SAndreas Gohr  $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
314f3f0262cSandi  return $crumbs;
315f3f0262cSandi}
316f3f0262cSandi
317f3f0262cSandi/**
31815fae107Sandi * Filter for page IDs
31915fae107Sandi *
320f3f0262cSandi * This is run on a ID before it is outputted somewhere
321f3f0262cSandi * currently used to replace the colon with something else
322f3f0262cSandi * on Windows systems and to have proper URL encoding
32315fae107Sandi *
32449c713a3Sandi * Urlencoding is ommitted when the second parameter is false
32549c713a3Sandi *
32615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
327f3f0262cSandi */
32849c713a3Sandifunction idfilter($id,$ue=true){
329f3f0262cSandi  global $conf;
330f3f0262cSandi  if ($conf['useslash'] && $conf['userewrite']){
331f3f0262cSandi    $id = strtr($id,':','/');
332f3f0262cSandi  }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
333f3f0262cSandi      $conf['userewrite']) {
334f3f0262cSandi    $id = strtr($id,':',';');
335f3f0262cSandi  }
33649c713a3Sandi  if($ue){
337b6c6979fSAndreas Gohr    $id = rawurlencode($id);
338f3f0262cSandi    $id = str_replace('%3A',':',$id); //keep as colon
339f3f0262cSandi    $id = str_replace('%2F','/',$id); //keep as slash
34049c713a3Sandi  }
341f3f0262cSandi  return $id;
342f3f0262cSandi}
343f3f0262cSandi
344f3f0262cSandi/**
345ed7b5f09Sandi * This builds a link to a wikipage
34615fae107Sandi *
3476c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3486c7843b5Sandi * given in $more
3496c7843b5Sandi *
35015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
351f3f0262cSandi */
352b174aeaeSchrisfunction wl($id='',$more='',$abs=false,$sep='&amp;'){
353f3f0262cSandi  global $conf;
3546de3759aSAndreas Gohr  if(is_array($more)){
355b174aeaeSchris    $more = buildURLparams($more,$sep);
3566de3759aSAndreas Gohr  }else{
357b174aeaeSchris    $more = str_replace(',',$sep,$more);
3586de3759aSAndreas Gohr  }
359f3f0262cSandi
360f3f0262cSandi  $id    = idfilter($id);
361ed7b5f09Sandi  if($abs){
362ed7b5f09Sandi    $xlink = DOKU_URL;
363ed7b5f09Sandi  }else{
364ed7b5f09Sandi    $xlink = DOKU_BASE;
365ed7b5f09Sandi  }
366f3f0262cSandi
3676c7843b5Sandi  if($conf['userewrite'] == 2){
3686c7843b5Sandi    $xlink .= DOKU_SCRIPT.'/'.$id;
3696c7843b5Sandi    if($more) $xlink .= '?'.$more;
3706c7843b5Sandi  }elseif($conf['userewrite']){
371f3f0262cSandi    $xlink .= $id;
372f3f0262cSandi    if($more) $xlink .= '?'.$more;
373bce3726dSAndreas Gohr  }elseif($id){
3746c7843b5Sandi    $xlink .= DOKU_SCRIPT.'?id='.$id;
375b174aeaeSchris    if($more) $xlink .= $sep.$more;
376bce3726dSAndreas Gohr  }else{
377bce3726dSAndreas Gohr    $xlink .= DOKU_SCRIPT;
378bce3726dSAndreas Gohr    if($more) $xlink .= '?'.$more;
379f3f0262cSandi  }
380f3f0262cSandi
381f3f0262cSandi  return $xlink;
382f3f0262cSandi}
383f3f0262cSandi
384f3f0262cSandi/**
385f5c2808fSBen Coburn * This builds a link to an alternate page format
386f5c2808fSBen Coburn *
387f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
388f5c2808fSBen Coburn *
389f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
390f5c2808fSBen Coburn */
391f5c2808fSBen Coburnfunction exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
392f5c2808fSBen Coburn  global $conf;
393f5c2808fSBen Coburn  if(is_array($more)){
394f5c2808fSBen Coburn    $more = buildURLparams($more,$sep);
395f5c2808fSBen Coburn  }else{
396f5c2808fSBen Coburn    $more = str_replace(',',$sep,$more);
397f5c2808fSBen Coburn  }
398f5c2808fSBen Coburn
399f5c2808fSBen Coburn  $format = rawurlencode($format);
400f5c2808fSBen Coburn  $id = idfilter($id);
401f5c2808fSBen Coburn  if($abs){
402f5c2808fSBen Coburn    $xlink = DOKU_URL;
403f5c2808fSBen Coburn  }else{
404f5c2808fSBen Coburn    $xlink = DOKU_BASE;
405f5c2808fSBen Coburn  }
406f5c2808fSBen Coburn
407f5c2808fSBen Coburn  if($conf['userewrite'] == 2){
408f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
409f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
410f5c2808fSBen Coburn  }elseif($conf['userewrite'] == 1){
411f5c2808fSBen Coburn    $xlink .= '_export/'.$format.'/'.$id;
412f5c2808fSBen Coburn    if($more) $xlink .= '?'.$more;
413f5c2808fSBen Coburn  }else{
414f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
415f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
416f5c2808fSBen Coburn  }
417f5c2808fSBen Coburn
418f5c2808fSBen Coburn  return $xlink;
419f5c2808fSBen Coburn}
420f5c2808fSBen Coburn
421f5c2808fSBen Coburn/**
4226de3759aSAndreas Gohr * Build a link to a media file
4236de3759aSAndreas Gohr *
4246de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4258c08db0aSAndreas Gohr *
4268c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4278c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4288c08db0aSAndreas Gohr *
4298c08db0aSAndreas Gohr * @param string  $id     - the media file id or URL
4308c08db0aSAndreas Gohr * @param mixed   $more   - string or array with additional parameters
4318c08db0aSAndreas Gohr * @param boolean $direct - link to detail page if false
4328c08db0aSAndreas Gohr * @param string  $sep    - URL parameter separator
4338c08db0aSAndreas Gohr * @param boolean $abs    - Create an absolute URL
4346de3759aSAndreas Gohr */
43555b2b31bSAndreas Gohrfunction ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
4366de3759aSAndreas Gohr  global $conf;
4376de3759aSAndreas Gohr  if(is_array($more)){
4388c08db0aSAndreas Gohr    // strip defaults for shorter URLs
4398c08db0aSAndreas Gohr    if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4408c08db0aSAndreas Gohr    if(!$more['w']) unset($more['w']);
4418c08db0aSAndreas Gohr    if(!$more['h']) unset($more['h']);
4428c08db0aSAndreas Gohr    if(isset($more['id']) && $direct) unset($more['id']);
443b174aeaeSchris    $more = buildURLparams($more,$sep);
4446de3759aSAndreas Gohr  }else{
4458c08db0aSAndreas Gohr    $more = str_replace('cache=cache','',$more); //skip default
4468c08db0aSAndreas Gohr    $more = str_replace(',,',',',$more);
447b174aeaeSchris    $more = str_replace(',',$sep,$more);
4486de3759aSAndreas Gohr  }
4496de3759aSAndreas Gohr
45055b2b31bSAndreas Gohr  if($abs){
45155b2b31bSAndreas Gohr    $xlink = DOKU_URL;
45255b2b31bSAndreas Gohr  }else{
4536de3759aSAndreas Gohr    $xlink = DOKU_BASE;
45455b2b31bSAndreas Gohr  }
4556de3759aSAndreas Gohr
4566de3759aSAndreas Gohr  // external URLs are always direct without rewriting
4576de3759aSAndreas Gohr  if(preg_match('#^(https?|ftp)://#i',$id)){
4586de3759aSAndreas Gohr    $xlink .= 'lib/exe/fetch.php';
45969d17d94SAndreas Gohr    // add hash:
46069d17d94SAndreas Gohr    $xlink .= '?hash='.substr(md5(auth_cookiesalt().$id),0,6);
4616de3759aSAndreas Gohr    if($more){
46269d17d94SAndreas Gohr      $xlink .= $sep.$more;
463b174aeaeSchris      $xlink .= $sep.'media='.rawurlencode($id);
4646de3759aSAndreas Gohr    }else{
46569d17d94SAndreas Gohr      $xlink .= $sep.'media='.rawurlencode($id);
4666de3759aSAndreas Gohr    }
4676de3759aSAndreas Gohr    return $xlink;
4686de3759aSAndreas Gohr  }
4696de3759aSAndreas Gohr
4706de3759aSAndreas Gohr  $id = idfilter($id);
4716de3759aSAndreas Gohr
4726de3759aSAndreas Gohr  // decide on scriptname
4736de3759aSAndreas Gohr  if($direct){
4746de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4756de3759aSAndreas Gohr      $script = '_media';
4766de3759aSAndreas Gohr    }else{
4776de3759aSAndreas Gohr      $script = 'lib/exe/fetch.php';
4786de3759aSAndreas Gohr    }
4796de3759aSAndreas Gohr  }else{
4806de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4816de3759aSAndreas Gohr      $script = '_detail';
4826de3759aSAndreas Gohr    }else{
4836de3759aSAndreas Gohr      $script = 'lib/exe/detail.php';
4846de3759aSAndreas Gohr    }
4856de3759aSAndreas Gohr  }
4866de3759aSAndreas Gohr
4876de3759aSAndreas Gohr  // build URL based on rewrite mode
4886de3759aSAndreas Gohr   if($conf['userewrite']){
4896de3759aSAndreas Gohr     $xlink .= $script.'/'.$id;
4906de3759aSAndreas Gohr     if($more) $xlink .= '?'.$more;
4916de3759aSAndreas Gohr   }else{
4926de3759aSAndreas Gohr     if($more){
493a99d3236SEsther Brunner       $xlink .= $script.'?'.$more;
494b174aeaeSchris       $xlink .= $sep.'media='.$id;
4956de3759aSAndreas Gohr     }else{
496a99d3236SEsther Brunner       $xlink .= $script.'?media='.$id;
4976de3759aSAndreas Gohr     }
4986de3759aSAndreas Gohr   }
4996de3759aSAndreas Gohr
5006de3759aSAndreas Gohr  return $xlink;
5016de3759aSAndreas Gohr}
5026de3759aSAndreas Gohr
5036de3759aSAndreas Gohr
5046de3759aSAndreas Gohr
5056de3759aSAndreas Gohr/**
506f3f0262cSandi * Just builds a link to a script
50715fae107Sandi *
508ed7b5f09Sandi * @todo   maybe obsolete
50915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
510f3f0262cSandi */
511f3f0262cSandifunction script($script='doku.php'){
512ed7b5f09Sandi#  $link = getBaseURL();
513ed7b5f09Sandi#  $link .= $script;
514ed7b5f09Sandi#  return $link;
515ed7b5f09Sandi  return DOKU_BASE.DOKU_SCRIPT;
516f3f0262cSandi}
517f3f0262cSandi
518f3f0262cSandi/**
51915fae107Sandi * Spamcheck against wordlist
52015fae107Sandi *
521f3f0262cSandi * Checks the wikitext against a list of blocked expressions
522f3f0262cSandi * returns true if the text contains any bad words
52315fae107Sandi *
524e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
525e403cc58SMichael Klier *
526e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
527e403cc58SMichael Klier *  and gain information about the user who was blocked.
528e403cc58SMichael Klier *
529e403cc58SMichael Klier *  Event data:
530e403cc58SMichael Klier *    data['matches']  - array of matches
531e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
532e403cc58SMichael Klier *      [ip]           - ip address
533e403cc58SMichael Klier *      [user]         - username (if logged in)
534e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
535e403cc58SMichael Klier *      [name]         - real name (if logged in)
536e403cc58SMichael Klier *
53715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
5386dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
5396dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
5406dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
541f3f0262cSandi */
5426dffa0e0SAndreas Gohrfunction checkwordblock($text=''){
543f3f0262cSandi  global $TEXT;
5446dffa0e0SAndreas Gohr  global $PRE;
5456dffa0e0SAndreas Gohr  global $SUF;
546f3f0262cSandi  global $conf;
547e403cc58SMichael Klier  global $INFO;
548f3f0262cSandi
549f3f0262cSandi  if(!$conf['usewordblock']) return false;
550f3f0262cSandi
5516dffa0e0SAndreas Gohr  if(!$text) $text = "$PRE $TEXT $SUF";
5526dffa0e0SAndreas Gohr
553041d1964SAndreas Gohr  // we prepare the text a tiny bit to prevent spammers circumventing URL checks
5546dffa0e0SAndreas Gohr  $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
555041d1964SAndreas Gohr
556b9ac8716Schris  $wordblocks = getWordblocks();
5573e2965d7Sandi  //how many lines to read at once (to work around some PCRE limits)
5583e2965d7Sandi  if(version_compare(phpversion(),'4.3.0','<')){
5593e2965d7Sandi    //old versions of PCRE define a maximum of parenthesises even if no
5603e2965d7Sandi    //backreferences are used - the maximum is 99
5613e2965d7Sandi    //this is very bad performancewise and may even be too high still
5623e2965d7Sandi    $chunksize = 40;
5633e2965d7Sandi  }else{
564a51d08efSAndreas Gohr    //read file in chunks of 200 - this should work around the
5653e2965d7Sandi    //MAX_PATTERN_SIZE in modern PCRE
566a51d08efSAndreas Gohr    $chunksize = 200;
5673e2965d7Sandi  }
568b9ac8716Schris  while($blocks = array_splice($wordblocks,0,$chunksize)){
569f3f0262cSandi    $re = array();
570f3f0262cSandi    #build regexp from blocks
571f3f0262cSandi    foreach($blocks as $block){
572f3f0262cSandi      $block = preg_replace('/#.*$/','',$block);
573f3f0262cSandi      $block = trim($block);
574f3f0262cSandi      if(empty($block)) continue;
575f3f0262cSandi      $re[]  = $block;
576f3f0262cSandi    }
577e403cc58SMichael Klier    if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
578e403cc58SMichael Klier      //prepare event data
579e403cc58SMichael Klier      $data['matches'] = $matches;
580e403cc58SMichael Klier      $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
581e403cc58SMichael Klier      if($_SERVER['REMOTE_USER']) {
582e403cc58SMichael Klier          $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
583e403cc58SMichael Klier          $data['userinfo']['name'] = $INFO['userinfo']['name'];
584e403cc58SMichael Klier          $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
585e403cc58SMichael Klier      }
586e403cc58SMichael Klier      $callback = create_function('', 'return true;');
587e403cc58SMichael Klier      return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
588b9ac8716Schris    }
589703f6fdeSandi  }
590f3f0262cSandi  return false;
591f3f0262cSandi}
592f3f0262cSandi
593f3f0262cSandi/**
59415fae107Sandi * Return the IP of the client
59515fae107Sandi *
5966d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
59715fae107Sandi *
5986d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5996d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
6006d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
6016d8affe6SAndreas Gohr * headers
6026d8affe6SAndreas Gohr *
6036d8affe6SAndreas Gohr * @param  boolean $single If set only a single IP is returned
60415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
605f3f0262cSandi */
6066d8affe6SAndreas Gohrfunction clientIP($single=false){
6076d8affe6SAndreas Gohr  $ip = array();
6086d8affe6SAndreas Gohr  $ip[] = $_SERVER['REMOTE_ADDR'];
609bb4866bdSchris  if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
6106d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
611bb4866bdSchris  if(!empty($_SERVER['HTTP_X_REAL_IP']))
6126d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
6136d8affe6SAndreas Gohr
614dc14c6d1SGuy Brand  // some IPv4/v6 regexps borrowed from Feyd
615dc14c6d1SGuy Brand  // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
616dc14c6d1SGuy Brand  $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
617dc14c6d1SGuy Brand  $hex_digit = '[A-Fa-f0-9]';
618dc14c6d1SGuy Brand  $h16 = "{$hex_digit}{1,4}";
619dc14c6d1SGuy Brand  $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
620dc14c6d1SGuy Brand  $ls32 = "(?:$h16:$h16|$IPv4Address)";
621dc14c6d1SGuy Brand  $IPv6Address =
622dc14c6d1SGuy Brand    "(?:(?:{$IPv4Address})|(?:".
623dc14c6d1SGuy Brand    "(?:$h16:){6}$ls32" .
624dc14c6d1SGuy Brand    "|::(?:$h16:){5}$ls32" .
625dc14c6d1SGuy Brand    "|(?:$h16)?::(?:$h16:){4}$ls32" .
626dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
627dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
628dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
629dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
630dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,5}$h16)?::$h16" .
631dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,6}$h16)?::" .
632dc14c6d1SGuy Brand    ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
633dc14c6d1SGuy Brand
6346d8affe6SAndreas Gohr  // remove any non-IP stuff
6356d8affe6SAndreas Gohr  $cnt = count($ip);
6364ff28443Schris  $match = array();
6376d8affe6SAndreas Gohr  for($i=0; $i<$cnt; $i++){
638dc14c6d1SGuy Brand    if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
6394ff28443Schris      $ip[$i] = $match[0];
6404ff28443Schris    } else {
6414ff28443Schris      $ip[$i] = '';
6424ff28443Schris    }
6436d8affe6SAndreas Gohr    if(empty($ip[$i])) unset($ip[$i]);
644f3f0262cSandi  }
6456d8affe6SAndreas Gohr  $ip = array_values(array_unique($ip));
6466d8affe6SAndreas Gohr  if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6476d8affe6SAndreas Gohr
6486d8affe6SAndreas Gohr  if(!$single) return join(',',$ip);
6496d8affe6SAndreas Gohr
6506d8affe6SAndreas Gohr  // decide which IP to use, trying to avoid local addresses
6516d8affe6SAndreas Gohr  $ip = array_reverse($ip);
6526d8affe6SAndreas Gohr  foreach($ip as $i){
6536d8affe6SAndreas Gohr    if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
6546d8affe6SAndreas Gohr      continue;
6556d8affe6SAndreas Gohr    }else{
6566d8affe6SAndreas Gohr      return $i;
6576d8affe6SAndreas Gohr    }
6586d8affe6SAndreas Gohr  }
6596d8affe6SAndreas Gohr  // still here? just use the first (last) address
6606d8affe6SAndreas Gohr  return $ip[0];
661f3f0262cSandi}
662f3f0262cSandi
663f3f0262cSandi/**
6641c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6651c548ebeSAndreas Gohr *
6661c548ebeSAndreas Gohr * Adapted from the example code at url below
6671c548ebeSAndreas Gohr *
6681c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6691c548ebeSAndreas Gohr */
6701c548ebeSAndreas Gohrfunction clientismobile(){
6711c548ebeSAndreas Gohr
6721c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
6731c548ebeSAndreas Gohr
6741c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
6751c548ebeSAndreas Gohr
6761c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
6771c548ebeSAndreas Gohr
6781c548ebeSAndreas Gohr    $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';
6791c548ebeSAndreas Gohr
6801c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
6811c548ebeSAndreas Gohr
6821c548ebeSAndreas Gohr    return false;
6831c548ebeSAndreas Gohr}
6841c548ebeSAndreas Gohr
6851c548ebeSAndreas Gohr
6861c548ebeSAndreas Gohr/**
68763211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
68863211f61SGlen Harris *
68963211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
69063211f61SGlen Harris * @returns a comma separated list of hostnames
69163211f61SGlen Harris */
69263211f61SGlen Harrisfunction gethostsbyaddrs($ips){
69363211f61SGlen Harris  $hosts = array();
69463211f61SGlen Harris  $ips = explode(',',$ips);
695551a720fSMichael Klier
696551a720fSMichael Klier  if(is_array($ips)) {
6973886270dSAndreas Gohr    foreach($ips as $ip){
698551a720fSMichael Klier      $hosts[] = gethostbyaddr(trim($ip));
69963211f61SGlen Harris    }
700551a720fSMichael Klier    return join(',',$hosts);
701551a720fSMichael Klier  } else {
702551a720fSMichael Klier    return gethostbyaddr(trim($ips));
703551a720fSMichael Klier  }
70463211f61SGlen Harris}
70563211f61SGlen Harris
70663211f61SGlen Harris/**
70715fae107Sandi * Checks if a given page is currently locked.
70815fae107Sandi *
709f3f0262cSandi * removes stale lockfiles
71015fae107Sandi *
71115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
712f3f0262cSandi */
713f3f0262cSandifunction checklock($id){
714f3f0262cSandi  global $conf;
715c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
716f3f0262cSandi
717f3f0262cSandi  //no lockfile
718f3f0262cSandi  if(!@file_exists($lock)) return false;
719f3f0262cSandi
720f3f0262cSandi  //lockfile expired
721f3f0262cSandi  if((time() - filemtime($lock)) > $conf['locktime']){
722d8186216SBen Coburn    @unlink($lock);
723f3f0262cSandi    return false;
724f3f0262cSandi  }
725f3f0262cSandi
726f3f0262cSandi  //my own lock
727f3f0262cSandi  $ip = io_readFile($lock);
728f3f0262cSandi  if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
729f3f0262cSandi    return false;
730f3f0262cSandi  }
731f3f0262cSandi
732f3f0262cSandi  return $ip;
733f3f0262cSandi}
734f3f0262cSandi
735f3f0262cSandi/**
73615fae107Sandi * Lock a page for editing
73715fae107Sandi *
73815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
739f3f0262cSandi */
740f3f0262cSandifunction lock($id){
741c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
742f3f0262cSandi  if($_SERVER['REMOTE_USER']){
743f3f0262cSandi    io_saveFile($lock,$_SERVER['REMOTE_USER']);
744f3f0262cSandi  }else{
745f3f0262cSandi    io_saveFile($lock,clientIP());
746f3f0262cSandi  }
747f3f0262cSandi}
748f3f0262cSandi
749f3f0262cSandi/**
75015fae107Sandi * Unlock a page if it was locked by the user
751f3f0262cSandi *
75215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
75315fae107Sandi * @return bool true if a lock was removed
754f3f0262cSandi */
755f3f0262cSandifunction unlock($id){
756c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
757f3f0262cSandi  if(@file_exists($lock)){
758f3f0262cSandi    $ip = io_readFile($lock);
759f3f0262cSandi    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
760f3f0262cSandi      @unlink($lock);
761f3f0262cSandi      return true;
762f3f0262cSandi    }
763f3f0262cSandi  }
764f3f0262cSandi  return false;
765f3f0262cSandi}
766f3f0262cSandi
767f3f0262cSandi/**
768f3f0262cSandi * convert line ending to unix format
769f3f0262cSandi *
77015fae107Sandi * @see    formText() for 2crlf conversion
77115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
772f3f0262cSandi */
773f3f0262cSandifunction cleanText($text){
774f3f0262cSandi  $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
775f3f0262cSandi  return $text;
776f3f0262cSandi}
777f3f0262cSandi
778f3f0262cSandi/**
779f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
780f3f0262cSandi * It also converts line endings to Windows format which is
781f3f0262cSandi * pseudo standard for webforms.
782f3f0262cSandi *
78315fae107Sandi * @see    cleanText() for 2unix conversion
78415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
785f3f0262cSandi */
786f3f0262cSandifunction formText($text){
7875b7d45a5SAndreas Gohr  $text = str_replace("\012","\015\012",$text);
788f3f0262cSandi  return htmlspecialchars($text);
789f3f0262cSandi}
790f3f0262cSandi
791f3f0262cSandi/**
79215fae107Sandi * Returns the specified local text in raw format
79315fae107Sandi *
79415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
795f3f0262cSandi */
796f3f0262cSandifunction rawLocale($id){
797f3f0262cSandi  return io_readFile(localeFN($id));
798f3f0262cSandi}
799f3f0262cSandi
800f3f0262cSandi/**
801f3f0262cSandi * Returns the raw WikiText
80215fae107Sandi *
80315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
804f3f0262cSandi */
805f3f0262cSandifunction rawWiki($id,$rev=''){
806cc7d0c94SBen Coburn  return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
807f3f0262cSandi}
808f3f0262cSandi
809f3f0262cSandi/**
8107146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8117146cee2SAndreas Gohr *
8127146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8137146cee2SAndreas Gohr */
814b7d5a5f0SAndreas Gohrfunction pageTemplate($data){
815b7d5a5f0SAndreas Gohr  $id = $data[0];
816a15ce62dSEsther Brunner  global $conf;
817a15ce62dSEsther Brunner  global $INFO;
818e29549feSAndreas Gohr
819e29549feSAndreas Gohr  $path = dirname(wikiFN($id));
820e29549feSAndreas Gohr
821e29549feSAndreas Gohr  if(@file_exists($path.'/_template.txt')){
822e29549feSAndreas Gohr    $tpl = io_readFile($path.'/_template.txt');
823e29549feSAndreas Gohr  }else{
824e29549feSAndreas Gohr    // search upper namespaces for templates
825e29549feSAndreas Gohr    $len = strlen(rtrim($conf['datadir'],'/'));
826e29549feSAndreas Gohr    while (strlen($path) >= $len){
827e29549feSAndreas Gohr      if(@file_exists($path.'/__template.txt')){
828e29549feSAndreas Gohr        $tpl = io_readFile($path.'/__template.txt');
829e29549feSAndreas Gohr        break;
830e29549feSAndreas Gohr      }
831e29549feSAndreas Gohr      $path = substr($path, 0, strrpos($path, '/'));
832e29549feSAndreas Gohr    }
833e29549feSAndreas Gohr  }
834e29549feSAndreas Gohr  if(!$tpl) return '';
835e29549feSAndreas Gohr
836e29549feSAndreas Gohr  // replace placeholders
83726ece5a7SAndreas Gohr  $file = noNS($id);
83826ece5a7SAndreas Gohr  $page = strtr($file,'_',' ');
83926ece5a7SAndreas Gohr
84026ece5a7SAndreas Gohr  $tpl = str_replace(array(
84126ece5a7SAndreas Gohr                        '@ID@',
84226ece5a7SAndreas Gohr                        '@NS@',
84326ece5a7SAndreas Gohr                        '@FILE@',
84426ece5a7SAndreas Gohr                        '@!FILE@',
84526ece5a7SAndreas Gohr                        '@!FILE!@',
84626ece5a7SAndreas Gohr                        '@PAGE@',
84726ece5a7SAndreas Gohr                        '@!PAGE@',
84826ece5a7SAndreas Gohr                        '@!!PAGE@',
84926ece5a7SAndreas Gohr                        '@!PAGE!@',
85026ece5a7SAndreas Gohr                        '@USER@',
85126ece5a7SAndreas Gohr                        '@NAME@',
85226ece5a7SAndreas Gohr                        '@MAIL@',
85326ece5a7SAndreas Gohr                        '@DATE@',
85426ece5a7SAndreas Gohr                     ),
85526ece5a7SAndreas Gohr                     array(
85626ece5a7SAndreas Gohr                        $id,
85726ece5a7SAndreas Gohr                        getNS($id),
85826ece5a7SAndreas Gohr                        $file,
85926ece5a7SAndreas Gohr                        utf8_ucfirst($file),
86026ece5a7SAndreas Gohr                        utf8_strtoupper($file),
86126ece5a7SAndreas Gohr                        $page,
86226ece5a7SAndreas Gohr                        utf8_ucfirst($page),
86326ece5a7SAndreas Gohr                        utf8_ucwords($page),
86426ece5a7SAndreas Gohr                        utf8_strtoupper($page),
86526ece5a7SAndreas Gohr                        $_SERVER['REMOTE_USER'],
86626ece5a7SAndreas Gohr                        $INFO['userinfo']['name'],
86726ece5a7SAndreas Gohr                        $INFO['userinfo']['mail'],
86826ece5a7SAndreas Gohr                        $conf['dformat'],
86926ece5a7SAndreas Gohr                     ), $tpl);
87026ece5a7SAndreas Gohr
8717d644fc8SAndreas Gohr  // we need the callback to work around strftime's char limit
8727d644fc8SAndreas Gohr  $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
8737d644fc8SAndreas Gohr
874a15ce62dSEsther Brunner  return $tpl;
8757146cee2SAndreas Gohr}
8767146cee2SAndreas Gohr
8777146cee2SAndreas Gohr
8787146cee2SAndreas Gohr/**
87915fae107Sandi * Returns the raw Wiki Text in three slices.
88015fae107Sandi *
88115fae107Sandi * The range parameter needs to have the form "from-to"
88215cfe303Sandi * and gives the range of the section in bytes - no
88315cfe303Sandi * UTF-8 awareness is needed.
884f3f0262cSandi * The returned order is prefix, section and suffix.
88515fae107Sandi *
88615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
887f3f0262cSandi */
888f3f0262cSandifunction rawWikiSlices($range,$id,$rev=''){
8894b7f9e70STom N Harris  list($from,$to) = explode('-',$range,2);
890cc7d0c94SBen Coburn  $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
891f3f0262cSandi  if(!$from) $from = 0;
892c3d8e19bSandi  if(!$to)   $to   = strlen($text)+1;
893f3f0262cSandi
89415cfe303Sandi  $slices[0] = substr($text,0,$from-1);
89515cfe303Sandi  $slices[1] = substr($text,$from-1,$to-$from);
89615cfe303Sandi  $slices[2] = substr($text,$to);
897f3f0262cSandi
898f3f0262cSandi  return $slices;
899f3f0262cSandi}
900f3f0262cSandi
901f3f0262cSandi/**
90215fae107Sandi * Joins wiki text slices
90315fae107Sandi *
904f3f0262cSandi * function to join the text slices with correct lineendings again.
905f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
906f3f0262cSandi * lines between sections if needed (used on saving).
90715fae107Sandi *
90815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
909f3f0262cSandi */
910f3f0262cSandifunction con($pre,$text,$suf,$pretty=false){
911f3f0262cSandi
912f3f0262cSandi  if($pretty){
913f3f0262cSandi    if($pre && substr($pre,-1) != "\n") $pre .= "\n";
914f3f0262cSandi    if($suf && substr($text,-1) != "\n") $text .= "\n";
915f3f0262cSandi  }
916f3f0262cSandi
9177e038d4eSAndreas Gohr  // Avoid double newline above section when saving section edit
9187e038d4eSAndreas Gohr  //if($pre) $pre .= "\n";
919f3f0262cSandi  if($suf) $text .= "\n";
920f3f0262cSandi  return $pre.$text.$suf;
921f3f0262cSandi}
922f3f0262cSandi
923f3f0262cSandi/**
924a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
925a701424fSBen Coburn * Also directs changelog and attic updates.
92615fae107Sandi *
92715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
92871726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
929f3f0262cSandi */
930b6912aeaSAndreas Gohrfunction saveWikiText($id,$text,$summary,$minor=false){
931a701424fSBen Coburn  /* Note to developers:
932a701424fSBen Coburn     This code is subtle and delicate. Test the behavior of
933a701424fSBen Coburn     the attic and changelog with dokuwiki and external edits
934a701424fSBen Coburn     after any changes. External edits change the wiki page
935a701424fSBen Coburn     directly without using php or dokuwiki.
936a701424fSBen Coburn  */
937f3f0262cSandi  global $conf;
938f3f0262cSandi  global $lang;
93971726d78SBen Coburn  global $REV;
940f3f0262cSandi  // ignore if no changes were made
941f3f0262cSandi  if($text == rawWiki($id,'')){
942f3f0262cSandi    return;
943f3f0262cSandi  }
944f3f0262cSandi
945f3f0262cSandi  $file = wikiFN($id);
946a701424fSBen Coburn  $old = @filemtime($file); // from page
94771726d78SBen Coburn  $wasRemoved = empty($text);
948d8186216SBen Coburn  $wasCreated = !@file_exists($file);
94971726d78SBen Coburn  $wasReverted = ($REV==true);
950e45b34cdSBen Coburn  $newRev = false;
951a701424fSBen Coburn  $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
952a701424fSBen Coburn  $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
953a701424fSBen Coburn  if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
95446844156SBen Coburn    // add old revision to the attic if missing
95546844156SBen Coburn    saveOldRevision($id);
95646844156SBen Coburn    // add a changelog entry if this edit came from outside dokuwiki
957a701424fSBen Coburn    if ($old>$oldRev) {
958ebf1501fSBen Coburn      addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
95946844156SBen Coburn      // remove soon to be stale instructions
96046844156SBen Coburn      $cache = new cache_instructions($id, $file);
96146844156SBen Coburn      $cache->removeCache();
96246844156SBen Coburn    }
96346844156SBen Coburn  }
964f3f0262cSandi
96571726d78SBen Coburn  if ($wasRemoved){
96630725328SGabriel Birke    // Send "update" event with empty data, so plugins can react to page deletion
96730725328SGabriel Birke    $data = array(array($file, '', false), getNS($id), noNS($id), false);
96830725328SGabriel Birke    trigger_event('IO_WIKIPAGE_WRITE', $data);
969e45b34cdSBen Coburn    // pre-save deleted revision
970e45b34cdSBen Coburn    @touch($file);
97146844156SBen Coburn    clearstatcache();
972e45b34cdSBen Coburn    $newRev = saveOldRevision($id);
973e1f3d9e1SEsther Brunner    // remove empty file
974f3f0262cSandi    @unlink($file);
97571726d78SBen Coburn    // remove old meta info...
976e1f3d9e1SEsther Brunner    $mfiles = metaFiles($id);
97771726d78SBen Coburn    $changelog = metaFN($id, '.changes');
9783d1f9ec3SMichael Klier    $metadata  = metaFN($id, '.meta');
979e1f3d9e1SEsther Brunner    foreach ($mfiles as $mfile) {
9803d1f9ec3SMichael Klier      // but keep per-page changelog to preserve page history and keep meta data
9813d1f9ec3SMichael Klier      if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); }
982b158d625SSteven Danz    }
9833d1f9ec3SMichael Klier    // purge meta data
9843d1f9ec3SMichael Klier    p_purge_metadata($id);
985f3f0262cSandi    $del = true;
9863ce054b3Sandi    // autoset summary on deletion
9873ce054b3Sandi    if(empty($summary)) $summary = $lang['deleted'];
98853d6ccfeSandi    // remove empty namespaces
989cc7d0c94SBen Coburn    io_sweepNS($id, 'datadir');
990cc7d0c94SBen Coburn    io_sweepNS($id, 'mediadir');
991f3f0262cSandi  }else{
992cc7d0c94SBen Coburn    // save file (namespace dir is created in io_writeWikiPage)
993cc7d0c94SBen Coburn    io_writeWikiPage($file, $text, $id);
99446844156SBen Coburn    // pre-save the revision, to keep the attic in sync
99546844156SBen Coburn    $newRev = saveOldRevision($id);
996f3f0262cSandi    $del = false;
997f3f0262cSandi  }
998f3f0262cSandi
99971726d78SBen Coburn  // select changelog line type
100071726d78SBen Coburn  $extra = '';
1001ebf1501fSBen Coburn  $type = DOKU_CHANGE_TYPE_EDIT;
100271726d78SBen Coburn  if ($wasReverted) {
1003ebf1501fSBen Coburn    $type = DOKU_CHANGE_TYPE_REVERT;
100471726d78SBen Coburn    $extra = $REV;
100571726d78SBen Coburn  }
1006ebf1501fSBen Coburn  else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
1007ebf1501fSBen Coburn  else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
1008ebf1501fSBen Coburn  else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
100971726d78SBen Coburn
1010e45b34cdSBen Coburn  addLogEntry($newRev, $id, $type, $summary, $extra);
101126a0801fSAndreas Gohr  // send notify mails
101290033e9dSAndreas Gohr  notify($id,'admin',$old,$summary,$minor);
101390033e9dSAndreas Gohr  notify($id,'subscribers',$old,$summary,$minor);
1014f3f0262cSandi
1015ce6b63d9Schris  // update the purgefile (timestamp of the last time anything within the wiki was changed)
101698407a7aSandi  io_saveFile($conf['cachedir'].'/purgefile',time());
10172eccbdaaSGina Haeussge
10182eccbdaaSGina Haeussge  // if useheading is enabled, purge the cache of all linking pages
1019fe9ec250SChris Smith  if(useHeading('content')){
10202eccbdaaSGina Haeussge    require_once(DOKU_INC.'inc/fulltext.php');
10212eccbdaaSGina Haeussge    $pages = ft_backlinks($id);
10222eccbdaaSGina Haeussge    foreach ($pages as $page) {
10232eccbdaaSGina Haeussge      $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
10242eccbdaaSGina Haeussge      $cache->removeCache();
10252eccbdaaSGina Haeussge    }
10262eccbdaaSGina Haeussge  }
1027f3f0262cSandi}
1028f3f0262cSandi
1029f3f0262cSandi/**
1030f3f0262cSandi * moves the current version to the attic and returns its
1031f3f0262cSandi * revision date
103215fae107Sandi *
103315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1034f3f0262cSandi */
1035f3f0262cSandifunction saveOldRevision($id){
1036f3f0262cSandi  global $conf;
1037f3f0262cSandi  $oldf = wikiFN($id);
1038f3f0262cSandi  if(!@file_exists($oldf)) return '';
1039f3f0262cSandi  $date = filemtime($oldf);
1040f3f0262cSandi  $newf = wikiFN($id,$date);
1041cc7d0c94SBen Coburn  io_writeWikiPage($newf, rawWiki($id), $id, $date);
1042f3f0262cSandi  return $date;
1043f3f0262cSandi}
1044f3f0262cSandi
1045f3f0262cSandi/**
104626a0801fSAndreas Gohr * Sends a notify mail on page change
104726a0801fSAndreas Gohr *
104826a0801fSAndreas Gohr * @param  string  $id       The changed page
104926a0801fSAndreas Gohr * @param  string  $who      Who to notify (admin|subscribers)
105026a0801fSAndreas Gohr * @param  int     $rev      Old page revision
105126a0801fSAndreas Gohr * @param  string  $summary  What changed
105290033e9dSAndreas Gohr * @param  boolean $minor    Is this a minor edit?
105302a498e7Schris * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
105415fae107Sandi *
105515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1056f3f0262cSandi */
105702a498e7Schrisfunction notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1058f3f0262cSandi  global $lang;
1059f3f0262cSandi  global $conf;
106030d7d718SMike Frysinger  global $INFO;
1061b158d625SSteven Danz
106226a0801fSAndreas Gohr  // decide if there is something to do
106326a0801fSAndreas Gohr  if($who == 'admin'){
106426a0801fSAndreas Gohr    if(empty($conf['notify'])) return; //notify enabled?
1065f3f0262cSandi    $text = rawLocale('mailtext');
106626a0801fSAndreas Gohr    $to   = $conf['notify'];
106726a0801fSAndreas Gohr    $bcc  = '';
106826a0801fSAndreas Gohr  }elseif($who == 'subscribers'){
106926a0801fSAndreas Gohr    if(!$conf['subscribers']) return; //subscribers enabled?
107090033e9dSAndreas Gohr    if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
107155eea442SAndreas Gohr    $bcc  = subscriber_addresslist($id,false);
107226a0801fSAndreas Gohr    if(empty($bcc)) return;
107326a0801fSAndreas Gohr    $to   = '';
107426a0801fSAndreas Gohr    $text = rawLocale('subscribermail');
1075a06e4bdbSSebastian Harl  }elseif($who == 'register'){
1076a06e4bdbSSebastian Harl    if(empty($conf['registernotify'])) return;
1077a06e4bdbSSebastian Harl    $text = rawLocale('registermail');
1078a06e4bdbSSebastian Harl    $to   = $conf['registernotify'];
1079a06e4bdbSSebastian Harl    $bcc  = '';
108026a0801fSAndreas Gohr  }else{
108126a0801fSAndreas Gohr    return; //just to be safe
108226a0801fSAndreas Gohr  }
108326a0801fSAndreas Gohr
108463211f61SGlen Harris  $ip   = clientIP();
1085*f2263577SAndreas Gohr  $text = str_replace('@DATE@',dformat(),$text);
1086f3f0262cSandi  $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
108763211f61SGlen Harris  $text = str_replace('@IPADDRESS@',$ip,$text);
108863211f61SGlen Harris  $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1089c9321d91SAndreas Gohr  $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
109026a0801fSAndreas Gohr  $text = str_replace('@PAGE@',$id,$text);
109126a0801fSAndreas Gohr  $text = str_replace('@TITLE@',$conf['title'],$text);
1092ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1093f3f0262cSandi  $text = str_replace('@SUMMARY@',$summary,$text);
10947a82afdcSandi  $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1095f3f0262cSandi
109602a498e7Schris  foreach ($replace as $key => $substitution) {
109702a498e7Schris    $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
109802a498e7Schris  }
109902a498e7Schris
1100a06e4bdbSSebastian Harl  if($who == 'register'){
1101a06e4bdbSSebastian Harl    $subject = $lang['mail_new_user'].' '.$summary;
1102a06e4bdbSSebastian Harl  }elseif($rev){
1103f3f0262cSandi    $subject = $lang['mail_changed'].' '.$id;
1104c9321d91SAndreas Gohr    $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1105ccdfa6c0SAndreas Gohr    require_once(DOKU_INC.'inc/DifferenceEngine.php');
11064b7f9e70STom N Harris    $df  = new Diff(explode("\n",rawWiki($id,$rev)),
11074b7f9e70STom N Harris                    explode("\n",rawWiki($id)));
1108f3f0262cSandi    $dformat = new UnifiedDiffFormatter();
1109f3f0262cSandi    $diff    = $dformat->format($df);
1110f3f0262cSandi  }else{
1111f3f0262cSandi    $subject=$lang['mail_newpage'].' '.$id;
1112f3f0262cSandi    $text = str_replace('@OLDPAGE@','none',$text);
1113f3f0262cSandi    $diff = rawWiki($id);
1114f3f0262cSandi  }
1115f3f0262cSandi  $text = str_replace('@DIFF@',$diff,$text);
1116241f3a36Sandi  $subject = '['.$conf['title'].'] '.$subject;
1117f3f0262cSandi
111830d7d718SMike Frysinger  $from = $conf['mailfrom'];
111930d7d718SMike Frysinger  $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
112030d7d718SMike Frysinger  $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
112130d7d718SMike Frysinger  $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
112230d7d718SMike Frysinger
112330d7d718SMike Frysinger  mail_send($to,$subject,$text,$from,'',$bcc);
1124f3f0262cSandi}
1125f3f0262cSandi
112615fae107Sandi/**
112771f7bde7SAndreas Gohr * extracts the query from a search engine referrer
112815fae107Sandi *
112915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
113071f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1131f3f0262cSandi */
1132f3f0262cSandifunction getGoogleQuery(){
1133f3f0262cSandi  $url = parse_url($_SERVER['HTTP_REFERER']);
11345c3f206fSandi  if(!$url) return '';
1135f3f0262cSandi
1136f3f0262cSandi  $query = array();
1137f3f0262cSandi  parse_str($url['query'],$query);
113871f7bde7SAndreas Gohr  if(isset($query['q']))
1139f93b3b50SAndreas Gohr    $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
114071f7bde7SAndreas Gohr  elseif(isset($query['p']))
1141f93b3b50SAndreas Gohr    $q = $query['p'];        // yahoo
114271f7bde7SAndreas Gohr  elseif(isset($query['query']))
1143f93b3b50SAndreas Gohr    $q = $query['query'];    // lycos, netscape, clusty, hotbot
114471f7bde7SAndreas Gohr  elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1145f93b3b50SAndreas Gohr    $q = urldecode(ltrim($url['path'],'/'));
1146f3f0262cSandi
1147f93b3b50SAndreas Gohr  if(!$q) return '';
11486531ab03SAndreas Gohr  $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1149f93b3b50SAndreas Gohr  return $q;
1150f3f0262cSandi}
1151f3f0262cSandi
1152f3f0262cSandi/**
115315fae107Sandi * Try to set correct locale
115415fae107Sandi *
1155095bfd5cSandi * @deprecated No longer used
115615fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1157f3f0262cSandi */
1158f3f0262cSandifunction setCorrectLocale(){
1159f3f0262cSandi  global $conf;
1160f3f0262cSandi  global $lang;
1161f3f0262cSandi
1162f3f0262cSandi  $enc = strtoupper($lang['encoding']);
1163f3f0262cSandi  foreach ($lang['locales'] as $loc){
1164f3f0262cSandi    //try locale
1165f3f0262cSandi    if(@setlocale(LC_ALL,$loc)) return;
1166f3f0262cSandi    //try loceale with encoding
1167f3f0262cSandi    if(@setlocale(LC_ALL,"$loc.$enc")) return;
1168f3f0262cSandi  }
1169f3f0262cSandi  //still here? try to set from environment
1170f3f0262cSandi  @setlocale(LC_ALL,"");
1171f3f0262cSandi}
1172f3f0262cSandi
1173f3f0262cSandi/**
1174f3f0262cSandi * Return the human readable size of a file
1175f3f0262cSandi *
1176f3f0262cSandi * @param       int    $size   A file size
1177f3f0262cSandi * @param       int    $dec    A number of decimal places
1178f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1179f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1180f3f0262cSandi * @version     1.0.0
1181f3f0262cSandi */
1182f31d5b73Sandifunction filesize_h($size, $dec = 1){
1183f3f0262cSandi  $sizes = array('B', 'KB', 'MB', 'GB');
1184f3f0262cSandi  $count = count($sizes);
1185f3f0262cSandi  $i = 0;
1186f3f0262cSandi
1187f3f0262cSandi  while ($size >= 1024 && ($i < $count - 1)) {
1188f3f0262cSandi    $size /= 1024;
1189f3f0262cSandi    $i++;
1190f3f0262cSandi  }
1191f3f0262cSandi
1192f3f0262cSandi  return round($size, $dec) . ' ' . $sizes[$i];
1193f3f0262cSandi}
1194f3f0262cSandi
119515fae107Sandi/**
1196c57e365eSAndreas Gohr * Return the given timestamp as human readable, fuzzy age
1197c57e365eSAndreas Gohr *
1198c57e365eSAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1199c57e365eSAndreas Gohr */
1200c57e365eSAndreas Gohrfunction datetime_h($dt){
1201c57e365eSAndreas Gohr  global $lang;
1202c57e365eSAndreas Gohr
1203c57e365eSAndreas Gohr  $ago = time() - $dt;
1204c57e365eSAndreas Gohr  if($ago > 24*60*60*30*12*2){
1205c57e365eSAndreas Gohr    return sprintf($lang['years'], round($ago/(24*60*60*30*12)));
1206c57e365eSAndreas Gohr  }
1207c57e365eSAndreas Gohr  if($ago > 24*60*60*30*2){
1208c57e365eSAndreas Gohr    return sprintf($lang['months'], round($ago/(24*60*60*30)));
1209c57e365eSAndreas Gohr  }
1210c57e365eSAndreas Gohr  if($ago > 24*60*60*7*2){
1211c57e365eSAndreas Gohr    return sprintf($lang['weeks'], round($ago/(24*60*60*7)));
1212c57e365eSAndreas Gohr  }
1213c57e365eSAndreas Gohr  if($ago > 24*60*60*2){
1214c57e365eSAndreas Gohr    return sprintf($lang['days'], round($ago/(24*60*60)));
1215c57e365eSAndreas Gohr  }
1216c57e365eSAndreas Gohr  if($ago > 60*60*2){
1217c57e365eSAndreas Gohr    return sprintf($lang['hours'], round($ago/(60*60)));
1218c57e365eSAndreas Gohr  }
1219c57e365eSAndreas Gohr  if($ago > 60*2){
1220c57e365eSAndreas Gohr    return sprintf($lang['minutes'], round($ago/(60)));
1221c57e365eSAndreas Gohr  }
1222c57e365eSAndreas Gohr  return sprintf($lang['seconds'], $ago);
1223c57e365eSAndreas Gohr
1224c57e365eSAndreas Gohr}
1225c57e365eSAndreas Gohr
1226c57e365eSAndreas Gohr/**
1227*f2263577SAndreas Gohr * Wraps around strftime but provides support for fuzzy dates
1228*f2263577SAndreas Gohr *
1229*f2263577SAndreas Gohr * The format default to $conf['dformat']. It is passed to
1230*f2263577SAndreas Gohr * strftime - %f can be used to get the value from datetime_h()
1231*f2263577SAndreas Gohr *
1232*f2263577SAndreas Gohr * @see datetime_h
1233*f2263577SAndreas Gohr * @author Andreas Gohr <gohr@cosmocode.de>
1234*f2263577SAndreas Gohr */
1235*f2263577SAndreas Gohrfunction dformat($dt=null,$format=''){
1236*f2263577SAndreas Gohr  global $conf;
1237*f2263577SAndreas Gohr
1238*f2263577SAndreas Gohr  if(is_null($dt)) $dt = time();
1239*f2263577SAndreas Gohr  $dt = (int) $dt;
1240*f2263577SAndreas Gohr  if(!$format) $format = $conf['dformat'];
1241*f2263577SAndreas Gohr
1242*f2263577SAndreas Gohr  $format = str_replace('%f',datetime_h($dt),$format);
1243*f2263577SAndreas Gohr  return strftime($format,$dt);
1244*f2263577SAndreas Gohr}
1245*f2263577SAndreas Gohr
1246*f2263577SAndreas Gohr/**
124700a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
124800a7b5adSEsther Brunner *
124900a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
125000a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
125100a7b5adSEsther Brunner */
125200a7b5adSEsther Brunnerfunction obfuscate($email) {
125300a7b5adSEsther Brunner  global $conf;
125400a7b5adSEsther Brunner
125500a7b5adSEsther Brunner  switch ($conf['mailguard']) {
125600a7b5adSEsther Brunner    case 'visible' :
125700a7b5adSEsther Brunner      $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
125800a7b5adSEsther Brunner      return strtr($email, $obfuscate);
125900a7b5adSEsther Brunner
126000a7b5adSEsther Brunner    case 'hex' :
126100a7b5adSEsther Brunner      $encode = '';
126200a7b5adSEsther Brunner      for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';';
126300a7b5adSEsther Brunner      return $encode;
126400a7b5adSEsther Brunner
126500a7b5adSEsther Brunner    case 'none' :
126600a7b5adSEsther Brunner    default :
126700a7b5adSEsther Brunner      return $email;
126800a7b5adSEsther Brunner  }
126900a7b5adSEsther Brunner}
127000a7b5adSEsther Brunner
127100a7b5adSEsther Brunner/**
127252b0dd67SGuy Brand * Let us know if a user is tracking a page or a namespace
1273b158d625SSteven Danz *
12741380fc45SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1275b158d625SSteven Danz */
127652b0dd67SGuy Brandfunction is_subscribed($id,$uid,$ns=false){
127752b0dd67SGuy Brand  if(!$ns) {
12781380fc45SAndreas Gohr    $file=metaFN($id,'.mlist');
127952b0dd67SGuy Brand  } else {
128052b0dd67SGuy Brand    if(!getNS($id)) {
128152b0dd67SGuy Brand      $file = metaFN(getNS($id),'.mlist');
128252b0dd67SGuy Brand    } else {
128352b0dd67SGuy Brand      $file = metaFN(getNS($id),'/.mlist');
128452b0dd67SGuy Brand    }
128552b0dd67SGuy Brand  }
12861380fc45SAndreas Gohr  if (@file_exists($file)) {
1287b158d625SSteven Danz    $mlist = file($file);
12881380fc45SAndreas Gohr    $pos = array_search($uid."\n",$mlist);
12891380fc45SAndreas Gohr    return is_int($pos);
1290b158d625SSteven Danz  }
12911380fc45SAndreas Gohr
1292b158d625SSteven Danz  return false;
1293b158d625SSteven Danz}
1294340756e4Sandi
1295f9eb5648Ssteven-danz/**
1296f9eb5648Ssteven-danz * Return a string with the email addresses of all the
1297f9eb5648Ssteven-danz * users subscribed to a page
1298f9eb5648Ssteven-danz *
129926a0801fSAndreas Gohr * @author Steven Danz <steven-danz@kc.rr.com>
1300f9eb5648Ssteven-danz */
130155eea442SAndreas Gohrfunction subscriber_addresslist($id,$self=true){
1302f9eb5648Ssteven-danz  global $conf;
1303cd52f92dSchris  global $auth;
1304f9eb5648Ssteven-danz
130512cb3a51STom N Harris  if (!$conf['subscribers']) return '';
1306f9eb5648Ssteven-danz
130712cb3a51STom N Harris  $users = array();
130812cb3a51STom N Harris  $emails = array();
130926a0801fSAndreas Gohr
131052b0dd67SGuy Brand  // load the page mlist file content
1311f9eb5648Ssteven-danz  $mlist = array();
1312f9eb5648Ssteven-danz  $file=metaFN($id,'.mlist');
1313d8186216SBen Coburn  if (@file_exists($file)) {
1314f9eb5648Ssteven-danz    $mlist = file($file);
1315f9eb5648Ssteven-danz    foreach ($mlist as $who) {
1316f9eb5648Ssteven-danz      $who = rtrim($who);
131755eea442SAndreas Gohr      if(!$self && $who == $_SERVER['REMOTE_USER']) continue;
131812cb3a51STom N Harris      $users[$who] = true;
1319f9eb5648Ssteven-danz    }
1320f9eb5648Ssteven-danz  }
1321f9eb5648Ssteven-danz
132252b0dd67SGuy Brand  // load also the namespace mlist file content
132312cb3a51STom N Harris  $ns = getNS($id);
132412cb3a51STom N Harris  while ($ns) {
132512cb3a51STom N Harris    $nsfile = metaFN($ns,'/.mlist');
132652b0dd67SGuy Brand    if (@file_exists($nsfile)) {
132752b0dd67SGuy Brand      $mlist = file($nsfile);
132852b0dd67SGuy Brand      foreach ($mlist as $who) {
132952b0dd67SGuy Brand        $who = rtrim($who);
133055eea442SAndreas Gohr        if(!$self && $who == $_SERVER['REMOTE_USER']) continue;
133112cb3a51STom N Harris        $users[$who] = true;
133212cb3a51STom N Harris      }
133312cb3a51STom N Harris    }
133412cb3a51STom N Harris    $ns = getNS($ns);
133512cb3a51STom N Harris  }
133612cb3a51STom N Harris  // root namespace
133712cb3a51STom N Harris  $nsfile = metaFN('','.mlist');
133812cb3a51STom N Harris  if (@file_exists($nsfile)) {
133912cb3a51STom N Harris    $mlist = file($nsfile);
134012cb3a51STom N Harris    foreach ($mlist as $who) {
134112cb3a51STom N Harris      $who = rtrim($who);
134255eea442SAndreas Gohr      if(!$self && $who == $_SERVER['REMOTE_USER']) continue;
134312cb3a51STom N Harris      $users[$who] = true;
134412cb3a51STom N Harris    }
134512cb3a51STom N Harris  }
134612cb3a51STom N Harris  if(!empty($users)) {
134712cb3a51STom N Harris    foreach (array_keys($users) as $who) {
134852b0dd67SGuy Brand      $info = $auth->getUserData($who);
134952b0dd67SGuy Brand      if($info === false) continue;
135052b0dd67SGuy Brand      $level = auth_aclcheck($id,$who,$info['grps']);
135152b0dd67SGuy Brand      if ($level >= AUTH_READ) {
135252b0dd67SGuy Brand        if (strcasecmp($info['mail'],$conf['notify']) != 0) {
135312cb3a51STom N Harris          $emails[] = $info['mail'];
135452b0dd67SGuy Brand        }
135552b0dd67SGuy Brand      }
135652b0dd67SGuy Brand    }
135752b0dd67SGuy Brand  }
135852b0dd67SGuy Brand
135912cb3a51STom N Harris  return implode(',',$emails);
1360f9eb5648Ssteven-danz}
1361f9eb5648Ssteven-danz
136289541d4bSAndreas Gohr/**
136389541d4bSAndreas Gohr * Removes quoting backslashes
136489541d4bSAndreas Gohr *
136589541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
136689541d4bSAndreas Gohr */
136789541d4bSAndreas Gohrfunction unslash($string,$char="'"){
136889541d4bSAndreas Gohr  return str_replace('\\'.$char,$char,$string);
136989541d4bSAndreas Gohr}
137089541d4bSAndreas Gohr
137173038c47SAndreas Gohr/**
137273038c47SAndreas Gohr * Convert php.ini shorthands to byte
137373038c47SAndreas Gohr *
137473038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
137573038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
137673038c47SAndreas Gohr */
137773038c47SAndreas Gohrfunction php_to_byte($v){
137873038c47SAndreas Gohr    $l = substr($v, -1);
137973038c47SAndreas Gohr    $ret = substr($v, 0, -1);
138073038c47SAndreas Gohr    switch(strtoupper($l)){
138173038c47SAndreas Gohr        case 'P':
138273038c47SAndreas Gohr            $ret *= 1024;
138373038c47SAndreas Gohr        case 'T':
138473038c47SAndreas Gohr            $ret *= 1024;
138573038c47SAndreas Gohr        case 'G':
138673038c47SAndreas Gohr            $ret *= 1024;
138773038c47SAndreas Gohr        case 'M':
138873038c47SAndreas Gohr            $ret *= 1024;
138973038c47SAndreas Gohr        case 'K':
139073038c47SAndreas Gohr            $ret *= 1024;
139173038c47SAndreas Gohr        break;
139273038c47SAndreas Gohr    }
139373038c47SAndreas Gohr    return $ret;
139473038c47SAndreas Gohr}
139573038c47SAndreas Gohr
1396546d3a99SAndreas Gohr/**
1397546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1398546d3a99SAndreas Gohr */
1399546d3a99SAndreas Gohrfunction preg_quote_cb($string){
1400546d3a99SAndreas Gohr    return preg_quote($string,'/');
1401546d3a99SAndreas Gohr}
140273038c47SAndreas Gohr
1403bd2f6c2fSAndreas Gohr/**
1404bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1405bd2f6c2fSAndreas Gohr *
1406bd2f6c2fSAndreas Gohr * You can give the string in two parts, teh first part $keep
1407bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1408bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1409bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1410bd2f6c2fSAndreas Gohr *
1411bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1412bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1413bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1414bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1415bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1416bd2f6c2fSAndreas Gohr */
1417a5d27328SAndreas Gohrfunction shorten($keep,$short,$max,$min=9,$char='…'){
1418bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1419bd2f6c2fSAndreas Gohr   if($max < $min) return $keep;
1420bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1421bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1422bd2f6c2fSAndreas Gohr    $half = floor($max/2);
1423bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1424bd2f6c2fSAndreas Gohr}
1425bd2f6c2fSAndreas Gohr
1426dc58b6f4SAndy Webber/**
1427dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1428dc58b6f4SAndy Webber * in page footer and recent changes pages
1429dc58b6f4SAndy Webber *
1430dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1431dc58b6f4SAndy Webber */
1432dc58b6f4SAndy Webberfunction editorinfo($username){
1433dc58b6f4SAndy Webber    global $conf;
1434dc58b6f4SAndy Webber    global $auth;
1435dc58b6f4SAndy Webber
1436dc58b6f4SAndy Webber    switch($conf['showuseras']){
1437dc58b6f4SAndy Webber      case 'username':
1438dc58b6f4SAndy Webber      case 'email':
1439dc58b6f4SAndy Webber      case 'email_link':
1440173d78c4SAndreas Gohr        if($auth) $info = $auth->getUserData($username);
1441dc58b6f4SAndy Webber        break;
1442dc58b6f4SAndy Webber      default:
1443dc58b6f4SAndy Webber        return hsc($username);
1444dc58b6f4SAndy Webber    }
1445dc58b6f4SAndy Webber
1446dc58b6f4SAndy Webber    if(isset($info) && $info) {
1447dc58b6f4SAndy Webber        switch($conf['showuseras']){
1448dc58b6f4SAndy Webber          case 'username':
1449dc58b6f4SAndy Webber            return hsc($info['name']);
1450dc58b6f4SAndy Webber          case 'email':
1451dc58b6f4SAndy Webber            return obfuscate($info['mail']);
1452dc58b6f4SAndy Webber          case 'email_link':
1453dc58b6f4SAndy Webber            $mail=obfuscate($info['mail']);
1454dc58b6f4SAndy Webber            return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1455dc58b6f4SAndy Webber          default:
1456dc58b6f4SAndy Webber            return hsc($username);
1457dc58b6f4SAndy Webber        }
1458dc58b6f4SAndy Webber    } else {
1459dc58b6f4SAndy Webber        return hsc($username);
1460dc58b6f4SAndy Webber    }
1461066fee30SAndreas Gohr}
1462066fee30SAndreas Gohr
1463066fee30SAndreas Gohr/**
1464066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1465066fee30SAndreas Gohr * When no image exists, returns an empty string
1466066fee30SAndreas Gohr *
1467066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1468066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
1469066fee30SAndreas Gohr */
1470066fee30SAndreas Gohrfunction license_img($type){
1471066fee30SAndreas Gohr    global $license;
1472066fee30SAndreas Gohr    global $conf;
1473066fee30SAndreas Gohr    if(!$conf['license']) return '';
1474066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1475066fee30SAndreas Gohr    $lic = $license[$conf['license']];
1476066fee30SAndreas Gohr    $try = array();
1477066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1478066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1479066fee30SAndreas Gohr    if(substr($conf['license'],0,3) == 'cc-'){
1480066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1481066fee30SAndreas Gohr    }
1482066fee30SAndreas Gohr    foreach($try as $src){
1483066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1484066fee30SAndreas Gohr    }
1485066fee30SAndreas Gohr    return '';
1486dc58b6f4SAndy Webber}
1487dc58b6f4SAndy Webber
148813c08e2fSMichael Klier/**
148913c08e2fSMichael Klier * Checks if the given amount of memory is available
149013c08e2fSMichael Klier *
149113c08e2fSMichael Klier * If the memory_get_usage() function is not available the
149213c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
149313c08e2fSMichael Klier *
149413c08e2fSMichael Klier * @param  int $mem  Size of memory you want to allocate in bytes
149513c08e2fSMichael Klier * @param  int $used already allocated memory (see above)
149613c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
149713c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
149813c08e2fSMichael Klier */
149913c08e2fSMichael Klierfunction is_mem_available($mem,$bytes=1048576){
150013c08e2fSMichael Klier  $limit = trim(ini_get('memory_limit'));
150113c08e2fSMichael Klier  if(empty($limit)) return true; // no limit set!
150213c08e2fSMichael Klier
150313c08e2fSMichael Klier  // parse limit to bytes
150413c08e2fSMichael Klier  $limit = php_to_byte($limit);
150513c08e2fSMichael Klier
150613c08e2fSMichael Klier  // get used memory if possible
150713c08e2fSMichael Klier  if(function_exists('memory_get_usage')){
150813c08e2fSMichael Klier    $used = memory_get_usage();
150913c08e2fSMichael Klier  }
151013c08e2fSMichael Klier
151113c08e2fSMichael Klier  if($used+$mem > $limit){
151213c08e2fSMichael Klier    return false;
151313c08e2fSMichael Klier  }
151413c08e2fSMichael Klier
151513c08e2fSMichael Klier  return true;
151613c08e2fSMichael Klier}
151713c08e2fSMichael Klier
1518af2408d5SAndreas Gohr/**
1519af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1520af2408d5SAndreas Gohr *
1521af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1522af2408d5SAndreas Gohr *
1523af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1524af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1525af2408d5SAndreas Gohr */
1526af2408d5SAndreas Gohrfunction send_redirect($url){
1527d4869846SAndreas Gohr    // always close the session
1528d4869846SAndreas Gohr    session_write_close();
1529d4869846SAndreas Gohr
1530af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1531af2408d5SAndreas Gohr    if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1532af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1533af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1534af2408d5SAndreas Gohr        $matches[1] < 6 ){
1535af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1536af2408d5SAndreas Gohr    }else{
1537af2408d5SAndreas Gohr        header('Location: '.$url);
1538af2408d5SAndreas Gohr    }
1539af2408d5SAndreas Gohr    exit;
1540af2408d5SAndreas Gohr}
1541af2408d5SAndreas Gohr
1542340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1543