<?php

/*---------------------------------------------
  MAIAN EVENTS v2.0
  Written by David Ian Bennett
  E-Mail: support@maianscriptworld.co.uk
  Website: www.maianscriptworld.co.uk
  This File: Program Functions
----------------------------------------------*/

// Load comments for events...
function loadEventComments($id,$limitvalue,$limit)
{
  global $database,$theme,$SETTINGS,$p_event17;
  $string = '';
  
  $q_comments = mysql_query("SELECT *,DATE_FORMAT(addDate,'".$SETTINGS->formatdate."') AS c_date 
                             FROM ".$database['prefix']."comments 
                             WHERE eventid    = '{$id}'
                             AND is_active    = '1'
                             ORDER BY ".ORDER_COMMENTS_BY."
                             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),
                           $p_event17.cleanData($COMMENTS->name),
                           $COMMENTS->c_date
                           ),
                           file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/comment.tpl')
                           );
  }
  
  return $string;
}

// Build search data and/or coming soon data..
function buildEvents($date,$SQL='')
{
  global $database,$limitvalue,$limit,$p_event13,$SETTINGS,$theme,
         $manage5,$manage6,$p_soon3,$p_soon4,$p_soon5;
  $data = '';
  
  $q_events = mysql_query("SELECT *,DATE_FORMAT(fromDate,'".$SETTINGS->formatdate."') AS f_date,
                           DATE_FORMAT(toDate,'".$SETTINGS->formatdate."') AS t_date 
                           FROM ".$database['prefix']."events
                           ".($SQL ? $SQL : 'WHERE (fromDate > \''.date("Y-m-d").'\' AND fromDate <= \''.$date.'\') AND is_archived  = \'0\'')." 
                           ORDER BY fromDate
                           LIMIT $limitvalue,$limit
                           ") or die(mysql_error());
  if (mysql_num_rows($q_events)>0) {
    while ($EVENTS = mysql_fetch_object($q_events)) {
      $data .= str_replace(array('{url}','{path}','{title_txt}','{title}','{dates_txt}',
                                 '{dates}','{status_txt}','{status}'),
                           array(
                           $SETTINGS->folder.'/'.($SETTINGS->modr ? 'event/'.$EVENTS->id.'/'.cleanEventName(cleanData($EVENTS->title)).'/index.html' : 'index.php?cmd=event&amp;event='.$EVENTS->id),
                           'themes/'.$theme,
                           $manage5,
                           cleanData($EVENTS->title),
                           $manage6,
                           ($EVENTS->fromDate===$EVENTS->toDate ? translateCalendar($EVENTS->f_date) : translateCalendar($EVENTS->f_date).' / '.translateCalendar($EVENTS->t_date)),
                           $p_soon3,
                           ($EVENTS->is_archived ? $p_soon5 : $p_soon4)
                           ),
                           file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/event.tpl')
                           );
    } 
  } else {
    $data = str_replace('{txt}',$p_event13,
                        file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/general_message.tpl')
                        );
  }   
  
  return $data;
}

// Build picture display..
function pictureGallery($id,$nopics=false)
{
  global $database,$theme,$p_event9,$p_event10,$p_event11,$SETTINGS;
  $pics = '';
  $data = '';
  
  $q_gallery = mysql_query("SELECT * FROM ".$database['prefix']."pictures
                            WHERE eventid  = '{$id}'
                            ORDER BY id
                            ") or die(mysql_error());
  if (mysql_num_rows($q_gallery)>0) {
    while ($PICTURES = mysql_fetch_object($q_gallery)) {
      $event = getEvent($id);
      $data .= '<li><a href="'.$SETTINGS->folder.'/'.($SETTINGS->modr ? 'view-picture/'.$PICTURES->id.'/'.cleanEventName(cleanData($event->title)).'/index.html' : 'index.php?cmd=view-picture&amp;picture='.$PICTURES->id).'" rel="gb_page_center['.IMG_POP_WINDOW.']" title="'.($PICTURES->name ? cleanData($PICTURES->name) : $p_event11).'"><img class="thumbnail" src="'.($PICTURES->thumb ? $PICTURES->thumb : $PICTURES->image).'" alt="'.($PICTURES->name ? cleanData($PICTURES->name) : $p_event11).'" title="'.($PICTURES->name ? cleanData($PICTURES->name) : $p_event11).'" /></a></li>'."\n";
    }
    // Add placeholders where no image was specified..
    if (mysql_num_rows($q_gallery)<4) {
      for ($i=0; $i<4-mysql_num_rows($q_gallery); $i++) {
        $data .= '<li><img class="thumbnail" src="'.$SETTINGS->folder.'/themes/'.$theme.'/img/no_picture_preview.gif" title="'.$p_event10.'" alt="'.$p_event10.'" /></li>'."\n";
      }
    }
    $pics = str_replace('{pictures}',$data,
                        file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/pictures.tpl')
                        );
  } else {
    $pics = str_replace('{txt}',$p_event9,
                        file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/'.($nopics ? 'no_pictures' : 'general_message').'.tpl')
                        );
  }
  
  return $pics;
}

// Archive events..
function archiveEvents()
{
  global $database;
  $date = date("Y-m-d",strtotime("-1 day"));
  
  $q_archive = mysql_query("SELECT * FROM ".$database['prefix']."events
                            WHERE toDate     <= '{$date}'
                            AND is_archived  = '0'
                            ") or die(mysql_error());
  if (mysql_num_rows($q_archive)>0) {
    while ($ARCHIVES = mysql_fetch_object($q_archive)) {
      // What are we doing with event?
      // If archiving, auto disable the contact option..
      switch($ARCHIVES->finish) {
        // 1. archive with comments..
        // 2. archive with no comments..
        case '1':
        case '2':
        mysql_query("UPDATE ".$database['prefix']."events SET
                     contact      = '0',
                     en_comments  = '0',
                     is_archived  = '1'
                     WHERE id     = '{$ARCHIVES->id}'
                     LIMIT 1
                     ") or die(mysql_error());
        if ($ARCHIVES->finish=='2') {
          mysql_query("DELETE FROM ".$database['prefix']."comments
                       WHERE eventid = '{$ARCHIVES->id}'
                       ") or die(mysql_error());
        }             
        break;
        // delete event..clear pictures..
        case '3':
        mysql_query("DELETE FROM ".$database['prefix']."events
                     WHERE id = '{$ARCHIVES->id}'
                     LIMIT 1
                     ") or die(mysql_error());
        mysql_query("DELETE FROM ".$database['prefix']."pictures
                     WHERE eventid = '{$ARCHIVES->id}'
                     ") or die(mysql_error());
        break;
      }
    }
  }                        
}

// Get event data based on id..
function getEvent($id)
{
  global $database,$SETTINGS;
  
  $q_event = mysql_query("SELECT *,DATE_FORMAT(fromDate,'".$SETTINGS->formatdate."') AS f_date,
                          DATE_FORMAT(toDate,'".$SETTINGS->formatdate."') AS t_date 
                          FROM ".$database['prefix']."events
                          WHERE id = '{$id}'
                          LIMIT 1
                          ") or die(mysql_error());
  return mysql_fetch_object($q_event);                        
}

// Get comment data based on id..
function getComment($id)
{
  global $database,$SETTINGS;
  
  $q_comment = mysql_query("SELECT * FROM ".$database['prefix']."comments
                            WHERE id = '{$id}'
                            LIMIT 1
                            ") or die(mysql_error());
  return mysql_fetch_object($q_comment);                        
}

// Get pictures..
function getPicture($event,$identifier,$rows=false)
{
  global $database,$SETTINGS;
  
  $q_pictures = mysql_query("SELECT * FROM ".$database['prefix']."pictures
                             WHERE eventid   = '{$event}'
                             AND identifier  = '{$identifier}'
                             LIMIT 1
                             ") or die(mysql_error());
  return ($rows ? mysql_num_rows($q_pictures) : mysql_fetch_object($q_pictures));                        
}

// Get pictures..
function getSinglePicture($id)
{
  global $database;
  
  $q_picture = mysql_query("SELECT * FROM ".$database['prefix']."pictures
                             WHERE id = '{$id}'
                             LIMIT 1
                             ") or die(mysql_error());
  return mysql_fetch_object($q_picture);                        
}

// Return overlib tooltip
function toolTip($msg,$msg2,$dir='CENTER')
{
  return '<span class="tip">[<a href="javascript:void(0);" onclick="return overlib(\''.htmlspecialchars($msg2).'\', STICKY, CAPTION, \''.$msg.'\', '.$dir.');" onmouseout="nd();"><b>?</b></a>]</span>';
}

// Removes potentially 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 strip_tags(trim($data));
}

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

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

// 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);
}

// Check var is numeric..
function checkVar($var)
{
  if (!is_numeric($var)) {
    header("HTTP/1.0 404 Not Found");
    exit;
  }
}

// Parses english calendar months/days into translated language..
// Cheap and nasty, but effective enough..
function translateCalendar($data,$area='months')
{
  global $calendar,$calendar2,$calendar3,$calendar4;
  
  // Do NOT change these values..
  $days     = array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday');
  $sdays    = array('Sun','Mon','Tue','Wed','Thu','Fri','Sat');
  $months   = array('January','February','March','April','May','June','July',
                    'August','September','October','November','December');
  $smonths  = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 
                    'Sep', 'Oct', 'Nov', 'Dec');
                      
  // If months and months are 3 chars, we are converting short months...
  if ($area=='months') {
    $data = str_replace((strlen($data)==3 ? $smonths : $months),(strlen($data)==3 ? $calendar3 : $calendar2),$data);
  // If days and days are 3 chars, we are converting short days..
  } else {
    $data = str_replace((strlen($data)==3 ? $sdays : $days),(strlen($data)==3 ? $calendar4 : $calendar),$data);
  }
  
  return $data;
}

// Cleans event name into url friendly string..
function cleanEventName($title)
{
  $title = strtolower(preg_replace('`[^\w_-]`', '-', $title));
  
  return str_replace(array('--','---','----','-amp-','-039-'),
                     array('-','-','-','-and-',''),
                     $title
                     );
}

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

// Shows page numbers
function page_numbers($count,$limit,$page,$raw,$stringVar='page')
{
  global $script5,$script6,$SETTINGS,$theme;
  $file = file_get_contents(FOLDER_PATH.'themes/'.$theme.'/tpl_files/page_numbers.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; '.$script5,
                              ' &bull; ',
                              $script6.' &raquo;'
                              );
  $PaginateIt->SetModRewrite($SETTINGS->modr);                            
                              
  return str_replace('{pages}',$PaginateIt->GetPageLinks(),$file);                            
}

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

  while ($read = readdir($showthemes)) {
  	if ($read!='.' && $read!='..' && $read!='index.html' && $read!='email') {
      $count++;
      $string .= '<option'.(($read == $cur_theme) ? ' selected="selected"' : '').' style="padding-left:3px" value="index.php?load_theme='.$read.'">'.ucfirst($read).'</option>'."\n";
    }
  }

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

// Theme switcher..changes theme if enabled..
function updateEventTheme($new_theme)
{
  global $SETTINGS;
  
  // Check this directory exists before reload..
  if (is_dir('themes/'.$new_theme)) {
    setcookie("mevents_theme_cookie", $new_theme, time()+60*60*24*30);
  }
  
  header("Location: ".($SETTINGS->modr ? 'index.html' : 'index.php').""); 
}

// 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);
}

?>
