<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    $allowedExts = array("mp4", "mov", "wmv", "flv", "avi", "avchd", "webm", "mkv");
    $extension = pathinfo($_FILES['videoFile']['name'], PATHINFO_EXTENSION);

    if ((($_FILES["videoFile"]["type"] == "video/mp4")
            || ($_FILES["videoFile"]["type"] == "video/x-msvideo")
            || ($_FILES["videoFile"]["type"] == "video/mpeg")
            || ($_FILES["videoFile"]["type"] == "video/ogg")
            || ($_FILES["videoFile"]["type"] == "video/mp2t")
            || ($_FILES["videoFile"]["type"] == "video/webm")
            || ($_FILES["videoFile"]["type"] == "video/3gpp")
            || ($_FILES["videoFile"]["type"] == "video/x-matroska")
            || ($_FILES["videoFile"]["type"] == "video/3gpp2"))

        && ($_FILES["videoFile"]["size"] < 500000000)
        && in_array($extension, $allowedExts)
        && isset($_POST["xmlFile"])
    ) {
        if ($_FILES["videoFile"]["error"] > 0) {
            redirect("?e='" . $_FILES["videoFile"]["error"] . "'");
        } else {
            do {
                $generatedFileName = generateRandomString();
            } while (file_exists("videos/" . $generatedFileName . "." . $extension));

            move_uploaded_file(
                $_FILES["videoFile"]["tmp_name"],
                "videos/" .
                    $generatedFileName . "." . $extension
            );
            $xml = $_POST["xmlFile"];
            $xml = str_replace("<video>", '<video src="' . $generatedFileName . '.' . $extension . '">', $xml);

            writeToFile("videos/" . $generatedFileName . ".xml", $xml);
            redirect("?v=" . $generatedFileName);
        }
    } else {
        redirect("?e='invalid file'");
    }
} else {
    redirect();
}

function writeToFile($file, $xml)
{
    $myfile = fopen($file, "w") or die("Unable to open file!");
    $txt = "John Doe\n";
    fwrite($myfile, $xml);
    fclose($myfile);
}

function redirect($videoID = null)
{
    header("Location: index.html" . $videoID);
    die();
}

function generateRandomString($length = 4)
{
    $characters = 'abcdefghijklmnopqrstuvwxyz';
    $charactersLength = strlen($characters);
    $randomString = '';
    for ($i = 0; $i < $length; $i++) {
        $randomString .= $characters[rand(0, $charactersLength - 1)];
    }
    return $randomString;
}
