Here is my first plugin:
<?php
/**
* Plugin class for update the Cloudflare Cache after save a article
*/
class plgContentBk_onsave extends JPlugin
{
public function onContentAfterSave ($context, $article, $isNew)
{
// I have saved the URL in a custom field by the article to protect against duplicate content.
// I use this field for <link rel="canonical" href="..."> too.
// so I get the URl from the article:
$context = 'com_content.article';
$article = JModelLegacy::getInstance('Article', 'ContentModel')->getItem();
JLoader::register('FieldsHelper', JPATH_ADMINISTRATOR . '/components/com_fields/helpers/fields.php'); // Helper to get the field by the article
$fields = FieldsHelper::getFields($context, $article);
$fields = json_decode(json_encode($fields), true); // convert to a array
$url = $fields[0]["value"]; // Get the URL from the Field $fields[0]["value"] the custom field in the article
// if you want to see all your custom fields : var_dump($fields)
// Okay now the part that delete the Cloudflare cache:
$authKey = "XXX";
$authEmail = "XXX";
$zoneId = "XXX";
$endpoint = "purge_cache";
$data = '{"files":[
"'.$url.'"
]}';
$url = "https://api.cloudflare.com/client/v4/zones/{$zoneId}/{$endpoint}";
$opts = ['http' => [
'method' => 'DELETE',
'header' => [
"Content-Type: application/json",
"X-Auth-Key: {$authKey}",
"X-Auth-Email: {$authEmail}",
],
'content' => $data,
]];
$context = stream_context_create($opts);
$result = file_get_contents($url, false, $context);
// to sse the Cloudflare result use: var_dump($result);
// add exit; to see all otputs like var_dumps
return true;
}
}
?>
Tested and works fine. After save the article the Cloudflare CDN for the one url is purged.
Any improvements are welcome.
Thanks to all here for your support to solve my problem.
I have added to see the succes after save:
ob_start();
var_dump($result);
$ext = ob_get_clean();
// to see the Cloudflare result use: var_dump($result);
// add exit; to see all otputs like var_dumps
$application = JFactory::getApplication();
$message="Cloudflare Update von: ".$fields[0]["value"]."<br>".$ext; $type="notice";
$application->enqueueMessage(JText::_($message), 'notice');
onContentAfterSave
event. – Lodder Jan 8 '19 at 18:48