<?php if (!defined('PmWiki')) exit();
/**
  DoTheRightThing link redirector for PmWiki
  Written by (c) Petko Yotov 2009-2023 pmwiki.org/Petko

  This text is written for PmWiki; 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. See pmwiki.php for full details
  and lack of warranty.
*/
# Version date
$RecipeInfo['DoTheRightThing']['Version'] = '20230622';

SDVA($DTRT_links, array(
  'g'   => 'https://www.google.com/search?q=$1',
  'w'   => 'https://en.wikipedia.org/wiki/Special:Search?go=1&search=$1',
  '_default'   => 'https://www.google.com/search?q=$1',
));


SDVA($HandleActions, array('dtrt'=>'HandleDTRT'));
SDVA($HTMLHeaderFmt, array('DTRT-opensearch'=>"<link rel='search' type='application/opensearchdescription+xml'
  title='DTRT for this page' href='{\$PageUrl}?action=dtrt&amp;q=opensearch'/>"));

function HandleDTRT($pagename, $auth="read") {
  global $DTRT_links, $WikiTitle, $EnableRedirect, $Charset;

  #will ask for password if needed
  $page = RetrieveAuthPage($pagename,$auth,1, READPAGE_CURRENT);

  if (preg_match_all("/^\\s*(\\S*)\\s*:[^\\S\n]+(\\S*)/m", $page['text'],
    $match, PREG_SET_ORDER)) {
    foreach($match as $m)
    {
      $tmp = explode(',', $m[1]);
      foreach($tmp as $key)
        $DTRT_links[$key] = $m[2];
    }
  }
  list($k, $q) = explode(' ', urldecode(stripmagic($_GET['q'])), 2);
  
  if($k == "opensearch") {
    $url = PageVar($pagename, '$PageUrl');
    $xmltpl = <<<EOF
<?xml version="1.0" encoding="UTF-8"?>
<OpenSearchDescription xmlns="http://a9.com/-/spec/opensearch/1.1/">
  <ShortName>DTRT {$WikiTitle}</ShortName>
  <Description>Do the right thing custom search</Description>
  <Url type="text/html" method="get" template="{$url}?action=dtrt&amp;q={searchTerms}"></Url>
  <InputEncoding>UTF-8</InputEncoding>
</OpenSearchDescription>
EOF;
    header("Content-type: application/opensearchdescription+xml");
    echo $xmltpl;
    exit;
  }
  elseif ($k == "setdefault") {
    $q = trim($q);
    if($q) {
      setcookie('DTRT_default', $q);
      $GLOBALS['MessagesFmt'][] = "Default redirection set to '$q'";
    }
    else {
      setcookie ("DTRT_default", "", time() - 3600);
      $GLOBALS['MessagesFmt'][] = "Default redirection reset";
   }
   return HandleBrowse($pagename, 'read');
  }
  
  if(!isset($DTRT_links[$k]) || $DTRT_links[$k] == 'null' || $DTRT_links[$k] == '' ) {
    $rxfound = 0;
    foreach ($DTRT_links as $rx=>$u) {
      if (!preg_match('/^\\/.*\\/i?$/', $rx)) continue;
      if (! preg_match($rx, $k)) continue;
      $rxfound = 1;
      $k = $rx; # no 'break', later defs override earlier ones
    }
    if(!$rxfound) {
      $qd = @$_COOKIE["DTRT_default"];
      if ($qd && @$DTRT_links[$qd]) {
        $k = $qd;
      }
      else $k = '_default';
      $q = stripmagic($_GET['q']);
    }
  }
  $where = $DTRT_links[$k];
  if(strpos($where, 'function:')===0 ) {
    $func = str_replace('function:', "DTRT_", $where);
    if(! function_exists($func))
      Abort("User function '$func' does not exist.");
    $url = $func($q);
  }
  else {
     $url = str_replace('$1', rawurlencode($q), $where);
     $url = str_replace('$2', rawurlencode(utf8_decode($q)), $url);
  }
  if(!$url) Abort("Bad configuration, where='$where', key='$k'; query='$q'.");

  if($url{0} == ',') {
    $url = substr($url, 1);
    $EnableRedirect = 0;
  }
  if(strpos($url, '&&')) {
    $opt = ParseArgs(str_replace('&&',' ', $url),'(?>(\\w+)[=])');
    $frm = "<!DOCTYPE html><html>
    <head><meta http-equiv='Content-Type' content='text/html; charset=$Charset'/></head>
    <body>
    Redirecting...
    <form name='dtrt' action='{$opt[''][0]}' method='post' rel='noreferrer'>";
    foreach($opt as $k=>$v) {
      if($k == '' || $k == '#') continue;
      $v = PHSC(urldecode($v), ENT_QUOTES);
      $frm .= "<input type='hidden' name='$k' value='$v'/>";
    }
    $frm .= "<input type='submit'/></form>";
    if(IsEnabled($EnableRedirect, 1))
      $frm .= "<script>
    document.dtrt.submit();
    </script>";
    $frm .= "</body></html>";
    die($frm);
  }
  $url = PUE($url);
  Redirect($pagename, $url);
}