<?php if ( !defined( 'ABSPATH' ) ) exit;//PHPの宣言と直接アクセスの拒否

/*** カスタムフィールドの登録 ***/
/* Block Bindings APIで呼び出せるよう、タイトルと説明のみを登録 */
/* Block Bindings APIで呼び出す可能性のある項目は登録が必要なのを忘れないこと */
function haup_register_access_count_fields(){
	register_meta(
		'post',
		'post_views_count',
		array(
			'show_in_rest' => true,
			'single'       => true,
			'type'         => 'string',
			'default'      => '',
		)
	);
}
add_action('init','haup_register_access_count_fields');

/***** ログインユーザー以外のアクセスごとにカスタムフィールドへ数字を足す *****/
/*** 関数 ***/
/* 投稿 */
function haup_set_post_views($postID) {
	$count_key = 'post_views_count';
	$count = get_post_meta($postID, $count_key, true);

	if($count==''){
		$count = 0;
		delete_post_meta($postID, $count_key);
		add_post_meta($postID, $count_key, '0');
	}else{
		$count++;
		update_post_meta($postID, $count_key, $count);
	}
}

/* 固定ページ */
function haup_set_page_views($pageID) {
	$count_key = 'post_views_count';
	$count = get_post_meta($pageID, $count_key, true);

	if($count==''){
		$count = 0;
		delete_post_meta($pageID, $count_key);
		add_post_meta($pageID, $count_key, '0');
	}else{
		$count++;
		update_post_meta($pageID, $count_key, $count);
	}
}

/*** ログインしていないユーザーでカウンターを発火 ***/
function haup_views_count_sc(){
//固定ページ
if(is_user_logged_in()){
	$view_counter = '';
}elseif(is_page() && !haup_is_bot()){
	$view_counter = haup_set_page_views(get_the_ID());
}else{
	$view_counter = '';
}

//投稿
if(is_user_logged_in()){
	$view_counter = '';
}elseif(!is_page() && !haup_is_bot()){
	$view_counter = haup_set_post_views(get_the_ID());
}else{
	$view_counter = '';
}

	return $view_counter;
}

add_action('wp_footer','haup_views_count_sc');

/***** クローラーのアクセス判別 *****/
function haup_is_bot() {
	if (!isset($_SERVER['HTTP_USER_AGENT']) || empty(trim($_SERVER['HTTP_USER_AGENT']))) {
		return true; // UAが空の場合はボットとみなす
	}

	$ua = sanitize_text_field(wp_unslash($_SERVER['HTTP_USER_AGENT']));

	// 特定の文字列が含まれているか
	$bot_keywords = array(
		//1-9 & other
			'360Spider',
			'7Siters',
			'80legs.com/webcrawler',
			'(BOT for JCE)',

		//a
			'A6-Indexer',
			'Abonti',
			'acebookexternalhit',
			'AdlesseBot',
			'admantx',
			'admantx-adform',
			'ADmantX Platform',
			'Adsbot',
			'adscanner',
			'AHC/2.1',
			'AhrefsBot',
			'Apache-HttpClient/5',
			'app.hypefactors.com',
			'Applebot',
			'archive.org_bot',
			'Astute SRM',
			'AwarioSmartBot',
			'axios',
			'axios/',
			'A PHP script',

		//b
			'BacklinkCrawler',
			'Baidu',
			'Baidu ( catchall )',
			'Baiduspider',
			'Barkrowler',
			'BazQuxBot',
			'BehloolBot',
			'bingbot',
			'BingPreview',
			'bitlybot',
			'Blackboard',
			'BLEXBot',
			'BoardReader',
			'BTWebClient',
			'Buck/2.2',
			'Butterfly',
			'bingbot',
			'blog',
			'bidswitchbot',

		//c
			'CCBot',
			'CensysInspect',
			'ChatGPT-User',
			'ClaudeBot',
			'Cliqzbot',
			'commoncrawl',
			'CommonCrawler',
			'CommonCrawler Node',
			'cs.daum.net',
			'curl/7',
			'crawl',
			'CFNetwork',
			'Curl',

		//d
			'Datadog/Synthetic',
			'dlvr.it',
			'DotBot',
			'domainappender',
			'DomainCrawler',
			'Domains Project',
			'DomainStatsBot',
			'DuckDuckBot',
			'DuckDuckGo',
			'DuckDuckGo-Favicons-Bot',
			'Dalvik',
			'Discordbot',

		//e
			'eCairn-Grabber', 
			'Exabot',
			'Ezooms',
			'empty user agent string',

		//f
			'facebookexternalhit',
			'feedbot',
			'Feedfetcher-Google',
			'Feedly',
			'FemtosearchBot',
			'fetcher',
			'Firefox version 10 and lower - various robots',
			'FlipboardProxy',
			'fetcher',
			'feed',

		//g
			'GarlikCrawler',
			'genieo',
			'getstream.io/winds',
			'GigablastOpenSource/1.0',
			'Gluten Free Crawler',
			'glutenfreepleasure.com',
			'Go-http-client',
			'Go-http-client/',
			'Googlebot',
			'Google-Extended',
			'Googlebot-Image',
			'Googlebot-Video',
			'GrapeshotCrawler',
			'grokkit-crawler',
			'GroupHigh',
			'GPTBot',
			'GuzzleHttp',

		//h
			'HeadlessChrome',
			'HTTP_Request2',

		//i
			'ia_archiver',
			'ibwww-perl',
			'InAGist',
			'istellabot',

		//j
			'Java/1.8',
			'Java ( catchall )',
			'Jetslide',

		//k
			'KatBot',
			'Kraken',

		//l
			'libwww-perl',
			 'Lighthouse',
			'Linguee Bot',
			'Linguee Bot',
			'linkdex',
			'linkdexbot',
			'linkfluence.com',
			'ltx71',
			'LivelapBot',
			'link',

		//m
			'Mail.RU',
			'Mail.RU_Bot',
			'majestic12',
			'magpie-crawler',
			'MaxPointCrawler',
			'Mediapartners-Google',
			'Mediatoolkitbot',
			'mediawords bot',
			'MegaIndex',
			'MegaIndex.ru',  
			'metadataparser',
			'MetaJobBot',
			'metauri.com',
			'MetaURI',
			'merlinkbot',
			'MJ12bot',
			'Microsoft Office',
			'mon.itor.us',
			'monitoring-plugins', 
			'Moreover',
			'msnbot',

		//n
			'Nmap',
			'NetcraftSurveyAgent',
			'netEstate NE Crawler',
			'NetNewsWire',
			'NetSeer crawler',
			'newsblur',
			'newspaper', 
			'Niki-Bot',
			'NING',
			'node-fetch',
			'Nutch',
			'Nuzzel',
			'nbot',

		//o
			'oBot',
			'okhttp',
			'omgili',  
			'OnalyticaBot',

		//p
			'PaperLiBot',
			'Pcore-HTTP',
			'perl',
			'PercolateCrawler',
			'PerplexityBot',
			'PHP-Curl-Class',
			'Pingdom',
			'Pinterest',
			'Pinterestbot',
			'picsearch',
			'PocketParser',
			'PrintfulBot',
			'profound',
			'proximic',
			'PulseCrawler',
			'python-requests',
			'Python-urllib',

		//q
			'Qwantify',
			'QuerySeekerSpider',

		//r
			'R6_CommentReader',
			'R6_FeedFetcher',
			'Re-Animator Bot',
			'rogerbot',
			'rogerbot-crawler',
			'robot',
			'Ruby',

		//s
			'scalaj-http',
			'schmorp.de',
			'ScooperBot',
			'Scrapy',
			'searchmetrics',
			'SearchmetricsBot',
			'Seekport Crawler',
			'Selfoss',
			'SemanticScholarBot',
			'semantic-visions.com',
			'semrush.com',
			'SemrushBot',
			'SEOkicks',
			'SerendeputyBot',
			'serpstatbot',
			'SeznamBot/3.2',
			'ShowyouBot',
			'SISTRIX Crawler',
			'SiteCheck',
			'Sleuth',
			'SMXCrawler',
			'Sogou web spider',
			'spbot',
			'spider',
			'SpiderLing',
			'Spinn3r',
			'StormCrawler',
			'sysomos.com',
			'spider',
			'SeznamBot',
			'serendeputy',
			'Slackbot-LinkExpanding',
			'seek',
			'survey',
			'SurdotlyBot',
			'Screaming Frog SEO Spider',

		//t
			'TencentTraveler',
			'terrykyleseoagency.com',
			'The Knowledge AI',
			'Tiny Tiny RSS',
			'Traackr.com',
			'trendiction',
			'trendictionbot',
			'TrendsmapResolver',
			'TweetedTimes Bot',
			'Twitterbot',
			'TwitterFeed',
			'TweetmemeBot',
			'TelegramBot',

		//u
			'ubermetrics',
			'Unknown robot identified by bot',
			'UnwindFetchor',
			'updown_tester',
			'UptimeRobot',
			'urlresolver',
			'Unknown',

		//v
			'VegeBot',
			'VelenPublicWebCrawler/1.0',
			'Velen',

		//w
			'webdatastats.com',
			'Wget/',
			'Wget',
			'Winds: Open Source RSS & Podcast',
			'WordPress.com mShots',
			'woriobot',

		//x
			'XoviBot',

		//y
			'Y!J-BRW',
			'Yahoo! Slurp',
			'YaK/1.0',
			'Yandex',
			'YandexBot',
			'YisouSpider',
			'Yandex ( catchall )',
			'yak-linkfluence',
			'YandexImages',

		//z
			'zgrab', 
			'ZoominfoBot',
			'Zombiebot'

	);

	foreach ($bot_keywords as $bot) {
		if (stripos($ua, $bot) !== false) {
			return true;
		}
	}

	// 長さが極端に短い（例: 10文字未満）UAをボットとする場合
	//if (strlen($ua) < 10) {
		//return true;
	//}

	return false;
}