HEX
Server: Apache/2.4.65 (Debian)
System: Linux 88f31f35b0b8 6.1.0-38-amd64 #1 SMP PREEMPT_DYNAMIC Debian 6.1.147-1 (2025-08-02) x86_64
User: www-data (33)
PHP: 8.2.29
Disabled: NONE
Upload Files
File: /var/www/html/wp-content/plugins/adnkronos/inc/utility.php
<?php

/***************************************************** */
// Function for get XML from feed and convert in array
/**************************************************** */

function adnki_feed2string($url)
{
    $log_file = dirname(__FILE__) . '/../logs/' . gmdate('Ymd') . '_import.log';
    $response_xml_data = false;
    $clientHttp = new WP_Http();
    $response = $clientHttp->request($url, ['timeout' => 10]);

    if ($response instanceof WP_Error) {
        file_put_contents($log_file, " Response: " . json_encode($response) . "\n ", FILE_APPEND);

        return;
    }

    $response_xml_data = $response['body'];
    if (is_string($response_xml_data)) {
        return $response_xml_data;
    }

    return null;
}

function adnki_feed2xml($url)
{
    $log_file = dirname(__FILE__) . '/../logs/' . gmdate('Ymd') . '_import.log';
    $response_xml_data = false;
    $clientHttp = new WP_Http();
    $response = $clientHttp->request($url, ['timeout' => 10]);

    if ($response instanceof WP_Error) {
        file_put_contents($log_file, " Response: " . json_encode($response) . "\n ", FILE_APPEND);

        return;
    }

    $response_xml_data = $response['body'];
    if (is_string($response_xml_data)) {
        libxml_use_internal_errors(true);
        $data = simplexml_load_string($response_xml_data, null, LIBXML_NOCDATA);

        if (!$data) {
            foreach (libxml_get_errors() as $error) {
                file_put_contents($log_file, " Errore: " . $error->message . "\n", FILE_APPEND);
            }
        } else {
            return ($data);
        }
    }

}

function adnki_xml2array($xmlObject, $out = array())
{
    foreach ((array)$xmlObject as $index => $node) {
        $out[$index] = (is_object($node)) ? adnki_xml2array($node) : $node;
    }

    return $out;
}

/* create post from Feed */

function adnk_create_post_from_result(
    $import_post,
    $post_category,
    $post_status = 'publish',
    $post_owner_email,
    $feed_name,
    $check_no_import_image,
    $image_owner_email)
{
    /* Create post object */
    $log_file = dirname(__FILE__) . '/../logs/' . date('Ymd') . '_import.log';
    file_put_contents($log_file, " Valuto {$import_post->uuid} \n", FILE_APPEND);

    $header = false;
    if (!file_exists(dirname(__FILE__) . '/../logs/' . date('Ymd') . '_' . $_SERVER['SERVER_NAME'] . '_import.csv')) {
        $header = true;
    }
    $csv_file = dirname(__FILE__) . '/../logs/' . date('Ymd') . '_' . $_SERVER['SERVER_NAME'] . '_import.csv';

    if ($header) {
        $row = array(
            'IMPORTATAZIONE',
            'PUBBLICAZIONE',
            'DIFFERENZA',
            'CATEGORIA',
            'TITOLO',
            'URL',
            'SERVER',
        );
        file_put_contents($csv_file, implode(';', $row) . "\n", FILE_APPEND);
    }
    try {

        $category = array($post_category); // category id

        $post_owner = get_user_by('email', $post_owner_email);

        //$adkn_guid_post_feed = trim(substr( (string) $import_post->guid, strpos( (string) $import_post->guid, "_" ) + 1 ));
        $adkn_guid_post_feed = $import_post->uuid->__toString();

        $fullstring = $import_post->pubDate;
        $date_article = adnk_import_tdm_get_string_between($fullstring, ',', '+');
        $date_article = str_replace([
            'Gen',
            'Mag',
            'Giu',
            'Lug',
            'Ago',
            'Set',
            'Ott',
            'Dic',
        ], [
            'Jan',
            'May',
            'Jun',
            'Jul',
            'Aug',
            'Sep',
            'Oct',
            'Dec',
        ], $date_article);
        $date_post = gmdate('Y-m-d H:i:s', strtotime($date_article));
        $new_post_id = '';

        $args = array(
            'post_type' => 'post',
            'post_status' => 'any',
            'posts_per_page' => -1,
            'meta_query' => array(
                array(
                    'key' => 'adkn_guid_post_feed',
                    'value' => $adkn_guid_post_feed,
                    'compare' => 'LIKE',
                ),
            ),
        );
        $query = new WP_Query($args);
        $hasdata = $query->get_posts();
        $count = count($hasdata);

        if ($count === 0) {
            global $wpdb;
            $adkn_guid_post_feed = trim(substr((string)($import_post->guid->__toString() ?: $import_post->uuid->__toString()), strpos((string)($import_post->guid ?: $import_post->uuid), "_") + 1));
            $hasdata = $wpdb->get_results("select * from $wpdb->postmeta where meta_key='adkn_guid_post_feed' and meta_value='$adkn_guid_post_feed'");
            $count = count($hasdata);
        }
        file_put_contents($log_file, "           {$import_post->title} | " . ($count == 0 ? "DA ELABORARE" : "già importato") . " \n", FILE_APPEND);
        if ($count == 0) {
            $enclosure = adnki_xml2array($import_post->enclosure)['@attributes'];

            $post_content = $import_post->description;
            $excerpt = $post_content;

            $post_content .= '<p>---</p>';
            $post_content .= '<p>' . $import_post->category . '</p>';
            $post_content .= '<p>' . $import_post->author . '</p>';

            $excerpt = esc_html(wp_strip_all_tags($excerpt));

            $position = stripos($excerpt, '.'); //find first dot position
            $excerpt = substr(trim($excerpt), 0, $position); //put two first sentences under $first_two

            $metaInput = array(
                'oimmei' => true,
            );

            // Prepare Yoast SEO meta fields if plugin is active
            if (defined('WPSEO_VERSION')) {
                $metaInput['_yoast_wpseo_title'] = (string)$import_post->title;
                $metaInput['_yoast_wpseo_focuskw'] = (string)$import_post->title;
                $metaInput['_yoast_wpseo_metadesc'] = $excerpt;
                $metaInput['_yoast_wpseo_opengraph-title'] = (string)$import_post->title;
                $metaInput['_yoast_wpseo_opengraph-description'] = $excerpt;
                $metaInput['_yoast_wpseo_twitter-title'] = (string)$import_post->title;
                $metaInput['_yoast_wpseo_twitter-description'] = $excerpt;
                // Image will be set after upload
            }

            $new_post = array(
                'post_title' => $import_post->title,
                //'post_content'  => esc_html( wp_strip_all_tags( $post_content ) ),
                'post_content' => $post_content,
                'post_date' => $date_post,
                'post_status' => $post_status,
                'post_author' => $post_owner->ID,
                'post_category' => $category,
                'post_excerpt' => $excerpt,
                'meta_input' => $metaInput,
            );
            // Insert the post into the database
            $new_post_id = wp_insert_post($new_post);
            $adkn_guid_post_feed = sanitize_text_field($adkn_guid_post_feed);
            update_post_meta($new_post_id, 'adkn_guid_post_feed', $adkn_guid_post_feed);
            $adkn_feed_category = sanitize_text_field($import_post->category->__toString());
            update_post_meta($new_post_id, 'adkn_feed_category', $adkn_feed_category);

            // assign featured image from url
            $image_url = $enclosure['url'];
            $photo_name = $import_post->title;

            if ($image_url && substr($image_url, -3) != 'mp4' && $feed_name != 'video') {
                if (!$check_no_import_image == 'on') {
                    // Try to upload and assign image - if it fails, delete the post
                    $image_result = adnk_upload_assign_image($new_post_id, $image_url, $photo_name, $image_owner_email);
                    if ($image_result === false) {
                        // Image upload failed, delete the post and return null
                        wp_delete_post($new_post_id, true);
                        file_put_contents($log_file, "           Post {$new_post_id} eliminato a causa di errore nell'upload dell'immagine\n", FILE_APPEND);
                        return null;
                    } else {
                        // Image uploaded successfully, set as sharing image for Yoast SEO
                        if (defined('WPSEO_VERSION') && is_numeric($image_result)) {
                            $image_url_for_sharing = wp_get_attachment_url($image_result);
                            if ($image_url_for_sharing) {
                                update_post_meta($new_post_id, '_yoast_wpseo_opengraph-image', $image_url_for_sharing);
                                update_post_meta($new_post_id, '_yoast_wpseo_twitter-image', $image_url_for_sharing);
                                file_put_contents($log_file, "           Immagine impostata come sharing image per post {$new_post_id}\n", FILE_APPEND);
                            }
                        }
                    }
                }
            }

            //file_put_contents($log_file, "           " . json_encode($new_post) . "\n", FILE_APPEND);
            $diff = date_diff(new \DateTime(), \DateTime::createFromFormat('Y-m-d H:i:s', $date_post));
            $c = get_term_by('id', $post_category, 'category');
            $row = array(
                date('Y-m-d H:i:s'),
                $date_post,
                $diff->format("%H:%I:%S"),
                $c->name,
                (string)$import_post->title,
                $import_post->guid,
                $_SERVER['SERVER_NAME'],
            );
            file_put_contents($csv_file, implode(';', $row) . "\n", FILE_APPEND);

            $tags = array('adnkronos', $feed_name); // Array of Tags to add
            wp_set_post_tags($new_post_id, $tags); // Set tags to Post

            return $new_post_id;
        }
    } catch (Exception $e) {
        file_put_contents($log_file, " Eccezione:  \n" . $e->getMessage(), FILE_APPEND);
    }

    return null;
}

function adnk_create_video_post_from_result(
    $import_post,
    $post_category,
    $post_status = 'publish',
    $post_owner_email,
    $feed_name,
    $check_no_import_image,
    $image_owner_email)
{
    /* Create post object */
    $log_file = dirname(__FILE__) . '/../logs/' . date('Ymd') . '_import.log';
    file_put_contents($log_file, " Valuto {$import_post['id']} \n", FILE_APPEND);
    $header = false;
    if (!file_exists(dirname(__FILE__) . '/../logs/' . date('Ymd') . '_' . $_SERVER['SERVER_NAME'] . '_import.csv')) {
        $header = true;
    }

    $csv_file = dirname(__FILE__) . '/../logs/' . date('Ymd') . '_' . $_SERVER['SERVER_NAME'] . '_import.csv';

    if ($header) {
        $row = array(
            'IMPORTATAZIONE',
            'PUBBLICAZIONE',
            'DIFFERENZA',
            'CATEGORIA',
            'TITOLO',
            'URL',
            'SERVER',
        );
        file_put_contents($csv_file, implode(';', $row) . "\n", FILE_APPEND);
    }
    try {

        $category = array($post_category); // category id

        $media = adnki_xml2array($import_post->media_group);

        $post_owner = get_user_by('email', $post_owner_email);

        $adkn_guid_post_feed = $import_post['id'];

        $fullstring = $import_post->published;
        $date_article = str_replace('T', ' ', $fullstring);
        $date_post = substr($date_article, 0, 19);

        $args = array(
            'post_type' => 'post',
            'post_status' => 'any',
            'posts_per_page' => -1,
            'meta_query' => array(
                array(
                    'key' => 'adkn_guid_post_feed',
                    'value' => $adkn_guid_post_feed,
                    'compare' => 'LIKE',
                ),
            ),
        );
        $query = new WP_Query($args);
        $hasdata = $query->get_posts();

        $count = count($hasdata);

        file_put_contents($log_file, "           {$import_post->title} | " . ($count == 0 ? "DA ELABORARE" : "già importato") . " \n", FILE_APPEND);
        if ($count == 0) {
            /** @var SimpleXMLElement $link */
            $link = $import_post->link;
            $attributes = $link->attributes();
            $post_content = $media['media_description'] . '
        
[embed width="600" height="400"]

' . $link->attributes()->href . '[/embed]';
            $new_post = array(
                'post_title' => $import_post->title,
                'post_content' => $post_content,
                'post_date' => $date_post,
                'post_status' => $post_status,
                'post_author' => $post_owner->ID,
                'post_category' => $category
            );
            // Insert the post into the database
            $new_post_id = wp_insert_post($new_post);
            $adkn_guid_post_feed = sanitize_text_field($adkn_guid_post_feed);
            update_post_meta($new_post_id, 'adkn_guid_post_feed', $adkn_guid_post_feed);
            $adkn_feed_category = sanitize_text_field($import_post->category->__toString());
            update_post_meta($new_post_id, 'adkn_feed_category', $adkn_feed_category);

            // assign featured image from url
            if (isset($media['media_thumbnail']['@attributes']['url'])) {
                $image_url = $media['media_thumbnail']['@attributes']['url'];
                $photo_name = $import_post->title;
                if ($image_url && substr($image_url, -3) != 'mp4' && $feed_name != 'video') {
                    if (!$check_no_import_image == 'on') {
                        // Try to upload and assign image - if it fails, delete the post
                        $image_result = adnk_upload_assign_image($new_post_id, $image_url, $photo_name, $image_owner_email);
                        if ($image_result === false) {
                            // Image upload failed, delete the post and return null
                            wp_delete_post($new_post_id, true);
                            file_put_contents($log_file, "           Video post {$new_post_id} eliminato a causa di errore nell'upload dell'immagine\n", FILE_APPEND);
                            return null;
                        } else {
                            // Image uploaded successfully, set as sharing image for Yoast SEO
                            if (defined('WPSEO_VERSION') && is_numeric($image_result)) {
                                $image_url_for_sharing = wp_get_attachment_url($image_result);
                                if ($image_url_for_sharing) {
                                    update_post_meta($new_post_id, '_yoast_wpseo_opengraph-image', $image_url_for_sharing);
                                    update_post_meta($new_post_id, '_yoast_wpseo_twitter-image', $image_url_for_sharing);
                                    file_put_contents($log_file, "           Immagine impostata come sharing image per video post {$new_post_id}\n", FILE_APPEND);
                                }
                            }
                        }
                    }
                }
            }

            //file_put_contents($log_file, "           " . json_encode($new_post) . "\n", FILE_APPEND);
            $diff = date_diff(new \DateTime(), \DateTime::createFromFormat('Y-m-d H:i:s', $date_post));
            $c = get_term_by('id', $post_category, 'category');
            $row = array(
                date('Y-m-d H:i:s'),
                $date_post,
                $diff->format("%H:%I:%S"),
                $c->name,
                (string)$import_post->title,
                $import_post->guid,
                $_SERVER['SERVER_NAME'],
            );
            file_put_contents($csv_file, implode(';', $row) . "\n", FILE_APPEND);

            $tags = array('adnkronos', $feed_name); // Array of Tags to add
            wp_set_post_tags($new_post_id, $tags); // Set tags to Post

            return $new_post_id;
        }
    } catch (Exception $e) {
        file_put_contents($log_file, " Eccezione:  \n" . $e->getMessage(), FILE_APPEND);
    }

    return null;
}

/*
function adnk_eventual_consistency($ids){

}
*/

/********************************************************** */
/* upload image from URL and assign as post featured image */
/********************************************************* */

function adnk_upload_assign_image($post_id, $image_url, $photo_name, $owner_image_email)
{
    $log_file = dirname(__FILE__) . '/../logs/' . gmdate('Ymd') . '_import.log';
    $title = get_the_title($post_id);

    $image_owner = get_user_by('email', $owner_image_email);

    try {
        $photo = new WP_Http();
        $photo = $photo->request($image_url, ['timeout' => 10]);

        // Check if the request failed (WP_Error or not an array)
        if (is_wp_error($photo)) {
            $error_message = $photo->get_error_message();
            file_put_contents($log_file, " Errore upload immagine per post {$post_id}: {$error_message}\n", FILE_APPEND);
            return false;
        }

        if (!is_array($photo)) {
            file_put_contents($log_file, " Errore upload immagine per post {$post_id}: Risposta non valida\n", FILE_APPEND);
            return false;
        }

        // Check HTTP response code
        if (isset($photo['response']['code']) && $photo['response']['code'] != 200) {
            file_put_contents($log_file, " Errore upload immagine per post {$post_id}: HTTP {$photo['response']['code']}\n", FILE_APPEND);
            return false;
        }

        // Check if body exists and is not empty
        if (empty($photo['body'])) {
            file_put_contents($log_file, " Errore upload immagine per post {$post_id}: Corpo risposta vuoto\n", FILE_APPEND);
            return false;
        }

        // Try to upload the file
        $upload_date = isset($photo['headers']['last-modified']) ?
            gmdate("Y-m", strtotime($photo['headers']['last-modified'])) :
            gmdate("Y-m");

        $attachment = wp_upload_bits(
            $photo_name . '.jpg',
            null,
            $photo['body'],
            $upload_date
        );

        // Check if wp_upload_bits failed
        if (isset($attachment['error']) && $attachment['error']) {
            file_put_contents($log_file, " Errore wp_upload_bits per post {$post_id}: {$attachment['error']}\n", FILE_APPEND);
            return false;
        }

        $filetype = wp_check_filetype(basename($attachment['file']), null);

        $postinfo = array(
            'post_mime_type' => $filetype['type'],
            'post_title' => $title . ' ',
            'post_content' => '',
            'post_status' => 'inherit',
            'post_author' => $image_owner->ID,
        );

        $filename = $attachment['file'];
        $attach_id = wp_insert_attachment($postinfo, $filename, $post_id);

        if (!$attach_id) {
            file_put_contents($log_file, " Errore wp_insert_attachment per post {$post_id}\n", FILE_APPEND);
            // Clean up uploaded file
            if (file_exists($filename)) {
                unlink($filename);
            }
            return false;
        }

        if (!function_exists('wp_generate_attachment_data')) {
            require_once(ABSPATH . "wp-admin" . '/includes/image.php');
        }

        $attach_data = wp_generate_attachment_metadata($attach_id, $filename);
        wp_update_attachment_metadata($attach_id, $attach_data);

        $thumbnail_result = set_post_thumbnail($post_id, $attach_id);

        if (!$thumbnail_result) {
            file_put_contents($log_file, " Warning: Impossibile impostare thumbnail per post {$post_id}\n", FILE_APPEND);
            // Don't return false here as the attachment was created successfully
        }

        file_put_contents($log_file, " Immagine caricata con successo per post {$post_id} (attachment ID: {$attach_id})\n", FILE_APPEND);
        return $attach_id; // Return attachment ID instead of just true

    } catch (Exception $e) {
        file_put_contents($log_file, " Eccezione upload immagine per post {$post_id}: " . $e->getMessage() . "\n", FILE_APPEND);
        return false;
    }
}


add_action('adki_add_cron_onceaday', 'adnk_import_invio_dati_statistici');
add_action('admin_action_adnkinvio', 'adnk_import_invio_dati_statistici');
/* invio dati statistici */


function adnk_import_invio_dati_statistici()
{

    $consent_send_statistical_data = get_adnk_settings_option('consent_send_statistical_data');

    if ($consent_send_statistical_data != 'on') {
        return;
    }
    if (!adnk_verify_site()) {
        return;
    }

    $array_dati = adnk_import_dati_statistici();
    $yesterday = getdate(time() - 86400);
    $yesterdaStr = $yesterday['year'] . '-' . $yesterday['mon'] . '-' . $yesterday['mday'];
    $site_url = get_home_url();
    $url = 'https://plugin.adnkronos.com/api/v1/stat/send';

    foreach ($array_dati as $category => $value) {

        $dati_ieri = array(
            'domain' => $site_url,
            'category' => $category,
            'date' => $yesterdaStr,
            'published' => $value['publish'],
            'imported' => $value['publish'] + $value['draft'],
        );
        /* chiamata per invio dati */
        $response = wp_remote_post($url, array(
            'method' => 'POST',
            'timeout' => 45,
            'redirection' => 5,
            'httpversion' => '1.1',
            'sslverify' => false,
            'blocking' => true,
            'headers' => array('Authorization' => 'adn83jhfk823rh2r'),
            'body' => json_encode($dati_ieri),
            'cookies' => array(),
        ));
    }

}

/*{
    "domain": "http://www.provadomanio.it",
    "date": "2022-06-30",
    "category": "sport",
    "imported": 36,
    "published": 12
} */
function adnk_import_dati_statistici()
{

    $yesterday = getdate(time() - 86400);
    $y_posts_ids = array();
    $agrs = array(
        'post_type' => 'post',
        'posts_per_page' => -1,
        'date_query' => array(
            array(
                'year' => $yesterday['year'],
                'month' => $yesterday['mon'],
                'day' => $yesterday['mday'],
            ),
        ),
    );
    $loop = new WP_Query($agrs);

    if ($loop->have_posts()) :
        while ($loop->have_posts()) : $loop->the_post();

            $categoria = get_post_meta(get_the_ID(), 'adkn_feed_category', true);

            if (!empty($categoria)) {
                if (!array_key_exists($categoria, $y_posts_ids)) {
                    $y_posts_ids[$categoria] = array();
                }

                if (get_post_status() == 'publish') {
                    $y_posts_ids[$categoria]['publish']++;
                } else {
                    $y_posts_ids[$categoria]['draft']++;
                }
            }

        endwhile;
    endif;

    return $y_posts_ids;
}


function adnk_verify_site()
{
    $log_file = dirname(__FILE__) . '/../logs/' . gmdate('Ymd') . '_import.log';
    $orario = (new DateTime())->format('Y-m-d H:i:s');

    $site_url = get_home_url();
    $url = ADNK_API_BASE_URL . '/api/v1/site/verify';
    $parameters = [
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 10,
        'httpversion' => '1.1',
        //'sslverify'   => false,
        'blocking' => true,
        'headers' => array('Content-Type' => 'application/json'),
        'body' => json_encode(array('domain' => $site_url))
    ];
    $response = wp_remote_post($url, $parameters);
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        file_put_contents($log_file,
            $orario . " Importazione non possibile per problema chiamata elenco feed: " . $error_message . " \n con parametri: " . json_encode($parameters) . "\n",
            FILE_APPEND);
        update_option('adn_site_active', 0, true);

        return false;
    } else {
        //var_dump($response);
        $body = $response['body'];
        $esito = json_decode($body);
        if ($esito->response == 'OK') {
            update_option('adn_site_active', 1, true);

            return true;
        }
        if ($esito->response == 'KO') {
            file_put_contents($log_file,
                $orario . " Importazione non possibile per problema autenticazione: KO \n con parametri: " . json_encode($parameters) . "\n",
                FILE_APPEND);
            update_option('adn_site_active', 0, true);

            return true;
        }

        update_option('adn_site_active', 1, true);

        return false;
    }
}

function adnk_feed_by_site()
{
    $log_file = dirname(__FILE__) . '/../logs/' . gmdate('Ymd') . '_import.log';
    $orario = (new DateTime())->format('Y-m-d H:i:s');

    $site_url = get_home_url();
    $url = ADNK_API_BASE_URL . '/api/v1/site/feeds';
    $parameters = [
        'method' => 'POST',
        'timeout' => 45,
        'redirection' => 10,
        'httpversion' => '1.1',
        //'sslverify'   => false,
        'blocking' => true,
        'headers' => array('Content-Type' => 'application/json'),
        'body' => json_encode(array('domain' => $site_url))
    ];
    $response = wp_remote_post($url, $parameters);
    if (is_wp_error($response)) {
        $error_message = $response->get_error_message();
        file_put_contents($log_file,
            $orario . " Importazione non possibile per problema chiamata elenco feed: " . $error_message . " \n con parametri: " . json_encode($parameters) . "\n",
            FILE_APPEND);
        //update_option( 'adn_site_active', 0, true );
        return false;
    } else {
        $body = $response['body'];
        $esito = json_decode($body, true);

        if ($esito['response'] == 'OK') {
            //update_option( 'adn_site_active', 1, true );
            file_put_contents($log_file,
                $orario . " Response OK\n",
                FILE_APPEND);
            return $esito['feeds'];
            //return true;
        }
        if ($esito['response'] == 'KO') {
            //update_option( 'adn_site_active', 0, true );
            file_put_contents($log_file,
                $orario . " Response KO \n " . json_encode($body) . "\n",
                FILE_APPEND);
            return false;
        }
        file_put_contents($log_file,
            $orario . " Response \n " . json_encode($body) . "\n",
            FILE_APPEND);
        //update_option( 'adn_site_active', 1, true );
        return false;
    }
}

add_action('admin_action_adnkverify', 'adnk_verify_site');


if (is_admin()) {
    //remove_action('admin_action_adnk_import_now', 'adnk_import_feed');
    add_action('admin_action_adnk_import_now', 'adnk_import_feed_by_button');
}

function adnk_import_now()
{
    $log_file = dirname(__FILE__) . '/../logs/' . gmdate('Ymd') . '_import.log';
    $orario = (new DateTime())->format('Y-m-d H:i:s');
    file_put_contents($log_file, $orario . " Inizio importazione in adnk_import_now()\n", FILE_APPEND);

    adnk_import_feed();

    //torno alla pagina chiamante
    //$url = wp_get_raw_referer();
    //wp_redirect( site_url() . '/wp-admin/edit.php' );
}


function adnk_import_tdm_get_string_between($string, $start, $end)
{
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) {
        return '';
    }
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;

    return substr($string, $ini, $len);
}

add_action('adki_add_delete_cron', 'adnk_delete_old_post');
add_action('admin_action_adnkdelete', 'adnk_delete_old_post');

function adnk_delete_old_post()
{
    $threshold = get_adnk_settings_option('selected_freq_cancel');

    //var_dump($threshold);
}

/**
 * Converts a YouTube XML feed into a structured array
 *
 * @param string $xml_string The XML string from YouTube feed
 *
 * @return array The structured array containing feed data
 */
function youtube_xml_to_array($xml_string)
{
    // Enable internal error handling for XML parsing
    libxml_use_internal_errors(true);

    // Load the XML string
    $xml = simplexml_load_string($xml_string);

    // Check if XML was parsed successfully
    if (!$xml) {
        $errors = [];
        foreach (libxml_get_errors() as $error) {
            $errors[] = $error->message;
        }

        return ['error' => 'Failed to parse XML', 'details' => $errors];
    }

    // Register namespaces
    $namespaces = $xml->getNamespaces(true);

    // Initialize the result array with channel information
    $result = [
        'channel' => [
            'title' => (string)$xml->title,
            'id' => (string)$xml->id,
            'link' => (string)$xml->link['href'],
            'author' => [
                'name' => (string)$xml->author->name,
                'uri' => (string)$xml->author->uri,
            ],
            'published' => (string)$xml->published,
        ],
        'entries' => [],
    ];

    // Process each entry (video)
    foreach ($xml->entry as $entry) {
        // Get media namespace
        $media = $entry->children($namespaces['media']);
        $img = ((string)$media->group->thumbnail->attributes()['url']);
        $yt = $entry->children($namespaces['yt']);

        // Create entry array
        $entry_data = [
            'id' => (string)$entry->id,
            'videoId' => (string)$yt->videoId,
            'channelId' => (string)$yt->channelId,
            'title' => (string)$entry->title,
            'link' => (string)$entry->link['href'],
            'author' => [
                'name' => (string)$entry->author->name,
                'uri' => (string)$entry->author->uri,
            ],
            'published' => (string)$entry->published,
            'updated' => (string)$entry->updated,
            'img' => $img,
            'description' => (string)$media->group->description,
        ];

        $result['entries'][] = $entry_data;
    }

    return $result;
}