sepiariver
9/14/2014 - 1:14 AM

StatCacheOnDemand snippet for MODX - see: http://www.sepiariver.ca/blog/modx-web/statcache-optimized-cms-website-performance/

<?php
/*
 * Copyright (c) YJ Tso <info@sepiariver.com>
 *
 * GPL2, do what you want at your own risk. No warranties whatsoever.
 *
 */

// Get &resources property from snippet call
$ids = array_map('trim', explode(',', $modx->getOption('resources', $scriptProperties, '')));

// Debugging
$debug = false;

// Loop through resources
foreach ($ids as $id) {
    
    // check and get
    if (empty($id)) continue;
    $res = $modx->getObject('modResource', (int) $id);
    if ($debug) echo var_dump($res->pagetitle) . ' Line: ' . __LINE__ . PHP_EOL;
    
    // clear the standard MODX cache 
    // * this is kinda heavy-handed, would not suggest doing this on page request, but rather Manager action only
    $modx->cacheManager->refresh();

    // assemble curl
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_USERAGENT, $modx->getOption('regenerate_useragent', $scriptProperties, 'MODX RegenCache'));
    curl_setopt($curl, CURLOPT_HTTPHEADER, array('X-StatCache-Regen: 1'));
    curl_setopt($curl, CURLOPT_FAILONERROR, false);
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, false);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    if ($debug) {
        curl_setopt($curl, CURLOPT_NOBODY, false);
    } else {
        curl_setopt($curl, CURLOPT_NOBODY, true);
    }
    
    // request the resource to trigger cache regen
    $url = $modx->makeUrl($res->get('id'), '', '', 'full');
    if (!empty($url)) {
        $modx->log(modX::LOG_LEVEL_INFO, "Requesting resource at {$url}");
        if ($debug) echo var_dump($url) . ' Line: ' . __LINE__ . PHP_EOL;
        curl_setopt($curl, CURLOPT_URL, $url);
        $response = curl_exec($curl);
        if ($debug) echo var_dump($response) . ' Line: ' . __LINE__ . PHP_EOL;
        $modx->log(modX::LOG_LEVEL_INFO, "cURL request complete for resource at {$url}");
    }
    curl_close($curl);
    
}

// Returns nothing
return;