aboutsummaryrefslogtreecommitdiffhomepage
path: root/inc/3rdparty/content-extractor
diff options
context:
space:
mode:
authorNicolas LÅ“uillet <nicolas.loeuillet@gmail.com>2013-12-06 00:49:43 -0800
committerNicolas LÅ“uillet <nicolas.loeuillet@gmail.com>2013-12-06 00:49:43 -0800
commitd5501950e2470d52f6bf5954d2179010cdee0475 (patch)
treec452a0cbcbe3a49fa72e5ba7e8c249302da8ae29 /inc/3rdparty/content-extractor
parent0b5c6ff3195e145a1fb5edb67741b8f6ed231fa2 (diff)
parent42c80841c846610be280218d53fcde06b0f0063b (diff)
downloadwallabag-d5501950e2470d52f6bf5954d2179010cdee0475.tar.gz
wallabag-d5501950e2470d52f6bf5954d2179010cdee0475.tar.zst
wallabag-d5501950e2470d52f6bf5954d2179010cdee0475.zip
Merge pull request #353 from inthepoche/ftr
[change] we now use Full-Text RSS 3.1, thank you so much @fivefilters
Diffstat (limited to 'inc/3rdparty/content-extractor')
-rw-r--r--inc/3rdparty/content-extractor/ContentExtractor.php612
-rw-r--r--inc/3rdparty/content-extractor/SiteConfig.php184
2 files changed, 0 insertions, 796 deletions
diff --git a/inc/3rdparty/content-extractor/ContentExtractor.php b/inc/3rdparty/content-extractor/ContentExtractor.php
deleted file mode 100644
index 26878392..00000000
--- a/inc/3rdparty/content-extractor/ContentExtractor.php
+++ /dev/null
@@ -1,612 +0,0 @@
1<?php
2/**
3 * Content Extractor
4 *
5 * Uses patterns specified in site config files and auto detection (hNews/PHP Readability)
6 * to extract content from HTML files.
7 *
8 * @version 0.8
9 * @date 2012-02-21
10 * @author Keyvan Minoukadeh
11 * @copyright 2011 Keyvan Minoukadeh
12 * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
13 */
14
15class ContentExtractor
16{
17 protected static $tidy_config = array(
18 'clean' => true,
19 'output-xhtml' => true,
20 'logical-emphasis' => true,
21 'show-body-only' => false,
22 'new-blocklevel-tags' => 'article, aside, footer, header, hgroup, menu, nav, section, details, datagrid',
23 'new-inline-tags' => 'mark, time, meter, progress, data',
24 'wrap' => 0,
25 'drop-empty-paras' => true,
26 'drop-proprietary-attributes' => false,
27 'enclose-text' => true,
28 'enclose-block-text' => true,
29 'merge-divs' => true,
30 'merge-spans' => true,
31 'char-encoding' => 'utf8',
32 'hide-comments' => true
33 );
34 protected $html;
35 protected $config;
36 protected $title;
37 protected $author = array();
38 protected $language;
39 protected $date;
40 protected $body;
41 protected $success = false;
42 public $fingerprints = array();
43 public $readability;
44 public $debug = false;
45
46 function __construct($path, $fallback=null) {
47 SiteConfig::set_config_path($path, $fallback);
48 }
49
50 protected function debug($msg) {
51 if ($this->debug) {
52 $mem = round(memory_get_usage()/1024, 2);
53 $memPeak = round(memory_get_peak_usage()/1024, 2);
54 echo '* ',$msg;
55 echo ' - mem used: ',$mem," (peak: $memPeak)\n";
56 ob_flush();
57 flush();
58 }
59 }
60
61 public function reset() {
62 $this->html = null;
63 $this->readability = null;
64 $this->config = null;
65 $this->title = null;
66 $this->body = null;
67 $this->author = array();
68 $this->language = null;
69 $this->date = null;
70 $this->success = false;
71 }
72
73 public function findHostUsingFingerprints($html) {
74 $this->debug('Checking fingerprints...');
75 $head = substr($html, 0, 8000);
76 foreach ($this->fingerprints as $_fp => $_fphost) {
77 $lookin = 'html';
78 if (is_array($_fphost)) {
79 if (isset($_fphost['head']) && $_fphost['head']) {
80 $lookin = 'head';
81 }
82 $_fphost = $_fphost['hostname'];
83 }
84 if (strpos($$lookin, $_fp) !== false) {
85 $this->debug("Found match: $_fphost");
86 return $_fphost;
87 }
88 }
89 return false;
90 }
91
92 // returns true on success, false on failure
93 // $smart_tidy indicates that if tidy is used and no results are produced, we will
94 // try again without it. Tidy helps us deal with PHP's patchy HTML parsing most of the time
95 // but it has problems of its own which we try to avoid with this option.
96 public function process($html, $url, $smart_tidy=true) {
97 $this->reset();
98 // extract host name
99 $host = @parse_url($url, PHP_URL_HOST);
100 if (!($this->config = SiteConfig::build($host))) {
101 // no match, check HTML for fingerprints
102 if (!empty($this->fingerprints) && ($_fphost = $this->findHostUsingFingerprints($html))) {
103 $this->config = SiteConfig::build($_fphost);
104 }
105 unset($_fphost);
106 if (!$this->config) {
107 // no match, so use defaults
108 $this->config = new SiteConfig();
109 }
110 }
111 // store copy of config in our static cache array in case we need to process another URL
112 SiteConfig::add_to_cache($host, $this->config);
113
114 // do string replacements
115 foreach ($this->config->replace_string as $_repl) {
116 $html = str_replace($_repl[0], $_repl[1], $html);
117 }
118 unset($_repl);
119
120 // use tidy (if it exists)?
121 // This fixes problems with some sites which would otherwise
122 // trouble DOMDocument's HTML parsing. (Although sometimes it
123 // makes matters worse, which is why you can override it in site config files.)
124 $tidied = false;
125 if ($this->config->tidy && function_exists('tidy_parse_string') && $smart_tidy) {
126 $this->debug('Using Tidy');
127 $tidy = tidy_parse_string($html, self::$tidy_config, 'UTF8');
128 if (tidy_clean_repair($tidy)) {
129 $original_html = $html;
130 $tidied = true;
131 // $html = $tidy->value;
132 }
133 $body = $tidy->body();
134 if (preg_replace('/\s+/', '', $body->value) !== "<body></body>") {
135 $html = $tidy->value;
136 }
137 unset($tidy);
138 }
139
140 // load and parse html
141 $this->readability = new PocheReadability($html, $url);
142
143 // we use xpath to find elements in the given HTML document
144 // see http://en.wikipedia.org/wiki/XPath_1.0
145 $xpath = new DOMXPath($this->readability->dom);
146
147 // try to get title
148 foreach ($this->config->title as $pattern) {
149 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
150 if (is_string($elems)) {
151 $this->debug('Title expression evaluated as string');
152 $this->title = trim($elems);
153 break;
154 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
155 $this->debug('Title matched');
156 $this->title = $elems->item(0)->textContent;
157 // remove title from document
158 try {
159 $elems->item(0)->parentNode->removeChild($elems->item(0));
160 } catch (DOMException $e) {
161 // do nothing
162 }
163 break;
164 }
165 }
166
167 // try to get author (if it hasn't already been set)
168 if (empty($this->author)) {
169 foreach ($this->config->author as $pattern) {
170 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
171 if (is_string($elems)) {
172 $this->debug('Author expression evaluated as string');
173 if (trim($elems) != '') {
174 $this->author[] = trim($elems);
175 break;
176 }
177 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
178 foreach ($elems as $elem) {
179 if (!isset($elem->parentNode)) continue;
180 $this->author[] = trim($elem->textContent);
181 }
182 if (!empty($this->author)) break;
183 }
184 }
185 }
186
187 // try to get language
188 $_lang_xpath = array('//html[@lang]/@lang', '//meta[@name="DC.language"]/@content');
189 foreach ($_lang_xpath as $pattern) {
190 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
191 if (is_string($elems)) {
192 if (trim($elems) != '') {
193 $this->language = trim($elems);
194 break;
195 }
196 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
197 foreach ($elems as $elem) {
198 if (!isset($elem->parentNode)) continue;
199 $this->language = trim($elem->textContent);
200 }
201 if ($this->language) break;
202 }
203 }
204
205 // try to get date
206 foreach ($this->config->date as $pattern) {
207 $elems = @$xpath->evaluate($pattern, $this->readability->dom);
208 if (is_string($elems)) {
209 $this->debug('Date expression evaluated as string');
210 $this->date = strtotime(trim($elems, "; \t\n\r\0\x0B"));
211 } elseif ($elems instanceof DOMNodeList && $elems->length > 0) {
212 $this->debug('Date matched');
213 $this->date = $elems->item(0)->textContent;
214 $this->date = strtotime(trim($this->date, "; \t\n\r\0\x0B"));
215 // remove date from document
216 // $elems->item(0)->parentNode->removeChild($elems->item(0));
217 }
218 if (!$this->date) {
219 $this->date = null;
220 } else {
221 break;
222 }
223 }
224
225 // strip elements (using xpath expressions)
226 foreach ($this->config->strip as $pattern) {
227 $elems = @$xpath->query($pattern, $this->readability->dom);
228 // check for matches
229 if ($elems && $elems->length > 0) {
230 $this->debug('Stripping '.$elems->length.' elements (strip)');
231 for ($i=$elems->length-1; $i >= 0; $i--) {
232 $elems->item($i)->parentNode->removeChild($elems->item($i));
233 }
234 }
235 }
236
237 // strip elements (using id and class attribute values)
238 foreach ($this->config->strip_id_or_class as $string) {
239 $string = strtr($string, array("'"=>'', '"'=>''));
240 $elems = @$xpath->query("//*[contains(@class, '$string') or contains(@id, '$string')]", $this->readability->dom);
241 // check for matches
242 if ($elems && $elems->length > 0) {
243 $this->debug('Stripping '.$elems->length.' elements (strip_id_or_class)');
244 for ($i=$elems->length-1; $i >= 0; $i--) {
245 $elems->item($i)->parentNode->removeChild($elems->item($i));
246 }
247 }
248 }
249
250 // strip images (using src attribute values)
251 foreach ($this->config->strip_image_src as $string) {
252 $string = strtr($string, array("'"=>'', '"'=>''));
253 $elems = @$xpath->query("//img[contains(@src, '$string')]", $this->readability->dom);
254 // check for matches
255 if ($elems && $elems->length > 0) {
256 $this->debug('Stripping '.$elems->length.' image elements');
257 for ($i=$elems->length-1; $i >= 0; $i--) {
258 $elems->item($i)->parentNode->removeChild($elems->item($i));
259 }
260 }
261 }
262 // strip elements using Readability.com and Instapaper.com ignore class names
263 // .entry-unrelated and .instapaper_ignore
264 // See https://www.readability.com/publishers/guidelines/#view-plainGuidelines
265 // and http://blog.instapaper.com/post/730281947
266 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' entry-unrelated ') or contains(concat(' ',normalize-space(@class),' '),' instapaper_ignore ')]", $this->readability->dom);
267 // check for matches
268 if ($elems && $elems->length > 0) {
269 $this->debug('Stripping '.$elems->length.' .entry-unrelated,.instapaper_ignore elements');
270 for ($i=$elems->length-1; $i >= 0; $i--) {
271 $elems->item($i)->parentNode->removeChild($elems->item($i));
272 }
273 }
274
275 // strip elements that contain style="display: none;"
276 $elems = @$xpath->query("//*[contains(@style,'display:none')]", $this->readability->dom);
277 // check for matches
278 if ($elems && $elems->length > 0) {
279 $this->debug('Stripping '.$elems->length.' elements with inline display:none style');
280 for ($i=$elems->length-1; $i >= 0; $i--) {
281 $elems->item($i)->parentNode->removeChild($elems->item($i));
282 }
283 }
284
285 // try to get body
286 foreach ($this->config->body as $pattern) {
287 $elems = @$xpath->query($pattern, $this->readability->dom);
288 // check for matches
289 if ($elems && $elems->length > 0) {
290 $this->debug('Body matched');
291 if ($elems->length == 1) {
292 $this->body = $elems->item(0);
293 // prune (clean up elements that may not be content)
294 if ($this->config->prune) {
295 $this->debug('Pruning content');
296 $this->readability->prepArticle($this->body);
297 }
298 break;
299 } else {
300 $this->body = $this->readability->dom->createElement('div');
301 $this->debug($elems->length.' body elems found');
302 foreach ($elems as $elem) {
303 if (!isset($elem->parentNode)) continue;
304 $isDescendant = false;
305 foreach ($this->body->childNodes as $parent) {
306 if ($this->isDescendant($parent, $elem)) {
307 $isDescendant = true;
308 break;
309 }
310 }
311 if ($isDescendant) {
312 $this->debug('Element is child of another body element, skipping.');
313 } else {
314 // prune (clean up elements that may not be content)
315 if ($this->config->prune) {
316 $this->debug('Pruning content');
317 $this->readability->prepArticle($elem);
318 }
319 $this->debug('Element added to body');
320 $this->body->appendChild($elem);
321 }
322 }
323 }
324 }
325 }
326
327 // auto detect?
328 $detect_title = $detect_body = $detect_author = $detect_date = false;
329 // detect title?
330 if (!isset($this->title)) {
331 if (empty($this->config->title) || $this->config->autodetect_on_failure) {
332 $detect_title = true;
333 }
334 }
335 // detect body?
336 if (!isset($this->body)) {
337 if (empty($this->config->body) || $this->config->autodetect_on_failure) {
338 $detect_body = true;
339 }
340 }
341 // detect author?
342 if (empty($this->author)) {
343 if (empty($this->config->author) || $this->config->autodetect_on_failure) {
344 $detect_author = true;
345 }
346 }
347 // detect date?
348 if (!isset($this->date)) {
349 if (empty($this->config->date) || $this->config->autodetect_on_failure) {
350 $detect_date = true;
351 }
352 }
353
354 // check for hNews
355 if ($detect_title || $detect_body) {
356 // check for hentry
357 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' hentry ')]", $this->readability->dom);
358 if ($elems && $elems->length > 0) {
359 $this->debug('hNews: found hentry');
360 $hentry = $elems->item(0);
361
362 if ($detect_title) {
363 // check for entry-title
364 $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-title ')]", $hentry);
365 if ($elems && $elems->length > 0) {
366 $this->debug('hNews: found entry-title');
367 $this->title = $elems->item(0)->textContent;
368 // remove title from document
369 $elems->item(0)->parentNode->removeChild($elems->item(0));
370 $detect_title = false;
371 }
372 }
373
374 if ($detect_date) {
375 // check for time element with pubdate attribute
376 $elems = @$xpath->query(".//time[@pubdate] | .//abbr[contains(concat(' ',normalize-space(@class),' '),' published ')]", $hentry);
377 if ($elems && $elems->length > 0) {
378 $this->debug('hNews: found publication date');
379 $this->date = strtotime(trim($elems->item(0)->textContent));
380 // remove date from document
381 //$elems->item(0)->parentNode->removeChild($elems->item(0));
382 if ($this->date) {
383 $detect_date = false;
384 } else {
385 $this->date = null;
386 }
387 }
388 }
389
390 if ($detect_author) {
391 // check for time element with pubdate attribute
392 $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' vcard ') and (contains(concat(' ',normalize-space(@class),' '),' author ') or contains(concat(' ',normalize-space(@class),' '),' byline '))]", $hentry);
393 if ($elems && $elems->length > 0) {
394 $this->debug('hNews: found author');
395 $author = $elems->item(0);
396 $fn = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' fn ')]", $author);
397 if ($fn && $fn->length > 0) {
398 foreach ($fn as $_fn) {
399 if (trim($_fn->textContent) != '') {
400 $this->author[] = trim($_fn->textContent);
401 }
402 }
403 } else {
404 if (trim($author->textContent) != '') {
405 $this->author[] = trim($author->textContent);
406 }
407 }
408 $detect_author = empty($this->author);
409 }
410 }
411
412 // check for entry-content.
413 // according to hAtom spec, if there are multiple elements marked entry-content,
414 // we include all of these in the order they appear - see http://microformats.org/wiki/hatom#Entry_Content
415 if ($detect_body) {
416 $elems = @$xpath->query(".//*[contains(concat(' ',normalize-space(@class),' '),' entry-content ')]", $hentry);
417 if ($elems && $elems->length > 0) {
418 $this->debug('hNews: found entry-content');
419 if ($elems->length == 1) {
420 // what if it's empty? (some sites misuse hNews - place their content outside an empty entry-content element)
421 $e = $elems->item(0);
422 if (($e->tagName == 'img') || (trim($e->textContent) != '')) {
423 $this->body = $elems->item(0);
424 // prune (clean up elements that may not be content)
425 if ($this->config->prune) {
426 $this->debug('Pruning content');
427 $this->readability->prepArticle($this->body);
428 }
429 $detect_body = false;
430 } else {
431 $this->debug('hNews: skipping entry-content - appears not to contain content');
432 }
433 unset($e);
434 } else {
435 $this->body = $this->readability->dom->createElement('div');
436 $this->debug($elems->length.' entry-content elems found');
437 foreach ($elems as $elem) {
438 if (!isset($elem->parentNode)) continue;
439 $isDescendant = false;
440 foreach ($this->body->childNodes as $parent) {
441 if ($this->isDescendant($parent, $elem)) {
442 $isDescendant = true;
443 break;
444 }
445 }
446 if ($isDescendant) {
447 $this->debug('Element is child of another body element, skipping.');
448 } else {
449 // prune (clean up elements that may not be content)
450 if ($this->config->prune) {
451 $this->debug('Pruning content');
452 $this->readability->prepArticle($elem);
453 }
454 $this->debug('Element added to body');
455 $this->body->appendChild($elem);
456 }
457 }
458 $detect_body = false;
459 }
460 }
461 }
462 }
463 }
464
465 // check for elements marked with instapaper_title
466 if ($detect_title) {
467 // check for instapaper_title
468 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_title ')]", $this->readability->dom);
469 if ($elems && $elems->length > 0) {
470 $this->debug('title found (.instapaper_title)');
471 $this->title = $elems->item(0)->textContent;
472 // remove title from document
473 $elems->item(0)->parentNode->removeChild($elems->item(0));
474 $detect_title = false;
475 }
476 }
477 // check for elements marked with instapaper_body
478 if ($detect_body) {
479 $elems = @$xpath->query("//*[contains(concat(' ',normalize-space(@class),' '),' instapaper_body ')]", $this->readability->dom);
480 if ($elems && $elems->length > 0) {
481 $this->debug('body found (.instapaper_body)');
482 $this->body = $elems->item(0);
483 // prune (clean up elements that may not be content)
484 if ($this->config->prune) {
485 $this->debug('Pruning content');
486 $this->readability->prepArticle($this->body);
487 }
488 $detect_body = false;
489 }
490 }
491
492 // Find author in rel="author" marked element
493 // We only use this if there's exactly one.
494 // If there's more than one, it could indicate more than
495 // one author, but it could also indicate that we're processing
496 // a page listing different articles with different authors.
497 if ($detect_author) {
498 $elems = @$xpath->query("//a[contains(concat(' ',normalize-space(@rel),' '),' author ')]", $this->readability->dom);
499 if ($elems && $elems->length == 1) {
500 $this->debug('Author found (rel="author")');
501 $author = trim($elems->item(0)->textContent);
502 if ($author != '') {
503 $this->author[] = $author;
504 $detect_author = false;
505 }
506 }
507 }
508
509 // Find date in pubdate marked time element
510 // For the same reason given above, we only use this
511 // if there's exactly one element.
512 if ($detect_date) {
513 $elems = @$xpath->query("//time[@pubdate]", $this->readability->dom);
514 if ($elems && $elems->length == 1) {
515 $this->debug('Date found (pubdate marked time element)');
516 $this->date = strtotime(trim($elems->item(0)->textContent));
517 // remove date from document
518 //$elems->item(0)->parentNode->removeChild($elems->item(0));
519 if ($this->date) {
520 $detect_date = false;
521 } else {
522 $this->date = null;
523 }
524 }
525 }
526
527 // still missing title or body, so we detect using Readability
528 if ($detect_title || $detect_body) {
529 $this->debug('Using Readability');
530 // clone body if we're only using Readability for title (otherwise it may interfere with body element)
531 if (isset($this->body)) $this->body = $this->body->cloneNode(true);
532 $success = $this->readability->init();
533 }
534 if ($detect_title) {
535 $this->debug('Detecting title');
536 $this->title = $this->readability->getTitle()->textContent;
537 }
538 if ($detect_body && $success) {
539 $this->debug('Detecting body');
540 $this->body = $this->readability->getContent();
541 if ($this->body->childNodes->length == 1 && $this->body->firstChild->nodeType === XML_ELEMENT_NODE) {
542 $this->body = $this->body->firstChild;
543 }
544 // prune (clean up elements that may not be content)
545 if ($this->config->prune) {
546 $this->debug('Pruning content');
547 $this->readability->prepArticle($this->body);
548 }
549 }
550 if (isset($this->body)) {
551 // remove scripts
552 $this->readability->removeScripts($this->body);
553 // remove any h1-h6 elements that appear as first thing in the body
554 // and which match our title
555 if (isset($this->title) && ($this->title != '')) {
556 $firstChild = $this->body->firstChild;
557 while ($firstChild->nodeType && ($firstChild->nodeType !== XML_ELEMENT_NODE)) {
558 $firstChild = $firstChild->nextSibling;
559 }
560 if (($firstChild->nodeType === XML_ELEMENT_NODE)
561 && in_array(strtolower($firstChild->tagName), array('h1', 'h2', 'h3', 'h4', 'h5', 'h6'))
562 && (strtolower(trim($firstChild->textContent)) == strtolower(trim($this->title)))) {
563 $this->body->removeChild($firstChild);
564 }
565 }
566 $this->success = true;
567 }
568
569 // if we've had no success and we've used tidy, there's a chance
570 // that tidy has messed up. So let's try again without tidy...
571 if (!$this->success && $tidied && $smart_tidy) {
572 $this->debug('Trying again without tidy');
573 $this->process($original_html, $url, false);
574 }
575
576 return $this->success;
577 }
578
579 private function isDescendant(DOMElement $parent, DOMElement $child) {
580 $node = $child->parentNode;
581 while ($node != null) {
582 if ($node->isSameNode($parent)) return true;
583 $node = $node->parentNode;
584 }
585 return false;
586 }
587
588 public function getContent() {
589 return $this->body;
590 }
591
592 public function getTitle() {
593 return $this->title;
594 }
595
596 public function getAuthors() {
597 return $this->author;
598 }
599
600 public function getLanguage() {
601 return $this->language;
602 }
603
604 public function getDate() {
605 return $this->date;
606 }
607
608 public function getSiteConfig() {
609 return $this->config;
610 }
611}
612?> \ No newline at end of file
diff --git a/inc/3rdparty/content-extractor/SiteConfig.php b/inc/3rdparty/content-extractor/SiteConfig.php
deleted file mode 100644
index efb229dd..00000000
--- a/inc/3rdparty/content-extractor/SiteConfig.php
+++ /dev/null
@@ -1,184 +0,0 @@
1<?php
2/**
3 * Site Config
4 *
5 * Each instance of this class should hold extraction patterns and other directives
6 * for a website. See ContentExtractor class to see how it's used.
7 *
8 * @version 0.6
9 * @date 2011-10-30
10 * @author Keyvan Minoukadeh
11 * @copyright 2011 Keyvan Minoukadeh
12 * @license http://www.gnu.org/licenses/agpl-3.0.html AGPL v3
13 */
14
15class SiteConfig
16{
17 // Use first matching element as title (0 or more xpath expressions)
18 public $title = array();
19
20 // Use first matching element as body (0 or more xpath expressions)
21 public $body = array();
22
23 // Use first matching element as author (0 or more xpath expressions)
24 public $author = array();
25
26 // Use first matching element as date (0 or more xpath expressions)
27 public $date = array();
28
29 // Strip elements matching these xpath expressions (0 or more)
30 public $strip = array();
31
32 // Strip elements which contain these strings (0 or more) in the id or class attribute
33 public $strip_id_or_class = array();
34
35 // Strip images which contain these strings (0 or more) in the src attribute
36 public $strip_image_src = array();
37
38 // Additional HTTP headers to send
39 // NOT YET USED
40 public $http_header = array();
41
42 // Process HTML with tidy before creating DOM
43 public $tidy = true;
44
45 // Autodetect title/body if xpath expressions fail to produce results.
46 // Note that this applies to title and body separately, ie.
47 // * if we get a body match but no title match, this option will determine whether we autodetect title
48 // * if neither match, this determines whether we autodetect title and body.
49 // Also note that this only applies when there is at least one xpath expression in title or body, ie.
50 // * if title and body are both empty (no xpath expressions), this option has no effect (both title and body will be auto-detected)
51 // * if there's an xpath expression for title and none for body, body will be auto-detected and this option will determine whether we auto-detect title if the xpath expression for it fails to produce results.
52 // Usage scenario: you want to extract something specific from a set of URLs, e.g. a table, and if the table is not found, you want to ignore the entry completely. Auto-detection is unlikely to succeed here, so you construct your patterns and set this option to false. Another scenario may be a site where auto-detection has proven to fail (or worse, picked up the wrong content).
53 public $autodetect_on_failure = true;
54
55 // Clean up content block - attempt to remove elements that appear to be superfluous
56 public $prune = true;
57
58 // Test URL - if present, can be used to test the config above
59 public $test_url = null;
60
61 // Single-page link - should identify a link element or URL pointing to the page holding the entire article
62 // This is useful for sites which split their articles across multiple pages. Links to such pages tend to
63 // display the first page with links to the other pages at the bottom. Often there is also a link to a page
64 // which displays the entire article on one page (e.g. 'print view').
65 // This should be an XPath expression identifying the link to that page. If present and we find a match,
66 // we will retrieve that page and the rest of the options in this config will be applied to the new page.
67 public $single_page_link = array();
68
69 // Single-page link in feed? - same as above, but patterns applied to item description HTML taken from feed
70 public $single_page_link_in_feed = array();
71
72 // TODO: which parser to use for turning raw HTML into a DOMDocument
73 public $parser = 'libxml';
74
75 // String replacement to be made on HTML before processing begins
76 public $replace_string = array();
77
78 // the options below cannot be set in the config files which this class represents
79
80 public static $debug = false;
81 protected static $config_path;
82 protected static $config_path_fallback;
83 protected static $config_cache = array();
84 const HOSTNAME_REGEX = '/^(([a-zA-Z0-9-]*[a-zA-Z0-9])\.)*([A-Za-z0-9-]*[A-Za-z0-9])$/';
85
86 protected static function debug($msg) {
87 if (self::$debug) {
88 $mem = round(memory_get_usage()/1024, 2);
89 $memPeak = round(memory_get_peak_usage()/1024, 2);
90 echo '* ',$msg;
91 echo ' - mem used: ',$mem," (peak: $memPeak)\n";
92 ob_flush();
93 flush();
94 }
95 }
96
97 public static function set_config_path($path, $fallback=null) {
98 self::$config_path = $path;
99 self::$config_path_fallback = $fallback;
100 }
101
102 public static function add_to_cache($host, SiteConfig $config) {
103 $host = strtolower($host);
104 self::$config_cache[$host] = $config;
105 }
106
107 // returns SiteConfig instance if an appropriate one is found, false otherwise
108 public static function build($host) {
109 $host = strtolower($host);
110 if (substr($host, 0, 4) == 'www.') $host = substr($host, 4);
111 if (!$host || (strlen($host) > 200) || !preg_match(self::HOSTNAME_REGEX, $host)) return false;
112 // check for site configuration
113 $try = array($host);
114 $split = explode('.', $host);
115 if (count($split) > 1) {
116 array_shift($split);
117 $try[] = implode('.', $split);
118 }
119 foreach ($try as $h) {
120 if (array_key_exists($h, self::$config_cache)) {
121 self::debug("... cached ($h)");
122 return self::$config_cache[$h];
123 } elseif (file_exists(self::$config_path."/$h.txt")) {
124 self::debug("... from file ($h)");
125 $file = self::$config_path."/$h.txt";
126 break;
127 }
128 }
129 if (!isset($file)) {
130 if (isset(self::$config_path_fallback)) {
131 self::debug("... trying fallback ($host)");
132 foreach ($try as $h) {
133 if (file_exists(self::$config_path_fallback."/$h.txt")) {
134 self::debug("... from fallback file ($h)");
135 $file = self::$config_path_fallback."/$h.txt";
136 break;
137 }
138 }
139 if (!isset($file)) {
140 self::debug("... no match in fallback directory");
141 return false;
142 }
143 } else {
144 self::debug("... no match ($host)");
145 return false;
146 }
147 }
148 $config_file = file($file, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
149 if (!$config_file || !is_array($config_file)) return false;
150 $config = new SiteConfig();
151 foreach ($config_file as $line) {
152 $line = trim($line);
153
154 // skip comments, empty lines
155 if ($line == '' || $line[0] == '#') continue;
156
157 // get command
158 $command = explode(':', $line, 2);
159 // if there's no colon ':', skip this line
160 if (count($command) != 2) continue;
161 $val = trim($command[1]);
162 $command = trim($command[0]);
163 if ($command == '' || $val == '') continue;
164
165 // check for commands where we accept multiple statements
166 if (in_array($command, array('title', 'body', 'author', 'date', 'strip', 'strip_id_or_class', 'strip_image_src', 'single_page_link', 'single_page_link_in_feed', 'http_header'))) {
167 array_push($config->$command, $val);
168 // check for single statement commands that evaluate to true or false
169 } elseif (in_array($command, array('tidy', 'prune', 'autodetect_on_failure'))) {
170 $config->$command = ($val == 'yes');
171 // check for single statement commands stored as strings
172 } elseif (in_array($command, array('test_url', 'parser'))) {
173 $config->$command = $val;
174 } elseif ((substr($command, -1) == ')') && preg_match('!^([a-z0-9_]+)\((.*?)\)$!i', $command, $match)) {
175 if (in_array($match[1], array('replace_string'))) {
176 $command = $match[1];
177 array_push($config->$command, array($match[2], $val));
178 }
179 }
180 }
181 return $config;
182 }
183}
184?>