Location: PHPKode > projects > Maian Gallery > maian_gallery/inc/functions.php
<?php

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

  Script: Maian Gallery v2.0
  Written by: David Ian Bennett
  E-Mail: hide@address.com
  Website: http://www.maianscriptworld.co.uk
  
  ++++++++++++++++++++++++++++++++++++++++
  
  This File: functions.php
  Description: Program Functions

  ++++++++++++++++++++++++++++++++++++++++*/
  
// This builds navigation menu for categories as a select list..
// Used for some template themes..
// Can be called in the footer/header template..
function buildCategoriesSelectList($id=0)
{
  global $database,$SETTINGS;
  $string = '<option value="0" style="padding-left:3px">---</option>';

  $q_cats = mysql_query("SELECT * FROM ".$database['prefix']."categories
                         WHERE parent = '1' 
                         AND en_cat   = '1'
                         ORDER BY catname
                         ") or die(mysql_error());
 
  if (mysql_num_rows($q_cats)>0) {
    while ($CATS = mysql_fetch_object($q_cats)) {
      $string .= '<option'.($id>0 && $CATS->id==$id ? ' selected="selected" ' : ' ').'value="'.($SETTINGS->modr ? $SETTINGS->folder.'/category/'.$CATS->id.'/'.addTitleToUrl(getCategoryName($CATS->id)).'/index.html' : $SETTINGS->folder.'/index.php?cmd=category&amp;category='.$CATS->id).'" title="'.cleanData($CATS->catname).'" style="padding-left:3px">'.cleanData($CATS->catname).'</option>'."\n";
      // Children..
      $q_children = mysql_query("SELECT * FROM ".$database['prefix']."categories
                                 WHERE child  = '{$CATS->id}'
                                 AND en_cat   = '1'
                                 ORDER BY catname
                                 ") or die(mysql_error());
      if (mysql_num_rows($q_children)>0) {
        while ($CHILDREN = mysql_fetch_object($q_children)) {
          $string .= '<option'.($id>0 && $CHILDREN->id==$id ? ' selected="selected" ' : ' ').'value="'.($SETTINGS->modr ? $SETTINGS->folder.'/category/'.$CHILDREN->id.'/'.addTitleToUrl(getCategoryName($CHILDREN->id)).'/index.html' : $SETTINGS->folder.'/index.php?cmd=category&amp;category='.$CHILDREN->id).'" title="'.cleanData($CHILDREN->catname).'" style="padding-left:3px">- '.cleanData($CHILDREN->catname).'</option>'."\n";
        }
      }
    }
  }
  return $string;
}

// This builds navigation menu for categories as ordered list..
// Used for some template themes as some css menus require this format..
// Can be called in the header/footer template..
function buildCategoriesOrderedList()
{
  global $database,$SETTINGS;
  $string = '';

  $q_cats = mysql_query("SELECT * FROM ".$database['prefix']."categories
                         WHERE parent = '1' 
                         AND en_cat   = '1'
                         ORDER BY catname
                         ") or die(mysql_error());

  if (mysql_num_rows($q_cats)>0) {
    while ($CATS = mysql_fetch_object($q_cats)) {
      $children = '';
      // Children..
      $q_children = mysql_query("SELECT * FROM ".$database['prefix']."categories
                                 WHERE child  = '{$CATS->id}'
                                 AND en_cat   = '1'
                                 ORDER BY catname
                                 ") or die(mysql_error());
      if (mysql_num_rows($q_children)>0) {
        $children = '<ul class="child">'."\n";
        // If you have no images in the top level category and don`t want the link to show
        // comment out or remove the line below..
        $children .= '<li class="children"><a href="'.($SETTINGS->modr ? $SETTINGS->folder.'/category/'.$CATS->id.'/'.addTitleToUrl(getCategoryName($CATS->id)).'/index.html' : $SETTINGS->folder.'/index.php?cmd=category&amp;category='.$CATS->id).'" title="'.cleanData($CATS->catname).'">'.cleanData($CATS->catname).' ('.getCategoryImageCount($CATS->id).')</a></li>'."\n";
        while ($CHILDREN = mysql_fetch_object($q_children)) {
          $children .= '<li class="children"><a href="'.($SETTINGS->modr ? $SETTINGS->folder.'/category/'.$CHILDREN->id.'/'.addTitleToUrl(getCategoryName($CHILDREN->id)).'/index.html' : $SETTINGS->folder.'/index.php?cmd=category&amp;category='.$CHILDREN->id).'" title="'.cleanData($CHILDREN->catname).'">'.cleanData($CHILDREN->catname).' ('.getCategoryImageCount($CHILDREN->id).')</a></li>'."\n";
        }
        $children .= '</ul>'."\n";
      }
      $string .= ($children ?
                  '<li><a href="#" title="'.cleanData($CATS->catname).'">'.cleanData($CATS->catname).'</a>'.$children.'</li>' :
                  '<li><a href="'.($SETTINGS->modr ? $SETTINGS->folder.'/category/'.$CATS->id.'/'.addTitleToUrl(getCategoryName($CATS->id)).'/index.html' : $SETTINGS->folder.'/index.php?cmd=category&amp;category='.$CATS->id).'" title="'.cleanData($CATS->catname).'">'.cleanData($CATS->catname).' ('.getCategoryImageCount($CATS->id).')</a></li>')."\n";
    }
  }
  return $string;
}
  
// Clears dead comments and cart data not used..
// These are comments left where e-mail verification wasn`t completed in 14 days..
// or cart data where someone didn`t complete the paypal payment..
function clearDeadData()
{
  global $database;
  $date = date("Y-m-d",strtotime("-14 days"));
  
  // Delete comments..
  mysql_query("DELETE FROM ".$database['prefix']."comments
               WHERE addDate    <= '{$date}'
               AND is_active    = '0'
               AND is_approved  = '0'
               ") or die(mysql_error());
               
  // Delete purchase data..
  $query = mysql_query("SELECT * FROM ".$database['prefix']."ipndata
                        WHERE pay_date   <= '{$date}'
                        AND activeCart   = '0'
                        ") or die(mysql_error());  
  while ($row = mysql_fetch_object($query)) {
    mysql_query("DELETE FROM ".$database['prefix']."purchases 
                 WHERE cartID = '{$row->cartID}'
                 ") or die(mysql_error());
  } 
  
  // Delete ipn data..
  mysql_query("DELETE FROM ".$database['prefix']."ipndata
               WHERE pay_date   <= '{$date}'
               AND activeCart   = '0'
               ") or die(mysql_error());                                  
}  
  
// Load comments for image...
function loadImageComments($id,$limitvalue,$limit)
{
  global $database,$theme,$SETTINGS,$msg_pictures14;
  $string = '';
  
  $q_comments = mysql_query("SELECT *,DATE_FORMAT(addDate,'".$SETTINGS->mysql_date."') AS c_date 
                             FROM ".$database['prefix']."comments 
                             WHERE imageID    = '{$id}'
                             AND is_active    = '1'
                             AND is_approved  = '0'
                             ORDER BY ".($SETTINGS->commentsorder ? 'id DESC' : 'id')."
                             LIMIT $limitvalue,$limit
                             ") or die(mysql_error());
  
  while ($COMMENTS = mysql_fetch_object($q_comments)) {
    $string .= str_replace(array('{comment}','{posted_by}','{date}'),
                           array(
                           cleanData(nl2br($COMMENTS->comments),COMMENTS_TEXT_WRAP),
                           $msg_pictures14.cleanData($COMMENTS->name),
                           $COMMENTS->c_date
                           ),
                           file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/comment.tpl')
                           );
  }
  
  return $string;
}  

// Get buy options for picture..
function getBuyOptions($id,$paragraph=false)
{
  global $PP;
  
  $string   = '';
  $image    = getImageData($id);
  $options  = explode(define_newline(),cleanData($image->details));
  
  for ($i=0; $i<count($options); $i++) {
    $split = explode("|",$options[$i]);
    // $split[0] = Cost
    // $split[1] = Sizes
    // $split[2] = Item Number
    if (isset($split[0]) && isset($split[1])) {
      $string .= ($paragraph ? '<p class="item">' : '<li>').'
                  <input type="hidden" name="id[]" value="'.$id.'-'.$i.'" />
                  <input type="hidden" name="size[]" value="'.cleanData($split[1]).'" />
                  <input type="hidden" name="cost[]" value="'.$split[0].'" />
                  <input type="hidden" name="item[]" value="'.(isset($split[2]) ? $split[2] : 'none').'" />
                  <input type="text" class="qty" name="qty[]" value="0" /> '.cleanData($split[1]).' - '.get_cur_symbol($split[0],$PP->ppCurrency).'
                  '.($paragraph ? '</p>' : '</li>');
    }
  }
  
  return $string;
}  
  
// Update image visit count..
function updateImageVisitCount($id)
{
  global $database;
  
  mysql_query("UPDATE ".$database['prefix']."images SET
               visits    = (visits+1)
               WHERE id  = '{$id}'
               LIMIT 1
               ") or die(mysql_error());
}

// Image width/height calculator...
// Determines display size on page..
// Pop up full size specified in settings..
function imgDisplaySize($path,$which='width')
{
  global $SETTINGS;
  
  // Max display width..
  $width  = (isset($_COOKIE['mgallery_display_width']) ? $_COOKIE['mgallery_display_width'] : $SETTINGS->pagedisplaysize);
  $size   = getimagesize($path); // $size[0] - width, $size[1] = height
  
  // Calculate height based on how much width was reduced..
  switch ($which) {
    case 'width':
    return ($size[0]>$width ? $width : $size[0]);
    break;
    
    /*case 'height':
    $minus = $size[0]-$width;
    return ($size[0]<=$width ? $size[1] : $size[1]-$minus);
    break;
    */
    
    case 'height':
    $scale = $size[0]>$width ? $width/$size[0] : 1;
    return floor($size[1]*$scale);
    break;
  }
}  
  
// Full size display size..
function fullSizeDisplaySize()
{
  global $SETTINGS;
  $string  = '';
  
  if ($SETTINGS->imgwidth>0) {
    $string = 'width="'.$SETTINGS->imgwidth.' "';
  }
  if ($SETTINGS->imgheight>0) {
    $string .= 'height="'.$SETTINGS->imgheight.'"';
  }
  
  return $string;
}

// Get image count for category..
function getCategoryImageCount($id)
{
  global $database;
  
  $q_img = mysql_query("SELECT count(*) AS i_count FROM ".$database['prefix']."images 
                        WHERE cat = '{$id}'
                        ") or die(mysql_error());
  $IMG = mysql_fetch_object($q_img);
  
  return $IMG->i_count;
}  
  
// Load single image data into array..
function getImageData($id)
{
  global $database,$SETTINGS;
  
  $q_img = mysql_query("SELECT *,DATE_FORMAT(addDate,'".$SETTINGS->mysql_date."') AS i_date 
                        FROM ".$database['prefix']."images 
                        WHERE id = '{$id}'
                        LIMIT 1") or die(mysql_error());
  
  return mysql_fetch_object($q_img);
}

// Load single image data into array..
function get_comment_data($id,$code='',$check=false)
{
  global $database;
  
  $q_comment = mysql_query("SELECT * FROM ".$database['prefix']."comments 
                            ".($code ? 'WHERE verification_key = \''.$code.'\'' : 'WHERE id = \''.$id.'\'')."
                            LIMIT 1
                            ") or die(mysql_error());
  
  return ($check ? (mysql_num_rows($q_comment)>0 ? true : false) : mysql_fetch_object($q_comment));
}

// Gets category data
function getCategoryData($id)
{
  global $database;
  
  $query = mysql_query("SELECT * FROM ".$database['prefix']."categories 
                        WHERE id = '{$id}'
                        LIMIT 1") or die(mysql_error());
  
  return mysql_fetch_object($query);
}

// Gets category name
function getCategoryName($cat)
{
  global $database;
  
  $query = mysql_query("SELECT * FROM ".$database['prefix']."categories 
                        WHERE id = '{$cat}'
                        LIMIT 1") or die(mysql_error());
  $row = mysql_fetch_object($query);
  
  return cleanData($row->catname);
}

// Gets folder name for image
function getFolderName($cat)
{
  global $database;
  
  $query = mysql_query("SELECT * FROM ".$database['prefix']."categories 
                        WHERE id = '{$cat}'
                        LIMIT 1") or die(mysql_error());
  $row = mysql_fetch_object($query);
  
  return cleanData($row->folder);
}

// Parses data into url friendly string
function addTitleToUrl($title)
{
  // Convert special characters from European countries into the English alphabetic equivalent..
  $chars = array(
   'Ñ'=>'Dj', '·'=>'A', 'µ'=>'A', '¶'=>'A', 'Ç'=>'A', 'Ž'=>'A', ''=>'A', '’'=>'A', '€'=>'C', 'Ô'=>'E', 
   ''=>'E', 'Ò'=>'E', 'Ó'=>'E', 'Þ'=>'I', 'Ö'=>'I', '×'=>'I', 'Ø'=>'I', '¥'=>'N', 'ã'=>'O', 'à'=>'O', 
   'â'=>'O', 'å'=>'O', '™'=>'O', ''=>'O', 'ë'=>'U', 'é'=>'U', 'ê'=>'U', 'š'=>'U', 'í'=>'Y', 'è'=>'B', 
   'á'=>'Ss', '…'=>'a', ' '=>'a', 'ƒ'=>'a', 'Æ'=>'a', '„'=>'a', '†'=>'a', '‘'=>'a', '‡'=>'c', 'Š'=>'e', 
   '‚'=>'e', 'ˆ'=>'e', '‰'=>'e', ''=>'i', '¡'=>'i', 'Œ'=>'i', '‹'=>'i', 'Ð'=>'o', '¤'=>'n', '•'=>'o', 
   '¢'=>'o', '“'=>'o', 'ä'=>'o', '”'=>'o', '›'=>'o', '—'=>'u', '£'=>'u', '–'=>'u', 'ì'=>'y', 'ì'=>'y', 
   'ç'=>'b', '˜'=>'y'
  );
			
  // Replace chars in array..
  $title = strtr($title, $chars);

  // Strip none alphabetic and none numeric chars..
  $title = strtolower(preg_replace('`[^\w_-]`', '-', $title));
  
  // Replace other data that may be passed, such as double hyphens..
  return str_replace(array('--','---','----','-amp-','-039-'),
                     array('-','-','-','-and-',''),
                     $title
                     );
}

// Loads captcha data into string
function showCaptcha($error='',$file='1',$div=true)
{
  global $SETTINGS,$msg_contact10,$theme,$msg_contact8,$msg_contact9;
  
  $find     = array('{captcha}','{text}','{code_error}');
  $replace  = array(dsp_crypt(0,1,$msg_contact8,$msg_contact9,$div),$msg_contact10,$error);
  $captcha  = file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/captcha'.$file.'.tpl');
  
  return ($SETTINGS->captcha ? str_replace($find,$replace,$captcha) : '');
} 

// Displays sub category links and cat link if viewing sub category...
function displaySubCategoryLinks($cat,$child=false,$id,$comma=false)
{
  global $database,$theme,$SETTINGS,$msg_category4;
  $string    = '';
  $file      = file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/sub_categories.tpl');
  $standard  = (!$comma ? '<li>' : '').$msg_category4.(!$comma ? '</li>' : '');
  $count     = 0;
  
  $q_sub = mysql_query("SELECT * FROM ".$database['prefix']."categories
                        ".($child ? '
                        WHERE (child = \''.$cat.'\' OR id = \''.$cat.'\')
                        ' : '
                        WHERE child = \''.$cat.'\'
                        ')."
                        AND en_cat = '1'
                        ORDER BY catname") or die(mysql_error());
  
  while ($SUB = mysql_fetch_object($q_sub)) {
    // Show cats/sub cats, but not category being viewed..
    if ($comma=='list') {
      if ($SUB->id!=$id) {
        $string .= '<a href="'.($SETTINGS->modr ? 'category/'.$SUB->id.'/'.addTitleToUrl(getCategoryName($SUB->id)).'/index.html' : 'index.php?cmd=category&amp;category='.$SUB->id).'" title="'.cleanData($SUB->catname).'">'.cleanData($SUB->catname).'</a>'.(++$count!=mysql_num_rows($q_sub) ? '<br />' : '')."\n";
      }
    } else {
      if ($SUB->id!=$id) {
        $string .= (!$comma ? '<li>' : '').'<a href="'.($SETTINGS->modr ? 'category/'.$SUB->id.'/'.addTitleToUrl(getCategoryName($SUB->id)).'/index.html' : 'index.php?cmd=category&amp;category='.$SUB->id).'" title="'.cleanData($SUB->catname).'">'.cleanData($SUB->catname).'</a>'.(!$comma ? '</li>' : (++$count!=mysql_num_rows($q_sub) ? ', ' : ''))."\n";
      }
    }
  }
  
  return str_replace("{sub_categories}",($string ? $string : $standard),$file);
}

// Returns only a portion of the picture name...
// Can help maintain template structure..
function cropPictureName($name,$chars=0)
{
  // If length of name string isn`t greater than limit, make no change..
  if ($chars>0) {
    return (strlen($name)<=$chars ? $name : substr($name,0,$chars).'..');
  } else {
    return $name;
  }
}

// Load most viewed/random pictures etc
function loadStatPictures($orderby,$limit,$cat='')
{
  global $database,$SETTINGS;
  $string = '';
  
  $q_images = mysql_query("SELECT * FROM ".$database['prefix']."images 
                           ".($cat ? 'WHERE cat = \''.$cat.'\' AND enabled = \'1\'' : 'WHERE enabled = \'1\'')."
                           ORDER BY $orderby 
                           LIMIT $limit
                           ") or die(mysql_error());
  
  while ($IMAGES = mysql_fetch_object($q_images)) {
    $i_url = ($SETTINGS->modr ? 'picture/'.$IMAGES->id.'/'.addTitleToUrl(getCategoryName($IMAGES->cat)).'/'.addTitleToUrl($IMAGES->name).'.html' : 'index.php?cmd=pictures&amp;picture='.$IMAGES->id);
       
    $string .= '<li><a href="'.$i_url.'"><img src="galleries/'.$SETTINGS->folder_name.'/'.getFolderName($IMAGES->cat).'/'.$IMAGES->thumbpath.'" '.($SETTINGS->thumbwidth>0 ? 'width="'.$SETTINGS->thumbwidth.'"' : '').' '.($SETTINGS->thumbheight>0 ? 'height="'.$SETTINGS->thumbheight.'"' : '').' alt="'.cleanData($IMAGES->name).'" title="'.cleanData($IMAGES->name).'" class="thumbnail" /></a><span class="catname">'.cleanData(cropPictureName($IMAGES->name,CROP_FILE_NAME),IMAGE_NAME_TEXT_WRAP).'</span></li>'."\n";
  }
  
  return $string;
}

// Load categories/sub categories..
function loadGalleryCategories($sub='',$id='')
{
  global $database;
  $string = '';
  
  $q_cats = mysql_query("SELECT * FROM ".$database['prefix']."categories 
                         ".($sub ? 'WHERE (child > \'0\') AND parent = \'0\'' : 'WHERE parent = \'1\'')."
                         ".($id ? 'AND id = '.$id : '')."
                         AND en_cat = '1'
                         ORDER BY catname 
                         ") or die(mysql_error());
  
  while ($CATS = mysql_fetch_object($q_cats)) {
    if (getCategoryImageCount($CATS->id)==0) {
      $string .= loadGalleryPictures($CATS->id,1,'rand()',0,true,'cat',false);
    } else {
      $string .= '<li>'.loadGalleryPictures($CATS->id,1,'rand()',0,true,'cat',false).'</li>'."\n";
    }
  }
  
  return $string;
}

// Loads images...
function loadGalleryPictures($cat,$limit='',$order='',$limitvalue='',$catname=false,$url,$li_tags=false)
{
  global $database,$msg_publichome3,$SETTINGS,$msg_publichome3,$theme;
  $string    = '';
  $standard  = '<li><img src="themes/'.$theme.'/images/no_image.gif" '.($SETTINGS->thumbwidth>0 ? 'width="'.$SETTINGS->thumbwidth.'"' : '').' '.($SETTINGS->thumbheight>0 ? 'height="'.$SETTINGS->thumbheight.'"' : '').' alt="'.$msg_publichome3.'" title="'.$msg_publichome3.'" class="thumbnail" /><span class="catname">'.$msg_publichome3.'</span></li>';
  $i_url     = '';
  
  $q_images = mysql_query("SELECT * FROM ".$database['prefix']."images
                           WHERE cat    = '{$cat}'
                           AND enabled  = '1'
                           ".($order ? 'ORDER BY '.$order : '')."
                           LIMIT $limitvalue,$limit
                           ") or die(mysql_error());
  
  while ($IMG = mysql_fetch_object($q_images)) {
    // Determine url..
    switch ($url) {
      case 'cat':
      case 'sub':
      $i_url = ($SETTINGS->modr ? 'category/'.$IMG->cat.'/'.addTitleToUrl(getCategoryName($IMG->cat)).'/index.html' : 'index.php?cmd=category&amp;category='.$IMG->cat);
      break;
      case 'img':
      $i_url = ($SETTINGS->modr ? 'picture/'.$IMG->id.'/'.addTitleToUrl(getCategoryName($IMG->cat)).'/'.addTitleToUrl($IMG->name).'.html' : 'index.php?cmd=pictures&amp;picture='.$IMG->id);
      break;
    }
    
    $string .= ($li_tags ? '<li>' : '');
    $string .= '<a href="'.$i_url.'"><img src="galleries/'.$SETTINGS->folder_name.'/'.getFolderName($IMG->cat).'/'.$IMG->thumbpath.'" '.($SETTINGS->thumbwidth>0 ? 'width="'.$SETTINGS->thumbwidth.'"' : '').' '.($SETTINGS->thumbheight>0 ? 'height="'.$SETTINGS->thumbheight.'"' : '').' alt="'.cleanData(($catname ? getCategoryName($IMG->cat) : $IMG->name)).'" title="'.cleanData(($catname ? getCategoryName($IMG->cat) : $IMG->name)).'" class="thumbnail" /></a><span class="catname">'.cleanData(($catname ? getCategoryName($IMG->cat) : cropPictureName($IMG->name,CROP_FILE_NAME)),IMAGE_NAME_TEXT_WRAP).'</span>';
    $string .= ($li_tags ? '</li>' : '');
  }
  
  return ($string ? $string : $standard);
}

// Fetch paypal data..
function paypal()
{
  global $database;
  
  $query = mysql_query("SELECT * FROM ".$database['prefix']."paypal LIMIT 1") or die(mysql_error());
  
  return mysql_fetch_object($query);
}

// Return cost of payment with cur symbol
function get_cur_symbol($price,$cur)
{
  $symbol = '';
  
  switch($cur)
  {
    case 'USD': return 'US&#036;'.$price; break;
    case 'AUD': return 'AU&#036;'.$price; break;
    case 'CAD': return 'CA&#036;'.$price; break;
    case 'GBP': return '&#163;'.$price;   break;
    case 'JPY': return '&#165;'.$price;   break;
    case 'EUR': return '&#8364;'.$price;  break;
    case 'CHF': return '&#067;'.$price;   break;
    case 'CZK': return '&#075;'.$price;   break;
    case 'DKK': return '&#107;'.$price;   break;
    case 'HKD': return '&#22291;'.$price; break;
    case 'HUF': return '&#070;'.$price;   break;
    case 'SGD': return 'S&#036;'.$price;  break;
    case 'NOK': return '&#107;'.$price;   break;
    case 'NZD': return '&#036;'.$price;   break;
    case 'PLN': return '&#122;'.$price;   break;
    case 'SEK': return '&#107;'.$price;   break;
  }
}

// Removes potential harmful tags
function cleanEvilTags($data)
{
  $data = preg_replace("/javascript/i", "j&#097;v&#097;script",$data);
  $data = preg_replace("/alert/i", "&#097;lert",$data);
  $data = preg_replace("/about:/i", "&#097;bout:",$data);
  $data = preg_replace("/onmouseover/i", "&#111;nmouseover",$data);
  $data = preg_replace("/onclick/i", "&#111;nclick",$data);
  $data = preg_replace("/onload/i", "&#111;nload",$data);
  $data = preg_replace("/onsubmit/i", "&#111;nsubmit",$data);
  $data = preg_replace("/<body/i", "&lt;body",$data);
  $data = preg_replace("/<html/i", "&lt;html",$data);
  $data = preg_replace("/document\./i", "&#100;ocument.",$data);

  return trim(strip_tags($data));
}

// Tidies up output
function cleanData($data,$wrap=0)
{
  if ($wrap>0) {
    $data = stopTableStretching($data,$wrap);
  }
  
  return (get_magic_quotes_gpc() ? stripslashes($data) : $data);
}  

// Shows page numbers
function page_numbers($count,$limit,$page,$raw,$file='page_numbers',$stringVar='page')
{
  global $msg_script9,$msg_script10,$SETTINGS,$theme;
  $file = file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/'.$file.'.tpl');

  $PaginateIt = new PaginateIt();
  $PaginateIt->SetRawPageUrl($raw);
  $PaginateIt->SetCurrentPage($page);
  $PaginateIt->SetItemCount($count);
  $PaginateIt->SetItemsPerPage($limit);
  $PaginateIt->SetLinksToDisplay(40);
  $PaginateIt->SetQueryStringVar($stringVar);
  $PaginateIt->SetLinksFormat('&laquo; '.$msg_script9,
                              ' &bull; ',
                              $msg_script10.' &raquo;'
                              );
  $PaginateIt->SetModRewrite($SETTINGS->modr);                            
                              
  return str_replace('{pages}',$PaginateIt->GetPageLinks(),$file);                            
}

// Converts bytes to MB/KB..
// Alter if necessary..
function file_size_conversion($size=0,$base)
{
  global $msg_script34;
  
  if ($size>0)
  {
    if ($size>$base) {
      return number_format($size/$base,1).'MB';
    } else if ($size<1024) {
      return $size.' '.$msg_script34;
    } else {
      return number_format($size/1024,0).'KB';
    }
  } else {
    return '0';
  }
}
  
// Return overlib tooltip
function toolTip($msg,$msg2)
{
  return '[<a href="javascript:void(0);" onclick="return overlib(\''.htmlspecialchars($msg2).'\', STICKY, CAPTION, \''.$msg.'\', CENTER);" onmouseout="nd();"><b>?</b></a>]';
}

// Prevent table stretching for certain types of data..
// ie: visitor comments, image names
function stopTableStretching($data,$chars)
{
  return wordwrap($data, $chars, "\n", 1);
}

// Define new line character..
function define_newline()
{
  $unewline = "\r\n";

  if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'win')) {
    $unewline = "\r\n";
  } else if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'mac')) {
    $unewline = "\r";
  } else {
    $unewline = "\n";
  }

  return $unewline;
}

// Check digit var..
function checkDigit($id)
{
  if (!ctype_digit($id)) {
    header("HTTP/1.0 404 Not Found");
    exit;
  }
}

// Displays gallery error..
function showPageMessage($msg)
{
  global $msg_error,$msg_error2,$theme;
  
  $tpl_error =& new Savant2();
  $tpl_error->assign('MESSAGE',$msg_error);
  $tpl_error->assign('HEAD_MESSAGE',$msg_error2);
  $tpl_error->assign('ERROR', $msg);
  $tpl_error->display('themes/'.$theme.'/message.tpl.php');
}

// Theme switcher..displays themes if enabled..
function themeSwitcher($cur_theme)
{
  global $SETTINGS,$msg_script27,$theme;
  
  // Is switcher enabled?
  if (!$SETTINGS->themeswitcher) {
    return false;
  }
  
  $string  = '';
  $thme    = array();
  
  // Load themes...
  $showthemes = opendir(FOLDER_PATH.'themes/');

  // Read themes into array..
  while ($read = readdir($showthemes)) {
  	if ($read!='.' && $read!='..' && $read!='index.html' && $read!='email') {
      $thme[] = $read;
    }
  }
  
  // Sort theme array by value and load as string..
  if (!empty($thme)) {
    sort($thme);
    foreach ($thme AS $showTheme) {
  	  $string .= '<option'.(($showTheme == $cur_theme) ? ' selected="selected"' : '').' style="padding-left:3px" value="index.php?load_theme='.$showTheme.'">'.ucfirst($showTheme).'</option>'."\n";
    }
  }

  closedir($showthemes);
  
  // Change tag data for template..
  $find     = array('{change_theme}','{themes}');
  $replace  = array($msg_script27,$string);
  
  // Only return data if more than a single theme..
  return ($string && count($thme)>1 ? 
          str_replace($find,$replace,
          file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/theme_switcher.tpl')
          ) : '');
}

// Theme switcher..changes theme if enabled..
function updateGalleryTheme($new_theme)
{
  global $SETTINGS,$reloadCaptchaRGB,$themePicDisplayWidth;
  
  // Check this directory exists before reload..
  if (is_dir('themes/'.$new_theme)) {
    // Reset captcha colours...
    if (isset($reloadCaptchaRGB[$new_theme]) && $new_theme!=$SETTINGS->theme) {
      setcookie("mgallery_captcha_rgb", $reloadCaptchaRGB[$new_theme], time()+60*60*24*30);
    }
    // Change display width..
    if (isset($themePicDisplayWidth[$new_theme]) && $new_theme!=$SETTINGS->theme) {
      setcookie("mgallery_display_width", $themePicDisplayWidth[$new_theme], time()+60*60*24*30);
    }

    // If theme is default theme, clear cookies..
    if ($new_theme===$SETTINGS->theme) {
      if (isset($_COOKIE['mgallery_display_width'])) {
        setcookie("mgallery_display_width", "");
      }
      if (isset($_COOKIE['mgallery_captcha_rgb'])) {
        setcookie("mgallery_captcha_rgb", "");
      }
      setcookie("mgallery_theme_cookie","");
    } else {
      // Set cookie for theme..
      setcookie("mgallery_theme_cookie", $new_theme, time()+60*60*24*30);
    }
  }
  header("Location: ".($SETTINGS->modr ? 'index.html' : 'index.php').""); 
}

// Checks for banned IP address..
function isIPAddressBanned($ip) 
{
  global $database;
  
  // Explode ip address for wildcards..
  $wildcards = explode(".",$ip);
  $sql       = '';
  
  // Create syntax for wild cards..
  // Don`t bother with final slot as that will just return the complete ip..
  // So, reducing count by 1 skips final slot..
  for ($i=0; $i<count($wildcards)-1; $i++) {
    switch ($i) {
      case 0: $sql = "OR address = '*".$wildcards[0].".' ";                                      break;
      case 1: $sql .= "OR address = '*".$wildcards[0].".".$wildcards[1].".' ";                   break;
      case 2: $sql .= "OR address = '*".$wildcards[0].".".$wildcards[1].".".$wildcards[2].".' "; break;
    }
  }
  
  // Don`t bother with full e-mail addresses..
  $q_banned = mysql_query("SELECT * FROM ".$database['prefix']."banned
                           WHERE address = '{$ip}'
                           $sql
                           ORDER BY id
                           ") or die(mysql_error());
  
  // Is there a match?
  if (mysql_num_rows($q_banned)>0) {
    return true;
  }
}

// Syntax count/last picture date..
function dbSyntax($table,$select,$row,$option='')
{
  global $database;
  
  $q_syntax = mysql_query("SELECT $select FROM ".$database['prefix'].$table.$option."") or die(mysql_error());
  $SYNTAX   = mysql_fetch_object($q_syntax);
  
  return (isset($SYNTAX->$row) ? $SYNTAX->$row : 'N/A');
}

// Parses stats..
function stats()
{
  global $msg_publichome5,$SETTINGS;
  
  return str_replace(array('{pics}','{cats}','{views}','{date}'),
                     array(
                     number_format(dbSyntax('images','count(*) AS i_count','i_count',' WHERE enabled = \'1\'')),
                     number_format(dbSyntax('categories','count(*) AS c_count','c_count')),
                     number_format(dbSyntax('images','sum(visits) AS views','views',' WHERE enabled = \'1\'')),
                     dbSyntax('images','DATE_FORMAT(addDate,\''.$SETTINGS->mysql_date.'\') AS l_date','l_date',' WHERE enabled = \'1\' ORDER BY id DESC LIMIT 1'),
                     ),
                     $msg_publichome5);
}

// Calculates search query time..
function executionTime()
{
  $mtime  = explode(" ",microtime());
  $msec   = (double)$mtime[0];
  $sec    = (double)$mtime[1];
  
  return $sec + $msec;
}

// Query string for search..
// Standard and advanced searches return different parameters, so we can use the query string
//  var to list them. This function prevents duplicate page vars appearing..
// The advantage here being new vars can be added later and this function won`t need changing..
function searchQueryString()
{
  $cleaned = '';
  
  if (isset($_SERVER['QUERY_STRING'])) {
    $split = explode("&",$_SERVER['QUERY_STRING']);
    
    // Clean string..no ampersand for first query..
    // Remove page vars..
    // Use entities for ampersands for validation..
    for ($i=0; $i<count($split); $i++) {
      $cleaned .= (strpos($split[$i],'page')===FALSE ? ($i ? '&amp;'.$split[$i] : $split[$i]) : '');
    }
  }
  
  return trim($cleaned);
}

// Get all categories..
function showCategories()
{
  global $database;
  $cats = '';
  
  // Parents..
  $q_cats = mysql_query("SELECT * FROM ".$database['prefix']."categories 
                         WHERE parent = '1'
                         AND en_cat   = '1'
                         ORDER BY catname
                         ") or die(mysql_error());
  
  if (mysql_num_rows($q_cats)>0){
    while ($CATS = mysql_fetch_object($q_cats)) {
      $cats .= '<option value="'.$CATS->id.'"'.(isset($_SESSION['av_search_category']) && $_SESSION['av_search_category']==$CATS->id ? ' selected="selected"' : '').' style="padding-left:3px">'.cleanData($CATS->catname).'</option>'."\n";
      // Children..
      $q_child = mysql_query("SELECT * FROM ".$database['prefix']."categories 
                              WHERE child  = '{$CATS->id}'
                              AND en_cat   = '1'
                              ORDER BY catname
                              ") or die(mysql_error());
                             
      if (mysql_num_rows($q_child)>0){
        while ($CHILDREN = mysql_fetch_object($q_child)) {
          $cats .= '<option value="'.$CHILDREN->id.'"'.(isset($_SESSION['av_search_category']) && $_SESSION['av_search_category']==$CHILDREN->id ? ' selected="selected"' : '').' style="padding-left:3px">- '.cleanData($CHILDREN->catname).'</option>'."\n";
        }
      }
    }
  }
  
  return $cats;
}

// Row count of table..
function rowCount($table,$where='')
{
  global $database;
  
  $q_count = mysql_query("SELECT count(*) AS t_count FROM ".$database['prefix'].$table.$where."") or die(mysql_error());
  $COUNT   = mysql_fetch_object($q_count);
  
  return number_format($COUNT->t_count);
}

// Recursive way of handling multi dimensional arrays..
// This cleans query string data and prevents code injections..
function multiDimensionalArrayMap($func,$arr) {
  $newArr = array();
  if (!empty($arr)) {
    foreach($arr AS $key => $value) {
      $newArr[$key] = (is_array($value) ? multiDimensionalArrayMap($func,$value) : $func($value));
    }
  }
  return $newArr;
}
if (!empty($_GET)) {
  $_GET  = multiDimensionalArrayMap('htmlspecialchars',$_GET);
}

?>
Return current item: Maian Gallery