<?php

include './core.php';

if( !isset( $user ) || !$user->can_access( 'templates_admin' ) ) access_error();

if( isset( $_REQUEST['file'] ) )
{
    $file_extension = strtolower( substr( strrchr( $_REQUEST['file'], "." ), 1 ) );
    if( !file_exists( combine_path( './templates', $_REQUEST['file'] ) ) || strstr( $_REQUEST['file'], '..' ) || $file_extension != 'tpl' )
    	die();

    if( isset( $_POST['send_form'] ) )
	{
        $fp = fopen( combine_path( './templates', $_REQUEST['file'] ), 'w' );
	    $newtpl = $_POST['template'];
	    fputs( $fp, $newtpl );
	    fclose( $fp );
    }

    $Smarty->assign( 'template', implode( '', file( combine_path( './templates', $_REQUEST['file'] ) ) ) );
    $Smarty->assign( 'filename', $_REQUEST['file'] );

    $page['content'] = $Smarty->fetch( 'templates_admin_item.tpl' );
}
else
{
    $dir = null;
    if( isset( $_REQUEST['dir'] ) && !empty( $_REQUEST['dir'] ) )
	    $dir = $_REQUEST['dir'];

	if( strstr( $dir, '..' ) )
	    die();

	$complete_dir = combine_path( './templates', $dir );
	$Smarty->assign( 'complete_dir', $complete_dir );

	$handle = @opendir( $complete_dir );

	$files = array();
	$dirs = array();

    if( $dir != null )
    {
        if( strstr( $dir, '/' ) )
       		$dirs[] = Array( '..',  strtok( $dir, '/' ) );
        else
        	$dirs[] = Array( '..', '' );
    }

	while( $file = readdir( $handle ) )
	{
        if( $file==".." || $file=="." ) continue;

        $filepath = combine_path( $complete_dir, $file );
        $file_extension = strtolower( substr( strrchr( $file, "." ), 1 ) );
	    if ( $file_extension == 'tpl' )
	    {
	        $files[] = Array( $file, combine_path( $dir, $file ), round( filesize( $filepath ), 2 ) );
	    }
	    elseif( is_dir( $filepath ) )
	    {
	        $dirs[] = Array( $file, combine_path( $dir, $file ) );
	    }
	}
	@closedir( $handle );
	$count = count( $files );
	sort( $files );
	$Smarty->assign( 'files', $files );
	sort( $dirs );
	$Smarty->assign( 'dirs', $dirs );

	$page['content'] = $Smarty->fetch( 'templates_admin.tpl' );
}

$Smarty->assign( 'page', $page );
$Smarty->display( 'main.tpl' );

?>