Completed
Branch newinternal (113bb8)
by Michael
05:12
created

RecreateTrustedIpTableTask   A

Complexity

Total Complexity 19

Size/Duplication

Total Lines 148
Duplicated Lines 0 %

Test Coverage

Coverage 0%

Importance

Changes 1
Bugs 0 Features 0
Metric Value
wmc 19
eloc 64
c 1
b 0
f 0
dl 0
loc 148
ccs 0
cts 92
cp 0
rs 10

5 Methods

Rating   Name   Duplication   Size   Complexity  
A readFile() 0 34 6
A doInserts() 0 25 5
A execute() 0 32 1
A explodeCidrs() 0 7 3
A resolveDns() 0 16 4
1
<?php
2
/******************************************************************************
3
 * Wikipedia Account Creation Assistance tool                                 *
4
 *                                                                            *
5
 * All code in this file is released into the public domain by the ACC        *
6
 * Development Team. Please see team.json for a list of contributors.         *
7
 ******************************************************************************/
8
9
namespace Waca\ConsoleTasks;
10
11
use Exception;
12
use PDOException;
13
use PDOStatement;
14
use Waca\RegexConstants;
15
use Waca\Tasks\ConsoleTaskBase;
16
17
class RecreateTrustedIpTableTask extends ConsoleTaskBase
18
{
19
    public function execute()
20
    {
21
22
        echo "Fetching file...\n";
23
24
        $htmlfile = file($this->getSiteConfiguration()->getXffTrustedHostsFile(),
25
            FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
26
27
        $ip = array();
28
        $iprange = array();
29
        $dnsdomain = array();
30
31
        echo "Sorting file...\n";
32
        $this->readFile($htmlfile, $iprange, $ip, $dnsdomain);
33
34
        echo "Exploding CIDRs...\n";
35
        $this->explodeCidrs($iprange, $ip);
36
37
        echo "Resolving DNS...\n";
38
        $this->resolveDns($dnsdomain, $ip);
39
40
        echo "Uniq-ing array...\n";
41
42
        $ip = array_unique($ip);
43
44
        $database = $this->getDatabase();
45
46
        $database->exec('DELETE FROM xfftrustcache;');
47
48
        $insert = $database->prepare('INSERT INTO xfftrustcache (ip) VALUES (:ip);');
49
50
        $this->doInserts($ip, $insert);
0 ignored issues
show
Bug introduced by
It seems like $insert can also be of type boolean; however, parameter $insert of Waca\ConsoleTasks\Recrea...pTableTask::doInserts() does only seem to accept PDOStatement, maybe add an additional type check? ( Ignorable by Annotation )

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

50
        $this->doInserts($ip, /** @scrutinizer ignore-type */ $insert);
Loading history...
51
    }
0 ignored issues
show
Coding Style introduced by
Expected //end execute()
Loading history...
52
53
    /**
54
     * @param string[] $dnsDomains  the DNS domains to resolve
55
     * @param string[] $ipAddresses existing array of IPs to add to
56
     */
57
    protected function resolveDns($dnsDomains, &$ipAddresses)
58
    {
59
        foreach ($dnsDomains as $domain) {
60
            $ipList = gethostbynamel($domain);
61
62
            if ($ipList === false) {
63
                echo "Invalid DNS name $domain\n";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $domain instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
64
                continue;
65
            }
66
67
            foreach ($ipList as $ipAddress) {
68
                $ipAddresses[] = $ipAddress;
69
            }
70
71
            // don't DoS
72
            usleep(10000);
73
        }
74
    }
0 ignored issues
show
Coding Style introduced by
Expected //end resolveDns()
Loading history...
75
76
    /**
77
     * @param $iprange
78
     * @param $ip
79
     */
80
    protected function explodeCidrs($iprange, &$ip)
81
    {
82
        foreach ($iprange as $r) {
83
            $ips = $this->getXffTrustProvider()->explodeCidr($r);
84
85
            foreach ($ips as $i) {
86
                $ip[] = $i;
87
            }
88
        }
89
    }
0 ignored issues
show
Coding Style introduced by
Expected //end explodeCidrs()
Loading history...
90
91
    /**
92
     * @param $htmlfile
93
     * @param $iprange
94
     * @param $ip
95
     * @param $dnsdomain
96
     */
97
    protected function readFile($htmlfile, &$iprange, &$ip, &$dnsdomain)
98
    {
99
        foreach ($htmlfile as $line_num => $rawline) {
100
            // remove the comments
101
            $hashPos = strpos($rawline, '#');
102
            if ($hashPos !== false) {
103
                $line = substr($rawline, 0, $hashPos);
104
            }
105
            else {
106
                $line = $rawline;
107
            }
108
109
            $line = trim($line);
110
111
            // this was a comment or empty line...
112
            if ($line == "") {
0 ignored issues
show
Coding Style Comprehensibility introduced by
The string literal does not require double quotes, as per coding-style, please use single quotes.

PHP provides two ways to mark string literals. Either with single quotes 'literal' or with double quotes "literal". The difference between these is that string literals in double quotes may contain variables with are evaluated at run-time as well as escape sequences.

String literals in single quotes on the other hand are evaluated very literally and the only two characters that needs escaping in the literal are the single quote itself (\') and the backslash (\\). Every other character is displayed as is.

Double quoted string literals may contain other variables or more complex escape sequences.

<?php

$singleQuoted = 'Value';
$doubleQuoted = "\tSingle is $singleQuoted";

print $doubleQuoted;

will print an indented: Single is Value

If your string literal does not contain variables or escape sequences, it should be defined using single quotes to make that fact clear.

For more information on PHP string literals and available escape sequences see the PHP core documentation.

Loading history...
113
                continue;
114
            }
115
116
            // match a regex of an CIDR range:
117
            $ipcidr = '@' . RegexConstants::IPV4 . RegexConstants::IPV4_CIDR . '@';
118
            if (preg_match($ipcidr, $line) === 1) {
119
                $iprange[] = $line;
120
                continue;
121
            }
122
123
            $ipnoncidr = '@' . RegexConstants::IPV4 . '@';
124
            if (preg_match($ipnoncidr, $line) === 1) {
125
                $ip[] = $line;
126
                continue;
127
            }
128
129
            // it's probably a DNS name.
130
            $dnsdomain[] = $line;
131
        }
132
    }
0 ignored issues
show
Coding Style introduced by
Expected //end readFile()
Loading history...
133
134
    /**
135
     * @param array        $ip
136
     * @param PDOStatement $insert
137
     *
138
     * @throws Exception
139
     */
140
    protected function doInserts($ip, PDOStatement $insert)
141
    {
142
        $successful = true;
143
144
        foreach ($ip as $i) {
145
            if (count($i) > 15) {
146
                echo "Rejected $i\n";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $i instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
147
                $successful = false;
148
149
                continue;
150
            }
151
152
            try {
153
                $insert->execute(array(':ip' => $i));
154
            }
155
            catch (PDOException $ex) {
156
                echo "Exception on $i :\n";
0 ignored issues
show
Coding Style Best Practice introduced by
As per coding-style, please use concatenation or sprintf for the variable $i instead of interpolation.

It is generally a best practice as it is often more readable to use concatenation instead of interpolation for variables inside strings.

// Instead of
$x = "foo $bar $baz";

// Better use either
$x = "foo " . $bar . " " . $baz;
$x = sprintf("foo %s %s", $bar, $baz);
Loading history...
157
                echo $ex->getMessage();
158
                $successful = false;
159
                break;
160
            }
161
        }
162
163
        if (!$successful) {
164
            throw new Exception('Encountered errors during transaction processing');
165
        }
166
    }
0 ignored issues
show
Coding Style introduced by
Expected //end doInserts()
Loading history...
167
}
0 ignored issues
show
Coding Style introduced by
Expected //end class
Loading history...