Пример #1
0
     $metadataPath = $_POST['metadataPath'] . ".xml";
     $oldFilename = $_POST['meta_filename'] . ".xml";
     $xml_filename = $basedir . str_replace('/..', '', $metadataPath);
     $xml_date = date("Y\\-m\\-d G\\:i\\:s");
     $file_format = ".meta";
     metaCreateDomDocument($xml_filename);
     $result = Database::get()->querySingle("SELECT * FROM document WHERE {$group_sql} AND path = ?s", $metadataPath);
     if ($result) {
         Database::get()->query("UPDATE document SET\n                                creator = ?s,\n                                date_modified = NOW(),\n                                format = ?s,\n                                language = ?s\n                                WHERE {$group_sql} AND path = ?s", $_SESSION['givenname'] . " " . $_SESSION['surname'], $file_format, $_POST['meta_language'], $metadataPath);
     } else {
         Database::get()->query("INSERT INTO document SET\n                                course_id = ?d ,\n                                subsystem = ?d ,\n                                subsystem_id = ?d ,\n                                path = ?s,\n                                filename = ?s ,\n                                visible = 0,\n                                creator = ?s,\n                                date = ?t ,\n                                date_modified = ?t ,\n                                format = ?s,\n                                language = ?s", $course_id, $subsystem, $subsystem_id, $metadataPath, $oldFilename, $_SESSION['givenname'] . " " . $_SESSION['surname'], $xml_date, $xml_date, $file_format, $_POST['meta_language']);
     }
     $action_message = "<div class='alert alert-success'>{$langMetadataMod}</div>";
 }
 if (isset($_POST['replacePath']) and isset($_FILES['newFile']) and is_uploaded_file($_FILES['newFile']['tmp_name'])) {
     validateUploadedFile($_FILES['newFile']['name'], $menuTypeID);
     $replacePath = $_POST['replacePath'];
     // Check if file actually exists
     $result = Database::get()->querySingle("SELECT id, path, format FROM document WHERE\n                                        {$group_sql} AND\n                                        format <> '.dir' AND\n                                        path=?s", $replacePath);
     if ($result) {
         $docId = $result->id;
         $oldpath = $result->path;
         $oldformat = $result->format;
         // check for disk quota
         $diskUsed = dir_total_space($basedir);
         if ($diskUsed - filesize($basedir . $oldpath) + $_FILES['newFile']['size'] > $diskQuotaDocument) {
             $action_message = "<div class='alert alert-danger'>{$langNoSpace}</div>";
         } elseif (unwanted_file($_FILES['newFile']['name'])) {
             $action_message = "<div class='alert alert-danger'>{$langUnwantedFiletype}: " . q($_FILES['newFile']['name']) . "</div>";
         } else {
             $newformat = get_file_extension($_FILES['newFile']['name']);
function validateZipFile($file)
{
    $validationResult = validateUploadedFile($file);
    if (!isset($file["tmp_name"]) || $file["tmp_name"] == "") {
        return "No file uploaded for deployment.";
    }
    if (!endsWith($file['name'], '.zip', true)) {
        return "The file uploaded is not a valid ZIP file. Please try again.";
    }
    return $validationResult;
}
Пример #3
0
/**
 * Main logic and control flow for all PUT funcions
 * @param unknown_type $action
 */
function put($action)
{
    $confirmAction = 'Confirm ' . ucwords($action);
    if (isset($_POST['action']) && $_POST['action'] == $confirmAction) {
        if (isset($_POST['sourceType']) && $_POST['sourceType'] == "singleRecord") {
            $singleRecordCsv = array();
            if (requiresObject($action)) {
                $fields = WorkbenchContext::get()->describeSObjects(WorkbenchContext::get()->getDefaultObject())->fields;
            } else {
                $idField = new stdClass();
                $idField->name = "Id";
                $fields['Id'] = $idField;
            }
            $singleRecordFieldMap = convertFieldMapToArray($_POST, fieldsToNameArray($fields));
            $anySet = false;
            foreach ($fields as $field) {
                if (isset($_POST[$field->name])) {
                    if (get_magic_quotes_gpc()) {
                        $_POST[$field->name] = stripslashes($_POST[$field->name]);
                    }
                    $anySet |= $_POST[$field->name] != "";
                    $singleRecordCsv[0][] = $field->name;
                    $singleRecordCsv[1][] = trim($_POST[$field->name]);
                    $singleRecordFieldMap[$field->name]["csvField"] = $field->name;
                }
            }
            if (!$anySet) {
                displayError("Must set a value for at least one field to {$action}.", true, true);
            }
            $_SESSION['csv_array'] = $singleRecordCsv;
            $_SESSION['field_map'] = $singleRecordFieldMap;
        }
        if ($action == 'upsert' && (isset($_SESSION['_ext_id']) || isset($_POST['_ext_id']))) {
            $extId = isset($_SESSION['_ext_id']) ? $_SESSION['_ext_id'] : $_POST['_ext_id'];
        } else {
            $extId = NULL;
        }
        if ($action == 'delete' && isset($_POST['doHardDelete']) && $_POST['doHardDelete']) {
            $action = 'hardDelete';
        }
        if (isset($_POST['doAsync'])) {
            putAsync($action, $extId, isset($_SESSION['field_map']) ? $_SESSION['field_map'] : null, isset($_SESSION['csv_array']) ? $_SESSION['csv_array'] : null, isset($_SESSION['tempZipFile']) ? $_SESSION['tempZipFile'] : null, isset($_POST['contentType']) ? $_POST['contentType'] : null);
        } else {
            require_once 'header.php';
            $apiCall = $action == 'insert' ? 'create' : $action;
            if ($action == "insert" || $action == "update" || $action == "upsert") {
                putSync($apiCall, $extId, isset($_SESSION['field_map']) ? $_SESSION['field_map'] : null, isset($_SESSION['csv_array']) ? $_SESSION['csv_array'] : null, true);
            } else {
                putSyncIdOnly($action, isset($_SESSION['field_map']) ? $_SESSION['field_map'] : null, isset($_SESSION['csv_array']) ? $_SESSION['csv_array'] : null, true);
            }
            include_once 'footer.php';
        }
        unset($_SESSION['field_map'], $_SESSION['csv_array'], $_SESSION['_ext_id'], $_SESSION['file_tmp_name'], $_SESSION['tempZipFile']);
    } else {
        if (isset($_POST['action']) && $_POST['action'] == 'Map Fields') {
            require_once 'header.php';
            array_pop($_POST);
            //remove header row
            if (isset($_POST['_ext_id'])) {
                $_SESSION['_ext_id'] = $_POST['_ext_id'];
                $_POST['_ext_id'] = NULL;
            }
            if (requiresObject($action)) {
                $fields = WorkbenchContext::get()->describeSObjects(WorkbenchContext::get()->getDefaultObject())->fields;
            } else {
                $idField = new stdClass();
                $idField->name = "Id";
                $fields['Id'] = $idField;
            }
            $fieldNames = fieldsToNameArray($fields);
            $_SESSION['field_map'] = convertFieldMapToArray($_POST, $fieldNames);
            confirmFieldMappings($confirmAction, $_SESSION['field_map'], isset($_SESSION['csv_array']) ? $_SESSION['csv_array'] : null, isset($_SESSION['_ext_id']) ? $_SESSION['_ext_id'] : null);
            include_once 'footer.php';
        } else {
            if (isset($_REQUEST['sourceType']) && $_REQUEST['sourceType'] == "singleRecord") {
                require_once 'header.php';
                setFieldMappings($action, false);
                include_once 'footer.php';
            } else {
                if (isset($_REQUEST['sourceType']) && $_REQUEST['sourceType'] == "file" && isset($_FILES['file'])) {
                    require_once 'header.php';
                    $validationResult = validateUploadedFile($_FILES['file']);
                    if ($validationResult === 0) {
                        $fileType = resolveFileType($_FILES['file']);
                    }
                    if ($validationResult || $fileType != "csv" && $fileType != "zip") {
                        displayError($validationResult);
                    } else {
                        if (requiresObject($action) && $_POST['default_object'] == "") {
                            displayError("Must select an object to {$action}.");
                        } else {
                            if ($fileType == "csv") {
                                $csvFileName = basename($_FILES['file']['name']);
                                $_SESSION['file_tmp_name'] = $_FILES['file']['tmp_name'];
                                $_SESSION['csv_array'] = convertCsvFileToArray($_SESSION['file_tmp_name']);
                                $csvArrayCount = count($_SESSION['csv_array']) - 1;
                                if (!$csvArrayCount) {
                                    displayError("The file uploaded contains no records. Please try again.", false, true);
                                } else {
                                    if ($csvArrayCount > WorkbenchConfig::get()->value("maxFileLengthRows")) {
                                        displayError("The file uploaded contains more than " . WorkbenchConfig::get()->value("maxFileLengthRows") . " records. Please try again.", false, true);
                                    }
                                }
                                $info = "The file {$csvFileName} was uploaded successfully and contains {$csvArrayCount} row";
                                if ($csvArrayCount !== 1) {
                                    $info .= 's';
                                }
                                displayInfo($info);
                                print "<br/>";
                                setFieldMappings($action, $_SESSION['csv_array']);
                            } else {
                                if ($fileType == "zip") {
                                    if (!supportsBulk($action)) {
                                        displayError("ZIP-based " . $action . "s not supported.", false, true);
                                        exit;
                                    }
                                    if (!WorkbenchContext::get()->isApiVersionAtLeast(20.0)) {
                                        displayError("ZIP-based " . $action . "s not supported until API 20.0", false, true);
                                        exit;
                                    }
                                    $_SESSION['tempZipFile'] = file_get_contents($_FILES['file']['tmp_name']);
                                    displayInfo(array("Successfully staged " . ceil($_FILES["file"]["size"] / 1024) . " KB zip file " . $_FILES["file"]["name"] . " for {$action} via the Bulk API. ", "Note, custom field mappings are not available for ZIP-based requests."));
                                    print "<br/>";
                                    print "<form method='POST' action=''>" . getCsrfFormTag() . "<div class='instructions'>Choose the options below and confirm the {$action}:<p/></div>" . "<table border='0'>";
                                    if ($action == 'upsert') {
                                        print "<tr><td align='right'><label><strong>External Id:</strong> </label></td>" . "<td><select name='_ext_id'>\n";
                                        foreach (WorkbenchContext::get()->describeSObjects($_POST['default_object'])->fields as $field) {
                                            if ($field->idLookup) {
                                                print " <option value='{$field->name}'";
                                                if ($field->name == 'Id') {
                                                    print " selected='true'";
                                                }
                                                print ">{$field->name}</option>\n";
                                            }
                                        }
                                        print "</select></td></tr>";
                                    }
                                    print "<tr><td align='right'><label><strong>Manifest Format:</strong> </label></td>" . "<td><select name='contentType'>\n" . "<option value='ZIP_CSV'>CSV</option>\n" . "<option value='ZIP_XML'>XML</option>\n" . "</select></td></tr>";
                                    print "</table>";
                                    displayBulkApiOptions($confirmAction, true);
                                    print "<br/><p><input type='submit' name='action' value='{$confirmAction}' /></p>\n";
                                    print "</form>\n";
                                } else {
                                    throw new Exception("Illegal State");
                                }
                            }
                        }
                    }
                    include_once 'footer.php';
                } else {
                    unset($_SESSION['field_map'], $_SESSION['csv_array'], $_SESSION['_ext_id'], $_SESSION['file_tmp_name'], $_SESSION['tempZipFile']);
                    displayUploadFileWithObjectSelectionForm($action);
                }
            }
        }
    }
}
Пример #4
0
        $objQuestion->updateDifficulty($difficulty);
        $objQuestion->updateCategory($category);

        //If grade field set (only in Free text questions)
        if (isset($questionGrade)) {
            $objQuestion->updateWeighting($questionGrade);
        }
        (isset($exerciseId)) ? $objQuestion->save($exerciseId) : $objQuestion->save();
        $questionId = $objQuestion->selectId();
        // upload or delete picture
        if (isset($_POST['deletePicture'])) {
            $objQuestion->removePicture();
        } elseif (isset($_FILES['imageUpload']) && is_uploaded_file($_FILES['imageUpload']['tmp_name'])) {

            require_once 'include/lib/fileUploadLib.inc.php';
            validateUploadedFile($_FILES['imageUpload']['name'], 2);

            $type = $_FILES['imageUpload']['type'];
            if (!$objQuestion->uploadPicture($_FILES['imageUpload']['tmp_name'], $type)) {
                $tool_content .= "<div class='alert alert-danger'>$langInvalidPicture</div>";
            }
        }
        if (isset($exerciseId)) {
            // adds the question ID into the question list of the Exercise object
            if ($objExercise->addToList($questionId)) {
                $objExercise->save();
                $nbrQuestions++;
            }
        }
        //if the answer type is free text (which means doesn't have predefined answers) 
        //redirects to either pool or edit exercise page
Пример #5
0
    $retrieveAsyncResults = WorkbenchContext::get()->getMetadataConnection()->retrieve($_SESSION[$retrieveRequestId]);
    if (!isset($retrieveAsyncResults->id)) {
        throw new Exception("Unknown retrieval error.\n" . isset($retrieveAsyncResults->message) ? $retrieveAsyncResults->message : "");
    }
    unset($_SESSION[$retrieveRequestId]);
    header("Location: metadataStatus.php?asyncProcessId=" . $retrieveAsyncResults->id . "&op=R");
} else {
    if (isset($_POST['stageForRetrieval'])) {
        if (isset($_FILES["packageXmlFile"]["name"]) && $_FILES["packageXmlFile"]["name"] == "" && isset($_POST['packageNames']) && $_POST['packageNames'] == "") {
            throw new WorkbenchHandledException("Must specify at least an unpackaged manifest file or a package name.");
        }
        $retrieveRequest = new RetrieveRequest();
        $retrieveRequest->apiVersion = WorkbenchContext::get()->getApiVersion();
        $retrieveRequest->singlePackage = isset($_POST['singlePackage']);
        if (isset($_FILES["packageXmlFile"]["name"]) && $_FILES["packageXmlFile"]["name"] != "") {
            $validationErrors = validateUploadedFile($_FILES["packageXmlFile"]);
            if ($validationErrors) {
                throw new WorkbenchHandledException($validationErrors);
            }
            if (!endsWith($_FILES["packageXmlFile"]["name"], ".xml", true)) {
                throw new WorkbenchHandledException("The file uploaded is not a valid XML file. Please try again.");
            }
            $retrieveRequest->unpackaged = parseUnpackagedManifest($_FILES["packageXmlFile"]["tmp_name"]);
        }
        if (isset($_POST['packageNames']) && $_POST['packageNames'] != "") {
            $encodedPackageNames = array();
            foreach (explodeCommaSeparated(htmlspecialchars($_POST['packageNames'])) as $p) {
                if ($p == "unpackaged") {
                    throw new WorkbenchHandledException("Cannot retrieve a package named 'unpackaged' -- to retrieve metadata not in a package, upload an unpackaged manifest file (i.e. 'package.xml').");
                }
                $encodedPackageNames[] = urlencode($p);
Пример #6
0
function edit_assignment($id)
{
    global $tool_content, $langBackAssignment, $langEditSuccess, $m, $langTheField, $langEditError, $course_code, $works_url, $course_id, $uid, $workPath, $langFormErrors;
    $v = new Valitron\Validator($_POST);
    $v->rule('required', array('title', 'max_grade'));
    $v->rule('numeric', array('max_grade'));
    $v->labels(array('title' => "{$langTheField} {$m['title']}", 'max_grade' => "{$langTheField} {$m['max_grade']}"));
    if ($v->validate()) {
        $row = Database::get()->querySingle("SELECT * FROM assignment WHERE id = ?d", $id);
        $title = $_POST['title'];
        $desc = purify($_POST['desc']);
        $deadline = trim($_POST['WorkEnd']) == FALSE ? '0000-00-00 00:00' : date('Y-m-d H:i', strtotime($_POST['WorkEnd']));
        $late_submission = isset($_POST['late_submission']) && trim($_POST['WorkEnd']) != FALSE ? 1 : 0;
        $group_submissions = $_POST['group_submissions'];
        $max_grade = filter_input(INPUT_POST, 'max_grade', FILTER_VALIDATE_FLOAT);
        $assign_to_specific = filter_input(INPUT_POST, 'assign_to_specific', FILTER_VALIDATE_INT);
        $assigned_to = filter_input(INPUT_POST, 'ingroup', FILTER_VALIDATE_INT, FILTER_REQUIRE_ARRAY);
        $auto_judge = filter_input(INPUT_POST, 'auto_judge', FILTER_VALIDATE_INT);
        $auto_judge_scenarios = serialize($_POST['auto_judge_scenarios']);
        $lang = filter_input(INPUT_POST, 'lang');
        if ($assign_to_specific == 1 && empty($assigned_to)) {
            $assign_to_specific = 0;
        }
        if (!isset($_POST['comments'])) {
            $comments = '';
        } else {
            $comments = purify($_POST['comments']);
        }
        if (!isset($_FILES) || !$_FILES['userfile']['size']) {
            $_FILES['userfile']['name'] = '';
            $_FILES['userfile']['tmp_name'] = '';
            $filename = $row->file_path;
            $file_name = $row->file_name;
        } else {
            validateUploadedFile($_FILES['userfile']['name'], 2);
            if (preg_match('/\\.(ade|adp|bas|bat|chm|cmd|com|cpl|crt|exe|hlp|hta|' . 'inf|ins|isp|jse|lnk|mdb|mde|msc|msi|msp|mst|pcd|pif|reg|scr|sct|shs|' . 'shb|url|vbe|vbs|wsc|wsf|wsh)$/', $_FILES['userfile']['name'])) {
                $tool_content .= "<p class=\"caution\">{$langUnwantedFiletype}: {$_FILES['userfile']['name']}<br />";
                $tool_content .= "<a href=\"{$_SERVER['SCRIPT_NAME']}?course={$course_code}&amp;id={$id}\">{$langBack}</a></p><br />";
                return;
            }
            $local_name = uid_to_name($uid);
            $am = Database::get()->querySingle("SELECT am FROM user WHERE id = ?d", $uid)->am;
            if (!empty($am)) {
                $local_name .= $am;
            }
            $local_name = greek_to_latin($local_name);
            $local_name = replace_dangerous_char($local_name);
            $secret = $row->secret_directory;
            $ext = get_file_extension($_FILES['userfile']['name']);
            $filename = "{$secret}/{$local_name}" . (empty($ext) ? '' : '.' . $ext);
            if (move_uploaded_file($_FILES['userfile']['tmp_name'], "{$workPath}/admin_files/{$filename}")) {
                @chmod("{$workPath}/admin_files/{$filename}", 0644);
                $file_name = $_FILES['userfile']['name'];
            }
        }
        Database::get()->query("UPDATE assignment SET title = ?s, description = ?s, deadline = ?t, late_submission = ?d, comments = ?s,\n                                group_submissions = ?d, max_grade = ?d, assign_to_specific = ?d, file_path = ?s, file_name = ?s,\n                                auto_judge = ?d, auto_judge_scenarios = ?s, lang = ?s WHERE course_id = ?d AND id = ?d", $title, $desc, $deadline, $late_submission, $comments, $group_submissions, $max_grade, $assign_to_specific, $filename, $file_name, $auto_judge, $auto_judge_scenarios, $lang, $course_id, $id);
        Database::get()->query("DELETE FROM assignment_to_specific WHERE assignment_id = ?d", $id);
        if ($assign_to_specific && !empty($assigned_to)) {
            if ($group_submissions == 1) {
                $column = 'group_id';
                $other_column = 'user_id';
            } else {
                $column = 'user_id';
                $other_column = 'group_id';
            }
            foreach ($assigned_to as $assignee_id) {
                Database::get()->query("INSERT INTO assignment_to_specific ({$column}, {$other_column}, assignment_id) VALUES (?d, ?d, ?d)", $assignee_id, 0, $id);
            }
        }
        Log::record($course_id, MODULE_ID_ASSIGN, LOG_MODIFY, array('id' => $id, 'title' => $title, 'description' => $desc, 'deadline' => $deadline, 'group' => $group_submissions));
        \Session::Messages($langEditSuccess, 'alert-success');
        redirect_to_home_page("modules/work/index.php?course={$course_code}");
    } else {
        //        $new_or_modify = isset($_GET['NewExercise']) ? "&NewExercise=Yes" : "&exerciseId=$_GET[exerciseId]&modifyExercise=yes";
        Session::flashPost()->Messages($langFormErrors)->Errors($v->errors());
        redirect_to_home_page("modules/work/index.php?course={$course_code}&id={$id}&choice=edit");
    }
}
Пример #7
0
require_once '../../include/baseTheme.php';
require_once 'modules/units/functions.php';
require_once 'include/lib/fileUploadLib.inc.php';
$pageName = $langEditCourseProgram;
$navigation[] = array('url' => 'index.php?course=' . $course_code, 'name' => $langCourseProgram);
$course = Database::get()->querySingle('SELECT description, home_layout, course_image FROM course WHERE id = ?d', $course_id);
if (isset($_GET['delete_image'])) {
    Database::get()->query("UPDATE course SET course_image = NULL WHERE id = ?d", $course_id);
    unlink("{$webDir}/courses/{$course_code}/image/{$course->course_image}");
    redirect_to_home_page('modules/course_home/editdesc.php');
} elseif (isset($_POST['submit'])) {
    $db_vars = array(purify($_POST['description']), $_POST['layout']);
    $extra_sql = '';
    if (isset($_FILES['course_image']) && is_uploaded_file($_FILES['course_image']['tmp_name'])) {
        $file_name = $_FILES['course_image']['name'];
        validateUploadedFile($file_name, 2);
        $i = 0;
        while (is_file("{$webDir}/courses/{$course_code}/image/{$file_name}")) {
            $i++;
            $name = pathinfo($file_name, PATHINFO_FILENAME);
            $ext = get_file_extension($file_name);
            $file_name = "{$name}-{$i}.{$ext}";
        }
        move_uploaded_file($_FILES['course_image']['tmp_name'], "{$webDir}/courses/{$course_code}/image/{$file_name}");
        $extra_sql = ", course_image = ?s";
        array_push($db_vars, $file_name);
    }
    array_push($db_vars, $course_id);
    Database::get()->query("UPDATE course SET description = ?s, home_layout = ?d{$extra_sql} WHERE id = ?d", $db_vars);
    // update index
    require_once 'modules/search/indexer.class.php';
Пример #8
0
function upload_images()
{
    global $webDir, $theme;
    if (isset($_FILES['imageUpload']) && is_uploaded_file($_FILES['imageUpload']['tmp_name'])) {
        $file_name = $_FILES['imageUpload']['name'];
        validateUploadedFile($file_name, 2);
        $i = 0;
        while (is_file("{$webDir}/template/{$theme}/img/{$file_name}")) {
            $i++;
            $name = pathinfo($file_name, PATHINFO_FILENAME);
            $ext = get_file_extension($file_name);
            $file_name = "{$name}-{$i}.{$ext}";
        }
        move_uploaded_file($_FILES['imageUpload']['tmp_name'], "{$webDir}/template/{$theme}/img/{$file_name}");
        $_POST['custom_logo'] = $file_name;
    }
    if (isset($_FILES['imageUploadSmall']) && is_uploaded_file($_FILES['imageUploadSmall']['tmp_name'])) {
        $file_name = $_FILES['imageUploadSmall']['name'];
        validateUploadedFile($file_name, 2);
        $i = 0;
        while (is_file("{$webDir}/template/{$theme}/img/{$file_name}")) {
            $i++;
            $name = pathinfo($file_name, PATHINFO_FILENAME);
            $ext = get_file_extension($file_name);
            $file_name = "{$name}-{$i}.{$ext}";
        }
        move_uploaded_file($_FILES['imageUploadSmall']['tmp_name'], "{$webDir}/template/{$theme}/img/{$file_name}");
        $_POST['custom_logo_small'] = $file_name;
    }
    if (isset($_FILES['bgImage']) && is_uploaded_file($_FILES['bgImage']['tmp_name'])) {
        $file_name = $_FILES['bgImage']['name'];
        validateUploadedFile($file_name, 2);
        $i = 0;
        while (is_file("{$webDir}/template/{$theme}/img/{$file_name}")) {
            $i++;
            $name = pathinfo($file_name, PATHINFO_FILENAME);
            $ext = get_file_extension($file_name);
            $file_name = "{$name}-{$i}.{$ext}";
        }
        move_uploaded_file($_FILES['bgImage']['tmp_name'], "{$webDir}/template/{$theme}/img/{$file_name}");
        $_POST['bgImage'] = $file_name;
    }
    if (isset($_FILES['loginImg']) && is_uploaded_file($_FILES['loginImg']['tmp_name'])) {
        $file_name = $_FILES['loginImg']['name'];
        validateUploadedFile($file_name, 2);
        $i = 0;
        while (is_file("{$webDir}/template/{$theme}/img/{$file_name}")) {
            $i++;
            $name = pathinfo($file_name, PATHINFO_FILENAME);
            $ext = get_file_extension($file_name);
            $file_name = "{$name}-{$i}.{$ext}";
        }
        move_uploaded_file($_FILES['loginImg']['tmp_name'], "{$webDir}/template/{$theme}/img/{$file_name}");
        $_POST['loginImg'] = $file_name;
    }
}
Пример #9
0
function upload_images($new_theme_id = null) {
    global $webDir, $theme, $theme_id;
    if (isset($new_theme_id)) $theme_id = $new_theme_id;
    if(!is_dir("$webDir/courses/theme_data/$theme_id")) {
        mkdir("$webDir/courses/theme_data/$theme_id", 0755);
    }
    $images = array('bgImage','imageUpload','imageUploadSmall','loginImg');
    foreach($images as $image) {
        if (isset($_FILES[$image]) && is_uploaded_file($_FILES[$image]['tmp_name'])) {
            $file_name = $_FILES[$image]['name'];
            validateUploadedFile($file_name, 2);
            $i=0;
            while (is_file("$webDir/courses/theme_data/$theme_id/$file_name")) {
                $i++;
                $name = pathinfo($file_name, PATHINFO_FILENAME);
                $ext =  get_file_extension($file_name);
                $file_name = "$name-$i.$ext";
            }
            $file_name = php2phps($file_name);
            move_uploaded_file($_FILES[$image]['tmp_name'], "$webDir/courses/theme_data/$theme_id/$file_name");
            $_POST[$image] = $file_name;
        }
    }
}
Пример #10
0
function submit_work($id, $on_behalf_of = null) {
    global $course_id, $uid, $langOnBehalfOfGroupComment,
           $works_url, $langOnBehalfOfUserComment, $workPath,
           $langUploadSuccess, $langUploadError, $course_code,
           $langAutoJudgeEmptyFile, $langAutoJudgeInvalidFileType,
           $langAutoJudgeScenariosPassed;
    $connector = AutojudgeApp::getAutojudge();
    $langExt = $connector->getSupportedLanguages();

    $row = Database::get()->querySingle("SELECT id, title, group_submissions, submission_type,
                            deadline, late_submission, CAST(UNIX_TIMESTAMP(deadline)-UNIX_TIMESTAMP(NOW()) AS SIGNED) AS time,
                            auto_judge, auto_judge_scenarios, lang, max_grade
                            FROM assignment
                            WHERE course_id = ?d AND id = ?d",
                            $course_id, $id);
    $auto_judge = $row->auto_judge;
    $auto_judge_scenarios = ($auto_judge == true) ? unserialize($row->auto_judge_scenarios) : null;
    $lang = $row->lang;
    $max_grade = $row->max_grade;

    $nav[] = $works_url;
    $nav[] = array('url' => "$_SERVER[SCRIPT_NAME]?id=$id", 'name' => q($row->title));

    $submit_ok = FALSE; // Default do not allow submission
    if (isset($uid) && $uid) { // check if logged-in
        if ($GLOBALS['status'] == USER_GUEST) { // user is guest
            $submit_ok = FALSE;
        } else { // user NOT guest
            if (isset($_SESSION['courses']) && isset($_SESSION['courses'][$_SESSION['dbname']])) {
                // user is registered to this lesson
                if (($row->time < 0 && (int) $row->deadline && !$row->late_submission) and !$on_behalf_of) {
                    $submit_ok = FALSE; // after assignment deadline
                } else {
                    $submit_ok = TRUE; // before deadline
                }
            } else {
                //user NOT registered to this lesson
                $submit_ok = FALSE;
            }
        }
    } //checks for submission validity end here
    if ($submit_ok) {
        $success_msgs = array();
        $error_msgs = array();
        //Preparing variables
        $user_id = isset($on_behalf_of) ? $on_behalf_of : $uid;
        if ($row->group_submissions) {
            $group_id = isset($_POST['group_id']) ? intval($_POST['group_id']) : -1;
            $gids = user_group_info($on_behalf_of ? null : $user_id, $course_id);
        } else {
            $group_id = 0;
        }
        // If submission type is Online Text
        if($row->submission_type){
            $filename = '';
            $file_name = '';
            $success_msgs[] = $langUploadSuccess;
        } else { // If submission type is File
            if ($row->group_submissions) {
                $local_name = isset($gids[$group_id]) ? greek_to_latin($gids[$group_id]) : '';
            } else {
                $student_name = trim(uid_to_name($user_id));
                $local_name = !empty($student_name)? $student_name : uid_to_name($user_id, 'username');
                $am = Database::get()->querySingle("SELECT am FROM user WHERE id = ?d", $user_id)->am;
                if (!empty($am)) {
                    $local_name .= $am;
                }
                $local_name = greek_to_latin($local_name);
            }
            $local_name = replace_dangerous_char($local_name);
            if (isset($on_behalf_of) and !isset($_FILES)) {
                $_FILES['userfile']['name'] = '';
                $_FILES['userfile']['tmp_name'] = '';
                $no_files = true;
            } else {
                $no_files = false;
            }
            $file_name = $_FILES['userfile']['name'];
            validateUploadedFile($file_name, 2);
            $secret = work_secret($row->id);
            $ext = get_file_extension($file_name);
            $filename = "$secret/$local_name" . (empty($ext) ? '' : '.' . $ext);
            if ($no_files or move_uploaded_file($_FILES['userfile']['tmp_name'], "$workPath/$filename")) {
                if ($no_files) {
                    $filename = '';
                } else {
                    @chmod("$workPath/$filename", 0644);
                }
                $success_msgs[] = $langUploadSuccess;
            } else {
                $error_msgs[] = $langUploadError;
                Session::Messages($error_msgs, 'alert-danger');
                redirect_to_home_page("modules/work/index.php?course=$course_code&id=$id");
            }
        }

        $submit_ip = $_SERVER['REMOTE_ADDR'];
        $submission_text = isset($_POST['submission_text']) ? purify($_POST['submission_text']) : NULL;
        if (isset($on_behalf_of)) {
            if ($row->group_submissions) {
                $stud_comments = sprintf($langOnBehalfOfGroupComment, uid_to_name($uid), $gids[$group_id]);
            } else {
                $stud_comments = sprintf($langOnBehalfOfUserComment, uid_to_name($uid), uid_to_name($user_id));
            }
            $grade_comments = $_POST['stud_comments'];
            $grade_valid = filter_input(INPUT_POST, 'grade', FILTER_VALIDATE_FLOAT);
            (isset($_POST['grade']) && $grade_valid!== false) ? $grade = $grade_valid : $grade = NULL;
            $grade_ip = $submit_ip;
        } else {
            if ($row->group_submissions) {
                if (array_key_exists($group_id, $gids)) {
                    $del_submission_msg = delete_submissions_by_uid(-1, $group_id, $row->id);
                    if (!empty($del_submission_msg)) {
                        $success_msgs[] = $del_submission_msg;
                    }
                }
            } else {
                $del_submission_msg = delete_submissions_by_uid($user_id, -1, $row->id);
                if (!empty($del_submission_msg)) {
                    $success_msgs[] = $del_submission_msg;
                }
            }
            $stud_comments = $_POST['stud_comments'];
            $grade = NULL;
            $grade_comments = $grade_ip = "";
        }

        if (!$row->group_submissions || array_key_exists($group_id, $gids)) {
            $data = array(
                $user_id,
                $row->id,
                $submit_ip,
                $filename,
                $file_name,
                $submission_text,
                $stud_comments,
                $grade,
                $grade_comments,
                $grade_ip,
                $group_id
            );
            $sid = Database::get()->query("INSERT INTO assignment_submit
                                    (uid, assignment_id, submission_date, submission_ip, file_path,
                                     file_name, submission_text, comments, grade, grade_comments, grade_submission_ip,
                                     grade_submission_date, group_id)
                                     VALUES (?d, ?d, NOW(), ?s, ?s, ?s, ?s, ?s, ?f, ?s, ?s, NOW(), ?d)", $data)->lastInsertID;
            Log::record($course_id, MODULE_ID_ASSIGN, LOG_INSERT, array('id' => $sid,
                'title' => $row->title,
                'assignment_id' => $row->id,
                'filepath' => $filename,
                'filename' => $file_name,
                'comments' => $stud_comments,
                'group_id' => $group_id));
            if ($row->group_submissions) {
                $group_id = Database::get()->querySingle("SELECT group_id FROM assignment_submit WHERE id = ?d", $sid)->group_id;
                $user_ids = Database::get()->queryArray("SELECT user_id FROM group_members WHERE group_id = ?d", $group_id);
                foreach ($user_ids as $user_id) {
                    update_attendance_book($user_id, $row->id, GRADEBOOK_ACTIVITY_ASSIGNMENT);
                    update_gradebook_book($user_id, $row->id, $grade/$row->max_grade, GRADEBOOK_ACTIVITY_ASSIGNMENT);
                }
            } else {   
                $quserid = Database::get()->querySingle("SELECT uid FROM assignment_submit WHERE id = ?d", $sid)->uid;
                // update attendance book as well
                update_attendance_book($quserid, $row->id, GRADEBOOK_ACTIVITY_ASSIGNMENT);
                //update gradebook if needed
                update_gradebook_book($quserid, $id, $grade/$row->max_grade, GRADEBOOK_ACTIVITY_ASSIGNMENT);
            }
            if ($on_behalf_of and isset($_POST['email'])) {
                $email_grade = $_POST['grade'];
                $email_comments = "\n$auto_comments\n\n" . $_POST['stud_comments'];
                grade_email_notify($row->id, $sid, $email_grade, $email_comments);
            }
        }

        // Auto-judge: Send file to hackearth
        if(AutojudgeApp::getAutojudge()->isEnabled()) {
            if ($auto_judge && $ext === $langExt[$lang]) {
                    $content = file_get_contents("$workPath/$filename");
                    // Run each scenario and count how many passed
                     $auto_judge_scenarios_output = array(
                        array(
                            'student_output'=> '',
                            'passed'=> 0,
                        )
                    );

                    $passed = 0;
                    $i = 0;
                    $partial = 0;
                    $errorsComment = '';
                    $weight_sum = 0;
                    foreach($auto_judge_scenarios as $curScenario) {
                        $input = new AutoJudgeConnectorInput();
                        $input->input = $curScenario['input'];
                        $input->code = $content;
                        $input->lang = $lang;
                        $result = $connector->compile($input);
                        // Check if we have compilation errors.
                        if ($result->compileStatus !== $result::COMPILE_STATUS_OK) {
                            // Write down the error message.
                            $num = $i+1;
                            $errorsComment = $result->compileStatus." ".$result->output."<br />";
                            $auto_judge_scenarios_output[$i]['passed'] = 0;
                        } else {
                            // Get all needed values to run the assertion.
                            $auto_judge_scenarios_output[$i]['student_output'] = $result->output;
                            $scenarioOutputExpectation = trim($curScenario['output']);
                            $scenarionAssertion        = $curScenario['assertion'];
                            // Do it now.
                            $assertionResult = doScenarioAssertion(
                                $scenarionAssertion,
                                $auto_judge_scenarios_output[$i]['student_output'],
                                $scenarioOutputExpectation
                            );
                            // Check if assertion passed.
                            if ($assertionResult) {
                                $passed++;
                                $auto_judge_scenarios_output[$i]['passed'] = 1;
                                $partial += $curScenario['weight'];
                            } else {
                                $num = $i+1;
                                $auto_judge_scenarios_output[$i]['passed'] = 0;
                            }
                        }

                        $weight_sum += $curScenario['weight'];
                        $i++;
                    }

                    // 3 decimal digits precision
                    $grade = round($partial / $weight_sum * $max_grade, 3);
                    // allow an error of 0.001
                    if($max_grade - $grade <= 0.001)
                        $grade = $max_grade;
                    // Add the output as a comment
                    $comment = $langAutoJudgeScenariosPassed.': '.$passed.'/'.count($auto_judge_scenarios);
                    rtrim($errorsComment, '<br />');
                    if ($errorsComment !== '') {
                        $comment .= '<br /><br />'.$errorsComment;
                    }
                    submit_grade_comments(array(
                        'assignment' => $id,
                        'submission' => $sid,
                        'grade' => $grade,
                        'comments' => $comment,
                        'email' => false,
                        'auto_judge_scenarios_output' => $auto_judge_scenarios_output,
                        'preventUiAlterations' => true,
                    ));

            } else if ($auto_judge && $ext !== $langExt[$lang]) {
                if($lang == null) { die('Auto Judge is enabled but no language is selected'); }
                if($langExt[$lang] == null) { die('An unsupported language was selected. Perhaps platform-wide auto judge settings have been changed?'); }
                submit_grade_comments($id, $sid, 0, sprintf($langAutoJudgeInvalidFileType, $langExt[$lang], $ext), false, null, true);
            }
        }
        // End Auto-judge

        Session::Messages($success_msgs, 'alert-success');        
        redirect_to_home_page("modules/work/index.php?course=$course_code&id=$id");
    } else { // not submit_ok
        Session::Messages($langExerciseNotPermit);
        redirect_to_home_page("modules/work/index.php?course=$course_code");
    }
}
Пример #11
0
     if (isset($_POST['message_title']) and $_POST['message_title'] != '') {
         $subject = $_POST['message_title'];
     } else {
         $subject = $langMessage;
     }
     $msg = new Msg($uid, $cid, $subject, $_POST['body'], $recipients, $filename, $real_filename, $filesize);
 } else {
     $cwd = getcwd();
     if (is_dir($dropbox_dir)) {
         $dropbox_space = dir_total_space($dropbox_dir);
     }
     $filename = php2phps($_FILES['file']['name']);
     $filesize = $_FILES['file']['size'];
     $filetype = $_FILES['file']['type'];
     $filetmpname = $_FILES['file']['tmp_name'];
     validateUploadedFile($_FILES['file']['name'], 1);
     if ($filesize + $dropbox_space > $diskQuotaDropbox) {
         $errormsg = $langNoSpace;
         $error = TRUE;
     } elseif (!is_uploaded_file($filetmpname)) {
         // check user found : no clean error msg
         die($langBadFormData);
     }
     // set title
     if (isset($_POST['message_title']) and $_POST['message_title'] != '') {
         $subject = $_POST['message_title'];
     } else {
         $subject = $langMessage;
     }
     $format = get_file_extension($filename);
     $real_filename = $filename;
Пример #12
0
 Database::get()->query("UPDATE user SET lang = ?s WHERE id = ?d", $langcode, $uid);
 $all_ok = register_posted_variables(array('am_form' => get_config('am_required') and $myrow->status != 1, 'desc_form' => false, 'phone_form' => false, 'email_form' => get_config('email_required'), 'surname_form' => !$is_admin, 'givenname_form' => true, 'username_form' => true, 'email_public' => false, 'phone_public' => false, 'am_public' => false), 'all');
 $departments = null;
 if (!get_config('restrict_owndep')) {
     if (!isset($_POST['department']) and !$is_admin) {
         $all_ok = false;
     } else {
         $departments = $_POST['department'];
     }
 }
 $email_public = valid_access($email_public);
 $phone_public = valid_access($phone_public);
 $am_public = valid_access($am_public);
 // upload user picture
 if (isset($_FILES['userimage']) && is_uploaded_file($_FILES['userimage']['tmp_name'])) {
     validateUploadedFile($_FILES['userimage']['name'], 1);
     $type = $_FILES['userimage']['type'];
     $image_file = $_FILES['userimage']['tmp_name'];
     if (!copy_resized_image($image_file, $type, IMAGESIZE_LARGE, IMAGESIZE_LARGE, $image_path . '_' . IMAGESIZE_LARGE . '.jpg')) {
         Session::Messages($langInvalidPicture);
         redirect_to_home_page("main/profile/profile.php");
     }
     if (!copy_resized_image($image_file, $type, IMAGESIZE_SMALL, IMAGESIZE_SMALL, $image_path . '_' . IMAGESIZE_SMALL . '.jpg')) {
         Session::Messages($langInvalidPicture);
         redirect_to_home_page("main/profile/profile.php");
     }
     Database::get()->query("UPDATE user SET has_icon = 1 WHERE id = ?d", $_SESSION['uid']);
     Log::record(0, 0, LOG_PROFILE, array('uid' => intval($_SESSION['uid']), 'addimage' => 1, 'imagetype' => $type));
 }
 // check if email is valid
 if (get_config('email_required') | get_config('email_verification_required') and !email_seems_valid($email_form)) {
Пример #13
0
 } else {  // add video
         if (isset($_POST['fileCloudInfo'])) { // upload cloud file
             $cloudfile = CloudFile::fromJSON($_POST['fileCloudInfo']);
             $file_name = $cloudfile->name();
         } else if (isset($_FILES['userFile']) && is_uploaded_file($_FILES['userFile']['tmp_name'])) { // upload local file
             $file_name = $_FILES['userFile']['name'];
             if ($diskUsed + @$_FILES['userFile']['size'] > $diskQuotaVideo) {
                 $tool_content .= "<div class='alert alert-danger'>$langNoSpace<br>
                                                 <a href='$_SERVER[SCRIPT_NAME]?course=$course_code'>$langBack</a></div><br>";
                 draw($tool_content, $menuTypeID, null, $head_content);
                 exit;
             } else {
                 $tmpfile = $_FILES['userFile']['tmp_name'];
             }
         }
         validateUploadedFile($file_name, $menuTypeID);
         // convert php file in phps to protect the platform against malicious codes
         $file_name = php2phps($file_name);                    
         $file_name = str_replace(" ", "%20", $file_name);
         $file_name = str_replace("%20", "", $file_name);
         $file_name = str_replace("\'", "", $file_name);
         $uploaded = true;
     if ($uploaded) {
         $safe_filename = sprintf('%x', time()) . randomkeys(16) . "." . get_file_extension($file_name);
         if (isset($cloudfile)) {
             $iscopy = ($cloudfile->storeToLocalFile("$updir/$safe_filename") == CloudDriveResponse::OK);                    
         } else {                    
             $iscopy = copy("$tmpfile", "$updir/$safe_filename");
         }
         if (!$iscopy) {
             $tool_content .= "<div class='alert alert-success'>$langFileNot<br>
Пример #14
0
        <legend>" . $langFileSent . "</legend>
        <table class='table-default'>
                   <tr><th width='150'>$langFileSentName</td><td>" . q($_FILES['archiveZipped']['name']) . "</th></tr>
                   <tr><th>$langFileSentSize</td><td>" . q($_FILES['archiveZipped']['size']) . "</th></tr>
                   <tr><th>$langFileSentType</td><td>" . q($_FILES['archiveZipped']['type']) . "</th></tr>
                   <tr><th>$langFileSentTName</td><td>" . q($_FILES['archiveZipped']['tmp_name']) . "</th></tr>
                </table></fieldset>
                        <fieldset>
        <legend>" . $langFileUnzipping . "</legend>
        <table class='table-default'>
                    <tr><td>" . unpack_zip_show_files($_FILES['archiveZipped']['tmp_name']) . "</td></tr>
                </table></fieldset>";
} elseif (isset($_POST['send_path']) and isset($_POST['pathToArchive'])) {
    if (!isset($_POST['token']) || !validate_csrf_token($_POST['token'])) csrf_token_error();
    $pathToArchive = $_POST['pathToArchive'];
    validateUploadedFile(basename($pathToArchive), 3);
    if (get_file_extension($pathToArchive) !== 'zip') {
        $tool_content .= "<div class='alert alert-danger'>" . $langErrorFileMustBeZip . "</div>";
    } else if (file_exists($pathToArchive)) {
        $tool_content .= "<fieldset>
        <legend>" . $langFileUnzipping . "</legend>
        <table class='table-default'>";
        $tool_content .= "<tr><td>" . unpack_zip_show_files($pathToArchive) . "</td></tr>";
        $tool_content .= "</table></fieldset>";
    } else {
        $tool_content .= "<div class='alert alert-danger'>$langFileNotFound</div>";
    }
} elseif (isset($_POST['create_restored_course'])) {
    if (!isset($_POST['token']) || !validate_csrf_token($_POST['token'])) csrf_token_error();
    register_posted_variables(array('restoreThis' => true,
        'course_code' => true,