Location: PHPKode > scripts > Flickr Comments > 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.1
Author URI: http://www.jdleungs.com

**/




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

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

require_once('phpFlickr/phpFlickr.php');
$f = new phpFlickr($api_key, $api_secret);


if($_GET['do']=="gettoken" && $_POST['api_key'] && $_POST['api_secret']){

	$flickr_comments_API['api_key']= $_POST['api_key'];
	$flickr_comments_API['api_secret']= $_POST['api_secret'];
	update_option('flickr_comments_API', $flickr_comments_API);
	
	unset($_SESSION['phpFlickr_auth_token']);
	$f = new phpFlickr($flickr_comments_API['api_key'], $flickr_comments_API['api_secret']);
	$f->auth("read", false );
}

	
if($_GET['frob']){
	$admin_url = admin_url();

	$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=plugin');
		exit;
	}
}


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

function plugin_admin_add_page() {
	add_options_page('Flickr Comments', 'Flickr Comments', 'manage_options', 'plugin', 'flickr_comments_config_page');
}

// display the admin options page
function flickr_comments_config_page() {
	
	if($_GET['update'] == "manual")
		flcikr_comments_mupdate();
	
	flickr_comments_config();
	
	$fc_config = get_option('flickr_comments_config');
//	$timeframe = $fc_config['timeframe'];
	$interval = $fc_config['interval'];
	$lastupdate =$fc_config['lastupdate'];	
	
	$last_timestamp = strtotime($lastupdate);
	$next_update_timestamp = $last_timestamp+$interval;
	$next_update_time = date('Y-m-d H:i:s', $next_update_timestamp);
	
		
	$fc_option = get_option('flickr_comments_API');
	if($fc_option['token']){
		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 "Last update: ".$lastupdate." &nbsp;&nbsp;Next update: ".$next_update_time;
		echo "<hr size=1><h3>Notes:</h3>";
		echo "1. Both API key and secret must be need. 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 plugin is linked up with Flickr, NO NEED confirm again unless you want to use another API key.<br>";
		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> .";

	}	
}

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

function plugin_admin_init(){
	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');
}

function plugin_section_text() {
	// $fc_config =	get_option('flickr_comments_config');
	// next_update = $fc_config['lastupdate']+$fc_config['timeframe'];
	// echo '<p>Last update: '.$fc_config['lastupdate'];
} 

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

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

function lastupdate_config() {
	$options = get_option('flickr_comments_config');
	if($options['lastupdate']=="")
		$lastupdate = date('Y-m-d H:i:s');
	else $lastupdate = $options['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'] = 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;
}

	
// function to display the plugin options page
function flickr_comments_config() {
	global $api_key,$api_secret,$token;
	
	$admin_url = admin_url();
 	$site_url = site_url();

	echo "<h1>Flickr Comments - By <a href='http://www.jdleungs.com' target='_blank'>jdleung</a></h1>";
	echo "<h2>1. Flickr API:</h2>";
	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."\".<p>
	<form action='".$site_url."/index.php?do=gettoken' method='post' accept-charset='UTF-8'>
	<b>API KEY: </b><br>
	<input type='text' size='40' value='".$api_key."' name='api_key' ><P>
	<b>API SECRET: </b><br>
	<input type='text' size='20' value='".$api_secret."' name='api_secret' > <br><br>";
	echo "<input type='submit' value='CONFIRM'><p></form>";

	if($token){
		echo "<h3><font color=red>First step done!</font></h3>
			  <hr size=1><h2>2. <font color=red>Do <a href='".$admin_url."options-general.php?page=plugin&update=manual'>Manual Update</a> for the first time!</font></h2>
			  Auto-update will not retrieve the comments one year before! Manual Update can read all comments of the post with 'flickr_photo_id'.<br>	
			  <hr size=1>
		";
	}
}

function flcikr_comments_mupdate(){
	global $wpdb,$api_key,$api_secret;
	
	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 ) {
					$f_commentdate = strftime ("%Y-%m-%d %H:%M:%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);
				}
					
			}

		}

	}	
				
}	// end flickr_comments_mupdate()


function flickr_comments(){
	global $wpdb,$api_key,$api_secret,$token,$comment_num;

	$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){	
		
		$_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){
				// show only comments
				
					$type = $d['type'];
					if($type == "comment" && $c['type'] == "photo"){
						
						if(in_array($flickr_photo_id,$all_photo_id) == false)  { //jump if the photo has been read by 'more than 10 commnets'
						
							$timezone = get_option('timezone_string');
							date_default_timezone_set($timezone);	
												
							$f_url = "http://www.flickr.com/photos/".$d['user'];
							$f_commentdate = strftime ("%Y-%m-%d %H:%M:%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;
								
								$timezone = get_option('timezone_string');
								date_default_timezone_set($timezone);
									
								$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 ) {
										$f_commentdate = strftime ("%Y-%m-%d %H:%M:%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++;
			// echo $result_page." ".$total_pages."<br>";
	
		} 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);

		// clean the name
		$f_name = strip_tags($f_name);	
		$f_name = htmlspecialchars($f_name,ENT_QUOTES);
		$f_name = addslashes($f_name);
		$f_name = preg_replace("/((\x0D\x0A){3,}|[\x0A]{3,}|[\x0D]{3,})/","\n\n",$f_name);
		$f_name = nl2br($f_name);
		
		// clean the message
		$pattern = 	"/<img[\s]+[^>]*?((alt*?[\s]?=[\s\"\']+(.*?)[\"\']+.*?)|(src*?[\s]?=[\s\"\']+(.*?)[\"\']+.*?))((src*?[\s]?=[\s\"\']+(.*?)[\"\']+.*?>)|(alt*?[\s]?=[\s\"\']+(.*?)[\"\']+.*?>)|>)/";
		$replacement = "";
		$f_comment = preg_replace($pattern, $replacement, $f_comment);
		$f_comment = strip_tags($f_comment);
		$f_comment = htmlspecialchars($f_comment,ENT_QUOTES);
		$f_comment = addslashes($f_comment);
		$f_comment = preg_replace("/((\x0D\x0A){3,}|[\x0A]{3,}|[\x0D]{3,})/","\n\n",$f_comment);
		$f_comment = nl2br($f_comment);
		$f_comment = preg_replace("/\[http:\/\/.*\]/i","",$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()



add_filter('the_content', 'flickr_comments');


?>
Return current item: Flickr Comments