<?php
class DirTree
{
protected $root;
protected $active;
const URL_KEY = 'el';
public function __construct($root, $active = null) {
$this->root = realpath($root);
if ($active !== null) {
$this->active = realpath($this->root . '/' . $active);
}
}
public function isActive($element) {
return substr($this->active, 0, strlen($element->getPathname())) === $element->getPathname();
}
public function getLink($element) {
return '?' . http_build_query(array(
self::URL_KEY => substr($element->getPathname(), strlen($this->root))
));
}
protected function _get(Iterator $it) {
$result = array();
$dirs = $files = array();
foreach ($it as $entry) {
if ($entry->isDir()) {
$data = (object)array(
'type' => 'dir',
'name' => $entry->getBasename(),
'object' => $entry
);
if ($this->isActive($entry)) {
$data->children = $this->_get($it->getChildren());
$data->active = true;
}
$dirs[$entry->getBasename()] = $data;
}
else {
$files[$entry->getFilename()] = (object)array(
'type' => 'file',
'name' => $entry->getFilename(),
'object' => $entry,
'active' => $this->isActive($entry)
);
}
}
uksort($dirs, 'strnatcmp');
uksort($files, 'strnatcmp');
return array_values(array_merge($dirs, $files));
}
public function get() {
return $this->_get(
new RecursiveDirectoryIterator($this->root)
);
}
public function outputUl($dirTree = null) {
if ($dirTree === null) {
$dirTree = $this->get();
}
echo '<ul>';
foreach ($dirTree as $element) {
$classes = array($element->type);
if ($element->type === 'dir') {
if ($element->active) {
$classes[] = 'active';
}
echo '<li class="', implode(' ', $classes), '">';
echo '<a href="', $this->getLink($element->object),'">';
echo $element->name;
echo '</a>';
if (sizeof($element->children) > 0) {
$this->outputUl($element->children);
}
echo '</li>';
}
else {
if ($element->active) {
$classes[] = 'active';
}
echo '<li class="', implode(' ', $classes), '">';
echo '<a href="', $this->getLink($element->object),'">';
echo $element->name;
echo '</a>';
echo '</li>';
}
}
echo '</ul>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>DirTree</title>
<style type="text/css">
#dirTree a {
text-decoration: none;
color: #171717;
}
#dirTree .file a {
color: #999999;
}
#dirTree .active > a {
font-weight: bold;
}
</style>
</head>
<body>
<div id="dirTree">
<?php
$dirTree = new DirTree(
'.',
isset($_GET[DirTree::URL_KEY]) ? $_GET[DirTree::URL_KEY] : null
);
$dirTree->outputUl();
?>
</div>
</body>
</html>