<?

// A viewer for older DBs that were patched with an index

// Functions

function breadcrumbs($dbo, $pathname) {

	$zpath = $dbo->query("SELECT zpath FROM _walkwalk")->fetch()['zpath'];
	$pathname_adjusted = str_replace($zpath."/", "", $pathname);

	$parts = explode("/", $pathname_adjusted);
	$i = count($parts);	

	echo "<pre>"; echo "pathname = ".$pathname; print_r($parts);

	while ($i) {
		$search_path = $zpath."/".implode("/", array_slice($parts, 0, $i));
		$id = $dbo->query("SELECT id FROM files WHERE (Pathname='".str_replace("'", "''", $search_path)."')")->fetch()['id'];
		if ($i == count($parts)) {
			$result[] = array(null, basename($search_path));
			} else {
			$result[] = array($id, basename($search_path));
			}
		$i--;
		}

	if ($pathname == $zpath) {
		return array(array(null,basename($zpath)));
		} else {
		$result[] = array("1",basename($zpath));
		return array_reverse($result);
		}
		
	}

////////////////////////////////

// View

$id = $_GET['id'];
if (!$id) { $id = 1; }
$db_file = "db/patch.sqlite3";

$dbo = new PDO("sqlite:".$db_file);
$dbo->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);

//echo $dbo->query("SELECT COUNT(1) FROM files")->fetch()['COUNT(1)']." files<hr>";

$view = $dbo->query("SELECT * FROM files WHERE (rowid=".$id.")")->fetchAll()[0];

print_r($view);

echo "<hr>";

$crumb = breadcrumbs($dbo, $view['Pathname']);

foreach ($crumb as $myparts) {
	if ($myparts[0] === null) {
		echo $myparts[1];
		} else {
		echo "<a href='?id=".$myparts[0]."'>".$myparts[1]."</a> > ";
		}
	}

echo "<hr>";

$items = unserialize($dbo->query("SELECT children FROM patch WHERE (rowid=".$id.")")->fetch()['children']);

foreach ($items as $id) {
	$row_a = $dbo->query("SELECT * FROM files WHERE (rowid='".$id."')")->fetchAll()[0];
	$row_b = $dbo->query("SELECT * FROM mdls WHERE (rowid='".$id."')")->fetchAll()[0];
	$row_c = $dbo->query("SELECT * FROM metadata WHERE (rowid='".$id."')")->fetchAll()[0];
	if (!$row_a['Extension']) {
		echo "<a href='?id=".$id."'>".$row_a['Filename']."</a>&nbsp;";
		} else {
		echo $row_a['Filename']."&nbsp;";
		}
	}

////////////////////////////////

echo "<hr>".round(microtime(true)-$_SERVER["REQUEST_TIME_FLOAT"],2)." seconds<br><hr><br>";

?>