• Welcome to the Chevereto User Community!

    Here, users from all over the world come together to learn, share, and collaborate on everything related to Chevereto. It's a place to exchange ideas, ask questions, and help improve the software.

    Please keep in mind:

    • This community is user-driven. Always be polite and respectful to others.
    • Support development by purchasing a Chevereto license, which also gives you priority support.
    • Go further by joining the Community Subscription for even faster response times and to help sustain this space
  • Chevereto Support CLST

    Support response

    Support checklist

    • Got a Something went wrong message? Read this guide and provide the actual error. Do not skip this.
    • Confirm that the server meets the System Requirements
    • Check for any available Hotfix - your issue could be already reported/fixed
    • Read documentation - It will be required to Debug and understand Errors for a faster support response

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:
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.
good !
 
Hi all, there is a new update version for Chevereto v4.3.4

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("frame",$image['file_resource']['chain'])) {
            $imagelink[] = $image['file_resource']['chain']['frame'];
        };
        if (array_key_exists("medium",$image['file_resource']['chain'])) {
            $imagelink[] = $image['file_resource']['chain']['medium'];
        };
        if (array_key_exists("thumb",$image['file_resource']['chain'])) {
            $imagelink[] = $image['file_resource']['chain']['thumb'];
        };
        // End of additional Part 1
Find:
PHP:
'content_original_filename' => $image['original_filename'],
Add code below the above code:
PHP:
PHP:
// additional content for CF clear cache
'content_addition'    => json_encode($imagelink),

In cron.php (app/legacy/commands)
Find:
PHP:
$jobs = [
    'deleteExpiredFiles',
    'cleanUnconfirmedUsers',
    'removeDeleteLog',
    'storageDelete',
    'deleteExpiredUploads',
];
Replace it with:
PHP:
$jobs = [
    'deleteExpiredFiles',
    'cleanUnconfirmedUsers',
    'removeDeleteLog',
    'storageDelete',
    'deleteExpiredUploads',
    '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, X-Auth-Email and the global API key.

This script works with Chevereto cron task, please make sure your chevereto cron task works well.

UPDATE 2025-05-29(GMT+8) : Im using s3 storage for my files, and I found that if the system fail to upload the file to s3 storage and fallback the image to local storage, the url will goes wrong, it will become "/home/www/yourwebsiteroot/images/XYZ.png", etc. Dont know how to handle this case😱 Maybe the 'file_resource' will become the server real path when using the local storage😵
 
Last edited:
Back
Top