xref: /dokuwiki/inc/common.php (revision 6dffa0e0121b02d0258a96b5108dd43dee44c673)
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){
71634d7150SAndreas Gohr  if(is_null($token)) $token = $_REQUEST['sectok'];
72634d7150SAndreas Gohr  if(getSecurityToken() != $token){
73634d7150SAndreas Gohr    msg('Security Token did not match. Possible CSRF attack.',-1);
74634d7150SAndreas Gohr    return false;
75634d7150SAndreas Gohr  }
76634d7150SAndreas Gohr  return true;
77634d7150SAndreas Gohr}
78634d7150SAndreas Gohr
79634d7150SAndreas Gohr/**
80634d7150SAndreas Gohr * Print a hidden form field with a secret CSRF token
81634d7150SAndreas Gohr *
82634d7150SAndreas Gohr * @author  Andreas Gohr <andi@splitbrain.org>
83634d7150SAndreas Gohr */
84634d7150SAndreas Gohrfunction formSecurityToken($print=true){
852404d0edSAnika Henke  $ret = '<div class="no"><input type="hidden" name="sectok" value="'.getSecurityToken().'" /></div>'."\n";
86634d7150SAndreas Gohr  if($print){
87634d7150SAndreas Gohr    echo $ret;
88634d7150SAndreas Gohr  }else{
89634d7150SAndreas Gohr    return $ret;
90634d7150SAndreas Gohr  }
91634d7150SAndreas Gohr}
92634d7150SAndreas Gohr
93634d7150SAndreas Gohr/**
9415fae107Sandi * Return info about the current document as associative
95f3f0262cSandi * array.
9615fae107Sandi *
9715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
98f3f0262cSandi */
99f3f0262cSandifunction pageinfo(){
100f3f0262cSandi  global $ID;
101f3f0262cSandi  global $REV;
1027b3a6803SAndreas Gohr  global $RANGE;
103f3f0262cSandi  global $USERINFO;
104f3f0262cSandi  global $conf;
1057b3a6803SAndreas Gohr  global $lang;
106f3f0262cSandi
1076afe8dcaSchris  // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1086afe8dcaSchris  // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1096afe8dcaSchris  $info['id'] = $ID;
1106afe8dcaSchris  $info['rev'] = $REV;
1116afe8dcaSchris
112f3f0262cSandi  if($_SERVER['REMOTE_USER']){
113f3f0262cSandi    $info['userinfo']     = $USERINFO;
114f3f0262cSandi    $info['perm']         = auth_quickaclcheck($ID);
11552b0dd67SGuy Brand    $info['subscribed']   = is_subscribed($ID,$_SERVER['REMOTE_USER'],false);
11652b0dd67SGuy Brand    $info['subscribedns'] = is_subscribed($ID,$_SERVER['REMOTE_USER'],true);
117ee4c4a1bSAndreas Gohr    $info['client']       = $_SERVER['REMOTE_USER'];
11817ee7f66SAndreas Gohr
119f8cc712eSAndreas Gohr    // set info about manager/admin status
120f8cc712eSAndreas Gohr    $info['isadmin']   = false;
121f8cc712eSAndreas Gohr    $info['ismanager'] = false;
122f8cc712eSAndreas Gohr    if($info['perm'] == AUTH_ADMIN){
123f8cc712eSAndreas Gohr      $info['isadmin']   = true;
124f8cc712eSAndreas Gohr      $info['ismanager'] = true;
125f8cc712eSAndreas Gohr    }elseif(auth_ismanager()){
126f8cc712eSAndreas Gohr      $info['ismanager'] = true;
127f8cc712eSAndreas Gohr    }
128f8cc712eSAndreas Gohr
12917ee7f66SAndreas Gohr    // if some outside auth were used only REMOTE_USER is set
13017ee7f66SAndreas Gohr    if(!$info['userinfo']['name']){
13117ee7f66SAndreas Gohr      $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
13217ee7f66SAndreas Gohr    }
133ee4c4a1bSAndreas Gohr
134f3f0262cSandi  }else{
135f3f0262cSandi    $info['perm']       = auth_aclcheck($ID,'',null);
1361380fc45SAndreas Gohr    $info['subscribed'] = false;
137ee4c4a1bSAndreas Gohr    $info['client']     = clientIP(true);
138f3f0262cSandi  }
139f3f0262cSandi
140f3f0262cSandi  $info['namespace'] = getNS($ID);
141f3f0262cSandi  $info['locked']    = checklock($ID);
14200976812SAndreas Gohr  $info['filepath']  = fullpath(wikiFN($ID));
1432ca9d91cSBen Coburn  $info['exists']    = @file_exists($info['filepath']);
1442ca9d91cSBen Coburn  if($REV){
1452ca9d91cSBen Coburn    //check if current revision was meant
1462ca9d91cSBen Coburn    if($info['exists'] && (@filemtime($info['filepath'])==$REV)){
1472ca9d91cSBen Coburn      $REV = '';
1487b3a6803SAndreas Gohr    }elseif($RANGE){
1497b3a6803SAndreas Gohr      //section editing does not work with old revisions!
1507b3a6803SAndreas Gohr      $REV   = '';
1517b3a6803SAndreas Gohr      $RANGE = '';
1527b3a6803SAndreas Gohr      msg($lang['nosecedit'],0);
1532ca9d91cSBen Coburn    }else{
1542ca9d91cSBen Coburn      //really use old revision
15500976812SAndreas Gohr      $info['filepath'] = fullpath(wikiFN($ID,$REV));
156f3f0262cSandi      $info['exists']   = @file_exists($info['filepath']);
157f3f0262cSandi    }
158f3f0262cSandi  }
159c112d578Sandi  $info['rev'] = $REV;
160f3f0262cSandi  if($info['exists']){
161f3f0262cSandi    $info['writable'] = (is_writable($info['filepath']) &&
162f3f0262cSandi                         ($info['perm'] >= AUTH_EDIT));
163f3f0262cSandi  }else{
164f3f0262cSandi    $info['writable'] = ($info['perm'] >= AUTH_CREATE);
165f3f0262cSandi  }
166f3f0262cSandi  $info['editable']  = ($info['writable'] && empty($info['lock']));
167f3f0262cSandi  $info['lastmod']   = @filemtime($info['filepath']);
168f3f0262cSandi
16971726d78SBen Coburn  //load page meta data
17071726d78SBen Coburn  $info['meta'] = p_get_metadata($ID);
17171726d78SBen Coburn
172652610a2Sandi  //who's the editor
173652610a2Sandi  if($REV){
17471726d78SBen Coburn    $revinfo = getRevisionInfo($ID, $REV, 1024);
175652610a2Sandi  }else{
176aa27cf05SAndreas Gohr    if (is_array($info['meta']['last_change'])) {
177aa27cf05SAndreas Gohr       $revinfo = $info['meta']['last_change'];
178aa27cf05SAndreas Gohr    } else {
179cd00a034SBen Coburn      $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
180cd00a034SBen Coburn      // cache most recent changelog line in metadata if missing and still valid
181cd00a034SBen Coburn      if ($revinfo!==false) {
182cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
183cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
184cd00a034SBen Coburn      }
185cd00a034SBen Coburn    }
186cd00a034SBen Coburn  }
187cd00a034SBen Coburn  //and check for an external edit
188cd00a034SBen Coburn  if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
189cd00a034SBen Coburn    // cached changelog line no longer valid
190cd00a034SBen Coburn    $revinfo = false;
191cd00a034SBen Coburn    $info['meta']['last_change'] = $revinfo;
192cd00a034SBen Coburn    p_set_metadata($ID, array('last_change' => $revinfo));
193652610a2Sandi  }
194bb4866bdSchris
195652610a2Sandi  $info['ip']     = $revinfo['ip'];
196652610a2Sandi  $info['user']   = $revinfo['user'];
197652610a2Sandi  $info['sum']    = $revinfo['sum'];
19871726d78SBen Coburn  // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
199ebf1501fSBen Coburn  // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
20059f257aeSchris
20188f522e9Sandi  if($revinfo['user']){
20288f522e9Sandi    $info['editor'] = $revinfo['user'];
20388f522e9Sandi  }else{
20488f522e9Sandi    $info['editor'] = $revinfo['ip'];
20588f522e9Sandi  }
206652610a2Sandi
207ee4c4a1bSAndreas Gohr  // draft
208ee4c4a1bSAndreas Gohr  $draft = getCacheName($info['client'].$ID,'.draft');
209ee4c4a1bSAndreas Gohr  if(@file_exists($draft)){
210ee4c4a1bSAndreas Gohr    if(@filemtime($draft) < @filemtime(wikiFN($ID))){
211ee4c4a1bSAndreas Gohr      // remove stale draft
212ee4c4a1bSAndreas Gohr      @unlink($draft);
213ee4c4a1bSAndreas Gohr    }else{
214ee4c4a1bSAndreas Gohr      $info['draft'] = $draft;
215ee4c4a1bSAndreas Gohr    }
216ee4c4a1bSAndreas Gohr  }
217ee4c4a1bSAndreas Gohr
2181c548ebeSAndreas Gohr  // mobile detection
2191c548ebeSAndreas Gohr  $info['ismobile'] = clientismobile();
2201c548ebeSAndreas Gohr
221f3f0262cSandi  return $info;
222f3f0262cSandi}
223f3f0262cSandi
224f3f0262cSandi/**
2252684e50aSAndreas Gohr * Build an string of URL parameters
2262684e50aSAndreas Gohr *
2272684e50aSAndreas Gohr * @author Andreas Gohr
2282684e50aSAndreas Gohr */
229b174aeaeSchrisfunction buildURLparams($params, $sep='&amp;'){
2302684e50aSAndreas Gohr  $url = '';
2312684e50aSAndreas Gohr  $amp = false;
2322684e50aSAndreas Gohr  foreach($params as $key => $val){
233b174aeaeSchris    if($amp) $url .= $sep;
2342684e50aSAndreas Gohr
2352684e50aSAndreas Gohr    $url .= $key.'=';
2363a50618cSgweissbach    $url .= rawurlencode((string)$val);
2372684e50aSAndreas Gohr    $amp = true;
2382684e50aSAndreas Gohr  }
2392684e50aSAndreas Gohr  return $url;
2402684e50aSAndreas Gohr}
2412684e50aSAndreas Gohr
2422684e50aSAndreas Gohr/**
2432684e50aSAndreas Gohr * Build an string of html tag attributes
2442684e50aSAndreas Gohr *
2457bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2467bff22c0SAndreas Gohr *
2472684e50aSAndreas Gohr * @author Andreas Gohr
2482684e50aSAndreas Gohr */
2494b030ce7SAndreas Gohrfunction buildAttributes($params,$skipempty=false){
2502684e50aSAndreas Gohr  $url = '';
2512684e50aSAndreas Gohr  foreach($params as $key => $val){
2527bff22c0SAndreas Gohr    if($key{0} == '_') continue;
253b1c94f1dSAndreas Gohr    if($val === '' && $skipempty) continue;
2547bff22c0SAndreas Gohr
2552684e50aSAndreas Gohr    $url .= $key.'="';
2562684e50aSAndreas Gohr    $url .= htmlspecialchars ($val);
2572684e50aSAndreas Gohr    $url .= '" ';
2582684e50aSAndreas Gohr  }
2592684e50aSAndreas Gohr  return $url;
2602684e50aSAndreas Gohr}
2612684e50aSAndreas Gohr
2622684e50aSAndreas Gohr
2632684e50aSAndreas Gohr/**
26415fae107Sandi * This builds the breadcrumb trail and returns it as array
26515fae107Sandi *
26615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
267f3f0262cSandi */
268f3f0262cSandifunction breadcrumbs(){
2698746e727Sandi  // we prepare the breadcrumbs early for quick session closing
2708746e727Sandi  static $crumbs = null;
2718746e727Sandi  if($crumbs != null) return $crumbs;
2728746e727Sandi
273f3f0262cSandi  global $ID;
274f3f0262cSandi  global $ACT;
275f3f0262cSandi  global $conf;
276e71ce681SAndreas Gohr  $crumbs = $_SESSION[DOKU_COOKIE]['bc'];
277f3f0262cSandi
278f3f0262cSandi  //first visit?
279f3f0262cSandi  if (!is_array($crumbs)){
280f3f0262cSandi    $crumbs = array();
281f3f0262cSandi  }
282f3f0262cSandi  //we only save on show and existing wiki documents
283a77f5846Sjan  $file = wikiFN($ID);
284a77f5846Sjan  if($ACT != 'show' || !@file_exists($file)){
285e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
286f3f0262cSandi    return $crumbs;
287f3f0262cSandi  }
288a77f5846Sjan
289a77f5846Sjan  // page names
2901a84a0f3SAnika Henke  $name = noNSorNS($ID);
291fe9ec250SChris Smith  if (useHeading('navigation')) {
292a77f5846Sjan    // get page title
293955cd091SChris Smith    $title = p_get_first_heading($ID,true);
294a77f5846Sjan    if ($title) {
295a77f5846Sjan      $name = $title;
296a77f5846Sjan    }
297a77f5846Sjan  }
298a77f5846Sjan
299f3f0262cSandi  //remove ID from array
300a77f5846Sjan  if (isset($crumbs[$ID])) {
301a77f5846Sjan    unset($crumbs[$ID]);
302f3f0262cSandi  }
303f3f0262cSandi
304f3f0262cSandi  //add to array
305a77f5846Sjan  $crumbs[$ID] = $name;
306f3f0262cSandi  //reduce size
307f3f0262cSandi  while(count($crumbs) > $conf['breadcrumbs']){
308f3f0262cSandi    array_shift($crumbs);
309f3f0262cSandi  }
310f3f0262cSandi  //save to session
311e71ce681SAndreas Gohr  $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
312f3f0262cSandi  return $crumbs;
313f3f0262cSandi}
314f3f0262cSandi
315f3f0262cSandi/**
31615fae107Sandi * Filter for page IDs
31715fae107Sandi *
318f3f0262cSandi * This is run on a ID before it is outputted somewhere
319f3f0262cSandi * currently used to replace the colon with something else
320f3f0262cSandi * on Windows systems and to have proper URL encoding
32115fae107Sandi *
32249c713a3Sandi * Urlencoding is ommitted when the second parameter is false
32349c713a3Sandi *
32415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
325f3f0262cSandi */
32649c713a3Sandifunction idfilter($id,$ue=true){
327f3f0262cSandi  global $conf;
328f3f0262cSandi  if ($conf['useslash'] && $conf['userewrite']){
329f3f0262cSandi    $id = strtr($id,':','/');
330f3f0262cSandi  }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
331f3f0262cSandi      $conf['userewrite']) {
332f3f0262cSandi    $id = strtr($id,':',';');
333f3f0262cSandi  }
33449c713a3Sandi  if($ue){
335b6c6979fSAndreas Gohr    $id = rawurlencode($id);
336f3f0262cSandi    $id = str_replace('%3A',':',$id); //keep as colon
337f3f0262cSandi    $id = str_replace('%2F','/',$id); //keep as slash
33849c713a3Sandi  }
339f3f0262cSandi  return $id;
340f3f0262cSandi}
341f3f0262cSandi
342f3f0262cSandi/**
343ed7b5f09Sandi * This builds a link to a wikipage
34415fae107Sandi *
3456c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3466c7843b5Sandi * given in $more
3476c7843b5Sandi *
34815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
349f3f0262cSandi */
350b174aeaeSchrisfunction wl($id='',$more='',$abs=false,$sep='&amp;'){
351f3f0262cSandi  global $conf;
3526de3759aSAndreas Gohr  if(is_array($more)){
353b174aeaeSchris    $more = buildURLparams($more,$sep);
3546de3759aSAndreas Gohr  }else{
355b174aeaeSchris    $more = str_replace(',',$sep,$more);
3566de3759aSAndreas Gohr  }
357f3f0262cSandi
358f3f0262cSandi  $id    = idfilter($id);
359ed7b5f09Sandi  if($abs){
360ed7b5f09Sandi    $xlink = DOKU_URL;
361ed7b5f09Sandi  }else{
362ed7b5f09Sandi    $xlink = DOKU_BASE;
363ed7b5f09Sandi  }
364f3f0262cSandi
3656c7843b5Sandi  if($conf['userewrite'] == 2){
3666c7843b5Sandi    $xlink .= DOKU_SCRIPT.'/'.$id;
3676c7843b5Sandi    if($more) $xlink .= '?'.$more;
3686c7843b5Sandi  }elseif($conf['userewrite']){
369f3f0262cSandi    $xlink .= $id;
370f3f0262cSandi    if($more) $xlink .= '?'.$more;
371bce3726dSAndreas Gohr  }elseif($id){
3726c7843b5Sandi    $xlink .= DOKU_SCRIPT.'?id='.$id;
373b174aeaeSchris    if($more) $xlink .= $sep.$more;
374bce3726dSAndreas Gohr  }else{
375bce3726dSAndreas Gohr    $xlink .= DOKU_SCRIPT;
376bce3726dSAndreas Gohr    if($more) $xlink .= '?'.$more;
377f3f0262cSandi  }
378f3f0262cSandi
379f3f0262cSandi  return $xlink;
380f3f0262cSandi}
381f3f0262cSandi
382f3f0262cSandi/**
383f5c2808fSBen Coburn * This builds a link to an alternate page format
384f5c2808fSBen Coburn *
385f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
386f5c2808fSBen Coburn *
387f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
388f5c2808fSBen Coburn */
389f5c2808fSBen Coburnfunction exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
390f5c2808fSBen Coburn  global $conf;
391f5c2808fSBen Coburn  if(is_array($more)){
392f5c2808fSBen Coburn    $more = buildURLparams($more,$sep);
393f5c2808fSBen Coburn  }else{
394f5c2808fSBen Coburn    $more = str_replace(',',$sep,$more);
395f5c2808fSBen Coburn  }
396f5c2808fSBen Coburn
397f5c2808fSBen Coburn  $format = rawurlencode($format);
398f5c2808fSBen Coburn  $id = idfilter($id);
399f5c2808fSBen Coburn  if($abs){
400f5c2808fSBen Coburn    $xlink = DOKU_URL;
401f5c2808fSBen Coburn  }else{
402f5c2808fSBen Coburn    $xlink = DOKU_BASE;
403f5c2808fSBen Coburn  }
404f5c2808fSBen Coburn
405f5c2808fSBen Coburn  if($conf['userewrite'] == 2){
406f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
407f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
408f5c2808fSBen Coburn  }elseif($conf['userewrite'] == 1){
409f5c2808fSBen Coburn    $xlink .= '_export/'.$format.'/'.$id;
410f5c2808fSBen Coburn    if($more) $xlink .= '?'.$more;
411f5c2808fSBen Coburn  }else{
412f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
413f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
414f5c2808fSBen Coburn  }
415f5c2808fSBen Coburn
416f5c2808fSBen Coburn  return $xlink;
417f5c2808fSBen Coburn}
418f5c2808fSBen Coburn
419f5c2808fSBen Coburn/**
4206de3759aSAndreas Gohr * Build a link to a media file
4216de3759aSAndreas Gohr *
4226de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4238c08db0aSAndreas Gohr *
4248c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4258c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4268c08db0aSAndreas Gohr *
4278c08db0aSAndreas Gohr * @param string  $id     - the media file id or URL
4288c08db0aSAndreas Gohr * @param mixed   $more   - string or array with additional parameters
4298c08db0aSAndreas Gohr * @param boolean $direct - link to detail page if false
4308c08db0aSAndreas Gohr * @param string  $sep    - URL parameter separator
4318c08db0aSAndreas Gohr * @param boolean $abs    - Create an absolute URL
4326de3759aSAndreas Gohr */
43355b2b31bSAndreas Gohrfunction ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
4346de3759aSAndreas Gohr  global $conf;
4356de3759aSAndreas Gohr  if(is_array($more)){
4368c08db0aSAndreas Gohr    // strip defaults for shorter URLs
4378c08db0aSAndreas Gohr    if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4388c08db0aSAndreas Gohr    if(!$more['w']) unset($more['w']);
4398c08db0aSAndreas Gohr    if(!$more['h']) unset($more['h']);
4408c08db0aSAndreas Gohr    if(isset($more['id']) && $direct) unset($more['id']);
441b174aeaeSchris    $more = buildURLparams($more,$sep);
4426de3759aSAndreas Gohr  }else{
4438c08db0aSAndreas Gohr    $more = str_replace('cache=cache','',$more); //skip default
4448c08db0aSAndreas Gohr    $more = str_replace(',,',',',$more);
445b174aeaeSchris    $more = str_replace(',',$sep,$more);
4466de3759aSAndreas Gohr  }
4476de3759aSAndreas Gohr
44855b2b31bSAndreas Gohr  if($abs){
44955b2b31bSAndreas Gohr    $xlink = DOKU_URL;
45055b2b31bSAndreas Gohr  }else{
4516de3759aSAndreas Gohr    $xlink = DOKU_BASE;
45255b2b31bSAndreas Gohr  }
4536de3759aSAndreas Gohr
4546de3759aSAndreas Gohr  // external URLs are always direct without rewriting
4556de3759aSAndreas Gohr  if(preg_match('#^(https?|ftp)://#i',$id)){
4566de3759aSAndreas Gohr    $xlink .= 'lib/exe/fetch.php';
4576de3759aSAndreas Gohr    if($more){
4586de3759aSAndreas Gohr      $xlink .= '?'.$more;
459b174aeaeSchris      $xlink .= $sep.'media='.rawurlencode($id);
4606de3759aSAndreas Gohr    }else{
461b6c6979fSAndreas Gohr      $xlink .= '?media='.rawurlencode($id);
4626de3759aSAndreas Gohr    }
4636de3759aSAndreas Gohr    return $xlink;
4646de3759aSAndreas Gohr  }
4656de3759aSAndreas Gohr
4666de3759aSAndreas Gohr  $id = idfilter($id);
4676de3759aSAndreas Gohr
4686de3759aSAndreas Gohr  // decide on scriptname
4696de3759aSAndreas Gohr  if($direct){
4706de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4716de3759aSAndreas Gohr      $script = '_media';
4726de3759aSAndreas Gohr    }else{
4736de3759aSAndreas Gohr      $script = 'lib/exe/fetch.php';
4746de3759aSAndreas Gohr    }
4756de3759aSAndreas Gohr  }else{
4766de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4776de3759aSAndreas Gohr      $script = '_detail';
4786de3759aSAndreas Gohr    }else{
4796de3759aSAndreas Gohr      $script = 'lib/exe/detail.php';
4806de3759aSAndreas Gohr    }
4816de3759aSAndreas Gohr  }
4826de3759aSAndreas Gohr
4836de3759aSAndreas Gohr  // build URL based on rewrite mode
4846de3759aSAndreas Gohr   if($conf['userewrite']){
4856de3759aSAndreas Gohr     $xlink .= $script.'/'.$id;
4866de3759aSAndreas Gohr     if($more) $xlink .= '?'.$more;
4876de3759aSAndreas Gohr   }else{
4886de3759aSAndreas Gohr     if($more){
489a99d3236SEsther Brunner       $xlink .= $script.'?'.$more;
490b174aeaeSchris       $xlink .= $sep.'media='.$id;
4916de3759aSAndreas Gohr     }else{
492a99d3236SEsther Brunner       $xlink .= $script.'?media='.$id;
4936de3759aSAndreas Gohr     }
4946de3759aSAndreas Gohr   }
4956de3759aSAndreas Gohr
4966de3759aSAndreas Gohr  return $xlink;
4976de3759aSAndreas Gohr}
4986de3759aSAndreas Gohr
4996de3759aSAndreas Gohr
5006de3759aSAndreas Gohr
5016de3759aSAndreas Gohr/**
502f3f0262cSandi * Just builds a link to a script
50315fae107Sandi *
504ed7b5f09Sandi * @todo   maybe obsolete
50515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
506f3f0262cSandi */
507f3f0262cSandifunction script($script='doku.php'){
508ed7b5f09Sandi#  $link = getBaseURL();
509ed7b5f09Sandi#  $link .= $script;
510ed7b5f09Sandi#  return $link;
511ed7b5f09Sandi  return DOKU_BASE.DOKU_SCRIPT;
512f3f0262cSandi}
513f3f0262cSandi
514f3f0262cSandi/**
51515fae107Sandi * Spamcheck against wordlist
51615fae107Sandi *
517f3f0262cSandi * Checks the wikitext against a list of blocked expressions
518f3f0262cSandi * returns true if the text contains any bad words
51915fae107Sandi *
520e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
521e403cc58SMichael Klier *
522e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
523e403cc58SMichael Klier *  and gain information about the user who was blocked.
524e403cc58SMichael Klier *
525e403cc58SMichael Klier *  Event data:
526e403cc58SMichael Klier *    data['matches']  - array of matches
527e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
528e403cc58SMichael Klier *      [ip]           - ip address
529e403cc58SMichael Klier *      [user]         - username (if logged in)
530e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
531e403cc58SMichael Klier *      [name]         - real name (if logged in)
532e403cc58SMichael Klier *
53315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
534*6dffa0e0SAndreas Gohr * @author Michael Klier <chi@chimeric.de>
535*6dffa0e0SAndreas Gohr * @param  string $text - optional text to check, if not given the globals are used
536*6dffa0e0SAndreas Gohr * @return bool         - true if a spam word was found
537f3f0262cSandi */
538*6dffa0e0SAndreas Gohrfunction checkwordblock($text=''){
539f3f0262cSandi  global $TEXT;
540*6dffa0e0SAndreas Gohr  global $PRE;
541*6dffa0e0SAndreas Gohr  global $SUF;
542f3f0262cSandi  global $conf;
543e403cc58SMichael Klier  global $INFO;
544f3f0262cSandi
545f3f0262cSandi  if(!$conf['usewordblock']) return false;
546f3f0262cSandi
547*6dffa0e0SAndreas Gohr  if(!$text) $text = "$PRE $TEXT $SUF";
548*6dffa0e0SAndreas Gohr
549041d1964SAndreas Gohr  // we prepare the text a tiny bit to prevent spammers circumventing URL checks
550*6dffa0e0SAndreas Gohr  $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$text);
551041d1964SAndreas Gohr
552b9ac8716Schris  $wordblocks = getWordblocks();
5533e2965d7Sandi  //how many lines to read at once (to work around some PCRE limits)
5543e2965d7Sandi  if(version_compare(phpversion(),'4.3.0','<')){
5553e2965d7Sandi    //old versions of PCRE define a maximum of parenthesises even if no
5563e2965d7Sandi    //backreferences are used - the maximum is 99
5573e2965d7Sandi    //this is very bad performancewise and may even be too high still
5583e2965d7Sandi    $chunksize = 40;
5593e2965d7Sandi  }else{
560a51d08efSAndreas Gohr    //read file in chunks of 200 - this should work around the
5613e2965d7Sandi    //MAX_PATTERN_SIZE in modern PCRE
562a51d08efSAndreas Gohr    $chunksize = 200;
5633e2965d7Sandi  }
564b9ac8716Schris  while($blocks = array_splice($wordblocks,0,$chunksize)){
565f3f0262cSandi    $re = array();
566f3f0262cSandi    #build regexp from blocks
567f3f0262cSandi    foreach($blocks as $block){
568f3f0262cSandi      $block = preg_replace('/#.*$/','',$block);
569f3f0262cSandi      $block = trim($block);
570f3f0262cSandi      if(empty($block)) continue;
571f3f0262cSandi      $re[]  = $block;
572f3f0262cSandi    }
573e403cc58SMichael Klier    if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
574e403cc58SMichael Klier      //prepare event data
575e403cc58SMichael Klier      $data['matches'] = $matches;
576e403cc58SMichael Klier      $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
577e403cc58SMichael Klier      if($_SERVER['REMOTE_USER']) {
578e403cc58SMichael Klier          $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
579e403cc58SMichael Klier          $data['userinfo']['name'] = $INFO['userinfo']['name'];
580e403cc58SMichael Klier          $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
581e403cc58SMichael Klier      }
582e403cc58SMichael Klier      $callback = create_function('', 'return true;');
583e403cc58SMichael Klier      return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
584b9ac8716Schris    }
585703f6fdeSandi  }
586f3f0262cSandi  return false;
587f3f0262cSandi}
588f3f0262cSandi
589f3f0262cSandi/**
59015fae107Sandi * Return the IP of the client
59115fae107Sandi *
5926d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
59315fae107Sandi *
5946d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5956d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
5966d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
5976d8affe6SAndreas Gohr * headers
5986d8affe6SAndreas Gohr *
5996d8affe6SAndreas Gohr * @param  boolean $single If set only a single IP is returned
60015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
601f3f0262cSandi */
6026d8affe6SAndreas Gohrfunction clientIP($single=false){
6036d8affe6SAndreas Gohr  $ip = array();
6046d8affe6SAndreas Gohr  $ip[] = $_SERVER['REMOTE_ADDR'];
605bb4866bdSchris  if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
6066d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
607bb4866bdSchris  if(!empty($_SERVER['HTTP_X_REAL_IP']))
6086d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
6096d8affe6SAndreas Gohr
610dc14c6d1SGuy Brand  // some IPv4/v6 regexps borrowed from Feyd
611dc14c6d1SGuy Brand  // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
612dc14c6d1SGuy Brand  $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
613dc14c6d1SGuy Brand  $hex_digit = '[A-Fa-f0-9]';
614dc14c6d1SGuy Brand  $h16 = "{$hex_digit}{1,4}";
615dc14c6d1SGuy Brand  $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
616dc14c6d1SGuy Brand  $ls32 = "(?:$h16:$h16|$IPv4Address)";
617dc14c6d1SGuy Brand  $IPv6Address =
618dc14c6d1SGuy Brand    "(?:(?:{$IPv4Address})|(?:".
619dc14c6d1SGuy Brand    "(?:$h16:){6}$ls32" .
620dc14c6d1SGuy Brand    "|::(?:$h16:){5}$ls32" .
621dc14c6d1SGuy Brand    "|(?:$h16)?::(?:$h16:){4}$ls32" .
622dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
623dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
624dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
625dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
626dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,5}$h16)?::$h16" .
627dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,6}$h16)?::" .
628dc14c6d1SGuy Brand    ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
629dc14c6d1SGuy Brand
6306d8affe6SAndreas Gohr  // remove any non-IP stuff
6316d8affe6SAndreas Gohr  $cnt = count($ip);
6324ff28443Schris  $match = array();
6336d8affe6SAndreas Gohr  for($i=0; $i<$cnt; $i++){
634dc14c6d1SGuy Brand    if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
6354ff28443Schris      $ip[$i] = $match[0];
6364ff28443Schris    } else {
6374ff28443Schris      $ip[$i] = '';
6384ff28443Schris    }
6396d8affe6SAndreas Gohr    if(empty($ip[$i])) unset($ip[$i]);
640f3f0262cSandi  }
6416d8affe6SAndreas Gohr  $ip = array_values(array_unique($ip));
6426d8affe6SAndreas Gohr  if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6436d8affe6SAndreas Gohr
6446d8affe6SAndreas Gohr  if(!$single) return join(',',$ip);
6456d8affe6SAndreas Gohr
6466d8affe6SAndreas Gohr  // decide which IP to use, trying to avoid local addresses
6476d8affe6SAndreas Gohr  $ip = array_reverse($ip);
6486d8affe6SAndreas Gohr  foreach($ip as $i){
6496d8affe6SAndreas Gohr    if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
6506d8affe6SAndreas Gohr      continue;
6516d8affe6SAndreas Gohr    }else{
6526d8affe6SAndreas Gohr      return $i;
6536d8affe6SAndreas Gohr    }
6546d8affe6SAndreas Gohr  }
6556d8affe6SAndreas Gohr  // still here? just use the first (last) address
6566d8affe6SAndreas Gohr  return $ip[0];
657f3f0262cSandi}
658f3f0262cSandi
659f3f0262cSandi/**
6601c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6611c548ebeSAndreas Gohr *
6621c548ebeSAndreas Gohr * Adapted from the example code at url below
6631c548ebeSAndreas Gohr *
6641c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6651c548ebeSAndreas Gohr */
6661c548ebeSAndreas Gohrfunction clientismobile(){
6671c548ebeSAndreas Gohr
6681c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
6691c548ebeSAndreas Gohr
6701c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
6711c548ebeSAndreas Gohr
6721c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
6731c548ebeSAndreas Gohr
6741c548ebeSAndreas 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';
6751c548ebeSAndreas Gohr
6761c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
6771c548ebeSAndreas Gohr
6781c548ebeSAndreas Gohr    return false;
6791c548ebeSAndreas Gohr}
6801c548ebeSAndreas Gohr
6811c548ebeSAndreas Gohr
6821c548ebeSAndreas Gohr/**
68363211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
68463211f61SGlen Harris *
68563211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
68663211f61SGlen Harris * @returns a comma separated list of hostnames
68763211f61SGlen Harris */
68863211f61SGlen Harrisfunction gethostsbyaddrs($ips){
68963211f61SGlen Harris  $hosts = array();
69063211f61SGlen Harris  $ips = explode(',',$ips);
691551a720fSMichael Klier
692551a720fSMichael Klier  if(is_array($ips)) {
6933886270dSAndreas Gohr    foreach($ips as $ip){
694551a720fSMichael Klier      $hosts[] = gethostbyaddr(trim($ip));
69563211f61SGlen Harris    }
696551a720fSMichael Klier    return join(',',$hosts);
697551a720fSMichael Klier  } else {
698551a720fSMichael Klier    return gethostbyaddr(trim($ips));
699551a720fSMichael Klier  }
70063211f61SGlen Harris}
70163211f61SGlen Harris
70263211f61SGlen Harris/**
70315fae107Sandi * Checks if a given page is currently locked.
70415fae107Sandi *
705f3f0262cSandi * removes stale lockfiles
70615fae107Sandi *
70715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
708f3f0262cSandi */
709f3f0262cSandifunction checklock($id){
710f3f0262cSandi  global $conf;
711c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
712f3f0262cSandi
713f3f0262cSandi  //no lockfile
714f3f0262cSandi  if(!@file_exists($lock)) return false;
715f3f0262cSandi
716f3f0262cSandi  //lockfile expired
717f3f0262cSandi  if((time() - filemtime($lock)) > $conf['locktime']){
718d8186216SBen Coburn    @unlink($lock);
719f3f0262cSandi    return false;
720f3f0262cSandi  }
721f3f0262cSandi
722f3f0262cSandi  //my own lock
723f3f0262cSandi  $ip = io_readFile($lock);
724f3f0262cSandi  if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
725f3f0262cSandi    return false;
726f3f0262cSandi  }
727f3f0262cSandi
728f3f0262cSandi  return $ip;
729f3f0262cSandi}
730f3f0262cSandi
731f3f0262cSandi/**
73215fae107Sandi * Lock a page for editing
73315fae107Sandi *
73415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
735f3f0262cSandi */
736f3f0262cSandifunction lock($id){
737c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
738f3f0262cSandi  if($_SERVER['REMOTE_USER']){
739f3f0262cSandi    io_saveFile($lock,$_SERVER['REMOTE_USER']);
740f3f0262cSandi  }else{
741f3f0262cSandi    io_saveFile($lock,clientIP());
742f3f0262cSandi  }
743f3f0262cSandi}
744f3f0262cSandi
745f3f0262cSandi/**
74615fae107Sandi * Unlock a page if it was locked by the user
747f3f0262cSandi *
74815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
74915fae107Sandi * @return bool true if a lock was removed
750f3f0262cSandi */
751f3f0262cSandifunction unlock($id){
752c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
753f3f0262cSandi  if(@file_exists($lock)){
754f3f0262cSandi    $ip = io_readFile($lock);
755f3f0262cSandi    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
756f3f0262cSandi      @unlink($lock);
757f3f0262cSandi      return true;
758f3f0262cSandi    }
759f3f0262cSandi  }
760f3f0262cSandi  return false;
761f3f0262cSandi}
762f3f0262cSandi
763f3f0262cSandi/**
764f3f0262cSandi * convert line ending to unix format
765f3f0262cSandi *
76615fae107Sandi * @see    formText() for 2crlf conversion
76715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
768f3f0262cSandi */
769f3f0262cSandifunction cleanText($text){
770f3f0262cSandi  $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
771f3f0262cSandi  return $text;
772f3f0262cSandi}
773f3f0262cSandi
774f3f0262cSandi/**
775f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
776f3f0262cSandi * It also converts line endings to Windows format which is
777f3f0262cSandi * pseudo standard for webforms.
778f3f0262cSandi *
77915fae107Sandi * @see    cleanText() for 2unix conversion
78015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
781f3f0262cSandi */
782f3f0262cSandifunction formText($text){
7835b7d45a5SAndreas Gohr  $text = str_replace("\012","\015\012",$text);
784f3f0262cSandi  return htmlspecialchars($text);
785f3f0262cSandi}
786f3f0262cSandi
787f3f0262cSandi/**
78815fae107Sandi * Returns the specified local text in raw format
78915fae107Sandi *
79015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
791f3f0262cSandi */
792f3f0262cSandifunction rawLocale($id){
793f3f0262cSandi  return io_readFile(localeFN($id));
794f3f0262cSandi}
795f3f0262cSandi
796f3f0262cSandi/**
797f3f0262cSandi * Returns the raw WikiText
79815fae107Sandi *
79915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
800f3f0262cSandi */
801f3f0262cSandifunction rawWiki($id,$rev=''){
802cc7d0c94SBen Coburn  return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
803f3f0262cSandi}
804f3f0262cSandi
805f3f0262cSandi/**
8067146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
8077146cee2SAndreas Gohr *
8087146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
8097146cee2SAndreas Gohr */
810b7d5a5f0SAndreas Gohrfunction pageTemplate($data){
811b7d5a5f0SAndreas Gohr  $id = $data[0];
812a15ce62dSEsther Brunner  global $conf;
813a15ce62dSEsther Brunner  global $INFO;
814e29549feSAndreas Gohr
815e29549feSAndreas Gohr  $path = dirname(wikiFN($id));
816e29549feSAndreas Gohr
817e29549feSAndreas Gohr  if(@file_exists($path.'/_template.txt')){
818e29549feSAndreas Gohr    $tpl = io_readFile($path.'/_template.txt');
819e29549feSAndreas Gohr  }else{
820e29549feSAndreas Gohr    // search upper namespaces for templates
821e29549feSAndreas Gohr    $len = strlen(rtrim($conf['datadir'],'/'));
822e29549feSAndreas Gohr    while (strlen($path) >= $len){
823e29549feSAndreas Gohr      if(@file_exists($path.'/__template.txt')){
824e29549feSAndreas Gohr        $tpl = io_readFile($path.'/__template.txt');
825e29549feSAndreas Gohr        break;
826e29549feSAndreas Gohr      }
827e29549feSAndreas Gohr      $path = substr($path, 0, strrpos($path, '/'));
828e29549feSAndreas Gohr    }
829e29549feSAndreas Gohr  }
830e29549feSAndreas Gohr  if(!$tpl) return '';
831e29549feSAndreas Gohr
832e29549feSAndreas Gohr  // replace placeholders
83326ece5a7SAndreas Gohr  $file = noNS($id);
83426ece5a7SAndreas Gohr  $page = strtr($file,'_',' ');
83526ece5a7SAndreas Gohr
83626ece5a7SAndreas Gohr  $tpl = str_replace(array(
83726ece5a7SAndreas Gohr                        '@ID@',
83826ece5a7SAndreas Gohr                        '@NS@',
83926ece5a7SAndreas Gohr                        '@FILE@',
84026ece5a7SAndreas Gohr                        '@!FILE@',
84126ece5a7SAndreas Gohr                        '@!FILE!@',
84226ece5a7SAndreas Gohr                        '@PAGE@',
84326ece5a7SAndreas Gohr                        '@!PAGE@',
84426ece5a7SAndreas Gohr                        '@!!PAGE@',
84526ece5a7SAndreas Gohr                        '@!PAGE!@',
84626ece5a7SAndreas Gohr                        '@USER@',
84726ece5a7SAndreas Gohr                        '@NAME@',
84826ece5a7SAndreas Gohr                        '@MAIL@',
84926ece5a7SAndreas Gohr                        '@DATE@',
85026ece5a7SAndreas Gohr                     ),
85126ece5a7SAndreas Gohr                     array(
85226ece5a7SAndreas Gohr                        $id,
85326ece5a7SAndreas Gohr                        getNS($id),
85426ece5a7SAndreas Gohr                        $file,
85526ece5a7SAndreas Gohr                        utf8_ucfirst($file),
85626ece5a7SAndreas Gohr                        utf8_strtoupper($file),
85726ece5a7SAndreas Gohr                        $page,
85826ece5a7SAndreas Gohr                        utf8_ucfirst($page),
85926ece5a7SAndreas Gohr                        utf8_ucwords($page),
86026ece5a7SAndreas Gohr                        utf8_strtoupper($page),
86126ece5a7SAndreas Gohr                        $_SERVER['REMOTE_USER'],
86226ece5a7SAndreas Gohr                        $INFO['userinfo']['name'],
86326ece5a7SAndreas Gohr                        $INFO['userinfo']['mail'],
86426ece5a7SAndreas Gohr                        $conf['dformat'],
86526ece5a7SAndreas Gohr                     ), $tpl);
86626ece5a7SAndreas Gohr
8677d644fc8SAndreas Gohr  // we need the callback to work around strftime's char limit
8687d644fc8SAndreas Gohr  $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
8697d644fc8SAndreas Gohr
870a15ce62dSEsther Brunner  return $tpl;
8717146cee2SAndreas Gohr}
8727146cee2SAndreas Gohr
8737146cee2SAndreas Gohr
8747146cee2SAndreas Gohr/**
87515fae107Sandi * Returns the raw Wiki Text in three slices.
87615fae107Sandi *
87715fae107Sandi * The range parameter needs to have the form "from-to"
87815cfe303Sandi * and gives the range of the section in bytes - no
87915cfe303Sandi * UTF-8 awareness is needed.
880f3f0262cSandi * The returned order is prefix, section and suffix.
88115fae107Sandi *
88215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
883f3f0262cSandi */
884f3f0262cSandifunction rawWikiSlices($range,$id,$rev=''){
885f3f0262cSandi  list($from,$to) = split('-',$range,2);
886cc7d0c94SBen Coburn  $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
887f3f0262cSandi  if(!$from) $from = 0;
888c3d8e19bSandi  if(!$to)   $to   = strlen($text)+1;
889f3f0262cSandi
89015cfe303Sandi  $slices[0] = substr($text,0,$from-1);
89115cfe303Sandi  $slices[1] = substr($text,$from-1,$to-$from);
89215cfe303Sandi  $slices[2] = substr($text,$to);
893f3f0262cSandi
894f3f0262cSandi  return $slices;
895f3f0262cSandi}
896f3f0262cSandi
897f3f0262cSandi/**
89815fae107Sandi * Joins wiki text slices
89915fae107Sandi *
900f3f0262cSandi * function to join the text slices with correct lineendings again.
901f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
902f3f0262cSandi * lines between sections if needed (used on saving).
90315fae107Sandi *
90415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
905f3f0262cSandi */
906f3f0262cSandifunction con($pre,$text,$suf,$pretty=false){
907f3f0262cSandi
908f3f0262cSandi  if($pretty){
909f3f0262cSandi    if($pre && substr($pre,-1) != "\n") $pre .= "\n";
910f3f0262cSandi    if($suf && substr($text,-1) != "\n") $text .= "\n";
911f3f0262cSandi  }
912f3f0262cSandi
9137e038d4eSAndreas Gohr  // Avoid double newline above section when saving section edit
9147e038d4eSAndreas Gohr  //if($pre) $pre .= "\n";
915f3f0262cSandi  if($suf) $text .= "\n";
916f3f0262cSandi  return $pre.$text.$suf;
917f3f0262cSandi}
918f3f0262cSandi
919f3f0262cSandi/**
920a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
921a701424fSBen Coburn * Also directs changelog and attic updates.
92215fae107Sandi *
92315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
92471726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
925f3f0262cSandi */
926b6912aeaSAndreas Gohrfunction saveWikiText($id,$text,$summary,$minor=false){
927a701424fSBen Coburn  /* Note to developers:
928a701424fSBen Coburn     This code is subtle and delicate. Test the behavior of
929a701424fSBen Coburn     the attic and changelog with dokuwiki and external edits
930a701424fSBen Coburn     after any changes. External edits change the wiki page
931a701424fSBen Coburn     directly without using php or dokuwiki.
932a701424fSBen Coburn  */
933f3f0262cSandi  global $conf;
934f3f0262cSandi  global $lang;
93571726d78SBen Coburn  global $REV;
936f3f0262cSandi  // ignore if no changes were made
937f3f0262cSandi  if($text == rawWiki($id,'')){
938f3f0262cSandi    return;
939f3f0262cSandi  }
940f3f0262cSandi
941f3f0262cSandi  $file = wikiFN($id);
942a701424fSBen Coburn  $old = @filemtime($file); // from page
94371726d78SBen Coburn  $wasRemoved = empty($text);
944d8186216SBen Coburn  $wasCreated = !@file_exists($file);
94571726d78SBen Coburn  $wasReverted = ($REV==true);
946e45b34cdSBen Coburn  $newRev = false;
947a701424fSBen Coburn  $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
948a701424fSBen Coburn  $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
949a701424fSBen Coburn  if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
95046844156SBen Coburn    // add old revision to the attic if missing
95146844156SBen Coburn    saveOldRevision($id);
95246844156SBen Coburn    // add a changelog entry if this edit came from outside dokuwiki
953a701424fSBen Coburn    if ($old>$oldRev) {
954ebf1501fSBen Coburn      addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
95546844156SBen Coburn      // remove soon to be stale instructions
95646844156SBen Coburn      $cache = new cache_instructions($id, $file);
95746844156SBen Coburn      $cache->removeCache();
95846844156SBen Coburn    }
95946844156SBen Coburn  }
960f3f0262cSandi
96171726d78SBen Coburn  if ($wasRemoved){
96230725328SGabriel Birke    // Send "update" event with empty data, so plugins can react to page deletion
96330725328SGabriel Birke    $data = array(array($file, '', false), getNS($id), noNS($id), false);
96430725328SGabriel Birke    trigger_event('IO_WIKIPAGE_WRITE', $data);
965e45b34cdSBen Coburn    // pre-save deleted revision
966e45b34cdSBen Coburn    @touch($file);
96746844156SBen Coburn    clearstatcache();
968e45b34cdSBen Coburn    $newRev = saveOldRevision($id);
969e1f3d9e1SEsther Brunner    // remove empty file
970f3f0262cSandi    @unlink($file);
97171726d78SBen Coburn    // remove old meta info...
972e1f3d9e1SEsther Brunner    $mfiles = metaFiles($id);
97371726d78SBen Coburn    $changelog = metaFN($id, '.changes');
9743d1f9ec3SMichael Klier    $metadata  = metaFN($id, '.meta');
975e1f3d9e1SEsther Brunner    foreach ($mfiles as $mfile) {
9763d1f9ec3SMichael Klier      // but keep per-page changelog to preserve page history and keep meta data
9773d1f9ec3SMichael Klier      if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); }
978b158d625SSteven Danz    }
9793d1f9ec3SMichael Klier    // purge meta data
9803d1f9ec3SMichael Klier    p_purge_metadata($id);
981f3f0262cSandi    $del = true;
9823ce054b3Sandi    // autoset summary on deletion
9833ce054b3Sandi    if(empty($summary)) $summary = $lang['deleted'];
98453d6ccfeSandi    // remove empty namespaces
985cc7d0c94SBen Coburn    io_sweepNS($id, 'datadir');
986cc7d0c94SBen Coburn    io_sweepNS($id, 'mediadir');
987f3f0262cSandi  }else{
988cc7d0c94SBen Coburn    // save file (namespace dir is created in io_writeWikiPage)
989cc7d0c94SBen Coburn    io_writeWikiPage($file, $text, $id);
99046844156SBen Coburn    // pre-save the revision, to keep the attic in sync
99146844156SBen Coburn    $newRev = saveOldRevision($id);
992f3f0262cSandi    $del = false;
993f3f0262cSandi  }
994f3f0262cSandi
99571726d78SBen Coburn  // select changelog line type
99671726d78SBen Coburn  $extra = '';
997ebf1501fSBen Coburn  $type = DOKU_CHANGE_TYPE_EDIT;
99871726d78SBen Coburn  if ($wasReverted) {
999ebf1501fSBen Coburn    $type = DOKU_CHANGE_TYPE_REVERT;
100071726d78SBen Coburn    $extra = $REV;
100171726d78SBen Coburn  }
1002ebf1501fSBen Coburn  else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
1003ebf1501fSBen Coburn  else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
1004ebf1501fSBen Coburn  else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
100571726d78SBen Coburn
1006e45b34cdSBen Coburn  addLogEntry($newRev, $id, $type, $summary, $extra);
100726a0801fSAndreas Gohr  // send notify mails
100890033e9dSAndreas Gohr  notify($id,'admin',$old,$summary,$minor);
100990033e9dSAndreas Gohr  notify($id,'subscribers',$old,$summary,$minor);
1010f3f0262cSandi
1011ce6b63d9Schris  // update the purgefile (timestamp of the last time anything within the wiki was changed)
101298407a7aSandi  io_saveFile($conf['cachedir'].'/purgefile',time());
10132eccbdaaSGina Haeussge
10142eccbdaaSGina Haeussge  // if useheading is enabled, purge the cache of all linking pages
1015fe9ec250SChris Smith  if(useHeading('content')){
10162eccbdaaSGina Haeussge    require_once(DOKU_INC.'inc/fulltext.php');
10172eccbdaaSGina Haeussge    $pages = ft_backlinks($id);
10182eccbdaaSGina Haeussge    foreach ($pages as $page) {
10192eccbdaaSGina Haeussge      $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
10202eccbdaaSGina Haeussge      $cache->removeCache();
10212eccbdaaSGina Haeussge    }
10222eccbdaaSGina Haeussge  }
1023f3f0262cSandi}
1024f3f0262cSandi
1025f3f0262cSandi/**
1026f3f0262cSandi * moves the current version to the attic and returns its
1027f3f0262cSandi * revision date
102815fae107Sandi *
102915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1030f3f0262cSandi */
1031f3f0262cSandifunction saveOldRevision($id){
1032f3f0262cSandi  global $conf;
1033f3f0262cSandi  $oldf = wikiFN($id);
1034f3f0262cSandi  if(!@file_exists($oldf)) return '';
1035f3f0262cSandi  $date = filemtime($oldf);
1036f3f0262cSandi  $newf = wikiFN($id,$date);
1037cc7d0c94SBen Coburn  io_writeWikiPage($newf, rawWiki($id), $id, $date);
1038f3f0262cSandi  return $date;
1039f3f0262cSandi}
1040f3f0262cSandi
1041f3f0262cSandi/**
104226a0801fSAndreas Gohr * Sends a notify mail on page change
104326a0801fSAndreas Gohr *
104426a0801fSAndreas Gohr * @param  string  $id       The changed page
104526a0801fSAndreas Gohr * @param  string  $who      Who to notify (admin|subscribers)
104626a0801fSAndreas Gohr * @param  int     $rev      Old page revision
104726a0801fSAndreas Gohr * @param  string  $summary  What changed
104890033e9dSAndreas Gohr * @param  boolean $minor    Is this a minor edit?
104902a498e7Schris * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
105015fae107Sandi *
105115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1052f3f0262cSandi */
105302a498e7Schrisfunction notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1054f3f0262cSandi  global $lang;
1055f3f0262cSandi  global $conf;
105630d7d718SMike Frysinger  global $INFO;
1057b158d625SSteven Danz
105826a0801fSAndreas Gohr  // decide if there is something to do
105926a0801fSAndreas Gohr  if($who == 'admin'){
106026a0801fSAndreas Gohr    if(empty($conf['notify'])) return; //notify enabled?
1061f3f0262cSandi    $text = rawLocale('mailtext');
106226a0801fSAndreas Gohr    $to   = $conf['notify'];
106326a0801fSAndreas Gohr    $bcc  = '';
106426a0801fSAndreas Gohr  }elseif($who == 'subscribers'){
106526a0801fSAndreas Gohr    if(!$conf['subscribers']) return; //subscribers enabled?
106690033e9dSAndreas Gohr    if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
106755eea442SAndreas Gohr    $bcc  = subscriber_addresslist($id,false);
106826a0801fSAndreas Gohr    if(empty($bcc)) return;
106926a0801fSAndreas Gohr    $to   = '';
107026a0801fSAndreas Gohr    $text = rawLocale('subscribermail');
1071a06e4bdbSSebastian Harl  }elseif($who == 'register'){
1072a06e4bdbSSebastian Harl    if(empty($conf['registernotify'])) return;
1073a06e4bdbSSebastian Harl    $text = rawLocale('registermail');
1074a06e4bdbSSebastian Harl    $to   = $conf['registernotify'];
1075a06e4bdbSSebastian Harl    $bcc  = '';
107626a0801fSAndreas Gohr  }else{
107726a0801fSAndreas Gohr    return; //just to be safe
107826a0801fSAndreas Gohr  }
107926a0801fSAndreas Gohr
108063211f61SGlen Harris  $ip   = clientIP();
1081e656dcd4SAndreas Gohr  $text = str_replace('@DATE@',strftime($conf['dformat']),$text);
1082f3f0262cSandi  $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
108363211f61SGlen Harris  $text = str_replace('@IPADDRESS@',$ip,$text);
108463211f61SGlen Harris  $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1085c9321d91SAndreas Gohr  $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
108626a0801fSAndreas Gohr  $text = str_replace('@PAGE@',$id,$text);
108726a0801fSAndreas Gohr  $text = str_replace('@TITLE@',$conf['title'],$text);
1088ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1089f3f0262cSandi  $text = str_replace('@SUMMARY@',$summary,$text);
10907a82afdcSandi  $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1091f3f0262cSandi
109202a498e7Schris  foreach ($replace as $key => $substitution) {
109302a498e7Schris    $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
109402a498e7Schris  }
109502a498e7Schris
1096a06e4bdbSSebastian Harl  if($who == 'register'){
1097a06e4bdbSSebastian Harl    $subject = $lang['mail_new_user'].' '.$summary;
1098a06e4bdbSSebastian Harl  }elseif($rev){
1099f3f0262cSandi    $subject = $lang['mail_changed'].' '.$id;
1100c9321d91SAndreas Gohr    $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1101ccdfa6c0SAndreas Gohr    require_once(DOKU_INC.'inc/DifferenceEngine.php');
1102f3f0262cSandi    $df  = new Diff(split("\n",rawWiki($id,$rev)),
1103f3f0262cSandi                    split("\n",rawWiki($id)));
1104f3f0262cSandi    $dformat = new UnifiedDiffFormatter();
1105f3f0262cSandi    $diff    = $dformat->format($df);
1106f3f0262cSandi  }else{
1107f3f0262cSandi    $subject=$lang['mail_newpage'].' '.$id;
1108f3f0262cSandi    $text = str_replace('@OLDPAGE@','none',$text);
1109f3f0262cSandi    $diff = rawWiki($id);
1110f3f0262cSandi  }
1111f3f0262cSandi  $text = str_replace('@DIFF@',$diff,$text);
1112241f3a36Sandi  $subject = '['.$conf['title'].'] '.$subject;
1113f3f0262cSandi
111430d7d718SMike Frysinger  $from = $conf['mailfrom'];
111530d7d718SMike Frysinger  $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
111630d7d718SMike Frysinger  $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
111730d7d718SMike Frysinger  $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
111830d7d718SMike Frysinger
111930d7d718SMike Frysinger  mail_send($to,$subject,$text,$from,'',$bcc);
1120f3f0262cSandi}
1121f3f0262cSandi
112215fae107Sandi/**
112371f7bde7SAndreas Gohr * extracts the query from a search engine referrer
112415fae107Sandi *
112515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
112671f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1127f3f0262cSandi */
1128f3f0262cSandifunction getGoogleQuery(){
1129f3f0262cSandi  $url = parse_url($_SERVER['HTTP_REFERER']);
11305c3f206fSandi  if(!$url) return '';
1131f3f0262cSandi
1132f3f0262cSandi  $query = array();
1133f3f0262cSandi  parse_str($url['query'],$query);
113471f7bde7SAndreas Gohr  if(isset($query['q']))
1135f93b3b50SAndreas Gohr    $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
113671f7bde7SAndreas Gohr  elseif(isset($query['p']))
1137f93b3b50SAndreas Gohr    $q = $query['p'];        // yahoo
113871f7bde7SAndreas Gohr  elseif(isset($query['query']))
1139f93b3b50SAndreas Gohr    $q = $query['query'];    // lycos, netscape, clusty, hotbot
114071f7bde7SAndreas Gohr  elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1141f93b3b50SAndreas Gohr    $q = urldecode(ltrim($url['path'],'/'));
1142f3f0262cSandi
1143f93b3b50SAndreas Gohr  if(!$q) return '';
11446531ab03SAndreas Gohr  $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1145f93b3b50SAndreas Gohr  return $q;
1146f3f0262cSandi}
1147f3f0262cSandi
1148f3f0262cSandi/**
114915fae107Sandi * Try to set correct locale
115015fae107Sandi *
1151095bfd5cSandi * @deprecated No longer used
115215fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1153f3f0262cSandi */
1154f3f0262cSandifunction setCorrectLocale(){
1155f3f0262cSandi  global $conf;
1156f3f0262cSandi  global $lang;
1157f3f0262cSandi
1158f3f0262cSandi  $enc = strtoupper($lang['encoding']);
1159f3f0262cSandi  foreach ($lang['locales'] as $loc){
1160f3f0262cSandi    //try locale
1161f3f0262cSandi    if(@setlocale(LC_ALL,$loc)) return;
1162f3f0262cSandi    //try loceale with encoding
1163f3f0262cSandi    if(@setlocale(LC_ALL,"$loc.$enc")) return;
1164f3f0262cSandi  }
1165f3f0262cSandi  //still here? try to set from environment
1166f3f0262cSandi  @setlocale(LC_ALL,"");
1167f3f0262cSandi}
1168f3f0262cSandi
1169f3f0262cSandi/**
1170f3f0262cSandi * Return the human readable size of a file
1171f3f0262cSandi *
1172f3f0262cSandi * @param       int    $size   A file size
1173f3f0262cSandi * @param       int    $dec    A number of decimal places
1174f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1175f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1176f3f0262cSandi * @version     1.0.0
1177f3f0262cSandi */
1178f31d5b73Sandifunction filesize_h($size, $dec = 1){
1179f3f0262cSandi  $sizes = array('B', 'KB', 'MB', 'GB');
1180f3f0262cSandi  $count = count($sizes);
1181f3f0262cSandi  $i = 0;
1182f3f0262cSandi
1183f3f0262cSandi  while ($size >= 1024 && ($i < $count - 1)) {
1184f3f0262cSandi    $size /= 1024;
1185f3f0262cSandi    $i++;
1186f3f0262cSandi  }
1187f3f0262cSandi
1188f3f0262cSandi  return round($size, $dec) . ' ' . $sizes[$i];
1189f3f0262cSandi}
1190f3f0262cSandi
119115fae107Sandi/**
119200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
119300a7b5adSEsther Brunner *
119400a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
119500a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
119600a7b5adSEsther Brunner */
119700a7b5adSEsther Brunnerfunction obfuscate($email) {
119800a7b5adSEsther Brunner  global $conf;
119900a7b5adSEsther Brunner
120000a7b5adSEsther Brunner  switch ($conf['mailguard']) {
120100a7b5adSEsther Brunner    case 'visible' :
120200a7b5adSEsther Brunner      $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
120300a7b5adSEsther Brunner      return strtr($email, $obfuscate);
120400a7b5adSEsther Brunner
120500a7b5adSEsther Brunner    case 'hex' :
120600a7b5adSEsther Brunner      $encode = '';
120700a7b5adSEsther Brunner      for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';';
120800a7b5adSEsther Brunner      return $encode;
120900a7b5adSEsther Brunner
121000a7b5adSEsther Brunner    case 'none' :
121100a7b5adSEsther Brunner    default :
121200a7b5adSEsther Brunner      return $email;
121300a7b5adSEsther Brunner  }
121400a7b5adSEsther Brunner}
121500a7b5adSEsther Brunner
121600a7b5adSEsther Brunner/**
121752b0dd67SGuy Brand * Let us know if a user is tracking a page or a namespace
1218b158d625SSteven Danz *
12191380fc45SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1220b158d625SSteven Danz */
122152b0dd67SGuy Brandfunction is_subscribed($id,$uid,$ns=false){
122252b0dd67SGuy Brand  if(!$ns) {
12231380fc45SAndreas Gohr    $file=metaFN($id,'.mlist');
122452b0dd67SGuy Brand  } else {
122552b0dd67SGuy Brand    if(!getNS($id)) {
122652b0dd67SGuy Brand      $file = metaFN(getNS($id),'.mlist');
122752b0dd67SGuy Brand    } else {
122852b0dd67SGuy Brand      $file = metaFN(getNS($id),'/.mlist');
122952b0dd67SGuy Brand    }
123052b0dd67SGuy Brand  }
12311380fc45SAndreas Gohr  if (@file_exists($file)) {
1232b158d625SSteven Danz    $mlist = file($file);
12331380fc45SAndreas Gohr    $pos = array_search($uid."\n",$mlist);
12341380fc45SAndreas Gohr    return is_int($pos);
1235b158d625SSteven Danz  }
12361380fc45SAndreas Gohr
1237b158d625SSteven Danz  return false;
1238b158d625SSteven Danz}
1239340756e4Sandi
1240f9eb5648Ssteven-danz/**
1241f9eb5648Ssteven-danz * Return a string with the email addresses of all the
1242f9eb5648Ssteven-danz * users subscribed to a page
1243f9eb5648Ssteven-danz *
124426a0801fSAndreas Gohr * @author Steven Danz <steven-danz@kc.rr.com>
1245f9eb5648Ssteven-danz */
124655eea442SAndreas Gohrfunction subscriber_addresslist($id,$self=true){
1247f9eb5648Ssteven-danz  global $conf;
1248cd52f92dSchris  global $auth;
1249f9eb5648Ssteven-danz
125012cb3a51STom N Harris  if (!$conf['subscribers']) return '';
1251f9eb5648Ssteven-danz
125212cb3a51STom N Harris  $users = array();
125312cb3a51STom N Harris  $emails = array();
125426a0801fSAndreas Gohr
125552b0dd67SGuy Brand  // load the page mlist file content
1256f9eb5648Ssteven-danz  $mlist = array();
1257f9eb5648Ssteven-danz  $file=metaFN($id,'.mlist');
1258d8186216SBen Coburn  if (@file_exists($file)) {
1259f9eb5648Ssteven-danz    $mlist = file($file);
1260f9eb5648Ssteven-danz    foreach ($mlist as $who) {
1261f9eb5648Ssteven-danz      $who = rtrim($who);
126255eea442SAndreas Gohr      if(!$self && $who == $_SERVER['REMOTE_USER']) continue;
126312cb3a51STom N Harris      $users[$who] = true;
1264f9eb5648Ssteven-danz    }
1265f9eb5648Ssteven-danz  }
1266f9eb5648Ssteven-danz
126752b0dd67SGuy Brand  // load also the namespace mlist file content
126812cb3a51STom N Harris  $ns = getNS($id);
126912cb3a51STom N Harris  while ($ns) {
127012cb3a51STom N Harris    $nsfile = metaFN($ns,'/.mlist');
127152b0dd67SGuy Brand    if (@file_exists($nsfile)) {
127252b0dd67SGuy Brand      $mlist = file($nsfile);
127352b0dd67SGuy Brand      foreach ($mlist as $who) {
127452b0dd67SGuy Brand        $who = rtrim($who);
127555eea442SAndreas Gohr        if(!$self && $who == $_SERVER['REMOTE_USER']) continue;
127612cb3a51STom N Harris        $users[$who] = true;
127712cb3a51STom N Harris      }
127812cb3a51STom N Harris    }
127912cb3a51STom N Harris    $ns = getNS($ns);
128012cb3a51STom N Harris  }
128112cb3a51STom N Harris  // root namespace
128212cb3a51STom N Harris  $nsfile = metaFN('','.mlist');
128312cb3a51STom N Harris  if (@file_exists($nsfile)) {
128412cb3a51STom N Harris    $mlist = file($nsfile);
128512cb3a51STom N Harris    foreach ($mlist as $who) {
128612cb3a51STom N Harris      $who = rtrim($who);
128755eea442SAndreas Gohr      if(!$self && $who == $_SERVER['REMOTE_USER']) continue;
128812cb3a51STom N Harris      $users[$who] = true;
128912cb3a51STom N Harris    }
129012cb3a51STom N Harris  }
129112cb3a51STom N Harris  if(!empty($users)) {
129212cb3a51STom N Harris    foreach (array_keys($users) as $who) {
129352b0dd67SGuy Brand      $info = $auth->getUserData($who);
129452b0dd67SGuy Brand      if($info === false) continue;
129552b0dd67SGuy Brand      $level = auth_aclcheck($id,$who,$info['grps']);
129652b0dd67SGuy Brand      if ($level >= AUTH_READ) {
129752b0dd67SGuy Brand        if (strcasecmp($info['mail'],$conf['notify']) != 0) {
129812cb3a51STom N Harris          $emails[] = $info['mail'];
129952b0dd67SGuy Brand        }
130052b0dd67SGuy Brand      }
130152b0dd67SGuy Brand    }
130252b0dd67SGuy Brand  }
130352b0dd67SGuy Brand
130412cb3a51STom N Harris  return implode(',',$emails);
1305f9eb5648Ssteven-danz}
1306f9eb5648Ssteven-danz
130789541d4bSAndreas Gohr/**
130889541d4bSAndreas Gohr * Removes quoting backslashes
130989541d4bSAndreas Gohr *
131089541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
131189541d4bSAndreas Gohr */
131289541d4bSAndreas Gohrfunction unslash($string,$char="'"){
131389541d4bSAndreas Gohr  return str_replace('\\'.$char,$char,$string);
131489541d4bSAndreas Gohr}
131589541d4bSAndreas Gohr
131673038c47SAndreas Gohr/**
131773038c47SAndreas Gohr * Convert php.ini shorthands to byte
131873038c47SAndreas Gohr *
131973038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
132073038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
132173038c47SAndreas Gohr */
132273038c47SAndreas Gohrfunction php_to_byte($v){
132373038c47SAndreas Gohr    $l = substr($v, -1);
132473038c47SAndreas Gohr    $ret = substr($v, 0, -1);
132573038c47SAndreas Gohr    switch(strtoupper($l)){
132673038c47SAndreas Gohr        case 'P':
132773038c47SAndreas Gohr            $ret *= 1024;
132873038c47SAndreas Gohr        case 'T':
132973038c47SAndreas Gohr            $ret *= 1024;
133073038c47SAndreas Gohr        case 'G':
133173038c47SAndreas Gohr            $ret *= 1024;
133273038c47SAndreas Gohr        case 'M':
133373038c47SAndreas Gohr            $ret *= 1024;
133473038c47SAndreas Gohr        case 'K':
133573038c47SAndreas Gohr            $ret *= 1024;
133673038c47SAndreas Gohr        break;
133773038c47SAndreas Gohr    }
133873038c47SAndreas Gohr    return $ret;
133973038c47SAndreas Gohr}
134073038c47SAndreas Gohr
1341546d3a99SAndreas Gohr/**
1342546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1343546d3a99SAndreas Gohr */
1344546d3a99SAndreas Gohrfunction preg_quote_cb($string){
1345546d3a99SAndreas Gohr    return preg_quote($string,'/');
1346546d3a99SAndreas Gohr}
134773038c47SAndreas Gohr
1348bd2f6c2fSAndreas Gohr/**
1349bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1350bd2f6c2fSAndreas Gohr *
1351bd2f6c2fSAndreas Gohr * You can give the string in two parts, teh first part $keep
1352bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1353bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1354bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1355bd2f6c2fSAndreas Gohr *
1356bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1357bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1358bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1359bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1360bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1361bd2f6c2fSAndreas Gohr */
1362bd2f6c2fSAndreas Gohrfunction shorten($keep,$short,$max,$min=9,$char='⌇'){
1363bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1364bd2f6c2fSAndreas Gohr   if($max < $min) return $keep;
1365bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1366bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1367bd2f6c2fSAndreas Gohr    $half = floor($max/2);
1368bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1369bd2f6c2fSAndreas Gohr}
1370bd2f6c2fSAndreas Gohr
1371dc58b6f4SAndy Webber/**
1372dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1373dc58b6f4SAndy Webber * in page footer and recent changes pages
1374dc58b6f4SAndy Webber *
1375dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1376dc58b6f4SAndy Webber */
1377dc58b6f4SAndy Webberfunction editorinfo($username){
1378dc58b6f4SAndy Webber    global $conf;
1379dc58b6f4SAndy Webber    global $auth;
1380dc58b6f4SAndy Webber
1381dc58b6f4SAndy Webber    switch($conf['showuseras']){
1382dc58b6f4SAndy Webber      case 'username':
1383dc58b6f4SAndy Webber      case 'email':
1384dc58b6f4SAndy Webber      case 'email_link':
1385173d78c4SAndreas Gohr        if($auth) $info = $auth->getUserData($username);
1386dc58b6f4SAndy Webber        break;
1387dc58b6f4SAndy Webber      default:
1388dc58b6f4SAndy Webber        return hsc($username);
1389dc58b6f4SAndy Webber    }
1390dc58b6f4SAndy Webber
1391dc58b6f4SAndy Webber    if(isset($info) && $info) {
1392dc58b6f4SAndy Webber        switch($conf['showuseras']){
1393dc58b6f4SAndy Webber          case 'username':
1394dc58b6f4SAndy Webber            return hsc($info['name']);
1395dc58b6f4SAndy Webber          case 'email':
1396dc58b6f4SAndy Webber            return obfuscate($info['mail']);
1397dc58b6f4SAndy Webber          case 'email_link':
1398dc58b6f4SAndy Webber            $mail=obfuscate($info['mail']);
1399dc58b6f4SAndy Webber            return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1400dc58b6f4SAndy Webber          default:
1401dc58b6f4SAndy Webber            return hsc($username);
1402dc58b6f4SAndy Webber        }
1403dc58b6f4SAndy Webber    } else {
1404dc58b6f4SAndy Webber        return hsc($username);
1405dc58b6f4SAndy Webber    }
1406066fee30SAndreas Gohr}
1407066fee30SAndreas Gohr
1408066fee30SAndreas Gohr/**
1409066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1410066fee30SAndreas Gohr * When no image exists, returns an empty string
1411066fee30SAndreas Gohr *
1412066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1413066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
1414066fee30SAndreas Gohr */
1415066fee30SAndreas Gohrfunction license_img($type){
1416066fee30SAndreas Gohr    global $license;
1417066fee30SAndreas Gohr    global $conf;
1418066fee30SAndreas Gohr    if(!$conf['license']) return '';
1419066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1420066fee30SAndreas Gohr    $lic = $license[$conf['license']];
1421066fee30SAndreas Gohr    $try = array();
1422066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1423066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1424066fee30SAndreas Gohr    if(substr($conf['license'],0,3) == 'cc-'){
1425066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1426066fee30SAndreas Gohr    }
1427066fee30SAndreas Gohr    foreach($try as $src){
1428066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1429066fee30SAndreas Gohr    }
1430066fee30SAndreas Gohr    return '';
1431dc58b6f4SAndy Webber}
1432dc58b6f4SAndy Webber
143313c08e2fSMichael Klier/**
143413c08e2fSMichael Klier * Checks if the given amount of memory is available
143513c08e2fSMichael Klier *
143613c08e2fSMichael Klier * If the memory_get_usage() function is not available the
143713c08e2fSMichael Klier * function just assumes $bytes of already allocated memory
143813c08e2fSMichael Klier *
143913c08e2fSMichael Klier * @param  int $mem  Size of memory you want to allocate in bytes
144013c08e2fSMichael Klier * @param  int $used already allocated memory (see above)
144113c08e2fSMichael Klier * @author Filip Oscadal <webmaster@illusionsoftworks.cz>
144213c08e2fSMichael Klier * @author Andreas Gohr <andi@splitbrain.org>
144313c08e2fSMichael Klier */
144413c08e2fSMichael Klierfunction is_mem_available($mem,$bytes=1048576){
144513c08e2fSMichael Klier  $limit = trim(ini_get('memory_limit'));
144613c08e2fSMichael Klier  if(empty($limit)) return true; // no limit set!
144713c08e2fSMichael Klier
144813c08e2fSMichael Klier  // parse limit to bytes
144913c08e2fSMichael Klier  $limit = php_to_byte($limit);
145013c08e2fSMichael Klier
145113c08e2fSMichael Klier  // get used memory if possible
145213c08e2fSMichael Klier  if(function_exists('memory_get_usage')){
145313c08e2fSMichael Klier    $used = memory_get_usage();
145413c08e2fSMichael Klier  }
145513c08e2fSMichael Klier
145613c08e2fSMichael Klier  if($used+$mem > $limit){
145713c08e2fSMichael Klier    return false;
145813c08e2fSMichael Klier  }
145913c08e2fSMichael Klier
146013c08e2fSMichael Klier  return true;
146113c08e2fSMichael Klier}
146213c08e2fSMichael Klier
1463af2408d5SAndreas Gohr/**
1464af2408d5SAndreas Gohr * Send a HTTP redirect to the browser
1465af2408d5SAndreas Gohr *
1466af2408d5SAndreas Gohr * Works arround Microsoft IIS cookie sending bug. Exits the script.
1467af2408d5SAndreas Gohr *
1468af2408d5SAndreas Gohr * @link   http://support.microsoft.com/kb/q176113/
1469af2408d5SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1470af2408d5SAndreas Gohr */
1471af2408d5SAndreas Gohrfunction send_redirect($url){
1472d4869846SAndreas Gohr    // always close the session
1473d4869846SAndreas Gohr    session_write_close();
1474d4869846SAndreas Gohr
1475af2408d5SAndreas Gohr    // check if running on IIS < 6 with CGI-PHP
1476af2408d5SAndreas Gohr    if( isset($_SERVER['SERVER_SOFTWARE']) && isset($_SERVER['GATEWAY_INTERFACE']) &&
1477af2408d5SAndreas Gohr        (strpos($_SERVER['GATEWAY_INTERFACE'],'CGI') !== false) &&
1478af2408d5SAndreas Gohr        (preg_match('|^Microsoft-IIS/(\d)\.\d$|', trim($_SERVER['SERVER_SOFTWARE']), $matches)) &&
1479af2408d5SAndreas Gohr        $matches[1] < 6 ){
1480af2408d5SAndreas Gohr        header('Refresh: 0;url='.$url);
1481af2408d5SAndreas Gohr    }else{
1482af2408d5SAndreas Gohr        header('Location: '.$url);
1483af2408d5SAndreas Gohr    }
1484af2408d5SAndreas Gohr    exit;
1485af2408d5SAndreas Gohr}
1486af2408d5SAndreas Gohr
1487340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1488