// Based heavily on mdp_calendar - thanks!
//TODO: Investigate
/*
$d = new DateTime('2008-12-22 12:52');
echo $d->getTimezone()->getName();
*/
if( $date = gps('date') ) {
$_GET['month'] = $date;
}
function smd_calendar($atts, $thing='') {
global $pretext, $variable, $prefs, $smd_cal_flag, $smd_cal_id, $smd_year, $smd_month, $smd_week, $smd_day;
extract(lAtts(array(
'time' => 'any', // past, future, any
'size' => 'large', // small or large (calendar)
'expired' => '', // 0=no, 1=yes publish expired events, empty=use prefs
'category' => $pretext['c'],
'section' => $pretext['s'],
'author' => $pretext['author'],
'status' => 'live',
'static' => '',
'form' => '',
'spanform' => 'SMD_SAME',
'stepfield' => '',
'skipfield' => '',
'showskipped' => '0',
'showspanned' => '1',
'holidays' => '',
'holidayflags' => 'event', // permit these events to "land" on a holiday (event, recur, multi)
'classlevels' => 'cell, event', // cell, event, cellplus (combines event and cell into cell level classes)
'classprefixes' => 'smd_cal_, smd_cal_ev_', // 1st=cell-level pfx, 2nd=event-level pfx (optional)
'class' => '', // Table class
'rowclass' => '',
'cellclass' => '',
'emptyclass' => 'empty',
'isoweekclass' => 'week',
'navclass' => 'nav',
'eventclasses' => 'category',
'eventwraptag' => 'span',
'select' => '', // month and/or year (to display dropdowns)
'selectbtn' => '', // empty = autoselect (onchange), or text to go on the submit button
'myclass' => '', // month-year header class
'mywraptag' => '', // month-year header wraptag
'id' => '', // Table ID (=calid)
'week' => '',
'month' => '',
'year' => '',
'yearwidth' => '0,0', // number of years either side of the first/last article to permit
'isoweeks' => '', // empty = don't show ISO weeks, or text of column heading
'dayformat' => 'ABBR', // ABBR = %a, FULL = %A, or custom strftime string
'monthformat' => 'FULL', // ABBR = %b, FULL = %B, or custom strftime string
'firstday' => 0, // 1st day of week 0=Sunday, 6=Saturday (forced to Monday if isoweeks=1)
'gmt' => 0,
'lang' => '',
'debug' => 0,
), $atts));
$future = ( $time != "past" ) ? true : false; // Determine heading style
$status = ($status) ? $status : 'live';
$firstday = ($isoweeks == '') ? $firstday : 1;
$spanform = ($spanform == "SMD_SAME") ? $form : $spanform;
// Set up the class prefixes
$clevs = do_list($classlevels);
$cls = do_list($classprefixes);
$classprefix = $evclassprefix = $cls[0];
if (count($cls) > 1){
$evclassprefix = $cls[1];
}
// Filters
$fopts = array();
$catSQL = $secSQL = $authSQL = '';
if($category) {
$fopts[] = array('c' => $category);
$catSQL = doQuote(join("','", do_list($category)));
$catSQL = " AND ( Category1 IN (".$catSQL.") OR Category2 IN (".$catSQL.") ) ";
}
if($section) {
$fopts[] = array('s' => $section);
$secSQL = doQuote(join("','", do_list($section)));
$secSQL = " AND Section IN (".$secSQL.") ";
}
if($author) {
$fopts[] = array('author' => htmlentities(gps('author')));
$authSQL = doQuote(join("','", do_list($author)));
$authSQL = " AND AuthorID IN (".$authSQL.") ";
}
$status = do_list($status);
$stati = array();
foreach ($status as $stat) {
if (empty($stat)) {
continue;
} else if (is_numeric($stat)) {
$stati[] = $stat;
} else {
$stati[] = getStatusNum($stat);
}
}
$stati = " Status IN (".doQuote(join("','", $stati)).")";
$expired = ($expired) ? $expired : $prefs['publish_expired_articles'];
$expired = (($expired) ? '' : ' AND (now() <= Expires OR Expires = '.NULLDATETIME.')');
$eventclasses = do_list($eventclasses);
$holidayflags = do_list($holidayflags);
// Work out the first and last posts to determine the year range
$earliest = safe_row('unix_timestamp(Posted) AS uPosted', 'textpattern', $stati.(($category) ? $catSQL : '').(($section) ? $secSQL : '').(($author) ? $authSQL : '').' ORDER BY Posted ASC LIMIT 0, 1', $debug);
$latest = safe_row('unix_timestamp(LastMod) AS uLastMod', 'textpattern', $stati.(($category) ? $catSQL : '').(($section) ? $secSQL : '').(($author) ? $authSQL : '').' AND Posted < now() ORDER BY LastMod DESC LIMIT 0, 1', $debug);
$yearwidth = do_list($yearwidth);
if (count($yearwidth) == 1) $yearwidth[1] = $yearwidth[0];
$earliest = date("Y", strtotime("-".$yearwidth[0]." year", ( (empty($earliest)) ? time() : $earliest['uPosted']) ) );
$latest = date("Y", strtotime("+".$yearwidth[1]." year", ( (empty($latest)) ? time() : $latest['uLastMod']) ) );
// Check the URL for current date and calendar target info
$incoming_calid = gps('calid');
$incoming_year = (gps('y') and is_numeric(gps('y'))) ? (int)gps('y') : '';
$incoming_month = (gps('m') and is_numeric(gps('m'))) ? (int)gps('m') : '';
$incoming_week = (gps('w') and is_numeric(gps('w'))) ? (int)gps('w') : '';
if($static) { // if we're static w/o any supplied vars, use the current date
if(!$year) { $year = safe_strftime('%Y'); }
if(!$month) { $month = safe_strftime('%m'); }
} else { // otherwise use current date only if there's nothing else
if( $id == $incoming_calid ) { // use incoming
$year = ($incoming_year) ? $incoming_year : (($year) ? $year : safe_strftime('%Y'));
$month = ($incoming_month) ? $incoming_month : (($month) ? $month : safe_strftime('%m'));
// If week is used, adjust month so it encompasses the given week
$week = $incoming_week;
if ($week) {
$month = safe_strftime("%m", mktime (1,1,1,1,7*$week,$year)); // Guess the month from the week
}
} else { // use current
if(!$year) { $year = safe_strftime('%Y'); }
if(!$month) { $month = safe_strftime('%m'); }
if($week) { $month = safe_strftime("%m", mktime (1,1,1,1,7*$week,$year)); }
}
}
$smd_cal_id = ($incoming_calid) ? $incoming_calid : $id;
$smd_year = $year; $smd_month = $month; // $smd_week and smd_day are set per event later
// The times in the DB are stored using the server's local time, so we don't
// want to adjust anything (since mktime uses the server's local time).
//TODO: Worry about gmt / dst
$ts_first = mktime(0, 0, 0, $month, 1, $year);
$ts_last = mktime(23, 59, 59, $month, date('t',$ts_first), $year);
$extrasql = $catSQL . $secSQL . $authSQL;
switch($time) {
case "any" : /* Don't care about date */ break;
case "future" : $extrasql .= " AND Posted > CURDATE()"; break;
default : $extrasql .= " AND Posted < CURDATE()"; break; // The past
}
// Holidays are global 'exclusions', either defined directly or in a
$holidays = do_list($holidays);
$txphols = do_list($holidays[0], ":");
if ($txphols[0] == "txpvar") {
$holidays = do_list($variable[$txphols[1]]);
}
// Force each holiday to a known format. Holidays without years use current year
foreach ($holidays as $key => $val) {
if (empty($val)) continue;
$numparts = preg_match('/^([\d\w]+).?([\d\w]+).?([\d\w]+)?$/', $val, $parts);
if ($numparts) {
if (count($parts) == 3) {
$parts[3] = $year;
}
$val = str_pad($parts[1], 2, '0', STR_PAD_LEFT).'-'.str_pad($parts[2], 2, '0', STR_PAD_LEFT).'-'.$parts[3];
}
$holidays[$key] = date("d-m-Y", strtotime($val));
}
if ($debug > 0 && !empty($holidays) && $holidays[0] != '') {
echo "++ HOLIDAYS ++ ";
dmp($holidays);
}
// Get all matching articles in (and before) this month
$events = array();
$sql2 = $stati . " HAVING uPosted <= ".$ts_last . $expired . $extrasql ." ORDER BY Posted ASC";
$grabCols = '*, unix_timestamp(Posted) as uPosted, unix_timestamp(LastMod) as uLastMod, unix_timestamp(Expires) as uExpires';
$evlist = safe_rows($grabCols, 'textpattern', $sql2, $debug);
// If any events recur and fall within the current month, add those as well
// If any dates are to be excluded, the entry is skipped UNLESS showskipped indicates otherwise
foreach ($evlist as $row) {
$idx = 0; // In case the 1st day of the month is a continuation of an event from the end of the previous month
$start = $row['uPosted'];
$real_end = $row['uExpires'];
$end = ($real_end != 0 && $real_end < $ts_last) ? $real_end : $ts_last;
$smd_cal_flag = array();
if ($debug > 1) {
echo '++ EVENT START // END // REAL END ++';
dmp($row['Title']);
dmp(date('d-m-Y H:i:s', $start) .' // '. date('d-m-Y H:i:s', $end) .' // '. date('d-m-Y H:i:s', $real_end));
if ($debug > 2) {
dmp($row);
}
}
$multi = ($row['uExpires'] > $row['uPosted'] && $row['uExpires'] > $ts_first) ? true : false;
$recur = (empty($row[$stepfield])) ? false : true;
$hol_hit = in_array(date("d-m-Y", $start), $holidays);
$evclasses = array();
foreach ($eventclasses as $evcls) {
switch ($evcls) {
case "":
break;
case "gcat":
if (isset($pretext['c']) && !empty($pretext['c'])) {
$evclasses[] = $evclassprefix.$pretext['c'];
}
break;
case "category":
if (isset($row['Category1']) && !empty($row['Category1'])) {
$evclasses[] = $evclassprefix.$row['Category1'];
}
if (isset($row['Category2']) && !empty($row['Category2'])) {
$evclasses[] = $evclassprefix.$row['Category2'];
}
break;
case "section":
if (isset($pretext['s']) && !empty($pretext['s'])) {
$evclasses[] = $evclassprefix.$pretext['s'];
}
break;
case "author":
if (isset($pretext['author']) && !empty($pretext['author'])) {
$evclasses[] = $evclassprefix.$pretext['author'];
}
break;
default:
if (isset($row[$evcls]) && !empty($row[$evcls])) {
$evclasses[] = $evclassprefix.$row[$evcls];
}
break;
}
}
$evclasses = ($evclasses) ? ' '. join(' ', $evclasses) : '';
$ignore = array();
if ($debug > 1 && $evclasses) {
echo '++ EVENT CLASSES ++';
dmp($evclasses);
}
// Events that start this month
if ($start < $end && $start > $ts_first) {
populateArticleData($row);
// start of a multi that may or may not be cancelled due to holidays
$flag = ($showspanned && $multi && !$recur) ? 'multifirst' . (( $hol_hit && !in_array('multi',$holidayflags) ) ? ' cancel hols' : '' ) : '';
// a standard event that may or may not be cancelled due to holidays
$flag = ($flag) ? $flag : (( $hol_hit && !in_array('event',$holidayflags) ) ? 'event cancel hols' : 'event' );
$smd_cal_flag = $flag = explode(' ', $flag);
foreach ($flag as $idx => $item) {
$flag[$idx] = $classprefix.$item;
}
$flag = join (' ', $flag);
$idx = (int)safe_strftime('%d', $start, $gmt, $lang);
$smd_day = $idx;
$smd_week = safe_strftime('%V', $start, $gmt, $lang);
$op = ($thing) ? parse($thing) : (($form) ? parse_form($form) : (($size=="small") ? '' : href($row['Title'], permlinkurl($row), ' title="'.$row['Title'].'"')) );
$events[$idx][] = array('ev' => $op, 'type' => (($flag) ? $flag : '').$evclasses);
$smd_cal_flag = array();
}
// Generate a skip array for this event
if ($skipfield && $row[$skipfield] != '') {
$ignore = do_list($row[$skipfield]);
foreach ($ignore as $key => $val) {
$ignore[$key] = date("d-m-Y", strtotime($val)); // Force each date to a known format
}
}
// Calculate the date offsets and check recurring events that fall within the month of interest
if ($stepfield && $row[$stepfield] != '') {
$freq = do_list($row[$stepfield]);
foreach ($freq as $interval) {
$ts_curr = $start;
while ($ts_curr < $end) {
if (($ts_curr = strtotime($interval, $ts_curr)) === false) {
break;
} else {
if ($ts_curr < $end && $ts_curr > $ts_first) {
// A recurring event. Check it isn't a holiday or to be ignored
populateArticleData($row);
$op = '';
$idx = (int)safe_strftime('%d', $ts_curr, $gmt, $lang);
$smd_cal_flag[] = 'recur';
$show_me = !in_array(date("d-m-Y", $ts_curr), $ignore);
$hol_hit = in_array(date("d-m-Y", $ts_curr), $holidays);
$show_hol = ($hol_hit && !in_array('recur',$holidayflags) ) ? false : true;
if ( !$show_me || !$show_hol ) {
$smd_cal_flag[] = 'cancel';
}
if ($hol_hit) {
$smd_cal_flag[] = 'hols';
}
// Create the events that appear in the cell but only if they've not appeared before, or are to be ignored
if (($show_me && $show_hol) || $showskipped) {
$smd_day = $idx;
$smd_week = safe_strftime('%V', $ts_curr, $gmt, $lang);
$op = ($thing) ? parse($thing) : (($form) ? parse_form($form) : (($size=="small") ? '' : href($row['Title'], permlinkurl($row), ' title="'.$row['Title'].'"')) );
}
$used = array();
if (isset($events[$idx]) && $events[$idx] != NULL) {
foreach ($events[$idx] as $ev) {
$used[] = $ev['ev'];
}
}
if (isset($events[$idx]) && $events[$idx] == NULL || !in_array($op, $used)) {
$events[$idx][] = array('ev' => $op, 'type' => $classprefix.'recur'. (($show_me && $show_hol) ? '' : ' '.$classprefix.'cancel').$evclasses);
}
$smd_cal_flag = array();
}
}
}
}
} else if ($showspanned && $multi) {
// Non-recurring events may span more than one date but they must still respect ignored dates and holidays
populateArticleData($row);
$lastday = (int)safe_strftime('%d', $end, $gmt, $lang);
$real_lastday = (int)safe_strftime('%d', $real_end, $gmt, $lang);
while (++$idx <= $lastday) {
$op = '';
$multiflag = ($idx==$real_lastday) ? 'multilast' : (($idx==1) ? 'multiprev' : 'multi');
$smd_cal_flag[] = $multiflag;
$thisdate = mktime(0, 0, 0, $month, $idx, $year);
$show_me = !in_array(date("d-m-Y", $thisdate), $ignore);
$hol_hit = in_array(date("d-m-Y", $thisdate), $holidays);
$show_hol = ($hol_hit && !in_array('multi',$holidayflags) ) ? false : true;
if ( !$show_me || !$show_hol ) {
$smd_cal_flag[] = 'cancel';
}
if ($hol_hit) {
$smd_cal_flag[] = 'hols';
}
if ( ($show_me && $show_hol) || $showskipped) {
$smd_day = $idx;
$smd_week = safe_strftime('%V', $thisdate, $gmt, $lang);
$op = ($spanform) ? parse_form($spanform) : (($thing) ? parse($thing) : (($size=="small") ? '' : href('→', permlinkurl($row), ' title="'.$row['Title'].'"')) );
}
$events[$idx][] = array('ev' => $op, 'type' => $classprefix.$multiflag. (($show_me && $show_hol) ? '' : ' '.$classprefix.'cancel').$evclasses);
$smd_cal_flag = array();
}
}
}
// Generate the calendar
if( $size == "small" ) {
$calendar = new SMD_Small_Calendar($year, $month, $events, $section, $category);
} else {
$calendar = new SMD_Calendar($year, $month, $events);
}
$calendar->setGMT($gmt);
$calendar->setLang($lang);
$calendar->setClassLevels($clevs);
$calendar->setClassPrefix($classprefix);
$calendar->setEventPrefix($evclassprefix);
$calendar->setEventWraptag($eventwraptag);
$calendar->setMYWraptag($mywraptag);
$calendar->setTableID($id);
$calendar->setTableClass($class);
$calendar->setRowClass($rowclass);
$calendar->setCellClass($cellclass);
$calendar->setEmptyClass($emptyclass);
$calendar->setISOWeekClass($isoweekclass);
$calendar->setNavClass($navclass);
$calendar->setMYClass($myclass);
$calendar->setNameFormat($dayformat, "d");
$calendar->setNameFormat($monthformat, "m");
$calendar->setShowISOWeek($isoweeks);
$calendar->setEYear($earliest);
$calendar->setLYear($latest);
$calendar->setFilterOpts($fopts);
$calendar->setHolidays($holidays);
$calendar->setSelectors(do_list($select), $selectbtn);
$calendar->setFirstDayOfWeek($firstday);
return $calendar->display($static, $future);
}
class SMD_Calendar extends SMD_Raw_Calendar {
// Override Constructor
// Permits multiple events to show per day
function SMD_Calendar($year,$month,$events) {
$this->events = $events;
$this->SMD_Raw_Calendar($year,$month);
}
// Override dspDayCell to display stuff right
function dspDayCell($theday) {
$cellclass = $this->getCellClass();
$hasarticle = isset($this->events[$theday]);
$tdclass = $cellclass . (($hasarticle) ? ' '.$this->classprefix.'event' : '')
. ((in_array( date('d-m-Y', mktime( 0, 0, 0, $this->getMonth(), $theday, $this->getYear()) ), $this->holidays)) ? ' '.$this->classprefix.'hols' : '');
$runningclass = (in_array("cell", $this->classlevels) || in_array("cellplus", $this->classlevels)) ? explode(' ', $tdclass) : array();
if($this->year == date('Y',time()+tz_offset() ) and $this->month == date('n',time()+tz_offset() ) and $theday == date('j',time()+tz_offset()) ) {
$runningclass[] = $this->classprefix.'today';
}
$out[] = hed($theday,4);
if( isset($this->events[$theday]) ) {
$days_events = $this->events[$theday];
foreach($days_events as $ev) {
$evclass = trim($ev['type']);
if (in_array("cellplus", $this->classlevels)) {
foreach (explode(' ', $evclass) as $evc) {
$runningclass[]= $evc;
}
}
$out[] = ($this->evwraptag) ? tag($ev['ev'], $this->evwraptag, (($evclass && in_array("event", $this->classlevels)) ? ' class="'.$evclass.'"' : '')) : $ev['ev'];
}
}
$runningclass = array_unique($runningclass);
// Amalgamate the event-level classes and cell-level classes, if required
return doTag(join('',$out),'td',join(' ',$runningclass));
}
function display($static=false, $future=false) {
$id = ($this->tableID) ? ' id="'.$this->tableID.'"' : '';
$c[] = $this->dspHeader($static, $future);
$c[] = $this->dspDayNames();
$c[] = $this->dspDayCells();
return doTag(join('',$c),'table',$this->tableclass,$id);
}
function dspHeader($static, $future) {
$curryr = $this->getYear();
$currmo = $this->getMonth();
$navclass = $this->getNavClass();
$navclass = ($navclass) ? ' class="'.$navclass.'"' : '';
$filters = array();
$filterHid = array();
if (!$static) {
foreach($this->fopts as $filter) {
foreach($filter as $key => $val) {
$filters[] = $key.'='.$val;
$filterHid[] = hInput($key, $val);
}
}
}
$filterURL = join(a, $filters);
// Month select list
if ($this->useSelector('month') && !$static) {
for ( $idx = 1; $idx <= 12; $idx++ ) {
$tagatts = ' value="'.$idx.'"';
if ( $idx == $currmo ) $tagatts .= ' selected="selected"';
$optiontags[] = doTag(safe_strftime($this->mthNameFmt, mktime(0,0,0,$idx), $this->gmt, $this->lang), 'option', '', $tagatts);
}
$selector[] = doTag(join(n, $optiontags), 'select', (($this->mywraptag) ? '' : $this->myclass), ' name="m"'.(($this->selbtn) ? '' : ' onchange="submit()"'), '')
. (($this->useSelector('year')) ? '' : hInput('y', $curryr));
$optiontags = array(); // Blank out
} else {
$selector[] = doTag($this->getMonthName(), 'span', (($this->mywraptag) ? '' : $this->myclass));
}
// Year select list
$y0 = $this->getEYear();
$y1 = $this->getLYear();
if ($this->useSelector('year') && ($y0 != $y1) && !$static) {
for ( $idx = $y0; $idx <= $y1; $idx++ ) {
$tagatts = ' value="'.$idx.'"';
if ( $idx == $curryr ) $tagatts .= ' selected="selected"';
$optiontags[] = doTag($idx, 'option', '', $tagatts);
}
$selector[] = doTag(join(n, $optiontags), 'select', (($this->mywraptag) ? '' : $this->myclass), ' name="y"'.(($this->selbtn) ? '' : ' onchange="submit()"'), '')
. (($this->useSelector('month')) ? '' : hInput('m', $currmo));
} else {
$selector[] = doTag($this->getYear(), 'span', (($this->mywraptag) ? '' : $this->myclass));
}
$extras = '';
if (!$static && ( $this->useSelector('month') || $this->useSelector('year') )) {
if ($this->selbtn) {
$extras .= doTag('', 'input', 'smd_cal_input', ' type="submit" value="'.$this->selbtn.'"');
}
if ($this->tableID) {
$extras .= hInput('calid',$this->tableID);
}
$extras .= join('', $filterHid);
}
$selector = '
';
$nav_back_link = $this->navigation($this->year, $this->month, '-', $filterURL);
$nav_fwd_link = $this->navigation($this->year, $this->month, '+', $filterURL);
$nav_back = (!$static && $nav_back_link) ? '<' : ' ';
// $nav_fwd = ((!$static && $future && $nav_fwd_link) or ($this->month != date('n',time()))) ? '>' : ' '; // *shrug* breaks if static set and month < this month used
$nav_fwd = (!$static && $future && $nav_fwd_link) ? '>' : ' ';
$c[] = doTag($nav_back,'th');
$c[] = ''.$selector.' | ';
$c[] = doTag($nav_fwd,'th');
return doTag(join('',$c),'tr');
}
function navigation($year,$month,$direction,$flt) {
global $permlink_mode;
if($direction == '-') {
if($month - 1 < 1) {
$month = 12;
$year -= 1;
} else {
$month -= 1;
}
} else {
if($month + 1 > 12) {
$month = 1;
$year += 1;
} else {
$month += 1;
}
}
// Abort if we're about to go out of range
if ($year < $this->getEYear() || $year > $this->getLYear()) {
return '';
}
$id = ($this->tableID) ? a.'calid='.$this->tableID : ''; // Allow specific calendar navigation, in case there's more than one per page
if($permlink_mode != 'messy') {
return "?m=$month".a."y=$year".$id.a.$flt;
} else { // for messy URL's we need to build the entire request string first, then tack on the rest
$out = makeOut('id','s','c','q','pg','p','month');
$r = '?';
foreach($out as $key => $val ) {
$r .= ($val) ? "$key=$val".a : '';
}
return $r."m=$month".a."y=$year".$id.a.$flt;
}
}
}
class SMD_Small_Calendar extends SMD_Calendar {
var $section = '';
var $category = '';
function SMD_Small_Calendar($year,$month,$events,$section,$category) {
$this->section = $section;
$this->category = $category;
$this->SMD_Calendar($year,$month,$events);
}
function dspDayCell($theday) {
global $permlink_mode;
$cellclass = $this->getCellClass().' ';
$hasarticle = isset($this->events[$theday]);
$class[] = $cellclass . (($hasarticle) ? $this->classprefix.'event' : '');
if ((in_array( date('d-m-Y', mktime( 0, 0, 0, $this->getMonth(), $theday, $this->getYear()) ), $this->holidays)) ) {
$class[] = $this->classprefix.'hols';
}
if($this->month == date('n',time()+tz_offset() ) and $theday == date('j',time()+tz_offset()) ) {
$class[] = $this->classprefix.'today';
}
if( isset($this->events[$theday]) ) {
$days_events = $this->events[$theday];
foreach($days_events as $ev) {
$evclass = trim($ev['type']);
foreach (explode(' ', $evclass) as $evc) {
$class[]= $evc;
}
$out[] = ($this->evwraptag) ? tag($ev['ev'], $this->evwraptag, (($evclass) ? ' class="'.$evclass.'"' : '')) : $ev['ev'];
}
if( $permlink_mode != 'year_month_day_title' ) {
$href = ' href="'.hu.'?date='.$this->year.'-'.$this->doubledigit($this->month).'-'.$this->doubledigit($theday);
if($this->section) { $href = $href.a.'s='.$this->section; }
if($this->category) { $href = $href.a.'c='.$this->category; }
$href .= '"';
} else {
$section = ($this->section) ? $this->section.'/' : '';
$href = ' href="'.hu.$section.$this->year.'/'.$this->doubledigit($this->month).'/'.$this->doubledigit($theday).'"';
}
// $title = ' title="'.safe_strftime('%x',gmmktime(0,0,0,$this->month,$theday+1,$this->year)).'"'; // no idea why $theday+1, but otherwise it won't work
$c[] = doTag($theday.join('',$out),'a','',$href);
} else {
$c[] = $theday;
}
return doTag(join('',$c),'td',join(' ',$class));
}
function doubledigit($n) {
if($n < 10) { $n = '0'.(int)$n; }
return $n;
}
}
/**
* Basic Calendar data and display
* http://www.oscarm.org/static/pg/calendarClass/
* @author Oscar Merida
* @created Jan 18 2004
* @package goCoreLib
*/
class SMD_Raw_Calendar {
var $gmt = 1;
var $lang;
var $year;
var $eyr;
var $lyr;
var $month;
var $dayNameFmt;
var $mthNameFmt;
var $startDay;
var $selectors;
var $selbtn;
var $showISOWeek;
var $endDay;
var $firstDayOfWeek = 0;
var $startOffset = 0;
var $classlevels;
var $classprefix;
var $evclassprefix;
var $evwraptag;
var $mywraptag;
var $rowclass;
var $cellclass;
var $emptyclass;
var $isoclass;
var $navclass;
var $myclass;
var $fopts;
var $holidays;
/**
* Constructor
*
* @param integer, year
* @param integer, month
* @return object
* @public
*/
function SMD_Raw_Calendar ( $yr, $mo ) {
$this->setYear($yr);
$this->setMonth($mo);
$this->setClassPrefix('smd_cal_');
$this->startTime = strtotime( "$yr-$mo-01 00:00" );
$this->startDay = date( 'D', $this->startTime );
$this->weekDay = date( 'w', $this->startTime );
$this->endDay = date( 't', $this->startTime );
$this->endTime = strtotime( "$yr-$mo-".$this->endDay." 23:59" );
$this->setNameFormat('%a', 'd');
$this->setNameFormat('%B', 'm');
$this->setFirstDayOfWeek(0);
$this->setShowISOWeek('');
$this->setTableID('');
$this->setTableClass('');
}
// ==== end Calendar ================================================
// Getters
function getStartTime() { return $this->startTime; }
function getWeekDay() { return $this->weekDay; }
function getEndTime() { return $this->endTime; }
function getYear() { return $this->year; }
function getEYear() { return $this->eyr; }
function getLYear() { return $this->lyr; }
function getMonth() { return $this->month; }
function getRowClass() { return $this->rowclass; }
function getCellClass() { return $this->cellclass; }
function getEmptyClass() { return $this->emptyclass; }
function getISOWeekClass() { return $this->isoclass; }
function getNavClass() { return $this->navclass; }
function getMonthName() { return safe_strftime( $this->mthNameFmt, $this->startTime, $this->gmt, $this->lang ); }
// Setters
function setGMT($b){ $this->gmt = $b; }
function setLang($code){ $this->lang = $code; }
function setTableID($id) { $this->tableID = $id; }
function setYear($year){ $this->year = $year; }
function setEYear($year){ $this->eyr = $year; }
function setLYear($year){ $this->lyr = $year; }
function setMonth($month) { $this->month = (int)$month; }
function setShowISOWeek($val) { $this->showISOWeek = $val; }
function setClassLevels($cls){ $this->classlevels = $cls; }
function setClassPrefix($cls){ $this->classprefix = $cls; }
function setEventPrefix($cls){ $this->evclassprefix = $cls; }
function setEventWraptag($wrap){ $this->evwraptag = $wrap; }
function setMYWraptag($wrap){ $this->mywraptag = $wrap; }
function setTableClass($cls) { $this->tableclass = ($cls) ? $this->classprefix.$cls : ''; }
function setRowClass($cls){ $this->rowclass = ($cls) ? $this->classprefix.$cls : ''; }
function setCellClass($cls){ $this->cellclass = ($cls) ? $this->classprefix.$cls : ''; }
function setEmptyClass($cls){ $this->emptyclass = ($cls) ? $this->classprefix.$cls : ''; }
function setISOWeekClass($cls){ $this->isoclass = ($cls) ? $this->classprefix.$cls : ''; }
function setNavClass($cls){ $this->navclass = ($cls) ? $this->classprefix.$cls : ''; }
function setMYClass($cls){ $this->myclass = ($cls) ? $this->classprefix.$cls : ''; }
function setFilterOpts($f) { $this->fopts = $f; }
function setHolidays($hols) { $this->holidays = $hols; }
function setSelectors($sel, $btn) { $this->selectors = $sel; $this->selbtn = $btn; }
function useSelector($val) { return in_array($val, $this->selectors); }
function setFirstDayOfWeek($d) {
$this->firstDayOfWeek = ((int)$d <= 6 and (int)$d >= 0) ? (int)$d : 0;
$this->startOffset = date( 'w', $this->startTime )-$this->firstDayOfWeek;
if ( $this->startOffset < 0 ) {
$this->startOffset = 7 - abs($this->startOffset);
}
}
/**
* frm: any valid PHP strftime() string or ABBR/FULL
* typ: d to set day, m to set month format
*/
function setNameFormat($frm, $typ="d") {
switch ($frm) {
case "FULL":
$fmt = ($typ == "d") ? "%A" : "%B";
break;
case "ABBR":
$fmt = ($typ == "d") ? "%a" : "%b";
break;
default:
$fmt = $frm;
break;
}
if ($typ == "d") {
$this->dayNameFmt = $fmt;
} else {
$this->mthNameFmt = $fmt;
}
}
/**
* Returns markup for displaying the calendar.
* @return
* @public
*/
function display ( ) {
$id = ($this->tableID) ? ' id="'.$this->tableID.'"' : '';
$c[] = '';
$c[] = $this->dspDayNames();
$c[] = $this->dspDayCells();
$c[] = '
';
return join('',$c);
}
// ==== end display ================================================
/**
* Displays the row of day names.
* @return string
* @private
*/
function dspDayNames ( ) {
// This is done to make sure Sunday is always the first day of our array
// Unix time gets a little funky at the beginning depending upon your timezone.
$serveroffset = gmmktime(0,0,0) - mktime(0,0,0);
$start = ($serveroffset < 0) ? 4 : 3;
$end = $start + 7;
for($i=$start; $i<$end; $i++) {
$names[] = ucfirst(safe_strftime($this->dayNameFmt, 86400*$i - tz_offset(), $this->gmt, $this->lang ));
}
$c[] = '';
$i = $this->firstDayOfWeek;
$j = 0; // count number of days displayed
$end = false;
if ($this->showISOWeek != '') {
$c[] = "".$this->showISOWeek." | ";
}
for($j = 0; $j<=6; $j++, $i++) {
if($i == 7) { $i = 0; }
$c[] = ''.$names[$i]." | ";
}
$c[] = '
';
return join('',$c);
}
// ==== end dspDayNames ================================================
/**
* Displays all day cells for the month
*
* @return string
* @private
*/
function dspDayCells ( ) {
$i = 0; // cell counter
$emptyClass = $this->getEmptyClass();
$isoClass = $this->getISOWeekClass();
$rowClass = $this->getRowClass();
$rowClass = ($rowClass) ? ' class="'.$rowClass.'"' : '';
$c[] = '';
if ($this->showISOWeek != '') {
$c[] = ''.date( 'W', $this->startTime ).' | ';
}
// first display empty cells based on what weekday the month starts in
for( $j=0; $j<$this->startOffset; $j++ ) {
$i++;
$c[] = ' | ';
} // end offset cells
// write out the rest of the days, at each sunday, start a new row.
for( $d=1; $d<=$this->endDay; $d++ ) {
$i++;
$c[] = $this->dspDayCell( $d );
if ( $i%7 == 0 ) { $c[] = '
'; }
if ( $d<$this->endDay && $i%7 == 0 ) {
$c[] = '';
if ($this->showISOWeek != '') {
$c[] = ''.date( 'W', strtotime( $this->getYear()."-".$this->getMonth()."-".(int)($d + 1) ." 00:00" )).' | ';
}
}
}
// fill in the final row
$left = 7 - ( $i%7 );
if ( $left < 7) {
for ( $j=0; $j<$left; $j++ ) {
$c[] = ' | ';
}
$c[] = "\n\t
";
}
return join('',$c);
}
// ==== end dspDayCells ================================================
/**
* outputs the contents for a given day
*
* @param integer, day
* @abstract
*/
function dspDayCell ( $day ) {
return ''.$day.' | ';
}
// ==== end dayCell ================================================
} // end class
// Perform one of 2 types of test: a flag-based test, or an info-based test
function smd_if_cal($atts, $thing) {
global $smd_cal_flag, $smd_cal_id, $smd_year, $smd_month, $smd_week, $smd_day;
extract(lAtts(array(
'flag' => '', // event, recur, multi(prev,first,last), cancel, hols
'calid' => '',
'year' => '',
'month' => '',
'week' => '',
'day' => '',
'logic' => 'and',
'debug' => '0',
), $atts));
$flag = do_list($flag);
$ctr = $num = 0;
if ($smd_cal_flag && $flag && $flag[0] != '') {
$num += count($flag);
foreach ($flag as $whatnot) {
if (empty($whatnot)) continue;
$ctr += (in_array($whatnot, $smd_cal_flag)) ? 1 : 0;
}
}
if ($calid) {
$num++;
$ctr += ($smd_cal_id === $calid) ? 1 : 0;
}
foreach (array("year", "month", "week", "day") as $test) {
$tester = $$test;
$gbl = 'smd_'.$test;
$compare = $$gbl;
if ($tester) {
$num++;
preg_match('/([!=<>]+)?([\d]+)/', $tester, $matches);
if ($debug) {
dmp("TEST IF: ". $compare. (($matches[1]) ? $matches[1] : '=') . $matches[2] );
}
switch ($matches[1]) {
case "!":
$ctr += ($compare!=$matches[2]) ? 1 : 0;
break;
case ">":
$ctr += ($compare>$matches[2]) ? 1 : 0;
break;
case ">=":
$ctr += ($compare>=$matches[2]) ? 1 : 0;
break;
case "<":
$ctr += ($compare<$matches[2]) ? 1 : 0;
break;
case "<=":
$ctr += ($compare<=$matches[2]) ? 1 : 0;
break;
default:
$ctr += ($compare==$matches[2]) ? 1 : 0;
break;
}
}
}
$result = (($ctr === $num && $logic == "and") || $ctr > 0 && $logic == "or") ? true : false;
return parse(EvalElse($thing, $result));
}
function smd_cal_info($atts) {
global $pretext, $smd_cal_flag, $smd_cal_id, $smd_year, $smd_month, $smd_week, $smd_day;
extract(lAtts(array(
'type' => 'flag', // flag, year, month, week, day, calid, section, category, author
'join' => ' ',
'html' => 0,
'escape' => 'html',
), $atts));
$join = ($html) ? a : $join; // html mode forces ampersand join
$type = do_list($type);
$ret = array();
foreach ($type as $item) {
switch ($item) {
case "flag":
$ret[] = join($join, $smd_cal_flag);
break;
case "year":
if ($smd_year) {
$ret[] = (($html) ? 'y=' : '') . $smd_year;
}
break;
case "month":
if ($smd_month) {
$ret[] = (($html) ? 'm=' : '') . $smd_month;
}
break;
case "week":
if ($smd_week) {
$ret[] = (($html) ? 'w=' : '') . $smd_week;
}
break;
case "day":
if ($smd_day) {
$ret[] = (($html) ? 'd=' : '') . $smd_day;
}
break;
case "section":
if ($pretext['s']) {
$ret[] = (($html) ? 's=' : '') . $pretext['s'];
}
break;
case "category":
if ($pretext['c']) {
$ret[] = (($html) ? 'c=' : '') . $pretext['c'];
}
break;
case "author":
$currauthor = author(array());
if ($currauthor) {
$ret[] = (($html) ? 'author=' : '') . $currauthor;
}
break;
case "calid":
if ($smd_cal_id) {
$ret[] = (($html) ? 'calid=' : '') . $smd_cal_id;
}
break;
}
}
$out = join($join, $ret);
return ($escape=='html') ? htmlspecialchars($out) : $out;
}
function smd_cal_now($atts) {
global $dateformat;
extract(lAtts(array(
'format' => $dateformat,
'gmt' => '',
'lang' => '',
), $atts));
return safe_strftime($format, time(), $gmt, $lang);
}