<commit_before><?php

// Relative to public directory
static $site_config_path = "../config.json";

//This will be changed to whatever exists in the above file
static $config = NULL;

// Path to course data directory, loaded from config
static $data_path = NULL;

// Returns course data path, loads if necessary
function get_data_path() {
    global $data_path;
    global $site_config_path;
    global $config;

    // If config doesn't exist, load it
    if ($config == NULL) {
        if (!file_exists($site_config_path)) {
            error_out("$site_config_path does not exist. See setup guide");
        }

        $config = load_json($site_config_path);

        $data_path = $config["course_data_path"];

    }
    return $get_data_path;
}

// For displaying error and stopping execution
function error_out($info){
    echo "<script>alert(\"" . str_replace("\n","",str_replace("\"","",$info)) . "\");</script>";
    exit();
}

// For loading and parsing json
function load_json($path){
    if (!file_exists($path)){
        error_out("ERROR: Cannot load json from non-existant file $path");
    }

    $json_data = json_decode(file_get_contents($path),true);

    if ($json_data == NULL){
        error_out("ERROR: Cannot parse json $path");
    }

    return $json_data;

}

// Upload HW Assignment to server and unzip
function upload_homework($username, $assignment_id, $homework_file) {
    $data_path = get_data_path();

    // Check user and assignment authenticity
    $class_config = get_class_config($username);
    if ($username !== $_SESSION["id"]) {//Validate the id
        echo "Something really got screwed up with usernames and session ids";
        return array("error"=>"Something really got screwed up with usernames and session ids");
    }
    if (!is_valid_assignment($class_config, $assignment_id)) {
        return array("error"=>"This assignment is not valid");
    }
    $assignment_config = get_assignment_config($username, $assignment_id);
    if (!can_edit_assignment($username, $assignment_id, $assignment_config)) {//Made sure the user can upload to this homework
        return array("error"=>"assignment_closed");
    }
    //VALIDATE HOMEWORK CAN BE UPLOADED HERE
    //ex: homework number, due date, late days

    $max_size = 50000;//CHANGE THIS TO GET VALUE FROM APPROPRIATE FILE
    $allowed = array("zip");
    $filename = explode(".", $homework_file["name"]);
    $extension = end($filename);

    $upload_path = $data_path."/submissions/".$assignment_id."/".$username;//Upload path

    // TODO should support more than zip (.tar.gz etc.)
    if (!($homework_file["type"] === "application/zip")) {//Make sure the file is a zip file
        echo "Incorrect file upload type.  Not a zip, got ".htmlspecialchars($homework_file["type"]);
        return array("error"=>"Incorrect file upload type.  Not a zip, got ".htmlspecialchars($homework_file["type"]));
    }

    // If user path doesn't exist, create new one

    if (!file_exists($upload_path)) {
        // TODO permission level is INCORRECT
        mkdir($upload_path, 0777, true);
    }

    //Find the next homework version number

    $i = 1;
    while (file_exists($upload_path."/".$i)) {
        //Replace with symlink?
        $i++;
    }

    // Attempt to create folder
    if (!mkdir($upload_path."/".$i, 0777, false)) {//Create a new directory corresponding to a new version number
        // TODO permission level is INCORRECT
        echo "Error, failed to make folder ".$upload_path."/".$i;
        return array("error"=>"failed to make folder ".$upload_path."/".$i);
    }
    // Unzip files in folder

    $zip = new ZipArchive;
    $res = $zip->open($homework_file["tmp_name"]);
    if ($res === TRUE) {
      $zip->extractTo($upload_path."/".$i."/");
      $zip->close();
    } else {
        "Error failed to move uploaded file from ".$homework_file["tmp_name"]." to ". $upload_path."/".$i."/".$homework_file["name"];
        return array ("error"=>"failed to move uploaded file from ".$homework_file["tmp_name"]." to ". $upload_path."/".$i."/".$homework_file["name"]);

    }
    $settings_file = $upload_path."/user_assignment_settings.json";
    if (!file_exists($settings_file)) {
        $json = array("selected_assignment"=>1);
        file_put_contents($settings_file, json_encode($json));
    }
    $to_be_compiled = $data_path."/submissions/to_be_compiled.txt";
    if (!file_exists($to_be_compiled)) {
        file_put_contents($to_be_compiled, $assignment_id."/".$username."/".$i."\n");
    } else {
        $text = file_get_contents($to_be_compiled, false);
        $text = $text.$assignment_id."/".$username."/".$i."\n";
        file_put_contents($to_be_compiled, $text);
    }
    return array("success"=>"File uploaded successfully");
}

// Check if user has permission to edit homework
function can_edit_assignment($username, $assignment_id, $assignment_config) {
    $data_path = get_data_path();
    date_default_timezone_set('America/New_York');
    $file = $data_path."/results/".$assignment_id."/".$username."/user_assignment_config.json";
    if (file_exists($file)) {
        $json = json_decode(file_get_contents($file), true);
        if (isset($json["due_date"]) && $json["due_date"] != "default") {
            $date = new DateTime($json["due_date"]);
            $now = new DateTime("NOW");
            return $now <= $date;
        }
        return; //TODO
    }
    $date = new DateTime($assignment_config["due_date"]);
    $now = new DateTime("NOW");
    return $now <= $date;
}


//Gets the class information for assignments

function get_class_config($username) {
    $data_path = get_data_path();
    $file = $data_path."/results/class.json";
    if (!file_exists($file)) {
        ?><script>alert("Configuration for this class (class.JSON) does not exist.  Quitting");</script>
        <?php exit();
    }
    return json_decode(file_get_contents($file), true);
}


// Find most recent submission from user
function most_recent_assignment_version($username, $assignment_id) {
    $data_path = get_data_path();
    $path = $data_path."/submissions/".$assignment_id."/".$username;
    $i = 1;
    while (file_exists($path."/".$i)) {
        $i++;
    }
    return $i - 1;<commit_msg>refactoring and path specification changes<commit_after><?php

// Relative to public directory
static $site_config_path = "../config.json";

//This will be changed to whatever exists in the above file
static $config = NULL;

// Returns course data path, loads config if necessary
function get_data_path() {
    global $config;

    // If config hasn't been loaded, load it
    if ($config == NULL) {
        loadConfig();
    }

    // Return course data path
    return $config["course_data_path"];
}

// Returns submissions path, loads config if necessary
function get_submissions_path(){
    global $config;

    // If config hasn't been loaded, load it
    if ($config == NULL) {
        loadConfig();
    }

    // Return course data path
    return $config["submissions_path"];
}


// Load site configuration file
function loadConfig(){
    global $site_config_path;
    global $config;

    if (!file_exists($site_config_path)) {
        error_out("$site_config_path does not exist. See setup guide");
    }
    $config = load_json($site_config_path);
}

// For displaying error and stopping execution
function error_out($info){
    echo "<script>alert(\"" . str_replace("\n","",str_replace("\"","",$info)) . "\");</script>";
    exit();
}

// For loading and parsing json
function load_json($path){
    if (!file_exists($path)){
        error_out("ERROR: Cannot load json from non-existant file $path");
    }

    $json_data = json_decode(file_get_contents($path),true);

    if ($json_data == NULL){
        error_out("ERROR: Cannot parse json $path");
    }

    return $json_data;
}

// Security check for that makes sure the session id matches the username
function check_session($username){
    if ($username !== $_SESSION["id"]){
        error_out("Invalid Session!");
    }
}

// Upload HW Assignment to server and unzip
function upload_homework($username, $assignment_id, $homework_file) {
    $data_path = get_data_path();

    // Check user and assignment authenticity
    $class_config = get_class_config($username);

    check_session($username);

    if (!is_valid_assignment($class_config, $assignment_id)) {
        return array("error"=>"This assignment is not valid");
    }

    $assignment_config = get_assignment_config($username, $assignment_id);

    if (!can_edit_assignment($username, $assignment_id, $assignment_config)) {//Made sure the user can upload to this homework
        return array("error"=>"assignment_closed");
    }
    //VALIDATE HOMEWORK CAN BE UPLOADED HERE
    //ex: homework number, due date, late days

    $max_size = 50000;//CHANGE THIS TO GET VALUE FROM APPROPRIATE FILE
    $allowed = array("zip");
    $filename = explode(".", $homework_file["name"]);
    $extension = end($filename);

    $upload_path = $data_path."/submissions/".$assignment_id."/".$username;//Upload path

    // TODO should support more than zip (.tar.gz etc.)
    if (!($homework_file["type"] === "application/zip")) {//Make sure the file is a zip file
        echo "Incorrect file upload type.  Not a zip, got ".htmlspecialchars($homework_file["type"]);
        return array("error"=>"Incorrect file upload type.  Not a zip, got ".htmlspecialchars($homework_file["type"]));
    }

    // If user path doesn't exist, create new one

    if (!file_exists($upload_path)) {
        // TODO permission level is INCORRECT
        mkdir($upload_path, 0777, true);
    }

    //Find the next homework version number

    $i = 1;
    while (file_exists($upload_path."/".$i)) {
        //Replace with symlink?
        $i++;
    }

    // Attempt to create folder
    if (!mkdir($upload_path."/".$i, 0777, false)) {//Create a new directory corresponding to a new version number
        // TODO permission level is INCORRECT
        echo "Error, failed to make folder ".$upload_path."/".$i;
        return array("error"=>"failed to make folder ".$upload_path."/".$i);
    }
    // Unzip files in folder

    $zip = new ZipArchive;
    $res = $zip->open($homework_file["tmp_name"]);
    if ($res === TRUE) {
      $zip->extractTo($upload_path."/".$i."/");
      $zip->close();
    } else {
        "Error failed to move uploaded file from ".$homework_file["tmp_name"]." to ". $upload_path."/".$i."/".$homework_file["name"];
        return array ("error"=>"failed to move uploaded file from ".$homework_file["tmp_name"]." to ". $upload_path."/".$i."/".$homework_file["name"]);

    }
    $settings_file = $upload_path."/user_assignment_settings.json";
    if (!file_exists($settings_file)) {
        $json = array("selected_assignment"=>1);
        file_put_contents($settings_file, json_encode($json));
    }
    $to_be_compiled = $data_path."/submissions/to_be_compiled.txt";
    if (!file_exists($to_be_compiled)) {
        file_put_contents($to_be_compiled, $assignment_id."/".$username."/".$i."\n");
    } else {
        $text = file_get_contents($to_be_compiled, false);
        $text = $text.$assignment_id."/".$username."/".$i."\n";
        file_put_contents($to_be_compiled, $text);
    }
    return array("success"=>"File uploaded successfully");
}

// Check if user has permission to edit homework
function can_edit_assignment($username, $assignment_id, $assignment_config) {
    $data_path = get_data_path();
    date_default_timezone_set('America/New_York');
    $file = $data_path."/results/".$assignment_id."/".$username."/user_assignment_config.json";
    if (file_exists($file)) {
        $json = json_decode(file_get_contents($file), true);
        if (isset($json["due_date"]) && $json["due_date"] != "default") {
            $date = new DateTime($json["due_date"]);
            $now = new DateTime("NOW");
            return $now <= $date;
        }
        return; //TODO
    }
    $date = new DateTime($assignment_config["due_date"]);
    $now = new DateTime("NOW");
    return $now <= $date;
}


//Gets the class information for assignments
function get_class_config($username) {
    $data_path = get_data_path();

    $class_path = $data_path . "/class.json";

    return load_json($class_path);
}


// Find most recent submission from user
function most_recent_assignment_version($username, $assignment_id) {
    $data_path = get_data_path();
    $path = $data_path."/submissions/".$assignment_id."/".$username;
    $i = 1;
    while (file_exists($path."/".$i)) {
        $i++;
    }
    return $i - 1;
{'fraction_non_alphanumeric': 0.15434748052773803, 'fraction_numerical': 0.0027022730885391828, 'mean_word_length': 3.298940895114452, 'pattern_counts': {'":': 0, '<': 16, '<?xml version=': 0, '>': 31, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '7475771', 'n_tokens_mistral': 4011, 'n_tokens_neox': 3871, 'n_words': 984}