<?php if (!defined('PmWiki')) exit();
/*  Copyright 2006-2010 Petko Yotov http://5ko.fr

    This file is linktitles.php; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation; either version 3 of the License, or
    (at your option) any later version.

    This script allows you to adds titles to local wiki-page links.
    See http://www.pmwiki.org/wiki/Cookbook/LinkTitles for more information.
*/

$RecipeInfo['LinkTitles']['Version'] = '20101221';

if($VersionNum<=2002021) die("LinkTitles requires PmWiki 2.2.22, svn revision 2613, or newer.");

SDV($LinkTitleFmtSet, 0);
SDV($LinkTitleRegExp, '/\\(([^\\(\\)]*)\\)\\s*$/'); # $0 will be removed, $1 will be the title
SDV($EnableLinkTitleDefaultUrl, 1);
SDV($EnableLinkTitleDefaultPage, 1);

foreach(array('http:','https:','mailto:','ftp:','news:','gopher:','nap:', 'file:', '<:page>') as $m) {
  $OldLinkFunctions[$m] = $LinkFunctions[$m];
  $LinkFunctions[$m] = 'LinkTitles'; ; 
}

function LinkFmtAddTitle() {
  global $LinkTitleFmtSet;
  if($LinkTitleFmtSet) return;

  foreach(array('Self', 'Exists', 'Create') as $k)
    if(! strpos($GLOBALS["LinkPage{$k}Fmt"], "title=")) 
      $GLOBALS["LinkPage{$k}Fmt"] = preg_replace('/^<a /i', "$0title='\$LinkAlt' ", $GLOBALS["LinkPage{$k}Fmt"]);
   $GLOBALS["UrlLinkFmt"] = preg_replace('/^<a /i', "$0title='\$LinkAlt' ", $GLOBALS["UrlLinkFmt"]);
  $LinkTitleFmtSet = 1;
}

function LinkTitles($pagename,$imap,$path,$alt,$txt,$fmt=NULL) {
  global $IMap, $QueryFragPattern, $LinkTitleRegExp, $OldLinkFunctions, 
    $EnableLinkTitleDefaultUrl, $EnableLinkTitleDefaultPage;
  LinkFmtAddTitle();

  $fn = $OldLinkFunctions[$imap];

  # default title eg. in quotes has prioroty http://site/"some title"
  if($alt>'') return $fn($pagename,$imap,$path,$alt,$txt,$fmt);

  if(preg_match($LinkTitleRegExp, $txt, $mm) ) {
    $alt = $mm[1];
    $txt = preg_replace($LinkTitleRegExp, '', $txt);
  }
  else {
    if($imap != '<:page>' && $EnableLinkTitleDefaultUrl)
      $alt = PUE(str_replace('$1',$path,$IMap[$imap]));

    elseif($imap == '<:page>' && $EnableLinkTitleDefaultPage) {
      if(preg_match("/^\\s*([^#?]+)($QueryFragPattern)?$/",$path,$m)) {
        $alt = MakePageName($pagename, $m[1]);
      }
    }
  }
  return $fn($pagename,$imap,$path,$alt,$txt,$fmt);
}