<?php

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

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

  ++++++++++++++++++++++++++++++++++++++++
  
  This File: class_calendar.inc.php
  Description: Calendar Class

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


class calendar extends genericOptions {
  
var $prefix,$month,$year;
var $settings     = array();
var $shortDays    = array();
var $days         = array();
var $shortMonths  = array();
var $months       = array();

// Displays events calendar for month/year...
function showEventCalendar($view='',$path,$theme)
{
  $count    = 0;
  $content  = '';
  $events   = '';
  $weekend  = array('0','6');
                       
  for($i=1; $i<$this->daysInMonth(); $i++)
  {
    $events = ''; 

    // Determine template for this day..
    $template   = (in_array(date("w", mktime(0,0,0,$this->month,($i<10 ? '0'.$i : $i),$this->year)),$weekend) ? 'weekend_day.tpl' : 'week_day.tpl');
    // Start day as string..
    $start_day  = $this->year.'-'.$this->month.'-'.($i<10 ? '0'.$i : $i);
    // Are we spanning days with event data..
    // Don`t span days for archives..
    if ($this->settings->dayspan && $view!='archive') {
      if ($this->eventSpanDays(($this->month<10 ? substr($this->month,-1) : $this->month),$this->year,$i)) {
        $events .= $this->eventSpanDays(($this->month<10 ? substr($this->month,-1) : $this->month),$this->year,$i);
      }
    } else {
      $q_events = mysql_query("SELECT * FROM ".$this->prefix."events 
                               WHERE fromDate   = '{$start_day}'
                               AND is_archived  = '".($view=='archive' ? '1' : '0')."'
                               ") or die(mysql_error());

      if (mysql_num_rows($q_events)>0) {
        while ($EVENTS = mysql_fetch_object($q_events)) {
          $events .= '<p class="event"><a href="'.$this->settings->folder.'/'.($this->settings->modr ? 'event/'.$EVENTS->id.'/'.$this->cleanEventName($this->strip_slashes($EVENTS->title)).'/index.html' : 'index.php?cmd=event&amp;event='.$EVENTS->id).'" title="'.$this->strip_slashes($EVENTS->title).'">'.$this->strip_slashes($EVENTS->title).'</a></p>'.$this->define_newline();
        }
      }
    }
    // Build template data..
    // Overwrite template if day is current day..
    $content .= str_replace(array('{day}','{date}','{events}'),
                            array(
                            $this->getDayName(date("w", mktime(0,0,0,$this->month,($i<10 ? '0'.$i : $i),$this->year))),
                            $i,
                            $events
                            ),
                            file_get_contents($path.'themes/'.$theme.'/tpl_files/'.($this->isToday(($i<10 ? '0'.$i : $i),$this->month) ? 'current_day.tpl' : $template))
                            );
  }
  
  return trim($content);
}

// Get calendar drop down navigation options..
function calendarNavigation($area,$current,$page,$archive='')
{
  $data = '';
  
  switch ($area) {
    case 'months':
    for ($i=1; $i<13; $i++) {
      $data .= '<option value="'.$this->settings->folder.'/'.($this->settings->modr ? $page.'/'.($i<10 ? '0'.$i : $i).'/'.$this->year.'/index.html' : 'index.php?cmd='.$page.'&amp;month='.($i<10 ? '0'.$i : $i).'&amp;year='.$this->year).'"'.(($i<10 ? '0'.$i : $i)==$current ? ' selected="selected"' : '').'>'.$this->getCurrentMonth(($i-1)).'</option>'."\n";
    }
    break;
    
    case 'years':
    for ($i=($archive ? $archive : date("Y")); $i<date("Y")+5; $i++) {
      $data .= '<option value="'.$this->settings->folder.'/'.($this->settings->modr ? $page.'/'.$this->month.'/'.$i.'/index.html' : 'index.php?cmd='.$page.'&amp;month='.$this->month.'&amp;year='.$i).'"'.($i==$current ? ' selected="selected" ' : ' ').'>'.$i.'</option>'."\n";
    }
    break;
  }
    
  return $data;
}

// Current month..
function getCurrentMonth($num)
{
  return $this->months[$num];
}

// Current day mame..
function getDayName($num)
{
  return $this->shortDays[$num];
}

// Calculate how many days in month..
// Increment count by one for loop..
function daysInMonth()
{
  return cal_days_in_month(CAL_GREGORIAN,$this->month,$this->year)+1;
}

function eventSpanDays($month,$year,$cal_day)
{
  $data       = '';
  $eventDays  = array();
  $eventComs  = array();
  $first      = '1';
  $last       = date('t', mktime(0,0,0,$month+1,0,$year));

  // Build query for span..
  // Thanks to Todd @ Webmaster World for help with this query..

  $stmt = "SELECT
             id,
             comments,
             title,
             fromDate,
             toDate,
               CASE MONTH(fromDate)
                WHEN $month THEN DAYOFMONTH(fromDate)
                  ELSE $first
                  END AS
                lo,
               CASE MONTH(toDate)
                WHEN $month THEN DAYOFMONTH(toDate)
                  ELSE $last
                  END AS
                hi
               FROM ".$this->prefix."events
               WHERE
               (
                 YEAR(fromDate) < $year
                 OR
                 YEAR(fromDate) = $year AND MONTH(fromDate) <= $month
               )
               AND
               (
                 YEAR(toDate) > $year
                 OR
                 YEAR(toDate) = $year AND MONTH(toDate) >= $month
               )
               AND 
               (
                 is_archived = '0'
               )
               ORDER BY lo, id
               ";                  

  $rows = mysql_query($stmt) or die(mysql_error());

  // Populate arrays with event data
  // Check for PHP version to prevent incorrect data with the range() function
  if (phpversion()<='4.3.2') {
    while ($row = mysql_fetch_array($rows)) {
      for ($i=$row['lo']; $i<$row['hi']+1; $i++) {
        $eventDays[$i][$row['id']] = $row['title'];
        $eventComs[$i][$row['id']] = $row['comments'];
      }
    }
  } else {
    while ($row = mysql_fetch_array($rows)) {
      foreach (range($row['lo'], $row['hi']) as $day) {
        $eventDays[$day][$row['id']] = $row['title'];
        $eventComs[$day][$row['id']] = $row['comments'];
      }
    }
  }

  // Sort event day array..
  ksort($eventDays);

  // Loop through arrays
  // Check for PHP version to prevent incorrect data with the range() function
  if (phpversion()<='4.3.2') {
    for ($i=$first; $i<$last+1; $i++) {
      if (array_key_exists($i, $eventDays)) {
        foreach($eventDays[$i] as $id => $name) {
          if ($cal_day==$i) {
            $data .= '<p class="event"><a href="'.$this->settings->folder.'/'.($this->settings->modr ? 'event/'.$id.'/'.$this->cleanEventName($this->strip_slashes($name)).'/index.html' : 'index.php?cmd=event&amp;event='.$id).'" title="'.$this->strip_slashes($name).'">'.$this->strip_slashes($name).'</a></p>'.$this->define_newline();
          }
        }
      }
    }
  } else {
    foreach (range($first, $last) as $day) {
      if (array_key_exists($day, $eventDays)) {
        foreach($eventDays[$day] as $id => $name) {
          if ($cal_day==$day) {
            $data .= '<p class="event"><a href="'.$this->settings->folder.'/'.($this->settings->modr ? 'event/'.$id.'/'.$this->cleanEventName($this->strip_slashes($name)).'/index.html' : 'index.php?cmd=event&amp;event='.$id).'" title="'.$this->strip_slashes($name).'">'.$this->strip_slashes($name).'</a></p>'.$this->define_newline();
          }
        }
      }
    }
  }
                        
  return $data;
}

// Cleans event name into url friendly string..
function cleanEventName($title)
{
  // 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
                     );
}

// Calculates if day is current day..
function isToday($day,$month)
{
  return (date("d")==$day && date("m")==$month ? true : false);
}

}

?>
