<?php

if ( ! @include_once( './mainfile.php' ) ) { exit( '!! INCLUDE ERROR. ACCESS DENIED !!' ); }
error_reporting( _E_VALUE );


/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | myPHPNuke Version 188_8 RC2                                          |
// +----------------------------------------------------------------------+
// | License: GNU/GPL - http://www.gnu.org/copyleft/gpl.html              |
// +----------------------------------------------------------------------+
// | Support: http://myphpnuke.com/                                       |
// +----------------------------------------------------------------------+
// | Author: myPHPNuke Dev Team                                           |
// +----------------------------------------------------------------------+
// | Copyright: © 2001-2004 myPHPNuke Dev Team                            |
// +----------------------------------------------------------------------+
// $Id: galladmin.php,v 1.11.2.7 2004/04/18 20:15:10 ajvwaay Exp $



######################################################################
# For PHP-NUKE: Web Portal System
# ===========================
# My_eGallery
# Copyright (c) 2001 by MarsisHere (marsishere@yahoo.fr)
# http://kodred.fr.st
#
# This modules is for image galleries
#
# 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.
######################################################################

( (bool)FALSE === strpos( $_SERVER['REQUEST_URI'], __FILE__ ) )
  OR exit( '!! ACCESS DENIED !!' );


include 'admin/gallery/config.php';
include "$basepath/imageFunctions.php";

$langType = 'admin';

if(isset($newlang)) {
    $language = $newlang;
} elseif(isset($lang)) {
    $language = $lang;
}
if(file_exists("$languagepath/lang-$language.php")) {
    include("$languagepath/lang-$language.php");
}
else {
    include("$languagepath/lang-english.php");
}

function getThumbnail($img, $galloc) {
    global
        $gallerypath,
        $imagepath,
        $mpnTables
    ;

    $ext = substr($img, (strrpos($img,'.') +  1));
    $name_gif = str_replace(".$ext", ".gif", $img);
    $name_jpg = str_replace(".$ext", ".jpg", $img);

    if (file_exists("$gallerypath/$galloc/thumb/$name_gif")) {
        $thumb = "$gallerypath/$galloc/thumb/$name_gif";
    }
    elseif (file_exists("$gallerypath/$galloc/thumb/$name_jpg")) {
            $thumb = "$gallerypath/$galloc/thumb/$name_jpg";
    }
    else {
        $row = mysql_fetch_array(mysql_query("SELECT thumbnail from ".$mpnTables['gallery_media_types']." where extension='$ext'"));
        $thumbnail = $row['thumbnail'];
        $thumb = "$imagepath/$thumbnail";
    }

    //echo $thumb;
    return $thumb;
}

function showoption() {
    global
        $adminurl,
        $module_name,
        $imagepath,
        $gallerypath,
        $adminpath,
        $languagepath,
        $baseurl,
        $version,
        $mpnTables,
        $textcolor1
    ;
#   include 'header.php';
#   GraphicAdmin($hlpfile);
    OpenTable();
    print '<center><font size="4"><b>'._GALADMIN.'</b></font></center>';
    CloseTable();
    print '<br>';
    OpenTable();
    $wait = mysql_fetch_array(mysql_query("SELECT COUNT(pid) AS total FROM ".$mpnTables['gallery_pictures_newpicture'].""));
    print "<a href=\"$adminurl&amp;op=Configure\">"._GALGENERALSETTINGS."</a> - "._GALGENERALSETTINGSDESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=editallcategories\">"._GALEDITCATEGORIES."</a> - "._GALEDITCATEGORIESDESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=maineditmedia\">"._GALEDITMEDIA."</a> - "._GALEDITMEDIADESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=editmediatypes\">"._GALEDITMEDIATYPE."</a> - "._GALEDITMEDIATYPEDESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=editalltemplate\">"._GALEDITTEMPLATE."</a> - "._GALEDITTEMPLATEDESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=doeditmedia&amp;type=new\">"._GALADDNEWMEDIA."</a> - "._GALADDNEWMEDIADESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=quickaddpics\">"._GALBATCHBUILD."</a> - "._GALBATCHBUILDDESC."<br><br>\n"
        ."<a href=\"$adminurl&amp;op=validnew&amp;type=checknew\">"._GALPOSTEDMEDIA.' ['.sprintf(_GALWAITING, $wait['total']).']</a> - '._GALPOSTEDMEDIADESC."<br><br>\n"
    ;
    CloseTable();
    print '<br>';
    // Start Of Footer
    OpenTable();
    print '
    <table><tr>
    <td>'
      ."<font face=\"Verdana,Arial\" color=\"$textcolor1\">mpn eGallery Version - $version<br>"._GALVISITUPDATE.'</font>
    </td>
    </tr></table>';
    CloseTable();
#   include 'footer.php';
}

function indent($gid) {
    global $mpnTables;
    $tab = 0;
    list($parent) = mysql_fetch_row(mysql_query("SELECT parent FROM ".$mpnTables['gallery_categories']." WHERE gallid=$gid"));
    while ($parent != -1) {
        list($parent) = mysql_fetch_row(mysql_query("SELECT parent FROM ".$mpnTables['gallery_categories']." WHERE gallid=$parent"));
        $tab ++;
    }
    return $tab;
}

function listcategories($dir){
  global
    $gallerypath, $mpnTables;

  $dossier = opendir($dir);
  $category = "";
  while ($file = readdir($dossier)) {
    if ($file != "." && $file != ".." && $file!="thumb"){
        if (is_dir($dir."/".$file)){
            $galloc  = substr($dir."/".$file, strlen("$gallerypath/"));
            $result = mysql_query("select gallid from ".$mpnTables['gallery_categories']." where galloc='$galloc'");
            if (mysql_num_rows($result)>0) {
                list($gid) = mysql_fetch_array($result);
                $category .= "$gid ";
            }
            $category .= listcategories("$dir/$file");
        }
    }
  }
  return $category;
}

function split_words($string){
 $retour = array();
  $delimiteurs = ' .!?, :;(){}[]%|';
  $tok = strtok($string, " ");
  while (strlen(join(" ", $retour)) != strlen($string)) {
  array_push($retour, $tok);
  $tok = strtok ($delimiteurs);
  }
  return $retour;
}


function Configure() {
    global
        $bgcolor1,
        $bgcolor2,
        $bgcolor3,
        $bgcolor4,
        $textcolor1,
        $textcolor2,
        $version,
        $adminurl,
        $module_name,
        $imagepath,
        $gallerypath,
        $adminpath,
        $languagepath,
        $baseurl,
        $adminurl,
        $mpnTables
    ;
    include "$adminpath/config.php";
//  include "$basepath/classes.php";
#   include "header.php";
#   GraphicAdmin($hlpfile);
    OpenTable();
    print '<center><font size="4"><b>'._GALADMIN.'</b></font></center>';
    CloseTable();
    print '<br>';
    //OpenTable();

    // for alternating row colors, easy :-)
    //$colorBG = new alternator(array($bgcolor3,$bgcolor3));
    //$colorFG = new alternator(array($textcolor1,$textcolor2));
    $bg = $bgcolor3;
    $fg = $textcolor2;
    // fetch the main page template
    $templateRow = mysql_fetch_array(mysql_query("SELECT templateCategory AS templateMain, templatePictures AS numcol, templateCSS FROM ".$mpnTables['gallery_template_types']." WHERE id=1"));
    // now, on with the page
        OpenTable();
    print "<a href=\"$adminurl\">"._GALCONFIG."</a> &gt;"._GALGENERALSETTINGS;
    CloseTable();

    print   '<!-- Start of Body --><br>'
        .'<form action="admin.php" method="post">'
        .'<input type="hidden" name="fct" value="gallery">'
        .'<input type="hidden" name="op" value="ConfigSave">'
    ;

    // Save
    print "<table width=\"100%\"><tr height=\"60\" bgcolor=\"$bg\"><td colspan=\"2\"><font color=\"$fg\"><br>"
        .'<center><input class="button" type="submit" value="'._SAVECHANGES.'"></center>'
        .'</td></tr></table><br>'
    ;

    // Module Name
    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";
    print    "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALMODULENAME."</font></td><td><font color=\"$fg\">"
        ."<input type=\"text\" name=\"xmodule_name\" value=\"$module_name\" size=\"15\">"
        .'</font></td></tr>'
    ;
    // Default Gallery Icon
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALDEFPICNAME.'</td><td>'
        ."<input type=\"text\" name=\"xGalleryPictureName\" value=\"$GalleryPictureName\" size=\"15\">"
        .'</font></td></tr>'
    ;

    // Display Top 10
    $check_displaytop = array(0 => null, 1 => null);
    $check_displaytop[$displaytop] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALDISPLAYTOP."</font></td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xdisplaytop\" value=\"1\"$check_displaytop[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xdisplaytop\" value=\"0\"$check_displaytop[0]>"._NO
        .'</font></td></tr>'
    ;

    print '</table>'.CloseTable().'<br>';
    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";
    // Maximum Number Of Pictures Per Page
    $sel_maxNumberMedia[$maxNumberMedia] = ' selected';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALNUMBERMEDIA.'</td><td>'
        .'<select name="xmaxNumberMedia">'
    ;
    for($i=1; $i<=50; $i++) {
        if (isset( $sel_maxNumberMedia[$i] ))
        {
            $sel = $sel_maxNumberMedia[$i];
        }
        else
        {
            $sel = null;
        }

        print "<option value=\"$i\"$sel>$i</option>\n";
    }
    print '</select>'
        .'</font></td></tr>'
    ;
    // Number Of Columns In Main Page
    $sel_numColMain[$numColMain] = ' selected';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALNUMCOLMAIN.'</td><td>'
        .'<select name="xnumColMain">'
    ;
    for($i=1; $i<=4; $i++) {
        if (isset( $sel_numColMain[$i] ))
        {
            $sel = $sel_numColMain[$i];
        }
        else
        {
            $sel = null;
        }

        print "<option value=\"$i\"$sel>$i</option>\n";
    }
    print '</select>'
        .'</font></td></tr>'
    ;
    // Template To Use For Main Page
    $sel_maintemplate[$maintemplate] = ' selected';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALMAINTEMPLATE.'</td><td>'
        .'<select name="xmaintemplate">'
    ;
    $result = mysql_query("SELECT id, title FROM ".$mpnTables['gallery_template_types']." WHERE type=1 ORDER BY title");
    while($row = mysql_fetch_array($result)) {
        $sel = $sel_maintemplate[$row['id']];
        print "<option value=\"" . $row['id'] . "\"$sel>" . $row['title'] . "</option>\n";
    }
    print '</select>'
        .'</font></td></tr>'
    ;

    print '</table>'.CloseTable().'<br>';
    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";

    // Display Sort Bar
    $check_displaysortbar = array(0 => null, 1 => null);
    $check_displaysortbar[$displaysortbar] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\">
        <td colspan=\"3\"><font color=\"$fg\">"._GALDISPLAYSORTBAR."</font></td>
        <td><font color=\"$fg\">
        <input type=\"radio\" name=\"xdisplaysortbar\" value=\"1\"$check_displaysortbar[1]>"._YES."&nbsp;
        <input type=\"radio\" name=\"xdisplaysortbar\" value=\"0\"$check_displaysortbar[0]>"._NO."
        </font>
        </td>
          </tr>"
    ;

    // Default Sort
    print '<tr height="60" bgcolor="'.$bg.'">'
        .'<td><font color="'.$fg.'" size="-1">'._GALDEFAULTSORTMEDIA.'</font></td>'
        .'<td  align="center" colspan="2">'
        .'<select name="xdefaultsortmedia">'
    ;
        $sel_SortingMedia = array('titleA' => null, 'titleD' => null, 'dateA' => null, 'dateD' => null,
                                  'hitsA' => null, 'hitsD' => null, 'ratingA' => null, 'ratingD' => null);

        $sel_SortingMedia[$defaultsortmedia] = ' selected';

        print "<option value=\"titleA\"" . $sel_SortingMedia['titleA'] . ">" . _GALNAMEAZ . "</option>\n";
        print "<option value=\"titleD\"" . $sel_SortingMedia['titleD'] . ">"._GALNAMEZA."</option>\n";
        print "<option value=\"dateA\"" . $sel_SortingMedia['dateA'] . ">"._GALDATE1."</option>\n";
        print "<option value=\"dateD\"" . $sel_SortingMedia['dateD'] . ">"._GALDATE2."</option>\n";
        print "<option value=\"hitsA\"" . $sel_SortingMedia['hitsA'] . ">"._GALPOPULARITY1."</option>\n";
        print "<option value=\"hitsD\"" . $sel_SortingMedia['hitsD'] . ">"._GALPOPULARITY2."</option>\n";
        print "<option value=\"ratingA\"" . $sel_SortingMedia['ratingA'] . ">"._GALRATING1."</option>\n";
        print "<option value=\"ratingD\"" . $sel_SortingMedia['ratingD'] . ">"._GALRATING2."</option>\n";
    print '</select>'
    .'</td></tr>'
    ;

    print '</table>'.CloseTable().'<br>';
    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";
    // Allow Comments
    $check_allowcomments = array(0 => null, 1 => null);
    $check_allowcomments[$allowcomments] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALALLOWCOMMENTS."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xallowcomments\" value=\"1\"$check_allowcomments[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xallowcomments\" value=\"0\"$check_allowcomments[0]>"._NO
        .'</font></td></tr>'
    ;
    // Allow Anon Comments
    $check_anoncomments = array(0 => null, 1 => null);
    $check_anoncomments[$anoncomments] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALANONCOMMENTS."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xanoncomments\" value=\"1\"$check_anoncomments[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xanoncomments\" value=\"0\"$check_anoncomments[0]>"._NO
        .'</font></td></tr>'
    ;
    print '</table>'.CloseTable().'<br>';

    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";
    // Allow Upload
    $check_allowpostpics = array(0 => null, 1 => null);
    $check_allowpostpics[$allowpostpics] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALALLOWPOSTPICS."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xallowpostpics\" value=\"1\"$check_allowpostpics[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xallowpostpics\" value=\"0\"$check_allowpostpics[0]>"._NO
        .'</font></td></tr>'
    ;
    // Allow Anon Upload
    $check_anonpostpics = array(0 => null, 1 => null);
    $check_anonpostpics[$anonpostpics] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALANONPOSTPICS."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xanonpostpics\" value=\"1\"$check_anonpostpics[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xanonpostpics\" value=\"0\"$check_anonpostpics[0]>"._NO
        .'</font></td></tr>'
    ;
    // Limit Upload Size
    $check_limitSize = array(0 => null, 1 => null);
    $check_limitSize[$limitSize] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALLIMITSIZE."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xlimitSize\" value=\"1\"$check_limitSize[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xlimitSize\" value=\"0\"$check_limitSize[0]>"._NO
        .'</font></td></tr>'
    ;
    // Maximum Upload Size
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALMAXSIZE.'</td><td>'
        ."<input type=\"text\" name=\"xmaxSize\" value=\"$maxSize\" size=\"15\"> <br>"
        .'</font></td></tr>'
    ;
    print '</table>'.CloseTable().'<br>';

    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";
    // Allow Rate
    $check_allowrate = array(0 => null, 1 => null);
    $check_allowrate[$allowrate] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALALLOWRATE."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xallowrate\" value=\"1\"$check_allowrate[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xallowrate\" value=\"0\"$check_allowrate[0]>"._NO
        .'</font></td></tr>'
    ;

    // Allow Anon Rate
    ////$bg = $colorBG->get_value(); $fg = $colorFG->get_value();
    $check_anonrate = array(0 => null, 1 => null);
    $check_anonrate[$anonrate] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALANONRATE."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xanonrate\" value=\"1\"$check_anonrate[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xanonrate\" value=\"0\"$check_anonrate[0]>"._NO
        .'</font></td></tr>'
    ;
    // Use Cookies For Rating
    ////$bg = $colorBG->get_value(); $fg = $colorFG->get_value();
    $check_setRateCookies = array(0 => null, 1 => null);
    $check_setRateCookies[$setRateCookies] = ' checked';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALSETRATECOOKIES."</td><td><font color=\"$fg\">"
        ."<input type=\"radio\" name=\"xsetRateCookies\" value=\"1\"$check_setRateCookies[1]>"._YES.'&nbsp;'
        ."<input type=\"radio\" name=\"xsetRateCookies\" value=\"0\"$check_setRateCookies[0]>"._NO
        .'</font></td></tr>'
    ;
    print '</table>'.CloseTable().'<br>';

    print OpenTable()."<table border=\"0\" cellpadding=\"0\" cellspacing=\"0\" width=\"100%\" bgcolor=\"$bg\">";
    // Default Thumbnail width
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><font color=\"$fg\">"._GALDEFTHUMBWIDTH.'</td><td>'
        ."<input type=\"text\" name=\"xthumbnailwidth\" value=\"$thumbnailwidth\" size=\"15\">"
        .'</font></td></tr>'
    ;

    // Image Conversion System
    $sel_imageSoftware = array('none' => null, 'browser' => null, 'GD' => null, 'ImageMagick' => null);
    $sel_imageSoftware[$imageSoftware] = ' selected';
    print "<tr height=\"60\" bgcolor=\"$bg\"><td><br><font color=\"$fg\">"._GALIMAGESOFTWARE.'</td><td><br>'
        .'<select name="ximageSoftware">'
        ."<option value=\"none\"" . $sel_imageSoftware['none'] . ">"._GALNONEIMAGESOFTWARE."</option>\n"
    ;
    print "<option value=\"browser\"" . $sel_imageSoftware['browser'] . ">"._GALBROWSERIMAGESOFTWARE."</option>\n";
    if(function_exists('imagecreate')){
        print "<option value=\"GD\"" . $sel_imageSoftware['GD'] . ">"._GALGDIMAGESOFTWARE."</option>\n";
    }
    print "<option value=\"ImageMagick\"" . $sel_imageSoftware['ImageMagick'] . ">ImageMagick</option>\n"
        .'</select>'
        .'</font></td></tr>'
    ;
    print '</table>'.CloseTable().'<br>';

    // Save
    //$bg = $colorBG->get_value(); $fg = $colorFG->get_value();
    print "<table width=\"100%\"><tr height=\"60\" bgcolor=\"$bg\"><td colspan=\"2\"><font color=\"$fg\"><br>"
        .'<center><input class="button" type="submit" value="'._SAVECHANGES.'"></center><br>'
        .'</td></tr></table>'
    ;
    print '</form>';
    // Start Of Footer
    OpenTable();
    print '
    <table><tr>
    <td>'
      ."<font face=\"Verdana,Arial\" color=\"$textcolor1\">mpn eGallery Version - $version<br>"._GALVISITUPDATE.'</font>
    </td>
    </tr></table>';
    CloseTable();

#   include 'footer.php';
}

function ConfigSave($vars)
{
    global $adminpath, $mpnTables;

    $check_ary = array( $vars['xthumbnailwidth'], $vars['xmaxSize'] );

    $verify_check_ary = $_SERVER['SAN'] -> verifyContent( $check_ary, 5 );

    // Check Num Only

    if ( in_array( (bool)FALSE, $verify_check_ary ) )
    {
        goBack( translate( 'Please Make Sure You Have Numbers In Number Only Fields' ) );
        exit;
    }

    include "$adminpath/config.php";


    $template[] = "<?php\n";
    $template[] = require('./admin/configs_header.php');
    $template[] = "##################################################################\n";
    $template[] = "# General Gallery Configuration\n";
    $template[] = "#\n";
    $template[] = "# Go to the Admin Panel (General Settings) to modify this File\n";
    $template[] = "#\n";
    $template[] = "##################################################################\n\n";

    $config = array(
        'version' => _GALVERSION,
        'module_name' => $vars['xmodule_name'],
        'basepath' => "gallery",
        'imagepath' => "gallery/images",
        'gallerypath' => "gallery/gallery",
        'modulepath' => "gallery",
        'adminpath' => "admin/gallery",
        'languagepath' => "gallery/language",
        'baseurl' => "myegallery.php?",
        'adminurl' => "admin.php?fct=gallery",
        'allowcomments' => $vars['xallowcomments'],
        'thumbnailwidth' => $vars['xthumbnailwidth'],
        'anoncomments' => $vars['xanoncomments'],
        'allowpostpics' => $vars['xallowpostpics'],
        'anonpostpics' => $vars['xanonpostpics'],
        'allowrate' => $vars['xallowrate'],
        'anonrate' => $vars['xanonrate'],
        'setRateCookies' => $vars['xsetRateCookies'],
        'limitSize' => $vars['xlimitSize'],
        'maxSize' => $vars['xmaxSize'],
        'GalleryPictureName' => $vars['xGalleryPictureName'],
        'maxNumberMedia' => $vars['xmaxNumberMedia'],
        'displaytop' => $vars['xdisplaytop'],
        'displaysortbar' => $vars['xdisplaysortbar'],
        'defaultsortmedia' => $vars['xdefaultsortmedia'],
        'maintemplate' => $vars['xmaintemplate'],
        'numColMain' => $vars['xnumColMain'],
        'imageSoftware' => $vars['ximageSoftware']
    );

    /*if(phpversion() >= '4.0.0') { // php4+
        foreach($config as $k=>$v) {
            $template[] = "\$$k = '$v';\n";
        }
    }
    else { // php3
        while(list($k, $v) = each($config)) {
            $template[] = "\$$k = '$v';\n";
        }
    }*/

    foreach( $config AS $var => $v )
    {
        $template[] = '$' . $var . ' = "' . $v . '";';
    }

    $template[] = '?>';

    $filename = 'admin/gallery/config.php';

    if ( ! $_SERVER['F_LIB'] -> writeFile( $filename, 'w+b', $template ) )
    {
        goBack( translate( 'File Write Error.  Check Permissions On ' ) . $filename );
        exit;
    }

   /* fwrite($fp, implode($template,''));
    fclose($fp);*/

#   // rename the module if needed
#   if($module_name != $vars[xmodule_name]) {
#       rename("modules/$module_name", "modules/$vars[xmodule_name]");
#   }
#   return;
    $_SERVER['F_LIB'] -> redirectRequest(  "$adminurl" );
}

function rebuild_totals($debug = false) {
    global $mpnTables;
    $result = mysql_query("SELECT gallid FROM ".$mpnTables['gallery_categories']." WHERE visible>0 ORDER BY gallid");
    while($row = mysql_fetch_array($result)) {
        $total = mysql_fetch_array(mysql_query("SELECT COUNT(pid) AS total FROM ".$mpnTables['gallery_pictures']." WHERE gid=" . $row['gallid']));
        $catTotal[$row['gallid']] = $total['total']; // id=>total
    }
    // total for parents
    $result = mysql_query("SELECT gallid, parent FROM ".$mpnTables['gallery_categories']." WHERE visible>0 ORDER BY parent DESC");

    $t = array();

    while($row = mysql_fetch_array($result)) {
        if($row['parent']) {

            @$t[$row['parent']] = ($t[$row['parent']] + $catTotal[$row['gallid']]) + $t[$row['gallid']];
        }
    }

    // add total of current category to total of all sub-categories
    $result = mysql_query("SELECT gallid, parent FROM ".$mpnTables['gallery_categories']." WHERE visible>0 ORDER BY parent DESC");
    while($row = mysql_fetch_array($result)) {
        @$t[$row['gallid']] = $t[$row['gallid']] + $catTotal[$row['gallid']];
    }
    // do some zero filling on all categories, even non-visible
    $result = mysql_query("SELECT gallid FROM ".$mpnTables['gallery_categories']." ORDER BY gallid");
    while($row = mysql_fetch_array($result)) {
        $t[$row['gallid']] = intval($t[$row['gallid']]);
    }
    // ok, update our tables here
    foreach($t as $k=>$v) {
        mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET total=$v WHERE gallid=$k");
        if($debug) print mysql_error();
    }
    // debug
    if($debug) {
        print '<table><tr><th>ID</th><th>Category</th><th>Total</th></tr>';
        $result = mysql_query("SELECT gallid, gallname, total FROM ".$mpnTables['gallery_categories']." ORDER BY parent DESC");
        while($row = mysql_fetch_array($result)) {
            print "<tr><td>" . $row['gallid'] . "</td><td>" . $row['gallname'] . "</td><td>" . $row['total'] . "</td></tr>\n";
        }
        print '</table>';
        exit;
    }
}
if(isset($do) && $do == 'test_totals') {
    rebuild_totals(true);
    exit;
}

function rebuild_lastadd($debug = false) {
    global $mpnTables;
    // update each category last add first
    $result = mysql_query("SELECT gallid FROM ".$mpnTables['gallery_categories']." ORDER BY gallid");
    while($row = mysql_fetch_array($result)) {
        $high = mysql_fetch_array(mysql_query("SELECT COUNT(pid) AS total, TO_DAYS(date) AS days FROM ".$mpnTables['gallery_pictures']." WHERE gid=" . $row['gallid'] . " GROUP BY date ORDER BY date DESC"));
        print mysql_error();
        if($high['total']) {
            mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET lastadd=FROM_DAYS(" . $high['days'] . ") WHERE gallid=" . $row['gallid']);
            if($debug) print mysql_error();
        }
        else {
            mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET lastadd=0 WHERE gallid=" . $row['gallid']);
            if($debug) print mysql_error();
        }
    }
    // step backward and compare
    $result = mysql_query("SELECT gallid, parent, TO_DAYS(lastadd) AS days FROM ".$mpnTables['gallery_categories']." WHERE visible>0 ORDER BY parent DESC");
    while($row = mysql_fetch_array($result)) {
        if($row['parent']) {
            $prow = mysql_fetch_array(mysql_query("SELECT TO_DAYS(lastadd) AS days FROM ".$mpnTables['gallery_categories']." WHERE gallid=" . $row['parent']));
            // update parent is current is greater
            if($row['days'] > $prow['days']) {
                mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET lastadd=FROM_DAYS(" . $row['days'] . ") WHERE gallid=" . $row['parent']);
                if($debug) print mysql_error();
            }
        }
    }
    // debug
    if($debug) {
        print '<table><tr><th>ID</th><th>Category</th><th>Last Add</th></tr>';
        $result = mysql_query("SELECT gallid, gallname, lastadd AS days FROM ".$mpnTables['gallery_categories']." ORDER BY parent DESC");
        while($row = mysql_fetch_array($result)) {
            print "<tr><td>" . $row['gallid'] . "</td><td>" . $row['gallname'] . "</td><td>" . $row['days'] . "</td></tr>\n";
        }
        print '</table>';
        exit;
    }
}
if(isset($do) && $do == 'test_add') {
    rebuild_lastadd(true);
    exit;
}


function changeStatus($gid, $visible) {
    global $mpnTables;

    $sql = "UPDATE ".$mpnTables['gallery_categories']." SET visible=$visible WHERE gallid=$gid";
    mysql_query($sql);

    $sql= "SELECT gallid FROM ".$mpnTables['gallery_categories']." WHERE parent=$gid";
    $result = mysql_query($sql);
    while ($row = mysql_fetch_array($result)) {
        changeStatus($row['gallid'], $visible);
    }
    mysql_free_result($result);
}

function doeditcategory($type, $category, $parent) {
global $adminurl, $module_name, $imagepath, $gallerypath, $adminpath, $languagepath, $baseurl, $adminurl, $modulepath;
global $version, $bgcolor1, $bgcolor2, $bgcolor3, $bgcolor4, $GalleryPictureName, $basedir;
global $categoryname, $image, $description, $xtemplate, $visible, $numcol, $categoryloc, $mpnTables;
global $oldloc, $newloc, $parentloc, $confirmed, $oldlocation, $newparent, $userfile, $userfile_name;
        if (isset($type) && $type!="") {
          switch ($type) {
            case "save": //OK!
                if (isset($category) && $category!="") {
                    mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET gallname='$categoryname', gallimg='$image', description='$description', template=$xtemplate, visible=$visible, numcol=$numcol WHERE gallid=$category");
                }
                rebuild_totals();
                rebuild_lastadd();

                $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editallcategories' );

                break;

            case "create": //OK!
                include ("$adminpath/fileFunctions.php");
                $categoryloc = traite_nom_fichier($categoryloc);
                if ($parent!=-1)
                    $categoryloc = $parentloc."/".$categoryloc;

                $basedir = $gallerypath;
                $wdir = "/";
                $makeDir_return = makeDir($basedir, $categoryloc);
                if ($makeDir_return==0) {
                    $userfile_size = null;
                    if (!isset($userfile) || $userfile=="" || $userfile=="none") {
                        $userfile = $imagepath."/gallery.gif";
                        $userfile_name = "gallery.gif";
                        $userfile_size = 10;
                    }
                    $upload_return = UploadFile($gallerypath.$wdir.$categoryloc, $userfile, $userfile_name, $userfile_size) ;
                    if ($upload_return == 0)
                        mysql_query("INSERT INTO ".$mpnTables['gallery_categories']." (gallid, gallname, gallimg, galloc, description, parent, visible, template, numcol, total, lastadd) VALUES (NULL, '$categoryname', '$userfile_name', '$categoryloc', '$description', $parent, $visible, 2, $numcol, 0, now())");
                    else {
#                       include ("header.php");
#                       GraphicAdmin($hlpfile);
                        OpenTable();
                        echo "<center><font size=\"4\"><b>"._GALADMIN."</b></font></center>";
                        CloseTable();
                        echo "<br>";
                        OpenTable();
                        echo '<br>';
                        if ($upload_return==1)
                            echo '<center>'._GALNOMEDIA.'<br><br>'._GOBACK.'</center>';
                        else
                        if ($upload_return==2)
                            echo '<center>'._GALPBUPLOAD.'<br><br>'._GOBACK.'</center>';
                        //echo '<center>'.$upload_return.'<br><br>'._GOBACK.'</center>';
                        CloseTable();
#                       include('footer.php');
                    }
                rebuild_totals();
                rebuild_lastadd();
                }
                else {
                    include ("header.php");
#                   GraphicAdmin($hlpfile);
#                   OpenTable();
                    echo "<center><font size=\"4\"><b>"._GALADMIN."</b></font></center>";
                    CloseTable();
                    echo "<br>";
                    OpenTable();
                    echo '<br>';
                    echo '<center>'.$makeDir_return.'<br><br>'._GOBACK.'</center>';
                    CloseTable();
#                   include('footer.php');
                }

                $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editallcategories' );

                break;
            case "move": //OK!
                include ("$adminpath/movecategory.php");
                $basedir = "$gallerypath";
                $wdir = "/";
                if (!isset($confirmed) || $confirmed=="")
                    movecategory($category);
                else {
                    list($oldloc) = mysql_fetch_row(mysql_query("SELECT galloc FROM ".$mpnTables['gallery_categories']." WHERE gallid=$oldlocation"));
                    list($newloc) = mysql_fetch_row(mysql_query("SELECT galloc FROM ".$mpnTables['gallery_categories']." WHERE gallid=$newparent"));
                    $dir = substr (strrchr ($oldloc, "/"), 1);

                    if ($dir=="") {
                        if ($newloc!="") {
                            //echo $basedir.$wdir.$oldloc." 1-> ".$basedir.$wdir.$newloc.$wdir.$oldloc."<br>";
                            mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET parent=$newparent, galloc='$newloc/$oldloc' WHERE gallid=$oldlocation");
                            rmove($basedir.$wdir.$oldloc,$basedir.$wdir.$newloc.$wdir.$oldloc);
                        }
                        else {
                            //echo $basedir.$wdir.$oldloc." 2-> ".$basedir.$wdir.$oldloc."<br>";
                            mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET parent=$newparent, galloc='$oldloc' WHERE gallid=$oldlocation");
                            rmove($basedir.$wdir.$oldloc,$basedir.$wdir.$oldloc);
                        }
                    }
                    else {
                        if ($newloc!="") {
                            //echo $basedir.$wdir.$oldloc." 3-> ".$basedir.$wdir.$newloc.$wdir.$dir."<br>";
                            mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET parent=$newparent, galloc='$newloc/$dir' WHERE gallid=$oldlocation");
                            rmove($basedir.$wdir.$oldloc,$basedir.$wdir.$newloc.$wdir.$dir);
                        }
                        else {
                            //echo $basedir.$wdir.$oldloc." 4-> ".$basedir.$wdir.$dir."<br>";
                            mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET parent=$newparent, galloc='$dir' WHERE gallid=$oldlocation");
                            rmove($basedir.$wdir.$oldloc,$basedir.$wdir.$dir);
                        }

                    }
                    rebuild_totals();
                    rebuild_lastadd();

                    $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editallcategories' );
                }

                break;

            case "delete": //OK!
                include ("$adminpath/deletecategory.php");
                deletecategory($category);
                rebuild_totals();
                rebuild_lastadd();

                $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editallcategories' );

                break;

            case 'status':
                changeStatus($category, $visible);
                //  mysql_query("UPDATE ".$mpnTables['gallery_categories']." SET visible=$visible WHERE gallid=$category");
                rebuild_totals();
                rebuild_lastadd();

                $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editallcategories' );

                break;
          }
        }
        else {
            include ("$adminpath/editcategory.php");
            editcategory($category, $parent);
        }
}

function doedittemplate($type, $template, $delete) {
global $adminurl, $xtemplatename, $xtemplateCat ,$xtemplatePic, $xtemplateCSS, $templateid, $xtype, $mpnTables;
        if (isset($delete) && $delete!="") {
             $sql = "DELETE FROM ".$mpnTables['gallery_template_types']." WHERE id=$template";
             //echo $sql;
             mysql_query($sql);

             $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editalltemplate' );

         }
         else
                if (isset($type) && $type!="") {

             switch ($type) {
                 case "edit":
                     echo "hier nicht";
                     break;

                 case "save":
                     $sql = "UPDATE ".$mpnTables['gallery_template_types']." SET title='$xtemplatename', templateCategory='$xtemplateCat', templatePictures='$xtemplatePic', templateCSS='$xtemplateCSS' WHERE id=$templateid";
                     //echo $sql;
                     mysql_query($sql);

                     $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editalltemplate' );

                     break;

                 case "create":
                     $sql = "INSERT INTO ".$mpnTables['gallery_template_types']." (id, title, type, templateCategory, templatePictures, templateCSS) VALUES (NULL, '$xtemplatename', $xtype, '$xtemplateCat', '$xtemplatePic', '$xtemplateCSS')";
                     //echo $sql;
                     mysql_query($sql);

                     $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=editalltemplate' );

                     break;
             } // switch
         } //if
}
function doeditmedia($type, $category) {
    global $adminurl, $module_name, $imagepath, $gallerypath, $adminpath, $languagepath, $baseurl, $adminurl;
    global $version, $bgcolor1, $bgcolor2, $bgcolor3, $bgcolor4;
    global $offset, $mpnTables;
    global $adminurl, $module_name, $imagepath, $gallerypath, $adminpath, $languagepath, $baseurl, $adminurl, $modulepath;
    global $version, $bgcolor1, $bgcolor2, $bgcolor3, $bgcolor4, $GalleryPictureName, $basedir;
    global $categoryname, $image, $description, $xtemplate, $visible, $numcol, $Task0, $Task1, $Description0;
    global $categoryloc, $oldloc, $newloc, $parentloc, $confirmed, $oldlocation, $newparent, $userfile;

#           .search_form($HTTP_POST_VARS)


        $limit=5;
        if (isset($type) && $type!="") {
          switch ($type) {
            case "edit": //OK!
                include ("$adminpath/editmedia.php");
                editmedia($category);
                break;

            case "new": //OK!
                include ("$adminpath/fileFunctions.php");
                //include ("$adminpath/quickaddmedia.php");
                if (isset($add) && $add=="Insert") {
                    list($galloc) = mysql_fetch_row(mysql_query("SELECT galloc FROM ".$mpnTables['gallery_categories']." WHERE gallid=$Category"));
                    //$basedir = $gallerypath;
                    $wdir = "/";
                    $upload_return = UploadFile($gallerypath.$wdir.$galloc, $userfile, $userfile_name, $userfile_size);
                    if ($upload_return==0) {
                        $userfile_name=  traite_nom_fichier($userfile_name);
                        $ext = substr($userfile_name, (strrpos($userfile_name,'.') +  1));
                        list($type) = mysql_fetch_row(mysql_query("select filetype from ".$mpnTables['gallery_media_types']." where extension='$ext'"));
                        if($type == 1) {
                            $size = getimagesize($gallerypath.$wdir.$galloc.$wdir.$userfile_name);
                        }
                        else {
                            switch($type) {
                                case 3 :
                                    $size[0] = 320;
                                    $size[1] = 240;
                                    break;
                                default:
                                    $size[0] = 0;
                                    $size[1] = 0;
                                    break;
                            }
                        }
                        $sql = "insert into ".$mpnTables['gallery_pictures']." (pid, gid, img, counter, submitter, date, name, description, votes, rate, extension, width, height) values(NULL, $Category, '$userfile_name', 0, '$Submitter', now(), '$MediaName', '$Description', 0, 0, '$ext', ".$size[0].", ".$size[1].")";
                        //echo $sql;
                        mysql_query($sql);
                    }
                    else {
#                       include ("header.php");
#                       GraphicAdmin($hlpfile);
                        OpenTable();
                        echo "<center><font size=\"4\"><b>"._GALADMIN."</b></font></center>";
                        CloseTable();
                        echo "<br>";
                        OpenTable();
                        echo '<br>';
                        echo '<center>'.$upload_return.'<br><br>'._GOBACK.'</center>';
                        CloseTable();
#                       include('footer.php');
                    }

                    $_SERVER['F_LIB'] -> redirectRequest( $adminurl );
                }
                else {
                    include ("$adminpath/createmedia.php");
                    createmedia();
                }
                rebuild_totals();
                rebuild_lastadd();
                break;

            case "existing": //OK!
                for ($i=0; $i<$limit; $i++) {
                    $task = "Task$i";

                    if (isset($$task)) {
                        switch ($$task) {
                            case "Save" : // OK!
                                $file = "FileName$i";
                                $fileid = "FileId$i";
                                $desc = "Description$i";
                                $name = "FileName$i";
                                //$oldname = "OldFileName$i";
                                $mname = "MediaName$i";
                                $date = "Date$i";
                                $cat = "Category$i";
                                $oldcat = "OldCategory$i";
                                $submitter = "Submitter$i";
                                $width = "Width$i";
                                $height = "Height$i";
                                //list($galloc) = mysql_fetch_row(mysql_query("SELECT galloc FROM ".$mpnTables['gallery_categories']." WHERE gallid=".$$cat));

                                $sql  = "UPDATE ".$mpnTables['gallery_pictures']." ";
                                $sql .= "SET gid=".$$cat.", ";
                                $sql .= "submitter='".$$submitter."', date='".$$date."', img='".$$name."', ";
                                $sql .= "name='".$$mname."', description = '".$$desc."', ";
                                $sql .= "width='".$$width."', height='".$$height."' ";
                                $sql .= "WHERE pid=".$$fileid;
                                //echo $sql;
                                $okcat =1;
                                $basedir = $basepath;
                                $wdir = "/";
                                if ($$cat != $$oldcat) {
                                    // We move the picture
                                    list($oldloc) = mysql_fetch_row(mysql_query("SELECT galloc from ".$mpnTables['gallery_categories']." WHERE gallid=".$$oldcat));
                                    list($newloc) =  mysql_fetch_row(mysql_query("SELECT galloc from ".$mpnTables['gallery_categories']." WHERE gallid=".$$cat));
                                    if (!is_writable($gallerypath.$wdir.$oldloc.$wdir.$$name) || !is_writable($gallerypath.$wdir.$newloc.$wdir))
                                    {
                                        goBack( translate('Gallery Folders misconfigured for renaming files') );
                                    }

                                    if (rename($gallerypath.$wdir.$oldloc.$wdir.$$name,$gallerypath.$wdir.$newloc.$wdir.$$name)) {
                                        @chmod($gallerypath.$wdir.$newloc.$wdir.$$name, 0666);
                                        $okcat = 1;
                                        $thumb = getThumbnail($$name, $oldloc);
                                        if (!strstr($thumb,$imagepath)) {
                                            $thumb = substr (strrchr ($thumb, "/"), 1);
                                            //echo "move : ".$gallerypath.$wdir.$oldloc.$wdir."thumb/".$thumb." -> ".$gallerypath.$wdir.$newloc.$wdir."thumb/".$thumb."<br>";
                                            if (!is_writeable($gallerypath.$wdir.$oldloc.$wdir."thumb/".$thumb) || !is_writeable($gallerypath.$wdir.$newloc.$wdir."thumb/"))
                                            {
                                                goBack( translate('Gallery Folders misconfigured for renaming files') );
                                            }

                                            if (rename($gallerypath.$wdir.$oldloc.$wdir."thumb/".$thumb,$gallerypath.$wdir.$newloc.$wdir."thumb/".$thumb)) {
                                                @chmod($gallerypath.$wdir.$newloc.$wdir."thumb/".$thumb, 0666);
                                                $okcat = 1;
                                            } else {
                                                $okcat = 0;
                                            }
                                        }
                                    }
                                    else
                                        $okcat = 0;
                                }
                                if ($okcat)
                                    mysql_query($sql);
                                rebuild_totals();
                                rebuild_lastadd();
                                break;

                            case "Delete" : // OK!
                                $file = "FileName$i";
                                $cat = "Category$i";
                                $fileid = "FileId$i";
                                list($galloc) = mysql_fetch_row(mysql_query("SELECT galloc FROM ".$mpnTables['gallery_categories']." WHERE gallid=".$$cat));
                                $basedir = "$gallerypath";
                                $wdir = "/";
                                //echo "delete : ".$basedir.$wdir.$galloc.$wdir.$$file."<br>";
                                if (file_exists($basedir.$wdir.$galloc.$wdir.$$file))
                                    unlink($basedir.$wdir.$galloc.$wdir.$$file);
                                $thumb = getThumbnail($$file, $galloc);
                                //echo "delete thumb: $thumb<br>";
                                if (!strstr($thumb, $imagepath))
                                    unlink($thumb);
                                $sql  = "DELETE FROM ".$mpnTables['gallery_pictures']." WHERE pid=".$$fileid;
                                //echo $sql;
                                mysql_query($sql);
                                rebuild_totals();
                                rebuild_lastadd();
                                break;
                        }
                    }
                } // for
                rebuild_totals();
                rebuild_lastadd();

                $_SERVER['F_LIB'] -> redirectRequest( $adminurl . '&op=maineditmedia' );

                break;
          } // Switch
        } // If

}

?>
