diff --git a/api/index.php b/api/index.php index 3c82bb6..878c818 100644 --- a/api/index.php +++ b/api/index.php @@ -120,7 +120,7 @@ switch ($VARS['action']) { case "addmachine": dieWithoutRole(Roles::ROLE_ADDEDIT); if (empty($VARS['id'])) { - sendError("nomachineid"); + $VARS['id'] = Machine::generateId(); } if ($database->has('machines', ['machineid' => $VARS['id']])) { sendError("", "A machine with that ID already exists."); @@ -157,7 +157,7 @@ switch ($VARS['action']) { if ($database->error()[1] != 0) { sendError("dberror", $database->error()[2]); } - exit(json_encode(["status" => "OK"])); + exit(json_encode(["status" => "OK", "id" => $data['machineid']])); break; case "addhistory": dieWithoutRole([Roles::ROLE_ADDEDIT, Roles::ROLE_ADDHIST]); diff --git a/machine.php b/machine.php index 2767fa4..2605065 100644 --- a/machine.php +++ b/machine.php @@ -118,4 +118,20 @@ class Machine { $database->insert('components', ['serial' => $serial, 'typeid' => $type, 'tested' => $tested, 'notes' => $notes, 'capacity' => $capacity, 'model' => $model, 'machineid' => $this->machineid]); } + + /** + * Generate a random machine ID number that is not in use. + * @global $database + * @param int $min Optional minimum number. + * @param int $max Optional maximum number. + * @return int + */ + public static function generateId(int $min = 1000000000, int $max = 9999999999): int { + global $database; + $id = random_int(1000000000, 9999999999); + while ($database->has('machines', ['machineid' => $id])) { + $id = random_int(1000000000, 9999999999); + } + return $id; + } }