Location: PHPKode > projects > VideoDB > videodb/core/template.php
<?php
/**
 * Template functions
 *
 * These functions prepare the data for assignment to the template engine
 *
 * @todo replace additional assignments of config options by using $config
 *
 * @package Core
 * @author  Andreas Gohr    <hide@address.com>
 * @author  Andreas Goetz    <hide@address.com>
 * @author  Chinamann       <hide@address.com>
 * @version $Id: template.php,v 1.57 2008/10/19 10:47:17 andig2 Exp $
 */

require_once './core/session.php';
require_once './core/output.php';
require_once './core/genres.php';
require_once './engines/engines.php';
require_once './core/constants.php';

/**
 * Display template with standard header and footer
 */
function tpl_display_show($template, $flush = true)
{
    smarty_display('header.tpl');

    if ($flush) flush();
    smarty_display($template);
    smarty_display('footer.tpl');
}

/**
 * Display page using templates
 * If page content is unmodified, return HTTP 304 Not modified
 *
 * @param   string  $template Template name for main content
 */
function tpl_display($template)
{
    global $config;

    // caching enabled?
    if ($config['http_caching'])
    {
        require_once('./core/httpcache.php');

        httpCacheCaptureStart();
#        cache_start();
/*        
        tpl_display_show($template, false);
        httpCacheOutput($template, httpCacheCaptureEnd());
*/
    }
/*
    else
    {
        tpl_display_show($template);
    }
*/
    tpl_display_show($template, !$config['http_caching']);

    if ($config['http_caching'])
    {
        httpCacheOutput($template, httpCacheCaptureEnd());
    }

/*
        cache_start($template);
    }
    tpl_display_show($template, false);
*/
}

/**
 * Prepare standard page templates
 */
function tpl_page($help = '', $title = '')
{
    tpl_language();
    tpl_header($help, $title);
    tpl_footer();
}

/**
 * Assigns language strings and config options to the smarty engine
 */
function tpl_language()
{
    global $smarty, $lang, $config;

    $smarty->assign('lang', $lang);
    $smarty->assign('config', $config);
}

/**
 * Assigns the headerurls to the smarty engine
 *
 * @param string $help    The helpfile to display (optional, without extension)
 * @param string $title   The text to add to html <title> tag (optional, will be html-encoded)
 */
function tpl_header($help = '', $title = '')
{
    global $smarty, $lang, $config;
    global $id, $diskid;

    // viewing is only availble if autorized or public access
    if (auth_check(false))
    {
        $header['browse'] = 'index.php';
        if (check_permission(PERM_READ, PERM_ANY))
        {
        	$header['random'] = 'show.php';
        	$header['search'] = 'search.php';
        }
        $header['stats']  = 'stats.php';
        if ($config['imdbBrowser']) $header['trace'] = 'trace.php';
        $header['help'] = 'help.php';
        if ($help) $header['help'] .= '?page='.$help.'.html';
    }

    // editing is only available in local network
    if (localnet())
    {
        if (check_permission(PERM_WRITE, PERM_ANY))
        {
            $header['new']    = 'edit.php';
            if ($config['showtools']) $header['contrib'] = 'contrib.php';
        }
        if (check_permission(PERM_ADMIN)) $header['setup'] = 'setup.php';

        // edit or show?
        if ($id)
        {
            if (check_videopermission(PERM_WRITE, $id)) $header['edit'] = 'edit.php?id='.$id;
            if (!ereg ('show.php$', $_SERVER['PHP_SELF']))
            {
                $header['view']   = 'show.php?id='.$id;
            }
            if (check_videopermission(PERM_WRITE, $id)) $header['del'] = 'delete.php?id='.$id;
        }
        if (check_permission(PERM_WRITE, PERM_ANY))
        {
            $header['borrow'] = 'borrow.php';
            if (isset($diskid)) $header['borrow'] .= '?diskid='.$diskid;
        }
    }

    // multiuser settings
    if ($config['multiuser'])
    {
        $header['login'] = 'login.php';

        // logged in?
        if (!empty($_COOKIE['VDBusername']) && $_COOKIE['VDBuserid'] != $config['guestid'])
        {
            $header['profile'] = 'profile.php';
            $smarty->assign('loggedin', $_COOKIE['VDBusername']);
        }
        else
        {
            // make sure anonymous users don't get access to trace for security reasons
            unset($header['trace']);
        }
    }

	// determine active tab
	if (preg_match('/(\w+)\.php/', $_SERVER['PHP_SELF'], $m))
    {
		$tab = strtolower($m[1]);
		switch ($tab)
        {
			case 'show':
			case 'edit':
				if (!empty($id)) $header['active'] = $tab;
				// uncomment this if you want the 'Browse' tab to remember last visited movie
				// { ... $smarty->assign('browseid', $_REQUEST['id']); }
				else $header['active'] = ($tab == 'show') ? 'random' : 'new';
				break;
            default:
                $translate = array('index' => 'browse', 'users' => 'setup', 'permissions' => 'setup', 'delete' => 'show');
                if (in_array($tab, array_keys($translate)))
                {
                    $tab = $translate[$tab];
                }
				$header['active'] = $tab;
		}
	}

    $smarty->assign('title',	htmlspecialchars($title));
    $smarty->assign('header',	$header);
    $smarty->assign('style',	$config['style']);
    $smarty->assign('langcode', $config['language']);
}

/**
 * Assigns the filter options to the smarty engine
 */
function tpl_filters($filter,$showtv)
{
    global $smarty, $lang;
    global $filter_expr;

    // build filter array
    foreach ($filter_expr as $flt => $regex)
    {
        $filters[$flt] = ($flt == "NUM") ? "#" : $flt;
    }
    $filters['all']	    = $lang['radio_all'];
    $filters['unseen']  = $lang['radio_unseen'];
    $filters['new']     = $lang['radio_new'];
    $filters['wanted']  = $lang['radio_wanted'];

    $smarty->assign('filters',  $filters);
    $smarty->assign('filter',   $filter);
    $smarty->assign('showtv',   $showtv);
    // enable dynamic columns in list view
    $smarty->assign('listcolumns', session_get('listcolumns'));
}

/**
 * Assigns the searchresults/browselist to the smarty engine
 *
 * @param   array   indexed array containing the item data
 */
function tpl_list($list)
{
    global $smarty, $config;
    global $listcolumns;

    for ($i=0; $i < count($list); $i++)
    {
        // setup imgurls
        $list[$i]['imgurl'] = ($config['thumbnail']) ? getThumbnail($list[$i]['imgurl']) : '';

        // check for flagfile
        $languages = $list[$i]['language'];
        $flagfile = img('flags/'.$languages.'.gif');
        if (file_exists($flagfile))
        {
            // one langage
            $list[$i]['flagfile'][$languages] = $flagfile;
            $list[$i]['language'] = array($list[$i]['language']);
        }
        else
        {
            // multiple languages
            $langary  = preg_split('/,\s*/', $languages);
            $list[$i]['language'] = $langary;

            // assign them all
            foreach ($langary as $languagepart)
            {
                $flagfile = img('flags/'.$languagepart.'.gif');
                if (file_exists($flagfile))
                {
                    $list[$i]['flagfile'][$languagepart] = $flagfile;
                }
            }
        }

        // is this file editable?
        if (localnet())
        {
            $list[$i]['editable'] = ($config['multiuser']) ?
                check_permission(PERM_WRITE, $list[$i]['owner_id']) : true;
        }
        else
        {
            $list[$i]['editable'] = false;
        }
/*
    uncomment this to allow display of rating in the 'Browse' tab
    require_once 'custom.php';
    customfields($list[$i], 'out');
*/
    }

	// do adultcheck
	if (is_array($list))
	{
		$list = array_filter($list, create_function('$video', 'return adultcheck($video["id"]);'));
	}

    // enable dynamic columns in list view
    $smarty->assign('listcolumns', session_get('listcolumns'));
    $smarty->assign('list', $list);

    // show total number of movies in footer
    $smarty->assign('totalresults', count($list));
}

/**
 * Assigns debug infos and version to the smarty engine
 */
function tpl_footer()
{
    global $smarty, $config, $SQLtrace;

    if ($config['debug'])
    {
        $out                = $config;
        $out['db_password'] = '***';
        $session            = $_SESSION['vdb'];
        $session['db_password'] = '***';
        
        ob_start();
        print '<pre>';
        dump($SQLtrace);
        dump($out);
        dump($session);
        print '</pre>';
#        phpinfo();
        $debug = ob_get_contents();
        ob_end_clean();
        
        $smarty->assign('DEBUG', $debug);
    }
    $smarty->assign('version', VERSION);
}

/**
 * Converts plain cast data into array of actors with thumbnails
 *
 * @author  Andreas Goetz    <hide@address.com>
 */
function prepare_cast($actors)
{
	global $config;
	
	$result = array();
	
    // loop over actors from full-text field
    foreach (split("\r?\n", $actors) as $actor)
    {
        $actorary       = split('::', $actor);
        $roleary        = split('/', $actorary[1]);
        $cast['name']   = $actorary[0];

        for ($i=0; $i < count($roleary);$i++)
        {
            $roleary[$i] = preg_replace('/\(/', '<small>(', $roleary[$i]);
            $roleary[$i] = preg_replace('/\)/', ')</small>', $roleary[$i]);
        }
        $cast['roles'] = $roleary;

        $cast['imdburl'] = engineGetActorUrl($cast['name'], $actorary[2], engineGetActorEngine($actorary[2]));

        // check for actor thumbnail
        $cast['imgurl'] = ($config['actorpics']) ? getActorThumbnail($cast['name'], $actorary[2]) : '';
        $cast['id']     = $actorary[2];

        $result[] 		= $cast;
    }

    return $result;
}

/**
 * Assigns the videoinfos to the smarty engine
 *
 * @param   array   associative array containing the item data
 */
function tpl_show($video)
{
    global $smarty, $config;

    // imageurl
    $video['imgurl'] = getThumbnail($video['imgurl']);

    // make soft linebreaks:
    $video['filename'] = preg_replace('/(_|\.|-)/', '$1<wbr />', $video['filename']);

    // split comma-separated countries, prevent empty array
    $video['country'] = preg_split('/,\s*/', $video['country'], -1, PREG_SPLIT_NO_EMPTY);

    // split comma-separated multiple languages, prevent empty array
    $video['language'] = preg_split('/,\s*/', $video['language'], -1, PREG_SPLIT_NO_EMPTY);

    // humanreadable filesize:
    if ($video['filesize'] > 0)
    {
        $video['filesize'] = round($video['filesize']/(1024*1024), 2);
    }

    // break plot and comment
    $video['plot']     = nl2br($video['plot']);
    $video['comment']  = nl2br($video['comment']);

	// cast
	$video['cast']     = prepare_cast($video['actors']);

    // prepare the custom fields
    customfields($video, 'out');

    // hide owner if not using multi-user
    if (!$config['multiuser']) unset($video['owner']);

    // get drilldown url for image
    if ($video['imdbID'])
    {
        require_once './engines/engines.php';
        $smarty->assign('link', engineGetContentUrl($video['imdbID'], engineGetEngine($video['imdbID'])));
    }

    // add episodes information
    if (is_array($video['episodes']))
    {
        // allow multiple columns
        $smarty->assign('listcolumns', session_get('listcolumns'));
    }

    $smarty->assign('castcolumns', $config['castcolumns']);
    $smarty->assign('video', $video);

    // get genre ids and names
    $smarty->assign('genres', getItemGenres($video['id'], true));

    // allow XML export
    if ($config['xml']) $smarty->assign('xml', 'show.php?id='.$video['id'].'&amp;');
}

/**
 * Assigns the videoinfos to the smarty engine
 */
function tpl_edit($video)
{
	global $smarty, $config, $lang;

	// create a form ready quoted version for each value
	foreach (array_keys($video) as $key)
    {
		$video['q_'.$key] = formvar($video[$key]);
	}

	// use custom function for language
	$video['f_language']  = custom_language_input('language', $video['language']);

	// create mediatype selectbox
    $smarty->assign('mediatypes', out_mediatypes());
    if (!isset($video['mediatype'])) $video['mediatype'] = $config['mediadefault'];

	// prepare the custom fields
	customfields($video, 'in');

    if ($config['multiuser'])
    {
        $smarty->assign('owners', out_owners(array('0' => ''), (check_permission(PERM_ADMIN)) ? false : PERM_WRITE, true));
    }

	// get drilldown url for visit link
	if ($video['imdbID'])
    {
        require_once './engines/engines.php';
        $engine = engineGetEngine($video['imdbID']);	
        $smarty->assign('link', engineGetContentUrl($video['imdbID'], $engine));
        $smarty->assign('engine', $engine);
	}
/*
    // populate autocomplete boxes
    $smarty->assign('audio_codecs', array_extract(runSQL('SELECT DISTINCT audio_codec FROM '.TBL_DATA.' WHERE audio_codec IS NOT NULL'), 'audio_codec'));
    $smarty->assign('video_codecs', array_extract(runSQL('SELECT DISTINCT video_codec FROM '.TBL_DATA.' WHERE video_codec IS NOT NULL'), 'video_codec'));
*/        
	$smarty->assign('lookup', array('0' => $lang['radio_look_ignore'],
							        '1' => $lang['radio_look_lookup'],
							        '2' => $lang['radio_look_overwrite']));
	$smarty->assign('video', $video);
    $smarty->assign('genreselect', out_genres(getItemGenres($video['id'])));

    // needed for ajax image lookup
    $smarty->assign('engines', $config['engines']);
}

?>
Return current item: VideoDB