aa9abcc27752879cbcfa99241d82cff7a588eb0d
[stapibas.git] / src / stapibas / Pingback / ContentFetcher.php
1 <?php
2 namespace stapibas;
3
4 class Pingback_ContentFetcher
5 {
6     public $db;
7     public $log;
8
9     public function __construct(Dependencies $deps)
10     {
11         $this->deps = $deps;
12         $this->db   = $deps->db;
13         $this->log  = $deps->log;
14     }
15
16     /**
17      * Fetches HTML content of all pingbacks that are marked as "needs update"
18      */
19     public function updateAll()
20     {
21         $this->log->info('Fetching pingback content..');
22         $res = $this->db->query(
23             'SELECT * FROM pingbacks'
24             . ' WHERE p_use = 1' . $this->sqlNeedsUpdate()
25         );
26         $items = 0;
27         while ($pingbackRow = $res->fetch(\PDO::FETCH_OBJ)) {
28             ++$items;
29             $this->updateContent($pingbackRow);
30         }
31         $this->log->info('Finished fetching %d pingback sources.', $items);
32     }
33
34     protected function updateContent($pingbackRow)
35     {
36         $this->log->info(
37             'Fetching pingback source #%d: %s',
38             $pingbackRow->p_id, $pingbackRow->p_source
39         );
40
41         $req = new \HTTP_Request2($pingbackRow->p_source);
42         $req->setHeader('User-Agent', 'stapibas');
43         $req->setHeader(
44             'Accept',
45             'application/xhtml+xml; q=1'
46             . ', application/xml; q=0.9'
47             . ', text/xml; q=0.9'
48             . ', text/html; q=0.5'
49             . ', */*; q=0.1'
50         );
51
52         $res = $req->send();
53         if (intval($res->getStatus() / 100) != 2) {
54             //no 2xx is an error for us
55             $this->log->err('Error fetching pingback source content');
56             return;
57         }
58
59         $this->db->exec(
60             'DELETE FROM pingbackcontent WHERE'
61             . ' pc_p_id = ' . $this->db->quote($pingbackRow->p_id)
62         );
63         $this->db->exec(
64             'INSERT INTO pingbackcontent SET'
65             . '  pc_p_id = ' . $this->db->quote($pingbackRow->p_id)
66             . ', pc_mime_type = '
67             . $this->db->quote($res->getHeader('content-type'))
68             . ', pc_fulltext = ' . $this->db->quote($res->getBody())
69         );
70         $this->db->exec(
71             'UPDATE pingbacks'
72             . ' SET p_needs_update = 0'
73             . ' WHERE p_id = ' . $this->db->quote($pingbackRow->p_id)
74         );
75     }
76
77
78     protected function sqlNeedsUpdate()
79     {
80         if ($this->deps->options['force']) {
81             return '';
82         }
83         return ' AND p_needs_update = 1';
84     }
85
86 }
87
88 ?>