xref: /dokuwiki/inc/common.php (revision dc14c6d1104eea9f954b6aa31c0383a55186e177)
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
900976812SAndreas Gohrif(!defined('DOKU_INC')) define('DOKU_INC',fullpath(dirname(__FILE__).'/../').'/');
10e7cb32dcSAndreas Gohrrequire_once(DOKU_CONF.'dokuwiki.php');
11ed7b5f09Sandirequire_once(DOKU_INC.'inc/io.php');
127d559c7fSBen Coburnrequire_once(DOKU_INC.'inc/changelog.php');
13ed7b5f09Sandirequire_once(DOKU_INC.'inc/utf8.php');
14ed7b5f09Sandirequire_once(DOKU_INC.'inc/mail.php');
15c112d578Sandirequire_once(DOKU_INC.'inc/parserutils.php');
16c29dc6e4SAndreas Gohrrequire_once(DOKU_INC.'inc/infoutils.php');
17f3f0262cSandi
18f3f0262cSandi/**
19b6912aeaSAndreas Gohr * These constants are used with the recents function
20b6912aeaSAndreas Gohr */
21b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_DELETED',2);
22b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_MINORS',4);
23b6912aeaSAndreas Gohrdefine('RECENTS_SKIP_SUBSPACES',8);
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;
102f3f0262cSandi  global $USERINFO;
103f3f0262cSandi  global $conf;
104f3f0262cSandi
1056afe8dcaSchris  // include ID & REV not redundant, as some parts of DokuWiki may temporarily change $ID, e.g. p_wiki_xhtml
1066afe8dcaSchris  // FIXME ... perhaps it would be better to ensure the temporary changes weren't necessary
1076afe8dcaSchris  $info['id'] = $ID;
1086afe8dcaSchris  $info['rev'] = $REV;
1096afe8dcaSchris
110f3f0262cSandi  if($_SERVER['REMOTE_USER']){
111f3f0262cSandi    $info['userinfo']     = $USERINFO;
112f3f0262cSandi    $info['perm']         = auth_quickaclcheck($ID);
11352b0dd67SGuy Brand    $info['subscribed']   = is_subscribed($ID,$_SERVER['REMOTE_USER'],false);
11452b0dd67SGuy Brand    $info['subscribedns'] = is_subscribed($ID,$_SERVER['REMOTE_USER'],true);
115ee4c4a1bSAndreas Gohr    $info['client']       = $_SERVER['REMOTE_USER'];
11617ee7f66SAndreas Gohr
117f8cc712eSAndreas Gohr    // set info about manager/admin status
118f8cc712eSAndreas Gohr    $info['isadmin']   = false;
119f8cc712eSAndreas Gohr    $info['ismanager'] = false;
120f8cc712eSAndreas Gohr    if($info['perm'] == AUTH_ADMIN){
121f8cc712eSAndreas Gohr      $info['isadmin']   = true;
122f8cc712eSAndreas Gohr      $info['ismanager'] = true;
123f8cc712eSAndreas Gohr    }elseif(auth_ismanager()){
124f8cc712eSAndreas Gohr      $info['ismanager'] = true;
125f8cc712eSAndreas Gohr    }
126f8cc712eSAndreas Gohr
12717ee7f66SAndreas Gohr    // if some outside auth were used only REMOTE_USER is set
12817ee7f66SAndreas Gohr    if(!$info['userinfo']['name']){
12917ee7f66SAndreas Gohr      $info['userinfo']['name'] = $_SERVER['REMOTE_USER'];
13017ee7f66SAndreas Gohr    }
131ee4c4a1bSAndreas Gohr
132f3f0262cSandi  }else{
133f3f0262cSandi    $info['perm']       = auth_aclcheck($ID,'',null);
1341380fc45SAndreas Gohr    $info['subscribed'] = false;
135ee4c4a1bSAndreas Gohr    $info['client']     = clientIP(true);
136f3f0262cSandi  }
137f3f0262cSandi
138f3f0262cSandi  $info['namespace'] = getNS($ID);
139f3f0262cSandi  $info['locked']    = checklock($ID);
14000976812SAndreas Gohr  $info['filepath']  = fullpath(wikiFN($ID));
1412ca9d91cSBen Coburn  $info['exists']    = @file_exists($info['filepath']);
1422ca9d91cSBen Coburn  if($REV){
1432ca9d91cSBen Coburn    //check if current revision was meant
1442ca9d91cSBen Coburn    if($info['exists'] && (@filemtime($info['filepath'])==$REV)){
1452ca9d91cSBen Coburn      $REV = '';
1462ca9d91cSBen Coburn    }else{
1472ca9d91cSBen Coburn      //really use old revision
14800976812SAndreas Gohr      $info['filepath'] = fullpath(wikiFN($ID,$REV));
149f3f0262cSandi      $info['exists']   = @file_exists($info['filepath']);
150f3f0262cSandi    }
151f3f0262cSandi  }
152c112d578Sandi  $info['rev'] = $REV;
153f3f0262cSandi  if($info['exists']){
154f3f0262cSandi    $info['writable'] = (is_writable($info['filepath']) &&
155f3f0262cSandi                         ($info['perm'] >= AUTH_EDIT));
156f3f0262cSandi  }else{
157f3f0262cSandi    $info['writable'] = ($info['perm'] >= AUTH_CREATE);
158f3f0262cSandi  }
159f3f0262cSandi  $info['editable']  = ($info['writable'] && empty($info['lock']));
160f3f0262cSandi  $info['lastmod']   = @filemtime($info['filepath']);
161f3f0262cSandi
16271726d78SBen Coburn  //load page meta data
16371726d78SBen Coburn  $info['meta'] = p_get_metadata($ID);
16471726d78SBen Coburn
165652610a2Sandi  //who's the editor
166652610a2Sandi  if($REV){
16771726d78SBen Coburn    $revinfo = getRevisionInfo($ID, $REV, 1024);
168652610a2Sandi  }else{
169aa27cf05SAndreas Gohr    if (is_array($info['meta']['last_change'])) {
170aa27cf05SAndreas Gohr       $revinfo = $info['meta']['last_change'];
171aa27cf05SAndreas Gohr    } else {
172cd00a034SBen Coburn      $revinfo = getRevisionInfo($ID, $info['lastmod'], 1024);
173cd00a034SBen Coburn      // cache most recent changelog line in metadata if missing and still valid
174cd00a034SBen Coburn      if ($revinfo!==false) {
175cd00a034SBen Coburn        $info['meta']['last_change'] = $revinfo;
176cd00a034SBen Coburn        p_set_metadata($ID, array('last_change' => $revinfo));
177cd00a034SBen Coburn      }
178cd00a034SBen Coburn    }
179cd00a034SBen Coburn  }
180cd00a034SBen Coburn  //and check for an external edit
181cd00a034SBen Coburn  if($revinfo!==false && $revinfo['date']!=$info['lastmod']){
182cd00a034SBen Coburn    // cached changelog line no longer valid
183cd00a034SBen Coburn    $revinfo = false;
184cd00a034SBen Coburn    $info['meta']['last_change'] = $revinfo;
185cd00a034SBen Coburn    p_set_metadata($ID, array('last_change' => $revinfo));
186652610a2Sandi  }
187bb4866bdSchris
188652610a2Sandi  $info['ip']     = $revinfo['ip'];
189652610a2Sandi  $info['user']   = $revinfo['user'];
190652610a2Sandi  $info['sum']    = $revinfo['sum'];
19171726d78SBen Coburn  // See also $INFO['meta']['last_change'] which is the most recent log line for page $ID.
192ebf1501fSBen Coburn  // Use $INFO['meta']['last_change']['type']===DOKU_CHANGE_TYPE_MINOR_EDIT in place of $info['minor'].
19359f257aeSchris
19488f522e9Sandi  if($revinfo['user']){
19588f522e9Sandi    $info['editor'] = $revinfo['user'];
19688f522e9Sandi  }else{
19788f522e9Sandi    $info['editor'] = $revinfo['ip'];
19888f522e9Sandi  }
199652610a2Sandi
200ee4c4a1bSAndreas Gohr  // draft
201ee4c4a1bSAndreas Gohr  $draft = getCacheName($info['client'].$ID,'.draft');
202ee4c4a1bSAndreas Gohr  if(@file_exists($draft)){
203ee4c4a1bSAndreas Gohr    if(@filemtime($draft) < @filemtime(wikiFN($ID))){
204ee4c4a1bSAndreas Gohr      // remove stale draft
205ee4c4a1bSAndreas Gohr      @unlink($draft);
206ee4c4a1bSAndreas Gohr    }else{
207ee4c4a1bSAndreas Gohr      $info['draft'] = $draft;
208ee4c4a1bSAndreas Gohr    }
209ee4c4a1bSAndreas Gohr  }
210ee4c4a1bSAndreas Gohr
2111c548ebeSAndreas Gohr  // mobile detection
2121c548ebeSAndreas Gohr  $info['ismobile'] = clientismobile();
2131c548ebeSAndreas Gohr
214f3f0262cSandi  return $info;
215f3f0262cSandi}
216f3f0262cSandi
217f3f0262cSandi/**
2182684e50aSAndreas Gohr * Build an string of URL parameters
2192684e50aSAndreas Gohr *
2202684e50aSAndreas Gohr * @author Andreas Gohr
2212684e50aSAndreas Gohr */
222b174aeaeSchrisfunction buildURLparams($params, $sep='&amp;'){
2232684e50aSAndreas Gohr  $url = '';
2242684e50aSAndreas Gohr  $amp = false;
2252684e50aSAndreas Gohr  foreach($params as $key => $val){
226b174aeaeSchris    if($amp) $url .= $sep;
2272684e50aSAndreas Gohr
2282684e50aSAndreas Gohr    $url .= $key.'=';
2293a50618cSgweissbach    $url .= rawurlencode((string)$val);
2302684e50aSAndreas Gohr    $amp = true;
2312684e50aSAndreas Gohr  }
2322684e50aSAndreas Gohr  return $url;
2332684e50aSAndreas Gohr}
2342684e50aSAndreas Gohr
2352684e50aSAndreas Gohr/**
2362684e50aSAndreas Gohr * Build an string of html tag attributes
2372684e50aSAndreas Gohr *
2387bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2397bff22c0SAndreas Gohr *
2402684e50aSAndreas Gohr * @author Andreas Gohr
2412684e50aSAndreas Gohr */
2424b030ce7SAndreas Gohrfunction buildAttributes($params,$skipempty=false){
2432684e50aSAndreas Gohr  $url = '';
2442684e50aSAndreas Gohr  foreach($params as $key => $val){
2457bff22c0SAndreas Gohr    if($key{0} == '_') continue;
246b1c94f1dSAndreas Gohr    if($val === '' && $skipempty) continue;
2477bff22c0SAndreas Gohr
2482684e50aSAndreas Gohr    $url .= $key.'="';
2492684e50aSAndreas Gohr    $url .= htmlspecialchars ($val);
2502684e50aSAndreas Gohr    $url .= '" ';
2512684e50aSAndreas Gohr  }
2522684e50aSAndreas Gohr  return $url;
2532684e50aSAndreas Gohr}
2542684e50aSAndreas Gohr
2552684e50aSAndreas Gohr
2562684e50aSAndreas Gohr/**
25715fae107Sandi * This builds the breadcrumb trail and returns it as array
25815fae107Sandi *
25915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
260f3f0262cSandi */
261f3f0262cSandifunction breadcrumbs(){
2628746e727Sandi  // we prepare the breadcrumbs early for quick session closing
2638746e727Sandi  static $crumbs = null;
2648746e727Sandi  if($crumbs != null) return $crumbs;
2658746e727Sandi
266f3f0262cSandi  global $ID;
267f3f0262cSandi  global $ACT;
268f3f0262cSandi  global $conf;
269e71ce681SAndreas Gohr  $crumbs = $_SESSION[DOKU_COOKIE]['bc'];
270f3f0262cSandi
271f3f0262cSandi  //first visit?
272f3f0262cSandi  if (!is_array($crumbs)){
273f3f0262cSandi    $crumbs = array();
274f3f0262cSandi  }
275f3f0262cSandi  //we only save on show and existing wiki documents
276a77f5846Sjan  $file = wikiFN($ID);
277a77f5846Sjan  if($ACT != 'show' || !@file_exists($file)){
278e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
279f3f0262cSandi    return $crumbs;
280f3f0262cSandi  }
281a77f5846Sjan
282a77f5846Sjan  // page names
2831a84a0f3SAnika Henke  $name = noNSorNS($ID);
284a77f5846Sjan  if ($conf['useheading']) {
285a77f5846Sjan    // get page title
286955cd091SChris Smith    $title = p_get_first_heading($ID,true);
287a77f5846Sjan    if ($title) {
288a77f5846Sjan      $name = $title;
289a77f5846Sjan    }
290a77f5846Sjan  }
291a77f5846Sjan
292f3f0262cSandi  //remove ID from array
293a77f5846Sjan  if (isset($crumbs[$ID])) {
294a77f5846Sjan    unset($crumbs[$ID]);
295f3f0262cSandi  }
296f3f0262cSandi
297f3f0262cSandi  //add to array
298a77f5846Sjan  $crumbs[$ID] = $name;
299f3f0262cSandi  //reduce size
300f3f0262cSandi  while(count($crumbs) > $conf['breadcrumbs']){
301f3f0262cSandi    array_shift($crumbs);
302f3f0262cSandi  }
303f3f0262cSandi  //save to session
304e71ce681SAndreas Gohr  $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
305f3f0262cSandi  return $crumbs;
306f3f0262cSandi}
307f3f0262cSandi
308f3f0262cSandi/**
30915fae107Sandi * Filter for page IDs
31015fae107Sandi *
311f3f0262cSandi * This is run on a ID before it is outputted somewhere
312f3f0262cSandi * currently used to replace the colon with something else
313f3f0262cSandi * on Windows systems and to have proper URL encoding
31415fae107Sandi *
31549c713a3Sandi * Urlencoding is ommitted when the second parameter is false
31649c713a3Sandi *
31715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
318f3f0262cSandi */
31949c713a3Sandifunction idfilter($id,$ue=true){
320f3f0262cSandi  global $conf;
321f3f0262cSandi  if ($conf['useslash'] && $conf['userewrite']){
322f3f0262cSandi    $id = strtr($id,':','/');
323f3f0262cSandi  }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
324f3f0262cSandi      $conf['userewrite']) {
325f3f0262cSandi    $id = strtr($id,':',';');
326f3f0262cSandi  }
32749c713a3Sandi  if($ue){
328b6c6979fSAndreas Gohr    $id = rawurlencode($id);
329f3f0262cSandi    $id = str_replace('%3A',':',$id); //keep as colon
330f3f0262cSandi    $id = str_replace('%2F','/',$id); //keep as slash
33149c713a3Sandi  }
332f3f0262cSandi  return $id;
333f3f0262cSandi}
334f3f0262cSandi
335f3f0262cSandi/**
336ed7b5f09Sandi * This builds a link to a wikipage
33715fae107Sandi *
3386c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3396c7843b5Sandi * given in $more
3406c7843b5Sandi *
34115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
342f3f0262cSandi */
343b174aeaeSchrisfunction wl($id='',$more='',$abs=false,$sep='&amp;'){
344f3f0262cSandi  global $conf;
3456de3759aSAndreas Gohr  if(is_array($more)){
346b174aeaeSchris    $more = buildURLparams($more,$sep);
3476de3759aSAndreas Gohr  }else{
348b174aeaeSchris    $more = str_replace(',',$sep,$more);
3496de3759aSAndreas Gohr  }
350f3f0262cSandi
351f3f0262cSandi  $id    = idfilter($id);
352ed7b5f09Sandi  if($abs){
353ed7b5f09Sandi    $xlink = DOKU_URL;
354ed7b5f09Sandi  }else{
355ed7b5f09Sandi    $xlink = DOKU_BASE;
356ed7b5f09Sandi  }
357f3f0262cSandi
3586c7843b5Sandi  if($conf['userewrite'] == 2){
3596c7843b5Sandi    $xlink .= DOKU_SCRIPT.'/'.$id;
3606c7843b5Sandi    if($more) $xlink .= '?'.$more;
3616c7843b5Sandi  }elseif($conf['userewrite']){
362f3f0262cSandi    $xlink .= $id;
363f3f0262cSandi    if($more) $xlink .= '?'.$more;
364bce3726dSAndreas Gohr  }elseif($id){
3656c7843b5Sandi    $xlink .= DOKU_SCRIPT.'?id='.$id;
366b174aeaeSchris    if($more) $xlink .= $sep.$more;
367bce3726dSAndreas Gohr  }else{
368bce3726dSAndreas Gohr    $xlink .= DOKU_SCRIPT;
369bce3726dSAndreas Gohr    if($more) $xlink .= '?'.$more;
370f3f0262cSandi  }
371f3f0262cSandi
372f3f0262cSandi  return $xlink;
373f3f0262cSandi}
374f3f0262cSandi
375f3f0262cSandi/**
376f5c2808fSBen Coburn * This builds a link to an alternate page format
377f5c2808fSBen Coburn *
378f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
379f5c2808fSBen Coburn *
380f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
381f5c2808fSBen Coburn */
382f5c2808fSBen Coburnfunction exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
383f5c2808fSBen Coburn  global $conf;
384f5c2808fSBen Coburn  if(is_array($more)){
385f5c2808fSBen Coburn    $more = buildURLparams($more,$sep);
386f5c2808fSBen Coburn  }else{
387f5c2808fSBen Coburn    $more = str_replace(',',$sep,$more);
388f5c2808fSBen Coburn  }
389f5c2808fSBen Coburn
390f5c2808fSBen Coburn  $format = rawurlencode($format);
391f5c2808fSBen Coburn  $id = idfilter($id);
392f5c2808fSBen Coburn  if($abs){
393f5c2808fSBen Coburn    $xlink = DOKU_URL;
394f5c2808fSBen Coburn  }else{
395f5c2808fSBen Coburn    $xlink = DOKU_BASE;
396f5c2808fSBen Coburn  }
397f5c2808fSBen Coburn
398f5c2808fSBen Coburn  if($conf['userewrite'] == 2){
399f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
400f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
401f5c2808fSBen Coburn  }elseif($conf['userewrite'] == 1){
402f5c2808fSBen Coburn    $xlink .= '_export/'.$format.'/'.$id;
403f5c2808fSBen Coburn    if($more) $xlink .= '?'.$more;
404f5c2808fSBen Coburn  }else{
405f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
406f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
407f5c2808fSBen Coburn  }
408f5c2808fSBen Coburn
409f5c2808fSBen Coburn  return $xlink;
410f5c2808fSBen Coburn}
411f5c2808fSBen Coburn
412f5c2808fSBen Coburn/**
4136de3759aSAndreas Gohr * Build a link to a media file
4146de3759aSAndreas Gohr *
4156de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
4168c08db0aSAndreas Gohr *
4178c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
4188c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
4198c08db0aSAndreas Gohr *
4208c08db0aSAndreas Gohr * @param string  $id     - the media file id or URL
4218c08db0aSAndreas Gohr * @param mixed   $more   - string or array with additional parameters
4228c08db0aSAndreas Gohr * @param boolean $direct - link to detail page if false
4238c08db0aSAndreas Gohr * @param string  $sep    - URL parameter separator
4248c08db0aSAndreas Gohr * @param boolean $abs    - Create an absolute URL
4256de3759aSAndreas Gohr */
42655b2b31bSAndreas Gohrfunction ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
4276de3759aSAndreas Gohr  global $conf;
4286de3759aSAndreas Gohr  if(is_array($more)){
4298c08db0aSAndreas Gohr    // strip defaults for shorter URLs
4308c08db0aSAndreas Gohr    if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
4318c08db0aSAndreas Gohr    if(!$more['w']) unset($more['w']);
4328c08db0aSAndreas Gohr    if(!$more['h']) unset($more['h']);
4338c08db0aSAndreas Gohr    if(isset($more['id']) && $direct) unset($more['id']);
434b174aeaeSchris    $more = buildURLparams($more,$sep);
4356de3759aSAndreas Gohr  }else{
4368c08db0aSAndreas Gohr    $more = str_replace('cache=cache','',$more); //skip default
4378c08db0aSAndreas Gohr    $more = str_replace(',,',',',$more);
438b174aeaeSchris    $more = str_replace(',',$sep,$more);
4396de3759aSAndreas Gohr  }
4406de3759aSAndreas Gohr
44155b2b31bSAndreas Gohr  if($abs){
44255b2b31bSAndreas Gohr    $xlink = DOKU_URL;
44355b2b31bSAndreas Gohr  }else{
4446de3759aSAndreas Gohr    $xlink = DOKU_BASE;
44555b2b31bSAndreas Gohr  }
4466de3759aSAndreas Gohr
4476de3759aSAndreas Gohr  // external URLs are always direct without rewriting
4486de3759aSAndreas Gohr  if(preg_match('#^(https?|ftp)://#i',$id)){
4496de3759aSAndreas Gohr    $xlink .= 'lib/exe/fetch.php';
4506de3759aSAndreas Gohr    if($more){
4516de3759aSAndreas Gohr      $xlink .= '?'.$more;
452b174aeaeSchris      $xlink .= $sep.'media='.rawurlencode($id);
4536de3759aSAndreas Gohr    }else{
454b6c6979fSAndreas Gohr      $xlink .= '?media='.rawurlencode($id);
4556de3759aSAndreas Gohr    }
4566de3759aSAndreas Gohr    return $xlink;
4576de3759aSAndreas Gohr  }
4586de3759aSAndreas Gohr
4596de3759aSAndreas Gohr  $id = idfilter($id);
4606de3759aSAndreas Gohr
4616de3759aSAndreas Gohr  // decide on scriptname
4626de3759aSAndreas Gohr  if($direct){
4636de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4646de3759aSAndreas Gohr      $script = '_media';
4656de3759aSAndreas Gohr    }else{
4666de3759aSAndreas Gohr      $script = 'lib/exe/fetch.php';
4676de3759aSAndreas Gohr    }
4686de3759aSAndreas Gohr  }else{
4696de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4706de3759aSAndreas Gohr      $script = '_detail';
4716de3759aSAndreas Gohr    }else{
4726de3759aSAndreas Gohr      $script = 'lib/exe/detail.php';
4736de3759aSAndreas Gohr    }
4746de3759aSAndreas Gohr  }
4756de3759aSAndreas Gohr
4766de3759aSAndreas Gohr  // build URL based on rewrite mode
4776de3759aSAndreas Gohr   if($conf['userewrite']){
4786de3759aSAndreas Gohr     $xlink .= $script.'/'.$id;
4796de3759aSAndreas Gohr     if($more) $xlink .= '?'.$more;
4806de3759aSAndreas Gohr   }else{
4816de3759aSAndreas Gohr     if($more){
482a99d3236SEsther Brunner       $xlink .= $script.'?'.$more;
483b174aeaeSchris       $xlink .= $sep.'media='.$id;
4846de3759aSAndreas Gohr     }else{
485a99d3236SEsther Brunner       $xlink .= $script.'?media='.$id;
4866de3759aSAndreas Gohr     }
4876de3759aSAndreas Gohr   }
4886de3759aSAndreas Gohr
4896de3759aSAndreas Gohr  return $xlink;
4906de3759aSAndreas Gohr}
4916de3759aSAndreas Gohr
4926de3759aSAndreas Gohr
4936de3759aSAndreas Gohr
4946de3759aSAndreas Gohr/**
495f3f0262cSandi * Just builds a link to a script
49615fae107Sandi *
497ed7b5f09Sandi * @todo   maybe obsolete
49815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
499f3f0262cSandi */
500f3f0262cSandifunction script($script='doku.php'){
501ed7b5f09Sandi#  $link = getBaseURL();
502ed7b5f09Sandi#  $link .= $script;
503ed7b5f09Sandi#  return $link;
504ed7b5f09Sandi  return DOKU_BASE.DOKU_SCRIPT;
505f3f0262cSandi}
506f3f0262cSandi
507f3f0262cSandi/**
50815fae107Sandi * Spamcheck against wordlist
50915fae107Sandi *
510f3f0262cSandi * Checks the wikitext against a list of blocked expressions
511f3f0262cSandi * returns true if the text contains any bad words
51215fae107Sandi *
513e403cc58SMichael Klier * Triggers COMMON_WORDBLOCK_BLOCKED
514e403cc58SMichael Klier *
515e403cc58SMichael Klier *  Action Plugins can use this event to inspect the blocked data
516e403cc58SMichael Klier *  and gain information about the user who was blocked.
517e403cc58SMichael Klier *
518e403cc58SMichael Klier *  Event data:
519e403cc58SMichael Klier *    data['matches']  - array of matches
520e403cc58SMichael Klier *    data['userinfo'] - information about the blocked user
521e403cc58SMichael Klier *      [ip]           - ip address
522e403cc58SMichael Klier *      [user]         - username (if logged in)
523e403cc58SMichael Klier *      [mail]         - mail address (if logged in)
524e403cc58SMichael Klier *      [name]         - real name (if logged in)
525e403cc58SMichael Klier *
52615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
527e403cc58SMichael Klier * Michael Klier <chi@chimeric.de>
528f3f0262cSandi */
529f3f0262cSandifunction checkwordblock(){
530f3f0262cSandi  global $TEXT;
531f3f0262cSandi  global $conf;
532e403cc58SMichael Klier  global $INFO;
533f3f0262cSandi
534f3f0262cSandi  if(!$conf['usewordblock']) return false;
535f3f0262cSandi
536041d1964SAndreas Gohr  // we prepare the text a tiny bit to prevent spammers circumventing URL checks
537041d1964SAndreas Gohr  $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$TEXT);
538041d1964SAndreas Gohr
539b9ac8716Schris  $wordblocks = getWordblocks();
5403e2965d7Sandi  //how many lines to read at once (to work around some PCRE limits)
5413e2965d7Sandi  if(version_compare(phpversion(),'4.3.0','<')){
5423e2965d7Sandi    //old versions of PCRE define a maximum of parenthesises even if no
5433e2965d7Sandi    //backreferences are used - the maximum is 99
5443e2965d7Sandi    //this is very bad performancewise and may even be too high still
5453e2965d7Sandi    $chunksize = 40;
5463e2965d7Sandi  }else{
547a51d08efSAndreas Gohr    //read file in chunks of 200 - this should work around the
5483e2965d7Sandi    //MAX_PATTERN_SIZE in modern PCRE
549a51d08efSAndreas Gohr    $chunksize = 200;
5503e2965d7Sandi  }
551b9ac8716Schris  while($blocks = array_splice($wordblocks,0,$chunksize)){
552f3f0262cSandi    $re = array();
553f3f0262cSandi    #build regexp from blocks
554f3f0262cSandi    foreach($blocks as $block){
555f3f0262cSandi      $block = preg_replace('/#.*$/','',$block);
556f3f0262cSandi      $block = trim($block);
557f3f0262cSandi      if(empty($block)) continue;
558f3f0262cSandi      $re[]  = $block;
559f3f0262cSandi    }
560e403cc58SMichael Klier    if(count($re) && preg_match('#('.join('|',$re).')#si',$text,$matches)) {
561e403cc58SMichael Klier      //prepare event data
562e403cc58SMichael Klier      $data['matches'] = $matches;
563e403cc58SMichael Klier      $data['userinfo']['ip'] = $_SERVER['REMOTE_ADDR'];
564e403cc58SMichael Klier      if($_SERVER['REMOTE_USER']) {
565e403cc58SMichael Klier          $data['userinfo']['user'] = $_SERVER['REMOTE_USER'];
566e403cc58SMichael Klier          $data['userinfo']['name'] = $INFO['userinfo']['name'];
567e403cc58SMichael Klier          $data['userinfo']['mail'] = $INFO['userinfo']['mail'];
568e403cc58SMichael Klier      }
569e403cc58SMichael Klier      $callback = create_function('', 'return true;');
570e403cc58SMichael Klier      return trigger_event('COMMON_WORDBLOCK_BLOCKED', $data, $callback, true);
571b9ac8716Schris    }
572703f6fdeSandi  }
573f3f0262cSandi  return false;
574f3f0262cSandi}
575f3f0262cSandi
576f3f0262cSandi/**
57715fae107Sandi * Return the IP of the client
57815fae107Sandi *
5796d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
58015fae107Sandi *
5816d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5826d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
5836d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
5846d8affe6SAndreas Gohr * headers
5856d8affe6SAndreas Gohr *
5866d8affe6SAndreas Gohr * @param  boolean $single If set only a single IP is returned
58715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
588f3f0262cSandi */
5896d8affe6SAndreas Gohrfunction clientIP($single=false){
5906d8affe6SAndreas Gohr  $ip = array();
5916d8affe6SAndreas Gohr  $ip[] = $_SERVER['REMOTE_ADDR'];
592bb4866bdSchris  if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
5936d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
594bb4866bdSchris  if(!empty($_SERVER['HTTP_X_REAL_IP']))
5956d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
5966d8affe6SAndreas Gohr
597*dc14c6d1SGuy Brand  // some IPv4/v6 regexps borrowed from Feyd
598*dc14c6d1SGuy Brand  // see: http://forums.devnetwork.net/viewtopic.php?f=38&t=53479
599*dc14c6d1SGuy Brand  $dec_octet = '(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|[0-9])';
600*dc14c6d1SGuy Brand  $hex_digit = '[A-Fa-f0-9]';
601*dc14c6d1SGuy Brand  $h16 = "{$hex_digit}{1,4}";
602*dc14c6d1SGuy Brand  $IPv4Address = "$dec_octet\\.$dec_octet\\.$dec_octet\\.$dec_octet";
603*dc14c6d1SGuy Brand  $ls32 = "(?:$h16:$h16|$IPv4Address)";
604*dc14c6d1SGuy Brand  $IPv6Address =
605*dc14c6d1SGuy Brand    "(?:(?:{$IPv4Address})|(?:".
606*dc14c6d1SGuy Brand    "(?:$h16:){6}$ls32" .
607*dc14c6d1SGuy Brand    "|::(?:$h16:){5}$ls32" .
608*dc14c6d1SGuy Brand    "|(?:$h16)?::(?:$h16:){4}$ls32" .
609*dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,1}$h16)?::(?:$h16:){3}$ls32" .
610*dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,2}$h16)?::(?:$h16:){2}$ls32" .
611*dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,3}$h16)?::(?:$h16:){1}$ls32" .
612*dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,4}$h16)?::$ls32" .
613*dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,5}$h16)?::$h16" .
614*dc14c6d1SGuy Brand    "|(?:(?:$h16:){0,6}$h16)?::" .
615*dc14c6d1SGuy Brand    ")(?:\\/(?:12[0-8]|1[0-1][0-9]|[1-9][0-9]|[0-9]))?)";
616*dc14c6d1SGuy Brand
6176d8affe6SAndreas Gohr  // remove any non-IP stuff
6186d8affe6SAndreas Gohr  $cnt = count($ip);
6194ff28443Schris  $match = array();
6206d8affe6SAndreas Gohr  for($i=0; $i<$cnt; $i++){
621*dc14c6d1SGuy Brand    if(preg_match("/^$IPv4Address$/",$ip[$i],$match) || preg_match("/^$IPv6Address$/",$ip[$i],$match)) {
6224ff28443Schris      $ip[$i] = $match[0];
6234ff28443Schris    } else {
6244ff28443Schris      $ip[$i] = '';
6254ff28443Schris    }
6266d8affe6SAndreas Gohr    if(empty($ip[$i])) unset($ip[$i]);
627f3f0262cSandi  }
6286d8affe6SAndreas Gohr  $ip = array_values(array_unique($ip));
6296d8affe6SAndreas Gohr  if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
6306d8affe6SAndreas Gohr
6316d8affe6SAndreas Gohr  if(!$single) return join(',',$ip);
6326d8affe6SAndreas Gohr
6336d8affe6SAndreas Gohr  // decide which IP to use, trying to avoid local addresses
6346d8affe6SAndreas Gohr  $ip = array_reverse($ip);
6356d8affe6SAndreas Gohr  foreach($ip as $i){
6366d8affe6SAndreas Gohr    if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
6376d8affe6SAndreas Gohr      continue;
6386d8affe6SAndreas Gohr    }else{
6396d8affe6SAndreas Gohr      return $i;
6406d8affe6SAndreas Gohr    }
6416d8affe6SAndreas Gohr  }
6426d8affe6SAndreas Gohr  // still here? just use the first (last) address
6436d8affe6SAndreas Gohr  return $ip[0];
644f3f0262cSandi}
645f3f0262cSandi
646f3f0262cSandi/**
6471c548ebeSAndreas Gohr * Check if the browser is on a mobile device
6481c548ebeSAndreas Gohr *
6491c548ebeSAndreas Gohr * Adapted from the example code at url below
6501c548ebeSAndreas Gohr *
6511c548ebeSAndreas Gohr * @link http://www.brainhandles.com/2007/10/15/detecting-mobile-browsers/#code
6521c548ebeSAndreas Gohr */
6531c548ebeSAndreas Gohrfunction clientismobile(){
6541c548ebeSAndreas Gohr
6551c548ebeSAndreas Gohr    if(isset($_SERVER['HTTP_X_WAP_PROFILE'])) return true;
6561c548ebeSAndreas Gohr
6571c548ebeSAndreas Gohr    if(preg_match('/wap\.|\.wap/i',$_SERVER['HTTP_ACCEPT'])) return true;
6581c548ebeSAndreas Gohr
6591c548ebeSAndreas Gohr    if(!isset($_SERVER['HTTP_USER_AGENT'])) return false;
6601c548ebeSAndreas Gohr
6611c548ebeSAndreas 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';
6621c548ebeSAndreas Gohr
6631c548ebeSAndreas Gohr    if(preg_match("/$uamatches/i",$_SERVER['HTTP_USER_AGENT'])) return true;
6641c548ebeSAndreas Gohr
6651c548ebeSAndreas Gohr    return false;
6661c548ebeSAndreas Gohr}
6671c548ebeSAndreas Gohr
6681c548ebeSAndreas Gohr
6691c548ebeSAndreas Gohr/**
67063211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
67163211f61SGlen Harris *
67263211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
67363211f61SGlen Harris * @returns a comma separated list of hostnames
67463211f61SGlen Harris */
67563211f61SGlen Harrisfunction gethostsbyaddrs($ips){
67663211f61SGlen Harris  $hosts = array();
67763211f61SGlen Harris  $ips = explode(',',$ips);
678551a720fSMichael Klier
679551a720fSMichael Klier  if(is_array($ips)) {
6803886270dSAndreas Gohr    foreach($ips as $ip){
681551a720fSMichael Klier      $hosts[] = gethostbyaddr(trim($ip));
68263211f61SGlen Harris    }
683551a720fSMichael Klier    return join(',',$hosts);
684551a720fSMichael Klier  } else {
685551a720fSMichael Klier    return gethostbyaddr(trim($ips));
686551a720fSMichael Klier  }
68763211f61SGlen Harris}
68863211f61SGlen Harris
68963211f61SGlen Harris/**
69015fae107Sandi * Checks if a given page is currently locked.
69115fae107Sandi *
692f3f0262cSandi * removes stale lockfiles
69315fae107Sandi *
69415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
695f3f0262cSandi */
696f3f0262cSandifunction checklock($id){
697f3f0262cSandi  global $conf;
698c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
699f3f0262cSandi
700f3f0262cSandi  //no lockfile
701f3f0262cSandi  if(!@file_exists($lock)) return false;
702f3f0262cSandi
703f3f0262cSandi  //lockfile expired
704f3f0262cSandi  if((time() - filemtime($lock)) > $conf['locktime']){
705d8186216SBen Coburn    @unlink($lock);
706f3f0262cSandi    return false;
707f3f0262cSandi  }
708f3f0262cSandi
709f3f0262cSandi  //my own lock
710f3f0262cSandi  $ip = io_readFile($lock);
711f3f0262cSandi  if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
712f3f0262cSandi    return false;
713f3f0262cSandi  }
714f3f0262cSandi
715f3f0262cSandi  return $ip;
716f3f0262cSandi}
717f3f0262cSandi
718f3f0262cSandi/**
71915fae107Sandi * Lock a page for editing
72015fae107Sandi *
72115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
722f3f0262cSandi */
723f3f0262cSandifunction lock($id){
724c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
725f3f0262cSandi  if($_SERVER['REMOTE_USER']){
726f3f0262cSandi    io_saveFile($lock,$_SERVER['REMOTE_USER']);
727f3f0262cSandi  }else{
728f3f0262cSandi    io_saveFile($lock,clientIP());
729f3f0262cSandi  }
730f3f0262cSandi}
731f3f0262cSandi
732f3f0262cSandi/**
73315fae107Sandi * Unlock a page if it was locked by the user
734f3f0262cSandi *
73515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
73615fae107Sandi * @return bool true if a lock was removed
737f3f0262cSandi */
738f3f0262cSandifunction unlock($id){
739c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
740f3f0262cSandi  if(@file_exists($lock)){
741f3f0262cSandi    $ip = io_readFile($lock);
742f3f0262cSandi    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
743f3f0262cSandi      @unlink($lock);
744f3f0262cSandi      return true;
745f3f0262cSandi    }
746f3f0262cSandi  }
747f3f0262cSandi  return false;
748f3f0262cSandi}
749f3f0262cSandi
750f3f0262cSandi/**
751f3f0262cSandi * convert line ending to unix format
752f3f0262cSandi *
75315fae107Sandi * @see    formText() for 2crlf conversion
75415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
755f3f0262cSandi */
756f3f0262cSandifunction cleanText($text){
757f3f0262cSandi  $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
758f3f0262cSandi  return $text;
759f3f0262cSandi}
760f3f0262cSandi
761f3f0262cSandi/**
762f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
763f3f0262cSandi * It also converts line endings to Windows format which is
764f3f0262cSandi * pseudo standard for webforms.
765f3f0262cSandi *
76615fae107Sandi * @see    cleanText() for 2unix conversion
76715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
768f3f0262cSandi */
769f3f0262cSandifunction formText($text){
7705b7d45a5SAndreas Gohr  $text = str_replace("\012","\015\012",$text);
771f3f0262cSandi  return htmlspecialchars($text);
772f3f0262cSandi}
773f3f0262cSandi
774f3f0262cSandi/**
77515fae107Sandi * Returns the specified local text in raw format
77615fae107Sandi *
77715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
778f3f0262cSandi */
779f3f0262cSandifunction rawLocale($id){
780f3f0262cSandi  return io_readFile(localeFN($id));
781f3f0262cSandi}
782f3f0262cSandi
783f3f0262cSandi/**
784f3f0262cSandi * Returns the raw WikiText
78515fae107Sandi *
78615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
787f3f0262cSandi */
788f3f0262cSandifunction rawWiki($id,$rev=''){
789cc7d0c94SBen Coburn  return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
790f3f0262cSandi}
791f3f0262cSandi
792f3f0262cSandi/**
7937146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
7947146cee2SAndreas Gohr *
7957146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7967146cee2SAndreas Gohr */
797b7d5a5f0SAndreas Gohrfunction pageTemplate($data){
798b7d5a5f0SAndreas Gohr  $id = $data[0];
799a15ce62dSEsther Brunner  global $conf;
800a15ce62dSEsther Brunner  global $INFO;
801e29549feSAndreas Gohr
802e29549feSAndreas Gohr  $path = dirname(wikiFN($id));
803e29549feSAndreas Gohr
804e29549feSAndreas Gohr  if(@file_exists($path.'/_template.txt')){
805e29549feSAndreas Gohr    $tpl = io_readFile($path.'/_template.txt');
806e29549feSAndreas Gohr  }else{
807e29549feSAndreas Gohr    // search upper namespaces for templates
808e29549feSAndreas Gohr    $len = strlen(rtrim($conf['datadir'],'/'));
809e29549feSAndreas Gohr    while (strlen($path) >= $len){
810e29549feSAndreas Gohr      if(@file_exists($path.'/__template.txt')){
811e29549feSAndreas Gohr        $tpl = io_readFile($path.'/__template.txt');
812e29549feSAndreas Gohr        break;
813e29549feSAndreas Gohr      }
814e29549feSAndreas Gohr      $path = substr($path, 0, strrpos($path, '/'));
815e29549feSAndreas Gohr    }
816e29549feSAndreas Gohr  }
817e29549feSAndreas Gohr  if(!$tpl) return '';
818e29549feSAndreas Gohr
819e29549feSAndreas Gohr  // replace placeholders
820a15ce62dSEsther Brunner  $tpl = str_replace('@ID@',$id,$tpl);
821a15ce62dSEsther Brunner  $tpl = str_replace('@NS@',getNS($id),$tpl);
822a15ce62dSEsther Brunner  $tpl = str_replace('@PAGE@',strtr(noNS($id),'_',' '),$tpl);
823a15ce62dSEsther Brunner  $tpl = str_replace('@USER@',$_SERVER['REMOTE_USER'],$tpl);
824a15ce62dSEsther Brunner  $tpl = str_replace('@NAME@',$INFO['userinfo']['name'],$tpl);
825a15ce62dSEsther Brunner  $tpl = str_replace('@MAIL@',$INFO['userinfo']['mail'],$tpl);
826e656dcd4SAndreas Gohr  $tpl = str_replace('@DATE@',$conf['dformat'],$tpl);
8277d644fc8SAndreas Gohr  // we need the callback to work around strftime's char limit
8287d644fc8SAndreas Gohr  $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
8297d644fc8SAndreas Gohr
830a15ce62dSEsther Brunner  return $tpl;
8317146cee2SAndreas Gohr}
8327146cee2SAndreas Gohr
8337146cee2SAndreas Gohr
8347146cee2SAndreas Gohr/**
83515fae107Sandi * Returns the raw Wiki Text in three slices.
83615fae107Sandi *
83715fae107Sandi * The range parameter needs to have the form "from-to"
83815cfe303Sandi * and gives the range of the section in bytes - no
83915cfe303Sandi * UTF-8 awareness is needed.
840f3f0262cSandi * The returned order is prefix, section and suffix.
84115fae107Sandi *
84215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
843f3f0262cSandi */
844f3f0262cSandifunction rawWikiSlices($range,$id,$rev=''){
845f3f0262cSandi  list($from,$to) = split('-',$range,2);
846cc7d0c94SBen Coburn  $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
847f3f0262cSandi  if(!$from) $from = 0;
848c3d8e19bSandi  if(!$to)   $to   = strlen($text)+1;
849f3f0262cSandi
85015cfe303Sandi  $slices[0] = substr($text,0,$from-1);
85115cfe303Sandi  $slices[1] = substr($text,$from-1,$to-$from);
85215cfe303Sandi  $slices[2] = substr($text,$to);
853f3f0262cSandi
854f3f0262cSandi  return $slices;
855f3f0262cSandi}
856f3f0262cSandi
857f3f0262cSandi/**
85815fae107Sandi * Joins wiki text slices
85915fae107Sandi *
860f3f0262cSandi * function to join the text slices with correct lineendings again.
861f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
862f3f0262cSandi * lines between sections if needed (used on saving).
86315fae107Sandi *
86415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
865f3f0262cSandi */
866f3f0262cSandifunction con($pre,$text,$suf,$pretty=false){
867f3f0262cSandi
868f3f0262cSandi  if($pretty){
869f3f0262cSandi    if($pre && substr($pre,-1) != "\n") $pre .= "\n";
870f3f0262cSandi    if($suf && substr($text,-1) != "\n") $text .= "\n";
871f3f0262cSandi  }
872f3f0262cSandi
8737e038d4eSAndreas Gohr  // Avoid double newline above section when saving section edit
8747e038d4eSAndreas Gohr  //if($pre) $pre .= "\n";
875f3f0262cSandi  if($suf) $text .= "\n";
876f3f0262cSandi  return $pre.$text.$suf;
877f3f0262cSandi}
878f3f0262cSandi
879f3f0262cSandi/**
880a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
881a701424fSBen Coburn * Also directs changelog and attic updates.
88215fae107Sandi *
88315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
88471726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
885f3f0262cSandi */
886b6912aeaSAndreas Gohrfunction saveWikiText($id,$text,$summary,$minor=false){
887a701424fSBen Coburn  /* Note to developers:
888a701424fSBen Coburn     This code is subtle and delicate. Test the behavior of
889a701424fSBen Coburn     the attic and changelog with dokuwiki and external edits
890a701424fSBen Coburn     after any changes. External edits change the wiki page
891a701424fSBen Coburn     directly without using php or dokuwiki.
892a701424fSBen Coburn  */
893f3f0262cSandi  global $conf;
894f3f0262cSandi  global $lang;
89571726d78SBen Coburn  global $REV;
896f3f0262cSandi  // ignore if no changes were made
897f3f0262cSandi  if($text == rawWiki($id,'')){
898f3f0262cSandi    return;
899f3f0262cSandi  }
900f3f0262cSandi
901f3f0262cSandi  $file = wikiFN($id);
902a701424fSBen Coburn  $old = @filemtime($file); // from page
90371726d78SBen Coburn  $wasRemoved = empty($text);
904d8186216SBen Coburn  $wasCreated = !@file_exists($file);
90571726d78SBen Coburn  $wasReverted = ($REV==true);
906e45b34cdSBen Coburn  $newRev = false;
907a701424fSBen Coburn  $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
908a701424fSBen Coburn  $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
909a701424fSBen Coburn  if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
91046844156SBen Coburn    // add old revision to the attic if missing
91146844156SBen Coburn    saveOldRevision($id);
91246844156SBen Coburn    // add a changelog entry if this edit came from outside dokuwiki
913a701424fSBen Coburn    if ($old>$oldRev) {
914ebf1501fSBen Coburn      addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
91546844156SBen Coburn      // remove soon to be stale instructions
91646844156SBen Coburn      $cache = new cache_instructions($id, $file);
91746844156SBen Coburn      $cache->removeCache();
91846844156SBen Coburn    }
91946844156SBen Coburn  }
920f3f0262cSandi
92171726d78SBen Coburn  if ($wasRemoved){
92230725328SGabriel Birke    // Send "update" event with empty data, so plugins can react to page deletion
92330725328SGabriel Birke    $data = array(array($file, '', false), getNS($id), noNS($id), false);
92430725328SGabriel Birke    trigger_event('IO_WIKIPAGE_WRITE', $data);
925e45b34cdSBen Coburn    // pre-save deleted revision
926e45b34cdSBen Coburn    @touch($file);
92746844156SBen Coburn    clearstatcache();
928e45b34cdSBen Coburn    $newRev = saveOldRevision($id);
929e1f3d9e1SEsther Brunner    // remove empty file
930f3f0262cSandi    @unlink($file);
93171726d78SBen Coburn    // remove old meta info...
932e1f3d9e1SEsther Brunner    $mfiles = metaFiles($id);
93371726d78SBen Coburn    $changelog = metaFN($id, '.changes');
9343d1f9ec3SMichael Klier    $metadata  = metaFN($id, '.meta');
935e1f3d9e1SEsther Brunner    foreach ($mfiles as $mfile) {
9363d1f9ec3SMichael Klier      // but keep per-page changelog to preserve page history and keep meta data
9373d1f9ec3SMichael Klier      if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); }
938b158d625SSteven Danz    }
9393d1f9ec3SMichael Klier    // purge meta data
9403d1f9ec3SMichael Klier    p_purge_metadata($id);
941f3f0262cSandi    $del = true;
9423ce054b3Sandi    // autoset summary on deletion
9433ce054b3Sandi    if(empty($summary)) $summary = $lang['deleted'];
94453d6ccfeSandi    // remove empty namespaces
945cc7d0c94SBen Coburn    io_sweepNS($id, 'datadir');
946cc7d0c94SBen Coburn    io_sweepNS($id, 'mediadir');
947f3f0262cSandi  }else{
948cc7d0c94SBen Coburn    // save file (namespace dir is created in io_writeWikiPage)
949cc7d0c94SBen Coburn    io_writeWikiPage($file, $text, $id);
95046844156SBen Coburn    // pre-save the revision, to keep the attic in sync
95146844156SBen Coburn    $newRev = saveOldRevision($id);
952f3f0262cSandi    $del = false;
953f3f0262cSandi  }
954f3f0262cSandi
95571726d78SBen Coburn  // select changelog line type
95671726d78SBen Coburn  $extra = '';
957ebf1501fSBen Coburn  $type = DOKU_CHANGE_TYPE_EDIT;
95871726d78SBen Coburn  if ($wasReverted) {
959ebf1501fSBen Coburn    $type = DOKU_CHANGE_TYPE_REVERT;
96071726d78SBen Coburn    $extra = $REV;
96171726d78SBen Coburn  }
962ebf1501fSBen Coburn  else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
963ebf1501fSBen Coburn  else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
964ebf1501fSBen Coburn  else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
96571726d78SBen Coburn
966e45b34cdSBen Coburn  addLogEntry($newRev, $id, $type, $summary, $extra);
96726a0801fSAndreas Gohr  // send notify mails
96890033e9dSAndreas Gohr  notify($id,'admin',$old,$summary,$minor);
96990033e9dSAndreas Gohr  notify($id,'subscribers',$old,$summary,$minor);
970f3f0262cSandi
971ce6b63d9Schris  // update the purgefile (timestamp of the last time anything within the wiki was changed)
97298407a7aSandi  io_saveFile($conf['cachedir'].'/purgefile',time());
9732eccbdaaSGina Haeussge
9742eccbdaaSGina Haeussge  // if useheading is enabled, purge the cache of all linking pages
9752eccbdaaSGina Haeussge  if($conf['useheading']){
9762eccbdaaSGina Haeussge    require_once(DOKU_INC.'inc/fulltext.php');
9772eccbdaaSGina Haeussge    $pages = ft_backlinks($id);
9782eccbdaaSGina Haeussge    foreach ($pages as $page) {
9792eccbdaaSGina Haeussge      $cache = new cache_renderer($page, wikiFN($page), 'xhtml');
9802eccbdaaSGina Haeussge      $cache->removeCache();
9812eccbdaaSGina Haeussge    }
9822eccbdaaSGina Haeussge  }
983f3f0262cSandi}
984f3f0262cSandi
985f3f0262cSandi/**
986f3f0262cSandi * moves the current version to the attic and returns its
987f3f0262cSandi * revision date
98815fae107Sandi *
98915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
990f3f0262cSandi */
991f3f0262cSandifunction saveOldRevision($id){
992f3f0262cSandi  global $conf;
993f3f0262cSandi  $oldf = wikiFN($id);
994f3f0262cSandi  if(!@file_exists($oldf)) return '';
995f3f0262cSandi  $date = filemtime($oldf);
996f3f0262cSandi  $newf = wikiFN($id,$date);
997cc7d0c94SBen Coburn  io_writeWikiPage($newf, rawWiki($id), $id, $date);
998f3f0262cSandi  return $date;
999f3f0262cSandi}
1000f3f0262cSandi
1001f3f0262cSandi/**
100226a0801fSAndreas Gohr * Sends a notify mail on page change
100326a0801fSAndreas Gohr *
100426a0801fSAndreas Gohr * @param  string  $id       The changed page
100526a0801fSAndreas Gohr * @param  string  $who      Who to notify (admin|subscribers)
100626a0801fSAndreas Gohr * @param  int     $rev      Old page revision
100726a0801fSAndreas Gohr * @param  string  $summary  What changed
100890033e9dSAndreas Gohr * @param  boolean $minor    Is this a minor edit?
100902a498e7Schris * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
101015fae107Sandi *
101115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
1012f3f0262cSandi */
101302a498e7Schrisfunction notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
1014f3f0262cSandi  global $lang;
1015f3f0262cSandi  global $conf;
101630d7d718SMike Frysinger  global $INFO;
1017b158d625SSteven Danz
101826a0801fSAndreas Gohr  // decide if there is something to do
101926a0801fSAndreas Gohr  if($who == 'admin'){
102026a0801fSAndreas Gohr    if(empty($conf['notify'])) return; //notify enabled?
1021f3f0262cSandi    $text = rawLocale('mailtext');
102226a0801fSAndreas Gohr    $to   = $conf['notify'];
102326a0801fSAndreas Gohr    $bcc  = '';
102426a0801fSAndreas Gohr  }elseif($who == 'subscribers'){
102526a0801fSAndreas Gohr    if(!$conf['subscribers']) return; //subscribers enabled?
102690033e9dSAndreas Gohr    if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
102726a0801fSAndreas Gohr    $bcc  = subscriber_addresslist($id);
102826a0801fSAndreas Gohr    if(empty($bcc)) return;
102926a0801fSAndreas Gohr    $to   = '';
103026a0801fSAndreas Gohr    $text = rawLocale('subscribermail');
1031a06e4bdbSSebastian Harl  }elseif($who == 'register'){
1032a06e4bdbSSebastian Harl    if(empty($conf['registernotify'])) return;
1033a06e4bdbSSebastian Harl    $text = rawLocale('registermail');
1034a06e4bdbSSebastian Harl    $to   = $conf['registernotify'];
1035a06e4bdbSSebastian Harl    $bcc  = '';
103626a0801fSAndreas Gohr  }else{
103726a0801fSAndreas Gohr    return; //just to be safe
103826a0801fSAndreas Gohr  }
103926a0801fSAndreas Gohr
104063211f61SGlen Harris  $ip   = clientIP();
1041e656dcd4SAndreas Gohr  $text = str_replace('@DATE@',strftime($conf['dformat']),$text);
1042f3f0262cSandi  $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
104363211f61SGlen Harris  $text = str_replace('@IPADDRESS@',$ip,$text);
104463211f61SGlen Harris  $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
1045c9321d91SAndreas Gohr  $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
104626a0801fSAndreas Gohr  $text = str_replace('@PAGE@',$id,$text);
104726a0801fSAndreas Gohr  $text = str_replace('@TITLE@',$conf['title'],$text);
1048ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
1049f3f0262cSandi  $text = str_replace('@SUMMARY@',$summary,$text);
10507a82afdcSandi  $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
1051f3f0262cSandi
105202a498e7Schris  foreach ($replace as $key => $substitution) {
105302a498e7Schris    $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
105402a498e7Schris  }
105502a498e7Schris
1056a06e4bdbSSebastian Harl  if($who == 'register'){
1057a06e4bdbSSebastian Harl    $subject = $lang['mail_new_user'].' '.$summary;
1058a06e4bdbSSebastian Harl  }elseif($rev){
1059f3f0262cSandi    $subject = $lang['mail_changed'].' '.$id;
1060c9321d91SAndreas Gohr    $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
1061ccdfa6c0SAndreas Gohr    require_once(DOKU_INC.'inc/DifferenceEngine.php');
1062f3f0262cSandi    $df  = new Diff(split("\n",rawWiki($id,$rev)),
1063f3f0262cSandi                    split("\n",rawWiki($id)));
1064f3f0262cSandi    $dformat = new UnifiedDiffFormatter();
1065f3f0262cSandi    $diff    = $dformat->format($df);
1066f3f0262cSandi  }else{
1067f3f0262cSandi    $subject=$lang['mail_newpage'].' '.$id;
1068f3f0262cSandi    $text = str_replace('@OLDPAGE@','none',$text);
1069f3f0262cSandi    $diff = rawWiki($id);
1070f3f0262cSandi  }
1071f3f0262cSandi  $text = str_replace('@DIFF@',$diff,$text);
1072241f3a36Sandi  $subject = '['.$conf['title'].'] '.$subject;
1073f3f0262cSandi
107430d7d718SMike Frysinger  $from = $conf['mailfrom'];
107530d7d718SMike Frysinger  $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
107630d7d718SMike Frysinger  $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
107730d7d718SMike Frysinger  $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
107830d7d718SMike Frysinger
107930d7d718SMike Frysinger  mail_send($to,$subject,$text,$from,'',$bcc);
1080f3f0262cSandi}
1081f3f0262cSandi
108215fae107Sandi/**
108371f7bde7SAndreas Gohr * extracts the query from a search engine referrer
108415fae107Sandi *
108515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
108671f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1087f3f0262cSandi */
1088f3f0262cSandifunction getGoogleQuery(){
1089f3f0262cSandi  $url = parse_url($_SERVER['HTTP_REFERER']);
10905c3f206fSandi  if(!$url) return '';
1091f3f0262cSandi
1092f3f0262cSandi  $query = array();
1093f3f0262cSandi  parse_str($url['query'],$query);
109471f7bde7SAndreas Gohr  if(isset($query['q']))
1095f93b3b50SAndreas Gohr    $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
109671f7bde7SAndreas Gohr  elseif(isset($query['p']))
1097f93b3b50SAndreas Gohr    $q = $query['p'];        // yahoo
109871f7bde7SAndreas Gohr  elseif(isset($query['query']))
1099f93b3b50SAndreas Gohr    $q = $query['query'];    // lycos, netscape, clusty, hotbot
110071f7bde7SAndreas Gohr  elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1101f93b3b50SAndreas Gohr    $q = urldecode(ltrim($url['path'],'/'));
1102f3f0262cSandi
1103f93b3b50SAndreas Gohr  if(!$q) return '';
11046531ab03SAndreas Gohr  $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1105f93b3b50SAndreas Gohr  return $q;
1106f3f0262cSandi}
1107f3f0262cSandi
1108f3f0262cSandi/**
110915fae107Sandi * Try to set correct locale
111015fae107Sandi *
1111095bfd5cSandi * @deprecated No longer used
111215fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1113f3f0262cSandi */
1114f3f0262cSandifunction setCorrectLocale(){
1115f3f0262cSandi  global $conf;
1116f3f0262cSandi  global $lang;
1117f3f0262cSandi
1118f3f0262cSandi  $enc = strtoupper($lang['encoding']);
1119f3f0262cSandi  foreach ($lang['locales'] as $loc){
1120f3f0262cSandi    //try locale
1121f3f0262cSandi    if(@setlocale(LC_ALL,$loc)) return;
1122f3f0262cSandi    //try loceale with encoding
1123f3f0262cSandi    if(@setlocale(LC_ALL,"$loc.$enc")) return;
1124f3f0262cSandi  }
1125f3f0262cSandi  //still here? try to set from environment
1126f3f0262cSandi  @setlocale(LC_ALL,"");
1127f3f0262cSandi}
1128f3f0262cSandi
1129f3f0262cSandi/**
1130f3f0262cSandi * Return the human readable size of a file
1131f3f0262cSandi *
1132f3f0262cSandi * @param       int    $size   A file size
1133f3f0262cSandi * @param       int    $dec    A number of decimal places
1134f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1135f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1136f3f0262cSandi * @version     1.0.0
1137f3f0262cSandi */
1138f31d5b73Sandifunction filesize_h($size, $dec = 1){
1139f3f0262cSandi  $sizes = array('B', 'KB', 'MB', 'GB');
1140f3f0262cSandi  $count = count($sizes);
1141f3f0262cSandi  $i = 0;
1142f3f0262cSandi
1143f3f0262cSandi  while ($size >= 1024 && ($i < $count - 1)) {
1144f3f0262cSandi    $size /= 1024;
1145f3f0262cSandi    $i++;
1146f3f0262cSandi  }
1147f3f0262cSandi
1148f3f0262cSandi  return round($size, $dec) . ' ' . $sizes[$i];
1149f3f0262cSandi}
1150f3f0262cSandi
115115fae107Sandi/**
115200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
115300a7b5adSEsther Brunner *
115400a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
115500a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
115600a7b5adSEsther Brunner */
115700a7b5adSEsther Brunnerfunction obfuscate($email) {
115800a7b5adSEsther Brunner  global $conf;
115900a7b5adSEsther Brunner
116000a7b5adSEsther Brunner  switch ($conf['mailguard']) {
116100a7b5adSEsther Brunner    case 'visible' :
116200a7b5adSEsther Brunner      $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
116300a7b5adSEsther Brunner      return strtr($email, $obfuscate);
116400a7b5adSEsther Brunner
116500a7b5adSEsther Brunner    case 'hex' :
116600a7b5adSEsther Brunner      $encode = '';
116700a7b5adSEsther Brunner      for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';';
116800a7b5adSEsther Brunner      return $encode;
116900a7b5adSEsther Brunner
117000a7b5adSEsther Brunner    case 'none' :
117100a7b5adSEsther Brunner    default :
117200a7b5adSEsther Brunner      return $email;
117300a7b5adSEsther Brunner  }
117400a7b5adSEsther Brunner}
117500a7b5adSEsther Brunner
117600a7b5adSEsther Brunner/**
117752b0dd67SGuy Brand * Let us know if a user is tracking a page or a namespace
1178b158d625SSteven Danz *
11791380fc45SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1180b158d625SSteven Danz */
118152b0dd67SGuy Brandfunction is_subscribed($id,$uid,$ns=false){
118252b0dd67SGuy Brand  if(!$ns) {
11831380fc45SAndreas Gohr    $file=metaFN($id,'.mlist');
118452b0dd67SGuy Brand  } else {
118552b0dd67SGuy Brand    if(!getNS($id)) {
118652b0dd67SGuy Brand      $file = metaFN(getNS($id),'.mlist');
118752b0dd67SGuy Brand    } else {
118852b0dd67SGuy Brand      $file = metaFN(getNS($id),'/.mlist');
118952b0dd67SGuy Brand    }
119052b0dd67SGuy Brand  }
11911380fc45SAndreas Gohr  if (@file_exists($file)) {
1192b158d625SSteven Danz    $mlist = file($file);
11931380fc45SAndreas Gohr    $pos = array_search($uid."\n",$mlist);
11941380fc45SAndreas Gohr    return is_int($pos);
1195b158d625SSteven Danz  }
11961380fc45SAndreas Gohr
1197b158d625SSteven Danz  return false;
1198b158d625SSteven Danz}
1199340756e4Sandi
1200f9eb5648Ssteven-danz/**
1201f9eb5648Ssteven-danz * Return a string with the email addresses of all the
1202f9eb5648Ssteven-danz * users subscribed to a page
1203f9eb5648Ssteven-danz *
120426a0801fSAndreas Gohr * @author Steven Danz <steven-danz@kc.rr.com>
1205f9eb5648Ssteven-danz */
1206f9eb5648Ssteven-danzfunction subscriber_addresslist($id){
1207f9eb5648Ssteven-danz  global $conf;
1208cd52f92dSchris  global $auth;
1209f9eb5648Ssteven-danz
121012cb3a51STom N Harris  if (!$conf['subscribers']) return '';
1211f9eb5648Ssteven-danz
121212cb3a51STom N Harris  $users = array();
121312cb3a51STom N Harris  $emails = array();
121426a0801fSAndreas Gohr
121552b0dd67SGuy Brand  // load the page mlist file content
1216f9eb5648Ssteven-danz  $mlist = array();
1217f9eb5648Ssteven-danz  $file=metaFN($id,'.mlist');
1218d8186216SBen Coburn  if (@file_exists($file)) {
1219f9eb5648Ssteven-danz    $mlist = file($file);
1220f9eb5648Ssteven-danz    foreach ($mlist as $who) {
1221f9eb5648Ssteven-danz      $who = rtrim($who);
122212cb3a51STom N Harris      $users[$who] = true;
1223f9eb5648Ssteven-danz    }
1224f9eb5648Ssteven-danz  }
1225f9eb5648Ssteven-danz
122652b0dd67SGuy Brand  // load also the namespace mlist file content
122712cb3a51STom N Harris  $ns = getNS($id);
122812cb3a51STom N Harris  while ($ns) {
122912cb3a51STom N Harris    $nsfile = metaFN($ns,'/.mlist');
123052b0dd67SGuy Brand    if (@file_exists($nsfile)) {
123152b0dd67SGuy Brand      $mlist = file($nsfile);
123252b0dd67SGuy Brand      foreach ($mlist as $who) {
123352b0dd67SGuy Brand        $who = rtrim($who);
123412cb3a51STom N Harris        $users[$who] = true;
123512cb3a51STom N Harris      }
123612cb3a51STom N Harris    }
123712cb3a51STom N Harris    $ns = getNS($ns);
123812cb3a51STom N Harris  }
123912cb3a51STom N Harris  // root namespace
124012cb3a51STom N Harris  $nsfile = metaFN('','.mlist');
124112cb3a51STom N Harris  if (@file_exists($nsfile)) {
124212cb3a51STom N Harris    $mlist = file($nsfile);
124312cb3a51STom N Harris    foreach ($mlist as $who) {
124412cb3a51STom N Harris      $who = rtrim($who);
124512cb3a51STom N Harris      $users[$who] = true;
124612cb3a51STom N Harris    }
124712cb3a51STom N Harris  }
124812cb3a51STom N Harris  if(!empty($users)) {
124912cb3a51STom N Harris    foreach (array_keys($users) as $who) {
125052b0dd67SGuy Brand      $info = $auth->getUserData($who);
125152b0dd67SGuy Brand      if($info === false) continue;
125252b0dd67SGuy Brand      $level = auth_aclcheck($id,$who,$info['grps']);
125352b0dd67SGuy Brand      if ($level >= AUTH_READ) {
125452b0dd67SGuy Brand        if (strcasecmp($info['mail'],$conf['notify']) != 0) {
125512cb3a51STom N Harris          $emails[] = $info['mail'];
125652b0dd67SGuy Brand        }
125752b0dd67SGuy Brand      }
125852b0dd67SGuy Brand    }
125952b0dd67SGuy Brand  }
126052b0dd67SGuy Brand
126112cb3a51STom N Harris  return implode(',',$emails);
1262f9eb5648Ssteven-danz}
1263f9eb5648Ssteven-danz
126489541d4bSAndreas Gohr/**
126589541d4bSAndreas Gohr * Removes quoting backslashes
126689541d4bSAndreas Gohr *
126789541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
126889541d4bSAndreas Gohr */
126989541d4bSAndreas Gohrfunction unslash($string,$char="'"){
127089541d4bSAndreas Gohr  return str_replace('\\'.$char,$char,$string);
127189541d4bSAndreas Gohr}
127289541d4bSAndreas Gohr
127373038c47SAndreas Gohr/**
127473038c47SAndreas Gohr * Convert php.ini shorthands to byte
127573038c47SAndreas Gohr *
127673038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
127773038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
127873038c47SAndreas Gohr */
127973038c47SAndreas Gohrfunction php_to_byte($v){
128073038c47SAndreas Gohr    $l = substr($v, -1);
128173038c47SAndreas Gohr    $ret = substr($v, 0, -1);
128273038c47SAndreas Gohr    switch(strtoupper($l)){
128373038c47SAndreas Gohr        case 'P':
128473038c47SAndreas Gohr            $ret *= 1024;
128573038c47SAndreas Gohr        case 'T':
128673038c47SAndreas Gohr            $ret *= 1024;
128773038c47SAndreas Gohr        case 'G':
128873038c47SAndreas Gohr            $ret *= 1024;
128973038c47SAndreas Gohr        case 'M':
129073038c47SAndreas Gohr            $ret *= 1024;
129173038c47SAndreas Gohr        case 'K':
129273038c47SAndreas Gohr            $ret *= 1024;
129373038c47SAndreas Gohr        break;
129473038c47SAndreas Gohr    }
129573038c47SAndreas Gohr    return $ret;
129673038c47SAndreas Gohr}
129773038c47SAndreas Gohr
1298546d3a99SAndreas Gohr/**
1299546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1300546d3a99SAndreas Gohr */
1301546d3a99SAndreas Gohrfunction preg_quote_cb($string){
1302546d3a99SAndreas Gohr    return preg_quote($string,'/');
1303546d3a99SAndreas Gohr}
130473038c47SAndreas Gohr
1305bd2f6c2fSAndreas Gohr/**
1306bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1307bd2f6c2fSAndreas Gohr *
1308bd2f6c2fSAndreas Gohr * You can give the string in two parts, teh first part $keep
1309bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1310bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1311bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1312bd2f6c2fSAndreas Gohr *
1313bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1314bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1315bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1316bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1317bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1318bd2f6c2fSAndreas Gohr */
1319bd2f6c2fSAndreas Gohrfunction shorten($keep,$short,$max,$min=9,$char='⌇'){
1320bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1321bd2f6c2fSAndreas Gohr   if($max < $min) return $keep;
1322bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1323bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1324bd2f6c2fSAndreas Gohr    $half = floor($max/2);
1325bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1326bd2f6c2fSAndreas Gohr}
1327bd2f6c2fSAndreas Gohr
1328dc58b6f4SAndy Webber/**
1329dc58b6f4SAndy Webber * Return the users realname or e-mail address for use
1330dc58b6f4SAndy Webber * in page footer and recent changes pages
1331dc58b6f4SAndy Webber *
1332dc58b6f4SAndy Webber * @author Andy Webber <dokuwiki AT andywebber DOT com>
1333dc58b6f4SAndy Webber */
1334dc58b6f4SAndy Webberfunction editorinfo($username){
1335dc58b6f4SAndy Webber    global $conf;
1336dc58b6f4SAndy Webber    global $auth;
1337dc58b6f4SAndy Webber
1338dc58b6f4SAndy Webber    switch($conf['showuseras']){
1339dc58b6f4SAndy Webber      case 'username':
1340dc58b6f4SAndy Webber      case 'email':
1341dc58b6f4SAndy Webber      case 'email_link':
1342dc58b6f4SAndy Webber        $info = $auth->getUserData($username);
1343dc58b6f4SAndy Webber        break;
1344dc58b6f4SAndy Webber      default:
1345dc58b6f4SAndy Webber        return hsc($username);
1346dc58b6f4SAndy Webber    }
1347dc58b6f4SAndy Webber
1348dc58b6f4SAndy Webber    if(isset($info) && $info) {
1349dc58b6f4SAndy Webber        switch($conf['showuseras']){
1350dc58b6f4SAndy Webber          case 'username':
1351dc58b6f4SAndy Webber            return hsc($info['name']);
1352dc58b6f4SAndy Webber          case 'email':
1353dc58b6f4SAndy Webber            return obfuscate($info['mail']);
1354dc58b6f4SAndy Webber          case 'email_link':
1355dc58b6f4SAndy Webber            $mail=obfuscate($info['mail']);
1356dc58b6f4SAndy Webber            return '<a href="mailto:'.$mail.'">'.$mail.'</a>';
1357dc58b6f4SAndy Webber          default:
1358dc58b6f4SAndy Webber            return hsc($username);
1359dc58b6f4SAndy Webber        }
1360dc58b6f4SAndy Webber    } else {
1361dc58b6f4SAndy Webber        return hsc($username);
1362dc58b6f4SAndy Webber    }
1363066fee30SAndreas Gohr}
1364066fee30SAndreas Gohr
1365066fee30SAndreas Gohr/**
1366066fee30SAndreas Gohr * Returns the path to a image file for the currently chosen license.
1367066fee30SAndreas Gohr * When no image exists, returns an empty string
1368066fee30SAndreas Gohr *
1369066fee30SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1370066fee30SAndreas Gohr * @param  string $type - type of image 'badge' or 'button'
1371066fee30SAndreas Gohr */
1372066fee30SAndreas Gohrfunction license_img($type){
1373066fee30SAndreas Gohr    global $license;
1374066fee30SAndreas Gohr    global $conf;
1375066fee30SAndreas Gohr    if(!$conf['license']) return '';
1376066fee30SAndreas Gohr    if(!is_array($license[$conf['license']])) return '';
1377066fee30SAndreas Gohr    $lic = $license[$conf['license']];
1378066fee30SAndreas Gohr    $try = array();
1379066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.png';
1380066fee30SAndreas Gohr    $try[] = 'lib/images/license/'.$type.'/'.$conf['license'].'.gif';
1381066fee30SAndreas Gohr    if(substr($conf['license'],0,3) == 'cc-'){
1382066fee30SAndreas Gohr        $try[] = 'lib/images/license/'.$type.'/cc.png';
1383066fee30SAndreas Gohr    }
1384066fee30SAndreas Gohr    foreach($try as $src){
1385066fee30SAndreas Gohr        if(@file_exists(DOKU_INC.$src)) return $src;
1386066fee30SAndreas Gohr    }
1387066fee30SAndreas Gohr    return '';
1388dc58b6f4SAndy Webber}
1389dc58b6f4SAndy Webber
1390340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1391