/** * End Date * * Returns the event end date * * @param int $event (optional) * @param bool $displayTime If true shows date and time, if false only shows date * @param string $dateFormat Allows date and time formating using standard php syntax (http://php.net/manual/en/function.date.php) * @return string Date * @since 2.0 */ function tribe_get_end_date($event = null, $displayTime = true, $dateFormat = '') { if (is_null($event)) { global $post; $event = $post; } if (is_numeric($event)) { $event = get_post($event); } if (tribe_event_is_all_day($event)) { $displayTime = false; } if (empty($event->EventEndDate) && is_object($event)) { $event->EventEndDate = tribe_get_event_meta($event->ID, '_EventEndDate', true); } if (isset($event->EventEndDate)) { if (tribe_event_is_all_day($event) && empty($event->_end_date_fixed) && TribeDateUtils::timeOnly($event->EventEndDate) != '23:59:59' && TribeDateUtils::timeOnly(tribe_event_end_of_day()) != '23:59') { // set the event end date to be one day earlier, if it's an all day event and the cutoff is past midnight // @todo remove this once we can have all day events without a start / end time $event->EventEndDate = date_create($event->EventEndDate); $event->EventEndDate->modify('-1 day'); $event->EventEndDate = $event->EventEndDate->format(TribeDateUtils::DBDATEFORMAT); $event->_end_date_fixed = true; } $date = strtotime($event->EventEndDate); } else { return; // '—'; } return tribe_event_format_date($date, $displayTime, $dateFormat); }
protected function setup_where_clause() { /** @var wpdb $wpdb */ global $wpdb; $clauses = array(); $values = array_map('intval', $this->currentValue); $values = implode(',', $values); $eod_cutoff = tribe_get_option('multiDayCutoff', '00:00'); if ($eod_cutoff != '00:00') { $eod_time_difference = TribeDateUtils::timeBetween('1/1/2014 00:00:00', "1/1/2014 {$eod_cutoff}:00"); $start_date = "DATE_SUB({$wpdb->postmeta}.meta_value, INTERVAL {$eod_time_difference} SECOND)"; $end_date = "DATE_SUB(tribe_event_end_date.meta_value, INTERVAL {$eod_time_difference} SECOND)"; } else { $start_date = "{$wpdb->postmeta}.meta_value"; $end_date = "tribe_event_end_date.meta_value"; } $clauses[] = "(DAYOFWEEK({$start_date}) IN ({$values}))"; // is it on at least 7 days (first day is 0) $clauses[] = "(DATEDIFF({$end_date}, {$start_date}) >=6)"; // determine if the start of the nearest matching day is between the start and end dates $distance_to_day = array(); foreach ($this->currentValue as $day_of_week_index) { $day_of_week_index = (int) $day_of_week_index; $distance_to_day[] = "MOD( 7 + {$day_of_week_index} - DAYOFWEEK({$start_date}), 7 )"; } if (count($distance_to_day) > 1) { $distance_to_next_matching_day = "LEAST(" . implode(',', $distance_to_day) . ")"; } else { $distance_to_next_matching_day = reset($distance_to_day); } $clauses[] = "(DATE(DATE_ADD({$start_date}, INTERVAL {$distance_to_next_matching_day} DAY)) < {$end_date})"; $this->whereClause = ' AND (' . implode(' OR ', $clauses) . ')'; }
public static function addEventConditions($where, $cur_query) { global $wpdb; if ($cur_query->get('start_date')) { $start_date = TribeDateUtils::beginningOfDay($cur_query->get('start_date')); } if ($cur_query->get('end_date')) { $end_date = TribeDateUtils::endOfDay($cur_query->get('end_date')); } // we can't store end date directly because it messes up the distinc clause $endDate = " IFNULL(DATE_ADD(CAST(eventStart.meta_value AS DATETIME), INTERVAL eventDuration.meta_value SECOND), eventEnd.meta_value) "; if (!empty($start_date) && !empty($end_date)) { $start_clause = $wpdb->prepare("(eventStart.meta_value >= %s AND eventStart.meta_value <= %s)", $start_date, $end_date); $end_clause = $wpdb->prepare("({$endDate} >= %s AND eventStart.meta_value <= %s )", $start_date, $end_date); $within_clause = $wpdb->prepare("(eventStart.meta_value < %s AND {$endDate} >= %s )", $start_date, $end_date); $where .= " AND ({$start_clause} OR {$end_clause} OR {$within_clause})"; } else { if (!empty($end_date)) { $start_clause = $wpdb->prepare("{$endDate} < %s", $end_date); $where .= " AND {$start_clause}"; } else { if (!empty($start_date)) { $end_clause = $wpdb->prepare("eventStart.meta_value > %s", $start_date); $within_clause = $wpdb->prepare("(eventStart.meta_value <= %s AND {$endDate} >= %s )", $start_date, $start_date); $where .= " AND ({$end_clause} OR {$within_clause})"; } } } if ($cur_query->get('hide_upcoming')) { $where .= " AND (hideUpcoming.meta_value != 'yes' OR hideUpcoming.meta_value IS null) "; } return $where; }
/** * Add the date to the edit link for recurring events. * * @param string $link The current link. * @param int $eventId The event id. * @return string The modified link. */ public static function add_event_occurrance_to_edit_link($link, $eventId) { if (get_query_var('post_type') != TribeEvents::POSTTYPE) { return $link; } // if is a recurring event if (function_exists('tribe_is_recurring_event') && tribe_is_recurring_event($eventId) && isset(self::$events_list[0])) { $link = add_query_arg('eventDate', urlencode(TribeDateUtils::dateOnly(self::$events_list[0]->EventStartDate)), $link); } return $link; }
/** * Checks the recurrence amount and adds a filter to display an errir if it is not correct. * * @since 3.0 * @author Paul Hughes * * @param int $post_id The post id. * @return void */ public function checkRecurrenceAmount($post_id) { $is_success = true; if (get_post_type($post_id) == TribeEvents::POSTTYPE && get_post_meta($post_id, '_EventRecurrence')) { extract(TribeEventsRecurrenceMeta::getRecurrenceMeta($post_id)); $rules = TribeEventsRecurrenceMeta::getSeriesRules($post_id); // use the recurrence start meta if necessary because we can't guarantee which order the start date will come back in $recStart = strtotime(get_post_meta($post_id, '_EventStartDate', true)); $eventEnd = strtotime(get_post_meta($post_id, '_EventEndDate', true)); $duration = $eventEnd - $recStart; $recEnd = $recEndType == "On" ? strtotime(TribeDateUtils::endOfDay($recEnd)) : $recEndCount - 1; // subtract one because event is first occurrence $old_start_dates = get_post_meta($post_id, '_EventStartDate'); if ($recType != "None") { $recurrence = new TribeRecurrence($recStart, $recEnd, $rules, $recEndType == "After", get_post($post_id)); $dates = (array) $recurrence->getDates(true, $old_start_dates); $max_recurrences = apply_filters('tribe_events_max_recurrences', 199); if (count($dates) > $max_recurrences) { add_filter('redirect_post_location', array(__CLASS__, 'tooManyRecurrencesError')); $is_success = false; } } } return $is_success; }
selected($recEndType, "After"); ?> ><?php _e('After', 'tribe-events-calendar-pro'); ?> </option> <option value="Never" <?php selected($recEndType, "Never"); ?> ><?php _e('Never', 'tribe-events-calendar-pro'); ?> </option> </select> <input autocomplete="off" placeholder="<?php echo TribeDateUtils::dateOnly(date(TribeDateUtils::DBDATEFORMAT)); ?> " type="text" class="tribe-datepicker" name="recurrence[end]" id="recurrence_end" value="<?php echo $recEnd; ?> " style="display:<?php echo !$recEndType || $recEndType == "On" ? "inline" : "none"; ?> "/> <span id="rec-count" style="display:<?php echo $recEndType == "After" ? "inline" : "none"; ?> "><input autocomplete="off" type="text" name="recurrence[end-count]" id="recurrence_end_count" value="<?php echo $recEndCount ? $recEndCount : 1; ?> " style='width: 40px;'/> <span id='occurence-count-text'><?php
public function setup_list($template_file) { if (basename(dirname($template_file)) . '/' . basename($template_file) == 'mini-calendar/list.php') { if ($this->args['count'] == 0) { return; } // make sure the widget taxonomy filter setting is respected add_action('pre_get_posts', array($this, 'set_count'), 1000); global $wp_query; // hijack the main query to load the events via provided $args if (!is_null($this->args)) { $query_args = array('posts_per_page' => $this->args['count'], 'tax_query' => $this->args['tax_query'], 'eventDisplay' => 'custom', 'start_date' => $this->get_month(), 'post_status' => array('publish'), 'is_tribe_mini_calendar' => true, 'tribeHideRecurrence' => false); // set end date if initial load, or ajax month switch if (!defined('DOING_AJAX') || defined('DOING_AJAX') && $_POST['action'] == 'tribe-mini-cal') { $query_args['end_date'] = substr_replace($this->get_month(TribeDateUtils::DBDATEFORMAT), TribeDateUtils::getLastDayOfMonth(strtotime($this->get_month())), -2); // @todo use tribe_events_end_of_day() ? $query_args['end_date'] = TribeDateUtils::endOfDay($query_args['end_date']); } $wp_query = TribeEventsQuery::getEvents($query_args, true); } } }
/** * Adds a style chooser to the write post page * * @param WP_Post $event * @return void */ public function EventsChooserBox($event = null) { $saved = false; if (!$event) { global $post; if (isset($_GET['post']) && $_GET['post']) { $saved = true; } } else { $post = $event; //echo $post->ID; if ($post->ID) { $saved = true; } else { $saved = false; } } $options = ''; $style = ''; if (isset($post->ID)) { $postId = $post->ID; } else { $postId = 0; } foreach ($this->metaTags as $tag) { if ($postId && $saved) { //if there is a post AND the post has been saved at least once. // Sort the meta to make sure it is correct for recurring events $meta = get_post_meta($postId, $tag); sort($meta); if (isset($meta[0])) { ${$tag} = $meta[0]; } } else { $cleaned_tag = str_replace('_Event', '', $tag); //allow posted data to override default data if (isset($_POST['Event' . $cleaned_tag])) { ${$tag} = stripslashes_deep($_POST['Event' . $cleaned_tag]); } else { ${$tag} = class_exists('TribeEventsPro') && $this->defaultValueReplaceEnabled() ? tribe_get_option('eventsDefault' . $cleaned_tag) : ""; } } } if (isset($_EventOrganizerID) && $_EventOrganizerID) { foreach ($this->organizerTags as $tag) { ${$tag} = get_post_meta($_EventOrganizerID, $tag, true); } } else { foreach ($this->organizerTags as $tag) { $cleaned_tag = str_replace('_Organizer', '', $tag); if (isset($_POST['organizer'][$cleaned_tag])) { ${$tag} = stripslashes_deep($_POST['organizer'][$cleaned_tag]); } } } if (isset($_EventVenueID) && $_EventVenueID) { foreach ($this->venueTags as $tag) { ${$tag} = get_post_meta($_EventVenueID, $tag, true); } } else { $defaults = $this->venueTags; $defaults[] = '_VenueState'; $defaults[] = '_VenueProvince'; foreach ($defaults as $tag) { $cleaned_tag = str_replace('_Venue', '', $tag); //echo $tag.' | '.$cleaned_tag.'<BR>'; $var_name = '_Venue' . $cleaned_tag; if ($cleaned_tag != 'Cost') { ${$var_name} = class_exists('TribeEventsPro') && $this->defaultValueReplaceEnabled() ? tribe_get_option('eventsDefault' . $cleaned_tag) : ""; } if (isset($_POST['venue'][$cleaned_tag])) { ${$var_name} = stripslashes_deep($_POST['venue'][$cleaned_tag]); } } if (isset($_VenueState) && !empty($_VenueState)) { $_VenueStateProvince = $_VenueState; } elseif (isset($_VenueProvince)) { $_VenueStateProvince = $_VenueProvince; } else { $_VenueStateProvince = null; } if (isset($_POST['venue']['Country'])) { if ($_POST['venue']['Country'] == 'United States') { $_VenueStateProvince = stripslashes_deep($_POST['venue']['State']); } else { $_VenueStateProvince = stripslashes_deep($_POST['venue']['Province']); } } } $_EventAllDay = isset($_EventAllDay) ? $_EventAllDay : false; $_EventStartDate = isset($_EventStartDate) ? $_EventStartDate : null; if (isset($_EventEndDate)) { if ($_EventAllDay && TribeDateUtils::timeOnly($_EventEndDate) != '23:59:59' && TribeDateUtils::timeOnly(tribe_event_end_of_day()) != '23:59:59') { // If it's an all day event and the EOD cutoff is later than midnight // set the end date to be the previous day so it displays correctly in the datepicker // so the datepickers will match. we'll set the correct end time upon saving // @todo: remove this once we're allowed to have all day events without a start/end time $_EventEndDate = date_create($_EventEndDate); $_EventEndDate->modify('-1 day'); $_EventEndDate = $_EventEndDate->format(TribeDateUtils::DBDATETIMEFORMAT); } } else { $_EventEndDate = null; } $isEventAllDay = $_EventAllDay == 'yes' || !TribeDateUtils::dateOnly($_EventStartDate) ? 'checked="checked"' : ''; // default is all day for new posts $startMonthOptions = TribeEventsViewHelpers::getMonthOptions($_EventStartDate); $endMonthOptions = TribeEventsViewHelpers::getMonthOptions($_EventEndDate); $startYearOptions = TribeEventsViewHelpers::getYearOptions($_EventStartDate); $endYearOptions = TribeEventsViewHelpers::getYearOptions($_EventEndDate); $startMinuteOptions = TribeEventsViewHelpers::getMinuteOptions($_EventStartDate, true); $endMinuteOptions = TribeEventsViewHelpers::getMinuteOptions($_EventEndDate); $startHourOptions = TribeEventsViewHelpers::getHourOptions($_EventAllDay == 'yes' ? null : $_EventStartDate, true); $endHourOptions = TribeEventsViewHelpers::getHourOptions($_EventAllDay == 'yes' ? null : $_EventEndDate); $startMeridianOptions = TribeEventsViewHelpers::getMeridianOptions($_EventStartDate, true); $endMeridianOptions = TribeEventsViewHelpers::getMeridianOptions($_EventEndDate); if ($_EventStartDate) { $start = TribeDateUtils::dateOnly($_EventStartDate); } $EventStartDate = isset($start) && $start ? $start : date('Y-m-d'); if (!empty($_REQUEST['eventDate'])) { $EventStartDate = esc_attr($_REQUEST['eventDate']); } if ($_EventEndDate) { $end = TribeDateUtils::dateOnly($_EventEndDate); } $EventEndDate = isset($end) && $end ? $end : date('Y-m-d'); $recStart = isset($_REQUEST['event_start']) ? esc_attr($_REQUEST['event_start']) : null; $recPost = isset($_REQUEST['post']) ? absint($_REQUEST['post']) : null; if (!empty($_REQUEST['eventDate'])) { $duration = get_post_meta($postId, '_EventDuration', true); $start_time = isset($_EventStartDate) ? TribeDateUtils::timeOnly($_EventStartDate) : TribeDateUtils::timeOnly(tribe_get_start_date($post->ID)); $EventEndDate = TribeDateUtils::dateOnly(strtotime($_REQUEST['eventDate'] . ' ' . $start_time) + $duration, true); } $events_meta_box_template = $this->pluginPath . 'admin-views/events-meta-box.php'; $events_meta_box_template = apply_filters('tribe_events_meta_box_template', $events_meta_box_template); include $events_meta_box_template; }
/** * Used by createEvent and updateEvent - saves all the various event meta * * @param int $event_id The event ID we are modifying meta for. * @param array $data The meta fields we want saved. * @param WP_Post The event itself. * @return void */ public static function saveEventMeta($event_id, $data, $event = null) { $tribe_ecp = TribeEvents::instance(); if (isset($data['EventAllDay']) && ($data['EventAllDay'] == 'yes' || $data['EventAllDay'] == true || !isset($data['EventStartDate']))) { $data['EventStartDate'] = TribeDateUtils::beginningOfDay($data['EventStartDate']); $data['EventEndDate'] = TribeDateUtils::endOfDay($data['EventEndDate']); } else { delete_post_meta($event_id, '_EventAllDay'); if (isset($data['EventStartMeridian'])) { $data['EventStartDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventStartDate'] . " " . $data['EventStartHour'] . ":" . $data['EventStartMinute'] . ":00 " . $data['EventStartMeridian'])); $data['EventEndDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventEndDate'] . " " . $data['EventEndHour'] . ":" . $data['EventEndMinute'] . ":00 " . $data['EventEndMeridian'])); } else { $data['EventStartDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventStartDate'] . " " . $data['EventStartHour'] . ":" . $data['EventStartMinute'] . ":00")); $data['EventEndDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventEndDate'] . " " . $data['EventEndHour'] . ":" . $data['EventEndMinute'] . ":00")); } } if (!isset($data['EventHideFromUpcoming']) || !$data['EventHideFromUpcoming']) { delete_post_meta($event_id, '_EventHideFromUpcoming'); } // sanity check that start date < end date $startTimestamp = strtotime($data['EventStartDate']); $endTimestamp = strtotime($data['EventEndDate']); if ($startTimestamp > $endTimestamp) { $data['EventEndDate'] = $data['EventStartDate']; } $data['EventDuration'] = strtotime($data['EventEndDate']) - $startTimestamp; $old_data['EventStartDate'] = TribeEvents::get_series_start_date($event_id); update_post_meta($event_id, '_EventShowMapLink', isset($data['venue']['EventShowMapLink'])); update_post_meta($event_id, '_EventShowMap', isset($data['venue']['EventShowMap'])); if (isset($data['post_status'])) { $post_status = $data['post_status']; } else { //print_r($data); if (isset($data["Organizer"]["OrganizerID"])) { $post_status = get_post($data["Organizer"]['OrganizerID'])->post_status; } if (isset($data['Venue']["VenueID"])) { $post_status = get_post($data['Venue']['VenueID'])->post_status; } } if (isset($data["Organizer"])) { $data['EventOrganizerID'] = TribeEventsAPI::saveEventOrganizer($data["Organizer"], $event, $post_status); } if (isset($data["Venue"])) { $data['EventVenueID'] = TribeEventsAPI::saveEventVenue($data["Venue"], $event, $post_status); } $cost = isset($data['EventCost']) ? $data['EventCost'] : ''; $data['EventCost'] = $cost; do_action('tribe_events_event_save', $event_id); $cost = isset($data['EventCost']) ? $data['EventCost'] : ''; $data['EventCost'] = $cost; //update meta fields foreach ($tribe_ecp->metaTags as $tag) { $htmlElement = ltrim($tag, '_'); if (isset($data[$htmlElement]) && $tag != TribeEvents::EVENTSERROROPT) { if (is_string($data[$htmlElement])) { $data[$htmlElement] = filter_var($data[$htmlElement], FILTER_SANITIZE_STRING); } if (isset($old_data[$htmlElement])) { update_post_meta($event_id, $tag, $data[$htmlElement], $old_data[$htmlElement]); } else { update_post_meta($event_id, $tag, $data[$htmlElement]); } } } // Set sticky state for calendar view. if (isset($data['EventShowInCalendar']) && $data['EventShowInCalendar'] == 'yes' && $event->menu_order != '-1') { $update_event = array('ID' => $event_id, 'menu_order' => '-1'); wp_update_post($update_event); } elseif ((!isset($data['EventShowInCalendar']) || $data['EventShowInCalendar'] != 'yes') && $event->menu_order == '-1') { $update_event = array('ID' => $event_id, 'menu_order' => '0'); wp_update_post($update_event); } do_action('tribe_events_update_meta', $event_id, $data); }
/** * Accepts two dates and returns the number of days between them * * @param string $start_date * @param string $end_date * @param string|bool $day_cutoff * @return int * @author Modern Tribe * @see TribeDateUtils::dateDiff() **/ function tribe_get_days_between($start_date, $end_date, $day_cutoff = '00:00') { if ($day_cutoff === FALSE) { $day_cutoff = '00:00'; } elseif ($day_cutoff === TRUE) { $day_cutoff = tribe_get_option('multiDayCutoff', '00:00'); } $start_date = new DateTime($start_date); if ($start_date < new DateTime($start_date->format('Y-m-d ' . $day_cutoff))) { $start_date->modify('-1 day'); } $end_date = new DateTime($end_date); if ($end_date <= new DateTime($end_date->format('Y-m-d ' . $day_cutoff))) { $end_date->modify('-1 day'); } // This doesn't work on php 5.2 // $interval = $start_date->diff($end_date); return TribeDateUtils::dateDiff($start_date->format('Y-m-d ' . $day_cutoff), $end_date->format('Y-m-d ' . $day_cutoff)); }
/** * Formatted Date * * Returns formatted date * * @param string $date * @param bool $displayTime If true shows date and time, if false only shows date * @param string $dateFormat Allows date and time formating using standard php syntax (http://php.net/manual/en/function.date.php) * * @return string */ function tribe_event_format_date($date, $displayTime = true, $dateFormat = '') { if (!TribeDateUtils::isTimestamp($date)) { $date = strtotime($date); } if ($dateFormat) { $format = $dateFormat; } else { $date_year = date('Y', $date); $cur_year = date('Y', current_time('timestamp')); // only show the year in the date if it's not in the current year $with_year = $date_year == $cur_year ? false : true; if ($displayTime) { $format = tribe_get_datetime_format($with_year); } else { $format = tribe_get_date_format($with_year); } } $date = date_i18n($format, $date); return apply_filters('tribe_event_formatted_date', $date, $displayTime, $dateFormat); }
/** * Delete view for an event. * * @param int $tribe_event_id The event's ID. * @return string The deletion view. * @author Nick Ciske * @since 1.0 */ public function doDelete($tribe_event_id) { $this->default_template_compatibility(); if (isset($_GET['eventDate'])) { $eventDate = date('Y-m-d', strtotime($_GET['eventDate'])); } if (isset($_GET['deleteAll'])) { $deleteAll = true; } $current_user = wp_get_current_user(); if (wp_verify_nonce($_GET['_wpnonce'], 'tribe_community_events_delete') && current_user_can('delete_post', $tribe_event_id)) { //does this event even exist? $event = get_post($tribe_event_id); if (isset($event->ID)) { if (isset($deleteAll) && $deleteAll || !isset($eventDate)) { if ($this->trashItemsVsDelete) { wp_trash_post($tribe_event_id); $this->enqueueOutputMessage(__('Trashed Event #', 'tribe-events-community') . $tribe_event_id); } else { wp_delete_post($tribe_event_id, true); $this->enqueueOutputMessage(__('Deleted Event #', 'tribe-events-community') . $tribe_event_id); } } else { $date = $eventDate; $startDate = TribeEvents::get_series_start_date($tribe_event_id); $date = TribeDateUtils::addTimeToDate($date, TribeDateUtils::timeOnly($startDate)); delete_post_meta($tribe_event_id, '_EventStartDate', $date); $this->enqueueOutputMessage(sprintf(__('Removed occurence %s from Event #', 'tribe-events-community') . $tribe_event_id, $eventDate)); } } else { $this->enqueueOutputMessage(sprintf(__('This event (#%s) does not appear to exist.', 'tribe-events-community'), $tribe_event_id)); } } else { $this->enqueueOutputMessage(__('You do not have permission to delete this event.', 'tribe-events-community')); } $output = '<div id="tribe-community-events" class="delete">'; ob_start(); $this->addScriptsAndStyles(); include TribeEventsTemplates::getTemplateHierarchy('community/modules/delete'); $output .= ob_get_clean(); $output .= '<a href="javascript:history.go(-1);">« ' . _x('Back', 'As in "go back to previous page"', 'tribe-events-community') . '</a>'; $output .= '</div>'; return $output; }
/** * Return the event end date string with a default of today. * * @param null|int $event_id * @return string event date * @author Peter Chester * @since 3.1 */ function tribe_community_events_get_end_date($event_id = null) { $event_id = TribeEvents::postIdHelper($event_id); $event = $event_id ? get_post($event_id) : null; $date = tribe_get_end_date($event, true, 'Y-m-d'); $date = $date ? TribeDateUtils::dateOnly($date) : date_i18n('Y-m-d'); return apply_filters('tribe_community_events_get_end_date', $date, $event_id); }
/** * Return the details of the start/end date/time. * * The highest level means of customizing this function's output is simply to adjust the WordPress date and time * formats (via the General Settings admin screen). Beyond that however there are two filters which can be used to * exercise further control here. * * The first is 'tribe_events_event_schedule_details_formatting' which allows an array of format settings to be * altered - it's basic make-up is as a simple set of key:value pairs as follows. * * "datetime_separator": this is inserted between the date and the time and defaults to an ampersat @ character. * Note that if you modify this you should ordinarily be careful to include leading and trailing spaces (an * example might be ' at '). * * "same_year_format": if an event starts and ends in the same year it's assumed that including the year in the * output is superfluous. That being the case the function changes the date format, by default, to 'F j'. This * may not be ideal in all locales so an alternative can be provided here. Do note that this substitution is * only ever made if A) the event starts and ends in the same year and B) the date format does not include any * time formatting characters. * * This can also effectively be used to turn off the assumption that the year should be omitted, simply by * setting it to the value of the 'date_format' option, for example. * * "show_end_time": for single day events only (not including all day events) it may not always be desirable to * include the end time. In that situation, this setting can be set to false and the end time will not be * displayed. * * "time": if it is undesirable to show times and only dates should be displayed then this setting can be set to * false. If it is false it will by extension cause 'show_end_time' to be false. * * The resulting string can also be caught and manipulated, or completely overridden, using the * 'tribe_events_event_schedule_details' filter, should none of the above settings be sufficient. * * @since 3.0 * @param int|null $event * @return string */ function tribe_events_event_schedule_details($event = null) { if (is_null($event)) { global $post; $event = $post; } if (is_numeric($event)) { $event = get_post($event); } $schedule = ''; $format = ''; $date_format = get_option('date_format'); $time_format = get_option('time_format'); $microformatStartFormat = tribe_get_start_date($event, false, 'Y-m-dTh:i'); $microformatEndFormat = tribe_get_end_date($event, false, 'Y-m-dTh:i'); $settings = array('datetime_separator' => ' @ ', 'same_year_format' => 'F j', 'show_end_time' => true, 'time' => true); $settings = wp_parse_args(apply_filters('tribe_events_event_schedule_details_formatting', $settings), $settings); if (!$settings['time']) { $settings['show_end_time'] = false; } extract($settings); // If the date format will result in the year being shown but does *not* include any time formatting... if (TribeDateUtils::formatContainsYear($date_format) && !TribeDateUtils::formatContainsTime($date_format)) { // ... and it starts and ends in the current year then there is no need to display the year if (tribe_get_start_date($event, false, 'Y') === date('Y') && tribe_get_end_date($event, false, 'Y') === date('Y')) { $format = $same_year_format; } } if (tribe_event_is_multiday($event)) { // multi-date event $format2ndday = $format; // If the WordPress date setting matches DATEONLYFORMAT, make the string more readable if (get_option('date_format') == TribeDateUtils::DATEONLYFORMAT) { //If it's all day and the end date is in the same month and year, just show the day. if (tribe_event_is_all_day($event) && tribe_get_end_date($event, false, 'm') === tribe_get_start_date($event, false, 'm') && tribe_get_end_date($event, false, 'Y') === date('Y')) { $format2ndday = 'j'; } } if (tribe_event_is_all_day($event)) { // If the multi-day event begins and ends in the same month, just show the month once. if (tribe_get_end_date($event, false, 'm') === tribe_get_start_date($event, false, 'm') && tribe_get_end_date($event, false, 'Y') === date('Y')) { $schedule .= '<span class="date-start dtstart">'; $schedule .= tribe_get_start_date($event, true, $format); $schedule .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>'; $schedule .= '</span> - '; $schedule .= '<span class="date-end dtend">'; $schedule .= tribe_get_end_date($event, true, $format2ndday); $schedule .= '<span class="value-title" title="' . $microformatEndFormat . '"></span>'; $schedule .= '</span>'; } else { $schedule .= '<span class="date-start dtstart">'; $schedule .= tribe_get_start_date($event, true, $format); $schedule .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>'; $schedule .= '</span> - '; $schedule .= '<span class="date-end dtend">'; $schedule .= tribe_get_end_date($event, true, $format2ndday); $schedule .= '<span class="value-title" title="' . $microformatEndFormat . '"></span>'; $schedule .= '</span>'; } } else { $schedule .= '<span class="date-start dtstart">'; $schedule .= tribe_get_start_date($event, false, $format) . ($time ? $datetime_separator . tribe_get_start_date($event, false, $time_format) : ''); $schedule .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>'; $schedule .= '</span> - '; $schedule .= '<span class="date-end dtend">'; $schedule .= tribe_get_end_date($event, false, $format2ndday) . ($time ? $datetime_separator . tribe_get_end_date($event, false, $time_format) : ''); $schedule .= '<span class="value-title" title="' . $microformatEndFormat . '"></span>'; $schedule .= '</span>'; } } elseif (tribe_event_is_all_day($event)) { // all day event $schedule .= '<span class="date-start dtstart">'; $schedule .= tribe_get_start_date($event, true, $format); $schedule .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>'; $schedule .= '</span>'; } else { // single day event if (tribe_get_start_date($event, false, 'g:i A') === tribe_get_end_date($event, false, 'g:i A')) { // Same start/end time $schedule .= '<span class="date-start dtstart">'; $schedule .= tribe_get_start_date($event, false, $format) . ($time ? $datetime_separator . tribe_get_start_date($event, false, $time_format) : ''); $schedule .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>'; $schedule .= '</span>'; } else { // defined start/end time $schedule .= '<span class="date-start dtstart">'; $schedule .= tribe_get_start_date($event, false, $format) . ($time ? $datetime_separator . tribe_get_start_date($event, false, $time_format) : ''); $schedule .= '<span class="value-title" title="' . $microformatStartFormat . '"></span>'; $schedule .= '</span>' . ($show_end_time ? ' - ' : ''); $schedule .= '<span class="end-time dtend">'; $schedule .= ($show_end_time ? tribe_get_end_date($event, false, $time_format) : '') . '<span class="value-title" title="' . $microformatEndFormat . '"></span>'; $schedule .= '</span>'; } } return apply_filters('tribe_events_event_schedule_details', $schedule); }
private function getNthDayOfMonth($curdate, $day_of_week, $week_of_month, $next_month_of_year) { $nextdate = $this->advanceDate($curdate, $next_month_of_year, 1); // advance to correct month $nextdate = TribeDateUtils::getFirstDayOfWeekInMonth($nextdate, $day_of_week); if ($week_of_month == -1) { // LAST WEEK $nextdate = TribeDateUtils::getLastDayOfWeekInMonth($nextdate, $day_of_week); return $nextdate; } else { $maybe_date = strtotime(date(DateSeriesRules::DATE_FORMAT, $nextdate) . " + " . ($week_of_month - 1) . " weeks"); // if this doesn't exist, then try next month while (date('n', $maybe_date) != date('n', $nextdate)) { // advance again $next_month_of_year = $this->getNextMonthOfYear(date('n', $nextdate)); $nextdate = $this->advanceDate($nextdate, $next_month_of_year); $nextdate = TribeDateUtils::getFirstDayOfWeekInMonth($curdate, $day_of_week); $maybe_date = strtotime(date(DateSeriesRules::DATE_FORMAT, $nextdate) . " + " . ($week_of_month - 1) . " weeks"); } return $maybe_date; } }
/** * Return the date of the first day in the month view grid. * * This is not necessarily the last day of the specified month, rather it is the date of * the final grid cell which could be anything upto 6 days into the next month. * * @param string $month * @param int $start_of_week * * @return bool|string (Y-m-d) */ protected function calculate_final_cell_date($month, $start_of_week = null) { if (null === $start_of_week) { $start_of_week = (int) get_option('start_of_week', 0); } $last_day = TribeDateUtils::last_day_in_month($month); $end_of_week = TribeDateUtils::week_ends_on($start_of_week); if ($end_of_week < $last_day) { $end_of_week += 7; } $diff = $end_of_week - $last_day; if ($diff >= 0) { $diff = "+{$diff}"; } try { $date = new DateTime($month); $date = new DateTime($date->format('Y-m-t')); $date->modify("{$diff} days"); return $date->format(TribeDateUtils::DBDATEFORMAT); } catch (Exception $e) { return false; } }
/** * Returns the earliest known event start date, which can be expected to be a string * in MySQL datetime format (unless some other specific format is provided). * * If this is impossible to determine it will return boolean false. * * @param string $format * * @return mixed bool|string */ function tribe_events_earliest_date($format = TribeDateUtils::DBDATETIMEFORMAT) { // Check if the earliest start date is already known $earliest = tribe_get_option('earliest_date', false); if (false !== $earliest) { return TribeDateUtils::reformat($earliest, $format); } // If not, try to determine now TribeEvents::instance()->rebuild_known_range(); $earliest = tribe_get_option('earliest_date', false); if (false !== $earliest) { return TribeDateUtils::reformat($earliest, $format); } return false; }
/** * Gets the first day of the week in a month (ie the first Tuesday). * * @param int $curdate A timestamp. * @param int $day_of_week The index of the day of the week. * * @return int The timestamp of the date that fits the qualifications. */ public static function getFirstDayOfWeekInMonth($curdate, $day_of_week) { $nextdate = mktime(0, 0, 0, date('n', $curdate), 1, date('Y', $curdate)); while (!($day_of_week > 0 && date('N', $nextdate) == $day_of_week) && !($day_of_week == -1 && TribeDateUtils::isWeekday($nextdate)) && !($day_of_week == -2 && TribeDateUtils::isWeekend($nextdate))) { $nextdate = strtotime(date(DateSeriesRules::DATE_FORMAT, $nextdate) . " + 1 day"); } return $nextdate; }
/** * Adds a style chooser to the write post page * * @return void */ public function EventsChooserBox($event = null) { $saved = false; if (!$event) { global $post; if (isset($_GET['post']) && $_GET['post']) { $saved = true; } } else { $post = $event; //echo $post->ID; if ($post->ID) { $saved = true; } else { $saved = false; } } $options = ''; $style = ''; if (isset($post->ID)) { $postId = $post->ID; } else { $postId = 0; } foreach ($this->metaTags as $tag) { if ($postId && $saved) { //if there is a post AND the post has been saved at least once. // Sort the meta to make sure it is correct for recurring events $meta = get_post_meta($postId, $tag); sort($meta); if (isset($meta[0])) { ${$tag} = $meta[0]; } } else { $cleaned_tag = str_replace('_Event', '', $tag); //allow posted data to override default data if (isset($_POST['Event' . $cleaned_tag])) { ${$tag} = stripslashes_deep($_POST['Event' . $cleaned_tag]); } else { ${$tag} = class_exists('TribeEventsPro') && $this->defaultValueReplaceEnabled() ? tribe_get_option('eventsDefault' . $cleaned_tag) : ""; } } } if (isset($_EventOrganizerID) && $_EventOrganizerID) { foreach ($this->organizerTags as $tag) { ${$tag} = get_post_meta($_EventOrganizerID, $tag, true); } } else { foreach ($this->organizerTags as $tag) { $cleaned_tag = str_replace('_Organizer', '', $tag); if (isset($_POST['organizer'][$cleaned_tag])) { ${$tag} = stripslashes_deep($_POST['organizer'][$cleaned_tag]); } } } if (isset($_EventVenueID) && $_EventVenueID) { foreach ($this->venueTags as $tag) { ${$tag} = get_post_meta($_EventVenueID, $tag, true); } } else { $defaults = $this->venueTags; $defaults[] = '_VenueState'; $defaults[] = '_VenueProvince'; foreach ($defaults as $tag) { $cleaned_tag = str_replace('_Venue', '', $tag); //echo $tag.' | '.$cleaned_tag.'<BR>'; $var_name = '_Venue' . $cleaned_tag; if ($cleaned_tag != 'Cost') { ${$var_name} = class_exists('TribeEventsPro') && $this->defaultValueReplaceEnabled() ? tribe_get_option('eventsDefault' . $cleaned_tag) : ""; } if (isset($_POST['venue'][$cleaned_tag])) { ${$var_name} = stripslashes_deep($_POST['venue'][$cleaned_tag]); } } if (isset($_VenueState) && !empty($_VenueState)) { $_VenueStateProvince = $_VenueState; } elseif (isset($_VenueProvince)) { $_VenueStateProvince = $_VenueProvince; } else { $_VenueStateProvince = null; } if (isset($_POST['venue']['Country'])) { if ($_POST['venue']['Country'] == 'United States') { $_VenueStateProvince = stripslashes_deep($_POST['venue']['State']); } else { $_VenueStateProvince = stripslashes_deep($_POST['venue']['Province']); } } } $_EventStartDate = isset($_EventStartDate) ? $_EventStartDate : null; $_EventEndDate = isset($_EventEndDate) ? $_EventEndDate : null; $_EventAllDay = isset($_EventAllDay) ? $_EventAllDay : false; $isEventAllDay = $_EventAllDay == 'yes' || !TribeDateUtils::dateOnly($_EventStartDate) ? 'checked="checked"' : ''; // default is all day for new posts $startMonthOptions = TribeEventsViewHelpers::getMonthOptions($_EventStartDate); $endMonthOptions = TribeEventsViewHelpers::getMonthOptions($_EventEndDate); $startYearOptions = TribeEventsViewHelpers::getYearOptions($_EventStartDate); $endYearOptions = TribeEventsViewHelpers::getYearOptions($_EventEndDate); $startMinuteOptions = TribeEventsViewHelpers::getMinuteOptions($_EventStartDate, true); $endMinuteOptions = TribeEventsViewHelpers::getMinuteOptions($_EventEndDate); $startHourOptions = TribeEventsViewHelpers::getHourOptions($_EventAllDay == 'yes' ? null : $_EventStartDate, true); $endHourOptions = TribeEventsViewHelpers::getHourOptions($_EventAllDay == 'yes' ? null : $_EventEndDate); $startMeridianOptions = TribeEventsViewHelpers::getMeridianOptions($_EventStartDate, true); $endMeridianOptions = TribeEventsViewHelpers::getMeridianOptions($_EventEndDate); if ($_EventStartDate) { $start = TribeDateUtils::dateOnly($_EventStartDate); } $EventStartDate = isset($start) && $start ? $start : date('Y-m-d'); if (!empty($_REQUEST['eventDate'])) { $EventStartDate = $_REQUEST['eventDate']; } if ($_EventEndDate) { $end = TribeDateUtils::dateOnly($_EventEndDate); } $EventEndDate = isset($end) && $end ? $end : date('Y-m-d'); $recStart = isset($_REQUEST['event_start']) ? $_REQUEST['event_start'] : null; $recPost = isset($_REQUEST['post']) ? $_REQUEST['post'] : null; if (!empty($_REQUEST['eventDate'])) { $duration = get_post_meta($postId, '_EventDuration', true); $EventEndDate = TribeDateUtils::dateOnly(strtotime($EventStartDate) + $duration, true); } $events_meta_box_template = $this->pluginPath . 'admin-views/events-meta-box.php'; $events_meta_box_template = apply_filters('tribe_events_meta_box_template', $events_meta_box_template); include $events_meta_box_template; }
public function where($where, $wp_query) { global $ecp_apm, $wpdb; // run once remove_filter('posts_where', array($this, 'where'), 10, 2); foreach ($this->active as $key => $active) { $field = ''; if ($key === 'ecp_start_date') { $field = "{$wpdb->postmeta}.meta_value"; } if ($key === 'ecp_end_date') { $field = "IFNULL(DATE_ADD(CAST({$wpdb->postmeta}.meta_value AS DATETIME), INTERVAL eventDuration.meta_value SECOND), eventEnd.meta_value)"; } if (empty($field)) { continue; } $value = $active['value']; switch ($active['is']) { case "is": $where .= $wpdb->prepare(" AND {$field} BETWEEN %s AND %s ", TribeDateUtils::beginningOfDay($value), TribeDateUtils::endOfDay($value)); break; case "not": $where .= $wpdb->prepare(" AND {$field} NOT BETWEEN %s AND %s ", TribeDateUtils::beginningOfDay($value), TribeDateUtils::endOfDay($value)); break; case "gte": $where .= $wpdb->prepare(" AND {$field} >= %s ", TribeDateUtils::beginningOfDay($value)); break; case "lte": $where .= $wpdb->prepare(" AND {$field} <= %s ", TribeDateUtils::endOfDay($value)); break; } } return $where; }
/** * Used by createEvent and updateEvent - saves all the various event meta */ public static function saveEventMeta($event_id, $data, $event = null) { $tribe_ecp = TribeEvents::instance(); if (isset($data['EventAllDay']) && ($data['EventAllDay'] == 'yes' || $data['EventAllDay'] == true || !isset($data['EventStartDate']))) { $data['EventStartDate'] = TribeDateUtils::beginningOfDay($data['EventStartDate']); $data['EventEndDate'] = TribeDateUtils::endOfDay($data['EventEndDate']); } else { delete_post_meta($event_id, '_EventAllDay'); if (isset($data['EventStartMeridian'])) { $data['EventStartDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventStartDate'] . " " . $data['EventStartHour'] . ":" . $data['EventStartMinute'] . ":00 " . $data['EventStartMeridian'])); $data['EventEndDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventEndDate'] . " " . $data['EventEndHour'] . ":" . $data['EventEndMinute'] . ":00 " . $data['EventEndMeridian'])); } else { $data['EventStartDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventStartDate'] . " " . $data['EventStartHour'] . ":" . $data['EventStartMinute'] . ":00")); $data['EventEndDate'] = date(TribeDateUtils::DBDATETIMEFORMAT, strtotime($data['EventEndDate'] . " " . $data['EventEndHour'] . ":" . $data['EventEndMinute'] . ":00")); } } if (!isset($data['EventHideFromUpcoming']) || !$data['EventHideFromUpcoming']) { delete_post_meta($event_id, '_EventHideFromUpcoming'); } // sanity check that start date < end date $startTimestamp = strtotime($data['EventStartDate']); $endTimestamp = strtotime($data['EventEndDate']); if ($startTimestamp > $endTimestamp) { $data['EventEndDate'] = $data['EventStartDate']; } if (!isset($data['EventShowMapLink'])) { update_post_meta($event_id, '_EventShowMapLink', 'false'); } if (!isset($data['EventShowMap'])) { update_post_meta($event_id, '_EventShowMap', 'false'); } if (isset($data['post_status'])) { $post_status = $data['post_status']; } else { //print_r($data); if (isset($data["Organizer"]["OrganizerID"])) { $post_status = get_post($data["Organizer"]['OrganizerID'])->post_status; } if (isset($data['Venue']["VenueID"])) { $post_status = get_post($data['Venue']['VenueID'])->post_status; } } if (isset($data["Organizer"])) { $data['EventOrganizerID'] = TribeEventsAPI::saveEventOrganizer($data["Organizer"], $event, $post_status); } if (isset($data["Venue"])) { $data['EventVenueID'] = TribeEventsAPI::saveEventVenue($data["Venue"], $event, $post_status); } $tribe_ecp->do_action('tribe_events_event_save', $event_id); //update meta fields foreach ($tribe_ecp->metaTags as $tag) { $htmlElement = ltrim($tag, '_'); if (isset($data[$htmlElement]) && $tag != TribeEvents::EVENTSERROROPT) { if (is_string($data[$htmlElement])) { $data[$htmlElement] = filter_var($data[$htmlElement], FILTER_SANITIZE_STRING); } update_post_meta($event_id, $tag, $data[$htmlElement]); } } $tribe_ecp->do_action('tribe_events_update_meta', $event_id, false, $data, $event); }
/** * Convert the event recurrence meta into a human readable string * @param array $postId The recurring event * @return The human readable string */ public static function recurrenceToText($postId = null) { $text = ""; $custom_text = ""; $occurrence_text = ""; if ($postId == null) { global $post; $postId = $post->ID; } extract(TribeEventsRecurrenceMeta::getRecurrenceMeta($postId)); if ($recType == "Every Day") { $text = __("Every day", 'tribe-events-calendar-pro'); $occurrence_text = sprintf(_n(" for %d day", " for %d days", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); $custom_text = ""; } else { if ($recType == "Every Week") { $text = __("Every week", 'tribe-events-calendar-pro'); $occurrence_text = sprintf(_n(" for %d week", " for %d weeks", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } else { if ($recType == "Every Month") { $text = __("Every month", 'tribe-events-calendar-pro'); $occurrence_text = sprintf(_n(" for %d month", " for %d months", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } else { if ($recType == "Every Year") { $text = __("Every year", 'tribe-events-calendar-pro'); $occurrence_text = sprintf(_n(" for %d year", " for %d years", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } else { if ($recType == "Custom") { if ($recCustomType == "Daily") { $text = $recCustomInterval == 1 ? __("Every day", 'tribe-events-calendar-pro') : sprintf(__("Every %d days", 'tribe-events-calendar-pro'), $recCustomInterval); $occurrence_text = sprintf(_n(", recurring %d time", ", recurring %d times", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } else { if ($recCustomType == "Weekly") { $text = $recCustomInterval == 1 ? __("Every week", 'tribe-events-calendar-pro') : sprintf(__("Every %d weeks", 'tribe-events-calendar-pro'), $recCustomInterval); $custom_text = sprintf(__(" on %s", 'tribe-events-calendar-pro'), self::daysToText($recCustomWeekDay)); $occurrence_text = sprintf(_n(", recurring %d time", ", recurring %d times", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } else { if ($recCustomType == "Monthly") { $text = $recCustomInterval == 1 ? __("Every month", 'tribe-events-calendar-pro') : sprintf(__("Every %d months", 'tribe-events-calendar-pro'), $recCustomInterval); $number_display = is_numeric($recCustomMonthNumber) ? TribeDateUtils::numberToOrdinal($recCustomMonthNumber) : strtolower($recCustomMonthNumber); $custom_text = sprintf(__(" on the %s %s", 'tribe-events-calendar-pro'), $number_display, is_numeric($recCustomMonthNumber) ? __("day", 'tribe-events-calendar-pro') : self::daysToText($recCustomMonthDay)); $occurrence_text = sprintf(_n(", recurring %d time", ", recurring %d times", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } else { if ($recCustomType == "Yearly") { $text = $recCustomInterval == 1 ? __("Every year", 'tribe-events-calendar-pro') : sprintf(__("Every %d years", 'tribe-events-calendar-pro'), $recCustomInterval); $customYearNumber = $recCustomYearMonthNumber != -1 ? TribeDateUtils::numberToOrdinal($recCustomYearMonthNumber) : __("last", 'tribe-events-calendar-pro'); $day = $recCustomYearFilter ? $customYearNumber : TribeDateUtils::numberToOrdinal(date('j', strtotime(TribeEvents::getRealStartDate($postId)))); $of_week = $recCustomYearFilter ? self::daysToText($recCustomYearMonthDay) : ""; $months = self::monthsToText($recCustomYearMonth); $custom_text = sprintf(__(" on the %s %s of %s", 'tribe-events-calendar-pro'), $day, $of_week, $months); $occurrence_text = sprintf(_n(", recurring %d time", ", recurring %d times", $recEndCount, 'tribe-events-calendar-pro'), $recEndCount); } } } } } } } } } // end text if ($recEndType == "On") { $endText = ' ' . sprintf(__(" until %s", 'tribe-events-calendar-pro'), date_i18n(get_option('date_format'), strtotime($recEnd))); } else { $endText = $occurrence_text; } return sprintf(__('%s%s%s', 'tribe-events-calendar-pro'), $text, $custom_text, $endText); }
/** * Gets the event counts for individual days. * * @param array $args * * @return array The counts array. */ public static function getEventCounts($args = array()) { global $wpdb; do_action('log', 'getEventCounts() $args', 'tribe-events-query', $args); $date = date('Y-m-d'); $defaults = array('post_type' => TribeEvents::POSTTYPE, 'start_date' => tribe_event_beginning_of_day($date), 'end_date' => tribe_event_end_of_day($date), 'display_type' => 'daily', 'hide_upcoming_ids' => null); $args = wp_parse_args($args, $defaults); $args['posts_per_page'] = -1; $args['fields'] = 'ids'; // remove empty args and sort by key, this increases chance of a cache hit $args = array_filter($args, array(__CLASS__, 'filter_args')); ksort($args); $cache = new TribeEventsCache(); $cache_key = 'daily_counts_and_ids_' . serialize($args); $found = $cache->get($cache_key, 'save_post'); if ($found) { do_action('log', 'cache hit ' . __LINE__, 'tribe-events-cache', $args); return $found; } do_action('log', 'no cache hit ' . __LINE__, 'tribe-events-cache', $args); $cache_key = 'month_post_ids_' . serialize($args); $found = $cache->get($cache_key, 'save_post'); if ($found && is_array($found)) { do_action('log', 'cache hit ' . __LINE__, 'tribe-events-cache', $args); $post_ids = $found; } else { do_action('log', 'no cache hit ' . __LINE__, 'tribe-events-cache', $args); $post_id_query = new WP_Query(); $post_ids = $post_id_query->query($args); do_action('log', 'final args for month view post ids', 'tribe-events-query', $post_id_query->query_vars); do_action('log', 'Month view getEventCounts SQL', 'tribe-events-query', $post_id_query->request); $cache->set($cache_key, $post_ids, TribeEventsCache::NON_PERSISTENT, 'save_post'); } do_action('log', 'Month view post ids found', 'tribe-events-query', $post_ids); $counts = array(); $event_ids = array(); if (!empty($post_ids)) { switch ($args['display_type']) { case 'daily': default: global $wp_query; $output_date_format = '%Y-%m-%d %H:%i:%s'; do_action('log', 'raw counts args', 'tribe-events-query', $args); $raw_counts = $wpdb->get_results($wpdb->prepare("\n\t\t\t\t\t\t\tSELECT \ttribe_event_start.post_id as ID, \n\t\t\t\t\t\t\t\t\ttribe_event_start.meta_value as EventStartDate, \n\t\t\t\t\t\t\t\t\tDATE_FORMAT( tribe_event_end_date.meta_value, '%1\$s') as EventEndDate,\n\t\t\t\t\t\t\t\t\t{$wpdb->posts}.menu_order as menu_order\n\t\t\t\t\t\t\tFROM {$wpdb->postmeta} AS tribe_event_start\n\t\t\t\t\t\t\t\t\tLEFT JOIN {$wpdb->posts} ON (tribe_event_start.post_id = {$wpdb->posts}.ID)\n\t\t\t\t\t\t\tLEFT JOIN {$wpdb->postmeta} as tribe_event_end_date ON ( tribe_event_start.post_id = tribe_event_end_date.post_id AND tribe_event_end_date.meta_key = '_EventEndDate' )\n\t\t\t\t\t\t\tWHERE tribe_event_start.meta_key = '_EventStartDate'\n\t\t\t\t\t\t\tAND tribe_event_start.post_id IN ( %5\$s )\n\t\t\t\t\t\t\tAND ( (tribe_event_start.meta_value >= '%3\$s' AND tribe_event_start.meta_value <= '%4\$s')\n\t\t\t\t\t\t\t\tOR (tribe_event_start.meta_value <= '%3\$s' AND tribe_event_end_date.meta_value >= '%3\$s')\n\t\t\t\t\t\t\t\tOR ( tribe_event_start.meta_value >= '%3\$s' AND tribe_event_start.meta_value <= '%4\$s')\n\t\t\t\t\t\t\t)\n\t\t\t\t\t\t\tORDER BY menu_order ASC, DATE(tribe_event_start.meta_value) ASC, TIME(tribe_event_start.meta_value) ASC;", $output_date_format, $output_date_format, $post_id_query->query_vars['start_date'], $post_id_query->query_vars['end_date'], implode(',', array_map('intval', $post_ids)))); do_action('log', 'raw counts query', 'tribe-events-query', $wpdb->last_query); $start_date = new DateTime($post_id_query->query_vars['start_date']); $end_date = new DateTime($post_id_query->query_vars['end_date']); $days = TribeDateUtils::dateDiff($start_date->format('Y-m-d'), $end_date->format('Y-m-d')); $term_id = isset($wp_query->query_vars[TribeEvents::TAXONOMY]) ? $wp_query->query_vars[TribeEvents::TAXONOMY] : null; if (is_int($term_id)) { $term = get_term_by('id', $term_id, TribeEvents::TAXONOMY); } elseif (is_string($term_id)) { $term = get_term_by('slug', $term_id, TribeEvents::TAXONOMY); } for ($i = 0, $date = $start_date; $i <= $days; $i++, $date->modify('+1 day')) { $formatted_date = $date->format('Y-m-d'); $start_of_day = strtotime(tribe_event_beginning_of_day($formatted_date)); $end_of_day = strtotime(tribe_event_end_of_day($formatted_date)) + 1; $count = 0; $_day_event_ids = array(); foreach ($raw_counts as $record) { $record_start = strtotime($record->EventStartDate); $record_end = strtotime($record->EventEndDate); /** * conditions: * event starts on this day (event start time is between start and end of day) * event ends on this day (event end time is between start and end of day) * event starts before start of day and ends after end of day (spans across this day) * note: * events that start exactly on the EOD cutoff will count on the following day * events that end exactly on the EOD cutoff will count on the previous day */ $event_starts_today = $record_start >= $start_of_day && $record_start < $end_of_day; $event_ends_today = $record_end > $start_of_day && $record_end <= $end_of_day; $event_spans_across_today = $record_start < $start_of_day && $record_end > $end_of_day; if ($event_starts_today || $event_ends_today || $event_spans_across_today) { if (isset($term->term_id)) { if (!has_term($term, TribeEvents::TAXONOMY, $record->ID)) { continue; } } if (count($_day_event_ids) < apply_filters('tribe_events_month_day_limit', tribe_get_option('monthEventAmount', '3'))) { $_day_event_ids[] = $record->ID; } $count++; } } $event_ids[$formatted_date] = $_day_event_ids; $counts[$formatted_date] = $count; } break; } // get a unique list of the event IDs that will be displayed, and update all their postmeta and term caches at once $final_event_ids = array(); $final_event_ids = call_user_func_array('array_merge', $event_ids); $final_event_ids = array_unique($final_event_ids); do_action('log', 'updating term and postmeta caches for events', 'tribe-events-cache', $final_event_ids); update_object_term_cache($final_event_ids, TribeEvents::POSTTYPE); update_postmeta_cache($final_event_ids); } // return IDs per day and total counts per day $return = array('counts' => $counts, 'event_ids' => $event_ids); $cache = new TribeEventsCache(); $cache_key = 'daily_counts_and_ids_' . serialize($args); $cache->set($cache_key, $return, TribeEventsCache::NON_PERSISTENT, 'save_post'); do_action('log', 'final event counts result', 'tribe-events-query', $return); return $return; }
public function iCalFeed($post = null, $eventCatSlug = null, $eventDate = null) { $tribeEvents = TribeEvents::instance(); $postId = $post ? $post->ID : null; $getstring = isset($_GET['ical']) ? $_GET['ical'] : null; $wpTimezoneString = get_option('timezone_string'); $postType = TribeEvents::POSTTYPE; $events = ''; $lastBuildDate = ''; $eventsTestArray = array(); $blogHome = get_bloginfo('url'); $blogName = get_bloginfo('name'); $includePosts = $postId ? '&include=' . $postId : ''; $eventsCats = $eventCatSlug ? '&' . TribeEvents::TAXONOMY . '=' . $eventCatSlug : ''; if ($post) { $eventPosts = array(); $eventPosts[] = $post; } else { $eventPosts = get_posts('posts_per_page=-1&post_type=' . $postType . $includePosts . $eventsCats); } foreach ($eventPosts as $eventPost) { if ($eventDate) { $duration = TribeDateUtils::timeBetween($eventPost->EventStartDate, $eventPost->EventEndDate); $startDate = TribeDateUtils::addTimeToDate($eventDate, TribeDateUtils::timeOnly($eventPost->EventStartDate)); $endDate = TribeDateUtils::dateAndTime(strtotime($startDate) + $duration, true); } else { $startDate = $eventPost->EventStartDate; $endDate = $eventPost->EventEndDate; } // convert 2010-04-08 00:00:00 to 20100408T000000 or YYYYMMDDTHHMMSS $startDate = str_replace(array('-', ' ', ':'), array('', 'T', ''), $startDate); $endDate = str_replace(array('-', ' ', ':'), array('', 'T', ''), $endDate); if (get_post_meta($eventPost->ID, '_EventAllDay', true) == 'yes') { $startDate = substr($startDate, 0, 8); $endDate = substr($endDate, 0, 8); // endDate bumped ahead one day to counter iCal's off-by-one error $endDateStamp = strtotime($endDate); $endDate = date('Ymd', $endDateStamp + 86400); $type = 'DATE'; } else { $type = 'DATE-TIME'; } $description = preg_replace("/[\n\t\r]/", ' ', strip_tags($eventPost->post_content)); // add fields to iCal output $item = array(); $item[] = "DTSTART;VALUE={$type}:" . $startDate; $item[] = "DTEND;VALUE={$type}:" . $endDate; $item[] = 'DTSTAMP:' . date('Ymd\\THis', time()); $item[] = 'CREATED:' . str_replace(array('-', ' ', ':'), array('', 'T', ''), $eventPost->post_date); $item[] = 'LAST-MODIFIED:' . str_replace(array('-', ' ', ':'), array('', 'T', ''), $eventPost->post_modified); $item[] = 'UID:' . $eventPost->ID . '-' . strtotime($startDate) . '-' . strtotime($endDate) . '@' . $blogHome; $item[] = 'SUMMARY:' . $eventPost->post_title; $item[] = 'DESCRIPTION:' . str_replace(',', '\\,', $description); $item[] = 'LOCATION:' . html_entity_decode($tribeEvents->fullAddressString($eventPost->ID), ENT_QUOTES); $item[] = 'URL:' . get_permalink($eventPost->ID); $item = apply_filters('tribe_ical_feed_item', $item, $eventPost); $events .= "BEGIN:VEVENT\n" . implode("\n", $item) . "\nEND:VEVENT\n"; } header('Content-type: text/calendar'); header('Content-Disposition: attachment; filename="iCal-TribeEvents.ics"'); $content = "BEGIN:VCALENDAR\n"; $content .= "VERSION:2.0\n"; $content .= 'PRODID:-//' . $blogName . ' - ECPv' . TribeEvents::VERSION . "//NONSGML v1.0//EN\n"; $content .= "CALSCALE:GREGORIAN\n"; $content .= "METHOD:PUBLISH\n"; $content .= 'X-WR-CALNAME:' . apply_filters('tribe_ical_feed_calname', $blogName) . "\n"; $content .= 'X-ORIGINAL-URL:' . $blogHome . "\n"; $content .= 'X-WR-CALDESC:Events for ' . $blogName . "\n"; if ($wpTimezoneString) { $content .= 'X-WR-TIMEZONE:' . $wpTimezoneString . "\n"; } $content = apply_filters('tribe_ical_properties', $content); $content .= $events; $content .= 'END:VCALENDAR'; echo $content; exit; }