function mc_instance_list($id, $occur = false, $template = '<h3>{title}</h3>{description}', $list = '<li>{date}, {time}</li>', $before = "<ul>", $after = "</ul>", $instance = false)
{
    global $wpdb;
    $id = (int) $id;
    $output = '';
    if ($instance == true) {
        $sql = "SELECT * FROM " . my_calendar_event_table() . " WHERE occur_id={$id}";
    } else {
        $sql = "SELECT * FROM " . my_calendar_event_table() . " WHERE occur_event_id={$id}";
    }
    $results = $wpdb->get_results($sql);
    if (is_array($results) && is_admin()) {
        foreach ($results as $result) {
            $begin = "<span id='occur_date_{$result->occur_id}'>" . date_i18n(get_option('mc_date_format'), strtotime($result->occur_begin)) . ', ' . date(get_option('mc_time_format'), strtotime($result->occur_begin)) . "</span>";
            if ($result->occur_id == $occur) {
                $form_control = '';
                $edit = "<em>" . __('Editing Now', 'my-calendar') . "</em>";
            } else {
                $form_control = "{$begin}: <button class='delete_occurrence' type='button' data-value='{$result->occur_id}' aria-describedby='occur_date_{$result->occur_id}' />" . __('Delete', 'my-calendar') . "</button> ";
                $edit = "<a href='" . admin_url('admin.php?page=my-calendar') . "&amp;mode=edit&amp;event_id={$id}&amp;date={$result->occur_id}' aria-describedby='occur_date_{$result->occur_id}'>" . __('Edit', 'my-calendar') . "</a>";
            }
            $output .= "<li>{$form_control}{$edit}</li>";
        }
    } else {
        $details = '';
        foreach ($results as $result) {
            $event_id = $result->occur_id;
            $event = mc_get_event($event_id);
            $array = mc_create_tags($event);
            if (in_array($template, array('details', 'grid', 'list', 'mini')) || mc_key_exists($template)) {
                if (get_option('mc_use_' . $template . '_template') == 1) {
                    $template = mc_get_template($template);
                } else {
                    if (mc_key_exists($template)) {
                        $template = mc_get_custom_template($template);
                    } else {
                        $details = my_calendar_draw_event($event, $type = "single", $event->event_begin, $event->event_time, '');
                    }
                }
            }
            $item = $list != '' ? jd_draw_template($array, $list) : '';
            if ($details == '') {
                $details = $template != '' ? jd_draw_template($array, $template) : '';
            }
            $output .= $item;
            if ($list == '') {
                break;
            }
        }
        $output = $details . $before . $output . $after;
    }
    return get_option('mc_process_shortcodes') == 'true' ? do_shortcode($output) : $output;
}
function edit_mc_templates()
{
    $templates = get_option('mc_templates');
    if (!empty($_POST)) {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce, 'my-calendar-nonce')) {
            die("Security check failed");
        }
    }
    if (isset($_POST['mc_template_key'])) {
        $key = $_POST['mc_template_key'];
    } else {
        $key = isset($_GET['mc_template']) ? $_GET['mc_template'] : 'grid';
    }
    if (isset($_POST['delete'])) {
        delete_option('mc_ctemplate_' . $key);
        echo "<div class=\"updated\"><p>" . __('Custom template deleted', 'my-calendar') . "</p></div>";
        $key = 'grid';
    } else {
        if (mc_is_core_template($key) && isset($_POST['add-new'])) {
            echo "<div class=\"updated\"><p>" . __('Custom templates cannot have the same key as a core template', 'my-calendar') . "</p></div>";
        } else {
            if (mc_is_core_template($key) && isset($_POST['mc_template'])) {
                $template = $_POST['mc_template'];
                $templates[$key] = $template;
                update_option('mc_templates', $templates);
                update_option('mc_use_' . $key . '_template', empty($_POST['mc_use_template']) ? 0 : 1);
                echo "<div class=\"updated\"><p>" . sprintf(__('%s Template saved', 'my-calendar'), ucfirst($key)) . "</p></div>";
            } else {
                if (isset($_POST['mc_template'])) {
                    $template = $_POST['mc_template'];
                    if (mc_key_exists($key)) {
                        $key = mc_update_template($key, $template);
                    } else {
                        $key = mc_create_template($template);
                    }
                    echo "<div class='updated'><p>" . __('Custom Template saved', 'my-calendar') . "</p></div>";
                }
            }
        }
    }
    // TODO: create UI for managing additional templates
    // TODO: create admin system for modifying shortcodes
    global $grid_template, $list_template, $mini_template, $single_template, $rss_template;
    $mc_grid_template = $templates['grid'] != '' ? $templates['grid'] : $grid_template;
    $mc_rss_template = $templates['rss'] != '' ? $templates['rss'] : $rss_template;
    $mc_list_template = $templates['list'] != '' ? $templates['list'] : $list_template;
    $mc_mini_template = $templates['mini'] != '' ? $templates['mini'] : $mini_template;
    $mc_details_template = $templates['details'] != '' ? $templates['details'] : $single_template;
    $template = mc_is_core_template($key) ? ${"mc_" . $key . "_template"} : mc_get_custom_template($key);
    $template = stripslashes($template);
    $core = mc_template_description($key);
    ?>
	<div class="wrap jd-my-calendar">
		<?php 
    my_calendar_check_db();
    ?>
		<h1 class="wp-heading-inline"><?php 
    _e('My Calendar Templates', 'my-calendar');
    ?>
</h1>
		<a href="<?php 
    echo add_query_arg('mc_template', 'add-new', admin_url("admin.php?page=my-calendar-templates"));
    ?>
" class="page-title-action"><?php 
    _e('Add New', 'my-calendar');
    ?>
</a> 
		<hr class="wp-header-end">
		<div class="postbox-container jcd-wide">
			<div class="metabox-holder">
				<div class="ui-sortable meta-box-sortables">
					<div class="postbox">
						<h2><?php 
    _e('Edit Template', 'my-calendar');
    ?>
</h2>
						<div class="inside">
							<p>
								<a href="<?php 
    echo admin_url("admin.php?page=my-calendar-help#templates");
    ?>
"><?php 
    _e("Templates Help", 'my-calendar');
    ?>
</a> &raquo;
							</p>
							<?php 
    if ($core != '') {
        echo "<p class='template-description'>{$core}</p>";
    }
    ?>
							<?php 
    if ($key == 'add-new') {
        ?>
								<form method="post" action="<?php 
        echo add_query_arg('mc_template', $key, admin_url("admin.php?page=my-calendar-templates"));
        ?>
">
								<div>
									<input type="hidden" name="_wpnonce" value="<?php 
        echo wp_create_nonce('my-calendar-nonce');
        ?>
"/>
								</div>
								<p>
									<label for="mc_template_key"><?php 
        _e('Template Description (required)', 'my-calendar');
        ?>
</label><br />
									<input type="text" class="widefat" name="mc_template_key" id="mc_template_key" value="" required />
								</p>
								<p>
									<label for="mc_template"><?php 
        _e('Custom Template', 'my-calendar');
        ?>
</label><br/>
									<textarea id="mc_template" name="mc_template" class="template-editor widefat" rows="32" cols="76"></textarea>
								</p>

								<p>
									<input type="submit" name="save" class="button-primary" value="<?php 
        _e('Add Template', 'my-calendar');
        ?>
" />
								</p>
							</form>								
							<?php 
    } else {
        ?>
							<form method="post" action="<?php 
        echo add_query_arg('mc_template', $key, admin_url("admin.php?page=my-calendar-templates"));
        ?>
">
								<div>
									<input type="hidden" name="_wpnonce" value="<?php 
        echo wp_create_nonce('my-calendar-nonce');
        ?>
"/>
									<input type="hidden" name="mc_template_key" value="<?php 
        esc_attr_e($key);
        ?>
"/>
								</div>
								<?php 
        if (mc_is_core_template($key)) {
            ?>
								<p>
									<input type="checkbox" id="mc_use_template" name="mc_use_template" value="1" <?php 
            mc_is_checked("mc_use_" . $key . "_template", 1);
            ?>
 /> <label for="mc_use_template"><?php 
            _e('Use this template', 'my-calendar');
            ?>
</label>
								</p>
								<?php 
        }
        ?>
								<p>
									<label for="mc_template"><?php 
        _e('Custom Template', 'my-calendar');
        ?>
</label><br/>
									<textarea id="mc_template" name="mc_template" class="template-editor widefat" rows="32" cols="76"><?php 
        echo $template;
        ?>
</textarea>
								</p>
								<p>
									<input type="submit" name="save" class="button-primary" value="<?php 
        _e('Update Template', 'my-calendar');
        ?>
" />
								<?php 
        if (!mc_is_core_template($key)) {
            ?>
									<input type="submit" name="delete" class="button-secondary" value=<?php 
            _e('Delete Template', 'my-calendar');
            ?>
" />
								<?php 
        }
        ?>
								</p>
							</form>
							<?php 
    }
    ?>
						</div>
					</div>
				</div>
			</div>
			<div class="metabox-holder">
				<div class="ui-sortable meta-box-sortables">
					<div class="postbox">
						<h2><?php 
    _e('Templates', 'my-calendar');
    ?>
</h2>

						<div class="inside">
							<?php 
    mc_list_templates();
    ?>
							<p>
								<a href="<?php 
    echo add_query_arg('mc_template', 'add-new', admin_url("admin.php?page=my-calendar-templates"));
    ?>
"><?php 
    _e('Add New Template', 'my-calendar');
    ?>
</a>
							</p>							
						</div>
					</div>
				</div>
			</div>
			<div class="metabox-holder">
				<div class="ui-sortable meta-box-sortables">
					<div class="postbox">
						<h2 class='hndle'><?php 
    _e('Event Template Tags', 'my-calendar');
    ?>
</h2>

						<div class='mc_template_tags inside'>
							<p>
								<a href="<?php 
    echo admin_url('admin.php?page=my-calendar-help#templates');
    ?>
"><?php 
    _e('All Template Tags &raquo;', 'my-calendar');
    ?>
</a>
							</p>						
							<dl>
								<dt><code>{title}</code></dt>
								<dd><?php 
    _e('Title of the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{link_title}</code></dt>
								<dd><?php 
    _e('Title of the event as a link if a URL is present, or the title alone if not.', 'my-calendar');
    ?>
</dd>

								<dt><code>{time}</code></dt>
								<dd><?php 
    _e('Start time for the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{date}</code></dt>
								<dd><?php 
    _e('Date on which the event begins.', 'my-calendar');
    ?>
</dd>

								<dt><code>{daterange}</code></dt>
								<dd><?php 
    _e('Beginning date to end date; excludes end date if same as beginning.', 'my-calendar');
    ?>
</dd>

								<dt><code>{multidate}</code></dt>
								<dd><?php 
    _e('Multi-day events: an unordered list of dates/times. Otherwise, beginning date/time.', 'my-calendar');
    ?>
</dd>

								<dt><code>{author}</code></dt>
								<dd><?php 
    _e('Author who posted the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{host}</code></dt>
								<dd><?php 
    _e('Name of the assigned host for the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{shortdesc}</code></dt>
								<dd><?php 
    _e('Short event description.', 'my-calendar');
    ?>
</dd>

								<dt><code>{description}</code></dt>
								<dd><?php 
    _e('Description of the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{image}</code></dt>
								<dd><?php 
    _e('Image associated with the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{link}</code></dt>
								<dd><?php 
    _e('URL provided for the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{details}</code></dt>
								<dd><?php 
    _e('Link to an auto-generated page containing information about the event.', 'my-calendar');
    ?>

								<dt><code>{event_open}</code></dt>
								<dd><?php 
    _e('Whether event is currently open for registration.', 'my-calendar');
    ?>
</dd>

								<dt><code>{event_status}</code></dt>
								<dd><?php 
    _e('Current status of event: either "Published" or "Reserved."', 'my-calendar');
    ?>
</dd>
							</dl>

							<h3><?php 
    _e('Location Template Tags', 'my-calendar');
    ?>
</h3>
							<dl>
								<dt><code>{location}</code></dt>
								<dd><?php 
    _e('Name of the location of the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{street}</code></dt>
								<dd><?php 
    _e('First line of the site address.', 'my-calendar');
    ?>
</dd>

								<dt><code>{street2}</code></dt>
								<dd><?php 
    _e('Second line of the site address.', 'my-calendar');
    ?>
</dd>

								<dt><code>{city}</code></dt>
								<dd><?php 
    _e('City', 'my-calendar');
    ?>
</dd>

								<dt><code>{state}</code></dt>
								<dd><?php 
    _e('State', 'my-calendar');
    ?>
</dd>

								<dt><code>{postcode}</code></dt>
								<dd><?php 
    _e('Postal Code', 'my-calendar');
    ?>
</dd>

								<dt><code>{region}</code></dt>
								<dd><?php 
    _e('Custom region.', 'my-calendar');
    ?>
</dd>

								<dt><code>{country}</code></dt>
								<dd><?php 
    _e('Country for the event location.', 'my-calendar');
    ?>
</dd>

								<dt><code>{sitelink}</code></dt>
								<dd><?php 
    _e('Output the URL for the location.', 'my-calendar');
    ?>
</dd>

								<dt><code>{hcard}</code></dt>
								<dd><?php 
    _e('Event address in <a href="http://microformats.org/wiki/hcard">hcard</a> format.', 'my-calendar');
    ?>
</dd>

								<dt><code>{link_map}</code></dt>
								<dd><?php 
    _e('Link to Google Map to the event, if address information is available.', 'my-calendar');
    ?>
</dd>
							</dl>
							<h3><?php 
    _e('Category Template Tags', 'my-calendar');
    ?>
</h3>

							<dl>
								<dt><code>{category}</code></dt>
								<dd><?php 
    _e('Name of the category of the event.', 'my-calendar');
    ?>
</dd>

								<dt><code>{icon}</code></dt>
								<dd><?php 
    _e('URL for the event\'s category icon.', 'my-calendar');
    ?>
</dd>

								<dt><code>{color}</code></dt>
								<dd><?php 
    _e('Hex code for the event\'s category color.', 'my-calendar');
    ?>
</dd>

								<dt><code>{cat_id}</code></dt>
								<dd><?php 
    _e('ID of the category of the event.', 'my-calendar');
    ?>
</dd>
							</dl>
						</div>
					</div>
				</div>
			</div>
		</div>
	</div>
	<?php 
    mc_show_sidebar();
}
function my_calendar_show_locations($datatype = 'name', $template = '')
{
    global $wpdb;
    $mcdb = $wpdb;
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        $mcdb = mc_remote_db();
    }
    switch ($datatype) {
        case "name":
        case "location":
            $data = "location_label";
            break;
        case "city":
            $data = "location_city";
            break;
        case "state":
            $data = "location_state";
            break;
        case "zip":
            $data = "location_postcode";
            break;
        case "country":
            $data = "location_country";
            break;
        case "hcard":
            $data = "location_label";
            break;
        case "region":
            $data = "location_region";
            break;
        default:
            $data = "location_label";
    }
    $locations = $mcdb->get_results("SELECT DISTINCT * FROM " . my_calendar_locations_table() . " ORDER BY {$data} ASC");
    if ($locations) {
        $output = "<ul class='mc-locations'>";
        foreach ($locations as $key => $value) {
            if ($datatype != 'hcard' && $template == '') {
                $label = stripslashes($value->{$data});
                $url = mc_maplink($value, 'url', $source = 'location');
                if ($url) {
                    $output .= "<li>{$url}</li>";
                } else {
                    $output .= "<li>{$label}</li>";
                }
            } else {
                if ($datatype == 'hcard') {
                    $label = mc_hcard($value, true, true, 'location');
                    $output .= "<li>{$label}</li>";
                } else {
                    if ($template != '') {
                        if (mc_key_exists($template)) {
                            $template = mc_get_custom_template($template);
                        }
                        $values = array('id' => $value->location_id, 'label' => $value->location_label, 'street' => $value->location_street, 'street2' => $value->location_street2, 'city' => $value->location_city, 'state' => $value->location_state, 'postcode' => $value->location_postcode, 'region' => $value->location_region, 'url' => $value->location_url, 'country' => $value->location_country, 'longitude' => $value->location_longitude, 'latitude' => $value->location_latitude, 'zoom' => $value->location_zoom, 'phone' => $value->location_phone);
                        $label = jd_draw_template($values, $template);
                        $output .= "<li>{$label}</li>";
                    }
                }
            }
        }
        $output .= "</ul>";
        $output = apply_filters('mc_location_list', $output, $locations);
        return $output;
    }
    return '';
}
function my_calendar_todays_events($category = 'default', $template = 'default', $substitute = '', $author = 'all', $host = 'all', $date = false, $site = false)
{
    if ($site) {
        $site = $site == 'global' ? BLOG_ID_CURRENT_SITE : $site;
        switch_to_blog($site);
    }
    $caching = apply_filters('mc_cache_enabled', false);
    $todays_cache = $caching ? get_transient('mc_todays_cache') : '';
    if ($caching && is_array($todays_cache) && @$todays_cache[$category]) {
        return @$todays_cache[$category];
    }
    $args = array('category' => $category, 'template' => $template, 'substitute' => $substitute, 'author' => $author, 'host' => $host, 'date' => $date);
    $hash = md5(implode(',', $args));
    global $default_template;
    $output = '';
    // allow reference by file to external template.
    if ($template != '' && mc_file_exists(sanitize_file_name($template))) {
        $template = @file_get_contents(mc_get_file(sanitize_file_name($template)));
    }
    $defaults = get_option('mc_widget_defaults');
    $template = $template == 'default' ? $defaults['today']['template'] : $template;
    $template = $template == '' ? $default_template : $template;
    if (mc_key_exists($template)) {
        $template = mc_get_custom_template($template);
    }
    $category = $category == 'default' ? $defaults['today']['category'] : $category;
    $no_event_text = $substitute == '' ? $defaults['today']['text'] : $substitute;
    if ($date) {
        $from = $to = date('Y-m-d', strtotime($date));
    } else {
        $from = $to = date('Y-m-d', current_time('timestamp'));
    }
    $events = my_calendar_events($from, $to, $category, '', '', 'upcoming', $author, $host, '', $site);
    $today = isset($events[$from]) ? $events[$from] : false;
    $header = "<ul id='todays-events-{$hash}' class='todays-events'>";
    $footer = "</ul>";
    $groups = $todays_events = array();
    // quick loop through all events today to check for holidays
    if (is_array($today)) {
        foreach ($today as $e) {
            if ($e->category_private == 1 && !is_user_logged_in()) {
            } else {
                if (!in_array($e->event_group_id, $groups)) {
                    $event_details = mc_create_tags($e);
                    $ts = $e->ts_occur_begin;
                    $end = $e->ts_occur_end;
                    $now = current_time('timestamp');
                    $category = 'mc_' . sanitize_title($e->category_name);
                    if ($ts < $now && $end > $now) {
                        $class = 'on-now';
                    } else {
                        if ($now < $ts) {
                            $class = 'future-event';
                        } else {
                            if ($now > $ts) {
                                $class = 'past-event';
                            }
                        }
                    }
                    $prepend = apply_filters('mc_todays_events_before', "<li class='{$class} {$category}'>", $class, $category);
                    $append = apply_filters('mc_todays_events_after', "</li>");
                    if (get_option('mc_event_approve') == 'true') {
                        if ($e->event_approved != 0) {
                            $todays_events[$ts][] = $prepend . jd_draw_template($event_details, $template) . $append;
                        }
                    } else {
                        $todays_events[$ts][] = $prepend . jd_draw_template($event_details, $template) . $append;
                    }
                }
            }
        }
        $todays_events = apply_filters('mc_event_today', $todays_events, $events);
        foreach ($todays_events as $k => $t) {
            foreach ($t as $now) {
                $output .= $now;
            }
        }
        if (count($events) != 0) {
            $return = apply_filters('mc_todays_events_header', $header) . $output . apply_filters('mc_todays_events_footer', $footer);
        } else {
            $return = stripcslashes($no_event_text);
        }
        $time = strtotime(date('Y-m-d H:m:s', current_time('timestamp'))) - strtotime(date('Y-m-d', current_time('timestamp')));
        $time_remaining = 24 * 60 * 60 - $time;
        $todays_cache[$category] = $caching ? $return : '';
        if ($caching) {
            set_transient('mc_todays_cache', $todays_cache, $time_remaining);
        }
    } else {
        $return = stripcslashes($no_event_text);
    }
    if ($site) {
        restore_current_blog();
    }
    return get_option('mc_process_shortcodes') == 'true' ? do_shortcode($return) : $return;
}
function my_calendar_events_now($category = 'default', $template = '<strong>{link_title}</strong> {timerange}', $site = '')
{
    if ($site) {
        $site = $site == 'global' ? BLOG_ID_CURRENT_SITE : $site;
        switch_to_blog($site);
    }
    global $wpdb;
    $mcdb = $wpdb;
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        $mcdb = mc_remote_db();
    }
    $arr_events = array();
    $limit_string = "event_flagged <> 1 AND event_approved = 1";
    $select_category = $category != 'default' ? mc_select_category($category) : '';
    // may add support for location/author/host later.
    $select_location = $select_author = $select_host = '';
    $now = date('Y-m-d H:i:s', current_time('timestamp'));
    $event_query = "SELECT *, UNIX_TIMESTAMP(occur_begin) AS ts_occur_begin, UNIX_TIMESTAMP(occur_end) AS ts_occur_end\r\n\t\t\t\t\tFROM " . my_calendar_event_table($site) . " AS e \r\n\t\t\t\t\tJOIN " . my_calendar_table($site) . " AS t \r\n\t\t\t\t\tON (event_id=occur_event_id) \t\t\t\t\t\r\n\t\t\t\t\tJOIN " . my_calendar_categories_table($site) . " AS c \r\n\t\t\t\t\tON (event_category=category_id) \r\n\t\t\t\t\tWHERE {$select_category} {$select_location} {$select_author} {$select_host} {$limit_string}  \r\n\t\t\t\t\tAND ( CAST('{$now}' AS DATETIME) BETWEEN occur_begin AND occur_end ) \r\n\t\t\t\t\t\tORDER BY " . apply_filters('mc_primary_sort', 'occur_begin') . ", " . apply_filters('mc_secondary_sort', 'event_title ASC');
    $events = $mcdb->get_results($event_query);
    if (!empty($events)) {
        foreach (array_keys($events) as $key) {
            $event =& $events[$key];
            $arr_events[] = $event;
        }
    }
    if (!empty($arr_events)) {
        $event = mc_create_tags($arr_events[0]);
        if (mc_key_exists($template)) {
            $template = mc_get_custom_template($template);
        }
        $output = jd_draw_template($event, apply_filters('mc_happening_now_template', $template, $event));
        $return = get_option('mc_process_shortcodes') == 'true' ? do_shortcode($output) : $output;
    } else {
        $return = '';
    }
    if ($site) {
        restore_current_blog();
    }
    return $return;
}