<?php

function dirListing() {
    $PATH = getHomeDir() . "/Desktop/";
    $GeneratedXML = "";

    $GeneratedXML = $GeneratedXML . "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" .
                          "<DIR_LIST>" . "<PATH_HEAD>" . $PATH . "</PATH_HEAD>";

    $dirContents = scandir($PATH);
    foreach ($dirContents as $fileName) {
        $fullPath = $PATH . $fileName;

        if (is_dir($fullPath)) {
           $GeneratedXML = $GeneratedXML . "<DIR>" . $fileName . "/</DIR>";
       } elseif (preg_match('/^.*\.(png|jpg|gif|jpeg)$/i', strtolower($fullPath))) {
            $GeneratedXML = $GeneratedXML .
            "<IMG_FILE>" .
              "<IMAGE_LINK>". $fullPath . "</IMAGE_LINK>" .
              "<IMAGE_NAME>" . $fileName . "</IMAGE_NAME>" .
            "</IMG_FILE>";
        } else {
           $GeneratedXML = $GeneratedXML .
           "<FILE>" .
             "<FILE_PATH>" . $fullPath .  "</FILE_PATH>"  .
             "<FILE_NAME>" . $fileName . "</FILE_NAME>" .
           "</FILE>";
       }
    }
    $GeneratedXML = $GeneratedXML . "</DIR_LIST>";
    echo $GeneratedXML;
}

// Return the user's home directory.
function getHomeDir() {
  $home = getenv('HOME');
  if (!empty($home)) {
    $home = rtrim($home, '/');
  } elseif (!empty($_SERVER['HOMEDRIVE']) &&
            !empty($_SERVER['HOMEPATH'])) {
    $home = $_SERVER['HOMEDRIVE'] . $_SERVER['HOMEPATH'];
    $home = rtrim($home, '\\/');
  }
  return empty($home) ? NULL : $home;
}


function launchProg($FILE) {
    $COMM = "xdg-open \"" . getHomeDir() .
                          "/Desktop/" .
                          $FILE . "\"";
    exec($COMM);
}


// Determin action
if (isset($_POST['dirQuery'])) {
    dirListing();
} elseif (isset($_POST['launchComm'])) {
    launchProg($_POST['file']);
} else {
    echo "<h2 class='errorStyling'>Error! Illegal Access Method!</h2>";
}

?>
