Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Registration cleanup (part 2) #173

Merged
merged 13 commits into from
Mar 18, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 4 additions & 0 deletions includes/db.php
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,10 @@ function closeDBLink() {
$_DBLink->close();
}

function getLastInsertId () {
return getDBLink()->insert_id;
}

function mapQueryResults ($results, callable $callback) {
if ($results->num_rows <= 0) {
return [];
Expand Down
11 changes: 11 additions & 0 deletions includes/unlocalised.php
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,17 @@ function array_map_withkeys(array $inputArray, callable $callback) {
return array_map($callback, $inputArray, array_keys($inputArray));
}

/**
* Maps an object, allowing to access the key of each value, and change both key & value
*/
function object_map(array $inputObject, callable $callback) {
return array_column(
array_map($callback, $inputObject, array_keys($inputObject)),
0,
1
);
}

// Important functions
function ReadFromFile($filename)
{
Expand Down
5 changes: 5 additions & 0 deletions modules/registration/_includes.php
Original file line number Diff line number Diff line change
Expand Up @@ -9,8 +9,13 @@
include($includePath . './components/RegistrationConfirmationMail/RegistrationConfirmationMail.component.php');

include($includePath . './utils/cookies.utils.php');
include($includePath . './utils/galaxy.utils.php');
include($includePath . './utils/general.utils.php');
include($includePath . './utils/queries.utils.php');

include($includePath . './validators/validateTakenParams.validators.php');
include($includePath . './validators/validateReCaptcha.validators.php');

});

?>
3 changes: 3 additions & 0 deletions modules/registration/utils/cookies.utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,9 @@

namespace UniEngine\Engine\Modules\Registration\Utils\Cookies;

/**
* @return float | null Sanitized user Id or `null`
*/
function getStoredReferrerId() {
if (empty($_COOKIE[REFERING_COOKIENAME])) {
return null;
Expand Down
159 changes: 159 additions & 0 deletions modules/registration/utils/galaxy.utils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,159 @@
<?php

namespace UniEngine\Engine\Modules\Registration\Utils\Galaxy;

// Arguments
// - $params (Object)
// - galaxy (Number)
// - systemMin (Number)
// - systemMax (Number)
// - planetMin (Number)
// - planetMax (Number)
// - invertPlanetCoords (Boolean)
//
function _getPlanetsInGalaxyBetweenCoordinates($params) {
$selectPlanetsQuery = (
"SELECT " .
"`system`, `planet` " .
"FROM {{table}} " .
"WHERE " .
"`galaxy` = {$params['galaxy']} AND " .
(
(
isset($params['systemMin']) &&
isset($params['systemMax'])
) ?
"`system` BETWEEN {$params['systemMin']} AND {$params['systemMax']} AND " :
""
) .
"`planet` " . (!empty($params['systemMax']) ? "NOT" : "") . " BETWEEN {$params['planetMin']} AND {$params['planetMax']} " .
";"
);

$selectPlanetsResult = doquery($selectPlanetsQuery, 'galaxy');

$selectPlanets = mapQueryResults($selectPlanetsResult, function ($planetRow) {
return "{$planetRow['system']}:{$planetRow['planet']}";
});
$selectPlanets = object_map($selectPlanets, function ($value, $key) {
return [
true,
$value
];
});

return $selectPlanets;
}

// Arguments
// - $params (Object)
// - preferredGalaxy (Number)
//
function findNewPlanetPosition($params) {
$GalaxyNo = $params['preferredGalaxy'];

$SystemsRange = 25;
$SystemRandom = mt_rand(1, MAX_SYSTEM_IN_GALAXY);

if (($SystemRandom + $SystemsRange) >= MAX_SYSTEM_IN_GALAXY) {
$System_Lower = $SystemRandom - $SystemsRange;
} else {
$System_Lower = $SystemRandom;
}

$System_Higher = $System_Lower + $SystemsRange;
$Planet_Lower = 4;
$Planet_Higher = 12;

// - Attempt 1: check random range of solar systems
$Position_NonFree = _getPlanetsInGalaxyBetweenCoordinates([
'galaxy' => $GalaxyNo,
'systemMin' => $System_Lower,
'systemMax' => $System_Higher,
'planetMin' => $Planet_Lower,
'planetMax' => $Planet_Higher,
]);
$Position_NonFreeCount = count($Position_NonFree);
$Position_TotalCount = (($System_Higher - $System_Lower) + 1) * (($Planet_Higher - $Planet_Lower) + 1);

if (($Position_TotalCount - $Position_NonFreeCount) > 0) {
// TODO: Figure out a better, more deterministic way
while (true) {
$System = mt_rand($System_Lower, $System_Higher);
$Planet = mt_rand($Planet_Lower, $Planet_Higher);

if (!isset($Position_NonFree["{$System}:{$Planet}"])) {
return [
'galaxy' => $GalaxyNo,
'system' => $System,
'planet' => $Planet,
];
}
}
}


// - Attempt 2: check whole galaxy, if space not found earlier
$Position_NonFree = _getPlanetsInGalaxyBetweenCoordinates([
'galaxy' => $GalaxyNo,
'planetMin' => $Planet_Lower,
'planetMax' => $Planet_Higher,
]);
$Position_NonFreeCount = count($Position_NonFree);
$Position_TotalCount = MAX_SYSTEM_IN_GALAXY * (($Planet_Higher - $Planet_Lower) + 1);

if (($Position_TotalCount - $Position_NonFreeCount) > 0) {
// TODO: Figure out a better, more deterministic way
while (true) {
$System = mt_rand(1, MAX_SYSTEM_IN_GALAXY);
$Planet = mt_rand($Planet_Lower, $Planet_Higher);

if (!isset($Position_NonFree["{$System}:{$Planet}"])) {
return [
'galaxy' => $GalaxyNo,
'system' => $System,
'planet' => $Planet,
];
}
}
}

// - Attempt 3: check whole galaxy and all slots which has not been checked
$Planet_PosArray = [];
for ($i = 1; $i < $Planet_Lower; $i += 1) {
$Planet_PosArray[] = $i;
}
// TODO: Fix end range
for ($i = $Planet_Higher; $i < MAX_PLANET_IN_SYSTEM; $i += 1) {
$Planet_PosArray[] = $i;
}

$Position_NonFree = _getPlanetsInGalaxyBetweenCoordinates([
'galaxy' => $GalaxyNo,
'planetMin' => $Planet_Lower,
'planetMax' => $Planet_Higher,
'invertPlanetCoords' => true,
]);
$Position_NonFreeCount = count($Position_NonFree);
$Position_TotalCount = MAX_SYSTEM_IN_GALAXY * count($Planet_PosArray);

if (($Position_TotalCount - $Position_NonFreeCount) > 0) {
// TODO: Figure out a better, more deterministic way
while (true) {
$System = mt_rand(1, MAX_SYSTEM_IN_GALAXY);
$Planet = $Planet_PosArray[array_rand($Planet_PosArray)];

if (!isset($Position_NonFree["{$System}:{$Planet}"])) {
return [
'galaxy' => $GalaxyNo,
'system' => $System,
'planet' => $Planet,
];
}
}
}

return null;
}

?>
23 changes: 23 additions & 0 deletions modules/registration/utils/general.utils.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
<?php

namespace UniEngine\Engine\Modules\Registration\Utils\General;

use UniEngine\Engine\Modules\Registration\Utils;

/**
* @return float | null Sanitized user Id or `null`
*/
function getRegistrationReferrerId() {
$cookieReferrerId = Utils\Cookies\getStoredReferrerId();

if ($cookieReferrerId === null) {
return null;
}
if (!(Utils\Queries\checkIfUserExists([ 'userId' => $cookieReferrerId ]))) {
return null;
}

return $cookieReferrerId;
}

?>
73 changes: 73 additions & 0 deletions modules/registration/utils/queries.utils.php
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,27 @@

namespace UniEngine\Engine\Modules\Registration\Utils\Queries;

// Arguments
// - $params (Object)
// - userId (string | null)
//
function checkIfUserExists ($params) {
$selectUserQuery = (
"SELECT " .
"`id` " .
"FROM {{table}} " .
"WHERE " .
"`id` = {$params['userId']} " .
"LIMIT 1 " .
";"
);

$selectUserResult = doquery($selectUserQuery, 'users');
$doesUserExist = $selectUserResult->num_rows == 1;

return $doesUserExist;
}

// Arguments
// - $params (Object)
// - ips (string[])
Expand Down Expand Up @@ -78,6 +99,39 @@ function insertReferralsTableEntry ($params) {
doquery($insertEntryQuery, 'referring_table');
}

// Arguments
// - $params (Object)
// - username (String)
// - passwordHash (String)
// - langCode (String)
// - email (String)
// - registrationIP (String)
// - currentTimestamp (String)
//
function insertNewUser ($params) {
$insertUserQuery = (
"INSERT INTO {{table}} " .
"SET " .
"`username` = '{$params['username']}', " .
"`password` = '{$params['passwordHash']}', " .
"`lang` = '{$params['langCode']}', " .
"`email` = '{$params['email']}', " .
"`email_2` = '{$params['email']}', " .
"`ip_at_reg` = '{$params['registrationIP']}', " .
"`id_planet` = 0, " .
"`register_time` = {$params['currentTimestamp']}, " .
"`onlinetime` = {$params['currentTimestamp']} - (24*60*60), " .
"`rules_accept_stamp` = {$params['currentTimestamp']} " .
";"
);

doquery($insertUserQuery, 'users');

return [
'userId' => getLastInsertId()
];
}

// Arguments
// - $params (Object)
// - userId (String)
Expand Down Expand Up @@ -121,4 +175,23 @@ function updateUserFinalDetails ($params) {
doquery($updateUserQuery, 'users');
}

function incrementUsersCounterInGameConfig () {
global $_GameConfig, $_MemCache;

$_GameConfig['users_amount'] += 1;

$updateUserConfigQuery = (
"UPDATE {{table}} " .
"SET " .
"`config_value` = {$_GameConfig['users_amount']} " .
"WHERE " .
"`config_name` = 'users_amount' " .
";"
);

doquery($updateUserConfigQuery, 'config');

$_MemCache->GameConfig = $_GameConfig;
}

?>
5 changes: 5 additions & 0 deletions modules/registration/validators/index.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
<?php

header("Location: ../index.php");

?>
40 changes: 40 additions & 0 deletions modules/registration/validators/validateReCaptcha.validators.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
<?php

namespace UniEngine\Engine\Modules\Registration\Validators;

// Arguments
// - $params (Object)
// - responseValue (String | null)
// - currentSessionIp (String)
//
function validateReCaptcha($params) {
global $_EnginePath;

require("{$_EnginePath}vendor/google/recaptcha/src/autoload.php");

$serverIdentificator = $_SERVER['SERVER_NAME'];

if (
defined("REGISTER_RECAPTCHA_SERVERIP_AS_HOSTNAME") &&
REGISTER_RECAPTCHA_SERVERIP_AS_HOSTNAME
) {
$serverIdentificator = $_SERVER['SERVER_ADDR'];
}

$recaptcha = new \ReCaptcha\ReCaptcha(REGISTER_RECAPTCHA_PRIVATEKEY);

$recaptchaResponse = $recaptcha
->setExpectedHostname($serverIdentificator)
->verify(
$params['responseValue'],
$params['currentSessionIp']
);

$verificationResult = $recaptchaResponse->isSuccess();

return [
'isValid' => $verificationResult,
];
}

?>
Loading