Externe Seiten in MODx cachen

von Thomas Jakobi am Freitag, 14. Dezember 2007 um 09:24 Uhr.

Manchmal möchte man Inhalte einer externen Webseite in MODx zwischenspeichern, z.B. wenn der Zugriff auf die externen Daten nur langsam funktioniert. Mit Hausmitteln von MODx ist dies leider nicht möglich. Aus diesem Grund ist das GetCached Snippet entstanden.

Das Snippet kann in einem MODx-Dokument aufgerufen werden und erwartet folgende Parameter:

  • &docid – Die Dokument-ID in der der Inhalt der externen Website abgespeichert wird
  • &geturl – Die URL der externe Website (Folgende Zeichen müssen maskiert werden: '?' als 'q', '=' als '!eq!' und '&' als '!and!')
  • &utf8encode – 1 = Umwandeln des Encoding des Inhalts der externen Website in UTF-8

 

Durch den Aufruf des Snippet-Dokuments per Cronjob ist z.B. eine tägliche Aktualisierung der gecachten Ablage eines 'fremden' Dokuments möglich.

GetCached.snippet.php
<?php
// GetCached
// Saves the content of an URL to the content of a document
// License GPL
// Written 12-2007 by Bitte Javascript aktivieren!
//
// Parameter:
// &docid – id of the published document the content of the url will be saved to 
// &geturl – url to save
// &utf8encode – 1 = translate the charset of the content of the url from ISO-8859-1 to UTF-8
//
// [!GetCached? &docid=`1` &geturl=`http://www.sample.url/document.html`!]
// will load the content of http://www.sample.url/document.html to the content of the document 1.
// '?' in the url have to be masked as '!q!'
// '=' in the url have to be masked as '!eq!'
// '&' in the url have to be masked as '!and!'
 
$docid = isset ($docid) ? $docid : -1;
$geturl = isset ($geturl) ? $geturl : '';
$utf8encode = isset ($utf8encode) ? $utf8encode : 0;
$geturl = ereg_replace('!q!', '?', $geturl);
$geturl = ereg_replace('!eq!', '=', $geturl);
$geturl = ereg_replace('!and!', '&', $geturl);
echo $docid . ' – ' . $geturl . ' – ';
$document = $modx->getDocumentObject('id', $docid);
if (empty ($document)) {
    return;
} // The document has to be published
$url = curl_init($geturl);
curl_setopt($url, CURLOPT_RETURNTRANSFER, 1);
$data = curl_exec($url);
curl_close($url);
if (!$data) {
    return 'Seite nicht gefunden!<br />';
}
$data = trim($data);
if ($utf8encode) {
    $data = utf8_encode($data);
}
$table = $modx->getFullTableName('site_content');
$fields = array('content' => $data, 'editedon' => time());
$result = $modx->db->update($fields, $table, 'id = "' . $docid . '"');
if ($result) {
    return 'Seite geändert.<br />';
} else {
    return 'Fehler!<br />';
}