/** * Overloaded compare method * * The convertTZ calls are time intensive calls. When a compare call is * made in a recussive loop the lag can be significant. */ function compare($d1, $d2, $convertTZ = false) { if ($convertTZ) { $d1->convertTZ(new Date_TimeZone('UTC')); $d2->convertTZ(new Date_TimeZone('UTC')); } $days1 = Date_Calc::dateToDays($d1->day, $d1->month, $d1->year); $days2 = Date_Calc::dateToDays($d2->day, $d2->month, $d2->year); if ($days1 < $days2) { return -1; } if ($days1 > $days2) { return 1; } if ($d1->hour < $d2->hour) { return -1; } if ($d1->hour > $d2->hour) { return 1; } if ($d1->minute < $d2->minute) { return -1; } if ($d1->minute > $d2->minute) { return 1; } if ($d1->second < $d2->second) { return -1; } if ($d1->second > $d2->second) { return 1; } return 0; }
protected function _hours() { $hours_html = ''; $dayWidth = round(100 / $this->_days); $week = Date_Calc::weekOfYear(1, $this->_start->month, $this->_start->year); $span = (7 - $week) % 7 + 1; $span_left = $this->_days; $t = new Horde_Date($this->_start); while ($span_left > 0) { $span_left -= $span; $week_label = Horde::url('#')->link(array('onclick' => 'return switchDateView(\'Week\',' . $t->dateString() . ');')) . "Week" . ' ' . $week . '</a>'; $hours_html .= sprintf('<th colspan="%d" width="%s%%">%s</th>', $span, $dayWidth, $week_label); $week++; $t->mday += 7; $span = min($span_left, 7); } $hours_html .= '</tr><tr><td width="100" class="label"> </td>'; for ($i = 0; $i < $this->_days; $i++) { $t = new Horde_Date(array('month' => $this->_start->month, 'mday' => $this->_start->mday + $i, 'year' => $this->_start->year)); $day_label = Horde::url('#')->link(array('onclick' => 'return switchDateView(\'Day\',' . $t->dateString() . ');')) . ($i + 1) . '.</a>'; $hours_html .= sprintf('<th width="%s%%">%s</th>', $dayWidth, $day_label); } for ($i = 0; $i < $this->_days; $i++) { $start = new Horde_Date(array('hour' => $this->_startHour, 'month' => $this->_start->month, 'mday' => $this->_start->mday + $i, 'year' => $this->_start->year)); $end = new Horde_Date(array('hour' => $this->_endHour, 'month' => $this->_start->month, 'mday' => $this->_start->mday + $i, 'year' => $this->_start->year)); $this->_timeBlocks[] = array($start, $end); } return $hours_html; }
function MAX_getDatesByPeriodLimitStart($period, $limit, $start) { $begin = $limit + $start - 1; $end = $start; switch ($period) { case 'daily': $dayBegin = new Date(); $dayBegin->subtractSpan(new Date_Span("{$begin}, 0, 0, 0")); $dayEnd = new Date(); $dayBegin->subtractSpan(new Date_Span("{$end}, 0, 0, 0")); break; case 'weekly': $dayBegin = new Date(Date_Calc::prevDay()); $dayEnd = new Date(Date_Calc::prevDay()); break; case 'monthly': $dayBegin = new Date(); $dayBegin->subtractSpan(new Date_Span('6, 0, 0, 0')); $dayEnd = new Date(); break; case 'allstats': default: $dayBegin = null; $dayEnd = null; } $aDates = array(); $aDates['day_begin'] = is_object($dayBegin) ? $dayBegin->format('%Y-%m-%d') : ''; $aDates['day_end'] = is_object($dayEnd) ? $dayEnd->format('%Y-%m-%d') : ''; return $aDates; }
/** * Overloaded compare method * * The convertTZ calls are time intensive calls. When a compare call is * made in a recussive loop the lag can be significant. */ function compare($d1, $d2, $convertTZ = false) { if ($convertTZ) { $d1->convertTZ(new Date_TimeZone('UTC')); $d2->convertTZ(new Date_TimeZone('UTC')); } $days1 = Date_Calc::dateToDays($d1->day, $d1->month, $d1->year); $days2 = Date_Calc::dateToDays($d2->day, $d2->month, $d2->year); $comp_value = 0; if ($days1 - $days2) { $comp_value = $days1 - $days2; } else { if ($d1->hour - $d2->hour) { $comp_value = dPsgn($d1->hour - $d2->hour); } else { if ($d1->minute - $d2->minute) { $comp_value = dPsgn($d1->minute - $d2->minute); } else { if ($d1->second - $d2->second) { $comp_value = dPsgn($d1->second - $d2->second); } } } } return dPsgn($comp_value); }
protected function _render(Horde_Date $day = null) { $this->_start = new Horde_Date(Date_Calc::beginOfWeek($day->mday, $day->month, $day->year, '%Y%m%d000000')); $this->_end = new Horde_Date($this->_start); $this->_end->hour = 23; $this->_end->min = $this->_end->sec = 59; $this->_end->mday += $this->_days - 1; }
function isbatchingmaintenancecurrent($batching_expiration_date) { $bedate = $batching_expiration_date ? new CDate($batching_expiration_date) : null; $now = new CDate(); if (Date_Calc::compareDates($bedate->day, $bedate->month, $bedate->year, $now->day, $now->month, $now->year) < 0) { return "No"; } else { return "Yes"; } }
function cal_work_day_conv($val) { global $locale_char_set; $wk = Date_Calc::getCalendarWeek(null, null, null, "%a", LOCALE_FIRST_DAY); $day_name = $wk[($val - LOCALE_FIRST_DAY) % 7]; if ($locale_char_set == "utf-8" && function_exists("utf8_encode")) { $day_name = utf8_encode($day_name); } return htmlentities($day_name, ENT_COMPAT, $locale_char_set); }
function cal_work_day_conv($val) { global $locale_char_set, $AppUI; setlocale(LC_TIME, 'en'); $wk = Date_Calc::getCalendarWeek(null, null, null, '%a', LOCALE_FIRST_DAY); setlocale(LC_ALL, $AppUI->user_lang); $day_name = $AppUI->_($wk[($val - LOCALE_FIRST_DAY) % 7]); if ($locale_char_set == 'utf-8' && function_exists('utf8_encode')) { $day_name = utf8_encode($day_name); } return htmlspecialchars($day_name, ENT_COMPAT, $locale_char_set); }
function cal_work_day_conv($val) { global $locale_char_set; setlocale(LC_ALL, 'en_AU' . ($locale_char_set ? '.' . $locale_char_set : '.utf8')); $wk = Date_Calc::getCalendarWeek(null, null, null, "%a", LOCALE_FIRST_DAY); setlocale(LC_ALL, $AppUI->user_lang); $day_name = $wk[($val - LOCALE_FIRST_DAY) % 7]; if ($locale_char_set == "utf-8" && function_exists("utf8_encode")) { $day_name = utf8_encode($day_name); } return htmlentities($day_name, ENT_COMPAT, $locale_char_set); }
/** * * @global Horde_Prefs $prefs * @param Horde_Date $date * * @return Kronolith_View_Month */ public function __construct(Horde_Date $date) { global $prefs; $this->month = $date->month; $this->year = $date->year; // Need to calculate the start and length of the view. $this->date = new Horde_Date($date); $this->date->mday = 1; $this->_startday = $this->date->dayOfWeek(); $this->_daysInView = Date_Calc::weeksInMonth($this->month, $this->year) * 7; if (!$prefs->getValue('week_start_monday')) { $this->_startOfView = 1 - $this->_startday; // We may need to adjust the number of days in the view if // we're starting weeks on Sunday. if ($this->_startday == Horde_Date::DATE_SUNDAY) { $this->_daysInView -= 7; } $endday = new Horde_Date(array('mday' => Horde_Date_Utils::daysInMonth($this->month, $this->year), 'month' => $this->month, 'year' => $this->year)); $endday = $endday->dayOfWeek(); if ($endday == Horde_Date::DATE_SUNDAY) { $this->_daysInView += 7; } } else { if ($this->_startday == Horde_Date::DATE_SUNDAY) { $this->_startOfView = -5; } else { $this->_startOfView = 2 - $this->_startday; } } $startDate = new Horde_Date(array('year' => $this->year, 'month' => $this->month, 'mday' => $this->_startOfView)); $endDate = new Horde_Date(array('year' => $this->year, 'month' => $this->month, 'mday' => $this->_startOfView + $this->_daysInView)); if ($prefs->getValue('show_shared_side_by_side')) { $allCalendars = Kronolith::listInternalCalendars(); $this->_currentCalendars = array(); foreach ($GLOBALS['calendar_manager']->get(Kronolith::DISPLAY_CALENDARS) as $id) { $this->_currentCalendars[$id] = $allCalendars[$id]; } } else { $this->_currentCalendars = array('internal_0' => true); } try { $this->_events = Kronolith::listEvents($startDate, $endDate); } catch (Exception $e) { $GLOBALS['notification']->push($e, 'horde.error'); $this->_events = array(); } if (!is_array($this->_events)) { $this->_events = array(); } }
public static function getAgo($timestamp) { if ($timestamp === null) { return ''; } $diffdays = Date_Calc::dateDiff(date('j', $timestamp), date('n', $timestamp), date('Y', $timestamp), date('j'), date('n'), date('Y')); /* An error occured. */ if ($diffdays == -1) { return; } $ago = $diffdays * Date_Calc::compareDates(date('j', $timestamp), date('n', $timestamp), date('Y', $timestamp), date('j'), date('n'), date('Y')); if ($ago < -1) { return sprintf(Horde_Model_Translation::t(" (%s days ago)"), $diffdays); } elseif ($ago == -1) { return Horde_Model_Translation::t(" (yesterday)"); } elseif ($ago == 0) { return Horde_Model_Translation::t(" (today)"); } elseif ($ago == 1) { return Horde_Model_Translation::t(" (tomorrow)"); } else { return sprintf(Horde_Model_Translation::t(" (in %s days)"), $diffdays); } }
/** * Validate date and times. Note that this method need the Date_Calc class * * @param string $date Date to validate * @param array $options array options where : * 'format' The format of the date (%d-%m-%Y) * or rfc822_compliant * 'min' The date has to be greater * than this array($day, $month, $year) * or PEAR::Date object * 'max' The date has to be smaller than * this array($day, $month, $year) * or PEAR::Date object * * @return boolean true if valid date/time, false if not * * @access public */ function date($date, $options) { $max = $min = false; $format = ''; if (is_array($options)) { extract($options); } if (strtolower($format) == 'rfc822_compliant') { $preg = '&^(?:(Mon|Tue|Wed|Thu|Fri|Sat|Sun),) \\s+ (?:(\\d{2})?) \\s+ (?:(Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec)?) \\s+ (?:(\\d{2}(\\d{2})?)?) \\s+ (?:(\\d{2}?)):(?:(\\d{2}?))(:(?:(\\d{2}?)))? \\s+ (?:[+-]\\d{4}|UT|GMT|EST|EDT|CST|CDT|MST|MDT|PST|PDT|[A-IK-Za-ik-z])$&xi'; if (!preg_match($preg, $date, $matches)) { return false; } $year = (int) $matches[4]; $months = array('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'); $month = array_keys($months, $matches[3]); $month = (int) $month[0] + 1; $day = (int) $matches[2]; $weekday = $matches[1]; $hour = (int) $matches[6]; $minute = (int) $matches[7]; isset($matches[9]) ? $second = (int) $matches[9] : ($second = 0); if (strlen($year) != 4 || ($day > 31 || $day < 1) || $hour > 23 || $minute > 59 || $second > 59) { return false; } } else { $date_len = strlen($format); for ($i = 0; $i < $date_len; $i++) { $c = $format[$i]; if ($c == '%') { $next = $format[$i + 1]; switch ($next) { case 'j': case 'd': if ($next == 'j') { $day = (int) Validate::_substr($date, 1, 2); } else { $day = (int) Validate::_substr($date, 0, 2); } if ($day < 1 || $day > 31) { return false; } break; case 'm': case 'n': if ($next == 'm') { $month = (int) Validate::_substr($date, 0, 2); } else { $month = (int) Validate::_substr($date, 1, 2); } if ($month < 1 || $month > 12) { return false; } break; case 'Y': case 'y': if ($next == 'Y') { $year = Validate::_substr($date, 4); $year = (int) $year ? $year : ''; } else { $year = (int) (substr(date('Y'), 0, 2) . Validate::_substr($date, 2)); } if (strlen($year) != 4 || $year < 0 || $year > 9999) { return false; } break; case 'g': case 'h': if ($next == 'g') { $hour = Validate::_substr($date, 1, 2); } else { $hour = Validate::_substr($date, 2); } if (!preg_match('/^\\d+$/', $hour) || $hour < 0 || $hour > 12) { return false; } break; case 'G': case 'H': if ($next == 'G') { $hour = Validate::_substr($date, 1, 2); } else { $hour = Validate::_substr($date, 2); } if (!preg_match('/^\\d+$/', $hour) || $hour < 0 || $hour > 24) { return false; } break; case 's': case 'i': $t = Validate::_substr($date, 2); if (!preg_match('/^\\d+$/', $t) || $t < 0 || $t > 59) { return false; } break; default: trigger_error("Not supported char `{$next}' after % in offset " . ($i + 2), E_USER_WARNING); } $i++; } else { //literal if (Validate::_substr($date, 1) != $c) { return false; } } } } // there is remaing data, we don't want it if (strlen($date) && strtolower($format) != 'rfc822_compliant') { return false; } if (isset($day) && isset($month) && isset($year)) { if (!checkdate($month, $day, $year)) { return false; } if (strtolower($format) == 'rfc822_compliant') { if ($weekday != date("D", mktime(0, 0, 0, $month, $day, $year))) { return false; } } if ($min) { include_once 'Date/Calc.php'; if (is_a($min, 'Date') && Date_Calc::compareDates($day, $month, $year, $min->getDay(), $min->getMonth(), $min->getYear()) < 0) { return false; } elseif (is_array($min) && Date_Calc::compareDates($day, $month, $year, $min[0], $min[1], $min[2]) < 0) { return false; } } if ($max) { include_once 'Date/Calc.php'; if (is_a($max, 'Date') && Date_Calc::compareDates($day, $month, $year, $max->getDay(), $max->getMonth(), $max->getYear()) > 0) { return false; } elseif (is_array($max) && Date_Calc::compareDates($day, $month, $year, $max[0], $max[1], $max[2]) > 0) { return false; } } } return true; }
/** * Get a Date object for the weekday before this one * * Get a Date object for the weekday before this one. * The time of the returned Date object is the same as this time. * * @access public * @return object Date Date representing the previous weekday */ function getPrevWeekday() { $day = Date_Calc::prevWeekday($this->day, $this->month, $this->year, "%Y-%m-%d"); $date = sprintf("%s %02d:%02d:%02d", $day, $this->hour, $this->minute, $this->second); $newDate = new Date(); $newDate->setDate($date); return $newDate; }
function showDays() { global $allocated_hours_sum, $end_date, $start_date, $AppUI, $user_list, $user_names, $user_usage, $hideNonWd, $table_header, $table_rows, $df, $working_days_count, $total_hours_capacity, $total_hours_capacity_all; $days_difference = $end_date->dateDiff($start_date); $actual_date = $start_date; $working_days_count = 0; $allocated_hours_sum = 0; $table_header = "<tr><th>" . $AppUI->_("User") . "</th>"; for ($i = 0; $i <= $days_difference; $i++) { if ($actual_date->isWorkingDay() || !$actual_date->isWorkingDay() && !$hideNonWd) { $table_header .= "<th>" . utf8_encode(Date_Calc::getWeekdayAbbrname($actual_date->day, $actual_date->month, $actual_date->year, 3)) . "<br>" . $actual_date->format('%d/%m') . "</th>"; } if ($actual_date->isWorkingDay()) { $working_days_count++; } $actual_date->addDays(1); } $table_header .= "<th nowrap='nowrap' colspan='2'>" . $AppUI->_("Allocated") . "</th></tr>"; $table_rows = ""; foreach ($user_list as $user_id => $user_data) { @($user_names[$user_id] = $user_data["user_username"]); if (isset($user_usage[$user_id])) { $table_rows .= "<tr><td nowrap='nowrap'>(" . $user_data["user_username"] . ") " . $user_data["contact_first_name"] . " " . $user_data["contact_last_name"] . "</td>"; $actual_date = $start_date; for ($i = 0; $i <= $days_difference; $i++) { if ($actual_date->isWorkingDay() || !$actual_date->isWorkingDay() && !$hideNonWd) { $table_rows .= "<td>"; if (isset($user_usage[$user_id][$actual_date->format("%Y%m%d")])) { $hours = number_format($user_usage[$user_id][$actual_date->format("%Y%m%d")], 2); $table_rows .= $hours; $percentage_used = round($hours / dPgetConfig("daily_working_hours") * 100); $bar_color = "blue"; if ($percentage_used > 100) { $bar_color = "red"; $percentage_used = 100; } $table_rows .= "<div style='height:2px;width:{$percentage_used}%; background-color:{$bar_color}'> </div>"; } else { $table_rows .= " "; } $table_rows .= "</td>"; } $actual_date->addDays(1); } $array_sum = array_sum($user_usage[$user_id]); $average_user_usage = number_format($array_sum / ($working_days_count * dPgetConfig("daily_working_hours")) * 100, 2); $allocated_hours_sum += $array_sum; $bar_color = "blue"; if ($average_user_usage > 100) { $bar_color = "red"; $average_user_usage = 100; } $table_rows .= "<td ><div align='left'>" . round($array_sum, 2) . " " . $AppUI->_("hours") . "</td> <td align='right'> " . $average_user_usage; $table_rows .= "%</div>"; $table_rows .= "<div align='left' style='height:2px;width:{$average_user_usage}%; background-color:{$bar_color}'> </div></td>"; $table_rows .= "</tr>"; } } $total_hours_capacity = $working_days_count * dPgetConfig("daily_working_hours") * count($user_usage); $total_hours_capacity_all = $working_days_count * dPgetConfig("daily_working_hours") * count($user_list); }
public function getDuration() { if (isset($this->_duration)) { return $this->_duration; } if ($this->start && $this->end) { $dur_day_match = Date_Calc::dateDiff($this->start->mday, $this->start->month, $this->start->year, $this->end->mday, $this->end->month, $this->end->year); $dur_hour_match = $this->end->hour - $this->start->hour; $dur_min_match = $this->end->min - $this->start->min; while ($dur_min_match < 0) { $dur_min_match += 60; --$dur_hour_match; } while ($dur_hour_match < 0) { $dur_hour_match += 24; --$dur_day_match; } } else { $dur_day_match = 0; $dur_hour_match = 1; $dur_min_match = 0; } $this->_duration = new stdClass(); $this->_duration->day = $dur_day_match; $this->_duration->hour = $dur_hour_match; $this->_duration->min = $dur_min_match; $this->_duration->wholeDay = $this->isAllDay(); return $this->_duration; }
/** * Display a small monthly calendar for the current month. * Dates that have events scheduled are highlighted. * * @param integer $year Year to display, default is current year * @param integer $month Starting month * @return string HTML for calendar page */ function EVLIST_smallmonth($year = 0, $month = 0, $opts = array()) { global $_CONF, $_EV_CONF, $LANG_MONTH, $_SYSTEM; $retval = ''; // Default to the current year if ($year == 0) { $year = date('Y'); } if ($month == 0) { $month = date('m'); } $monthnum_str = sprintf("%02d", (int) $month); // Get all the dates in the period $starting_date = date('Y-m-d', mktime(0, 0, 0, $month, 1, $year)); $ending_date = date('Y-m-d', mktime(23, 59, 59, $month, 31, $year)); $calendarView = Date_Calc::getCalendarMonth($month, $year, '%Y-%m-%d'); $events = EVLIST_getEvents($starting_date, $ending_date, $opts); $T = new Template(EVLIST_PI_PATH . '/templates'); $T->set_file(array('smallmonth' => 'phpblock_month.thtml')); $T->set_var('thisyear', $year); $T->set_var('month', $month); $T->set_var('monthname', $LANG_MONTH[(int) $month]); // Set each day column header to the first letter of the day name $T->set_block('smallmonth', 'daynames', 'nBlock'); $daynames = EVLIST_getDayNames(1); foreach ($daynames as $key => $dayname) { $T->set_var('dayname', $dayname); $T->parse('nBlock', 'daynames', true); } $T->set_block('smallmonth', 'week', 'wBlock'); USES_class_date(); $dt = new Date('now', $_CONF['timezone']); foreach ($calendarView as $weeknum => $weekdata) { list($weekYear, $weekMonth, $weekDay) = explode('-', $weekdata[0]); $T->set_var(array('weekyear' => $weekYear, 'weekmonth' => $weekMonth, 'weekday' => $weekDay)); $T->set_block('smallmonth', 'day', 'dBlock'); foreach ($weekdata as $daynum => $daydata) { list($y, $m, $d) = explode('-', $daydata); $T->clear_var('no_day_link'); if ($daydata == $_EV_CONF['_today']) { $dayclass = 'monthtoday'; } elseif ($m == $monthnum_str) { $dayclass = 'monthon'; } else { $T->set_var('no_day_link', 'true'); $dayclass = 'monthoff'; } $popup = ''; if (isset($events[$daydata])) { // Create the tooltip hover text $daylinkclass = $dayclass == 'monthoff' ? 'nolink-events' : 'day-events'; foreach ($events[$daydata] as $event) { // Show event titles on different lines if more than one if (!empty($popup)) { $popup .= EVLIST_tooltip_newline(); } // Don't show a time for all-day events if ($event['allday'] == 0 && $event['rp_date_start'] == $event['rp_date_end']) { $dt->setTimestamp(strtotime($event['rp_date_start'] . ' ' . $event['rp_time_start1'])); // Time is a localized string, not a timestamp, so // don't adjust for the timezone $popup .= $dt->format($_CONF['timeonly'], false) . ': '; } $popup .= htmlentities($event['title']); } $T->set_var('popup', $popup); } else { $daylinkclass = 'day-noevents'; $T->clear_var('popup'); } $T->set_var(array('daylinkclass' => $daylinkclass, 'dayclass' => $dayclass, 'day' => substr($daydata, 8, 2), 'pi_url' => EVLIST_URL)); $T->parse('dBlock', 'day', true); } $T->parse('wBlock', 'week', true); $T->clear_var('dBlock'); } $T->parse('output', 'smallmonth'); return $T->finish($T->get_var('output')); }
/** * Returns the numeric month from the month name or an abreviation * * Both August and Aug would return 8. * Month name is case insensitive. * * @param string month name * @return integer month number */ function getMonthFromFullName($month) { $month = strtolower($month); $months = Date_Calc::getMonthNames(); while (list($id, $name) = each($months)) { if (ereg($month, strtolower($name))) { return $id; } } return 0; }
/** * Rounds seconds up or down to the nearest specified unit * * @param int $pn_precision number of digits after the decimal point * @param int $pn_day the day of the month * @param int $pn_month the month * @param int $pn_year the year * @param int $pn_hour the hour * @param int $pn_minute the minute * @param mixed $pn_second the second as integer or float * @param bool $pb_countleap whether to count leap seconds (defaults to * DATE_COUNT_LEAP_SECONDS) * * @return array array of year, month, day, hour, minute, second * @access public * @static * @since Method available since Release 1.5.0 */ function roundSeconds($pn_precision, $pn_day, $pn_month, $pn_year, $pn_hour, $pn_minute, $pn_second, $pb_countleap = DATE_COUNT_LEAP_SECONDS) { return Date_Calc::round(DATE_PRECISION_SECOND + $pn_precision, $pn_day, $pn_month, $pn_year, $pn_hour, $pn_minute, $pn_second); }
/** * Returns the number of the day of the week (0=sunday, 1=monday...) * @param int year (2003) * @param int month (9) * @param int day (4) * @return int weekday number * @access protected */ function getDayOfWeek($y, $m, $d) { return Date_Calc::dayOfWeek($d, $m, $y); }
/** * A method to update the summary table from the intermediate tables. * * @param PEAR::Date $oStartDate The start date/time to update from. * @param PEAR::Date $oEndDate The end date/time to update to. * @param array $aActions An array of data types to summarise. Contains * two array, the first containing the data types, * and the second containing the connection type * values associated with those data types, if * appropriate. For example: * array( * 'types' => array( * 0 => 'request', * 1 => 'impression', * 2 => 'click' * ), * 'connections' => array( * 1 => MAX_CONNECTION_AD_IMPRESSION, * 2 => MAX_CONNECTION_AD_CLICK * ) * ) * Note that the order of the items must match * the order of the items in the database tables * (e.g. in data_intermediate_ad and * data_summary_ad_hourly for the above example). * @param string $fromTable The name of the intermediate table to summarise * from (e.g. 'data_intermediate_ad'). * @param string $toTable The name of the summary table to summarise to * (e.g. 'data_summary_ad_hourly'). */ function saveSummary($oStartDate, $oEndDate, $aActions, $fromTable, $toTable) { $aConf = $GLOBALS['_MAX']['CONF']; // Check that there are types to summarise if (empty($aActions['types']) || empty($aActions['connections'])) { return; } // How many days does the start/end period span? $days = Date_Calc::dateDiff($oStartDate->getDay(), $oStartDate->getMonth(), $oStartDate->getYear(), $oEndDate->getDay(), $oEndDate->getMonth(), $oEndDate->getYear()); if ($days == 0) { // Save the data $this->_saveSummary($oStartDate, $oEndDate, $aActions, $fromTable, $toTable); } else { // Save each day's data separately for ($counter = 0; $counter <= $days; $counter++) { if ($counter == 0) { // This is the first day $oInternalStartDate = new Date(); $oInternalStartDate->copy($oStartDate); $oInternalEndDate = new Date($oStartDate->format('%Y-%m-%d') . ' 23:59:59'); } elseif ($counter == $days) { // This is the last day $oInternalStartDate = new Date($oEndDate->format('%Y-%m-%d') . ' 00:00:00'); $oInternalEndDate = new Date(); $oInternalEndDate->copy($oEndDate); } else { // This is a day in the middle $oDayDate = new Date(); $oDayDate->copy($oStartDate); $oDayDate->addSeconds(SECONDS_PER_DAY * $counter); $oInternalStartDate = new Date($oDayDate->format('%Y-%m-%d') . ' 00:00:00'); $oInternalEndDate = new Date($oDayDate->format('%Y-%m-%d') . ' 23:59:59'); } $this->_saveSummary($oInternalStartDate, $oInternalEndDate, $aActions, $fromTable, $toTable); } } }
/** * Returns textual representation of the next day of week of the decorated calendar object * @param object subclass of Calendar e.g. Calendar_Month * @param string (optional) format of returned months (one,two,short or long) * @return string * @access public * @static */ function nextDayName($Calendar, $format = 'long') { $days = Calendar_Util_Textual::weekdayNames($format); $stamp = $Calendar->nextDay('timestamp'); $cE = $Calendar->getEngine(); require_once 'Date/Calc.php'; $day = Date_Calc::dayOfWeek($cE->stampToDay($stamp), $cE->stampToMonth($stamp), $cE->stampToYear($stamp)); return $days[$day]; }
/** * Compares two dates * * @param int $day1 the day of the month * @param int $month1 the month * @param int $year1 the year. Use the complete year instead of the * abbreviated version. E.g. use 2005, not 05. * Do not add leading 0's for years prior to 1000. * @param int $day2 the day of the month * @param int $month2 the month * @param int $year2 the year. Use the complete year instead of the * abbreviated version. E.g. use 2005, not 05. * Do not add leading 0's for years prior to 1000. * * @return int 0 if the dates are equal. 1 if date 1 is later, -1 if * date 1 is earlier. * * @access public * @static */ function compareDates($day1, $month1, $year1, $day2, $month2, $year2) { $ndays1 = Date_Calc::dateToDays($day1, $month1, $year1); $ndays2 = Date_Calc::dateToDays($day2, $month2, $year2); if ($ndays1 == $ndays2) { return 0; } return $ndays1 > $ndays2 ? 1 : -1; }
/** * Determines julian date of the given season * Adapted from previous work in Java by James Mark Hamilton, mhamilton@qwest.net * * @author Robert Butler <*****@*****.**> * * @param string is VERNALEQUINOX, SUMMERSOLSTICE, AUTUMNALEQUINOX, or WINTERSOLSTICE. * @param string year in format CCYY, must be a calendar year between -1000BC and 3000AD. * * @access public * * @return float $juliandate */ function dateSeason($season, $year = '') { if ($year == '') { $year = Date_Calc::dateNow('%Y'); } if ($year >= -1000 && $year <= 1000) { $y = $year / 1000.0; if ($season == "VERNALEQUINOX") { $juliandate = (((-0.00071 * $y - 0.00111) * $y + 0.06134) * $y + 365242.1374) * $y + 1721139.29189; } else { if ($season == "SUMMERSOLSTICE") { $juliandate = (((0.00025 * $y + 0.00907) * $y - 0.05323) * $y + 365241.72562) * $y + 1721233.25401; } else { if ($season == "AUTUMNALEQUINOX") { $juliandate = (((0.00074 * $y - 0.00297) * $y - 0.11677) * $y + 365242.49558) * $y + 1721325.70455; } else { if ($season == "WINTERSOLSTICE") { $juliandate = (((-6.0E-5 * $y - 0.00933) * $y - 0.00769) * $y + 365242.88257) * $y + 1721414.39987; } } } } } elseif ($year > 1000 && $year <= 3000) { $y = ($year - 2000) / 1000; if ($season == "VERNALEQUINOX") { $juliandate = (((-0.00057 * $y - 0.00411) * $y + 0.05169) * $y + 365242.37404) * $y + 2451623.80984; } else { if ($season == "SUMMERSOLSTICE") { $juliandate = (((-0.0003 * $y + 0.008880000000000001) * $y + 0.00325) * $y + 365241.62603) * $y + 2451716.56767; } else { if ($season == "AUTUMNALEQUINOX") { $juliandate = (((0.00078 * $y + 0.00337) * $y - 0.11575) * $y + 365242.01767) * $y + 2451810.21715; } else { if ($season == "WINTERSOLSTICE") { $juliandate = (((0.00032 * $y - 0.008229999999999999) * $y - 0.06223) * $y + 365242.74049) * $y + 2451900.05952; } } } } } return $juliandate; }
*/ define('DATE_CALC_BEGIN_WEEKDAY', 1); require_once "Date/Calc.php"; /** * Test dates from 1970 to 2029 * Data from: http://www.merlyn.demon.co.uk/wknotest.txt * Others usefull datas available from: * http://www.merlyn.demon.co.uk/#dat */ $datapath = dirname(__FILE__); $failed_test_data = false; $dates = file($datapath . '/weeksinmonth_4_monday.txt'); $cnt = sizeof($dates); $valids = array(); for ($i = 0; $i < $cnt; $i++) { $parts = explode('/', $dates[$i]); $valids[$parts[0]] = array($parts[1] => (int) str_replace("\n", '', $parts[2])); } unset($dates); foreach ($valids as $year => $months) { foreach ($months as $month => $valid_weeks) { $calc_weeks = Date_Calc::weeksInMonth($month, $year); if ($calc_weeks != $valid_weeks) { $failed_test_data = true; echo "Bug #727, pass 1: {$year}/{$month} failed. Expect:{$valid_weeks} Got:{$calc_weeks}\n"; } } } if (!$failed_test_data) { echo "Bug #727, pass 1: OK\n"; }
/** * Utility function to return an array of events with a period * @param Date Start date of the period * @param Date End date of the period * @return array A list of events */ function getEventsForPeriod($start_date, $end_date, $filter = 'all', $user_id = null, $project_id = 0) { global $AppUI; // the event times are stored as unix time stamps, just to be different // convert to default db time stamp $db_start = $start_date->format(FMT_DATETIME_MYSQL); $db_end = $end_date->format(FMT_DATETIME_MYSQL); if (!isset($user_id)) { $user_id = $AppUI->user_id; } $project =& new CProject(); if ($project_id) { $p =& $AppUI->acl(); if ($p->checkModuleItem('projects', 'view', $project_id, $user_id)) { $allowedProjects = array('p.project_id = ' . $project_id); } else { $allowedProjects = array('1=0'); } } else { $allowedProjects = $project->getAllowedSQL($user_id, 'event_project'); } //do similiar actions for recurring and non-recurring events $queries = array('q' => 'q', 'r' => 'r'); foreach ($queries as $query_set) { ${$query_set} = new DBQuery(); ${$query_set}->addTable('events', 'e'); ${$query_set}->addQuery('e.*'); ${$query_set}->addOrder('e.event_start_date, e.event_end_date ASC'); ${$query_set}->addJoin('projects', 'p', 'p.project_id = e.event_project'); if ($AppUI->getState('CalIdxCompany')) { ${$query_set}->addWhere('project_company = ' . $AppUI->getState('CalIdxCompany')); } if (count($allowedProjects)) { ${$query_set}->addWhere('((' . implode(' AND ', $allowedProjects) . ') ' . ($AppUI->getState('CalIdxCompany') ? '' : $project_id ? '' : ' OR event_project = 0 ') . ')'); } switch ($filter) { case 'my': ${$query_set}->addJoin('user_events', 'ue', 'ue.event_id = e.event_id AND ue.user_id =' . $user_id); ${$query_set}->addWhere('(ue.user_id = ' . $user_id . ') AND (event_private=0 OR event_owner=' . $user_id . ')'); break; case 'own': ${$query_set}->addWhere('event_owner =' . $user_id); break; case 'all': ${$query_set}->addWhere('(event_private=0 OR event_owner=' . $user_id . ')'); break; } if ($query_set == 'q') { // assemble query for non-recursive events ${$query_set}->addWhere('(event_recurs <= 0)'); // following line is only good for *non-recursive* events ${$query_set}->addWhere("(event_start_date <= '{$db_end}' AND event_end_date >= '{$db_start}' " . "OR event_start_date BETWEEN '{$db_start}' AND '{$db_end}')"); $eventList = ${$query_set}->loadList(); } else { if ($query_set == 'r') { // assemble query for recursive events ${$query_set}->addWhere('(event_recurs > 0)'); $eventListRec = ${$query_set}->loadList(); } } } //Calculate the Length of Period (Daily, Weekly, Monthly View) setlocale(LC_TIME, 'en_AU'); $periodLength = Date_Calc::dateDiff($start_date->getDay(), $start_date->getMonth(), $start_date->getYear(), $end_date->getDay(), $end_date->getMonth(), $end_date->getYear()); setlocale(LC_ALL, $AppUI->user_lang); // AJD: Should this be going off the end of the array? I don't think so. // If it should then a comment to that effect would be nice. // for ($i=0; $i < sizeof($eventListRec)+1; $i++) { for ($i = 0, $sz = sizeof($eventListRec); $i < $sz; $i++) { //note from merlinyoda: j=0 is the original event according to getRecurrentEventforPeriod // So, since the event is *recurring* x times, the loop condition should be j <= x, not j < x. // This way the original and all recurrances are covered. //for ($j=0; $j < intval($eventListRec[$i]['event_times_recuring']); $j++) { for ($j = 0, $end = intval($eventListRec[$i]['event_times_recuring']); $j < $end; $j++) { if ($periodLength == 1) { // Daily View: show all $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] == 1 && $j == 0) { // Weekly or Monthly View and Hourly Recurrent Events: show one time and add string 'hourly' $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); $eventListRec[$i]['event_title'] = $eventListRec[$i]['event_title'] . ' (' . $AppUI->_('Hourly') . ')'; } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] > 1) { //Weekly and Monthly View and higher recurrence mode: show all events of recurrence > 1 $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } //add values to the eventsArray if check for recurrent event was positive if (sizeof($recEventDate) > 0) { $eList[0] = $eventListRec[$i]; $eList[0]['event_start_date'] = $recEventDate[0]->format(FMT_DATETIME_MYSQL); $eList[0]['event_end_date'] = $recEventDate[1]->format(FMT_DATETIME_MYSQL); $eventList = array_merge($eventList, $eList); } // clear array of positive recurrent events for the case that next loop recEventDate is empty in order to avoid double display $recEventDate = array(); } } //return a list of non-recurrent and recurrent events return $eventList; }
/** * Utility function to return an array of events with a period * @param Date Start date of the period * @param Date End date of the period * @return array A list of events */ function getEventsForPeriod($start_date, $end_date, $filter = 'all', $user_id = null) { global $AppUI; // the event times are stored as unix time stamps, just to be different // convert to default db time stamp $db_start = $start_date->format(FMT_DATETIME_MYSQL); $db_end = $end_date->format(FMT_DATETIME_MYSQL); if (!isset($user_id)) { $user_id = $AppUI->user_id; } $project =& new CProject(); $allowedProjects = $project->getAllowedSQL($user_id, 'event_project'); $q = new DBQuery(); $q->addTable('events', 'e'); $q->addQuery('e.*'); if (count($allowedProjects)) { $q->addWhere('( ( ' . implode(' AND ', $allowedProjects) . ") OR event_project = 0 )"); $q->addJoin('projects', 'p', 'p.project_id = e.event_project'); } switch ($filter) { case 'my': $q->addJoin('user_events', 'ue', 'ue.event_id = e.event_id AND ue.user_id =' . $user_id); $q->addWhere("( ( event_private = 0 AND ue.user_id = {$user_id} )\n\t\t\t\t\t\tOR event_owner={$user_id} )"); break; case 'own': $q->addWhere("( event_owner = {$user_id} )"); break; case 'all': $q->addWhere("( event_private=0 OR (event_private=1 AND event_owner={$user_id}) )"); break; } $q->addWhere("( event_start_date <= '{$db_end}' AND event_end_date >= '{$db_start}'\n\t\t\t\tOR event_start_date BETWEEN '{$db_start}' AND '{$db_end}')"); // duplicate query object for recursive events; $r = $q; // assemble query for non-recursive events $q->addWhere('( event_recurs <= 0 )'); $eventList = $q->loadList(); // assemble query for recursive events $r->addWhere('( event_recurs > 0 )'); $eventListRec = $r->loadList(); //Calculate the Length of Period (Daily, Weekly, Monthly View) $periodLength = Date_Calc::dateDiff($start_date->getDay(), $start_date->getMonth(), $start_date->getYear(), $end_date->getDay(), $end_date->getMonth(), $end_date->getYear()); // AJD: Should this be going off the end of the array? I don't think so. // If it should then a comment to that effect would be nice. // for ($i=0; $i < sizeof($eventListRec)+1; $i++) { for ($i = 0; $i < sizeof($eventListRec); $i++) { for ($j = 0; $j < intval($eventListRec[$i]['event_times_recuring']); $j++) { //Daily View //show all if ($periodLength == 1) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] == 1 && $j == 0) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); $eventListRec[$i]['event_title'] = $eventListRec[$i]['event_title'] . " (" . $AppUI->_('Hourly') . ")"; } elseif ($periodLength > 1 && $eventListRec[$i]['event_recurs'] > 1) { $recEventDate = CEvent::getRecurrentEventforPeriod($start_date, $end_date, $eventListRec[$i]['event_start_date'], $eventListRec[$i]['event_end_date'], $eventListRec[$i]['event_recurs'], $eventListRec[$i]['event_times_recuring'], $j); } //add values to the eventsArray if check for recurrent event was positive if (sizeof($recEventDate) > 0) { $eList[0] = $eventListRec[$i]; $eList[0]['event_start_date'] = $recEventDate[0]->format(FMT_DATETIME_MYSQL); $eList[0]['event_end_date'] = $recEventDate[1]->format(FMT_DATETIME_MYSQL); $eventList = array_merge($eventList, $eList); } // clear array of positive recurrent events for the case that next loop recEventDate is empty in order to avoid double display $recEventDate = array(); } } //return a list of non-recurrent and recurrent events return $eventList; }
/** * 指定された年月にメッセージを送受信した日のリストを返す */ function db_message_is_message_list4date($u, $year, $month, $box) { include_once 'Date/Calc.php'; if ($box == 'inbox' || !$box) { $where = "c_member_id_to = ?" . " AND is_deleted_to = 0" . " AND is_send = 1"; } elseif ($box == 'outbox') { $where = "c_member_id_from = ?" . " AND is_deleted_from = 0" . " AND is_send = 1"; } else { return null; } if ($GLOBALS['_OPENPNE_DSN_LIST']['main']['dsn']['phptype'] == 'pgsql') { $sql = "SELECT DISTINCT date_part('day', r_datetime) FROM c_message" . " WHERE {$where}" . ' AND is_send=1 AND r_datetime >= ? AND r_datetime < ?'; } else { $sql = 'SELECT DISTINCT DAYOFMONTH(r_datetime) FROM c_message' . " WHERE {$where}" . ' AND is_send=1 AND r_datetime >= ? AND r_datetime < ?'; } $date_format = '%Y-%m-%d 00:00:00'; $thismonth = Date_Calc::beginOfMonth($month, $year, $date_format); $nextmonth = Date_Calc::beginOfNextMonth(0, $month, $year, $date_format); $params = array(intval($u), $thismonth, $nextmonth); return db_get_col($sql, $params); }
/** * How many whole days are covered by the range? * * @return int The number of whole days covered by the range. */ function countDays() { $start = $this->getStartDate(); $end = $this->getEndDate(); $days = Date_Calc::dateDiff($start->getDay(), $start->getMonth(), $start->getYear(), $end->getDay(), $end->getMonth(), $end->getYear()); return $days; }
/** * Set the span from the elapsed time between two dates * * The time span is unsigned, so the date's order is not important. * * @param object $date1 first Date * @param object $date2 second Date * * @return bool true on success * @access public */ function setFromDateDiff($date1, $date2) { if (!is_a($date1, 'date') or !is_a($date2, 'date')) { return false; } $date1->toUTC(); $date2->toUTC(); if ($date1->after($date2)) { list($date1, $date2) = array($date2, $date1); } $days = Date_Calc::dateDiff($date1->getDay(), $date1->getMonth(), $date1->getYear(), $date2->getDay(), $date2->getMonth(), $date2->getYear()); $hours = $date2->getHour() - $date1->getHour(); $mins = $date2->getMinute() - $date1->getMinute(); $secs = $date2->getSecond() - $date1->getSecond(); $this->setFromSeconds($days * 86400 + $hours * 3600 + $mins * 60 + $secs); return true; }
function showWeeks() { global $allocated_hours_sum, $end_date, $start_date, $AppUI, $user_list, $user_names, $user_usage, $hideNonWd, $table_header, $table_rows, $df, $working_days_count, $total_hours_capacity, $total_hours_capacity_all; $working_days_count = 0; $allocated_hours_sum = 0; $ed = new CDate(Date_Calc::endOfWeek($end_date->day, $end_date->month, $end_date->year)); $sd = new CDate(Date_Calc::beginOfWeek($start_date->day, $start_date->month, $start_date->year)); $week_difference = ceil($ed->workingDaysInSpan($sd) / count(explode(",", dPgetConfig("cal_working_days")))); $actual_date = $sd; $table_header = "<tr><th>" . $AppUI->_("User") . "</th>"; for ($i = 0; $i < $week_difference; $i++) { //$table_header .= "<th>".Date_Calc::weekOfYear($actual_date->day, $actual_date->month, $actual_date->year)."<br><table><td style='font-weight:normal; font-size:70%'>".$actual_date->format( $df )."</td></table></th>"; $actual_date->addSeconds(168 * 3600); // + one week $working_days_count = $working_days_count + count(explode(",", dPgetConfig("cal_working_days"))); } $table_header .= "<th nowrap='nowrap' colspan='2'>" . $AppUI->_("Allocated") . "</th></tr>"; $table_rows = ""; foreach ($user_list as $user_id => $user_data) { @($user_names[$user_id] = $user_data["user_username"]); if (isset($user_usage[$user_id])) { $table_rows .= "<tr><td nowrap='nowrap'>(" . $user_data["user_username"] . ") " . $user_data["contact_first_name"] . " " . $user_data["contact_last_name"] . "</td>"; $actual_date = $sd; /* for($i=0; $i<$week_difference; $i++){ $awoy = $actual_date->year.Date_Calc::weekOfYear($actual_date->day,$actual_date->month,$actual_date->year); $table_rows .= "<td align='right'>"; if(isset($user_usage[$user_id][$awoy])){ $hours = number_format($user_usage[$user_id][$awoy],2); $table_rows .= $hours; $percentage_used = round(($hours/(dPgetConfig("daily_working_hours")*count(explode(",",dPgetConfig("cal_working_days")))) )*100); $bar_color = "blue"; if($percentage_used > 100){ $bar_color = "red"; $percentage_used = 100; } $table_rows .= "<div style='height:2px;width:$percentage_used%; background-color:$bar_color'> </div>"; } else { $table_rows .= " "; } $table_rows .= "</td>"; $actual_date->addSeconds(168*3600); // + one week } */ $array_sum = array_sum($user_usage[$user_id]); $average_user_usage = number_format($array_sum / ($week_difference * count(explode(",", dPgetConfig("cal_working_days"))) * dPgetConfig("daily_working_hours")) * 100, 2); $allocated_hours_sum += $array_sum; $bar_color = "blue"; if ($average_user_usage > 100) { $bar_color = "red"; $average_user_usage = 100; } $table_rows .= "<td ><div align='left'>" . round($array_sum, 2) . " " . $AppUI->_("hours") . "</td> <td align='right'> " . $average_user_usage; $table_rows .= "%</div>"; $table_rows .= "<div align='left' style='height:2px;width:{$average_user_usage}%; background-color:{$bar_color}'> </div></td>"; $table_rows .= "</tr>"; } } /* $total_hours_capacity = $week_difference * count(explode(",",dPgetConfig("cal_working_days"))) * dPgetConfig("daily_working_hours") * count($user_usage); $total_hours_capacity_all = $week_difference * count(explode(",",dPgetConfig("cal_working_days"))) *dPgetConfig("daily_working_hours") * count($user_list); */ $total_hours_capacity = $working_days_count / 2 * dPgetConfig("daily_working_hours") * count($user_usage); $total_hours_capacity_all = $working_days_count / 2 * dPgetConfig("daily_working_hours") * count($user_list); }