<?php
/*
author: Timotheus Pokorra (timotheus@pokorra.de)
file: xml.php
autumn 2002
feel free to use and modify
no guarantuee
*/
?>

<?
	function spaceline($printword, $parabrp=1, $brp=1, $br=1)
	{
		$output="";
		if ($printword)
		{
			for ($count=0; $count < $parabrp; $count++)
				$output .= "*** parabr *** \n";
			for ($count=0; $count < $brp; $count++)
				$output .= "<br/>\n";
		}
		else		
		{
			for ($count=0; $count < $br; $count++)
				$output .= "<br/>\n";
		}
		return $output;
	}

		
		function getCurrent($id, $Array)
        {
            $current = -1;
            $number = count($Array);
            for ($counter=0; $counter<$number; $counter++)
            {
                if ($Array[$counter]['id'] >= 0)
                {
                    if ($id == $Array[$counter]['id'])
                    {
                        $current = $counter;
                        $counter = $number+1;
                    }
                }
            }
            if (($current==-1) && ($id == ($number+1)))
                $current = ($number);
            return $current;
        }


function completeTag(&$value)
{
    return ($value['type'] == 'complete');
}

function beginTag(&$value)
{
    return ($value['type'] == 'open' || $value['type'] == 'complete');
}
function endTag(&$value)
{
    return ($value['type'] == 'complete' || $value['type'] == 'close');
}
function emptyTag(&$value)
{
    return $value['value']=="" && $value['type'] == 'complete';
}
function getAttributes($value)
{
    $result = array();
    if ($value['attributes'] != 0)
        foreach ( $value['attributes'] as $key => $val )
            $result[strtolower($key)] = $val;
    return $result;
}

function is_alnum($c)
// needed when php without ctype; use ctype_alnum
{
   return (($c >= 'a' && $c <= 'z') || ($c >= 'A' && $c <= 'Z') ||
             ($c>='0' && $c <='9'));
}

function unhtmlentities ($string)
{
    $trans_tbl = get_html_translation_table (HTML_ENTITIES);
    $trans_tbl = array_flip ($trans_tbl);
    return strtr ($string, $trans_tbl);
}

function makeTextAreaConform($value)
{
        $value = unhtmlentities($value);
        $value = str_replace("&\"",'"', $value);
        $value = str_replace('<br/>', "\n", $value);
        $value = str_replace('&auml;', 'ä', $value);
        $value = str_replace('&Auml;', "Ä",$value);
        $value = str_replace('&uuml;', "ü",$value);
        $value = str_replace('&Uuml;', "Ü",$value);
        $value = str_replace('&ouml;', "ö",$value);
        $value = str_replace('&Ouml;', "Ö",$value);
        $value = str_replace('&szlig;', "ß",$value);
        return $value;
}

function makeHTMLConform($value)
{
        $value = str_replace("\n"," ", $value);
        $value = str_replace("<br/>","\n", $value);
        $value = htmlentities($value);
        $value = str_replace("&amp;llt;","<", $value);
        $value = str_replace("&amp;ggt;",">", $value);
        $value = str_replace("\n","<br/>", $value);
        $value = str_replace("\\&quot;",'&quot;', $value);
        $value = str_replace("&amp;",'&', $value);
        $value = str_replace("\"",'&quot;', $value);
        return $value;
}

function makeXMLConform($value)
{
        $value = unhtmlentities($value);
        $value = str_replace("\\\"",'&quot;', $value);
        $value = str_replace("\"",'&quot;', $value);
        $value = str_replace("\\'","'", $value);
        $value = str_replace("ä",'&auml;', $value);
        $value = str_replace("Ä",'&Auml;', $value);
        $value = str_replace("ü",'&uuml;', $value);
        $value = str_replace("Ü",'&Uuml;', $value);
        $value = str_replace("ö",'&ouml;', $value);
        $value = str_replace("Ö",'&Ouml;', $value);
        $value = str_replace("ß",'&szlig;', $value);
        $value = str_replace('&','&amp;', $value);
        return $value;
}

function replaceLink($s, $link='http://')
{
		$gt = ">";
		$lt = "<";
		if ($parsebook)
		{
			$gt = "&ggt;";
			$lt = "&llt;";
        }
		$start = 0;
        $poshttp = strpos($s, $link, $start);
        while ($poshttp > 0)
        {
            $poshttp = strpos($s, $link, $start);
            if ($poshttp > 0)
            {
                $posafter = strpos($s,' ', $poshttp);
		$posafter2 = strpos($s,"<", $poshttp);
		if (!($posafter2===false) && $posafter2 < $posafter)
		   $posafter = $posafter2;
                if (!$posafter > 0)
                    $posafter = strlen($s);
                 $before = substr($s, 0, $poshttp);
                 $http = substr($s, $poshttp, $posafter-$poshttp);
                 while (!is_alnum($http[strlen($http)-1]))
                 {
                    $posafter--;
                    $http = substr($s, $poshttp, $posafter-$poshttp);
                 }
                 $after = substr($s, $posafter);
                 $s = $before.$lt."a href='".$http."' target=_blank".$gt.$http.$lt."/a".$gt.$after;
                 $start = strlen($s) - strlen($after);
                 if (strlen($after) == 0)
                     $poshttp = -1;
            }
        }
		return $s;
}

function replaceHTTP($s, $parsebook=0)
{
global $printword;
if ($printword)
	return $s;

	$s = replaceLink($s, 'http://');
	$s = replaceLink($s, 'ftp://');
    return $s;
}
function readHtml($values, &$counter, $endtag)
{
	global $printword;
    $val = $values[$counter];
    $text = $val['value'];
    if ($endtag == "PRE" || $endtag == "PREBR")
         $text = str_replace("\n","<br/>", $text);
    // unnested html tag => just return the text inside
    if ($val['tag'] == $endtag && $val['type'] == 'complete')
         return $text;
    $counter++;
    for (; $counter < count($values); $counter++)
    {
            $val = $values[$counter];
            $s = $val['value'];
            if ($val['tag'] == $endtag && $val['type'] == 'close')
                 return $text.$s;
            $val['tag'] = strtolower($val['tag']);
            if (emptyTag($val))
                 $s = "&llt;".$val['tag']."/&ggt;\n";
            else
            {
              if (beginTag($val))
              {
                   if ($val['tag'] == 'pre' || $val['tag'] == 'prebr')
  						$s = str_replace("\n","<br/>", $s);
                   $s2 = "&llt;".$val['tag'];
                   if ($val['tag'] != 'a')
						$s2 = replaceHTTP($s2);
				   if ($val['attributes'] != 0)
                   foreach ( $val['attributes'] as $key => $value )
				   {
					 if (!(isset($printword) && $val['tag'] == "table" && $key == "BORDER"))
				        $s2 = $s2." ".strtolower($key)."='".$value."'";
                   }
				   $s = $s2."&ggt;".$s;
              }
              if (endTag($val))
                   $s = $s."&llt;/".$val['tag']."&ggt;\n";
            }
            $text = $text.$s;
    }
    return "";
}
function readTexts($values, &$counter, $list, $entry)
{
 $debug =0;
        $texts=array();
        $current = 0;  // the current entry that is composed
        $counter++;
        $prevtag = "";
        $id = 1;
        for (; $counter < count($values); $counter++)
        {
                $val = $values[$counter];
                //$val["type"] != "cdata" &&
                if ($debug)
                     echo $val['tag']."&nbsp;".$val["value"]."&nbsp;".$val["type"]."<br>";

                if ($val['tag'] == $list && $val["type"] == 'close')
                {
                   return $texts;
                }
                else if ($val['tag'] ==$entry)
                {
                        if (beginTag($val))
                        {
                            $current = array();
                            if ($val['attributes'] != 0)
                                foreach ( $val['attributes'] as $key => $value )
                                {
                                    $current[strtolower($key)] = $value;
                                }
                        }
                        if (endTag($val) && $current != 0)
                        {
                                if ($current["id"] == "")
                                     $current["id"] = $id;
                                foreach ( $current as $key => $value )
                                {
                                    $current[$key] = replaceHTTP(makeHTMLConform($value));
                                }
                                $texts[] = $current;
                                $current = 0;
                                $id++;
                        }
                }
                else if ($current != 0)
                {
                    if ($val['tag'] == "HTML")
                         $s = readHTML($values, $counter, "HTML");
                    else if ($val['tag'] == "PRE")
                         $s = "&llt;pre&ggt;".readHTML($values, $counter, "PRE").
                          "&llt;/pre&ggt;\n";
                    else if ($val['tag'] == "PREBR")
                         $s = readHTML($values, $counter, "PREBR").
                          "&llt;br/&ggt;\n";
                    else if ($val['tag'] == "BR")
                    {
                         $s = "&llt;br/&ggt;";
                    }
                    else
                    {
                        $s = $val["value"];
                        $newtag = strtolower($val['tag']);
                        $prevtag = $newtag;
                    }
                    $current[$prevtag] = $current[$prevtag].$s;
                }
    }
}

function readDatabase($filename, $list, $entry='') {
    // read the xml database of menu
    $data = implode("",file($filename));
    $parser = xml_parser_create();
    xml_parse_into_struct($parser,$data,$values,$tags);
    xml_parser_free($parser);

    $counter = 0;
    $menu = readTexts($values, &$counter, $list, $entry);
    return $menu;
}

function saveDatabase($filename, $data, $list, $entry)
{
        $fp = fopen($filename, 'w');
        fwrite($fp, "<".$list.">\r\n");
        for ($counter=0; $counter < count($data); $counter++)
        {
              $current = $data[$counter];
              fwrite($fp, "<".$entry);
              foreach ( $current as $key => $value )
              {
                   $value = makeXMLConform($value);
                   if (strlen($value) <= 30)
                       fwrite($fp, "  ".$key."=\"".$value."\"\r\n");
              }
              fwrite($fp, ">\r\n");
              foreach ( $current as $key => $value )
              {
                   $value = makeXMLConform($value);
                   if (strlen($value) > 30)
                       fwrite($fp, "  <".$key.">".$value."</".$key.">\r\n");
              }
              fwrite($fp, "</".$entry.">\r\n");
        }

        fwrite($fp, "</".$list.">");
        fclose($fp);
}

function createNew(&$data, $templateEntry)
{
        $newEntry = array();
        foreach ( $templateEntry as $key => $value )
        {
           $newEntry[$key] = $value;
        }
        $data[] = $newEntry;
}

function displayForm($entry)
{
        echo "<form>";
        echo "<table width=100%>\n";
        foreach ( $entry as $key => $value )
        {
             echo "<tr><td>".$key."</td><td><textarea cols=80 rows=5>".
                  $value."</textarea></td></tr>\n";
        }
        echo "</table>\n";
        echo "</form>";
}

function showList($data)
{
        echo "<table width=100%>\n";
        for ($counter=0; $counter < count($data); $counter++)
        {
              $current = $data[$counter];
              echo "<tr><td>".$current["title"]."</td>";
              echo "<td><a href='edit.php?id=".$current["id"]."'>edit</a></td>";
              echo "<td><a href='delete.php?id=".$current["id"]."'>delete</a></td>";
              echo "</tr>\n";
        }
        echo "</table>";
        echo "<a href='createNew.php'>create new entry</a>";
}

  //showList($links);
  //displayForm($links[1]);
  /*createNew($links, array("title" => "", "description" => "", "local" => "",
             "local2"=>"", "internet" => "", "server" => ""));
  saveDatabase("test.xml", $links);*/

?>