Adapt user insertion and logic to Física UB

Change-Id: Iece1abb1e2611c7fc77f379dca89ce3aead1a2d7
diff --git a/admin/insert.php b/admin/insert.php
index 3a22ca4..5a50a8f 100644
--- a/admin/insert.php
+++ b/admin/insert.php
@@ -13,16 +13,46 @@
 	// Read from CSV
 	$inscrits = array_map('str_getcsv', file($csvname));
 	array_shift($inscrits); // remove header
+
+	foreach ($inscrits as $key => &$inscrit) {
+		$inscrit["key"] = $key;
+	}
+
 	shuffle($inscrits); // shuffle randomly
-	
+
+	$forceposraw = $_POST['forcepos'] ?? "[]";
+	$forcepos = json_decode($forceposraw, true);
+	foreach ($forcepos as $pos) {
+		if (!isset($pos["id"]) || !isset($pos["pos"])) continue;
+
+		// Switch entry with key |$pos["id"]| to position |$pos["pos"]|.
+		$key = -1;
+		foreach ($inscrits as $itKey => &$inscrit) {
+			if ($inscrit["key"] == $pos["id"]) {
+				$key = $itKey;
+				break;
+			}
+		}
+		if ($key === -1) continue;
+
+		// Switch places
+		$tmp = $inscrits[$pos["pos"]];
+		$inscrits[$pos["pos"]] = $inscrits[$key];
+		$inscrits[$key] = $tmp;
+	}
+
 	$start = 1;
 	$i = $start;
 	foreach ($inscrits as $user) {
 		$i = ($i + 1) % ($start + count($inscrits));
 		if ($i == 0) $i = $i + 1;
+		$nom = mysqli_real_escape_string($conn, $user[0]);
+		$curs = mysqli_real_escape_string($conn, $user[1]);
+		$grau = mysqli_real_escape_string($conn, $user[2]);
+		$password = mysqli_real_escape_string($conn, password_hash($user[3], PASSWORD_DEFAULT));
 		// Input values into SQL values
 		$template = "INSERT INTO `$dbname` (`id`, `nom`, `curs`, `grau`, `quimata`, `requested`, `mort`, `password`, `bits`)" .
-					" VALUES (NULL, '$user[0]', '$user[1]', '$user[2]', $i, 0, 0, '', ".(int)rand(1,512).")";
+					" VALUES (NULL, '$nom', '$curs', '$grau', $i, 0, 0, '$password', ".(int)rand(1,512).")";
 
 		if (!query($template)) die("An error ocurred." . $template);
 	}