static function formatSchool($name, $city, $country)
 {
     $saniValid = 1;
     $msgs = "";
     foreach (array("name", "city", "country") as $field) {
         // Let's try to sanitize it
         try {
             ${$field} = DataSanitizer::formatNameComplex(${$field});
         } catch (Exception $e) {
             // Oups : do not modify it, it will be checked in the future
             // Statistically : 0.5% of names only
             $saniValid = 0;
             $msgs .= $e->getMessage() . ";";
         }
     }
     // The name has been fixed, let's try to format the school category
     try {
         $name = DataSanitizer::postFormatSchoolName($name);
     } catch (Exception $e) {
         $saniValid = 0;
         $msgs .= $e->getMessage() . ";";
     }
     return array($name, $city, $country, $saniValid, $msgs);
 }
function checkAndCorrectSchoolField($field, $execRequests = false)
{
    global $db;
    if (!in_array($field, array("city", "country", "name"))) {
        echo "INVALID FIELD {$field}";
        return;
    }
    /*
    if ($field == "city")
    {
       $query = "UPDATE school SET saniMsg = ''";
       $db->prepare($query)->execute();
    }
    */
    $query = "\n      SELECT \n         `school`.ID, \n         `school`.{$field}\n      FROM `school`\n      WHERE\n          `school`.`orig_" . $field . "` IS NULL      \n      ";
    $stmt = $db->prepare($query);
    $stmt->execute();
    $all = array();
    while ($row = $stmt->fetchObject()) {
        $all[] = $row;
    }
    //$all[] = (object)array('ID'=>-1, 'city' => 'Aude', "$field"=>"Bidule de Truc Machin de la marne d'arras de l'eau");
    $updateQuery = "UPDATE school SET `orig_" . $field . "` = `" . $field . "`, `" . $field . "` = :value, `saniValid` = :saniValid, saniMsg = CONCAT(saniMsg, :saniMsg) WHERE ID = :ID";
    $updateStmt = $db->prepare($updateQuery);
    foreach ($all as $row) {
        $newVal = $row->{$field};
        $saniValid = 1;
        $msg = "";
        try {
            $newVal = DataSanitizer::formatNameComplex($row->{$field});
            if ($field == 'name') {
                $newVal = DataSanitizer::postFormatSchoolName($newVal);
            }
            if ($newVal != $row->{$field}) {
                echo "DIFF : {$row->{$field}} => {$newVal}<br/>\n";
            } else {
                echo "GOOD : {$row->{$field}}<br/>\n";
            }
        } catch (Exception $e) {
            $saniValid = 0;
            $msg = $e->getMessage() . ";";
            echo "ERROR : (id={$row->ID}) {$row->{$field}} => " . $e->getMessage() . "<br/>\n";
        }
        if ($execRequests) {
            $updateStmt->execute(array(':ID' => $row->ID, ':value' => $newVal, ':saniValid' => $saniValid, ":saniMsg" => $msg));
        }
    }
    echo "Updated schools (" . $field . ") : " . count($all) . "<br/>";
}
function createTeam($db, $contestants)
{
    global $tinyOrm, $config;
    if ($_SESSION["groupClosed"]) {
        error_log("Hack attempt ? trying to create team on closed group " . $_SESSION["groupID"]);
        echo json_encode(array("success" => false, "message" => "Groupe fermé"));
        return;
    }
    if (isset($_SESSION["userCode"])) {
        $password = $_SESSION["userCode"];
    } else {
        $password = genAccessCode($db);
    }
    $stmt = $db->prepare("INSERT INTO `team` (`groupID`, `password`) VALUES (?, ?)");
    $stmt->execute(array($_SESSION["groupID"], $password));
    $teamID = $db->lastInsertId();
    if ($config->db->use == 'dynamoDB') {
        try {
            $tinyOrm->insert('team', array('ID' => $teamID, 'groupID' => $_SESSION["groupID"], 'password' => $password));
        } catch (\Aws\DynamoDb\Exception $e) {
            error_log($e->getMessage . " - " . $e->getCode());
            error_log('DynamoDB error creating team, teamID: ' . $teamID);
        }
    }
    $stmt = $db->prepare("UPDATE `group` SET `startTime` = NOW() WHERE `group`.`ID` = ? AND `startTime` IS NULL");
    $stmt->execute(array($_SESSION["groupID"]));
    $stmt = $db->prepare("UPDATE `group` SET `nbTeamsEffective` = `nbTeamsEffective` + 1, `nbStudentsEffective` = `nbStudentsEffective` + ? WHERE `ID` = ?");
    $stmt->execute(array(count($contestants), $_SESSION["groupID"]));
    $_SESSION["teamID"] = $teamID;
    $_SESSION["teamPassword"] = $password;
    foreach ($contestants as $contestant) {
        if (!isset($contestant["grade"])) {
            $contestant["grade"] = -2;
        }
        list($contestant["firstName"], $contestant["lastName"], $saniValid, $trash) = DataSanitizer::formatUserNames($contestant["firstName"], $contestant["lastName"]);
        $stmt = $db->prepare("\n         INSERT INTO `contestant` (`lastName`, `firstName`, `genre`, `grade`, `teamID`, `cached_schoolID`, `saniValid`) \n         VALUES (?, ?, ?, ?, ?, ?, ?)");
        $stmt->execute(array($contestant["lastName"], $contestant["firstName"], $contestant["genre"], $contestant["grade"], $teamID, $_SESSION["schoolID"], $saniValid));
    }
    echo json_encode((object) array("success" => true, "teamID" => $teamID, "password" => $password));
}
function checkRequestSchool($db, &$request, &$record, $operation, &$roles)
{
    // Generated fields
    list($record["name"], $record["city"], $record["country"], $record["saniValid"], $record["saniMsg"]) = DataSanitizer::formatSchool($record["name"], $record["city"], $record["country"]);
    $roles[] = "generator";
    list($lat, $lng, $msg) = getCoordinatesSchool($record);
    $record["saniMsg"] .= $msg;
    $record['coords'] = $lng . "," . $lat . ",0";
    if (!$_SESSION["isAdmin"] || $operation === "insert") {
        $record["userID"] = $_SESSION["userID"];
    }
    // Filters
    if (!$_SESSION["isAdmin"]) {
        $request["filters"]["accessUserID"] = array('values' => array('userID' => $_SESSION["userID"]));
        $request["filters"]["userID"] = $_SESSION["userID"];
    }
    return true;
}