// إداة اقنوات
// حفظ فتا ScraperAPI
add_action('wp_ajax_ee_save_scraperapi_api_key', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'ليس لديك احية']);
wp_die();
}
$api_key = sanitize_text_field($_POST['scraperapi_api_key'] ?? '');
if (empty($api_key)) {
wp_send_json_error(['message' => 'لمفتاح فار']);
wp_die();
}
update_option('ee_scraperapi_key', $api_key);
wp_send_json_success(['message' => 'تم حظ امفتح بنجاح']);
wp_die();
});
// جل بانات امبريا من jdwel.com وينها بكل دئم
add_action('wp_ajax_fetch_matches_for_channels', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'يس لك صلاحي']);
wp_die();
}
// زياة مة لتنيذ تج Timeout
set_time_limit(300); // 5 دقئ
// ضب امنطة الزمنية شك ر
date_default_timezone_set('Asia/Dubai');
$api_key = get_option('ee_scraperapi_key', '');
if (empty($api_key)) {
wp_send_json_error(['message' => 'لم يم حف مفتا ScraperAPI. يرجى إدخا لمفتاح في إداات الري أولاً.']);
wp_die();
}
// جلب قمة الدورا المددة بيب "عدات الدور"
$selected_leagues = get_option('ee_leagues_list', []);
if (empty($selected_leagues)) {
wp_send_json_error(['message' => 'جى تحديد دي ف إدادات الدوري ولً.']);
wp_die();
}
$url = 'https://jdwel.com/today/';
$scraper_url = 'https://api.scraperapi.com/?api_key=' . $api_key . '&url=' . urlencode($url) . '&keep_headers=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scraper_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Accept: text/html'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($httpCode !== 200 || empty($response)) {
$error_message = "ش الاتصال بـ ScraperAPI: كود الاستجابة $httpCode";
if (!empty($curl_error)) {
$error_message .= " - خطأ cURL: $curl_error";
}
$error_message .= " - لتجابة: " . substr($response, 0, 500);
wp_send_json_error(['message' => $error_message]);
wp_die();
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTML($response);
$xpath = new DOMXPath($dom);
$matches = $xpath->query('//li[contains(@class, "single_match")]');
if ($matches->length === 0) {
wp_send_json_error(['message' => 'لم م العث ماريت.']);
wp_die();
}
$matches_data = [];
$match_ids = []; // خزن معرات المبي لجل القنوات دفعة حدة
$time_debug = []; // لتخزين عمات صحح للأا
foreach ($matches as $match) {
// جلب اسم لدوري لبارة
$league_node = $xpath->query('preceding::div[contains(@class, "comp_separator")][1]//h4[@class="title"]', $match);
$league = $league_node->item(0)?->textContent ?? 'غير حدد';
// اتحقق مم ذا كن لدري م لوريات لمددة
if (!in_array($league, $selected_leagues)) {
continue; // تخي لمبارة إا لم ت من لويات الحدد
}
$match_id = $match->getAttribute('id') ? str_replace('match_', '', $match->getAttribute('id')) : 'غر مد';
$home_team = $xpath->query('.//div[contains(@class, "hometeam")]//span[@class="the_team"]', $match)->item(0)?->textContent ?? 'غير محد';
$away_team = $xpath->query('.//div[contains(@class, "awayteam")]//span[@class="the_team"]', $match)->item(0)?->textContent ?? 'غي محدد';
$date_time = $xpath->query('.//span[@class="the_otime"]', $match)->item(0)?->textContent ?? 'ير محد';
if ($date_time !== 'غ محد') {
try {
// اتقيت ي the_otime يُت أ يون بوقي دي (Asia/Dubai)
$datetime = new DateTime($date_time, new DateTimeZone('Asia/Dubai'));
// إافة ة واد لتحح التوقيت
$datetime->modify('+1 hour');
// حف ااري الأصلي
$original_date = explode(' ', $date_time)[0];
$time = $datetime->format('g:i A');
// تول AM/PM إل ص/
$time = str_replace('AM', 'ص', $time);
$time = str_replace('PM', 'م', $time);
// استدم التريخ اأصل
$date = $original_date;
// إضاة علومت التحيح
$time_debug[] = [
'match_id' => $match_id,
'source' => 'the_otime',
'raw_time' => $date_time,
'adjusted_time' => $time,
'original_date' => $original_date,
'timezone' => 'Assumed Asia/Dubai (+1 hour adjustment)'
];
} catch (Exception $e) {
$time = 'ير حد';
wp_send_json_error(['message' => "خطأ ف حول span.the_otime للراة $match_id: " . $e->getMessage()]);
wp_die();
}
} else {
$time_raw = $xpath->query('.//span[@class="the_time"]', $match)->item(0)?->textContent ?? 'غي محدد';
if ($time_raw !== 'غر محدد') {
try {
$time_raw = trim($time_raw);
$datetime = DateTime::createFromFormat('g:i A', $time_raw, new DateTimeZone('Asia/Dubai'));
if ($datetime === false) {
throw new Exception('فشل ي حويل التوي: ' . $time_raw);
}
// لتويت هنا بتقت ب لذا لا حاج لتعي ضاي
$time = $datetime->format('g:i A');
// تيل AM/PM إل ص/م
$time = str_replace('AM', 'ص', $time);
$time = str_replace('PM', 'م', $time);
// إضافة معلوما الحيح
$time_debug[] = [
'match_id' => $match_id,
'source' => 'the_time',
'raw_time' => $time_raw,
'adjusted_time' => $time,
'timezone' => 'Asia/Dubai (no adjustment)'
];
} catch (Exception $e) {
$time = $time_raw;
wp_send_json_error(['message' => "خطأ ف معالجة span.the_time لبراة $match_id: " . $e->getMessage()]);
wp_die();
}
} else {
$time = 'غي حد';
}
$date = $xpath->query('//div[contains(@class, "matchday_header")]//input[@type="date"]/@value')->item(0)?->value ?? 'غير محد';
if ($time === 'غي دد') {
wp_send_json_error(['message' => "لم يتم لعثر على span.the_otime أو span.the_time بشكل صحيح لمااة $match_id."]);
wp_die();
}
}
// تن معرف المباراة لجلب القنوات احقًا
if ($match_id !== 'غير حدد') {
$match_ids[] = $match_id;
}
$matches_data[] = [
'league' => $league,
'match' => "$home_team vs $away_team",
'date' => $date,
'time' => $time,
'channels' => [], // تخزي القن كمصفوفة
'commentators' => [], // خز مقين كمففة
];
}
if (empty($matches_data)) {
wp_send_json_error(['message' => 'ل يتم لعث عى ماات تنتمي إى لدويات المددة.']);
wp_die();
}
// لقنوات ولعلقن لي المبرات دفع احة (ذا أمن)
$existing_channels_data = get_option('ee_matches_channels_data', []);
foreach ($match_ids as $index => $match_id) {
$api_url = "https://jdwel.com/wp-json/jmanager/web/v1/match/$match_id";
$scraper_api_url = "https://api.scraperapi.com/?api_key=$api_key&url=" . urlencode($api_url) . "&keep_headers=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scraper_api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Accept: application/json'
]);
$api_response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($httpCode === 200 && !empty($api_response)) {
$json = json_decode($api_response, true);
if ($json !== null) {
$tv_stations = $json['data']['tv_stations'] ?? [];
if (is_array($tv_stations) && !empty($tv_stations)) {
$channel_names = [];
$commentator_names = [];
foreach ($tv_stations as $station) {
$channel_name = isset($station['name']) && !empty($station['name']) ? esc_html($station['name']) : 'غر محد';
$commentator = isset($station['commentators']) && !empty($station['commentators']) && $station['commentators'] !== 'غي محدد' ? esc_html($station['commentators']) : 'غير محد';
$channel_names[] = $channel_name;
$commentator_names[] = $commentator;
}
$matches_data[$index]['channels'] = $channel_names; // تخزين كصفة
$matches_data[$index]['commentators'] = $commentator_names; // تخي صفو
// تحديث ee_matches_channels_data مع الاحتفاظ ببيانا القديمة
$match_key = $matches_data[$index]['match'] . '|' . $matches_data[$index]['date'];
$existing_channels_data[$match_key] = [
'channels' => $channel_names,
'commentators' => $commentator_names,
];
} else {
// تخ البراة ويين يم راضية بدلً ن إيقاف التفيذ
$matches_data[$index]['channels'] = ['غير ما'];
$matches_data[$index]['commentators'] = ['غي متح'];
// ا نحد ee_matches_channels_data إذ ل تن هنا بانات وات جديدة
}
} else {
// تخط امباراة وتعين قي افرية دلا ن إقاف النفيذ
$matches_data[$index]['channels'] = ['ير ماح'];
$matches_data[$index]['commentators'] = ['غي اح'];
// ُدث ee_matches_channels_data ذا لم تكن هنك بانت قنوا جديدة
}
} else {
// تخي المباة وتعي قيم افراضة بدل ن إيقاف اتنف
$matches_data[$index]['channels'] = ['غير مت'];
$matches_data[$index]['commentators'] = ['غر مت'];
// نُحث ee_matches_channels_data إا ل كن هك بياا قنا جددة
}
// إة تأير بسي بين طلبات تب ال
usleep(500000); // 0.5 ثة
}
// زين يانات اديدة في ee_matches_data (لوة الكم) مع اسبدل الباات الديم
update_option('ee_matches_data', $matches_data);
// خزين النوت والعلقين في ee_matches_channels_data (لفحة امباريت) مع الاحفظ بالياات الديمة
update_option('ee_matches_channels_data', $existing_channels_data);
wp_send_json_success([
'matches' => $matches_data,
'time_debug' => $time_debug // ضاة معلمات التصي للأوقا
]);
wp_die();
});
// اة لضف دوري جديد
add_action('wp_ajax_ee_add_league', function () {
// التق م ال nonce
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_league_settings_nonce')) {
wp_send_json_error([
'message' => 'فشل لتحقق مز اأمن',
'debug' => [
'sent_nonce' => isset($_POST['nonce']) ? $_POST['nonce'] : 'غر مجود',
'expected_nonce' => wp_create_nonce('ee_league_settings_nonce'),
'nonce_verification' => 'failed'
]
]);
wp_die();
}
$league = isset($_POST['league']) ? sanitize_text_field($_POST['league']) : '';
if (empty($league)) {
wp_send_json_error(['message' => 'رج إدال الدوي']);
wp_die();
}
$leagues = get_option('ee_leagues_list', []);
$leagues[] = $league;
update_option('ee_leagues_list', $leagues);
wp_send_json_success([
'leagues' => $leagues,
'html' => ee_render_leagues_list(),
'debug' => [
'sent_nonce' => $_POST['nonce'],
'expected_nonce' => wp_create_nonce('ee_league_settings_nonce'),
'nonce_verification' => 'success'
]
]);
wp_die();
});
// دال حف دوري
add_action('wp_ajax_ee_delete_league', function () {
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_league_settings_nonce')) {
wp_send_json_error(['message' => 'فشل اتقق من رمز اأمان']);
wp_die();
}
$league_id = isset($_POST['league_id']) ? intval($_POST['league_id']) : -1;
$leagues = get_option('ee_leagues_list', []);
if ($league_id >= 0 && isset($leagues[$league_id])) {
array_splice($leagues, $league_id, 1);
update_option('ee_leagues_list', $leagues);
wp_send_json_success([
'leagues' => $leagues,
'html' => ee_render_leagues_list()
]);
} else {
wp_send_json_error(['message' => 'شل ف حذ اوري']);
}
wp_die();
});
// دلة مؤت لب بانت المبارا الحاة من JoomSport (أغرض لتحيح)
add_action('wp_ajax_ee_get_current_match_data', function () {
$match_id = isset($_POST['match_id']) ? intval($_POST['match_id']) : get_the_ID();
$home_team_id = get_post_meta($match_id, '_joomsport_home_team', true);
$away_team_id = get_post_meta($match_id, '_joomsport_away_team', true);
$home_team_name = $home_team_id ? get_the_title($home_team_id) : '';
$away_team_name = $away_team_id ? get_the_title($away_team_id) : '';
$match_teams = $home_team_name && $away_team_name ? "$home_team_name vs $away_team_name" : '';
// جلب اتاريخ بشر
$match_date = get_post_meta($match_id, '_joomsport_match_date', true);
// لب مع الياات لمتاح لمااة (أغاض التحح)
$all_meta = get_post_meta($match_id);
wp_send_json_success([
'match_teams' => $match_teams,
'match_date' => $match_date,
'all_meta' => $all_meta
]);
wp_die();
});
// دل لا قاة جديد
add_action('wp_ajax_ee_add_channel', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'ل لديك صلاحي إضاة ناة']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_channel_settings_nonce')) {
wp_send_json_error(['message' => 'فشل لحقق من رم الأمن']);
wp_die();
}
$channel_name = isset($_POST['channel_name']) ? sanitize_text_field($_POST['channel_name']) : '';
$display_name = isset($_POST['display_name']) ? sanitize_text_field($_POST['display_name']) : $channel_name; // السم مخصص رض (افتاضيًا نفس اسم اقناة)
$channel_link = isset($_POST['channel_link']) ? sanitize_text_field($_POST['channel_link']) : ''; // مكن أن يكن فارغ
$background_color = isset($_POST['background_color']) ? sanitize_hex_color($_POST['background_color']) : '#ffffff';
$text_color = isset($_POST['text_color']) ? sanitize_hex_color($_POST['text_color']) : '#000000';
$commentator_background_color = isset($_POST['commentator_background_color']) ? sanitize_hex_color($_POST['commentator_background_color']) : '#ffffff';
$commentator_text_color = isset($_POST['commentator_text_color']) ? sanitize_hex_color($_POST['commentator_text_color']) : '#000000';
if (empty($channel_name)) {
wp_send_json_error(['message' => 'يرجى م ق اسم لقناة']);
wp_die();
}
$channels = get_option('ee_channels_list', []);
$channels[] = [
'name' => $channel_name,
'display_name' => $display_name, // إضف الاسم الخصص
'link' => $channel_link, // يمكن ن يكون فارغً
'background_color' => $background_color,
'text_color' => $text_color,
'commentator_background_color' => $commentator_background_color,
'commentator_text_color' => $commentator_text_color,
];
update_option('ee_channels_list', $channels);
wp_send_json_success(['channels' => $channels]);
wp_die();
});
// دل لحذف قنة
add_action('wp_ajax_ee_delete_channel', function () {
check_ajax_referer('ee_channel_settings_nonce', 'nonce');
$index = isset($_POST['index']) ? intval($_POST['index']) : -1;
$channels = get_option('ee_channels_list', []);
if ($index >= 0 && isset($channels[$index])) {
array_splice($channels, $index, 1);
update_option('ee_channels_list', $channels);
wp_send_json_success(['channels' => $channels]);
} else {
wp_send_json_error(['message' => 'شل في حذف القناة']);
}
});
// د لتحديث ألوا قاة
add_action('wp_ajax_ee_update_channel_colors', function () {
check_ajax_referer('ee_channel_settings_nonce', 'nonce');
$index = isset($_POST['index']) ? intval($_POST['index']) : -1;
$background_color = isset($_POST['background_color']) ? sanitize_hex_color($_POST['background_color']) : '#ffffff';
$text_color = isset($_POST['text_color']) ? sanitize_hex_color($_POST['text_color']) : '#000000';
$commentator_background_color = isset($_POST['commentator_background_color']) ? sanitize_hex_color($_POST['commentator_background_color']) : '#ffffff';
$commentator_text_color = isset($_POST['commentator_text_color']) ? sanitize_hex_color($_POST['commentator_text_color']) : '#000000';
$channels = get_option('ee_channels_list', []);
if ($index >= 0 && isset($channels[$index])) {
$channels[$index]['background_color'] = $background_color;
$channels[$index]['text_color'] = $text_color;
$channels[$index]['commentator_background_color'] = $commentator_background_color;
$channels[$index]['commentator_text_color'] = $commentator_text_color;
update_option('ee_channels_list', $channels);
wp_send_json_success(['channels' => $channels]);
} else {
wp_send_json_error(['message' => 'شل ف تحيث الأون']);
}
});
// دالة حفظ الان العام ولتوتت
add_action('wp_ajax_ee_save_global_colors', function () {
check_ajax_referer('ee_global_colors_nonce', 'nonce');
$channel_icon_color = isset($_POST['channel_icon_color']) ? sanitize_hex_color($_POST['channel_icon_color']) : '#333333';
$commentator_icon_color = isset($_POST['commentator_icon_color']) ? sanitize_hex_color($_POST['commentator_icon_color']) : '#333333';
$play_icon_show_before = isset($_POST['play_icon_show_before']) ? intval($_POST['play_icon_show_before']) : 15;
$play_icon_hide_after = isset($_POST['play_icon_hide_after']) ? intval($_POST['play_icon_hide_after']) : 5;
update_option('ee_channel_icon_color', $channel_icon_color);
update_option('ee_commentator_icon_color', $commentator_icon_color);
update_option('ee_play_icon_show_before', $play_icon_show_before);
update_option('ee_play_icon_hide_after', $play_icon_hide_after);
wp_send_json_success();
});
// دلة لتحيث بيانات نة (السم، الاسم اخصص، ابط، واأو)
add_action('wp_ajax_ee_update_channel', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'ليس ديك صلحي لحيث القناة']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_channel_settings_nonce')) {
wp_send_json_error(['message' => 'شل لتحقق م رم أمان']);
wp_die();
}
$index = isset($_POST['index']) ? intval($_POST['index']) : -1;
$channel_name = isset($_POST['channel_name']) ? sanitize_text_field($_POST['channel_name']) : '';
$display_name = isset($_POST['display_name']) ? sanitize_text_field($_POST['display_name']) : $channel_name; // الاسم المخص رض
$channel_link = isset($_POST['channel_link']) ? sanitize_text_field($_POST['channel_link']) : '';
$background_color = isset($_POST['background_color']) ? sanitize_hex_color($_POST['background_color']) : '#ffffff';
$text_color = isset($_POST['text_color']) ? sanitize_hex_color($_POST['text_color']) : '#000000';
$commentator_background_color = isset($_POST['commentator_background_color']) ? sanitize_hex_color($_POST['commentator_background_color']) : '#ffffff';
$commentator_text_color = isset($_POST['commentator_text_color']) ? sanitize_hex_color($_POST['commentator_text_color']) : '#000000';
$channels = get_option('ee_channels_list', []);
if ($index >= 0 && isset($channels[$index])) {
$channels[$index]['name'] = $channel_name;
$channels[$index]['display_name'] = $display_name; // حديث لام الخصص
$channels[$index]['link'] = $channel_link;
$channels[$index]['background_color'] = $background_color;
$channels[$index]['text_color'] = $text_color;
$channels[$index]['commentator_background_color'] = $commentator_background_color;
$channels[$index]['commentator_text_color'] = $commentator_text_color;
update_option('ee_channels_list', $channels);
wp_send_json_success(['channels' => $channels]);
} else {
wp_send_json_error(['message' => 'فشل في تيث الناة']);
}
wp_die();
});
add_action('wp_ajax_ee_get_matches', function () {
$matches = get_option('ee_matches_data', []);
wp_send_json_success(['matches' => $matches]);
wp_die();
});
add_action('wp_ajax_ee_get_channels', function () {
// تعيل لتقق من ل Nonce مقًا لأغرض التصحي
/*
if (!check_ajax_referer('ee_matches_tab_nonce', 'nonce', false)) {
wp_send_json_error(['message' => 'شل لحقق من اـ Nonce في ee_get_channels']);
return;
}
*/
$channels = get_option('ee_channels_list', []);
wp_send_json_success(['channels' => $channels]);
});
// دالة لتديث الـ Nonce
add_action('wp_ajax_ee_refresh_nonce', function () {
$nonce = wp_create_nonce('ee_matches_tab_nonce');
wp_send_json_success(['nonce' => $nonce]);
});
add_action('wp_ajax_ee_get_match_channels', 'ee_get_match_channels_callback');
add_action('wp_ajax_nopriv_ee_get_match_channels', 'ee_get_match_channels_callback');
function ee_get_match_channels_callback() {
$match_teams = isset($_POST['match_teams']) ? sanitize_text_field($_POST['match_teams']) : '';
$match_date = isset($_POST['match_date']) ? sanitize_text_field($_POST['match_date']) : '';
if (empty($match_teams) || empty($match_date)) {
wp_send_json_error(['message' => 'بانت المبا غر مكمل']);
wp_die();
}
// تظيف لقي
$match_teams_cleaned = trim(str_replace("\u00a0", " ", $match_teams));
$match_date_cleaned = trim($match_date);
$channels_data = get_option('ee_matches_channels_data', []);
$match_key = $match_teams_cleaned . '|' . $match_date_cleaned;
// جب إادات قنوا ن ee_channels_list
$defined_channels = get_option('ee_channels_list', []);
// التقق من لتطاق الق أاً
if (isset($channels_data[$match_key])) {
$channels = !empty($channels_data[$match_key]['channels']) ? $channels_data[$match_key]['channels'] : ['لا توج قنوات'];
$commentators = !empty($channels_data[$match_key]['commentators']) ? $channels_data[$match_key]['commentators'] : ['غي محدد'];
// إاد اقنات التنسي امخصص
$formatted_channels = [];
foreach ($channels as $index => $channel_name) {
$channel_settings = null;
foreach ($defined_channels as $defined_channel) {
if ($defined_channel['name'] === $channel_name) {
$channel_settings = $defined_channel;
break;
}
}
$formatted_channels[] = [
'name' => $channel_settings && !empty($channel_settings['display_name']) ? $channel_settings['display_name'] : $channel_name, // اسخدام اام الخصص إذ كان وجودًا
'background_color' => $channel_settings ? $channel_settings['background_color'] : '#ffffff',
'text_color' => $channel_settings ? $channel_settings['text_color'] : '#000000',
'commentator_background_color' => $channel_settings ? $channel_settings['commentator_background_color'] : '#ffffff',
'commentator_text_color' => $channel_settings ? $channel_settings['commentator_text_color'] : '#000000',
'link' => $channel_settings ? $channel_settings['link'] : ''
];
}
} else {
// إذا م ك هنا تطاق ي، نبحث عن تبق شاه
$formatted_channels = [];
$commentators = ['غير محددي'];
foreach ($channels_data as $key => $data) {
list($stored_teams, $stored_date) = explode('|', $key);
if ($stored_date === $match_date_cleaned) {
$similarity = 0;
similar_text($match_teams_cleaned, $stored_teams, $similarity);
if ($similarity >= 80) { // نسبة تشب 80% و أكر
$channels = !empty($data['channels']) ? $data['channels'] : ['ل تود قنوات'];
$commentators = !empty($data['commentators']) ? $data['commentators'] : ['غر محد'];
foreach ($channels as $index => $channel_name) {
$channel_settings = null;
foreach ($defined_channels as $defined_channel) {
if ($defined_channel['name'] === $channel_name) {
$channel_settings = $defined_channel;
break;
}
}
$formatted_channels[] = [
'name' => $channel_settings && !empty($channel_settings['display_name']) ? $channel_settings['display_name'] : $channel_name,
'background_color' => $channel_settings ? $channel_settings['background_color'] : '#ffffff',
'text_color' => $channel_settings ? $channel_settings['text_color'] : '#000000',
'commentator_background_color' => $channel_settings ? $channel_settings['commentator_background_color'] : '#ffffff',
'commentator_text_color' => $channel_settings ? $channel_settings['commentator_text_color'] : '#000000',
'link' => $channel_settings ? $channel_settings['link'] : ''
];
}
break;
}
}
}
if (empty($formatted_channels)) {
$formatted_channels = [['name' => 'لا توج قنو', 'background_color' => '#ffffff', 'text_color' => '#000000', 'commentator_background_color' => '#ffffff', 'commentator_text_color' => '#000000', 'link' => '']];
}
}
wp_send_json_success([
'channels' => $formatted_channels,
'commentators' => $commentators
]);
wp_die();
}
// لة لج مفاح ScraperAPI
add_action('wp_ajax_ee_get_scraperapi_api_key', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'لس لي احية']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_channel_settings_nonce')) {
wp_send_json_error(['message' => 'فش لقق م رمز الأمان']);
wp_die();
}
$api_key = get_option('ee_scraperapi_key', '');
wp_send_json_success(['api_key' => $api_key]);
wp_die();
});
// رض ائم الدرا المحفظة
function ee_render_leagues_list() {
$leagues = get_option('ee_leagues_list', []);
if (empty($leagues)) {
return '
ا وجد دويات ضاة حالً.
';
}
$output = '';
foreach ($leagues as $index => $league) {
$output .= '- ';
$output .= '' . esc_html($league) . '';
$output .= '';
$output .= '
';
}
$output .= '
';
return $output;
}
// الة للتق م صلايات امستخد
add_action('wp_ajax_ee_check_user_permissions', function () {
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_channel_settings_nonce')) {
wp_send_json_error(['message' => 'فش التحق رمز لن']);
wp_die();
}
$is_admin = current_user_can('manage_options');
wp_send_json_success(['is_admin' => $is_admin]);
wp_die();
});
// داة لتديث اـ Nonce
add_action('wp_ajax_ee_refresh_channel_nonce', function () {
$nonce = wp_create_nonce('ee_channel_settings_nonce');
wp_send_json_success(['nonce' => $nonce]);
wp_die();
});
// دالة لتديث لـ Nonce لوي إاات لكرن جوب
add_action('wp_ajax_ee_refresh_cron_settings_nonce', function () {
$nonce = wp_create_nonce('ee_cron_settings_nonce');
wp_send_json_success(['nonce' => $nonce]);
wp_die();
});
// دالة لتحديث ال Nonce لتي سجل الكون جوب
add_action('wp_ajax_ee_refresh_cron_log_nonce', function () {
$nonce = wp_create_nonce('ee_cron_log_nonce');
wp_send_json_success(['nonce' => $nonce]);
wp_die();
});
// دالة لحظ إعدادا لرون جوب
add_action('wp_ajax_ee_save_cron_settings', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'ل لديك صاحية']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_cron_settings_nonce')) {
wp_send_json_error(['message' => 'فشل الحقق من مز لأمان']);
wp_die();
}
$enabled = isset($_POST['cron_enabled']) && $_POST['cron_enabled'] == 1 ? 1 : 0;
$frequency = isset($_POST['cron_frequency']) ? intval($_POST['cron_frequency']) : 1;
$times = isset($_POST['cron_times']) && is_array($_POST['cron_times']) ? array_map('sanitize_text_field', $_POST['cron_times']) : ['00:00'];
update_option('ee_cron_enabled', $enabled);
update_option('ee_cron_frequency', $frequency);
update_option('ee_cron_times', $times);
// جدولة الكرون جو نءً على الإعدات لديدة
ee_schedule_cron_job();
wp_send_json_success(['message' => 'تم حظ اإعادات بنجا']);
wp_die();
});
// دالة لدوة لكرون جوب
function ee_schedule_cron_job() {
$enabled = get_option('ee_cron_enabled', false);
$frequency = get_option('ee_cron_frequency', 1);
$times = get_option('ee_cron_times', ['00:00']);
// إغاء جميع الدولا الديمة بشل كامل
$crons = _get_cron_array();
if (!empty($crons)) {
foreach ($crons as $timestamp => $cron) {
if (isset($cron['ee_fetch_matches_cron'])) {
foreach ($cron['ee_fetch_matches_cron'] as $hook => $args) {
wp_unschedule_event($timestamp, 'ee_fetch_matches_cron', $args['args']);
}
}
}
}
// جلب السائل المزة الحلية أو إاء وف فارغة
$cron_messages = get_option('ee_cron_messages', []);
if (!$enabled) {
$cron_messages[] = ['message' => 'Cron job disabled', 'timestamp' => (new DateTime('now', new DateTimeZone('Asia/Dubai')))->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
return;
}
// ضبط المنقة الزمنية لتوقي دبي
$timezone = new DateTimeZone('Asia/Dubai');
$current_time = new DateTime('now', $timezone);
$current_timestamp = $current_time->getTimestamp();
// جدول لكرن جوب بناءً عى اتوقات
foreach ($times as $index => $time) {
list($hour, $minute) = explode(':', $time);
$scheduled_time = new DateTime('today', $timezone);
$scheduled_time->setTime($hour, $minute, 0);
$timestamp = $scheduled_time->getTimestamp();
if ($timestamp < $current_timestamp) {
$scheduled_time->modify('+1 day');
$timestamp = $scheduled_time->getTimestamp();
}
// دولة الحد
wp_schedule_event($timestamp, 'daily', 'ee_fetch_matches_cron', ['index' => $index]);
$cron_messages[] = ['message' => 'Scheduled cron job for time ' . $time . ' at timestamp ' . $timestamp, 'timestamp' => $current_time->format('Y-m-d H:i:s')];
}
update_option('ee_cron_messages', $cron_messages);
}
// دالة تنفيذ لرون جب
add_action('ee_fetch_matches_cron', function ($index) {
$start_time = microtime(true);
$timezone = new DateTimeZone('Asia/Dubai');
$start_date = new DateTime('now', $timezone);
$start_timestamp = $start_date->getTimestamp();
// جب الس المخزة الحالي أو إنشا مصفة فغة
$cron_messages = get_option('ee_cron_messages', []);
$cron_messages[] = ['message' => 'Cron job started for index ' . $index . ' at: ' . $start_date->format('Y-m-d H:i:s'), 'timestamp' => $start_date->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
try {
// تنفيذ جل الينا (نفس الد الجود ي fetch_matches_for_channels)
$api_key = get_option('ee_scraperapi_key', '');
if (empty($api_key)) {
throw new Exception('Cron job failed: ScraperAPI key not found');
}
$selected_leagues = get_option('ee_leagues_list', []);
if (empty($selected_leagues)) {
throw new Exception('Cron job failed: No leagues selected');
}
$url = 'https://jdwel.com/today/';
$scraper_url = 'https://api.scraperapi.com/?api_key=' . $api_key . '&url=' . urlencode($url) . '&keep_headers=true';
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scraper_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Accept: text/html'
]);
$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($httpCode !== 200 || empty($response)) {
throw new Exception('Cron job failed: ScraperAPI error - HTTP Code ' . $httpCode . ', cURL Error: ' . $curl_error);
}
libxml_use_internal_errors(true);
$dom = new DOMDocument();
@$dom->loadHTML($response);
$xpath = new DOMXPath($dom);
$matches = $xpath->query('//li[contains(@class, "single_match")]');
if ($matches->length === 0) {
throw new Exception('Cron job: No matches found on the page');
}
$matches_data = [];
$match_ids = [];
$time_debug = [];
foreach ($matches as $match) {
$league_node = $xpath->query('preceding::div[contains(@class, "comp_separator")][1]//h4[@class="title"]', $match);
$league = $league_node->item(0)?->textContent ?? 'غير محد';
if (!in_array($league, $selected_leagues)) {
continue;
}
$match_id = $match->getAttribute('id') ? str_replace('match_', '', $match->getAttribute('id')) : 'غ مح';
$home_team = $xpath->query('.//div[contains(@class, "hometeam")]//span[@class="the_team"]', $match)->item(0)?->textContent ?? 'غير محد';
$away_team = $xpath->query('.//div[contains(@class, "awayteam")]//span[@class="the_team"]', $match)->item(0)?->textContent ?? 'غر محدد';
$date_time = $xpath->query('.//span[@class="the_otime"]', $match)->item(0)?->textContent ?? 'ير محدد';
if ($date_time !== 'غر حدد') {
try {
$datetime = new DateTime($date_time, $timezone);
$datetime->modify('+1 hour');
$original_date = explode(' ', $date_time)[0];
$time = $datetime->format('g:i A');
$time = str_replace('AM', '', $time);
$time = str_replace('PM', '', $time);
$date = $original_date;
$time_debug[] = [
'match_id' => $match_id,
'source' => 'the_otime',
'raw_time' => $date_time,
'adjusted_time' => $time,
'original_date' => $original_date,
'timezone' => 'Assumed Asia/Dubai (+1 hour adjustment)'
];
} catch (Exception $e) {
$cron_messages[] = ['message' => 'Cron job error parsing the_otime for match ' . $match_id . ': ' . $e->getMessage(), 'timestamp' => (new DateTime('now', $timezone))->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
continue;
}
} else {
$time_raw = $xpath->query('.//span[@class="the_time"]', $match)->item(0)?->textContent ?? 'غير حد';
if ($time_raw !== 'غي محدد') {
try {
$time_raw = trim($time_raw);
$datetime = DateTime::createFromFormat('g:i A', $time_raw, $timezone);
if ($datetime === false) {
throw new Exception('فشل في حل التوقي: ' . $time_raw);
}
$time = $datetime->format('g:i A');
$time = str_replace('AM', 'ص', $time);
$time = str_replace('PM', 'م', $time);
$time_debug[] = [
'match_id' => $match_id,
'source' => 'the_time',
'raw_time' => $time_raw,
'adjusted_time' => $time,
'timezone' => 'Asia/Dubai (no adjustment)'
];
} catch (Exception $e) {
$cron_messages[] = ['message' => 'Cron job error parsing the_time for match ' . $match_id . ': ' . $e->getMessage(), 'timestamp' => (new DateTime('now', $timezone))->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
continue;
}
} else {
$time = 'ر محد';
}
$date = $xpath->query('//div[contains(@class, "matchday_header")]//input[@type="date"]/@value')->item(0)?->value ?? 'غي مدد';
if ($time === 'غير حدد') {
$cron_messages[] = ['message' => 'Cron job: No valid time found for match ' . $match_id, 'timestamp' => (new DateTime('now', $timezone))->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
continue;
}
}
if ($match_id !== 'غي محد') {
$match_ids[] = $match_id;
}
$matches_data[] = [
'league' => $league,
'match' => "$home_team vs $away_team",
'date' => $date,
'time' => $time,
'channels' => [],
'commentators' => [],
];
}
if (empty($matches_data)) {
throw new Exception('Cron job: No matches found for selected leagues');
}
$existing_channels_data = get_option('ee_matches_channels_data', []);
foreach ($match_ids as $index => $match_id) {
$api_url = "https://jdwel.com/wp-json/jmanager/web/v1/match/$match_id";
$scraper_api_url = "https://api.scraperapi.com/?api_key=$api_key&url=" . urlencode($api_url) . "&keep_headers=true";
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $scraper_api_url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
curl_setopt($ch, CURLOPT_TIMEOUT, 60);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
'Accept: application/json'
]);
$api_response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curl_error = curl_error($ch);
curl_close($ch);
if ($httpCode === 200 && !empty($api_response)) {
$json = json_decode($api_response, true);
if ($json !== null) {
$tv_stations = $json['data']['tv_stations'] ?? [];
if (is_array($tv_stations) && !empty($tv_stations)) {
$channel_names = [];
$commentator_names = [];
foreach ($tv_stations as $station) {
$channel_name = isset($station['name']) && !empty($station['name']) ? esc_html($station['name']) : 'ي حدد';
$commentator = isset($station['commentators']) && !empty($station['commentators']) && $station['commentators'] !== 'ر مدد' ? esc_html($station['commentators']) : 'غير مد';
$channel_names[] = $channel_name;
$commentator_names[] = $commentator;
}
$matches_data[$index]['channels'] = $channel_names;
$matches_data[$index]['commentators'] = $commentator_names;
$match_key = $matches_data[$index]['match'] . '|' . $matches_data[$index]['date'];
$existing_channels_data[$match_key] = [
'channels' => $channel_names,
'commentators' => $commentator_names,
];
} else {
$matches_data[$index]['channels'] = [' متح'];
$matches_data[$index]['commentators'] = ['غير تح'];
}
} else {
$matches_data[$index]['channels'] = ['غي مت'];
$matches_data[$index]['commentators'] = ['غير متاح'];
}
} else {
$cron_messages[] = ['message' => 'Cron job failed to fetch channels for match ' . $match_id . ': HTTP Code ' . $httpCode . ', cURL Error: ' . $curl_error, 'timestamp' => (new DateTime('now', $timezone))->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
usleep(100000); // 0.1 ثا
continue;
}
usleep(100000); // 0.1 ثانة
}
update_option('ee_matches_data', $matches_data);
update_option('ee_matches_channels_data', $existing_channels_data);
// تسجي الحد ف السجل
$cron_log = get_option('ee_cron_log', []);
$cron_log[] = [
'time' => $start_date->format('Y-m-d H:i:s'),
'status' => 'success',
'matches_count' => count($matches_data),
'message' => 'تم جلب ' . count($matches_data) . ' مااة بنجح'
];
update_option('ee_cron_log', $cron_log);
$end_time = microtime(true);
$end_date = new DateTime('now', $timezone);
$cron_messages[] = ['message' => 'Cron job completed in ' . ($end_time - $start_time) . ' seconds at: ' . $end_date->format('Y-m-d H:i:s'), 'timestamp' => $end_date->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
} catch (Exception $e) {
$end_time = microtime(true);
$end_date = new DateTime('now', $timezone);
$cron_messages[] = ['message' => 'Cron job failed: ' . $e->getMessage(), 'timestamp' => $end_date->format('Y-m-d H:i:s')];
$cron_messages[] = ['message' => 'Cron job terminated after ' . ($end_time - $start_time) . ' seconds at: ' . $end_date->format('Y-m-d H:i:s'), 'timestamp' => $end_date->format('Y-m-d H:i:s')];
update_option('ee_cron_messages', $cron_messages);
}
});
// ال لب رسائل الكرون جب وعرضها ي الكونسل
add_action('wp_ajax_ee_get_cron_messages', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'يس لدك صلاحي']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_cron_settings_nonce')) {
wp_send_json_error(['message' => 'فل اتحق م رمز اأمن']);
wp_die();
}
$messages = get_option('ee_cron_messages', []);
wp_send_json_success(['messages' => $messages]);
wp_die();
});
// داة اخار الكرن جو يدويا
add_action('wp_ajax_ee_test_cron_job', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'لي لدي صلية']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_cron_settings_nonce')) {
wp_send_json_error(['message' => 'فش التقق من مز الما']);
wp_die();
}
// تفيذ الكرن جوب ييً
do_action('ee_fetch_matches_cron', 0);
// تأي سيط لتأكد من خزي الرسئل
sleep(1);
// لب السائل بع اتنفذ
$messages = get_option('ee_cron_messages', []);
wp_send_json_success([
'message' => 'تم تشي الرو ج دويًا. تحقق من لسائل ي الكونسو.',
'messages' => $messages
]);
wp_die();
});
// الة ذف سجل ارون ب
add_action('wp_ajax_ee_clear_cron_log', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'ليس لدك صلاحية']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_cron_settings_nonce')) {
wp_send_json_error(['message' => 'فشل التقق من رز الأما']);
wp_die();
}
// حذف السجل
delete_option('ee_cron_log');
wp_send_json_success(['message' => 'ت حذف ج بنجاح']);
wp_die();
});
// دالة لب جل الكرون جوب
add_action('wp_ajax_ee_get_cron_log', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'س لديك صلاي']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_cron_settings_nonce')) {
wp_send_json_error(['message' => 'فش التحق ن م لأمان']);
wp_die();
}
$logs = get_option('ee_cron_log', []);
wp_send_json_success(['logs' => $logs]);
wp_die();
});
// داة تحديث الن وامعقين
add_action('wp_ajax_ee_update_channels', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'لي ليك صلاية لحدي القنوا والملقين']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_matches_tab_nonce')) {
wp_send_json_error(['message' => 'ل الحق ن مز لمان']);
wp_die();
}
if (!isset($_POST['index']) || !is_numeric($_POST['index'])) {
wp_send_json_error(['message' => 'الهرس غر صح']);
wp_die();
}
$index = intval($_POST['index']);
$channels_input = isset($_POST['channels']) ? sanitize_textarea_field($_POST['channels']) : '';
$commentators_input = isset($_POST['commentators']) ? sanitize_textarea_field($_POST['commentators']) : '';
// تحول مدخلات ل مصففت
$channels = $channels_input ? array_map('trim', explode("\n", $channels_input)) : [];
$commentators = $commentators_input ? array_map('trim', explode("\n", $commentators_input)) : [];
$matches = get_option('ee_matches_data', []);
if (isset($matches[$index])) {
$matches[$index]['channels'] = $channels;
$matches[$index]['commentators'] = $commentators;
// تحديث ee_matches_channels_data
$match_key = $matches[$index]['match'] . '|' . $matches[$index]['date'];
$channels_data = get_option('ee_matches_channels_data', []);
$channels_data[$match_key] = [
'channels' => $channels,
'commentators' => $commentators,
];
update_option('ee_matches_data', $matches);
update_option('ee_matches_channels_data', $channels_data);
wp_send_json_success(['matches' => $matches]);
} else {
wp_send_json_error(['message' => 'فشل ي تديث اباراة']);
}
wp_die();
});
// الة مسح بيانات البيا
add_action('wp_ajax_ee_clear_matches_data', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'ل لدك احية لمح ليت']);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_channel_settings_nonce')) {
wp_send_json_error(['message' => 'فشل لح من رمز الأمان']);
wp_die();
}
// ح يانا المرا
delete_option('ee_matches_data');
delete_option('ee_matches_channels_data');
wp_send_json_success(['message' => 'ت مح بيانا لمبيت بجاح']);
wp_die();
});
// ملخ اليوتيو
// إجراء تحديث ربط ملخص يتيوب لباراة
add_action('wp_ajax_ee_update_highlight', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'لس ليك صاحي']);
wp_die();
}
$match_id = isset($_POST['match_id']) ? intval($_POST['match_id']) : 0;
$highlight_url = isset($_POST['highlight_url']) ? esc_url_raw($_POST['highlight_url']) : '';
if ($match_id <= 0) {
wp_send_json_error(['message' => 'معر المبااة ير صال']);
wp_die();
}
// تحيث حقل meta
update_post_meta($match_id, '_highlight_url', $highlight_url);
wp_send_json_success(['message' => 'ت تحيث الربط بجاح']);
wp_die();
});
// إجرء لتحديث روبط ملصات يوتيوب بشل جمعي
add_action('wp_ajax_ee_bulk_update_highlights', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => 'لس لديك صلاحية']);
wp_die();
}
// التحقق من وجو بانت التحديثا
$updates = isset($_POST['updates']) ? json_decode(stripslashes($_POST['updates']), true) : [];
if (empty($updates) || !is_array($updates)) {
wp_send_json_error(['message' => 'بينات لتحديثات ي صالح']);
wp_die();
}
// معالجة كل تحديث
foreach ($updates as $update) {
$match_id = isset($update['match_id']) ? intval($update['match_id']) : 0;
$highlight_url = isset($update['highlight_url']) ? esc_url_raw($update['highlight_url']) : '';
if ($match_id <= 0) {
continue; // تخطي لتحديث إ كان معرف المباراة غير صال
}
// تحديث حقل meta
update_post_meta($match_id, '_highlight_url', $highlight_url);
}
wp_send_json_success(['message' => 'تم تحث الروابط بنجاح']);
wp_die();
});
// دالة تظيف النصوص
if (!function_exists('sanitize_title_for_match')) {
function sanitize_title_for_match($title) {
$title = mb_strtolower($title);
$title = str_replace(['ملخص', 'مباراة', 'دوري', 'نادي', 'sc', 'vs', 'ضد', ':', '-', '|', '(', ')', '[', ']', '!', '?'], ' ', $title);
$title = preg_replace('/\d{4}-\d{2}-\d{2}/', '', $title);
$title = preg_replace('/\d+/', '', $title);
$title = str_replace("\u00a0", " ", $title);
$title = preg_replace('/\s+/', ' ', trim($title));
return $title;
}
}
// إجراء لحفظ إعدادات الكرون جوب
add_action('wp_ajax_ee_save_youtube_cron_settings', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => __('ليس لديك صلاحية', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_youtube_cron_settings_nonce')) {
wp_send_json_error(['message' => __('فشل التحقق ن رمز الأمان', 'eighty-eight-manager')]);
wp_die();
}
$enabled = isset($_POST['cron_enabled']) && $_POST['cron_enabled'] == 1 ? 1 : 0;
$frequency = isset($_POST['cron_frequency']) ? intval($_POST['cron_frequency']) : 1;
$times = isset($_POST['cron_times']) && is_array($_POST['cron_times']) ? array_map('sanitize_text_field', $_POST['cron_times']) : ['00:00'];
update_option('ee_youtube_cron_enabled', $enabled);
update_option('ee_youtube_cron_frequency', $frequency);
update_option('ee_youtube_cron_times', $times);
// جدولة الكرون جوب
ee_schedule_youtube_cron_job();
wp_send_json_success(['message' => __('تم حفظ الإدادات بنجاح', 'eighty-eight-manager')]);
wp_die();
});
// دالة لجدولة الكرون جوب
function ee_schedule_youtube_cron_job() {
$enabled = get_option('ee_youtube_cron_enabled', false);
$frequency = get_option('ee_youtube_cron_frequency', 1);
$times = get_option('ee_youtube_cron_times', ['00:00']);
// إغاء جميع الجدولا القديمة
$crons = _get_cron_array();
if (!empty($crons)) {
foreach ($crons as $timestamp => $cron) {
if (isset($cron['ee_youtube_cron'])) {
foreach ($cron['ee_youtube_cron'] as $hook => $args) {
wp_unschedule_event($timestamp, 'ee_youtube_cron', $args['args']);
}
}
}
}
if (!$enabled) {
return;
}
// ضبط الناق الزمني لتوقيت دبي
$timezone = new DateTimeZone('Asia/Dubai');
$current_time = new DateTime('now', $timezone);
$current_timestamp = $current_time->getTimestamp();
// جدولة الأحداث
foreach ($times as $index => $time) {
list($hour, $minute) = explode(':', $time);
$scheduled_time = new DateTime('today', $timezone);
$scheduled_time->setTime($hour, $minute, 0);
$timestamp = $scheduled_time->getTimestamp();
if ($timestamp < $current_timestamp) {
$scheduled_time->modify('+1 day');
$timestamp = $scheduled_time->getTimestamp();
}
wp_schedule_event($timestamp, 'daily', 'ee_youtube_cron', ['index' => $index]);
}
}
// إجراء لشغيل الكرون جوب
add_action('ee_youtube_cron', function ($index) {
$start_time = microtime(true);
$timezone = new DateTimeZone('Asia/Dubai');
$start_date = new DateTime('now', $timezone);
$cron_log = get_option('ee_youtube_cron_log', []);
$matches_processed = 0;
$with_highlights = 0;
$without_highlights = 0;
try {
// تنفيذ منطق المطابقة
$yesterday = date('Y-m-d', strtotime('-1 day'));
$today = date('Y-m-d');
// جلب الملخصات
$latest_summaries = get_posts([
'post_type' => 'post',
'posts_per_page' => 50,
'post_status' => 'publish',
'orderby' => 'date',
'order' => 'DESC',
'cat' => 2419,
]);
if (is_wp_error($latest_summaries)) {
throw new Exception('فشل في جلب الملخصات: ' . $latest_summaries->get_error_message());
}
$summaries = [];
foreach ($latest_summaries as $post) {
$title = get_the_title($post->ID);
$clean_title = strpos($title, '|') !== false ? trim(explode('|', $title)[0]) : $title;
$clean_title = sanitize_title_for_match($clean_title);
$summaries[] = [
'id' => $post->ID,
'title' => $clean_title,
'permalink' => get_permalink($post->ID)
];
}
// جلب المباريات
$args = [
'post_type' => 'joomsport_match',
'post_status' => 'publish',
'posts_per_page' => 50,
'meta_query' => [
'relation' => 'OR',
[
'key' => '_joomsport_match_date',
'value' => $yesterday,
'compare' => '=',
],
[
'key' => '_joomsport_match_date',
'value' => $today,
'compare' => '=',
],
],
];
$query = new WP_Query($args);
if (is_wp_error($query)) {
throw new Exception('فل في جلب المباريات: ' . $query->get_error_message());
}
if ($query->have_posts()) {
while ($query->have_posts()) {
$query->the_post();
$match_id = get_the_ID();
$title = get_the_title();
$match_date = get_post_meta($match_id, '_joomsport_match_date', true);
$match_time = get_post_meta($match_id, '_joomsport_match_time', true);
$team1_score = get_post_meta($match_id, '_joomsport_home_score', true);
$team2_score = get_post_meta($match_id, '_joomsport_away_score', true);
$manual_highlight_url = get_post_meta($match_id, '_manual_highlight_url', true);
$highlight_locked = get_post_meta($match_id, '_highlight_locked', true);
$teams = explode('vs', $title);
$team1 = isset($teams[0]) ? trim(mb_ereg_replace('[^\\p{Arabic}a-zA-Z\\s]', '', str_ireplace(['نادي', 'SC'], '', $teams[0]))) : '-';
$team2 = isset($teams[1]) ? trim(mb_ereg_replace('[^\\p{Arabic}a-zA-Z\\s]', '', str_ireplace(['نادي', 'SC'], '', $teams[1]))) : '-';
$teams_display = sanitize_title_for_match($team1 . ' vs ' . $team2);
// التحقق مما إذا كانت المباراة منتهية
$match_datetime = new DateTime("$match_date $match_time", new DateTimeZone('Asia/Dubai'));
$current_datetime = new DateTime('now', new DateTimeZone('Asia/Dubai'));
$is_match_finished = ($match_datetime < $current_datetime) && ($team1_score !== '' && $team2_score !== '');
if (!$is_match_finished) {
update_post_meta($match_id, '_highlight_url', '');
update_post_meta($match_id, '_manual_highlight_url', '');
$matches_processed++;
$without_highlights++;
continue;
}
// تخطي المباراة إذا كان الرابط مقفلاً
if ($highlight_locked === 'true') {
$matches_processed++;
$without_highlights++;
continue;
}
// إذا كان هناك رابط يدوي، استخدمه
if ($manual_highlight_url) {
update_post_meta($match_id, '_highlight_url', $manual_highlight_url);
$matches_processed++;
$with_highlights++;
continue;
}
$best_match = null;
$highest_similarity = 0;
foreach ($summaries as $summary) {
$title_to_check = $summary['title'];
$similarity = 0;
similar_text($teams_display, $title_to_check, $similarity);
error_log("Cron Matching: $teams_display vs $title_to_check, Similarity: $similarity%");
$team1_found = stripos($title_to_check, mb_strtolower($team1)) !== false;
$team2_found = stripos($title_to_check, mb_strtolower($team2)) !== false;
// الأكد من وجود كلا افريقين في العنوا
if ($similarity >= 80 && $team1_found && $team2_found) {
if ($similarity > $highest_similarity) {
$highest_similarity = $similarity;
$best_match = $summary;
}
}
}
if ($best_match) {
update_post_meta($match_id, '_highlight_url', $best_match['permalink']);
$with_highlights++;
} else {
update_post_meta($match_id, '_highlight_url', '');
$without_highlights++;
}
$matches_processed++;
}
}
wp_reset_postdata();
// تسجيل القيم للتحقق
error_log("ee_youtube_cron: matches_processed=$matches_processed, with_highlights=$with_highlights, without_highlights=$without_highlights");
// تسجيل الحدث في السجل
$message_template = __('إجمالي المباريات المعالجة: %d، مباريت مع ملخص: %d، مباريات بدون ملخص: %d', 'eighty-eight-manager');
$message = sprintf($message_template, $matches_processed, $with_highlights, $without_highlights);
error_log("ee_youtube_cron: message_template=$message_template, final_message=$message");
$cron_log[] = [
'time' => $start_date->format('Y-m-d H:i:s'),
'status' => 'success',
'matches_processed' => $matches_processed,
'message' => $message
];
update_option('ee_youtube_cron_log', $cron_log);
} catch (Exception $e) {
$message_template = __('فشل الرون جوب: %s. إجمالي المباريات المعالجة: %d، مباريات مع لخص: %d، مباريات بون ملخص: %d', 'eighty-eight-manager');
$message = sprintf($message_template, $e->getMessage(), $matches_processed, $with_highlights, $without_highlights);
error_log("ee_youtube_cron: error_message_template=$message_template, final_error_message=$message");
$cron_log[] = [
'time' => $start_date->format('Y-m-d H:i:s'),
'status' => 'error',
'matches_processed' => $matches_processed,
'message' => $message
];
update_option('ee_youtube_cron_log', $cron_log);
error_log('Caught Exception in ee_youtube_cron: ' . $e->getMessage());
}
});
// إجراء لاختبار الكرون جوب يدويًا
add_action('wp_ajax_ee_test_youtube_cron', function () {
if (!current_user_can('manage_options')) {
wp_send_json_error(['message' => __('ليس ليك صلاحية', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_youtube_cron_settings_nonce')) {
wp_send_json_error(['message' => __('فشل التحقق من رمز الأمان', 'eighty-eight-manager')]);
wp_die();
}
try {
ob_start();
do_action('ee_youtube_cron', 0);
ob_end_clean();
// تأخير بسي لضمان حفظ السجل
sleep(1);
$cron_log = get_option('ee_youtube_cron_log', []);
$latest_log = end($cron_log);
if ($latest_log && is_array($latest_log) && isset($latest_log['status']) && $latest_log['status'] === 'success') {
$matches_processed = isset($latest_log['matches_processed']) ? $latest_log['matches_processed'] : 0;
wp_send_json_success(['message' => sprintf(__('تم تشغيل الكرون جوب نجاح، تم معالجة %d مباراة', 'eighty-eight-manager'), $matches_processed)]);
} else {
$error_message = isset($latest_log['message']) ? $latest_log['message'] : __('خطأ غير معرف أثناء تشغيل الكرون جوب', 'eighty-eight-manager');
wp_send_json_error(['message' => __('فشل في تشغيل الكرون جوب: ', 'eighty-eight-manager') . $error_message]);
}
} catch (Exception $e) {
error_log('Test YouTube Cron Error: ' . $e->getMessage());
wp_send_json_error(['message' => __('فشل في تشغيل الكرون جوب: ', 'eighty-eight-manager') . $e->getMessage()]);
}
wp_die();
});
// إجراء لحذف سجلات الكرون جوب
add_action('wp_ajax_ee_clear_youtube_cron_logs', function () {
error_log('ee_clear_youtube_cron_logs: Action triggered');
if (!current_user_can('manage_options')) {
error_log('ee_clear_youtube_cron_logs: User lacks manage_options capability');
wp_send_json_error(['message' => __('ليس لديك لاحية', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_youtube_cron_settings_nonce')) {
error_log('ee_clear_youtube_cron_logs: Nonce verification failed, nonce=' . ($_POST['nonce'] ?? 'unset'));
wp_send_json_error(['message' => __('فشل التحقق من رمز الأمان', 'eighty-eight-manager')]);
wp_die();
}
try {
$current_log = get_option('ee_youtube_cron_log', []);
error_log('ee_clear_youtube_cron_logs: Current log size=' . count($current_log));
$result = update_option('ee_youtube_cron_log', []);
error_log('ee_clear_youtube_cron_logs: update_option result=' . ($result ? 'true' : 'false'));
wp_send_json_success(['message' => __('تم حذف سجلات الكرون جوب بنجاح', 'eighty-eight-manager')]);
} catch (Exception $e) {
error_log('Clear YouTube Cron Logs Error: ' . $e->getMessage());
wp_send_json_error(['message' => __('فشل في حذف السجلات: ', 'eighty-eight-manager') . $e->getMessage()]);
}
wp_die();
});
// إجراء لحفظ الرابط الدوي
add_action('wp_ajax_ee_save_manual_highlight_url', function () {
error_log('ee_save_manual_highlight_url: Action triggered');
if (!current_user_can('manage_options')) {
error_log('ee_save_manual_highlight_url: User lacks manage_options capability');
wp_send_json_error(['message' => __('ليس لديك صلاحية', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_youtube_cron_settings_nonce')) {
error_log('ee_save_manual_highlight_url: Nonce verification failed, nonce=' . ($_POST['nonce'] ?? 'unset'));
wp_send_json_error(['message' => __('شل التحقق من رمز لأمان', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['match_id']) || !isset($_POST['url'])) {
error_log('ee_save_manual_highlight_url: Missing match_id or url');
wp_send_json_error(['message' => __('البيانات المطلوبة غير موجودة', 'eighty-eight-manager')]);
wp_die();
}
try {
$match_id = intval($_POST['match_id']);
$url = esc_url_raw($_POST['url']);
if (empty($url)) {
// إذا كن الرابط فارغًا، احذف الرابط اليدوي
update_post_meta($match_id, '_manual_highlight_url', '');
update_post_meta($match_id, '_highlight_url', '');
update_post_meta($match_id, '_highlight_locked', 'true');
error_log("ee_save_manual_highlight_url: Cleared manual URL and locked for match_id=$match_id");
} else {
// حف الرابط اليدوي وتحديث الرابط التلقائي
update_post_meta($match_id, '_manual_highlight_url', $url);
update_post_meta($match_id, '_highlight_url', $url);
update_post_meta($match_id, '_highlight_locked', 'false');
error_log("ee_save_manual_highlight_url: Saved manual URL=$url for match_id=$match_id");
}
wp_send_json_success(['message' => __('تم حف الرابط اليدوي بنجاح', 'eighty-eight-manager')]);
} catch (Exception $e) {
error_log('Save Manual Highlight URL Error: ' . $e->getMessage());
wp_send_json_error(['message' => __('فشل في حفظ الرابط اليوي: ', 'eighty-eight-manager') . $e->getMessage()]);
}
wp_die();
});
// إجراء لتحديث جميع روابط الملخصات
add_action('wp_ajax_ee_update_all_highlight_urls', function () {
error_log('ee_update_all_highlight_urls: Action triggered');
if (!current_user_can('manage_options')) {
error_log('ee_update_all_highlight_urls: User lacks manage_options capability');
wp_send_json_error(['message' => __('ليس لديك صلاحية', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_youtube_cron_settings_nonce')) {
error_log('ee_update_all_highlight_urls: Nonce verification failed, nonce=' . ($_POST['nonce'] ?? 'unset'));
wp_send_json_error(['message' => __('فشل التحقق م رمز الأمان', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['updates'])) {
error_log('ee_update_all_highlight_urls: Missing updates data');
wp_send_json_error(['message' => __('البيانات المطلوبة غير موجودة', 'eighty-eight-manager')]);
wp_die();
}
try {
// محاولة تحليل updates كمصفوفة أو سلسلة JSON
$updates = $_POST['updates'];
if (is_string($updates)) {
$updates = json_decode($updates, true);
error_log('ee_update_all_highlight_urls: Decoded JSON updates: ' . print_r($updates, true));
}
if (!is_array($updates)) {
error_log('ee_update_all_highlight_urls: Invalid updates data, not an array');
wp_send_json_error(['message' => __('البيانات امطلوبة غير موجود', 'eighty-eight-manager')]);
wp_die();
}
error_log('ee_update_all_highlight_urls: Processing ' . count($updates) . ' updates');
foreach ($updates as $update) {
if (!isset($update['match_id']) || !isset($update['url'])) {
error_log('ee_update_all_highlight_urls: Invalid update data, skipping: ' . json_encode($update));
continue;
}
$match_id = intval($update['match_id']);
$url = esc_url_raw($update['url']);
// التأكد من عدم وجد رابط يدوي
$manual_highlight_url = get_post_meta($match_id, '_manual_highlight_url', true);
if ($manual_highlight_url) {
error_log("ee_update_all_highlight_urls: Skipping match_id=$match_id due to existing manual URL");
continue;
}
// تحديث الرابط لتلقائي
if (empty($url)) {
update_post_meta($match_id, '_highlight_url', '');
update_post_meta($match_id, '_highlight_locked', 'true');
error_log("ee_update_all_highlight_urls: Cleared highlight URL and locked for match_id=$match_id");
} else {
update_post_meta($match_id, '_highlight_url', $url);
update_post_meta($match_id, '_highlight_locked', 'false');
error_log("ee_update_all_highlight_urls: Updated highlight URL=$url for match_id=$match_id");
}
}
wp_send_json_success(['message' => __('تم تحديث جمع الروابط بنجاح', 'eighty-eight-manager')]);
} catch (Exception $e) {
error_log('Update All Highlight URLs Error: ' . $e->getMessage());
wp_send_json_error(['message' => __('فشل في تحديث الروابط: ', 'eighty-eight-manager') . $e->getMessage()]);
}
wp_die();
});
// إجراء لتحديث ربط ملخص واحد (للقئمة المنسدلة)
add_action('wp_ajax_ee_update_highlight_url', function () {
error_log('ee_update_highlight_url: Action triggered');
if (!current_user_can('manage_options')) {
error_log('ee_update_highlight_url: User lacks manage_options capability');
wp_send_json_error(['message' => __('ليس لديك صلاحية', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['nonce']) || !wp_verify_nonce($_POST['nonce'], 'ee_youtube_cron_settings_nonce')) {
error_log('ee_update_highlight_url: Nonce verification failed, nonce=' . ($_POST['nonce'] ?? 'unset'));
wp_send_json_error(['message' => __('فل التحقق من رمز اأمان', 'eighty-eight-manager')]);
wp_die();
}
if (!isset($_POST['match_id']) || !isset($_POST['url'])) {
error_log('ee_update_highlight_url: Missing match_id or url');
wp_send_json_error(['message' => __('البيانت المطلوبة غير موجودة', 'eighty-eight-manager')]);
wp_die();
}
try {
$match_id = intval($_POST['match_id']);
$url = esc_url_raw($_POST['url']);
// إزالة الابط اليدوي إذا تم اختيار رابط تلقاي
update_post_meta($match_id, '_manual_highlight_url', '');
// تحديث ارابط التلقائي
if (empty($url)) {
update_post_meta($match_id, '_highlight_url', '');
update_post_meta($match_id, '_highlight_locked', 'true');
error_log("ee_update_highlight_url: Cleared highlight URL and locked for match_id=$match_id");
} else {
update_post_meta($match_id, '_highlight_url', $url);
update_post_meta($match_id, '_highlight_locked', 'false');
error_log("ee_update_highlight_url: Updated highlight URL=$url for match_id=$match_id");
}
wp_send_json_success(['message' => __('تم تحديث الرابط بناح', 'eighty-eight-manager')]);
} catch (Exception $e) {
error_log('Update Highlight URL Error: ' . $e->getMessage());
wp_send_json_error(['message' => __('فشل في حديث الرابط: ', 'eighty-eight-manager') . $e->getMessage()]);
}
wp_die();
});