Location: PHPKode > scripts > Flickr Comments > flickr-comments/flickr-comments.php
<?php

/*  Copyright 2013  jdleung  (email : hide@address.com)

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License, version 2, as 
    published by the Free Software Foundation.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; if not, write to the Free Software
    Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
*/

/**

Plugin Name: Flickr Comments
Plugin URI: http://wordpress.org/extend/plugins/flickr-comments/
Description: Retrieve Flickr comments to your wordpress photoblog posts with flickr photo id. 
Author: jdleung
Version: 1.11
Author URI: http://www.jdleungs.com

**/

// $user = $wpdb->get_row( "SELECT post_id,meta_value FROM {$wpdb->postmeta} WHERE meta_key='flickr_photo_id'" );
// echo $user->post_id;
// 
// 
// $user_count = $wpdb->get_var( "SELECT post_id,meta_value FROM {$wpdb->postmeta} WHERE meta_key='flickr_photo_id'" );
// echo "<p>User count is {$user_count}</p>";

$timezone = get_option('timezone_string');
date_default_timezone_set($timezone);


if($_GET['frob']){
	$admin_url = admin_url();
	$fc_api = get_option('flickr_comments_API');
	$api_key = $fc_api['api_key'];
	$api_secret =$fc_api['api_secret'];
	
	$frob = $_GET['frob'];	
	$perms = "read";	
	$method = "flickr.auth.getToken";
	$format= "php_serial";
	$sig = md5($api_secret."api_key".$api_key."format".$format."frob".$frob."method".$method."perms".$perms);
	$url = "http://api.flickr.com/services/rest/?api_key=".$api_key."&format=".$format."&frob=".$frob."&method=".$method."&perms=".$perms."&api_sig=".$sig;
	
	$token_content = file_get_contents($url);
	$rsp_obj = unserialize($token_content);
	$token = $rsp_obj['auth']['token']['_content'];

	$flickr_comments_API['api_key']= $api_key;
	$flickr_comments_API['api_secret']= $api_secret;
	$flickr_comments_API['token']= $token;
	
	if(!empty($token)){
		update_option('flickr_comments_API', $flickr_comments_API);
		header('location:'.$admin_url.'options-general.php?page=flickr-comments/flickr-comments.php');
		exit;
	}
}
	

// add the admin options page
add_action('admin_menu', 'plugin_admin_add_page');

function plugin_admin_add_page() {
	
	
	if($_POST['flickr_comments_API']){
		
		$flickr_comments_API['api_key']= $_POST['flickr_comments_API']['api_key'];
		$flickr_comments_API['api_secret']= $_POST['flickr_comments_API']['api_secret'];
		update_option('flickr_comments_API', $flickr_comments_API);
		
		$fc_config = get_option('flickr_comments_config');
		if(empty($fc_config['timeframe']) && empty($fc_config['interval'])){
			$flickr_comments_config['timeframe'] = '7d';
			$flickr_comments_config['interval'] = 36000;
			$flickr_comments_config['lastupdate'] = date('Y-m-d H:i:s');
			update_option('flickr_comments_config',$flickr_comments_config);
		}

		require_once('phpFlickr/phpFlickr.php');
		unset($_SESSION['phpFlickr_auth_token']);
		$f = new phpFlickr($flickr_comments_API['api_key'], $flickr_comments_API['api_secret']);
		$f->auth("read", false );
	
	}
	
		
	if($_POST['manual_update'])
		flcikr_comments_mupdate();
	
	add_options_page('Flickr Comments', 'Flickr Comments', 'manage_options', __FILE__, 'flickr_comments_config_page');

}

// add the admin settings and such
add_action('admin_init', 'plugin_admin_init');

function plugin_admin_init(){
	
	register_setting( 'flickr_comments_API', 'flickr_comments_API', '' );
	add_settings_section('api_main', '<h2>1. Flickr API:</h2>', 'flickr_comments_API_text', 'api');
	add_settings_field('api_key', 'API key', 'api_key_input', 'api', 'api_main');
	add_settings_field('api_secret', 'API secret', 'api_secret_input', 'api', 'api_main');	
	
	register_setting( 'manual_update', 'manual_update', '' );
	add_settings_section('manual_update_main', '<h2>2. <font color=red>Recomend a Manual Update for the first time!</font></h2>', 'manual_update_text', 'mupdate');
	
	register_setting( 'flickr_comments_config', 'flickr_comments_config', 'flickr_comments_config_validate' );
	add_settings_section('plugin_main', '<h2>3. Auto-update Settings:</h2>', 'plugin_section_text', 'plugin');
	add_settings_field('timeframe', 'Time frame', 'timeframe_config', 'plugin', 'plugin_main');
	add_settings_field('interval', 'Time interval', 'interval_config', 'plugin', 'plugin_main');
	add_settings_field('lastupdate', '', 'lastupdate_config', 'plugin', 'plugin_main');
		
}


// display the admin options page
function flickr_comments_config_page() {
	
	$fc_api = get_option('flickr_comments_API');

	echo "<h1>Flickr Comments by <a href='http://www.jdleungs.com/' target='_blank'>jdleung</a></h1><br>";
	echo "<form action='options.php' method='post'>";
	 settings_fields('flickr_comments_API'); 
	 do_settings_sections('api'); 
	echo "<input name='get_token' type='submit' value='Get Token' /></form>";		
		
	if($fc_api['token']){
		echo "<h3><font color=red>First step done!</font></h3><hr size=1>";
			  
		echo "<form action='options.php' method='post'>";
		 settings_fields('manual_update'); 
		 do_settings_sections('mupdate'); 
		echo "<input name='manual_update' type='submit' value='Manual Update' /></form><br><hr size=1>";			  
			  
		echo "<form action='options.php' method='post'>";
		 settings_fields('flickr_comments_config'); 
		 do_settings_sections('plugin'); 
		echo "<input name='Submit' type='submit' value='Save setting' /></form><br>";

	}

	echo "<hr size=1><h3>Notes:</h3>";
	echo "1. Both API key and secret is needed. You can <a href='http://www.flickr.com/services/api/keys/'>Get Another Key</a> from Flickr. And edit the Callback URL to your site url.<br>";
	echo "2. When a red 'First step done!' shows in the first step, it means the Flickr Token is saved, NO NEED to get again unless you want to use another API key.<br>";
		
	if($fc_api['token']){
		echo "3. If Timeframe is set to A big number, the webpage loads may take a long time. Recommend: No more than 30 days. Invalid format will be replaced by '7d'.<br>"; 
		echo "4. In the post, A custom field called 'flickr_photo_id' is needed to input the Flickr photo id!<br>";
		echo "5. Flickr Photo ID is usually the number in the URL of a photo page eg: <a href='http://www.flickr.com/photos/jdleung/435246848/' target='_blank'>http://www.flickr.com/photos/jdleung/435246848/</a> or <a href='http://www.flickr.com/photos/jdleung/3260156539/in/photostream/'  target='_blank'>http://www.flickr.com/photos/jdleung/3260156539/in/photostream/</a> .";
	}
	
}



function manual_update_text(){
	echo  "Auto-update will not retrieve the comments one year before! Manual Update can read all comments of the post with 'flickr_photo_id'.<br>";	
	
}

function api_key_input() {
	$fc_api = get_option('flickr_comments_API');
	echo "<input id='api_key' name='flickr_comments_API[api_key]' size='30' type='text' value='{$fc_api['api_key']}' />";
} 

function api_secret_input() {
	$fc_api = get_option('flickr_comments_API');
	echo "<input id='api_secret' name='flickr_comments_API[api_secret]' size='20' type='text' value='{$fc_api['api_secret']}' />";
} 

function flickr_comments_API_text(){
	$site_url = site_url();
	echo "Login Flickr first, <a href='http://www.flickr.com/services/api/keys/' target='_blank'>SET Callback URL</a> to your site url:  ".$site_url;
	}

function plugin_section_text() {
	$fc_config = get_option('flickr_comments_config');
	$interval = $fc_config['interval'];
	$lastupdate =$fc_config['lastupdate'];	
	
	$timezone = get_option('timezone_string');
	date_default_timezone_set($timezone);	
	
	$last_timestamp = strtotime($lastupdate);
	$next_update_timestamp = $last_timestamp+$interval;
	$next_update_time = date('Y-m-d H:i:s', $next_update_timestamp);
	if($lastupdate != "" )
		echo "Last update: ".$lastupdate." &nbsp;&nbsp;Next update: ".$next_update_time;

} 

function timeframe_config() {
	$fc_config = get_option('flickr_comments_config');
	echo "<input id='timeframe' name='flickr_comments_config[timeframe]' size='10' type='text' value='{$fc_config['timeframe']}' /><br>";
	echo "The timeframe in which to return updates for. This can be specified in days ('2d') or hours ('4h'). <br>It means it reads comments created within 2 days or 4 hours.<br>";
} 

function interval_config() {
	$fc_config = get_option('flickr_comments_config');
	echo "<input id='interval' name='flickr_comments_config[interval]' size='10' type='text' value='{$fc_config['interval']}' /><br>";
	echo "Numbers ONLY. By default, it's 36000 seconds(10 hours). <br>It means it reads comments from Flickr every 10 hours.";

} 

function lastupdate_config() {
	$fc_config = get_option('flickr_comments_config');
	if($fc_config['lastupdate']=="")
		$lastupdate = date('Y-m-d H:i:s');
	else $lastupdate = $fc_config['lastupdate'];
		echo "<input id='lastupdate' name='flickr_comments_config[lastupdate]' size='20' type='hidden' value='{$lastupdate}' />";
} 

// validate our options
function flickr_comments_config_validate($input) {
	$newinput['timeframe'] = strtolower(trim($input['timeframe']));
	$newinput['interval'] = trim($input['interval']);
	$newinput['lastupdate'] = $input['lastupdate'];

	if(!preg_match('/^[0-9]+(H|h|D|d)$/', $newinput['timeframe'])) 
		$newinput['timeframe'] = '7d';
	
	if(!preg_match('/^[1-9]\d*$/', $newinput['interval'])) 
		$newinput['interval'] = '36000';

	return $newinput;
}


add_filter( 'plugin_action_links', 'fc_config_links', 10, 2 );

// Display a Settings link on the main Plugins page
function fc_config_links( $links, $file ) {

	if ( $file == plugin_basename( __FILE__ ) ) {
		$fc_links = '<a href="'.get_admin_url().'options-general.php?page=flickr-comments/flickr-comments.php">'.__('Settings').'</a>';
		
		// make the 'Settings' link appear first
		array_unshift( $links, $fc_links );
	}

	return $links;
}


function flcikr_comments_mupdate(){
	global $wpdb,$comment_num;
	
	$fc_api = get_option('flickr_comments_API');
	$api_key = $fc_api['api_key'];
	$api_secret =$fc_api['api_secret'];
	$token = $fc_api['token'];	
	
	require_once('phpFlickr/phpFlickr.php');
	$f = new phpFlickr($api_key, $api_secret);
	
	$fc_config = get_option('flickr_comments_config');
	$timeframe = $fc_config['timeframe'];
	$interval = $fc_config['interval'];
	
	set_time_limit(0); 

	$f = new phpFlickr($api_key, $api_secret);
	
	// get photo post id
	$meta_infos = $wpdb->get_results( "SELECT post_id,meta_value FROM {$wpdb->postmeta} WHERE meta_key='flickr_photo_id' ");	
	$comment_num=0;
	
	if($meta_infos){ 	
		foreach ( $meta_infos as $meta_info ) {
			
			$post_id = $meta_info->post_id;
			$flickr_photo_id = $meta_info->meta_value;

			$comments   = $f->photos_comments_getList($flickr_photo_id); //get comments of the photo

			if(isset($comments['comments']['comment'])) {
				foreach( $comments['comments']['comment'] as $comment ) {
					
					$timezone = get_option('timezone_string');
					date_default_timezone_set($timezone);	
							
					$f_commentdate = date ("Y-m-d H:i:s",$comment['datecreate']);						
					$f_url = "http://www.flickr.com/photos/".$comment['author'];
					$f_name = $comment['authorname'];
					$f_comment = $comment['_content'];	

					handle_comments($post_id,$f_commentdate,$f_url,$f_name,$f_comment,$comment_num);
				}
					
			}

		}

	}	
	
	$flickr_comments_config['timeframe']= $timeframe;
	$flickr_comments_config['interval']= $interval;
	$flickr_comments_config['lastupdate']= date('Y-m-d H:i:s');
	update_option('flickr_comments_config', $flickr_comments_config);

	
}	// end flickr_comments_mupdate


add_action('wp_head', 'flickr_comments');

function flickr_comments(){
	global $wpdb,$comment_num;
	
	$timezone = get_option('timezone_string');
	date_default_timezone_set($timezone);	
							
	$fc_config = get_option('flickr_comments_config');
	$timeframe = $fc_config['timeframe'];
	$interval = $fc_config['interval'];
	$lastupdate =$fc_config['lastupdate'];
	$curr_datetime = date('Y-m-d H:i:s');
	$curr_timestamp = strtotime($curr_datetime);

	if(!$lastupdate)
		$lastupdate=$curr_datetime;
		
	$last_timestamp = strtotime($lastupdate);
	$update = ($last_timestamp+$interval)-$curr_timestamp;

	if( $update <= 0){	

		$fc_api = get_option('flickr_comments_API');
		$api_key = $fc_api['api_key'];
		$api_secret =$fc_api['api_secret'];
		$token = $fc_api['token'];	

		require_once('phpFlickr/phpFlickr.php');

		$_SESSION['phpFlickr_auth_token'] = $token;
		$f = new phpFlickr($api_key, $api_secret);
	
		$comment_num = 0;
		$result_page = 1;
		$all_photo_id[] = array();

		do{
			$comments_info = $f->activity_userPhotos($timeframe,50,$result_page);
			
	 		$total_pages = $comments_info['pages'];

	 		foreach ((array)$comments_info['item'] as $key=>$c) {

			 	$total_comments = $c['comments'];
				$flickr_photo_id = $c['id'];

				foreach((array)$c['activity']['event'] as $key2=>$d){
					
					$type = $d['type'];
					if($type == "comment" && $c['type'] == "photo"){ // show only comments
						
						if(in_array($flickr_photo_id,$all_photo_id) == false)  { //jump if the photo has been read by 'more than 10 comments'
						
							$timezone = get_option('timezone_string');
							date_default_timezone_set($timezone);	

							$f_url = "http://www.flickr.com/photos/".$d['user'];
							$f_commentdate = date ("Y-m-d H:i:s",$d['dateadded']);
							$f_name = $d['username'];
							$f_comment = $d['_content'];

							// get photo post id
							$meta_infos = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='flickr_photo_id' AND meta_value='{$flickr_photo_id}'");	
					
							if($meta_infos){ 	
								foreach ( $meta_infos as $meta_info ) 
									{
										$post_id = $meta_info->post_id;
									}
													
								handle_comments($post_id,$f_commentdate,$f_url,$f_name,$f_comment,$comment_num);
							}	
					
						}	

						if($total_comments>10){ //photo has more than 10 comments
		
							set_time_limit(0); 
							$flickr_comm_data = "";				
							$all_photo_id[] = $flickr_photo_id;
										
							$meta_infos = $wpdb->get_results( "SELECT post_id FROM {$wpdb->postmeta} WHERE meta_key='flickr_photo_id' AND meta_value='{$flickr_photo_id}'");	
							if($meta_infos){ 	
								
								foreach ( $meta_infos as $meta_info ) {
										$post_id = $meta_info->post_id;
										
									}

								$timeframe_format = substr($timeframe,-1);	
								
								if($timeframe_format == 'd')
									$timeframe_second = trim($timeframe,'d')*3600*24;
									
								if($timeframe_format == 'h')
									$timeframe_second = trim($timeframe,'h')*3600; 
									
								$max_comment_date = $curr_timestamp;
								$min_comment_date = $curr_timestamp-$timeframe_second;
								
									
								$comments = $f->photos_comments_getList($flickr_photo_id, $min_comment_date, $max_comment_date); //get comments of the photo
								if(isset($comments['comments']['comment'])) {
									foreach( $comments['comments']['comment'] as $comment ) {
									
										$timezone = get_option('timezone_string');
										date_default_timezone_set($timezone);

										$f_commentdate = date ("Y-m-d H:i:s",$comment['datecreate']);	
										$f_url = "http://www.flickr.com/photos/".$comment['author'];
										$f_name = $comment['authorname'];
										$f_comment = $comment['_content'];	
				
										handle_comments($post_id,$f_commentdate,$f_url,$f_name,$f_comment);
									}
								}
			
							}
									
						}//end more than 10 comments	
								
					}//type of comment
				
				}

			}//end foreach
	
			$result_page++;
	
		} while ($result_page <= $total_pages);

		// if($comment_num){
			$flickr_comments_config['timeframe']= $timeframe;
			$flickr_comments_config['interval']= $interval;
			$flickr_comments_config['lastupdate']= date('Y-m-d H:i:s');
			update_option('flickr_comments_config', $flickr_comments_config);
		// }
	
	}//end update



}// end flickr_comments


			
function handle_comments($post_id,$f_commentdate,$f_url,$f_name,$f_comment){
	global $wpdb,$comment_num;
	
	// Is the comment already in the database?
	$check_dupes = $wpdb->get_results( "SELECT comment_ID FROM {$wpdb->comments} WHERE comment_date='{$f_commentdate}'", ARRAY_N);

	$has_dupes = count($check_dupes);
	if(empty($has_dupes)){ 
								
		$timezone = get_option('timezone_string');
		date_default_timezone_set($timezone);

		//convert icon and icon link to author name
		preg_match("/(<a href.+\/photos\/)(.*)(\/.+)(<img.*\/a>)(.*)/i", $f_comment, $matches); 
		$author_name = "[".$matches[2]."]";
		$f_comment = preg_replace("/<a href.+<img.+\/a>/i",$author_name ,$f_comment); 

		//[http://...] to author name
		preg_match("/(\[http.+photos\/)(.*)(\].*)/i",$f_comment,$matches2);
		$author_name = "[".$matches2[2]."]";
		$f_comment = preg_replace("/\[http:\/\/.*\]/i",$author_name ,$f_comment); 
		
		$flickr_comm_data['comment_post_ID'] = $post_id;
	    $flickr_comm_data['comment_author'] = $f_name;
	    // $flickr_comm_data['comment_author_email'] = 'hide@address.com';
	    $flickr_comm_data['comment_author_url'] = $f_url;
	    $flickr_comm_data['comment_content'] = $f_comment;
	    // $flickr_comm_data['comment_author_IP'] = '127.0.0.1';
	    $flickr_comm_data['comment_agent'] = 'Flickr Comments';
	    $flickr_comm_data['comment_date'] = $f_commentdate;
	    $flickr_comm_data['comment_approved'] = 1;

		wp_insert_comment($flickr_comm_data);
		
		// $comment_num++;
			
	}

}//end handle_comment()




	
?>
Return current item: Flickr Comments