Completed
Push — master ( 735ffd...9b092c )
by Anton
8s
created

local-search.php ➔ localSearchUrl()   C

Complexity

Conditions 8
Paths 8

Size

Total Lines 35
Code Lines 17

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 8
eloc 17
nc 8
nop 2
dl 0
loc 35
rs 5.3846
c 0
b 0
f 0
1
<?php
2
/**
3
 * Example of usage Yandex\SafeBrowsing package
4
 *
5
 * @author   Alexander Khaylo <[email protected]>
6
 * @created  07.02.14 13:57
7
 */
8
9
use Yandex\SafeBrowsing\SafeBrowsingClient;
10
use Yandex\SafeBrowsing\SafeBrowsingException;
11
use Yandex\Common\Exception\YandexException;
12
13
ini_set('memory_limit', '256M');
14
15
/**
16
 * @param string $url
17
 * @param string $key
18
 * @return bool|null
19
 */
20
function localSearchUrl($url, $key)
21
{
22
    $safeBrowsing = new SafeBrowsingClient($key);
23
24
    //Creating hashes by url
25
    $hashes = $safeBrowsing->getHashesByUrl($url);
26
    $localDbFile = 'hosts_prefixes.json';
27
28
    if (!is_file($localDbFile)) {
29
        exit('File "' . $localDbFile . '" not found');
30
    }
31
32
    $data = file_get_contents($localDbFile);
33
    $localHashPrefixes = json_decode($data, true);
34
35
    foreach ($hashes as $hash) {
36
        foreach ($localHashPrefixes as $shavar) {
37
            foreach ($shavar as $chunkNum => $chunk) {
38
                foreach ($chunk as $hashPrefix) {
39
                    if ($hash['prefix'] === $hashPrefix) {
40
                        //Found prefix in local DB
41
                        echo '<div class="alert alert-info">
42
                        Префикс хеша найден в локальной БД. Ищем в списке опасных сайтов...
43
                        </div>';
44
                        //Check full hash
45
                        if ($safeBrowsing->searchUrl($url)) {
46
                            return true;
47
                        }
48
                    }
49
                }
50
            }
51
        }
52
    }
53
    return false;
54
}
55
56
?>
57
<!doctype html>
58
<html lang="en-US">
59
<head>
60
    <meta charset="UTF-8">
61
    <title>Yandex PHP Library: Safe Browsing Demo</title>
62
    <link rel="stylesheet" href="//yandex.st/bootstrap/3.0.0/css/bootstrap.min.css">
63
    <link href="//netdna.bootstrapcdn.com/font-awesome/3.2.1/css/font-awesome.css" rel="stylesheet">
64
    <link rel="stylesheet" href="/examples/Disk/css/style.css">
65
    <style>
66
        .btn {
67
            padding: 6px 12px;
68
        }
69
    </style>
70
</head>
71
<body>
72
73
<div class="container">
74
    <ol class="breadcrumb">
75
        <li><a href="/examples">Examples</a></li>
76
        <li><a href="/examples/SafeBrowsing">SafeBrowsing</a></li>
77
        <li class="active">Поиск префикса хеша сайта в локальной БД</li>
78
    </ol>
79
    <h3>Поиск префикса хеша сайта в локальной БД</h3>
80
    <?php
81
    try {
82
83
        $settings = require_once '../settings.php';
84
85 View Code Duplication
        if (!isset($settings["safebrowsing"]["key"]) || !$settings["safebrowsing"]["key"]) {
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...
86
            throw new SafeBrowsingException('Empty Safe Browsing key');
87
        }
88
89 View Code Duplication
        if (isset($_GET['url']) && $_GET['url']) {
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...
90
            $url = $_GET['url'];
91
92
            $key = $settings["safebrowsing"]["key"];
93
94
            $safeBrowsing = new SafeBrowsingClient($key);
95
96
            /**
97
             * Using "gethash" request
98
             */
99
            //If exist local DB of prefixes
100
            if (localSearchUrl($url, $key)) {
101
                ?>
102
                <div class="alert alert-danger">Найден полный хеш для "<?= htmlentities($url) ?>" в списке опасных сайтов</div>
103
            <?php
104
            } else {
105
                ?>
106
                <div class="alert alert-success"><?= htmlentities($url) ?> - не найден в списке опасных сайтов</div>
107
            <?php
108
            }
109
        }
110
        ?>
111
112
        <form method="get">
113
            <div class="input-group">
114
                <input name="url" placeholder="URL" type="text" class="form-control"/>
115
                <span class="input-group-btn">
116
                    <input class="btn btn-primary" type="submit" value="Проверить URL"/>
117
                </span>
118
            </div>
119
        </form>
120
        <p>
121
            Пример: http://www.wmconvirus.narod.ru/
122
        </p>
123
        <div>
124
            Также можно посмотреть примеры:
125
            <ul>
126
                <li>
127
                    <a href="index.php">Проверить адреса</a>
128
                </li>
129
                <li>
130
                    <a href="lookup.php">Lookup API и Check Adult API</a>
131
                </li>
132
                <li>
133
                    <a href="save-prefixes-db.php">Сохранение базы префиксов хешей вредоносных сайтов (начнется
134
                        автоматически)</a>
135
                </li>
136
                <li>
137
                    <a href="update-prefixes-db.php">Обновить локальную базу префиксов хешей вредоносных сайтов (начнется
138
                        автоматически)</a>
139
                </li>
140
            </ul>
141
        </div>
142
    <?php
143
    } catch (SafeBrowsingException $e) {
144
        echo "Safe Browsing Exception:<br/>";
145
        echo nl2br($e->getMessage());
146
    } catch (YandexException $e) {
147
        echo "Yandex Library Exception:<br/>";
148
        echo nl2br($e->getMessage());
149
    } catch (\Exception $e) {
150
        echo get_class($e) . "<br/>";
151
        echo nl2br($e->getMessage());
152
    }
153
    ?>
154
</div>
155
156
</body>
157
</html>
158