#include <infodrom.style>
#include <linx.style>
#include <db.style>

<page title="Infodrom Linx" stylesheet="linx.css">
<linxtop>

<h3>Lookup of <?
  $keywords = $_POST[keywords];
  $category = $_REQUEST[category];

  if (strlen ($keywords)) { echo ($keywords); }
  if (strlen ($keywords) && strlen ($category)) { echo (" and "); }
  if (strlen ($category)) { echo ($category); }
?></h3>

<?
  $query = "SELECT url,subject,category FROM links";

  $condition = '';
  if (strlen ($keywords)) {
    $keys = explode (" ", $keywords);
    $keys_and = array();
    $keys_not = array();
    $keys_or = array();

    # Investigate all given keywords
    for ($i=0; $i < count ($keys); $i++) {
      if (substr ($keys[$i], 0, 1) == "-") {
        $keys_not[] = substr ($keys[$i], 1, strlen ($keys[$i])-1);
      } elseif (substr ($keys[$i], 0, 1) == "+") {
        $keys_and[] = substr ($keys[$i], 1, strlen ($keys[$i])-1);
      } else {
        $keys_or[] = $keys[$i];
      }
    }

    # Process all OR-keywords
    #
    if (count ($keys_or) > 1) {
      $condition .= "( ";
    }
    for ($i=0; $i < count ($keys_or); $i++) {
      if ($i > 0) {
        $condition .= "OR ";
      }
      $condition .= sprintf ("( category ~* '%s' OR keywords ~* '%s' OR subject ~* '%s' OR url ~* '%s' ) ",
			$keys_or[$i], $keys_or[$i], $keys_or[$i], $keys_or[$i]);
    }
    if (count ($keys_or) > 1) {
      $condition .= ") ";
    }

    # Process all AND-keywords
    #
    for ($i=0; $i < count ($keys_and); $i++) {
      if ($i > 0 || (count ($keys_or) > 0)) {
        $condition .= "AND ";
      }
      $condition .= sprintf ("( category ~* '%s' OR keywords ~* '%s' OR subject ~* '%s' OR url ~* '%s' ) ",
			$keys_and[$i], $keys_and[$i], $keys_and[$i], $keys_and[$i]);
    }

    # Process all NOT-keywords
    #
    if ((count ($keys_or) > 0) || (count ($keys_and) > 0)) {
      for ($i=0; $i < count ($keys_not); $i++) {
	$condition .= sprintf ("AND NOT ( category ~* '%s' OR keywords ~* '%s' OR subject ~* '%s' OR url ~* '%s' ) ",
			  $keys_not[$i], $keys_not[$i], $keys_not[$i], $keys_not[$i]);
      }
    }
  }

  if (strlen ($keywords) && strlen ($category)) { $condition .= " AND "; }
  if (strlen ($category)) {
    if (substr ($category, 0, 1) == "/") {
      $condition .= sprintf ("category = '%s'", $category);
    } else {
      $condition .= sprintf ("category ~* '%s'", $category);
    }
  }

  if (strlen($condition)) { $query .= " WHERE " . $condition; }
  $query .= " ORDER BY category,subject";
?>

<linx "$query">

<linxbot>
</page>

# Local variables:
# mode: indented-text
# mode: auto-fill
# end:
