File: /var/www/html/wp-content/plugins/citycomm-feed-importer/inc/utility.php
<?php
/***************************************************** */
// Function for get XML from feed and convert in array
/**************************************************** */
function citycomm_feed2xml($url)
{
$log_file = dirname(__FILE__) . '/../logs/' . date('Ymd') . '_import.log';
$response_xml_data = false;
$clientHttp = new WP_Http();
$response = $clientHttp->request($url);
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 citycomm_xml2array($xmlObject, $out = array())
{
$log_file = dirname(__FILE__) . '/../logs/' . date('Ymd') . '_import.log';
foreach ((array)$xmlObject as $index => $node) {
$out[$index] = (is_object($node)) ? citycomm_xml2array($node) : $node;
}
//file_put_contents($log_file, " Lines: " . count($out). "\n", FILE_APPEND);
return $out;
}
/* create post from Feed */
function citycomm_create_post_from_result(
$import_post,
$post_category,
$post_status,
$post_owner_email,
$feed_name,
$check_no_import_image,
$image_owner_email,
$place = null
)
{
$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");
}
$header = false;
$csv_file = $basepath . '/' . date('Ym') . '_' . $_SERVER['SERVER_NAME'] . '_import.csv';
if (!file_exists($csv_file)) {
$header = true;
fopen($csv_file, "w");
}
if ($header) {
$row = array(
'IMPORTATAZIONE',
'PUBBLICAZIONE',
'DIFFERENZA',
'CATEGORIA',
'TITOLO',
'URL',
'SERVER',
);
file_put_contents($csv_file, implode(';', $row) . "\n", FILE_APPEND);
}
$c = null;
$category = array($post_category); // category id
if ($import_post->type != 'oi_rubrica' && (null == $post_category || '' == $post_category || 1 == $post_category)) {
if (is_array($import_post->category)) {
$category = array();
foreach($import_post->category as $cName) {
$c = get_term_by('name', $import_post->category, 'category');
$category[] = $c->term_id;
}
} else {
$c = get_term_by('name', $import_post->category, 'category');
$category = array($c->term_id);
}
}
//file_put_contents( $log_file, " Categorie: " . json_encode($category) . " \n", FILE_APPEND );
// Modifica della selezione dell'autore
$post_owner = get_user_by('email', (string)$import_post->authorEmail);
// Se l'email non esiste tra gli utenti, usa l'email passata come parametro
if (!$post_owner) {
$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));
$old_guid_post_feed = isset ($import_post->oldGuid) ? trim(substr((string)$import_post->oldGuid, strpos((string)$import_post->oldGuid, "_") + 1)) : false;
$fullstring = $import_post->pubDate;
$date_article = citycomm_import_tdm_get_string_between($fullstring, ',', '+');
$date_post = date('Y-m-d H:i:s', strtotime($date_article));
$new_post_id = '';
global $wpdb;
$hasdata = $wpdb->get_results("select * from $wpdb->postmeta where meta_key IN ('citycomm_guid_post_feed', 'adkn_guid_post_feed') and meta_value='$adkn_guid_post_feed'");
$count = count($hasdata);
if ($old_guid_post_feed && $count == 0) {
$hasdata = $wpdb->get_results("select * from $wpdb->postmeta where meta_key='adkn_guid_post_feed' and meta_value='$old_guid_post_feed'");
$count = count($hasdata);
}
file_put_contents($log_file, " Verifica ID {$import_post->guid}: '{$import_post->title}' = {$count}\n", FILE_APPEND);
if ($count == 0) {
try {
file_put_contents($log_file, " Importazione '{$import_post->title}'\n", FILE_APPEND);
$post_content = '<p>' . $import_post->description . '</p>';
$post_content .= '<p><em>' . $import_post->author . '</em></p>';
$enclosures = $import_post->enclosure;
if (!is_array($enclosures)) {
$enclosures = [$enclosures];
}
$tags = $import_post->tag;
if (!is_array($tags)) {
$tags = [$tags];
}
foreach ($enclosures as $enclosure) {
$enclosure = citycomm_xml2array($enclosure)['@attributes'];
// if ( $feed_name == 'video'){
if ($enclosure['type'] == 'video/mp4') {
@set_time_limit(120);
$video_url = $enclosure['url'];
file_put_contents($log_file, " Video enclosure: " . json_encode($enclosure) . "\n", FILE_APPEND);
$tmp = download_url($video_url);
$file_array = array(
'name' => basename($video_url),
'tmp_name' => $tmp
);
if (is_wp_error($tmp)) {
file_put_contents($log_file, " Errore A: " . __LINE__ . "\n\n", FILE_APPEND);
@unlink($file_array['tmp_name']);
return;
}
$id = media_handle_sideload($file_array, 0); //download the file (0 represents the Post ID. (At this point in time I don't want it to be attached to a post so I've left it as 0)
// Check for handle sideload errors.
if (is_wp_error($id)) {
file_put_contents($log_file, " Errore B: " . __LINE__ . "\n\n", FILE_APPEND);
@unlink($file_array['tmp_name']);
return;
} else {
file_put_contents($log_file, " Elaborazione video: {$id}\n", FILE_APPEND);
$attachment_url = wp_get_attachment_url($id);
$attachment_file = substr($attachment_url, strpos($attachment_url, '/', 10));
$attachment_path = realpath(__DIR__ . "/../../../.." . $attachment_file);
$attachment_size = filesize($attachment_path);
$filename = basename($attachment_path, '.mp4');
file_put_contents($log_file, " Delete {$filename}: {$attachment_size}\n", FILE_APPEND);
unlink($attachment_path);
}
}
}
$excerpt = $import_post->excerpt;
$metaInput = array(
'oimmei' => true,
'no_home' => $import_post->no_home == 'true',
);
if (defined('WPSEO_VERSION')) {
// Campi base SEO
if (!empty($import_post->yoast_seo->title)) {
$metaInput['_yoast_wpseo_title'] = (string)$import_post->yoast_seo->title;
}
if (!empty($import_post->yoast_seo->metadesc)) {
$metaInput['_yoast_wpseo_metadesc'] = (string)$import_post->yoast_seo->metadesc;
$metaInput['_yoast_wpseo_opengraph-description'] = (string)$import_post->yoast_seo->metadesc;
$metaInput['_yoast_wpseo_twitter-description'] = (string)$import_post->yoast_seo->metadesc;
}
if (!empty($import_post->yoast_seo->focuskw)) {
$metaInput['_yoast_wpseo_focuskw'] = (string)$import_post->yoast_seo->focuskw;
}
if (!empty($import_post->yoast_seo->canonical)) {
$metaInput['_yoast_wpseo_canonical'] = (string)$import_post->yoast_seo->canonical;
}
// Campi Open Graph
if (!empty($import_post->yoast_seo->opengraph->title)) {
$metaInput['_yoast_wpseo_opengraph-title'] = (string)$import_post->yoast_seo->opengraph->title;
}
if (!empty($import_post->yoast_seo->opengraph->description)) {
$metaInput['_yoast_wpseo_opengraph-description'] = (string)$import_post->yoast_seo->opengraph->description;
}
if (!empty($import_post->yoast_seo->opengraph->image)) {
$metaInput['_yoast_wpseo_opengraph-image'] = (string)$import_post->yoast_seo->opengraph->image;
}
// Campi Yoast Pro (se disponibile)
if (defined('WPSEO_PREMIUM_PLUGIN_FILE')) {
if (!empty($import_post->yoast_seo->pro->cornerstone)) {
$metaInput['_yoast_wpseo_is_cornerstone'] = $import_post->yoast_seo->pro->cornerstone === 'true' ? 1 : 0;
}
if (!empty($import_post->yoast_seo->pro->schema_type)) {
$metaInput['_yoast_wpseo_schema_type'] = (string)$import_post->yoast_seo->pro->schema_type;
}
if (!empty($import_post->yoast_seo->pro->social->facebook)) {
$metaInput['_yoast_wpseo_facebook'] = (string)$import_post->yoast_seo->pro->social->facebook;
}
if (!empty($import_post->yoast_seo->pro->social->twitter)) {
$metaInput['_yoast_wpseo_twitter'] = (string)$import_post->yoast_seo->pro->social->twitter;
}
}
}
$new_post = array(
'post_type' => (string)$import_post->type,
'post_title' => (string)$import_post->title,
'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,
);
//file_put_contents($log_file, " " . json_encode($new_post) . "\n", FILE_APPEND);
$cc = null;
if (count($category) > 0) {
$cc = get_term_by('term_id', $category[0], 'category');
}
$diff = date_diff(new \DateTime(), \DateTime::createFromFormat('Y-m-d H:i:s', $date_post));
$row = array(
date('Y-m-d H:i:s'), //'IMPORTATAZIONE',
$date_post, //'PUBBLICAZIONE',
$diff->format("%a"), //'DIFFERENZA',
$cc ? $cc->name : 'Rubrica', //'CATEGORIA',
(string)$import_post->title, //'TITOLO',
$import_post->guid, //'URL',
$_SERVER['SERVER_NAME'], //'SERVER',
);
file_put_contents($csv_file, implode(';', $row) . "\n", FILE_APPEND);
// Insert the post into the database
$new_post_id = wp_insert_post($new_post);
file_put_contents($log_file, " post_id = {$new_post_id} \n", FILE_APPEND);
$adkn_guid_post_feed = sanitize_text_field($adkn_guid_post_feed);
update_post_meta($new_post_id, 'citycomm_guid_post_feed', $adkn_guid_post_feed);
update_post_meta($new_post_id, 'citycomm_post_last_update', is_string($import_post->modDate) ? $import_post->modDate : $import_post->modDate->__toString());
$adkn_feed_category = sanitize_text_field($import_post->category->__toString());
update_post_meta($new_post_id, 'citycomm_feed_category', $adkn_feed_category);
// assign feautures image from url
foreach ($enclosures as $enclosure) {
$enclosure = citycomm_xml2array($enclosure)['@attributes'];
$image_url = $enclosure['url'];
$photo_name = $import_post->title;
if (substr($image_url, -3) != 'mp4') { // && $feed_name != 'video') {
if (!$check_no_import_image == 'on') {
citycomm_upload_assign_image($new_post_id, $image_url, $photo_name, $image_owner_email);
}
}
}
$tags = array_merge($tags, array($feed_name)); // Array of Tags to add
wp_set_post_tags($new_post_id, $tags); // Set tags to Post
if (isset($place)) {
wp_set_post_terms($new_post_id, $place, 'places');
}
if ($import_post->type == 'oi_rubrica') {
file_put_contents($log_file, " category {$import_post->type}: " . json_encode($import_post->category) . "\n", FILE_APPEND);
$category = get_term_by('name', $import_post->category, 'oi_rubrica_category');
wp_set_post_terms($new_post_id, $category->term_id, 'oi_rubrica_category');
}
return $new_post_id;
} catch (Exception $e) {
file_put_contents($log_file, " Errore {$e->getMessage()} \n", FILE_APPEND);
}
} else {
// Here we check if the post has been updated
$existing_post_id = $hasdata[0]->post_id;
$existing_last_update = get_post_meta($existing_post_id, 'citycomm_post_last_update', true);
if ($existing_last_update != $import_post->modDate) {
file_put_contents($log_file, " Aggiornamento post '{$import_post->title}'\n", FILE_APPEND);
// Update post content
$post_content = '<p>' . $import_post->description . '</p>';
$post_content .= '<p><em>' . $import_post->author . '</em></p>';
$updated_post = array(
'ID' => $existing_post_id,
'post_title' => (string)$import_post->title,
'post_content' => $post_content,
'post_excerpt' => $import_post->excerpt,
);
wp_update_post($updated_post);
// Update post meta
update_post_meta($existing_post_id, 'citycomm_post_last_update', is_string($import_post->modDate) ? $import_post->modDate : $import_post->modDate->__toString());
// Update categories if needed
if ($import_post->type != 'oi_rubrica' && (null == $post_category || '' == $post_category || 1 == $post_category)) {
if (is_array($import_post->category)) {
$category = array();
foreach($import_post->category as $cName) {
$c = get_term_by('name', $import_post->category, 'category');
$category[] = $c->term_id;
}
} else {
$c = get_term_by('name', $import_post->category, 'category');
$category = array($c->term_id);
}
wp_set_post_categories($existing_post_id, $category);
}
// Update tags
$tags = $import_post->tag;
if (!is_array($tags)) {
$tags = [$tags];
}
$tags = array_merge($tags, array($feed_name));
wp_set_post_tags($existing_post_id, $tags);
// Update featured image if needed
if (!$check_no_import_image == 'on') {
$enclosures = $import_post->enclosure;
if (!is_array($enclosures)) {
$enclosures = [$enclosures];
}
foreach ($enclosures as $enclosure) {
$enclosure = citycomm_xml2array($enclosure)['@attributes'];
$image_url = $enclosure['url'];
$photo_name = $import_post->title;
if (substr($image_url, -3) != 'mp4') {
citycomm_upload_assign_image($existing_post_id, $image_url, $photo_name, $image_owner_email);
break; // Only update the first image
}
}
}
file_put_contents($log_file, " Post aggiornato: ID {$existing_post_id}\n", FILE_APPEND);
} else {
file_put_contents($log_file, " Nessun aggiornamento necessario per '{$import_post->title}'\n", FILE_APPEND);
}
}
return null;
}
/*
function citycomm_eventual_consistency($ids){
}
*/
/********************************************************** */
/* upload image from URL and assign as post feauture image */
/********************************************************* */
function citycomm_upload_assign_image($post_id, $image_url, $photo_name, $owner_image_email)
{
$title = get_the_title($post_id);
$image_owner = get_user_by('email',$owner_image_email);
$photo = new WP_Http();
$photo = $photo->request($image_url);
if (is_array($photo)) {
$attachment = wp_upload_bits($photo_name . '.jpg', null, $photo['body'], date("Y-m", strtotime($photo['headers']['last-modified'])));
$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 (!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);
set_post_thumbnail($post_id, $attach_id);
if (defined('WPSEO_VERSION')) {
// Imposta l'immagine caricata come immagine di condivisione per Yoast
update_post_meta($post_id, '_yoast_wpseo_opengraph-image', wp_get_attachment_image_src($attach_id, 'full')[0]);
update_post_meta($post_id, '_yoast_wpseo_twitter-image', wp_get_attachment_image_src($attach_id, 'full')[0]);
}
}
}
add_action('citycomm_add_cron_onceaday', 'citycomm_import_invio_dati_statistici');
add_action('admin_action_citycommnvio', 'citycomm_import_invio_dati_statistici');
/* invio dati statistici */
function citycomm_import_invio_dati_statistici()
{
$consent_send_statistical_data = get_citycomm_settings_option('consent_send_statistical_data');
if ($consent_send_statistical_data != 'on') {
return;
}
if (!citycomm_verify_site()) {
return;
}
$array_dati = citycomm_import_dati_statistici();
$yesterday = getdate(time() - 86400);
$yesterdaStr = $yesterday['year'] . '-' . $yesterday['mon'] . '-' . $yesterday['mday'];
$site_url = get_home_url();
$url = 'https://plugin.citycommronos.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 citycomm_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 citycomm_verify_site()
{
$site_url = get_home_url();
$url = 'https://plugin.citycommronos.com/api/v1/site/verify';
$response = wp_remote_post($url, array(
'method' => 'POST',
'timeout' => 45,
'redirection' => 5,
'httpversion' => '1.1',
//'sslverify' => false,
'blocking' => true,
'headers' => array(),
'body' => array('domain' => $site_url),
'cookies' => array()
));
//var_dump($response);
if (is_wp_error($response)) {
$error_message = $response->get_error_message();
update_option('adn_site_active', 0, true);
return false;
} else {
$body = $response['body'];
$esito = json_decode($body);
if ($esito->response == 'OK') {
update_option('adn_site_active', 1, true);
return true;
}
if ($esito->response == 'KO') {
update_option('adn_site_active', 0, true);
return true;
}
update_option('adn_site_active', 1, true);
return false;
}
}
add_action('admin_action_citycommverify', 'citycomm_verify_site');
if (is_admin()) {
remove_action('admin_action_citycomm_import_now', 'citycomm_feed_importer');
add_action('admin_action_citycomm_import_now', 'citycomm_feed_importer');
remove_action('admin_action_citycomm_import_all', 'citycomm_feed_all_importer');
add_action('admin_action_citycomm_import_all', 'citycomm_feed_all_importer');
}
function citycomm_import_now()
{
$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 in citycomm_import_now()\n", FILE_APPEND);
citycomm_feed_importer();
//torno alla pagina chiamante
//$url = wp_get_raw_referer();
//wp_redirect( site_url() . '/wp-admin/edit.php' );
}
function citycomm_import_all()
{
$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 in citycomm_import_all()\n", FILE_APPEND);
citycomm_feed_all_importer();
//torno alla pagina chiamante
//$url = wp_get_raw_referer();
//wp_redirect( site_url() . '/wp-admin/edit.php' );
}
function citycomm_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);
}