Failed Conditions
Pull Request — master (#353)
by Florian
07:09
created

QueryManagerPostgresqlMonocleAlternate   C

Complexity

Total Complexity 74

Size/Duplication

Total Lines 488
Duplicated Lines 40.78 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 199
loc 488
rs 5.5244
c 0
b 0
f 0
wmc 74
lcom 1
cbo 1

37 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 3 1
A __destruct() 0 3 1
A testTotalPokemon() 15 15 3
A testTotalGyms() 15 15 3
A testTotalPokestops() 15 15 3
A getTotalLures() 0 4 1
A getRecentAll() 0 15 3
A getRecentMythic() 0 16 3
A getGymsProtectedByPokemon() 6 6 1
A getPokemonLastSeen() 10 10 1
A getTop50Pokemon() 15 15 2
A getTop50Trainers() 0 21 3
A getPokemonHeatmap() 0 11 2
A getPokemonGraph() 0 15 3
C getPokemonLive() 0 35 11
A getAllPokestops() 0 9 2
A getTeamGuardians() 0 11 2
A getOwnedAndPoints() 9 9 1
A getAllGyms() 0 9 2
A getGymData() 11 11 1
A getGymDefenders() 0 12 2
A getAllRaids() 15 15 2
A getTrainers() 0 3 1
A getTrainerLevelCount() 9 9 3
A getPokemonCountsActive() 0 9 2
A getPoekmonCountsLastDay() 0 13 2
A getTotalPokemon() 6 6 1
A getTotalGyms() 6 6 1
A getTotalRaids() 6 6 1
A getTotalGymsForTeam() 6 6 1
A getPokemonSliederMinMax() 6 6 1
A getMapsCoords() 6 6 1
A getTotalPokestops() 6 6 1
A getPokemonSinceLastUpdate() 15 15 1
A getRaidsSinceLastUpdate() 16 16 1
A getCaptchaCount() 6 6 1
A getNestData() 0 20 3

How to fix   Duplicated Code    Complexity   

Duplicated Code

Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.

Common duplication problems, and corresponding solutions are:

Complex Class

 Tip:   Before tackling complexity, make sure that you eliminate any duplication first. This often can reduce the size of classes significantly.

Complex classes like QueryManagerPostgresqlMonocleAlternate often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

While breaking up the class, it is a good idea to analyze how other classes use QueryManagerPostgresqlMonocleAlternate, and based on these observations, apply Extract Interface, too.

1
<?php
2
/**
3
 * Created by PhpStorm.
4
 * User: floriankostenzer
5
 * Date: 27.01.18
6
 * Time: 02:26
7
 */
8
9
class QueryManagerPostgresqlMonocleAlternate extends QueryManagerPostgresql {
0 ignored issues
show
Coding Style Compatibility introduced by
PSR1 recommends that each class must be in a namespace of at least one level to avoid collisions.

You can fix this by adding a namespace to your class:

namespace YourVendor;

class YourClass { }

When choosing a vendor namespace, try to pick something that is not too generic to avoid conflicts with other libraries.

Loading history...
10
11
	public function __construct() {
12
		parent::__construct();
13
	}
14
15
	public function __destruct() {
16
		parent::__destruct();
17
	}
18
19
	///////////
20
	// Tester
21
	///////////
22
23 View Code Duplication
	function testTotalPokemon() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for testTotalPokemon.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
24
		$req = "SELECT COUNT(*) as total FROM sightings";
25
		$result = pg_query($this->db, $req);
26
		if ($result === false) {
27
			return 1;
28
		} else {
29
			$data = pg_fetch_object($result);
30
			$total = $data->total;
31
32
			if ($total == 0) {
33
				return 2;
34
			}
35
		}
36
		return 0;
37
	}
38
39 View Code Duplication
	function testTotalGyms() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for testTotalGyms.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
40
		$req = "SELECT COUNT(*) as total FROM forts";
41
		$result = pg_query($this->db, $req);
42
		if ($result === false) {
43
			return 1;
44
		} else {
45
			$data = pg_fetch_object($result);
46
			$total = $data->total;
47
48
			if ($total == 0) {
49
				return 2;
50
			}
51
		}
52
		return 0;
53
	}
54
55 View Code Duplication
	function testTotalPokestops() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for testTotalPokestops.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
56
		$req = "SELECT COUNT(*) as total FROM pokestops";
57
		$result = pg_query($this->db, $req);
58
		if ($result === false) {
59
			return 1;
60
		} else {
61
			$data = pg_fetch_object($result);
62
			$total = $data->total;
63
64
			if ($total == 0) {
65
				return 2;
66
			}
67
		}
68
		return 0;
69
	}
70
71
72
	/////////////
73
	// Homepage
74
	/////////////
75
76 View Code Duplication
	function getTotalPokemon() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTotalPokemon.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
77
		$req = "SELECT COUNT(*) AS total FROM sightings WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW())";
78
		$result = pg_query($this->db, $req);
79
		$data = pg_fetch_object($result);
80
		return $data;
81
	}
82
83
	function getTotalLures() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTotalLures.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
84
		$data = (object) array("total" => 0);
85
		return $data;
86
	}
87
88 View Code Duplication
	function getTotalGyms() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTotalGyms.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
89
		$req = "SELECT COUNT(*) AS total FROM forts";
90
		$result = pg_query($this->db, $req);
91
		$data = pg_fetch_object($result);
92
		return $data;
93
	}
94
95 View Code Duplication
	function getTotalRaids() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTotalRaids.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
96
		$req = "SELECT COUNT(*) AS total FROM raids WHERE time_battle <= EXTRACT(EPOCH FROM NOW()) AND time_end >= EXTRACT(EPOCH FROM NOW())";
97
		$result = pg_query($this->db, $req);
98
		$data = pg_fetch_object($result);
99
		return $data;
100
	}
101
102
103 View Code Duplication
	function getTotalGymsForTeam($team_id) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTotalGymsForTeam.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
104
		$req = "SELECT COUNT(*) AS total FROM fort_sightings WHERE team = '$team_id'";
105
		$result = pg_query($this->db, $req);
106
		$data = pg_fetch_object($result);
107
		return $data;
108
	}
109
110
	function getRecentAll() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getRecentAll.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
111
		$req = "SELECT DISTINCT pokemon_id, encounter_id, TO_TIMESTAMP(expire_timestamp) AS disappear_time, TO_TIMESTAMP(updated) AS last_modified, TO_TIMESTAMP(expire_timestamp) AS disappear_time_real,
112
              lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
113
              FROM sightings
114
              ORDER BY last_modified DESC
115
              LIMIT 12 OFFSET 0";
116
		$result = pg_query($this->db, $req);
117
		$data = array();
118
		if ($result->num_rows > 0) {
119
			while ($row = pg_fetch_object($result)) {
120
				$data[] = $row;
121
			}
122
		}
123
		return $data;
124
	}
125
126
	function getRecentMythic($mythic_pokemon) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getRecentMythic.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
127
		$req = "SELECT DISTINCT pokemon_id as pokemon_id, CONCAT('A', encounter_id) as encounter_id, TO_TIMESTAMP(expire_timestamp) AS disappear_time, TO_TIMESTAMP(updated) AS last_modified, TO_TIMESTAMP(expire_timestamp) AS disappear_time_real,
128
                lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
129
                FROM sightings
130
                WHERE pokemon_id IN (".implode(",", $mythic_pokemon).")
131
                ORDER BY last_modified DESC
132
                LIMIT 12 OFFSET 0";
133
		$result = pg_query($this->db, $req);
134
		$data = array();
135
		if ($result->num_rows > 0) {
136
			while ($row = pg_fetch_object($result)) {
137
				$data[] = $row;
138
			}
139
		}
140
		return $data;
141
	}
142
143
	///////////////////
144
	// Single Pokemon
145
	///////////////////
146
147 View Code Duplication
	function getGymsProtectedByPokemon($pokemon_id) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getGymsProtectedByPokemon.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
148
		$req = "SELECT COUNT(DISTINCT(fort_id)) AS total FROM fort_sightings WHERE guard_pokemon_id = '".$pokemon_id."'";
149
		$result = pg_query($this->db, $req);
150
		$data = pg_fetch_object($result);
151
		return $data;
152
	}
153
154 View Code Duplication
	function getPokemonLastSeen($pokemon_id) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getPokemonLastSeen.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
155
		$req = "SELECT TO_TIMESTAMP(expire_timestamp) AS expire_timestamp, TO_TIMESTAMP(expire_timestamp) AS disappear_time_real, lat AS latitude, lon AS longitude
156
                FROM sightings
157
                WHERE pokemon_id = '".$pokemon_id."'
158
                ORDER BY expire_timestamp DESC
159
                LIMIT 1 OFFSET 0";
160
		$result = pg_query($this->db, $req);
161
		$data = pg_fetch_object($result);
162
		return $data;
163
	}
164
165 View Code Duplication
	function getTop50Pokemon($pokemon_id, $top_order_by, $top_direction) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTop50Pokemon.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
166
		$req = "SELECT DISTINCT encounter_id, expire_timestamp, TO_TIMESTAMP(expire_timestamp) AS distime, pokemon_id as pokemon_id, TO_TIMESTAMP(expire_timestamp) as disappear_time, lat as latitude, lon as longitude,
167
                cp, atk_iv as individual_attack, def_iv as individual_defense, sta_iv as individual_stamina,
168
                ROUND(100*(atk_iv+def_iv+sta_iv)/45,1) AS \"IV\", move_1 as move_1, move_2, form
169
                FROM sightings
170
	            WHERE pokemon_id = '" . $pokemon_id . "' AND move_1 IS NOT NULL AND move_1 <> '0'
171
	            ORDER BY $top_order_by $top_direction, expire_timestamp DESC
172
	            LIMIT 50 OFFSET 0";
173
		$result = pg_query($this->db, $req);
174
		$top = array();
175
		while ($data = pg_fetch_object($result)) {
176
			$top[] = $data;
177
		}
178
		return $top;
179
	}
180
181
	function getTop50Trainers($pokemon_id, $best_order_by, $best_direction) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTop50Trainers.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
182
		$trainer_blacklist = "";
183
		if (!empty(self::$config->system->trainer_blacklist)) {
184
			$trainer_blacklist = " AND owner_name NOT IN ('" . implode("','", self::$config->system->trainer_blacklist) . "')";
185
		}
186
187
		$req = "SELECT DISTINCT external_id, owner_name as trainer_name, ROUND((100.0*((atk_iv)+(def_iv)+(sta_iv))/45),1) AS \"IV\", move_1, move_2, cp as cp,
188
                TO_TIMESTAMP(last_modified) AS lasttime, last_modified as last_seen
189
                FROM gym_defenders
190
				WHERE pokemon_id = '" . $pokemon_id . "'" . $trainer_blacklist . "
191
				GROUP BY external_id, owner_name, atk_iv, def_iv, sta_iv, move_1, move_2, cp, last_modified
192
				ORDER BY $best_order_by $best_direction, owner_name ASC
193
				LIMIT 50 OFFSET 0";
194
195
		$result = pg_query($this->db, $req);
196
		$toptrainer = array();
197
		while ($data = pg_fetch_object($result)) {
198
			$toptrainer[] = $data;
199
		}
200
		return $toptrainer;
201
	}
202
203
	public function getPokemonHeatmap($pokemon_id, $start, $end) {
204
		$where = " WHERE pokemon_id = ".$pokemon_id." "
205
			. "AND TO_TIMESTAMP(expire_timestamp) BETWEEN '".$start."' AND '".$end."'";
206
		$req 		= "SELECT lat AS latitude, lon AS longitude FROM sightings".$where." ORDER BY expire_timestamp DESC LIMIT 100000";
207
		$result = pg_query($this->db, $req);
208
		$points = array();
209
		while ($data = pg_fetch_object($result)) {
210
			$points[] = $data;
211
		}
212
		return $points;
213
	}
214
215
	public function getPokemonGraph($pokemon_id) {
216
		$req = "SELECT COUNT(*) AS total, EXTRACT(HOUR FROM disappear_time) AS disappear_hour
217
					FROM (SELECT TO_TIMESTAMP(expire_timestamp) as disappear_time FROM sightings WHERE pokemon_id = '".$pokemon_id."' ORDER BY disappear_time LIMIT 100000) AS pokemonFiltered
218
				GROUP BY disappear_hour
219
				ORDER BY disappear_hour";
220
		$result = pg_query($this->db, $req);
221
		$array = array_fill(0, 24, 0);
222
		while ($result && $data = pg_fetch_object($result)) {
223
			$array[$data->disappear_hour] = $data->total;
224
		}
225
		// shift array because AM/PM starts at 1AM not 0:00
226
		$array[] = $array[0];
227
		array_shift($array);
228
		return $array;
229
	}
230
231
	public function getPokemonLive($pokemon_id, $ivMin, $ivMax, $inmap_pokemons) {
0 ignored issues
show
Coding Style introduced by
getPokemonLive uses the super-global variable $_POST which is generally not recommended.

Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable:

// Bad
class Router
{
    public function generate($path)
    {
        return $_SERVER['HOST'].$path;
    }
}

// Better
class Router
{
    private $host;

    public function __construct($host)
    {
        $this->host = $host;
    }

    public function generate($path)
    {
        return $this->host.$path;
    }
}

class Controller
{
    public function myAction(Request $request)
    {
        // Instead of
        $page = isset($_GET['page']) ? intval($_GET['page']) : 1;

        // Better (assuming you use the Symfony2 request)
        $page = $request->query->get('page', 1);
    }
}
Loading history...
232
		$inmap_pkms_filter = "";
233
		$where = " WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW()) AND pokemon_id = " . $pokemon_id;
234
235
		$reqTestIv = "SELECT MAX(atk_iv) AS iv FROM sightings " . $where;
236
		$resultTestIv = pg_query($this->db, $reqTestIv);
237
		$testIv = pg_fetch_object($resultTestIv);
238
		if (!is_null($inmap_pokemons) && ($inmap_pokemons != "")) {
239
			foreach ($_POST['inmap_pokemons'] as $inmap) {
240
				$inmap_pkms_filter .= "'".$inmap."',";
241
			}
242
			$inmap_pkms_filter = rtrim($inmap_pkms_filter, ",");
243
			$where .= " AND encounter_id NOT IN (" . $inmap_pkms_filter . ") ";
244
		}
245
		if ($testIv->iv != null && !is_null($ivMin) && ($ivMin != "")) {
246
			$where .= " AND ((100/45)*(atk_iv + def_iv + sta_iv)) >= (" . $ivMin . ") ";
247
		}
248
		if ($testIv->iv != null && !is_null($ivMax) && ($ivMax != "")) {
249
			$where .= " AND ((100/45)*(atk_iv + def_iv + sta_iv)) <= (" . $ivMax . ") ";
250
		}
251
		$req = "SELECT pokemon_id, lat AS latitude, lon AS longitude,
252
    					TO_TIMESTAMP(expire_timestamp) AS disappear_time,
253
    					TO_TIMESTAMP(expire_timestamp) AS disappear_time_real,
254
    					atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina,
255
   						move_1, move_2
256
					FROM sightings " . $where . "
257
					ORDER BY disappear_time DESC
258
					LIMIT 5000";
259
		$result = pg_query($this->db, $req);
0 ignored issues
show
Security SQL Injection introduced by
$req can contain request data and is used in sql context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_POST, and $inmap is assigned
    in core/process/queries/QueryManagerPostgresqlMonocleAlternate.php on line 239
  2. $inmap_pkms_filter is assigned
    in core/process/queries/QueryManagerPostgresqlMonocleAlternate.php on line 240
  3. $inmap_pkms_filter is passed through rtrim(), and $inmap_pkms_filter is assigned
    in core/process/queries/QueryManagerPostgresqlMonocleAlternate.php on line 242
  4. $where is assigned
    in core/process/queries/QueryManagerPostgresqlMonocleAlternate.php on line 243
  5. $req is assigned
    in core/process/queries/QueryManagerPostgresqlMonocleAlternate.php on line 251

Preventing SQL Injection

There are two options to prevent SQL injection. Generally, it is recommended to use parameter binding:

$stmt = mysqli_prepare("SELECT * FROM users WHERE name = ?");
$stmt->bind_param("s", $taintedUserName);

An alternative – although generally not recommended – is to escape your data manually:

$mysqli = new mysqli('localhost', 'user', 'pass', 'dbname');

$escaped = $mysqli->real_escape_string($taintedUserName);
$mysqli->query("SELECT * FROM users WHERE name = '".$escaped."'");

General Strategies to prevent injection

In general, it is advisable to prevent any user-data to reach this point. This can be done by white-listing certain values:

if ( ! in_array($value, array('this-is-allowed', 'and-this-too'), true)) {
    throw new \InvalidArgumentException('This input is not allowed.');
}

For numeric data, we recommend to explicitly cast the data:

$sanitized = (integer) $tainted;
Loading history...
260
		$spawns = array();
261
		while ($data = pg_fetch_object($result)) {
262
			$spawns[] = $data;
263
		}
264
		return $spawns;
265
	}
266
267 View Code Duplication
	public function getPokemonSliederMinMax() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
268
		$req = "SELECT TO_TIMESTAMP(MIN(expire_timestamp)) AS min, TO_TIMESTAMP(MAX(expire_timestamp)) AS max FROM sightings";
269
		$result = pg_query($this->db, $req);
270
		$data = pg_fetch_object($result);
271
		return $data;
272
	}
273
274 View Code Duplication
	public function getMapsCoords() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
275
		$req = "SELECT MAX(lat) AS max_latitude, MIN(lat) AS min_latitude, MAX(lon) AS max_longitude, MIN(lon) as min_longitude FROM spawnpoints";
276
		$result = pg_query($this->db, $req);
277
		$data = pg_fetch_object($result);
278
		return $data;
279
	}
280
281
282
	///////////////
283
	// Pokestops
284
	//////////////
285
286
287 View Code Duplication
	function getTotalPokestops() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTotalPokestops.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
288
		$req = "SELECT COUNT(*) as total FROM pokestops";
289
		$result = pg_query($this->db, $req);
290
		$data = pg_fetch_object($result);
291
		return $data;
292
	}
293
294
	public function getAllPokestops() {
295
		$req = "SELECT lat as latitude, lon as longitude, null AS lure_expiration, EXTRACT(EPOCH FROM NOW()) AS now, null AS lure_expiration_real FROM pokestops";
296
		$result = pg_query($this->db, $req);
297
		$pokestops = array();
298
		while ($data = pg_fetch_object($result)) {
299
			$pokestops[] = $data;
300
		}
301
		return $pokestops;
302
	}
303
304
305
	/////////
306
	// Gyms
307
	/////////
308
309
	function getTeamGuardians($team_id) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getTeamGuardians.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
310
		$req = "SELECT COUNT(*) AS total, guard_pokemon_id FROM fort_sightings WHERE team = '".$team_id."' GROUP BY guard_pokemon_id ORDER BY total DESC LIMIT 3 OFFSET 0";
311
		$result = pg_query($this->db, $req);
312
313
		$datas = array();
314
		while ($data = pg_fetch_object($result)) {
315
			$datas[] = $data;
316
		}
317
318
		return $datas;
319
	}
320
321 View Code Duplication
	function getOwnedAndPoints($team_id) {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getOwnedAndPoints.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
322
		$req = "SELECT COUNT(DISTINCT(fs.fort_id)) AS total, ROUND((SUM(gd.cp)) / COUNT(DISTINCT(fs.fort_id)),0) AS average_points
323
        			FROM fort_sightings fs
324
        			JOIN gym_defenders gd ON fs.fort_id = gd.fort_id
325
        			WHERE fs.team = '" . $team_id . "'";
326
		$result = pg_query($this->db, $req);
327
		$data = pg_fetch_object($result);
328
		return $data;
329
	}
330
331
	function getAllGyms() {
0 ignored issues
show
Best Practice introduced by
It is generally recommended to explicitly declare the visibility for methods.

Adding explicit visibility (private, protected, or public) is generally recommend to communicate to other developers how, and from where this method is intended to be used.

Loading history...
Comprehensibility Best Practice introduced by
It is recommend to declare an explicit visibility for getAllGyms.

Generally, we recommend to declare visibility for all methods in your source code. This has the advantage of clearly communication to other developers, and also yourself, how this method should be consumed.

If you are not sure which visibility to choose, it is a good idea to start with the most restrictive visibility, and then raise visibility as needed, i.e. start with private, and only raise it to protected if a sub-class needs to have access, or public if an external class needs access.

Loading history...
332
		$req = "SELECT f.id as gym_id, team as team_id, f.lat as latitude, f.lon as longitude, updated as last_scanned, (6 - fs.slots_available) AS level FROM forts f LEFT JOIN fort_sightings fs ON f.id = fs.fort_id;";
333
		$result = pg_query($this->db, $req);
334
		$gyms = array();
335
		while ($data = pg_fetch_object($result)) {
336
			$gyms[] = $data;
337
		}
338
		return $gyms;
339
	}
340
341 View Code Duplication
	public function getGymData($gym_id) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
342
		$req = "SELECT f.name AS name, null AS description, f.url AS url, fs.team AS team, TO_TIMESTAMP(fs.updated) AS last_scanned, fs.guard_pokemon_id AS guard_pokemon_id, (6 - fs.slots_available) AS level, SUM(gd.cp) as total_cp	
343
			FROM fort_sightings fs
344
			LEFT JOIN forts f ON f.id = fs.fort_id
345
			LEFT JOIN gym_defenders gd ON f.id = gd.fort_id
346
			WHERE f.id ='".$gym_id."'
347
			GROUP BY f.name, f.url, fs.team, fs.updated, fs.guard_pokemon_id, fs.slots_available, gd.cp";
348
		$result = pg_query($this->db, $req);
349
		$data = pg_fetch_object($result);
350
		return $data;
351
	}
352
353
	public function getGymDefenders($gym_id) {
354
		$req = "SELECT DISTINCT external_id as pokemon_uid, pokemon_id, atk_iv as iv_attack, def_iv as iv_defense, sta_iv as iv_stamina, cp, fort_id as gym_id
355
			FROM gym_defenders 
356
			WHERE fort_id='".$gym_id."'
357
			ORDER BY cp DESC";
358
		$result = pg_query($this->db, $req);
359
		$defenders = array();
360
		while ($data = pg_fetch_object($result)) {
361
			$defenders[] = $data;
362
		}
363
		return $defenders;
364
	}
365
366
367
	///////////
368
	// Raids
369
	///////////
370
371 View Code Duplication
	public function getAllRaids($page) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
372
		$limit = " LIMIT 10 OFFSET ". ($page * 10);
373
		$req = "SELECT r.fort_id AS gym_id, r.level AS level, r.pokemon_id AS pokemon_id, r.cp AS cp, r.move_1 AS move_1, r.move_2 AS move_2, TO_TIMESTAMP(r.time_spawn) AS spawn, TO_TIMESTAMP(r.time_battle) AS start, TO_TIMESTAMP(r.time_end) AS end, TO_TIMESTAMP(fs.updated) AS last_scanned, f.name, f.lat AS latitude, f.lon as longitude 
374
					FROM raids r 
375
					JOIN forts f ON f.id = r.fort_id 
376
					LEFT JOIN fort_sightings fs ON fs.fort_id = r.fort_id 
377
					WHERE r.time_end > EXTRACT(EPOCH FROM NOW()) 
378
					ORDER BY r.level DESC, r.time_battle" . $limit;
379
		$result = pg_query($this->db, $req);
380
		$raids = array();
381
		while ($data = pg_fetch_object($result)) {
382
			$raids[] = $data;
383
		}
384
		return $raids;
385
	}
386
387
388
	//////////////
389
	// Trainers
390
	//////////////
391
392
	public function getTrainers($trainer_name, $team, $page, $ranking) {
393
		return array(); // Waiting for Monocle to store level
394
	}
395
396 View Code Duplication
	public function getTrainerLevelCount($team_id) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
397
		$levelData = array();
398
		for ($i = 5; $i <= 40; $i++) {
399
			if (!isset($levelData[$i])) {
400
				$levelData[$i] = 0;
401
			}
402
		}
403
		return $levelData; // Waiting for Monocle to store level
404
	}
405
406
407
	/////////
408
	// Cron
409
	/////////
410
411
	public function getPokemonCountsActive() {
412
		$req = "SELECT pokemon_id, COUNT(*) as total FROM sightings WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW()) GROUP BY pokemon_id";
413
		$result = pg_query($this->db, $req);
414
		$counts = array();
415
		while ($data = pg_fetch_object($result)) {
416
			$counts[$data->pokemon_id] = $data->total;
417
		}
418
		return $counts;
419
	}
420
421
	public function getPoekmonCountsLastDay() {
422
		$req = "SELECT pokemon_id, COUNT(*) AS spawns_last_day
423
					FROM sightings
424
					WHERE TO_TIMESTAMP(expire_timestamp) >= (SELECT TO_TIMESTAMP(MAX(expire_timestamp)) FROM sightings) - INTERVAL 1 DAY
425
					GROUP BY pokemon_id
426
				  	ORDER BY pokemon_id ASC";
427
		$result = pg_query($this->db, $req);
428
		$counts = array();
429
		while ($data = pg_fetch_object($result)) {
430
			$counts[$data->pokemon_id] = $data->spawns_last_day;
431
		}
432
		return $counts;
433
	}
434
435 View Code Duplication
	public function getPokemonSinceLastUpdate($pokemon_id, $last_update) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
436
		$where = "WHERE pokemon_id = '".$pokemon_id."' AND id > '".$last_update."'";
437
		$req = "SELECT count, id AS last_timestamp, (TO_TIMESTAMP(expire_timestamp)) AS disappear_time_real, lat as latitude, lon as longitude
438
					FROM sightings
439
					JOIN (SELECT COUNT(*) AS count
440
						FROM sightings
441
                    	" . $where. "
442
                    ) count ON 1 = 1
443
					" . $where . "
444
					ORDER BY expire_timestamp DESC
445
					LIMIT 1 OFFSET 0";
446
		$result = pg_query($this->db, $req);
447
		$data = pg_fetch_object($result);
448
		return $data;
449
	}
450
451 View Code Duplication
	public function getRaidsSinceLastUpdate($pokemon_id, $last_update) {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
452
		$where = "WHERE pokemon_id = '".$pokemon_id."' AND time_battle > '".$last_update."'";
453
		$req = "SELECT time_battle AS start_timestamp, time_end as end, (TO_TIMESTAMP(time_end)) AS end_time_real, lat as latitude, lon as longitude, count
454
					FROM raids r
455
					JOIN forts g ON r.fort_id = g.id
456
					JOIN (SELECT COUNT(*) AS count
457
						FROM raids
458
                    	" . $where."
459
                    ) count ON 1 = 1 
460
	                " . $where."
461
	                ORDER BY time_battle DESC
462
					LIMIT 1 OFFSET 0";
463
		$result = pg_query($this->db, $req);
464
		$data = pg_fetch_object($result);
465
		return $data;
466
	}
467
468 View Code Duplication
	public function getCaptchaCount() {
0 ignored issues
show
Duplication introduced by
This method seems to be duplicated in your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
469
		$req = " SELECT COUNT(*) as total FROM accounts WHERE captchaed IS NOT NULL AND reason IS NULL";
470
		$result = pg_query($this->db, $req);
471
		$data = pg_fetch_object($result);
472
		return $data;
473
	}
474
475
	public function getNestData() {
476
		$pokemon_exclude_sql = "";
477
		if (!empty(self::$config->system->nest_exclude_pokemon)) {
478
			$pokemon_exclude_sql = "AND p.pokemon_id NOT IN (" . implode(",", self::$config->system->nest_exclude_pokemon) . ")";
479
		}
480
		$req = "SELECT p.spawn_id, p.pokemon_id, MAX(p.lat) AS latitude, MAX(p.lon) AS longitude, count(p.pokemon_id) AS total_pokemon, TO_TIMESTAMP(MAX(s.updated)) as latest_seen, coalesce(MAX(duration),30)*60 as duration
481
			          FROM sightings p
482
			          INNER JOIN spawnpoints s ON (p.spawn_id = s.spawn_id)
483
			          WHERE p.expire_timestamp > EXTRACT(EPOCH FROM NOW()) - 86400
484
			          " . $pokemon_exclude_sql . "
485
			          GROUP BY p.spawn_id, p.pokemon_id
486
			          HAVING COUNT(p.pokemon_id) >= 6
487
			          ORDER BY p.pokemon_id";
488
		$result = pg_query($this->db, $req);
489
		$nests = array();
490
		while ($data = pg_fetch_object($result)) {
491
			$nests[] = $data;
492
		}
493
		return $nests;
494
	}
495
496
}
497