Failed Conditions
Pull Request — master (#371)
by
unknown
02:05
created

QueryManagerPostgresqlMonocleAlternate   F

Complexity

Total Complexity 115

Size/Duplication

Total Lines 778
Duplicated Lines 38.17 %

Coupling/Cohesion

Components 1
Dependencies 1

Importance

Changes 0
Metric Value
dl 297
loc 778
rs 1.822
c 0
b 0
f 0
wmc 115
lcom 1
cbo 1

45 Methods

Rating   Name   Duplication   Size   Complexity  
A __construct() 0 4 1
A __destruct() 0 4 1
A testTotalPokemon() 15 17 3
A testTotalGyms() 15 17 3
A testTotalPokestops() 15 17 3
A getTotalPokemon() 6 8 1
A getTotalLures() 0 6 1
A getTotalGyms() 6 8 1
A getTotalRaids() 6 8 1
A getTotalGymsForTeam() 9 11 1
A getRecentAll() 0 17 3
A getRecentMythic() 0 18 3
A getGymsProtectedByPokemon() 9 11 1
A getPokemonLastSeen() 10 12 1
A getTop50Pokemon() 15 17 2
A getTop50Trainers() 0 22 3
A getPokemonHeatmap() 0 13 2
A getPokemonGraph() 0 17 3
B getPokemonLive() 0 36 11
A getPokemonSliderMinMax() 6 8 1
A getMapsCoords() 6 8 1
A getPokemonCount() 8 10 1
A getRaidCount() 8 10 1
A getTotalPokestops() 6 8 1
A getAllPokestops() 0 11 2
A getTeamGuardians() 0 15 2
A getOwnedAndPoints() 9 11 1
A getAllGyms() 0 13 2
A getGymData() 10 12 1
A getGymDefenders() 0 14 2
B getGymHistories() 13 35 9
A getGymHistoriesPokemon() 0 14 2
B getHistoryForGym() 20 39 8
A getHistoryForGymPokemon() 14 15 2
A getAllRaids() 15 17 2
B getTrainers() 26 53 9
A getTrainerLevelRanking() 22 22 5
A getActivePokemon() 0 14 2
A getInactivePokemon() 0 14 2
A getTrainerLevelCount() 22 22 5
A getPokemonCountsActive() 0 11 2
A getPokemonCountsLastDay() 0 15 2
A getCaptchaCount() 6 8 1
A getNestData() 0 23 3
A getSpawnpointCount() 0 10 1

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
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...
4
{
5
    public function __construct()
6
    {
7
        parent::__construct();
8
    }
9
10
    public function __destruct()
11
    {
12
        parent::__destruct();
13
    }
14
15
    ///////////
16
    // Tester
17
    ///////////
18
19 View Code Duplication
    public function testTotalPokemon()
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...
20
    {
21
        $req = 'SELECT COUNT(*) as total FROM sightings';
22
        $result = pg_query($this->db, $req);
23
        if (false === $result) {
24
            return 1;
25
        } else {
26
            $data = pg_fetch_object($result);
27
            $total = $data->total;
28
29
            if (0 == $total) {
30
                return 2;
31
            }
32
        }
33
34
        return 0;
35
    }
36
37 View Code Duplication
    public function testTotalGyms()
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...
38
    {
39
        $req = 'SELECT COUNT(*) as total FROM forts';
40
        $result = pg_query($this->db, $req);
41
        if (false === $result) {
42
            return 1;
43
        } else {
44
            $data = pg_fetch_object($result);
45
            $total = $data->total;
46
47
            if (0 == $total) {
48
                return 2;
49
            }
50
        }
51
52
        return 0;
53
    }
54
55 View Code Duplication
    public function testTotalPokestops()
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...
56
    {
57
        $req = 'SELECT COUNT(*) as total FROM pokestops';
58
        $result = pg_query($this->db, $req);
59
        if (false === $result) {
60
            return 1;
61
        } else {
62
            $data = pg_fetch_object($result);
63
            $total = $data->total;
64
65
            if (0 == $total) {
66
                return 2;
67
            }
68
        }
69
70
        return 0;
71
    }
72
73
    /////////////
74
    // Homepage
75
    /////////////
76
77 View Code Duplication
    public function getTotalPokemon()
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...
78
    {
79
        $req = 'SELECT COUNT(*) AS total FROM sightings WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW())';
80
        $result = pg_query($this->db, $req);
81
        $data = pg_fetch_object($result);
82
83
        return $data;
84
    }
85
86
    public function getTotalLures()
87
    {
88
        $data = (object) array('total' => 0);
89
90
        return $data;
91
    }
92
93 View Code Duplication
    public function getTotalGyms()
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...
94
    {
95
        $req = 'SELECT COUNT(*) AS total FROM forts';
96
        $result = pg_query($this->db, $req);
97
        $data = pg_fetch_object($result);
98
99
        return $data;
100
    }
101
102 View Code Duplication
    public function getTotalRaids()
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...
103
    {
104
        $req = 'SELECT COUNT(*) AS total FROM raids WHERE time_battle <= EXTRACT(EPOCH FROM NOW()) AND time_end >= EXTRACT(EPOCH FROM NOW())';
105
        $result = pg_query($this->db, $req);
106
        $data = pg_fetch_object($result);
107
108
        return $data;
109
    }
110
111 View Code Duplication
    public function getTotalGymsForTeam($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...
112
    {
113
        $req = "SELECT COUNT(*) AS total
114
					FROM forts f
115
					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))
116
					WHERE team = '$team_id'";
117
        $result = pg_query($this->db, $req);
118
        $data = pg_fetch_object($result);
119
120
        return $data;
121
    }
122
123
    public function getRecentAll()
124
    {
125
        $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,
126
              lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
127
              FROM sightings
128
              ORDER BY updated DESC
129
              LIMIT 12 OFFSET 0';
130
        $result = pg_query($this->db, $req);
131
        $data = array();
132
        if ($result->num_rows > 0) {
133
            while ($row = pg_fetch_object($result)) {
134
                $data[] = $row;
135
            }
136
        }
137
138
        return $data;
139
    }
140
141
    public function getRecentMythic($mythic_pokemon)
142
    {
143
        $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,
144
                lat AS latitude, lon AS longitude, cp, atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina
145
                FROM sightings
146
                WHERE pokemon_id IN ('.implode(',', $mythic_pokemon).')
147
                ORDER BY updated DESC
148
                LIMIT 12 OFFSET 0';
149
        $result = pg_query($this->db, $req);
150
        $data = array();
151
        if ($result->num_rows > 0) {
152
            while ($row = pg_fetch_object($result)) {
153
                $data[] = $row;
154
            }
155
        }
156
157
        return $data;
158
    }
159
160
    ///////////////////
161
    // Single Pokemon
162
    ///////////////////
163
164 View Code Duplication
    public function getGymsProtectedByPokemon($pokemon_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...
165
    {
166
        $req = "SELECT COUNT(f.id) AS total
167
					FROM forts f
168
					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))
169
					WHERE guard_pokemon_id = '".$pokemon_id."'";
170
        $result = pg_query($this->db, $req);
171
        $data = pg_fetch_object($result);
172
173
        return $data;
174
    }
175
176 View Code Duplication
    public function getPokemonLastSeen($pokemon_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...
177
    {
178
        $req = "SELECT TO_TIMESTAMP(expire_timestamp) AS expire_timestamp, TO_TIMESTAMP(expire_timestamp) AS disappear_time_real, lat AS latitude, lon AS longitude
179
                FROM sightings
180
                WHERE pokemon_id = '".$pokemon_id."'
181
                ORDER BY expire_timestamp DESC
182
                LIMIT 1 OFFSET 0";
183
        $result = pg_query($this->db, $req);
184
        $data = pg_fetch_object($result);
185
186
        return $data;
187
    }
188
189 View Code Duplication
    public function getTop50Pokemon($pokemon_id, $top_order_by, $top_direction)
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...
190
    {
191
        $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,
192
                cp, atk_iv as individual_attack, def_iv as individual_defense, sta_iv as individual_stamina,
193
                ROUND(100*(atk_iv+def_iv+sta_iv)/45,1) AS \"IV\", move_1 as move_1, move_2, form
194
                FROM sightings
195
	            WHERE pokemon_id = '".$pokemon_id."' AND move_1 IS NOT NULL AND move_1 <> '0'
196
	            ORDER BY $top_order_by $top_direction, expire_timestamp DESC
197
	            LIMIT 50 OFFSET 0";
198
        $result = pg_query($this->db, $req);
199
        $top = array();
200
        while ($data = pg_fetch_object($result)) {
201
            $top[] = $data;
202
        }
203
204
        return $top;
205
    }
206
207
    public function getTop50Trainers($pokemon_id, $best_order_by, $best_direction)
208
    {
209
        $trainer_blacklist = '';
210
        if (!empty(self::$config->system->trainer_blacklist)) {
211
            $trainer_blacklist = " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
212
        }
213
214
        $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,
215
                TO_TIMESTAMP(last_modified) AS lasttime, last_modified as last_seen
216
                FROM gym_defenders
217
				WHERE pokemon_id = '".$pokemon_id."'".$trainer_blacklist."
218
				ORDER BY $best_order_by $best_direction, owner_name ASC
219
				LIMIT 50 OFFSET 0";
220
221
        $result = pg_query($this->db, $req);
222
        $toptrainer = array();
223
        while ($data = pg_fetch_object($result)) {
224
            $toptrainer[] = $data;
225
        }
226
227
        return $toptrainer;
228
    }
229
230
    public function getPokemonHeatmap($pokemon_id, $start, $end)
231
    {
232
        $where = ' WHERE pokemon_id = '.$pokemon_id.' '
233
            ."AND TO_TIMESTAMP(expire_timestamp) BETWEEN '".$start."' AND '".$end."'";
234
        $req = 'SELECT lat AS latitude, lon AS longitude FROM sightings'.$where.' LIMIT 100000';
235
        $result = pg_query($this->db, $req);
236
        $points = array();
237
        while ($data = pg_fetch_object($result)) {
238
            $points[] = $data;
239
        }
240
241
        return $points;
242
    }
243
244
    public function getPokemonGraph($pokemon_id)
245
    {
246
        $req = "SELECT COUNT(*) AS total, EXTRACT(HOUR FROM disappear_time) AS disappear_hour
247
					FROM (SELECT TO_TIMESTAMP(expire_timestamp) as disappear_time FROM sightings WHERE pokemon_id = '".$pokemon_id."' LIMIT 100000) AS pokemonFiltered
248
				GROUP BY disappear_hour
249
				ORDER BY disappear_hour";
250
        $result = pg_query($this->db, $req);
251
        $array = array_fill(0, 24, 0);
252
        while ($result && $data = pg_fetch_object($result)) {
253
            $array[$data->disappear_hour] = $data->total;
254
        }
255
        // shift array because AM/PM starts at 1AM not 0:00
256
        $array[] = $array[0];
257
        array_shift($array);
258
259
        return $array;
260
    }
261
262
    public function getPokemonLive($pokemon_id, $ivMin, $ivMax, $inmap_pokemons)
263
    {
264
        $inmap_pkms_filter = '';
265
        $where = ' WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW()) AND pokemon_id = '.$pokemon_id;
266
267
        $reqTestIv = 'SELECT MAX(atk_iv) AS iv FROM sightings '.$where;
268
        $resultTestIv = pg_query($this->db, $reqTestIv);
269
        $testIv = pg_fetch_object($resultTestIv);
270
        if (!is_null($inmap_pokemons) && ('' != $inmap_pokemons)) {
271
            foreach ($inmap_pokemons as $inmap) {
272
                $inmap_pkms_filter .= "'".$inmap."',";
273
            }
274
            $inmap_pkms_filter = rtrim($inmap_pkms_filter, ',');
275
            $where .= ' AND encounter_id NOT IN ('.$inmap_pkms_filter.') ';
276
        }
277
        if (null != $testIv->iv && !is_null($ivMin) && ('' != $ivMin)) {
278
            $where .= ' AND ((100/45)*(atk_iv + def_iv + sta_iv)) >= ('.$ivMin.') ';
279
        }
280
        if (null != $testIv->iv && !is_null($ivMax) && ('' != $ivMax)) {
281
            $where .= ' AND ((100/45)*(atk_iv + def_iv + sta_iv)) <= ('.$ivMax.') ';
282
        }
283
        $req = 'SELECT pokemon_id, lat AS latitude, lon AS longitude,
284
    					TO_TIMESTAMP(expire_timestamp) AS disappear_time,
285
    					TO_TIMESTAMP(expire_timestamp) AS disappear_time_real,
286
    					atk_iv AS individual_attack, def_iv AS individual_defense, sta_iv AS individual_stamina,
287
   						move_1, move_2
288
					FROM sightings '.$where.'
289
					LIMIT 5000';
290
        $result = pg_query($this->db, $req);
291
        $spawns = array();
292
        while ($data = pg_fetch_object($result)) {
293
            $spawns[] = $data;
294
        }
295
296
        return $spawns;
297
    }
298
299 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...
300
    {
301
        $req = 'SELECT TO_TIMESTAMP(MIN(expire_timestamp)) AS min, TO_TIMESTAMP(MAX(expire_timestamp)) AS max FROM sightings';
302
        $result = pg_query($this->db, $req);
303
        $data = pg_fetch_object($result);
304
305
        return $data;
306
    }
307
308 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...
309
    {
310
        $req = 'SELECT MAX(lat) AS max_latitude, MIN(lat) AS min_latitude, MAX(lon) AS max_longitude, MIN(lon) as min_longitude FROM spawnpoints';
311
        $result = pg_query($this->db, $req);
312
        $data = pg_fetch_object($result);
313
314
        return $data;
315
    }
316
317 View Code Duplication
    public function getPokemonCount($pokemon_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...
318
    {
319
        $req = 'SELECT count, last_seen, latitude, longitude
320
					FROM pokemon_stats
321
					WHERE pid = '.$pokemon_id;
322
        $result = pg_query($this->db, $req);
323
        $data = pg_fetch_object($result);
324
325
        return $data;
326
    }
327
328 View Code Duplication
    public function getRaidCount($pokemon_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...
329
    {
330
        $req = 'SELECT count, last_seen, latitude, longitude
331
					FROM raid_stats
332
					WHERE pid = '.$pokemon_id;
333
        $result = pg_query($this->db, $req);
334
        $data = pg_fetch_object($result);
335
336
        return $data;
337
    }
338
339
    ///////////////
340
    // Pokestops
341
    //////////////
342
343 View Code Duplication
    public function getTotalPokestops()
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...
344
    {
345
        $req = 'SELECT COUNT(*) as total FROM pokestops';
346
        $result = pg_query($this->db, $req);
347
        $data = pg_fetch_object($result);
348
349
        return $data;
350
    }
351
352
    public function getAllPokestops()
353
    {
354
        $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';
355
        $result = pg_query($this->db, $req);
356
        $pokestops = array();
357
        while ($data = pg_fetch_object($result)) {
358
            $pokestops[] = $data;
359
        }
360
361
        return $pokestops;
362
    }
363
364
    /////////
365
    // Gyms
366
    /////////
367
368
    public function getTeamGuardians($team_id)
369
    {
370
        $req = "SELECT COUNT(*) AS total, guard_pokemon_id
371
					FROM forts f
372
					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))
373
					WHERE team = '".$team_id."' GROUP BY guard_pokemon_id ORDER BY total DESC LIMIT 3 OFFSET 0";
374
        $result = pg_query($this->db, $req);
375
376
        $datas = array();
377
        while ($data = pg_fetch_object($result)) {
378
            $datas[] = $data;
379
        }
380
381
        return $datas;
382
    }
383
384 View Code Duplication
    public function getOwnedAndPoints($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...
385
    {
386
        $req = "SELECT COUNT(f.id) AS total, ROUND(AVG(fs.total_cp))AS average_points
387
        			FROM forts f
388
					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))
389
        			WHERE fs.team = '".$team_id."'";
390
        $result = pg_query($this->db, $req);
391
        $data = pg_fetch_object($result);
392
393
        return $data;
394
    }
395
396
    public function getAllGyms()
397
    {
398
        $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
399
					FROM forts f
400
					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))';
401
        $result = pg_query($this->db, $req);
402
        $gyms = array();
403
        while ($data = pg_fetch_object($result)) {
404
            $gyms[] = $data;
405
        }
406
407
        return $gyms;
408
    }
409
410 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...
411
    {
412
        $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
413
			FROM forts f
414
			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))
415
			WHERE f.id ='".$gym_id."'
416
			GROUP BY f.name, f.url, fs.team, fs.updated, fs.guard_pokemon_id, fs.slots_available, gd.cp";
417
        $result = pg_query($this->db, $req);
418
        $data = pg_fetch_object($result);
419
420
        return $data;
421
    }
422
423
    public function getGymDefenders($gym_id)
424
    {
425
        $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
426
			FROM gym_defenders
427
			WHERE fort_id='".$gym_id."'
428
			ORDER BY deployment_time";
429
        $result = pg_query($this->db, $req);
430
        $defenders = array();
431
        while ($data = pg_fetch_object($result)) {
432
            $defenders[] = $data;
433
        }
434
435
        return $defenders;
436
    }
437
438
    ////////////////
439
    // Gym History
440
    ////////////////
441
442
    public function getGymHistories($gym_name, $team, $page, $ranking)
443
    {
444
        $where = '';
445
        if (isset($gym_name) && '' != $gym_name) {
446
            $where = " WHERE name LIKE '%".$gym_name."%'";
447
        }
448 View Code Duplication
        if (isset($team) && '' != $team) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
449
            $where .= ('' === $where ? ' WHERE' : ' AND').' fs.team = '.$team;
450
        }
451 View Code Duplication
        switch ($ranking) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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
            case 1:
453
                $order = ' ORDER BY name, last_modified DESC';
454
                break;
455
            case 2:
456
                $order = ' ORDER BY total_cp DESC, last_modified DESC';
457
                break;
458
            default:
459
                $order = ' ORDER BY last_modified DESC, name';
460
        }
461
462
        $limit = ' LIMIT 10 OFFSET '.($page * 10);
463
464
        $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
465
			FROM forts f
466
			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))
467
			'.$where.$order.$limit;
468
469
        $result = pg_query($this->db, $req);
470
        $gym_history = array();
471
        while ($data = pg_fetch_object($result)) {
472
            $gym_history[] = $data;
473
        }
474
475
        return $gym_history;
476
    }
477
478
    public function getGymHistoriesPokemon($gym_id)
479
    {
480
        $req = "SELECT external_id AS pokemon_uid, pokemon_id, cp_now as cp, owner_name AS trainer_name
481
					FROM gym_defenders
482
					WHERE fort_id = '".$gym_id."'
483
					ORDER BY deployment_time";
484
        $result = pg_query($this->db, $req);
485
        $pokemons = array();
486
        while ($data = pg_fetch_object($result)) {
487
            $pokemons[] = $data;
488
        }
489
490
        return $pokemons;
491
    }
492
493
    public function getHistoryForGym($page, $gym_id)
494
    {
495 View Code Duplication
        if (isset(self::$config->system->gymhistory_hide_cp_changes) && true === self::$config->system->gymhistory_hide_cp_changes) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
496
            $pageSize = 25;
497
        } else {
498
            $pageSize = 10;
499
        }
500
        $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
501
					FROM fort_sightings fs
502
					LEFT JOIN forts f ON f.id = fs.fort_id
503
					WHERE f.id = '".$gym_id."'
504
					ORDER BY fs.last_modified DESC
505
					LIMIT ".($pageSize + 1).' OFFSET '.($page * $pageSize);
506
        $result = pg_query($this->db, $req);
507
        $history = array();
508
        $count = 0;
509 View Code Duplication
        while ($data = pg_fetch_object($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
510
            ++$count;
511
            if (0 == $data->total_cp) {
512
                $data->pokemon = array();
513
                $data->pokemon_count = 0;
514
                $data->pokemon_uids = '';
515
            } else {
516
                $data->pokemon = $this->getHistoryForGymPokemon($gym_id, $data->last_modified_real);
517
                $data->pokemon_count = count($data->pokemon);
518
                $data->pokemon_uids = implode(',', array_keys($data->pokemon));
519
            }
520
            if (0 === $data->total_cp || 0 !== $data->pokemon_count) {
521
                $history[] = $data;
522
            }
523
        }
524
        if ($count !== ($pageSize + 1)) {
525
            $last_page = true;
526
        } else {
527
            $last_page = false;
528
        }
529
530
        return array('last_page' => $last_page, 'data' => $history);
531
    }
532
533 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...
534
    {
535
        $req = "SELECT ghd.defender_id, gd.pokemon_id, ghd.cp, gd.owner_name as trainer_name
536
					FROM gym_history_defenders ghd
537
					JOIN gym_defenders gd ON ghd.defender_id = gd.external_id
538
					WHERE ghd.fort_id = '".$gym_id."' AND date = '".$last_modified."'
539
					ORDER BY gd.deployment_time";
540
        $result = pg_query($this->db, $req);
541
        $pokemons = array();
542
        while ($data = pg_fetch_object($result)) {
543
            $pokemons[$data->defender_id] = $data;
544
        }
545
546
        return $pokemons;
547
    }
548
549
    ///////////
550
    // Raids
551
    ///////////
552
553 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...
554
    {
555
        $limit = ' LIMIT 10 OFFSET '.($page * 10);
556
        $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
557
					FROM forts f
558
					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))
559
				 	LEFT JOIN raids r ON (r.fort_id = f.id AND r.time_end >= UNIX_TIMESTAMP())
560
					WHERE r.time_end > EXTRACT(EPOCH FROM NOW())
561
					ORDER BY r.level DESC, r.time_battle'.$limit;
562
        $result = pg_query($this->db, $req);
563
        $raids = array();
564
        while ($data = pg_fetch_object($result)) {
565
            $raids[] = $data;
566
        }
567
568
        return $raids;
569
    }
570
571
    //////////////
572
    // Trainers
573
    //////////////
574
575
    public function getTrainers($trainer_name, $team, $page, $rankingNumber)
576
    {
577
        $ranking = $this->getTrainerLevelRanking();
578
        $where = '';
579
        if (!empty(self::$config->system->trainer_blacklist)) {
580
            $where .= " AND gd.owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
581
        }
582
        if ('' != $trainer_name) {
583
            $where = " AND gd.owner_name LIKE '%".$trainer_name."%'";
584
        }
585 View Code Duplication
        if (0 != $team) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
586
            $where .= ('' == $where ? ' HAVING' : ' AND').' team = '.$team;
587
        }
588 View Code Duplication
        switch ($rankingNumber) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
589
            case 1:
590
                $order = ' ORDER BY active DESC, level DESC';
591
                break;
592
            case 2:
593
                $order = ' ORDER BY maxCp DESC, level DESC';
594
                break;
595
            default:
596
                $order = ' ORDER BY level DESC, active DESC';
597
        }
598
        $order .= ', last_seen DESC, name ';
599
        $limit = ' LIMIT 10 OFFSET '.($page * 10);
600
        $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
601
				  	FROM gym_defenders gd
602
				  	LEFT JOIN (
603
				  		SELECT owner_name, COUNT(*) as active
604
				  		FROM gym_defenders gd2
605
						WHERE fort_id IS NOT NULL
606
				  		GROUP BY owner_name
607
				  	) active ON active.owner_name = gd.owner_name
608
				  	WHERE level IS NOT NULL '.$where.'
609
				  	GROUP BY gd.owner_name'.$order.$limit;
610
        $result = pg_query($this->db, $req);
611
        $trainers = array();
612 View Code Duplication
        while ($data = pg_fetch_object($result)) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across 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...
613
            $data->last_seen = date('Y-m-d', strtotime($data->last_seen));
614
            if (is_null($data->active)) {
615
                $data->active = 0;
616
            }
617
            $trainers[$data->name] = $data;
618
619
            $pokemon = array_merge($this->getActivePokemon($data->name), $this->getInactivePokemon($data->name));
620
621
            $trainers[$data->name]->gyms = $data->active;
622
            $trainers[$data->name]->pokemons = $pokemon;
623
            $trainers[$data->name]->rank = $ranking[$data->level];
624
        }
625
626
        return $trainers;
627
    }
628
629 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...
630
    {
631
        $exclue = '';
632
        if (!empty(self::$config->system->trainer_blacklist)) {
633
            $exclue .= " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
634
        }
635
        $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';
636
        $result = pg_query($this->db, $req);
637
        $levelData = array();
638
        while ($data = pg_fetch_object($result)) {
639
            $levelData[$data->level] = $data->count;
640
        }
641
        for ($i = 5; $i <= 40; ++$i) {
642
            if (!isset($levelData[$i])) {
643
                $levelData[$i] = 0;
644
            }
645
        }
646
        // sort array again
647
        ksort($levelData);
648
649
        return $levelData;
650
    }
651
652
    public function getActivePokemon($trainer_name)
653
    {
654
        $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
655
						FROM gym_defenders
656
						WHERE owner_name = '".$trainer_name."' AND fort_id IS NOT NULL
657
						ORDER BY deployment_time";
658
        $result = pg_query($this->db, $req);
659
        $pokemon = array();
660
        while ($data = pg_fetch_object($result)) {
661
            $pokemon[] = $data;
662
        }
663
664
        return $pokemon;
665
    }
666
667
    public function getInactivePokemon($trainer_name)
668
    {
669
        $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
670
					FROM gym_defenders
671
					WHERE owner_name = '".$trainer_name."' AND fort_id IS NULL
672
					ORDER BY last_scanned";
673
        $result = pg_query($this->db, $req);
674
        $pokemon = array();
675
        while ($data = pg_fetch_object($result)) {
676
            $pokemon[] = $data;
677
        }
678
679
        return $pokemon;
680
    }
681
682 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...
683
    {
684
        $exclue = '';
685
        if (!empty(self::$config->system->trainer_blacklist)) {
686
            $exclue .= " AND owner_name NOT IN ('".implode("','", self::$config->system->trainer_blacklist)."')";
687
        }
688
        $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';
689
        $result = pg_query($this->db, $req);
690
        $levelData = array();
691
        while ($data = pg_fetch_object($result)) {
692
            $levelData[$data->level] = $data->count;
693
        }
694
        for ($i = 5; $i <= 40; ++$i) {
695
            if (!isset($levelData[$i])) {
696
                $levelData[$i] = 0;
697
            }
698
        }
699
        // sort array again
700
        ksort($levelData);
701
702
        return $levelData;
703
    }
704
705
    /////////
706
    // Cron
707
    /////////
708
709
    public function getPokemonCountsActive()
710
    {
711
        $req = 'SELECT pokemon_id, COUNT(*) as total FROM sightings WHERE expire_timestamp >= EXTRACT(EPOCH FROM NOW()) GROUP BY pokemon_id';
712
        $result = pg_query($this->db, $req);
713
        $counts = array();
714
        while ($data = pg_fetch_object($result)) {
715
            $counts[$data->pokemon_id] = $data->total;
716
        }
717
718
        return $counts;
719
    }
720
721
    public function getPokemonCountsLastDay()
722
    {
723
        $req = 'SELECT pokemon_id, COUNT(*) AS spawns_last_day
724
					FROM sightings
725
					WHERE expire_timestamp >= (SELECT MAX(expire_timestamp) - 86400 FROM sightings)
726
					GROUP BY pokemon_id
727
				  	ORDER BY pokemon_id ASC';
728
        $result = pg_query($this->db, $req);
729
        $counts = array();
730
        while ($data = pg_fetch_object($result)) {
731
            $counts[$data->pokemon_id] = $data->spawns_last_day;
732
        }
733
734
        return $counts;
735
    }
736
737 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...
738
    {
739
        $req = ' SELECT COUNT(*) as total FROM accounts WHERE captchaed IS NOT NULL AND reason IS NULL';
740
        $result = pg_query($this->db, $req);
741
        $data = pg_fetch_object($result);
742
743
        return $data;
744
    }
745
746
    public function getNestData($time, $minLatitude, $maxLatitude, $minLongitude, $maxLongitude)
747
    {
748
        $pokemon_exclude_sql = '';
749
        if (!empty(self::$config->system->nest_exclude_pokemon)) {
750
            $pokemon_exclude_sql = 'AND p.pokemon_id NOT IN ('.implode(',', self::$config->system->nest_exclude_pokemon).')';
751
        }
752
        $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
753
			          FROM sightings p
754
			          INNER JOIN spawnpoints s ON (p.spawn_id = s.spawn_id)
755
			          WHERE p.expire_timestamp > EXTRACT(EPOCH FROM NOW()) - '.($time * 3600).'
756
			            AND p.lat >= '.$minLatitude.' AND p.lat < '.$maxLatitude.' AND p.lon >= '.$minLongitude.' AND p.lon < '.$maxLongitude.'
757
			          '.$pokemon_exclude_sql.'
758
			          GROUP BY p.spawn_id, p.pokemon_id
759
			          HAVING COUNT(p.pokemon_id) >= '.($time / 4).'
760
			          ORDER BY p.pokemon_id';
761
        $result = pg_query($this->db, $req);
762
        $nests = array();
763
        while ($data = pg_fetch_object($result)) {
764
            $nests[] = $data;
765
        }
766
767
        return $nests;
768
    }
769
770
    public function getSpawnpointCount($minLatitude, $maxLatitude, $minLongitude, $maxLongitude)
771
    {
772
        $req = 'SELECT COUNT(*) as total 
773
					FROM spawnpoints 
774
 					WHERE lat >= '.$minLatitude.' AND lat < '.$maxLatitude.' AND lon >= '.$minLongitude.' AND lon < '.$maxLongitude;
775
        $result = pg_query($this->db, $req);
776
        $data = pg_fetch_object($result);
777
778
        return $data;
779
    }
780
}
781