04cc9ac01c39b2244c465a1702ce37ae809694bc
[phinde.git] / bin / index.php
1 #!/usr/bin/env php
2 <?php
3 namespace phinde;
4 // index a given URL
5 require_once __DIR__ . '/../src/init.php';
6
7 $supportedIndexTypes = array(
8     'application/xhtml+xml',
9     'text/html',
10 );
11
12 if ($argc < 2) {
13     echo "No URL given\n";
14     exit(1);
15 }
16
17 function removeTags($doc, $tag) {
18     $elems = array();
19     foreach ($doc->getElementsbyTagName($tag) as $elem) {
20         $elems[] = $elem;
21     }
22     foreach ($elems as $elem) {
23         $elem->parentNode->removeChild($elem);
24     }
25 }
26
27 $es = new Elasticsearch($GLOBALS['phinde']['elasticsearch']);
28
29 $url = $argv[1];
30 $existingDoc = $es->get($url);
31 if ($existingDoc && $existingDoc->status == 'indexed') {
32     echo "URL already indexed: $url\n";
33     exit(0);
34 }
35 //FIXME: sourcetitle, sourcelink
36
37 $req = new \HTTP_Request2($url);
38 $req->setConfig('follow_redirects', true);
39 $req->setConfig('connect_timeout', 5);
40 $req->setConfig('timeout', 10);
41 $req->setConfig('ssl_verify_peer', false);
42 $res = $req->send();
43 //FIXME: try-catch
44
45 //FIXME: delete if 401 gone or 404 when updating
46 if ($res->getStatus() !== 200) {
47     echo "Response code is not 200 but " . $res->getStatus() . ", stopping\n";
48     //FIXME: update status
49     exit(3);
50 }
51
52 $mimetype = explode(';', $res->getHeader('content-type'))[0];
53 if (!in_array($mimetype, $supportedIndexTypes)) {
54     echo "MIME type not supported for indexing: $mimetype\n";
55     //FIXME: update status
56     exit(4);
57 }
58
59
60 //FIXME: update index only if changed since last index time
61 //FIXME: extract base url from html
62 $url = $res->getEffectiveUrl();
63 $base = new \Net_URL2($url);
64
65 $indexDoc = new \stdClass();
66
67 //FIXME: MIME type switch
68 $doc = new \DOMDocument();
69 //@ to hide parse warning messages in invalid html
70 @$doc->loadHTML($res->getBody());
71 $dx = new \DOMXPath($doc);
72
73 //remove script tags
74 removeTags($doc, 'script');
75 removeTags($doc, 'style');
76 removeTags($doc, 'nav');
77
78 //default content: <body>
79 $xpContext = $doc->getElementsByTagName('body')->item(0);
80
81 //use microformats content if it exists
82 $xpElems = $dx->query(
83     "//*[contains(concat(' ', normalize-space(@class), ' '), ' e-content ')]"
84 );
85 if ($xpElems->length) {
86     $xpContext = $xpElems->item(0);
87 } else if ($doc->getElementById('content')) {
88     //if there is an element with ID "content", we'll use this
89     $xpContext = $doc->getElementById('content');
90 }
91
92 $indexDoc->url = $url;
93 $indexDoc->schemalessUrl = Helper::noSchema($url);
94 $indexDoc->type = 'html';
95 $indexDoc->subtype = '';
96 $indexDoc->mimetype = $mimetype;
97 $indexDoc->domain   = parse_url($url, PHP_URL_HOST);
98
99 //$indexDoc->source = 'FIXME';
100 //$indexDoc->sourcetitle = 'FIXME';
101
102 $indexDoc->author = new \stdClass();
103
104 $arXpElems = $dx->query('/html/head/meta[@name="author"]');
105 if ($arXpElems->length) {
106     $indexDoc->author->name = trim(
107         $arXpElems->item(0)->attributes->getNamedItem('content')->textContent
108     );
109 }
110 $arXpElems = $dx->query('/html/head/link[@rel="author"]');
111 if ($arXpElems->length) {
112     $indexDoc->author->url = trim(
113         $base->resolve(
114             $arXpElems->item(0)->attributes->getNamedItem('href')->textContent
115         )
116     );
117 }
118
119
120 $arXpElems = $dx->query('/html/head/title');
121 if ($arXpElems->length) {
122     $indexDoc->title = trim(
123         $arXpElems->item(0)->textContent
124     );
125 }
126
127 foreach (array('h1', 'h2', 'h3', 'h4', 'h5', 'h6') as $headlinetype) {
128     $indexDoc->$headlinetype = array();
129     foreach ($xpContext->getElementsByTagName($headlinetype) as $xheadline) {
130         array_push(
131             $indexDoc->$headlinetype,
132             trim($xheadline->textContent)
133         );
134     }
135 }
136
137 //FIXME: split paragraphs
138 //FIXME: insert space after br
139 $indexDoc->text = array();
140 $indexDoc->text[] = trim(
141     str_replace(
142         array("\r\n", "\n", "\r", '  '),
143         ' ',
144         $xpContext->textContent
145     )
146 );
147
148 //tags
149 $tags = array();
150 foreach ($dx->query('/html/head/meta[@name="keywords"]') as $xkeywords) {
151     $keywords = $xkeywords->attributes->getNamedItem('content')->textContent;
152     foreach (explode(',', $keywords) as $keyword) {
153         $tags[trim($keyword)] = true;
154     }
155 }
156 $indexDoc->tags = array_keys($tags);
157
158 //dates
159 $arXpdates = $dx->query('/html/head/meta[@name="DC.date.created"]');
160 if ($arXpdates->length) {
161     $indexDoc->crdate = date(
162         'c',
163         strtotime(
164             $arXpdates->item(0)->attributes->getNamedItem('content')->textContent
165         )
166     );
167 }
168 //FIXME: keep creation date from database, or use modified date if we
169 // do not have it there
170
171 $arXpdates = $dx->query('/html/head/meta[@name="DC.date.modified"]');
172 if ($arXpdates->length) {
173     $indexDoc->modate = date(
174         'c',
175         strtotime(
176             $arXpdates->item(0)->attributes->getNamedItem('content')->textContent
177         )
178     );
179 } else {
180     $lm = $res->getHeader('last-modified');
181     if ($lm !== null) {
182         $indexDoc->modate = date('c', strtotime($lm));
183     } else {
184         //use current time since we don't have any other data
185         $indexDoc->modate = date('c');
186     }
187 }
188
189 //language
190 //there may be "en-US" and "de-DE"
191 $xlang = $doc->documentElement->attributes->getNamedItem('lang');
192 if ($xlang) {
193     $indexDoc->language = strtolower(substr($xlang->textContent, 0, 2));
194 }
195 //FIXME: fallback, autodetection
196 //FIXME: check noindex
197
198 //var_dump($indexDoc);die();
199
200 $indexDoc->status = 'indexed';
201
202 //FIXME: update index if it exists already
203 $r = new Elasticsearch_Request(
204     $GLOBALS['phinde']['elasticsearch'] . 'document/' . rawurlencode($url),
205     \HTTP_Request2::METHOD_PUT
206 );
207 $r->setBody(json_encode($indexDoc));
208 $r->send();
209
210
211 ?>