<?php

defined('ABSPATH') || exit();

// enable auto update
add_filter('allow_major_auto_core_updates', '__return_true');
add_filter('allow_minor_auto_core_updates', '__return_true');
add_filter('auto_update_theme', '__return_true');
add_filter('auto_update_plugin', 'cbsonline_exclude_plugins_from_auto_update', 10, 2);
function cbsonline_exclude_plugins_from_auto_update($update, $item)
{
    return !in_array($item->slug, ['bogo']);
}

// remove parent theme defined filters and actions
add_action('after_setup_theme', 'cbsonline_disable_parent_defines');
function cbsonline_disable_parent_defines()
{
    // remove web fonts
    remove_action('wp_enqueue_scripts', 'biz_vektor_addWebFonts');
    // remove buggy biz_vector script
    remove_action('wp_head', 'biz_vektor_addJScripts');
    // remove pingback css
    remove_action('wp_enqueue_scripts', 'biz_vektor_addPingback');
}

// disable emoji
remove_action('wp_head', 'print_emoji_detection_script', 7);
remove_action('admin_print_scripts', 'print_emoji_detection_script');
remove_action('wp_print_styles', 'print_emoji_styles');
remove_action('admin_print_styles', 'print_emoji_styles');
remove_filter('the_content_feed', 'wp_staticize_emoji');
remove_filter('comment_text_rss', 'wp_staticize_emoji');
remove_filter('wp_mail', 'wp_staticize_emoji_for_email');
// add_filter('tiny_mce_plugins', 'disable_emojis_tinymce');

// remove unnecessary head tags
// - rest
remove_action('wp_head', 'rest_output_link_wp_head');
// - embed
remove_action('wp_head', 'wp_oembed_add_discovery_links');
remove_action('wp_head', 'wp_oembed_add_host_js');
// - feed
remove_action('wp_head', 'feed_links', 2);
remove_action('wp_head', 'feed_links_extra', 3);
// - rsd
remove_action('wp_head', 'rsd_link');
// - windows live writer
remove_action('wp_head', 'wlwmanifest_link');
// - generator
remove_action('wp_head', 'wp_generator');
// - shortlink
remove_action('wp_head', 'wp_shortlink_wp_head');
// - rel link
remove_action('wp_head', 'index_rel_link');
remove_action('wp_head', 'parent_post_rel_link', 10);
remove_action('wp_head', 'start_post_rel_link', 10);
remove_action('wp_head', 'adjacent_posts_rel_link_wp_head');

// disable automatically appending srcset attribute in img tag
add_filter('wp_calculate_image_srcset_meta', '__return_null');

// disable DNS prefetch
add_filter('wp_resource_hints', 'cbsonline_remove_dns_prefetch', 10, 2);
function cbsonline_remove_dns_prefetch($hints, $relation_type)
{
    if ('dns-prefetch' === $relation_type) {
        return array_diff(wp_dependencies_unique_hosts(), $hints);
    }

    return $hints;
}

// add styles
add_action('wp_enqueue_scripts', 'cbsonline_add_styles');
function cbsonline_add_styles()
{
    wp_enqueue_style('parent-style', get_template_directory_uri().'/style.css');
    wp_enqueue_style('dashicons');
}

// add scripts
add_action('wp_head', 'cbsonline_add_scripts');
function cbsonline_add_scripts()
{
    wp_register_script('biz-vektor-fix-min-js', get_stylesheet_directory_uri().'/js/biz-vektor-fix-min.js', ['jquery'], '20201029');
    wp_enqueue_script('biz-vektor-fix-min-js');
}

// add widgets
function cbsonline_widgets_init()
{
    register_sidebar([
        'name' => 'ヘッダー ウィジェット',
        'id' => 'header-widget-area',
        'before_widget' => '<div class="header-widget-area">',
        'after_widget' => '</div>',
        'before_title' => '<h2 class="rounded">',
        'after_title' => '</h2>',
    ]);

    register_sidebar([
        'name' => 'トップバナー ウィジェット',
        'id' => 'topbnr-widget-area',
        'before_widget' => '<div class="topbnr-widget-area clearfix"><div class="topbnr-widget-area-inner clearfix">',
        'after_widget' => '</div></div>',
        'before_title' => '<h2 class="rounded">',
        'after_title' => '</h2>',
    ]);

    register_sidebar([
        'name' => 'トップイメージ ウィジェット',
        'id' => 'topimg-widget-area',
        'before_widget' => '<div class="topimg-widget-area clearfix">',
        'after_widget' => '</div>',
        'before_title' => '<h2 class="rounded">',
        'after_title' => '</h2>',
    ]);
}
add_action('widgets_init', 'cbsonline_widgets_init');

// tweak bogo plugin
// - disable flags
add_filter('bogo_use_flags', 'cbsonline_bogo_use_flags_false');
function cbsonline_bogo_use_flags_false()
{
    return false;
}
// - remove ' (United States)' strings from en_US language
add_filter('bogo_language_switcher', 'cbsonline_replace_bogo_text');
function cbsonline_replace_bogo_text($output)
{
    return str_replace(' (United States)', '', $output);
}

// add short code
// - topbox : http://www.webopixel.net/wordpress/53.html
function cbsonline_shortcode_TopBox($atts, $content = null)
{
    $content = do_shortcode(shortcode_unautop($content));
    extract(shortcode_atts(['class' => 'default'], $atts));

    return '<div class="topbox">'.$content.'</div>';
}
add_shortcode('topbox', 'cbsonline_shortcode_TopBox');

// allow additional image file upload
add_filter('upload_mimes', 'cbsonline_allow_additional_image_upload');
function cbsonline_allow_additional_image_upload($mimes)
{
    $mimes['ai'] = 'image/x-illustrator';
    $mimes['ico'] = 'image/vnd.microsoft.icon';

    return $mimes;
}

// force override Archive widget arguments
add_filter('widget_archives_args', 'cbsonline_widget_archives_args');
function cbsonline_widget_archives_args($args)
{
    // yearly
    $args['type'] = 'yearly';
    // maximum number of items : 10 years
    $args['limit'] = 10;

    return $args;
}

// support category based archives
add_filter('getarchives_join', 'cbsonline_category_getarchives_join', 10, 2);
function cbsonline_category_getarchives_join($join, $r)
{
    global $wpdb;
    if (is_category()) {
        $cat = intval(get_query_var('cat'));
        if ($cat > 0) {
            return
              " LEFT JOIN $wpdb->term_relationships as r ON $wpdb->posts.ID = r.object_ID
                LEFT JOIN $wpdb->term_taxonomy as t ON r.term_taxonomy_id = t.term_taxonomy_id
                LEFT JOIN $wpdb->terms as terms ON t.term_id = terms.term_id";
        }
    }
}
add_filter('getarchives_where', 'cbsonline_category_getarchives_where', 10, 2);
function cbsonline_category_getarchives_where($where, $r)
{
    if (is_category()) {
        $cat = intval(get_query_var('cat'));
        if ($cat > 0) {
            return $where." AND t.taxonomy = 'category' AND terms.term_id = $cat";
        }
    }
}
add_filter('year_link', 'cbsonline_category_year_link', 10, 2);
function cbsonline_category_year_link($url, $year)
{
    global $wp_rewrite;
    if (is_category()) {
        $cat = intval(get_query_var('cat'));
        if ($cat > 0) {
            $url .= '?cat='.get_query_var('cat');
        }
    }

    return $url;
}

// support tag cloud for static pages
add_action('init', 'cbsonline_add_tag_to_page');
function cbsonline_add_tag_to_page()
{
    register_taxonomy_for_object_type('post_tag', 'page');
}
add_action('pre_get_posts', 'cbsonline_add_page_to_tag_archive');
function cbsonline_add_page_to_tag_archive($obj)
{
    if (is_tag()) {
        $obj->query_vars['post_type'] = ['post', 'page'];
    }
}

// override date_format option
add_filter('option_date_format', 'cbsonline_date_format');
function cbsonline_date_format($format)
{
    $lang = get_query_var('lang', '');
    switch ($lang) {
    case 'ja':
       return 'Y年n月j日';
    case 'en_US':
       return 'D, d M Y';
    }

    return $format;
}

// for wpforo
// - helper funcitons for template customization - used by wpforo/layouts/2/*.php
function cbsonline_wpforo_get_topic_fields_list()
{
    static $ret = [];
    if (!empty($ret)) {
        return $ret;
    }
    $fields = WPF()->post->get_topic_fields_list();
    foreach ($fields as $name) {
        $ret[$name] = WPF()->post->get_field($name);
    }

    return $ret;
}
function cbsonline_wpforo_get_topic_custom_fields($topic_id)
{
    $fields = cbsonline_wpforo_get_topic_fields_list();
    $postmetas = WPF()->postmeta->get_postmeta($topic_id, '', true);
    $ret = [];
    foreach ($fields as $name => $field) {
        if ($postmeta = wpfval($postmetas, $name)) {
            if (!(int) wpfval($fields[$name], 'isDefault')) {
                $field['value'] = $postmeta;
                $field = WPF()->form->prepare_values(WPF()->form->esc_field($field));
                $ret[$name] = wpfval($field, 'value');
            }
        }
    }

    return $ret;
}
// - sort topics by seminar date
add_filter('wpforo_after_init_current_object', 'cbsonline_wpforo_after_init_current_object', 10, 2);
function cbsonline_wpforo_after_init_current_object($current_object, $wpf_url_parse)
{
    if (wpfval($current_object, 'forum_slug')) {
        $topic = wpfval($current_object, 'topic_slug') ? WPF()->topic->get_topic(['slug' => $current_object['topic_slug']], false) : false;
        $args = (empty($topic) ? ['slug' => $current_object['forum_slug']] : $topic['forumid']);
        if ($forum = WPF()->forum->get_forum($args)) {
            if ('topic' === $current_object['template']) {
                $args = [
                    'offset' => ($current_object['paged'] - 1) * $current_object['items_per_page'],
                    'row_count' => $current_object['items_per_page'],
                    'forumid' => $current_object['forumid'],
                    'orderby' => 'type, metavalue, modified',
                    'order' => 'DESC',
                    'join' => ' INNER JOIN `'.WPF()->tables->postmeta.'` AS `m1` ON `m1`.`postid`=`'.WPF()->tables->topics.'`.`first_postid` AND `m1`.`metakey`=\'seminar_date\'',
                ];
                $current_object['topics'] = cbsonline_wpforo_topic_get_topics($args, $current_object['items_count']);
            }
        } else {
            $current_object['is_404'] = true;
        }
    }

    return $current_object;
}
function cbsonline_wpforo_topic_get_topics($args = [], &$items_count = 0, $count = true)
{
    $cache = WPF()->cache->on('object_cashe');

    $default = [
        'include' => [],     // array( 2, 10, 25 )
        'exclude' => [],     // array( 2, 10, 25 )
        'forumids' => [],
        'forumid' => null,
        'userid' => null,    // user id in DB
        'type' => null,      // 0, 1, etc . . .
        'solved' => null,
        'closed' => null,
        'status' => null,    // 0, 1, etc . . .
        'private' => null,   // 0, 1, etc . . .''
        'pollid' => null,
        'orderby' => 'type, topicid', // type, topicid, modified, created
        'order' => 'DESC',   // ASC DESC
        'offset' => null,    // this use when you give row_count
        'row_count' => null, // 4 or 1 ...
        'permgroup' => null, // Checks permissions based on attribute value not on current user usergroup
        'read' => null,      // true / false
        'where' => null,
        'join' => null,      // join clause
    ];

    $args = wpforo_parse_args($args, $default);

    if (is_array($args) && !empty($args)) {
        extract($args, EXTR_OVERWRITE);

        if (0 === $row_count) {
            return [];
        }

        $include = wpforo_parse_args($include);
        $exclude = wpforo_parse_args($exclude);
        $forumids = wpforo_parse_args($forumids);

        $guest = [];
        $wheres = [];

        if (!is_null($read)) {
            $last_read_postid = WPF()->log->get_all_read('post');
            if ($read) {
                if ($last_read_postid) {
                    $wheres[] = '`last_post` <= '.intval($last_read_postid);
                }
                $include_read = WPF()->log->get_read();
                $include = array_merge($include, $include_read);
            } else {
                if ($last_read_postid) {
                    $wheres[] = '`last_post` > '.intval($last_read_postid);
                }
                $exclude_read = WPF()->log->get_read();
                $exclude = array_merge($exclude, $exclude_read);
            }
        }

        if (!empty($include)) {
            $wheres[] = '`topicid` IN('.implode(', ', array_map('intval', $include)).')';
        }
        if (!empty($exclude)) {
            $wheres[] = '`topicid` NOT IN('.implode(', ', array_map('intval', $exclude)).')';
        }
        if (!empty($forumids)) {
            $wheres[] = '`forumid` IN('.implode(', ', array_map('intval', $forumids)).')';
        }
        if (!is_null($forumid)) {
            $wheres[] = '`forumid` = '.intval($forumid);
        }
        if (!is_null($userid)) {
            $wheres[] = '`userid` = '.wpforo_bigintval($userid);
        }
        if (!is_null($solved)) {
            $wheres[] = '`solved` = '.intval($solved);
        }
        if (!is_null($closed)) {
            $wheres[] = '`closed` = '.intval($closed);
        }
        if (!is_null($type)) {
            $wheres[] = '`type` = '.intval($type);
        }
        if (!is_null($where)) {
            $wheres[] = $where;
        }

        if (!is_user_logged_in()) {
            $guest = WPF()->member->get_guest_cookies();
        }

        if (empty($forumids)) {
            if (isset($forumid) && !WPF()->perm->forum_can('vf', $forumid, $permgroup)) {
                return [];
            }
        }

        if (isset($forumid) && $forumid) {
            if (WPF()->perm->forum_can('vp', $forumid, $permgroup)) {
                if (!is_null($private)) {
                    $wheres[] = ' `private` = '.intval($private);
                }
            } elseif (isset(WPF()->current_userid) && WPF()->current_userid) {
                $wheres[] = ' ( `private` = 0 OR (`private` = 1 AND `userid` = '.intval(WPF()->current_userid).') )';
            } elseif (wpfval($guest, 'email')) {
                $wheres[] = " ( `private` = 0 OR (`private` = 1 AND `email` = '".sanitize_email($guest['email'])."') )";
            } else {
                $wheres[] = ' `private` = 0';
            }
        } else {
            if (!is_null($private)) {
                $wheres[] = ' `private` = '.intval($private);
            }
        }

        if (isset($forumid) && $forumid) {
            if (WPF()->perm->forum_can('au', $forumid, $permgroup)) {
                if (!is_null($status)) {
                    $wheres[] = ' `status` = '.intval($status);
                }
            } elseif (isset(WPF()->current_userid) && WPF()->current_userid) {
                $wheres[] = ' ( `status` = 0 OR (`status` = 1 AND `userid` = '.intval(WPF()->current_userid).') )';
            } elseif (wpfval($guest, 'email')) {
                $wheres[] = " ( `status` = 0 OR (`status` = 1 AND `email` = '".sanitize_email($guest['email'])."') )";
            } else {
                $wheres[] = ' `status` = 0';
            }
        } else {
            if (!is_null($status)) {
                $wheres[] = ' `status` = '.intval($status);
            }
        }

        if (function_exists('WPF_POLL')) {
            if (!is_null($pollid)) {
                $wheres[] = ' `pollid` <> 0';
            }
        }

        $columns = ['topics', 'forumid', 'first_postid', 'userid', 'title', 'slug', 'created', 'modified', 'last_post', 'posts', 'votes', 'answers', 'views', 'meta_key', 'meta_desc', 'type', 'solved', 'closed', 'has_attach', 'private', 'status', 'name', 'email', 'prefix', 'tags'];
        $sql = 'SELECT `'.WPF()->tables->topics.'`.* FROM `'.WPF()->tables->topics.'`';
        if (!is_null($join)) {
            $sql .= $join;
        }
        if (!empty($wheres)) {
            $sql .= ' WHERE '.implode(' AND ', $wheres);
        }
        if ($count) {
            $item_count_sql = preg_replace('#SELECT.+?FROM#isu', 'SELECT count(*) FROM', $sql);
            if ($item_count_sql) {
                if (!is_null($join)) {
                    foreach ($columns as $column) {
                        $item_count_sql = preg_replace('/([( ])`'.$column.'`/', '\1`'.WPF()->tables->topics.'`.`'.$column.'`', $item_count_sql);
                    }
                }
                $items_count = WPF()->db->get_var($item_count_sql);
            }
        }

        $sql .= ' ORDER BY '.str_replace(',', ' '.esc_sql($order).',', esc_sql($orderby)).' '.esc_sql($order);

        if (!is_null($row_count)) {
            if (!is_null($offset)) {
                $sql .= esc_sql(" LIMIT $offset,$row_count");
            } else {
                $sql .= esc_sql(" LIMIT $row_count");
            }
        }

        if (!is_null($join)) {
            foreach ($columns as $column) {
                $sql = preg_replace('/([( ])`'.$column.'`/', '\1`'.WPF()->tables->topics.'`.`'.$column.'`', $sql);
            }
        }

        if ($cache) {
            $object_key = md5($sql.WPF()->current_user_groupid);
            $object_cache = WPF()->cache->get($object_key);
            if (!empty($object_cache)) {
                if (!empty($object_cache['items'])) {
                    $access_filter = apply_filters('wpforo_topic_access_filter_cache', true);
                    if ($access_filter) {
                        return WPF()->topic->access_filter($object_cache['items'], $permgroup);
                    } else {
                        return $object_cache['items'];
                    }
                }
            }
        }

        $topics = WPF()->db->get_results($sql, ARRAY_A);
        $topics = apply_filters('wpforo_get_topics', $topics);

        if ($cache && isset($object_key) && !empty($topics)) {
            wpForoTopic::$cache['topics'][$object_key]['items'] = $topics;
            wpForoTopic::$cache['topics'][$object_key]['items_count'] = $items_count;
        }

        if (!empty($forumids) || !$forumid) {
            $topics = WPF()->topic->access_filter($topics, $permgroup);
        }

        return $topics;
    }
}
// - set hostname if annoymous user add topic data
add_filter('wpforo_add_topic_data_filter', 'cbsonline_wpforo_add_topic_data_filter');
function cbsonline_wpforo_add_topic_data_filter($args)
{
    if ($args['name'] == wpforo_phrase('Anonymous', false)) {
        $host = gethostbyaddr($_SERVER['REMOTE_ADDR'] ?? '127.0.0.1');
        if (false !== $host) {
            $args['name'] = $host;
        }
    }

    return $args;
}