General calendar class for apps. I'm a little worried that the way I find the number of weeks in the month isn't the best way. What do you think?
<?php
class calendar {
//calendar construct
//takes timestamp as arg.
//if no timestamp it defaults to current
function show_calendar($timestamp) {
//if there is no timestamp give it now
if(strlen($timestamp) == 0)
$timestamp = time();
$day_array = array("Sun","Mon","Tue","Wed","Thu","Fri","Sat");
//numeral for day of week
$start = date("w", mktime(0, 0, 0, date("m", $timestamp), 1, date("Y", $timestamp)));
//days in the month
$ending = date("t", $timestamp);
//find the correct number of calendar weeks
$cal_weeks = round(($start + $ending) / 7) + 1;
//functions to format the date
include_once("date_functions.php");
echo "<table class=\"calendar\">";
echo "<tr>";
echo "<th colspan=\"" . count($day_array) . "\">";
echo "<a href=\"" . $_SERVER["SCRIPT_NAME"] . "?shift=back×tamp=" . $timestamp . "\"><=</a> ";
$cal_title = cal_title($timestamp);
echo $cal_title;
echo " <a href=\"" . $_SERVER["SCRIPT_NAME"] . "?shift=forward×tamp=" . $timestamp . "\">=></a>";
echo "</th>";
echo "</tr>";
echo "<tr>";
for($i=0;$i<count($day_array);$i++) {
echo "<th class=\"calendar\">";
echo $day_array[$i];
echo "</th>";
}
//day number
$x = 1;
echo "</tr>";
for($i = 0; $i < $cal_weeks; $i++) {
echo "<tr>";
if($i == 0) {
for($j = 0; $j < 7; $j++) {
if($j < $start) {
echo "<td class=\"calendar\">";
echo "</td>";
}
else {
echo "<td class=\"calendar\"><a href=\"" . $_SERVER["SCRIPT_NAME"] . "?timestamp=" . mktime(0, 0, 0, date("M", $timestamp), $x, date("Y", $timestamp)) . "\" class=\"calendar\">";
echo $x;
echo "</a></td>";
$x++;
}
}
}
if($i > 0 && $i < $cal_weeks - 1) {
for($j = 0; $j < 7; $j++) {
echo "<td class=\"calendar\"><a href=\"" . $_SERVER["SCRIPT_NAME"] . "?timestamp=" . mktime(0, 0, 0, date("M", $timestamp), $x, date("Y", $timestamp)) . "\" class=\"calendar\">";
echo $x;
echo "</a></td>";
$x++;
}
}
if($i == $cal_weeks - 1) {
for($j = 0; $j < 7; $j++) {
if($x > $ending) {
echo "<td class=\"calendar\">";
echo "</td>";
}
else {
echo "<td class=\"calendar\"><a href=\"" . $_SERVER["SCRIPT_NAME"] . "?timestamp=" . mktime(0, 0, 0, date("M", $timestamp), $x, date("Y", $timestamp)) . "\" class=\"calendar\">";
echo $x;
echo "</a></td>";
$x++;
}
}
}
echo "</tr>";
}
echo "</table>";
}
//shifts back and forth from month to month
//takes the action as the arg
function shift($action, $timestamp) {
if(strcmp($action, "back") == 0) {
$timestamp = mktime(0, 0, 0, date("m", $timestamp) - 1, 1, date("Y", $timestamp));
}
if(strcmp($action, "forward") == 0) {
$timestamp = mktime(0, 0, 0, date("m", $timestamp) + 1, 1, date("Y", $timestamp));
}
else
$timestamp = $timestamp;
return $timestamp;
}
//returns the new timestamp
}
$c1 = new calendar();
if($_GET["shift"])
$timestamp = $c1->shift($_GET["shift"], $_GET["timestamp"]);
$c1->show_calendar($timestamp);
?>