function mc_switch_sites()
{
    if (function_exists('is_multisite') && is_multisite()) {
        if (get_site_option('mc_multisite') == 2 && my_calendar_table() != my_calendar_table('global')) {
            if (get_option('mc_current_table') == '1') {
                // can post to either, but is currently set to post to central table
                return true;
            }
        } else {
            if (get_site_option('mc_multisite') == 1 && my_calendar_table() != my_calendar_table('global')) {
                // can only post to central table
                return true;
            }
        }
    }
    return false;
}
function mc_deal_with_deleted_user($id)
{
    global $wpdb;
    $mcdb = $wpdb;
    // Do the queries
    // This may not work quite right in multi-site. Need to explore further when I have time.
    $mcdb->get_results("UPDATE " . my_calendar_table() . " SET event_author=" . apply_filters('mc_deleted_author', $mcdb->get_var("SELECT MIN(ID) FROM " . $mcdb->prefix . "users", 0, 0)) . " WHERE event_author=" . $id);
    $mcdb->get_results("UPDATE " . my_calendar_table() . " SET event_host=" . apply_filters('mc_deleted_host', $mcdb->get_var("SELECT MIN(ID) FROM " . $mcdb->prefix . "users", 0, 0)) . " WHERE event_host=" . $id);
}
function mc_list_groups()
{
    global $wpdb;
    $mcdb = $wpdb;
    $sortby = isset($_GET['sort']) ? (int) $_GET['sort'] : get_option('mc_default_sort');
    if (isset($_GET['order'])) {
        $sortdir = isset($_GET['order']) && $_GET['order'] == 'ASC' ? 'ASC' : 'default';
    } else {
        $sortdir = 'default';
    }
    if (empty($sortby)) {
        $sortbyvalue = 'event_begin';
    } else {
        switch ($sortby) {
            case 1:
                $sortbyvalue = 'event_ID';
                break;
            case 2:
                $sortbyvalue = 'event_title';
                break;
            case 3:
                $sortbyvalue = 'event_desc';
                break;
            case 4:
                $sortbyvalue = 'event_begin';
                break;
            case 5:
                $sortbyvalue = 'event_author';
                break;
            case 6:
                $sortbyvalue = 'event_category';
                break;
            case 7:
                $sortbyvalue = 'event_label';
                break;
            case 8:
                $sortbyvalue = 'group_id';
                break;
            default:
                $sortbyvalue = 'event_begin';
        }
    }
    $sortbydirection = $sortdir == 'default' ? 'DESC' : $sortdir;
    $sorting = $sortbydirection == 'DESC' ? "&order=ASC" : '';
    $current = empty($_GET['paged']) ? 1 : intval($_GET['paged']);
    $user = get_current_user_id();
    $screen = get_current_screen();
    $option = $screen->get_option('per_page', 'option');
    $items_per_page = get_user_meta($user, $option, true);
    if (empty($items_per_page) || $items_per_page < 1) {
        $items_per_page = $screen->get_option('per_page', 'default');
    }
    $limit = isset($_GET['limit']) ? $_GET['limit'] : 'all';
    switch ($limit) {
        case 'all':
            $limit = '';
            break;
        case 'grouped':
            $limit = 'WHERE event_group_id <> 0';
            break;
        case 'ungrouped':
            $limit = 'WHERE event_group_id = 0';
            break;
        default:
            $limit = '';
    }
    $events = $mcdb->get_results("SELECT SQL_CALC_FOUND_ROWS * FROM " . my_calendar_table() . " {$limit} ORDER BY {$sortbyvalue} {$sortbydirection} LIMIT " . ($current - 1) * $items_per_page . ", " . $items_per_page);
    $found_rows = $wpdb->get_col("SELECT FOUND_ROWS();");
    $items = $found_rows[0];
    ?>
<div class='inside'><?php 
    if (get_option('mc_event_approve') == 'true') {
        ?>
		<ul class="links">
		<li><a <?php 
        echo isset($_GET['limit']) && $_GET['limit'] == 'groupeed' ? ' class="active-link"' : '';
        ?>
 href="<?php 
        echo admin_url('admin.php?page=my-calendar-groups&amp;limit=grouped#my-calendar-admin-table');
        ?>
"><?php 
        _e('Grouped Events', 'my-calendar');
        ?>
</a></li>
		<li><a <?php 
        echo isset($_GET['limit']) && $_GET['limit'] == 'ungrouped' ? ' class="active-link"' : '';
        ?>
  href="<?php 
        echo admin_url('admin.php?page=my-calendar-groups&amp;limit=ungrouped#my-calendar-admin-table');
        ?>
"><?php 
        _e('Ungrouped Events', 'my-calendar');
        ?>
</a></li> 
		<li><a <?php 
        echo isset($_GET['limit']) && $_GET['limit'] == 'all' || !isset($_GET['limit']) ? ' class="active-link"' : '';
        ?>
  href="<?php 
        echo admin_url('admin.php?page=my-calendar-groups#my-calendar-admin-table');
        ?>
"><?php 
        _e('All', 'my-calendar');
        ?>
</a></li>
		</ul>
	<?php 
    }
    ?>
	<p><?php 
    _e('Check a set of events to group them for mass editing.', 'my-calendar');
    ?>
</p><?php 
    $num_pages = ceil($items / $items_per_page);
    if ($num_pages > 1) {
        $page_links = paginate_links(array('base' => add_query_arg('paged', '%#%'), 'format' => '', 'prev_text' => __('&laquo; Previous<span class="screen-reader-text"> Events</span>', 'my-calendar'), 'next_text' => __('Next<span class="screen-reader-text"> Events</span> &raquo;', 'my-calendar'), 'total' => $num_pages, 'current' => $current, 'mid_size' => 1));
        printf("<div class='tablenav'><div class='tablenav-pages'>%s</div></div>", $page_links);
    }
    if (!empty($events)) {
        ?>
		<form action="<?php 
        echo admin_url("admin.php?page=my-calendar-groups");
        ?>
" method="post">
		<div>
		<input type="hidden" name="_wpnonce" value="<?php 
        echo wp_create_nonce('my-calendar-nonce');
        ?>
" />
		<input type="hidden" name="event_action" value="group" />
		</div>
		<p style="position:relative;display:inline-block;">
		<input type="submit" class="button-primary group" value="<?php 
        _e('Group checked events for mass editing', 'my-calendar');
        ?>
" />
		</p>
	</div>
	<table class="widefat wp-list-table" id="my-calendar-admin-table">
	<thead>
	<tr>
		<th  scope="col" style="width: 50px;"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=1{$sorting}");
        ?>
"><?php 
        _e('ID', 'my-calendar');
        ?>
</a></th>
		<th  scope="col"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=8{$sorting}");
        ?>
"><?php 
        _e('Group', 'my-calendar');
        ?>
</a></th>
		<th  scope="col"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=2{$sorting}");
        ?>
"><?php 
        _e('Title', 'my-calendar');
        ?>
</a></th>
		<th  scope="col"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=7{$sorting}");
        ?>
"><?php 
        _e('Where', 'my-calendar');
        ?>
</a></th>
		<th  scope="col"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=4{$sorting}");
        ?>
"><?php 
        _e('Starts', 'my-calendar');
        ?>
</a></th>
		<th  scope="col"><?php 
        _e('Recurs', 'my-calendar');
        ?>
</th>
		<th  scope="col"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=5{$sorting}");
        ?>
"><?php 
        _e('Author', 'my-calendar');
        ?>
</a></th>
		<th  scope="col"><a href="<?php 
        echo admin_url("admin.php?page=my-calendar-groups&amp;sort=6{$sorting}");
        ?>
"><?php 
        _e('Category', 'my-calendar');
        ?>
</a></th>
	</tr>
	</thead>
		<?php 
        $class = '';
        $sql = "SELECT * FROM " . my_calendar_categories_table();
        $categories = $mcdb->get_results($sql);
        foreach ($events as $event) {
            $class = $class == 'alternate' ? '' : 'alternate';
            $spam = $event->event_flagged == 1 ? ' spam' : '';
            $spam_label = $event->event_flagged == 1 ? '<strong>Possible spam:</strong> ' : '';
            $author = $event->event_author != 0 ? get_userdata($event->event_author) : 'Public Submitter';
            if ($event->event_link != '') {
                $title = "<a href='" . esc_attr($event->event_link) . "'>{$event->event_title}</a>";
            } else {
                $title = $event->event_title;
            }
            ?>
			<tr class="<?php 
            echo $class;
            echo $spam;
            ?>
" id="event<?php 
            echo $event->event_id;
            ?>
">
				<th scope="row"><input type="checkbox" value="<?php 
            echo $event->event_id;
            ?>
" name="group[]" id="mc<?php 
            echo $event->event_id;
            ?>
" <?php 
            echo mc_event_is_grouped($event->event_group_id) ? ' disabled="disabled"' : '';
            ?>
 /> <label for="mc<?php 
            echo $event->event_id;
            ?>
"><?php 
            echo $event->event_id;
            ?>
</label></th>
				<th scope="row"><?php 
            echo $event->event_group_id == 0 ? '-' : $event->event_group_id;
            ?>
</th>
				<td title="<?php 
            echo esc_attr(substr(strip_tags(stripslashes($event->event_desc)), 0, 240));
            ?>
">
					<strong><?php 
            if (mc_can_edit_event($event->event_author)) {
                ?>
						<a href="<?php 
                echo admin_url("admin.php?page=my-calendar&amp;mode=edit&amp;event_id={$event->event_id}");
                ?>
" class='edit'>
					<?php 
            }
            echo $spam_label;
            echo stripslashes($title);
            ?>
					<?php 
            if (mc_can_edit_event($event->event_author)) {
                echo "</a>";
            }
            ?>
</strong>
				<div class='row-actions' style="visibility:visible;">
				<?php 
            if (mc_can_edit_event($event->event_author)) {
                ?>
				<a href="<?php 
                echo admin_url("admin.php?page=my-calendar&amp;mode=edit&amp;event_id={$event->event_id}");
                ?>
" class='edit'><?php 
                _e('Edit Event', 'my-calendar');
                ?>
</a> | 
					<?php 
                if (mc_event_is_grouped($event->event_group_id)) {
                    ?>
					<a href="<?php 
                    echo admin_url("admin.php?page=my-calendar-groups&amp;mode=edit&amp;event_id={$event->event_id}&amp;group_id={$event->event_group_id}");
                    ?>
" class='edit group'><?php 
                    _e('Edit Group', 'my-calendar');
                    ?>
</a>
					<?php 
                } else {
                    ?>
					<em><?php 
                    _e('Ungrouped', 'my-calendar');
                    ?>
</em>
					<?php 
                }
            } else {
                _e("Not editable.", 'my-calendar');
            }
            ?>
		
				</div>
				</td>
				<td><?php 
            echo stripslashes($event->event_label);
            ?>
</td>
				<?php 
            if ($event->event_time != "00:00:00") {
                $eventTime = date_i18n(get_option('mc_time_format'), strtotime($event->event_time));
            } else {
                $eventTime = get_option('mc_notime_text');
            }
            ?>
				<td><?php 
            echo "{$event->event_begin}<br />{$eventTime}";
            ?>
</td>
				<td>
				<?php 
            $recurs = str_split($event->event_recur, 1);
            $recur = $recurs[0];
            $every = isset($recurs[1]) ? $recurs[1] : 1;
            // Interpret the DB values into something human readable
            if ($recur == 'S') {
                _e('Never', 'my-calendar');
            } else {
                if ($recur == 'D') {
                    _e('Daily', 'my-calendar');
                } else {
                    if ($recur == 'E') {
                        _e('Weekdays', 'my-calendar');
                    } else {
                        if ($recur == 'W') {
                            _e('Weekly', 'my-calendar');
                        } else {
                            if ($recur == 'B') {
                                _e('Bi-Weekly', 'my-calendar');
                            } else {
                                if ($recur == 'M') {
                                    _e('Monthly (by date)', 'my-calendar');
                                } else {
                                    if ($recur == 'U') {
                                        _e('Monthly (by day)', 'my-calendar');
                                    } else {
                                        if ($recur == 'Y') {
                                            _e('Yearly', 'my-calendar');
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            ?>
&ndash;<?php 
            if ($recur == 'S') {
                _e('N/A', 'my-calendar');
            } else {
                if (mc_event_repeats_forever($recur, $event->event_repeats)) {
                    _e('Forever', 'my-calendar');
                } else {
                    if ($event->event_repeats > 0) {
                        printf(__('%d Times', 'my-calendar'), $event->event_repeats);
                    }
                }
            }
            ?>
				
				</td>
				<td><?php 
            echo is_object($author) ? $author->display_name : $author;
            ?>
</td>
					<?php 
            $this_category = $event->event_category;
            foreach ($categories as $key => $value) {
                if ($value->category_id == $this_category) {
                    $this_cat = $categories[$key];
                }
            }
            ?>
				<td><div class="category-color" style="background-color:<?php 
            echo strpos($this_cat->category_color, '#') !== 0 ? '#' : '';
            echo $this_cat->category_color;
            ?>
;"> </div> <?php 
            echo stripslashes($this_cat->category_name);
            ?>
</td>
				<?php 
            unset($this_cat);
            ?>
			</tr><?php 
        }
        ?>
		</table>
		<div class="inside">
			<p>
			<input type="submit" class="button-secondary group" value="<?php 
        _e('Group checked events for mass editing', 'my-calendar');
        ?>
" />
			</p>
		</div>
		</form><?php 
    } else {
        ?>
		<div class="inside"><p><?php 
        _e("There are no events in the database!", 'my-calendar');
        ?>
</p></div><?php 
    }
}
function mc_get_data($field, $id)
{
    global $wpdb;
    $mcdb = $wpdb;
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        $mcdb = mc_remote_db();
    }
    $field = esc_sql($field);
    $sql = $wpdb->prepare("SELECT {$field} FROM " . my_calendar_table() . " WHERE event_id = %d", $id);
    $result = $mcdb->get_var($sql);
    return $result;
}
function mc_transition_db()
{
    // copy to post types. Don't do this if referencing remote sites.
    if (get_option('mc_remote') != 'true') {
        global $wpdb;
        $results = $wpdb->get_results('SELECT * FROM ' . my_calendar_locations_table(), ARRAY_A);
        $locations = array();
        foreach ($results as $result) {
            $location_id = $result['location_id'];
            unset($result['location_id']);
            $hash = md5(serialize($result));
            $locations[$location_id] = $result;
        }
        $results = $wpdb->get_results('SELECT * FROM ' . my_calendar_categories_table());
        foreach ($results as $category) {
            $term = wp_insert_term($category->category_name, 'mc-event-category');
            if (!is_wp_error($term)) {
                $term_id = $term['term_id'];
                mc_update_category('category_term', $term_id, $category->category_id);
            } else {
                if (isset($term->error_data['term_exists'])) {
                    $term_id = $term->error_data['term_exists'];
                    mc_update_category('category_term', $term_id, $category->category_id);
                }
            }
        }
        $results = $wpdb->get_results('SELECT * FROM ' . my_calendar_table(), ARRAY_A);
        foreach ($results as $event) {
            $post_id = mc_create_event_post($event, $event['event_id']);
            mc_update_event('event_post', $post_id, $event['event_id']);
            // false if not found, id if found.
            $location = mc_check_location_table($event, $locations);
            if ($location) {
                mc_update_event('event_location', $location, $event['event_id']);
            } else {
                if ($event['event_label'] == '' && $event['event_street'] == '' && $event['event_url'] == '' && $event['event_city'] == '' && $event['event_state'] == '' && $event['event_country'] == '') {
                    // don't insert the row if location does not have basic data.
                } else {
                    $add = array('location_label' => $event['event_label'], 'location_street' => $event['event_street'], 'location_street2' => $event['event_street2'], 'location_city' => $event['event_city'], 'location_state' => $event['event_state'], 'location_postcode' => $event['event_postcode'], 'location_region' => $event['event_region'], 'location_country' => $event['event_country'], 'location_url' => $event['event_url'], 'location_longitude' => $event['event_longitude'], 'location_latitude' => $event['event_latitude'], 'location_zoom' => $event['event_zoom'], 'location_phone' => $event['event_phone'], 'location_access' => '');
                    mc_insert_location($add);
                }
                // could add delete routine to allow user to select what location to use for events using a given location.
            }
        }
    }
}
function my_calendar_import()
{
    if (get_option('ko_calendar_imported') != 'true') {
        global $wpdb;
        $mcdb = $wpdb;
        define('KO_CALENDAR_TABLE', $mcdb->prefix . 'calendar');
        define('KO_CALENDAR_CATS', $mcdb->prefix . 'calendar_categories');
        $events = $mcdb->get_results("SELECT * FROM " . KO_CALENDAR_TABLE, 'ARRAY_A');
        $event_ids = array();
        foreach ($events as $key) {
            $endtime = $key['event_time'] == '00:00:00' ? '00:00:00' : date('H:i:s', strtotime("{$key['event_time']} +1 hour"));
            $data = array('event_title' => $key['event_title'], 'event_desc' => $key['event_desc'], 'event_begin' => $key['event_begin'], 'event_end' => $key['event_end'], 'event_time' => $key['event_time'], 'event_endtime' => $endtime, 'event_recur' => $key['event_recur'], 'event_repeats' => $key['event_repeats'], 'event_author' => $key['event_author'], 'event_category' => $key['event_category'], 'event_hide_end' => 1, 'event_link' => isset($key['event_link']) ? $key['event_link'] : '');
            $format = array('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%d', '%d', '%d', '%d', '%s');
            $update = $mcdb->insert(my_calendar_table(), $data, $format);
            $events_results = $update ? true : false;
            $event_ids[] = $mcdb->insert_id;
        }
        foreach ($event_ids as $value) {
            // propagate event instances.
            $sql = "SELECT event_begin, event_time, event_end, event_endtime FROM " . my_calendar_table() . " WHERE event_id = {$value}";
            $event = $wpdb->get_results($sql);
            $event = $event[0];
            $dates = array('event_begin' => $event->event_begin, 'event_end' => $event->event_end, 'event_time' => $event->event_time, 'event_endtime' => $event->event_endtime);
            $event = mc_increment_event($value, $dates);
        }
        $cats = $mcdb->get_results("SELECT * FROM " . KO_CALENDAR_CATS, 'ARRAY_A');
        $catsql = "";
        foreach ($cats as $key) {
            $name = esc_sql($key['category_name']);
            $color = esc_sql($key['category_colour']);
            $id = (int) $key['category_id'];
            $catsql = "INSERT INTO " . my_calendar_categories_table() . " SET \n\t\t\t\tcategory_id='" . $id . "',\n\t\t\t\tcategory_name='" . $name . "', \n\t\t\t\tcategory_color='" . $color . "' \n\t\t\t\tON DUPLICATE KEY UPDATE \n\t\t\t\tcategory_name='" . $name . "', \n\t\t\t\tcategory_color='" . $color . "';\n\t\t\t\t";
            $cats_results = $mcdb->query($catsql);
        }
        $message = $cats_results !== false ? __('Categories imported successfully.', 'my-calendar') : __('Categories not imported.', 'my-calendar');
        $e_message = $events_results !== false ? __('Events imported successfully.', 'my-calendar') : __('Events not imported.', 'my-calendar');
        $return = "<div id='message' class='updated fade'><ul><li>{$message}</li><li>{$e_message}</li></ul></div>";
        echo $return;
        if ($cats_results !== false && $events_results !== false) {
            update_option('ko_calendar_imported', 'true');
        }
    }
}
function mc_event_is_grouped($group_id)
{
    global $wpdb;
    $mcdb = $wpdb;
    if ($group_id == 0) {
        return false;
    } else {
        $query = "SELECT count( event_group_id ) FROM " . my_calendar_table() . " WHERE event_group_id = {$group_id}";
        $value = $mcdb->get_var($query);
        if ($value > 1) {
            return true;
        } else {
            return false;
        }
    }
}
function my_calendar_check_db()
{
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        return;
    }
    global $wpdb;
    $mcdb = $wpdb;
    $row = $mcdb->get_row('SELECT * FROM ' . my_calendar_table());
    if (isset($_POST['upgrade']) && $_POST['upgrade'] == 'true') {
        my_calendar_mc_upgrade_db();
        ?>
		<div class='upgrade-db updated'>
			<p><?php 
        _e('My Calendar Database is updated.', 'my-calendar');
        ?>
</p>
		</div>
	<?php 
    } else {
        if (!isset($row->event_tickets) && isset($row->event_id)) {
            if ($_GET['page'] == 'my-calendar-config') {
                ?>
			<div class='upgrade-db error'>
				<form method="post" action="<?php 
                echo admin_url("admin.php?page=my-calendar-config");
                ?>
">
					<div>
						<input type="hidden" name="_wpnonce"
						       value="<?php 
                echo wp_create_nonce('my-calendar-nonce');
                ?>
"/>
						<input type="hidden" name="upgrade" value="true"/>
					</div>
					<p>
						<?php 
                _e('The My Calendar database needs to be updated.', 'my-calendar');
                ?>
						<input type="submit" value="<?php 
                _e('Update now', 'my-calendar');
                ?>
" name="update-calendar"
						       class="button-primary"/>
					</p>
				</form>
			</div>
		<?php 
            } else {
                ?>
			<div class='upgrade-db error'>
			<p>
				<?php 
                _e('The My Calendar database needs to be updated.', 'my-calendar');
                ?>
 <a
					href="<?php 
                echo admin_url("admin.php?page=my-calendar-config");
                ?>
"><?php 
                _e('Update now', 'my-calendar');
                ?>
</a>
			</p>
			</div><?php 
            }
        } elseif (!isset($row->event_id)) {
            ?>
		<div class='upgrade-db error'>
		<form method="post" action="<?php 
            echo admin_url("admin.php?page=my-calendar-config");
            ?>
">
			<div>
				<input type="hidden" name="_wpnonce" value="<?php 
            echo wp_create_nonce('my-calendar-nonce');
            ?>
" />
				<input type="hidden" name="upgrade" value="true" />
			</div>
			<p>
				<?php 
            _e('You haven\'t entered any events, so My Calendar can\'t tell whether your database is up to date. If you can\'t add events, upgrade your database!', 'my-calendar');
            ?>
				<input type="submit" value="<?php 
            _e('Update now', 'my-calendar');
            ?>
" name="update-calendar"
				       class="button-primary" />
			</p>
		</form>
		</div><?php 
        }
    }
}
function my_calendar_manage_categories()
{
    global $wpdb;
    $mcdb = $wpdb;
    $formats = array('%s', '%s', '%s');
    ?>
	<div class="wrap jd-my-calendar">
		<?php 
    my_calendar_check_db();
    // We do some checking to see what we're doing
    if (!empty($_POST)) {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce, 'my-calendar-nonce')) {
            die("Security check failed");
        }
    }
    if (isset($_POST['mode']) && $_POST['mode'] == 'add') {
        $term = wp_insert_term($_POST['category_name'], 'mc-event-category');
        if (!is_wp_error($term)) {
            $term = $term['term_id'];
        } else {
            $term = false;
        }
        $add = array('category_name' => $_POST['category_name'], 'category_color' => $_POST['category_color'], 'category_icon' => $_POST['category_icon'], 'category_private' => isset($_POST['category_private']) ? 1 : 0, 'category_term' => $term);
        // actions and filters
        $add = apply_filters('mc_pre_add_category', $add, $_POST);
        $results = $mcdb->insert(my_calendar_categories_table(), $add, $formats);
        do_action('mc_post_add_category', $add, $results, $_POST);
        $cat_ID = $mcdb->insert_id;
        if (isset($_POST['mc_default_category'])) {
            update_option('mc_default_category', $cat_ID);
            $append = __('Default category changed.', 'my-calendar');
        } else {
            $append = '';
        }
        if (isset($_POST['mc_skip_holidays_category'])) {
            update_option('mc_skip_holidays_category', $cat_ID);
            $append .= __('Holiday category changed.', 'my-calendar');
        }
        if ($results) {
            echo "<div class=\"updated\"><p><strong>" . __('Category added successfully', 'my-calendar') . ". {$append}</strong></p></div>";
        } else {
            echo "<div class=\"updated error\"><p><strong>" . __('Category addition failed.', 'my-calendar') . "</strong></p></div>";
        }
    } else {
        if (isset($_GET['mode']) && isset($_GET['category_id']) && $_GET['mode'] == 'delete') {
            $cat_ID = (int) $_GET['category_id'];
            $sql = "DELETE FROM " . my_calendar_categories_table() . " WHERE category_id={$cat_ID}";
            $results = $mcdb->query($sql);
            if ($results) {
                $sql = "UPDATE " . my_calendar_table() . " SET event_category=1 WHERE event_category={$cat_ID}";
                $cal_results = $mcdb->query($sql);
                mc_delete_cache();
            } else {
                $cal_results = false;
            }
            if (get_option('mc_default_category') == $cat_ID) {
                update_option('mc_default_category', 1);
            }
            if ($results && $cal_results) {
                echo "<div class=\"updated\"><p><strong>" . __('Category deleted successfully. Categories in calendar updated.', 'my-calendar') . "</strong></p></div>";
            } else {
                if ($results && !$cal_results) {
                    echo "<div class=\"updated\"><p><strong>" . __('Category deleted successfully. Categories in calendar not updated.', 'my-calendar') . "</strong></p></div>";
                } else {
                    if (!$results && $cal_results) {
                        echo "<div class=\"updated error\"><p><strong>" . __('Category not deleted. Categories in calendar updated.', 'my-calendar') . "</strong></p></div>";
                    }
                }
            }
        } else {
            if (isset($_GET['mode']) && isset($_GET['category_id']) && $_GET['mode'] == 'edit' && !isset($_POST['mode'])) {
                $cur_cat = (int) $_GET['category_id'];
                mc_edit_category_form('edit', $cur_cat);
            } else {
                if (isset($_POST['mode']) && isset($_POST['category_id']) && isset($_POST['category_name']) && isset($_POST['category_color']) && $_POST['mode'] == 'edit') {
                    $update = array('category_name' => $_POST['category_name'], 'category_color' => $_POST['category_color'], 'category_icon' => $_POST['category_icon'], 'category_private' => isset($_POST['category_private']) ? 1 : 0);
                    $where = array('category_id' => (int) $_POST['category_id']);
                    $append = '';
                    if (isset($_POST['mc_default_category'])) {
                        update_option('mc_default_category', (int) $_POST['category_id']);
                        $append .= __('Default category changed.', 'my-calendar');
                    } else {
                        if (get_option('mc_default_category') == (int) $_POST['category_id']) {
                            delete_option('mc_default_category');
                        }
                    }
                    if (isset($_POST['mc_skip_holidays_category'])) {
                        update_option('mc_skip_holidays_category', (int) $_POST['category_id']);
                        $append .= __('Holiday category changed.', 'my-calendar');
                    } else {
                        if (get_option('mc_skip_holidays_category') == (int) $_POST['category_id']) {
                            delete_option('mc_skip_holidays_category');
                        }
                    }
                    $results = $mcdb->update(my_calendar_categories_table(), $update, $where, $formats, '%d');
                    mc_delete_cache();
                    if ($results) {
                        echo "<div class=\"updated\"><p><strong>" . __('Category edited successfully.', 'my-calendar') . " {$append}</strong></p></div>";
                    } else {
                        echo "<div class=\"updated error\"><p><strong>" . __('Category was not edited.', 'my-calendar') . " {$append}</strong></p></div>";
                    }
                    $cur_cat = (int) $_POST['category_id'];
                    mc_edit_category_form('edit', $cur_cat);
                }
            }
        }
    }
    if (isset($_GET['mode']) && $_GET['mode'] != 'edit' || isset($_POST['mode']) && $_POST['mode'] != 'edit' || !isset($_GET['mode']) && !isset($_POST['mode'])) {
        mc_edit_category_form('add');
    }
    ?>
</div>
<?php 
}
function mc_span_time($group_id)
{
    global $wpdb;
    $mcdb = $wpdb;
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        $mcdb = mc_remote_db();
    }
    $group_id = (int) $group_id;
    $sql = "SELECT event_begin, event_time, event_end, event_endtime FROM " . my_calendar_table() . " WHERE event_group_id = {$group_id} ORDER BY event_begin ASC";
    $dates = $mcdb->get_results($sql);
    $count = count($dates);
    $last = $count - 1;
    $begin = $dates[0]->event_begin . ' ' . $dates[0]->event_time;
    $end = $dates[$last]->event_end . ' ' . $dates[$last]->event_endtime;
    return array($begin, $end);
}
function my_calendar_exists()
{
    global $wpdb;
    $tables = $wpdb->get_results("show tables;");
    foreach ($tables as $table) {
        foreach ($table as $value) {
            if ($value == my_calendar_table()) {
                // if the table exists, then My Calendar was already installed.
                return true;
            }
        }
    }
    return false;
}
function mc_generator($type)
{
    ?>
<form action="<?php 
    echo admin_url('admin.php?page=my-calendar-help');
    ?>
" method="POST" id="my-calendar-generate">
	<fieldset>
		<legend><strong><?php 
    echo ucfirst($type);
    ?>
</strong>: <?php 
    _e('Shortcode Attributes', 'my-calendar');
    ?>
		</legend>
		<div id="mc-generator" class="generator">
			<div><input type="hidden" name="_wpnonce" value="<?php 
    echo wp_create_nonce('my-calendar-generator');
    ?>
"/></div>		
			<input type='hidden' name='shortcode' value='<?php 
    esc_attr_e($type);
    ?>
'/>
			<?php 
    // Common Elements to all Shortcodes
    ?>
			<p><?php 
    echo my_calendar_categories_list('select', 'admin');
    ?>
</p>

			<p>
				<label for="ltype"><?php 
    _e('Location filter type:', 'my-calendar');
    ?>
</label>
				<select name="ltype" id="ltype">
					<option value="" selected="selected"><?php 
    _e('All locations', 'my-calendar');
    ?>
</option>
					<option value='event_label'><?php 
    _e('Location Name', 'my-calendar');
    ?>
</option>
					<option value='event_city'><?php 
    _e('City', 'my-calendar');
    ?>
</option>
					<option value='event_state'><?php 
    _e('State', 'my-calendar');
    ?>
</option>
					<option value='event_postcode'><?php 
    _e('Postal Code', 'my-calendar');
    ?>
</option>
					<option value='event_country'><?php 
    _e('Country', 'my-calendar');
    ?>
</option>
					<option value='event_region'><?php 
    _e('Region', 'my-calendar');
    ?>
</option>
				</select>
			</p>
			<p>
				<label for="lvalue" id='lval'><?php 
    _e('Location filter value:', 'my-calendar');
    ?>
</label>
				<input type="text" name="lvalue" id="lvalue" aria-labelledby='lval location-info' />
			</p>

			<p id='location-info'>
				<?php 
    _e('<strong>Note:</strong> If you provide a location filter value, it must be an exact match for that information as saved with your events. (e.g. "Saint Paul" is not equivalent to "saint paul" or "St. Paul")', 'my-calendar');
    ?>
			</p>
			<?php 
    // Grab users and list them
    $users = mc_get_users();
    $options = '';
    foreach ($users as $u) {
        $options .= '<option value="' . $u->ID . '">' . esc_html($u->display_name) . "</option>\n";
    }
    ?>
			<p>
				<label for="author"><?php 
    _e('Limit by Author', 'my-calendar');
    ?>
</label>
				<select name="author[]" id="author" multiple="multiple">
					<option value="all"><?php 
    _e('All authors', 'my-calendar');
    ?>
</option>
					<option value="current"><?php 
    _e('Currently logged-in user', 'my-calendar');
    ?>
</option>
					<?php 
    echo $options;
    ?>
				</select>
			</p>
			<p>
				<label for="host"><?php 
    _e('Limit by Host', 'my-calendar');
    ?>
</label>
				<select name="host[]" id="host" multiple="multiple">
					<option value="all"><?php 
    _e('All hosts', 'my-calendar');
    ?>
</option>
					<option value="current"><?php 
    _e('Currently logged-in user', 'my-calendar');
    ?>
</option>
					<?php 
    echo $options;
    ?>
				</select>
			</p>
			<?php 
    // Main shortcode only
    if ($type == 'main') {
        ?>
				<p>
					<label for="format"><?php 
        _e('Format', 'my-calendar');
        ?>
</label>
					<select name="format" id="format">
						<option value="calendar" selected="selected"><?php 
        _e('Grid', 'my-calendar');
        ?>
</option>
						<option value="list"><?php 
        _e('List', 'my-calendar');
        ?>
</option>
						<option value="mini"><?php 
        _e('Mini', 'my-calendar');
        ?>
</option>
					</select>
				</p>
				<p>
					<label for="time"><?php 
        _e('Time Segment', 'my-calendar');
        ?>
</label>
					<select name="time" id="time">
						<option value="month" selected="selected"><?php 
        _e('Month', 'my-calendar');
        ?>
</option>
						<option value="month+1"><?php 
        _e('Next Month', 'my-calendar');
        ?>
</option>
						<option value="week"><?php 
        _e('Week', 'my-calendar');
        ?>
</option>
						<option value="day"><?php 
        _e('Day', 'my-calendar');
        ?>
</option>
					</select>
				</p>
				<p>
					<label for="year"><?php 
        _e('Year', 'my-calendar');
        ?>
</label>
					<select name="year" id="year">
						<option value=''><?php 
        _e('Default', 'my-calendar');
        ?>
</option>					
						<?php 
        global $wpdb;
        $mcdb = $wpdb;
        $query = "SELECT event_begin FROM " . my_calendar_table() . " WHERE event_approved = 1 AND event_flagged <> 1 ORDER BY event_begin ASC LIMIT 0 , 1";
        $year1 = date('Y', strtotime($mcdb->get_var($query)));
        $diff1 = date('Y') - $year1;
        $past = $diff1;
        $future = apply_filters('mc_jumpbox_future_years', 5, false);
        $fut = 1;
        $f = '';
        $p = '';
        $offset = 60 * 60 * get_option('gmt_offset');
        while ($past > 0) {
            $p .= '<option value="';
            $p .= date("Y", time() + $offset) - $past;
            $p .= '">';
            $p .= date("Y", time() + $offset) - $past . "</option>\n";
            $past = $past - 1;
        }
        while ($fut < $future) {
            $f .= '<option value="';
            $f .= date("Y", time() + $offset) + $fut;
            $f .= '">';
            $f .= date("Y", time() + $offset) + $fut . "</option>\n";
            $fut = $fut + 1;
        }
        echo $p . '<option value="' . date("Y") . '">' . date("Y") . "</option>\n" . $f;
        ?>
					</select>
					</p>
					<p>
					<label for="month"><?php 
        _e('Month', 'my-calendar');
        ?>
</label>
					<select name="month" id="month">
						<option value=''><?php 
        _e('Default', 'my-calendar');
        ?>
</option>					
						<?php 
        $months = '';
        for ($i = 1; $i <= 12; $i++) {
            $months .= "<option value='{$i}'>" . date_i18n('F', mktime(0, 0, 0, $i, 1)) . '</option>' . "\n";
        }
        echo $months;
        ?>
					</select>
					</p>
					<p>
					<label for="day"><?php 
        _e('Day', 'my-calendar');
        ?>
</label>
					<select name="day" id="day">
						<option value=''><?php 
        _e('Default', 'my-calendar');
        ?>
</option>
						<?php 
        $days = '';
        for ($i = 1; $i <= 31; $i++) {
            $days .= "<option value='{$i}'>" . $i . '</option>' . "\n";
        }
        echo $days;
        ?>
					</select>
				</p>				
				<p id='navigation-info'>
					<?php 
        printf(__("Navigation above and below the calendar: your <a href='%s'>settings</a> if this is left blank. Use <code>none</code> to hide all navigation.", 'my-calendar'), admin_url('admin.php?page=my-calendar-config#mc-output'));
        ?>
				</p>
				<p>
					<label for="above" id='labove'><?php 
        _e('Navigation above calendar', 'my-calendar');
        ?>
</label>
					<input type="text" name="above" id="above" value="nav,toggle,jump,print,timeframe"
					       aria-labelledby='labove navigation-info' /><br/>
				</p>
				<p>
					<label for="below" id='lbelow'><?php 
        _e('Navigation below calendar', 'my-calendar');
        ?>
</label>
					<input type="text" name="below" id="below" value="key,feeds"
					       aria-labelledby='lbelow navigation-info' /><br/>
				</p>
			<?php 
    }
    if ($type == 'upcoming' || $type == 'today') {
        // Upcoming Events & Today's Events shortcodes
        ?>
				<p>
					<label for="fallback"><?php 
        _e('Fallback Text', 'my-calendar');
        ?>
</label>
					<input type="text" name="fallback" id="fallback" value="" />
				</p>
				<p>
					<label for="template"><?php 
        _e('Template', 'my-calendar');
        ?>
</label>
					<textarea cols="40" rows="4" name="template"
					          id="template"><?php 
        echo htmlentities("<strong>{date}</strong>, {time}: {link_title}");
        ?>
</textarea>
				</p>
			<?php 
    }
    if ($type == 'upcoming') {
        // Upcoming events only
        ?>
				<p>
					<label for="before"><?php 
        _e('Events/Days Before Current Day', 'my-calendar');
        ?>
</label>
					<input type="number" name="before" id="before" value="" />
				</p>
				<p>
					<label for="after"><?php 
        _e('Events/Days After Current Day', 'my-calendar');
        ?>
</label>
					<input type="number" name="after" id="after" value="" />
				</p>
				<p>
					<label for="skip"><?php 
        _e('Events/Days to Skip', 'my-calendar');
        ?>
</label>
					<input type="number" name="skip" id="skip" value="" />
				</p>
				<p>
					<label for="show_today"><?php 
        _e("Show Today's Events", 'my-calendar');
        ?>
</label>
					<input type="checkbox" name="show_today" id="show_today" value="yes"/>
				</p>
				<p>
					<label for="type"><?php 
        _e('Type of Upcoming Events List', 'my-calendar');
        ?>
</label>
					<select name="type" id="type">
						<option value="event" selected="selected"><?php 
        _e('Events', 'my-calendar');
        ?>
</option>
						<option value="year"><?php 
        _e('Current Year', 'my-calendar');
        ?>
</option>
						<option value="days"><?php 
        _e('Days', 'my-calendar');
        ?>
</option>
						<option value="custom"><?php 
        _e('Custom Dates', 'my-calendar');
        ?>
</option>
						<option value="month"><?php 
        _e('Current Month', 'my-calendar');
        ?>
</option>
						<option value="month+1"><?php 
        _e('Next Month', 'my-calendar');
        ?>
</option>
						<option value="month+2"><?php 
        _e('2nd Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+3"><?php 
        _e('3rd Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+4"><?php 
        _e('4th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+5"><?php 
        _e('5th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+6"><?php 
        _e('6th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+7"><?php 
        _e('7th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+8"><?php 
        _e('8th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+9"><?php 
        _e('9th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+10"><?php 
        _e('10th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+11"><?php 
        _e('11th Month Out', 'my-calendar');
        ?>
</option>
						<option value="month+12"><?php 
        _e('12th Month Out', 'my-calendar');
        ?>
</option>
					</select>
				</p>
				<div class='custom'>
					<p>
						<label for='from'><?php 
        _e('Starting Date', 'my-calendar');
        ?>
</label> <input type='text' name='from' id='from' />
					</p>
					<p>
						<label for='to'><?php 
        _e('End Date', 'my-calendar');
        ?>
</label> <input type='text' name='to' id='to' />
					</p>
				</div>
				<p>
					<label for="order"><?php 
        _e('Event Order', 'my-calendar');
        ?>
</label>
					<select name="order" id="order">
						<option value="asc" selected="selected"><?php 
        _e('Ascending', 'my-calendar');
        ?>
</option>
						<option value="desc"><?php 
        _e('Descending', 'my-calendar');
        ?>
</option>
					</select>
				</p>
			<?php 
    }
    ?>
		</div>
	</fieldset>
	<p>
		<input type="submit" class="button-primary" name="generator"
		       value="<?php 
    _e('Generate Shortcode', 'my-calendar');
    ?>
"/>
	</p>
	</form><?php 
}
function mc_get_search_results($search)
{
    global $wpdb;
    $mcdb = $wpdb;
    $event_array = array();
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        $mcdb = mc_remote_db();
    }
    $before = apply_filters('mc_past_search_results', 0);
    $after = apply_filters('mc_future_search_results', 15);
    // return only future events, nearest 10
    if (is_array($search)) {
        // if from & to are set, we need to use an alternate search query
        $from = $search['from'];
        $to = $search['to'];
        $category = isset($search['category']) ? $search['category'] : null;
        $ltype = isset($search['ltype']) ? $search['ltype'] : null;
        $lvalue = isset($search['lvalue']) ? $search['lvalue'] : null;
        $author = isset($search['author']) ? $search['author'] : null;
        $host = isset($search['host']) ? $search['host'] : null;
        $search = isset($search['search']) ? $search['search'] : '';
        $event_array = my_calendar_events($from, $to, $category, $ltype, $lvalue, 'search', $author, $host, $search);
    } else {
        $date = date('Y', current_time('timestamp')) . '-' . date('m', current_time('timestamp')) . '-' . date('d', current_time('timestamp'));
        // if a value is non-zero, I'll grab a handful of extra events so I can throw out holidays and others like that.
        if ($before > 0) {
            $before = $before + 5;
            $events1 = $mcdb->get_results("SELECT *, UNIX_TIMESTAMP(occur_begin) AS ts_occur_begin, UNIX_TIMESTAMP(occur_end) AS ts_occur_end \r\n\t\t\tFROM " . my_calendar_event_table() . " \r\n\t\t\tJOIN " . my_calendar_table() . " \r\n\t\t\tON (event_id=occur_event_id) \r\n\t\t\tJOIN " . my_calendar_categories_table() . " \r\n\t\t\tON (event_category=category_id) WHERE event_approved = 1 {$search} AND event_flagged <> 1 \r\n\t\t\tAND DATE(occur_begin) < '{$date}' ORDER BY occur_begin DESC LIMIT 0,{$before}");
        } else {
            $events1 = array();
        }
        $events3 = $mcdb->get_results("SELECT *, UNIX_TIMESTAMP(occur_begin) AS ts_occur_begin, UNIX_TIMESTAMP(occur_end) AS ts_occur_end \r\n\t\tFROM " . my_calendar_event_table() . " \r\n\t\tJOIN " . my_calendar_table() . " \r\n\t\tON (event_id=occur_event_id) \r\n\t\tJOIN " . my_calendar_categories_table() . " \r\n\t\tON (event_category=category_id) WHERE event_approved = 1 {$search} AND event_flagged <> 1 \r\n\t\tAND DATE(occur_begin) = '{$date}'");
        if ($after > 0) {
            $after = $after + 5;
            $events2 = $mcdb->get_results("SELECT *, UNIX_TIMESTAMP(occur_begin) AS ts_occur_begin, UNIX_TIMESTAMP(occur_end) AS ts_occur_end \r\n\t\t\tFROM " . my_calendar_event_table() . " \r\n\t\t\tJOIN " . my_calendar_table() . " \r\n\t\t\tON (event_id=occur_event_id) \r\n\t\t\tJOIN " . my_calendar_categories_table() . " \r\n\t\t\tON (event_category=category_id) WHERE event_approved = 1 {$search} AND event_flagged <> 1 \r\n\t\t\tAND DATE(occur_begin) > '{$date}' ORDER BY occur_begin ASC LIMIT 0,{$after}");
        } else {
            $events2 = array();
        }
        $arr_events = array();
        if (!empty($events1) || !empty($events2) || !empty($events3)) {
            $arr_events = array_merge($events1, $events3, $events2);
        }
        if (!get_option('mc_skip_holidays_category') || get_option('mc_skip_holidays_category') == '') {
            $holidays = array();
        } else {
            $holidays = mc_get_all_holidays($before, $after, 'yes');
            $holiday_array = mc_set_date_array($holidays);
        }
        if (is_array($arr_events) && !empty($arr_events)) {
            $no_events = false;
            $event_array = mc_set_date_array($arr_events);
            if (is_array($holidays) && count($holidays) > 0) {
                $event_array = mc_holiday_limit($event_array, $holiday_array);
                // if there are holidays, rejigger.
            }
        }
    }
    return $event_array;
}
function mc_get_db_type()
{
    global $wpdb;
    $mcdb = $wpdb;
    $db_type = 'MyISAM';
    if (get_option('mc_remote') == 'true' && function_exists('mc_remote_db')) {
        $mcdb = mc_remote_db();
    }
    $my_calendar = my_calendar_table();
    $dbs = $mcdb->get_results("SHOW TABLE STATUS WHERE name='{$my_calendar}'");
    foreach ($dbs as $db) {
        if ($db->Name == my_calendar_table()) {
            $db_type = $db->Engine;
        }
    }
    return $db_type;
}
function edit_my_calendar_config()
{
    global $wpdb;
    $mcdb = $wpdb;
    check_my_calendar();
    if (!empty($_POST)) {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce, 'my-calendar-nonce')) {
            die("Security check failed");
        }
        if (isset($_POST['remigrate'])) {
            echo "<div class='updated fade'><ol>";
            echo "<li>" . __('Dropping occurrences database table', 'my-calendar') . "</li>";
            mc_drop_table('my_calendar_event_table');
            sleep(1);
            echo "<li>" . __('Reinstalling occurrences database table.', 'my-calendar') . "</li>";
            mc_upgrade_db();
            sleep(1);
            echo "<li>" . __('Generating event occurrences.', 'my-calendar') . "</li>";
            mc_migrate_db();
            echo "<li>" . __('Event generation completed.', 'my-calendar') . "</li>";
            echo "</ol></div>";
        }
    }
    if (isset($_POST['mc_manage'])) {
        // management
        $clear = '';
        $mc_event_approve = !empty($_POST['mc_event_approve']) && $_POST['mc_event_approve'] == 'on' ? 'true' : 'false';
        $mc_api_enabled = !empty($_POST['mc_api_enabled']) && $_POST['mc_api_enabled'] == 'on' ? 'true' : 'false';
        $mc_remote = !empty($_POST['mc_remote']) && $_POST['mc_remote'] == 'on' ? 'true' : 'false';
        if (isset($_POST['mc_clear_cache']) && $_POST['mc_clear_cache'] == 'clear') {
            mc_delete_cache();
            $clear = __('My Calendar Cache cleared', 'my-calendar');
        }
        update_option('mc_uri', $_POST['mc_uri']);
        update_option('mc_event_approve', $mc_event_approve);
        update_option('mc_api_enabled', $mc_api_enabled);
        update_option('mc_remote', $mc_remote);
        update_option('mc_default_sort', $_POST['mc_default_sort']);
        update_option('mc_default_direction', $_POST['mc_default_direction']);
        if (get_site_option('mc_multisite') == 2) {
            $mc_current_table = (int) $_POST['mc_current_table'];
            update_option('mc_current_table', $mc_current_table);
        }
        echo "<div class='updated'><p><strong>" . __('My Calendar Management Settings saved', 'my-calendar') . ". {$clear}</strong></p></div>";
    }
    if (isset($_POST['mc_permissions'])) {
        $perms = $_POST['mc_caps'];
        $caps = array('mc_add_events' => __('Add Events', 'my-calendar'), 'mc_approve_events' => __('Approve Events', 'my-calendar'), 'mc_manage_events' => __('Manage Events', 'my-calendar'), 'mc_edit_cats' => __('Edit Categories', 'my-calendar'), 'mc_edit_locations' => __('Edit Locations', 'my-calendar'), 'mc_edit_styles' => __('Edit Styles', 'my-calendar'), 'mc_edit_behaviors' => __('Edit Behaviors', 'my-calendar'), 'mc_edit_templates' => __('Edit Templates', 'my-calendar'), 'mc_edit_settings' => __('Edit Settings', 'my-calendar'), 'mc_view_help' => __('View Help', 'my-calendar'));
        foreach ($perms as $key => $value) {
            $role = get_role($key);
            if (is_object($role)) {
                foreach ($caps as $k => $v) {
                    if (isset($value[$k])) {
                        $role->add_cap($k);
                    } else {
                        $role->remove_cap($k);
                    }
                }
            }
        }
        echo "<div class='updated'><p><strong>" . __('My Calendar Permissions Updated', 'my-calendar') . "</strong></p></div>";
    }
    // output
    if (isset($_POST['mc_show_months'])) {
        $permalinks = get_option('mc_use_permalinks');
        $mc_open_day_uri = !empty($_POST['mc_open_day_uri']) ? $_POST['mc_open_day_uri'] : '';
        update_option('mc_uri', $_POST['mc_uri']);
        update_option('mc_use_permalinks', !empty($_POST['mc_use_permalinks']) ? 'true' : 'false');
        update_option('mc_open_uri', !empty($_POST['mc_open_uri']) && $_POST['mc_open_uri'] == 'on' && get_option('mc_uri') != '' ? 'true' : 'false');
        update_option('mc_mini_uri', $_POST['mc_mini_uri']);
        update_option('mc_open_day_uri', $mc_open_day_uri);
        update_option('mc_display_author', !empty($_POST['mc_display_author']) && $_POST['mc_display_author'] == 'on' ? 'true' : 'false');
        update_option('mc_show_event_vcal', !empty($_POST['mc_show_event_vcal']) && $_POST['mc_show_event_vcal'] == 'on' ? 'true' : 'false');
        update_option('mc_show_gcal', !empty($_POST['mc_show_gcal']) && $_POST['mc_show_gcal'] == 'on' ? 'true' : 'false');
        update_option('mc_show_list_info', !empty($_POST['mc_show_list_info']) && $_POST['mc_show_list_info'] == 'on' ? 'true' : 'false');
        update_option('mc_show_months', (int) $_POST['mc_show_months']);
        // calculate sequence for navigation elements
        $top = $bottom = array();
        $nav = $_POST['mc_nav'];
        $set = 'top';
        foreach ($nav as $n) {
            if ($n == 'calendar') {
                $set = 'bottom';
            } else {
                if ($set == 'top') {
                    $top[] = $n;
                } else {
                    $bottom[] = $n;
                }
            }
            if ($n == 'stop') {
                break;
            }
        }
        $top = empty($top) ? 'none' : implode(',', $top);
        $bottom = empty($bottom) ? 'none' : implode(',', $bottom);
        update_option('mc_bottomnav', $bottom);
        update_option('mc_topnav', $top);
        update_option('mc_show_map', !empty($_POST['mc_show_map']) && $_POST['mc_show_map'] == 'on' ? 'true' : 'false');
        update_option('mc_gmap', !empty($_POST['mc_gmap']) && $_POST['mc_gmap'] == 'on' ? 'true' : 'false');
        update_option('mc_gmap_api_key', !empty($_POST['mc_gmap_api_key']) ? strip_tags($_POST['mc_gmap_api_key']) : '');
        update_option('mc_show_address', !empty($_POST['mc_show_address']) && $_POST['mc_show_address'] == 'on' ? 'true' : 'false');
        update_option('mc_display_more', !empty($_POST['mc_display_more']) && $_POST['mc_display_more'] == 'on' ? 'true' : 'false');
        update_option('mc_hide_icons', !empty($_POST['mc_hide_icons']) && $_POST['mc_hide_icons'] == 'on' ? 'true' : 'false');
        update_option('mc_apply_color', $_POST['mc_apply_color']);
        update_option('mc_event_registration', !empty($_POST['mc_event_registration']) && $_POST['mc_event_registration'] == 'on' ? 'true' : 'false');
        update_option('mc_inverse_color', !empty($_POST['mc_inverse_color']) && $_POST['mc_inverse_color'] == 'on' ? 'true' : 'false');
        update_option('mc_short', !empty($_POST['mc_short']) && $_POST['mc_short'] == 'on' ? 'true' : 'false');
        update_option('mc_desc', !empty($_POST['mc_desc']) && $_POST['mc_desc'] == 'on' ? 'true' : 'false');
        update_option('mc_process_shortcodes', !empty($_POST['mc_process_shortcodes']) && $_POST['mc_process_shortcodes'] == 'on' ? 'true' : 'false');
        update_option('mc_event_link', !empty($_POST['mc_event_link']) && $_POST['mc_event_link'] == 'on' ? 'true' : 'false');
        update_option('mc_show_weekends', !empty($_POST['mc_show_weekends']) && $_POST['mc_show_weekends'] == 'on' ? 'true' : 'false');
        update_option('mc_convert', !empty($_POST['mc_convert']) ? $_POST['mc_convert'] : 'false');
        if (isset($_POST['mc_use_permalinks']) && get_option('mc_use_permalinks') == 'true' && $permalinks != 'true') {
            $url = admin_url('options-permalink.php#mc_cpt_base');
            $note = ' ' . sprintf(__('You activated My Calendar permalinks. Go to <a href="%s">permalink settings</a> to set the base URL for My Calendar Events.', 'my-calendar'), $url);
        } else {
            $note = '';
        }
        echo "<div class=\"updated\"><p><strong>" . __('Output Settings saved', 'my-calendar') . "</strong>{$note}</p></div>";
    }
    // INPUT
    if (isset($_POST['mc_input'])) {
        $mc_input_options_administrators = !empty($_POST['mc_input_options_administrators']) && $_POST['mc_input_options_administrators'] == 'on' ? 'true' : 'false';
        $mc_input_options = array('event_short' => !empty($_POST['mci_event_short']) && $_POST['mci_event_short'] ? 'on' : 'off', 'event_desc' => !empty($_POST['mci_event_desc']) && $_POST['mci_event_desc'] ? 'on' : 'off', 'event_category' => !empty($_POST['mci_event_category']) && $_POST['mci_event_category'] ? 'on' : 'off', 'event_image' => !empty($_POST['mci_event_image']) && $_POST['mci_event_image'] ? 'on' : 'off', 'event_link' => !empty($_POST['mci_event_link']) && $_POST['mci_event_link'] ? 'on' : 'off', 'event_recurs' => !empty($_POST['mci_event_recurs']) && $_POST['mci_event_recurs'] ? 'on' : 'off', 'event_open' => !empty($_POST['mci_event_open']) && $_POST['mci_event_open'] ? 'on' : 'off', 'event_location' => !empty($_POST['mci_event_location']) && $_POST['mci_event_location'] ? 'on' : 'off', 'event_location_dropdown' => !empty($_POST['mci_event_location_dropdown']) && $_POST['mci_event_location_dropdown'] ? 'on' : 'off', 'event_specials' => !empty($_POST['mci_event_specials']) && $_POST['mci_event_specials'] ? 'on' : 'off', 'event_access' => !empty($_POST['mci_event_access']) && $_POST['mci_event_access'] ? 'on' : 'off', 'event_host' => !empty($_POST['mci_event_host']) && $_POST['mci_event_host'] ? 'on' : 'off');
        update_option('mc_input_options', $mc_input_options);
        update_option('mc_input_options_administrators', $mc_input_options_administrators);
        update_option('mc_skip_holidays', !empty($_POST['mc_skip_holidays']) && $_POST['mc_skip_holidays'] == 'on' ? 'true' : 'false');
        update_option('mc_no_fifth_week', !empty($_POST['mc_no_fifth_week']) && $_POST['mc_no_fifth_week'] == 'on' ? 'true' : 'false');
        update_option('mc_event_link_expires', !empty($_POST['mc_event_link_expires']) && $_POST['mc_event_link_expires'] == 'on' ? 'true' : 'false');
        echo "<div class=\"updated\"><p><strong>" . __('Input Settings saved', 'my-calendar') . ".</strong></p></div>";
    }
    if (current_user_can('manage_network') && is_multisite()) {
        if (isset($_POST['mc_network'])) {
            $mc_multisite = (int) $_POST['mc_multisite'];
            update_site_option('mc_multisite', $mc_multisite);
            $mc_multisite_show = (int) $_POST['mc_multisite_show'];
            update_site_option('mc_multisite_show', $mc_multisite_show);
            echo "<div class=\"updated\"><p><strong>" . __('Multisite settings saved', 'my-calendar') . ".</strong></p></div>";
        }
    }
    // custom text
    if (isset($_POST['mc_previous_events'])) {
        $mc_title_template = $_POST['mc_title_template'];
        $mc_title_template_solo = $_POST['mc_title_template_solo'];
        $mc_title_template_list = $_POST['mc_title_template_list'];
        $mc_details_label = $_POST['mc_details_label'];
        $mc_link_label = $_POST['mc_link_label'];
        $mc_event_title_template = $_POST['mc_event_title_template'];
        $mc_notime_text = $_POST['mc_notime_text'];
        $mc_previous_events = $_POST['mc_previous_events'];
        $mc_next_events = $_POST['mc_next_events'];
        $mc_event_open = $_POST['mc_event_open'];
        $mc_event_closed = $_POST['mc_event_closed'];
        $mc_week_caption = $_POST['mc_week_caption'];
        $mc_caption = $_POST['mc_caption'];
        $templates = get_option('mc_templates');
        $templates['title'] = $mc_title_template;
        $templates['title_solo'] = $mc_title_template_solo;
        $templates['title_list'] = $mc_title_template_list;
        $templates['label'] = $mc_details_label;
        $templates['link'] = $mc_link_label;
        update_option('mc_templates', $templates);
        update_option('mc_event_title_template', $mc_event_title_template);
        update_option('mc_notime_text', $mc_notime_text);
        update_option('mc_week_caption', $mc_week_caption);
        update_option('mc_next_events', $mc_next_events);
        update_option('mc_previous_events', $mc_previous_events);
        update_option('mc_caption', $mc_caption);
        update_option('mc_event_open', $mc_event_open);
        update_option('mc_event_closed', $mc_event_closed);
        // date/time
        update_option('mc_date_format', stripslashes($_POST['mc_date_format']));
        update_option('mc_week_format', stripslashes($_POST['mc_week_format']));
        update_option('mc_time_format', stripslashes($_POST['mc_time_format']));
        update_option('mc_month_format', stripslashes($_POST['mc_month_format']));
        $mc_ical_utc = !empty($_POST['mc_ical_utc']) && $_POST['mc_ical_utc'] == 'on' ? 'true' : 'false';
        update_option('mc_ical_utc', $mc_ical_utc);
        echo "<div class=\"updated\"><p><strong>" . __('Custom text settings saved', 'my-calendar') . ".</strong></p></div>";
    }
    // Mail function by Roland
    if (isset($_POST['mc_email'])) {
        $mc_event_mail = !empty($_POST['mc_event_mail']) && $_POST['mc_event_mail'] == 'on' ? 'true' : 'false';
        $mc_html_email = !empty($_POST['mc_html_email']) && $_POST['mc_html_email'] == 'on' ? 'true' : 'false';
        $mc_event_mail_to = $_POST['mc_event_mail_to'];
        $mc_event_mail_from = $_POST['mc_event_mail_from'];
        $mc_event_mail_subject = $_POST['mc_event_mail_subject'];
        $mc_event_mail_message = $_POST['mc_event_mail_message'];
        $mc_event_mail_bcc = $_POST['mc_event_mail_bcc'];
        update_option('mc_event_mail_to', $mc_event_mail_to);
        update_option('mc_event_mail_from', $mc_event_mail_from);
        update_option('mc_event_mail_subject', $mc_event_mail_subject);
        update_option('mc_event_mail_message', $mc_event_mail_message);
        update_option('mc_event_mail_bcc', $mc_event_mail_bcc);
        update_option('mc_event_mail', $mc_event_mail);
        update_option('mc_html_email', $mc_html_email);
        echo "<div class=\"updated\"><p><strong>" . __('Email notice settings saved', 'my-calendar') . ".</strong></p></div>";
    }
    // Custom User Settings
    apply_filters('mc_save_settings', '', $_POST);
    // pull templates for passing into functions.
    $templates = get_option('mc_templates');
    $mc_title_template = isset($templates['title']) ? esc_attr(stripslashes($templates['title'])) : '';
    $mc_title_template_solo = isset($templates['title_solo']) ? esc_attr(stripslashes($templates['title_solo'])) : '';
    $mc_title_template_list = isset($templates['title_list']) ? esc_attr(stripslashes($templates['title_list'])) : '';
    $mc_details_label = isset($templates['label']) ? esc_attr(stripslashes($templates['label'])) : '';
    $mc_link_label = isset($templates['link']) ? esc_attr(stripslashes($templates['link'])) : '';
    ?>

	<div class="wrap jd-my-calendar mc-settings-page" id="mc_settings">
	<?php 
    my_calendar_check_db();
    ?>
	<h1><?php 
    _e('My Calendar Settings', 'my-calendar');
    ?>
</h1>

	<div class="mc-tabs settings postbox-container jcd-wide">
	<div class="metabox-holder">
	<?php 
    //update_option( 'ko_calendar_imported','false' ); // for testing importing.
    if (isset($_POST['import']) && $_POST['import'] == 'true') {
        $nonce = $_REQUEST['_wpnonce'];
        if (!wp_verify_nonce($nonce, 'my-calendar-nonce')) {
            die("Security check failed");
        }
        my_calendar_import();
    }
    if (get_option('ko_calendar_imported') != 'true') {
        if (function_exists('check_calendar')) {
            ?>
			<div class='import upgrade-db'>
				<p>
					<?php 
            _e('My Calendar has identified that you have the Calendar plugin by Kieran O\'Shea installed. You can import those events and categories into the My Calendar database. Would you like to import these events?', 'my-calendar');
            ?>
				</p>

				<form method="post" action="<?php 
            echo admin_url("admin.php?page=my-calendar-config");
            ?>
">
					<div><input type="hidden" name="_wpnonce"
					            value="<?php 
            echo wp_create_nonce('my-calendar-nonce');
            ?>
"/></div>
					<div>
						<input type="hidden" name="import" value="true"/>
						<input type="submit" value="<?php 
            _e('Import from Calendar', 'my-calendar');
            ?>
"
						       name="import-calendar" class="button-primary"/>
					</div>
				</form>
			</div>
		<?php 
        }
    }
    ?>
		<ul class="tabs" role="tablist">
			<li role="tab" id="tab_manage" aria-controls="my-calendar-manage"><a href="#my-calendar-manage"><?php 
    _e('General', 'my-calendar');
    ?>
</a></li>
			<li role="tab" id="tab_text" aria-controls="my-calendar-text"><a href="#my-calendar-text"><?php 
    _e('Text', 'my-calendar');
    ?>
</a></li>
			<li role="tab" id="tab_output" aria-controls="mc-output"><a href="#mc-output"><?php 
    _e('Output', 'my-calendar');
    ?>
</a></li>
			<li role="tab" id="tab_input" aria-controls="my-calendar-input"><a href="#my-calendar-input"><?php 
    _e('Input', 'my-calendar');
    ?>
</a></li>
			<?php 
    if (current_user_can('manage_network') && is_multisite()) {
        ?>
				<li role="tab" id="tab_multi" aria-controls="my-calendar-multisite"><a href="#my-calendar-multisite"><?php 
        _e('Multi-site', 'my-calendar');
        ?>
</a></li>
			<?php 
    }
    ?>
			<li role="tab" id="tab_permissions" aria-controls="my-calendar-permissions"><a href="#my-calendar-permissions"><?php 
    _e('Permissions', 'my-calendar');
    ?>
</a></li>
			<li role="tab" id="tab_email" aria-controls="my-calendar-email"><a href="#my-calendar-email"><?php 
    _e('Notifications', 'my-calendar');
    ?>
</a></li>
			<?php 
    echo apply_filters('mc_settings_section_links', '');
    ?>
		</ul>

	<div class="ui-sortable meta-box-sortables">
		<div class="wptab postbox" aria-labelledby="tab_manage" role="tabpanel" aria-live="assertive" id="my-calendar-manage">
			<h2><?php 
    _e('My Calendar Management', 'my-calendar');
    ?>
</h2>

			<div class="inside">
				<?php 
    if (current_user_can('administrator')) {
        ?>
					<form method="post" action="<?php 
        echo admin_url("admin.php?page=my-calendar-config#my-calendar-manage");
        ?>
">
						<div><input type="hidden" name="_wpnonce"
						            value="<?php 
        echo wp_create_nonce('my-calendar-nonce');
        ?>
"/></div>
						<fieldset>
							<legend class="screen-reader-text"><?php 
        _e('Management', 'my-calendar');
        ?>
</legend>
							<ul>
								<?php 
        $guess = mc_guess_calendar();
        ?>
								<li><?php 
        mc_settings_field('mc_uri', __('Where is your main calendar page?', 'my-calendar'), '', "{$guess['message']}", array('size' => '60'), 'url');
        ?>
</li>							
								<li><?php 
        mc_settings_field('mc_remote', __('Get data (events, categories and locations) from a remote database.', 'my-calendar'), '', '', array(), 'checkbox-single');
        ?>
</li>
								<?php 
        if (get_option('mc_remote') == 'true') {
            ?>
									<li><?php 
            _e('Add this code to your theme\'s <code>functions.php</code> file:', 'my-calendar');
            ?>
										<pre>function mc_remote_db() {
	$mcdb = new wpdb('DB_USER','DB_PASSWORD','DB_NAME','DB_ADDRESS');
	return $mcdb;
}</pre>
										<?php 
            _e('You will need to allow remote connections from this site to the site hosting your My Calendar events. Replace the above placeholders with the host-site information. The two sites must have the same WP table prefix. While this option is enabled, you may not enter or edit events through this installation.', 'my-calendar');
            ?>
									</li>
								<?php 
        }
        ?>
								<li><?php 
        mc_settings_field('mc_event_approve', __('Enable approval options.', 'my-calendar'), '', '', array(), 'checkbox-single');
        ?>
</li>
								<li><?php 
        mc_settings_field('mc_api_enabled', __('Enable external API.', 'my-calendar'), '', '', array(), 'checkbox-single');
        ?>
</li>
								<?php 
        if (apply_filters('mc_caching_clear', false)) {
            ?>
									<li><?php 
            mc_settings_field('mc_clear_cache', __('Clear current cache. (Necessary if you edit shortcodes to change displayed categories, for example.)', 'my-calendar'), '', '', array(), 'checkbox-single');
            ?>
</li>
								<?php 
        }
        ?>
								<li><?php 
        mc_settings_field('mc_default_sort', __('Default Sort order for Admin Events List', 'my-calendar'), array('1' => __('Event ID', 'my-calendar'), '2' => __('Title', 'my-calendar'), '3' => __('Description', 'my-calendar'), '4' => __('Start Date', 'my-calendar'), '5' => __('Author', 'my-calendar'), '6' => __('Category', 'my-calendar'), '7' => __('Location Name', 'my-calendar')), '', array(), 'select');
        ?>
</li>
								<li><?php 
        mc_settings_field('mc_default_direction', __('Sort direction', 'my-calendar'), array('ASC' => __('Ascending', 'my-calendar'), 'DESC' => __('Descending', 'my-calendar')), '', array(), 'select');
        ?>
</li>										
								<?php 
        if (get_site_option('mc_multisite') == 2 && my_calendar_table() != my_calendar_table('global')) {
            mc_settings_field('mc_current_table', array('0' => __('Currently editing my local calendar', 'my-calendar'), '1' => __('Currently editing the network calendar', 'my-calendar')), '0', '', array(), 'radio');
        } else {
            if (get_option('mc_remote') != 'true' && current_user_can('manage_network') && is_multisite()) {
                ?>
										<li><?php 
                _e('You are currently working in the primary site for this network; your local calendar is also the global table.', 'my-calendar');
                ?>
</li><?php 
            }
        }
        ?>
								<li><?php 
        mc_settings_field('remigrate', __('Re-generate event occurrences table.', 'my-calendar'), '', '', array(), 'checkbox-single');
        ?>
</li>
							</ul>
						</fieldset>
						<p>
							<input type="submit" name="mc_manage" class="button-primary"
							       value="<?php 
        _e('Save Management Settings', 'my-calendar');
        ?>
"/>
						</p>
					</form>
				<?php 
    } else {
        ?>
					<?php 
        _e('My Calendar management settings are only available to administrators.', 'my-calendar');
        ?>
				<?php 
    }
    ?>
			</div>
		</div>

		<div class="wptab postbox" aria-labelledby="tab_text" role="tabpanel" aria-live="assertive" id="my-calendar-text">
			<h2><?php 
    _e('Text Settings', 'my-calendar');
    ?>
</h2>

			<div class="inside">
				<form method="post" action="<?php 
    echo admin_url("admin.php?page=my-calendar-config#my-calendar-text");
    ?>
">
					<div><input type="hidden" name="_wpnonce"
					            value="<?php 
    echo wp_create_nonce('my-calendar-nonce');
    ?>
"/></div>
					<fieldset>
						<legend class="screen-reader-text"><?php 
    _e('Customize Text Fields', 'my-calendar');
    ?>
</legend>
						<ul>
							<li><?php 
    mc_settings_field('mc_notime_text', __('Label for all-day events', 'my-calendar'), 'N/A');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_previous_events', __('Previous events link', 'my-calendar'), __('Previous', 'my-calendar'), __('Use <code>{date}</code> to display date in navigation.', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_next_events', __('Next events link', 'my-calendar'), __('Next', 'my-calendar'), __('Use <code>{date}</code> to display date in navigation.', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_open', __('If events are open', 'my-calendar'), __('Registration is open', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_closed', __('If events are closed', 'my-calendar'), __('Registration is closed', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_week_caption', __('Week view caption:', 'my-calendar'), '', __('Available tag: <code>{date format=""}</code>', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_caption', __('Extended caption:', 'my-calendar'), '', __('Follows month/year in list views.', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_title_template', __('Event title (Grid)', 'my-calendar'), $mc_title_template, "<a href='" . admin_url("admin.php?page=my-calendar-help#templates") . "'>" . __("Templating Help", 'my-calendar') . '</a>');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_title_template_solo', __('Event title (Single)', 'my-calendar'), $mc_title_template_solo, "<a href='" . admin_url("admin.php?page=my-calendar-help#templates") . "'>" . __("Templating Help", 'my-calendar') . '</a>');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_title_template_list', __('Event title (List)', 'my-calendar'), $mc_title_template_list, "<a href='" . admin_url("admin.php?page=my-calendar-help#templates") . "'>" . __("Templating Help", 'my-calendar') . '</a>');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_details_label', __('Event details link text', 'my-calendar'), $mc_details_label, __('Tags: <code>{title}</code>, <code>{location}</code>, <code>{color}</code>, <code>{icon}</code>, <code>{date}</code>, <code>{time}</code>.', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_link_label', __('Event URL link text', 'my-calendar'), $mc_link_label, "<a href='" . admin_url("admin.php?page=my-calendar-help#templates") . "'>" . __("Templating Help", 'my-calendar') . '</a>');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_title_template', __('Title element template', 'my-calendar'), '{title} &raquo; {date}', __('Current: %s', 'my-calendar'));
    ?>
</li>
						</ul>
					</fieldset>
					<fieldset>
						<legend><?php 
    _e('Date/Time formats', 'my-calendar');
    ?>
</legend>
						<div><input type='hidden' name='mc_dates' value='true'/></div>
						<ul>
							<?php 
    $month_format = get_option('mc_month_format') == '' ? date_i18n('F Y') : date_i18n(get_option('mc_month_format'));
    $time_format = get_option('mc_time_format') == '' ? date_i18n(get_option('time_format')) : date_i18n(get_option('mc_time_format'));
    $week_format = get_option('mc_week_format') == '' ? date_i18n('M j, \'y') : date_i18n(get_option('mc_week_format'));
    $date_format = get_option('mc_date_format') == '' ? date_i18n(get_option('date_format')) : date_i18n(get_option('mc_date_format'));
    ?>
							<li><?php 
    mc_settings_field('mc_month_format', __('Month format (calendar headings)', 'my-calendar'), '', $month_format);
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_time_format', __('Time format', 'my-calendar'), '', $time_format);
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_week_format', __('Date in grid mode, week view', 'my-calendar'), '', $week_format);
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_date_format', __('Date Format in other views', 'my-calendar'), '', $date_format);
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_ical_utc', __('iCal times are UTC', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
						</ul>
					</fieldset>					
					<p>
						<input type="submit" name="save" class="button-primary"
						       value="<?php 
    _e('Save Custom Text Settings', 'my-calendar');
    ?>
"/>
					</p>
				</form>
				<p>
				<?php 
    _e('Date formats use syntax from the <a href="http://php.net/date">PHP <code>date()</code> function</a>. Save to update sample output.', 'my-calendar');
    ?>
				</p>				
			</div>
		</div>

		<div class="wptab postbox" aria-labelledby="tab_output" role="tabpanel" aria-live="assertive" id="mc-output">
			<h2><?php 
    _e('Output Settings', 'my-calendar');
    ?>
</h2>

			<div class="inside">
				<form method="post" action="<?php 
    echo admin_url("admin.php?page=my-calendar-config#mc-output");
    ?>
">
					<div><input type="hidden" name="_wpnonce"
					            value="<?php 
    echo wp_create_nonce('my-calendar-nonce');
    ?>
"/></div>
					<input type="submit" name="save" class="button screen-reader-text" value="<?php 
    _e('Save Output Settings', 'my-calendar');
    ?>
" /></p>		
					<fieldset>
						<legend><?php 
    _e('Calendar Link Targets', 'my-calendar');
    ?>
</legend>
						<ul>
							<?php 
    $guess = mc_guess_calendar();
    ?>
							<li><?php 
    mc_settings_field('mc_uri', __('Where is your main calendar page?', 'my-calendar'), '', "{$guess['message']}", array('size' => '60'), 'url');
    ?>
</li>
							<?php 
    if (isset($_POST['mc_use_permalinks']) && $note != '') {
        $url = admin_url('options-permalink.php#mc_cpt_base');
        $note = ' <span class="mc-notice">' . sprintf(__('Go to <a href="%s">permalink settings</a> to set the base URL for events.', 'my-calendar') . '</span>', $url);
    } else {
        $note = '';
    }
    ?>
							<li><?php 
    mc_settings_field('mc_use_permalinks', __('Use Pretty Permalinks for Events', 'my-calendar'), '', $note, array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_open_uri', __('Open calendar links to event details URL', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_mini_uri', __('Target <abbr title="Uniform resource locator">URL</abbr> for mini calendar date links:', 'my-calendar'), '', '', array('size' => '60'), 'url');
    ?>
</li>							
							<?php 
    $disabled = !get_option('mc_uri') && !get_option('mc_mini_uri') ? array('disabled' => 'disabled') : array();
    ?>
							<li><?php 
    mc_settings_field('mc_open_day_uri', __('Mini calendar widget date links to:', 'my-calendar'), array('false' => __('jQuery pop-up view', 'my-calendar'), 'true' => __('daily view page (above)', 'my-calendar'), 'listanchor' => __('in-page anchor on main calendar page (list)', 'my-calendar'), 'calendaranchor' => __('in-page anchor on main calendar page (grid)', 'my-calendar')), '', $disabled, 'select');
    ?>
</li>
						</ul>
						<?php 
    // End General Options //
    ?>
					</fieldset>

					<fieldset>
						<legend><?php 
    _e('Re-order calendar layout', 'my-calendar');
    ?>
</legend>
						<?php 
    $topnav = explode(',', get_option('mc_topnav'));
    $calendar = array('calendar');
    $botnav = explode(',', get_option('mc_bottomnav'));
    $order = array_merge($topnav, $calendar, $botnav);
    $nav_elements = array('nav' => '<div class="dashicons dashicons-arrow-left-alt2"></div> <div class="dashicons dashicons-arrow-right-alt2"></div> ' . __('Primary Previous/Next Buttons', 'my-calendar'), 'toggle' => '<div class="dashicons dashicons-list-view"></div> <div class="dashicons dashicons-calendar"></div> ' . __('Switch between list and grid views', 'my-calendar'), 'jump' => '<div class="dashicons dashicons-redo"></div> ' . __('Jump to any other month/year', 'my-calendar'), 'print' => '<div class="dashicons dashicons-list-view"></div> ' . __('Link to printable view', 'my-calendar'), 'timeframe' => '<div class="dashicons dashicons-clock"></div> ' . __('Toggle between day, week, and month view', 'my-calendar'), 'calendar' => '<div class="dashicons dashicons-calendar"></div> ' . __('The calendar', 'my-calendar'), 'key' => '<div class="dashicons dashicons-admin-network"></div> ' . __('Categories', 'my-calendar'), 'feeds' => '<div class="dashicons dashicons-rss"></div> ' . __('Links to RSS and iCal output', 'my-calendar'), 'stop' => '<div class="dashicons dashicons-no"></div> ' . __('Elements below here will be hidden.'));
    echo "<div id='mc-sortable-update' aria-live='assertive'></div>";
    echo "<ul id='mc-sortable'>";
    $inserted = array();
    $class = 'visible';
    $count = count($nav_elements);
    $i = 1;
    foreach ($order as $k) {
        $k = trim($k);
        $v = isset($nav_elements[$k]) ? $nav_elements[$k] : false;
        if ($v !== false) {
            $inserted[$k] = $v;
            if ($k == 'stop') {
                $label = 'hide';
            } else {
                $label = $k;
            }
            if ($i == 1) {
                $buttons = "<button class='down' type='button'><i class='dashicons dashicons-arrow-down'></i><span class='screen-reader-text'>Down</span></button>";
            } else {
                if ($i == $count) {
                    $buttons = "<button class='up' type='button'><i class='dashicons dashicons-arrow-up'></i><span class='screen-reader-text'>Up</span></button>";
                } else {
                    $buttons = "<button class='up' type='button'><i class='dashicons dashicons-arrow-up'></i><span class='screen-reader-text'>Up</span></button> <button class='down'><i class='dashicons dashicons-arrow-down'></i><span class='screen-reader-text'>Down</span></button>";
                }
            }
            $buttons = "<div class='mc-buttons'>{$buttons}</div>";
            echo "<li class='ui-state-default mc-{$k} mc-{$class}'>{$buttons} <code>{$label}</code> {$v} <input type='hidden' name='mc_nav[]' value='{$k}' /></li>";
            $i++;
        }
    }
    $missed = array_diff($nav_elements, $inserted);
    $i = 1;
    $count = count($missed);
    foreach ($missed as $k => $v) {
        if ($i != $count) {
            $buttons = "<button class='up'><i class='dashicons dashicons-arrow-up'></i><span class='screen-reader-text'>Up</span></button> <button class='down'><i class='dashicons dashicons-arrow-down'></i><span class='screen-reader-text'>Down</span></button>";
        } else {
            $buttons = "<button class='up'><i class='dashicons dashicons-arrow-up'></i><span class='screen-reader-text'>Up</span></button>";
        }
        $buttons = "<div class='mc-buttons'>{$buttons}</div>";
        echo "<li class='ui-state-default mc-{$k} mc-hidden'>{$buttons} <code>{$k}</code> {$v} <input type='hidden' name='mc_nav[]' value='{$k}' /></li>";
        $i++;
    }
    echo "</ul>";
    ?>
					</fieldset>

					<fieldset>
						<legend><?php 
    _e('Single Event Details', 'my-calendar');
    ?>
</legend>
						<p><?php 
    _e('Custom templates override these settings.', 'my-calendar');
    ?>
						<ul class="checkboxes">
							<li><?php 
    mc_settings_field('mc_display_author', __('Author\'s name', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_show_event_vcal', __('Link to single event iCal download', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_show_gcal', __('Link to submit event to Google Calendar', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_show_map', __('Link to Google Map', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_gmap', __('Google Map (single event view only)', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_gmap_api_key', __('Google Maps API Key', 'my-calendar'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_show_address', __('Event Address', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_short', __('Short description', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_desc', __('Full description', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_process_shortcodes', __('Process WordPress shortcodes in descriptions', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_link', __('External link', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_display_more', __('More details link', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_registration', __('Registration info', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
						</ul>
					</fieldset>

					<fieldset>
						<legend><?php 
    _e('Grid Options', 'my-calendar');
    ?>
</legend>
						<ul>
							<li><?php 
    mc_settings_field('mc_show_weekends', __('Show Weekends on Calendar', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_convert', array('true' => __('Switch to list view on mobile devices', 'my-calendar'), 'mini' => __('Switch to mini calendar on mobile devices', 'my-calendar'), 'none' => __('Do not switch calendar mode', 'my-calendar')), 'false', '', array(), 'radio');
    ?>
</li>
						</ul>
					</fieldset>
					<fieldset>
						<legend><?php 
    _e('List Options', 'my-calendar');
    ?>
</legend>
						<ul>
							<li><?php 
    mc_settings_field('mc_show_months', __('How many months of events to show at a time:', 'my-calendar'), '', '', array('size' => '3'), 'text');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_show_list_info', __('Show the first event\'s title and the number of events that day next to the date.', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
						</ul>
					</fieldset>					
					
					<fieldset>
						<legend><?php 
    _e('Category Colors', 'my-calendar');
    ?>
</legend>
						<ul class='checkboxes'>
							<?php 
    mc_settings_field('mc_apply_color', array('default' => __('No category colors with titles.', 'my-calendar'), 'font' => __('Titles are in category colors.', 'my-calendar'), 'background' => __('Titles have category color as background.', 'my-calendar')), 'default', '', array(), 'radio');
    ?>
							<li><?php 
    mc_settings_field('mc_inverse_color', __('Optimize contrast for category colors.', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_hide_icons', __('Hide Category icons', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
						</ul>
						<?php 
    // End Event Options //
    ?>
					</fieldset>
					<p><input type="submit" name="save" class="button-primary"
					          value="<?php 
    _e('Save Output Settings', 'my-calendar');
    ?>
"/></p>
				</form>
			</div>
		</div>
		
		<div class="wptab postbox" aria-labelledby="tab_input" role="tabpanel" aria-live="assertive"  id="my-calendar-input">
			<h2><?php 
    _e('Calendar Input Fields', 'my-calendar');
    ?>
</h2>

			<div class="inside">
				<form method="post" action="<?php 
    echo admin_url("admin.php?page=my-calendar-config#my-calendar-input");
    ?>
">
					<div><input type="hidden" name="_wpnonce"
					            value="<?php 
    echo wp_create_nonce('my-calendar-nonce');
    ?>
"/></div>
					<fieldset>
						<legend><?php 
    _e('Show in event manager', 'my-calendar');
    ?>
</legend>
						<div><input type='hidden' name='mc_input' value='true'/></div>
						<ul class="checkboxes">
							<?php 
    $input_options = get_option('mc_input_options');
    $input_labels = array('event_location_dropdown' => __('Event Location Dropdown Menu', 'my-calendar'), 'event_short' => __('Event Short Description field', 'my-calendar'), 'event_desc' => __('Event Description Field', 'my-calendar'), 'event_category' => __('Event Category field', 'my-calendar'), 'event_image' => __('Event Image field', 'my-calendar'), 'event_link' => __('Event Link field', 'my-calendar'), 'event_recurs' => __('Event Recurrence Options', 'my-calendar'), 'event_open' => __('Event Registration options', 'my-calendar'), 'event_location' => __('Event Location fields', 'my-calendar'), 'event_specials' => __('Set Special Scheduling options', 'my-calendar'), 'event_access' => __('Event Accessibility', 'my-calendar'), 'event_host' => __('Event Host', 'my-calendar'));
    $output = '';
    // if input options isn't an array, we'll assume that this plugin wasn't upgraded properly, and reset them to the default.
    if (!is_array($input_options)) {
        update_option('mc_input_options', array('event_short' => 'on', 'event_desc' => 'on', 'event_category' => 'on', 'event_image' => 'on', 'event_link' => 'on', 'event_recurs' => 'on', 'event_open' => 'on', 'event_location' => 'off', 'event_location_dropdown' => 'on', 'event_specials' => 'on', 'event_access' => 'on', 'event_host' => 'on'));
        $input_options = get_option('mc_input_options');
    }
    foreach ($input_options as $key => $value) {
        $checked = $value == 'on' ? "checked='checked'" : '';
        if (isset($input_labels[$key])) {
            $output .= "<li><input type='checkbox' id='mci_{$key}' name='mci_{$key}' {$checked} /> <label for='mci_{$key}'>{$input_labels[$key]}</label></li>";
        }
    }
    echo $output;
    ?>
							<li><?php 
    mc_settings_field('mc_input_options_administrators', __('Administrators see all input options', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
						</ul>
					</fieldset>
					<fieldset>
						<legend><?php 
    _e('Event Scheduling Defaults', 'my-calendar');
    ?>
</legend>
						<ul>
							<li><?php 
    mc_settings_field('mc_event_link_expires', __('Event links expire after event passes.', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_no_fifth_week', __('If a recurring event falls on a date that doesn\'t exist (like the 5th Wednesday in February), move it back one week.', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_skip_holidays', __('If an event coincides with an event in the designated "Holiday" category, do not show the event.', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
						</ul>
						<?php 
    // End Scheduling Options //
    ?>
					</fieldset>					
					<p>
						<input type="submit" name="save" class="button-primary"
						       value="<?php 
    _e('Save Input Settings', 'my-calendar');
    ?>
"/>
					</p>
				</form>
			</div>
		</div>

	<?php 
    if (current_user_can('manage_network') && is_multisite()) {
        ?>
			<div class="wptab postbox" aria-labelledby="tab_multi" role="tabpanel" aria-live="assertive"  id="my-calendar-multisite">
				<h2><?php 
        _e('Multisite Settings (Network Administrators only)', 'my-calendar');
        ?>
</h2>

				<div class="inside">
					<p><?php 
        _e('The central calendar is the calendar associated with the primary site in your WordPress Multisite network.', 'my-calendar');
        ?>
</p>
					<form method="post" action="<?php 
        echo admin_url("admin.php?page=my-calendar-config#my-calendar-multisite");
        ?>
">
						<div>
							<input type="hidden" name="_wpnonce" value="<?php 
        echo wp_create_nonce('my-calendar-nonce');
        ?>
"/>
							<input type='hidden' name='mc_network' value='true'/>
						</div>
						<fieldset>
							<legend><?php 
        _e('Multisite configuration - input', 'my-calendar');
        ?>
</legend>
							<ul>
								<li>
									<input type="radio" value="0" id="ms0" name="mc_multisite"<?php 
        echo jd_option_selected(get_site_option('mc_multisite'), '0');
        ?>
 /> <label for="ms0"><?php 
        _e('Site owners may only post to their local calendar', 'my-calendar');
        ?>
</label>
								</li>
								<li>
									<input type="radio" value="1" id="ms1" name="mc_multisite"<?php 
        echo jd_option_selected(get_site_option('mc_multisite'), '1');
        ?>
 /> <label for="ms1"><?php 
        _e('Site owners may only post to the central calendar', 'my-calendar');
        ?>
</label>
								</li>
								<li>
									<input type="radio" value="2" id="ms2" name="mc_multisite"<?php 
        echo jd_option_selected(get_site_option('mc_multisite'), 2);
        ?>
 /> <label for="ms2"><?php 
        _e('Site owners may manage either calendar', 'my-calendar');
        ?>
</label>
								</li>
							</ul>
							<p>
								<em><?php 
        _e('Changes only effect input permissions. Public-facing calendars will be unchanged.', 'my-calendar');
        ?>
</em>
							</p>
						</fieldset>
						<fieldset>
							<legend><?php 
        _e('Multisite configuration - output', 'my-calendar');
        ?>
</legend>							
							<ul>
								<li><input type="radio" value="0" id="mss0"
								           name="mc_multisite_show"<?php 
        echo jd_option_selected(get_site_option('mc_multisite_show'), '0');
        ?>
 />
									<label
										for="mss0"><?php 
        _e('Sub-site calendars show events from their local calendar.', 'my-calendar');
        ?>
</label>
								</li>
								<li><input type="radio" value="1" id="mss1"
								           name="mc_multisite_show"<?php 
        echo jd_option_selected(get_site_option('mc_multisite_show'), '1');
        ?>
 />
									<label
										for="mss1"><?php 
        _e('Sub-site calendars show events from the central calendar.', 'my-calendar');
        ?>
</label>
								</li>
							</ul>
						</fieldset>
						<p>
							<input type="submit" name="save" class="button-primary"
							       value="<?php 
        _e('Save Multisite Settings', 'my-calendar');
        ?>
"/>
						</p>
					</form>
				</div>
			</div>
	<?php 
    }
    ?>

		<div class="wptab postbox" aria-labelledby="tab_permissions" role="tabpanel" aria-live="assertive"  id="my-calendar-permissions">
			<h2><?php 
    _e('My Calendar Permissions', 'my-calendar');
    ?>
</h2>

			<div class="inside">
				<?php 
    if (current_user_can('administrator')) {
        ?>

					<form method="post" action="<?php 
        echo admin_url("admin.php?page=my-calendar-config#my-calendar-permissions");
        ?>
">
						<div><input type="hidden" name="_wpnonce"
						            value="<?php 
        echo wp_create_nonce('my-calendar-nonce');
        ?>
"/></div>
						<?php 
        global $wp_roles;
        $roles = $wp_roles->get_names();
        $caps = array('mc_add_events' => __('Add Events', 'my-calendar'), 'mc_approve_events' => __('Approve Events', 'my-calendar'), 'mc_manage_events' => __('Manage Events', 'my-calendar'), 'mc_edit_cats' => __('Edit Categories', 'my-calendar'), 'mc_edit_locations' => __('Edit Locations', 'my-calendar'), 'mc_edit_styles' => __('Edit Styles', 'my-calendar'), 'mc_edit_behaviors' => __('Edit Behaviors', 'my-calendar'), 'mc_edit_templates' => __('Edit Templates', 'my-calendar'), 'mc_edit_settings' => __('Edit Settings', 'my-calendar'), 'mc_view_help' => __('View Help', 'my-calendar'));
        $role_container = '';
        foreach ($roles as $role => $rolename) {
            if ($role == 'administrator') {
                continue;
            }
            $role_container .= "<div class='mc_{$role} mc_permissions' id='container_mc_{$role}'><fieldset id='mc_{$role}' class='roles'><legend>{$rolename}</legend>";
            $role_container .= "<input type='hidden' value='none' name='mc_caps[" . $role . "][none]' />\r\n\t\t\t<ul class='mc-settings checkboxes'>";
            foreach ($caps as $cap => $name) {
                $role_container .= mc_cap_checkbox($role, $cap, $name);
            }
            $role_container .= "\r\n\t\t\t</ul></fieldset></div>\n";
        }
        echo "{$role_container}";
        ?>
						<p>
							<input type="submit" name="mc_permissions" class="button-primary"
							       value="<?php 
        _e('Save Permissions', 'my-calendar');
        ?>
"/>
						</p>
					</form>
				<?php 
    } else {
        ?>
					<?php 
        _e('My Calendar permission settings are only available to administrators.', 'my-calendar');
        ?>
				<?php 
    }
    ?>
			</div>
		</div>

		<div class="wptab postbox" aria-labelledby="tab_email" role="tabpanel" aria-live="assertive"  id="my-calendar-email">
			<h2><?php 
    _e('Calendar Email Settings', 'my-calendar');
    ?>
</h2>

			<div class="inside">
				<form method="post" action="<?php 
    echo admin_url("admin.php?page=my-calendar-config#my-calendar-email");
    ?>
">
					<div><input type="hidden" name="_wpnonce"
					            value="<?php 
    echo wp_create_nonce('my-calendar-nonce');
    ?>
"/></div>
					<fieldset>
						<legend><?php 
    _e('Email Notifications', 'my-calendar');
    ?>
</legend>
						<div><input type='hidden' name='mc_email' value='true'/></div>
						<ul>
							<li><?php 
    mc_settings_field('mc_event_mail', __('Send Email Notifications when new events are scheduled or reserved.', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_html_email', __('Send HTML email', 'my-calendar'), '', '', array(), 'checkbox-single');
    ?>
</li>	
							<li><?php 
    mc_settings_field('mc_event_mail_to', __('Notification messages are sent to:', 'my-calendar'), get_bloginfo('admin_email'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_mail_from', __('Notification messages are sent from:', 'my-calendar'), get_bloginfo('admin_email'));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_mail_bcc', __('BCC on notifications (one per line):', 'my-calendar'), '', '', array('cols' => 60, 'rows' => 6), 'textarea');
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_mail_subject', __('Email subject', 'my-calendar'), get_bloginfo('name') . ': ' . __('New event added', 'my-calendar'), '', array('size' => 60));
    ?>
</li>
							<li><?php 
    mc_settings_field('mc_event_mail_message', __('Message Body', 'my-calendar'), __('New Event:', 'my-calendar') . "\n{title}: {date}, {time} - {event_status}", "<br /><a href='" . admin_url("admin.php?page=my-calendar-help#templates") . "'>" . __("Templating Help", 'my-calendar') . '</a>', array('cols' => 60, 'rows' => 6), 'textarea');
    ?>
</li>
						</ul>
					</fieldset>
					<p>
						<input type="submit" name="save" class="button-primary" value="<?php 
    _e('Save Email Settings', 'my-calendar');
    ?>
"/>
					</p>
				</form>
			</div>
		</div>
	</div>

	<?php 
    echo apply_filters('mc_after_settings', '');
    ?>

	</div>
	</div>

	<?php 
    mc_show_sidebar();
    ?>

	</div>
<?php 
}