refactor: OOP code movements started :)

This commit is contained in:
Martin Ambrus
2017-10-25 13:38:38 +02:00
parent ab461e5945
commit 30d3b9c4fa
20 changed files with 484 additions and 76 deletions
+1 -1
View File
@@ -561,7 +561,7 @@ if (!empty($_GET['p'])) {
{
include('Templates/search.tpl');
}
if($_POST['p'] and $_POST['s'])
if(isset($_POST['p']) && isset($_POST['s']) && $_POST['p'] and $_POST['s'])
{
$filename = 'Templates/results_'.$_POST['p'].'.tpl';
if(file_exists($filename))
+6 -9
View File
@@ -1,5 +1,8 @@
<?php
include_once("src/Entity/User.php");
use App\Entity\User;
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
@@ -62,10 +65,7 @@ class Account {
else if(USRNM_SPECIAL && preg_match("/[:,\\. \\n\\r\\t\\s\\<\\>]+/", $_POST['name'])) {
$form->addError("name",USRNM_CHAR);
}
else if($database->checkExist($_POST['name'],0)) {
$form->addError("name",USRNM_TAKEN);
}
else if($database->checkExist_activate($_POST['name'],0)) {
else if(User::exists($database,$_POST['name'])) {
$form->addError("name",USRNM_TAKEN);
}
@@ -89,10 +89,7 @@ class Account {
if(!$this->validEmail($_POST['email'])) {
$form->addError("email",EMAIL_INVALID);
}
else if($database->checkExist($_POST['email'],1)) {
$form->addError("email",EMAIL_TAKEN);
}
else if($database->checkExist_activate($_POST['email'],1)) {
else if(User::exists($database,$_POST['email'])) {
$form->addError("email",EMAIL_TAKEN);
}
}
@@ -190,7 +187,7 @@ class Account {
if(!isset($_POST['user']) || $_POST['user'] == "") {
$form->addError("user",$user);
}
else if(!$database->checkExist($_POST['user'],0)) {
else if(!User::exists($database,$_POST['user'])) {
$form->addError("user",USR_NT_FOUND);
}
if(!isset($_POST['pw']) || $_POST['pw'] == "") {
+4 -1
View File
@@ -8,6 +8,9 @@
## Copyright: TravianZ (c) 2014. All rights reserved. ##
#########################################################
include_once("../../../src/Entity/User.php");
use App\Entity\User;
include_once("../../config.php");
include_once("../../Session.php");
include_once("../../Automation.php");
@@ -78,7 +81,7 @@ else
$act = "";
// Check username not already registered
if($database->checkExist($userName,0))
if(User::exists($database, $userName))
{
// Name already used, do nothing except update $skipped
$skipped ++;
+3 -3
View File
@@ -38,7 +38,7 @@ class adm_DB {
var $connection;
function __construct(){
global $database;
$database = new MYSQLi_DB;
$database = new MYSQLi_DB(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$this->connection = $database->return_link();
}
@@ -763,8 +763,8 @@ class adm_DB {
for($i=0;$i<=count($cropholder)-1;$i++) { $basecrop+= $bid4[$fdata[$cropholder[$i]]]['prod']; }
$crop = $basecrop + $basecrop * 0.25 * $ocounter[3];
$jcrop=0;
if($grainmill >= 1) $jcrop=$bid8[$grainmill]['attri'];
if($bakery >= 1) $jcrop+=$bid9[$bakery]['attri'];
if($grainmill >= 1) $jcrop=(isset($bid8[$grainmill]['attri']) ? $bid8[$grainmill]['attri'] : 0);
if($bakery >= 1) $jcrop+=(isset($bid9[$bakery]['attri']) ? $bid9[$bakery]['attri'] : 0);
$crop += $basecrop /100 * $jcrop;
if($b4 > time()) {
$crop *= 1.25;
+4 -4
View File
@@ -20,7 +20,7 @@
class funct {
function CheckLogin(){
if($_SESSION['access'] >= MULTIHUNTER and $_SESSION['id']){
if(isset($_SESSION['access']) && $_SESSION['access'] >= MULTIHUNTER and $_SESSION['id']){
return true;
}else{
return false;
@@ -212,14 +212,14 @@ class funct {
$funct = new funct;
if($funct->CheckLogin()){
if($_GET['action']){
if(isset($_GET['action']) && $_GET['action']){
$funct->Act($_GET);
}
if($_POST['action']){
if(isset($_POST['action']) && $_POST['action']){
$funct->Act2($_POST);
}
}
if($_POST['action']=='login'){
if(isset($_POST['action']) && $_POST['action']=='login'){
$funct->LogIN($_POST['name'],$_POST['pw']);
}
?>
+5 -2
View File
@@ -16,7 +16,10 @@
## ##
#################################################################################
class Alliance {
include_once("src/Entity/User.php");
use App\Entity\User;
class Alliance {
public $gotInvite = false;
public $inviteArray = array();
@@ -114,7 +117,7 @@
$form->addError("perm", NO_PERMISSION);
}elseif(!isset($post['a_name']) || $post['a_name'] == "") {
$form->addError("name1", NAME_EMPTY);
}elseif(!$database->checkExist(stripslashes($post['a_name']), 0)) {
}elseif(!User::exists($database, $post['a_name'])) {
$form->addError("name2", NAME_NO_EXIST."".stripslashes(stripslashes($post['a_name'])));
}elseif($UserData['id'] == $session->uid) {
$form->addError("name3", SAME_NAME);
+2 -2
View File
@@ -3891,10 +3891,10 @@ $wallimg = "<img src=\"".GP_LOCATE."img/g/g3".$targettribe."Icon.gif\" height=\"
}
for($i=0;$i<=count($cropholder)-1;$i++) { $crop+= $bid4[$this->bountyresarray[$cropholder[$i]]]['prod']; }
if($grainmill >= 1) {
$crop += $crop /100 * $bid8[$grainmill]['attri'];
$crop += $crop /100 * (isset($bid8[$grainmill]['attri']) ? $bid8[$grainmill]['attri'] : 0);
}
if($bakery >= 1) {
$crop += $crop /100 * $bid9[$bakery]['attri'];
$crop += $crop /100 * (isset($bid9[$bakery]['attri']) ? $bid9[$bakery]['attri'] : 0);
}
if($this->bountyocounter[3] != 0) {
$crop += $crop*0.25*$this->bountyocounter[3];
+1 -1
View File
@@ -110,7 +110,7 @@ class Building {
public function canBuild($id,$tid) {
global $village,$session,$database;
$demolition = $database->getDemolition($village->wid);
if($demolition[0]['buildnumber']==$id) { return 11; }
if((isset($demolition[0])) && $demolition[0]['buildnumber']==$id) { return 11; }
if($this->isMax($tid,$id)) {
return 1;
} else if($this->isMax($tid,$id,1) && ($this->isLoop($id) || $this->isCurrent($id))) {
+209 -42
View File
@@ -1,6 +1,4 @@
<?php
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
@@ -17,15 +15,216 @@
## ##
#################################################################################
$src_prefix = '';
if (substr(getcwd(), -5) === 'Admin') {
$src_prefix = '../';
}
if (substr(getcwd(), -4) === 'Mods') {
$src_prefix = '../../../';
}
include_once("config.php");
include_once($src_prefix."src/Database/IDbConnection.php");
include_once($src_prefix."src/Utils/Math.php");
class MYSQLi_DB {
use App\Database\IDbConnection;
use App\Utils\Math;
var $dblink;
function __construct() {
$this->dblink = mysqli_connect(SQL_SERVER, SQL_USER, SQL_PASS) or die(mysqli_error($this->dblink));
mysqli_select_db($this->dblink, SQL_DB);
mysqli_query($this->dblink,"SET NAMES 'UTF8'");
class MYSQLi_DB implements IDbConnection {
private
/**
* @var string MySQL server hostname to connect to.
*/
$hostname = 'localhost',
/**
* @var int MySQL server port to connect to.
*/
$port = 3306,
/**
* @var string Username to authenticate with to the MySQL connection.
*/
$username = 'root',
/**
* @var string Password to authenticate with to the MySQL connection.
*/
$password = '',
/**
* @var string Database to use with TravianZ.
*/
$dbname = 'travian',
/**
* @var int Counter of all SELECT queries performed.
*/
$selectQueryCount = 0,
/**
* @var int Counter of all INSERT queries performed.
*/
$insertQueryCount = 0,
/**
* @var int Counter of all UPDATE queries performed.
*/
$updateQueryCount = 0,
/**
* @var int Counter of all DELETE queries performed.
*/
$deleteQueryCount = 0,
/**
* @var int Counter of all REPLACE queries performed.
*/
$replaceQueryCount = 0;
public $dblink;
/**
*
* Constructor.
* Will initialize the connection to MySQL
* and die on any error it would encounter.
*
* @example $db = new MYSQLi_DB(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
*
* @param string $hostname Hostname of the MySQL server.
* @param string $username Username to be used to to connect.
* @param string $password Password to be used to to connect.
* @param string $dbname Name of the database to use.
* @param int $port [Optional] server port to connect to. Default: 3306
* @return void This method doesn't have a return value.
*/
public function __construct(string $hostname, string $username, string $password, string $dbname, int $port = 3306) {
$this->hostname = $hostname;
$this->port = $port;
$this->username = $username;
$this->password = $password;
$this->dbname = $dbname;
// connect to the DB
if (!$this->connect()) {
die(mysqli_errno($this->dblink));
}
// we will operate in UTF8
mysqli_query($this->dblink,"SET NAMES 'UTF8'");
}
/**
* {@inheritDoc}
* @see \App\Database\IDbConnection::connect()
*/
public function connect(): bool {
// try to connect
$this->dblink = mysqli_connect($this->hostname, $this->username, $this->password);
// return on error
if (mysqli_error($this->dblink)) {
return false;
}
// select the DB to use
mysqli_select_db($this->dblink, $this->dbname);
// return on error
if (mysqli_error($this->dblink)) {
return false;
} else {
// connected and DB exists, we're good to go
return true;
}
}
/**
* {@inheritDoc}
* @see \App\Database\IDbConnection::disconnect()
*/
public function disconnect(): bool {
if ($this->dblink) {
if (!$this->dblink->close()) {
return false;
}
$this->dblink = null;
}
return true;
}
/**
* {@inheritDoc}
* @see \App\Database\IDbConnection::reconnect()
*/
public function reconnect(): bool {
$this->disconnect();
return $this->connect();
}
/**
* {@inheritDoc}
* @see \App\Database\IDbConnection::query()
*/
public function query_new(string $statement, ...$params) {
// check for SELECT
preg_match('/[^AZ-az]*(\()?[^AZ-az]*SELECT/i', $statement, $matches);
// SELECT statement it is...
if (count($matches)) {
if ($prep = mysqli_prepare($this->dblink, $statement)) {
// prepare all parameter types
$types = [];
foreach ($params as $param) {
// default to string, change if neccessary
$paramType = 's';
if (Math::isInt($param)) {
$paramType = 'i';
} else if (Math::isFloat($param)) {
$paramType = 'd';
}
$types[] = $paramType;
}
// dynamically bind parameters
$bind_names = [implode('', $types)];
for ($i=0; $i<count($params); $i++){
$bind_name = 'bind' . $i;
$$bind_name = $params[$i];
$bind_names[] = &$$bind_name;
}
call_user_func_array(array($prep, 'bind_param'),$bind_names);
// execute the statement to get its value back
if (mysqli_stmt_execute($prep)) {
$this->selectQueryCount++;
return mysqli_stmt_get_result($prep);
} else {
throw new Exception('Failed to execute an SQL statement!');
}
} else {
throw new Exception('Failed to prepare an SQL statement!');
}
}
return false;
}
/**
* {@inheritDoc}
* @see \App\Database\IDbConnection::is_connected()
*/
public function is_connected(): bool {
return ($this->dblink ? true : false);
}
function escape($value) {
@@ -111,38 +310,6 @@ class MYSQLi_DB {
return mysqli_query($this->dblink,$q);
}
function checkExist($ref, $mode) {
list($ref, $mode) = $this->escape_input($ref, $mode);
if(!$mode) {
$q = "SELECT username FROM " . TB_PREFIX . "users where username = '$ref' LIMIT 1";
} else {
$q = "SELECT email FROM " . TB_PREFIX . "users where email = '$ref' LIMIT 1";
}
$result = mysqli_query($this->dblink,$q);
if(mysqli_num_rows($result)) {
return true;
} else {
return false;
}
}
function checkExist_activate($ref, $mode) {
list($ref, $mode) = $this->escape_input($ref, $mode);
if(!$mode) {
$q = "SELECT username FROM " . TB_PREFIX . "activate where username = '$ref' LIMIT 1";
} else {
$q = "SELECT email FROM " . TB_PREFIX . "activate where email = '$ref' LIMIT 1";
}
$result = mysqli_query($this->dblink,$q);
if(mysqli_num_rows($result)) {
return true;
} else {
return false;
}
}
public function hasBeginnerProtection($vid) {
list($vid) = $this->escape_input($vid);
@@ -4205,7 +4372,7 @@ class MYSQLi_DB {
for($i=0;$i<=count($cropholder)-1;$i++) { $basecrop+= $bid4[$buildarray[$cropholder[$i]]]['prod']; }
$crop = $basecrop + $basecrop * 0.25 * $cropo;
if($grainmill >= 1 || $bakery >= 1) {
$crop += $basecrop /100 * ($bid8[$grainmill]['attri'] + $bid9[$bakery]['attri']);
$crop += $basecrop /100 * ((isset($bid8[$grainmill]['attri']) ? $bid8[$grainmill]['attri'] : 0) + (isset($bid9[$bakery]['attri']) ? $bid9[$bakery]['attri'] : 0));
}
if($bonus > time()) {
$crop *= 1.25;
@@ -4635,7 +4802,7 @@ References:
// database is not needed if we're displaying static pages
$req_file = basename($_SERVER['PHP_SELF']);
if (!in_array($req_file, ['tutorial.php', 'anleitung.php'])) {
$database = new MYSQLi_DB;
$database = new MYSQLi_DB(SQL_SERVER, SQL_USER, SQL_PASS, SQL_DB);
$link = $database->return_link();
$GLOBALS['db'] = $database;
$GLOBALS['link'] = $database->return_link();
+6
View File
@@ -1,4 +1,6 @@
<?php
use App\Entity\User;
ob_start(); // Enesure, that no more header already been sent error not showing up again
mb_internal_encoding("UTF-8"); // Add for utf8 varriables.
@@ -282,6 +284,10 @@ $form = new Form;
// if there is no user, we'd try to load messages for user with ID 0, which is wrong
if (!empty($_SESSION['id_user'])) {
$message = new Message;
// create a global user variable which will later be removed from here
// and created + retrieved either via Service Locator or other DI concept
$user = new User((int) $_SESSION['id_user'], $database);
}
?>
+1 -1
View File
@@ -229,7 +229,7 @@ class Village {
for($i=0;$i<=count($cropholder)-1;$i++) { $basecrop+= $bid4[$this->resarray[$cropholder[$i]]]['prod']; }
$crop = $basecrop + $basecrop * 0.25 * $this->ocounter[3];
if($grainmill >= 1 || $bakery >= 1) {
$crop += $basecrop /100 * ($bid8[$grainmill]['attri'] + $bid9[$bakery]['attri']);
$crop += $basecrop /100 * (isset($bid8[$grainmill]['attri']) ? $bid8[$grainmill]['attri'] : 0) + (isset($bid9[$bakery]['attri']) ? $bid9[$bakery]['attri'] : 0);
}
if($session->bonus4 == 1) {
$crop *= 1.25;
+1 -1
View File
@@ -43,7 +43,7 @@ if (count($allianceInvitations) == 0) {
echo "</tr>";
} else {
foreach($allianceInvitations as $invit) {
$invited = $database->getUserField($invit['uid'],username,0);
$invited = $database->getUserField($invit['uid'],'username',0);
echo "<tr>";
echo "<td class=abo><a href=\"?o=4&s=5&d=".$invit['id']."\"><img src=\"gpack/travian_default/img/a/del.gif\" width=\"12\" height=\"12\" alt=\"Del\"></a></td>";
echo "<td><a href=spieler.php?uid=".$invit['uid'].">".$invited."</td>";
+1 -1
View File
@@ -42,7 +42,7 @@ $search = $_SESSION['search'];
echo "<tr><td class=\"ra \" >";
}
echo $i.".</td><td class=\"pla \" >";
if($ranking[$i]['access'] > 2){
if(isset($ranking[$i]['access']) && $ranking[$i]['access'] > 2){
echo"<u><a href=\"spieler.php?uid=".$ranking[$i]['userid']."\">".$ranking[$i]['username']."</a></u>";
} else {
echo"<a href=\"spieler.php?uid=".$ranking[$i]['userid']."\">".$ranking[$i]['username']."</a>";
+1 -1
View File
@@ -69,7 +69,7 @@ foreach($varray as $vil){
$prod_iron += $prod_iron /100 * $bid7[$foundry]['attri'];
}
if ($grainmill >= 1 || $bakery >= 1) {
$prod_crop += $prod_crop /100 * ($bid8[$grainmill]['attri'] + $bid9[$bakery]['attri']);
$prod_crop += $prod_crop /100 * ((isset($bid8[$grainmill]['attri']) ? $bid8[$grainmill]['attri'] : 0) + (isset($bid9[$bakery]['attri']) ? $bid9[$bakery]['attri'] : 0));
}
$oasisowned = $database->getOasis($vid);
//more oasis logic required
+7 -2
View File
@@ -9,7 +9,12 @@
## ##
#################################################################################
if(count($session->villages) > 1){?>
if (!isset($id)) {
$id = '';
}
if(count($session->villages) > 1){
?>
<table id="vlist" cellpadding="1" cellspacing="1">
<thead><tr><td colspan="3"><a href="dorf3.php" accesskey="9"><?php echo MULTI_V_HEADER; ?>:</a></td></tr></thead>
<tbody><?php
@@ -112,7 +117,7 @@ else if(isset($_GET['t']) && isset($_GET['id'])) {
for($i=1;$i<=count($session->villages);++$i){echo'
<tr>
<td class="dot '.(($_SESSION['wid'] == $returnVillageArray[$i-1]['wref'] ) ? 'hl':'').'">●</td>
<td class="link"><a href="?newdid='.$returnVillageArray[$i-1]['wref'].(($id>=19) ? "&id=".$id : "&id=".$_GET['id']).'">'.$returnVillageArray[$i-1]['name'].'</a></td>
<td class="link"><a href="?newdid='.$returnVillageArray[$i-1]['wref'].(($id>=19) ? "&id=".$id : (!empty($_GET['id']) ? "&id=".$_GET['id'] : '')).'">'.$returnVillageArray[$i-1]['name'].'</a></td>
<td class="aligned_coords"><div class="cox">('.$returnVillageArray[$i-1]['x'].'</div><div class="pi">|</div><div class="coy">'.$returnVillageArray[$i-1]['y'].')</div></td></tr>';
}}?>
</tbody>
+3 -3
View File
@@ -40,7 +40,7 @@ if(isset($_GET['id'])) {
$_GET['id'] = "1";
}
$checkBuildings = array(0,16,17,25,26,27);
if($_GET['id'] < 19 || !in_array($_GET['gid'], $checkBuildings)){
if($_GET['id'] < 19 || (isset($_GET['gid']) && !in_array($_GET['gid'], $checkBuildings))){
$_GET['t'] = "";
$_GET['s'] = "";
}
@@ -250,7 +250,7 @@ header("Location: banned.php");
exit;
}
}
if($_GET['mode']=='troops' && $_GET['cancel']==1){
if(isset($_GET['mode']) && $_GET['mode']=='troops' && isset($_GET['cancel']) && $_GET['cancel']==1){
if($session->access != BANNED){
$oldmovement=$database->getMovementById($_GET['moveid']);
$now=time();
@@ -367,7 +367,7 @@ if(isset($_GET['id']) or isset($_GET['gid']) or $route == 1 or isset($_GET['rout
else {
include("Templates/Build/".$village->resarray['f'.$_GET['id'].'t'].".tpl");
}
if($_GET['buildingFinish'] == 1) {
if((isset($_GET['buildingFinish'])) && $_GET['buildingFinish'] == 1) {
if($session->gold >= 2) {
$building->finishAll("build.php?gid=".$_GET['id']."&ty=".$_GET['ty']);
exit;
+5 -2
View File
@@ -18,7 +18,10 @@
#################################################################################
include_once ("GameEngine/Session.php");
include_once("src/Entity/User.php");
use App\Entity\User;
include_once ("GameEngine/Session.php");
include_once ("GameEngine/config.php");
@@ -493,7 +496,7 @@ if($_POST['password'] != ""){
}
echo "Done";
}elseif($database->checkExist('Natars', 0)) {
}elseif(User::exists($database,'Natars')) {
?>
<p>
<span class="c2">Error: Natar account already exist</span>
+74
View File
@@ -0,0 +1,74 @@
<?php
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
## Project: TravianZ ##
## Filename User.php ##
## Developed by: martinambrus ##
## License: TravianZ Project ##
## Copyright: TravianZ (c) 2010-2017. All rights reserved. ##
## URLs: https://travian.martinambrus.com ##
## Source code: https://github.com/Shadowss/TravianZ ##
## ##
#################################################################################
namespace App\Database;
/**
* Defines database connection class structure
* and all required methods for it to work.
*
* @author martinambrus
*/
interface IDbConnection {
/**
* Method used to connect to the database
* using the data provided via the DB class' constructor.
*
* @return bool Returns true if the connection was made and the chosen database exists, false otherwise.
*/
public function connect(): bool;
/**
* Method used to disconnect from the database.
*
* @return bool Returns true if the disconnect was successful, false otherwise.
*/
public function disconnect(): bool;
/**
* Method used to reconnect to the database
* using the data provided via the DB class' constructor.
*
* @return bool Returns true if the reconnect was successful, false otherwise.
*/
public function reconnect(): bool;
/**
* Method to check whether or not we are connected
* to the database.
*
* @return bool Returns true if a connection exists, false otherwise.
*/
public function is_connected(): bool;
/**
* Prepares and executes a MySQL query and returns the result.
* -> SELECT statements will return a mysqli_result
* -> INSERT, UPDATE, DELETE, REPLACE statements will return an integer
* (last insert ID for INSERTs, number of affected rows for everything else)
*
* @example $dbConnection->query("SELECT id FROM ".TB_PREFIX."users WHERE email = ? AND activated = ?", "my@mail.com", 1);
* @example $dbConnection->query("UPDATE ".TB_PREFIX."users SET name = ? WHERE id = ?", "John Doe", 1);
* @example $dbConnection->query("INSERT INTO ".TB_PREFIX."users (name, email) VALUES (?, ?)", "John Doe", "john@doe.com");
* @example $dbConnection->query("REPLACE INTO ".TB_PREFIX."users (name, email) VALUES (?, ?)", "John Doe", "john@doe.com");
* @example $dbConnection->query("DELETE FROM ".TB_PREFIX."users WHERE id IN(?, ?, ?)", 1, 2 3);
*
* @param string $statement The query to prepare and execute.
* @param mixed ...$params Parameters for the query. These usually come from user via POST or GET requests.
* @return mixed Returns either a mysqli_result or a number. If number is returned, it will be last insert ID
* for INSERTs or number of affected rows for anything else.
*/
public function query_new(string $statement, ...$params);
}
+116
View File
@@ -0,0 +1,116 @@
<?php
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
## Project: TravianZ ##
## Filename User.php ##
## Developed by: martinambrus ##
## License: TravianZ Project ##
## Copyright: TravianZ (c) 2010-2017. All rights reserved. ##
## URLs: https://travian.martinambrus.com ##
## Source code: https://github.com/Shadowss/TravianZ ##
## ##
#################################################################################
namespace App\Entity;
$src_prefix = '';
if (substr(getcwd(), -5) === 'Admin') {
$src_prefix = '../';
}
if (substr(getcwd(), -4) === 'Mods') {
$src_prefix = '../../../';
}
include_once($src_prefix."src/Database/IDbConnection.php");
include_once($src_prefix."src/Utils/Math.php");
use App\Database\IDbConnection;
use App\Utils\Math;
/**
* Defines the properties of a user, e.g. player entity
* connected to their profile and other personal and account-specific
* information.
*
* @author martinambrus
*/
class User {
/**
* @var int Database ID of the user.
*/
private $id;
/**
* @var string A unique username for this user.
*/
private $username;
/**
*
* @var IDbConnection Database connection to perform queries on.
*/
private $db;
/**
* Constructor for the User class.
* Depending on the parameter input, a User class with
* database ID or username will be instantiated.
*
* @example $user = new User(1);
* @example $user = new User("martinambrus");
*
* @param int|string $identifier ID or username for this user.
* @param IDbConnection $database Instance of the database class to use to perform queries.
*
* @return void This method doesn't have a return value.
*/
public function __construct($identifier, IDbConnection $database) {
// check if we passed an ID or a username
if (Math::isInt($identifier)) {
$this->id = $identifier;
} else {
$this->username = $identifier;
}
$this->db = $database;
}
/**
* Checks whether username or e-mail already exists in the database.
*
* @param IDbConnection $db The current database connection.
* @param string $value Value to check names and emails for.
* @return boolean Returns true if the value exists in database,
* false otherwise.
*/
public static function exists(IDbConnection $db, string $value) {
$sql = '(
SELECT
Count(*) AS in_users
FROM
'.TB_PREFIX.'users
WHERE
username = ? OR email = ?
)
UNION ALL
(
SELECT
Count(*) AS in_act
FROM
'.TB_PREFIX.'activate
WHERE
username = ? OR email = ?
)';
$res = $db->query_new($sql, $value, $value, $value, $value);
// convert result into an array
$res = mysqli_fetch_array($res, MYSQLI_NUM);
return ($res[0] > 0 || $res[1] > 0);
}
}
+34
View File
@@ -0,0 +1,34 @@
<?php
#################################################################################
## -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =- ##
## --------------------------------------------------------------------------- ##
## Project: TravianZ ##
## Filename User.php ##
## Developed by: martinambrus ##
## License: TravianZ Project ##
## Copyright: TravianZ (c) 2010-2017. All rights reserved. ##
## URLs: https://travian.martinambrus.com ##
## Source code: https://github.com/Shadowss/TravianZ ##
## ##
#################################################################################
namespace App\Utils;
/**
*
* Mathematics-related helpers.
*
* @author martinambrus
*
*/
class Math {
public static function isInt($val) {
return (is_numeric($val) && intval($val) === $val);
}
public static function isFloat($val) {
return (is_numeric($val) && floatval($val) === $val);
}
}