• Welcome to the Chevereto user community!

    Here users from all over the world gather around to learn the latest about Chevereto and contribute with ideas to improve the software.

    Please keep in mind:

    • 😌 This community is user driven. Be polite with other users.
    • 👉 Is required to purchase a Chevereto license to participate in this community (doesn't apply to Pre-sales).
    • 💸 Purchase a Pro Subscription to get access to active software support and faster ticket response times.
  • Chevereto Support CLST

    Support response

    Support checklist

Try to purge cache for Cloudflare when image was deleted

koxle

Chevereto Member
Hi All,

I tried to add this function to my website.
As a PHP newbie, please tell me if the code has any mistake or can be improved.
Below is my workflow.

Visit Cloudflare -> Select my domain -> Get the zone ID -> Get the Global API KEY

Database chv_deletions,
Add 2 new columns
1. "deleted_content_addition" Type: TEXT Checked:NULL
2. "deleted_content_timestamp" Type: TIMESTAMP Default : CURRENT_TIMESTAMP Checked:NULL

In class.image.php (app/lib/classes)
Find:
Code:
// Log image deletion
Add below code above of this:
PHP:
$imagelink[] = $image['file_resource']['chain']['image'];
if ($image['file_resource']['chain']['thumb'] !== NULL){
    $imagelink[] = $image['file_resource']['chain']['thumb'];
};
if ($image['file_resource']['chain']['medium'] !== NULL) {
    $imagelink[] = $image['file_resource']['chain']['medium'];
};
Find:
PHP:
'content_original_filename'    => $image['original_filename'],
Add below code below the above code:
PHP:
'content_addition'    => json_encode($imagelink),

Create route.cron.php at app/routes/overrides:
Add below code:
PHP:
<?php
/* Just an example of route extension */
$route = function ($handler) {
    $db = CHV\DB::getInstance();
                $db->query('SELECT deleted_content_addition FROM ' . CHV\DB::getTable('deletions') . ' WHERE deleted_content_addition IS NOT NULL AND deleted_content_timestamp > (NOW() - INTERVAL 2 MINUTE)');
                $result = $db->fetchAll();
                $new_data = array();
                $filelist['files'] = array();
                $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($result));
                foreach($it as $v) {
                    $v = json_decode($v);
                    $new_data[] = $v;
                }
                $it1 = new RecursiveIteratorIterator(new RecursiveArrayIterator($new_data));
                foreach($it1 as $v1) {
                    $filelist['files'][] = $v1;;
                }
                $string = json_encode($filelist);
                if (is_null($filelist['files'][0])){
                    die("Diu! No job do ar");
                }

                $ch = curl_init();

                curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/zones/****ZONE ID****/purge_cache');
                curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
                curl_setopt($ch, CURLOPT_POST, 1);
                curl_setopt($ch, CURLOPT_POSTFIELDS,$string);

                $headers = array();
                $headers[] = 'X-Auth-Email: youecloudflareaccount@example.com';
                $headers[] = 'X-Auth-Key: **You Account Global API Key**';
                $headers[] = 'Content-Type: application/json';
                curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

                $result = curl_exec($ch);
                if (curl_errno($ch)) {
                    echo 'Error:' . curl_error($ch);
                }
                curl_close($ch);

                die("Job Done");
};

Please do remember to replace the zone ID and the global API key.

Create Cron job:
Code:
* * * * * curl https://example.com/cron

Then the system will purge the cache of deleted images(the images which were deleted from now to 2 mins ago).
The Cron job runs every minute. The system won't connect to CF API when there is no deleted image at the nearest 2 mins.
 
Hi all, there is a new update version for Chevereto v4 (Tested on v4.0.7)

Follow the old way at the first step,
Visit Cloudflare -> Select my domain -> Get the zone ID -> Get the Global API KEY.

Database chv_deletions,
Add two new columns
1. "deleted_content_addition" Type: TEXT Checked: NULL
2. "deleted_content_timestamp" Type: TIMESTAMP Default: CURRENT_TIMESTAMP Checked: NULL

In Image.php (app/src/Legacy/Classes)

Find:
PHP:
DB::delete('likes', ['content_type' => 'image', 'content_id' => $image['id']]);
Add the below code above this:
PHP:
// Start of additional part 1
$imagelink[] = $image['file_resource']['chain']['image'];
if (array_key_exists("thumb",$image['file_resource']['chain'])) {
    $imagelink[] = $image['file_resource']['chain']['thumb'];
};
if (array_key_exists("medium",$image['file_resource']['chain'])) {
    $imagelink[] = $image['file_resource']['chain']['medium'];
};
// End of additional Part 1
Find:
PHP:
'content_original_filename' => $image['original_filename'],
Add code below the above code:
PHP:
// additional content for CF clear cache
'content_addition'    => json_encode($imagelink),

In cron.php (app/legacy/commands)
Find:
PHP:
$jobs = ['deleteExpiredImages', 'cleanUnconfirmedUsers', 'removeDeleteLog', 'checkForNews'];
Replace with the below code:
PHP:
$jobs = ['deleteExpiredImages', 'cleanUnconfirmedUsers', 'removeDeleteLog', 'checkForNews', 'clearCFcache'];
Add below code at the end of this cron.php
PHP:
function clearCFcache(): void
{
    $job = 'clear-CFcache';
    $lock = new Lock($job);
    if ($lock->create()) {
        $db = DB::getInstance();
        $db->query('SELECT deleted_content_addition FROM ' . DB::getTable('deletions') . ' WHERE deleted_content_addition IS NOT NULL AND deleted_content_timestamp > (NOW() - INTERVAL 10 MINUTE)');
        $result = $db->fetchAll();
        $new_data = array();
        $filelist['files'] = array();
        $it = new RecursiveIteratorIterator(new RecursiveArrayIterator($result));
        foreach($it as $v) {
            $v = json_decode($v);
            $new_data[] = $v;
        }
        $it1 = new RecursiveIteratorIterator(new RecursiveArrayIterator($new_data));
        foreach($it1 as $v1) {
            $filelist['files'][] = $v1;
        }
        $string = json_encode($filelist);


        $ch = curl_init();


        curl_setopt($ch, CURLOPT_URL, 'https://api.cloudflare.com/client/v4/zones/****ZONE ID****/purge_cache');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 1);
        curl_setopt($ch, CURLOPT_POSTFIELDS,$string);


        $headers = array();
        $headers[] = 'X-Auth-Email: youecloudflareaccount@example.com';
        $headers[] = 'X-Auth-Key: **You Account Global API Key**';
        $headers[] = 'Content-Type: application/json';
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);


        $result = curl_exec($ch);
        if (curl_errno($ch)) {
            echo 'Error:' . curl_error($ch);
        }
        curl_close($ch);
       
        $lock->destroy();


        return;
    }
    echoLocked($job);
}

Please remember to replace the zone ID and the global API key.
 
Last edited:
Back
Top