Passed
Push — master ( bc874f...230097 )
by SuperNova.WS
04:01
created
classes/classPersistent.php 3 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -41,6 +41,9 @@  discard block
 block discarded – undo
41 41
     return self::$cacheObject;
42 42
   }
43 43
 
44
+  /**
45
+   * @param string $index
46
+   */
44 47
   public function db_loadItem($index) {
45 48
     $result = null;
46 49
     if($index) {
@@ -80,6 +83,9 @@  discard block
 block discarded – undo
80 83
     $this->db_saveItem(array_combine(array_keys($this->defaults), array_fill(0, count($this->defaults), null)));
81 84
   }
82 85
 
86
+  /**
87
+   * @param integer $value
88
+   */
83 89
   public function db_saveItem($item_list, $value = NULL) {
84 90
     if(empty($item_list)) {
85 91
       return;
Please login to merge, or discard this patch.
Spacing   +9 added lines, -9 removed lines patch added patch discarded remove patch
@@ -28,7 +28,7 @@  discard block
 block discarded – undo
28 28
     $this->sql_index_field = "{$table_name}_name";
29 29
     $this->sql_value_field = "{$table_name}_value";
30 30
 
31
-    if(!$this->_DB_LOADED) {
31
+    if (!$this->_DB_LOADED) {
32 32
       $this->db_loadAll();
33 33
     }
34 34
   }
@@ -43,7 +43,7 @@  discard block
 block discarded – undo
43 43
 
44 44
   public function db_loadItem($index) {
45 45
     $result = null;
46
-    if($index) {
46
+    if ($index) {
47 47
       $index_safe = db_escape($index);
48 48
       $result = doquery("SELECT `{$this->sql_value_field}` FROM `{{{$this->table_name}}}` WHERE `{$this->sql_index_field}` = '{$index_safe}' FOR UPDATE", true);
49 49
       // В две строки - что бы быть уверенным в порядке выполнения
@@ -57,7 +57,7 @@  discard block
 block discarded – undo
57 57
     $this->loadDefaults();
58 58
 
59 59
     $query = doquery("SELECT * FROM {{{$this->table_name}}} FOR UPDATE;");
60
-    while($row = db_fetch($query)) {
60
+    while ($row = db_fetch($query)) {
61 61
       $this->$row[$this->sql_index_field] = $row[$this->sql_value_field];
62 62
     }
63 63
 
@@ -65,7 +65,7 @@  discard block
 block discarded – undo
65 65
   }
66 66
 
67 67
   public function loadDefaults() {
68
-    foreach($this->defaults as $defName => $defValue) {
68
+    foreach ($this->defaults as $defName => $defValue) {
69 69
       $this->$defName = $defValue;
70 70
     }
71 71
   }
@@ -81,7 +81,7 @@  discard block
 block discarded – undo
81 81
   }
82 82
 
83 83
   public function db_saveItem($item_list, $value = NULL) {
84
-    if(empty($item_list)) {
84
+    if (empty($item_list)) {
85 85
       return;
86 86
     }
87 87
 
@@ -89,8 +89,8 @@  discard block
 block discarded – undo
89 89
 
90 90
     // Сначала записываем данные в базу - что бы поймать все блокировки
91 91
     $qry = array();
92
-    foreach($item_list as $item_name => $item_value) {
93
-      if($item_name) {
92
+    foreach ($item_list as $item_name => $item_value) {
93
+      if ($item_name) {
94 94
         $item_value = db_escape($item_value === NULL ? $this->$item_name : $item_value);
95 95
         $item_name = db_escape($item_name);
96 96
         $qry[] = "('{$item_name}', '{$item_value}')";
@@ -99,8 +99,8 @@  discard block
 block discarded – undo
99 99
     doquery("REPLACE INTO `{{" . $this->table_name . "}}` (`{$this->sql_index_field}`, `{$this->sql_value_field}`) VALUES " . implode(',', $qry) . ";");
100 100
 
101 101
     // И только после взятия блокировок - меняем значения в кэше
102
-    foreach($item_list as $item_name => $item_value) {
103
-      if($item_name && $item_value !== NULL) {
102
+    foreach ($item_list as $item_name => $item_value) {
103
+      if ($item_name && $item_value !== NULL) {
104 104
         $this->$item_name = $item_value;
105 105
       }
106 106
     }
Please login to merge, or discard this patch.
Upper-Lower-Casing   +3 added lines, -3 removed lines patch added patch discarded remove patch
@@ -80,7 +80,7 @@  discard block
 block discarded – undo
80 80
     $this->db_saveItem(array_combine(array_keys($this->defaults), array_fill(0, count($this->defaults), null)));
81 81
   }
82 82
 
83
-  public function db_saveItem($item_list, $value = NULL) {
83
+  public function db_saveItem($item_list, $value = null) {
84 84
     if(empty($item_list)) {
85 85
       return;
86 86
     }
@@ -91,7 +91,7 @@  discard block
 block discarded – undo
91 91
     $qry = array();
92 92
     foreach($item_list as $item_name => $item_value) {
93 93
       if($item_name) {
94
-        $item_value = db_escape($item_value === NULL ? $this->$item_name : $item_value);
94
+        $item_value = db_escape($item_value === null ? $this->$item_name : $item_value);
95 95
         $item_name = db_escape($item_name);
96 96
         $qry[] = "('{$item_name}', '{$item_value}')";
97 97
       }
@@ -100,7 +100,7 @@  discard block
 block discarded – undo
100 100
 
101 101
     // И только после взятия блокировок - меняем значения в кэше
102 102
     foreach($item_list as $item_name => $item_value) {
103
-      if($item_name && $item_value !== NULL) {
103
+      if($item_name && $item_value !== null) {
104 104
         $this->$item_name = $item_value;
105 105
       }
106 106
     }
Please login to merge, or discard this patch.
classes/classSupernova.php 3 patches
Doc Comments   +5 added lines, -2 removed lines patch added patch discarded remove patch
@@ -323,7 +323,7 @@  discard block
 block discarded – undo
323 323
    *   <p>null - транзакция НЕ должна быть запущена</p>
324 324
    *   <p>true - транзакция должна быть запущена - для совместимости с $for_update</p>
325 325
    *   <p>false - всё равно - для совместимости с $for_update</p>
326
-   * @return bool Текущий статус транзакции
326
+   * @return null|boolean Текущий статус транзакции
327 327
    */
328 328
   public static function db_transaction_check($status = null) {
329 329
     $error_msg = false;
@@ -399,7 +399,7 @@  discard block
 block discarded – undo
399 399
   /**
400 400
    * Блокирует указанные таблицу/список таблиц
401 401
    *
402
-   * @param string|array $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
402
+   * @param string $tables Таблица/список таблиц для блокировки. Названия таблиц - без префиксов
403 403
    * <p>string - название таблицы для блокировки</p>
404 404
    * <p>array - массив, где ключ - имя таблицы, а значение - условия блокировки элементов</p>
405 405
    */
@@ -574,6 +574,9 @@  discard block
 block discarded – undo
574 574
     return $result;
575 575
   }
576 576
 
577
+  /**
578
+   * @param integer $location_type
579
+   */
577 580
   public static function db_ins_field_set($location_type, $field_set, $serialize = false) {
578 581
     // TODO multiinsert
579 582
     !sn_db_field_set_is_safe($field_set) ? $field_set = sn_db_field_set_make_safe($field_set, $serialize) : false;
Please login to merge, or discard this patch.
Spacing   +103 added lines, -105 removed lines patch added patch discarded remove patch
@@ -190,7 +190,7 @@  discard block
 block discarded – undo
190 190
 
191 191
 
192 192
   public static function log_file($message, $spaces = 0) {
193
-    if(self::$debug) {
193
+    if (self::$debug) {
194 194
       self::$debug->log_file($message, $spaces);
195 195
     }
196 196
   }
@@ -198,14 +198,14 @@  discard block
 block discarded – undo
198 198
   // Перепаковывает массив на заданную глубину, убирая поля с null
199 199
   public static function array_repack(&$array, $level = 0) {
200 200
     // TODO $lock_table не нужна тут
201
-    if(!is_array($array)) return;
201
+    if (!is_array($array)) return;
202 202
 
203
-    foreach($array as $key => &$value) {
204
-      if($value === null) {
203
+    foreach ($array as $key => &$value) {
204
+      if ($value === null) {
205 205
         unset($array[$key]);
206
-      } elseif($level > 0 && is_array($value)) {
206
+      } elseif ($level > 0 && is_array($value)) {
207 207
         static::array_repack($value, $level - 1);
208
-        if(empty($value)) unset($array[$key]);
208
+        if (empty($value)) unset($array[$key]);
209 209
       }
210 210
     }
211 211
   }
@@ -214,7 +214,7 @@  discard block
 block discarded – undo
214 214
   // TODO Вынести в отдельный объект
215 215
   public static function cache_repack($location_type, $record_id = 0) {
216 216
     // Если есть $user_id - проверяем, а надо ли перепаковывать?
217
-    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
217
+    if ($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
218 218
 
219 219
     static::array_repack(static::$data[$location_type]);
220 220
     static::array_repack(static::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ???
@@ -222,9 +222,9 @@  discard block
 block discarded – undo
222 222
   }
223 223
   public static function cache_clear($location_type, $hard = true) {
224 224
     //print("<br />CACHE CLEAR {$cache_id} " . ($hard ? 'HARD' : 'SOFT') . "<br />");
225
-    if($hard && !empty(static::$data[$location_type])) {
225
+    if ($hard && !empty(static::$data[$location_type])) {
226 226
       // Здесь нельзя делать unset - надо записывать NULL, что бы это отразилось на зависимых записях
227
-      array_walk(static::$data[$location_type], function(&$item){$item = null;});
227
+      array_walk(static::$data[$location_type], function(&$item) {$item = null; });
228 228
     }
229 229
     static::$locator[$location_type] = array();
230 230
     static::$queries[$location_type] = array();
@@ -232,7 +232,7 @@  discard block
 block discarded – undo
232 232
   }
233 233
   public static function cache_clear_all($hard = true) {
234 234
     //print('<br />CACHE CLEAR ALL<br />');
235
-    if($hard) {
235
+    if ($hard) {
236 236
       static::$data = array();
237 237
       static::cache_lock_unset_all();
238 238
     }
@@ -259,10 +259,10 @@  discard block
 block discarded – undo
259 259
   */
260 260
   public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) {
261 261
     // нет идентификатора - выход
262
-    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
262
+    if (!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
263 263
 
264 264
     $in_transaction = static::db_transaction_check(false);
265
-    if(
265
+    if (
266 266
       $force_overwrite
267 267
       ||
268 268
       // Не заменяются заблокированные записи во время транзакции
@@ -272,14 +272,14 @@  discard block
 block discarded – undo
272 272
       !static::cache_isset($location_type, $record_id)
273 273
     ) {
274 274
       static::$data[$location_type][$record_id] = $record;
275
-      if($in_transaction && !$skip_lock) {
275
+      if ($in_transaction && !$skip_lock) {
276 276
         static::cache_lock_set($location_type, $record_id);
277 277
       }
278 278
     }
279 279
   }
280 280
   public static function cache_unset($cache_id, $safe_record_id) {
281 281
     // $record_id должен быть проверен заранее !
282
-    if(isset(static::$data[$cache_id][$safe_record_id]) && static::$data[$cache_id][$safe_record_id] !== null) {
282
+    if (isset(static::$data[$cache_id][$safe_record_id]) && static::$data[$cache_id][$safe_record_id] !== null) {
283 283
       // Выставляем запись в null
284 284
       static::$data[$cache_id][$safe_record_id] = null;
285 285
       // Очищаем кэш мягко - что бы удалить очистить связанные данные - кэш локаций и кэш запоросов и всё, что потребуется впредь
@@ -293,7 +293,7 @@  discard block
 block discarded – undo
293 293
     return static::$locks[$location_type][$record_id] = true; // Не всегда - от результата
294 294
   }
295 295
   public static function cache_lock_unset($location_type, $record_id) {
296
-    if(isset(static::$locks[$location_type][$record_id]))
296
+    if (isset(static::$locks[$location_type][$record_id]))
297 297
       unset(static::$locks[$location_type][$record_id]);
298 298
     return true; // Не всегда - от результата
299 299
   }
@@ -323,13 +323,13 @@  discard block
 block discarded – undo
323 323
    */
324 324
   public static function db_transaction_check($status = null) {
325 325
     $error_msg = false;
326
-    if($status && !static::$db_in_transaction) {
326
+    if ($status && !static::$db_in_transaction) {
327 327
       $error_msg = 'No transaction started for current operation';
328
-    } elseif($status === null && static::$db_in_transaction) {
328
+    } elseif ($status === null && static::$db_in_transaction) {
329 329
       $error_msg = 'Transaction is already started';
330 330
     }
331 331
 
332
-    if($error_msg) {
332
+    if ($error_msg) {
333 333
       // TODO - Убрать позже
334 334
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_transaction_check() - ' . $error_msg . '</h1>');
335 335
       $backtrace = debug_backtrace();
@@ -350,7 +350,7 @@  discard block
 block discarded – undo
350 350
     static::$transaction_id++;
351 351
     doquery('START TRANSACTION');
352 352
 
353
-    if($config->db_manual_lock_enabled) {
353
+    if ($config->db_manual_lock_enabled) {
354 354
       $config->db_loadItem('var_db_manually_locked');
355 355
       $config->db_saveItem('var_db_manually_locked', SN_TIME_SQL);
356 356
     }
@@ -365,7 +365,7 @@  discard block
 block discarded – undo
365 365
   public static function db_transaction_commit() {
366 366
     static::db_transaction_check(true);
367 367
 
368
-    if(!empty(static::$delayed_changset)) {
368
+    if (!empty(static::$delayed_changset)) {
369 369
       static::db_changeset_apply(static::$delayed_changset, true);
370 370
     }
371 371
     static::$delayed_changset = array();
@@ -379,7 +379,7 @@  discard block
 block discarded – undo
379 379
   }
380 380
   public static function db_transaction_rollback() {
381 381
     // static::db_transaction_check(true); // TODO - вообще-то тут тоже надо проверять есть ли транзакция
382
-    if(!empty(static::$delayed_changset)) {
382
+    if (!empty(static::$delayed_changset)) {
383 383
       static::db_changeset_revert();
384 384
     }
385 385
     static::$delayed_changset = array();
@@ -400,7 +400,7 @@  discard block
 block discarded – undo
400 400
    */
401 401
   public static function db_lock_tables($tables) {
402 402
     $tables = is_array($tables) ? $tables : array($tables => '');
403
-    foreach($tables as $table_name => $condition) {
403
+    foreach ($tables as $table_name => $condition) {
404 404
       self::$db->doquery("SELECT 1 FROM {{{$table_name}}}" . ($condition ? ' WHERE ' . $condition : ''));
405 405
     }
406 406
   }
@@ -440,14 +440,14 @@  discard block
 block discarded – undo
440 440
   public static function db_get_record_list($location_type, $filter = '', $fetch = false, $no_return = false) {
441 441
     $query_cache = &static::$queries[$location_type][$filter];
442 442
 
443
-    if(!isset($query_cache) || $query_cache === null) {
443
+    if (!isset($query_cache) || $query_cache === null) {
444 444
       $location_info = &static::$location_info[$location_type];
445 445
       $id_field = $location_info[P_ID];
446 446
       $query_cache = array();
447 447
 
448
-      if(static::db_transaction_check(false)) {
448
+      if (static::db_transaction_check(false)) {
449 449
         // Проходим по всем родителям данной записи
450
-        foreach($location_info[P_OWNER_INFO] as $owner_data) {
450
+        foreach ($location_info[P_OWNER_INFO] as $owner_data) {
451 451
           $owner_location_type = $owner_data[P_LOCATION];
452 452
           $parent_id_list = array();
453 453
           // Выбираем родителей данного типа и соответствующие ИД текущего типа
@@ -458,14 +458,14 @@  discard block
 block discarded – undo
458 458
             ($filter ? ' WHERE ' . $filter : '') .
459 459
             ($fetch ? ' LIMIT 1' : ''), false, true);
460 460
 
461
-          while($row = db_fetch($query)) {
461
+          while ($row = db_fetch($query)) {
462 462
             // Исключаем из списка родительских ИД уже заблокированные записи
463
-            if(!static::cache_lock_get($owner_location_type, $row['parent_id']))
463
+            if (!static::cache_lock_get($owner_location_type, $row['parent_id']))
464 464
               $parent_id_list[$row['parent_id']] = $row['parent_id'];
465 465
           }
466 466
 
467 467
           // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
468
-          if($indexes_str = implode(',', $parent_id_list)) {
468
+          if ($indexes_str = implode(',', $parent_id_list)) {
469 469
             $parent_id_field = static::$location_info[$owner_location_type][P_ID];
470 470
             static::db_get_record_list($owner_location_type,
471 471
               $parent_id_field . (count($parent_id_list) > 1 ? " IN ({$indexes_str})" : " = {$indexes_str}"), $fetch, true);
@@ -477,21 +477,21 @@  discard block
 block discarded – undo
477 477
         "SELECT * FROM {{{$location_info[P_TABLE_NAME]}}}" .
478 478
         (($filter = trim($filter)) ? " WHERE {$filter}" : '')
479 479
       );
480
-      while($row = db_fetch($query)) {
480
+      while ($row = db_fetch($query)) {
481 481
         // static::db_get_record_by_id($location_type, $row[$id_field]);
482 482
         static::cache_set($location_type, $row[$id_field], $row);
483 483
         $query_cache[$row[$id_field]] = &static::$data[$location_type][$row[$id_field]];
484 484
       }
485 485
     }
486 486
 
487
-    if($no_return) {
487
+    if ($no_return) {
488 488
       return true;
489 489
     } else {
490 490
       $result = false;
491
-      if(is_array($query_cache)) {
492
-        foreach($query_cache as $key => $value) {
491
+      if (is_array($query_cache)) {
492
+        foreach ($query_cache as $key => $value) {
493 493
           $result[$key] = $value;
494
-          if($fetch) break;
494
+          if ($fetch) break;
495 495
         }
496 496
       }
497 497
       return $fetch ? (is_array($result) ? reset($result) : false) : $result;
@@ -499,14 +499,14 @@  discard block
 block discarded – undo
499 499
   }
500 500
 
501 501
   public static function db_upd_record_by_id($location_type, $record_id, $set) {
502
-    if(!($record_id = idval($record_id)) || !($set = trim($set))) return false;
502
+    if (!($record_id = idval($record_id)) || !($set = trim($set))) return false;
503 503
 
504 504
     $location_info = &static::$location_info[$location_type];
505 505
     $id_field = $location_info[P_ID];
506 506
     $table_name = $location_info[P_TABLE_NAME];
507
-    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
507
+    if ($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
508 508
     {
509
-      if(static::$db->db_affected_rows()) {
509
+      if (static::$db->db_affected_rows()) {
510 510
         // Обновляем данные только если ряд был затронут
511 511
         // TODO - переделать под работу со структурированными $set
512 512
 
@@ -521,16 +521,16 @@  discard block
 block discarded – undo
521 521
     return $result;
522 522
   }
523 523
   public static function db_upd_record_list($location_type, $condition, $set) {
524
-    if(!($set = trim($set))) return false;
524
+    if (!($set = trim($set))) return false;
525 525
 
526 526
     $condition = trim($condition);
527 527
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
528 528
 
529 529
 //static::db_get_record_list($location_type, $condition, false, true);
530 530
 
531
-    if($result = static::db_query("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
531
+    if ($result = static::db_query("UPDATE {{{$table_name}}} SET " . $set . ($condition ? ' WHERE ' . $condition : ''))) {
532 532
 
533
-      if(static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
533
+      if (static::$db->db_affected_rows()) { // Обновляем данные только если ряд был затронут
534 534
         // Поскольку нам неизвестно, что и как обновилось - сбрасываем кэш этого типа полностью
535 535
         // TODO - когда будет структурированный $condition и $set - перепаковывать данные
536 536
         static::cache_clear($location_type, true);
@@ -543,8 +543,8 @@  discard block
 block discarded – undo
543 543
   public static function db_ins_record($location_type, $set) {
544 544
     $set = trim($set);
545 545
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
546
-    if($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
547
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
546
+    if ($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
547
+      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
548 548
       {
549 549
         $record_id = db_insert_id();
550 550
         // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
@@ -566,8 +566,8 @@  discard block
 block discarded – undo
566 566
     $fields = implode(',', array_keys($field_set));
567 567
 
568 568
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
569
-    if($result = static::db_query("INSERT INTO `{{{$table_name}}}` ($fields) VALUES ($values);")) {
570
-      if(static::$db->db_affected_rows()) {
569
+    if ($result = static::db_query("INSERT INTO `{{{$table_name}}}` ($fields) VALUES ($values);")) {
570
+      if (static::$db->db_affected_rows()) {
571 571
         // Обновляем данные только если ряд был затронут
572 572
         $record_id = db_insert_id();
573 573
         // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
@@ -583,14 +583,14 @@  discard block
 block discarded – undo
583 583
 
584 584
   public static function db_del_record_by_id($location_type, $safe_record_id)
585 585
   {
586
-    if(!($safe_record_id = idval($safe_record_id))) return false;
586
+    if (!($safe_record_id = idval($safe_record_id))) return false;
587 587
 
588 588
     $location_info = &static::$location_info[$location_type];
589 589
     $id_field = $location_info[P_ID];
590 590
     $table_name = $location_info[P_TABLE_NAME];
591
-    if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
591
+    if ($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
592 592
     {
593
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
593
+      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
594 594
       {
595 595
         static::cache_unset($location_type, $safe_record_id);
596 596
       }
@@ -600,14 +600,14 @@  discard block
 block discarded – undo
600 600
   }
601 601
   public static function db_del_record_list($location_type, $condition)
602 602
   {
603
-    if(!($condition = trim($condition))) return false;
603
+    if (!($condition = trim($condition))) return false;
604 604
 
605 605
     $location_info = &static::$location_info[$location_type];
606 606
     $table_name = $location_info[P_TABLE_NAME];
607 607
 
608
-    if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
608
+    if ($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
609 609
     {
610
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
610
+      if (static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
611 611
       {
612 612
         // Обнуление кэша, потому что непонятно, что поменялось
613 613
         // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
@@ -654,21 +654,21 @@  discard block
 block discarded – undo
654 654
   public static function db_get_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false)
655 655
   {
656 656
     // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
657
-    if(!($username_unsafe = trim($username_unsafe))) return false;
657
+    if (!($username_unsafe = trim($username_unsafe))) return false;
658 658
 
659 659
     $user = null;
660
-    if(is_array(static::$data[LOC_USER]))
661
-    foreach(static::$data[LOC_USER] as $user_id => $user_data)
660
+    if (is_array(static::$data[LOC_USER]))
661
+    foreach (static::$data[LOC_USER] as $user_id => $user_data)
662 662
     {
663
-      if(is_array($user_data) && isset($user_data['username']))
663
+      if (is_array($user_data) && isset($user_data['username']))
664 664
       {
665 665
         // проверяем поле
666 666
         // TODO Возможно есть смысл всегда искать по strtolower - но может игрок захочет переименоваться с другим регистром? Проверить!
667
-        if((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe)))
667
+        if ((!$like && $user_data['username'] == $username_unsafe) || ($like && strtolower($user_data['username']) == strtolower($username_unsafe)))
668 668
         {
669 669
           // $user_as_ally = intval($user_data['user_as_ally']);
670 670
           $user_as_ally = idval($user_data['user_as_ally']);
671
-          if($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
671
+          if ($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
672 672
           {
673 673
             $user = $user_data;
674 674
             break;
@@ -677,7 +677,7 @@  discard block
 block discarded – undo
677 677
       }
678 678
     }
679 679
 
680
-    if($user === null)
680
+    if ($user === null)
681 681
     {
682 682
       // Вытаскиваем запись
683 683
       $username_safe = db_escape($like ? strtolower($username_unsafe) : $username_unsafe); // тут на самом деле strtolower() лишняя, но пусть будет
@@ -686,7 +686,7 @@  discard block
 block discarded – undo
686 686
       // self::db_get_record_list(LOC_USER, "`username` " . ($like ? 'LIKE' : '='). " '{$username_safe}'");
687 687
 
688 688
       $user = static::db_query(
689
-        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '='). " '{$username_safe}'"
689
+        "SELECT * FROM {{users}} WHERE `username` " . ($like ? 'LIKE' : '=') . " '{$username_safe}'"
690 690
       , true);
691 691
       static::cache_set(LOC_USER, $user['id'], $user); // В кэш-юзер так же заполнять индексы
692 692
     }
@@ -695,15 +695,15 @@  discard block
 block discarded – undo
695 695
   }
696 696
   // UNUSED
697 697
   public static function db_get_user_by_email($email_unsafe, $use_both = false, $for_update = false, $fields = '*') {
698
-    if(!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
698
+    if (!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
699 699
 
700 700
     $user = null;
701 701
     // TODO переделать на индексы
702
-    if(is_array(static::$data[LOC_USER])) {
703
-      foreach(static::$data[LOC_USER] as $user_id => $user_data) {
704
-        if(is_array($user_data) && isset($user_data['email_2'])) {
702
+    if (is_array(static::$data[LOC_USER])) {
703
+      foreach (static::$data[LOC_USER] as $user_id => $user_data) {
704
+        if (is_array($user_data) && isset($user_data['email_2'])) {
705 705
           // проверяем поле
706
-          if(strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
706
+          if (strtolower($user_data['email_2']) == $email_unsafe || ($use_both && strtolower($user_data['email']) == $email_unsafe)) {
707 707
             $user = $user_data;
708 708
             break;
709 709
           }
@@ -711,7 +711,7 @@  discard block
 block discarded – undo
711 711
       }
712 712
     }
713 713
 
714
-    if($user === null) {
714
+    if ($user === null) {
715 715
       // Вытаскиваем запись
716 716
       $email_safe = db_escape($email_unsafe);
717 717
       $user = static::db_query(
@@ -728,7 +728,7 @@  discard block
 block discarded – undo
728 728
     $user = null;
729 729
     // TODO переделать на индексы
730 730
 
731
-    if($user === null && !empty($where_safe)) {
731
+    if ($user === null && !empty($where_safe)) {
732 732
       // Вытаскиваем запись
733 733
       $user = static::db_query("SELECT * FROM {{users}} WHERE {$where_safe}", true);
734 734
 
@@ -763,7 +763,7 @@  discard block
 block discarded – undo
763 763
   {
764 764
     // TODO запихивать в $data[LOC_LOCATION][$location_type][$location_id]
765 765
     $unit = static::db_get_record_by_id(LOC_UNIT, $unit_id, $for_update, $fields);
766
-    if(is_array($unit))
766
+    if (is_array($unit))
767 767
     {
768 768
       static::$locator[LOC_UNIT][$unit['unit_location_type']][$unit['unit_location_id']][$unit['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
769 769
     }
@@ -773,15 +773,15 @@  discard block
 block discarded – undo
773 773
 
774 774
   public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id)
775 775
   {
776
-    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
776
+    if (!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
777 777
 
778 778
     $query_cache = &static::$locator[LOC_UNIT][$location_type][$location_id];
779
-    if(!isset($query_cache))
779
+    if (!isset($query_cache))
780 780
     {
781 781
       $got_data = static::db_get_record_list(LOC_UNIT, "unit_location_type = {$location_type} AND unit_location_id = {$location_id} AND " . static::db_unit_time_restrictions());
782
-      if(is_array($got_data))
782
+      if (is_array($got_data))
783 783
       {
784
-        foreach($got_data as $unit_id => $unit_data)
784
+        foreach ($got_data as $unit_id => $unit_data)
785 785
         {
786 786
           // static::$data[LOC_LOCATION][$location_type][$location_id][$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
787 787
           $query_cache[$unit_data['unit_snid']] = &static::$data[LOC_UNIT][$unit_id];
@@ -790,8 +790,8 @@  discard block
 block discarded – undo
790 790
     }
791 791
 
792 792
     $result = false;
793
-    if(is_array($query_cache)) {
794
-      foreach($query_cache as $key => $value) {
793
+    if (is_array($query_cache)) {
794
+      foreach ($query_cache as $key => $value) {
795 795
         $result[$key] = $value;
796 796
       }
797 797
     }
@@ -829,7 +829,7 @@  discard block
 block discarded – undo
829 829
    */
830 830
   public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, $for_update = false)
831 831
   {
832
-    if(!$user_id)
832
+    if (!$user_id)
833 833
     {
834 834
       pdump(debug_backtrace());
835 835
       die('No user_id for que_get_que()');
@@ -839,14 +839,14 @@  discard block
 block discarded – undo
839 839
 
840 840
     $query = array();
841 841
 
842
-    if($user_id = idval($user_id))
842
+    if ($user_id = idval($user_id))
843 843
       $query[] = "`que_player_id` = {$user_id}";
844 844
 
845
-    if($que_type == QUE_RESEARCH || $planet_id === null)
845
+    if ($que_type == QUE_RESEARCH || $planet_id === null)
846 846
       $query[] = "`que_planet_id` IS NULL";
847
-    elseif($planet_id)
847
+    elseif ($planet_id)
848 848
       $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
849
-    if($que_type)
849
+    if ($que_type)
850 850
       $query[] = "`que_type` = {$que_type}";
851 851
 
852 852
     $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
@@ -909,14 +909,14 @@  discard block
 block discarded – undo
909 909
 
910 910
   public static function db_changeset_prepare_unit($unit_id, $unit_value, $user, $planet_id = null)
911 911
   {
912
-    if(!is_array($user))
912
+    if (!is_array($user))
913 913
     {
914 914
       // TODO - remove later
915 915
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER is not ARRAY</h1>');
916 916
       pdump(debug_backtrace());
917 917
       die('USER is not ARRAY');
918 918
     }
919
-    if(!isset($user['id']) || !$user['id'])
919
+    if (!isset($user['id']) || !$user['id'])
920 920
     {
921 921
       // TODO - remove later
922 922
       print('<h1>СООБЩИТЕ ЭТО АДМИНУ: sn_db_unit_changeset_prepare() - USER[id] пустой</h1>');
@@ -932,7 +932,7 @@  discard block
 block discarded – undo
932 932
 
933 933
     $db_changeset = array();
934 934
     $temp = DBStaticUnit::db_unit_by_location($user['id'], $unit_location, $location_id, $unit_id, true, 'unit_id');
935
-    if($temp['unit_id'])
935
+    if ($temp['unit_id'])
936 936
     {
937 937
       $db_changeset = array(
938 938
         'action' => SQL_OP_UPDATE,
@@ -996,9 +996,9 @@  discard block
 block discarded – undo
996 996
   }
997 997
 
998 998
   public function db_changeset_condition_compile(&$conditions, &$table_name = '') {
999
-    if(!$conditions[P_LOCATION] || $conditions[P_LOCATION] == LOC_NONE) {
999
+    if (!$conditions[P_LOCATION] || $conditions[P_LOCATION] == LOC_NONE) {
1000 1000
       $conditions[P_LOCATION] = LOC_NONE;
1001
-      switch($table_name) {
1001
+      switch ($table_name) {
1002 1002
         case 'users':
1003 1003
         case LOC_USER:
1004 1004
           $conditions[P_TABLE_NAME] = $table_name = 'users';
@@ -1020,18 +1020,18 @@  discard block
 block discarded – undo
1020 1020
     }
1021 1021
 
1022 1022
     $conditions[P_FIELDS_STR] = '';
1023
-    if($conditions['fields']) {
1023
+    if ($conditions['fields']) {
1024 1024
       $fields = array();
1025
-      foreach($conditions['fields'] as $field_name => $field_data) {
1025
+      foreach ($conditions['fields'] as $field_name => $field_data) {
1026 1026
         $condition = "`{$field_name}` = ";
1027 1027
         $value = '';
1028
-        if($field_data['delta']) {
1028
+        if ($field_data['delta']) {
1029 1029
           $value = "`{$field_name}`" . ($field_data['delta'] >= 0 ? '+' : '') . $field_data['delta'];
1030
-        } elseif($field_data['set']) {
1031
-          $value = (is_string($field_data['set']) ? "'{$field_data['set']}'": $field_data['set']);
1030
+        } elseif ($field_data['set']) {
1031
+          $value = (is_string($field_data['set']) ? "'{$field_data['set']}'" : $field_data['set']);
1032 1032
         }
1033 1033
 
1034
-        if($value) {
1034
+        if ($value) {
1035 1035
           $fields[] = $condition . $value;
1036 1036
         }
1037 1037
       }
@@ -1039,16 +1039,14 @@  discard block
 block discarded – undo
1039 1039
     }
1040 1040
 
1041 1041
     $conditions[P_WHERE_STR] = '';
1042
-    if(!empty($conditions['where'])) {
1043
-      if($conditions[P_VERSION] == 1) {
1042
+    if (!empty($conditions['where'])) {
1043
+      if ($conditions[P_VERSION] == 1) {
1044 1044
         $the_conditions = array();
1045
-        foreach($conditions['where'] as $field_id => $field_value) {
1045
+        foreach ($conditions['where'] as $field_id => $field_value) {
1046 1046
           // Простое условие - $field_id = $field_value
1047
-          if(is_string($field_id)) {
1047
+          if (is_string($field_id)) {
1048 1048
             $field_value =
1049
-              $field_value === null ? 'NULL' :
1050
-                (is_string($field_value) ? "'" . db_escape($field_value) . "'" :
1051
-                  (is_bool($field_value) ? intval($field_value) : $field_value));
1049
+              $field_value === null ? 'NULL' : (is_string($field_value) ? "'" . db_escape($field_value) . "'" : (is_bool($field_value) ? intval($field_value) : $field_value));
1052 1050
             $the_conditions[] = "`{$field_id}` = {$field_value}";
1053 1051
           } else {
1054 1052
             die('Неподдерживаемый тип условия');
@@ -1060,7 +1058,7 @@  discard block
 block discarded – undo
1060 1058
       $conditions[P_WHERE_STR] = implode(' AND ', $the_conditions);
1061 1059
     }
1062 1060
 
1063
-    switch($conditions['action']) {
1061
+    switch ($conditions['action']) {
1064 1062
       case SQL_OP_DELETE: $conditions[P_ACTION_STR] = ("DELETE FROM {{{$table_name}}}"); break;
1065 1063
       case SQL_OP_UPDATE: $conditions[P_ACTION_STR] = ("UPDATE {{{$table_name}}} SET"); break;
1066 1064
       case SQL_OP_INSERT: $conditions[P_ACTION_STR] = ("INSERT INTO {{{$table_name}}} SET"); break;
@@ -1073,9 +1071,9 @@  discard block
 block discarded – undo
1073 1071
 
1074 1072
   public static function db_changeset_apply($db_changeset, $flush_delayed = false) {
1075 1073
     $result = true;
1076
-    if(!is_array($db_changeset) || empty($db_changeset)) return $result;
1074
+    if (!is_array($db_changeset) || empty($db_changeset)) return $result;
1077 1075
 
1078
-    foreach($db_changeset as $table_name => &$table_data) {
1076
+    foreach ($db_changeset as $table_name => &$table_data) {
1079 1077
       // TODO - delayed changeset
1080 1078
       /*
1081 1079
       if(static::db_transaction_check(false) && !$flush_delayed && ($table_name == 'users' || $table_name == 'planets' || $table_name == 'unit'))
@@ -1084,15 +1082,15 @@  discard block
 block discarded – undo
1084 1082
         continue;
1085 1083
       }
1086 1084
       */
1087
-      foreach($table_data as $record_id => &$conditions) {
1085
+      foreach ($table_data as $record_id => &$conditions) {
1088 1086
         static::db_changeset_condition_compile($conditions, $table_name);
1089 1087
 
1090
-        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) continue;
1091
-        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) continue; // Защита от случайного удаления всех данных в таблице
1088
+        if ($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) continue;
1089
+        if ($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) continue; // Защита от случайного удаления всех данных в таблице
1092 1090
 
1093
-        if($conditions[P_LOCATION] != LOC_NONE) {
1091
+        if ($conditions[P_LOCATION] != LOC_NONE) {
1094 1092
           //die('spec ops classSupernova.php line 928 Добавить работу с кэшем юнитов итд');
1095
-          switch($conditions['action'])
1093
+          switch ($conditions['action'])
1096 1094
           {
1097 1095
             case SQL_OP_DELETE: $result = self::db_del_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR]) && $result; break;
1098 1096
             case SQL_OP_UPDATE: $result = self::db_upd_record_list($conditions[P_LOCATION], $conditions[P_WHERE_STR], $conditions[P_FIELDS_STR]) && $result; break;
@@ -1173,7 +1171,7 @@  discard block
 block discarded – undo
1173 1171
   }
1174 1172
 
1175 1173
 
1176
-  public static function init_0_prepare () {
1174
+  public static function init_0_prepare() {
1177 1175
     static::$gc = new GlobalContainer();
1178 1176
   }
1179 1177
 
@@ -1239,7 +1237,7 @@  discard block
 block discarded – undo
1239 1237
   }
1240 1238
 
1241 1239
   public static function init_debug_state() {
1242
-    if($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
1240
+    if ($_SERVER['SERVER_NAME'] == 'localhost' && !defined('BE_DEBUG')) {
1243 1241
       define('BE_DEBUG', true);
1244 1242
     }
1245 1243
     // define('DEBUG_SQL_ONLINE', true); // Полный дамп запросов в рил-тайме. Подойдет любое значение
@@ -1251,7 +1249,7 @@  discard block
 block discarded – undo
1251 1249
     defined('DEBUG_SQL_ERROR') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1252 1250
     defined('DEBUG_SQL_COMMENT_LONG') && !defined('DEBUG_SQL_COMMENT') ? define('DEBUG_SQL_COMMENT', true) : false;
1253 1251
 
1254
-    if(defined('BE_DEBUG') || static::$config->debug) {
1252
+    if (defined('BE_DEBUG') || static::$config->debug) {
1255 1253
       @define('BE_DEBUG', true);
1256 1254
       @ini_set('display_errors', 1);
1257 1255
       @error_reporting(E_ALL ^ E_NOTICE ^ E_DEPRECATED);
Please login to merge, or discard this patch.
Braces   +91 added lines, -59 removed lines patch added patch discarded remove patch
@@ -198,14 +198,18 @@  discard block
 block discarded – undo
198 198
   // Перепаковывает массив на заданную глубину, убирая поля с null
199 199
   public static function array_repack(&$array, $level = 0) {
200 200
     // TODO $lock_table не нужна тут
201
-    if(!is_array($array)) return;
201
+    if(!is_array($array)) {
202
+      return;
203
+    }
202 204
 
203 205
     foreach($array as $key => &$value) {
204 206
       if($value === null) {
205 207
         unset($array[$key]);
206 208
       } elseif($level > 0 && is_array($value)) {
207 209
         static::array_repack($value, $level - 1);
208
-        if(empty($value)) unset($array[$key]);
210
+        if(empty($value)) {
211
+          unset($array[$key]);
212
+        }
209 213
       }
210 214
     }
211 215
   }
@@ -214,7 +218,9 @@  discard block
 block discarded – undo
214 218
   // TODO Вынести в отдельный объект
215 219
   public static function cache_repack($location_type, $record_id = 0) {
216 220
     // Если есть $user_id - проверяем, а надо ли перепаковывать?
217
-    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) return;
221
+    if($record_id && isset(static::$data[$location_type][$record_id]) && static::$data[$location_type][$record_id] !== null) {
222
+      return;
223
+    }
218 224
 
219 225
     static::array_repack(static::$data[$location_type]);
220 226
     static::array_repack(static::$locator[$location_type], 3); // TODO У каждого типа локации - своя глубина!!!! Но можно и глубже ???
@@ -259,7 +265,9 @@  discard block
 block discarded – undo
259 265
   */
260 266
   public static function cache_set($location_type, $record_id, $record, $force_overwrite = false, $skip_lock = false) {
261 267
     // нет идентификатора - выход
262
-    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) return;
268
+    if(!($record_id = $record[static::$location_info[$location_type][P_ID]])) {
269
+      return;
270
+    }
263 271
 
264 272
     $in_transaction = static::db_transaction_check(false);
265 273
     if(
@@ -293,8 +301,9 @@  discard block
 block discarded – undo
293 301
     return static::$locks[$location_type][$record_id] = true; // Не всегда - от результата
294 302
   }
295 303
   public static function cache_lock_unset($location_type, $record_id) {
296
-    if(isset(static::$locks[$location_type][$record_id]))
297
-      unset(static::$locks[$location_type][$record_id]);
304
+    if(isset(static::$locks[$location_type][$record_id])) {
305
+          unset(static::$locks[$location_type][$record_id]);
306
+    }
298 307
     return true; // Не всегда - от результата
299 308
   }
300 309
   public static function cache_lock_unset_all() {
@@ -460,8 +469,9 @@  discard block
 block discarded – undo
460 469
 
461 470
           while($row = db_fetch($query)) {
462 471
             // Исключаем из списка родительских ИД уже заблокированные записи
463
-            if(!static::cache_lock_get($owner_location_type, $row['parent_id']))
464
-              $parent_id_list[$row['parent_id']] = $row['parent_id'];
472
+            if(!static::cache_lock_get($owner_location_type, $row['parent_id'])) {
473
+                          $parent_id_list[$row['parent_id']] = $row['parent_id'];
474
+            }
465 475
           }
466 476
 
467 477
           // Если все-таки какие-то записи еще не заблокированы - вынимаем текущие версии из базы
@@ -491,7 +501,9 @@  discard block
 block discarded – undo
491 501
       if(is_array($query_cache)) {
492 502
         foreach($query_cache as $key => $value) {
493 503
           $result[$key] = $value;
494
-          if($fetch) break;
504
+          if($fetch) {
505
+            break;
506
+          }
495 507
         }
496 508
       }
497 509
       return $fetch ? (is_array($result) ? reset($result) : false) : $result;
@@ -499,12 +511,15 @@  discard block
 block discarded – undo
499 511
   }
500 512
 
501 513
   public static function db_upd_record_by_id($location_type, $record_id, $set) {
502
-    if(!($record_id = idval($record_id)) || !($set = trim($set))) return false;
514
+    if(!($record_id = idval($record_id)) || !($set = trim($set))) {
515
+      return false;
516
+    }
503 517
 
504 518
     $location_info = &static::$location_info[$location_type];
505 519
     $id_field = $location_info[P_ID];
506 520
     $table_name = $location_info[P_TABLE_NAME];
507
-    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) // TODO Как-то вернуть может быть LIMIT 1 ?
521
+    if($result = static::db_query($q = "UPDATE {{{$table_name}}} SET {$set} WHERE `{$id_field}` = {$record_id}")) {
522
+      // TODO Как-то вернуть может быть LIMIT 1 ?
508 523
     {
509 524
       if(static::$db->db_affected_rows()) {
510 525
         // Обновляем данные только если ряд был затронут
@@ -512,6 +527,7 @@  discard block
 block discarded – undo
512 527
 
513 528
         // Тут именно так, а не cache_unset - что бы в кэшах автоматически обновилась запись. Будет нужно на будущее
514 529
         static::$data[$location_type][$record_id] = null;
530
+    }
515 531
         // Вытаскиваем обновленную запись
516 532
         static::db_get_record_by_id($location_type, $record_id);
517 533
         static::cache_clear($location_type, false); // Мягкий сброс - только $queries
@@ -521,7 +537,9 @@  discard block
 block discarded – undo
521 537
     return $result;
522 538
   }
523 539
   public static function db_upd_record_list($location_type, $condition, $set) {
524
-    if(!($set = trim($set))) return false;
540
+    if(!($set = trim($set))) {
541
+      return false;
542
+    }
525 543
 
526 544
     $condition = trim($condition);
527 545
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
@@ -544,9 +562,11 @@  discard block
 block discarded – undo
544 562
     $set = trim($set);
545 563
     $table_name = static::$location_info[$location_type][P_TABLE_NAME];
546 564
     if($result = static::db_query("INSERT INTO `{{{$table_name}}}` SET {$set}")) {
547
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
565
+      if(static::$db->db_affected_rows()) {
566
+        // Обновляем данные только если ряд был затронут
548 567
       {
549 568
         $record_id = db_insert_id();
569
+      }
550 570
         // Вытаскиваем запись целиком, потому что в $set могли быть "данные по умолчанию"
551 571
         $result = static::db_get_record_by_id($location_type, $record_id);
552 572
         // Очищаем второстепенные кэши - потому что вставленная запись могла повлиять на результаты запросов или локация или еще чего
@@ -581,38 +601,44 @@  discard block
 block discarded – undo
581 601
     return $result;
582 602
   }
583 603
 
584
-  public static function db_del_record_by_id($location_type, $safe_record_id)
585
-  {
586
-    if(!($safe_record_id = idval($safe_record_id))) return false;
604
+  public static function db_del_record_by_id($location_type, $safe_record_id) {
605
+    if(!($safe_record_id = idval($safe_record_id))) {
606
+      return false;
607
+    }
587 608
 
588 609
     $location_info = &static::$location_info[$location_type];
589 610
     $id_field = $location_info[P_ID];
590 611
     $table_name = $location_info[P_TABLE_NAME];
591 612
     if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE `{$id_field}` = {$safe_record_id}"))
592 613
     {
593
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
614
+      if(static::$db->db_affected_rows()) {
615
+        // Обновляем данные только если ряд был затронут
594 616
       {
595 617
         static::cache_unset($location_type, $safe_record_id);
596 618
       }
619
+      }
597 620
     }
598 621
 
599 622
     return $result;
600 623
   }
601
-  public static function db_del_record_list($location_type, $condition)
602
-  {
603
-    if(!($condition = trim($condition))) return false;
624
+  public static function db_del_record_list($location_type, $condition) {
625
+    if(!($condition = trim($condition))) {
626
+      return false;
627
+    }
604 628
 
605 629
     $location_info = &static::$location_info[$location_type];
606 630
     $table_name = $location_info[P_TABLE_NAME];
607 631
 
608 632
     if($result = static::db_query("DELETE FROM `{{{$table_name}}}` WHERE {$condition}"))
609 633
     {
610
-      if(static::$db->db_affected_rows()) // Обновляем данные только если ряд был затронут
634
+      if(static::$db->db_affected_rows()) {
635
+        // Обновляем данные только если ряд был затронут
611 636
       {
612 637
         // Обнуление кэша, потому что непонятно, что поменялось
613 638
         // TODO - когда будет структурированный $condition можно будет делать только cache_unset по нужным записям
614 639
         static::cache_clear($location_type);
615 640
       }
641
+      }
616 642
     }
617 643
 
618 644
     return $result;
@@ -638,8 +664,7 @@  discard block
 block discarded – undo
638 664
    *    <p>false - Нет записи с указанным ID и $player</p>
639 665
    *    <p>array - запись типа $user</p>
640 666
    */
641
-  public static function db_get_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null)
642
-  {
667
+  public static function db_get_user_by_id($user_id_unsafe, $for_update = false, $fields = '*', $player = null) {
643 668
     $user = static::db_get_record_by_id(LOC_USER, $user_id_unsafe, $for_update, $fields);
644 669
 
645 670
     return (is_array($user) &&
@@ -651,14 +676,15 @@  discard block
 block discarded – undo
651 676
       ($player === false && $user['user_as_ally'])
652 677
     )) ? $user : false;
653 678
   }
654
-  public static function db_get_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false)
655
-  {
679
+  public static function db_get_user_by_username($username_unsafe, $for_update = false, $fields = '*', $player = null, $like = false) {
656 680
     // TODO Проверить, кстати - а везде ли нужно выбирать юзеров или где-то все-таки ищутся Альянсы ?
657
-    if(!($username_unsafe = trim($username_unsafe))) return false;
681
+    if(!($username_unsafe = trim($username_unsafe))) {
682
+      return false;
683
+    }
658 684
 
659 685
     $user = null;
660
-    if(is_array(static::$data[LOC_USER]))
661
-    foreach(static::$data[LOC_USER] as $user_id => $user_data)
686
+    if(is_array(static::$data[LOC_USER])) {
687
+        foreach(static::$data[LOC_USER] as $user_id => $user_data)
662 688
     {
663 689
       if(is_array($user_data) && isset($user_data['username']))
664 690
       {
@@ -668,6 +694,7 @@  discard block
 block discarded – undo
668 694
         {
669 695
           // $user_as_ally = intval($user_data['user_as_ally']);
670 696
           $user_as_ally = idval($user_data['user_as_ally']);
697
+    }
671 698
           if($player === null || ($player === true && !$user_as_ally) || ($player === false && $user_as_ally))
672 699
           {
673 700
             $user = $user_data;
@@ -695,7 +722,9 @@  discard block
 block discarded – undo
695 722
   }
696 723
   // UNUSED
697 724
   public static function db_get_user_by_email($email_unsafe, $use_both = false, $for_update = false, $fields = '*') {
698
-    if(!($email_unsafe = strtolower(trim($email_unsafe)))) return false;
725
+    if(!($email_unsafe = strtolower(trim($email_unsafe)))) {
726
+      return false;
727
+    }
699 728
 
700 729
     $user = null;
701 730
     // TODO переделать на индексы
@@ -752,15 +781,13 @@  discard block
 block discarded – undo
752 781
 
753 782
 
754 783
 
755
-  public static function db_unit_time_restrictions($date = SN_TIME_NOW)
756
-  {
784
+  public static function db_unit_time_restrictions($date = SN_TIME_NOW) {
757 785
     $date = is_numeric($date) ? "FROM_UNIXTIME({$date})" : "'{$date}'";
758 786
     return
759 787
       "(unit_time_start IS NULL OR unit_time_start <= {$date}) AND
760 788
     (unit_time_finish IS NULL OR unit_time_finish = '1970-01-01 03:00:00' OR unit_time_finish >= {$date})";
761 789
   }
762
-  public static function db_get_unit_by_id($unit_id, $for_update = false, $fields = '*')
763
-  {
790
+  public static function db_get_unit_by_id($unit_id, $for_update = false, $fields = '*') {
764 791
     // TODO запихивать в $data[LOC_LOCATION][$location_type][$location_id]
765 792
     $unit = static::db_get_record_by_id(LOC_UNIT, $unit_id, $for_update, $fields);
766 793
     if(is_array($unit))
@@ -771,9 +798,10 @@  discard block
 block discarded – undo
771 798
     return $unit;
772 799
   }
773 800
 
774
-  public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id)
775
-  {
776
-    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) return false;
801
+  public static function db_get_unit_list_by_location($user_id = 0, $location_type, $location_id) {
802
+    if(!($location_type = idval($location_type)) || !($location_id = idval($location_id))) {
803
+      return false;
804
+    }
777 805
 
778 806
     $query_cache = &static::$locator[LOC_UNIT][$location_type][$location_id];
779 807
     if(!isset($query_cache))
@@ -798,8 +826,7 @@  discard block
 block discarded – undo
798 826
 
799 827
     return $result;
800 828
   }
801
-  public static function db_get_unit_by_location($user_id = 0, $location_type, $location_id, $unit_snid = 0, $for_update = false, $fields = '*')
802
-  {
829
+  public static function db_get_unit_by_location($user_id = 0, $location_type, $location_id, $unit_snid = 0, $for_update = false, $fields = '*') {
803 830
     static::db_get_unit_list_by_location($user_id, $location_type, $location_id);
804 831
 
805 832
     return $unit_snid ? static::$locator[LOC_UNIT][$location_type][$location_id][$unit_snid] : static::$locator[LOC_UNIT][$location_type][$location_id];
@@ -827,8 +854,7 @@  discard block
 block discarded – undo
827 854
    * TODO Переформатировать вывод данных, что бы можно было возвращать данные по всем планетам и юзерам в одном запросе: добавить подмассивы 'que', 'planets', 'players'
828 855
    *
829 856
    */
830
-  public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, $for_update = false)
831
-  {
857
+  public static function db_que_list_by_type_location($user_id, $planet_id = null, $que_type = false, $for_update = false) {
832 858
     if(!$user_id)
833 859
     {
834 860
       pdump(debug_backtrace());
@@ -839,15 +865,18 @@  discard block
 block discarded – undo
839 865
 
840 866
     $query = array();
841 867
 
842
-    if($user_id = idval($user_id))
843
-      $query[] = "`que_player_id` = {$user_id}";
868
+    if($user_id = idval($user_id)) {
869
+          $query[] = "`que_player_id` = {$user_id}";
870
+    }
844 871
 
845
-    if($que_type == QUE_RESEARCH || $planet_id === null)
846
-      $query[] = "`que_planet_id` IS NULL";
847
-    elseif($planet_id)
848
-      $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
849
-    if($que_type)
850
-      $query[] = "`que_type` = {$que_type}";
872
+    if($que_type == QUE_RESEARCH || $planet_id === null) {
873
+          $query[] = "`que_planet_id` IS NULL";
874
+    } elseif($planet_id) {
875
+          $query[] = "(`que_planet_id` = {$planet_id}" . ($que_type ? '' : ' OR que_planet_id IS NULL') . ")";
876
+    }
877
+    if($que_type) {
878
+          $query[] = "`que_type` = {$que_type}";
879
+    }
851 880
 
852 881
     $ques['items'] = static::db_get_record_list(LOC_QUE, implode(' AND ', $query));
853 882
 
@@ -907,8 +936,7 @@  discard block
 block discarded – undo
907 936
 
908 937
 
909 938
 
910
-  public static function db_changeset_prepare_unit($unit_id, $unit_value, $user, $planet_id = null)
911
-  {
939
+  public static function db_changeset_prepare_unit($unit_id, $unit_value, $user, $planet_id = null) {
912 940
     if(!is_array($user))
913 941
     {
914 942
       // TODO - remove later
@@ -946,8 +974,7 @@  discard block
 block discarded – undo
946 974
           ),
947 975
         ),
948 976
       );
949
-    }
950
-    else
977
+    } else
951 978
     {
952 979
       $db_changeset = array(
953 980
         'action' => SQL_OP_INSERT,
@@ -979,16 +1006,14 @@  discard block
 block discarded – undo
979 1006
 
980 1007
 
981 1008
 
982
-  public function db_changeset_delay($table_name, $table_data)
983
-  {
1009
+  public function db_changeset_delay($table_name, $table_data) {
984 1010
     // TODO Применять ченджсет к записям
985 1011
     static::$delayed_changset[$table_name] = is_array(static::$delayed_changset[$table_name]) ? static::$delayed_changset[$table_name] : array();
986 1012
     // TODO - На самом деле дурацкая оптимизация, если честно - может быть идентичные записи с идентичными дельтами - и привет. Но не должны, конечно
987 1013
     static::$delayed_changset[$table_name] = array_merge(static::$delayed_changset[$table_name], $table_data);
988 1014
   }
989 1015
 
990
-  public function db_changeset_revert()
991
-  {
1016
+  public function db_changeset_revert() {
992 1017
     // TODO Для этапа 1 - достаточно чистить только те таблицы, что были затронуты
993 1018
     // Для этапа 2 - чистить только записи
994 1019
     // Для этапа 3 - возвращать всё
@@ -1073,7 +1098,9 @@  discard block
 block discarded – undo
1073 1098
 
1074 1099
   public static function db_changeset_apply($db_changeset, $flush_delayed = false) {
1075 1100
     $result = true;
1076
-    if(!is_array($db_changeset) || empty($db_changeset)) return $result;
1101
+    if(!is_array($db_changeset) || empty($db_changeset)) {
1102
+      return $result;
1103
+    }
1077 1104
 
1078 1105
     foreach($db_changeset as $table_name => &$table_data) {
1079 1106
       // TODO - delayed changeset
@@ -1087,8 +1114,13 @@  discard block
 block discarded – undo
1087 1114
       foreach($table_data as $record_id => &$conditions) {
1088 1115
         static::db_changeset_condition_compile($conditions, $table_name);
1089 1116
 
1090
-        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) continue;
1091
-        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) continue; // Защита от случайного удаления всех данных в таблице
1117
+        if($conditions['action'] != SQL_OP_DELETE && !$conditions[P_FIELDS_STR]) {
1118
+          continue;
1119
+        }
1120
+        if($conditions['action'] == SQL_OP_DELETE && !$conditions[P_WHERE_STR]) {
1121
+          continue;
1122
+        }
1123
+        // Защита от случайного удаления всех данных в таблице
1092 1124
 
1093 1125
         if($conditions[P_LOCATION] != LOC_NONE) {
1094 1126
           //die('spec ops classSupernova.php line 928 Добавить работу с кэшем юнитов итд');
Please login to merge, or discard this patch.
classes/core_auth.php 2 patches
Doc Comments   +7 added lines patch added patch discarded remove patch
@@ -829,10 +829,17 @@
 block discarded – undo
829 829
 
830 830
   // OK v4.5
831 831
   // TODO - REMEMBER_ME
832
+
833
+  /**
834
+   * @param integer $period
835
+   */
832 836
   protected static function cookie_set($value, $impersonate = false, $period = null) {
833 837
     sn_setcookie($impersonate ? SN_COOKIE_U_I : SN_COOKIE_U, $value, $period === null ? SN_TIME_NOW + PERIOD_YEAR : $period, SN_ROOT_RELATIVE);
834 838
   }
835 839
 
840
+  /**
841
+   * @param string $message
842
+   */
836 843
   protected static function flog($message, $die = false) {
837 844
     if(!defined('DEBUG_AUTH') || !DEBUG_AUTH) {
838 845
       return;
Please login to merge, or discard this patch.
Spacing   +64 added lines, -64 removed lines patch added patch discarded remove patch
@@ -205,18 +205,18 @@  discard block
 block discarded – undo
205 205
     // TODO Хотя тут может получится вечный цикл - ПОДУМАТЬ
206 206
     // TODO Тут же можно пробовать провести попытку слияния аккаунтов - хотя это и очень небезопасно
207 207
 
208
-    if(sys_get_param('login_player_register_logout')) {
208
+    if (sys_get_param('login_player_register_logout')) {
209 209
       $this->logout();
210 210
     }
211 211
 
212 212
     $original_suggest = '';
213 213
     // Смотрим - есть ли у нас данные от пользователя
214
-    if(($player_name_submitted = sys_get_param('submit_player_name'))) {
214
+    if (($player_name_submitted = sys_get_param('submit_player_name'))) {
215 215
       // Попытка регистрации нового игрока из данных, введенных пользователем
216 216
       $this->player_suggested_name = sys_get_param_str_unsafe('player_suggested_name');
217 217
     } else {
218
-      foreach($this->providers_authorised as $provider) {
219
-        if($this->player_suggested_name = $provider->player_name_suggest()) { // OK 4.5
218
+      foreach ($this->providers_authorised as $provider) {
219
+        if ($this->player_suggested_name = $provider->player_name_suggest()) { // OK 4.5
220 220
           $original_suggest = $provider->player_name_suggest();
221 221
           break;
222 222
         }
@@ -224,7 +224,7 @@  discard block
 block discarded – undo
224 224
     }
225 225
 
226 226
     // Если у нас провайдеры не дают имени и пользователь не дал свой вариант - это у нас первый логин в игру
227
-    if(!$this->player_suggested_name) {
227
+    if (!$this->player_suggested_name) {
228 228
       $max_user_id = db_player_get_max_id(); // 4.5
229 229
       // TODO - предлагать имя игрока по локали
230 230
 
@@ -233,15 +233,15 @@  discard block
 block discarded – undo
233 233
         sn_db_transaction_rollback();
234 234
         $this->player_suggested_name = 'Emperor ' . mt_rand($max_user_id + 1, $max_user_id + 1000);
235 235
         sn_db_transaction_start();
236
-      } while(db_player_name_exists($this->player_suggested_name));
236
+      } while (db_player_name_exists($this->player_suggested_name));
237 237
 
238 238
     }
239 239
 
240
-    if($player_name_submitted) {
240
+    if ($player_name_submitted) {
241 241
       $this->register_player_db_create($this->player_suggested_name); // OK 4.5
242
-      if($this->register_status == LOGIN_SUCCESS) {
242
+      if ($this->register_status == LOGIN_SUCCESS) {
243 243
         sys_redirect(SN_ROOT_VIRTUAL . 'overview.php');
244
-      } elseif($this->register_status == REGISTER_ERROR_PLAYER_NAME_EXISTS && $original_suggest == $this->player_suggested_name) {
244
+      } elseif ($this->register_status == REGISTER_ERROR_PLAYER_NAME_EXISTS && $original_suggest == $this->player_suggested_name) {
245 245
         // self::$player_suggested_name .= ' ' . $this->account->account_id;
246 246
       }
247 247
 //      if(self::$login_status != LOGIN_SUCCESS) {
@@ -265,7 +265,7 @@  discard block
 block discarded – undo
265 265
         : false
266 266
       );
267 267
 
268
-    if($this->register_status == LOGIN_ERROR_USERNAME_RESTRICTED_CHARACTERS) {
268
+    if ($this->register_status == LOGIN_ERROR_USERNAME_RESTRICTED_CHARACTERS) {
269 269
       $prohibited_characters = array_map(function($value) {
270 270
         return "'" . htmlentities($value, ENT_QUOTES, 'UTF-8') . "'";
271 271
       }, str_split(LOGIN_REGISTER_CHARACTERS_PROHIBITED));
@@ -297,27 +297,27 @@  discard block
 block discarded – undo
297 297
     global $sn_module_list, $lang;
298 298
 
299 299
     // !self::$is_init ? self::init() : false;
300
-    if(empty($sn_module_list['auth'])) {
300
+    if (empty($sn_module_list['auth'])) {
301 301
       die('{Не обнаружено ни одного провайдера авторизации в core_auth::login()!}');
302 302
     }
303 303
 
304 304
     !empty($_POST) ? self::flog(dump($_POST, '$_POST')) : false;
305 305
     !empty($_GET) ? self::flog(dump($_GET, '$_GET')) : false;
306
-    !empty($_COOKIE) ? self::flog(dump($_COOKIE,'$_COOKIE')) : false;
306
+    !empty($_COOKIE) ? self::flog(dump($_COOKIE, '$_COOKIE')) : false;
307 307
 
308 308
     $this->auth_reset(); // OK v4.5
309 309
 
310 310
     $this->providers = array();
311
-    foreach($sn_module_list['auth'] as $module_name => $module) {
311
+    foreach ($sn_module_list['auth'] as $module_name => $module) {
312 312
       $this->providers[$module->provider_id] = $module;
313 313
     }
314 314
 
315 315
     // $this->providers = array_reverse($this->providers, true); // НИНАДА! СН-аккаунт должен всегда авторизироваться первым!
316 316
 //pdump($this->providers);
317
-    foreach($this->providers as $provider_id => $provider) {
317
+    foreach ($this->providers as $provider_id => $provider) {
318 318
       $login_status = $provider->login(); // OK v4.5
319 319
       self::flog(($provider->manifest['name'] . '->' . 'login_try - ') . (empty($provider->account->account_id) ? $lang['sys_login_messages'][$provider->account_login_status] : dump($provider)));
320
-      if($login_status == LOGIN_SUCCESS && is_object($provider->account) && $provider->account instanceof Account && $provider->account->account_id) {
320
+      if ($login_status == LOGIN_SUCCESS && is_object($provider->account) && $provider->account instanceof Account && $provider->account->account_id) {
321 321
         $this->providers_authorised[$provider_id] = &$this->providers[$provider_id];
322 322
 
323 323
         $this->user_id_to_provider = array_replace_recursive(
@@ -325,20 +325,20 @@  discard block
 block discarded – undo
325 325
           // static::db_translate_get_users_from_account_list($provider_id, $provider->account->account_id) // OK 4.5
326 326
           PlayerToAccountTranslate::db_translate_get_users_from_account_list($provider_id, $provider->account->account_id) // OK 4.5
327 327
         );
328
-      } elseif($login_status != LOGIN_UNDEFINED) {
328
+      } elseif ($login_status != LOGIN_UNDEFINED) {
329 329
         $this->provider_error_list[$provider_id] = $login_status;
330 330
       }
331 331
     }
332 332
 
333
-    if(empty($this->providers_authorised)) {
333
+    if (empty($this->providers_authorised)) {
334 334
       // Ни один аккаунт не авторизирован
335 335
       // Проверяем - есть ли у нас ошибки в аккаунтах?
336
-      if(!empty($this->provider_error_list)) {
336
+      if (!empty($this->provider_error_list)) {
337 337
         // Если есть - выводим их
338 338
         self::$login_status = reset($this->provider_error_list);
339 339
         $providerError = $this->providers[key($this->provider_error_list)]->account_login_message;
340 340
 
341
-        if(!empty($providerError)) {
341
+        if (!empty($providerError)) {
342 342
           self::$login_message = $providerError;
343 343
         }
344 344
       }
@@ -353,12 +353,12 @@  discard block
 block discarded – undo
353 353
       // В self::$accessible_user_row_list - список доступных игроков для данных аккаунтов с соответствующими записями из таблицы `users`
354 354
 
355 355
       // Остались ли у нас в списке доступные игроки?
356
-      if(empty($this->accessible_user_row_list)) {
356
+      if (empty($this->accessible_user_row_list)) {
357 357
         // Нет ни одного игрока ни на одном авторизированном аккаунте
358 358
         // Надо регать нового игрока
359 359
 
360 360
         // Сейчас происходит процесс регистрации игрока?
361
-        if(!$this->is_player_register) {
361
+        if (!$this->is_player_register) {
362 362
           // Нет - отправляем на процесс регистрации
363 363
           $partner_id = sys_get_param_int('id_ref', sys_get_param_int('partner_id'));
364 364
           sys_redirect(SN_ROOT_VIRTUAL . 'index.php?page=player_register&player_register=1' . ($partner_id ? '&id_ref=' . $partner_id : ''));
@@ -367,7 +367,7 @@  discard block
 block discarded – undo
367 367
         // Да, есть доступные игроки, которые так же прописаны в базе
368 368
         $this->get_active_user(); // 4.5
369 369
 
370
-        if($this->is_impersonating = !empty($_COOKIE[SN_COOKIE_U_I]) ? $_COOKIE[SN_COOKIE_U_I] : 0) {
370
+        if ($this->is_impersonating = !empty($_COOKIE[SN_COOKIE_U_I]) ? $_COOKIE[SN_COOKIE_U_I] : 0) {
371 371
           $a_user = db_user_by_id($this->is_impersonating);
372 372
           $this->impersonator_username = $a_user['username'];
373 373
         }
@@ -375,9 +375,9 @@  discard block
 block discarded – undo
375 375
 
376 376
         //Прописываем текущего игрока на все авторизированные аккаунты
377 377
         // TODO - ИЛИ ВСЕХ ИГРОКОВ??
378
-        if(empty($this->is_impersonating)) {
379
-          foreach($this->providers_authorised as $provider_id => $provider) {
380
-            if(empty($this->user_id_to_provider[self::$user['id']][$provider_id])) {
378
+        if (empty($this->is_impersonating)) {
379
+          foreach ($this->providers_authorised as $provider_id => $provider) {
380
+            if (empty($this->user_id_to_provider[self::$user['id']][$provider_id])) {
381 381
               // self::db_translate_register_user($provider_id, $provider->account->account_id, self::$user['id']);
382 382
               PlayerToAccountTranslate::db_translate_register_user($provider_id, $provider->account->account_id, self::$user['id']);
383 383
               $this->user_id_to_provider[self::$user['id']][$provider_id][$provider->account->account_id] = true;
@@ -387,9 +387,9 @@  discard block
 block discarded – undo
387 387
       }
388 388
     }
389 389
 
390
-    if(empty(self::$user['id'])) {
390
+    if (empty(self::$user['id'])) {
391 391
       self::cookie_set(''); // OK 4.5
392
-    } elseif(self::$user['id'] != $_COOKIE[SN_COOKIE_U]) {
392
+    } elseif (self::$user['id'] != $_COOKIE[SN_COOKIE_U]) {
393 393
       self::cookie_set(self::$user['id']); // OK 4.5
394 394
     }
395 395
 
@@ -408,21 +408,21 @@  discard block
 block discarded – undo
408 408
    */
409 409
   // OK v4.7
410 410
   public function logout($redirect = true) {
411
-    if(!empty($_COOKIE[SN_COOKIE_U_I])) {
411
+    if (!empty($_COOKIE[SN_COOKIE_U_I])) {
412 412
       self::cookie_set($_COOKIE[SN_COOKIE_U_I]);
413 413
       self::cookie_set(0, true);
414 414
       self::$main_provider->logout();
415 415
     } else {
416
-      foreach($this->providers as $provider_name => $provider) {
416
+      foreach ($this->providers as $provider_name => $provider) {
417 417
         $provider->logout();
418 418
       }
419 419
 
420 420
       self::cookie_set(0);
421 421
     }
422 422
 
423
-    if($redirect === true) {
423
+    if ($redirect === true) {
424 424
       sys_redirect(SN_ROOT_RELATIVE . (empty($_COOKIE[SN_COOKIE_U]) ? 'login.php' : 'admin/overview.php'));
425
-    } elseif($redirect !== false) {
425
+    } elseif ($redirect !== false) {
426 426
       sys_redirect($redirect);
427 427
     }
428 428
   }
@@ -433,15 +433,15 @@  discard block
 block discarded – undo
433 433
    * @param $user_selected
434 434
    */
435 435
   public function impersonate($user_selected) {
436
-    if($_COOKIE[SN_COOKIE_U_I]) {
436
+    if ($_COOKIE[SN_COOKIE_U_I]) {
437 437
       die('You already impersonating someone. Go back to living other\'s life! Or clear your cookies and try again'); // TODO: Log it
438 438
     }
439 439
 
440
-    if($this->auth_level_max_local < AUTH_LEVEL_ADMINISTRATOR) {
440
+    if ($this->auth_level_max_local < AUTH_LEVEL_ADMINISTRATOR) {
441 441
       die('You can\'t impersonate - too low level'); // TODO: Log it
442 442
     }
443 443
 
444
-    if($this->auth_level_max_local <= $user_selected['authlevel']) {
444
+    if ($this->auth_level_max_local <= $user_selected['authlevel']) {
445 445
       die('You can\'t impersonate this account - level is greater or equal to yours'); // TODO: Log it
446 446
     }
447 447
 
@@ -449,7 +449,7 @@  discard block
 block discarded – undo
449 449
     $account_translate = reset($account_translate[$user_selected['id']][self::$main_provider->provider_id]);
450 450
     $account_to_impersonate = new Account(self::$main_provider->db);
451 451
     $account_to_impersonate->db_get_by_id($account_translate['provider_account_id']);
452
-    if(!$account_to_impersonate->is_exists) {
452
+    if (!$account_to_impersonate->is_exists) {
453 453
       die('Какая-то ошибка - не могу найти аккаунт для имперсонации'); // TODO: Log it
454 454
     }
455 455
     self::$main_provider->impersonate($account_to_impersonate);
@@ -475,12 +475,12 @@  discard block
 block discarded – undo
475 475
   public function password_check($password_unsafe) {
476 476
     $result = false;
477 477
 
478
-    if(empty($this->providers_authorised)) {
478
+    if (empty($this->providers_authorised)) {
479 479
       // TODO - такого быть не может!
480 480
       self::flog("password_check: Не найдено ни одного авторизированного провайдера в self::\$providers_authorised", true);
481 481
     } else {
482
-      foreach($this->providers_authorised as $provider_id => $provider) {
483
-        if($provider->is_feature_supported(AUTH_FEATURE_HAS_PASSWORD)) {
482
+      foreach ($this->providers_authorised as $provider_id => $provider) {
483
+        if ($provider->is_feature_supported(AUTH_FEATURE_HAS_PASSWORD)) {
484 484
           $result = $result || $provider->password_check($password_unsafe);
485 485
         }
486 486
       }
@@ -501,7 +501,7 @@  discard block
 block discarded – undo
501 501
   public function password_change($old_password_unsafe, $new_password_unsafe) {
502 502
     global $lang;
503 503
 
504
-    if(empty($this->providers_authorised)) {
504
+    if (empty($this->providers_authorised)) {
505 505
       // TODO - такого быть не может!
506 506
       self::flog("Не найдено ни одного авторизированного провайдера в self::\$providers_authorised", true);
507 507
       return false;
@@ -514,8 +514,8 @@  discard block
 block discarded – undo
514 514
     $salt_unsafe = self::password_salt_generate();
515 515
 
516 516
     $providers_changed_password = array();
517
-    foreach($this->providers_authorised as $provider_id => $provider) {
518
-      if(
517
+    foreach ($this->providers_authorised as $provider_id => $provider) {
518
+      if (
519 519
         !$provider->is_feature_supported(AUTH_FEATURE_PASSWORD_CHANGE)
520 520
         || !$provider->password_change($old_password_unsafe, $new_password_unsafe, $salt_unsafe)
521 521
       ) {
@@ -527,7 +527,7 @@  discard block
 block discarded – undo
527 527
       $account_translation = PlayerToAccountTranslate::db_translate_get_users_from_account_list($provider_id, $provider->account->account_id);
528 528
 
529 529
       // Рассылаем уведомления о смене пароля в ЛС
530
-      foreach($account_translation as $user_id => $provider_info) {
530
+      foreach ($account_translation as $user_id => $provider_info) {
531 531
         // TODO - УКазывать тип аккаунта, на котором сменён пароль
532 532
         msg_send_simple_message($user_id, 0, SN_TIME_NOW, MSG_TYPE_ADMIN,
533 533
           $lang['sys_administration'], $lang['sys_login_register_message_title'],
@@ -574,7 +574,7 @@  discard block
 block discarded – undo
574 574
       sn_db_transaction_start();
575 575
       // Проверить наличие такого имени в истории имён
576 576
 
577
-      if(db_player_name_exists($player_name_unsafe)) {
577
+      if (db_player_name_exists($player_name_unsafe)) {
578 578
         throw new Exception(REGISTER_ERROR_PLAYER_NAME_EXISTS, ERR_ERROR);
579 579
       }
580 580
 
@@ -582,11 +582,11 @@  discard block
 block discarded – undo
582 582
       $player_language = '';
583 583
       $player_email = '';
584 584
       // TODO - порнография - работа должна происходить над списком аккаунтов, а не только на одном аккаунте...
585
-      foreach($this->providers_authorised as $provider) {
586
-        if(!$player_language && $provider->account->account_language) {
585
+      foreach ($this->providers_authorised as $provider) {
586
+        if (!$player_language && $provider->account->account_language) {
587 587
           $player_language = $provider->account->account_language;
588 588
         }
589
-        if(!$player_email && $provider->account->account_email) {
589
+        if (!$player_email && $provider->account->account_email) {
590 590
           $player_email = $provider->account->account_email;
591 591
         }
592 592
       }
@@ -602,7 +602,7 @@  discard block
 block discarded – undo
602 602
       ));
603 603
       // Зарегестрировать на него аккаунты из self::$accounts_authorised
604 604
       $a_user = self::$user;
605
-      foreach($this->providers_authorised as $provider) {
605
+      foreach ($this->providers_authorised as $provider) {
606 606
         // TODO - порнография. Должен быть отдельный класс трансляторов - в т.ч. и кэширующий транслятор
607 607
         // TODO - ну и работа должна происходить над списком аккаунтов, а не только на одном аккаунте...
608 608
         // self::db_translate_register_user($provider->provider_id, $provider->account->account_id, $a_user['id']);
@@ -614,7 +614,7 @@  discard block
 block discarded – undo
614 614
 
615 615
       sn_db_transaction_commit();
616 616
       $this->register_status = LOGIN_SUCCESS;
617
-    } catch(Exception $e) {
617
+    } catch (Exception $e) {
618 618
       sn_db_transaction_rollback();
619 619
 
620 620
       // Если старое имя занято
@@ -633,10 +633,10 @@  discard block
 block discarded – undo
633 633
     // Пробиваем все ИД игроков по базе - есть ли вообще такие записи
634 634
     // Вообще-то это не особо нужно - у нас по определению стоят констраинты
635 635
     // Зато так мы узнаем максимальный authlevel, проверим права имперсонейта и вытащим все записи юзеров
636
-    foreach($this->user_id_to_provider as $user_id => $cork) {
636
+    foreach ($this->user_id_to_provider as $user_id => $cork) {
637 637
       $user = db_user_by_id($user_id);
638 638
       // Если записи игрока в БД не существует?
639
-      if(empty($user['id'])) {
639
+      if (empty($user['id'])) {
640 640
         // Удаляем этого и переходим к следующему
641 641
         unset($this->user_id_to_provider[$user_id]);
642 642
         // Де-регистрируем игрока из таблицы трансляции игроков
@@ -657,7 +657,7 @@  discard block
 block discarded – undo
657 657
   // OK v4.5
658 658
   protected function get_active_user() {
659 659
     // Проверяем куку "текущего игрока" из браузера
660
-    if(
660
+    if (
661 661
       // Кука не пустая
662 662
       ($_COOKIE[SN_COOKIE_U] = trim($_COOKIE[SN_COOKIE_U])) && !empty($_COOKIE[SN_COOKIE_U])
663 663
       // И в куке находится ID
@@ -682,7 +682,7 @@  discard block
 block discarded – undo
682 682
     }
683 683
 
684 684
     // В куке нет валидного ИД записи игрока, доступной с текущих аккаунтов
685
-    if(empty(self::$user['id'])) {
685
+    if (empty(self::$user['id'])) {
686 686
       // Берем первого из доступных
687 687
       // TODO - default_user
688 688
       self::$user = reset($this->accessible_user_row_list);
@@ -706,7 +706,7 @@  discard block
 block discarded – undo
706 706
 
707 707
     $result = array();
708 708
 
709
-    if($user_id && empty($this->is_impersonating)) {
709
+    if ($user_id && empty($this->is_impersonating)) {
710 710
       // self::db_counter_insert();
711 711
       self::$device->db_counter_insert($user_id);
712 712
 
@@ -714,12 +714,12 @@  discard block
 block discarded – undo
714 714
 
715 715
       sys_user_options_unpack($user);
716 716
 
717
-      if($user['banaday'] && $user['banaday'] <= SN_TIME_NOW) {
717
+      if ($user['banaday'] && $user['banaday'] <= SN_TIME_NOW) {
718 718
         $user['banaday'] = 0;
719 719
         $user['vacation'] = SN_TIME_NOW;
720 720
       }
721 721
 
722
-      $user['user_lastip'] = self::$device->ip_v4_string;// $ip['ip'];
722
+      $user['user_lastip'] = self::$device->ip_v4_string; // $ip['ip'];
723 723
       $user['user_proxy'] = self::$device->ip_v4_proxy_chain; //$ip['proxy_chain'];
724 724
 
725 725
       $result[F_BANNED_STATUS] = $user['banaday'];
@@ -733,13 +733,13 @@  discard block
 block discarded – undo
733 733
       );
734 734
     }
735 735
 
736
-    if($extra = $config->security_ban_extra) {
736
+    if ($extra = $config->security_ban_extra) {
737 737
       $extra = explode(',', $extra);
738
-      array_walk($extra,'trim');
738
+      array_walk($extra, 'trim');
739 739
       in_array(self::$device->device_id, $extra) and die();
740 740
     }
741 741
 
742
-    if(self::$login_message) {
742
+    if (self::$login_message) {
743 743
       $result[F_LOGIN_MESSAGE] = self::$login_message;
744 744
     }
745 745
 
@@ -775,21 +775,21 @@  discard block
 block discarded – undo
775 775
   protected function register_player_name_validate($player_name_unsafe) {
776 776
     // TODO - переделать под RAW-строки
777 777
     // Если имя игрока пустое - NO GO!
778
-    if(trim($player_name_unsafe) == '') {
778
+    if (trim($player_name_unsafe) == '') {
779 779
       throw new Exception(REGISTER_ERROR_PLAYER_NAME_EMPTY, ERR_ERROR);
780 780
     }
781 781
     // Проверяем, что бы в начале и конце не было пустых символов
782
-    if($player_name_unsafe != trim($player_name_unsafe)) {
782
+    if ($player_name_unsafe != trim($player_name_unsafe)) {
783 783
       throw new Exception(REGISTER_ERROR_PLAYER_NAME_TRIMMED, ERR_ERROR);
784 784
     }
785 785
     // Если логин имеет запрещенные символы - NO GO!
786
-    if(strpbrk($player_name_unsafe, LOGIN_REGISTER_CHARACTERS_PROHIBITED)) {
786
+    if (strpbrk($player_name_unsafe, LOGIN_REGISTER_CHARACTERS_PROHIBITED)) {
787 787
       // TODO - выдавать в сообщение об ошибке список запрещенных символов
788 788
       // TODO - заранее извещать игрока, какие символы являются запрещенными
789 789
       throw new Exception(REGISTER_ERROR_PLAYER_NAME_RESTRICTED_CHARACTERS, ERR_ERROR);
790 790
     }
791 791
     // Если логин меньше минимальной длины - NO GO!
792
-    if(strlen($player_name_unsafe) < LOGIN_LENGTH_MIN) {
792
+    if (strlen($player_name_unsafe) < LOGIN_LENGTH_MIN) {
793 793
       // TODO - выдавать в сообщение об ошибке минимальную длину имени игрока
794 794
       // TODO - заранее извещать игрока, какая минимальная и максимальная длина имени
795 795
       throw new Exception(REGISTER_ERROR_PLAYER_NAME_SHORT, ERR_ERROR);
@@ -847,7 +847,7 @@  discard block
 block discarded – undo
847 847
   }
848 848
 
849 849
   protected static function flog($message, $die = false) {
850
-    if(!defined('DEBUG_AUTH') || !DEBUG_AUTH) {
850
+    if (!defined('DEBUG_AUTH') || !DEBUG_AUTH) {
851 851
       return;
852 852
     }
853 853
     list($called, $caller) = debug_backtrace(false);
@@ -860,7 +860,7 @@  discard block
 block discarded – undo
860 860
     $_SERVER['SERVER_NAME'] == 'localhost' ? print("<div class='debug'>$message - $caller_name\r\n</div>") : false;
861 861
 
862 862
     classSupernova::log_file("$message - $caller_name");
863
-    if($die) {
863
+    if ($die) {
864 864
       $die && die("<div class='negative'>СТОП! Функция {$caller_name} при вызове в " . get_called_class() . " (располагается в " . get_class() . "). СООБЩИТЕ АДМИНИСТРАЦИИ!</div>");
865 865
     }
866 866
   }
Please login to merge, or discard this patch.
classes/db_mysql.php 2 patches
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -180,6 +180,9 @@  discard block
 block discarded – undo
180 180
   }
181 181
 
182 182
 
183
+  /**
184
+   * @param string $query
185
+   */
183 186
   function security_watch_user_queries($query) {
184 187
     // TODO Заменить это на новый логгер
185 188
     global $config, $is_watching, $user, $debug;
@@ -202,6 +205,9 @@  discard block
 block discarded – undo
202 205
   }
203 206
 
204 207
 
208
+  /**
209
+   * @param string $query
210
+   */
205 211
   function security_query_check_bad_words($query) {
206 212
     global $user, $dm_change_legit, $mm_change_legit;
207 213
 
Please login to merge, or discard this patch.
Spacing   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -76,23 +76,23 @@  discard block
 block discarded – undo
76 76
   function sn_db_connect($external_db_settings = null) {
77 77
     $this->db_disconnect();
78 78
 
79
-    if(!empty($external_db_settings) && is_array($external_db_settings)) {
79
+    if (!empty($external_db_settings) && is_array($external_db_settings)) {
80 80
       $this->dbsettings = $external_db_settings;
81 81
     }
82 82
 
83
-    if(empty($this->dbsettings)) {
83
+    if (empty($this->dbsettings)) {
84 84
       $this->load_db_settings();
85 85
     }
86 86
 
87 87
     // TODO - фатальные (?) ошибки на каждом шагу. Хотя - скорее Эксепшны
88
-    if(!empty($this->dbsettings)) {
88
+    if (!empty($this->dbsettings)) {
89 89
       $driver_name = empty($this->dbsettings['sn_driver']) ? 'db_mysql_v5' : $this->dbsettings['sn_driver'];
90 90
       $this->driver = new $driver_name();
91 91
       $this->db_prefix = $this->dbsettings['prefix'];
92 92
 
93 93
       $this->connected = $this->connected || $this->driver_connect();
94 94
 
95
-      if($this->connected) {
95
+      if ($this->connected) {
96 96
         $this->table_list = $this->db_get_table_list();
97 97
         // TODO Проверка на пустоту
98 98
       }
@@ -106,11 +106,11 @@  discard block
 block discarded – undo
106 106
   function driver_connect() {
107 107
     global $debug;
108 108
 
109
-    if(!is_object($this->driver)) {
109
+    if (!is_object($this->driver)) {
110 110
       $debug->error_fatal('DB Error - No driver for MySQL found!');
111 111
     }
112 112
 
113
-    if(!method_exists($this->driver, 'mysql_connect')) {
113
+    if (!method_exists($this->driver, 'mysql_connect')) {
114 114
       $debug->error_fatal('DB Error - WRONG MySQL driver!');
115 115
     }
116 116
 
@@ -118,7 +118,7 @@  discard block
 block discarded – undo
118 118
   }
119 119
 
120 120
   function db_disconnect() {
121
-    if($this->connected) {
121
+    if ($this->connected) {
122 122
       $this->connected = !$this->driver_disconnect();
123 123
       $this->connected = false;
124 124
     }
@@ -129,11 +129,11 @@  discard block
 block discarded – undo
129 129
   function doquery($query, $table = '', $fetch = false, $skip_query_check = false) {
130 130
     global $numqueries, $debug, $sn_cache, $config;
131 131
 
132
-    if(!is_string($table)) {
132
+    if (!is_string($table)) {
133 133
       $fetch = $table;
134 134
     }
135 135
 
136
-    if(!$this->connected) {
136
+    if (!$this->connected) {
137 137
       $this->sn_db_connect();
138 138
     }
139 139
 
@@ -142,31 +142,31 @@  discard block
 block discarded – undo
142 142
     $skip_query_check or $this->security_query_check_bad_words($query);
143 143
 
144 144
     $sql = $query;
145
-    if(strpos($sql, '{{') !== false) {
145
+    if (strpos($sql, '{{') !== false) {
146 146
 //     foreach($sn_cache->tables as $tableName) {
147
-      foreach($this->table_list as $tableName) {
147
+      foreach ($this->table_list as $tableName) {
148 148
         $sql = str_replace("{{{$tableName}}}", $this->db_prefix . $tableName, $sql);
149 149
       }
150 150
     }
151 151
 
152
-    if($config->debug) {
152
+    if ($config->debug) {
153 153
       $numqueries++;
154 154
       $arr = debug_backtrace();
155
-      $file = end(explode('/',$arr[0]['file']));
155
+      $file = end(explode('/', $arr[0]['file']));
156 156
       $line = $arr[0]['line'];
157 157
       $debug->add("<tr><th>Query $numqueries: </th><th>$query</th><th>$file($line)</th><th>$table</th><th>$fetch</th></tr>");
158 158
     }
159 159
 
160
-    if(defined('DEBUG_SQL_COMMENT')) {
160
+    if (defined('DEBUG_SQL_COMMENT')) {
161 161
       $backtrace = debug_backtrace();
162 162
       $sql_comment = $debug->compact_backtrace($backtrace, defined('DEBUG_SQL_COMMENT_LONG'));
163 163
 
164 164
       $sql_commented = '/* ' . implode("<br />", $sql_comment) . '<br /> */ ' . preg_replace("/\s+/", ' ', $sql);
165
-      if(defined('DEBUG_SQL_ONLINE')) {
165
+      if (defined('DEBUG_SQL_ONLINE')) {
166 166
         $debug->warning($sql_commented, 'SQL Debug', LOG_DEBUG_SQL);
167 167
       }
168 168
 
169
-      if(defined('DEBUG_SQL_ERROR')) {
169
+      if (defined('DEBUG_SQL_ERROR')) {
170 170
         array_unshift($sql_comment, preg_replace("/\s+/", ' ', $sql));
171 171
         $debug->add_to_array($sql_comment);
172 172
         // $debug->add_to_array($sql_comment . preg_replace("/\s+/", ' ', $sql));
@@ -174,7 +174,7 @@  discard block
 block discarded – undo
174 174
       $sql = $sql_commented;
175 175
     }
176 176
 
177
-    $sqlquery = $this->db_sql_query($sql) or $debug->error(db_error()."<br />$sql<br />",'SQL Error');
177
+    $sqlquery = $this->db_sql_query($sql) or $debug->error(db_error() . "<br />$sql<br />", 'SQL Error');
178 178
 
179 179
     return $fetch ? $this->db_fetch($sqlquery) : $sqlquery;
180 180
   }
@@ -184,16 +184,16 @@  discard block
 block discarded – undo
184 184
     // TODO Заменить это на новый логгер
185 185
     global $config, $is_watching, $user, $debug;
186 186
 
187
-    if(!$is_watching && $config->game_watchlist_array && in_array($user['id'], $config->game_watchlist_array))
187
+    if (!$is_watching && $config->game_watchlist_array && in_array($user['id'], $config->game_watchlist_array))
188 188
     {
189
-      if(!preg_match('/^(select|commit|rollback|start transaction)/i', $query)) {
189
+      if (!preg_match('/^(select|commit|rollback|start transaction)/i', $query)) {
190 190
         $is_watching = true;
191 191
         $msg = "\$query = \"{$query}\"\n\r";
192
-        if(!empty($_POST)) {
193
-          $msg .= "\n\r" . dump($_POST,'$_POST');
192
+        if (!empty($_POST)) {
193
+          $msg .= "\n\r" . dump($_POST, '$_POST');
194 194
         }
195
-        if(!empty($_GET)) {
196
-          $msg .= "\n\r" . dump($_GET,'$_GET');
195
+        if (!empty($_GET)) {
196
+          $msg .= "\n\r" . dump($_GET, '$_GET');
197 197
         }
198 198
         $debug->warning($msg, "Watching user {$user['id']}", 399, array('base_dump' => true));
199 199
         $is_watching = false;
@@ -205,7 +205,7 @@  discard block
 block discarded – undo
205 205
   function security_query_check_bad_words($query) {
206 206
     global $user, $dm_change_legit, $mm_change_legit;
207 207
 
208
-    switch(true) {
208
+    switch (true) {
209 209
       case stripos($query, 'RUNCATE TABL') != false:
210 210
       case stripos($query, 'ROP TABL') != false:
211 211
       case stripos($query, 'ENAME TABL') != false:
@@ -216,33 +216,33 @@  discard block
 block discarded – undo
216 216
       case stripos($query, 'RPG_POINTS') != false && stripos(trim($query), 'UPDATE ') === 0 && !$dm_change_legit:
217 217
       case stripos($query, 'METAMATTER') != false && stripos(trim($query), 'UPDATE ') === 0 && !$mm_change_legit:
218 218
       case stripos($query, 'AUTHLEVEL') != false && $user['authlevel'] < 3 && stripos($query, 'SELECT') !== 0:
219
-        $report  = "Hacking attempt (".date("d.m.Y H:i:s")." - [".time()."]):\n";
219
+        $report  = "Hacking attempt (" . date("d.m.Y H:i:s") . " - [" . time() . "]):\n";
220 220
         $report .= ">Database Inforamation\n";
221
-        $report .= "\tID - ".$user['id']."\n";
222
-        $report .= "\tUser - ".$user['username']."\n";
223
-        $report .= "\tAuth level - ".$user['authlevel']."\n";
224
-        $report .= "\tAdmin Notes - ".$user['adminNotes']."\n";
225
-        $report .= "\tCurrent Planet - ".$user['current_planet']."\n";
226
-        $report .= "\tUser IP - ".$user['user_lastip']."\n";
227
-        $report .= "\tUser IP at Reg - ".$user['ip_at_reg']."\n";
228
-        $report .= "\tUser Agent- ".$_SERVER['HTTP_USER_AGENT']."\n";
229
-        $report .= "\tCurrent Page - ".$user['current_page']."\n";
230
-        $report .= "\tRegister Time - ".$user['register_time']."\n";
221
+        $report .= "\tID - " . $user['id'] . "\n";
222
+        $report .= "\tUser - " . $user['username'] . "\n";
223
+        $report .= "\tAuth level - " . $user['authlevel'] . "\n";
224
+        $report .= "\tAdmin Notes - " . $user['adminNotes'] . "\n";
225
+        $report .= "\tCurrent Planet - " . $user['current_planet'] . "\n";
226
+        $report .= "\tUser IP - " . $user['user_lastip'] . "\n";
227
+        $report .= "\tUser IP at Reg - " . $user['ip_at_reg'] . "\n";
228
+        $report .= "\tUser Agent- " . $_SERVER['HTTP_USER_AGENT'] . "\n";
229
+        $report .= "\tCurrent Page - " . $user['current_page'] . "\n";
230
+        $report .= "\tRegister Time - " . $user['register_time'] . "\n";
231 231
         $report .= "\n";
232 232
 
233 233
         $report .= ">Query Information\n";
234
-        $report .= "\tQuery - ".$query."\n";
234
+        $report .= "\tQuery - " . $query . "\n";
235 235
         $report .= "\n";
236 236
 
237 237
         $report .= ">\$_SERVER Information\n";
238
-        $report .= "\tIP - ".$_SERVER['REMOTE_ADDR']."\n";
239
-        $report .= "\tHost Name - ".$_SERVER['HTTP_HOST']."\n";
240
-        $report .= "\tUser Agent - ".$_SERVER['HTTP_USER_AGENT']."\n";
241
-        $report .= "\tRequest Method - ".$_SERVER['REQUEST_METHOD']."\n";
242
-        $report .= "\tCame From - ".$_SERVER['HTTP_REFERER']."\n";
243
-        $report .= "\tPage is - ".$_SERVER['SCRIPT_NAME']."\n";
244
-        $report .= "\tUses Port - ".$_SERVER['REMOTE_PORT']."\n";
245
-        $report .= "\tServer Protocol - ".$_SERVER['SERVER_PROTOCOL']."\n";
238
+        $report .= "\tIP - " . $_SERVER['REMOTE_ADDR'] . "\n";
239
+        $report .= "\tHost Name - " . $_SERVER['HTTP_HOST'] . "\n";
240
+        $report .= "\tUser Agent - " . $_SERVER['HTTP_USER_AGENT'] . "\n";
241
+        $report .= "\tRequest Method - " . $_SERVER['REQUEST_METHOD'] . "\n";
242
+        $report .= "\tCame From - " . $_SERVER['HTTP_REFERER'] . "\n";
243
+        $report .= "\tPage is - " . $_SERVER['SCRIPT_NAME'] . "\n";
244
+        $report .= "\tUses Port - " . $_SERVER['REMOTE_PORT'] . "\n";
245
+        $report .= "\tServer Protocol - " . $_SERVER['SERVER_PROTOCOL'] . "\n";
246 246
 
247 247
         $report .= "\n--------------------------------------------------------------------------------------------------\n";
248 248
 
@@ -262,11 +262,11 @@  discard block
 block discarded – undo
262 262
     $prefix_length = strlen($this->db_prefix);
263 263
 
264 264
     $tl = array();
265
-    while($row = $this->db_fetch($query)) {
266
-      foreach($row as $table_name) {
267
-        if(strpos($table_name, $this->db_prefix) === 0) {
265
+    while ($row = $this->db_fetch($query)) {
266
+      foreach ($row as $table_name) {
267
+        if (strpos($table_name, $this->db_prefix) === 0) {
268 268
           $table_name = substr($table_name, $prefix_length);
269
-        } elseif($prefixed_only) {
269
+        } elseif ($prefixed_only) {
270 270
           continue;
271 271
         }
272 272
         // $table_name = str_replace($db_prefix, '', $table_name);
Please login to merge, or discard this patch.
classes/db_mysql_v4.php 2 patches
Doc Comments   +3 added lines patch added patch discarded remove patch
@@ -55,6 +55,9 @@
 block discarded – undo
55 55
     return true;
56 56
   }
57 57
 
58
+  /**
59
+   * @param string $query_string
60
+   */
58 61
   function mysql_query($query_string) {
59 62
     return mysql_query($query_string, $this->link);
60 63
   }
Please login to merge, or discard this patch.
Spacing   +4 added lines, -4 removed lines patch added patch discarded remove patch
@@ -30,17 +30,17 @@  discard block
 block discarded – undo
30 30
 
31 31
     static $need_keys = array('server', 'user', 'pass', 'name', 'prefix');
32 32
 
33
-    if($this->connected) {
33
+    if ($this->connected) {
34 34
       return true;
35 35
     }
36 36
 
37
-    if(empty($settings) || !is_array($settings) || array_intersect($need_keys, array_keys($settings)) != $need_keys) {
37
+    if (empty($settings) || !is_array($settings) || array_intersect($need_keys, array_keys($settings)) != $need_keys) {
38 38
       $debug->error_fatal('There is missconfiguration in your config.php. Check it again', $this->mysql_error());
39 39
     }
40 40
 
41 41
     // TODO !!!!!! DEBUG -> error!!!!
42 42
     @$this->link = mysql_connect($settings['server'], $settings['user'], $settings['pass']);
43
-    if(!is_resource($this->link)) {
43
+    if (!is_resource($this->link)) {
44 44
       $debug->error_fatal('DB Error - cannot connect to server', $this->mysql_error());
45 45
     }
46 46
 
@@ -68,7 +68,7 @@  discard block
 block discarded – undo
68 68
     return mysql_real_escape_string($unescaped_string, $this->link);
69 69
   }
70 70
   function mysql_close_link() {
71
-    if($this->connected) {
71
+    if ($this->connected) {
72 72
       $this->connected = false;
73 73
       mysql_close($this->link);
74 74
       unset($this->link);
Please login to merge, or discard this patch.
classes/DBStaticPlanet.php 2 patches
Doc Comments   +14 added lines patch added patch discarded remove patch
@@ -21,11 +21,19 @@  discard block
 block discarded – undo
21 21
     return empty($result) ? null : $result;
22 22
   }
23 23
 
24
+  /**
25
+   * @param integer $galaxy
26
+   * @param integer $system
27
+   * @param integer $planet
28
+   */
24 29
   public static function db_planet_by_gspt_safe($galaxy, $system, $planet, $planet_type, $for_update = false, $fields = '*') {
25 30
     return classSupernova::db_get_record_list(LOC_PLANET,
26 31
       "{{planets}}.`galaxy` = {$galaxy} AND {{planets}}.`system` = {$system} AND {{planets}}.`planet` = {$planet} AND {{planets}}.`planet_type` = {$planet_type}", true);
27 32
   }
28 33
 
34
+  /**
35
+   * @param integer $planet_type
36
+   */
29 37
   public static function db_planet_by_gspt($galaxy, $system, $planet, $planet_type, $for_update = false, $fields = '*') {
30 38
     $galaxy = intval($galaxy);
31 39
     $system = intval($system);
@@ -120,6 +128,9 @@  discard block
 block discarded – undo
120 128
       "`id_owner` = '{$user_row['id']}' {$conditions} ORDER BY {$order_by}");
121 129
   }
122 130
 
131
+  /**
132
+   * @param integer $planet_id
133
+   */
123 134
   public static function db_planet_list_by_user_or_planet($user_id, $planet_id) {
124 135
     if(!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) {
125 136
       return false;
@@ -138,6 +149,9 @@  discard block
 block discarded – undo
138 149
     return classSupernova::db_upd_record_by_id(LOC_PLANET, $planet_id, $set);
139 150
   }
140 151
 
152
+  /**
153
+   * @param integer $ui_planet_type
154
+   */
141 155
   public static function db_planet_set_by_gspt($ui_galaxy, $ui_system, $ui_planet, $ui_planet_type = PT_ALL, $set) {
142 156
     if(!($set = trim($set))) {
143 157
       return false;
Please login to merge, or discard this patch.
Spacing   +12 added lines, -13 removed lines patch added patch discarded remove patch
@@ -39,8 +39,7 @@  discard block
 block discarded – undo
39 39
     $galaxy = isset($vector[$prefix . 'galaxy']) ? intval($vector[$prefix . 'galaxy']) : 0;
40 40
     $system = isset($vector[$prefix . 'system']) ? intval($vector[$prefix . 'system']) : 0;
41 41
     $planet = isset($vector[$prefix . 'planet']) ? intval($vector[$prefix . 'planet']) : 0;
42
-    $planet_type = isset($vector[$prefix . 'planet_type']) ? intval($vector[$prefix . 'planet_type']) :
43
-      (isset($vector[$prefix . 'type']) ? intval($vector[$prefix . 'type']) : 0);
42
+    $planet_type = isset($vector[$prefix . 'planet_type']) ? intval($vector[$prefix . 'planet_type']) : (isset($vector[$prefix . 'type']) ? intval($vector[$prefix . 'type']) : 0);
44 43
     $planet_type = $planet_type == PT_DEBRIS ? PT_PLANET : $planet_type;
45 44
 
46 45
     return DBStaticPlanet::db_planet_by_gspt_safe($galaxy, $system, $planet, $planet_type, $for_update, $fields);
@@ -61,7 +60,7 @@  discard block
 block discarded – undo
61 60
   }
62 61
 
63 62
   public static function db_planet_by_parent($parent_id, $for_update = false, $fields = '*') {
64
-    if(!($parent_id = idval($parent_id))) {
63
+    if (!($parent_id = idval($parent_id))) {
65 64
       return false;
66 65
     }
67 66
 
@@ -70,7 +69,7 @@  discard block
 block discarded – undo
70 69
   }
71 70
 
72 71
   public static function db_planet_by_id_and_owner($planet_id, $owner_id, $for_update = false, $fields = '*') {
73
-    if(!($planet_id = idval($planet_id)) || !($owner_id = idval($owner_id))) {
72
+    if (!($planet_id = idval($planet_id)) || !($owner_id = idval($owner_id))) {
74 73
       return false;
75 74
     }
76 75
     return classSupernova::db_get_record_list(LOC_PLANET,
@@ -79,7 +78,7 @@  discard block
 block discarded – undo
79 78
 
80 79
 
81 80
   public static function db_planet_list_moon_other($user_id, $this_moon_id) {
82
-    if(!($user_id = idval($user_id)) || !($this_moon_id = idval($this_moon_id))) {
81
+    if (!($user_id = idval($user_id)) || !($this_moon_id = idval($this_moon_id))) {
83 82
       return false;
84 83
     }
85 84
     return classSupernova::db_get_record_list(LOC_PLANET,
@@ -94,7 +93,7 @@  discard block
 block discarded – undo
94 93
   }
95 94
 
96 95
   public static function db_planet_list_sorted($user_row, $skip_planet_id = false, $field_list = '', $conditions = '') {
97
-    if(!is_array($user_row)) {
96
+    if (!is_array($user_row)) {
98 97
       return false;
99 98
     }
100 99
     $conditions .= $skip_planet_id ? " AND `id` <> {$skip_planet_id} " : '';
@@ -115,7 +114,7 @@  discard block
 block discarded – undo
115 114
   }
116 115
 
117 116
   public static function db_planet_list_by_user_or_planet($user_id, $planet_id) {
118
-    if(!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) {
117
+    if (!($user_id = idval($user_id)) && !($planet_id = idval($planet_id))) {
119 118
       return false;
120 119
     }
121 120
 
@@ -124,14 +123,14 @@  discard block
 block discarded – undo
124 123
   }
125 124
 
126 125
   public static function db_planet_set_by_id($planet_id, $set) {
127
-    if(!($planet_id = idval($planet_id))) {
126
+    if (!($planet_id = idval($planet_id))) {
128 127
       return false;
129 128
     }
130 129
     return classSupernova::db_upd_record_by_id(LOC_PLANET, $planet_id, $set);
131 130
   }
132 131
 
133 132
   public static function db_planet_set_by_gspt($ui_galaxy, $ui_system, $ui_planet, $ui_planet_type = PT_ALL, $set) {
134
-    if(!($set = trim($set))) {
133
+    if (!($set = trim($set))) {
135 134
       return false;
136 135
     }
137 136
 
@@ -144,14 +143,14 @@  discard block
 block discarded – undo
144 143
   }
145 144
 
146 145
   public static function db_planet_set_by_parent($ui_parent_id, $ss_set) {
147
-    if(!($si_parent_id = idval($ui_parent_id)) || !($ss_set = trim($ss_set))) {
146
+    if (!($si_parent_id = idval($ui_parent_id)) || !($ss_set = trim($ss_set))) {
148 147
       return false;
149 148
     }
150 149
     return classSupernova::db_upd_record_list(LOC_PLANET, "`parent_planet` = {$si_parent_id}", $ss_set);
151 150
   }
152 151
 
153 152
   public static function db_planet_set_by_owner($ui_owner_id, $ss_set) {
154
-    if(!($si_owner_id = idval($ui_owner_id)) || !($ss_set = trim($ss_set))) {
153
+    if (!($si_owner_id = idval($ui_owner_id)) || !($ss_set = trim($ss_set))) {
155 154
       return false;
156 155
     }
157 156
     return classSupernova::db_upd_record_list(LOC_PLANET, "`id_owner` = {$si_owner_id}", $ss_set);
@@ -159,7 +158,7 @@  discard block
 block discarded – undo
159 158
 
160 159
 
161 160
   public static function db_planet_delete_by_id($planet_id) {
162
-    if(!($planet_id = idval($planet_id))) {
161
+    if (!($planet_id = idval($planet_id))) {
163 162
       return false;
164 163
     }
165 164
     classSupernova::db_del_record_by_id(LOC_PLANET, $planet_id);
@@ -169,7 +168,7 @@  discard block
 block discarded – undo
169 168
   }
170 169
 
171 170
   public static function db_planet_list_delete_by_owner($ui_owner_id) {
172
-    if(!($si_owner_id = idval($ui_owner_id))) {
171
+    if (!($si_owner_id = idval($ui_owner_id))) {
173 172
       return false;
174 173
     }
175 174
     classSupernova::db_del_record_list(LOC_PLANET, "`id_owner` = {$si_owner_id}");
Please login to merge, or discard this patch.
classes/DBStaticUnit.php 1 patch
Doc Comments   +6 added lines patch added patch discarded remove patch
@@ -56,6 +56,9 @@  discard block
 block discarded – undo
56 56
     WHERE unit_player_id = {$user_id} AND unit_location_type = " . LOC_PLANET . " AND unit_level > 0 AND unit_snid IN (" . STRUC_LABORATORY . ", " . STRUC_LABORATORY_NANO . ");");
57 57
   }
58 58
 
59
+  /**
60
+   * @param string $set
61
+   */
59 62
   public static function db_unit_set_by_id($unit_id, $set) {
60 63
     return classSupernova::db_upd_record_by_id(LOC_UNIT, $unit_id, $set);
61 64
   }
@@ -69,6 +72,9 @@  discard block
 block discarded – undo
69 72
     return classSupernova::db_ins_record(LOC_UNIT, $set);
70 73
   }
71 74
 
75
+  /**
76
+   * @param integer $unit_location_type
77
+   */
72 78
   public static function db_unit_list_delete($user_id = 0, $unit_location_type, $unit_location_id = 0, $unit_snid = 0) {
73 79
     return classSupernova::db_del_record_list(LOC_UNIT,
74 80
       "`unit_location_type` = {$unit_location_type}" .
Please login to merge, or discard this patch.
classes/Vector.php 2 patches
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -10,8 +10,8 @@
 block discarded – undo
10 10
   /**
11 11
    * UniverseVector constructor.
12 12
    *
13
-   * @param int|string       $galaxy
14
-   * @param int|Vector|array $system
13
+   * @param integer       $galaxy
14
+   * @param integer $system
15 15
    * @param int              $planet
16 16
    * @param int              $type
17 17
    */
Please login to merge, or discard this patch.
Spacing   +6 added lines, -6 removed lines patch added patch discarded remove patch
@@ -13,7 +13,7 @@  discard block
 block discarded – undo
13 13
   public $type = PT_NONE;
14 14
 
15 15
   public static function _staticInit() {
16
-    if(static::$_isStaticInit) {
16
+    if (static::$_isStaticInit) {
17 17
       return;
18 18
     }
19 19
     static::$knownGalaxies = intval(classSupernova::$config->game_maxGalaxy);
@@ -33,9 +33,9 @@  discard block
 block discarded – undo
33 33
   public function __construct($galaxy = 0, $system = 0, $planet = 0, $type = PT_NONE) {
34 34
     // static::_staticInit();
35 35
 
36
-    if(is_string($galaxy) && $galaxy == VECTOR_READ_VECTOR && is_object($system) && $system instanceof Vector) {
36
+    if (is_string($galaxy) && $galaxy == VECTOR_READ_VECTOR && is_object($system) && $system instanceof Vector) {
37 37
       $this->readFromVector($system);
38
-    } elseif(is_string($galaxy) && $galaxy == VECTOR_READ_PARAMS && is_array($system)) {
38
+    } elseif (is_string($galaxy) && $galaxy == VECTOR_READ_PARAMS && is_array($system)) {
39 39
       $this->readFromParamFleets($system);
40 40
     } else {
41 41
       $this->galaxy = intval($galaxy);
@@ -74,11 +74,11 @@  discard block
 block discarded – undo
74 74
    * @param Vector $vector
75 75
    */
76 76
   public function distance($vector) {
77
-    if($this->galaxy != $vector->galaxy) {
77
+    if ($this->galaxy != $vector->galaxy) {
78 78
       $distance = abs($this->galaxy - $vector->galaxy) * classSupernova::$config->uni_galaxy_distance;
79
-    } elseif($this->system != $vector->system) {
79
+    } elseif ($this->system != $vector->system) {
80 80
       $distance = abs($this->system - $vector->system) * 5 * 19 + 2700;
81
-    } elseif($this->planet != $vector->planet) {
81
+    } elseif ($this->planet != $vector->planet) {
82 82
       $distance = abs($this->planet - $vector->planet) * 5 + 1000;
83 83
       // TODO - uncomment
84 84
 //    } elseif($this->type != PT_NONE && $vector->type != PT_NONE && $this->type == $vector->type) {
Please login to merge, or discard this patch.
classes/Vector/Vector.php 1 patch
Doc Comments   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -70,8 +70,8 @@
 block discarded – undo
70 70
   /**
71 71
    * Vector constructor.
72 72
    *
73
-   * @param int|string       $galaxy
74
-   * @param int|Vector|array $system
73
+   * @param integer       $galaxy
74
+   * @param integer $system
75 75
    * @param int              $planet
76 76
    * @param int              $type
77 77
    */
Please login to merge, or discard this patch.