<?php
/**************************************************************************
* This file is part of the WebIssues Server program
* Copyright (C) 2006 Michał Męciński
* Copyright (C) 2007-2009 WebIssues Team
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
**************************************************************************/

function wi_load_template( $filename )
{
    $lines = file( wi_make_absolute_path( $filename ) );
    if ( $lines === false )
        return false;

    $template = array();

    $section = 'default';
    $template[ $section ] = '';

    foreach ( $lines as $line ) {
        if ( preg_match( '/^\[\[([a-z_]+)\]\]/', $line, $parts ) ) {
            $section = $parts[ 1 ];
            $template[ $section ] = '';
        } else {
            $template[ $section ] .= $line;
        }
    }

    return $template;
}

function wi_get_template( $template, $section = 'default', $args = null )
{
    if ( !isset( $template[ $section ] ) )
        return '';

    $result = $template[ $section ];

    if ( is_array( $args ) ) {
        $search = array();
        $replace = array();
        foreach ( $args as $key => $value ) {
            $search[] = '$' . $key;
            $replace[] = (string)$value;
        }
        $result = str_replace( $search, $replace, $result );
    }

    return $result;
}
