Completed
Push — work-fleets ( 22b024...7f5906 )
by SuperNova.WS
06:37
created

sys_stat.php ➔ sys_stat_calculate_flush()   B

Complexity

Conditions 4
Paths 3

Size

Total Lines 34
Code Lines 26

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 4
eloc 26
nc 3
nop 2
dl 0
loc 34
rs 8.5806
c 2
b 0
f 0
1
<?php
2
3
/**
4
 * sys_stat_functions.php
5
 *
6
 * @version 7 (c) copyright 2010-2014 by Gorlum for http://supernova.ws
7
 *   [!] Full rewrite
8
 * @version 6 (c) copyright 2010-2012 by Gorlum for http://supernova.ws
9
 *   [~] Made statistic non-transactional again to prevent locks
10
 * @version 5 (c) copyright 2010-2011 by Gorlum for http://supernova.ws
11
 *   [-] Rid of all procedures - they only called once per loop and make unneeded overhead
12
 *   [~] Some optimizations. +6% to script speed on test base
13
 *   [~] Wrapped update in transaction. Decreased script execution time by 98%
14
 * @version 4 (c) copyright 2010 by Gorlum for http://supernova.ws
15
 *   [~] Now setting time limit also update end time in the DB
16
 *   [+] Logging more information about update process to simplify error detection
17
 *   [+] Implemented locking mechanic that permits launches of more then one update process
18
 *   [+] Stat update logging statistic about it progress to DB
19
 * @version 3 (c) copyright 2010 by Gorlum for http://supernova.ws
20
 *   [+] Added resource stat
21
 * @version 2 (c) copyright 2010 by Gorlum for http://supernova.ws
22
 *   [!] Stats calculation greatly increased to 10x times (and even more in certain configurations)
23
 *   [!] Now all ranks for players/allies counting here - no unnecessary UPDATEs in /stats.php
24
 *   [*] All planet funcs merged into GetPlanetPoints
25
 *   [*] GetPlanetPoints optimized to utilize properties of geometrical progression
26
 *   [*] Planet-related calculations now made within one SQL-query for all planets - not per user
27
 *   [*] Fleet-On-Fly-related calculations now made within one SQL-query for all fleets - not per user
28
 *   [*] Greatly improved insertions of new Allie's stat by moving all calculation to single query
29
 *   [*] Greatly improved speed of updating Player's rank by moving every rank update to single query
30
 * StatFunctions.php @version 1 copyright 2008 by Chlorel for XNova
31
 */
32
33
function sta_set_time_limit($sta_update_msg = 'updating something', $next_step = true) {
34
  global $sta_update_step;
35
36
  $value = classSupernova::$config->stats_minimal_interval ? classSupernova::$config->stats_minimal_interval : 600;
0 ignored issues
show
Documentation introduced by
The property stats_minimal_interval does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
37
  set_time_limit($value);
38
  classSupernova::$config->db_saveItem('var_stat_update_end', time() + $value);
39
40
  $sta_update_msg = db_escape($sta_update_msg);
41
42
  if($next_step) {
43
    $sta_update_step++;
44
  }
45
  $sta_update_msg = "Update in progress. Step {$sta_update_step}/14: {$sta_update_msg}.";
46
47
  classSupernova::$config->db_saveItem('var_stat_update_msg', $sta_update_msg);
48
  if($next_step) {
49
    classSupernova::$debug->warning($sta_update_msg, 'Stat update', LOG_INFO_STAT_PROCESS);
50
  }
51
}
52
53
function sys_stat_calculate_flush(&$data, $force = false) {
54
  if(count($data) < 25 && !$force) {
55
    return;
56
  }
57
58
  if(!empty($data)) {
59
    classSupernova::$gc->db->doReplaceValuesDeprecated(
0 ignored issues
show
Bug introduced by
The method doReplaceValuesDeprecated does only exist in db_mysql, but not in Closure.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
60
      TABLE_STAT_POINTS,
61
      array(
62
        'id_owner',
63
        'id_ally',
64
        'stat_type',
65
        'stat_code',
66
        'tech_points',
67
        'tech_count',
68
        'build_points',
69
        'build_count',
70
        'defs_points',
71
        'defs_count',
72
        'fleet_points',
73
        'fleet_count',
74
        'res_points',
75
        'res_count',
76
        'total_points',
77
        'total_count',
78
        'stat_date',
79
      ),
80
      $data
81
    );
82
83
  }
84
85
  $data = array();
86
}
87
88
function sys_stat_calculate() {
89
  global $sta_update_step;
90
91
  ini_set('memory_limit', classSupernova::$config->stats_php_memory ? classSupernova::$config->stats_php_memory : '1024M');
0 ignored issues
show
Documentation introduced by
The property stats_php_memory does not exist on object<classConfig>. Since you implemented __get, maybe consider adding a @property annotation.

Since your code implements the magic getter _get, this function will be called for any read access on an undefined variable. You can add the @property annotation to your class or interface to document the existence of this variable.

<?php

/**
 * @property int $x
 * @property int $y
 * @property string $text
 */
class MyLabel
{
    private $properties;

    private $allowedProperties = array('x', 'y', 'text');

    public function __get($name)
    {
        if (isset($properties[$name]) && in_array($name, $this->allowedProperties)) {
            return $properties[$name];
        } else {
            return null;
        }
    }

    public function __set($name, $value)
    {
        if (in_array($name, $this->allowedProperties)) {
            $properties[$name] = $value;
        } else {
            throw new \LogicException("Property $name is not defined.");
        }
    }

}

If the property has read access only, you can use the @property-read annotation instead.

Of course, you may also just have mistyped another name, in which case you should fix the error.

See also the PhpDoc documentation for @property.

Loading history...
Security Other Vulnerability introduced by
\classSupernova::$config...ts_php_memory : '1024M' can contain request data and is used in security-relevant context(s) leading to a potential security vulnerability.

1 path for user data to reach this point

  1. Read from $_POST
    in includes/general.php on line 258
  2. sys_get_param() returns tainted data
    in includes/general.php on line 290
  3. Data is passed through strip_tags(), and Data is passed through trim()
    in vendor/includes/general.php on line 1289
  4. sys_get_param_str_unsafe() returns tainted data
    in includes/general.php on line 294
  5. Data is escaped by mysqli_real_escape_string() for sql context(s)
    in vendor/includes/classes/db_mysql_v5.php on line 87
  6. sys_get_param_str() returns tainted data, and $result_message is assigned
    in notes.php on line 21
  7. $result_message is passed to classLocale::offsetGet()
    in notes.php on line -1
  8. $offset is passed to classLocale::offsetExists()
    in includes/classes/classLocale.php on line 121
  9. $offset is passed to classLocale::locale_string_fallback()
    in includes/classes/classLocale.php on line 109
  10. $offset is passed to classLocale::offsetSet()
    in includes/classes/classLocale.php on line -1
  11. $this->cache_prefix_lang . $offset is passed to classCache::__set()
    in includes/classes/classLocale.php on line 98
  12. classCache::$data is assigned
    in includes/classes/classCache.php on line 101
  13. Tainted property classCache::$data is read
    in includes/classes/classCache.php on line 125
  14. classCache::__get() returns tainted data
    in includes/includes/sys_stat.php on line 91

General Strategies to prevent injection

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

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

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

$sanitized = (integer) $tainted;
Loading history...
92
93
  $user_skip_list = sys_stat_get_user_skip_list();
94
95
  $rate[RES_METAL] = classSupernova::$config->rpg_exchange_metal;
0 ignored issues
show
Coding Style Comprehensibility introduced by
$rate was never initialized. Although not strictly required by PHP, it is generally a good practice to add $rate = array(); before regardless.

Adding an explicit array definition is generally preferable to implicit array definition as it guarantees a stable state of the code.

Let’s take a look at an example:

foreach ($collection as $item) {
    $myArray['foo'] = $item->getFoo();

    if ($item->hasBar()) {
        $myArray['bar'] = $item->getBar();
    }

    // do something with $myArray
}

As you can see in this example, the array $myArray is initialized the first time when the foreach loop is entered. You can also see that the value of the bar key is only written conditionally; thus, its value might result from a previous iteration.

This might or might not be intended. To make your intention clear, your code more readible and to avoid accidental bugs, we recommend to add an explicit initialization $myArray = array() either outside or inside the foreach loop.

Loading history...
96
  $rate[RES_CRYSTAL] = classSupernova::$config->rpg_exchange_crystal / classSupernova::$config->rpg_exchange_metal;
97
  $rate[RES_DEUTERIUM] = classSupernova::$config->rpg_exchange_deuterium / classSupernova::$config->rpg_exchange_metal;
98
  $rate[RES_DARK_MATTER] = classSupernova::$config->rpg_exchange_darkMatter / classSupernova::$config->rpg_exchange_metal;
99
100
  $sta_update_step = -1;
101
102
  sta_set_time_limit('starting update');
103
  $counts = $points = $unit_cost_cache = $user_allies = array();
104
105
106
  sn_db_transaction_start();
107
108
109
  sta_set_time_limit('calculating players stats');
110
  $i = 0;
111
  // Блокируем всех пользователей
112
  classSupernova::$gc->cacheOperator->db_lock_tables('users');
0 ignored issues
show
Bug introduced by
The method db_lock_tables does only exist in SnDbCachedOperator, but not in Closure.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
113
  $user_list = DBStaticUser::db_user_list('', true, 'id, dark_matter, metal, crystal, deuterium, user_as_ally, ally_id');
114
  $row_num = count($user_list);
115
  foreach($user_list as $player) {
116
    if($i++ % 100 == 0) {
117
      sta_set_time_limit("calculating players stats (player {$i}/{$row_num})", false);
118
    }
119
    if(array_key_exists($user_id = $player['id'], $user_skip_list)) {
120
      continue;
121
    }
122
123
    $resources = $player['metal'] * $rate[RES_METAL] + $player['crystal'] * $rate[RES_CRYSTAL] +
124
      $player['deuterium'] * $rate[RES_DEUTERIUM] + $player['dark_matter'] * $rate[RES_DARK_MATTER];
125
    $counts[$user_id][UNIT_RESOURCES] += $resources;
126
127
    // А здесь мы фильтруем пользователей по $user_skip_list - далее не нужно этого делать, потому что
128
    if(!isset($user_skip_list[$user_id])) {
129
      $user_allies[$user_id] = $player['ally_id'];
130
    }
131
  }
132
  unset($user_list);
133
  classSupernova::$gc->snCache->cache_clear(LOC_USER, true);
0 ignored issues
show
Bug introduced by
The method cache_clear does only exist in SnCache, but not in Closure.

It seems like the method you are trying to call exists only in some of the possible types.

Let’s take a look at an example:

class A
{
    public function foo() { }
}

class B extends A
{
    public function bar() { }
}

/**
 * @param A|B $x
 */
function someFunction($x)
{
    $x->foo(); // This call is fine as the method exists in A and B.
    $x->bar(); // This method only exists in B and might cause an error.
}

Available Fixes

  1. Add an additional type-check:

    /**
     * @param A|B $x
     */
    function someFunction($x)
    {
        $x->foo();
    
        if ($x instanceof B) {
            $x->bar();
        }
    }
    
  2. Only allow a single type to be passed if the variable comes from a parameter:

    function someFunction(B $x) { /** ... */ }
    
Loading history...
134
135
136
  sta_set_time_limit('calculating planets stats');
137
  $i = 0;
138
  $query = DBStaticPlanet::db_planet_list_resources_by_owner();
139
  $row_num = classSupernova::$db->db_num_rows($query);
140
  while($planet = db_fetch($query)) {
141
    if($i++ % 100 == 0) {
142
      sta_set_time_limit("calculating planets stats (planet {$i}/{$row_num})", false);
143
    }
144
    if(array_key_exists($user_id = $planet['id_owner'], $user_skip_list)) {
145
      continue;
146
    }
147
148
    $resources = $planet['metal'] * $rate[RES_METAL] + $planet['crystal'] * $rate[RES_CRYSTAL] +
149
      $planet['deuterium'] * $rate[RES_DEUTERIUM];
150
    $counts[$user_id][UNIT_RESOURCES] += $resources;
151
  }
152
153
  // Calculation of Fleet-In-Flight
154
  sta_set_time_limit('calculating flying fleets stats');
155
  $i = 0;
156
  $query = FleetList::dbQueryAllId();
157
  $row_num = classSupernova::$db->db_num_rows($query);
158
  while($fleet_row = db_fetch($query)) {
159
    if($i++ % 100 == 0) {
160
      sta_set_time_limit("calculating flying fleets stats (fleet {$i}/{$row_num})", false);
161
    }
162
    $objFleet = new Fleet();
163
    // TODO - без дополнительной инициализации и перераспределений памяти на каждый new Fleet()/unset($fleet)
164
    // К тому же при включённом кэшировании это быстро забъёт кэш холодными данными
165
    $objFleet->dbRowParse($fleet_row);
166
    if(array_key_exists($user_id = $objFleet->playerOwnerId, $user_skip_list)) {
167
      continue;
168
    }
169
170
    foreach($objFleet->shipsIterator() as $unit_id => $unit) {
171
      $counts[$user_id][UNIT_SHIPS] += $unit->count;
172
173
      if(!isset($unit_cost_cache[$unit_id][0])) {
174
        $unit_cost_cache[$unit_id][0] = get_unit_param($unit_id, P_COST);
175
      }
176
      $unit_cost_data = &$unit_cost_cache[$unit_id][0];
177
      $points[$user_id][UNIT_SHIPS] += ($unit_cost_data[RES_METAL] * $rate[RES_METAL] + $unit_cost_data[RES_CRYSTAL] * $rate[RES_CRYSTAL] + $unit_cost_data[RES_DEUTERIUM] * $rate[RES_DEUTERIUM]) * $unit->count;
178
    }
179
180
    $resources = $objFleet->resourcesGetTotalInMetal($rate);
181
182
    $counts[$user_id][UNIT_RESOURCES] += $resources;
183
184
    unset($objFleet);
185
  }
186
187
188
  sta_set_time_limit('calculating unit stats');
189
  $i = 0;
190
  $query = DBStaticUnit::db_unit_list_stat_calculate();
191
  $row_num = classSupernova::$db->db_num_rows($query);
192
  while($unit = db_fetch($query)) {
193
    if($i++ % 100 == 0) {
194
      sta_set_time_limit("calculating unit stats (unit {$i}/{$row_num})", false);
195
    }
196
    if(array_key_exists($user_id = $unit['unit_player_id'], $user_skip_list)) {
197
      continue;
198
    }
199
200
    $counts[$user_id][$unit['unit_type']] += $unit['unit_level'] * $unit['unit_amount'];
201
    $total_cost = eco_get_total_cost($unit['unit_snid'], $unit['unit_level']);
202
    $points[$user_id][$unit['unit_type']] += (isset($total_cost['total']) ? $total_cost['total'] : 0) * $unit['unit_amount'];
203
  }
204
205
206
  sta_set_time_limit('calculating ques stats');
207
  $i = 0;
208
  $query = DBStaticQue::db_que_list_stat();
209
  $row_num = classSupernova::$db->db_num_rows($query);
210
  while($que_item = db_fetch($query)) {
211
    if($i++ % 100 == 0) {
212
      sta_set_time_limit("calculating ques stats (que item {$i}/{$row_num})", false);
213
    }
214
    if(array_key_exists($user_id = $que_item['que_player_id'], $user_skip_list)) {
215
      continue;
216
    }
217
    $que_unit_amount = $que_item['que_unit_amount'];
218
    $que_item = sys_unit_str2arr($que_item['que_unit_price']);
219
    $resources = ($que_item[RES_METAL] * $rate[RES_METAL] + $que_item[RES_CRYSTAL] * $rate[RES_CRYSTAL] + $que_item[RES_DEUTERIUM] * $rate[RES_DEUTERIUM]) * $que_unit_amount;
220
    $counts[$user_id][UNIT_RESOURCES] += $resources;
221
  }
222
223
  sta_set_time_limit('archiving old statistic');
224
  // Statistic rotation
225
  $classConfig = classSupernova::$config;
226
  classSupernova::$db->doDeleteComplex("DELETE FROM {{statpoints}} WHERE `stat_date` < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL {$classConfig->stats_history_days} DAY));");
227
  classSupernova::$db->doUpdate("UPDATE `{{statpoints}}` SET `stat_code` = `stat_code` + 1;");
228
229
  sta_set_time_limit('posting new user stats to DB');
230
  $data = array();
231
  foreach($user_allies as $user_id => $ally_id) {
232
    $points[$user_id][UNIT_RESOURCES] = $counts[$user_id][UNIT_RESOURCES] / 1000;
233
    $points[$user_id] = array_map('floor', $points[$user_id]);
234
    $counts[$user_id] = array_map('floor', $counts[$user_id]);
235
236
    $ally_id = $ally_id ? $ally_id : 'NULL';
237
    $user_defence_points = $points[$user_id][UNIT_DEFENCE] + $points[$user_id][UNIT_DEF_MISSILES];
238
    $user_defence_counts = $counts[$user_id][UNIT_DEFENCE] + $counts[$user_id][UNIT_DEF_MISSILES];
239
    $user_points = array_sum($points[$user_id]);
240
    $user_counts = array_sum($counts[$user_id]);
241
242
    $data[] = $q = "({$user_id},{$ally_id},1,1,'{$points[$user_id][UNIT_TECHNOLOGIES]}','{$counts[$user_id][UNIT_TECHNOLOGIES]}'," .
0 ignored issues
show
Unused Code introduced by
$q is not used, you could remove the assignment.

This check looks for variable assignements that are either overwritten by other assignments or where the variable is not used subsequently.

$myVar = 'Value';
$higher = false;

if (rand(1, 6) > 3) {
    $higher = true;
} else {
    $higher = false;
}

Both the $myVar assignment in line 1 and the $higher assignment in line 2 are dead. The first because $myVar is never used and the second because $higher is always overwritten for every possible time line.

Loading history...
243
      "'{$points[$user_id][UNIT_STRUCTURES]}','{$counts[$user_id][UNIT_STRUCTURES]}','{$user_defence_points}','{$user_defence_counts}'," .
244
      "'{$points[$user_id][UNIT_SHIPS]}','{$counts[$user_id][UNIT_SHIPS]}','{$points[$user_id][UNIT_RESOURCES]}','{$counts[$user_id][UNIT_RESOURCES]}'," .
245
      "{$user_points},{$user_counts}," . SN_TIME_NOW . ")";
246
247
    sys_stat_calculate_flush($data);
248
  }
249
  sys_stat_calculate_flush($data, true);
250
251
252
  // Updating Allie's stats
253
  sta_set_time_limit('posting new Alliance stats to DB');
254
  classSupernova::$db->doInsert(
255
    "INSERT INTO `{{statpoints}}`
256
      (`tech_points`, `tech_count`, `build_points`, `build_count`, `defs_points`, `defs_count`,
257
        `fleet_points`, `fleet_count`, `res_points`, `res_count`, `total_points`, `total_count`,
258
        `stat_date`, `id_owner`, `id_ally`, `stat_type`, `stat_code`,
259
        `tech_old_rank`, `build_old_rank`, `defs_old_rank`, `fleet_old_rank`, `res_old_rank`, `total_old_rank`
260
      )
261
      SELECT
262
        SUM(u.`tech_points`)+aus.`tech_points`, SUM(u.`tech_count`)+aus.`tech_count`, SUM(u.`build_points`)+aus.`build_points`, SUM(u.`build_count`)+aus.`build_count`,
263
        SUM(u.`defs_points`)+aus.`defs_points`, SUM(u.`defs_count`)+aus.`defs_count`, SUM(u.`fleet_points`)+aus.`fleet_points`, SUM(u.`fleet_count`)+aus.`fleet_count`,
264
        SUM(u.`res_points`)+aus.`res_points`, SUM(u.`res_count`)+aus.`res_count`, SUM(u.`total_points`)+aus.`total_points`, SUM(u.`total_count`)+aus.`total_count`,
265
        " . SN_TIME_NOW . ", NULL, u.`id_ally`, 2, 1,
266
        a.tech_rank, a.build_rank, a.defs_rank, a.fleet_rank, a.res_rank, a.total_rank
267
      FROM `{{statpoints}}` AS u
268
        JOIN `{{alliance}}` AS al ON al.id = u.id_ally
269
        LEFT JOIN `{{statpoints}}` AS aus ON aus.id_owner = al.ally_user_id AND aus.stat_type = 1 AND aus.stat_code = 1
270
        LEFT JOIN `{{statpoints}}` AS a ON a.id_ally = u.id_ally AND a.stat_code = 2 AND a.stat_type = 2
271
      WHERE u.`stat_type` = 1 AND u.stat_code = 1 AND u.id_ally<>0
272
      GROUP BY u.`id_ally`"
273
  );
274
275
  // Удаляем больше не нужные записи о достижении игрока-альянса
276
  db_stat_list_delete_ally_player();
277
278
  // Some variables we need to update ranks
279
  $qryResetRowNum = 'SET @rownum=0;';
280
  $qryFormat = "UPDATE `{{statpoints}}` SET `%1\$s_rank` = (SELECT @rownum:=@rownum+1) WHERE `stat_type` = '%2\$d' AND `stat_code` = 1 ORDER BY `%1\$s_points` DESC, `id_owner` ASC, `id_ally` ASC;";
281
282
  $rankNames = array('tech', 'build', 'defs', 'fleet', 'res', 'total');
283
284
  // Updating player's ranks
285
  sta_set_time_limit("updating ranks for players");
286 View Code Duplication
  foreach($rankNames as $rankName) {
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...
287
    sta_set_time_limit("updating player rank '{$rankName}'", false);
288
    classSupernova::$db->doExecute($qryResetRowNum);
289
    classSupernova::$db->doUpdate(sprintf($qryFormat, $rankName, 1));
290
  }
291
292
  sta_set_time_limit("updating ranks for Alliances");
293
  // Updating Allie's ranks
294 View Code Duplication
  foreach($rankNames as $rankName) {
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...
295
    sta_set_time_limit("updating Alliances rank '{$rankName}'", false);
296
    classSupernova::$db->doExecute($qryResetRowNum);
297
    classSupernova::$db->doUpdate(sprintf($qryFormat, $rankName, 2));
298
  }
299
300
  sta_set_time_limit('setting previous user stats from archive');
301
  classSupernova::$db->doUpdate(
302
    "UPDATE `{{statpoints}}` AS new
303
      LEFT JOIN `{{statpoints}}` AS old ON old.id_owner = new.id_owner AND old.stat_code = 2 AND old.stat_type = new.stat_type
304
    SET
305
      new.tech_old_rank = old.tech_rank,
306
      new.build_old_rank = old.build_rank,
307
      new.defs_old_rank  = old.defs_rank ,
308
      new.fleet_old_rank = old.fleet_rank,
309
      new.res_old_rank = old.res_rank,
310
      new.total_old_rank = old.total_rank
311
    WHERE
312
      new.stat_type = 1 AND new.stat_code = 1;");
313
314
  sta_set_time_limit('setting previous allies stats from archive');
315
  classSupernova::$db->doUpdate(
316
    "UPDATE `{{statpoints}}` AS new
317
      LEFT JOIN `{{statpoints}}` AS old ON old.id_ally = new.id_ally AND old.stat_code = 2 AND old.stat_type = new.stat_type
318
    SET
319
      new.tech_old_rank = old.tech_rank,
320
      new.build_old_rank = old.build_rank,
321
      new.defs_old_rank  = old.defs_rank ,
322
      new.fleet_old_rank = old.fleet_rank,
323
      new.res_old_rank = old.res_rank,
324
      new.total_old_rank = old.total_rank
325
    WHERE
326
      new.stat_type = 2 AND new.stat_code = 1;");
327
328
  sta_set_time_limit('updating players current rank and points');
329
  db_stat_list_update_user_stats();
330
331
  sta_set_time_limit('updating Allys current rank and points');
332
  db_stat_list_update_ally_stats();
333
334
  // Counting real user count and updating values
335
  classSupernova::$config->db_saveItem('users_amount', DBStaticUser::db_user_count());
336
337
  sn_db_transaction_commit();
338
}
339