forked from marcelbrueckner/FullFever
-
Notifications
You must be signed in to change notification settings - Fork 0
/
FeverFullFeed.php
executable file
·477 lines (355 loc) · 12.4 KB
/
FeverFullFeed.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
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
<?php
/***************************************************************
* Copyright notice
*
* (c) 2013 Daniel Lienert <[email protected]>, Daniel Lienert
*
* All rights reserved
*
* This script is part of the TYPO3 project. The TYPO3 project is
* free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 3 of the License, or
* (at your option) any later version.
*
* The GNU General Public License can be found at
* http://www.gnu.org/copyleft/gpl.html.
*
* This script is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
class FeverFullFeed {
/**
* Configuration parameters
*/
// MySQL
protected $mysqlHost = '';
protected $mysqlPort = '';
protected $mysqlUser = '';
protected $mysqlPassword = '';
protected $mysqlFeverDb = '';
protected $feedConfiguration = array();
/**
* @var PDO
*/
protected $mysqlConnection;
/**
* @var integer
*/
protected $itemsPerRun = 10;
/**
* @var bool
*/
protected $unreadOnly = TRUE;
/**
* @var string
*/
protected $logFile;
/**
* Cache already retrieved fullTexts
*
* @var bool
*/
protected $useFullTextCache = TRUE;
/**
* @var FullTextCache
*/
protected $fullTextCache;
public function run() {
if($this->useFullTextCache) $this->fullTextCache = FullTextCache::getInstance();
$this->loadConfigs();
$this->openMySQLConnection();
$this->processArticles();
if($this->useFullTextCache) {
try {
$this->fullTextCache->shutdown();
} catch (Exception $e) {
$this->writeToLog($e, FALSE);
}
}
}
protected function loadConfigs() {
$localConfiguration = array();
$feedConfiguration = array();
if(!file_exists(__DIR__ . '/LocalConfiguration.php')) $this->writeToLog('The file LocalConfiguration.php has to be existent within the directory ' . __DIR__ . '\n', FALSE);
if(!file_exists(__DIR__ . '/FeedConfiguration.php')) $this->writeToLog('The file FeedConfiguration.php has to be existent within the directory ' . __DIR__ . '\n', FALSE);
include __DIR__ . '/LocalConfiguration.php';
include __DIR__ . '/FeedConfiguration.php';
$this->itemsPerRun = $localConfiguration['itemsPerRun'];
$this->unreadOnly = $localConfiguration['unreadOnly'];
// Set absolute file path
if (array_key_exists('logFile', $localConfiguration)) {
if (substr($localConfiguration['logFile'], 0, 1) === '.') {
$this->logFile = __DIR__ . substr($localConfiguration['logFile'], 1, strlen($localConfiguration['logFile']) - 1);
} else {
$this->logFile = $localConfiguration['logFile'];
}
}
// Check permissions
$file = @fopen(__DIR__ . 'dummy', 'a+b');
if($file == false) {
$this->logFile = '';
} else {
// Close file handle and delete file created with fopen()
@fclose($file);
@unlink(__DIR__ . 'dummy');
}
$this->mysqlHost = $localConfiguration['mysqlHost'];
$this->mysqlUser = $localConfiguration['mysqlUser'];
$this->mysqlPassword = $localConfiguration['mysqlPassword'];
$this->mysqlFeverDb = $localConfiguration['mysqlFeverDb'];
$this->mysqlPort = $localConfiguration['mysqlPort'];
$this->feedConfiguration = $feedConfiguration;
}
protected function openMySQLConnection() {
$this->mysqlConnection = new PDO('mysql:host='.$this->mysqlHost.';port='.$mysqlPort.';dbname=' . $this->mysqlFeverDb, $this->mysqlUser, $this->mysqlPassword);
}
protected function processArticles() {
$items = $this->getItemsToProcess();
foreach($items as $item) {
$url = $item['link'];
$feedConfig = $this->getConfigForURL($url);
if($feedConfig) {
if($this->useFullTextCache && $this->fullTextCache->itemExists($item['uid'])) {
$item = $this->addFullTextToItem($item, $this->fullTextCache->get($item['uid']), $feedConfig->getKeepAbstract());
$this->persistItem($item);
$this->writeToLog("Set fullText for item " . $item['link'] . " from cache. \n");
} else {
if($feedConfig->getXPath()) {
$fullText = $this->getItemFulltextFromPage($url, $feedConfig->getXPath());
if(trim($fullText)) {
// Replace patterns in fulltext
if(is_array($feedConfig->getReplace())) {
$replaceArray = $feedConfig->getReplace();
foreach ($replaceArray as $replace) {
$fullText = preg_replace($replaceArray[0],$replaceArray[1], $fullText);
}
}
$item = $this->addFullTextToItem($item, $fullText, $feedConfig->getKeepAbstract());
$this->persistItem($item);
if($this->useFullTextCache) $this->fullTextCache->store($item['uid'], $fullText);
}
}
}
}
}
}
/**
* @param $item
* @param $fullText
* @param $keepAbstract
*/
protected function addFullTextToItem(&$item, $fullText, $keepAbstract) {
$abstract = $keepAbstract ? $item['description'] : '';
$newDescriptionPattern = '%s<!--FULLTEXT--><hr><br/>%s';
$item['description'] = sprintf($newDescriptionPattern, $abstract, $fullText);
return $item;
}
/**
* @param $url
* @return feedConfig
*/
protected function getConfigForURL($url) {
foreach($this->feedConfiguration as $urlRegex => $config) {
if(preg_match($urlRegex, $url)) {
try {
return new feedConfig($urlRegex, $config);
} catch (Exception $e) {
$this->writeToLog($e, FALSE);
}
}
}
return NULL;
}
/**
* @return array
*/
protected function getItemsToProcess() {
$statement = "SELECT * FROM `fever_items`
WHERE description NOT like '%<!--FULLTEXT-->%'" .
(($this->unreadOnly == TRUE) ? "AND `read_on_time` = 0" : "") .
"SORT BY created_on_time DESC" .
"LIMIT " . $this->itemsPerRun;
return $this->mysqlConnection->query($statement)->fetchAll();
}
/**
* @param $url
* @param $xPathQuery
* @return bool|string
*/
protected function getItemFulltextFromPage($url, $xPathQuery) {
if($xPathQuery) {
$this->writeToLog("Retrieve FullText for $url .. ");
$dom = new DOMDocument();
$htmlSource = $this->loadHTMLData($url);
$success = @$dom->loadHTML($htmlSource);
if($success) {
$itemFullText = '';
$domXPath = new DOMXPath($dom);
$result = $domXPath->query($xPathQuery);
foreach ( $result as $node ) {
$itemFullText .= $this->getInnerHTML($node);
}
$this->writeToLog("(Full Page " . strlen($htmlSource) . " Chars - Extracted " . strlen($itemFullText) . " Chars) DONE. \n");
return $itemFullText;
} else {
$this->writeToLog("Error while parsing HTML Content for URL $url");
}
}
return FALSE;
}
/**
* @param $node
* @return string
*/
public function getInnerHTML($node) {
$dom = new DOMDocument();
$dom->appendChild($dom->importNode($node,true));
$innerHTML = $dom->saveHTML();
return $innerHTML;
}
/**
* @param $url
* @return string
*/
protected function loadHTMLData($url) {
$html = file_get_contents($url);
if(mb_detect_encoding($html, 'UTF-8', TRUE) === 'UTF-8') {
$html = mb_convert_encoding($html, 'HTML-ENTITIES', "UTF-8");
}
return $html;
}
/**
* @param $item
*/
protected function persistItem($item) {
$query = $this->mysqlConnection->prepare('UPDATE `fever_items` SET `description` = :description WHERE `id` = :id');
$query->execute(array('description' => $item['description'], 'id' => $item['id']));
}
/**
* @param $message
* @param $proceed If set to false the script execution will be stopped
*/
protected function writeToLog($message, $proceed = TRUE) {
if ($this->logFile !== '') {
$file = @fopen($this->logFile, 'a+b');
fwrite($file, $message . '\n');
@fclose($file);
}
if (!$proceed) {
Throw new Exception($message);
}
}
}
/**
* Class feedConfig
*
* Configuration Objects for Feed URLS
*/
class feedConfig {
protected $url;
protected $xPath;
protected $keepAbstract = FALSE;
protected $replace = NULL;
public function __construct($url, $configArray) {
if(!trim($url)) throw new Exception('No URL was given to construct config object');
if(!trim($configArray['xPath'])) throw new Exception('No xPath was given to retrieve fulltext');
$this->url = $url;
$this->xPath = $configArray['xPath'];
if(array_key_exists('keepAbstract', $configArray)) $this->keepAbstract = $configArray['keepAbstract'];
if(array_key_exists('replace', $configArray)) $this->replace = $configArray['replace'];
}
/**
* @return boolean
*/
public function getKeepAbstract() {
return $this->keepAbstract;
}
/**
* @return null
*/
public function getReplace() {
return $this->replace;
}
/**
* @return mixed
*/
public function getUrl() {
return $this->url;
}
/**
* @return mixed
*/
public function getXPath() {
return $this->xPath;
}
}
class FullTextCache {
/**
* @var array
*/
protected $items = array();
/**
* @var string
*/
protected $cacheFilePath = '';
/**
* @return FullTextCache
*/
public static function getInstance() {
$cache = new self;
$cache->loadCache();
return $cache;
}
public function store($uid, $data) {
$this->items[$uid] = array('data' => $data, 'used' => TRUE);
}
public function get($uid) {
if(array_key_exists($uid, $this->items)) {
$this->items[$uid]['used'] = TRUE;
return $this->items[$uid]['data'];
}
}
/**
* @param $uid
* @return bool
*/
public function itemExists($uid) {
return array_key_exists($uid, $this->items);
}
public function shutdown() {
$this->compact();
$this->save();
}
protected function __construct() {
$this->cacheFilePath = __DIR__ . '/FullText.cache';
$this->loadCache();
}
/**
* Load the cache data
*/
protected function loadCache() {
if(file_exists($this->cacheFilePath) && is_readable($this->cacheFilePath) && filesize($this->cacheFilePath)) {
$serializedCacheData = file_get_contents($this->cacheFilePath);
$this->items = unserialize($serializedCacheData);
}
}
protected function compact() {
foreach($this->items as $key => $item) {
if(!$item['used']) {
unset($this->items[$key]);
}
}
}
protected function save() {
$result = file_put_contents($this->cacheFilePath, serialize($this->items));
if($result === FALSE) throw new Exception('Cache File ' . $this->cacheFilePath . ' was not writable.', 1379059123);
}
}
$feverFullFeed = new FeverFullFeed();
$feverFullFeed->run();
?>