xref: /dokuwiki/inc/common.php (revision 8c08db0a936bb99814fc12a60e2717882b6f9ee4)
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
211f3f0262cSandi  return $info;
212f3f0262cSandi}
213f3f0262cSandi
214f3f0262cSandi/**
2152684e50aSAndreas Gohr * Build an string of URL parameters
2162684e50aSAndreas Gohr *
2172684e50aSAndreas Gohr * @author Andreas Gohr
2182684e50aSAndreas Gohr */
219b174aeaeSchrisfunction buildURLparams($params, $sep='&amp;'){
2202684e50aSAndreas Gohr  $url = '';
2212684e50aSAndreas Gohr  $amp = false;
2222684e50aSAndreas Gohr  foreach($params as $key => $val){
223b174aeaeSchris    if($amp) $url .= $sep;
2242684e50aSAndreas Gohr
2252684e50aSAndreas Gohr    $url .= $key.'=';
2263a50618cSgweissbach    $url .= rawurlencode((string)$val);
2272684e50aSAndreas Gohr    $amp = true;
2282684e50aSAndreas Gohr  }
2292684e50aSAndreas Gohr  return $url;
2302684e50aSAndreas Gohr}
2312684e50aSAndreas Gohr
2322684e50aSAndreas Gohr/**
2332684e50aSAndreas Gohr * Build an string of html tag attributes
2342684e50aSAndreas Gohr *
2357bff22c0SAndreas Gohr * Skips keys starting with '_', values get HTML encoded
2367bff22c0SAndreas Gohr *
2372684e50aSAndreas Gohr * @author Andreas Gohr
2382684e50aSAndreas Gohr */
2394b030ce7SAndreas Gohrfunction buildAttributes($params,$skipempty=false){
2402684e50aSAndreas Gohr  $url = '';
2412684e50aSAndreas Gohr  foreach($params as $key => $val){
2427bff22c0SAndreas Gohr    if($key{0} == '_') continue;
243b1c94f1dSAndreas Gohr    if($val === '' && $skipempty) continue;
2447bff22c0SAndreas Gohr
2452684e50aSAndreas Gohr    $url .= $key.'="';
2462684e50aSAndreas Gohr    $url .= htmlspecialchars ($val);
2472684e50aSAndreas Gohr    $url .= '" ';
2482684e50aSAndreas Gohr  }
2492684e50aSAndreas Gohr  return $url;
2502684e50aSAndreas Gohr}
2512684e50aSAndreas Gohr
2522684e50aSAndreas Gohr
2532684e50aSAndreas Gohr/**
25415fae107Sandi * This builds the breadcrumb trail and returns it as array
25515fae107Sandi *
25615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
257f3f0262cSandi */
258f3f0262cSandifunction breadcrumbs(){
2598746e727Sandi  // we prepare the breadcrumbs early for quick session closing
2608746e727Sandi  static $crumbs = null;
2618746e727Sandi  if($crumbs != null) return $crumbs;
2628746e727Sandi
263f3f0262cSandi  global $ID;
264f3f0262cSandi  global $ACT;
265f3f0262cSandi  global $conf;
266e71ce681SAndreas Gohr  $crumbs = $_SESSION[DOKU_COOKIE]['bc'];
267f3f0262cSandi
268f3f0262cSandi  //first visit?
269f3f0262cSandi  if (!is_array($crumbs)){
270f3f0262cSandi    $crumbs = array();
271f3f0262cSandi  }
272f3f0262cSandi  //we only save on show and existing wiki documents
273a77f5846Sjan  $file = wikiFN($ID);
274a77f5846Sjan  if($ACT != 'show' || !@file_exists($file)){
275e71ce681SAndreas Gohr    $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
276f3f0262cSandi    return $crumbs;
277f3f0262cSandi  }
278a77f5846Sjan
279a77f5846Sjan  // page names
2801a84a0f3SAnika Henke  $name = noNSorNS($ID);
281a77f5846Sjan  if ($conf['useheading']) {
282a77f5846Sjan    // get page title
283955cd091SChris Smith    $title = p_get_first_heading($ID,true);
284a77f5846Sjan    if ($title) {
285a77f5846Sjan      $name = $title;
286a77f5846Sjan    }
287a77f5846Sjan  }
288a77f5846Sjan
289f3f0262cSandi  //remove ID from array
290a77f5846Sjan  if (isset($crumbs[$ID])) {
291a77f5846Sjan    unset($crumbs[$ID]);
292f3f0262cSandi  }
293f3f0262cSandi
294f3f0262cSandi  //add to array
295a77f5846Sjan  $crumbs[$ID] = $name;
296f3f0262cSandi  //reduce size
297f3f0262cSandi  while(count($crumbs) > $conf['breadcrumbs']){
298f3f0262cSandi    array_shift($crumbs);
299f3f0262cSandi  }
300f3f0262cSandi  //save to session
301e71ce681SAndreas Gohr  $_SESSION[DOKU_COOKIE]['bc'] = $crumbs;
302f3f0262cSandi  return $crumbs;
303f3f0262cSandi}
304f3f0262cSandi
305f3f0262cSandi/**
30615fae107Sandi * Filter for page IDs
30715fae107Sandi *
308f3f0262cSandi * This is run on a ID before it is outputted somewhere
309f3f0262cSandi * currently used to replace the colon with something else
310f3f0262cSandi * on Windows systems and to have proper URL encoding
31115fae107Sandi *
31249c713a3Sandi * Urlencoding is ommitted when the second parameter is false
31349c713a3Sandi *
31415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
315f3f0262cSandi */
31649c713a3Sandifunction idfilter($id,$ue=true){
317f3f0262cSandi  global $conf;
318f3f0262cSandi  if ($conf['useslash'] && $conf['userewrite']){
319f3f0262cSandi    $id = strtr($id,':','/');
320f3f0262cSandi  }elseif (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN' &&
321f3f0262cSandi      $conf['userewrite']) {
322f3f0262cSandi    $id = strtr($id,':',';');
323f3f0262cSandi  }
32449c713a3Sandi  if($ue){
325b6c6979fSAndreas Gohr    $id = rawurlencode($id);
326f3f0262cSandi    $id = str_replace('%3A',':',$id); //keep as colon
327f3f0262cSandi    $id = str_replace('%2F','/',$id); //keep as slash
32849c713a3Sandi  }
329f3f0262cSandi  return $id;
330f3f0262cSandi}
331f3f0262cSandi
332f3f0262cSandi/**
333ed7b5f09Sandi * This builds a link to a wikipage
33415fae107Sandi *
3356c7843b5Sandi * It handles URL rewriting and adds additional parameter if
3366c7843b5Sandi * given in $more
3376c7843b5Sandi *
33815fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
339f3f0262cSandi */
340b174aeaeSchrisfunction wl($id='',$more='',$abs=false,$sep='&amp;'){
341f3f0262cSandi  global $conf;
3426de3759aSAndreas Gohr  if(is_array($more)){
343b174aeaeSchris    $more = buildURLparams($more,$sep);
3446de3759aSAndreas Gohr  }else{
345b174aeaeSchris    $more = str_replace(',',$sep,$more);
3466de3759aSAndreas Gohr  }
347f3f0262cSandi
348f3f0262cSandi  $id    = idfilter($id);
349ed7b5f09Sandi  if($abs){
350ed7b5f09Sandi    $xlink = DOKU_URL;
351ed7b5f09Sandi  }else{
352ed7b5f09Sandi    $xlink = DOKU_BASE;
353ed7b5f09Sandi  }
354f3f0262cSandi
3556c7843b5Sandi  if($conf['userewrite'] == 2){
3566c7843b5Sandi    $xlink .= DOKU_SCRIPT.'/'.$id;
3576c7843b5Sandi    if($more) $xlink .= '?'.$more;
3586c7843b5Sandi  }elseif($conf['userewrite']){
359f3f0262cSandi    $xlink .= $id;
360f3f0262cSandi    if($more) $xlink .= '?'.$more;
361bce3726dSAndreas Gohr  }elseif($id){
3626c7843b5Sandi    $xlink .= DOKU_SCRIPT.'?id='.$id;
363b174aeaeSchris    if($more) $xlink .= $sep.$more;
364bce3726dSAndreas Gohr  }else{
365bce3726dSAndreas Gohr    $xlink .= DOKU_SCRIPT;
366bce3726dSAndreas Gohr    if($more) $xlink .= '?'.$more;
367f3f0262cSandi  }
368f3f0262cSandi
369f3f0262cSandi  return $xlink;
370f3f0262cSandi}
371f3f0262cSandi
372f3f0262cSandi/**
373f5c2808fSBen Coburn * This builds a link to an alternate page format
374f5c2808fSBen Coburn *
375f5c2808fSBen Coburn * Handles URL rewriting if enabled. Follows the style of wl().
376f5c2808fSBen Coburn *
377f5c2808fSBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
378f5c2808fSBen Coburn */
379f5c2808fSBen Coburnfunction exportlink($id='',$format='raw',$more='',$abs=false,$sep='&amp;'){
380f5c2808fSBen Coburn  global $conf;
381f5c2808fSBen Coburn  if(is_array($more)){
382f5c2808fSBen Coburn    $more = buildURLparams($more,$sep);
383f5c2808fSBen Coburn  }else{
384f5c2808fSBen Coburn    $more = str_replace(',',$sep,$more);
385f5c2808fSBen Coburn  }
386f5c2808fSBen Coburn
387f5c2808fSBen Coburn  $format = rawurlencode($format);
388f5c2808fSBen Coburn  $id = idfilter($id);
389f5c2808fSBen Coburn  if($abs){
390f5c2808fSBen Coburn    $xlink = DOKU_URL;
391f5c2808fSBen Coburn  }else{
392f5c2808fSBen Coburn    $xlink = DOKU_BASE;
393f5c2808fSBen Coburn  }
394f5c2808fSBen Coburn
395f5c2808fSBen Coburn  if($conf['userewrite'] == 2){
396f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'/'.$id.'?do=export_'.$format;
397f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
398f5c2808fSBen Coburn  }elseif($conf['userewrite'] == 1){
399f5c2808fSBen Coburn    $xlink .= '_export/'.$format.'/'.$id;
400f5c2808fSBen Coburn    if($more) $xlink .= '?'.$more;
401f5c2808fSBen Coburn  }else{
402f5c2808fSBen Coburn    $xlink .= DOKU_SCRIPT.'?do=export_'.$format.$sep.'id='.$id;
403f5c2808fSBen Coburn    if($more) $xlink .= $sep.$more;
404f5c2808fSBen Coburn  }
405f5c2808fSBen Coburn
406f5c2808fSBen Coburn  return $xlink;
407f5c2808fSBen Coburn}
408f5c2808fSBen Coburn
409f5c2808fSBen Coburn/**
4106de3759aSAndreas Gohr * Build a link to a media file
4116de3759aSAndreas Gohr *
4126de3759aSAndreas Gohr * Will return a link to the detail page if $direct is false
413*8c08db0aSAndreas Gohr *
414*8c08db0aSAndreas Gohr * The $more parameter should always be given as array, the function then
415*8c08db0aSAndreas Gohr * will strip default parameters to produce even cleaner URLs
416*8c08db0aSAndreas Gohr *
417*8c08db0aSAndreas Gohr * @param string  $id     - the media file id or URL
418*8c08db0aSAndreas Gohr * @param mixed   $more   - string or array with additional parameters
419*8c08db0aSAndreas Gohr * @param boolean $direct - link to detail page if false
420*8c08db0aSAndreas Gohr * @param string  $sep    - URL parameter separator
421*8c08db0aSAndreas Gohr * @param boolean $abs    - Create an absolute URL
4226de3759aSAndreas Gohr */
42355b2b31bSAndreas Gohrfunction ml($id='',$more='',$direct=true,$sep='&amp;',$abs=false){
4246de3759aSAndreas Gohr  global $conf;
4256de3759aSAndreas Gohr  if(is_array($more)){
426*8c08db0aSAndreas Gohr    // strip defaults for shorter URLs
427*8c08db0aSAndreas Gohr    if(isset($more['cache']) && $more['cache'] == 'cache') unset($more['cache']);
428*8c08db0aSAndreas Gohr    if(!$more['w']) unset($more['w']);
429*8c08db0aSAndreas Gohr    if(!$more['h']) unset($more['h']);
430*8c08db0aSAndreas Gohr    if(isset($more['id']) && $direct) unset($more['id']);
431b174aeaeSchris    $more = buildURLparams($more,$sep);
4326de3759aSAndreas Gohr  }else{
433*8c08db0aSAndreas Gohr    $more = str_replace('cache=cache','',$more); //skip default
434*8c08db0aSAndreas Gohr    $more = str_replace(',,',',',$more);
435b174aeaeSchris    $more = str_replace(',',$sep,$more);
4366de3759aSAndreas Gohr  }
4376de3759aSAndreas Gohr
43855b2b31bSAndreas Gohr  if($abs){
43955b2b31bSAndreas Gohr    $xlink = DOKU_URL;
44055b2b31bSAndreas Gohr  }else{
4416de3759aSAndreas Gohr    $xlink = DOKU_BASE;
44255b2b31bSAndreas Gohr  }
4436de3759aSAndreas Gohr
4446de3759aSAndreas Gohr  // external URLs are always direct without rewriting
4456de3759aSAndreas Gohr  if(preg_match('#^(https?|ftp)://#i',$id)){
4466de3759aSAndreas Gohr    $xlink .= 'lib/exe/fetch.php';
4476de3759aSAndreas Gohr    if($more){
4486de3759aSAndreas Gohr      $xlink .= '?'.$more;
449b174aeaeSchris      $xlink .= $sep.'media='.rawurlencode($id);
4506de3759aSAndreas Gohr    }else{
451b6c6979fSAndreas Gohr      $xlink .= '?media='.rawurlencode($id);
4526de3759aSAndreas Gohr    }
4536de3759aSAndreas Gohr    return $xlink;
4546de3759aSAndreas Gohr  }
4556de3759aSAndreas Gohr
4566de3759aSAndreas Gohr  $id = idfilter($id);
4576de3759aSAndreas Gohr
4586de3759aSAndreas Gohr  // decide on scriptname
4596de3759aSAndreas Gohr  if($direct){
4606de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4616de3759aSAndreas Gohr      $script = '_media';
4626de3759aSAndreas Gohr    }else{
4636de3759aSAndreas Gohr      $script = 'lib/exe/fetch.php';
4646de3759aSAndreas Gohr    }
4656de3759aSAndreas Gohr  }else{
4666de3759aSAndreas Gohr    if($conf['userewrite'] == 1){
4676de3759aSAndreas Gohr      $script = '_detail';
4686de3759aSAndreas Gohr    }else{
4696de3759aSAndreas Gohr      $script = 'lib/exe/detail.php';
4706de3759aSAndreas Gohr    }
4716de3759aSAndreas Gohr  }
4726de3759aSAndreas Gohr
4736de3759aSAndreas Gohr  // build URL based on rewrite mode
4746de3759aSAndreas Gohr   if($conf['userewrite']){
4756de3759aSAndreas Gohr     $xlink .= $script.'/'.$id;
4766de3759aSAndreas Gohr     if($more) $xlink .= '?'.$more;
4776de3759aSAndreas Gohr   }else{
4786de3759aSAndreas Gohr     if($more){
479a99d3236SEsther Brunner       $xlink .= $script.'?'.$more;
480b174aeaeSchris       $xlink .= $sep.'media='.$id;
4816de3759aSAndreas Gohr     }else{
482a99d3236SEsther Brunner       $xlink .= $script.'?media='.$id;
4836de3759aSAndreas Gohr     }
4846de3759aSAndreas Gohr   }
4856de3759aSAndreas Gohr
4866de3759aSAndreas Gohr  return $xlink;
4876de3759aSAndreas Gohr}
4886de3759aSAndreas Gohr
4896de3759aSAndreas Gohr
4906de3759aSAndreas Gohr
4916de3759aSAndreas Gohr/**
492f3f0262cSandi * Just builds a link to a script
49315fae107Sandi *
494ed7b5f09Sandi * @todo   maybe obsolete
49515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
496f3f0262cSandi */
497f3f0262cSandifunction script($script='doku.php'){
498ed7b5f09Sandi#  $link = getBaseURL();
499ed7b5f09Sandi#  $link .= $script;
500ed7b5f09Sandi#  return $link;
501ed7b5f09Sandi  return DOKU_BASE.DOKU_SCRIPT;
502f3f0262cSandi}
503f3f0262cSandi
504f3f0262cSandi/**
50515fae107Sandi * Spamcheck against wordlist
50615fae107Sandi *
507f3f0262cSandi * Checks the wikitext against a list of blocked expressions
508f3f0262cSandi * returns true if the text contains any bad words
50915fae107Sandi *
51015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
511f3f0262cSandi */
512f3f0262cSandifunction checkwordblock(){
513f3f0262cSandi  global $TEXT;
514f3f0262cSandi  global $conf;
515f3f0262cSandi
516f3f0262cSandi  if(!$conf['usewordblock']) return false;
517f3f0262cSandi
518041d1964SAndreas Gohr  // we prepare the text a tiny bit to prevent spammers circumventing URL checks
519041d1964SAndreas Gohr  $text = preg_replace('!(\b)(www\.[\w.:?\-;,]+?\.[\w.:?\-;,]+?[\w/\#~:.?+=&%@\!\-.:?\-;,]+?)([.:?\-;,]*[^\w/\#~:.?+=&%@\!\-.:?\-;,])!i','\1http://\2 \2\3',$TEXT);
520041d1964SAndreas Gohr
521b9ac8716Schris  $wordblocks = getWordblocks();
5223e2965d7Sandi  //how many lines to read at once (to work around some PCRE limits)
5233e2965d7Sandi  if(version_compare(phpversion(),'4.3.0','<')){
5243e2965d7Sandi    //old versions of PCRE define a maximum of parenthesises even if no
5253e2965d7Sandi    //backreferences are used - the maximum is 99
5263e2965d7Sandi    //this is very bad performancewise and may even be too high still
5273e2965d7Sandi    $chunksize = 40;
5283e2965d7Sandi  }else{
529a51d08efSAndreas Gohr    //read file in chunks of 200 - this should work around the
5303e2965d7Sandi    //MAX_PATTERN_SIZE in modern PCRE
531a51d08efSAndreas Gohr    $chunksize = 200;
5323e2965d7Sandi  }
533b9ac8716Schris  while($blocks = array_splice($wordblocks,0,$chunksize)){
534f3f0262cSandi    $re = array();
535f3f0262cSandi    #build regexp from blocks
536f3f0262cSandi    foreach($blocks as $block){
537f3f0262cSandi      $block = preg_replace('/#.*$/','',$block);
538f3f0262cSandi      $block = trim($block);
539f3f0262cSandi      if(empty($block)) continue;
540f3f0262cSandi      $re[]  = $block;
541f3f0262cSandi    }
542c2525298SAndreas Gohr    if(count($re) && preg_match('#('.join('|',$re).')#si',$text)) {
543b9ac8716Schris      return true;
544b9ac8716Schris    }
545703f6fdeSandi  }
546f3f0262cSandi  return false;
547f3f0262cSandi}
548f3f0262cSandi
549f3f0262cSandi/**
55015fae107Sandi * Return the IP of the client
55115fae107Sandi *
5526d8affe6SAndreas Gohr * Honours X-Forwarded-For and X-Real-IP Proxy Headers
55315fae107Sandi *
5546d8affe6SAndreas Gohr * It returns a comma separated list of IPs if the above mentioned
5556d8affe6SAndreas Gohr * headers are set. If the single parameter is set, it tries to return
5566d8affe6SAndreas Gohr * a routable public address, prefering the ones suplied in the X
5576d8affe6SAndreas Gohr * headers
5586d8affe6SAndreas Gohr *
5596d8affe6SAndreas Gohr * @param  boolean $single If set only a single IP is returned
56015fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
561f3f0262cSandi */
5626d8affe6SAndreas Gohrfunction clientIP($single=false){
5636d8affe6SAndreas Gohr  $ip = array();
5646d8affe6SAndreas Gohr  $ip[] = $_SERVER['REMOTE_ADDR'];
565bb4866bdSchris  if(!empty($_SERVER['HTTP_X_FORWARDED_FOR']))
5666d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']));
567bb4866bdSchris  if(!empty($_SERVER['HTTP_X_REAL_IP']))
5686d8affe6SAndreas Gohr    $ip = array_merge($ip,explode(',',$_SERVER['HTTP_X_REAL_IP']));
5696d8affe6SAndreas Gohr
5706d8affe6SAndreas Gohr  // remove any non-IP stuff
5716d8affe6SAndreas Gohr  $cnt = count($ip);
5724ff28443Schris  $match = array();
5736d8affe6SAndreas Gohr  for($i=0; $i<$cnt; $i++){
5744ff28443Schris    if(preg_match('/\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}/',$ip[$i],$match)) {
5754ff28443Schris      $ip[$i] = $match[0];
5764ff28443Schris    } else {
5774ff28443Schris      $ip[$i] = '';
5784ff28443Schris    }
5796d8affe6SAndreas Gohr    if(empty($ip[$i])) unset($ip[$i]);
580f3f0262cSandi  }
5816d8affe6SAndreas Gohr  $ip = array_values(array_unique($ip));
5826d8affe6SAndreas Gohr  if(!$ip[0]) $ip[0] = '0.0.0.0'; // for some strange reason we don't have a IP
5836d8affe6SAndreas Gohr
5846d8affe6SAndreas Gohr  if(!$single) return join(',',$ip);
5856d8affe6SAndreas Gohr
5866d8affe6SAndreas Gohr  // decide which IP to use, trying to avoid local addresses
5876d8affe6SAndreas Gohr  $ip = array_reverse($ip);
5886d8affe6SAndreas Gohr  foreach($ip as $i){
5896d8affe6SAndreas Gohr    if(preg_match('/^(127\.|10\.|192\.168\.|172\.((1[6-9])|(2[0-9])|(3[0-1]))\.)/',$i)){
5906d8affe6SAndreas Gohr      continue;
5916d8affe6SAndreas Gohr    }else{
5926d8affe6SAndreas Gohr      return $i;
5936d8affe6SAndreas Gohr    }
5946d8affe6SAndreas Gohr  }
5956d8affe6SAndreas Gohr  // still here? just use the first (last) address
5966d8affe6SAndreas Gohr  return $ip[0];
597f3f0262cSandi}
598f3f0262cSandi
599f3f0262cSandi/**
60063211f61SGlen Harris * Convert one or more comma separated IPs to hostnames
60163211f61SGlen Harris *
60263211f61SGlen Harris * @author Glen Harris <astfgl@iamnota.org>
60363211f61SGlen Harris * @returns a comma separated list of hostnames
60463211f61SGlen Harris */
60563211f61SGlen Harrisfunction gethostsbyaddrs($ips){
60663211f61SGlen Harris  $hosts = array();
60763211f61SGlen Harris  $ips = explode(',',$ips);
608551a720fSMichael Klier
609551a720fSMichael Klier  if(is_array($ips)) {
6103886270dSAndreas Gohr    foreach($ips as $ip){
611551a720fSMichael Klier      $hosts[] = gethostbyaddr(trim($ip));
61263211f61SGlen Harris    }
613551a720fSMichael Klier    return join(',',$hosts);
614551a720fSMichael Klier  } else {
615551a720fSMichael Klier    return gethostbyaddr(trim($ips));
616551a720fSMichael Klier  }
61763211f61SGlen Harris}
61863211f61SGlen Harris
61963211f61SGlen Harris/**
62015fae107Sandi * Checks if a given page is currently locked.
62115fae107Sandi *
622f3f0262cSandi * removes stale lockfiles
62315fae107Sandi *
62415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
625f3f0262cSandi */
626f3f0262cSandifunction checklock($id){
627f3f0262cSandi  global $conf;
628c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
629f3f0262cSandi
630f3f0262cSandi  //no lockfile
631f3f0262cSandi  if(!@file_exists($lock)) return false;
632f3f0262cSandi
633f3f0262cSandi  //lockfile expired
634f3f0262cSandi  if((time() - filemtime($lock)) > $conf['locktime']){
635d8186216SBen Coburn    @unlink($lock);
636f3f0262cSandi    return false;
637f3f0262cSandi  }
638f3f0262cSandi
639f3f0262cSandi  //my own lock
640f3f0262cSandi  $ip = io_readFile($lock);
641f3f0262cSandi  if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
642f3f0262cSandi    return false;
643f3f0262cSandi  }
644f3f0262cSandi
645f3f0262cSandi  return $ip;
646f3f0262cSandi}
647f3f0262cSandi
648f3f0262cSandi/**
64915fae107Sandi * Lock a page for editing
65015fae107Sandi *
65115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
652f3f0262cSandi */
653f3f0262cSandifunction lock($id){
654c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
655f3f0262cSandi  if($_SERVER['REMOTE_USER']){
656f3f0262cSandi    io_saveFile($lock,$_SERVER['REMOTE_USER']);
657f3f0262cSandi  }else{
658f3f0262cSandi    io_saveFile($lock,clientIP());
659f3f0262cSandi  }
660f3f0262cSandi}
661f3f0262cSandi
662f3f0262cSandi/**
66315fae107Sandi * Unlock a page if it was locked by the user
664f3f0262cSandi *
66515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
66615fae107Sandi * @return bool true if a lock was removed
667f3f0262cSandi */
668f3f0262cSandifunction unlock($id){
669c9b4bd1eSBen Coburn  $lock = wikiLockFN($id);
670f3f0262cSandi  if(@file_exists($lock)){
671f3f0262cSandi    $ip = io_readFile($lock);
672f3f0262cSandi    if( ($ip == clientIP()) || ($ip == $_SERVER['REMOTE_USER']) ){
673f3f0262cSandi      @unlink($lock);
674f3f0262cSandi      return true;
675f3f0262cSandi    }
676f3f0262cSandi  }
677f3f0262cSandi  return false;
678f3f0262cSandi}
679f3f0262cSandi
680f3f0262cSandi/**
681f3f0262cSandi * convert line ending to unix format
682f3f0262cSandi *
68315fae107Sandi * @see    formText() for 2crlf conversion
68415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
685f3f0262cSandi */
686f3f0262cSandifunction cleanText($text){
687f3f0262cSandi  $text = preg_replace("/(\015\012)|(\015)/","\012",$text);
688f3f0262cSandi  return $text;
689f3f0262cSandi}
690f3f0262cSandi
691f3f0262cSandi/**
692f3f0262cSandi * Prepares text for print in Webforms by encoding special chars.
693f3f0262cSandi * It also converts line endings to Windows format which is
694f3f0262cSandi * pseudo standard for webforms.
695f3f0262cSandi *
69615fae107Sandi * @see    cleanText() for 2unix conversion
69715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
698f3f0262cSandi */
699f3f0262cSandifunction formText($text){
7005b7d45a5SAndreas Gohr  $text = str_replace("\012","\015\012",$text);
701f3f0262cSandi  return htmlspecialchars($text);
702f3f0262cSandi}
703f3f0262cSandi
704f3f0262cSandi/**
70515fae107Sandi * Returns the specified local text in raw format
70615fae107Sandi *
70715fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
708f3f0262cSandi */
709f3f0262cSandifunction rawLocale($id){
710f3f0262cSandi  return io_readFile(localeFN($id));
711f3f0262cSandi}
712f3f0262cSandi
713f3f0262cSandi/**
714f3f0262cSandi * Returns the raw WikiText
71515fae107Sandi *
71615fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
717f3f0262cSandi */
718f3f0262cSandifunction rawWiki($id,$rev=''){
719cc7d0c94SBen Coburn  return io_readWikiPage(wikiFN($id, $rev), $id, $rev);
720f3f0262cSandi}
721f3f0262cSandi
722f3f0262cSandi/**
7237146cee2SAndreas Gohr * Returns the pagetemplate contents for the ID's namespace
7247146cee2SAndreas Gohr *
7257146cee2SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
7267146cee2SAndreas Gohr */
727b7d5a5f0SAndreas Gohrfunction pageTemplate($data){
728b7d5a5f0SAndreas Gohr  $id = $data[0];
729a15ce62dSEsther Brunner  global $conf;
730a15ce62dSEsther Brunner  global $INFO;
731e29549feSAndreas Gohr
732e29549feSAndreas Gohr  $path = dirname(wikiFN($id));
733e29549feSAndreas Gohr
734e29549feSAndreas Gohr  if(@file_exists($path.'/_template.txt')){
735e29549feSAndreas Gohr    $tpl = io_readFile($path.'/_template.txt');
736e29549feSAndreas Gohr  }else{
737e29549feSAndreas Gohr    // search upper namespaces for templates
738e29549feSAndreas Gohr    $len = strlen(rtrim($conf['datadir'],'/'));
739e29549feSAndreas Gohr    while (strlen($path) >= $len){
740e29549feSAndreas Gohr      if(@file_exists($path.'/__template.txt')){
741e29549feSAndreas Gohr        $tpl = io_readFile($path.'/__template.txt');
742e29549feSAndreas Gohr        break;
743e29549feSAndreas Gohr      }
744e29549feSAndreas Gohr      $path = substr($path, 0, strrpos($path, '/'));
745e29549feSAndreas Gohr    }
746e29549feSAndreas Gohr  }
747e29549feSAndreas Gohr  if(!$tpl) return '';
748e29549feSAndreas Gohr
749e29549feSAndreas Gohr  // replace placeholders
750a15ce62dSEsther Brunner  $tpl = str_replace('@ID@',$id,$tpl);
751a15ce62dSEsther Brunner  $tpl = str_replace('@NS@',getNS($id),$tpl);
752a15ce62dSEsther Brunner  $tpl = str_replace('@PAGE@',strtr(noNS($id),'_',' '),$tpl);
753a15ce62dSEsther Brunner  $tpl = str_replace('@USER@',$_SERVER['REMOTE_USER'],$tpl);
754a15ce62dSEsther Brunner  $tpl = str_replace('@NAME@',$INFO['userinfo']['name'],$tpl);
755a15ce62dSEsther Brunner  $tpl = str_replace('@MAIL@',$INFO['userinfo']['mail'],$tpl);
756e656dcd4SAndreas Gohr  $tpl = str_replace('@DATE@',$conf['dformat'],$tpl);
7577d644fc8SAndreas Gohr  // we need the callback to work around strftime's char limit
7587d644fc8SAndreas Gohr  $tpl = preg_replace_callback('/%./',create_function('$m','return strftime($m[0]);'),$tpl);
7597d644fc8SAndreas Gohr
760a15ce62dSEsther Brunner  return $tpl;
7617146cee2SAndreas Gohr}
7627146cee2SAndreas Gohr
7637146cee2SAndreas Gohr
7647146cee2SAndreas Gohr/**
76515fae107Sandi * Returns the raw Wiki Text in three slices.
76615fae107Sandi *
76715fae107Sandi * The range parameter needs to have the form "from-to"
76815cfe303Sandi * and gives the range of the section in bytes - no
76915cfe303Sandi * UTF-8 awareness is needed.
770f3f0262cSandi * The returned order is prefix, section and suffix.
77115fae107Sandi *
77215fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
773f3f0262cSandi */
774f3f0262cSandifunction rawWikiSlices($range,$id,$rev=''){
775f3f0262cSandi  list($from,$to) = split('-',$range,2);
776cc7d0c94SBen Coburn  $text = io_readWikiPage(wikiFN($id, $rev), $id, $rev);
777f3f0262cSandi  if(!$from) $from = 0;
778c3d8e19bSandi  if(!$to)   $to   = strlen($text)+1;
779f3f0262cSandi
78015cfe303Sandi  $slices[0] = substr($text,0,$from-1);
78115cfe303Sandi  $slices[1] = substr($text,$from-1,$to-$from);
78215cfe303Sandi  $slices[2] = substr($text,$to);
783f3f0262cSandi
784f3f0262cSandi  return $slices;
785f3f0262cSandi}
786f3f0262cSandi
787f3f0262cSandi/**
78815fae107Sandi * Joins wiki text slices
78915fae107Sandi *
790f3f0262cSandi * function to join the text slices with correct lineendings again.
791f3f0262cSandi * When the pretty parameter is set to true it adds additional empty
792f3f0262cSandi * lines between sections if needed (used on saving).
79315fae107Sandi *
79415fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
795f3f0262cSandi */
796f3f0262cSandifunction con($pre,$text,$suf,$pretty=false){
797f3f0262cSandi
798f3f0262cSandi  if($pretty){
799f3f0262cSandi    if($pre && substr($pre,-1) != "\n") $pre .= "\n";
800f3f0262cSandi    if($suf && substr($text,-1) != "\n") $text .= "\n";
801f3f0262cSandi  }
802f3f0262cSandi
8037e038d4eSAndreas Gohr  // Avoid double newline above section when saving section edit
8047e038d4eSAndreas Gohr  //if($pre) $pre .= "\n";
805f3f0262cSandi  if($suf) $text .= "\n";
806f3f0262cSandi  return $pre.$text.$suf;
807f3f0262cSandi}
808f3f0262cSandi
809f3f0262cSandi/**
810a701424fSBen Coburn * Saves a wikitext by calling io_writeWikiPage.
811a701424fSBen Coburn * Also directs changelog and attic updates.
81215fae107Sandi *
81315fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
81471726d78SBen Coburn * @author Ben Coburn <btcoburn@silicodon.net>
815f3f0262cSandi */
816b6912aeaSAndreas Gohrfunction saveWikiText($id,$text,$summary,$minor=false){
817a701424fSBen Coburn  /* Note to developers:
818a701424fSBen Coburn     This code is subtle and delicate. Test the behavior of
819a701424fSBen Coburn     the attic and changelog with dokuwiki and external edits
820a701424fSBen Coburn     after any changes. External edits change the wiki page
821a701424fSBen Coburn     directly without using php or dokuwiki.
822a701424fSBen Coburn  */
823f3f0262cSandi  global $conf;
824f3f0262cSandi  global $lang;
82571726d78SBen Coburn  global $REV;
826f3f0262cSandi  // ignore if no changes were made
827f3f0262cSandi  if($text == rawWiki($id,'')){
828f3f0262cSandi    return;
829f3f0262cSandi  }
830f3f0262cSandi
831f3f0262cSandi  $file = wikiFN($id);
832a701424fSBen Coburn  $old = @filemtime($file); // from page
83371726d78SBen Coburn  $wasRemoved = empty($text);
834d8186216SBen Coburn  $wasCreated = !@file_exists($file);
83571726d78SBen Coburn  $wasReverted = ($REV==true);
836e45b34cdSBen Coburn  $newRev = false;
837a701424fSBen Coburn  $oldRev = getRevisions($id, -1, 1, 1024); // from changelog
838a701424fSBen Coburn  $oldRev = (int)(empty($oldRev)?0:$oldRev[0]);
839a701424fSBen Coburn  if(!@file_exists(wikiFN($id, $old)) && @file_exists($file) && $old>=$oldRev) {
84046844156SBen Coburn    // add old revision to the attic if missing
84146844156SBen Coburn    saveOldRevision($id);
84246844156SBen Coburn    // add a changelog entry if this edit came from outside dokuwiki
843a701424fSBen Coburn    if ($old>$oldRev) {
844ebf1501fSBen Coburn      addLogEntry($old, $id, DOKU_CHANGE_TYPE_EDIT, $lang['external_edit'], '', array('ExternalEdit'=>true));
84546844156SBen Coburn      // remove soon to be stale instructions
84646844156SBen Coburn      $cache = new cache_instructions($id, $file);
84746844156SBen Coburn      $cache->removeCache();
84846844156SBen Coburn    }
84946844156SBen Coburn  }
850f3f0262cSandi
85171726d78SBen Coburn  if ($wasRemoved){
85230725328SGabriel Birke    // Send "update" event with empty data, so plugins can react to page deletion
85330725328SGabriel Birke    $data = array(array($file, '', false), getNS($id), noNS($id), false);
85430725328SGabriel Birke    trigger_event('IO_WIKIPAGE_WRITE', $data);
855e45b34cdSBen Coburn    // pre-save deleted revision
856e45b34cdSBen Coburn    @touch($file);
85746844156SBen Coburn    clearstatcache();
858e45b34cdSBen Coburn    $newRev = saveOldRevision($id);
859e1f3d9e1SEsther Brunner    // remove empty file
860f3f0262cSandi    @unlink($file);
86171726d78SBen Coburn    // remove old meta info...
862e1f3d9e1SEsther Brunner    $mfiles = metaFiles($id);
86371726d78SBen Coburn    $changelog = metaFN($id, '.changes');
8643d1f9ec3SMichael Klier    $metadata  = metaFN($id, '.meta');
865e1f3d9e1SEsther Brunner    foreach ($mfiles as $mfile) {
8663d1f9ec3SMichael Klier      // but keep per-page changelog to preserve page history and keep meta data
8673d1f9ec3SMichael Klier      if (@file_exists($mfile) && $mfile!==$changelog && $mfile!==$metadata) { @unlink($mfile); }
868b158d625SSteven Danz    }
8693d1f9ec3SMichael Klier    // purge meta data
8703d1f9ec3SMichael Klier    p_purge_metadata($id);
871f3f0262cSandi    $del = true;
8723ce054b3Sandi    // autoset summary on deletion
8733ce054b3Sandi    if(empty($summary)) $summary = $lang['deleted'];
87453d6ccfeSandi    // remove empty namespaces
875cc7d0c94SBen Coburn    io_sweepNS($id, 'datadir');
876cc7d0c94SBen Coburn    io_sweepNS($id, 'mediadir');
877f3f0262cSandi  }else{
878cc7d0c94SBen Coburn    // save file (namespace dir is created in io_writeWikiPage)
879cc7d0c94SBen Coburn    io_writeWikiPage($file, $text, $id);
88046844156SBen Coburn    // pre-save the revision, to keep the attic in sync
88146844156SBen Coburn    $newRev = saveOldRevision($id);
882f3f0262cSandi    $del = false;
883f3f0262cSandi  }
884f3f0262cSandi
88571726d78SBen Coburn  // select changelog line type
88671726d78SBen Coburn  $extra = '';
887ebf1501fSBen Coburn  $type = DOKU_CHANGE_TYPE_EDIT;
88871726d78SBen Coburn  if ($wasReverted) {
889ebf1501fSBen Coburn    $type = DOKU_CHANGE_TYPE_REVERT;
89071726d78SBen Coburn    $extra = $REV;
89171726d78SBen Coburn  }
892ebf1501fSBen Coburn  else if ($wasCreated) { $type = DOKU_CHANGE_TYPE_CREATE; }
893ebf1501fSBen Coburn  else if ($wasRemoved) { $type = DOKU_CHANGE_TYPE_DELETE; }
894ebf1501fSBen Coburn  else if ($minor && $conf['useacl'] && $_SERVER['REMOTE_USER']) { $type = DOKU_CHANGE_TYPE_MINOR_EDIT; } //minor edits only for logged in users
89571726d78SBen Coburn
896e45b34cdSBen Coburn  addLogEntry($newRev, $id, $type, $summary, $extra);
89726a0801fSAndreas Gohr  // send notify mails
89890033e9dSAndreas Gohr  notify($id,'admin',$old,$summary,$minor);
89990033e9dSAndreas Gohr  notify($id,'subscribers',$old,$summary,$minor);
900f3f0262cSandi
901ce6b63d9Schris  // update the purgefile (timestamp of the last time anything within the wiki was changed)
90298407a7aSandi  io_saveFile($conf['cachedir'].'/purgefile',time());
903f3f0262cSandi}
904f3f0262cSandi
905f3f0262cSandi/**
906f3f0262cSandi * moves the current version to the attic and returns its
907f3f0262cSandi * revision date
90815fae107Sandi *
90915fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
910f3f0262cSandi */
911f3f0262cSandifunction saveOldRevision($id){
912f3f0262cSandi  global $conf;
913f3f0262cSandi  $oldf = wikiFN($id);
914f3f0262cSandi  if(!@file_exists($oldf)) return '';
915f3f0262cSandi  $date = filemtime($oldf);
916f3f0262cSandi  $newf = wikiFN($id,$date);
917cc7d0c94SBen Coburn  io_writeWikiPage($newf, rawWiki($id), $id, $date);
918f3f0262cSandi  return $date;
919f3f0262cSandi}
920f3f0262cSandi
921f3f0262cSandi/**
92226a0801fSAndreas Gohr * Sends a notify mail on page change
92326a0801fSAndreas Gohr *
92426a0801fSAndreas Gohr * @param  string  $id       The changed page
92526a0801fSAndreas Gohr * @param  string  $who      Who to notify (admin|subscribers)
92626a0801fSAndreas Gohr * @param  int     $rev      Old page revision
92726a0801fSAndreas Gohr * @param  string  $summary  What changed
92890033e9dSAndreas Gohr * @param  boolean $minor    Is this a minor edit?
92902a498e7Schris * @param  array   $replace  Additional string substitutions, @KEY@ to be replaced by value
93015fae107Sandi *
93115fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
932f3f0262cSandi */
93302a498e7Schrisfunction notify($id,$who,$rev='',$summary='',$minor=false,$replace=array()){
934f3f0262cSandi  global $lang;
935f3f0262cSandi  global $conf;
93630d7d718SMike Frysinger  global $INFO;
937b158d625SSteven Danz
93826a0801fSAndreas Gohr  // decide if there is something to do
93926a0801fSAndreas Gohr  if($who == 'admin'){
94026a0801fSAndreas Gohr    if(empty($conf['notify'])) return; //notify enabled?
941f3f0262cSandi    $text = rawLocale('mailtext');
94226a0801fSAndreas Gohr    $to   = $conf['notify'];
94326a0801fSAndreas Gohr    $bcc  = '';
94426a0801fSAndreas Gohr  }elseif($who == 'subscribers'){
94526a0801fSAndreas Gohr    if(!$conf['subscribers']) return; //subscribers enabled?
94690033e9dSAndreas Gohr    if($conf['useacl'] && $_SERVER['REMOTE_USER'] && $minor) return; //skip minors
94726a0801fSAndreas Gohr    $bcc  = subscriber_addresslist($id);
94826a0801fSAndreas Gohr    if(empty($bcc)) return;
94926a0801fSAndreas Gohr    $to   = '';
95026a0801fSAndreas Gohr    $text = rawLocale('subscribermail');
951a06e4bdbSSebastian Harl  }elseif($who == 'register'){
952a06e4bdbSSebastian Harl    if(empty($conf['registernotify'])) return;
953a06e4bdbSSebastian Harl    $text = rawLocale('registermail');
954a06e4bdbSSebastian Harl    $to   = $conf['registernotify'];
955a06e4bdbSSebastian Harl    $bcc  = '';
95626a0801fSAndreas Gohr  }else{
95726a0801fSAndreas Gohr    return; //just to be safe
95826a0801fSAndreas Gohr  }
95926a0801fSAndreas Gohr
96063211f61SGlen Harris  $ip   = clientIP();
961e656dcd4SAndreas Gohr  $text = str_replace('@DATE@',strftime($conf['dformat']),$text);
962f3f0262cSandi  $text = str_replace('@BROWSER@',$_SERVER['HTTP_USER_AGENT'],$text);
96363211f61SGlen Harris  $text = str_replace('@IPADDRESS@',$ip,$text);
96463211f61SGlen Harris  $text = str_replace('@HOSTNAME@',gethostsbyaddrs($ip),$text);
965c9321d91SAndreas Gohr  $text = str_replace('@NEWPAGE@',wl($id,'',true,'&'),$text);
96626a0801fSAndreas Gohr  $text = str_replace('@PAGE@',$id,$text);
96726a0801fSAndreas Gohr  $text = str_replace('@TITLE@',$conf['title'],$text);
968ed7b5f09Sandi  $text = str_replace('@DOKUWIKIURL@',DOKU_URL,$text);
969f3f0262cSandi  $text = str_replace('@SUMMARY@',$summary,$text);
9707a82afdcSandi  $text = str_replace('@USER@',$_SERVER['REMOTE_USER'],$text);
971f3f0262cSandi
97202a498e7Schris  foreach ($replace as $key => $substitution) {
97302a498e7Schris    $text = str_replace('@'.strtoupper($key).'@',$substitution, $text);
97402a498e7Schris  }
97502a498e7Schris
976a06e4bdbSSebastian Harl  if($who == 'register'){
977a06e4bdbSSebastian Harl    $subject = $lang['mail_new_user'].' '.$summary;
978a06e4bdbSSebastian Harl  }elseif($rev){
979f3f0262cSandi    $subject = $lang['mail_changed'].' '.$id;
980c9321d91SAndreas Gohr    $text = str_replace('@OLDPAGE@',wl($id,"rev=$rev",true,'&'),$text);
981ccdfa6c0SAndreas Gohr    require_once(DOKU_INC.'inc/DifferenceEngine.php');
982f3f0262cSandi    $df  = new Diff(split("\n",rawWiki($id,$rev)),
983f3f0262cSandi                    split("\n",rawWiki($id)));
984f3f0262cSandi    $dformat = new UnifiedDiffFormatter();
985f3f0262cSandi    $diff    = $dformat->format($df);
986f3f0262cSandi  }else{
987f3f0262cSandi    $subject=$lang['mail_newpage'].' '.$id;
988f3f0262cSandi    $text = str_replace('@OLDPAGE@','none',$text);
989f3f0262cSandi    $diff = rawWiki($id);
990f3f0262cSandi  }
991f3f0262cSandi  $text = str_replace('@DIFF@',$diff,$text);
992241f3a36Sandi  $subject = '['.$conf['title'].'] '.$subject;
993f3f0262cSandi
99430d7d718SMike Frysinger  $from = $conf['mailfrom'];
99530d7d718SMike Frysinger  $from = str_replace('@USER@',$_SERVER['REMOTE_USER'],$from);
99630d7d718SMike Frysinger  $from = str_replace('@NAME@',$INFO['userinfo']['name'],$from);
99730d7d718SMike Frysinger  $from = str_replace('@MAIL@',$INFO['userinfo']['mail'],$from);
99830d7d718SMike Frysinger
99930d7d718SMike Frysinger  mail_send($to,$subject,$text,$from,'',$bcc);
1000f3f0262cSandi}
1001f3f0262cSandi
100215fae107Sandi/**
100371f7bde7SAndreas Gohr * extracts the query from a search engine referrer
100415fae107Sandi *
100515fae107Sandi * @author Andreas Gohr <andi@splitbrain.org>
100671f7bde7SAndreas Gohr * @author Todd Augsburger <todd@rollerorgans.com>
1007f3f0262cSandi */
1008f3f0262cSandifunction getGoogleQuery(){
1009f3f0262cSandi  $url = parse_url($_SERVER['HTTP_REFERER']);
10105c3f206fSandi  if(!$url) return '';
1011f3f0262cSandi
1012f3f0262cSandi  $query = array();
1013f3f0262cSandi  parse_str($url['query'],$query);
101471f7bde7SAndreas Gohr  if(isset($query['q']))
1015f93b3b50SAndreas Gohr    $q = $query['q'];        // google, live/msn, aol, ask, altavista, alltheweb, gigablast
101671f7bde7SAndreas Gohr  elseif(isset($query['p']))
1017f93b3b50SAndreas Gohr    $q = $query['p'];        // yahoo
101871f7bde7SAndreas Gohr  elseif(isset($query['query']))
1019f93b3b50SAndreas Gohr    $q = $query['query'];    // lycos, netscape, clusty, hotbot
102071f7bde7SAndreas Gohr  elseif(preg_match("#a9\.com#i",$url['host'])) // a9
1021f93b3b50SAndreas Gohr    $q = urldecode(ltrim($url['path'],'/'));
1022f3f0262cSandi
1023f93b3b50SAndreas Gohr  if(!$q) return '';
10246531ab03SAndreas Gohr  $q = preg_split('/[\s\'"\\\\`()\]\[?:!\.{};,#+*<>\\/]+/',$q,-1,PREG_SPLIT_NO_EMPTY);
1025f93b3b50SAndreas Gohr  return $q;
1026f3f0262cSandi}
1027f3f0262cSandi
1028f3f0262cSandi/**
102915fae107Sandi * Try to set correct locale
103015fae107Sandi *
1031095bfd5cSandi * @deprecated No longer used
103215fae107Sandi * @author     Andreas Gohr <andi@splitbrain.org>
1033f3f0262cSandi */
1034f3f0262cSandifunction setCorrectLocale(){
1035f3f0262cSandi  global $conf;
1036f3f0262cSandi  global $lang;
1037f3f0262cSandi
1038f3f0262cSandi  $enc = strtoupper($lang['encoding']);
1039f3f0262cSandi  foreach ($lang['locales'] as $loc){
1040f3f0262cSandi    //try locale
1041f3f0262cSandi    if(@setlocale(LC_ALL,$loc)) return;
1042f3f0262cSandi    //try loceale with encoding
1043f3f0262cSandi    if(@setlocale(LC_ALL,"$loc.$enc")) return;
1044f3f0262cSandi  }
1045f3f0262cSandi  //still here? try to set from environment
1046f3f0262cSandi  @setlocale(LC_ALL,"");
1047f3f0262cSandi}
1048f3f0262cSandi
1049f3f0262cSandi/**
1050f3f0262cSandi * Return the human readable size of a file
1051f3f0262cSandi *
1052f3f0262cSandi * @param       int    $size   A file size
1053f3f0262cSandi * @param       int    $dec    A number of decimal places
1054f3f0262cSandi * @author      Martin Benjamin <b.martin@cybernet.ch>
1055f3f0262cSandi * @author      Aidan Lister <aidan@php.net>
1056f3f0262cSandi * @version     1.0.0
1057f3f0262cSandi */
1058f31d5b73Sandifunction filesize_h($size, $dec = 1){
1059f3f0262cSandi  $sizes = array('B', 'KB', 'MB', 'GB');
1060f3f0262cSandi  $count = count($sizes);
1061f3f0262cSandi  $i = 0;
1062f3f0262cSandi
1063f3f0262cSandi  while ($size >= 1024 && ($i < $count - 1)) {
1064f3f0262cSandi    $size /= 1024;
1065f3f0262cSandi    $i++;
1066f3f0262cSandi  }
1067f3f0262cSandi
1068f3f0262cSandi  return round($size, $dec) . ' ' . $sizes[$i];
1069f3f0262cSandi}
1070f3f0262cSandi
107115fae107Sandi/**
107200a7b5adSEsther Brunner * return an obfuscated email address in line with $conf['mailguard'] setting
107300a7b5adSEsther Brunner *
107400a7b5adSEsther Brunner * @author Harry Fuecks <hfuecks@gmail.com>
107500a7b5adSEsther Brunner * @author Christopher Smith <chris@jalakai.co.uk>
107600a7b5adSEsther Brunner */
107700a7b5adSEsther Brunnerfunction obfuscate($email) {
107800a7b5adSEsther Brunner  global $conf;
107900a7b5adSEsther Brunner
108000a7b5adSEsther Brunner  switch ($conf['mailguard']) {
108100a7b5adSEsther Brunner    case 'visible' :
108200a7b5adSEsther Brunner      $obfuscate = array('@' => ' [at] ', '.' => ' [dot] ', '-' => ' [dash] ');
108300a7b5adSEsther Brunner      return strtr($email, $obfuscate);
108400a7b5adSEsther Brunner
108500a7b5adSEsther Brunner    case 'hex' :
108600a7b5adSEsther Brunner      $encode = '';
108700a7b5adSEsther Brunner      for ($x=0; $x < strlen($email); $x++) $encode .= '&#x' . bin2hex($email{$x}).';';
108800a7b5adSEsther Brunner      return $encode;
108900a7b5adSEsther Brunner
109000a7b5adSEsther Brunner    case 'none' :
109100a7b5adSEsther Brunner    default :
109200a7b5adSEsther Brunner      return $email;
109300a7b5adSEsther Brunner  }
109400a7b5adSEsther Brunner}
109500a7b5adSEsther Brunner
109600a7b5adSEsther Brunner/**
109752b0dd67SGuy Brand * Let us know if a user is tracking a page or a namespace
1098b158d625SSteven Danz *
10991380fc45SAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
1100b158d625SSteven Danz */
110152b0dd67SGuy Brandfunction is_subscribed($id,$uid,$ns=false){
110252b0dd67SGuy Brand  if(!$ns) {
11031380fc45SAndreas Gohr    $file=metaFN($id,'.mlist');
110452b0dd67SGuy Brand  } else {
110552b0dd67SGuy Brand    if(!getNS($id)) {
110652b0dd67SGuy Brand      $file = metaFN(getNS($id),'.mlist');
110752b0dd67SGuy Brand    } else {
110852b0dd67SGuy Brand      $file = metaFN(getNS($id),'/.mlist');
110952b0dd67SGuy Brand    }
111052b0dd67SGuy Brand  }
11111380fc45SAndreas Gohr  if (@file_exists($file)) {
1112b158d625SSteven Danz    $mlist = file($file);
11131380fc45SAndreas Gohr    $pos = array_search($uid."\n",$mlist);
11141380fc45SAndreas Gohr    return is_int($pos);
1115b158d625SSteven Danz  }
11161380fc45SAndreas Gohr
1117b158d625SSteven Danz  return false;
1118b158d625SSteven Danz}
1119340756e4Sandi
1120f9eb5648Ssteven-danz/**
1121f9eb5648Ssteven-danz * Return a string with the email addresses of all the
1122f9eb5648Ssteven-danz * users subscribed to a page
1123f9eb5648Ssteven-danz *
112426a0801fSAndreas Gohr * @author Steven Danz <steven-danz@kc.rr.com>
1125f9eb5648Ssteven-danz */
1126f9eb5648Ssteven-danzfunction subscriber_addresslist($id){
1127f9eb5648Ssteven-danz  global $conf;
1128cd52f92dSchris  global $auth;
1129f9eb5648Ssteven-danz
113012cb3a51STom N Harris  if (!$conf['subscribers']) return '';
1131f9eb5648Ssteven-danz
113212cb3a51STom N Harris  $users = array();
113312cb3a51STom N Harris  $emails = array();
113426a0801fSAndreas Gohr
113552b0dd67SGuy Brand  // load the page mlist file content
1136f9eb5648Ssteven-danz  $mlist = array();
1137f9eb5648Ssteven-danz  $file=metaFN($id,'.mlist');
1138d8186216SBen Coburn  if (@file_exists($file)) {
1139f9eb5648Ssteven-danz    $mlist = file($file);
1140f9eb5648Ssteven-danz    foreach ($mlist as $who) {
1141f9eb5648Ssteven-danz      $who = rtrim($who);
114212cb3a51STom N Harris      $users[$who] = true;
1143f9eb5648Ssteven-danz    }
1144f9eb5648Ssteven-danz  }
1145f9eb5648Ssteven-danz
114652b0dd67SGuy Brand  // load also the namespace mlist file content
114712cb3a51STom N Harris  $ns = getNS($id);
114812cb3a51STom N Harris  while ($ns) {
114912cb3a51STom N Harris    $nsfile = metaFN($ns,'/.mlist');
115052b0dd67SGuy Brand    if (@file_exists($nsfile)) {
115152b0dd67SGuy Brand      $mlist = file($nsfile);
115252b0dd67SGuy Brand      foreach ($mlist as $who) {
115352b0dd67SGuy Brand        $who = rtrim($who);
115412cb3a51STom N Harris        $users[$who] = true;
115512cb3a51STom N Harris      }
115612cb3a51STom N Harris    }
115712cb3a51STom N Harris    $ns = getNS($ns);
115812cb3a51STom N Harris  }
115912cb3a51STom N Harris  // root namespace
116012cb3a51STom N Harris  $nsfile = metaFN('','.mlist');
116112cb3a51STom N Harris  if (@file_exists($nsfile)) {
116212cb3a51STom N Harris    $mlist = file($nsfile);
116312cb3a51STom N Harris    foreach ($mlist as $who) {
116412cb3a51STom N Harris      $who = rtrim($who);
116512cb3a51STom N Harris      $users[$who] = true;
116612cb3a51STom N Harris    }
116712cb3a51STom N Harris  }
116812cb3a51STom N Harris  if(!empty($users)) {
116912cb3a51STom N Harris    foreach (array_keys($users) as $who) {
117052b0dd67SGuy Brand      $info = $auth->getUserData($who);
117152b0dd67SGuy Brand      if($info === false) continue;
117252b0dd67SGuy Brand      $level = auth_aclcheck($id,$who,$info['grps']);
117352b0dd67SGuy Brand      if ($level >= AUTH_READ) {
117452b0dd67SGuy Brand        if (strcasecmp($info['mail'],$conf['notify']) != 0) {
117512cb3a51STom N Harris          $emails[] = $info['mail'];
117652b0dd67SGuy Brand        }
117752b0dd67SGuy Brand      }
117852b0dd67SGuy Brand    }
117952b0dd67SGuy Brand  }
118052b0dd67SGuy Brand
118112cb3a51STom N Harris  return implode(',',$emails);
1182f9eb5648Ssteven-danz}
1183f9eb5648Ssteven-danz
118489541d4bSAndreas Gohr/**
118589541d4bSAndreas Gohr * Removes quoting backslashes
118689541d4bSAndreas Gohr *
118789541d4bSAndreas Gohr * @author Andreas Gohr <andi@splitbrain.org>
118889541d4bSAndreas Gohr */
118989541d4bSAndreas Gohrfunction unslash($string,$char="'"){
119089541d4bSAndreas Gohr  return str_replace('\\'.$char,$char,$string);
119189541d4bSAndreas Gohr}
119289541d4bSAndreas Gohr
119373038c47SAndreas Gohr/**
119473038c47SAndreas Gohr * Convert php.ini shorthands to byte
119573038c47SAndreas Gohr *
119673038c47SAndreas Gohr * @author <gilthans dot NO dot SPAM at gmail dot com>
119773038c47SAndreas Gohr * @link   http://de3.php.net/manual/en/ini.core.php#79564
119873038c47SAndreas Gohr */
119973038c47SAndreas Gohrfunction php_to_byte($v){
120073038c47SAndreas Gohr    $l = substr($v, -1);
120173038c47SAndreas Gohr    $ret = substr($v, 0, -1);
120273038c47SAndreas Gohr    switch(strtoupper($l)){
120373038c47SAndreas Gohr        case 'P':
120473038c47SAndreas Gohr            $ret *= 1024;
120573038c47SAndreas Gohr        case 'T':
120673038c47SAndreas Gohr            $ret *= 1024;
120773038c47SAndreas Gohr        case 'G':
120873038c47SAndreas Gohr            $ret *= 1024;
120973038c47SAndreas Gohr        case 'M':
121073038c47SAndreas Gohr            $ret *= 1024;
121173038c47SAndreas Gohr        case 'K':
121273038c47SAndreas Gohr            $ret *= 1024;
121373038c47SAndreas Gohr        break;
121473038c47SAndreas Gohr    }
121573038c47SAndreas Gohr    return $ret;
121673038c47SAndreas Gohr}
121773038c47SAndreas Gohr
1218546d3a99SAndreas Gohr/**
1219546d3a99SAndreas Gohr * Wrapper around preg_quote adding the default delimiter
1220546d3a99SAndreas Gohr */
1221546d3a99SAndreas Gohrfunction preg_quote_cb($string){
1222546d3a99SAndreas Gohr    return preg_quote($string,'/');
1223546d3a99SAndreas Gohr}
122473038c47SAndreas Gohr
1225bd2f6c2fSAndreas Gohr/**
1226bd2f6c2fSAndreas Gohr * Shorten a given string by removing data from the middle
1227bd2f6c2fSAndreas Gohr *
1228bd2f6c2fSAndreas Gohr * You can give the string in two parts, teh first part $keep
1229bd2f6c2fSAndreas Gohr * will never be shortened. The second part $short will be cut
1230bd2f6c2fSAndreas Gohr * in the middle to shorten but only if at least $min chars are
1231bd2f6c2fSAndreas Gohr * left to display it. Otherwise it will be left off.
1232bd2f6c2fSAndreas Gohr *
1233bd2f6c2fSAndreas Gohr * @param string $keep   the part to keep
1234bd2f6c2fSAndreas Gohr * @param string $short  the part to shorten
1235bd2f6c2fSAndreas Gohr * @param int    $max    maximum chars you want for the whole string
1236bd2f6c2fSAndreas Gohr * @param int    $min    minimum number of chars to have left for middle shortening
1237bd2f6c2fSAndreas Gohr * @param string $char   the shortening character to use
1238bd2f6c2fSAndreas Gohr */
1239bd2f6c2fSAndreas Gohrfunction shorten($keep,$short,$max,$min=9,$char='⌇'){
1240bd2f6c2fSAndreas Gohr    $max = $max - utf8_strlen($keep);
1241bd2f6c2fSAndreas Gohr	 if($max < $min) return $keep;
1242bd2f6c2fSAndreas Gohr    $len = utf8_strlen($short);
1243bd2f6c2fSAndreas Gohr    if($len <= $max) return $keep.$short;
1244bd2f6c2fSAndreas Gohr    $half = floor($max/2);
1245bd2f6c2fSAndreas Gohr    return $keep.utf8_substr($short,0,$half-1).$char.utf8_substr($short,$len-$half);
1246bd2f6c2fSAndreas Gohr}
1247bd2f6c2fSAndreas Gohr
1248340756e4Sandi//Setup VIM: ex: et ts=2 enc=utf-8 :
1249