<?php |
|
function dread($parent) { |
$array = array(); |
if (false !== ($resource = opendir($parent))) { |
while (false !== ($name = readdir($resource))) { |
if ('.' != $name && '..' != $name) { |
$child = $parent . DIRECTORY_SEPARATOR . $name; |
$array[] = $child; |
if (is_dir($child)) { |
$array = array_merge($array, dread($child)); |
} |
} |
} |
closedir($resource); |
} |
return $array; |
} |
|
// Get physical pathes |
$root = realpath('files'); |
$physical = dread($root); |
|
if (! empty($physical)) { |
// Get virtual pathes |
$virtual = array(); |
|
$pdo = new Pdo('mysql:dbname=downloads;host=127.0.0.1;', 'root', ''); |
$qt = 'SELECT `id`, `path` FROM `downloads`;'; |
if (false !== ($q = $pdo->query($qt))) { |
if ($q->rowCount()) { |
while ($path = $q->fetch(PDO::FETCH_ASSOC)) { |
$virtual[$path['id']] = $path['path']; |
} |
} |
} |
|
// Search new pathes |
$new = empty($virtual) ? $physical : array_diff($physical, $virtual); |
// Search invalid pathes |
// $invalid = array_diff($virtual, $physical); |
|
if (! empty($new)) { |
// Add new pathes on virtual |
$qt = 'INSERT INTO `downloads` (`path`, `name`, `type`, `parent_id`, `size`) ' |
. 'VALUES (:path, :name, :type, :parent_id, :size);'; |
|
$pdo->beginTransaction(); |
$q = $pdo->prepare($qt); |
$parentId = null; |
foreach ($new as $path) { |
if (false !== $q->execute(array( |
':path' => $path, |
':name' => basename($path), |
':type' => ($type = filetype($path)), |
':parent_id' => (int) array_search(dirname($path), $virtual), |
':size' => ('file' == $type ? filesize($path) : 0) |
))) { |
$parentId += (null === $parentId) ? $pdo->lastInsertId('downloads') : 1; |
if ('dir' == $type) { |
// $virtual[$pdo->lastInsertId('downloads.id')] = $path; |
$virtual[$parentId] = $path; |
} |
} |
} |
$pdo->commit(); |
} |
} |