<?php

header('Content-type: application/json');

$docRoot = dirname(__DIR__);

$topLevel = $docRoot . '/sample/filer';
$fileRoot = $docRoot . ($_REQUEST['path'] ?: '/sample/filer');
$items = [];
$glob = glob($fileRoot . '/*');

if($fileRoot !== $topLevel)
{
  $parentDir = dirname($fileRoot);
  $items[] = [
    'path' => getRelativePath($docRoot, $parentDir),
    'name' => '..',
    'type' => filetype($parentDir),
    'mime' => mime_content_type($parentDir),
  ];
}

foreach($glob as $g)
{
  $item = [
    'path' => getRelativePath($docRoot, $g),
    'name' => basename($g),
  ];

  $type = filetype($g);
  if($type === 'link')
  {
    $g = realpath($g);
    $type = filetype($g);
  }

  $item['type'] = $type;
  $item['mime'] = mime_content_type($g);
  $items[] = $item;
}

function get_mime_type($file)
{
  if(function_exists('finfo_open'))
  {
    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mimetype = finfo_file($finfo, $file);
    finfo_close($finfo);
  }
  else
  {
    $mimetype = mime_content_type($file);
  }
  if(empty($mimetype))
  {
    $mimetype = 'application/octet-stream';
  }
  return $mimetype;
}

function getRelativePath(string $docRoot, string $g)
{
  return preg_replace('/^' . preg_quote($docRoot, '/') . '/', '', $g);
}

echo json_encode($items);
