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

QueryManagerMysqlMonocleAlternate::getTrainers()   B

Complexity

Conditions 9
Paths 108

Size

Total Lines 53

Duplication

Lines 26
Ratio 49.06 %

Importance

Changes 0
Metric Value
cc 9
nc 108
nop 4
dl 26
loc 53
rs 7.4165
c 0
b 0
f 0

How to fix   Long Method   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

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