/**
 * Check if URL is local
 *
 * @since 0.9
 * @param string $url URL to test
 * @return bool True if URL is local
 */
function ctfw_is_local_url($url)
{
    $bool = false;
    if (ctfw_is_url($url) && preg_match('/^' . preg_quote(home_url(), '/') . '/', $url)) {
        $bool = true;
    }
    return apply_filters('ctfw_is_local_url', $bool, $url);
}
/**
 * Embed code based on audio/video URL or provided embed code
 *
 * If content is URL, use oEmbed to get embed code. If content is not URL, assume it is
 * embed code and run do_shortcode() in case of [video], [audio] or [embed]
 *
 * @since 0.9
 * @param string $content URL
 */
function ctfw_embed_code($content)
{
    global $wp_embed;
    // Convert URL into media shortcode like [audio] or [video]
    if (ctfw_is_url($content)) {
        $embed_code = $wp_embed->shortcode(array(), $content);
    } else {
        $embed_code = $content;
    }
    // Run shortcode
    // [video], [audio] or [embed] converted from URL or already existing in $content
    $embed_code = do_shortcode($embed_code);
    // Return filtered
    return apply_filters('ctfw_embed_code', $embed_code, $content);
}
/**
 * Get archives for content type
 *
 * Specify content type to get taxonomy and month archives.
 * This can be useful for creating taxonomy page templates, dropdown navigation, etc.
 *
 * @since 1.7.1
 * @global object $wp_locale
 * @param array $args Arguments, all optional (see defaults and comments below)
 * @return array Archive data
 */
function ctfw_content_type_archives($args = array())
{
    global $wp_locale;
    // Default arguments
    $args = wp_parse_args($args, array('content_type' => ctfw_current_content_type(), 'specific_archive' => false, 'all_books' => false));
    extract($args);
    // make available as variables
    // Start array
    $archives = array();
    // Blog
    if ('blog' == $content_type) {
        // Categories (alphabetical)
        $taxonomy = 'category';
        if (!$specific_archive || $taxonomy == $specific_archive) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('pad_counts' => true));
        }
        // Tag (biggest first)
        $taxonomy = 'post_tag';
        if (!$specific_archive || $taxonomy == $specific_archive) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('orderby' => 'count', 'order' => 'DESC', 'pad_counts' => true));
        }
        // Months
        if (!$specific_archive || 'months' == $specific_archive) {
            $archives['months']['items'] = ctfw_get_month_archives('post');
        }
    }
    // Sermon
    if ('sermon' == $content_type) {
        // Topics (alphabetical)
        $taxonomy = 'ctc_sermon_topic';
        if (ctfw_ctc_taxonomy_supported($taxonomy) && (!$specific_archive || $taxonomy == $specific_archive)) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('pad_counts' => true));
        }
        // Series (newest first)
        $taxonomy = 'ctc_sermon_series';
        if (ctfw_ctc_taxonomy_supported($taxonomy) && (!$specific_archive || $taxonomy == $specific_archive)) {
            // Cache with transient because getting all series / sermons can be intensive
            // It's possible this function is called more than once during a page load
            // so let's cache it for a few seconds so the queries and loops are not repeated
            $transient_name = 'ctfw_content_type_archives_sermon_series';
            // 45 char max
            $transient = get_transient($transient_name);
            if ($transient) {
                // we have it; let's use it
                $series = $transient;
            } else {
                // Get series terms
                $series_terms = get_terms($taxonomy, array('orderby' => 'id', 'order' => 'DESC', 'pad_counts' => true));
                // Loop series
                $series_ids = array();
                $series = array();
                foreach ($series_terms as $series_term) {
                    // Get series IDs
                    $series_ids[] = $series_term->term_id;
                    // Add term to series array with ID as key
                    $series[$series_term->term_id] = $series_term;
                }
                // Get sermons having a series
                $series_sermons = get_posts(array('posts_per_page' => -1, 'post_type' => 'ctc_sermon', 'tax_query' => array(array('taxonomy' => 'ctc_sermon_series', 'field' => 'id', 'terms' => $series_ids))));
                // Loop sermons
                foreach ($series_sermons as $sermon) {
                    // Get series having this sermon
                    $series_with_sermon = wp_get_post_terms($sermon->ID, 'ctc_sermon_series', array('fields' => 'ids'));
                    // Loop series to add sermon
                    foreach ($series_with_sermon as $series_id) {
                        if (isset($series[$series_id])) {
                            if (!isset($series[$series_id]->sermons)) {
                                $series[$series_id]->sermons = array();
                            }
                            $series[$series_id]->sermons[$sermon->ID] = $sermon;
                        }
                    }
                }
                // Loop series to record latest and earliest sermon dates
                foreach ($series as $series_id => $series_data) {
                    $sermons = $series_data->sermons;
                    if ($sermons) {
                        // Latest sermon
                        $values = array_values($sermons);
                        $latest_sermon = array_shift($values);
                        $series[$series_id]->sermon_latest_date = strtotime($latest_sermon->post_date);
                        // Earliest sermon
                        $values = array_values($sermons);
                        $earliest_sermon = end($values);
                        $series[$series_id]->sermon_earliest_date = strtotime($earliest_sermon->post_date);
                    }
                }
                // Re-order series by latest sermon date
                usort($series, 'ctfw_sort_by_latest_sermon');
                // Cache with transient
                set_transient($transient_name, $series, 15);
                // 15 seconds is more than enough for a regular pageload
            }
            // Add to archives array
            $archives[$taxonomy]['items'] = $series;
        }
        // Book (in order of books in Bible)
        $taxonomy = 'ctc_sermon_book';
        if (ctfw_ctc_taxonomy_supported($taxonomy) && (!$specific_archive || $taxonomy == $specific_archive)) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('pad_counts' => true));
            // Re-order according to books in Bible
            if ($archives[$taxonomy]['items']) {
                $reordered_books = array();
                $unmatched_books = array();
                $bible_books = ctfw_bible_books();
                // Loop books in Bible
                foreach ($bible_books['all'] as $bible_book_key => $bible_book) {
                    // Include this book if found in terms
                    $found_book_term = false;
                    foreach ($archives[$taxonomy]['items'] as $book_term) {
                        if (trim(strtolower($book_term->name)) == strtolower($bible_book['name'])) {
                            // Add book data (testament, alternate names)
                            $book_term->book_data = $bible_book;
                            // Add it
                            $reordered_books[] = $book_term;
                            // Stop looking
                            $found_book_term = true;
                            break;
                        }
                    }
                    // Add book if no term was found and argument for empty books is set
                    if (!$found_book_term && $all_books) {
                        // Add name and count
                        $book_term = new stdClass();
                        $book_term->term_id = '';
                        $book_term->name = $bible_book['name'];
                        $book_term->count = 0;
                        // Add book data (testament, alternate names)
                        $book_term->book_data = $bible_book;
                        // Add it
                        $reordered_books[] = $book_term;
                    }
                }
                // Add those not found to end
                foreach ($archives[$taxonomy]['items'] as $book_term) {
                    // Not added to new array?
                    foreach ($bible_books['all'] as $bible_book_key => $bible_book) {
                        $found = false;
                        // Found it?
                        if ($bible_book['name'] == $book_term->name) {
                            $found = true;
                            break;
                        }
                    }
                    // Not found, append to end
                    if (!$found) {
                        $reordered_books[] = $book_term;
                    }
                }
                // Replace books with reordered array
                $archives[$taxonomy]['items'] = $reordered_books;
            }
        }
        // Speakers -- (by count)
        $taxonomy = 'ctc_sermon_speaker';
        if (ctfw_ctc_taxonomy_supported($taxonomy) && (!$specific_archive || $taxonomy == $specific_archive)) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('pad_counts' => true));
        }
        // Months
        if (!$specific_archive || 'months' == $specific_archive) {
            $archives['months']['items'] = ctfw_get_month_archives('ctc_sermon');
        }
    }
    // Event
    if ('event' == $content_type) {
        // Category (alphabetical)
        $taxonomy = 'ctc_event_category';
        if (ctfw_ctc_taxonomy_supported($taxonomy) && (!$specific_archive || $taxonomy == $specific_archive)) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('pad_counts' => false));
        }
        // Months
        // Each theme decides how to handle event archives, if any (such as on a monthly calendar via page template)
        // Therefore, ctfw_content_types must be filtered by theme to add correct URL format for month archives
        if (!$specific_archive || 'months' == $specific_archive) {
            $url_format = ctfw_content_type_data('event', 'month_archive_url_format');
            if (ctfw_is_url($url_format)) {
                // valid URL (e.g. page for a page template exists)
                // Date info
                $month_limit = apply_filters('ctfw_content_type_archives_event_month_limit', 12);
                // show up to X months into the future
                $year_month = date_i18n('Y-m');
                // start with current
                $DateTime = new DateTime($year_month);
                // Loop next X months
                $months_looped = 0;
                while ($months_looped < $month_limit) {
                    // Add month to archives array if has events
                    $count = ctfw_month_events_count($year_month);
                    // get number of event occurences in month
                    if ($count) {
                        // Date
                        $month_ts = strtotime($year_month);
                        $month = date_i18n('n', $month_ts);
                        // e.g. 1
                        $year = date_i18n('Y', $month_ts);
                        // e.g.  2015
                        // Name
                        // 'name' that is automatically localized (key matches taxonomy term object)
                        /* translators: 1: month name, 2: 4-digit year */
                        $name = sprintf(_x('%1$s %2$d', 'month archive', 'church-theme-framework'), $wp_locale->get_month($month), $year);
                        // URL
                        $url = ctfw_events_month_archive_url($year_month);
                        // Add data
                        // Use same format as ctfw_get_month_archives()
                        $archives['months']['items'][$months_looped] = new stdClass();
                        $archives['months']['items'][$months_looped]->year = $year;
                        $archives['months']['items'][$months_looped]->month = $month;
                        $archives['months']['items'][$months_looped]->count = $count;
                        $archives['months']['items'][$months_looped]->post = $count;
                        $archives['months']['items'][$months_looped]->name = $name;
                        $archives['months']['items'][$months_looped]->url = $url;
                    }
                    // Next month
                    $DateTime->modify('+1 month');
                    $year_month = $DateTime->format('Y-m');
                    // PHP 5.2 cannot chain methods
                    $months_looped++;
                }
            }
        }
    }
    // People
    if ('people' == $content_type) {
        // Groups (alphabetical)
        $taxonomy = 'ctc_person_group';
        if (ctfw_ctc_taxonomy_supported($taxonomy) && (!$specific_archive || $taxonomy == $specific_archive)) {
            $archives[$taxonomy]['items'] = get_terms($taxonomy, array('pad_counts' => true));
        }
    }
    // Loop archives
    // Remove those with no items
    // Add archive name and URLs to terms
    foreach ($archives as $archive_key => $archive) {
        // No items, remove archive
        if (empty($archives[$archive_key]['items'])) {
            unset($archives[$archive_key]);
        } else {
            // Month archive
            if ($archive_key == 'months') {
                // Type
                $archives[$archive_key]['type'] = 'months';
                // Name
                $archives[$archive_key]['name'] = _x('Months', 'content type archives', 'church-theme-framework');
            } else {
                // Type
                $archives[$archive_key]['type'] = 'taxonomy';
                // Name
                $taxonomy_data = get_taxonomy($archive_key);
                if (!empty($taxonomy_data->labels->menu_name)) {
                    $archives[$archive_key]['name'] = $taxonomy_data->labels->menu_name;
                    // e.g. "Topics" instead of "Sermon Topics"
                } else {
                    // should never happen, but just in case
                    $archives[$archive_key]['name'] = isset($taxonomy_data->labels->name) ? $taxonomy_data->labels->name : ctfw_make_friendly($archive_key);
                }
                // Loop items
                $archive_items = $archive['items'];
                foreach ($archive['items'] as $archive_item_key => $archive_item) {
                    $archives[$archive_key]['items'][$archive_item_key]->url = !empty($archive_item->term_id) ? get_term_link($archive_item) : '';
                }
            }
            // Move items to end of array so name, etc. is first
            $items = $archives[$archive_key]['items'];
            unset($archives[$archive_key]['items']);
            $archives[$archive_key]['items'] = $items;
        }
    }
    // Specific Archive
    if ($specific_archive) {
        $archives = isset($archives[$specific_archive]) ? $archives[$specific_archive] : array();
    }
    // Make filterable
    $archives = apply_filters('ctfw_content_type_archives', $archives, $args);
    $archives = apply_filters('ctfw_content_type_archives-' . $content_type, $archives, $args);
    return $archives;
}
/**
 * Events month archive URL
 *
 * Theme can filter ctfw_content_types to specify event month archive URL format.
 * This makes replacements and returns working URL.
 *
 * For example, a theme may have a monthly calendar page template supporting months via query string.
 * This URL helps the framework know what URL to use, such as in ctfw_content_type_archives(), which
 * may be used to create archives nav, page template, widget, etc.
 *
 * @since 1.7.1
 * @param string $year_month Month as YYYY-MM (e.g. 2015-01 for January, 2015)
 * @return string URL to events month archive for the theme
 */
function ctfw_events_month_archive_url($year_month)
{
    $url = '';
    // Get URL format filered in by theme via ctfw_content_types
    $url_format = ctfw_content_type_data('event', 'month_archive_url_format');
    // Is URL provided and valid?
    // It may not be valid if, for example, page having a certain page template not yet setup
    if (ctfw_is_url($url_format)) {
        // valid URL (e.g. page for a page template exists)
        // Date
        $ts = strtotime($year_month);
        $year = date_i18n('Y', $ts);
        // e.g.  2015
        $month = date_i18n('n', $ts);
        // e.g. 1
        $month_padded = date_i18n('m', $ts);
        // e.g. 01
        // Make replacements
        $url = $url_format;
        $url = str_replace('{year}', $year, $url);
        $url = str_replace('{month}', $month, $url);
        $url = str_replace('{month_padded}', $month_padded, $url);
    }
    // Return filtered
    return apply_filters('ctfw_month_archive_url', $url, $year_month);
}