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/citycomm-feed-importer/citycomm-feed-importer.php
<?php
/**
 * Plugin Name:       Citycomm Feed Importer
 * Plugin URI:        https://www.citycomm.it
 *
 * Description:       Legge i feed rss da un sito che ha installato il plugin per exporter
 * Version:           1.1.0
 * Author:            Ephraim Pepe
 * Author URI:        https://www.oimmei.com
 */


if (!defined('ABSPATH')) exit; // Exit if accessed directly

/* register style and script */
/* add_action( 'wp_enqueue_scripts', 'citycomm_register_script');

function citycomm_register_script(){
   wp_register_style( 'slider-style', plugin_dir_url( __FILE__ ) . '/css/slider-style.css');

   wp_register_script( 'functionjs', plugin_dir_url( __FILE__ ) . '/js/citycomm-function.js', array ( 'jquery' ), 1.1, true);
} */


// includo file di utitlity
include_once('inc/utility.php');
include_once('admin/option-panel.php');

const CITYCOMM_BASE_URL = 'https://www.corrieretoscano.it';

function citycomm_feed_importer()
{
    /* get option from option page */
    $basepath = realpath(dirname(__FILE__) . '/logs');
    if (!file_exists($basepath)) {
        mkdir($basepath);
    }
    $basepath = realpath($basepath);

    /* Create post object */
    $log_file = $basepath . '/'. date('Ymd') . '_import.log';
    if (!file_exists($log_file)) {
        fopen($log_file, "w");
    }
    $orario = (new DateTime())->format('Y-m-d H:i:s');
    file_put_contents($log_file, $orario . " Inizio importazione\n", FILE_APPEND);
    sleep(random_int(0, 9));
    $transient = get_transient('citycomm_import_running');
    if (!(false === $transient) && false) {
        file_put_contents($log_file, $orario . " Importazione non lanciata perchè entro i 180s dalla precedente\n", FILE_APPEND);
        $url = wp_get_raw_referer();
        wp_redirect($url);
        return;
    }

    set_transient('citycomm_import_running', 'running', 180);
    file_put_contents($log_file, $orario . " Avvio effettivo\n", FILE_APPEND);

    $post_ids_array = array();

    $selected_post_owner_email = get_citycomm_importer_option('selected_post_owner');
    $selected_image_owner_email = get_citycomm_importer_option('selected_image_owner');
    $check_no_image_import = get_citycomm_importer_option('check_no_image_import');

    $consent_send_statistical_data = get_citycomm_settings_option('consent_send_statistical_data');

    $feeds = getCitycommFeed();

    $feed_url_array = array();

    foreach ($feeds as $feedName => $feedInfo) {
        if ($feedInfo['checked']) {
            //file_put_contents($log_file, "Check feed: " . json_encode($feedInfo) . "\n ", FILE_APPEND);
            $feed_url_array[$feedName]['url'] = CITYCOMM_BASE_URL . '/feed' . $feedInfo['path'];
            $feed_url_array[$feedName]['status'] = $feedInfo['status'];
            $feed_url_array[$feedName]['category'] = $feedInfo['category'];
            $feed_url_array[$feedName]['place'] = isset($feedInfo['place']) ? $feedInfo['place'] : null;
            $feed_url_array[$feedName]['author'] = $feedInfo['author'];
        }
    }

    $feedJson = json_encode($feed_url_array);

    foreach ($feed_url_array as $key => $feed_argument) {
        file_put_contents($log_file, "Load feed: " . $feed_argument['url'] . "\n ", FILE_APPEND);

        $post_feed_result_array = citycomm_xml2array(citycomm_feed2xml($feed_argument['url']));

        /* creare i post della categoria giusta e nello stato selezionato */
        if (!isset($post_feed_result_array['channel']['item'])) {
            file_put_contents($log_file, "  No Posts\n", FILE_APPEND);
            //file_put_contents($log_file, $orario." Ricevuto feed:\n ".json_encode($post_feed_result_array)."\n", FILE_APPEND);
            continue;
        }

        file_put_contents($log_file, "  Posts: " . count($post_feed_result_array['channel']['item']) . "\n", FILE_APPEND);

        if (isset($post_feed_result_array['channel']['item']['link'])) {
            $post_feed_result_array['channel']['item'] = [json_decode(json_encode($post_feed_result_array['channel']['item']))];
        }

        foreach ($post_feed_result_array['channel']['item'] as $post) {
            // guid creare custom field e controllare se già esiste prima di importarlo
            $new_post_id = citycomm_create_post_from_result(
                $post,
                $feed_argument['category'],
                $feed_argument['status'],
                $feed_argument['author'] ?: $selected_post_owner_email,
                $key,
                $check_no_image_import,
                $feed_argument['author'] ?: $selected_image_owner_email,
                $feed_argument['place']
            );

            if (!is_null($new_post_id)) {
                $post_ids_array[] = $new_post_id;
            }

            //error_log($new_post_id);
        }
    }

    //citycomm_eventual_consistency($post_ids_array);

    //wp_redirect( site_url() . '/wp-admin/edit.php' );
    return $post_ids_array;
}

function citycomm_feed_all_importer()
{
    /* get option from option page */
    $log_file = dirname(__FILE__) . '/logs/' . date('Ymd') . '_import.log';
    $orario = (new DateTime())->format('Y-m-d H:i:s');
    file_put_contents($log_file, $orario . " Inizio importazione\n", FILE_APPEND);
    sleep(random_int(0, 9));
    $transient = get_transient('citycomm_import_running');
    if (!(false === $transient) && false) {
        file_put_contents($log_file, $orario . " Importazione non lanciata perchè entro i 180s dalla precedente\n", FILE_APPEND);
        $url = wp_get_raw_referer();
        wp_redirect($url);
        return;
    }

    set_transient('citycomm_import_running', 'running', 180);
    file_put_contents($log_file, $orario . " Avvio effettivo\n", FILE_APPEND);

    $post_ids_array = array();

    $selected_post_owner_email = get_citycomm_importer_option('selected_post_owner');
    $selected_image_owner_email = get_citycomm_importer_option('selected_image_owner');
    $check_no_image_import = get_citycomm_importer_option('check_no_image_import');

    $consent_send_statistical_data = get_citycomm_settings_option('consent_send_statistical_data');

    $feeds = getCitycommFeed();

    $feed_url_array = array();

    foreach ($feeds as $feedName => $feedInfo) {
        if ($feedInfo['checked']) {
            //file_put_contents($log_file, "Check feed: " . json_encode($feedInfo) . "\n ", FILE_APPEND);
            $feed_url_array[$feedName]['url'] = CITYCOMM_BASE_URL . '/feed' . $feedInfo['path'];
            $feed_url_array[$feedName]['status'] = $feedInfo['status'];
            $feed_url_array[$feedName]['category'] = $feedInfo['category'];
            $feed_url_array[$feedName]['place'] = isset($feedInfo['place']) ? $feedInfo['place'] : null;
            $feed_url_array[$feedName]['author'] = $feedInfo['author'];
        }
    }

    $feedJson = json_encode($feed_url_array);

    foreach ($feed_url_array as $key => $feed_argument) {
        $nextPage = true;
        $page = 1;
        while ($nextPage) {
            file_put_contents($log_file, "Load feed: " . $feed_argument['url'] . "/pagina/" . $page . "\n ", FILE_APPEND);

            $post_feed_result_array = citycomm_xml2array(citycomm_feed2xml($feed_argument['url']. "/pagina/" . $page));

            /* creare i post della categoria giusta e nello stato selezionato */
            if (!isset($post_feed_result_array['channel']['item']) || count($post_feed_result_array['channel']['item']) == 0) {
                file_put_contents($log_file, "  No Posts\n", FILE_APPEND);
                $nextPage = false;
                continue;
            }

            file_put_contents($log_file, "  Posts: " . count($post_feed_result_array['channel']['item']) . "\n", FILE_APPEND);

            if (isset($post_feed_result_array['channel']['item']['link'])) {
                $post_feed_result_array['channel']['item'] = [json_decode(json_encode($post_feed_result_array['channel']['item']))];
            }

            foreach ($post_feed_result_array['channel']['item'] as $post) {
                // guid creare custom field e controllare se già esiste prima di importarlo
                $new_post_id = citycomm_create_post_from_result(
                    $post,
                    $feed_argument['category'],
                    $feed_argument['status'],
                    $feed_argument['author'] ?: $selected_post_owner_email,
                    $key,
                    $check_no_image_import,
                    $feed_argument['author'] ?: $selected_image_owner_email,
                    $feed_argument['place']
                );

                if (!is_null($new_post_id)) {
                    $post_ids_array[] = $new_post_id;
                }

                //error_log($new_post_id);
            }

            $page++;
        }
    }

    //citycomm_eventual_consistency($post_ids_array);

    //wp_redirect( site_url() . '/wp-admin/edit.php' );
    return $post_ids_array;
}


/* set cron job */
add_filter('cron_schedules', 'citycomm_import_cron_schedule');

function citycomm_import_cron_schedule($schedules)
{
    $schedules['halfhourly'] = array(
        'interval' => 1800,
        'display' => __('halfhourly'));

    $schedules['twohourly'] = array(
        'interval' => 7200,
        'display' => __('twohourly'));

    $schedules['fourhourly'] = array(
        'interval' => 14400,
        'display' => __('fourhourly'));

    $schedules['sixhourly'] = array(
        'interval' => 21600,
        'display' => __('sixhourly'));

    return $schedules;
}

register_activation_hook(__FILE__, 'citycomm_import_activation');

function citycomm_import_activation($selected_freq_import = 'daily')
{

    wp_clear_scheduled_hook('citycomm_import_event');

    if (!wp_next_scheduled('citycomm_import_event')) {
        $date = date("h:i:sa", strtotime('+5 minutes'));
        wp_schedule_event(strtotime($date), $selected_freq_import, 'citycomm_import_event');
    }

    /* cron invio dati statistici */
    // Schedule an action if it's not already scheduled
    if (!wp_next_scheduled('citycomm_add_cron_onceaday')) {
        wp_schedule_event(time(), 'daily', 'citycomm_add_cron_onceaday');
    }

}

add_action('citycomm_import_event', 'citycomm_feed_importer');
add_action('citycomm_import_all_event', 'citycomm_feed_all_importer');

function getCitycommFeed()
{
    $log_file = dirname(__FILE__) . '/logs/' . date('Ymd') . '_admin.log';

    // ODC: da sostituire con il parse di <CITYCOMM_BASE_URL>/feed/help
    file_put_contents($log_file, "Load feed: " . CITYCOMM_BASE_URL . "/feed/help\n ", FILE_APPEND);
    $post_feed_result_array = citycomm_xml2array(citycomm_feed2xml(CITYCOMM_BASE_URL . "/feed/help"));

    $feeds = json_decode(json_encode($post_feed_result_array['channel']['item']), true);

    $places = [];
    $categories = [];
    $authors = [
        'Rubriche' => '/rubriche',
    ];
    $adnCategories = [
        'Ambiente ed Energia' => '/rss/notizie/ambiente-energia',
        'Lavoro' => '/rss/notizie/lavoro',
        'Tecnologia' => '/rss/notizie/tecnologia',
        'Gusto' => '/rss/notizie/gusto',
        'Salute e Benessere' => '/rss/notizie/salute-benessere',
        'Fintech' => '/rss/notizie/fintech',
        'Motori' => '/rss/notizie/motori',
        'Facilitalia' => '/rss/notizie/facilitalia',
        'Immediapress' => '/rss/notizie/immediapress',
        'Video News' => '/rss/notizie/video-news',
    ];

    foreach ($feeds as $feed) {
        // file_put_contents($log_file, "    " . $feed['category'] . " - " . json_encode($feed) .  "\n ", FILE_APPEND);
        switch ($feed['category']) {
            case 'category':
                if (!array_key_exists($feed['title'], $adnCategories) && $feed['title'] !== 'Uncategorized') {
                    //file_put_contents($log_file, "    Categoria: " . $feed['title'] . "\n ", FILE_APPEND);
                    $categories[$feed['title']] = str_replace('/feed', '', trim($feed['link']));
                }
                break;
            case 'place':
                //file_put_contents($log_file, "    Luogo: " . $feed['title'] . "\n ", FILE_APPEND);
                $places[$feed['title']] = str_replace('/feed', '', trim($feed['link']));
                break;
            case 'newspaper_column_author':
                //file_put_contents($log_file, "    Autore: " . $feed['title'] . "\n ", FILE_APPEND);
                $authors[$feed['title']] = str_replace('/feed', '', trim($feed['link']));
                break;
        }
    }

    $feeds = array();
    foreach ($places as $place => $placeKey) {
        foreach ($categories as $category => $categoryKey) {
            $key = str_replace('/', '_', $placeKey) . str_replace('/', '_', $categoryKey);
            $feeds[$place . ' ' . $category] = array(
                'key' => $key,
                'path' => "{$placeKey}{$categoryKey}",
                'checked' => get_citycomm_importer_option("url{$key}_feed"),
                'status' => esc_html(get_citycomm_importer_option("selected{$key}_post_status")),
                'category' => esc_html(get_citycomm_importer_option("selected{$key}_feed_category")),
                'place' => esc_html(get_citycomm_importer_option("selected{$key}_feed_place")),
                'author' => esc_html(get_citycomm_importer_option("selected{$key}_post_author")),
                'tab' => "Categorie {$place}"
            );
        }
    }
    foreach ($places as $place => $placeKey) {
        $key = str_replace('/', '_', $placeKey);
        $feeds[$place] = array(
            'key' => $key,
            'path' => "{$placeKey}",
            'checked' => get_citycomm_importer_option("url{$key}_feed"),
            'status' => esc_html(get_citycomm_importer_option("selected{$key}_post_status")),
            'category' => esc_html(get_citycomm_importer_option("selected{$key}_feed_category")),
            'place' => esc_html(get_citycomm_importer_option("selected{$key}_feed_place")),
            'author' => esc_html(get_citycomm_importer_option("selected{$key}_post_author")),
            'tab' => "Località"
        );
    }
    foreach ($categories as $category => $categoryKey) {
        $key = str_replace('/', '_', $categoryKey);
        $feeds[$category] = array(
            'key' => $key,
            'path' => "{$categoryKey}",
            'checked' => get_citycomm_importer_option("url{$key}_feed"),
            'status' => esc_html(get_citycomm_importer_option("selected{$key}_post_status")),
            'category' => esc_html(get_citycomm_importer_option("selected{$key}_feed_category")),
            'place' => esc_html(get_citycomm_importer_option("selected{$key}_feed_place")),
            'author' => esc_html(get_citycomm_importer_option("selected{$key}_post_author")),
            'tab' => "Categorie"
        );
    }
    foreach ($authors as $name => $authorKey) {
        $key = str_replace('/', '_', $authorKey);
        $feeds[$name] = array(
            'key' => $key,
            'path' => $authorKey,
            'checked' => get_citycomm_importer_option("url{$key}_feed"),
            'status' => esc_html(get_citycomm_importer_option("selected{$key}_post_status")),
            'category' => esc_html(get_citycomm_importer_option("selected{$key}_feed_category")),
            'place' => esc_html(get_citycomm_importer_option("selected{$key}_feed_place")),
            'author' => esc_html(get_citycomm_importer_option("selected{$key}_post_author")),
            'tab' => "Autori"
        );
    }
    foreach ($adnCategories as $name => $categoryKey) {
        $key = str_replace('/', '_', $categoryKey);
        $feeds[$name] = array(
            'key' => $key,
            'path' => $categoryKey,
            'checked' => get_citycomm_importer_option("url{$key}_feed"),
            'status' => esc_html(get_citycomm_importer_option("selected{$key}_post_status")),
            'category' => esc_html(get_citycomm_importer_option("selected{$key}_feed_category")),
            'place' => esc_html(get_citycomm_importer_option("selected{$key}_feed_place")),
            'author' => esc_html(get_citycomm_importer_option("selected{$key}_post_author")),
            'tab' => "ADN Kronos"
        );
    }

    return $feeds;
}