/**
  * @return array(Todays events view, Todo view).
  */
 private function _GetMiniCalendars()
 {
     $this->load->library('academic_calendar');
     $this->load->library('calendar_backend');
     $this->load->library('calendar_source_my_calendar');
     $this->load->library('calendar_frontend');
     $this->load->library('calendar_view_upcoming');
     $this->load->library('calendar_view_todo_list');
     $now = new Academic_time(time());
     $start = $now;
     $end = $now->Midnight()->Adjust('+2day');
     $sources = new CalendarSourceMyCalendar();
     // lets be explicit just in case:
     $sources->EnableGroup('owned');
     $sources->EnableGroup('subscribed');
     $sources->EnableGroup('private');
     $sources->EnableGroup('active');
     $sources->DisableGroup('inactive');
     $sources->SetRange($start->Timestamp(), $end->Timestamp());
     $sources->SetTodoRange(time(), time());
     $calendar_data = new CalendarData();
     $this->messages->AddMessages($calendar_data->FetchEventsFromSources($sources));
     // Display data
     $this->load->library('calendar_view_days');
     $EventsView = new CalendarViewUpcoming();
     $EventsView->SetMiniMode();
     $EventsView->SetCalendarData($calendar_data);
     //$EventsView->SetStartEnd($start->Timestamp(), $end->Timestamp());
     $TodoView = NULL;
     // 		$TodoView = new CalendarViewTodoList();
     // 		$TodoView->SetCalendarData($calendar_data);
     return array($EventsView, $TodoView);
 }
 /**
  * @brief Default constructor.
  */
 function __construct()
 {
     parent::__construct('frames/public_frame.php');
     $this->mDataArray['description'] = '';
     $this->mDataArray['keywords'] = '';
     $this->mTitleSet = FALSE;
     $this->mDataArray['login'] = array('logged_in' => FALSE);
     $CI =& get_instance();
     if ($CI->user_auth->isLoggedIn) {
         $this->mDataArray['login']['logged_in'] = TRUE;
         $this->mDataArray['login']['username'] = $entity_id = $CI->user_auth->username;
     }
     $this->mDataArray['uri'] = $CI->uri->uri_string();
     $CI->load->library('academic_calendar');
     $academic_time = new Academic_time(mktime());
     $this->mDataArray['date'] = array('time' => date('H:i'), 'day' => date('l'), 'week' => $academic_time->AcademicWeek(), 'date' => date('jS'), 'month' => date('F'));
     $CI->load->model('ticker_model');
     $this->mDataArray['ticker'] = $CI->ticker_model->getNews();
     // Get user's Links
     $CI->load->model('links_model');
     if ($CI->user_auth->isLoggedIn) {
         $this->mDataArray['links'] = $CI->links_model->GetFormattedLinks($CI->user_auth->entityId);
     } else {
         $this->mDataArray['links'] = $CI->links_model->GetFormattedLinks(0);
     }
 }
 /**
  * @param $Keys array with keys 'userid', 'occid'.
  */
 function __construct($Keys, $Extra = NULL)
 {
     parent::__construct(self::$notTypeInfo, $Keys);
     if (NULL !== $Extra) {
         $start = new Academic_time($Extra['start_time']);
         $when = $start->Format('%D');
         if ($Extra['time_associated']) {
             $when = $start->Format('%T') . ", {$when}";
         }
         $CI =& get_instance();
         $this->SetData('Custom', '<p>Summary: <strong><a href="' . site_url($Extra['link']) . $CI->uri->uri_string() . '">' . xml_escape($Extra['name']) . '</a></strong><br />' . '<div class="Date" style="display:inline;">' . $when . '</div></p>');
     }
 }
/**
 * @param $Date &Academic_time Start time of day.
 * @return array[string] Class names.
 */
function CalCssGetDateClasses(&$day_start, $day_of_week, $past = NULL)
{
    $today = Academic_time::NewToday();
    $today_id = $today->Format('Ymd');
    $cell_id = $day_start->Format('Ymd');
    $classes_list = array();
    if ($cell_id == $today_id) {
        $classes_list[] = 'tod';
    }
    if ($day_start->Month() % 2 == 0) {
        $classes_list[] = 'ev';
    }
    if (($day_of_week + 6) % 7 > 4) {
        $classes_list[] = 'we';
    }
    if (NULL === $past && $day_start->Timestamp() < $today->Timestamp() || true === $past) {
        $classes_list[] = 'pa';
    }
    return $classes_list;
}
 private function _fillTipsFeed($category_id = null, $limit = 20)
 {
     $this->load->library('academic_calendar');
     $channel =& $this->main_frame->Channel();
     $channel->SetImage('http://' . $_SERVER['HTTP_HOST'] . '/images/crosswords/xw.png', 64, 64);
     $channel->SetEditor('crosswords@theyorker.co.uk (crosswords editor)');
     $channel->SetWebmaster('webmaster@theyorker.co.uk (webmaster)');
     $tips = $this->crosswords_model->GetTips($category_id, null, null, true);
     $url = 'http://' . $_SERVER['HTTP_HOST'];
     foreach ($tips as &$tip) {
         $item =& $channel->NewItem();
         $item->SetPublicationDate($tip['publication']);
         $pub = new Academic_time($tip['publication']);
         $pub_str = $pub->Format('D ') . $pub->AcademicTermNameUnique() . ' week ' . $pub->AcademicWeek();
         $title = '(' . $tip['category_name'] . ') ' . $pub_str;
         $item->SetTitle($title);
         $item->AddCategory($tip['category_name']);
         $item->SetLink($url . '/crosswords/' . (int) $tip['crossword_id'] . '#tip' . (int) $tip['id']);
         $item->SetDescription($tip['content_xhtml']);
     }
 }
    /**
     *	@param	$NumToGet	int	Number of comments to return
     *	@author	Chris Travis (cdt502 - ctravis@gmail.com)
     */
    function GetLatestComments($NumToGet = 10)
    {
        $ci =& get_instance();
        $ci->load->model('crosswords_model');
        $ci->load->library('academic_calendar');
        $article_sql = 'SELECT	comments.comment_id,
						comments.comment_anonymous,
						UNIX_TIMESTAMP(comments.comment_post_time) AS comment_post_time,
						comments.comment_content_wikitext,
						users.user_firstname,
						users.user_surname,
						article_contents.article_content_heading AS heading,
						UNIX_TIMESTAMP(articles.article_publish_date) AS publication,
					(	SELECT		COUNT(*)
						FROM		comments AS article_comments
						WHERE		article_comments.comment_comment_thread_id = comments.comment_comment_thread_id
						AND			article_comments.comment_post_time <= comments.comment_post_time
					)	AS article_comment_count,
						1 AS source
				FROM	articles,
						comments,
						users,
						article_contents,
						content_types
				WHERE	comments.comment_deleted = 0
				AND		comments.comment_comment_thread_id = articles.article_public_comment_thread_id
				AND		articles.article_publish_date < CURRENT_TIMESTAMP
				AND		articles.article_pulled = 0
				AND		articles.article_deleted = 0
				AND		articles.article_live_content_id IS NOT NULL
				AND		articles.article_live_content_id = article_contents.article_content_id
				AND		articles.article_content_type_id = content_types.content_type_id
				AND		comments.comment_author_entity_id = users.user_entity_id';
        $crossword_sql = 'SELECT	comments.comment_id,
						comments.comment_anonymous,
						UNIX_TIMESTAMP(comments.comment_post_time) AS comment_post_time,
						comments.comment_content_wikitext,
						users.user_firstname,
						users.user_surname,
						crossword_categories.crossword_category_name AS heading,
						UNIX_TIMESTAMP(crosswords.crossword_publication) AS publication,
					(	SELECT		COUNT(*)
						FROM		comments AS article_comments
						WHERE		article_comments.comment_comment_thread_id = comments.comment_comment_thread_id
						AND			article_comments.comment_post_time <= comments.comment_post_time
					)	AS article_comment_count,
						2 AS source
				FROM	comments
				INNER JOIN	users
					ON		users.user_entity_id = comments.comment_author_entity_id
				INNER JOIN	crosswords
					ON		comments.comment_comment_thread_id = crosswords.crossword_public_comment_thread_id
					AND		' . $ci->crosswords_model->published_sql . '
					AND		' . $ci->crosswords_model->expired_sql . '
				INNER JOIN	crossword_categories
					ON		crossword_categories.crossword_category_id = crosswords.crossword_category_id
				WHERE	comments.comment_deleted = 0';
        $sql = "({$article_sql}) UNION ({$crossword_sql})\n\t\t\t\tORDER BY comment_post_time DESC\n\t\t\t\tLIMIT\t0, ?";
        $query = $this->db->query($sql, array($NumToGet));
        $results = $query->result_array();
        foreach ($results as &$result) {
            if ($result['source'] == 2) {
                $pub = new Academic_time($result['publication']);
                $pub_date = $pub->Format('D') . ' week ' . $pub->AcademicWeek();
                $result['heading'] = $result['heading'] . ', ' . $pub_date;
            }
        }
        return $results;
    }
 function ajax_termdates()
 {
     OutputModes('ajax');
     if (!CheckPermissions('public')) {
         return;
     }
     $error = false;
     $years = array();
     if (isset($_GET['years'])) {
         $year_ranges = split(',', $_GET['years']);
         foreach ($year_ranges as $year_range) {
             if ($year_range === '') {
                 continue;
             }
             $ends = split('-', $year_range);
             if (count($ends) > 2) {
                 $this->main_frame->Error(array('class' => 'error', 'text' => 'Invalid year range: ' . $year_range));
                 $error = true;
             } else {
                 if (count($ends) == 1) {
                     $ends = array($year_range, $year_range);
                 }
                 $range_error = false;
                 foreach ($ends as &$end) {
                     if (is_numeric($end) && $end >= 1970 && $end < 2037) {
                         $end = (int) $end;
                     } else {
                         $this->main_frame->Error(array('class' => 'error', 'text' => 'Invalid year: ' . $end));
                         $range_error = true;
                     }
                 }
                 if (!$range_error) {
                     for ($year = $ends[0]; $year <= $ends[1]; ++$year) {
                         $years[] = $year;
                     }
                 } else {
                     $error = true;
                 }
             }
         }
     }
     if (!$error) {
         $root = array('_tag' => 'calendar', 'termdates' => array());
         foreach ($years as $year) {
             $acyear = array('_tag' => 'academicyear', '_attr' => array('year' => $year));
             for ($term = 0; $term < 6; ++$term) {
                 $start_ts = Academic_time::StartOfAcademicTerm($year, $term);
                 $monday_ts = Academic_time::MondayWeek1OfAcademicTerm($year, $term);
                 $start = new Academic_time($start_ts);
                 $days = Academic_time::LengthOfAcademicTerm($year, $term);
                 $end = $start->Adjust($days . 'days');
                 $monday = new Academic_time($monday_ts);
                 $acterm = array('_tag' => 'term', '_attr' => array('id' => "term_{$year}_{$term}", 'term' => $term), 'type' => $start->AcademicTermTypeName(), 'name' => $start->AcademicTermName(), 'unique' => $start->AcademicTermNameUnique(), 'start' => $start->Format('Y-m-d'), 'end' => $end->Format('Y-m-d'), 'days' => $days, 'mondayweek1' => $monday->Format('Y-m-d'), 'weeks' => $start->AcademicTermWeeks());
                 $acyear[] = $acterm;
             }
             $root['termdates'][] = $acyear;
         }
         $this->main_frame->SetXml($root);
     }
     $this->main_frame->Load();
 }
<a href="<?php 
    echo site_url('crosswords/' . $crossword['id']);
    ?>
"><?php 
    ?>
<img alt="" src="<?php 
    echo site_url('crosswords/' . $crossword['id'] . '/preview');
    ?>
" /><?php 
    ?>
</a><?php 
    ?>
</div><?php 
    // Find if crossword is "new"
    $now = new Academic_time(time());
    $since_publication = Academic_time::Difference($pub, $now, array('days'));
    if (!$crossword['expired'] || $since_publication['days'] < 7) {
        ?>
<div class="crossword_new">new!</div><?php 
    }
    // Title and details
    ?>
<div class="crossword_title"><?php 
    ?>
<a href="<?php 
    echo site_url('crosswords/' . $crossword['id']);
    ?>
"><?php 
    echo $pub->Format('D ') . $pub->AcademicTermNameUnique() . ' week ' . $pub->AcademicWeek();
    ?>
</a><?php 
 function GetWeeks(&$sources, $DateRange = NULL, $Filter = NULL, $Format = 'ac:re')
 {
     $CI =& get_instance();
     // Read date range
     $range = $CI->date_uri->ReadUri($DateRange, TRUE);
     $now = new Academic_time(time());
     if ($range['valid']) {
         $start = $range['start'];
         $end = $range['end'];
     } else {
         $start = $now->BackToMonday();
         $end = $start->Adjust('4weeks');
     }
     $sources->SetRange($start->Timestamp(), $end->Timestamp());
     $this->ReadFilter($sources, $Filter);
     $calendar_data = new CalendarData();
     $CI->messages->AddMessages($sources->FetchEvents($calendar_data));
     // Display data
     $CI->load->library('calendar_view_weeks');
     $weeks = new CalendarViewWeeks();
     $weeks->SetCalendarData($calendar_data);
     $weeks->SetStartEnd($start->Timestamp(), $end->Timestamp());
     $weeks->SetRangeUrl($this->mRangeUrl, $Format, NULL !== $Filter ? '/' . $Filter : '');
     $weeks->SetCategories($this->mCategories);
     $data = array('Filters' => $this->GetFilters($sources), 'ViewMode' => $weeks, 'RangeDescription' => $range['description'], 'ReadOnly' => $this->mReadOnly, 'Path' => $this->mPaths);
     $this->SetupTabs('weeks', $start, $Filter);
     return new FramesView('calendar/my_calendar', $data);
 }
 /**
  * @brief Perform tests on the academic calendar functions.
  * @return The number of errors detected.
  *
  * Runs through every day in the academic calendar checking that the term
  * number and week number functions are correct and that days are
  * consecutive when calculated using Academic_calendar::Academic.
  */
 function PerformTests()
 {
     // Store the previous date so can see how many days have elapsed
     $prev_date = 0;
     $errors = 0;
     // Go through academic years
     for ($year = 2004; $year < 2012; ++$year) {
         // Go through all 6 academic terms
         for ($term_counter = 0; $term_counter < 6; ++$term_counter) {
             // Go through every week in the term
             $term_days = Academic_time::LengthOfAcademicTerm($year, $term_counter);
             $term_day = 0;
             $dow_counter = Academic_time::DayOfStartOfAcademicTerm($year, $term_counter) + 1;
             for ($week_counter = 1; $term_day < $term_days; ++$week_counter) {
                 // Go through every day in the week
                 for ($dow_counter = $dow_counter; $dow_counter <= 7 && $term_day < $term_days; ++$dow_counter) {
                     // Create a date object from academic year/term/week/day_of_week
                     $actime = $this->Academic($year, $term_counter, $week_counter, $dow_counter);
                     // Create a date object from academic year/term/day_of_term
                     $actime2 = $this->AcademicDayOfTerm($year, $term_counter, $term_day);
                     // Detect any inconsistencies
                     $error_detected = FALSE;
                     // Do Academic and AcademicDayOfTerm give the same result?
                     if ($actime != $actime2) {
                         echo '!!Academic and AcademicDayOfTerm give different results!!<br/>';
                         ++$errors;
                         $error_detected = TRUE;
                     }
                     // Has more than one day elapsed?
                     if (0 !== $prev_date && 1 !== Academic_time::DaysBetweenTimestamps($prev_date->Timestamp(), $actime->Timestamp())) {
                         echo '!!days not consecutive!!<br/>';
                         ++$errors;
                         $error_detected = TRUE;
                     }
                     // Is the calculated academic year consistent?
                     if ($year != $actime->AcademicYear()) {
                         echo '!!year doesn\'t match!!<br/>';
                         ++$errors;
                         $error_detected = TRUE;
                     }
                     // Is the calculated academic term consistent?
                     if ($term_counter != $actime->AcademicTerm()) {
                         echo '!!term doesn\'t match!!<br/>';
                         ++$errors;
                         $error_detected = TRUE;
                     }
                     // Is the calculated academic week consistent?
                     if ($week_counter != $actime->AcademicWeek()) {
                         echo '!!week doesn\'t match!!<br/>';
                         ++$errors;
                         $error_detected = TRUE;
                     }
                     if ($error_detected) {
                         // an error has been detected so print date information
                         if (0 !== $prev_date) {
                             // starting with previous date
                             echo '&nbsp;&nbsp;prev date: ' . $prev_date->Format(DATE_RFC822) . '<br/>';
                             //*/
                             // elapsed days
                             echo '&nbsp;&nbsp;days between: ' . Academic_time::DaysBetweenTimestamps($prev_date->Timestamp(), $actime->Timestamp()) . '<br/>';
                             //*/;
                         }
                         // academic date input
                         echo '&nbsp;&nbsp;Year: ' . $year . ', Term: ' . $term_counter . ', Week: ' . $week_counter . ', Day of week: ' . $dow_counter . ', Day of term: ' . $term_day . '<br/>';
                         //*/
                         // standard date output
                         echo '&nbsp;&nbsp;date1: ' . $actime->Format(DATE_RFC822) . '<br/>';
                         //*/
                         echo '&nbsp;&nbsp;date2: ' . $actime2->Format(DATE_RFC822) . '<br/>';
                         //*/
                         // gregorian & academic date output
                         echo '&nbsp;&nbsp;date: ' . $actime->DayOfMonth() . '/' . $actime->Month() . '/' . $actime->Year() . ': ' . $actime->AcademicWeek() . ',' . $actime->AcademicTermName() . ',' . $actime->AcademicYearName() . '<br/>';
                         //*/
                         // data from inside DaysBetweenTimestamps function
                         // probably no longer required now its fixed
                         echo '&nbsp;&nbsp;&nbsp;Day of year of first: ' . (int) date('z', $prev_date->Timestamp()) . '<br/>';
                         echo '&nbsp;&nbsp;&nbsp;Day of year of second: ' . (int) date('z', $actime->Timestamp()) . '<br/>';
                         $difference = (int) date('z', $actime->Timestamp()) - (int) date('z', $prev_date->Timestamp());
                         if ($difference < 0) {
                             echo '&nbsp;&nbsp;&nbsp;Days of year of first: ' . (365 + (int) date('L', $prev_date->Timestamp())) . '<br/>';
                         }
                         // New line to seperate error dates
                         echo '<br/>';
                     }
                     $prev_date = $actime;
                     ++$term_day;
                 }
                 $dow_counter = 1;
             }
         }
     }
     return $errors;
 }
}
?>
">
<?php 
// Legend
if (isset($Legend) && is_array($Legend) && !empty($Legend)) {
    echo '<tr><th colspan="8" class="term">Legend</th></tr>';
    foreach ($Legend as $legend_info) {
        list($classes_array, $description) = $legend_info;
        $classnames = join(' ', $classes_array);
        echo "<tr><th /><td colspan=\"7\" class=\"{$classnames}\">{$description}</td></tr>";
    }
}
$day_of_week_headings = array('S', 'M', 'T', 'W', 'T', 'F', 'S');
$term_date_alteration = '4days';
$today = Academic_time::NewToday();
// 	$today = $today->Adjust('1month');
// 	$day_start = $today->StartOfWeek();
$day_start = $today->Adjust('-' . $today->AcademicDay() . 'days')->StartOfWeek($WeekStart);
$term_name = '';
$today_id = $today->Format('Ymd');
for ($week_counter = 0; $week_counter < 52; ++$week_counter) {
    $term_altered_date = $day_start->Adjust($term_date_alteration);
    $this_term_name = $term_altered_date->AcademicTermNameUnique() . ' ' . $term_altered_date->AcademicYearName(2);
    $week_number = $term_altered_date->AcademicWeek();
    if ($this_term_name != $term_name) {
        $term_name = $this_term_name;
        $this_term_name .= ' (' . $day_start->Format('M') . ')';
        ?>
	<tr><th colspan="8" class="term"><?php 
        echo $this_term_name;
 /**
  * @return array,NULL,FALSE: NULL if no recurrence, FALSE if too complicated.
  */
 static function transform_recur_for_view(&$recur, &$errors)
 {
     if (NULL === $recur) {
         return NULL;
     }
     /*
      * check in following order:
      * 	daily, interval, no bys
      *  weekly, interval, byday multiple
      *  monthly, interval
      * 	  bymonthday singular
      * 	  bydayn singular / byday singular, setpos / byday multiple special, setpos
      *  yearly, interval
      *    bymonthday singular, bymonth singular
      *    bydayn singular, bymonth singular
      *    byyearday
      */
     /// @TODO allow implicit monthly/yearly bymonthday[, bymonth]
     $rrule = $recur->GetSimpleRrule();
     if (NULL !== $rrule) {
         $fields = $rrule->GetUsedFields();
         $freq = $rrule->GetFrequency();
         $result = array('enable' => 'on', 'freq' => $freq, 'interval' => $rrule->GetInterval());
         if (isset($fields['count'])) {
             $result['range_method'] = 'count';
             $result['count'] = $rrule->GetCount();
         } elseif (isset($fields['until'])) {
             $result['range_method'] = 'until';
             $until = $rrule->GetUntil();
             $result['until'] = array('monthday' => (int) date('d', $until), 'month' => (int) date('n', $until), 'year' => (int) date('Y', $until));
         } else {
             $result['range_method'] = 'noend';
         }
         $by_fields = array();
         foreach ($fields as $field => $dummy) {
             if (substr($field, 0, 2) === 'by') {
                 $by_fields[$field] = $dummy;
             }
         }
         $match = true;
         if ('daily' === $freq) {
             if (!empty($by_fields)) {
                 $match = false;
             }
         } elseif ('weekly' === $freq) {
             foreach ($fields as $field => $dummy) {
                 if (substr($field, 0, 2) === 'by' && $field !== 'byday') {
                     $errors[] = array('text' => "Recurrence rule too complicated for basic interface ({$field} detected)");
                     $match = false;
                     break;
                 }
             }
             if ($match) {
                 if (isset($fields['byday'])) {
                     $days = $rrule->GetByDayWeekless();
                     $result['weekly_byday'] = array();
                     foreach ($days as $day) {
                         $result['weekly_byday'][$day] = 'on';
                     }
                 } else {
                     $result['weekly_byday'] = array();
                 }
             }
         } elseif ('monthly' === $freq) {
             if (isset($fields['bymonthday'])) {
                 $monthdays = $rrule->GetByMonthDay();
                 if (count($monthdays) === 1) {
                     foreach ($fields as $field => $dummy) {
                         if (substr($field, 0, 2) === 'by' && $field !== 'bymonthday') {
                             $errors[] = array('text' => "Recurrence rule too complicated for basic interface ({$field} detected)");
                             $match = false;
                             break;
                         }
                     }
                     if ($match) {
                         $result['monthly_method'] = 'monthday';
                         $monthdays_output = array();
                         $result['monthly_monthday'] = array('monthday' => $monthdays[0]);
                     }
                 } else {
                     // Not one bymonthday field
                     $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not one bymonthday)");
                     $match = false;
                 }
             } elseif (isset($fields['byday'])) {
                 $bydays = $rrule->GetByDay();
                 foreach ($fields as $field => $dummy) {
                     if (substr($field, 0, 2) === 'by' && $field !== 'byday' && $field !== 'bysetpos') {
                         $errors[] = array('text' => "Recurrence rule too complicated for basic interface ({$field} detected)");
                         $match = false;
                         break;
                     }
                 }
                 if ($match) {
                     // Either:
                     //  1. bydays is individual day with week and no setpos
                     //  2. bydays is individual day without week and setpos
                     //  3. bydays is 1,2,3,4,5 without weeks and setpos
                     $multiple_bydays = count($bydays);
                     $setpos = $rrule->GetBySetPos();
                     $dayweeks_specified = NULL;
                     $weekdays = array();
                     $has_setpos = isset($fields['bysetpos']);
                     if (!$has_setpos or count($setpos) == 1) {
                         foreach ($bydays as $day => $weeks) {
                             if (is_array($weeks)) {
                                 if (count($weeks) === 1) {
                                     $dayweeks_specified = true;
                                     $actual_weeks = array_keys($weeks);
                                     $result['monthly_weekday'] = array('week' => $actual_weeks[0], 'day' => $day);
                                 } else {
                                     // Not one week in byday field
                                     $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not one week in byday)");
                                     $match = false;
                                 }
                             } else {
                                 $weekdays[] = $day;
                             }
                         }
                         if ($multiple_bydays == 1) {
                             if ($dayweeks_specified && !$has_setpos) {
                                 // case 1
                                 $result['monthly_method'] = 'weekday';
                             } elseif (!$dayweeks_specified && $has_setpos) {
                                 // case 2
                                 $result['monthly_method'] = 'weekday';
                                 $result['monthly_weekday'] = array('week' => $setpos[0], 'day' => $weekdays[0]);
                                 // 									var_dump($result['monthly_weekday']);
                             } else {
                                 // Invalid combination of byday and bysetpos
                                 $errors[] = array('text' => "Recurrence rule too complicated for basic interface (unknown combination of byday and bysetpos)");
                                 $match = false;
                             }
                         } elseif (!$dayweeks_specified && $has_setpos) {
                             // days = 1,2,3,4,5
                             sort($weekdays);
                             if (count($weekdays) == 5 and $weekdays[0] == 1 and $weekdays[1] == 2 and $weekdays[2] == 3 and $weekdays[3] == 4 and $weekdays[4] == 5) {
                                 // case 3
                                 $result['monthly_method'] = 'weekday';
                                 $result['monthly_weekday'] = array('week' => $setpos[0], 'day' => join(',', $weekdays));
                             } else {
                                 // Not standard combination of days
                                 $errors[] = array('text' => "Recurrence rule too complicated for basic interface (using setpos with multiple bydays but not a standard combination of days)");
                                 $match = false;
                             }
                         } else {
                             // Multiple bydays without setpos
                             $errors[] = array('text' => "Recurrence rule too complicated for basic interface (no bysetpos with multiple bydays)");
                             $match = false;
                         }
                     } else {
                         // Multiple setpos on monthly byday
                         $errors[] = array('text' => "Recurrence rule too complicated for basic interface (multiple bysetpos on monthly byday)");
                         $match = false;
                     }
                 }
             } else {
                 // Not a recognised monthly method
                 $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not recognised monthly method)");
                 $match = false;
             }
         } elseif ('yearly' === $freq) {
             if (empty($by_fields) || isset($fields['bymonthday']) && isset($fields['bymonth'])) {
                 list($start_date) = $recur->GetStartEnd();
                 $start_date = new Academic_time($start_date);
                 if (empty($by_fields)) {
                     $monthdays = array($start_date->DayOfMonth());
                     $months = array($start_date->Month());
                 } else {
                     $monthdays = $rrule->GetByMonthDay();
                     $months = $rrule->GetByMonth();
                 }
                 if (count($monthdays) === 1 && count($months) === 1) {
                     foreach ($fields as $field => $dummy) {
                         if (substr($field, 0, 2) === 'by' && $field !== 'bymonthday' && $field !== 'bymonth') {
                             $errors[] = array('text' => "Recurrence rule too complicated for basic interface ({$field} detected)");
                             $match = false;
                             break;
                         }
                     }
                     if ($match) {
                         $result['yearly_method'] = 'monthday';
                         $monthdays_output = array();
                         $result['yearly_monthday'] = array('monthday' => $monthdays[0], 'month' => $months[0]);
                     }
                 } else {
                     // Not one bymonthday field or bymonth field
                     $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not one bymonthday or bymonth)");
                     $match = false;
                 }
             } elseif (isset($fields['byday']) && isset($fields['bymonth'])) {
                 $bydays = $rrule->GetByDay();
                 $months = $rrule->GetByMonth();
                 if (count($bydays) === 1 && count($months) === 1) {
                     foreach ($fields as $field => $dummy) {
                         if (substr($field, 0, 2) === 'by' && $field !== 'byday' && $field !== 'bymonth') {
                             $match = false;
                             break;
                         }
                     }
                     if ($match) {
                         foreach ($bydays as $day => $weeks) {
                             if (is_array($weeks) && count($weeks) === 1) {
                                 $actual_weeks = array_keys($weeks);
                                 $result['yearly_method'] = 'weekday';
                                 $result['yearly_weekday'] = array('week' => $actual_weeks[0], 'day' => $day, 'month' => $months[0]);
                             } else {
                                 // Not one week in byday field
                                 $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not one week in byday)");
                                 $match = false;
                             }
                         }
                     }
                 } else {
                     // Not one byday field or bymonth field
                     $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not one byday or bymonth)");
                     $match = false;
                 }
             } elseif (isset($fields['byyearday'])) {
                 $yeardays = $rrule->GetByYearDay();
                 if (count($yeardays) === 1) {
                     foreach ($fields as $field => $dummy) {
                         if (substr($field, 0, 2) === 'by' && $field !== 'byyearday') {
                             $errors[] = array('text' => "Recurrence rule too complicated for basic interface ({$field} detected)");
                             $match = false;
                             break;
                         }
                     }
                     if ($match) {
                         $result['yearly_method'] = 'yearday';
                         $monthdays_output = array();
                         $result['yearly_yearday'] = array('yearday' => $yeardays[0]);
                     }
                 } else {
                     // Not one byyearday field
                     $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not one byyearday)");
                     $match = false;
                 }
             } else {
                 // Not a recognised yearly method
                 $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not recognised yearly method)");
                 $match = false;
             }
         } else {
             // Not a recognised simple frequency
             $errors[] = array('text' => "Recurrence rule too complicated for basic interface (not recognised simple frequency)");
             $match = false;
         }
         if ($match) {
             return $result;
         } else {
             return false;
         }
     } else {
         return false;
     }
 }
 /**
  * @param $UriSegment string URI segment.
  * @param $AllowRange bool Whether to allow date ranges (using ':' in between).
  * @return array Return structure:
  *	- 'valid' (bool Whether successful)
  *	- 'start' (Academic_time Start of range specified by @a $UriSegment)
  *	- 'end'  (Academic_time End of range specified by @a $UriSegment)
  *	- 'format' (string Format string which can be passed to GenerateUri())
  *	- 'description' (string Description of the date [range])
  */
 function ReadUri($UriSegment, $AllowRange = TRUE)
 {
     // Use GenerateRegex to get regex
     $regex = $this->GetRegex($AllowRange);
     $format = self::DefaultFormat();
     $description = '';
     $valid = preg_match($regex, $UriSegment, $results) > 0;
     if ($valid) {
         if ($this->mDebug) {
             echo '<p>Result of regular expression process:<br/>' . str_replace("\n", "<br/>\n", var_export($results, true) . '</p>');
         }
         // Initial information extraction
         $start_academic = !empty($results['start_ac']);
         $start_gregorian = !empty($results['start_greg']);
         $start_relative = !empty($results['start_rel']);
         $end_academic = !empty($results['end_ac']);
         $end_gregorian = !empty($results['end_greg']);
         $end_relative = !empty($results['end_rel']);
         $has_start = $start_academic || $start_gregorian || $start_relative;
         $has_end = $end_academic || $end_gregorian || $end_relative;
         if ($has_end) {
             $description .= 'from ';
         }
         $start = Academic_time::NewToday();
         $end = $start;
         // Find the start, its either academic, gregorian, or relative
         if ($start_academic) {
             $format = 'ac';
             if ($end_academic) {
                 $format .= ':ac';
             }
             list($start, $end, $temp_description) = $this->ReadAcademic($start, $results['ac_year'], $results['ac_term'], empty($results['week']) ? '' : $results['week'], empty($results['day']) ? '' : $results['day']);
             $description .= $temp_description;
         } elseif ($start_gregorian) {
             $format = 'gr';
             if ($end_gregorian) {
                 $format .= ':gr';
             }
             list($start, $end, $temp_description) = $this->ReadGregorian($start, $results['year'], $results['month'], empty($results['dom']) ? '' : $results['dom']);
             $description .= $temp_description;
         } elseif ($start_relative) {
             $format = 'gr';
             if ($end_gregorian) {
                 $format .= ':gr';
             }
             $offset = '';
             if (!empty($results['base'])) {
                 switch ($results['base']) {
                     case 'yesterday':
                         $offset = '-1day';
                         break;
                     case 'tomorrow':
                         $offset = '1day';
                         break;
                 }
                 $description .= strtolower($results['base']);
             } else {
                 if (!empty($results['offset'])) {
                     if (!empty($results['offset_unit'])) {
                         $offset .= $results['offset'] . $results['offset_unit'];
                     } else {
                         $offset .= $results['offset'] . 'day';
                     }
                     $results['offset_unit'] = strtolower($results['offset_unit']);
                     if ('s' !== substr($results['offset_unit'], -1, 1)) {
                         $results['offset_unit'] .= 's';
                     }
                     $description .= $results['offset'] . ' ' . $results['offset_unit'] . ' time';
                 }
             }
             if (!empty($offset)) {
                 $start = $start->Adjust($offset);
             }
             // Set the implicit duration if no end is specified
             if (!$has_end) {
                 $end = $start->Adjust('1day');
             }
         }
         // Find the end, its either academic, gregorian, or relative
         if ($end_academic) {
             $description .= ' until ';
             list($dummy, $end, $temp_description) = $this->ReadAcademic($start, $results['end_ac_year'], $results['end_ac_term'], empty($results['end_week']) ? '' : $results['end_week'], empty($results['end_day']) ? '' : $results['end_day']);
             $description .= $temp_description;
         } elseif ($end_gregorian) {
             $description .= ' until ';
             list($dummy, $end, $temp_description) = $this->ReadGregorian($start, $results['end_year'], $results['end_month'], empty($results['end_dom']) ? '' : $results['end_dom']);
             $description .= $temp_description;
         } elseif ($end_relative) {
             $format .= ':re';
             $end = $start;
             $offset = '';
             if (!empty($results['end_base'])) {
                 $end = Academic_time::NewToday()->Adjust('1day');
                 switch ($results['end_base']) {
                     case 'yesterday':
                         $offset .= '-1day';
                         break;
                     case 'tomorrow':
                         $offset .= '1day';
                         break;
                 }
                 $description .= ' until ' . strtolower($results['end_base']);
             } else {
                 if (!empty($results['end_offset'])) {
                     if (!empty($results['end_offset_unit'])) {
                         $offset .= $results['end_offset'] . $results['end_offset_unit'];
                     } else {
                         $results['end_offset_unit'] = 'day';
                         $offset .= $results['end_offset'] . 'day';
                     }
                     $results['end_offset_unit'] = strtolower($results['end_offset_unit']);
                     if ('s' === substr($results['end_offset_unit'], -1, 1)) {
                         if (1 == $results['end_offset']) {
                             $results['end_offset_unit'] = substr($results['end_offset_unit'], 0, -1);
                         }
                     } else {
                         if (1 != $results['end_offset']) {
                             $results['end_offset_unit'] .= 's';
                         }
                     }
                     $description .= ' for ' . $results['end_offset'] . ' ' . $results['end_offset_unit'];
                 }
             }
             if (!empty($offset)) {
                 $end = $start->Adjust($offset);
             }
         }
         // If the end is before the start, use the start for 1 day
         if ($start->Timestamp() >= $end->Timestamp()) {
             $end = $start->Adjust('1day');
         }
     } else {
         // Invalid, so puke back saying it was unrecognised
         $description = 'Unrecognised ' . ($AllowRange ? 'date range' : 'date');
     }
     // Return the final array
     return array('valid' => $valid, 'format' => $format, 'start' => $valid ? $start : NULL, 'end' => $valid ? $end : NULL, 'description' => $description);
 }
 /**
  * @pre SetRange() must have already been called.
  */
 function Retrieve()
 {
     // Don't get any events from the database right now
     //parent::Retrieve();
     // Calculate links to next, previous, and this whole term
     $prev_term = $this->mSelectedWeekStart->AcademicYear() - ($this->mSelectedWeekStart->AcademicTerm() == 0 ? 1 : 0) . '-' . Academic_time::GetAcademicTermNameUnique(($this->mSelectedWeekStart->AcademicTerm() + 5) % 6) . '-1';
     //$this_term =
     //		$this->mSelectedWeekStart->AcademicYear() . '-' .
     //		$this->mSelectedWeekStart->AcademicTermNameUnique();
     $next_term = $this->mSelectedWeekStart->AcademicYear() + ($this->mSelectedWeekStart->AcademicTerm() == 5 ? 1 : 0) . '-' . Academic_time::GetAcademicTermNameUnique(($this->mSelectedWeekStart->AcademicTerm() + 1) % 6) . '-1';
     $this->SetData('links', array('prev_term' => site_url($this->mUriBase . $prev_term), 'this_term' => '', 'next_term' => site_url($this->mUriBase . $next_term)));
     $this->SetData('term', array('name' => $this->mSelectedWeekStart->AcademicTermName() . ' ' . $this->mSelectedWeekStart->AcademicTermTypeName()));
     // Get this monday
     $CI =& get_instance();
     $monday = Academic_time::NewToday()->BackToMonday()->Timestamp();
     $weeks = array();
     $last_term = -1;
     for ($week = $this->mStartTime; $week->Timestamp() < $this->mEndTime->Timestamp(); $week = $next_week) {
         // Find the end of the week
         $next_week = $week->Adjust('1week');
         if (FALSE) {
             // Titles before each new term
             if ($last_term !== $week->AcademicTerm()) {
                 $weeks[] = array('link' => site_url($this->mUriBase . $week->AcademicYear() . '-' . $week->AcademicTermNameUnique()), 'name' => strtoupper($week->AcademicTermName() . ' ' . $week->AcademicTermTypeName() . ' ' . $week->AcademicYearName()), 'events' => 0, 'select' => FALSE, 'old' => FALSE, 'heading' => TRUE, 'start_date' => '');
                 $last_term = $week->AcademicTerm();
             }
         }
         $old = $week->Timestamp() < $monday;
         // Is the week in the past?
         $selected = $this->mSelectedWeekStart->Timestamp() <= $week->Timestamp() && $this->mSelectedWeekEnd->Timestamp() >= $next_week->Timestamp();
         $weeks[] = array('link' => $this->GenerateUri($week, $next_week), 'name' => 'Week ' . $week->AcademicWeek(), 'events' => 0, 'select' => $selected, 'old' => $old, 'heading' => FALSE);
     }
     $this->SetData('weeks', $weeks);
 }
 function calendar($organisation, $DateRange = NULL, $Filter = NULL)
 {
     $this->load->model('subcontrollers/calendar_subcontroller');
     if (!CheckPermissions('public')) {
         return;
     }
     // Set up the filter
     $data = $this->organisations->_GetOrgData($organisation);
     if (!empty($data)) {
         $this->_SetupOrganisationFrame($organisation);
         $this->main_frame->SetPage('calendar', 'directory');
         $this->calendar_subcontroller->SetRangePageCode('directory_calendar');
         // restrict to this organisation
         $this->calendar_subcontroller->UseStreams(array((int) $data['organisation']['id'] => array('subscribed' => isset($data['organisation']['subscription']) && $data['organisation']['subscription']['calendar'], 'name' => $data['organisation']['name'], 'short_name' => $organisation)));
         // disable cancelled events
         $sources =& $this->calendar_subcontroller->GetSources();
         $sources->DisableGroup('inactive');
         $args = func_get_args();
         array_shift($args);
         $this->calendar_subcontroller->_map($args);
     } else {
         $this->load->library('custom_pages');
         $this->main_frame->SetContent(new CustomPageView('directory_notfound', 'error'));
         $this->main_frame->Load();
     }
     return;
     $this->pages_model->SetPageCode('directory_calendar');
     $data = $this->organisations->_GetOrgData($organisation);
     if (!empty($data)) {
         $this->_SetupOrganisationFrame($organisation);
         $this->load->library('my_calendar');
         $this->load->library('calendar_source_yorker');
         $this->my_calendar->SetUrlPrefix('/directory/' . $organisation . '/calendar/');
         //$this->My_calendar->SetAgenda(vip_url('calendar/agenda').'/');
         $yorker_source = new CalendarSourceYorker(0);
         // Only those events of the organisation
         $yorker_source->DisableGroup('subscribed');
         $yorker_source->DisableGroup('owned');
         $yorker_source->DisableGroup('private');
         $yorker_source->EnableGroup('active');
         $yorker_source->DisableGroup('inactive');
         $yorker_source->EnableGroup('hide');
         $yorker_source->EnableGroup('show');
         $yorker_source->EnableGroup('rsvp');
         $yorker_source->IncludeStream((int) $data['organisation']['id'], TRUE);
         $now = new Academic_time(time());
         $this->my_calendar->SetTabs(FALSE);
         $this->my_calendar->SetDefaultRange($now->AcademicYear() . '-' . $now->AcademicTermNameUnique());
         $this->my_calendar->SetPath('edit', site_url('calendar/event'));
         $calendar_view = $this->my_calendar->GetMyCalendar($yorker_source, $DateRange, $Filter);
         if (FALSE) {
             $this->load->model('calendar/events_model');
             $this->load->library('view_calendar_select_week');
             $this->load->library('view_calendar_list');
             $this->load->library('date_uri');
             $use_default_range = FALSE;
             if (empty($DateRange)) {
                 // $DateRange Empty
                 $use_default_range = TRUE;
             } else {
                 $uri_result = $this->date_uri->ReadUri($DateRange);
                 if ($uri_result['valid']) {
                     // valid
                     $start_time = $uri_result['start'];
                     $end_time = $uri_result['end'];
                     $format = $uri_result['format'];
                     $range_description = $uri_result['description'];
                 } else {
                     // invalid
                     $this->main_frame->AddMessage('error', 'Unrecognised date range: "' . $DateRange . '"');
                     $use_default_range = TRUE;
                 }
             }
             if ($use_default_range) {
                 // Default to this week
                 $start_time = Academic_time::NewToday();
                 $start_time = $start_time->BackToMonday();
                 $end_time = $start_time->Adjust('1week');
                 $format = 'ac';
                 //$range_description = 'from today for 1 week';
                 $range_description = 'this week';
             }
             // Use the start time, end time, and format to set up views
             //$weeks_start = $start_time->Adjust('-2week')->BackToMonday();
             $weeks_start = $this->academic_calendar->AcademicDayOfTerm($start_time->AcademicYear(), $start_time->AcademicTerm(), 1, 0, 0, 0);
             /*if ($weeks_start->Timestamp() < $monday->Timestamp()) {
             			$weeks_start = $monday;
             		}*/
             /*$weeks_end = $end_time->Adjust('5week')->BackToMonday();
             		if ($weeks_end->Timestamp() < $monday->Timestamp()) {
             			$weeks_end = $monday->Adjust('5week');
             		}*/
             // Set up the week select view
             $week_select = new ViewCalendarSelectWeek();
             $week_select->SetUriBase('directory/' . $organisation . '/calendar/');
             $week_select->SetUriFormat($format);
             //$week_select->SetRange($weeks_start, $weeks_end);
             $week_select->SetAcademicTerm($weeks_start->AcademicYear(), $weeks_start->AcademicTerm());
             $week_select->SetSelectedWeek($start_time, $end_time);
             $week_select->Retrieve();
             $occurrence_filter = new EventOccurrenceFilter();
             $occurrence_filter->EnableSource('all');
             $occurrence_filter->SetSpecialCondition('organisations.organisation_directory_entry_name = ' . $this->db->escape($organisation));
             // Set up the events list
             $events_list = new ViewCalendarList();
             $events_list->SetUriBase('directory/' . $organisation . '/calendar/');
             $events_list->SetUriFormat($format);
             $events_list->SetRange($start_time, $end_time);
             $events_list->SetOccurrenceFilter($occurrence_filter);
             $events_list->Retrieve();
             // Set up the directory events view to contain the week select and
             // events list
             $directory_events = new FramesFrame('directory/directory_view_events', $data);
             $directory_events->SetContent($week_select, 'week_select');
             $directory_events->SetContent($events_list, 'events_list');
             $directory_events->SetData('date_range_description', $range_description);
         }
         // Set up the directory frame to use the messages frame
         $this->main_frame->SetPage('calendar', 'directory');
         $this->frame_directory->SetOrganisation($data['organisation']);
         $this->frame_directory->SetContent($calendar_view);
         // Set up the public frame to use the directory frame
         $this->main_frame->SetTitleParameters(array('organisation' => $data['organisation']['name']));
         $this->main_frame->SetContent($this->frame_directory);
     } else {
         $this->load->library('custom_pages');
         $this->main_frame->SetContent(new CustomPageView('directory_notfound', 'error'));
     }
     // Load the public frame view
     $this->main_frame->Load();
 }
if (null !== $ShareUrl) {
    ?>
<div class="crosswordShare"><?php 
    ?>
<a href="http://www.facebook.com/share.php?u=http://<?php 
    echo $ShareUrl;
    ?>
" target="_blank" class="fb_share_button" onclick="return fbs_click()">Share</a><?php 
    ?>
</div><?php 
}
// Rest of top box
?>
<h2><?php 
if ($Crossword['publication'] !== null) {
    $pub = new Academic_time($Crossword['publication']);
    echo $pub->Format('D ') . $pub->AcademicTermNameUnique() . ' week ' . $pub->AcademicWeek();
} else {
    ?>
unscheduled<?php 
}
?>
</h2><?php 
if (!empty($Links)) {
    ?>
<ul><?php 
    // Main links
    foreach ($Links as $label => $url) {
        ?>
<li><a href="<?php 
        echo xml_escape($url);
<img alt="view" src="<?php 
    echo site_url('office/crosswords/crossword/' . $crossword['id'] . '/preview?cellsize=3');
    ?>
" /><?php 
    ?>
</a><?php 
    ?>
</div><?php 
    // Publishing date
    ?>
<div class="publish_date"><?php 
    if (null === $crossword['publication']) {
        ?>
<a>schedule</a><?php 
    } else {
        $pub = new Academic_time($crossword['publication']);
        echo $pub->Format('D') . ' ' . $pub->AcademicTermNameUnique() . ' ' . $pub->AcademicWeek() . $pub->Format(' (jS M Y)') . ' at ' . $pub->Format('H:i');
    }
    ?>
</div><?php 
    // Authors
    ?>
<div class="authors"><?php 
    echo xml_escape(join(', ', $crossword['author_fullnames']));
    ?>
</div><?php 
    // Progress bar
    ?>
<div class="completeness"><?php 
    ?>
<div class="bar" style="width: <?php 
 function Load()
 {
     /// Process the data before loading
     $this->ProcessEvents($this->mData, $this->mCategories);
     /// Make some links
     if (NULL !== $this->mPaths && NULL !== $this->mRangeFormat && NULL !== $this->mStartTime && NULL !== $this->mEndTime) {
         $days = Academic_time::DaysBetweenTimestamps($this->mStartTime, $this->mEndTime);
         $start = new Academic_time($this->mStartTime);
         $end = new Academic_time($this->mEndTime);
         $now = new Academic_time(time());
         $try_again = TRUE;
         if (0 === $start->AcademicDay() && 0 === $end->AcademicDay()) {
             $CI =& get_instance();
             $terms_apart = ($end->AcademicYear() - $start->AcademicYear()) * 6 + $end->AcademicTerm() - $start->AcademicTerm();
             // don't really need to scroll in years
             if (FALSE && $terms_apart >= 6) {
                 $this->SetData('ForwardUrl', $this->GenerateRangeUrl($CI->academic_calendar->Academic($start->AcademicYear() + 1, $start->AcademicTerm(), $start->AcademicWeek()), $CI->academic_calendar->Academic($end->AcademicYear() + 1, $end->AcademicTerm(), $end->AcademicWeek())));
                 $this->SetData('BackwardUrl', $this->GenerateRangeUrl($CI->academic_calendar->Academic($start->AcademicYear() - 1, $start->AcademicTerm(), $start->AcademicWeek()), $CI->academic_calendar->Academic($end->AcademicYear() - 1, $end->AcademicTerm(), $end->AcademicWeek())));
                 $try_again = FALSE;
             } elseif ($terms_apart > 0) {
                 $this->SetData('ForwardUrl', $this->GenerateRangeUrl($CI->academic_calendar->Academic($start->AcademicYear() + (5 === $start->AcademicTerm() ? 1 : 0), ($start->AcademicTerm() + 1) % 6, $start->AcademicWeek()), $CI->academic_calendar->Academic($end->AcademicYear() + (5 === $start->AcademicTerm() ? 1 : 0), ($end->AcademicTerm() + 1) % 6, $end->AcademicWeek())));
                 $this->SetData('BackwardUrl', $this->GenerateRangeUrl($CI->academic_calendar->Academic($start->AcademicYear() - (0 === $start->AcademicTerm() ? 1 : 0), ($start->AcademicTerm() + 5) % 6, $start->AcademicWeek()), $CI->academic_calendar->Academic($end->AcademicYear() - (0 === $start->AcademicTerm() ? 1 : 0), ($end->AcademicTerm() + 5) % 6, $end->AcademicWeek())));
                 $try_again = FALSE;
             }
             $this->SetData('NowUrl', $this->GenerateRangeUrl($CI->academic_calendar->Academic($now->AcademicYear(), $now->AcademicTerm(), 1), $CI->academic_calendar->Academic($now->AcademicYear() + (5 === $start->AcademicTerm() ? 1 : 0), ($now->AcademicTerm() + 1) % 6, 1)));
             $this->SetData('NowUrlLabel', 'This term');
         }
         if ($try_again) {
             $now = $now->Midnight();
             if ($days >= 7) {
                 $forward_jump = '1week';
                 $now = $now->BackToMonday();
                 $this->SetData('NowUrlLabel', 'This week');
             } else {
                 $forward_jump = '1day';
                 $this->SetData('NowUrlLabel', 'Today');
             }
             $this->SetData('ForwardUrl', $this->GenerateRangeUrl($start->Adjust($forward_jump), $end->Adjust($forward_jump)));
             $this->SetData('BackwardUrl', $this->GenerateRangeUrl($start->Adjust('-' . $forward_jump), $end->Adjust('-' . $forward_jump)));
             $this->SetData('NowUrl', $this->GenerateRangeUrl($now, $now->Adjust('+' . $forward_jump)));
         }
     }
     parent::Load();
 }
    ?>
<div><?php 
    ?>
be one of the first to complete a crossword online and have your name on the winner list!<?php 
    ?>
</div><?php 
} else {
    if (!empty($next)) {
        ?>
<div class="Date"><?php 
        echo 'next online crossword will be published ' . xml_escape($next_pub_text);
        ?>
</div><?php 
    }
    foreach ($latest as $crossword) {
        $pub = new Academic_time($crossword['publication']);
        $pub_text = $pub->Format('D') . ' week ' . $pub->AcademicWeek() . ' ' . $pub->Format('H:i');
        ?>
<div style="width:50%;float:left;"><?php 
        // Icon and category
        ?>
<a href="<?php 
        echo site_url('crosswords/' . $crossword['id']);
        ?>
"><?php 
        ?>
<img alt="" src="<?php 
        echo site_url('crosswords/' . $crossword['id'] . '/preview');
        ?>
" /><?php 
        echo xml_escape($crossword['category_name']);
    protected function _Load()
    {
        $value = $this->value;
        if (null === $value) {
            $value = Academic_time::NewToday();
        } else {
            $value = new Academic_time($value);
        }
        ?>
<div	class="input_date_display"<?php 
        ?>
	onclick="<?php 
        echo xml_escape('return input_date_click("' . $this->name . '");');
        ?>
"<?php 
        ?>
	><?php 
        if ($this->date) {
            ?>
<span class="day" id="<?php 
            echo $this->id . '__day';
            ?>
"><?php 
            echo $value->Format('l');
            ?>
</span> <?php 
            ?>
week <span class="week" id="<?php 
            echo $this->id . '__wk';
            ?>
"><?php 
            echo $value->AcademicWeek();
            ?>
</span> <?php 
            ?>
of <span class="term" id="<?php 
            echo $this->id . '__term';
            ?>
"><?php 
            echo ucfirst($value->AcademicTermNameUnique());
            echo ' ' . $value->StartOfTerm()->Year();
            ?>
</span> <?php 
        }
        if ($this->time) {
            ?>
at <span class="hour" id="<?php 
            echo $this->id . '__hr';
            ?>
"><?php 
            echo $value->Hour();
            ?>
</span><?php 
            ?>
:<span class="minute" id="<?php 
            echo $this->id . '__min';
            ?>
"><?php 
            echo $value->Minute();
            ?>
</span> <?php 
        }
        ?>
</div><?php 
        $days = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun');
        ?>
<div	class="input_date_selector"<?php 
        ?>
	id="<?php 
        echo $this->id . '__selector';
        ?>
"<?php 
        ?>
	><?php 
        // Init script
        ?>
<script type="text/javascript"><?php 
        echo xml_escape('onLoadFunctions.push(function() {' . 'input_date_init(' . js_literalise($this->name) . ');' . '});', false);
        ?>
</script><?php 
        ?>
<div><?php 
        // Day of the week
        ?>
<select	id="<?php 
        echo $this->id . '__day_select';
        ?>
"<?php 
        ?>
	name="<?php 
        echo $this->name . '[day]';
        ?>
"<?php 
        ?>
	onchange="<?php 
        echo xml_escape('return input_date_day_changed("' . $this->name . '");');
        ?>
"<?php 
        ?>
><?php 
        foreach ($days as $val => $day) {
            ?>
<option value="<?php 
            echo $val;
            ?>
"<?php 
            if ($val == $value->DayOfWeek(1)) {
                ?>
 selected="selected"<?php 
            }
            ?>
><?php 
            echo $day;
            ?>
</option><?php 
        }
        ?>
</select><?php 
        // Week of the term
        ?>
<span>week</span><?php 
        ?>
<select	id="<?php 
        echo $this->id . '__wk_select';
        ?>
"<?php 
        ?>
	name="<?php 
        echo $this->name . '[wk]';
        ?>
"<?php 
        ?>
	onchange="<?php 
        echo xml_escape('return input_date_day_changed("' . $this->name . '");');
        ?>
"<?php 
        ?>
><?php 
        $weeks = $value->AcademicTermWeeks();
        for ($wk = 1; $wk <= $weeks; ++$wk) {
            ?>
<option value="<?php 
            echo $wk;
            ?>
"<?php 
            if ($wk == $value->AcademicWeek()) {
                ?>
 selected="selected"<?php 
            }
            ?>
><?php 
            echo $wk;
            ?>
</option><?php 
        }
        ?>
</select><?php 
        // Term
        ?>
<span>of</span><?php 
        ?>
<select	id="<?php 
        echo $this->id . '__term_select';
        ?>
"<?php 
        ?>
	name="<?php 
        echo $this->name . '[term]';
        ?>
"<?php 
        ?>
	onchange="<?php 
        echo xml_escape('return input_date_term_changed("' . $this->name . '");');
        ?>
"<?php 
        ?>
><?php 
        $sel_year = $value->AcademicYear();
        $sel_term = $value->AcademicTerm();
        $year = $sel_year;
        $term = 0;
        ?>
<option value="earlier">(more)</option><?php 
        for ($i = 0; $i < 6; ++$i) {
            $cur = new Academic_time(Academic_time::StartOfAcademicTerm($year, $term));
            ?>
<option value="<?php 
            echo "{$year}-{$term}";
            ?>
"<?php 
            if ($term == $sel_term && $year == $sel_year) {
                ?>
 selected="selected"<?php 
            }
            ?>
><?php 
            echo xml_escape(ucfirst($cur->AcademicTermNameUnique()) . ' ' . $cur->Year());
            ?>
</option><?php 
            ++$term;
            if ($term == 6) {
                $term = 0;
                ++$year;
            }
        }
        ?>
<option value="later">(more)</option><?php 
        ?>
</select><?php 
        // Time of day
        if ($this->time) {
            ?>
<span>at</span><?php 
            ?>
<select	id="<?php 
            echo $this->id . '__hr_select';
            ?>
"<?php 
            ?>
	name="<?php 
            echo $this->name . '[hr]';
            ?>
"<?php 
            ?>
	onchange="<?php 
            echo xml_escape('return input_date_time_changed("' . $this->name . '");');
            ?>
"<?php 
            ?>
><?php 
            for ($hr = 0; $hr < 24; ++$hr) {
                ?>
<option value="<?php 
                echo $hr;
                ?>
"<?php 
                if ($hr == $value->Hour()) {
                    ?>
 selected="selected"<?php 
                }
                ?>
><?php 
                echo sprintf('%02d', $hr);
                ?>
</option><?php 
            }
            ?>
</select><?php 
            ?>
<span>:</span><?php 
            ?>
<select	id="<?php 
            echo $this->id . '__min_select';
            ?>
"<?php 
            ?>
	name="<?php 
            echo $this->name . '[min]';
            ?>
"<?php 
            ?>
	onchange="<?php 
            echo xml_escape('return input_date_time_changed("' . $this->name . '");');
            ?>
"<?php 
            ?>
><?php 
            $minute = $value->Minute();
            $minute_interval = 5;
            for ($min = 0; $min < 60; $min += $minute_interval) {
                ?>
<option value="<?php 
                echo $min;
                ?>
"<?php 
                if ($min <= $minute && $min + $minute_interval > $minute) {
                    ?>
 selected="selected"<?php 
                }
                ?>
><?php 
                echo sprintf('%02d', $min);
                ?>
</option><?php 
            }
            ?>
</select><?php 
        }
        // Close button
        ?>
<input	type="button" value="x"<?php 
        ?>
	onclick="<?php 
        echo xml_escape('return input_selector_click("' . $this->name . '__selector");');
        ?>
"<?php 
        ?>
	/><?php 
        ?>
</div><?php 
        ?>
<div><?php 
        ?>
<table class="recur-cal cal-text"><?php 
        // Days along the top
        ?>
<tr><?php 
        ?>
<th /><?php 
        foreach ($days as $day) {
            ?>
<th><?php 
            echo xml_escape($day);
            ?>
</th><?php 
        }
        ?>
</tr><?php 
        $cur = $value->MondayWeek1OfTerm();
        $sel = $value->Midnight()->Timestamp();
        $today = Academic_time::NewToday()->Timestamp();
        $last_month = 0;
        $term = $cur->AcademicTerm();
        for ($wk = 1; $cur->AcademicTerm() == $term; ++$wk) {
            ?>
<tr id="<?php 
            echo $this->id . '__wk_' . $wk;
            ?>
"><?php 
            ?>
<th><?php 
            echo $wk;
            ?>
</th><?php 
            for ($dy = 0; $dy < 7; ++$dy) {
                $month = $cur->Month();
                $ts = $cur->Timestamp();
                $classes = array();
                if ($ts < $today) {
                    $classes[] = "pa";
                }
                if ($month % 2 == 0) {
                    $classes[] = "ev";
                }
                if ($ts == $today) {
                    $classes[] = "tod";
                }
                if ($ts == $sel) {
                    $classes[] = "sel";
                }
                if ($dy >= 5) {
                    $classes[] = "we";
                }
                ?>
<td	class="<?php 
                echo join(' ', $classes);
                ?>
"<?php 
                ?>
	id="<?php 
                echo $this->id . '__' . $cur->AcademicWeek() . '_' . $cur->Format('D');
                ?>
"<?php 
                ?>
	onclick="<?php 
                echo xml_escape('return input_date_change(' . js_literalise($this->name) . ',' . js_literalise($wk) . ',' . js_literalise($dy) . ');');
                ?>
"<?php 
                ?>
	><?php 
                if ($month != $last_month) {
                    echo xml_escape($cur->Format('M')) . '&nbsp;';
                    $last_month = $month;
                }
                echo xml_escape($cur->Format('j'));
                ?>
</td><?php 
                $cur = $cur->Adjust('+1day');
            }
            ?>
</tr><?php 
        }
        ?>
</table><?php 
        ?>
</div><?php 
        ?>
</div><?php 
    }
 protected function RecurYearly(&$results, &$default)
 {
     // Start at the beginning of the year of base
     $yearstart = new Academic_time(mktime(0, 0, 0, 1, 1, $default->Year()));
     $count = NULL;
     if (NULL !== $this->mCount) {
         $count = $this->mCount;
     }
     while ((NULL === $count || $count > 0) && (NULL === $this->mEffectiveUntil || $yearstart->Timestamp() <= $this->mEffectiveUntil)) {
         $yearresults = array();
         $this->YearInner($yearresults, $default, $yearstart);
         $this->HandleInners($results, $yearresults, $default, $count);
         $yearstart = $yearstart->Adjust('+' . $this->mInterval . 'years');
     }
 }
                $atime = new Academic_time($ts);
                echo date('l, j', $ts);
                // DAY MONTHDAY
                echo '<sup>' . date('S', $ts) . '</sup> ';
                // <sup>NTH</sup>
                echo date('F Y', $ts);
                // MONTH YEAR
                echo ' at ' . $atime->Format('%T');
                // at TIME
                // Show simplistic changes to the time
                if (isset($confirm_occ['new_start_time'])) {
                    if ($confirm_occ['new_start_time'] != $confirm_occ['start_time']) {
                        $new_atime = new Academic_time($confirm_occ['new_start_time']);
                        echo ' (moving to <strong>' . $new_atime->Format('%T') . '</strong>)';
                    } elseif ($confirm_occ['new_end_time'] != $confirm_occ['end_time']) {
                        $new_atime = new Academic_time($confirm_occ['new_end_time']);
                        echo ' (ending <strong>' . $new_atime->Format('%T') . '</strong>)';
                    }
                }
                // close the description tag
                echo "</{$description_tag_type}>";
                ?>
</div>
							</div>
							<?php 
            }
            ?>
						</div>
						<?php 
        }
    }