Your IP : 216.73.217.117


Current Path : /var/www/cesa.co.za/cceconvenors/ajax/
Upload File :
Current File : /var/www/cesa.co.za/cceconvenors/ajax/markassignments.php

<?php
//ini_set('display_errors', 1);
//error_reporting(E_ERROR);

session_start(); // Initialize Session data

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

include_once($_SERVER['DOCUMENT_ROOT'] . "/cceconvenors/ewcfg7.php");
include_once($_SERVER['DOCUMENT_ROOT'] . "/cceconvenors/inc_functions.php");
include_once($_SERVER['DOCUMENT_ROOT'] . "/php/includes/sqlFunctions.php");
include_once($_SERVER['DOCUMENT_ROOT'] . "/cesanet/inc_shared.php");
include_once($_SERVER['DOCUMENT_ROOT'] . "/cceadmin/phpmailer/class.phpmailer.php");
include_once($_SERVER['DOCUMENT_ROOT'] . "/php/includes/CceUploadedFileService.php");

$cceAssignmentMarkingObj = new CCEAssignmentMarking($sqlf);
$cceUploadedFileService = new CceUploadedFileService();

$sWhere = "";
$sError = "";
$arrFieldErrs = array();
$feedback = [];

if ($_POST["action"] == "upload") {

    $assignmentId = isset($_REQUEST['id']) ? (int) $_REQUEST['id'] : 0;
    $uploadField = isset($_POST['uploadField']) ? (string) $_POST['uploadField'] : '';
    $isSupportingDoc = ($uploadField === 'SupportingDoc');
    $storageLocation = $isSupportingDoc
        ? CceUploadedFileService::STORAGE_ASSIGNMENTS_UPLOAD
        : CceUploadedFileService::STORAGE_MSGATTACH;

    $uploadOptions = array(
        'portal' => CceUploadedFileService::PORTAL_CONVENORS,
        'accessContext' => array(
            'fileRole' => $isSupportingDoc
                ? CceUploadedFileService::FILE_ROLE_SUPPORTING_DOC
                : CceUploadedFileService::FILE_ROLE_MSGATTACH,
            'CCEAssignmentID' => $assignmentId,
        ),
    );

    if (!$isSupportingDoc) {
        $uploadOptions['dateSuffix'] = date('Ymd');
    }

    $uploadResult = $cceUploadedFileService->storeUploadedFile('upload', $storageLocation, $uploadOptions);

    if (is_array($uploadResult) && !empty($uploadResult['error'])) {
        header('HTTP/1.1 400 Bad Request');
?>
        {
        "data":[],
        "error": <?php echo json_encode($uploadResult['message']); ?>

        }
<?php
        die();
    }

    if (is_array($uploadResult) && !empty($uploadResult['filename'])) {
        $storedFilename = $uploadResult['filename'];
        $webPath = isset($uploadResult['web_path']) ? $uploadResult['web_path'] : '';
?>
        {
        "data":[],
        "files": {
        "files": {
        <?php echo json_encode($storedFilename); ?>: {
        "filename": <?php echo json_encode($storedFilename); ?>,
        "web_path": <?php echo json_encode($webPath); ?>
        }
        }
        },
        "upload": {
        "id": <?php echo json_encode($storedFilename); ?>
        }
        }
<?php
        die();
    }

    $sError = 'Could not save uploaded file.';
    $sWhere .= "(1=0) ";
}

$extraInfo = array();

//echo 'here';
//echo $_POST["action"];
//exit;

if (isset($_POST["action"]) && isset($_POST["data"])) {
    $arrData = $_POST["data"];
    $markingAssignmentModuleId = 0;
    $sqlModuleGuard = "SELECT CCEModuleID FROM CCEAssignments WHERE CCEAssignmentID=" . intval($_REQUEST["id"]);
    $recModuleGuard = mysqli_query($conni, $sqlModuleGuard);
    if ($recModuleGuard && ($rowModuleGuard = mysqli_fetch_assoc($recModuleGuard))) {
        $markingAssignmentModuleId = (int) $rowModuleGuard["CCEModuleID"];
    }
    if ($recModuleGuard) {
        mysqli_free_result($recModuleGuard);
    }
    $cceStudentsMarkingGuard = class_exists('CCEStudents') ? new CCEStudents($sqlf) : null;

    if ($_POST["action"] == "edit") {

        $sWhere = '(';
        foreach ($arrData as $rowkey => $arrRow) {
            //            var_dump($rowkey);
            //            exit;
            //            var_dump($arrRow);
            //            exit;
            $key = array_shift(explode("_", $rowkey));
            $CCEStudentAssigID = array_pop(explode("_", $rowkey));
            if ($cceStudentsMarkingGuard && $markingAssignmentModuleId > 0
                && $cceStudentsMarkingGuard->isExcludedFromModule(intval($key), $markingAssignmentModuleId)) {
                $sError .= "Student is excluded from this module; marking cannot be updated.\n";
                continue;
            }
            $sWhere .= "CCEStudents.CCEStudentID=" . intval($key) . " OR ";

            if ((isset($arrRow["CCEExtensionDate"]) && !empty($arrRow["CCEExtensionDate"])) || (isset($arrRow["Status"]) && !empty($arrRow["Status"])) || (isset($arrRow["Motivation"]) && !empty($arrRow["Motivation"]))) {

                $iCCEStAssigExtensionID = 0;
                $sPrevStatus = "";
                $sPrevExtDate = "";

                $sql = "SELECT * FROM CCEStAssigExtensionRequests WHERE CCEStudentID=" . intval($key) . " AND CCEAssignmentID=" . intval($_REQUEST["id"])
                    . " ORDER BY CCEStAssigExtensionID DESC";
                $rec = mysqli_query($conni, $sql);

                if ($row = mysqli_fetch_assoc($rec)) {
                    $iCCEStAssigExtensionID = $row["CCEStAssigExtensionID"];
                    $sPrevStatus = $row["Status"];
                    $sMotivation = $row["Motivation"];
                    $sPrevExtDate = $row["CCEExtensionDate"];
                }

                if (isset($arrRow["CCEExtensionDate"]) && !empty($arrRow["CCEExtensionDate"]) && ($PrevExtDate != $arrRow["CCEExtensionDate"])) {
                    if (!empty($iCCEStAssigExtensionID)) {
                        $sql = "UPDATE CCEStAssigExtensionRequests SET CCEExtensionDate='" . date("Y-m-d", strtotime($arrRow["CCEExtensionDate"])) . "',
						UpdatedBy='" . $_SESSION[EW_SESSION_USER_NAME] . "', DateUpdated=NOW()
						WHERE CCEStAssigExtensionID=" . $iCCEStAssigExtensionID;
                        $extraInfo[] = 'Update extension on date: ' . $sql;
                        mysqli_query($conni, $sql);
                    } else {
                        $sql = "INSERT INTO CCEStAssigExtensionRequests (CCEStudentID, CCEAssignmentID, CCEExtensionDate, UpdatedBy, DateUpdated)
						VALUES (" . intval($key) . ", " . intval($_REQUEST["id"]) . ", '" . date("Y-m-d", strtotime($arrRow["CCEExtensionDate"])) . "', '" . $_SESSION[EW_SESSION_USER_NAME] . "', NOW())";
                        $extraInfo[] = 'Insert extension on date: ' . $sql;
                        mysqli_query($conni, $sql);
                        $iCCEStAssigExtensionID = mysqli_insert_id($conni);
                    }
                }

                if (isset($arrRow["Status"]) && !empty($arrRow["Status"]) && ($sPrevStatus != $arrRow["Status"])) {
                    $sql = "UPDATE CCEStAssigExtensionRequests SET Status='" . $arrRow["Status"] . "', StatusReason='" . addslashes($arrRow["StatusReason"]) . "',
					UpdatedBy='" . $_SESSION[EW_SESSION_USER_NAME] . "', DateUpdated=NOW()
					WHERE CCEStAssigExtensionID=" . $iCCEStAssigExtensionID;
                    mysqli_query($conni, $sql);

                    if ($arrRow["Status"] == "A" || $arrRow["Status"] == "P") {
                        $sql = "INSERT INTO CCEStAssigExtensions (CCEStudentID, CCEAssignmentID, CCEExtensionDate)
						select CCEStAssigExtensionRequests.CCEStudentID, CCEStAssigExtensionRequests.CCEAssignmentID, CCEStAssigExtensionRequests.CCEExtensionDate
						from CCEStAssigExtensionRequests
						WHERE (`Status`='A' OR `Status`='P') AND CCEStAssigExtensionID=" . $iCCEStAssigExtensionID;
                        $extraInfo[] = 'Insert extension on status: ' . $sql;
                        mysqli_query($conni, $sql);
                        SendStudentEmail(intval($key), intval($_REQUEST["id"]), $arrRow["Status"]);
                    }
                    if ($arrRow["Status"] == "D") {
                        $sql = "DELETE CCEStAssigExtensions FROM CCEStAssigExtensionRequests
						JOIN CCEStAssigExtensions USING (CCEStudentID, CCEAssignmentID, CCEExtensionDate)
						WHERE CCEStAssigExtensionRequests.CCEStAssigExtensionID=" . $iCCEStAssigExtensionID;
                        $extraInfo[] = 'Delete extension on status: ' . $sql;
                        mysqli_query($conni, $sql);
                        SendStudentEmail(intval($key), intval($_REQUEST["id"]), "D");
                    }
                }

                //                var_dump($arrRow);
                //                echo $sMotivation . ' motivation';

                if (isset($arrRow["Motivation"]) && !empty($arrRow["Motivation"]) && ($sMotivation != $arrRow["Motivation"])) {
                    $sql = "UPDATE CCEStAssigExtensionRequests SET Motivation='" . $arrRow["Motivation"] . "',
					UpdatedBy='" . $_SESSION[EW_SESSION_USER_NAME] . "', DateUpdated=NOW()
					WHERE CCEStAssigExtensionID=" . $iCCEStAssigExtensionID;
                    $extraInfo[] = 'Update extension on motivation: ' . $sql;
                    //                    echo $sql;
                    //                    exit;
                    mysqli_query($conni, $sql);
                }
                //                exit;
            } //update extension
            //$arrRow["DaysLate"]=0;

            if (isset($arrRow["CCEExtensionDate"]) || isset($arrRow["Status"])) {

                $sql = "SELECT CCEStAssigExtensionRequests.CCEExtensionDate, CCEAssignments.DueDate, CCEStudentAssignments.DateSubmitted
                    FROM CCEStAssigExtensionRequests JOIN CCEAssignments USING (CCEAssignmentID)
                    JOIN CCEStudentAssignments ON (CCEStAssigExtensionRequests.CCEStudentID=CCEStudentAssignments.CCEStudentID
                        AND CCEStAssigExtensionRequests.CCEAssignmentID=CCEStudentAssignments.CCEAssignmentID)
                    WHERE CCEStAssigExtensionRequests.Status='" . $arrRow["Status"] . "' ";

                if ($CCEStudentAssigID > 0) {
                    $sql .= "AND CCEStudentAssignments.CCEStudentAssigID=" . $CCEStudentAssigID;
                } else {
                    $sql .= "AND CCEStAssigExtensionRequests.CCEStudentID=" . intval($key) . " 
                        AND CCEStAssigExtensionRequests.CCEAssignmentID=" . intval($_REQUEST["id"]);
                }

                $sql .= " ORDER BY CCEStAssigExtensionID DESC LIMIT 0,1";

                // echo $sql;
                // exit;
                $rec = mysqli_query($conni, $sql);
                if ($row = mysqli_fetch_assoc($rec)) {
                    // No more grace period for late assignments
                    //                    $arrRow["DaysLate"] = floor((strtotime($row["DateSubmitted"]) - strtotime($row["CCEExtensionDate"])) / (24 * 60 * 60)) - 1;
                    $arrRow["DaysLate"] = floor((strtotime($row["DateSubmitted"]) - strtotime($row["CCEExtensionDate"])) / (24 * 60 * 60));
                    //                    echo $arrRow["DaysLate"] . '<br />';
                    //                    exit;
                    if ($arrRow["DaysLate"] < 0)
                        $arrRow["DaysLate"] = 0;
                    if ($arrRow["DaysLate"] > 0) {
                        if (!isset($arrRow["SubOnTime"]))
                            $arrRow["SubOnTime"] = "N";
                        /*
                          if (strtotime($row["DateSubmitted"])>strtotime("+8 days", strtotime($row["CCEExtensionDate"]." 23:59"))) {
                          if (!isset($arrRow["Over1WeekLate"])) $arrRow["Over1WeekLate"]="Y";
                          } else {
                          if (!isset($arrRow["Over1WeekLate"])) $arrRow["Over1WeekLate"]="N";
                          }
                         */
                    } else {
                        if (!isset($arrRow["SubOnTime"]))
                            $arrRow["SubOnTime"] = "Y";
                        //if (!isset($arrRow["Over1WeekLate"])) $arrRow["Over1WeekLate"]="N";
                    }
                }
            }
            //            var_dump($rowkey);
            //            echo "\r\n";
            //            echo $sql . ' - ' . $arrRow["DaysLate"] . ' days late' . "\r\n";
            //if (($arrRow["SubOnTime"]=="Y") && ($arrRow["Over1WeekLate"]=="Y")) $arrRow["Over1WeekLate"]="N";
            //            $sqlSA = "SELECT MAX(CCEAssignmentMarking.CCEStudentAssigID) AS CCEStudentAssigID FROM CCEAssignmentMarking JOIN CCEStudentAssignments USING (CCEStudentAssigID) "
            //                    . "WHERE CCEStudentID=" . intval($key) . " AND CCEAssignmentID=" . intval($_REQUEST["id"]);

            $sqlSA = "SELECT MAX(CCEStudentAssignments.CCEStudentAssigID) AS CCEStudentAssigID FROM CCEStudentAssignments "
                . "WHERE CCEStudentID=" . intval($key) . " AND CCEAssignmentID=" . intval($_REQUEST["id"]);
            //            echo $sql;
            //            exit;
            $rec = mysqli_query($conni, $sqlSA);
            if ($rec && $row = mysqli_fetch_assoc($rec)) {
                $studentAssigId = isset($row['CCEStudentAssigID']) ? intval($row['CCEStudentAssigID']) : 0;

                // Prevent invalid SQL updates when no student-assignment row exists yet.
                if ($studentAssigId <= 0) {
                    ErrorLog::logInfo("This student has not submitted this assignment yet. " . $sqlSA);
                    $sError = "This student has not submitted this assignment yet.";
                    break;
                }

                if (isset($_SESSION[EW_SESSION_USER_NAME]) && strlen($_SESSION[EW_SESSION_USER_NAME]) > 0) {
                    $sMarkedBy = $_SESSION[EW_SESSION_USER_NAME];
                } else {
                    // Call function in CCEAssignmentMarking.php to get marked by user
                    $sMarkedBy = $cceAssignmentMarkingObj->getMarkedByUser($studentAssigId);
                }

                $sql = "UPDATE CCEAssignmentMarking SET Score=NULL, ";
                $arrCols = array();
                foreach ($arrRow as $colName => $val) {
                    if (!in_array($colName, array("CCEExtensionDate", "Status", "StatusReason", "Motivation", "SupportingDoc", "Student", "FeedbackSent", "DateSubmitted"))) {
                        $arrCols[] = "`" . $colName . "`='" . sanitizeForDatabase($val, $conni) . "'";
                    }
                }
                $sql .= implode(", ", $arrCols);
                $sql .= " WHERE CCEStudentAssigID=" . $studentAssigId;

                // echo $sql;
                // echo var_dump($row["CCEStudentAssigID"]);
                // exit;

                $cceStAssigExtensionRequestObj = new CCEStAssigExtensionRequest($sqlf);

                if (count($arrCols) > 0) {
                    if (count($arrFieldErrs) == 0) {
                        if (!mysqli_query($conni, $sql)) {
                            // echo $sql . '<br />';
                            $sError = "Database error, could not update: " . mysqli_errno($conni) . ' - ' . mysqli_error($conni) . ' - ' . $sqlSA . ' - ' . $sql . ' - ' . print_r($row, true);
                            // echo $sError;
                            // exit;
                        } else {
                            // Update score
                            $sql = "SELECT * FROM CCEAssignmentMarking WHERE CCEStudentAssigID=" . $studentAssigId;
                            $rec = mysqli_query($conni, $sql);
                            if ($arrRow = mysqli_fetch_assoc($rec)) {

                                $sOnTime = $arrRow["SubOnTime"];
                                // $iDaysLate = $arrRow["DaysLate"];
                                $iDaysLate = $cceAssignmentMarkingObj->getLateDays(intval($_REQUEST["id"]), intval($key), $studentAssigId);
                                $sReferences = $arrRow["References"];
                                $Ruling = $arrRow["Ruling"];
                                // echo $iDaysLate . "\r\n";
                                $feedback[] = $iDaysLate . ' calculated days late';

                                $cceStAssigExtensionRequest = $cceStAssigExtensionRequestObj->getLastExtensionRequest(
                                    intval($key),
                                    $_REQUEST["id"],
                                    $studentAssigId
                                );
                                $feedback[] = 'Extension request: ' . print_r($cceStAssigExtensionRequest, true);

                                if (is_array($cceStAssigExtensionRequest) && count($cceStAssigExtensionRequest) > 0 && in_array($cceStAssigExtensionRequest['Status'], ['P', 'A'])) {
                                    // Calculate new days late
                                    $studentAssignmentObj = new CCEStudentAssignment($sqlf);
                                    $studentAssignment = $studentAssignmentObj->find($row["CCEStudentAssigID"]);

                                    $dateSubmitted = new DateTime($studentAssignment['DateSubmitted']);
                                    $dateSubmitted->setTime(0, 0, 0);
                                    $dateExtension = new DateTime($cceStAssigExtensionRequest['CCEExtensionDate']);
                                    $dateExtension->setTime(0, 0, 0);
                                    $feedback[] = 'Extension date: ' . $cceStAssigExtensionRequest['CCEExtensionDate'] . ' - ' . $dateExtension->format('Y-m-d') . ' - ' . 'Submitted date: ' . $dateSubmitted->format('Y-m-d') . "\r\n";
                                    $iDaysLate = ceil($dateExtension->diff($dateSubmitted)->days);
                                }
                                $feedback[] = 'Days late: ' . $iDaysLate . "\r\n";

                                if (!empty($sOnTime) && !empty($sReferences) && !empty($Ruling)) {

                                    $RulingPrev = "";
                                    $rulingPrevRow = [];
                                    //                                    $sql = "SELECT CASE WHEN sa.RulingCode IS NULL THEN am.Ruling ELSE sa.RulingCode END AS RulingCode "
                                    //                                            . "FROM CCEStudentAssignments sa "
                                    //                                            . "LEFT OUTER JOIN CCEAssignmentMarking am ON sa.CCEStudentAssigID = am.CCEStudentAssigID "
                                    //                                            . "WHERE sa.CCEStudentID=" . intval($key) . " AND sa.CCEAssignmentID=" . intval($_REQUEST["id"]) . " "
                                    //                                            . "ORDER BY sa.CCEStudentAssigID DESC"; // . $row["CCEStudentAssigID"];
                                    $sql = "SELECT CCEStudentAssignments.RulingCode, CCEAssignmentMarking.DaysLate, CCEAssignmentMarking.References, "
                                        . "CCEStudentAssignments.CCEStudentAssigID, CCEAssignmentMarking.SubOnTime "
                                        . "FROM CCEStudentAssignments "
                                        . "LEFT JOIN CCEAssignmentMarking ON CCEStudentAssignments.CCEStudentAssigID = CCEAssignmentMarking.CCEStudentAssigID "
                                        . "WHERE CCEStudentAssignments.CCEStudentID=" . intval($key)
                                        . " AND CCEStudentAssignments.CCEAssignmentID=" . intval($_REQUEST["id"]) . " "
                                        . "AND CCEStudentAssignments.CCEStudentAssigID<" . $studentAssigId;

                                    // echo $sql;
                                    // exit;

                                    $recPrev = mysqli_query($conni, $sql);

                                    if ($rowPrev = mysqli_fetch_assoc($recPrev)) {
                                        $RulingPrev = $rowPrev["RulingCode"];
                                        $rulingPrevRow = $rowPrev;
                                    }

                                    $iScore = 0;

                                    if ($Ruling != "R") {
                                        if ($Ruling == "E")
                                            $iScore = 10;
                                        if ($Ruling == "AE")
                                            $iScore = 9;
                                        if ($Ruling == "A")
                                            $iScore = 8;
                                        if ($Ruling == "AL")
                                            $iScore = 7;
                                        if ($Ruling == "AC")
                                            $iScore = 6;
                                        if ($RulingPrev == "R") {

                                            $iScore -= 1;

                                            if (is_array($rulingPrevRow) && count($rulingPrevRow) > 0) {

                                                if ($rulingPrevRow['SubOnTime'] != 'Y') {
                                                        $iScore -= $cceAssignmentMarkingObj->calcDaysLatePenalty(
                                                        $rulingPrevRow['DaysLate']
                                                    );
                                                }

                                                $feedback[] = 'Days late on previous submission: ' . $rulingPrevRow['DaysLate'];

                                                if ($rulingPrevRow['References'] == "N") {
                                                    $feedback[] = 'No references on previous submission';
                                                    $iScore -= 1;
                                                }

                                                // Check for extension with Penalty on previous submission
                                                $prevExtensionRequest = $cceStAssigExtensionRequestObj->getLastExtensionRequest(
                                                    $rulingPrevRow["CCEStudentID"],
                                                    $_REQUEST["id"],
                                                    $rulingPrevRow["CCEStudentAssigID"]
                                                );

                                                if (is_array($prevExtensionRequest) && count($prevExtensionRequest) > 0 && $prevExtensionRequest['Status'] == 'P') {
                                                    $feedback[] = 'Penalty on previous submission';
                                                    $iScore -= 1;
                                                }
                                            }
                                        }
                                        //                                        if ($Ruling == "AC")
                                        //                                            $iScore -= 1;
                                        if (!in_array($sReferences, ["Y", "N/A"]))
                                            $iScore -= 1;
                                        if ($sOnTime != "Y") {

                                            if ($iDaysLate > 0) {
                                                $iScore -= 1 + (($iDaysLate - 1) * 0.5);
                                            }
                                            // $iScore -= ($iDaysLate * 0.5);
                                        }
                                    }

                                    if (is_array($cceStAssigExtensionRequest) && count($cceStAssigExtensionRequest) > 0 && $cceStAssigExtensionRequest['Status'] == 'P') {
                                        $feedback[] = 'Subtracting score for penalty!';
                                        $iScore -= 1;
                                    }

                                    if ($iScore < 0)
                                        $iScore = 0;
                                    $sql = "UPDATE CCEAssignmentMarking SET Score=" . $iScore . ", DateMarked=NOW(), MarkedByUser='" . $sMarkedBy . "' "
                                        . "WHERE CCEStudentAssigID=" . $studentAssigId;
                                    $feedback[] = 'SQL updated: ' . $sql;
                                    $feedback[] = 'Score: ' . $iScore;
                                    mysqli_query($conni, $sql);
                                }
                                $arrCols[] = "`Score`=" . $iScore;
                            } //Select CCEAssignmentMarking
                        }
                    }
                }
            }
        } //foreach
        $sWhere .= "1=0) ";
    }

    if ($_POST["action"] == "remove") {
        $sWhere = '(';
        foreach ($arrData as $rowkey => $arrRow) {
            $key = array_shift(explode("_", $rowkey));
            if ($cceStudentsMarkingGuard && $markingAssignmentModuleId > 0
                && $cceStudentsMarkingGuard->isExcludedFromModule(intval($key), $markingAssignmentModuleId)) {
                $sError .= "Student is excluded from this module; marking cannot be deleted.\n";
                continue;
            }
            $sWhere .= "CCEStudents.CCEStudentID=" . intval($key) . " OR ";

            $sql = "SELECT MAX(CCEAssignmentMarking.CCEStudentAssigID) AS CCEStudentAssigID FROM CCEAssignmentMarking JOIN CCEStudentAssignments USING (CCEStudentAssigID) "
                . "WHERE CCEStudentID=" . intval($key) . " AND CCEAssignmentID=" . intval($_REQUEST["id"]);
            //            echo $sql;
            $rec = mysqli_query($conni, $sql);
            if ($row = mysqli_fetch_assoc($rec)) {
                $sql = "UPDATE CCEAssignmentMarking SET MarkedByUser=NULL, Ruling=NULL, `References`=NULL, Score=NULL, DateMarked=NULL, GeneralComments=NULL,
				Comment1=NULL, Comment2=NULL, Comment3=NULL, Comment4=NULL, Comment5=NULL, Comment6=NULL, Comment7=NULL,
				Comment8=NULL, Comment9=NULL, Comment10=NULL, Comment11=NULL, Comment12=NULL, Comment13=NULL, Comment14=NULL, Comment15=NULL
				WHERE CCEStudentAssigID=" . $row["CCEStudentAssigID"];
                if (!mysqli_query($conni, $sql)) {
                    $sError = "Database error, could not delete";
                }
            }
        } //foreach
        $sWhere .= "1=0) ";
    }
}
?>
{
<?php
$sql = "SELECT CCEModuleID FROM CCEAssignments WHERE CCEAssignmentID=" . intval($_REQUEST["id"]);
$rec = mysqli_query($conni, $sql);
$row = mysqli_fetch_assoc($rec);
$assignmentModuleId = isset($row["CCEModuleID"]) ? (int) $row["CCEModuleID"] : 0;

$sql = "SELECT CCEStudents.CCEStudentID, CONCAT(CCEStudents.KnownAs, ' ', CCEStudents.Surname) AS Student,
CCEStudents.ModulesEnrolled, CCEStudents.ModulesExcluded, CCEAssignments.CCEAssignmentID, CCEAssignments.CCEModuleID, CCEStudentAssignments.DateSubmitted,
IFNULL(CCEFacilitatorUsers.FullName, CCEAssignmentMarking.MarkedByUser) AS MarkedBy, CCEMessages.SentDateTime AS FeedbackSent,
CCEStudentAssignments.AssignmentFile1, CCEStudentAssignments.AssignmentFile2, CCEStudentAssignments.AssignmentFile3,
CCEStudentAssignments.AssignmentFile4, CCEStudentAssignments.AssignmentFile5,
CCEAssignmentMarking.*
FROM CCEStudents LEFT JOIN (CCEStudentAssignments
JOIN CCEAssignments USING (CCEAssignmentID)
JOIN CCEAssignmentMarking USING (CCEStudentAssigID))
ON (CCEStudents.CCEStudentID=CCEStudentAssignments.CCEStudentID
AND CCEStudentAssignments.DateSubmitted>='" . date("Y") . "-01-01'";
if (isset($_REQUEST["id"]))
    $sql .= " AND CCEStudentAssignments.CCEAssignmentID=" . intval($_REQUEST["id"]);
$sql .= ")
LEFT JOIN CCEFacilitatorUsers ON (MarkedByUser=Username)
LEFT JOIN (CCEAssignmentFeedback INNER JOIN CCEMessages USING (CCEMessageID)) USING (CCEStudentAssigID)
WHERE CCEStudents.Archived=0 AND CCEStudents.CCEStudentID in (select CCEStudentID from CCEStudentCourses, CCESetup WHERE CCECourseScheduleID=CurrentScheduleID)
AND CCEStudents.ModulesEnrolled LIKE '%" . $assignmentModuleId . "%' ";

if (true && $env == 'prod') {
    $sql .= " AND CCEStudents.CCEStudentID <> 54 ";
}

if (!empty($sWhere))
    $sql .= " AND " . $sWhere;
$sql .= " ORDER BY " . CCEStudentDisplayOrder::sqlOrderByDisplayName('CCEStudents') . ", CCEAssignmentMarking.CCEStudentAssigID";

//echo $sql;
mysqli_free_result($rec);
$rec = mysqli_query($conni, $sql);
?>
"sql": <?php echo json_encode($sql); ?>,
"request_data": <?php echo json_encode($_REQUEST); ?>
<?php
if ($rec && mysqli_num_rows($rec) > 0) {
?>,
"data": [
<?php
    $arrData = array();
    $iRow = 0;
    $editorFiles = array();

    // while ($row = mysqli_fetch_assoc($rec)) {
    //     $cceAssignmentMarkingObj->getLateDays(intval($_REQUEST["id"]), $row['CCEStudentID']);
    // }

    // mysqli_free_result($rec);
    // $rec = mysqli_query($conni, $sql);

    while ($row = mysqli_fetch_assoc($rec)) {

        $utf8row = $row;

        for ($cCnt = 1; $cCnt <= 15; $cCnt++) {
            if (!isset($row['COMMENT' . $cCnt])) {
                continue;
            }
            $utf8row['Comment' . $cCnt] = $row['COMMENT' . $cCnt];
        }

        $utf8row["rowkey"] = $row["CCEStudentID"] . "_" . $row["CCEStudentAssigID"];

        //        $utf8row['Status'] = '';
        //        $utf8row['Motivation'] = '';
        //        $utf8row['SupportingDoc'] = '';
        //        $utf8row['CCEExtensionDate'] = '';
        //        $utf8row['DateRequested'] = '';
        //        $utf8row['DateUpdated'] = '';
        //        $utf8row['UpdatedBy'] = '';
        $utf8row['extensions'] = array();
        if ($row["CCEStudentAssigID"] <= 0) {
            $row["CCEStudentAssigID"] = -1;
        }

        $sql = "SELECT CCEStAssigExtensionRequests.CCEExtensionDate, CCEStAssigExtensionRequests.Status, "
            . "CCEStAssigExtensionRequests.StatusReason, CCEStAssigExtensionRequests.Motivation, "
            . "CCEStAssigExtensionRequests.SupportingDoc, CCEStAssigExtensionRequests.DateRequested, "
            . "CCEStAssigExtensionRequests.DateUpdated, CCEStAssigExtensionRequests.UpdatedBy "
		    . "FROM CCEStAssigExtensionRequests "
		    . "WHERE ( "
            . "CCEStAssigExtensionRequests.CCEStudentID=" . $row["CCEStudentID"] . " "
            . "AND CCEStAssigExtensionRequests.CCEAssignmentID=" . intval($_REQUEST["id"]);

        if ($row["CCEStudentAssigID"] > 0) {
            $sql .= " AND ( "
                . "CCEStAssigExtensionRequests.CCEStudentAssigID IS NULL "
                . "OR CCEStAssigExtensionRequests.CCEStudentAssigID = 0 "
                . "OR CCEStAssigExtensionRequests.CCEStudentAssigID = " . intval($row["CCEStudentAssigID"])
                . ")";
        }
        
        $sql .= " ) ORDER BY CCEStAssigExtensionID DESC";

        if ($row["CCEStudentAssigID"] == 392) {
            // echo $sql . "\r\n";
            // exit;
        }

        $utf8row['extensions_sql'] = $sql;
        $rec2 = mysqli_query($conni, $sql);
        $extensionsFound = false;
        while ($rec2 && $row2 = mysqli_fetch_assoc($rec2)) {

            $extensionsFound = true;

            $oneExtension = array(
                'Status' => '',
                'StatusReason' => '',
                'Motivation' => '',
                'SupportingDoc' => '',
                'CCEExtensionDate' => '',
                'DateRequested' => '',
                'DateUpdated' => '',
                'UpdatedBy' => '',
            );

            $oneExtension["Status"] = $row2["Status"];
            $oneExtension["StatusReason"] = $row2["StatusReason"];
            $oneExtension["Motivation"] = $row2["Motivation"];
            $oneExtension["SupportingDoc"] = $row2["SupportingDoc"];
            if (!empty($row2["CCEExtensionDate"]))
                $oneExtension["CCEExtensionDate"] = date("Y-m-d", strtotime($row2["CCEExtensionDate"]));
            if (!empty($row2["DateRequested"]))
                $oneExtension["DateRequested"] = date("m-d H:i", strtotime($row2["DateRequested"]));
            if (!empty($row2["DateUpdated"]))
                $oneExtension["DateUpdated"] = date("Y-m-d", strtotime($row2["DateUpdated"]));
            if (!empty($row2["UpdatedBy"]))
                $oneExtension["UpdatedBy"] = $row2["UpdatedBy"];

            if (!isset($utf8row['CCEExtensionDate'])) {
                $utf8row = array_merge($utf8row, $oneExtension);
            }

            $utf8row['extensions'][] = $oneExtension;
        } //while extensions

        if (!$extensionsFound) {
            $utf8row['extensions'][] = array('Status' => 'None');
        }

        if (!empty($row["DateSubmitted"]))
            $utf8row["DateSubmitted"] = date("Y-m-d H:i", strtotime($row["DateSubmitted"]));
        if (!empty($row["DateMarked"]))
            $utf8row["DateMarked"] = date("Y-m-d", strtotime($row["DateMarked"]));
        if (!empty($row["FeedbackSent"]))
            $utf8row["FeedbackSent"] = date("Y-m-d", strtotime($row["FeedbackSent"]));

        $sourceRow = $utf8row;

        array_walk_recursive($utf8row, function (&$value) {
            $value = utf8_encode(str_replace("/", " / ", $value));
        });

        $utf8row = $cceUploadedFileService->enrichConvenorMarkingRowUrls(
            $utf8row,
            intval($_REQUEST["id"]),
            $sourceRow
        );

        $excludedModuleIds = CCEStudents::parseModulesExcludedCsv(
            isset($sourceRow["ModulesExcluded"]) ? $sourceRow["ModulesExcluded"] : (
                isset($row["ModulesExcluded"]) ? $row["ModulesExcluded"] : ''
            )
        );
        $utf8row["ModuleExcluded"] = ($assignmentModuleId > 0
            && in_array($assignmentModuleId, $excludedModuleIds, true));

        if (!empty($sourceRow['FileUpload']) && !empty($utf8row['FileUploadUrl'])) {
            $editorFiles[(string) $sourceRow['FileUpload']] = array(
                'filename' => (string) $sourceRow['FileUpload'],
                'web_path' => (string) $utf8row['FileUploadUrl'],
            );
        }
        if (!empty($sourceRow['extensions']) && is_array($sourceRow['extensions'])) {
            foreach ($sourceRow['extensions'] as $index => $extension) {
                if (!is_array($extension) || empty($extension['SupportingDoc']) || empty($utf8row['extensions'][$index]['SupportingDocUrl'])) {
                    continue;
                }
                $editorFiles[(string) $extension['SupportingDoc']] = array(
                    'filename' => (string) $extension['SupportingDoc'],
                    'web_path' => (string) $utf8row['extensions'][$index]['SupportingDocUrl'],
                );
            }
        }

        //	echo json_encode(array($row["ContactsID"],$row["Organisation"],$row["FirstName"],$row["Surname"],$row["EmailAddress"],$row["Telephone1"],$row["Telephone2"],$row["Position"]));
        echo json_encode($utf8row, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
        $iRow++;
        if ($iRow < mysqli_num_rows($rec))
            echo ",";
        echo "\r\n";
    } //while
?>
]<?php
    if (!empty($editorFiles)) {
?>,
"files": {
    "files": <?php echo json_encode($editorFiles, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); ?>

}
<?php
    }
}

if (is_array($feedback) && count($feedback) > 0) {
    // $sError .= json_encode($feedback, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}

if (!empty($sError)) {

    ErrorLog::logError($sError);
    ?>,
"error": <?php echo json_encode($sError); ?><?php
                                        }
                                        if (count($arrFieldErrs) > 0) {
                                            ?>,
"fieldErrors": [
<?php
                                            $iRow = 0;
                                            foreach ($arrFieldErrs as $arrErr) {
                                                echo json_encode($arrErr, JSON_FORCE_OBJECT);
                                                $iRow++;
                                                if ($iRow < count($arrFieldErrs))
                                                    echo ",";
                                                echo "\r\n";
                                            }
?>
]
<?php
                                        }
?>
}
<?php

/*
function maill($to, $subject, $message) {
    $mail = new PHPMailer();
    $mail->IsMail();  // use PHP mail function
    $mail->From = "brenda@cesa.co.za";
    $mail->FromName = "BCE CESAnet";
    $to = str_replace(";", ",", $to);
    $arrto = explode(",", $to);

    for ($ito = 0; $ito < count($arrto); $ito++) {
        if (!empty($arrto[$ito]))
            $mail->AddAddress(trim($arrto[$ito]));
    }

    $mail->Subject = $subject;
    $mail->IsHtml(false);
    $mail->Body = $message;

    $mail->Send();
}
 */