<?php

$twig = new Twig_Environment (
    new Twig_Loader_Filesystem ('templates/'),  // Path to templates
    [
        // ['cache' => './cache/template/']     // Path to templates cache
        'debug' => true
    ]
);

// Enable "dump()" function in templates
$twig->addExtension (new Twig_Extension_Debug());


// GLOBALS     =================================================================
// A global variable is like any other template variable, except that it's
// available in all templates and macros.


// $twig->addGlobal ('foo', 'bar');


// FILTERS     =================================================================
// A filter transforms the passed value to something else


// Convert a date to "[date] ago"
$twig->addFilter (new Twig_Filter ('ago', function ($datetime) {
    
    $datetime = strtotime ($datetime);
    
    $estimate_time = time () - $datetime;
    
    if( $estimate_time < 1 )
        return 'right now';
    
    $condition = array(
        12 * 30 * 24 * 60 * 60  =>  'year',
        30 * 24 * 60 * 60       =>  'month',
        24 * 60 * 60            =>  'day',
        60 * 60                 =>  'hour',
        60                      =>  'minute',
        1                       =>  'second');
        
    foreach ($condition as $seconds => $string)
    {
        $d = $estimate_time / $seconds;
        
        if ($d >= 1)
        {
            $r = round ($d);
            return $r . ' ' . $string . ($r > 1 ? 's' : '') . ' ago';
        }
    }
    
    return null;
}));

// Format Markdown to HTML
$twig->addFilter (new Twig_Filter ('markdown', function ($markdown) {
    $parsedown = new Parsedown ();
    
    $purifier_settings = HTMLPurifier_Config::createDefault ();
    $purifier_settings->set ('Core', 'EscapeInvalidTags', true);
    $purifier = new HTMLPurifier ($purifier_settings);
    
    return $purifier->purify ($parsedown->text ($markdown));
}));


// FUNCTIONS     ===============================================================


$twig->addFunction (new Twig_Function ('function_name', function () {
    return null;
}));










