Completed
Push — work-fleets ( d7065d...1ee481 )
by SuperNova.WS
08:22
created

DBStaticMessages::messageWrite()   F

Complexity

Conditions 13
Paths 2304

Size

Total Lines 72
Code Lines 44

Duplication

Lines 6
Ratio 8.33 %

Code Coverage

Tests 0
CRAP Score 182

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 13
eloc 44
c 1
b 0
f 0
nc 2304
nop 1
dl 6
loc 72
ccs 0
cts 56
cp 0
crap 182
rs 2.3514

How to fix   Long Method    Complexity   

Long Method

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

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

Commonly applied refactorings include:

1
<?php
2
3
namespace DBStatic;
4
5
use classLocale;
6
use classSupernova;
7
use DBStatic\DBStaticUser;
8
use mysqli_result;
9
use template;
10
11
class DBStaticMessages {
12
  public static $snMessageClassList = array(
13
    MSG_TYPE_NEW       => array(
14
      'name'       => 'new_message',
15
      'switchable' => false,
16
      'email'      => false,
17
    ),
18
    MSG_TYPE_ADMIN     => array(
19
      'name'       => 'msg_admin',
20
      'switchable' => false,
21
      'email'      => true,
22
    ),
23
    MSG_TYPE_PLAYER    => array(
24
      'name'       => 'mnl_joueur',
25
      'switchable' => false,
26
      'email'      => true,
27
    ),
28
    MSG_TYPE_ALLIANCE  => array(
29
      'name'       => 'mnl_alliance',
30
      'switchable' => false,
31
      'email'      => true,
32
    ),
33
    MSG_TYPE_SPY       => array(
34
      'name'       => 'mnl_spy',
35
      'switchable' => true,
36
      'email'      => true,
37
    ),
38
    MSG_TYPE_COMBAT    => array(
39
      'name'       => 'mnl_attaque',
40
      'switchable' => true,
41
      'email'      => true,
42
    ),
43
    MSG_TYPE_TRANSPORT => array(
44
      'name'       => 'mnl_transport',
45
      'switchable' => true,
46
      'email'      => true,
47
    ),
48
    MSG_TYPE_RECYCLE   => array(
49
      'name'       => 'mnl_exploit',
50
      'switchable' => true,
51
      'email'      => true,
52
    ),
53
    MSG_TYPE_EXPLORE   => array(
54
      'name'       => 'mnl_expedition',
55
      'switchable' => true,
56
      'email'      => true,
57
    ),
58
    //     97 => 'mnl_general',
0 ignored issues
show
Unused Code Comprehensibility introduced by
58% of this comment could be valid code. Did you maybe forget this after debugging?

Sometimes obsolete code just ends up commented out instead of removed. In this case it is better to remove the code once you have checked you do not need it.

The code might also have been commented out for debugging purposes. In this case it is vital that someone uncomments it again or your project may behave in very unexpected ways in production.

This check looks for comments that seem to be mostly valid code and reports them.

Loading history...
59
    MSG_TYPE_QUE       => array(
60
      'name'       => 'mnl_buildlist',
61
      'switchable' => true,
62
      'email'      => true,
63
    ),
64
    MSG_TYPE_OUTBOX    => array(
65
      'name'       => 'mnl_outbox',
66
      'switchable' => false,
67
      'email'      => false,
68
    ),
69
  );
70
  public static $snMessageGroup = array(
71
    'switchable' => array(MSG_TYPE_SPY, MSG_TYPE_COMBAT, MSG_TYPE_RECYCLE, MSG_TYPE_TRANSPORT, MSG_TYPE_EXPLORE, MSG_TYPE_QUE),
72
    'email'      => array(MSG_TYPE_SPY, MSG_TYPE_PLAYER, MSG_TYPE_ALLIANCE, MSG_TYPE_COMBAT, MSG_TYPE_RECYCLE, MSG_TYPE_TRANSPORT,
73
      MSG_TYPE_ADMIN, MSG_TYPE_EXPLORE, MSG_TYPE_QUE),
74
  );
75
76
  /**
77
   * @param mixed|array $owners
78
   * @param integer     $sender
79
   * @param integer     $timestamp
80
   * @param integer     $message_type
81
   * @param string      $from_unsafe
82
   * @param string      $subject_unsafe
83
   * @param string      $text_unsafe
84
   * @param bool        $force
85
   */
86
  public static function msg_send_simple_message($owners, $sender, $timestamp, $message_type, $from_unsafe, $subject_unsafe, $text_unsafe, $force = false) {
87
    global $user;
88
89
    if (!$owners) {
90
      return;
91
    }
92
93
    $timestamp = $timestamp ? $timestamp : SN_TIME_NOW;
94
    $sender = intval($sender);
95
    if (!is_array($owners)) {
96
      $owners = array($owners);
97
    }
98
99
    // TODO - check for valid message_type ?
100
    $message_class = static::$snMessageClassList[$message_type];
101
    $message_class_name = $message_class['name'];
102
103
    $message_class_name_total = static::$snMessageClassList[MSG_TYPE_NEW]['name'];
104
105
    if ($owners[0] == '*') {
106
      if ($user['authlevel'] < 3) {
107
        return false;
108
      }
109
      // TODO Добавить $timestamp - рассылка может быть и отсроченной
110
      // TODO Добавить $sender - рассылка может быть и от кого-то
111
      static::db_message_insert_all($message_type, $from_unsafe, $subject_unsafe, $text_unsafe);
112
      $owners = array();
113
    } else {
114
      $insert_values = array();
115
      foreach ($owners as $owner) {
116
        if ($user['id'] != $owner) {
117
          $owner_row = DBStaticUser::db_user_by_id($owner);
118
        } else {
119
          $owner_row = $user;
120
        }
121
        sys_user_options_unpack($owner_row);
122
123
        if ($force || !$message_class['switchable'] || $owner_row["opt_{$message_class_name}"]) {
124
          $insert_values[] = "('" . idval($owner) . "', '{$sender}', '{$timestamp}', '{$message_type}', '" . db_escape($from_unsafe) . "', '" . db_escape($subject_unsafe) . "', '" . db_escape($text_unsafe) . "')";
125
        }
126
127
        // TODO - allow sending HTML email only from admin
128
        if ($message_class['email'] && classSupernova::$config->game_email_pm && $owner_row["opt_email_{$message_class_name}"]) {
129
          $text_unescaped = str_replace(array('\\r\\n', '\\n', "\r\n", "\n"), "<br />", $text_unsafe);
130
          @$result = mymail($owner_row['email'], $subject_unsafe, $text_unescaped, '', true);
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
131
        }
132
      }
133
134
      if (empty($insert_values)) {
135
        return;
136
      }
137
138
      classSupernova::$db->doInsertValuesDeprecated(
0 ignored issues
show
Deprecated Code introduced by
The method db_mysql::doInsertValuesDeprecated() has been deprecated.

This method has been deprecated.

Loading history...
139
        TABLE_MESSAGES,
140
        array(
141
          'message_owner',
142
          'message_sender',
143
          'message_time',
144
          'message_type',
145
          'message_from',
146
          'message_subject',
147
          'message_text',
148
        ),
149
        $insert_values
150
      );
151
    }
152
    if (!empty($owners)) {
153
      // Danger - 'cause if IN clause
154
      classSupernova::$gc->cacheOperator->db_upd_record_list_DANGER(
0 ignored issues
show
Bug introduced by
The method db_upd_record_list_DANGER does only exist in SnDbCachedOperator, but not in Closure.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
155
        LOC_USER,
156
        array(),
157
        array(
158
          $message_class_name       => +1,
159
          $message_class_name_total => +1,
160
        ),
161
        array(),
162
        array(
163
          // TODO DANGER
164
          '`id` IN (' . implode(',', $owners) . ')',
165
        )
166
      );
167
    }
168
169
    if (in_array($user['id'], $owners) || $owners[0] == '*') {
170
      $user[$message_class_name]++;
171
      $user[$message_class_name_total]++;
172
    }
173
  }
174
175
  public static function msg_ali_send($message, $subject, $ally_rank_id = 0, $ally_id = 0) {
176
    global $user;
177
178
    $ally_id = $ally_id ? $ally_id : $user['ally_id'];
179
180
    $sendList = array();
181
    $list = '';
182
    $query = DBStaticUser::db_user_list(
183
      "ally_id = '{$ally_id}'" . ($ally_rank_id >= 0 ? " AND ally_rank_id = {$ally_rank_id}" : ''),
184
      false, 'id, username');
185
    foreach ($query as $u) {
186
      $sendList[] = $u['id'];
187
      $list .= "<br>{$u['username']} ";
188
    }
189
190
    static::msg_send_simple_message($sendList, $user['id'], SN_TIME_NOW, MSG_TYPE_ALLIANCE, $user['username'], $subject, $message);
191
192
    return $list;
193
  }
194
195
196
  /**
197
   * @param mixed|array $owners
198
   * @param string      $subject
199
   * @param string      $text
200
   * @param bool        $force
201
   */
202
  public static function msgSendFromAdmin($owners, $subject, $text, $force = false) {
203
    static::msg_send_simple_message($owners, 0, SN_TIME_NOW, MSG_TYPE_ADMIN, classLocale::$lang['sys_administration'], $subject, $text, $force);
204
  }
205
206
  /**
207
   * @param        $senderPlayerId
208
   * @param        $senderPlayerNameAndCoordinates
209
   * @param mixed  $recipientId
210
   * @param string $subject
211
   * @param string $text
212
   */
213
  public static function msgSendFromPlayer($senderPlayerId, $senderPlayerNameAndCoordinates, $recipientId, $subject, $text) {
214
    static::msg_send_simple_message(
215
      $recipientId, $senderPlayerId, SN_TIME_NOW, MSG_TYPE_PLAYER, $senderPlayerNameAndCoordinates, $subject, $text
216
    );
217
  }
218
219
  /**
220
   * @param \Buddy\BuddyParams $params
221
   * @param string             $localeSubjectId
222
   * @param string             $localeTextId
223
   */
224
  public static function msgSendFromPlayerBuddy($params, $localeSubjectId, $localeTextId) {
225
    static::msgSendFromPlayer(
226
      $params->playerId,
227
      $params->playerNameAndCoordinates,
228
      $params->newFriendIdSafe,
229
      classLocale::$lang[$localeSubjectId],
230
      sprintf(classLocale::$lang[$localeTextId], $params->playerName)
231
    );
232
  }
233
234
235
  /**
236
   * @param array $player
237
   *
238
   * @return template
239
   */
240
  public static function messageWrite($player) {
241
    $error_list = array();
242
243
    $recipientId = sys_get_param_id('id');
244
    $recipient_name_unescaped = sys_get_param_str_unsafe('recipient_name');
245
    $subject_unsafe = sys_get_param_str_unsafe('subject');
246
247
    if (!empty($recipientId)) {
248
      $recipient_row = DBStaticUser::db_user_by_id($recipientId);
249
    }
250
251
    if (empty($recipient_row)) {
252
      $recipient_row = DBStaticUser::db_user_by_username($recipient_name_unescaped);
253
    }
254
255
    if (!empty($recipient_row)) {
256
      $recipientId = $recipient_row['id'];
257
      $recipient_name_unescaped = $recipient_row['username'];
258
    } else {
259
      $recipientId = 0;
260
      $recipient_name_unescaped = '';
261
    }
262
263 View Code Duplication
    if ($recipientId == $player['id']) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
264
      $error_list[] = array('MESSAGE' => classLocale::$lang['msg_err_self_send'], 'STATUS' => ERR_ERROR);
265
    }
266
267
    $re = 0;
268
    while (strpos($subject_unsafe, classLocale::$lang['msg_answer_prefix']) !== false) {
269
      $subject_unsafe = substr($subject_unsafe, strlen(classLocale::$lang['msg_answer_prefix']));
270
      $re++;
271
    }
272
    $re ? $subject_unsafe = classLocale::$lang['msg_answer_prefix'] . $subject_unsafe : false;
273
274
    $subject_unsafe = $subject_unsafe ? $subject_unsafe : classLocale::$lang['msg_subject_default'];
275
276
    $textUnsafe = sys_get_param_str_unsafe('text');
277
    if (sys_get_param_str('msg_send')) {
278 View Code Duplication
      if (!$recipientId) {
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated across your project.

Duplicated code is one of the most pungent code smells. If you need to duplicate the same code in three or more different places, we strongly encourage you to look into extracting the code into a single class or operation.

You can also find more detailed suggestions in the “Code” section of your repository.

Loading history...
279
        $error_list[] = array('MESSAGE' => classLocale::$lang['msg_err_player_not_found'], 'STATUS' => ERR_ERROR);
280
      }
281
282
      if (empty($textUnsafe)) {
283
        $error_list[] = array('MESSAGE' => classLocale::$lang['msg_err_no_text'], 'STATUS' => ERR_ERROR);
284
      }
285
286
      if (empty($error_list)) {
287
        $error_list[] = array('MESSAGE' => classLocale::$lang['msg_not_message_sent'], 'STATUS' => ERR_NONE);
288
289
        static::msgSendFromPlayer($player['id'], DBStaticUser::renderNameAndCoordinates($player), $recipientId, $subject_unsafe, $textUnsafe);
290
291
        $textUnsafe = '';
292
      }
293
    }
294
295
    $template = gettemplate('msg_message_compose', true);
296
    $template->assign_vars(array(
297
      'RECIPIENT_ID'   => $recipientId,
298
      'RECIPIENT_NAME' => htmlspecialchars($recipient_name_unescaped),
299
      'SUBJECT'        => htmlspecialchars($subject_unsafe),
300
      'TEXT'           => htmlspecialchars($textUnsafe),
301
    ));
302
303
    foreach ($error_list as $error_message) {
304
      $template->assign_block_vars('result', $error_message);
305
    }
306
307
    $message_query = static::db_message_list_get_last_20($player, $recipientId);
308
    static::messageRenderList(MSG_TYPE_OUTBOX, $template, $message_query);
309
310
    return $template;
311
  }
312
313
314
  /**
315
   * @param array  $player
316
   * @param string $current_class
317
   */
318
  public static function messageDelete($player, $current_class) {
319
    $message_range = sys_get_param_str('message_range');
320
    $marked_message_list = sys_get_param('mark', array());
0 ignored issues
show
Documentation introduced by
array() is of type array, but the function expects a string.

It seems like the type of the argument is not accepted by the function/method which you are calling.

In some cases, in particular if PHP’s automatic type-juggling kicks in this might be fine. In other cases, however this might be a bug.

We suggest to add an explicit type cast like in the following example:

function acceptsInteger($int) { }

$x = '123'; // string "123"

// Instead of
acceptsInteger($x);

// we recommend to use
acceptsInteger((integer) $x);
Loading history...
321
322
    $deleteAll = false;
323
    $where = array();
324
    $whereDanger = array();
325
    $not = '';
326
    switch ($message_range) {
327
      case 'unchecked':
328
        $not = 'NOT';
329
      case 'checked':
330
        if ($message_range == 'checked' && empty($marked_message_list)) {
331
          break;
332
        }
333
334
        foreach ($marked_message_list as &$messageId) {
0 ignored issues
show
Bug introduced by
The expression $marked_message_list of type string|array is not guaranteed to be traversable. How about adding an additional type check?

There are different options of fixing this problem.

  1. If you want to be on the safe side, you can add an additional type-check:

    $collection = json_decode($data, true);
    if ( ! is_array($collection)) {
        throw new \RuntimeException('$collection must be an array.');
    }
    
    foreach ($collection as $item) { /** ... */ }
    
  2. If you are sure that the expression is traversable, you might want to add a doc comment cast to improve IDE auto-completion and static analysis:

    /** @var array $collection */
    $collection = json_decode($data, true);
    
    foreach ($collection as $item) { /** .. */ }
    
  3. Mark the issue as a false-positive: Just hover the remove button, in the top-right corner of this issue for more options.

Loading history...
335
          $messageId = idval($messageId);
336
        }
337
338
        if ($query_add = implode(',', $marked_message_list)) {
339
          $whereDanger[] = "`message_id` {$not} IN ({$query_add})";
340
        }
341
342
      case 'class':
343
        if ($current_class != MSG_TYPE_OUTBOX && $current_class != MSG_TYPE_NEW) {
344
          $where['message_type'] = $current_class;
345
        }
346
      case 'all':
347
        $deleteAll = true;
348
      break;
349
    }
350
351
    if ($deleteAll || !empty($where)) {
352
      $where['message_owner'] = $player['id'];
353
      // Malformed $where
354
      classSupernova::$gc->db->doDeleteDanger(
0 ignored issues
show
Bug introduced by
The method doDeleteDanger does only exist in db_mysql, but not in Closure.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
355
        TABLE_MESSAGES,
356
        $where,
357
        $whereDanger
358
      );
359
    }
360
  }
361
362
  /**
363
   * @param array $player
364
   * @param int   $current_class
365
   *
366
   * @return template
367
   */
368
  public static function messageShow(&$player, $current_class) {
369
    $SubUpdateQrySet = array();
370
    $SubUpdateQryAdjust = array();
371
    $SubSelectQry = '';
372
    if ($current_class == MSG_TYPE_OUTBOX) {
373
      $message_query = static::db_message_list_outbox_by_user_id($player['id']);
374
    } else {
375
      if ($current_class == MSG_TYPE_NEW) {
376
        foreach (static::$snMessageClassList as $message_class_id => $message_class) {
377
          if ($message_class_id != MSG_TYPE_OUTBOX) {
378
            $SubUpdateQrySet[$message_class['name']] = 0;
379
            $player[$message_class['name']] = 0;
380
          }
381
        }
382
      } else {
383
        $classFieldNameCurrent = static::$snMessageClassList[$current_class]['name'];
384
        $classFieldNameNew = static::$snMessageClassList[MSG_TYPE_NEW]['name'];
385
        $SubUpdateQrySet[$classFieldNameCurrent] = 0;
386
        $SubUpdateQryAdjust[$classFieldNameNew] = -$player[$classFieldNameCurrent];
387
        $SubSelectQry = "AND `message_type` = '{$current_class}'";
388
389
        $player[static::$snMessageClassList[MSG_TYPE_NEW]['name']] -= $player[static::$snMessageClassList[$current_class]['name']];
390
        $player[static::$snMessageClassList[$current_class]['name']] = 0;
391
      }
392
393
      DBStaticUser::db_user_set_by_id($player['id'], $SubUpdateQrySet);
394
      DBStaticUser::db_user_adjust_by_id($player['id'], $SubUpdateQryAdjust);
395
      $message_query = static::db_message_list_by_owner_and_string($player, $SubSelectQry);
396
    }
397
398
    if (sys_get_param_int('return')) {
399
      header('Location: messages.php');
400
      die();
401
    }
402
403
    $template = gettemplate('msg_message_list', true);
404
    static::messageRenderList($current_class, $template, $message_query);
405
406
    $current_class_text = classLocale::$lang['msg_class'][$current_class];
407
408
    $template->assign_vars(array(
409
      "MESSAGE_CLASS"      => $current_class,
410
      "MESSAGE_CLASS_TEXT" => $current_class_text,
411
    ));
412
413
    return $template;
414
  }
415
416
417
  /**
418
   * @param int      $current_class
419
   * @param template $template
420
   * @param          $message_query
421
   */
422
  public function messageRenderList($current_class, $template, $message_query) {
423
    while ($message_row = db_fetch($message_query)) {
424
      $template->assign_block_vars('messages', array(
425
        'ID'   => $message_row['message_id'],
426
        'DATE' => date(FMT_DATE_TIME, $message_row['message_time'] + SN_CLIENT_TIME_DIFF),
427
        'FROM' => htmlspecialchars($message_row['message_from']),
428
        'SUBJ' => htmlspecialchars($message_row['message_subject']),
429
        'TEXT' => in_array($message_row['message_type'], array(MSG_TYPE_PLAYER, MSG_TYPE_ALLIANCE)) && $message_row['message_sender']
430
          ? nl2br(htmlspecialchars($message_row['message_text']))
431
          : nl2br($message_row['message_text']),
432
433
        'FROM_ID'        => $message_row['message_sender'],
434
        'SUBJ_SANITIZED' => htmlspecialchars($message_row['message_subject']),
435
        'STYLE'          => $current_class == MSG_TYPE_OUTBOX
436
          ? static::$snMessageClassList[MSG_TYPE_OUTBOX]['name']
437
          : static::$snMessageClassList[$message_row['message_type']]['name'],
438
      ));
439
    }
440
  }
441
442
443
// Messages *************************************************************************************************************
444
  public static function db_message_list_get_last_20($user, $recipient_id) {
445
    return classSupernova::$db->doSelect(
446
      "SELECT * FROM {{messages}}
447
        WHERE
448
          `message_type` = '" . MSG_TYPE_PLAYER . "' AND
449
          ((`message_owner` = '{$user['id']}' AND `message_sender` = '{$recipient_id}')
450
          OR
451
          (`message_sender` = '{$user['id']}' AND `message_owner` = '{$recipient_id}')) ORDER BY `message_time` DESC LIMIT 20;");
452
  }
453
454
  public static function db_message_list_outbox_by_user_id($user_id) {
455
    $user_id = idval($user_id);
456
    if (empty($user_id)) {
457
      return false;
458
    }
459
460
    return classSupernova::$db->doSelect("SELECT {{messages}}.message_id, {{messages}}.message_owner, {{users}}.id AS message_sender, {{messages}}.message_time,
461
          {{messages}}.message_type, {{users}}.username AS message_from, {{messages}}.message_subject, {{messages}}.message_text
462
       FROM
463
         {{messages}} LEFT JOIN {{users}} ON {{users}}.id = {{messages}}.message_owner WHERE `message_sender` = '{$user_id}' AND `message_type` = 1
464
       ORDER BY `message_time` DESC;");
465
  }
466
467
  public static function db_message_list_by_owner_and_string($user, $SubSelectQry) {
468
    return classSupernova::$db->doSelect("SELECT * FROM {{messages}} WHERE `message_owner` = '{$user['id']}' {$SubSelectQry} ORDER BY `message_time` DESC;");
469
  }
470
471
  public static function db_message_count_by_owner_and_type($user) {
472
    return classSupernova::$db->doSelect("SELECT message_owner, message_type, COUNT(message_owner) AS message_count FROM {{messages}} WHERE `message_owner` = {$user['id']} GROUP BY message_owner, message_type ORDER BY message_owner ASC, message_type;");
473
  }
474
475
  public static function db_message_count_outbox($user) {
476
    $row = classSupernova::$db->doSelectFetch("SELECT COUNT(message_sender) AS message_count FROM {{messages}} WHERE `message_sender` = '{$user['id']}' AND message_type = 1 GROUP BY message_sender;");
477
478
    return intval($row['message_count']);
479
  }
480
481
  public static function db_message_list_admin_by_type($int_type_selected, $StartRec) {
482
    return classSupernova::$db->doSelect("SELECT
483
  message_id as `ID`,
484
  message_from as `FROM`,
485
  message_owner as `OWNER_ID`,
486
  u.username as `OWNER_NAME`,
487
  message_text as `TEXT`,
488
  FROM_UNIXTIME(message_time) as `TIME`
489
FROM
490
  {{messages}} AS m
491
  LEFT JOIN {{users}} AS u ON u.id = m.message_owner " .
492
      ($int_type_selected >= 0 ? "WHERE `message_type` = {$int_type_selected} " : '') .
493
      "ORDER BY
494
  `message_id` DESC
495
LIMIT
496
  {$StartRec}, 25;");
497
  }
498
499
  public static function db_message_insert_all($message_type, $from_unsafe, $subject_unsafe, $text_unsafe) {
500
    $message_type_safe = intval($message_type);
501
    $from_safe = db_escape($from_unsafe);
502
    $subject_safe = db_escape($subject_unsafe);
503
    $text_safe = db_escape($text_unsafe);
504
505
    return classSupernova::$db->doInsertComplex('INSERT INTO {{messages}} (`message_owner`, `message_sender`, `message_time`, `message_type`, `message_from`, `message_subject`, `message_text`) ' .
506
      "SELECT `id`, 0, unix_timestamp(now()), {$message_type_safe}, '{$from_safe}', '{$subject_safe}', '{$text_safe}' FROM {{users}}");
507
  }
508
509
  /**
510
   * @param $int_type_selected
511
   *
512
   * @return array|bool|mysqli_result|null
513
   */
514
  public static function db_message_count_by_type($int_type_selected) {
515
    $page_max = classSupernova::$db->doSelectFetch('SELECT COUNT(*) AS `max` FROM `{{messages}}`' . ($int_type_selected >= 0 ? " WHERE `message_type` = {$int_type_selected};" : ''));
516
517
    return $page_max;
518
  }
519
520
  /**
521
   * @param string $message_delete
522
   */
523
  public static function db_message_list_delete_set($message_delete) {
524
    classSupernova::$db->doDeleteDanger(
0 ignored issues
show
Deprecated Code introduced by
The method db_mysql::doDeleteDanger() has been deprecated.

This method has been deprecated.

Loading history...
525
      TABLE_MESSAGES,
526
      array(),
527
      array(
528
        "`message_id` IN ({$message_delete})",
529
      )
530
    );
531
  }
532
533
  public static function db_message_delete_by_id($messageId) {
534
    classSupernova::$gc->db->doDeleteRow(
0 ignored issues
show
Bug introduced by
The method doDeleteRow does only exist in db_mysql, but not in Closure.

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

Let’s take a look at an example:

class A
{
    public function foo() { }
}

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

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

Available Fixes

  1. Add an additional type-check:

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

    function someFunction(B $x) { /** ... */ }
    
Loading history...
535
      TABLE_MESSAGES,
536
      array(
537
        'message_id' => $messageId,
538
      )
539
    );
540
  }
541
542
543
  /**
544
   * @param $delete_date
545
   * @param $int_type_selected
546
   */
547
  public static function db_message_list_delete_by_date($delete_date, $int_type_selected) {
548
    $where = array();
549
    if ($int_type_selected >= 0) {
550
      $where['message_type'] = $int_type_selected;
551
    }
552
    classSupernova::$db->doDeleteDanger(
0 ignored issues
show
Deprecated Code introduced by
The method db_mysql::doDeleteDanger() has been deprecated.

This method has been deprecated.

Loading history...
553
      TABLE_MESSAGES,
554
      $where,
555
      array(
556
        "message_time <= UNIX_TIMESTAMP('{$delete_date}')"
557
      )
558
    );
559
  }
560
561
}
562