-
Notifications
You must be signed in to change notification settings - Fork 0
/
imageParser.php
257 lines (219 loc) · 7.83 KB
/
imageParser.php
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
<?php
require 'db/Connect.php';
class ImageParser
{
/**
* @var int
*/
private int $pageNo = 1;
/**
* @var int
*/
private int $sleep = 3;
/**
* @var string
*/
private string $url = "https://windows10spotlight.com/";
/**
* Making things simpliers by addin them in the construct function
*/
public function __construct()
{
$this->db = Connect::PDO();
}
/**
* Build the logic call
*/
public function run()
{
echo "Parsing Main pages -------------- \n\n";
$this->parseMain($this->url);
echo "Getting images links -------------- \n\n";
$this->parseSecond();
echo "Download images from links -------------- \n\n";
$this->downloadImages();
}
/**
* Parse main page to retrieve the links that will be later used to retrieve the images URLs
*
* @param string $nextPage
*/
public function parseMain(string $nextPage)
{
if ($nextPage != $this->url) {
echo "Waiting $this->sleep seconds before next request\n\n";
sleep($this->sleep);
}
echo "$this->pageNo-------------------------------\n";
echo "Getting content from main page\n";
echo "$nextPage \n";
$mainContent = $this->getContent($nextPage);
$continue = true;
preg_match_all('/<h2>\s*<a\s*href=.(.+)["\']/isU', $mainContent, $matches);
if (isset($matches[1])) {
echo "Found " . count($matches[1]) . " links:\n";
print_r($matches[1]);
foreach ($matches[1] as $link) {
echo "Checking link $link \n";
$stmt = $this->db->prepare("SELECT `id` FROM `pages` WHERE `link`=:link");
$stmt->execute([
'link' => $link
]);
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($records) == 0) {
$sql = "INSERT INTO `pages` (`link`, `parsed`) VALUES (:link, :parsed)";
echo "$sql\n\n";
$stmt = $this->db->prepare($sql);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($this->db->errorInfo());
exit();
}
$stmt->execute([
'link' => $link,
'parsed' => 0
]);
} else {
echo "Link exists... will skip\n";
$continue = false;
}
}
}
preg_match('/next\s*page-numbers\s*["\']\s*href=.(.+)["\']/isU', $mainContent, $match);
if (isset($match[1]) && $continue == true) {
echo "Next page found:\n";
$this->pageNo++;
$this->parseMain($match[1]);
} else {
echo "Finished parsing the main pages\n";
echo "Total parsed pages: $this->pageNo\n";
}
}
/**
* Get the image urls from the URls parted from parseMain()
*/
public function parseSecond()
{
$records = $this->db
->query("SELECT `id`, `link` FROM `pages` WHERE `parsed`=0 OR `regex_error_landscape`=1 OR `regex_error_portret`=1")
->fetchAll(PDO::FETCH_ASSOC);
$total_links = count($records);
echo "Parsing " . $total_links . " links\n";
$cnt = 1;
foreach ($records as $data) {
$link = $data['link'];
echo "$cnt / $total_links -------------------------------\n";
echo "Getting content from link page\n";
echo "$link \n";
// getting content from url
$content = $this->getContent($link);
// checkers in case we fail to get the images using regex
$regexErrorLandscape = false;
$regexErrorPortret = false;
//get landscape images
preg_match('/<figure[^>]*>\s*<a\s*href=["\'](.+\.jpg)["\']/isU', $content, $match);
if (isset($match[1])) {
echo "Found wide image " . $match[1] . "\n";
$this->addImageUrlToDB($match[1], "landscape");
} else {
echo "Waring: Landscape image not found. Please check regex \n";
$regexErrorLandscape = true;
}
// get portret images
preg_match('/<(br|p)[^>]*>\s*<a\s*href=.([^\'"]+)["\'][^>]*>\s*<img\s*loading/isU', $content, $match);
if (isset($match[2])) {
echo "Found portret image " . $match[2] . "\n";
$this->addImageUrlToDB($match[2], "portret");
} else {
echo "Waring: Portret image not found. Please check regex \n";
$regexErrorPortret = true;
}
// set page as parsed
$updateArray = [
"`parsed`=1"
];
$updateArray[] = "`regex_error_landscape`=" . ($regexErrorLandscape ? 1 : 0);
$updateArray[] = "`regex_error_portret`=" . ($regexErrorPortret ? 1 : 0);
$updateSql = "UPDATE `pages` SET " . implode(", ", $updateArray) . " WHERE id=" . $data['id'];
echo "$updateSql \n\n";
$this->db->query($updateSql);
echo "Waiting $this->sleep seconds before next request\n\n";
sleep($this->sleep);
$cnt++;
}
echo "Finished parsing images links\n";
echo "Done\n";
}
/**
* Save image url to DB for later download
*
* @param string $link
* @param string $type
*/
private function addImageUrlToDB(string $link, string $type)
{
$stmt = $this->db->prepare("SELECT `id` FROM `images` WHERE `link`=:link");
$stmt->execute([
'link' => $link
]);
$records = $stmt->fetchAll(PDO::FETCH_ASSOC);
if (count($records) == 0) {
$sql = "INSERT INTO `images` (`link`, `type`, `parsed`) VALUES (:link, :type, :parsed)";
echo "$sql\n\n";
$stmt = $this->db->prepare($sql);
if (!$stmt) {
echo "\nPDO::errorInfo():\n";
print_r($this->db->errorInfo());
exit();
}
$stmt->execute([
'link' => $link,
'type' => $type,
'parsed' => 0
]);
} else {
echo "Link exists... will skip\n";
}
}
/**
* Download images and save them in their respective folder
*/
public function downloadImages()
{
$records = $this->db
->query("SELECT * FROM `images` WHERE `parsed`=0")
->fetchAll(PDO::FETCH_ASSOC);
$total_links = count($records);
echo "Downloading " . $total_links . " images\n";
$cnt = 1;
foreach ($records as $record) {
echo "$cnt / $total_links -------------------------------\n";
echo "Saving image " . $record['type'] . " -> " . $record['link'] . "\n";
$imageName = end(explode("/", $record['link']));
file_put_contents('images/' . $record['type'] . '/' . $imageName, file_get_contents($record['link']));
// set image as parsed
$updateSql = "UPDATE `images` SET `parsed`=1 WHERE id=" . $record['id'];
echo "$updateSql \n\n";
$this->db->query($updateSql);
$cnt++;
}
echo "\nDone\n";
}
/**
* Get page content using cURL
*
* @param string $url
*
* @return string
*/
private function getContent(string $url): string
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
}
(new ImageParser())->run();