summaryrefslogtreecommitdiff
path: root/crawler.php
blob: abe79a8c4cedc01c7168f573836c37cb1cab3f6b (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php
/**
 * User: Marvin Borner
 * Date: 14/09/2018
 * Time: 23:48
 */

error_reporting(E_ERROR | E_PARSE);

include 'mysql_conf.inc';

$currentUrl = $argv[1];

while (true) {
    crawl($currentUrl);
}

function crawl($url)
{
    global $currentUrl;

    if (!alreadyCrawled(cleanUrl($url))) {
        $requestResponse = getContent($url);
        if ($requestResponse[1] !== 404) {
            print 'Download Size: ' . $requestResponse[2];

            $htmlPath = createPathFromHtml($requestResponse[0]);
            $urlInfo = getUrlInfo($htmlPath);
            $allLinks = getLinks($htmlPath);

            writeToQueue($allLinks);
            saveData($urlInfo);
        }
    }

    $currentUrl = getFirstFromQueue(); // set new
    removeFromQueue($currentUrl);
}


function getContent($url)
{
    $curl = curl_init($url);
    curl_setopt($curl, CURLOPT_USERAGENT, 'Googlebot/2.1 (+http://www.google.com/bot.html)');
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($curl, CURLOPT_BINARYTRANSFER, true);
    $content = curl_exec($curl);
    $responseCode = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $downloadSize = curl_getinfo($curl, CURLINFO_SIZE_DOWNLOAD) / 1000 . "KB\n";
    curl_close($curl);

    return [$content, $responseCode, $downloadSize];
}

function getUrlInfo($path)
{
    $urlInfo = [];

    $urlInfo['title'] = strip_tags($path->query('//title')[0]->textContent);
    foreach ($path->query('//html') as $language) {
        $urlInfo['language'] = strip_tags($language->getAttribute('lang'));
    }
    foreach ($path->query('/html/head/meta[@name="description"]') as $description) {
        $urlInfo['description'] = strip_tags($description->getAttribute('content'));
    }

    // Fix empty information
    if (!isset($urlInfo['description'])) {
        $urlInfo['description'] = '';
        foreach ($path->query('//p') as $text) {
            if (strlen($urlInfo['description']) < 350) {
                $urlInfo['description'] .= $text->textContent . ' ';
            }
        }
    }

    if (empty($urlInfo['title'])) {
        $urlInfo['title'] = '';
        if (strlen($urlInfo['title']) < 350) {
            $urlInfo['title'] .= $path->query('//h1')[0]->textContent . ' ';
        }
    }

    return $urlInfo;
}

function getLinks($path)
{
    $allLinks = [];

    foreach ($path->query('//a') as $ink) {
        $href = cleanUrl($ink->getAttribute('href'));
        $allLinks[] = $href;
    }

    return array_unique($allLinks);
}

function cleanUrl($url)
{
    global $currentUrl;

    $url = ltrim($url);

    if (!(strpos($url, 'http') === 0)) {
        if (strpos($url, 'www') === 0) {
            $url = 'http://' . $url;
        } else if (strpos($url, '/') === 0) {
            $url = $currentUrl . $url;
        } else {
            $url = $currentUrl . $url;
        }
    }

    // if it's pure domain without slash (prevents duplicate domains because of slash)
    if (preg_match('/\w+\.\w{2,3}$/', $url)) {
        $url .= '/';
    }

    // strip some things
    $url = preg_replace('/([^:])(\/{2,})/', '$1/', $url); // double slashes
    $url = strtok($url, '?'); // parameters
    $url = strtok($url, '#'); // hash fragments

    return $url;
}

function createPathFromHtml($content)
{
    $dom = new DOMDocument();
    libxml_use_internal_errors(true);
    $dom->loadHTML($content);
    libxml_use_internal_errors(false);
    return new DOMXPath($dom);
}

function getFirstFromQueue()
{
    $conn = initDbConnection();
    $checkStmt = $conn->query('SELECT url FROM queue LIMIT 1');

    return $checkStmt->fetchAll(PDO::FETCH_ASSOC)[0]['url'];
}

function writeToQueue($urls)
{
    $conn = initDbConnection();

    foreach ($urls as $url) {
        $hash = md5($url);

        $checkStmt = $conn->prepare('SELECT null FROM url_data where hash = :hash');
        $checkStmt->execute(['hash' => $hash]);
        if ($checkStmt->rowCount() === 0) {
            $stmt = $conn->prepare('INSERT IGNORE INTO queue (url, hash) VALUES (:url, :hash)');
            $stmt->execute([':url' => $url, 'hash' => $hash]);
        }
    }
}

function removeFromQueue($url)
{
    $hash = md5($url);

    $conn = initDbConnection();
    $checkStmt = $conn->prepare('DELETE FROM queue where hash = :hash');
    $checkStmt->execute(['hash' => $hash]);
}

function saveData($urlInfo)
{
    global $currentUrl;

    print $currentUrl . "\n";

    $title = $urlInfo['title'] ?? '';
    $description = $urlInfo['description'] ?? '';
    $language = $urlInfo['language'] ?? 'en';
    $hash = md5($currentUrl);

    try {
        $conn = initDbConnection();
        $stmt = $conn->prepare('INSERT IGNORE INTO url_data (url, title, description, lang, hash) VALUES (:url, :title, :description, :lang, :hash)');
        $stmt->execute([':url' => $currentUrl, ':title' => $title, ':description' => $description, ':lang' => $language, ':hash' => $hash]);
    } catch (PDOException $e) {
        print $e->getMessage();
    }
}

function alreadyCrawled($url)
{
    $hash = md5($url);
    $conn = initDbConnection();
    $checkStmt = $conn->prepare('SELECT null FROM url_data where hash = :hash');
    $checkStmt->execute(['hash' => $hash]);
    return $checkStmt->rowCount() !== 0; // return true if already crawled
}

function initDbConnection()
{
    global $servername, $dbname, $username, $password;
    $conn = new PDO("mysql:host=$servername;dbname=$dbname", $username, $password);
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $conn;
}