rework crawler; add atom link extraction
[phinde.git] / src / phinde / Crawler.php
1 <?php
2 namespace phinde;
3
4 class Crawler
5 {
6     protected $es;
7     protected $queue;
8
9     static $supportedIndexTypes = array(
10         'application/atom+xml'  => '\\phinde\\LinkExtractor\\Atom',
11         'application/xhtml+xml' => '\\phinde\\LinkExtractor\\Html',
12         'text/html'             => '\\phinde\\LinkExtractor\\Html',
13     );
14
15     public function __construct()
16     {
17         $this->es = new Elasticsearch($GLOBALS['phinde']['elasticsearch']);
18         $this->queue = new Queue();
19     }
20
21     public function crawl($url)
22     {
23         $res       = $this->fetch($url);
24         $linkInfos = $this->extractLinks($res);
25         $this->enqueue($linkInfos);
26     }
27
28     protected function fetch($url)
29     {
30         $req = new HttpRequest($url);
31         $res = $req->send();
32         if ($res->getStatus() !== 200) {
33             throw new \Exception(
34                 "Response code is not 200 but "
35                 . $res->getStatus() . ", stopping"
36             );
37         }
38         return $res;
39     }
40
41     protected function extractLinks(\HTTP_Request2_Response $res)
42     {
43         $mimetype = explode(';', $res->getHeader('content-type'))[0];
44         if (!isset(static::$supportedIndexTypes[$mimetype])) {
45             echo "MIME type not supported for indexing: $mimetype\n";
46             return array();
47         }
48
49         $class = static::$supportedIndexTypes[$mimetype];
50         $extractor = new $class();
51         return $extractor->extract($res);
52     }
53
54     protected function enqueue($linkInfos)
55     {
56         foreach ($linkInfos as $linkInfo) {
57             if ($this->es->isKnown($linkInfo->url)) {
58                 continue;
59             }
60             $this->es->markQueued($linkInfo->url);
61             $this->queue->addToIndex(
62                 $linkInfo->url, $linkInfo->title, $linkInfo->source
63             );
64             if (Helper::isUrlAllowed($linkInfo->url)) {
65                 $this->queue->addToCrawl($linkInfo->url);
66             }
67         }
68     }
69 }
70 ?>