Merge pull request #172 from annando/master

Unique contacts, bugfix in fbpost and better handling of avatars and cached data in privacy_image_cache
This commit is contained in:
tobiasd 2014-01-01 01:28:18 -08:00
commit b227650573
4 changed files with 193 additions and 72 deletions

View file

@ -293,8 +293,8 @@ function fbpost_content(&$a) {
function fbpost_plugin_settings(&$a,&$b) {
$b .= '<div class="settings-block">';
$b .= '<h3>' . t('Facebook Post Settings') . '</h3>';
$b .= '<a href="fbpost">' . t('Facebook Post Settings') . '</a><br />';
//$b .= '<h3>' . t('Facebook Post Settings') . '</h3>';
$b .= '<a href="fbpost"><h3>' . t('Facebook Post Settings') . '</a></h3>';
$b .= '</div>';
}
@ -765,6 +765,10 @@ function fbpost_post_hook(&$a,&$b) {
}
else {
if(! $likes) {
$r = q("SELECT `id` FROM `contact` WHERE `uid` = %d AND `self`", intval($b['uid']));
if (count($r))
$a->contact = $r[0]["id"];
$s = serialize(array('url' => $url, 'item' => $b['id'], 'post' => $postvars));
require_once('include/queue_fn.php');
add_to_queue($a->contact,NETWORK_FACEBOOK,$s);
@ -867,14 +871,17 @@ function fbpost_queue_hook(&$a,&$b) {
if($x['network'] !== NETWORK_FACEBOOK)
continue;
logger('facebook_queue: run');
logger('fbpost_queue_hook: run');
$r = q("SELECT `user`.* FROM `user` LEFT JOIN `contact` on `contact`.`uid` = `user`.`uid`
WHERE `contact`.`self` = 1 AND `contact`.`id` = %d LIMIT 1",
intval($x['cid'])
);
if(! count($r))
if(! count($r)) {
logger('fbpost_queue_hook: no user found for entry '.print_r($x, true));
update_queue_time($x['id']);
continue;
}
$user = $r[0];
@ -908,7 +915,13 @@ function fbpost_queue_hook(&$a,&$b) {
logger('fbpost_queue_hook: failed: ' . $j);
update_queue_time($x['id']);
}
} else {
logger('fbpost_queue_hook: No fb_post or fb_token.');
update_queue_time($x['id']);
}
} else {
logger('fbpost_queue_hook: No appid or secret.');
update_queue_time($x['id']);
}
}
}

View file

@ -200,6 +200,7 @@ function fbsync_createpost($a, $uid, $self, $contacts, $applications, $post, $cr
$postarray['wall'] = 0;
$postarray['verb'] = ACTIVITY_POST;
$postarray['network'] = dbesc(NETWORK_FACEBOOK);
$postarray['uri'] = "fb::".$post->post_id;
$postarray['thr-parent'] = $postarray['uri'];
@ -414,6 +415,7 @@ function fbsync_createcomment($a, $uid, $self_id, $self, $user, $contacts, $appl
$postarray['wall'] = 0;
$postarray['verb'] = ACTIVITY_POST;
$postarray['network'] = dbesc(NETWORK_FACEBOOK);
$postarray['uri'] = "fb::".$comment->id;
$postarray['thr-parent'] = $parent_uri;
@ -548,13 +550,13 @@ function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
$likedata = array();
$likedata['parent'] = $orig_post['id'];
$likedata['verb'] = ACTIVITY_LIKE;
$likedate['network'] = dbesc(NETWORK_FACEBOOK);
$likedata['gravity'] = 3;
$likedata['uid'] = $uid;
$likedata['wall'] = 0;
$likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
$likedata['parent-uri'] = $orig_post["uri"];
$likedata['app'] = "Facebook";
$likedata['verb'] = ACTIVITY_LIKE;
if ($like->user_id != $self_id) {
$likedata['contact-id'] = $contact_id;
@ -598,6 +600,24 @@ function fbsync_createlike($a, $uid, $self_id, $self, $contacts, $like) {
function fbsync_fetch_contact($uid, $contact, $create_user) {
// Check if the unique contact is existing
// To-Do: only update once a while
$r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
dbesc(normalise_link($contact->url)));
if (count($r) == 0)
q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
dbesc(normalise_link($contact->url)),
dbesc($contact->name),
dbesc($contact->username),
dbesc($contact->pic_square));
else
q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
dbesc($contact->name),
dbesc($contact->username),
dbesc($contact->pic_square),
dbesc(normalise_link($contact->url)));
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
intval($uid), dbesc("facebook::".$contact->id));
@ -834,7 +854,7 @@ function fbsync_fetchfeed($a, $uid) {
require_once('include/items.php');
if ($last_updated == "")
//if ($last_updated == "")
$last_updated = 0;
logger("fbsync_fetchfeed: fetching content for user ".$self_id);

View file

@ -34,6 +34,13 @@ function privacy_image_cache_module() {}
function privacy_image_cache_init() {
global $a, $_SERVER;
// The code needs to be reworked, it is too complicated
//
// it is doing the following:
// 1. If a folder "privacy_image_cache" exists and is writeable, then use this for caching
// 2. If a cache path is defined, use this
// 3. If everything else failed, cache into the database
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE'])) {
header('HTTP/1.1 304 Not Modified');
header("Last-Modified: " . gmdate("D, d M Y H:i:s", time()) . " GMT");
@ -55,6 +62,14 @@ function privacy_image_cache_init() {
$thumb = false;
// If the cache path isn't there, try to create it
if (!is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
if (is_writable($_SERVER["DOCUMENT_ROOT"]))
mkdir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache");
// Checking if caching into a folder in the webroot is activated and working
$direct_cache = (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache") AND is_writable($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"));
// Look for filename in the arguments
if (isset($a->argv[1]) OR isset($a->argv[2]) OR isset($a->argv[3])) {
if (isset($a->argv[3]))
@ -77,6 +92,7 @@ function privacy_image_cache_init() {
$thumb = (isset($a->argv[3]) and ($a->argv[3] == "thumb"));
}
if (!$direct_cache) {
$urlhash = 'pic:' . sha1($_REQUEST['url']);
// Double encoded url - happens with Diaspora
$urlhash2 = 'pic:' . sha1(urldecode($_REQUEST['url']));
@ -96,31 +112,33 @@ function privacy_image_cache_init() {
// reduce quality - if it isn't a GIF
if ($mime != "image/gif") {
$img = new Photo($img_str, $mime);
if($img->is_valid())
if($img->is_valid()) {
$img_str = $img->imageString();
}
}
echo $img_str;
if (is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
killme();
}
}
} else
$cachefile = "";
$valid = true;
if (!$direct_cache AND ($cachefile == "")) {
$r = q("SELECT * FROM `photo` WHERE `resource-id` in ('%s', '%s') LIMIT 1", $urlhash, $urlhash2);
if (count($r)) {
$img_str = $r[0]['data'];
$mime = $r[0]["desc"];
if ($mime == "") $mime = "image/jpeg";
}
} else
$r = array();
} else {
if (!count($r)) {
// It shouldn't happen but it does - spaces in URL
$_REQUEST['url'] = str_replace(" ", "+", $_REQUEST['url']);
$redirects = 0;
$img_str = fetch_url($_REQUEST['url'],true, $redirects, 10);
@ -140,7 +158,7 @@ function privacy_image_cache_init() {
$img->scaleImage(10);
$img_str = $img->imageString();
}
} else if ($mime != "image/jpeg") {
} else if (($mime != "image/jpeg") AND !$direct_cache AND ($cachefile == "")) {
$image = @imagecreatefromstring($img_str);
if($image === FALSE) die();
@ -165,25 +183,31 @@ function privacy_image_cache_init() {
} else {
$img = new Photo($img_str, $mime);
if($img->is_valid()) {
if (!$direct_cache AND ($cachefile == ""))
$img->store(0, 0, $urlhash, $_REQUEST['url'], '', 100);
if ($thumb)
if ($thumb) {
$img->scaleImage(200); // Test
$img_str = $img->imageString();
}
}
//$mime = "image/jpeg";
}
}
// reduce quality - if it isn't a GIF
if ($mime != "image/gif") {
$img = new Photo($img_str, $mime);
if($img->is_valid())
if($img->is_valid()) {
$img->scaleImage(1024); // Test
$img_str = $img->imageString();
}
}
// If there is a real existing directory then put the cache file there
// advantage: real file access is really fast
// Otherwise write in cachefile
if ($valid AND is_dir($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache"))
if ($valid AND $direct_cache)
file_put_contents($_SERVER["DOCUMENT_ROOT"]."/privacy_image_cache/".privacy_image_cache_cachename($_REQUEST['url'], true), $img_str);
elseif ($cachefile != '')
file_put_contents($cachefile, $img_str);
@ -306,13 +330,12 @@ function privacy_image_cache_display_item_hook(&$a, &$o) {
if (isset($o["output"])) {
if (isset($o["output"]["thumb"]) && !privacy_image_cache_is_local_image($o["output"]["thumb"]))
$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["thumb"]);
//$o["output"]["thumb"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["thumb"])));
if (isset($o["output"]["author-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["author-avatar"]))
$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["author-avatar"]);
//$o["output"]["author-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["author-avatar"])));
if (isset($o["output"]["owner-avatar"]) && !privacy_image_cache_is_local_image($o["output"]["owner-avatar"]))
$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner-avatar"]);
//$o["output"]["owner-avatar"] = $a->get_baseurl() . "/privacy_image_cache/?url=" . escape_tags(addslashes(rawurlencode($o["output"]["owner-avatar"])));
if (isset($o["output"]["owner_photo"]) && !privacy_image_cache_is_local_image($o["output"]["owner_photo"]))
$o["output"]["owner_photo"] = $a->get_baseurl() . "/privacy_image_cache/".privacy_image_cache_cachename($o["output"]["owner_photo"]);
}
}

View file

@ -169,6 +169,7 @@ function twitter_settings_post ($a,$post) {
del_pconfig(local_user(), 'twitter', 'intelligent_shortening');
del_pconfig(local_user(), 'twitter', 'import');
del_pconfig(local_user(), 'twitter', 'create_user');
del_pconfig(local_user(), 'twitter', 'own_id');
} else {
if (isset($_POST['twitter-pin'])) {
// if the user supplied us with a PIN from Twitter, let the magic of OAuth happen
@ -632,8 +633,12 @@ function twitter_post_hook(&$a,&$b) {
$orig_post = $r[0];
}
// To-Do: Ab dem letzten / nehmen
$b["body"] = "@".substr($orig_post["author-link"], 20)." ".$b["body"];
$nickname = preg_replace("=https?://twitter.com/(.*)=ism", "$1", $orig_post["author-link"]);
$nickname = "@[url=".$orig_post["author-link"]."]".$nickname."[/url]";
logger("twitter_post_hook: comparing ".$nickname." with ".$b["body"], LOGGER_DEBUG);
if (strpos($b["body"], $nickname) === false)
$b["body"] = $nickname." ".$b["body"];
logger("twitter_post_hook: parent found ".print_r($orig_post, true), LOGGER_DATA);
} else {
@ -680,9 +685,14 @@ function twitter_post_hook(&$a,&$b) {
if($ckey && $csecret && $otoken && $osecret) {
logger('twitter: we have customer key and oauth stuff, going to send.', LOGGER_DEBUG);
// If it's a repeated message from twitter then do a native retweet and exit
if (twitter_is_retweet($a, $b['uid'], $b['body']))
return;
require_once('library/twitteroauth.php');
require_once('include/bbcode.php');
$tweet = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
// in theory max char is 140 but T. uses t.co to make links
// longer so we give them 10 characters extra
if (!$intelligent_shortening) {
@ -767,6 +777,7 @@ function twitter_post_hook(&$a,&$b) {
$msg = $msgarr["msg"];
$image = $msgarr["image"];
}
// and now tweet it :-)
if(strlen($msg) and ($image != "")) {
$img_str = fetch_url($image);
@ -792,16 +803,6 @@ function twitter_post_hook(&$a,&$b) {
$result = $cb->statuses_updateWithMedia($post);
unlink($tempfile);
/*
// Old Code
$mime = image_type_to_mime_type(exif_imagetype($tempfile));
unlink($tempfile);
$filename = "upload";
$result = $tweet->post('statuses/update_with_media', array('media[]' => "{$img_str};type=".$mime.";filename={$filename}" , 'status' => $msg));
*/
logger('twitter_post_with_media send, result: ' . print_r($result, true), LOGGER_DEBUG);
if ($result->errors OR $result->error) {
logger('Send to Twitter failed: "' . print_r($result->errors, true) . '"');
@ -1119,6 +1120,24 @@ function twitter_queue_hook(&$a,&$b) {
function twitter_fetch_contact($uid, $contact, $create_user) {
// Check if the unique contact is existing
// To-Do: only update once a while
$r = q("SELECT id FROM unique_contacts WHERE url='%s' LIMIT 1",
dbesc(normalise_link("https://twitter.com/".$contact->screen_name)));
if (count($r) == 0)
q("INSERT INTO unique_contacts (url, name, nick, avatar) VALUES ('%s', '%s', '%s', '%s')",
dbesc(normalise_link("https://twitter.com/".$contact->screen_name)),
dbesc($contact->name),
dbesc($contact->screen_name),
dbesc($contact->profile_image_url_https));
else
q("UPDATE unique_contacts SET name = '%s', nick = '%s', avatar = '%s' WHERE url = '%s'",
dbesc($contact->name),
dbesc($contact->screen_name),
dbesc($contact->profile_image_url_https),
dbesc(normalise_link("https://twitter.com/".$contact->screen_name)));
$r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `alias` = '%s' LIMIT 1",
intval($uid), dbesc("twitter::".$contact->id_str));
@ -1191,6 +1210,7 @@ function twitter_fetch_contact($uid, $contact, $create_user) {
dbesc(datetime_convert()),
intval($contact_id)
);
} else {
// update profile photos once every two weeks as we have no notification of when they change.
@ -1282,6 +1302,7 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
$has_picture = false;
$postarray = array();
$postarray['network'] = NETWORK_TWITTER;
$postarray['gravity'] = 0;
$postarray['uid'] = $uid;
$postarray['wall'] = 0;
@ -1425,6 +1446,7 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
$postarray['body'] = $converted["body"];
$postarray['tag'] = $converted["tags"];
twitter_fetch_contact($uid, $post->retweeted_status->user, false);
// Deactivated at the moment, since there are problems with answers to retweets
if (false AND !intval(get_config('system','wall-to-wall_share'))) {
@ -1439,6 +1461,10 @@ function twitter_createpost($a, $uid, $post, $self, $create_user, $only_existing
$postarray['author-name'] = $post->retweeted_status->user->name;
$postarray['author-link'] = "https://twitter.com/".$post->retweeted_status->user->screen_name;
$postarray['author-avatar'] = $post->retweeted_status->user->profile_image_url_https;
//if (($post->retweeted_status->user->screen_name != "") AND ($post->retweeted_status->id_str != "")) {
// $postarray['plink'] = "https://twitter.com/".$post->retweeted_status->user->screen_name."/status/".$post->retweeted_status->id_str;
// $postarray['uri'] = "twitter::".$post->retweeted_status->id_str;
//}
}
}
@ -1757,7 +1783,8 @@ function twitter_siteinfo($url, $dontincludemedia) {
if (sizeof($data["images"]) > 0) {
$imagedata = $data["images"][0];
$text .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
//$text .= '[img='.$imagedata["width"].'x'.$imagedata["height"].']'.$imagedata["src"].'[/img]' . "\n";
$text .= '[img]'.$imagedata["src"].'[/img]'."\n";
}
if (is_string($data["text"]))
@ -1789,17 +1816,6 @@ function twitter_convertmsg($a, $body, $no_tags = false, $dontincludemedia) {
if ($type == "")
$type = $oembed_data->type;
// To-Do:
// Twitlonger
// if (strstr($expanded_url, "//www.youtube.com/"))
// $body = str_replace($match[2], "\n[youtube]".$expanded_url."[/youtube]\n", $body);
// elseif (strstr($expanded_url, "//player.vimeo.com/"))
// $body = str_replace($match[2], "\n[vimeo]".$expanded_url."[/vimeo]\n", $body);
// elseif (strstr($expanded_url, "//twitpic.com/")) // Test
// $body = str_replace($match[2], "\n[url]".$expanded_url."[/url]\n", $body);
// elseif (strstr($expanded_url, "//instagram.com/"))
// $body = str_replace($match[2], "\n[url]".$expanded_url."[/url]\n", $body);
if ($oembed_data->type != "link")
$body = str_replace($match[2], "\n[url]".$expanded_url."[/url]\n", $body);
else {
@ -1914,8 +1930,57 @@ function twitter_fetch_own_contact($a, $uid) {
intval($uid), dbesc("twitter::".$own_id));
if(count($r))
$contact_id = $r[0]["id"];
else
del_pconfig($uid, 'twitter', 'own_id');
}
return($contact_id);
}
function twitter_is_retweet($a, $uid, $body) {
$body = trim($body);
// Skip if it isn't a pure repeated messages
// Does it start with a share?
if (strpos($body, "[share") > 0)
return(false);
// Does it end with a share?
if (strlen($body) > (strrpos($body, "[/share]") + 8))
return(false);
$attributes = preg_replace("/\[share(.*?)\]\s?(.*?)\s?\[\/share\]\s?/ism","$1",$body);
// Skip if there is no shared message in there
if ($body == $attributes)
return(false);
$link = "";
preg_match("/link='(.*?)'/ism", $attributes, $matches);
if ($matches[1] != "")
$link = $matches[1];
preg_match('/link="(.*?)"/ism', $attributes, $matches);
if ($matches[1] != "")
$link = $matches[1];
$id = preg_replace("=https?://twitter.com/(.*)/status/(.*)=ism", "$2", $link);
if ($id == $link)
return(false);
logger('twitter_is_retweet: Retweeting id '.$id.' for user '.$uid, LOGGER_DEBUG);
$ckey = get_config('twitter', 'consumerkey');
$csecret = get_config('twitter', 'consumersecret');
$otoken = get_pconfig($uid, 'twitter', 'oauthtoken');
$osecret = get_pconfig($uid, 'twitter', 'oauthsecret');
require_once('library/twitteroauth.php');
$connection = new TwitterOAuth($ckey,$csecret,$otoken,$osecret);
$result = $connection->post('statuses/retweet/'.$id);
return(!isset($result->errors));
}
?>