<?php

/*++++++++++++++++++++++++++++++++++++++++

  Script: Maian Gallery v2.0
  Written by: David Ian Bennett
  E-Mail: support@maianscriptworld.co.uk
  Website: http://www.maianscriptworld.co.uk

  ++++++++++++++++++++++++++++++++++++++++
  
  This File: index.php
  Description: Main Admin Parsing File

  ++++++++++++++++++++++++++++++++++++++++*/
  
// Start session..  
session_start();

// Set error reporting..E_ALL for development..
error_reporting(0);
 
// Set paths..
define ('FOLDER_PATH', dirname(__FILE__).'/');
define ('RELATIVE_PATH', '../');
define ('INCLUDE_FILES', 1);
define ('PARENT',1);

// Database connection..
include(RELATIVE_PATH.'inc/db_connection.inc.php');
 
// Load settings..
$SETTINGS  = mysql_fetch_object(mysql_query("SELECT * FROM ".$database['prefix']."settings LIMIT 1 ")) or die(mysql_error());
    
// Load paypal data..                                        
$PP        = mysql_fetch_object(mysql_query("SELECT * FROM ".$database['prefix']."paypal LIMIT 1")) or die(mysql_error());                                            

// Load include files..
include(RELATIVE_PATH.'lang/'.$SETTINGS->language);
include(FOLDER_PATH.'inc/functions.php');
include(FOLDER_PATH.'inc/defined.inc.php');
include(RELATIVE_PATH.'inc/functions.php');
include(RELATIVE_PATH.'classes/class_generic.inc.php');
include(FOLDER_PATH.'classes/PaginateIt.php');
include(FOLDER_PATH.'classes/class_watermarker.inc.php');
include(FOLDER_PATH.'classes/class_mail.inc.php');
include(FOLDER_PATH.'classes/class_cats.inc.php');
include(FOLDER_PATH.'classes/class_sales.inc.php');
include(RELATIVE_PATH.'classes/class_cart.inc.php');
include(FOLDER_PATH.'classes/class_images.inc.php');
include(FOLDER_PATH.'classes/class_emails.inc.php');
include(FOLDER_PATH.'classes/class_ban.inc.php');

// Default vars..
$cmd           = (isset($_GET['cmd']) ? strip_tags($_GET['cmd']) : 'home');
$page          = (isset($_GET['page']) && ctype_digit($_GET['page']) ? $_GET['page'] : '1');
$count         = 0;
$limit         = DATA_PAGES;
$limitvalue    = $page * $limit - ($limit);
$error_string  = array();
$pageTitle     = '';
 
// Create objects of class files..
$MGA_WMARK            = new waterMarker();
$MGA_CART             = new mga_Cart();
$MGA_MAIL             = new mailClass();
$MGA_IMAGES           = new images();
$MGA_CATS             = new cats();
$MGA_EMAILS           = new emailAddress();
$MGA_BAN              = new banOption();
$MGA_SALES            = new sales();
$MGA_CATS->prefix     = $database['prefix'];
$MGA_IMAGES->prefix   = $database['prefix'];
$MGA_EMAILS->prefix   = $database['prefix'];
$MGA_BAN->prefix      = $database['prefix'];
$MGA_SALES->prefix    = $database['prefix'];
$MGA_CART->prefix     = $database['prefix'];
$MGA_MAIL->smtp        = $SETTINGS->smtp;
$MGA_MAIL->smtp_host   = $SETTINGS->smtp_host;
$MGA_MAIL->smtp_user   = $SETTINGS->smtp_user;
$MGA_MAIL->smtp_pass   = $SETTINGS->smtp_pass;
$MGA_MAIL->smtp_port   = $SETTINGS->smtp_port;
$MGA_MAIL->addTag('{WEBSITE_NAME}',$SETTINGS->website);
$MGA_MAIL->addTag('{WEBSITE_URL}',$SETTINGS->folder);
$MGA_MAIL->addTag('{WEBSITE_EMAIL}',$SETTINGS->email);

//----------------------------
//Load data file template
//----------------------------

switch ($cmd)
{
  // Home..
  case 'home':
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu2;
     
  // Does install dir exist?
  if (is_dir(RELATIVE_PATH.'install/')) {
    $INSTALL_FILE = true;
  }  

  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/home.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
     
  // Settings..
  case "settings":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu3;
     
  // View RGB converter
  if (isset($_GET['view']) && $_GET['view']=='rgb') {
    include(FOLDER_PATH.'data_files/popup/rgbcoverter.php');
    exit;
  }
  
  // Switch tabs..
  if (isset($_GET['tab'])) {
    $_SESSION['settings_tab'] = $_GET['tab'];
    header("Location: index.php?cmd=settings");
    exit;
  }

  // View Sample Watermark
  if (isset($_GET['watermark'])) {
    include(FOLDER_PATH.'data_files/popup/watermark.php');
    exit;
  }
     
  // Update settings..
  if (isset($_POST['process']))
  {
    include(FOLDER_PATH.'classes/class_settings.inc.php');
   
    $MGA_SETTINGS          = new settings();
    $MGA_SETTINGS->prefix  = $database['prefix'];
         
    if (isset($_POST['generalbutton'])) {
      $MGA_SETTINGS->update_general($_POST);
      
      if (isset($_POST['reset'])) {
        $MGA_SETTINGS->clear();
      }
    }     
    if (isset($_POST['imagesbutton'])) {
      $MGA_SETTINGS->update_images($_POST);
      $MGA_SETTINGS->update_slideshow($_POST);
    }
    if (isset($_POST['waterbutton'])) {
      $MGA_SETTINGS->update_watermarks($_POST);
    }
    if (isset($_POST['cartbutton'])) {
      $MGA_SETTINGS->update_cart($_POST);
    }
    if (isset($_POST['smtpbutton'])) {
      $MGA_SETTINGS->update_smtp($_POST);
    }     
    
    header("Location: index.php?cmd=settings");
    exit;
  }

  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/settings.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
     
  case 'comments':
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu14;
  
  // View/update pre-approved comments or current comments..
  if (isset($_GET['cid']) || isset($_POST['edit_comment'])) {
    if (isset($_POST['edit_comment'])) {
      $MGA_IMAGES->update_comment($_POST);
    }
    include(FOLDER_PATH.'data_files/popup/'.(isset($_POST['imgid']) ? 'comments' : 'view_comments').'.php');
    exit;
  }
  
  // Delete comment..
  if (isset($_GET['del'])) {
    $MGA_IMAGES->delete_comment($_GET['del']);
    header("Location: index.php?cmd=".$_GET['return']."&comments=".$_GET['comments']."");
    exit;
  }
  
  // Process comments..
  if (isset($_POST['process'])) {
    if (!empty($_POST['comment'])) {
      for ($i=0; $i<count($_POST['comment']); $i++) {
        $split  = explode("##", $_POST['comment'][$i]);
        $IMG    = getImageData($split[1]);
        $COM    = get_comment_data($split[0]);
        $CAT    = getCategoryData($IMG->cat);
        
        // Process..approve/reject..
        if (isset($_POST['approve'])) {
          $MGA_IMAGES->process_comment($split[0]);
        }
        if (isset($_POST['reject'])) {
          $MGA_IMAGES->process_comment($split[0],true);
        }
                
        // Send mail..
        if (isset($_POST['mail'])) {
          
          $MGA_MAIL->addTag('{NAME}',$COM->name);
          $MGA_MAIL->addTag('{COMMENTS}',$COM->comments);
          $MGA_MAIL->addTag('{IMG_NAME}',$IMG->name);
          $MGA_MAIL->addTag('{IMG_URL}',$SETTINGS->folder.'/'.($SETTINGS->modr ? 'picture/'.$IMG->id.'/'.addTitleToUrl(getCategoryName($IMG->cat)).'/'.addTitleToUrl($IMG->name).'.html' : 'index.php?cmd=picture&picture.'.$IMG->id));
          
          $MGA_MAIL->sendMail($COM->name,
                              $COM->email,
                              $SETTINGS->website,
                              $SETTINGS->email,
                              '['.$SETTINGS->website.'] '.(isset($_POST['approve']) ? $msg_comments17 : $msg_comments18),
                              $MGA_MAIL->template(RELATIVE_PATH.'themes/email/comments_'.(isset($_POST['approve']) ? 'approved' : 'rejected').'.txt')
                              );
        }
      }
    }
    
    header("Location: index.php?cmd=comments");
    exit;
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/comments.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
     
  // Sales..
  case "sales":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu12;
  
  // View order details..
  if (isset($_GET['view']) && ctype_digit($_GET['view'])) {
    include(FOLDER_PATH.'data_files/popup/view_order.php');
    exit;
  }
  
  // Change status..
  if (isset($_GET['status']) || isset($_POST['update_status'])) {
    // Update status..
    if (isset($_POST['update_status'])) {
      // Set status..
      $status = (isset($_POST['status']) ? (int)($_POST['status']-1) : '0');
      // Change order status..
      $MGA_SALES->changeOrderStatus((int)$_POST['id'],(int)$status);
      // Send email...
      if (isset($_POST['email'])) {
        // Get order information..
        $order = $MGA_SALES->getOrder($_POST['id'],$SETTINGS);
        // Set new status text..
        switch ($status) {
          case '0': $st_text = $msg_sales12; break;
          case '1': $st_text = $msg_sales13; break;
          case '2': $st_text = $msg_sales14; break;
        }
        // Send mail..
        $MGA_MAIL->addTag('{NAME}',$order->first_name.' '.$order->last_name);
        $MGA_MAIL->addTag('{TOTAL}',$MGA_CART->formatPrice($order->gross).' ('.$PP->ppCurrency.')');
        $MGA_MAIL->addTag('{INVOICE_NO}',$order->invoice);
        $MGA_MAIL->addTag('{PICTURES}',$MGA_CART->loadPurchasesIntoString($order->cartID,$msg_ipn6,$msg_ipn8,$msg_ipn7));
        $MGA_MAIL->addTag('{DATE}',$order->s_date);
        $MGA_MAIL->addTag('{COMMENTS}',($_POST['comments'] ? $_POST['comments'] : $msg_sales22));
        $MGA_MAIL->addTag('{STATUS}',$st_text);
        
        // Send mail to webmaster..
        $MGA_MAIL->sendMail($order->first_name.' '.$order->last_name,
                            $order->email,
                            $SETTINGS->website,
                            $SETTINGS->email,
                            '['.$SETTINGS->website.'] '.$msg_sales21,
                            $MGA_MAIL->template(RELATIVE_PATH.'themes/email/status_updated.txt')
                            );
      }
      
      header("Location: index.php?cmd=sales&status=".$_POST['id']."&updated=1");
      exit;
    }
    include(FOLDER_PATH.'data_files/popup/change_status.php');
    exit;
  }
  
  // Delete sales..
  if (isset($_POST['process'])) {
    if (!empty($_POST['id'])) {
      for ($i=0; $i<count($_POST['id']); $i++) {
        $MGA_SALES->delete($_POST['id'][$i]);
      }
    }
    header("Location: index.php?cmd=sales");
    exit;
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/sales.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
  
  // Sales..
  case "selling_options":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu15;
  
  // Update image sale options..
  if (isset($_POST['process'])) {
    $count  = $MGA_IMAGES->update_sale_options($_POST);
    $OK     = true;
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/selling_options.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
     
  // Categories..
  case "cats":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu4;
     
  // Add/Edit category..
  if (isset($_POST['process']))
  {
    if (isset($_POST['edit'])) {
      $MGA_CATS->update_cat_sql($_POST);
    } else {
      if (trim($_POST['cat'])) {
        $MGA_CATS->add_cat_sql($_POST);
      }
    }
    
    header("Location: index.php?cmd=cats".(isset($_POST['edit']) ? '&edit='.$_POST['edit'] : ''));
    exit;
  }

  // Delete child..
  if (isset($_GET['del'])) {
    $MGA_CATS->delete_cat_sql($_GET['del']);
    
    header("Location: index.php?cmd=cats");
    exit;
  }
  
  // Delete cats/children..
  if (isset($_POST['process_del'])) {
    if (!empty($_POST['cat'])) {
      for ($i=0; $i<count($_POST['cat']); $i++) {
        $MGA_CATS->delete_cat_sql($_POST['cat'][$i],true);
      }
    }
    
    header("Location: index.php?cmd=cats");
    exit;
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/cats.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
  
  // Add new images..
  case "add_images":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu6;
     
  // Sales help..
  if (isset($_GET['salehelp'])) {
    include(FOLDER_PATH.'data_files/popup/salehelp.php');
    exit;
  }

  // Add images..
  if (isset($_POST['process']))
  {
    // Set count var for processing..
    // Set array..
    // Get prefixes for files..
    $processed  = 0;
    $report     = array();
    $prefix     = explode("|", IMAGE_PREFIX);
    
    //  Process files..
    for ($i=0; $i<count($_POST['path']); $i++) {
      // Only process if name included..
      if (trim($_POST['name'][$i])) {
        // Increment count..
        $count++;
        
        // Filter path name for fullsize image..
        $path       = $MGA_IMAGES->filter_file_path($_POST['path'][$i],$_POST['cat'][$i],$prefix[0]);
        $tpath      = $MGA_IMAGES->filter_file_path($_POST['path'][$i],$_POST['cat'][$i],$prefix[1]);
        
        // For thumbnail uploads..
        $oname      = (isset($_FILES['thumb']['name'][$i]) ? $_FILES['thumb']['name'][$i] : '');
        $name       = (isset($_FILES['thumb']['name'][$i]) ? $MGA_IMAGES->filter_file_path($_FILES['thumb']['name'][$i],$_POST['cat'][$i],$prefix[1]) : '');
        $temp       = (isset($_FILES['thumb']['tmp_name'][$i]) ? $_FILES['thumb']['tmp_name'][$i] : '');
        $size       = (isset($_FILES['thumb']['size'][$i]) ? $_FILES['thumb']['size'][$i] : '');
        $type       = (isset($_FILES['thumb']['type'][$i]) ? $_FILES['thumb']['type'][$i] : '');
        
        // If upload box is present, is there an upload..
        if (isset($_POST['upload']) && ($name=='' || $temp=='')) {
          $count--;
        } 
        
        // Assign default report vars to array. These never change..
        $report[$i][0] = trim($_POST['name'][$i]);
        $report[$i][1] = getFolderName($_POST['cat'][$i]);
        $report[$i][2] = getCategoryName($_POST['cat'][$i]);
        
        // Process if count is ok..
        if ($count>0) {
          // Create/upload thumbnail..
          if ($SETTINGS->autothumb) {
            if (is_dir(DOC_ROOT_FOR_UPLOAD.'galleries/'.$SETTINGS->folder_name.'/'.getFolderName($_POST['cat'][$i]))) {
              if ($MGA_IMAGES->create_thumbnail(DOC_ROOT_FOR_UPLOAD.'galleries/new/',
                                                $_POST['path'][$i],
                                                $SETTINGS->autowidth,
                                                $SETTINGS->autoheight,
                                                DOC_ROOT_FOR_UPLOAD.'galleries/'.$SETTINGS->folder_name.'/'.getFolderName($_POST['cat'][$i]).'/',
                                                $tpath
                                                )) {
              } else {
                $report[$i][3] = 'error_create';
                $report[$i][4] = $_POST['path'][$i];
                $s1_error      = true;
              }
            } else {
              $report[$i][3] = 'error_create_dir';
              $report[$i][4] = $_POST['path'][$i];
              $s1_error      = true;
            }
          } else {
            if (is_dir(DOC_ROOT_FOR_UPLOAD.'galleries/'.$SETTINGS->folder_name.'/'.getFolderName($_POST['cat'][$i]))) {
              if (!isset($s1_error) && substr($type,0,5)=='image' && 
                   $name && $temp && $MGA_IMAGES->upload_thumbnail($name,
                                                                   $temp,
                                                                   DOC_ROOT_FOR_UPLOAD.'galleries/'.$SETTINGS->folder_name.'/'.getFolderName($_POST['cat'][$i]).'/'
                                                                   )) {
              } else {
                $report[$i][3] = 'error_upload';
                $report[$i][4] = $_POST['path'][$i];
                $s1_error      = true;
              }
            } else {
              $report[$i][3] = 'error_upload_dir';
              $report[$i][4] = $_POST['path'][$i];
              $s1_error      = true;
            }
          }
          
          // Move image..
          if (!isset($s1_error)) {
            if ($MGA_IMAGES->move_to_new_directory(DOC_ROOT_FOR_UPLOAD.'galleries/new/',
                                                   $_POST['path'][$i],
                                                   DOC_ROOT_FOR_UPLOAD.'galleries/'.$SETTINGS->folder_name.'/'.getFolderName($_POST['cat'][$i]).'/',
                                                   $path
                                                   )) {
            } else {
              $report[$i][3] = 'error_move';
              $s2_error      = true;
              $report[$i][4] = $_POST['path'][$i];
            }
          }
          
          // Add to database..
          if (!isset($s1_error) && !isset($s2_error)) {
            if ($MGA_IMAGES->insert_image_sql($_POST,
                                              $i,
                                              ($name ? $name : $tpath),
                                              $size,
                                              $path
                                              )) {
            } else {
              $report[$i][3] = 'error_db';
              $s3_error      = true;
              $report[$i][4] = $_POST['path'][$i];
            }
          }
          
          // If no errors, everything is ok..yippee..
          if (!isset($s1_error) && !isset($s2_error) && !isset($s3_error)) {
            $report[$i][3] = 'ok';
            $report[$i][4] = ($name ? $name : $tpath);
          }
          
          // Assign directory name...
          $report[$i][5] = 'galleries/'.$SETTINGS->folder_name.'/'.getFolderName($_POST['cat'][$i]);
          
          // Reset count for next loop..
          $processed++;
          $count = 0;
          unset($s1_error,$s2_error,$s3_error);
        }
      }
    }
    
    // Show upload report if at least 1 file was added..
    if ($processed>0) {
      include(FOLDER_PATH.'inc/header.php');
      include(FOLDER_PATH.'data_files/image_management/add_image_report.php');
      include(FOLDER_PATH.'inc/footer.php');
    } else {
      header("Location: index.php?cmd=add_images");
    }
    exit;
  }

  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/image_management/add_images.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
  
  // E-Mail Addresses..
  case "emails":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu17;
  
  // Add..
  if (isset($_POST['process'])) {
    if (trim($_POST['email']) && preg_match("/^[_\.0-9a-zA-Z-]+@([0-9a-zA-Z][0-9a-zA-Z-]+\.)+[a-zA-Z]{2,6}$/i", $_POST['email'])) {
      $MGA_EMAILS->add($_POST);
    }
    header("Location: index.php?cmd=emails");
    exit;
  }
  
  // Remove selected..
  if (isset($_POST['process_del'])) {
    if (isset($_POST['email'])) {
      $MGA_EMAILS->delete($_POST);
    }
    header("Location: index.php?cmd=emails");
    exit;
  }
  
  // Clear all..
  if (isset($_GET['clear'])) {
    $MGA_EMAILS->clear();
    header("Location: index.php?cmd=emails");
    exit;
  }
  
  // Import to CSV
  if (isset($_GET['csv'])) {
    $MGA_EMAILS->csv($msg_settings4,RELATIVE_PATH);
    exit;
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/email_addresses.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
  
  // Ban Options..
  case "ban":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu16;
  $SQL       = '';
  
  // Add..
  if (isset($_POST['process'])) {
    if (trim($_POST['data'])) {
      $MGA_BAN->add($_POST);
    }
    header("Location: index.php?cmd=ban");
    exit;
  }
  
  // Remove selected..
  if (isset($_POST['process_del'])) {
    if (isset($_POST['ban'])) {
      $MGA_BAN->delete($_POST);
    }
    header("Location: index.php?cmd=ban");
    exit;
  }
  
  // Clear all..
  if (isset($_GET['clear'])) {
    $MGA_BAN->clear();
    header("Location: index.php?cmd=ban");
    exit;
  }
  
  // Sql filtering..
  if (isset($_GET['show'])) {
    switch ($_GET['show']) {
      case 'email':    $SQL = "WHERE address LIKE '%@%'";    break;
      case 'ip':       $SQL = "WHERE address NOT LIKE '%@%' AND address NOT LIKE '%*%'"; break;
      case 'wildcard': $SQL = "WHERE address LIKE '%*%'";    break;
    }
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/ban.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
     
  // Image Management..
  case "manage":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu7;
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/image_management/categories.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
  
  // Show cat images..
  case 'cat_images':
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu7;
  
  // View/update comments..
  if (isset($_GET['comments'])) {
    if (isset($_POST['edit_comment'])) {
      $MGA_IMAGES->update_comment($_POST);
    }
    include(FOLDER_PATH.'data_files/popup/comments.php');
    exit;
  }
  
  // Edit image..
  if (isset($_GET['edit']) || isset($_POST['edit']))
  {
    if (isset($_POST['process'])) {
      if (trim($_POST['name'])) {
        $MGA_IMAGES->update_image_sql($_POST);
        $UPDATED = true;
      }
    }
    
    include(FOLDER_PATH.'data_files/image_management/edit_image.php');
    exit;
  }
  
  // View image..
  if (isset($_GET['img']) || isset($_GET['new_img']))
  {
    include(FOLDER_PATH.'data_files/image_management/view_image.php');
    exit;
  }
  
  // Remove selected images..
  if (isset($_POST['process_del']))
  {
    if (!empty($_POST['img'])) {
      $MGA_IMAGES->delete_images($_POST,
                                 DOC_ROOT_FOR_UPLOAD.'galleries/'.$SETTINGS->folder_name.'/'.$_POST['folder']
                                 );
    }
    
    header("Location: index.php?cmd=cat_images&cat=".$_POST['cat']);
    exit;
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/image_management/cat_images.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
  
  // Search..
  case "search":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu5;
     
  // Search database..   
  if (isset($_GET['search']))
  {
    $search_data  = array();
    $sql_string   = '';
    $keys         = '';
    
    if ($_GET['from_day'] && $_GET['from_month'] && $_GET['from_year']) {
      $from_date_string = $_GET['from_year'].'-'.$_GET['from_month'].'-'.$_GET['from_day'];
    }
    if ($_GET['to_day'] && $_GET['to_month'] && $_GET['to_year']) {
      $to_date_string = $_GET['to_year'].'-'.$_GET['to_month'].'-'.$_GET['to_day'];
    }
   
    // Build search data array..
    if (trim($_GET['keywords'])) {
      $split = explode(" ", $_GET['keywords']);
      for ($i=0; $i<count($split); $i++) {
        $keys .= ($i ? "OR name LIKE '%".mysql_real_escape_string($split[$i])."%' OR comments LIKE '%".mysql_real_escape_string($split[$i])."%' OR details LIKE '%".mysql_real_escape_string($split[$i])."%' " : 
                  "name LIKE '%".mysql_real_escape_string($split[$i])."%' OR comments LIKE '%".mysql_real_escape_string($split[$i])."%' OR details LIKE '%".mysql_real_escape_string($split[$i])."%' "
                  );
      }
      $search_data[] = $keys;
    }
    if ($_GET['cat']>0) {
      $search_data[] = "cat = '{$_GET['cat']}'";
    }
    if (isset($from_date_string) && isset($to_date_string)) {
      $search_data[] = "addDate BETWEEN '{$from_date_string}' AND '{$to_date_string}'";
    }
   
    // Has search data been specified..
    if (!empty($search_data)) {
      // Build query string..
      for ($i=0; $i<count($search_data); $i++) {
        $sql_string .= ($i ? 'AND '.$search_data[$i] : 'WHERE '.$search_data[$i]);
      }
         
      //Now query database
      $q_search = mysql_query("SELECT * FROM ".$database['prefix']."images
                               $sql_string
                               ORDER BY name
                               LIMIT $limitvalue,$limit
                               ") or die(mysql_error());

      if (mysql_num_rows($q_search)>0) {
        $SEARCH_RESULTS = true;
      } else {
        $NO_RESULTS     = true;
      }
    }
    else
    {
      header("Location: index.php?cmd=search");
      exit;
    }
  }

  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/search.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;
     
  // Search..
  case "searchsales":
  
  // Check login..
  isWebmasterLoggedIn();
  
  $pageTitle = $msg_adminmenu18;
     
  // Search database..   
  if (isset($_GET['search']))
  {
    $search_data  = array();
    $sql_string   = '';
    $keys         = '';
    
    if ($_GET['from_day'] && $_GET['from_month'] && $_GET['from_year']) {
      $from_date_string = $_GET['from_year'].'-'.$_GET['from_month'].'-'.$_GET['from_day'];
    }
    if ($_GET['to_day'] && $_GET['to_month'] && $_GET['to_year']) {
      $to_date_string = $_GET['to_year'].'-'.$_GET['to_month'].'-'.$_GET['to_day'];
    }
   
    // Build search data array..
    if (trim($_GET['keywords'])) {
      $split = explode(" ", $_GET['keywords']);
      for ($i=0; $i<count($split); $i++) {
        $keys .= ($i ? "OR first_name LIKE '%".mysql_real_escape_string($split[$i])."%' OR last_name LIKE '%".mysql_real_escape_string($split[$i])."%' OR address LIKE '%".mysql_real_escape_string($split[$i])."%' OR email LIKE '%".mysql_real_escape_string($split[$i])."%' OR txn_id = '".mysql_real_escape_string($split[$i])."' OR invoice = '".mysql_real_escape_string($split[$i])."' " : 
                  "first_name LIKE '%".mysql_real_escape_string($split[$i])."%' OR last_name LIKE '%".mysql_real_escape_string($split[$i])."%' OR address LIKE '%".mysql_real_escape_string($split[$i])."%' OR email LIKE '%".mysql_real_escape_string($split[$i])."%' OR txn_id = '".mysql_real_escape_string($split[$i])."' OR invoice = '".mysql_real_escape_string($split[$i])."' "
                  );
                  
      }
      $search_data[] = $keys;
    }
    if (isset($from_date_string) && isset($to_date_string)) {
      $search_data[] = "pay_date BETWEEN '{$from_date_string}' AND '{$to_date_string}'";
    }
   
    // Has search data been specified..
    if (!empty($search_data)) {
      // Build query string..
      for ($i=0; $i<count($search_data); $i++) {
        $sql_string .= ($i ? 'AND ('.$search_data[$i].')' : 'WHERE '.$search_data[$i]);
      }
      
      //Now query database
      $q_search = mysql_query("SELECT *,DATE_FORMAT(pay_date,'".$SETTINGS->mysql_date."') AS s_date 
                               FROM ".$database['prefix']."ipndata
                               $sql_string
                               AND activeCart = '1'
                               ORDER BY id
                               LIMIT $limitvalue,$limit
                               ") or die(mysql_error());

      if (mysql_num_rows($q_search)>0) {
        $SEARCH_RESULTS = true;
      } else {
        $NO_RESULTS     = true;
      }
    }
    else
    {
      header("Location: index.php?cmd=searchsales");
      exit;
    }
  }

  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/searchsales.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;   
  
  // Login..
  case "login":
  
  // If already logged in, direct to homepage..
  if (isset($_SESSION['mgallery_admin_session']) || isset($_COOKIE['mgallery_admin_cookie'])) {
    header("Location: index.php");
    exit;
  }
  
  $pageTitle = $msg_adminlogin5;

  // Process login..
  if (isset($_POST['process']))
  {
    // Use callback function to prepare data for importing..
    $_POST = array_map('trim',$_POST);
    
    include(FOLDER_PATH.'inc/password.inc.php');

    if (encrypt($admin_username)!=encrypt($_POST['user'])) {
      $u_error = true;
    }
    if (encrypt($admin_password)!=encrypt($_POST['pass'])) {
      $p_error = true;
    }
    if (!isset($u_error) && !isset($p_error))
    {
      $_SESSION['mgallery_admin_session'] = encrypt($_POST['user']);

      if (isset($_POST['cookie'])) {
        setcookie($database['cookieName'], encrypt($database['cookieKey']), time()+60*60*24*30);
      }
      
      header("Location: index.php");
      exit;
    }
  }
  
  include(FOLDER_PATH.'inc/header.php');
  include(FOLDER_PATH.'data_files/login.php');
  include(FOLDER_PATH.'inc/footer.php');
  break;

  // Logout..
  case "logout":

  session_unset();
  session_destroy();

  if (isset($_COOKIE[$database['cookieName']])) {
    setcookie($database['cookieName'], "");
    unset($_COOKIE);
  }
  
  unset($_SESSION);

  header("Location: index.php?cmd=login");

  break;
     
  case 'watermark':
  
  // Check login..
  isWebmasterLoggedIn();
   
  $MGA_WMARK->waterMarkText  = ($SETTINGS->watertext ? cleanData($SETTINGS->watertext) : $msg_script32);
  $MGA_WMARK->imagePath      = 'images/watermark/wmtestpic.jpg';
  $MGA_WMARK->font           = RELATIVE_PATH.'classes/fonts/'.$SETTINGS->waterfont.'.ttf';
  $MGA_WMARK->size           = $SETTINGS->watersize;
  $MGA_WMARK->red            = $SETTINGS->watertextr;
  $MGA_WMARK->green          = $SETTINGS->watertextg;
  $MGA_WMARK->blue           = $SETTINGS->watertextb;
  $MGA_WMARK->hSpacing       = $SETTINGS->waterhspace;
  $MGA_WMARK->vSpacing       = $SETTINGS->watervspace;
  $MGA_WMARK->angle          = $SETTINGS->waterangle;

  header("Content-type: image/jpeg");
  $MGA_WMARK->mark();
  echo $MGA_WMARK->imageResource;
  exit; 
  
  break; 
}

?>
