<?php
namespace Contao;
use Jaybizzle\CrawlerDetect\CrawlerDetect;
use Contao\System;
abstract class PrerenderableContentElement extends ContentElement
{
protected $templateMarkerName = '___default___';
public function generate()
{
$this->templateMarkerName = $this->templateMarkerName . $this->id;
$this->queueRendering();
if (!$this->cacheExists() || !$this->isCrawler()) {
return parent::generate();
}
return $this->getMarkedRange($this->loadCache());
}
protected function queueRendering()
{
// Request every time a crawler requests this page
// and one in 20 times a regular user requests it.
if (!$this->isCrawler() && rand(1, 20) !== 5) return;
$urlString = PrerenderFilenameGenerator::getUrlString();
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://websnapper.sttgs.de/add/' . urlencode($urlString));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_TIMEOUT_MS, 100);
$res = curl_exec($ch);
curl_close($ch);
}
protected function isCrawler()
{
$detect = new CrawlerDetect;
return $detect->isCrawler();
}
protected function cacheExists()
{
return file_exists(PrerenderFilenameGenerator::getCacheFilename());
}
protected function loadCache()
{
return file_get_contents(PrerenderFilenameGenerator::getCacheFilename());
}
protected function getMarkedRange($string)
{
$start = stripos($string, $this->startMarker());
$end = stripos($string, $this->endMarker());
// If the marked range can't be found, generate anew.
if (!$start || !$end) {
return parent::generate();
}
return substr($string, $start, $end - $start + strlen($this->endMarker()));
}
public function startMarker()
{
return "<!-- MARKER_{$this->templateMarkerName} -->";
}
public function endMarker()
{
return "<!-- ENDMARKER_{$this->templateMarkerName} -->";
}
protected function setupTemplate()
{
$this->Template->startMarker = [$this, 'startMarker'];
$this->Template->endMarker = [$this, 'endMarker'];
}
}