Skip to content

Instantly share code, notes, and snippets.

@bulini
Created October 4, 2018 08:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bulini/7ab42ccaf4725b858ccc1abcd78eaded to your computer and use it in GitHub Desktop.
Save bulini/7ab42ccaf4725b858ccc1abcd78eaded to your computer and use it in GitHub Desktop.
import
<?php
/**
*
*/
class FeedImport
{
private $xml_url;
function __construct()
{
add_action( 'rest_api_init', array( $this,'import_routes' ));
add_filter('views_edit-post', array( $this, 'import_button'));
add_action('admin_enqueue_scripts', array($this,'feed_assets'));
add_action('wp_ajax_publish_feeds', array($this,'publish_feeds'));
add_action('wp_ajax_feed_import', array($this,'feed_import'));
// Register the new dashboard widget with the 'wp_dashboard_setup' action
add_action('wp_dashboard_setup', array($this,'add_dashboard_widgets'));
}
public function feed_assets() {
wp_enqueue_script('feed-js', get_stylesheet_directory_uri() . '/assets/js/feed-app.js', array(
'jquery'
));
wp_localize_script('feed-js', 'feed_data', array(
'ajaxurl' => admin_url('admin-ajax.php') ,
'templateUrl' => get_stylesheet_directory_uri(),
'nonce' => wp_create_nonce('feed-nonce')
));
}
/**
* Rotte x importare e pubblicare i pdf
* @return [type] [description]
*/
public function import_routes(){
//rotta per importare TUTTO
register_rest_route( 'pressroom-import/v1', '/import', array(
'methods' => 'GET',
'callback' => array($this,'feed_import')
) );
//rotta x pubblicare e associare i PDF!
register_rest_route( 'pressroom-import/v1', '/publish', array(
'methods' => 'GET',
'callback' => array($this,'publish_feeds')
) );
}
/**
* Importa i feed ciclando il post type feed
* @param string $url
* @return integer [id del pdf creato]
*/
public function feed_import() {
$args = array(
'post_type' => 'feed',
'post_status' => 'publish'
);
$feeds = get_posts($args);
foreach($feeds as $feed) {
$this->parse_feed($feed->ID);
}
}
/**
* parse_feed salva i feed in articoli
* @param int $id del feed
* @return
*/
public function parse_feed($xml_id){
$feed_url = get_post_meta( $xml_id, 'rss_feed',true);
//$url= 'http://cercanotizie3.mimesi.com/Cercanotizie3/transform?code=c67fccfb-e6bd-11e6-818e-3ca82a1f2b60';
$xml = simplexml_load_file($feed_url) or die("feed not loading");
$i = 0;
foreach($xml->channel->item as $item):
$i++;
$data['feed_id'] = $xml_id;
$data['title'] = $item->title;
$data['description'] = $item->description;
$data['author'] = $item->author;
//$data['pdf_server'] = 'http://media.mimesi.com/cacheServer/servlet/CropServer';
//esplodo il link originale x recuperare le vars
$links = explode('&', $item->link);
//recupero il valore di idarticle=1342542
$id_article = explode('=', $links[1]);
//contiene la prima parte del link
$data['pdf_date'] = $links[0];
$data['idArticle'] = $id_article[1];
$data['authCookie'] = $links[2];
$post_id = $this->create_or_update_post($data);
//$this->save_pdf($item->link, $post_id);
foreach($item->category as $category):
$this->update_taxonomy($post_id, $category['domain'], $category);
endforeach;
//completo con tassonomia author
$this->update_taxonomy($post_id, 'author', $item->author);
endforeach;
$answer['message'] = 'Sono stati importati '.$i.' feed';
return $answer;
}
function import_button($views){
$views['import'] = '<a href="#" class="primary" id="feed-import">Importa</a>';
$views['publish_feeds'] = '<a href="#" class="primary" id="feed-publish">Pubblica Bozze</a>';
return $views;
}
/**
* [create_or_update_post]
* crea o aggiorna un post tramite idArticle
* @param [array] $data [array dati]
* @return [post_id] [description]
*/
public function create_or_update_post( $data ) {
$idArticle = $data['idArticle'];
//torno false in caso di $art_id null
if(!$idArticle ) return new WP_Error( 'idArticle_null', 'Non hai passato il parametro idArticle', array( 'status' => 404 ) );
$post_id = $this->id_imported( $idArticle, 'post');
// se non ho un post ID creo l'articolo in DRAFT
if( !$post_id ):
$post = array(
'post_title' => wp_strip_all_tags($data['title']),
'post_name' => wp_unique_post_slug( sanitize_title( $data['title'] ) ),
'post_content' => $data['description'],
'post_status' => 'draft'
);
//inserisco
$post_id = wp_insert_post( $post, true );
//altrimenti aggiorno articolo esistente
else:
//mantengo il post status invariato in caso di PUBLISH..
$post = array(
'post_title' => wp_strip_all_tags($data['title']),
'post_name' => wp_unique_post_slug( sanitize_title( $data['title'] ) ),
'post_content' => $data['description'],
);
// aggiorno l'articolo esistente
$post['ID'] = $post_id;
$post_id = wp_update_post( $post, true );
endif;
if( $data['idArticle'] ) {
update_post_meta( $post_id, 'idArticle', $data['idArticle']);
}
if( $data['pdf_date'] ) {
if(!get_post_meta($post_id,'pdf_url',true)){
update_post_meta( $post_id, 'pdf_url', $data['pdf_date'].'&idArticle='.$data['idArticle'].'&'.$data['authCookie']);
}
}
if( $data['feed_id'] ) {
//prendo array dei feed dove presente l articolo
//se gia ce un id lo pusho all array
$current_feed = unserialize(get_post_meta( $post_id, 'feed_id', true));
if(empty($current_feed)) { $current_feed = []; }
$new_feed = (int) $data['feed_id'];
array_push($current_feed, $new_feed);
update_post_meta( $post_id, 'feed_id', serialize($current_feed));
}
return $post_id;
}
/**
* [attach_pdf description]
* @param [type] $post_id [description]
* @return [type] [description]
*/
public function publish_feeds() {
// recupero i post che devo ancora pubblicare
$args = array(
'post_type' => 'post',
'post_status' => 'draft',
'posts_per_page' => 10,
'relation' => 'AND', // Optional, defaults to "AND"
array(
'key' => 'pdf_url',
'value' => site_url(),
'compare' => 'NOT LIKE'
)
);
$drafts = get_posts($args);
$ids = wp_list_pluck( $drafts, 'ID');
// aggiorno lo status dei post così da non sovrappormi con eventuali altri run
//print_r($ids);
//echo implode(",", $ids); //die();
global $wpdb;
$query = $wpdb->prepare( "UPDATE `{$wpdb->posts}` SET post_status = 'publish' WHERE ID IN (%s);", implode( ",", $ids ) );
$wpdb->query( $query );
foreach ($drafts as $draft) {
$orig_url = get_post_meta($draft->ID, 'pdf_url', true);
$this->save_pdf($orig_url, $draft->ID);
wp_publish_post( $draft->ID );
$published[$draft->ID]['title'] = $draft->post_title;
$published[$draft->ID]['id'] = $draft->ID;
}
return $published;
}
/**
* save_pdf salva un pdf dato l url e inserisce nel wp_media associando
* al post_id correntes
* @param string $url
* @param integer $post_id[post]
* @return integer [id del pdf creato]
*/
public function save_pdf($url,$post_id) {
$pdf = file_get_contents($url);
$upload_dir = wp_upload_dir();
$path = $upload_dir['basedir'].'/'.$upload_dir['subdir'].'/';
$file_url = $upload_dir['url'].'/crop-articolo-'.$post_id.'.pdf';
file_put_contents( "$path/crop-articolo-$post_id.pdf", $pdf );
$pdf_info = array(
'guid' => $path . 'crop-articolo-'.$post_id.'.pdf',
'post_mime_type' => 'application/pdf',
'post_title' => 'crop-articolo-'.$post_id.'.pdf',
'post_content' => '',
'post_status' => 'inherit',
);
// Create the attachment
$attach_id = wp_insert_attachment( $pdf_info, 'crop-articolo-'.$post_id.'.pdf', $post_id );
//salvo il filr url del file appena creato
if( $file_url )
update_post_meta( $post_id, 'pdf_url', $file_url);
}
/**
* aggiorno categorie partendo da array le creo
* se non esistono, e le associo al $post
* @param integer $post_id
* @param int $taxonomy ["pippo","pluto"]
* @param $term
* @return [type] []
*/
public function update_taxonomy( $post_id = 0, $taxonomy, $term) {
require_once (ABSPATH.'/wp-admin/includes/taxonomy.php');
switch ($taxonomy) {
case 'newspaper':
$taxonomy = 'testata';
break;
case 'argument':
$taxonomy = 'scenario';
break;
case 'language':
$taxonomy = 'language';
break;
case 'country':
$taxonomy = 'country';
break;
case 'author':
$taxonomy = 'author';
break;
}
$category_ids = array();
$category_id = get_term_by( 'name', esc_attr( $term ), $taxonomy);
$category_id = $category_id->term_id;
// se non ho la categoria la creo
if( !$category_id ) {
$category_id = wp_insert_term($term, $taxonomy);
}
array_push($category_ids, $category_id);
wp_set_object_terms( $post_id, $category_ids, $taxonomy);
}
/**
* id_imported verifica se esiste un post x $idArticle
* @param integer $idArticle [$idArticle]
* @param string $post_type [post]
* @return integer [id del post se lo trova]
*/
public function id_imported( $idArticle = 0 , $post_type = "post" ) {
if( !$idArticle ) return 0;
$args = array(
'post_type' => $post_type,
'post_status' => array('publish','draft'),
'meta_query' => array(
array(
'key' => 'idArticle',
'value' => $idArticle
)
)
);
$posts = get_posts($args);
return $posts ? $posts[0]->ID : 0;
}
/**
* [posts_by_rassegna TO DO!!!!]
* @param [type] $id_rassegna [description]
* @return [type] [description]
*/
public function posts_by_rassegna($id_rassegna) {
//to do estrarre post checckati in rassegna
}
public function get_daily_feeds($status) {
$today = getdate();
$args = array(
'post_type' => 'post',
'post_status' => $status,
'posts_per_page' => -1,
'date_query' => array(
array(
'year' => $today['year'],
'month' => $today['mon'],
'day' => $today['mday'],
),
),
);
$drafts = get_posts($args);
return count($drafts);
}
public function get_daily_stats() {
$drafts = $this->get_daily_feeds('draft');
$published = $this->get_daily_feeds('publish');
$all = $this->get_daily_feeds(array('draft','publish'));
$perc['draft'] = ($drafts * 100) / $all;
$perc['publish'] = ($published * 100) / $all;
return $perc;
}
/**
* [widget x visualizzare la rassegna]
*/
public function dashboard_dailyfeed( $post, $callback_args ) {
$daily = $this->get_daily_stats();
if($daily['draft']>0) {
?>
<h3>Feed pubblicati <?= round($daily['publish']) ?>%</h3>
<div class="cssProgress">
<div class="progress1">
<div class="cssProgress-bar cssProgress-success cssProgress-active" data-percent="<?= round($daily['publish']) ?>" style="width: <?= round($daily['publish']) ?>%;">
<span class="cssProgress-label"><?= round($daily['publish']) ?>%</span>
</div>
</div>
</div>
<h3>Feed da pubblicare <?= round($daily['draft']) ?>%</h3>
<div class="cssProgress">
<div class="progress1">
<div class="cssProgress-bar cssProgress-warning cssProgress-active" data-percent="<?= round($daily['draft']) ?>" style="width: <?= round($daily['draft']) ?>%;">
<span class="cssProgress-label"><?= round($daily['draft']) ?>%</span>
</div>
</div>
</div>
<?php } else { ?>
<h3>Non ci sono feed da pubblicare!</h3>
<?php }
}
// Function used in the action hook
public function add_dashboard_widgets() {
wp_add_dashboard_widget('dashboard_widget', 'Stato importazione feed', array($this,'dashboard_dailyfeed'));
}
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment