Self-Hosted Faux-API Script for Cotton Bureau Shirt Sales Data
<?php
header('Content-Type: application:json');
header("Access-Control-Allow-Origin: *");
/* CONFIG - EDIT THESE VARIABLEs TO YOUR HEART'S CONTENT */
$shirt_url = 'https://cottonbureau.com/products/your-shirt';
$cache_duration = 60; // in minutes
$notification_email = 'test@test.com';
$notification_from_header = 'From: CB Notification <no-reply@your-spf-safe-domain.com>';
/* NOPE - DON'T EDIT ANYTHING BELOW THIS LINE! */
function trim_data($content, $str_start, $str_end) {
$t_length = strlen($str_start);
$start = strpos($content, $str_start) + $t_length;
$end = strpos($content, $str_end, $start);
$length = $end - $start;
$data = substr($content, $start, $length) ? substr($content, $start, $length) : null;
return $data;
}
function curl_download($Url){
if (!function_exists('curl_init')){
die('cURL is not installed. Install and try again.');
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $Url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$output = curl_exec($ch);
curl_close($ch);
$sold = trim_data($output, 'data-sold="', '"');
$days_left = trim_data($output, '<span class="Meter-num">', '</span');
$return = array(
'sold' => $sold,
'days_left' => $days_left);
$return['meta']['cached'] = true;
$return['meta']['cache_time'] = date("Y-m-d H:i:s");
return $return;
}
$json = json_decode( file_get_contents('cb.json') );
$current_time = new DateTime('now');
$cache_time = new DateTime($json->meta->cache_time);
$interval = $current_time->diff($cache_time, true);
if ( $interval->i > $cache_duration ) :
$cb = curl_download( $shirt_url );
chmod('cb.json', 0777);
file_put_contents('cb.json', json_encode($cb));
chmod('cb.json', 0664);
echo json_encode($cb);
$cb['meta']['cached'] = false;
if ( $json->sold !== $cb['sold'] ) :
$address = $notification_email;
$subject = sprintf('CB Shirt Update: %s', $cb['sold']);
$msg = sprintf('You’re up to %s shirts!', $cb['sold']);
$from = $notification_from_header;
mail($address, $subject, $msg, $from);
endif;
else :
echo file_get_contents('cb.json');
endif;
?>