]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Irc/extlib/phergie/Phergie/Plugin/Caffeine/db.php
Cosmetic whitespace change
[quix0rs-gnu-social.git] / plugins / Irc / extlib / phergie / Phergie / Plugin / Caffeine / db.php
1 <?php
2
3 if (!defined('__DIR__')) {
4     define('__DIR__', dirname(__FILE__));
5 }
6
7 // Create database schema
8 echo 'Creating database', PHP_EOL;
9 $file = __DIR__ . '/caffeine.db';
10 if (file_exists($file)) {
11     unlink($file);
12 }
13 $db = new PDO('sqlite:' . $file);
14 $db->exec('CREATE TABLE caffeine (name VARCHAR(255), link VARCHAR(255))');
15 $db->exec('CREATE UNIQUE INDEX caffeine_name ON caffeine (name)');
16 $insert = $db->prepare('INSERT INTO caffeine (name, link) VALUES (:name, :link)');
17
18 // Get raw energyfiend.com data set
19 echo 'Downloading energyfiend.com data set', PHP_EOL;
20 $file = __DIR__ . '/the-caffeine-database.html';
21 if (!file_exists($file)) {
22     copy('http://www.energyfiend.com/the-caffeine-database', $file);
23 }
24 $contents = file_get_contents($file);
25
26 // Extract data from data set
27 echo 'Processing energyfiend.com data', PHP_EOL;
28 $contents = tidy_repair_string($contents);
29 libxml_use_internal_errors(true);
30 $doc = new DOMDocument;
31 $doc->loadHTML($contents);
32 libxml_clear_errors();
33 $xpath = new DOMXPath($doc);
34 $caffeine = $xpath->query('//table[@id="caffeinedb"]//tr/td[1]');
35 $db->beginTransaction();
36 foreach ($caffeine as $drink) {
37     $name = iconv('UTF-8', 'ISO-8859-1//TRANSLIT', $drink->textContent);
38     $name = preg_replace('/\s*\v+\s*/', ' ', $name);
39     if ($drink->firstChild->nodeName == 'a') {
40         $link = 'http://energyfiend.com'
41               . $drink->firstChild->getAttribute('href');
42     } else {
43         $link = null;
44     }
45     $insert->execute(array($name, $link));
46 }
47 $db->commit();
48
49 // Clean up
50 echo 'Cleaning up', PHP_EOL;
51 unlink($file);