Failed Conditions
Push — master ( 328b73...9cdd6e )
by Markus
04:54
created

getTotalGymsForTeam()   A

Complexity

Conditions 1
Paths 1

Size

Total Lines 11

Duplication

Lines 9
Ratio 81.82 %

Importance

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