Completed
Push — trunk ( 8e3c77...4322e5 )
by SuperNova.WS
04:12
created

nws_render()   F

Complexity

Conditions 22
Paths 541

Size

Total Lines 126
Code Lines 84

Duplication

Lines 0
Ratio 0 %

Importance

Changes 5
Bugs 0 Features 0
Metric Value
cc 22
eloc 84
c 5
b 0
f 0
nc 541
nop 4
dl 0
loc 126
rs 2.6561

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
use DBAL\DbSqlPaging;
4
use General\Helpers\PagingRenderer;
5
6
/**
7
 * @param template $template
8
 * @param string   $query_where
9
 * @param int      $query_limit
10
 */
11
function nws_render(&$user, &$template, $query_where = '', $query_limit = 20) {
12
  $mmModuleIsActive = !empty(SN::$gc->modules->getModulesInGroup('payment'));
13
14
  $sqlText = "SELECT a.*, UNIX_TIMESTAMP(`tsTimeStamp`) AS unix_time, u.authlevel, s.*
15
    FROM
16
      `{{announce}}` AS a
17
      LEFT JOIN `{{survey}}` AS s ON s.survey_announce_id = a.idAnnounce
18
      LEFT JOIN `{{users}}` AS u ON u.id = a.user_id
19
    WHERE 1 {$query_where}
20
    ORDER BY `tsTimeStamp` DESC, idAnnounce";
21
22
  $announce_list = new DbSqlPaging($sqlText, $query_limit, sys_get_param_int(PagingRenderer::KEYWORD));
23
  $pager = new PagingRenderer($announce_list, 'announce.php');
24
25
  $users = array();
26
  foreach ($announce_list as $announce) {
27
    if ($announce['user_id'] && !isset($users[$announce['user_id']])) {
28
      $users[$announce['user_id']] = db_user_by_id($announce['user_id']);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

28
      $users[$announce['user_id']] = /** @scrutinizer ignore-deprecated */ db_user_by_id($announce['user_id']);
Loading history...
29
    }
30
31
    $survey_vote = array('survey_vote_id' => 1);
32
    $survey_complete = strtotime($announce['survey_until']) < SN_TIME_NOW;
33
34
    if ($announce['survey_id'] && !empty($user['id'])) {
35
      $survey_vote = !$survey_complete ? $survey_vote = doquery("SELECT `survey_vote_id` FROM `{{survey_votes}}` WHERE survey_parent_id = {$announce['survey_id']} AND survey_vote_user_id = {$user['id']} LIMIT 1;", true) : array();
0 ignored issues
show
Unused Code introduced by
The assignment to $survey_vote is dead and can be removed.
Loading history...
36
    }
37
38
    $announce_exploded = explode("<br /><br />", SN::$gc->bbCodeParser->expandBbCode($announce['strAnnounce'], intval($announce['authlevel'])));
39
40
    $template->assign_block_vars('announces', array(
41
      'ID'              => $announce['idAnnounce'],
42
      'TIME'            => date(FMT_DATE_TIME, $announce['unix_time'] + SN_CLIENT_TIME_DIFF),
43
      'ANNOUNCE'        => SN::$gc->bbCodeParser->expandBbCode($announce['strAnnounce'], intval($announce['authlevel'])),
44
      'DETAIL_URL'      => $announce['detail_url'],
45
      'USER_NAME'       => !empty($users[$announce['user_id']])
46
        ? player_nick_render_to_html($users[$announce['user_id']], array('color' => true))
47
        : js_safe_string($announce['user_name']),
48
      'NEW'             => $announce['unix_time'] + SN::$config->game_news_actual >= SN_TIME_NOW,
49
      'FUTURE'          => $announce['unix_time'] > SN_TIME_NOW,
50
      'SURVEY_ID'       => $announce['survey_id'],
51
      'SURVEY_TEXT'     => $announce['survey_question'],
52
      'SURVEY_CAN_VOTE' => empty($survey_vote) && !$survey_complete,
53
      'SURVEY_COMPLETE' => $survey_complete,
54
      'SURVEY_UNTIL'    => $announce['survey_until'],
55
    ));
56
57
    foreach ($announce_exploded as $announce_paragraph) {
58
      $template->assign_block_vars('announces.paragraph', array(
59
        'TEXT' => $announce_paragraph,
60
      ));
61
    }
62
63
    if ($announce['survey_id']) {
64
      $survey_query = doquery(
65
        "SELECT survey_answer_id AS `ID`, survey_answer_text AS `TEXT`, count(DISTINCT survey_vote_id) AS `VOTES`
66
          FROM `{{survey_answers}}` AS sa
67
            LEFT JOIN `{{survey_votes}}` AS sv ON sv.survey_parent_answer_id = sa.survey_answer_id
68
          WHERE sa.survey_parent_id = {$announce['survey_id']}
69
          GROUP BY survey_answer_id
70
          ORDER BY survey_answer_id;"
71
      );
72
      $survey_vote_result = array();
73
      $total_votes = 0;
74
      $total_mm = 0;
75
      $total_money = 0;
76
      while ($row = db_fetch($survey_query)) {
77
        $survey_vote_result[$row['ID']] = $row;
78
        $total_votes += $row['VOTES'];
79
      }
80
81
      if ($mmModuleIsActive && $user['authlevel'] >= AUTH_LEVEL_ADMINISTRATOR) {
82
        $mQuery = doquery(
83
          "SELECT
84
            sa.survey_answer_id,
85
            sum(acc.account_metamatter_total) AS `mm`,
86
            (
87
              SELECT sum(payment_amount)
88
              FROM `{{payment}}` AS pay
89
              WHERE payment_currency = 'USD' AND pay.payment_user_id = sv.survey_vote_user_id
90
              GROUP BY payment_user_id, payment_currency
91
            )                                 AS `money`
92
          FROM `{{survey_votes}}` AS sv
93
            LEFT JOIN `{{survey_answers}}` AS sa ON sa.survey_answer_id = sv.survey_parent_answer_id
94
            LEFT JOIN `{{account_translate}}` AS act ON act.user_id = sv.survey_vote_user_id
95
            LEFT JOIN `{{account}}` AS acc ON acc.account_id = act.provider_account_id
96
          WHERE sv.survey_parent_id = {$announce['survey_id']}
97
          GROUP BY sv.survey_parent_id, sv.survey_parent_answer_id;"
98
        );
99
        while ($row = db_fetch($mQuery)) {
100
          $survey_vote_result[$row['survey_answer_id']] += [
101
            'MM'    => $row['mm'],
102
            'MONEY' => $row['money'],
103
          ];
104
          $total_mm += $row['mm'];
105
          $total_money += $row['money'];
106
        }
107
      }
108
109
      // Show result
110
      foreach ($survey_vote_result as &$vote_result) {
111
        $vote_percent = $total_votes ? $vote_result['VOTES'] / $total_votes * 100 : 0;
112
        $vote_result['PERCENT'] = $vote_percent;
113
        $vote_result['PERCENT_TEXT'] = round($vote_percent, 1);
114
        $vote_result['VOTES'] = HelperString::numberFloorAndFormat($vote_result['VOTES']);
115
116
        if ($mmModuleIsActive && $user['authlevel'] >= AUTH_LEVEL_ADMINISTRATOR) {
117
          $vote_result['PERCENT_MM'] = $total_mm ? $vote_result['MM'] / $total_mm * 100 : 0;
118
          $vote_result['PERCENT_MONEY'] = $total_money ? $vote_result['MONEY'] / $total_money * 100 : 0;
119
        }
120
121
        $template->assign_block_vars('announces.survey_answers', $vote_result);
122
      }
123
      // Dirty hack
124
      $template->assign_block_vars('announces.total_votes', array(
125
        'TOTAL_VOTES' => $total_votes,
126
        'TOTAL_MM'    => $total_mm,
127
        'TOTAL_MONEY' => $total_money,
128
      ));
129
    }
130
  }
131
132
  $template->assign_vars([
133
    'PAGER_MESSAGES' => $pager ? $pager->render() : '',
0 ignored issues
show
introduced by
$pager is of type General\Helpers\PagingRenderer, thus it always evaluated to true.
Loading history...
134
    'NEWS_COUNT'     => HelperString::numberFloorAndFormat($announce_list->getTotalRecords()),
135
136
    'MM_MODULE_ACTIVE' => $mmModuleIsActive,
137
  ]);
138
}
139
140
function nws_mark_read(&$user) {
141
  if (!empty($user['id'])) {
142
    db_user_set_by_id($user['id'], '`news_lastread` = ' . SN_TIME_NOW);
0 ignored issues
show
Deprecated Code introduced by
The function db_user_set_by_id() has been deprecated. ( Ignorable by Annotation )

If this is a false-positive, you can also ignore this issue in your code via the ignore-deprecated  annotation

142
    /** @scrutinizer ignore-deprecated */ db_user_set_by_id($user['id'], '`news_lastread` = ' . SN_TIME_NOW);
Loading history...
143
    $user['news_lastread'] = SN_TIME_NOW;
144
  }
145
146
  return true;
147
}
148
149
function survey_vote(&$user) {
150
  if (empty($user['id'])) {
151
    return true;
152
  }
153
154
  sn_db_transaction_start();
155
  $survey_id = sys_get_param_id('survey_id');
156
  $is_voted = doquery("SELECT `survey_vote_id` FROM `{{survey_votes}}` WHERE survey_parent_id = {$survey_id} AND survey_vote_user_id = {$user['id']} FOR UPDATE;", true);
157
  if (empty($is_voted)) {
158
    $survey_vote_id = sys_get_param_id('survey_vote');
159
    $is_answer_exists = doquery("SELECT `survey_answer_id` FROM `{{survey_answers}}` WHERE survey_parent_id = {$survey_id} AND survey_answer_id = {$survey_vote_id};", true);
160
    if (!empty($is_answer_exists)) {
161
      $user_name_safe = db_escape($user['username']);
162
      doquery("INSERT INTO `{{survey_votes}}` SET `survey_parent_id` = {$survey_id}, `survey_parent_answer_id` = {$survey_vote_id}, `survey_vote_user_id` = {$user['id']}, `survey_vote_user_name` = '{$user_name_safe}';");
163
    }
164
  }
165
  sn_db_transaction_commit();
166
167
  return true;
168
}
169