Skip to content

Instantly share code, notes, and snippets.

@hugosolar
Last active December 22, 2015 04:57
Show Gist options
  • Save hugosolar/10d9c0c5433843bb69de to your computer and use it in GitHub Desktop.
Save hugosolar/10d9c0c5433843bb69de to your computer and use it in GitHub Desktop.
<?php
// Social Feed para sitios en wordpress
class SocialFeed {
private static $instance;
public $feed_list;
public $yt_status;
public $fb_status;
public $tw_status;
//Constantes de Facebook
//Esto se puede obtener de http://findmyfacebookid.com/
const facebook_id = '';
const fb_app_id = '';
const fb_app_secret = '';
const fb_maximum_posts = 10;
// Constantes de Twitter
const tw_consumerKey = '';
const tw_consumerSecret = '';
const tw_accessToken = '';
const tw_accessTokenSecret = '';
const tw_bearerToken = '';
const tw_account = '';
const tw_maximum_posts = '10';
//Constantes de Youtube
const yt_api_browser = '';
const yt_client_id = '';
const yt_client_secret = '';
const yt_channel_id = '';
const transient_expiration = 1; //1 hora de duración
private function __construct(){
$this->actions_manager();
}
public static function get_instance(){
if ( !isset(self::$instance) ){
$c = __CLASS__;
self::$instance = new $c;
}
return self::$instance;
}
public function __clone(){
trigger_error( 'Clone is not allowed.', E_USER_ERROR );
}
/*
Llama a las acciones al instanciar la clase
*/
public function actions_manager() {
$this->mix_feed();
}
/*
Setea la variable feed_list que almacena todo el feed
*/
public function set_feed($feed) {
$this->feed_list = $feed;
}
/*
Obtiene la variable con todo el feed
*/
public function get_feed() {
return $this->feed_list;
}
/*
Obtiene todo los feeds, los normaliza y los ordena por fecha
*/
public function mix_feed() {
$fb_feed = json_decode($this->get_facebook_feed());
$tw_feed = json_decode($this->get_twitter_feed());
$yt_feed = json_decode($this->get_youtube_feed());
$post_feed = new WP_Query(array(
'post_type' => 'post',
'post_status' => 'publish',
'posts_per_page' => 10
));
$social_mix = array();
if (is_array($fb_feed->data)) {
foreach ( $fb_feed->data as $item ) {
$entry = new StdClass;
$entry->ID = $item->id;
$entry->type = 'facebook';
$entry->date = strtotime($item->created_time);
$entry->clean_date = $item->created_time;
if ( !empty( $item->message ) ) {
$entry->content = $item->message;
}
if ( !empty( $item->full_picture ) ) {
$entry->picture = $item->full_picture;
}
if ( !empty( $item->link ) ) {
$entry->link = $item->link;
}
array_push($social_mix, $entry);
}
}
if (is_array($tw_feed)) {
foreach ( $tw_feed as $item ) {
$entry = new StdClass;
$entry->ID = $item->id_str;
$entry->type = 'twitter';
$entry->date = strtotime($item->created_at);
$entry->clean_date = $item->created_at;
$entry->content = $item->text;
$entry->link = 'https://www.twitter.com/'.self::tw_account.'/status/'.$item->id_str;
array_push($social_mix, $entry);
}
}
if (is_array($yt_feed->items)) {
foreach ( $yt_feed->items as $item ) {
if ( !empty( $item->id->videoId ) ) {
$entry = new StdClass;
$entry->ID = $item->id->videoId;
$entry->type = 'youtube';
$entry->date = strtotime($item->snippet->publishedAt);
$entry->clean_date = $item->snippet->publishedAt;
$entry->content = $item->snippet->title;
$entry->picture = $item->snippet->thumbnails->high->url;
$entry->link = 'https://www.youtube.com/watch?v='.$entry->ID;
array_push($social_mix, $entry);
}
}
}
if ($post_feed->have_posts()) {
foreach ( $post_feed->posts as $item ) {
$entry = new StdClass;
$entry->ID = $item->ID;
$entry->type = 'site';
$entry->date = strtotime($item->post_date);
$entry->clean_date = $item->post_date;
$entry->content = get_the_title($item->ID);
$entry->picture = ( ( has_post_thumbnail( $item->ID ) ) ? current( wp_get_attachment_image_src( get_post_thumbnail_id( $item->ID ), 'medium' ) ) : '' );
$entry->link = get_the_permalink($item->ID);
array_push($social_mix, $entry);
}
}
$social_mix = $this->order_feed($social_mix);
$this->set_feed($social_mix);
}
/*
Regenera los transients de todos los feeds o por separado
*/
public function regenerate_transient($rrss=null) {
if ( !empty($rrss) ) {
switch ($rrss) {
case 'yt':
delete_transient( 'yt_feed' );
break;
case 'fb':
delete_transient( 'fb_feed' );
break;
case 'tw':
delete_transient( 'tw_feed' );
break;
}
}
else {
delete_transient( 'yt_feed' );
delete_transient( 'fb_feed' );
delete_transient( 'tw_feed' );
}
}
/*
Ordena por fecha el feed
*/
public function order_feed($feed) {
usort($feed, function($a, $b){
if ( $a->date < $b->date ) return 1;
if ( $a->date > $b->date ) return -1;
return 0;
});
return $feed;
}
/*
Parsea hashtags de twitter y facebook, transforma urls, y linkea cuentas de twitter
*/
public static function parse_hashtag($text,$rrss) {
$pre_ht_url = ( $rrss == 'fb' ) ? 'https://www.facebook.com/hashtag/' : 'https://twitter.com/hashtag/';
$pos_ht_url = ( $rrss == 'fb' ) ? '?source=web' : '?src=web';
$text = preg_replace('/([\w]+\:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/', ' <a href="$1" target="_blank">$1</a> ', $text);
$text = preg_replace('/(\#)([^\s]+)/', ' <a href="'.$pre_ht_url.'$2'.$pos_ht_url.'">#$2</a> ', $text);
//$text = preg_replace('/(\#)([^\s]+)/', ' '.$pre_ht_url.'$3'.$pos_ht_url.'">#$3 ', $text);
if ($rrss == 'tw') {
//parse users
$text = preg_replace('/@(\w+)/', ' <a href="http://twitter.com/$1">@$1</a> ', $text);
}
return $text;
}
/*
Trnasforma la fecha a "hace X minutos/horas/dias"
*/
public static function twitter_time($a) {
//get current timestampt
$b = strtotime("now");
//get timestamp when tweet created
$c = strtotime($a);
//get difference
$d = $b - $c;
//calculate different time values
$minute = 60;
$hour = $minute * 60;
$day = $hour * 24;
$week = $day * 7;
if(is_numeric($d) && $d > 0) {
//if less then 3 seconds
if($d < 3) return "ahora";
//if less then minute
if($d < $minute) return "hace ". floor($d) . " segundos";
//if less then 2 minutes
if($d < $minute * 2) return "hace 1 minuto";
//if less then hour
if($d < $hour) return "hace ". floor($d / $minute) . " minutos";
//if less then 2 hours
if($d < $hour * 2) return "hace 1 hora";
//if less then day
if($d < $day) return "hace ". floor($d / $hour) . " horas";
//if more then day, but less then 2 days
if($d > $day && $d < $day * 2) return "ayer";
//if less then year
if($d < $day * 365) return "hace ". floor($d / $day) . " días";
//else return more than a year
return "mas de 1 año";
}
}
/*
Obtenemos el feed de youtube transient
*/
public function get_youtube_feed() {
if ( false === ( $response = get_transient( 'yt_feed' ) ) ) {
$url = 'https://www.googleapis.com/youtube/v3/search?part=id%2Csnippet&channelId='.self::yt_channel_id.'&key='.self::yt_api_browser;
$response = wp_remote_get($url);
if ( !is_wp_error($response) ) {
$status_code = $response['response']['code'];
$status_message = $response['response']['message'];
$response = wp_remote_retrieve_body( $response );
$this->yt_status = $status_code;
$this->yt_status_message = $status_message;
set_transient( 'yt_feed', $response, 60*60*self::transient_expiration );
}
}
return $response;
}
/*
Obtenemos el feed de Twitter transient
*/
public function get_twitter_feed() {
if ( false === ( $response = get_transient( 'tw_feed' ) ) ) {
$response = wp_remote_get('https://api.twitter.com/1.1/statuses/user_timeline.json?screen_name='.self::tw_account, array(
'headers' => array(
'Authorization' => 'Bearer ' . self::tw_bearerToken
),
));
if (!is_wp_error( $response )) {
$status_code = $response['response']['code'];
$status_message = $response['response']['message'];
$response = wp_remote_retrieve_body( $response );
$this->tw_status = $status_code;
$this->tw_status_message = $status_message;
set_transient( 'tw_feed', $response, 60*60*self::transient_expiration );
}
}
return $response;
}
/*
Obtenemos el feed de Facebook transient
*/
public function get_facebook_feed() {
if ( false === ( $response = get_transient( 'fb_feed' ) ) ) {
$id_url = 'https://graph.facebook.com/oauth/access_token?grant_type=client_credentials&client_id='.self::fb_app_id.'&client_secret='.self::fb_app_secret.'';
$auth = wp_remote_get( $id_url );
$auth = wp_remote_retrieve_body($auth);
$response = wp_remote_get('https://graph.facebook.com/'.self::facebook_id.'/posts?'.$auth.'&limit='.self::fb_maximum_posts.'&fields=message,created_time,picture,full_picture,id,link');
if ( !is_wp_error( $response ) ) {
$status_code = $response['response']['code'];
$status_message = $response['response']['message'];
$response = wp_remote_retrieve_body($response);
$this->fb_status = $status_code;
$this->fb_status_message = $status_message;
set_transient( 'fb_feed', $response, 60*60*self::transient_expiration );
}
}
return $response;
}
/*
Layout de entrada twiiter
*/
static function render_tweet($item) {
$out = '';
$out .= '<article class="qentry hentry tweet">';
$out .= '<span class="comma">"</span>';
$out .= '<span class="tweet-text">';
$out .= self::parse_hashtag($item->content,'tw');
$out .= '</span>';
$out .= '<hr class="divider">';
$out .= '<span class="dashicons dashicons-twitter"></span> <a href="'.$item->link.'">'.self::twitter_time($item->clean_date).'</a>';
$out .= '<a href="https://www.twitter.com/'.self::tw_account.'" class="user float-right">@'.self::tw_account.'</a>';
$out .= '</article>';
return $out;
}
/*
Layout de entrada del sitio
*/
static function render_site($item) {
$out = '';
$out .= '<article class="qentry hentry site-entry">';
$out .= '<a href="'.get_permalink($item->ID).'">';
if ( has_post_thumbnail( $item->ID ) ) {
$out .= get_the_post_thumbnail( $item->ID, 'home-post' );
}
$out .= '<h4 class="entry-title">'.get_the_title($item->ID).'</h4>';
$out .= '</a>';
$out .= '<hr class="divider">';
$cats = wp_get_post_categories( $item->ID );
if (!empty( $cats )) {
$category = get_category( $cats[0] );
$link = get_category_link( $cats[0] );
$out .= '<a href="'.$link.'">'.$category->name.'</a>';
}
$out .= '<a href="'.get_permalink($item->ID).'" class="date float-right">'.get_the_date('d/m/Y',$item->ID).'</a>';
$out .= '</article>';
return $out;
}
/*
Layout de entrada de Youtube
*/
static function render_video($item) {
$out = '';
$out .= '<article class="qentry hentry video">';
$out .= '<a href="'.$item->link.'" class="box" rel="youtube">';
$out .= '<div class="wrap-image">';
$out .= '<img src="'.$item->picture.'" alt="">';
$out .= '<span class="dashicons dashicons-controls-play"></span>';
$out .= '</div>';
$out .= '<h4 class="entry-title">'.$item->content.'</h4>';
$out .= '</a>';
$out .= '<a href="https://www.youtube.com/channel/'.self::yt_channel_id.'"><span class="dashicons dashicons-video-alt3"></span> Une Chile</a> / <a href="'.$item->link.'">'.mysql2date('d/m/Y',$item->clean_date).'</a>';
$out .= '</article>';
return $out;
}
/*
Layout de entrada de Facebook
*/
static function render_fb($item) {
$out = '';
$out .= '<article class="qentry hentry fb">';
if ( !empty( $item->picture ) ) {
$out .= '<a href="'.$item->link.'">';
$out .= '<img src="'.$item->picture.'" alt="">';
$out .= '</a>';
}
$out .= '<p class="entry-content">';
$out .= self::parse_hashtag(do_excerpt($item->content),'fb');
$out .= '</p>';
$out .= '<hr class="divider">';
$out .= '<a href="https://www.facebook.com/UnionNacionalEstudiantil"><span class="dashicons dashicons-facebook-alt"></span> Une Chile </a>';
$out .= '<a href="'.$item->link.'" class="date float-right">'.mysql2date('d/m/Y',$item->clean_date).'</a>';
$out .= '</article>';
return $out;
}
}
$_feed = SocialFeed::get_instance();
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment