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