Completed
Pull Request — master (#154)
by Marcel
08:11 queued 04:04
created

Domain::__construct()   A

Complexity

Conditions 3
Paths 4

Size

Total Lines 14
Code Lines 8

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 3
eloc 8
nc 4
nop 2
dl 0
loc 14
rs 10
c 0
b 0
f 0
1
<?php
2
3
namespace App;
4
5
use GuzzleHttp\Client;
6
use Illuminate\Database\Eloquent\Model;
7
use Keygen\Keygen;
8
use Log;
9
10
const METATAGNAME = 'siwecostoken';
11
12
/**
13
 * App\Domain.
14
 *
15
 * @property int $id
16
 * @property \Carbon\Carbon|null $created_at
17
 * @property \Carbon\Carbon|null $updated_at
18
 * @property string $domain
19
 * @property string $domain_token
20
 * @property int|null $token_id
21
 * @property int $verified
22
 * @property-read \App\Token|null $token
23
 *
24
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereCreatedAt( $value )
25
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereDomain( $value )
26
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereDomainToken( $value )
27
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereId( $value )
28
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereTokenId( $value )
29
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereUpdatedAt( $value )
30
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereVerified( $value )
31
 * @mixin \Eloquent
32
 *
33
 * @property \Carbon\Carbon|null $last_notification
34
 * @property-read \Illuminate\Database\Eloquent\Collection|\App\Scan[] $scans
35
 *
36
 * @method static \Illuminate\Database\Eloquent\Builder|\App\Domain whereLastNotification( $value )
37
 */
38
class Domain extends Model
39
{
40
    protected $fillable = ['domain', 'token_id', 'verified', 'domain_token'];
41
    protected $client = null;
42
43
    public function __construct(array $attributes = [], Client $client = null)
44
    {
45
        parent::__construct($attributes);
46
47
        if (array_key_exists('domain', $attributes)) {
48
            $this->domain = $attributes['domain'];
49
        }
50
        if (array_key_exists('token', $attributes)) {
51
            $token = Token::getTokenByString($attributes['token']);
52
            $this->token_id = $token->id;
53
            $this->domain_token = Keygen::alphanum(64)->generate();
54
        }
55
56
        $this->client = $client;
57
    }
58
59
    /**
60
     * @return bool
61
     */
62
    public function checkMetatags()
63
    {
64
        try {
65
            ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0)');
66
            $tags = get_meta_tags($this->domain);
67
            foreach ($tags as $tagkey => $tagvalue) {
68
                if ($tagkey == METATAGNAME) {
69
                    if ($tagvalue == $this->domain_token) {
70
                        /*Hooray site is activated*/
71
                        $this->verified = 1;
72
                        $this->save();
73
74
                        return true;
75
                    }
76
                }
77
            }
78
        } catch (\Exception $exception) {
79
            Log::warning($exception->getMessage());
80
        }
81
82
        return false;
83
    }
84
85
    public function token()
86
    {
87
        return $this->belongsTo(Token::class);
88
    }
89
90
    /**
91
     * @return \Illuminate\Database\Eloquent\Relations\HasMany
92
     */
93
    public function scans()
94
    {
95
        return $this->hasMany(Scan::class, 'url', 'domain');
96
    }
97
98
    /**
99
     * @return bool
100
     */
101
    public function checkHtmlPage()
102
    {
103
        /*get the content of the page. there should be nothing, except the activationkey*/
104
        ini_set('user_agent', 'Mozilla/4.0 (compatible; MSIE 6.0)');
105
        $url = $this->domain.'/'.$this->domain_token.'.html';
106
107
        try {
108
            $pageRequest = file_get_contents($url);
109
            if ($pageRequest == false) {
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $pageRequest of type string to the boolean false. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
110
                return false;
111
            }
112
            if (strpos($pageRequest, $this->domain_token) !== false) {
113
                $this->verified = 1;
114
                $this->save();
115
116
                return true;
117
            }
118
        } catch (\Exception $exception) {
119
            Log::warning($exception->getMessage());
120
        }
121
122
        return false;
123
    }
124
125
    /**
126
     * @param string $domain
127
     * @param int    $tokenId
128
     *
129
     * @return Domain
130
     */
131
    public static function getDomainOrFail(string $domain, int $tokenId)
132
    {
133
        Log::warning('DOMAIN: '.$domain.' ID: '.$tokenId);
134
135
        $domain = self::where(['domain' => $domain, 'token_id' => $tokenId])->first();
136
        if ($domain instanceof self) {
137
            return $domain;
138
        }
139
    }
140
141
    /**
142
     * Returns a valid URL for the given domain (hostname) that is reachable.
143
     *
144
     * @param string $domain Domain / Hostname to get the URL for.
145
     * @param Client $client Guzzle Client for PHPUnit testing only.
146
     *
147
     * @return string|Collection|null A valid URL incl. schema if valid. Collection with alternative URL if the given one was not valid or or NULL if no URL is available.
0 ignored issues
show
Bug introduced by
The type App\Collection was not found. Maybe you did not declare it correctly or list all dependencies?

The issue could also be caused by a filter entry in the build configuration. If the path has been excluded in your configuration, e.g. excluded_paths: ["lib/*"], you can move it to the dependency path list as follows:

filter:
    dependency_paths: ["lib/*"]

For further information see https://scrutinizer-ci.com/docs/tools/php/php-scrutinizer/#list-dependency-paths

Loading history...
148
     */
149
    public static function getDomainURL(string $domain, Client $client = null)
150
    {
151
        $testDomain = $domain;
152
153
        // Pings via guzzle
154
        $client = $client ?: new Client();
155
156
        $scheme = parse_url($testDomain, PHP_URL_SCHEME);
157
158
        // if user entered a URL -> test if available
159
        if ($scheme) {
160
            try {
161
                $testURL = $testDomain;
162
                $response = $client->request('GET', $testURL, ['verify' => false]);
163
                if ($response->getStatusCode() === 200) {
164
                    return $testURL;
165
                }
166
            } catch (\Exception $e) {
167
                // if not available, remove scheme from domain
168
                // scheme = https; + 3 for ://
169
                $testDomain = substr($domain, strlen($scheme) + 3);
170
            }
171
        }
172
173
        // Domain is available via https://
174
        try {
175
            $testURL = 'https://'.$testDomain;
176
            $response = $client->request('GET', $testURL, ['verify' => false]);
177
            if ($response->getStatusCode() === 200) {
178
                return $testURL;
179
            }
180
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
181
        }
182
183
        // Domain is available via http://
184
        try {
185
            $testURL = 'http://'.$testDomain;
186
            $response = $client->request('GET', $testURL, ['verify' => false]);
187
            if ($response->getStatusCode() === 200) {
188
                return $testURL;
189
            }
190
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
191
        }
192
193
        // Domain is available with or without www
194
        // if www. is there, than remove it, otherwise add it
195
        $testDomain = substr($testDomain, 0, 4) === 'www.' ? substr($testDomain, 4) : 'www.'.$testDomain;
196
197
        try {
198
            $testURL = 'https://'.$testDomain;
199
            $response = $client->request('GET', $testURL, ['verify' => false]);
200
            if ($response->getStatusCode() === 200) {
201
                return collect([
202
                    'notAvailable'         => $domain,
203
                    'alternativeAvailable' => $testDomain,
204
                ]);
205
            }
206
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
207
        }
208
209
        try {
210
            $testURL = 'http://'.$testDomain;
211
            $response = $client->request('GET', $testURL, ['verify' => false]);
212
            if ($response->getStatusCode() === 200) {
213
                return collect([
214
                    'notAvailable'         => $domain,
215
                    'alternativeAvailable' => $testDomain,
216
                ]);
217
            }
218
        } catch (\Exception $e) {
0 ignored issues
show
Coding Style Comprehensibility introduced by
Consider adding a comment why this CATCH block is empty.
Loading history...
219
        }
220
    }
221
}
222