<?php
/**
 * Gallery View
 *
 * Lets you browse through your galleries
 *
 * @package PHP Competition System
 * @author  Eric GALLENE <okrome@free.fr>
 * @link	http://www.phpcompet.com
 * @version $Id: gallery.php,v 1.00 2006/12/17 12:15:00
 */

require_once './core/session.php';
require_once './core/functions.php';
require_once './core/output.php';

// check for localnet
localnet_or_die();
check_permission(PERM_GALLERY, $_COOKIE['PCSuserid']);

// set defaults
if (!$cat || !$subcat ) 
{
//redirect('index.php');
$WHERES = "";
}
else{
$WHERES = "WHERE cat_id =".$cat." AND subcat_id =".$subcat;
$smarty->assign('cat', $cat);
$smarty->assign('subcat', $subcat);
}
if ($idgallery) {
	$ORDER = ' ORDER BY id ASC ';
	$smarty->assign('idgallery', $idgallery);
	$select = 'SELECT id, cat_id, subcat_id, imgurl, title FROM '.TBL_GALLERY.' WHERE id='.$idgallery.';'; 
	$mygallery = runSQL($select);
	$smarty->assign('mygallery', $mygallery[0]);
	$smarty->assign('idgallery', $idgallery);	
}
else {
	$ORDER = ' ORDER BY id DESC ';
}

// add owner selection for multiuser mode
if ($config['multiuser']) 
{
	
		
//	$myuser = $_COOKIE['PCSuserid'];
	if (check_permission(PERM_WRITE, $_COOKIE['PCSuserid'])) 
        {
            $smarty->assign('editable', 'true');
		}
	if (check_permission(PERM_ADDGALLERY, $_COOKIE['PCSuserid']) && $config['activegallery']) 
        {
            $smarty->assign('addgallery', 'true');
		}
	if (check_permission(PERM_GALLERY, $_COOKIE['PCSuserid']) && $config['activegallery']) 
        {
            $smarty->assign('seegallery', 'true');
		}
	if (check_permission(PERM_MKCOMMENT, $_COOKIE['PCSuserid']) && $config['activecomments']) 
        {
            $smarty->assign('commentable', 'true');
		}
}

// XML / RSS / PDF export
if ($export && $config[$export])
{
    $func = $export.'export';
    if ($export == 'rss') $export = 'xml';
    require_once './core/'.$export.'.php';

    if (function_exists($func)) $func("$WHERES ORDER BY $ORDER $LIMIT");
    exit();
}

// This checks to see if user has selected the New items
// (This is seperately assigned as a LIMIT so, if this
// exists, lets just skip page numbers and carry on
if (!$LIMIT && ($config['pageno'] > 0))
{
    // check Page Number
    if (!isset($pageno))
    {
        $pageno = 1;
    }

	// define Max Results Per Page
	$maxresults = $config['pageno'];

	// define the Start Number
	$from = (($pageno * $maxresults) - $maxresults);

	// get total amount of results from DB
	$totalresults = runSQL('SELECT count(*) AS num 
                              FROM '.TBL_GALLERY.' '.$WHERES);

	// calculate Total amount of pages
	$totalpages = ceil($totalresults[0]['num'] / $maxresults);
	
	$LIMIT = ' LIMIT '.$from.', '.$maxresults;

    $smarty->assign('pageno', $pageno);                         // assign current Page Number
	$smarty->assign('maxpageno', $totalpages);		            // set Maximum Pages
	$smarty->assign('totalresults', $totalresults[0]['num']);   // set Total Records Returned
}

if ($cat) {
	switch ($cat)
	{
		case 1:
		$SELECT = 'SELECT id, shortname, imgurl, plot FROM '.TBL_CLUBS.' WHERE id = '.$subcat;  
		$res   = runSQL($SELECT);
		$res[0]['imgurl'] = getThumbnail($res[0]['imgurl']);
		$res[0]['tt'] = $res[0]['shortname'];
		$res[0]['title'] = '<a href="show_clubs.php?id='.$res[0]['id'].'">'.$res[0]['shortname'].'</a>';
		$res[0]['plot'] = bbdecode($res[0]['plot']);
		$smarty->assign('item', $res[0]);
	
		break;
		
		case 2:
		$SELECT = 'SELECT id, longname, imgurl, plot FROM '.TBL_COMPETITIONS.' WHERE id = '.$subcat;  
		$res   = runSQL($SELECT);
		$res[0]['imgurl'] = getThumbnail($res[0]['imgurl']);
		$res[0]['tt'] = $res[0]['longname'];
		$res[0]['title'] = '<a href="show_competitions.php?id='.$res[0]['id'].'">'.$res[0]['longname'].'</a>';
		$res[0]['plot'] = bbdecode($res[0]['plot']);
		$smarty->assign('item', $res[0]);	
		break;
		
		case 3:
		$SELECT = 'SELECT id, longname, country, plot AS plot FROM '.TBL_STADIUMS.' WHERE id = '.$subcat;  
		$res   = runSQL($SELECT);
		$res[0]['imgurl'] = getThumbnail($res[0]['imgurl']);
		$res[0]['tt'] = $res[0]['longname'];
		$res[0]['title'] = '<a href="show_studios.php?id='.$res[0]['id'].'">'.$res[0]['longname'].'</a>';
		$res[0]['plot'] = bbdecode($res[0]['plot']);	
		$smarty->assign('item', $res[0]);	
		break;
		
		case 4:
		$SELECT = 'SELECT id, firstname, lastname, imgurl, plot FROM '.TBL_PERSONS.' WHERE id = '.$subcat;  
		$res   = runSQL($SELECT);
		$res[0]['imgurl'] = getThumbnail($res[0]['imgurl']);
		$res[0]['tt'] = $res[0]['firstname'].' '.$res[0]['lastname'];
		$res[0]['title'] = '<a href="show_persons.php?id='.$res[0]['id'].'">'.$res[0]['firstname'].' '.$res[0]['lastname'].'</a>';
		$res[0]['plot'] = bbdecode($res[0]['plot']);	
		$smarty->assign('item', $res[0]);	
		break;
		
		default:
		$SELECT = 'SELECT id, firstname, lastname, imgurl, plot FROM '.TBL_PERSONS.' WHERE id = '.$subcat;  
		$res   = runSQL($SELECT);
		$res[0]['imgurl'] = getThumbnail($res[0]['imgurl']);
		$res[0]['tt'] = $res[0]['firstname'].' '.$res[0]['lastname'];
		$res[0]['title'] = '<a href="show_persons.php?id='.$res[0]['id'].'">'.$res[0]['firstname'].' '.$res[0]['lastname'].'</a>';
		$res[0]['plot'] = bbdecode($res[0]['plot']);	
		$smarty->assign('item', $res[0]);	
		break;	
	}
}

if ($new) {
$smarty->assign('new', 1);
	if ($editgallery) {
	$SELECT = 'SELECT id, cat_id, subcat_id, imgurl, title FROM '.TBL_GALLERY.' WHERE id = '.$id;  
	$gallery   = runSQL($SELECT);
	$smarty->assign('editmygallery', $gallery[0]);		
	}
}

if ($save) {
	$SETS = "cat_id = ".$cat.", subcat_id = ".$subcat;
		if ($title) {
		$SETS .= ", title='".$title."'"; 
		}
		
		 // uploaded cover?
        if (isset($_FILES['coverupload']) && is_uploaded_file($_FILES['coverupload']['tmp_name']))
        {
            $file = $_FILES['coverupload']['tmp_name'];
            $mime = $_FILES['coverupload']['type'];

            // determine file extension
            if (preg_match('=image/jpe?g=i', $mime))
            {
                $ext = 'jpg';
            }
            elseif (preg_match('=image/(gif|png)=i', $mime, $m))
            {
                $ext = $m[1];
            }
            elseif (preg_match('=application/octet-stream=i', $mime))
            {
                if (preg_match("/\.(jpe?g|gif|png)$/i", $_FILES['coverupload']['name'], $matches))
                {
                    $ext = $matches[1];
                }
            }

            // move to cache and update db
            if (!empty($ext))
            {
				if ($id) {
				$SELECT = "SELECT id, imgurl FROM ".TBL_GALLERY." WHERE id = ".$id." ORDER BY id DESC LIMIT 1";
				$result = runSQL($SELECT);
				$newid = $result[0]['id'] + 1;
                $coverfile = $result[0]['url'];
				}
				else {
				$SELECT = "SELECT id, title FROM ".TBL_GALLERY." WHERE cat_id = ".$cat." AND subcat_id = ".$subcat." ORDER BY id DESC LIMIT 1";
				$result = runSQL($SELECT);
				$newid = $result[0]['id'] + 1;
                $coverfile = 'cache/img/gallery/'.$cat.'_'.$subcat.'_'.$newid.'.'.$ext;
				}
                if (move_uploaded_file($file, $coverfile))
                {
                    //$sql = "UPDATE ".TBL_ACTORS." SET imgurl='".$coverfile."' WHERE id=".$id;
                    //runSQL($sql);
					$SETS .= ", imgurl = '".$coverfile."'";
                }
            }
			
	    }
		//if imgurl
		else if (preg_match('/http/i', $imgurl))
    	{
			if (preg_match('/\.(jpe?g|gif|png)$/i', $imgurl, $matches)) {
					// determine mime type
					switch (strtolower($matches[1]))
					{
						case 'gif':	$mime = 'image/gif';
									break;
						case 'png':	$mime = 'image/png';
									break;
						default:	$mime = 'image/jpeg';
					}
					
				if ($id) {
				$SELECT = "SELECT id, imgurl FROM ".TBL_GALLERY." WHERE id = ".$id." ORDER BY id DESC LIMIT 1";
				$result = runSQL($SELECT);
				$newid = $result[0]['id'] + 1;
				$coverfile = $result[0]['imgurl'];
				}
				else {
				$SELECT = "SELECT id, title FROM ".TBL_GALLERY." WHERE cat_id = ".$cat." AND subcat_id = ".$subcat." ORDER BY id DESC LIMIT 1";
				$result = runSQL($SELECT);
				$newid = $result[0]['id'] + 1;
				$coverfile = 'cache/img/gallery/'.$cat.'_'.$subcat.'_'.$newid.'.'.$matches[1];
				}
			
				if (download($imgurl, $coverfile)) {
					$SETS .= ", imgurl = '".$coverfile."'";
				}						
			}        
    	}


	
		if ($id) {
		$INSERT = 'UPDATE '.TBL_GALLERY.' SET '.$SETS.' WHERE id='.$id;
		}
		else
        {
            // insert new record
            $INSERT = 'INSERT INTO '.TBL_GALLERY.' SET '.$SETS;
        }

        runSQL($INSERT);
		
		
	redirect('gallery.php?cat='.$cat.'&subcat='.$subcat);
}


	
// do hard work
$select = 'SELECT id, cat_id, subcat_id, imgurl, title FROM '.TBL_GALLERY.' '.$WHERES.$ORDER.$LIMIT.';'; 
$result = runSQL($select);

// store query result in session for prev/next navigation
$_SESSION['pcs']['query_result'] = array_map(create_function('&$row', 'return $row["id"];'), $result);

// prepare
tpl_page('list_gallery');
tpl_list($result);

// docpart support
if ($docpart)
{
    smarty_display('list_gallery.tpl');
    exit;
}

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

$smarty->assign('moreless', true);           // show more/less control in list view

// allow XML and RSS export
if ($config['xls']) $smarty->assign('xls', 'index.php?');
if ($config['xml']) $smarty->assign('xml', 'index.php?');
if ($config['pdf']) $smarty->assign('pdf', 'index.php?');
if ($config['rss']) $smarty->assign('rss', 'index.php?');

// display templates
smarty_display('header.tpl');
//smarty_display('filters_actors.tpl');
if (!$config['http_caching']) flush();

smarty_display('list_gallery.tpl');
smarty_display('footer.tpl');

// caching enabled?
if ($config['httpcaching'])
{
    httpCacheOutput('gallery'.$cat.$subcat, httpCacheCaptureEnd());
}

?>