<?  // PHPmyGallery - Displays the gallery on the web page

/* File description:

This file holds the main functionality for the PHPmyGallery script.
The output is sent directly to the browser.
If you want to know more about the files this script includes, open
them in your editor.

### What this script does:
###
### Script starts
### |
### | (Uses templates from index_view, group_view, gallery_view, picture_view)
### +- Index View   (Load available Groups, Display Links to loaded Groups)
### +- Group View   (Load Galleries of selected Group, Display Links to Galleries)
### +- Gallery View (Load Thumbnails of selected Gallery, Load Descriptions, Display Links to Pictures)
### +- Picture View (Load selected Picture & Description, Display Picture)
### |
### Display DebugBox (Make DebugBox Template if $debugText holds Text)
### |
### Script Ends
###

----------------------------------

This file is part of PHPmyGallery.

PHPmyGallery 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.
 
PHPmyGallery is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
 
You should have received a copy of the GNU General Public License
along with PHPmyGallery; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

*/

/* Script starts */

// Load functions
require_once('confdir.config.php'); // Holds $admindir which tells where the admin directory is
require_once($admindir.'_php-core/globals.php');
require_once($admindir.'_php-core/functions.php');
require_once($admindir.'db_libs/'.$dbsystem.'.php');

// Load settings
$conf = getData('mainsetup');
$mainconf = getData('gallerysettings','all');
foreach($mainconf as $k=>$confItem)
    $conf[$k] = $confItem;

$groupsNames = getData('groupssetup');

// Retreive GET vars
$group  = urldecode($_GET['group']);
$picdir = urldecode($_GET['dir']);
$pic    = urldecode($_GET['pic']);

// Security fix: Format check for each variable
// Sorry, such a dumb security hole : /
if(!preg_match('/^[a-zA-Z0-9\-\.\_ \%\+]+$/',$group)) {
    
    $group = '';
    $picdir= '';
    $pic   = '';
} // if
else if(!preg_match('/^[a-zA-Z0-9\-\.\_ \%\+]+$/',$picdir)) {
    
    $picdir = '';
    $pic    = '';
} // else if
else if(!preg_match('/^[a-zA-Z0-9\-\.\_ \%\+]+$/',$pic)) {
    
    $pic = '';
} // else if

$picCount = 0;

// Get directory contents when viewing pictures
if ($group!='' && $picdir!='') {
    // gallery config init
    $picset = getData('picsdescriptions',$group.'--.--'.$picdir);
    
    // Retreive gallery settings and overwrite their entries in the conf array
    if(allocateData('gallerysettings',$group.'--.--'.$picdir)) {
        $galleryconf = getData('gallerysettings',$group.'--.--'.$picdir);
        
        foreach($galleryconf as $k=>$confItem)
            $conf[$k] = $confItem;
    } // if
    
    // set picture comments to empty string for pictures without comments
    $dirarr = filenames2arr($group.'/'.$picdir.'/',IMAGES);
    foreach ($dirarr as $file) {
        $picCount++;
        if (!isset($picset[PICSDATA][$file])) {
            $picset[PICSDATA][$file]['fullname'] = $file;
            $picset[PICSDATA][$file]['fulltext'] = '';
        } // if
    } // foreach
} // if

/* Call Statistics-function */
$file_exists = doStats($group,$picdir,$pic);

// Initiate template system and common template variables
$pktpl_vars = pktpl_start();
require_once($admindir.'_php-core/common-tpl-vars.php');

// Initiate titles and links
if($file_exists && $group != '') {
    if($groupsNames[$group] != '')
        $pktpl_vars['text_grouptitle'] = $groupsNames[$group];
    else
        $pktpl_vars['text_grouptitle'] = str_replace('_',' ',$group);
    
    $pktpl_vars['link_toSinglegroupindex'] = urlencode($conf['myGfilename']).'?group='.urlencode($group);
    
    if($picdir != '') {
        $pktpl_vars['link_toSinglegalleryindex'] = urlencode($conf['myGfilename']).'?group='.urlencode($group).'&dir='.urlencode($picdir);
        
        if($picset[METADATA]['pagetitle']=='')
            $pktpl_vars['text_gallerytitle'] = str_replace('_',' ',$picdir);
        else
            $pktpl_vars['text_gallerytitle'] = $picset[METADATA]['pagetitle'];
        
        if($pic != '') {
            $pktpl_vars['text_picname']  = stripslashes($picset[PICSDATA][$pic]['fullname']);
            $pktpl_vars['text_pictitle'] = $pktpl_vars['text_picname'];
        } // if
    } // if
} // if

// Set PHPmyGallery filename for templates
$pktpl_vars['link_tophpmygalleryindex'] = urlencode($conf['myGfilename']);

// Render templates for page logo, metatags
$pktpl_vars['pageLogo']                 = pktpl('all_pageLogo.html');
$pktpl_vars['template_all_metatags']    = pktpl('all_metatags.html');


/// Picture View
if ($file_exists && $group!=''&&$picdir!=''&&$pic!='') {
    // Put picture names in an array
    if (isset($picset[PICSDATA])) {
        $arr = array_keys($picset[PICSDATA]);
    } // if
    else {
        $arr = $dirarr;
    } // else
    
    // Find previous/next/first/last picture by picture names
    $tmp_c                         = findArrayNeighbourhood($arr,$pic);
    $pktpl_vars['text_picnumThis'] = $tmp_c[VALUEFOUNDATNUMBER];
    $pktpl_vars['text_picnumAll']  = $picCount;
    
    // linktext `next` / `first` or picture name
    if ($tmp_c[NEXTVALUE]!='') {
        if($conf['useprevnext']=='true')  // displaying "next" if settings say so
            $pktpl_vars['text_toNext'] = $pktpl_vars['l_next'];
        else  // else, displaying picturename
            $pktpl_vars['text_toNext'] = $picset[PICSDATA][$tmp_c[NEXTVALUE]]['fullname'];
        
        $nextpic = $tmp_c[NEXTVALUE];
    } // if
    else {
        if($conf['useprevnext']=='true')
            $pktpl_vars['text_toNext'] = $pktpl_vars['l_first'];
        else
            $pktpl_vars['text_toNext'] = $picset[PICSDATA][$tmp_c[FIRSTVALUE]]['fullname'];
        
        $nextpic = $tmp_c[FIRSTVALUE];
    } // else
    
    // linktext `previous` / `last` or picture name
    if ($tmp_c[PREVIOUSVALUE]!='') {
        if($conf['useprevnext']=='true')
            $pktpl_vars['text_toPrevious'] = $pktpl_vars['l_previous'];
        else
            $pktpl_vars['text_toPrevious'] = $picset[PICSDATA][$tmp_c[PREVIOUSVALUE]]['fullname'];
        
        $prevpic = $tmp_c[PREVIOUSVALUE];
    } // if
    else {
        if($conf['useprevnext']=='true')
            $pktpl_vars['text_toPrevious'] = $pktpl_vars['l_last'];
        else
            $pktpl_vars['text_toPrevious'] = $picset[PICSDATA][$tmp_c[LASTVALUE]]['fullname'];
        
        $prevpic = $tmp_c[LASTVALUE];
    } // else
    
    // EXIF parameters
    if ($conf['get_EXIF_parameters']) {
        $exif = @exif_read_data($picdir.'/'.$pic,0,true);
        foreach($exif as $key=>$section) {
            foreach($section as $name=>$val) {
                $pktpl_vars['EXIF_'.$key.'_'.$name] = $val;
            } // foreach
        } // foreach
    } // if
    
    // Other template variables for this picture
    $pktpl_vars['text_imgSrc']       = $group.'/'.$picdir.'/'.$pic;
    $pktpl_vars['text_imgName']      = filename_encode($pic);
    $pktpl_vars['text_imgAlttext']   = $pic;
    $pktpl_vars['text_imageComment'] = stripslashes(stripslashes($picset[PICSDATA][$pic]['fulltext']));
    
    $pktpl_vars['link_toPrevious']   = urlencode($conf['myGfilename']).'?group='.urlencode($group).'&dir='.urlencode($picdir).'&pic='.urlencode($prevpic);
    $pktpl_vars['link_toNext']       = urlencode($conf['myGfilename']).'?group='.urlencode($group).'&dir='.urlencode($picdir).'&pic='.urlencode($nextpic);
    
    $pktpl_vars['image_pic'] = pktpl('picture_view/picPicturetag.html');
    
    
    // Render final Template
    $pktpl_vars['pageNavi']               = pktpl('all_pageNavi_pic.html');
    $pktpl_vars['template_logo_and_navi'] = pktpl('all_pageLogo_and_Navi.html');
    $pktpl_vars['text_content']           = pktpl('picture_view/pic.html');
} // if
/// Gallery View
elseif ($file_exists && $group!=''&&$picdir!='' && is_array($picset[PICSDATA])) {
    // Run through the picset
    $galleryTableCells = '';
    $td = 0;
    $pktpl_vars['template_galleryTableCell'] = '';
    $tdMax = (int)$conf['use_htmlTable'];
    foreach ($picset[PICSDATA] as $picfilename=>$v) {
        // Make filename into array and get file extention out of it
        $filename_arr  = explode('.',$picfilename);
        $ext           = strtolower($filename_arr[count($filename_arr)-1]);
        unset( $filename_arr[count($filename_arr)-1] );
        $pic           = implode('.',$filename_arr);
        
        // Getting thumbnail filename
        if($conf['prefix_or_suffix']=='suffix')
            $thumbfilename = $group.'/'.$picdir.'/'.$pic.$conf['thumb_suffix'].'.'.$ext;
        else
            $thumbfilename = $group.'/'.$picdir.'/'.$conf['thumb_prefix'].$pic.'.'.$ext;
        
        // Set Image URL, Name and alt attribute
        $pktpl_vars['text_imgSrc']     = $thumbfilename;
        $pktpl_vars['text_imgName']    = filename_encode($picfilename);
        $pktpl_vars['text_imgAlttext'] = $picfilename;
        
        // Process configuration...
        
        // Using thumbnails and thumbnail exists
        if ($conf['usethumbs']=='true' && file_exists($thumbfilename)) {
            if(isset($v['fullname']))
                $pktpl_vars['text_pictitle'] = stripslashes($v['fullname']);
            else
                $pktpl_vars['text_pictitle'] = $picfilename;
            
            $th = ($conf['prefix_or_suffix']=='suffix') ? $conf['thumb_suffix']: $conf['thumb_prefix'];
            
            $pktpl_vars['image_thumbnail'] = pktpl('gallery_view/galleryTablePicturetag.html');
        } // if
        // Not using thumbnails or thumbnail doesnt exist
        else {
            $pktpl_vars['image_thumbnail'] = $picset[PICSDATA][$picfilename]['fullname'];
        } // else
        
        // Set link to picture
        $pktpl_vars['link_toPicture'] = urlencode($conf['myGfilename']).'?group='.urlencode($group).'&dir='.urlencode($picdir).'&pic='.urlencode($picfilename);
        
        // If no HTML table used, use alternative look
        if ($tdMax <= 0) {
            $galleryTableCells .= pktpl('gallery_view/galleryTable_alt.html');
        } // if
        // Use HTML table for thumbnails
        else {
            if ($td < $tdMax) {
                $pktpl_vars['template_galleryTableCell'] .= pktpl('gallery_view/galleryTableCell.html');
                $td += 1;
            } // if
            else {
                $galleryTableCells .= pktpl('gallery_view/galleryTableCellRow.html');
                $pktpl_vars['template_galleryTableCell'] = pktpl('gallery_view/galleryTableCell.html');
                $td = 1;
            } // else
        } // else
    } // foreach
    
    // Make templates (and fill up empty <td> cells)
    if ($tdMax > 0) {
        if ($td <= $tdMax) {
            for ($x = $td; $x < $tdMax; $x++) {
                $pktpl_vars['template_galleryTableCell'] .= pktpl('gallery_view/galleryTableCellEmpty.html');
            } // for
            $galleryTableCells .= pktpl('gallery_view/galleryTableCellRow.html');
        } // if
        
        $pktpl_vars['template_galleryTableCell'] = $galleryTableCells;
        $pktpl_vars['template_galleryTable']     = pktpl('gallery_view/galleryTable.html');
    } // if
    else {
        $pktpl_vars['template_galleryTable'] = $galleryTableCells;
    } // else
    
    // Render final Template
    $pktpl_vars['pageNavi']               = pktpl('all_pageNavi_gallery.html');
    $pktpl_vars['template_logo_and_navi'] = pktpl('all_pageLogo_and_Navi.html');
    $pktpl_vars['text_content']           = pktpl('gallery_view/gallery.html');
} // if
/// Group View
elseif($file_exists && $group!='') {
    // Make rows
    $groupsTablerow = '';
    $dirarr = filenames2arr($group.'/',DIRECTORIES);
    if(is_array($dirarr)) {
        foreach ($dirarr as $folder) {
            if(allocateData('picsdescriptions',$group.'--.--'.$folder))
                $picset = getData('picsdescriptions',$group.'--.--'.$folder);
            else
                $picset = array();
            
            if ($conf['gallerylisting_usesavedgallerytitle']) {
                $folderdesc = ($picset[METADATA]['pagetitle']!='') ? $picset[METADATA]['pagetitle']: str_replace('_',' ',$folder);
            } // if
            else {
                $folderdesc = str_replace('_',' ',$folder);
            } // else
            
            $dircount = count($picset[PICSDATA]);
            if($dircount > 0)
                $pktpl_vars['text_galleryPicturescount'] = $dircount;
            else
                $pktpl_vars['text_galleryPicturescount'] = '?';
            
            $pktpl_vars['text_galleryTitle'] = $folderdesc;
            $pktpl_vars['link_toAgallery']   = $conf['myGfilename'].'?group='.urlencode($group).'&dir='.urlencode($folder);
            
            $groupsTablerow .= pktpl('group_view/groupsTableRow.html');
        } // foreach
    } // if
    
    // Make template for group view HTML-table
    $pktpl_vars['template_groupsTablerow'] = $groupsTablerow;
    
    // Render final Template
    $pktpl_vars['pageNavi']               = pktpl('all_pageNavi_groups.html');
    $pktpl_vars['template_logo_and_navi'] = pktpl('all_pageLogo_and_Navi.html');
    $pktpl_vars['text_content']           = pktpl('group_view/groups.html');
} // elseif
/// Index View
else {
    // Get available groups (reads in all directories except '_conf')
    $indexTablerows = '';
    $dirarr = filenames2arr('./',GROUPS);
    
    foreach ($dirarr as $group) {
        if($groupsNames[$group] != '')
            $folderdesc = $groupsNames[$group];
        else
            $folderdesc = str_replace('_',' ',$group);
        
        $dircount = count(filenames2arr($group.'/',DIRECTORIES));
        $pktpl_vars['text_groupTitle']         = $folderdesc;
        $pktpl_vars['text_groupGaleriescount'] = $dircount;
        $pktpl_vars['link_toAgroup']           = $conf['myGfilename'].'?group='.urlencode($group);
        
        $indexTablerows .= pktpl('index_view/indexTableRow.html');
    } // foreach
    
    // Make template for group view HTML-table
    $pktpl_vars['template_indexTablerows'] = $indexTablerows;
    
    // Render final Template
    $pktpl_vars['pageNavi']               = ''; // not used for index view for now
    $pktpl_vars['template_logo_and_navi'] = pktpl('all_pageLogo_and_Navi.html');
    $pktpl_vars['text_content']           = pktpl('index_view/index.html');
} // else

/* Fire up Debugging System if $debugText holds a message */
if ($debugText!='') {
    $pktpl_vars['debug_box'] = debugBox();
} // if


// Get execution time and output rendered HTML templates to the browser
$pktpl_vars['text_timeExectime'] = pk_exectime($time_start,$l['decimal_point']);
echo(pktpl('phpmygallery.html'));

?>