Failed Conditions
Pull Request — master (#353)
by Florian
05:01 queued 02:21
created

QueryManagerPostgresqlMonocleAlternate   D

Complexity

Total Complexity 114

Size/Duplication

Total Lines 712
Duplicated Lines 51.54 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 367
loc 712
rs 4.4444
c 0
b 0
f 0
wmc 114
lcom 1
cbo 1

44 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 getTotalPokemon() 6 6 1
A getTotalGyms() 6 6 1
A getTotalRaids() 6 6 1
A getTotalGymsForTeam() 6 9 1
A getRecentAll() 0 15 3
A getRecentMythic() 0 16 3
A getGymsProtectedByPokemon() 6 9 1
A getPokemonLastSeen() 10 10 1
A getTop50Pokemon() 15 15 2
A getTop50Trainers() 0 20 3
A getPokemonHeatmap() 0 11 2
A getPokemonGraph() 0 15 3
C getPokemonLive() 0 34 11
A getPokemonSliderMinMax() 6 6 1
A getMapsCoords() 6 6 1
A getTotalPokestops() 6 6 1
A getAllPokestops() 0 9 2
A getTeamGuardians() 0 14 2
A getOwnedAndPoints() 9 9 1
A getAllGyms() 0 11 2
A getGymData() 10 10 1
A getGymDefenders() 0 12 2
D getGymHistories() 34 34 9
A getGymHistoriesPokemon() 0 13 2
C getHistoryForGym() 38 38 8
A getHistoryForGymPokemon() 14 14 2
A getAllRaids() 15 15 2
C getTrainers() 51 51 9
B getTrainerLevelRanking() 20 20 5
A getActivePokemon() 0 12 2
A getInactivePokemon() 0 12 2
B getTrainerLevelCount() 20 20 5
A getPokemonCountsActive() 0 9 2
A getPokemonCountsLastDay() 0 13 2
A getPokemonSinceLastUpdate() 15 17 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
105
					FROM forts f
106
					LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
107
					WHERE team = '$team_id'";
108
		$result = pg_query($this->db, $req);
109
		$data = pg_fetch_object($result);
110
		return $data;
111
	}
112
113
	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...
114
		$req = "SELECT 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,
115
              lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
116
              FROM sightings
117
              ORDER BY updated DESC
118
              LIMIT 12 OFFSET 0";
119
		$result = pg_query($this->db, $req);
120
		$data = array();
121
		if ($result->num_rows > 0) {
122
			while ($row = pg_fetch_object($result)) {
123
				$data[] = $row;
124
			}
125
		}
126
		return $data;
127
	}
128
129
	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...
130
		$req = "SELECT 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,
131
                lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
132
                FROM sightings
133
                WHERE pokemon_id IN (".implode(",", $mythic_pokemon).")
134
                ORDER BY updated DESC
135
                LIMIT 12 OFFSET 0";
136
		$result = pg_query($this->db, $req);
137
		$data = array();
138
		if ($result->num_rows > 0) {
139
			while ($row = pg_fetch_object($result)) {
140
				$data[] = $row;
141
			}
142
		}
143
		return $data;
144
	}
145
146
	///////////////////
147
	// Single Pokemon
148
	///////////////////
149
150 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...
151
		$req = "SELECT COUNT(f.id) AS total
152
					FROM forts f
153
					LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
154
					WHERE guard_pokemon_id = '".$pokemon_id."'";
155
		$result = pg_query($this->db, $req);
156
		$data = pg_fetch_object($result);
157
		return $data;
158
	}
159
160 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...
161
		$req = "SELECT TO_TIMESTAMP(expire_timestamp) AS expire_timestamp, TO_TIMESTAMP(expire_timestamp) AS disappear_time_real, lat AS latitude, lon AS longitude
162
                FROM sightings
163
                WHERE pokemon_id = '".$pokemon_id."'
164
                ORDER BY expire_timestamp DESC
165
                LIMIT 1 OFFSET 0";
166
		$result = pg_query($this->db, $req);
167
		$data = pg_fetch_object($result);
168
		return $data;
169
	}
170
171 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...
172
		$req = "SELECT 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,
173
                cp, atk_iv as individual_attack, def_iv as individual_defense, sta_iv as individual_stamina,
174
                ROUND(100*(atk_iv+def_iv+sta_iv)/45,1) AS \"IV\", move_1 as move_1, move_2, form
175
                FROM sightings
176
	            WHERE pokemon_id = '" . $pokemon_id . "' AND move_1 IS NOT NULL AND move_1 <> '0'
177
	            ORDER BY $top_order_by $top_direction, expire_timestamp DESC
178
	            LIMIT 50 OFFSET 0";
179
		$result = pg_query($this->db, $req);
180
		$top = array();
181
		while ($data = pg_fetch_object($result)) {
182
			$top[] = $data;
183
		}
184
		return $top;
185
	}
186
187
	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...
188
		$trainer_blacklist = "";
189
		if (!empty(self::$config->system->trainer_blacklist)) {
190
			$trainer_blacklist = " AND owner_name NOT IN ('" . implode("','", self::$config->system->trainer_blacklist) . "')";
191
		}
192
193
		$req = "SELECT 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,
194
                TO_TIMESTAMP(last_modified) AS lasttime, last_modified as last_seen
195
                FROM gym_defenders
196
				WHERE pokemon_id = '" . $pokemon_id . "'" . $trainer_blacklist . "
197
				ORDER BY $best_order_by $best_direction, owner_name ASC
198
				LIMIT 50 OFFSET 0";
199
200
		$result = pg_query($this->db, $req);
201
		$toptrainer = array();
202
		while ($data = pg_fetch_object($result)) {
203
			$toptrainer[] = $data;
204
		}
205
		return $toptrainer;
206
	}
207
208
	public function getPokemonHeatmap($pokemon_id, $start, $end) {
209
		$where = " WHERE pokemon_id = ".$pokemon_id." "
210
			. "AND TO_TIMESTAMP(expire_timestamp) BETWEEN '".$start."' AND '".$end."'";
211
		$req 		= "SELECT lat AS latitude, lon AS longitude FROM sightings".$where." LIMIT 100000";
212
		$result = pg_query($this->db, $req);
213
		$points = array();
214
		while ($data = pg_fetch_object($result)) {
215
			$points[] = $data;
216
		}
217
		return $points;
218
	}
219
220
	public function getPokemonGraph($pokemon_id) {
221
		$req = "SELECT COUNT(*) AS total, EXTRACT(HOUR FROM disappear_time) AS disappear_hour
222
					FROM (SELECT TO_TIMESTAMP(expire_timestamp) as disappear_time FROM sightings WHERE pokemon_id = '".$pokemon_id."' LIMIT 100000) AS pokemonFiltered
223
				GROUP BY disappear_hour
224
				ORDER BY disappear_hour";
225
		$result = pg_query($this->db, $req);
226
		$array = array_fill(0, 24, 0);
227
		while ($result && $data = pg_fetch_object($result)) {
228
			$array[$data->disappear_hour] = $data->total;
229
		}
230
		// shift array because AM/PM starts at 1AM not 0:00
231
		$array[] = $array[0];
232
		array_shift($array);
233
		return $array;
234
	}
235
236
	public function getPokemonLive($pokemon_id, $ivMin, $ivMax, $inmap_pokemons) {
237
		$inmap_pkms_filter = "";
238
		$where = " WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW()) AND pokemon_id = " . $pokemon_id;
239
240
		$reqTestIv = "SELECT MAX(atk_iv) AS iv FROM sightings " . $where;
241
		$resultTestIv = pg_query($this->db, $reqTestIv);
242
		$testIv = pg_fetch_object($resultTestIv);
243
		if (!is_null($inmap_pokemons) && ($inmap_pokemons != "")) {
244
			foreach ($inmap_pokemons as $inmap) {
245
				$inmap_pkms_filter .= "'".$inmap."',";
246
			}
247
			$inmap_pkms_filter = rtrim($inmap_pkms_filter, ",");
248
			$where .= " AND encounter_id NOT IN (" . $inmap_pkms_filter . ") ";
249
		}
250
		if ($testIv->iv != null && !is_null($ivMin) && ($ivMin != "")) {
251
			$where .= " AND ((100/45)*(atk_iv + def_iv + sta_iv)) >= (" . $ivMin . ") ";
252
		}
253
		if ($testIv->iv != null && !is_null($ivMax) && ($ivMax != "")) {
254
			$where .= " AND ((100/45)*(atk_iv + def_iv + sta_iv)) <= (" . $ivMax . ") ";
255
		}
256
		$req = "SELECT pokemon_id, lat AS latitude, lon AS longitude,
257
    					TO_TIMESTAMP(expire_timestamp) AS disappear_time,
258
    					TO_TIMESTAMP(expire_timestamp) AS disappear_time_real,
259
    					atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina,
260
   						move_1, move_2
261
					FROM sightings " . $where . "
262
					LIMIT 5000";
263
		$result = pg_query($this->db, $req);
264
		$spawns = array();
265
		while ($data = pg_fetch_object($result)) {
266
			$spawns[] = $data;
267
		}
268
		return $spawns;
269
	}
270
271 View Code Duplication
	public function getPokemonSliderMinMax() {
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...
272
		$req = "SELECT TO_TIMESTAMP(MIN(expire_timestamp)) AS min, TO_TIMESTAMP(MAX(expire_timestamp)) AS max FROM sightings";
273
		$result = pg_query($this->db, $req);
274
		$data = pg_fetch_object($result);
275
		return $data;
276
	}
277
278 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...
279
		$req = "SELECT MAX(lat) AS max_latitude, MIN(lat) AS min_latitude, MAX(lon) AS max_longitude, MIN(lon) as min_longitude FROM spawnpoints";
280
		$result = pg_query($this->db, $req);
281
		$data = pg_fetch_object($result);
282
		return $data;
283
	}
284
285
286
	///////////////
287
	// Pokestops
288
	//////////////
289
290
291 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...
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 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...
292
		$req = "SELECT COUNT(*) as total FROM pokestops";
293
		$result = pg_query($this->db, $req);
294
		$data = pg_fetch_object($result);
295
		return $data;
296
	}
297
298
	public function getAllPokestops() {
299
		$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";
300
		$result = pg_query($this->db, $req);
301
		$pokestops = array();
302
		while ($data = pg_fetch_object($result)) {
303
			$pokestops[] = $data;
304
		}
305
		return $pokestops;
306
	}
307
308
309
	/////////
310
	// Gyms
311
	/////////
312
313
	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...
314
		$req = "SELECT COUNT(*) AS total, guard_pokemon_id
315
					FROM forts f
316
					LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
317
					WHERE team = '".$team_id."' GROUP BY guard_pokemon_id ORDER BY total DESC LIMIT 3 OFFSET 0";
318
		$result = pg_query($this->db, $req);
319
320
		$datas = array();
321
		while ($data = pg_fetch_object($result)) {
322
			$datas[] = $data;
323
		}
324
325
		return $datas;
326
	}
327
328 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...
329
		$req = "SELECT COUNT(f.id) AS total, ROUND(AVG(fs.total_cp))AS average_points
330
        			FROM forts f
331
					LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
332
        			WHERE fs.team = '" . $team_id . "'";
333
		$result = pg_query($this->db, $req);
334
		$data = pg_fetch_object($result);
335
		return $data;
336
	}
337
338
	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...
339
		$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
340
					FROM forts f
341
					LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))";
342
		$result = pg_query($this->db, $req);
343
		$gyms = array();
344
		while ($data = pg_fetch_object($result)) {
345
			$gyms[] = $data;
346
		}
347
		return $gyms;
348
	}
349
350 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...
351
		$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, fs.total_cp
352
			FROM forts f
353
			LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
354
			WHERE f.id ='".$gym_id."'
355
			GROUP BY f.name, f.url, fs.team, fs.updated, fs.guard_pokemon_id, fs.slots_available, gd.cp";
356
		$result = pg_query($this->db, $req);
357
		$data = pg_fetch_object($result);
358
		return $data;
359
	}
360
361
	public function getGymDefenders($gym_id) {
362
		$req = "SELECT 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
363
			FROM gym_defenders
364
			WHERE fort_id='".$gym_id."'
365
			ORDER BY deployment_time";
366
		$result = pg_query($this->db, $req);
367
		$defenders = array();
368
		while ($data = pg_fetch_object($result)) {
369
			$defenders[] = $data;
370
		}
371
		return $defenders;
372
	}
373
374
375
376
	////////////////
377
	// Gym History
378
	////////////////
379
380 View Code Duplication
	public function getGymHistories($gym_name, $team, $page, $ranking)
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...
381
	{
382
		$where = "";
383
		if (isset($gym_name) && $gym_name != '') {
384
			$where = " WHERE name LIKE '%".$gym_name."%'";
385
		}
386
		if (isset($team) && $team != '') {
387
			$where .= ($where === "" ? " WHERE" : " AND")." fs.team = ".$team;
388
		}
389
		switch ($ranking) {
390
			case 1:
391
				$order = " ORDER BY name, last_modified DESC";
392
				break;
393
			case 2:
394
				$order = " ORDER BY total_cp DESC, last_modified DESC";
395
				break;
396
			default:
397
				$order = " ORDER BY last_modified DESC, name";
398
		}
399
400
		$limit = " LIMIT 10 OFFSET ".($page * 10);
401
402
		$req = "SELECT f.id as gym_id, fs.total_cp, f.name, fs.team as team_id, (6 - slots_available) as pokemon_count, TO_TIMESTAMP(last_modified) AS last_modified
403
			FROM forts f
404
			LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
405
			".$where.$order.$limit;
406
407
		$result = $this->mysqli->query($req);
0 ignored issues
show
Bug introduced by
The property mysqli does not exist. Did you maybe forget to declare it?

In PHP it is possible to write to properties without declaring them. For example, the following is perfectly valid PHP code:

class MyClass { }

$x = new MyClass();
$x->foo = true;

Generally, it is a good practice to explictly declare properties to avoid accidental typos and provide IDE auto-completion:

class MyClass {
    public $foo;
}

$x = new MyClass();
$x->foo = true;
Loading history...
408
		$gym_history = array();
409
		while ($data = $result->fetch_object()) {
410
			$gym_history[] = $data;
411
		}
412
		return $gym_history;
413
	}
414
415
	public function getGymHistoriesPokemon($gym_id)
416
	{
417
		$req = "SELECT external_id AS pokemon_uid, pokemon_id, cp_now as cp, owner_name AS trainer_name
418
					FROM gym_defenders
419
					WHERE fort_id = '". $gym_id ."'
420
					ORDER BY deployment_time";
421
		$result = $this->mysqli->query($req);
422
		$pokemons = array();
423
		while ($data = $result->fetch_object()) {
424
			$pokemons[] = $data;
425
		}
426
		return $pokemons;
427
	}
428
429 View Code Duplication
	public function getHistoryForGym($page, $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...
430
	{
431
		if (isset(self::$config->system->gymhistory_hide_cp_changes) && self::$config->system->gymhistory_hide_cp_changes === true) {
432
			$pageSize = 25;
433
		} else {
434
			$pageSize = 10;
435
		}
436
		$req = "SELECT f.id as gym_id, fs.team as team_id, total_cp, TO_TIMESTAMP(fs.last_modified) as last_modified, last_modified as last_modified_real
437
					FROM fort_sightings fs
438
					LEFT JOIN forts f ON f.id = fs.fort_id
439
					WHERE f.id = '". $gym_id ."'
440
					ORDER BY fs.last_modified DESC
441
					LIMIT ".($pageSize+1)." OFFSET ".($page * $pageSize);
442
		$result = $this->mysqli->query($req);
443
		$history = array();
444
		$count = 0;
445
		while ($data = $result->fetch_object()) {
446
			$count++;
447
			if ($data->total_cp == 0) {
448
				$data->pokemon = array();
449
				$data->pokemon_count = 0;
450
				$data->pokemon_uids = "";
451
			} else {
452
				$data->pokemon = $this->getHistoryForGymPokemon($gym_id, $data->last_modified_real);
453
				$data->pokemon_count = count($data->pokemon);
454
				$data->pokemon_uids = implode(",", array_keys($data->pokemon));
455
			}
456
			if ($data->total_cp === 0 || $data->pokemon_count !== 0) {
457
				$history[] = $data;
458
			}
459
		}
460
		if ($count !== ($pageSize + 1)) {
461
			$last_page = true;
462
		} else {
463
			$last_page = false;
464
		}
465
		return array("last_page" => $last_page, "data" => $history);
466
	}
467
468 View Code Duplication
	private function getHistoryForGymPokemon($gym_id, $last_modified)
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
	{
470
		$req = "SELECT ghd.defender_id, gd.pokemon_id, ghd.cp, gd.owner_name as trainer_name
471
					FROM gym_history_defenders ghd
472
					JOIN gym_defenders gd ON ghd.defender_id = gd.external_id
473
					WHERE ghd.fort_id = '". $gym_id ."' AND date = '".$last_modified."'
474
					ORDER BY gd.deployment_time";
475
		$result = $this->mysqli->query($req);
476
		$pokemons = array();
477
		while ($data = $result->fetch_object()) {
478
			$pokemons[$data->defender_id] = $data;
479
		}
480
		return $pokemons;
481
	}
482
483
	///////////
484
	// Raids
485
	///////////
486
487 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...
488
		$limit = " LIMIT 10 OFFSET ". ($page * 10);
489
		$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
490
					FROM forts f
491
					LEFT JOIN fort_sightings fs ON (fs.fort_id = f.id AND fs.last_modified = (SELECT MAX(last_modified) FROM fort_sightings fs2 WHERE fs2.fort_id=f.id))
492
				 	LEFT JOIN raids r ON (r.fort_id = f.id AND r.time_end >= UNIX_TIMESTAMP())
493
					WHERE r.time_end > EXTRACT(EPOCH FROM NOW())
494
					ORDER BY r.level DESC, r.time_battle" . $limit;
495
		$result = pg_query($this->db, $req);
496
		$raids = array();
497
		while ($data = pg_fetch_object($result)) {
498
			$raids[] = $data;
499
		}
500
		return $raids;
501
	}
502
503
504
	//////////////
505
	// Trainers
506
	//////////////
507
508 View Code Duplication
	public function getTrainers($trainer_name, $team, $page, $rankingNumber) {
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...
509
		$ranking = $this->getTrainerLevelRanking();
510
		$where = "";
511
		if (!empty(self::$config->system->trainer_blacklist)) {
512
			$where .= " AND gd.owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
513
		}
514
		if ($trainer_name != "") {
515
			$where = " AND gd.owner_name LIKE '%".$trainer_name."%'";
516
		}
517
		if ($team != 0) {
518
			$where .= ($where == "" ? " HAVING" : " AND")." team = ".$team;
519
		}
520
		switch ($rankingNumber) {
521
			case 1:
522
				$order = " ORDER BY active DESC, level DESC";
523
				break;
524
			case 2:
525
				$order = " ORDER BY maxCp DESC, level DESC";
526
				break;
527
			default:
528
				$order = " ORDER BY level DESC, active DESC";
529
		}
530
		$order .= ", last_seen DESC, name ";
531
		$limit = " LIMIT 10 OFFSET ".($page * 10);
532
		$req = "SELECT gd.owner_name AS name, MAX(owner_level) AS level, MAX(cp) AS maxCp, MAX(active) AS active, MAX(team) AS team, TO_TIMESTAMP(MAX(last_modified)) as last_seen
533
				  	FROM gym_defenders gd
534
				  	LEFT JOIN (
535
				  		SELECT owner_name, COUNT(*) as active
536
				  		FROM gym_defenders gd2
537
						WHERE fort_id IS NOT NULL
538
				  		GROUP BY owner_name
539
				  	) active ON active.owner_name = gd.owner_name
540
				  	WHERE level IS NOT NULL " . $where . "
541
				  	GROUP BY gd.owner_name" . $order  . $limit;
542
		$result = $this->mysqli->query($req);
543
		$trainers = array();
544
		while ($data = $result->fetch_object()) {
545
			$data->last_seen = date("Y-m-d", strtotime($data->last_seen));
546
			if (is_null($data->active)) {
547
				$data->active = 0;
548
			}
549
			$trainers[$data->name] = $data;
550
551
			$pokemon = array_merge($this->getActivePokemon($data->name),  $this->getInactivePokemon($data->name));
0 ignored issues
show
Coding Style introduced by
Expected 1 space instead of 2 after comma in function call.
Loading history...
552
553
			$trainers[$data->name]->gyms = $data->active;
554
			$trainers[$data->name]->pokemons = $pokemon;
555
			$trainers[$data->name]->rank = $ranking[$data->level];
556
		}
557
		return $trainers;
558
	}
559
560 View Code Duplication
	public function getTrainerLevelRanking() {
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...
561
		$exclue = "";
562
		if (!empty(self::$config->system->trainer_blacklist)) {
563
			$exclue .= " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
564
		}
565
		$req = "SELECT COUNT(*) AS count, level FROM (SELECT MAX(owner_level) as level FROM gym_defenders WHERE owner_level IS NOT NULL ".$exclue." GROUP BY owner_level, owner_name) x GROUP BY level";
566
		$result = $this->mysqli->query($req);
567
		$levelData = array();
568
		while ($data = $result->fetch_object()) {
569
			$levelData[$data->level] = $data->count;
570
		}
571
		for ($i = 5; $i <= 40; $i++) {
572
			if (!isset($levelData[$i])) {
573
				$levelData[$i] = 0;
574
			}
575
		}
576
		# sort array again
577
		ksort($levelData);
578
		return $levelData;
579
	}
580
581
	public function getActivePokemon($trainer_name) {
582
		$req = "SELECT pokemon_id, cp, atk_iv AS iv_attack, sta_iv AS iv_stamina, def_iv AS iv_defense, TO_TIMESTAMP(deployment_time) AS deployment_time, '1' AS active, fort_id as gym_id, FLOOR((UNIX_TIMESTAMP() - created) / 86400) AS last_scanned
583
						FROM gym_defenders
584
						WHERE owner_name = '".$trainer_name."' AND fort_id IS NOT NULL
585
						ORDER BY deployment_time";
586
		$result = $this->mysqli->query($req);
587
		$pokemon = array();
588
		while ($data = $result->fetch_object()) {
589
			$pokemon[] = $data;
590
		}
591
		return $pokemon;
592
	}
593
594
	public function getInactivePokemon($trainer_name) {
595
		$req = "SELECT pokemon_id, cp, atk_iv AS iv_attack, sta_iv AS iv_stamina, def_iv AS iv_defense, NULL AS deployment_time, '0' AS active, fort_id as gym_id, FLOOR((UNIX_TIMESTAMP() - created) / 86400) AS last_scanned
596
					FROM gym_defenders
597
					WHERE owner_name = '".$trainer_name."' AND fort_id IS NULL
598
					ORDER BY last_scanned";
599
		$result = $this->mysqli->query($req);
600
		$pokemon = array();
601
		while ($data = $result->fetch_object()) {
602
			$pokemon[] = $data;
603
		}
604
		return $pokemon;
605
	}
606
607 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...
608
		$exclue = "";
609
		if (!empty(self::$config->system->trainer_blacklist)) {
610
			$exclue .= " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
611
		}
612
		$req = "SELECT COUNT(*) AS count, level FROM (SELECT MAX(owner_level) as level FROM gym_defenders WHERE owner_level IS NOT NULL AND team = '".$team_id."' ".$exclue." GROUP BY owner_level, owner_name) x GROUP BY level";
613
		$result = $this->mysqli->query($req);
614
		$levelData = array();
615
		while ($data = $result->fetch_object()) {
616
			$levelData[$data->level] = $data->count;
617
		}
618
		for ($i = 5; $i <= 40; $i++) {
619
			if (!isset($levelData[$i])) {
620
				$levelData[$i] = 0;
621
			}
622
		}
623
		# sort array again
624
		ksort($levelData);
625
		return $levelData;
626
	}
627
628
629
	/////////
630
	// Cron
631
	/////////
632
633
	public function getPokemonCountsActive() {
634
		$req = "SELECT pokemon_id, COUNT(*) as total FROM sightings WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW()) GROUP BY pokemon_id";
635
		$result = pg_query($this->db, $req);
636
		$counts = array();
637
		while ($data = pg_fetch_object($result)) {
638
			$counts[$data->pokemon_id] = $data->total;
639
		}
640
		return $counts;
641
	}
642
643
	public function getPokemonCountsLastDay() {
644
		$req = "SELECT pokemon_id, COUNT(*) AS spawns_last_day
645
					FROM sightings
646
					WHERE expire_timestamp >= (SELECT MAX(expire_timestamp) - 86400 FROM sightings)
647
					GROUP BY pokemon_id
648
				  	ORDER BY pokemon_id ASC";
649
		$result = pg_query($this->db, $req);
650
		$counts = array();
651
		while ($data = pg_fetch_object($result)) {
652
			$counts[$data->pokemon_id] = $data->spawns_last_day;
653
		}
654
		return $counts;
655
	}
656
657 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...
658
		$where = "WHERE p.pokemon_id = '".$pokemon_id."' AND p.expire_timestamp - (coalesce(CASE WHEN duration = 0 THEN NULL ELSE duration END ,30)*60) > '".$last_update."'";
659
		$req = "SELECT count, p.expire_timestamp - (coalesce(CASE WHEN duration = 0 THEN NULL ELSE duration END ,30)*60) AS last_timestamp, (TO_TIMESTAMP(expire_timestamp)) AS disappear_time_real, lat as latitude, lon as longitude
660
					FROM sightings p
661
					LEFT JOIN spawnpoints s ON p.spawn_id = s.spawn_id
662
				  	JOIN (SELECT COUNT(*) AS count
663
						FROM FROM sightings p
664
						LEFT JOIN spawnpoints s ON p.spawn_id = s.spawn_id
665
                    	" . $where. "
666
                    ) count ON 1 = 1
667
					" . $where . "
668
					ORDER BY last_timestamp DESC
669
					LIMIT 1 OFFSET 0";
670
		$result = pg_query($this->db, $req);
671
		$data = pg_fetch_object($result);
672
		return $data;
673
	}
674
675 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...
676
		$where = "WHERE pokemon_id = '".$pokemon_id."' AND time_battle > '".$last_update."'";
677
		$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
678
					FROM raids r
679
					JOIN forts g ON r.fort_id = g.id
680
					JOIN (SELECT COUNT(*) AS count
681
						FROM raids
682
                    	" . $where."
683
                    ) count ON 1 = 1
684
	                " . $where."
685
	                ORDER BY time_battle DESC
686
					LIMIT 1 OFFSET 0";
687
		$result = pg_query($this->db, $req);
688
		$data = pg_fetch_object($result);
689
		return $data;
690
	}
691
692 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...
693
		$req = " SELECT COUNT(*) as total FROM accounts WHERE captchaed IS NOT NULL AND reason IS NULL";
694
		$result = pg_query($this->db, $req);
695
		$data = pg_fetch_object($result);
696
		return $data;
697
	}
698
699
	public function getNestData() {
700
		$pokemon_exclude_sql = "";
701
		if (!empty(self::$config->system->nest_exclude_pokemon)) {
702
			$pokemon_exclude_sql = "AND p.pokemon_id NOT IN (" . implode(",", self::$config->system->nest_exclude_pokemon) . ")";
703
		}
704
		$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, MAX(s.updated) as latest_seen, coalesce(CASE WHEN MAX(duration) = 0 THEN NULL ELSE MAX(duration) END ,30)*60 as duration
705
			          FROM sightings p
706
			          INNER JOIN spawnpoints s ON (p.spawn_id = s.spawn_id)
707
			          WHERE p.expire_timestamp > EXTRACT(EPOCH FROM NOW()) - 86400
708
			          " . $pokemon_exclude_sql . "
709
			          GROUP BY p.spawn_id, p.pokemon_id
710
			          HAVING COUNT(p.pokemon_id) >= 6
711
			          ORDER BY p.pokemon_id";
712
		$result = pg_query($this->db, $req);
713
		$nests = array();
714
		while ($data = pg_fetch_object($result)) {
715
			$nests[] = $data;
716
		}
717
		return $nests;
718
	}
719
720
}
721