bundles/dieschittigs/iconic/src/Resources/contao/elements/PrerenderableContentElement.php line 12

Open in your IDE?
  1. <?php
  2. namespace Contao;
  3. use Jaybizzle\CrawlerDetect\CrawlerDetect;
  4. use Contao\System;
  5. abstract class PrerenderableContentElement extends ContentElement
  6. {
  7. protected $templateMarkerName = '___default___';
  8. public function generate()
  9. {
  10. $this->templateMarkerName = $this->templateMarkerName . $this->id;
  11. $this->queueRendering();
  12. if (!$this->cacheExists() || !$this->isCrawler()) {
  13. return parent::generate();
  14. }
  15. return $this->getMarkedRange($this->loadCache());
  16. }
  17. protected function queueRendering()
  18. {
  19. // Request every time a crawler requests this page
  20. // and one in 20 times a regular user requests it.
  21. if (!$this->isCrawler() && rand(1, 20) !== 5) return;
  22. $urlString = PrerenderFilenameGenerator::getUrlString();
  23. $ch = curl_init();
  24. curl_setopt($ch, CURLOPT_URL, 'http://websnapper.sttgs.de/add/' . urlencode($urlString));
  25. curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  26. curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
  27. $res = curl_exec($ch);
  28. curl_close($ch);
  29. }
  30. protected function isCrawler()
  31. {
  32. $detect = new CrawlerDetect;
  33. return $detect->isCrawler();
  34. }
  35. protected function cacheExists()
  36. {
  37. return file_exists(PrerenderFilenameGenerator::getCacheFilename());
  38. }
  39. protected function loadCache()
  40. {
  41. return file_get_contents(PrerenderFilenameGenerator::getCacheFilename());
  42. }
  43. protected function getMarkedRange($string)
  44. {
  45. $start = stripos($string, $this->startMarker());
  46. $end = stripos($string, $this->endMarker());
  47. // If the marked range can't be found, generate anew.
  48. if (!$start || !$end) {
  49. return parent::generate();
  50. }
  51. return substr($string, $start, $end - $start + strlen($this->endMarker()));
  52. }
  53. public function startMarker()
  54. {
  55. return "<!-- MARKER_{$this->templateMarkerName} -->";
  56. }
  57. public function endMarker()
  58. {
  59. return "<!-- ENDMARKER_{$this->templateMarkerName} -->";
  60. }
  61. protected function setupTemplate()
  62. {
  63. $this->Template->startMarker = [$this, 'startMarker'];
  64. $this->Template->endMarker = [$this, 'endMarker'];
  65. }
  66. }