
<!-- 
	bibtex.php - v2006.05.30(beta)
	bibtex2html parser without any latex need to
				be installed!!!!
	(c) Thomas Döring
-->
<?php	

if (isset($_GET["cfg_file"])) {
	$cfg=$_GET["cfg_file"];
} else {
	$cfg = "bib2html.cfg";
}
$output = "html";
if (isset($_GET["bibtex"])) $output = "bibtex";

// CSS Definition
//--------------------------------------------------------------								
$css_standard = array("main" => "margin: 15px 0px 15px 0px;",
					  "author" => "font-variant: small-caps;",
					  "title" => "font-style: italic;");
					  
$css = array("article" => $css_standard,
			 "book" => $css_standard,
			 "booklet" => $css_standard,
			 "conference" => $css_standard,
			 "inbook" => $css_standard,
			 "incollection" => $css_standard,
			 "inproceedings" => $css_standard,
			 "manual" => $css_standard,		
			 "masterthesis" => $css_standard,		
			 "misc" => $css_standard,	
			 "other" => $css_standard,	
			 "phdthesis" => $css_standard,
			 "proceedings" => $css_standard,
			 "techreport" => $css_standard,
			 "unpublished" => $css_standard);

// FORMAT Definition
//--------------------------------------------------------------								
$standard = array("~(.*)~",'return $match[0];');
include $cfg;
		
if (!isset($forms)) { 
	$forms = array();
	foreach ($format as $key => $value) {
		$a = preg_match_all("~\%[^%]+%~m",$value,$match);
		$forms[$key] = array();
		foreach($match[0] as $attribute) {
			$tattr = str_replace("%","",$attribute);
			$forms[$key][$tattr] = (array_key_exists($tattr,$specialFormat)) ? $specialFormat[$tattr] : $standard;
		}
	}
				
}

// Check Variable for printed CSS definition 
$css_plotted = $css;
foreach($css_plotted as $key => $value) {
	$css_plotted[$key] = 0;
}

$str = "";
$keys = array_keys($forms);
for ($i = 0; $i < count($keys)-1; $i++) {
	$str = $str . $keys[$i] . "|";
}
$regex = $str . $keys[$i];

//reformates CSS definitions in valid CSS-Code
function standardCSS($key) {
	global $css;
	
	if ($key == "") return "";
	
	$str = "div.bib".$key." { ".$css[$key]["main"]." } \n";
	
	foreach ($css[$key] as $csskey => $value) 
		if ($csskey != "main") $str = $str . "        div.bib".$key." span.bib".$csskey." { ".$value." } \n";
			
	return $str;
}


function codeFilter($string) {
	global $replace;

	foreach($replace as $key => $value) $string = ereg_replace($key,$value,$string);
//	$string = str_replace(array_keys($replace),$replace,$string);
	return $string;
}
//returns an indexed array of attributes for ONE bibtex-String
function bib2dat($string) {
	global $regex;

	if (!preg_match('~@('.$regex.'){\s*(\w+)\s*,\s*(.*)\s*}~im',$string, $match)) {
    	trigger_error("\n<b>bib2html</b>: Couldn't interpet bibtex-string '<em>".$string."</em>'.<br>\n",E_USER_WARNING);
		return -1;
	}
	
	$type = strtolower($match[1]);
	$key = $match[2];
	$attrib  = $match[3];

	if (!preg_match_all('~(\w+)\s*=\s*{(.*?)}(,|$)~m',$attrib, $match)) {
    	trigger_error("\n<b>bib2html</b>: No entries found in bibtex record '<em>".$string."</em>'.<br>\n",E_USER_WARNING);
		return -1;
	}
	
	$c = count($match[1]);
	$str = array();

	for ($i=0; $i < $c; $i++) {
		$str[$match[1][$i]] = codeFilter($match[2][$i]);
	}
	
	$a = array("type" => $type,
				 "key" => $key,
				 "content" => $str);
				 
	return $a;	 
}

function formatAttribute($attribute,$key) {
	global $forms;

	if (!preg_match_all($forms[$attribute["type"]][$key][0],$attribute["content"][$key],$match)) {
		return "";
	}
	
	$match = array_slice($match[1],0,count($match[1])-1);
	$perform = create_function('$match',$forms[$attribute["type"]][$key][1]);
	
	return $perform($match);
}

function generateRecordString($string) {
	global $format, $bib_dir;
	
	$dataRecord = bib2dat($string);
	
	if ($dataRecord == -1)  return "";
	
	$actualFormat = $format[$dataRecord["type"]];
	$a = preg_match_all("~\[[^\]\[]+\]~m",$actualFormat,$attributeMatches);
	$attributeMatches[1] = $attributeMatches[0];
		
	$dataRecordContent = $dataRecord["content"];
	
	foreach($attributeMatches[0] as $akey) {
		$changed = 0;
		foreach($dataRecordContent as $key => $value) {
			if (strpos($akey,"%".$key."%")) {
				$pre = array("","");
				//if (array_key_exists("url",$dataRecordContent) && $key == "title") $pre = array("","<a href='".$dataRecordContent["url"]."' target='blank'><img border='0' src='scripts/bib2html/link.GIF'></a>");
				$actualFormat = str_replace($akey,
						str_replace("%".$key."%","\n        <span class='bib$key'>".$pre[0].formatAttribute($dataRecord,$key).$pre[1]."</span>",preg_replace("~[\]\[]~m","",$akey)),$actualFormat);
				$changed = 1;
			}
		}
		if ($changed == 0) $actualFormat = str_replace($akey, "", $actualFormat);
	}

	if (array_key_exists("url",$dataRecordContent)) $actualFormat = $actualFormat . "\n        <span><a href='".$dataRecordContent["url"]."' target='_blank'><img border='0' src='".$bib_dir."link.GIF'></a></span>";
	
	return $actualFormat;
		
}

function generateCleanBibTexCode($string) {
	global $format;
	
	$dataRecord = bib2dat($string);
	
	$str = "";
	if ($dataRecord == -1)  return "";
		
	$str = "@".$dataRecord["type"]."{".$dataRecord["key"].",<br>";
	$str = $str."<div style='margin: 0px 0px 0px 20px; padding: 0px;'>";
	foreach($dataRecord["content"] as $key => $value) $str = $str.$key . " = {".$value."},<br> ";
	$str = $str ."}";
	return str_replace("},<br> }","}}</div>",$str);
}


function readBibFile($name) {
	global $regex;
	
	ob_start();
	if (!@readfile($name)) {
		trigger_error("<b>bib2html</b>: BibTeX-File <em>".$name."</em> not found.",E_USER_WARNING);
		return FALSE;
	}
	$a = str_replace("\n","",ob_get_contents()).'@';
	ob_end_clean();
	$a = preg_match_all('~@[^@]+~',$a,$match);

	return $match[0];
}

function generateIndexedRecords($records) {

	$indexedRecord = array();
	foreach($records as $record) {
		$recordData = bib2dat($record);
		$IndexedRecord[$recordData["key"]] = array($recordData["type"],$record);
	}
	
	return $IndexedRecord;
}
	
function bib2html($name, $records) {
	global $css_plotted, $css;
	
	$allrecords = readBibFile($name);
	IF (!$allrecords) RETURN FALSE;
	$indexedRecords = generateIndexedRecords($allrecords);
	
	$str = array();
	print $bib_dir;
	print "<!-- bib2html CSS - START -->\n<style type='text/css'>\n<!--\n";

	if ($records == "") $records = array_keys($indexedRecords);
	foreach($records as $key) {
		if (array_key_exists($key,$indexedRecords)) {
			if ($css_plotted[$indexedRecords[$key][0]] == 0) { print "    ".standardCSS($indexedRecords[$key][0])."\n"; $css_plotted[$indexedRecords[$key][0]] = 1; }
			$str[$key]["html"] = "    <div class='bib".$indexedRecords[$key][0]."'>".generateRecordString($indexedRecords[$key][1])."\n    </div>\n\n";
			$str[$key]["bibtex"] = "    <div class='bib".$indexedRecords[$key][0]."'><tt>".generateCleanBibTexCode($indexedRecords[$key][1])."</tt>\n    </div>\n\n";
		}
	}	
	
	print "-->\n</style>\n<!-- bib2html CSS - END -->\n";
	return $str;
}

function printBibRecords($data,$records) {

	global $output;
	
	IF (!$data) {
		trigger_error("<b>bib2html</b>: No BibTeX-Data loaded. No output possible.",E_USER_WARNING);
		RETURN;
	}
	print "\n<!-- bib2html - START -->\n";
	if ($records == "") $records = array_keys($data);
	foreach($records as $key) {
		if (array_key_exists($key,$data)) print $data[$key][$output];
	}	
	print "<!-- bib2html - END -->";
}
	
?>