<?
# PHP Wiki
# Copyright (C) 1999 John L. Jorgensen 
#
# This program is free software; 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 program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

###################################
# Configurable variables are found in pwiki/pwikicfg.phl
include ("../pwikicfg.phl");

###################################
# Locale info
include ("../locale/$locale");
###################################
# Set up the necessary automatic variables

$browserequest = $publicview ? "view" : "browse";
if (ereg("^/wiki-editors/",$SCRIPT_NAME)){
  $browserequest = "browse";
}

if (!($REQUEST_METHOD=="POST")){
  $request= $HTTP_GET_VARS["request"] ? $HTTP_GET_VARS["request"] : "$browserequest";
  $topic= $HTTP_GET_VARS["topic"] ? $HTTP_GET_VARS["topic"] : $PATH_INFO;
}
$db= ereg_replace(".+/", "", $SCRIPT_FILENAME);
$topic=ereg_replace("\.html$", "", $topic);
$topic= ereg_replace("^/","",$topic);
$topic= $topic ? $topic : "overview";
$topic= ereg_replace("/+",":",$topic);

if ( ($SERVER_PORT==80 && !($HTTPS)) ){
  $port="";
} else {
  $port=":$SERVER_PORT";
}
$http_prot= $HTTPS ? "https" : "http";
$scripturl="$SCRIPT_NAME";

$pretag=0;
$txtinclude=0;

include ("../dbaccess/$dbtype/global.phl");
include ("../dbaccess/$dbtype/infile.phl");

$dbase=dbconnect();

############################
# Functions

######
# main file parsing function
function parsefile ($type, $name, $db) {
  $text="";
  $fcontents=infile($type, $name, $db);
  if ($fcontents){
    $lineAry=split("\n",$fcontents);
    while (list(, $line) = each($lineAry)) {
      $line=$line."\n";
      $line=linetagparse($line);
      $line=sublinetagparse($line);
      $text.= $line;
    }
  }
  return $text;
}

######
# line tags parsed here
function linetagparse ($line) {
  global $pretag;
  static $ul=0;
  static $ol=0;

  # pre tag handling
  if ((ereg("^<PRE>",$line))&&($pretag==0)){
    $line=ereg_replace("^<PRE>","<pre>",$line);
    $pretag=1;
    $prejustset=1;
  } else {
    $prejustset=0;
  }
  if ((ereg("^</PRE>",$line))&&($pretag==1)){
    $line=ereg_replace("^</PRE>","</pre>",$line);
    $pretag=0;
  }
  if ($pretag==0){

    # bullet list handling
    if (($ul>0)&&(!(($line[0]==" ")&&($line[1]==" ")&&($line[2]==" ")))){
        for ($i=0;$i<$ul;$i++){
          $line="</ul>".$line;
        }
        $ul=0;
      }
    if (ereg("^(   )+\* ",$line,$ulcnt)){
      $ulstrung="";
      $count=0;
      $foo=$line;
      $foo=ereg_replace("\*.*\n","",$foo);
      for ($i=1; $foo; $i++){
        $foo=ereg_replace("^   ", "", $foo);
        $count ++;
      }
      if ($count>$ul){
        for ($i=$ul;$i<$count;$i++){
          $ulstring.= "<ul>";
        }
        $ul=$count;
      }
      if ($count<$ul){
        for ($i=$count;$i<$ul;$i++){
        $ulstring.= "</ul>";
        }
        $ul=$count;
      }
      $line=ereg_replace("(^ +\* |\n)","",$line);
      $line="$ulstring<li> ".$line." </li>\n";
    }

    # numbered list handling
    if (($ol>0)&&(!(($line[0]==" ")&&($line[1]==" ")&&($line[2]==" ")))){
        for ($i=0;$i<$ol;$i++){
          $line="</ol>".$line;
        }
        $ol=0;
      }
    if (ereg("^(   )+# ",$line,$olcnt)){
      $olstring="";
      $count=0;
      $foo=$line;
      $foo=ereg_replace("#.*\n","",$foo);
      for ($i=1; $foo; $i++){
        $foo=ereg_replace("^   ", "", $foo);
        $count ++;
      }
      if ($count>$ol){
        for ($i=$ol;$i<$count;$i++){
          $olstring.= "<ol>";
        }
        $ol=$count;
      }
      if ($count<$ol){
        for ($i=$count;$i<$ol;$i++){
        $olstring.= "</ol>";
        }
        $ol=$count;
      }
      $line=ereg_replace("(^ +# |\n)","",$line);
      $line="$olstring<li> ".$line." </li>\n";
    }

    # paragraph tag
    if ($line=="\n"){
      $line="<p>\n";
      return $line;
    }
    # horizontal rule
    if (ereg("^-{4,}\n*$",$line)){
      $line="<hr>";
      return $line;
    }
    
  } else {
    # Proper handling of < inside a PRE area
    if ($prejustset==0){
      $line=ereg_replace ("<","&lt;",$line);
      $line=ereg_replace (">","&gt;",$line);
    }
  }
  return $line;
}

######
# sub-line tags parsed here
function sublinetagparse($line) {
  global $scripturl, $pretag, $autolinks, $textdir, $db, $txtfile, $REMOTE_USER, $request, $topic, $notextmsg, $areadir, $txtinclude, $extdir, $mixedcaps;
  if ($pretag==0){

    # autolinks. Autolinks are wiki.
    if ($autolinks==1){

      # Inline image link.
      $line=ereg_replace("(^| )((http|https|ftp|news|gopher)://[^[:blank:]\n<]+\.(gif|jpg|png))", "\\1<img src=\"\\2\">",$line);

      # url handling
      $line=ereg_replace("(^| )((http|https|ftp|news|gopher)://[^[:blank:]\n<]+)", "\\1<a href=\"\\2\">\\2</a>",$line);
      $line=ereg_replace("(^| )([[:alnum:]][-_\.[:alnum:]]+@[[:alnum:]][[:alnum:]\.-]+)", "\\1<a href=\"mailto:\\2\">\\2</a>", $line);

    }

    # percent variables
    $line=ereg_replace("%%", "%", $line);
    $line=ereg_replace("%gt%", "&gt;", $line);
    $line=ereg_replace("%lt%", "&lt;", $line);
    $line=ereg_replace("%amp%", "&amp;", $line);

    if ($autolinks==1){
      # percent links
      if (preg_match_all("|%(\w+[\w /'\.-]*)%|",$line,$link)){
        for ($i=0; $link[1][$i]; $i++) {
          $realfile=$link[1][$i];
          if ($ISO_8859_1=0) {
            $linkref=rawurlencode($realfile);
          }else{
            $linkref=$realfile;
          }
          $realfile=ereg_replace(" +","_",$realfile);
          $realfile=ereg_replace("/",":",$realfile);
          if (is_file("$textdir/$db/$realfile.txt")){
            $line=ereg_replace($link[0][$i],"<a href=\"$scripturl/$realfile\">".$link[1][$i]."</a>",$line);
          } else {
            $line=ereg_replace($link[0][$i],"<a href=\"$scripturl/".$realfile."\">?".$link[1][$i]."?</a>",$line);
          }
        }
      }
      # Extended percent links
      if (preg_match_all("|%(\w+[\w /'\.-]*)#(\w+[\w /'\.-]*)%|",$line,$link)){
        for ($i=0; $link[1][$i]; $i++) {
          $realfile=$link[2][$i];
          $alias=$link[1][$i];
          $realfile=ereg_replace(" ","_",$realfile);
          $realfile=ereg_replace("/",":",$realfile);
          if ($ISO_8859_1=0) {
            $linkref=rawurlencode($realfile);
          }else{
            $linkref=$realfile;
          }
          if (is_file("$textdir/$db/$realfile.txt")){
            $line=ereg_replace($link[0][$i],"<a href=\"$scripturl/$linkref\">".$alias."</a>",$line);
          } else {
            $line=ereg_replace($link[0][$i],"<a href=\"$scripturl/".$linkref."\">?".$alias."?</a>",$line);
          }
        }
      }
      # Mixed caps links
      if ($mixedcaps==1){
        if (preg_match_all("/[A-Z][a-z]+[A-Z][A-Za-z]+/",$line,$link)){
          for ($i=0; $link[0][$i]; $i++) {
            $realfile=$link[0][$i];
            if ($ISO_8859_1=0) {
              $linkref=rawurlencode($realfile);
            }else{
              $linkref=$realfile;
            }
            if (is_file("$textdir/$db/$realfile.txt")){
              $line=ereg_replace($link[0][$i],"<a href=\"$scripturl/$linkref\">".$linkref."</a>",$line);
            } else {
              $line=ereg_replace($link[0][$i],"<a href=\"$scripturl/".$linkref."\">?".$linkref."?</a>",$line);
            }
          }
        }
      }
    }

    # bold italic (__...__)
    $line=ereg_replace("(^| |\(|\[|\{)(__([^_]+)__)", "\\1<em><strong>\\3</strong></em>", $line);
    # bold (_..._)
    $line=ereg_replace("(^| |\(|\[|\{)(_([^_]+)_)", "\\1<strong>\\3</strong>", $line);
    # italic (*...*)
    $line=ereg_replace("(^| |\(|\[|\{)(\*([^*]+)\*)", "\\1<em>\\3</em>", $line);

    # <wiki *> handling
    if (preg_match_all('|<wiki (.*)>|U',$line,$match)){
      for ($i=0; $match[0][$i]; $i++){
        $cmd=ereg_replace("([[:alpha:]]+).*", "\\1", $match[1][$i]);
        $params=ereg_replace("[[:alpha:]]+ (.*)", "\\1", $match[1][$i]);
        if (is_file("$extdir/$cmd")){
          if (!(function_exists("wiki$cmd"))){
            include("$extdir/$cmd");
          }
          eval ("\$wikitxt=wiki$cmd(".'$params'.");");
        } else {
          $wikitxt= "";
        }
        $pattern=$match[0][$i];
        $pattern=ereg_replace("([\^[\(\|\{])","\\\\1",$pattern);
        $line=ereg_replace($pattern, $wikitxt, $line);
      }
    }
  }

  return $line;
}

############################
# Include the appropriate module and call the
# appropriate function.
if (function_exists($request)){
    eval ("\$request();");
} else {
  if (is_file("$modulesdir/$request.phl")){
    include("$modulesdir/$request.phl");
    eval ("\$request();");
  } else {
    $request="$browserequest";
    include("$modulesdir/$browserequest.phl");
    $browserequest();
  }
}

dbclose($dbase);

?>
