-
Notifications
You must be signed in to change notification settings - Fork 0
/
russert.php
executable file
·684 lines (539 loc) · 14.1 KB
/
russert.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
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
<?php
PHP_SAPI == 'cli' or die();
require_once("config.php");
require_once __DIR__ . "/vendor/autoload.php";
new Russert();
class Russert {
private $sources = [];
private $connection = NULL;
private $collection = NULL;
private $errors = [];
private $locked = FALSE;
// "Force" flags.
private $generate_rss = FALSE;
private $generate_html = TRUE;
function __construct() {
// Set start time.
$this->start_time = microtime(TRUE);
// Check lock.
if ($this->isLocked()) {
$this->log("Lock is in place.");
die();
}
try {
// Set lock.
$this->setLock();
// Connect to MongoDB.
$this->connectMongo();
// Set collection.
$this->collection = new MongoDB\Collection($this->connection, "russert", "item");
// Set some indexes.
$this->ensureIndexes();
// Help variable for getting single source name.
$single_source = NULL;
// Check custom command-line parameters.
if (!empty($_SERVER['argv']) && is_array($_SERVER['argv']) && count($_SERVER['argv']) > 1) {
// Unset the first since it's the script name.
unset($_SERVER['argv'][0]);
foreach ($_SERVER['argv'] as $argument) {
if (strpos($argument, "--source=") !== FALSE) {
$single_source = explode("--source=", $argument)[1];
// Skipt index generation.
$this->generate_html = FALSE;
continue;
}
else if ($argument == "--force-rss") {
$this->log("Forcing RSS generation.");
$this->generate_rss = TRUE;
continue;
}
elseif ($argument == "--help" || $argument == "-h") {
echo "Russert RSS file generator\n";
echo "Usage: php russert.php [OPTIONS]\n";
echo " --source=SOURCE NAME Only process a single source.\n";
echo " --force-rss Forces regeneration of RSS files.\n";
echo "-h, --help Display this message\n";
die();
}
}
}
$sources = [];
// Load all available sources if the single source mode isn't on.
if ($single_source) {
$sources = $this->getSourceFilenames($single_source);
}
else {
$sources = $this->getSourceFilenames();
}
if (!$sources) {
$this->log("No sources found.");
die();
}
// Load the source objects to $this->sources.
$this->loadSources($sources);
// Handle the sources and get updates.
$this->handleSources();
// Output RSS files.
$this->handleRssFiles();
// Generate HTML index file but only if not running single source mode.
$this->handleIndex();
}
catch (Exception $e) {
$this->log("Things went wrong: {$e->getMessage()}.", TRUE);
}
}
/**
* Do these when we are quitting.
*/
function __destruct() {
// Kill database connection.
unset($this->connection);
// Handle errors.
$this->handleErrors();
// Remove lock if it has been set on this run.
if ($this->locked) {
$this->freeLock();
}
// Time.
$this->end_time = microtime(TRUE);
$this->log("Process took " . (round($this->end_time - $this->start_time)) . " seconds.");
$this->log("Bye!");
}
/**
* Returns a list of source filenames in the folder.
* @param String $name A name filter for the query.
*
* @return Array Array of sources found.
*/
function getSourceFilenames(string $name = "") : array {
$file_query = SOURCE_FOLDER . "/*.php";
if (!empty($name)) {
$file_query = SOURCE_FOLDER . "/{$name}.php";
}
$files = glob($file_query);
$sources = [];
if ($files) {
foreach ($files as &$file) {
$file = explode("/", $file);
$file = end($file);
$file = explode(".php", $file);
$file = reset($file);
// See if the class exists.
// FIXME: Get this from somewhere else?
$namespace = "\\Russert\\Sources\\";
// Filename here.
$source = $namespace . $file;
if (class_exists($source)) {
// These all must come from "Source" class.
$source_object = new $source;
// FIXME: Get this from somewhere else?
if (is_subclass_of($source_object, "\\Russert\\Source")) {
$sources[] = $source;
}
}
else {
$this->log("Loading source {$source} failed.");
}
}
}
return $sources;
}
/**
* Loads the sources into memory.
*
* @param array $sources Flat list of source names to load. This is because of single source support.
* @return void
* @author Joonas Kokko
*/
function loadSources(array $sources) {
foreach ($sources as $source) {
$this->sources[] = new $source;
}
}
/**
* Handles all sources.
*
* @return Boolean True/false on success/fail.
*/
function handleSources() : bool {
foreach ($this->sources as &$source) {
$this->handleCargo($source);
}
return FALSE;
}
/**
* Handles individual set of cargo coming from the source.
*/
function handleCargo(object $source) : void {
$this->log("Checking new items for {$source->getName()}...");
try {
$cargo = $source->getCargo();
if (DEBUG_MODE) {
print_r($cargo);
}
if (!empty($cargo)) {
foreach ($cargo as $item) {
// Try getting the same item from the database.
if ($this->itemExists($item)) {
$this->log("Item already exists, skipping: {$item['guid']}");
}
else {
// Insert the item.
$this->log("Item found, saving: {$item['guid']}");
$this->saveItem($item, $source);
// Tell the source that it got updated so we'll re-generate RSS for it.
$source->setUpdated(TRUE);
}
}
}
else {
$this->log("Couldn't get any items from {$source->getName()}, DOM changed?", TRUE);
}
}
catch (Exception $e) {
$this->log("Couldn't handle cargo: {$e->getMessage()}.");
}
}
/**
* Handles RSS files to the disk.
*
* @return Boolean True on success, false on fail.
*/
function handleRssFiles() : bool {
if ($this->sources) {
// Get sources that were updated.
if (!$this->generate_rss) {
$sources = array_filter($this->sources, function($o) {
if ($o->getUpdated()) {
return TRUE;
}
});
}
else {
$sources = $this->sources;
}
if (!empty($sources)) {
foreach ($sources as $source) {
$items = $this->getLatestItemsBySource($source);
if ($items) {
$this->log("Generating RSS feed for {$source->getName()}");
$this->saveRssFile($items, $source);
}
}
}
else {
$this->log("No updates to RSS files.");
}
}
return FALSE;
}
/**
* Saves the RSS file to the disk using items and the source.
*
* @return Boolean True on success, false on fail.
*/
function saveRssFile(array $items, object $source) : bool {
ob_start();
require("rss.tpl.php");
$xml = ob_get_contents();
ob_end_clean();
$filename = RSS_FOLDER . "/" . $source->getClassName() . ".xml";
if (!DEBUG_MODE) {
if (@file_put_contents($filename, $xml)) {
$this->log("RSS file saved.");
return TRUE;
}
else {
throw new \Exception("Couldn't save RSS file.", 5112);
}
}
else {
$this->log("Would save RSS file to {$filename}.");
}
return FALSE;
}
/**
* Saves index.html into the RSS folder.
*
* @return void
* @author Joonas Kokko
*/
function handleIndex() {
if (!$this->generate_html) {
$this->log("Skipping index generation due to single source mode.");
return TRUE;
}
$this->log("Generating index file.");
$source_filenames = [];
$visible_sources = array_filter($this->sources, function($o) {
if ($o->getHidden() == FALSE) {
return TRUE;
}
});
// Get filenames
if (!empty($visible_sources)) {
$this->saveIndexFile($visible_sources);
$this->log("Index file updated.");
}
else {
$this->log("No visible souces.");
}
}
/**
* Saves an HTML index file to the disk.
* TODO: Exceptions.
*
* @param array $sources
* @return boolean Success true/false.
* @author Joonas Kokko
*/
function saveIndexFile(array $sources) : bool {
ob_start();
require("index.tpl.php");
$html = ob_get_contents();
ob_end_clean();
$filename = RSS_FOLDER . "/" . "index.html";
if (!DEBUG_MODE) {
if (file_put_contents($filename, $html)) {
return TRUE;
}
}
else {
$this->log("Would save index file to {$filename}.");
}
return TRUE;
}
/**
* Check if item exists.
* @param Array $item Item array.
*
* @return Boolean True if the item exists, false if it doesn't.
*/
function itemExists(array $item) : bool {
if (empty($item['guid'])) {
throw new \Exception("Missing guid.", 5014);
}
$guid = $item['guid'];
$existing_item = NULL;
try {
$existing_item = $this->getItemByGuid($guid);
}
catch (Exception $e) {
return FALSE;
}
return TRUE;
}
/**
* Returns an item from MongoDB by GUID.
*
* @return Object Item Object.
*/
function getItemByGuid(string $guid) : MongoDB\Model\BSONDocument {
if (empty($guid)) {
throw new \Exception("Invalid guid.", 5013);
}
$item = $this->collection->findOne([ 'guid' => $guid ]);
if (!empty($item)) {
return $item;
}
else {
throw new \Exception("No item found.", 5012);
}
}
/**
* Returns an array of latest items by source.
* @param Object $source Source object..
* @param Integer $limit How many to return at most.
*
* @return Mixed Array of items or false if nothing found.
*/
function getLatestItemsBySource(object $source, int $limit = 20) : array {
$items = [];
try {
$cursor = $this->collection->find(
[ "source" => $source->getClassName() ],
[ "sort" => [ "seen" => -1 ], "limit" => $limit ]
);
foreach ($cursor as $item) {
$items[] = $item;
}
}
catch (Exception $e) {
throw new \Exception("Getting latest items from source failed: {$e->getMessage()}.", 5010);
}
return $items;
}
/**
* Save item.
* @param Array $item Item array to be saved.
* @param Object $source The source object.
*
* @return Boolean True or false on success/fail.
*/
function saveItem(array $item, object $source) : void {
// Validate the item.
if (!$this->isItemValid($item)) {
throw new \Exception("Item is not valid.", 5009);
}
// Set date.
$item['seen'] = new MongoDB\BSON\UTCDateTime(round(microtime(TRUE) * 1000));
// Add source.
$item['source'] = $source->getClassName();
// Debug saving..
if (DEBUG_MODE) {
// Print the item to the log.
$this->log("Would insert: " . json_encode($item));
return;
}
// Actual save.
try {
$result = $this->collection->insertOne($item);
}
catch (Exception $e) {
throw new \Exception("Inserting item to database failed: {$e->getMessage()}.", 5008);
}
}
/**
* A simple item validator.
* @param Array $item Item to be validated.
*
* @return Boolean True if the item is valid, false if not.
*/
function isItemValid(array $item) : bool {
$keys = [ "title", "link", "guid" ];
foreach ($keys as $key) {
if (empty($item[$key])) {
$this->log("Item is not valid: Missing key {$key}.");
return FALSE;
}
}
return TRUE;
}
/**
* Sets lock.
*
* @return void
* @author Joonas Kokko
*/
function setLock() : void {
// Lock is disabled.
if (DEBUG_MODE) {
return;
}
$result = file_put_contents(LOCKFILE, "Locked as of " . date('c'));
if (!$result) {
throw new \Exception("Error writing lockfile.", 5007);
}
// This will tell the program that the lock has been set within this run.
$this->locked = TRUE;
}
/**
* See if we are locked or not.
*
* @return Boolean True/false.
*/
function isLocked() : bool {
// Lock is disabled.
if (DEBUG_MODE) {
return FALSE;
}
if (file_exists(LOCKFILE)) {
$created = filectime(LOCKFILE);
$check = time() - (LOCKFILE_MINUTES * 60);
if ($created > $check) {
return TRUE;
}
}
return FALSE;
}
/**
* Free the lockfile.
*
* @return void
* @author Joonas Kokko
*/
function freeLock() : void {
if (!file_exists(LOCKFILE)) {
throw new \Exception("File doesn't exist.", 5006);
}
if (!unlink(LOCKFILE)) {
throw new \Exception("Removing lockfile failed.", 5005);
}
$this->locked = FALSE;
}
/* --- Other internals --- */
/**
* Connects to MongoDB and sets $this->connection.
*/
function connectMongo() : void {
try {
$this->connection = new MongoDB\Driver\Manager("mongodb://" . MONGODB_HOST);
}
catch (Exception $e) {
throw new \Exception("Connecting to MongoDB failed: {$e->getMessage()}.", 5004);
}
}
/**
* Just a simple function to ensure that we have correct MongoDB indexes in the collection(s).
*
* @return boolean True/false.
* @author Joonas Kokko
*/
function ensureIndexes() : void {
try {
$this->collection->createIndex([ 'guid' => 1] );
$this->collection->createIndex([ 'source' => 1] );
$this->collection->createIndex([ 'seen' => -1] );
}
catch (Exception $e) {
$this->log("Creating indexes failed: {$e->getMessage()}.");
}
}
/**
* Handles encountered errors by printing them out and mailing them.
*/
function handleErrors() : void {
if ($this->errors) {
$this->log("Encountered " . count($this->errors) . " serious errors:");
foreach ($this->errors as $error) {
$this->log($error);
}
if (REPORT_EMAIL) {
$this->sendMails($this->errors);
}
}
}
/**
* Compile one mail from a set of errors.
*/
function sendMails(array $mails) : void {
if ($mails && !DEBUG_MODE) {
$this->log("Sending " . count($mails) . " errors(s) to " . REPORT_EMAIL . ".");
$message = "";
foreach ($mails as $mail) {
$message .= $mail . "\n";
}
$result = mail(REPORT_EMAIL, "Critical Russert error(s)", $message);
if (!$result) {
throw new \Exception("Sending mail failed due to unknown error.", 5003);
}
}
}
/**
* A simple log function
* @param String $message A message to be logged.
* @param Boolean $error If the thing is an error and should be notified via email.
*/
function log(string $message, bool $error = FALSE) : void {
// Timestamp.
echo terminal_style(date('c') . ": ", "info");
if ($error) {
echo terminal_style($message, "red") . "\n";
// Add the message to errors.
$this->errors[] = $message;
}
else {
echo terminal_style($message, "green") . "\n";
}
}
}