<?php if (!defined('PmWiki')) exit();
/*  Copyright 2005 Patrick R. Michaud (pmichaud@pobox.com)
    This file is searchterms.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.

    This script enables the access to a mysqldatabase.
    To use this script, simply place it in the cookbook/ directory and add the following lines
    $odbcPMWiki_dsn      = '<DSN>';
    $odbcPMWiki_Username = '<user>';
    $odbcPMWiki_Password = '<userpassword>';
    $odbcPMWiki_TableFmt = '';
    include_once('cookbook/odbcpmwiki.php');

    to a local customization file.

    This script is based on ideas by JamesDavis, but has
    been rewritten to work wiht PmWiki v2.

    Version 0.2
      change Markup vom _begin to inline

*/

Markup('odbcPmWiki','inline','/\(:odbcPmWiki *(.+):\)/e',"odbcPmWiki('\$1')");


function odbcPMWiki($SQL) {
  global $odbcPMWiki_dsn, $odbcPMWiki_Username, $odbcPMWiki_Password, $odbcPMWiki_TableFmt;
  global $action;
  global $FarmD;
  $ExtraErrMsg = "Please contact the administrator of this wiki.";
  if (!isset($odbcPMWiki_dsn))
    return "<font color='red'><strong>Error:</strong> \$odbcPMWiki_dsn not defined. $ExtraErrMsg</font>";
  if (!isset($odbcPMWiki_TableFmt))
    $odbcPMWiki_TableFmt = "border='1'";
  if (!isset($odbcPMWiki_Username))
    return "<font color='red'><strong>Error:</strong> \$odbcPMWiki_Username not defined. $ExtraErrMsg</font>";
  if (!isset($odbcPMWiki_Password))
    return "<font color='red'><strong>Error:</strong> \$odbcPMWiki_Password not defined. $ExtraErrMsg</font>";
  if (!$dbh = odbc_connect ($odbcPMWiki_dsn, $odbcPMWiki_Username, $odbcPMWiki_Password))
    return "<font color='red'><strong>Connection Error:</strong> ".odbc_error()." $ExtraErrMsg</font>";;
  if($result = odbc_exec($dbh,$SQL)) {
    $resultStr = "<table $odbcPMWiki_TableFmt><tr>";
    for ($i = 1; $i <= odbc_num_fields($result); $i++) {
      $resultStr .= "<th>".odbc_field_name($result, $i)."</th>";
    }
    $resultStr .= "</tr>";
    while(odbc_fetch_row($result)) {
      $resultStr .= "<tr>";
      for($i=1;$i<=odbc_num_fields($result);$i++)
      {
        $resultStr .= "<td>".odbc_result($result,$i)."</td>";
      }
      $resultStr .= "</tr>";
    }
    $resultStr .= "</table>";
  }
  else
    $resultStr = "<font color='red'><strong>SQL Error:</strong> ".odbc_error()."</font>";
  odbc_close($dbh);
  return $resultStr;
}