<?php

function file_curl_contents($url){
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,  FALSE);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_REFERER, 'http://oudanstoncul.free.fr');// notez le referer "custom"
    $data = curl_exec($ch);
    curl_close($ch);
    return $data;
}

/**
 * @return array
 */
function get_images()
{
    if (!is_dir('./cache') || !is_dir('./cache/images')) {
        mkdir('./cache/images');
    }

    $last_time = 0;

    if (is_readable('./cache/images/.cache')) {
        $last_time = file_get_contents('./cache/images/.cache');
    }

    $current_time = time();

    if ($current_time - $last_time >= 60*60*24) {
        foreach (glob('./cache/fonts/*') as $file) {
            unlink($file);
        }
        $images = json_decode(file_curl_contents('http://api.warriordudimanche.net/fancytation/?imageslist'), true);
        foreach ($images as $image) {
            touch('./cache/images/'.$image);
        }
        file_put_contents('./cache/images/.cache', $current_time);
        return $images;
    } else {
        return array_map('basename', glob('./cache/images/*'));
    }
}


/**
 * @return array
 */
function get_fonts()
{
    if (!is_dir('./cache') || !is_dir('./cache/fonts')) {
        mkdir('./cache/fonts');
    }

    $last_time = 0;

    if (is_readable('./cache/fonts/.cache')) {
        $last_time = file_get_contents('./cache/fonts/.cache');
    }

    $current_time = time();

    if ($current_time - $last_time >= 60*60*24) {
        foreach (glob('./cache/fonts/*') as $file) {
            unlink($file);
        }
        $fonts = json_decode(file_curl_contents('http://api.warriordudimanche.net/fancytation/?fontslist'), true);
        foreach ($fonts as $font) {
            touch('./cache/fonts/'.$font);
        }
        file_put_contents('./cache/fonts/.cache', $current_time);

        return $fonts;
    } else {
        return array_map('basename', glob('./cache/fonts/*'));
    }
}