<?php if (!defined('PmWiki')) exit();
/*  Copyright 2004/2005 Nils Knappmeier
    Copyright 2004 Patrick R. Michaud (pmichaud@pobox.com)

    This file is addlink.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 2 of the License, or
    (at your option) any later version.  

    Addlink.php creates an "add link" bookmarklet that makes it easy
    to bookmark pages you find while surfing the web into a wiki
    page.  This script was originally authored for PmWiki by Nils 
    Knappmeier, and updated for PmWiki 2 by Patrick R. Michaud on
    2004-11-30. Later updated on 2007-08-06 by Michael Shanley for
	more options.
 
    This new version prompts for a link text before adding the link 
    to the target page
*/

# VERSION INFO
	$RecipeInfo['AddLink2']['Version'] = '2007-08-06';

# VARIABLES
	# Add links to the bottom instead of the top?
	SDV($EnableAddLinkToEnd,0);
	# What text should be added immediate before and after each new link?
	# The default is a newline before and after.
	SDV($AddLinkPrefixText,"\n");
	SDV($AddLinkSuffixText,"\n");
	

# add the (:addlink [PageName]:) markup and HandleAddLink actions.
Markup('addlink', 'inline', '/\\(:addlink\\s*(.*?):\\)/e', 
  "Keep(CreateBookmarklet(\$pagename,'$1'))");

# function to create the bookmarklet
function CreateBookmarklet($pagename, $linkpage) {
  if ($linkpage) $pagename = MakePageName($pagename, $linkpage);
  return FmtPageName("<a href=\"javascript:var linktext=window.prompt('Text:'); if (linktext!=null) { document.location.href='\$PageUrl?action=addlink&url='+encodeURIComponent(document.location.href)+'&linktext='+encodeURIComponent(linktext); }\">+=$pagename</a>", $pagename);
}


if ($action=='addlink') {
   $action = 'edit';
   $OldEditHandler = $HandleActions['edit'];
   $HandleActions['edit'] = 'HandleAddLink';
   
}

# function to handle ?action=addlink (prepends the url to the page and
# then passes control to the edit function).
function HandleAddLink($pagename) {
  global $OldEditHandler, $EnableAddLinkToEnd, $AddLinkPrefixText, $AddLinkSuffixText;
  Lock(2);
  $page = RetrieveAuthPage($pagename, 'edit');
  if (!$page) Abort("?cannot edit $pagename");
  $text = $page['text'];
  if (@$_REQUEST['url']) {
    if (@$_REQUEST['linktext']) {
      $newtext = "[[{$_REQUEST['linktext']} -> {$_REQUEST['url']}]]";
    } else {
      $newtext = $_REQUEST['url'];
    }
    if (IsEnabled($EnableAddLinkToEnd,0))
      $text .= $AddLinkPrefixText . "* $newtext" . $AddLinkSuffixText;
    else $text = $AddLinkPrefixText . "* $newtext" . $AddLinkSuffixText . $text;
  }
  $action = 'edit';
  $_POST['text'] = addslashes($text);
  $OldEditHandler($pagename);
}
 
?>