Implement a class for automatic temporary file handling

And adopt it all over the code.
This commit is contained in:
Alexei Sorokin
2020-09-04 13:15:23 +03:00
committed by Diogo Peralta Cordeiro
parent 590891139f
commit 7fa4d56f05
9 changed files with 626 additions and 362 deletions

View File

@@ -30,8 +30,11 @@ class FFmpegPlugin extends Plugin
{
const PLUGIN_VERSION = '0.1.0';
public function onStartResizeImageFile(ImageFile $imagefile, string $outpath, array $box): bool
{
public function onStartResizeImageFile(
ImageFile $imagefile,
string $outpath,
array $box
): bool {
switch ($imagefile->mimetype) {
case 'image/gif':
// resize only if an animated GIF
@@ -49,7 +52,7 @@ class FFmpegPlugin extends Plugin
* @see http://blog.pkh.me/p/21-high-quality-gif-with-ffmpeg.html
* @see https://github.com/PHP-FFMpeg/PHP-FFMpeg/pull/592
*/
public function resizeImageFileAnimatedGif(ImageFile $imagefile, string $outpath, array $box): bool
public function resizeImageFileAnimatedGif(ImageFile $imagefile, string $outpath, array $box): bool
{
// Create FFMpeg instance
// Need to explictly tell the drivers location or it won't find them
@@ -60,7 +63,7 @@ class FFmpegPlugin extends Plugin
// FFmpeg can't edit existing files in place,
// generate temporary output file to avoid that
$tmp_outpath = tempnam(sys_get_temp_dir(), 'outpath-');
$tempfile = new TemporaryFile('gs-outpath');
// Generate palette file. FFmpeg explictly needs to be told the
// extension for PNG files outputs
@@ -89,7 +92,7 @@ class FFmpegPlugin extends Plugin
$commands_2[] = '-f';
$commands_2[] = 'gif';
$commands_2[] = '-y';
$commands_2[] = $tmp_outpath;
$commands_2[] = $tempfile->getRealPath();
$success = true;
@@ -112,10 +115,9 @@ class FFmpegPlugin extends Plugin
}
if ($success) {
$success = @rename($tmp_outpath, $outpath);
$success = $tempfile->commit($outpath);
}
@unlink($tmp_outpath);
@unlink($palette);
return $success;

View File

@@ -1,85 +1,121 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
function linkback_lenient_target_match($body, $target) {
return strpos(''.$body, str_replace(array('http://www.', 'http://', 'https://www.', 'https://'), '', preg_replace('/\/+$/', '', preg_replace( '/#.*/', '', $target))));
defined('GNUSOCIAL') || die();
function linkback_lenient_target_match($body, $target)
{
return strpos('' . $body, str_replace(
['http://www.', 'http://', 'https://www.', 'https://'],
'',
preg_replace('/\/+$/', '', preg_replace('/#.*/', '', $target))
));
}
function linkback_get_source($source, $target) {
function linkback_get_source($source, $target)
{
// Check if we are pinging ourselves and ignore
$localprefix = common_config('site', 'server') . '/' . common_config('site', 'path');
if(linkback_lenient_target_match($source, $localprefix) === 0) {
if (linkback_lenient_target_match($source, $localprefix) === 0) {
common_debug('Ignoring self ping from ' . $source . ' to ' . $target);
return NULL;
return null;
}
$request = HTTPClient::start();
try {
$response = $request->get($source);
} catch(Exception $ex) {
return NULL;
} catch (Exception $ex) {
return null;
}
$body = htmlspecialchars_decode($response->getBody());
// We're slightly more lenient in our link detection than the spec requires
if(linkback_lenient_target_match($body, $target) === FALSE) {
return NULL;
if (linkback_lenient_target_match($body, $target) === false) {
return null;
}
return $response;
}
function linkback_get_target($target) {
function linkback_get_target($target)
{
// Resolve target (https://github.com/converspace/webmention/issues/43)
$request = HTTPClient::start();
try {
$response = $request->head($target);
} catch(Exception $ex) {
return NULL;
} catch (Exception $ex) {
return null;
}
try {
$notice = Notice::fromUri($response->getEffectiveUrl());
} catch(UnknownUriException $ex) {
} catch (UnknownUriException $ex) {
preg_match('/\/notice\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
$notice = Notice::getKV('id', $match[1]);
}
if($notice instanceof Notice && $notice->isLocal()) {
if ($notice instanceof Notice && $notice->isLocal()) {
return $notice;
} else {
$user = User::getKV('uri', $response->getEffectiveUrl());
if(!$user) {
if (!$user) {
preg_match('/\/user\/(\d+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
$user = User::getKV('id', $match[1]);
}
if(!$user) {
if (!$user) {
preg_match('/\/([^\/\?#]+)(?:#.*)?$/', $response->getEffectiveUrl(), $match);
if(linkback_lenient_target_match(common_profile_url($match[1]), $response->getEffectiveUrl()) !== FALSE) {
if (linkback_lenient_target_match(
common_profile_url($match[1]),
$response->getEffectiveUrl()
) !== false) {
$user = User::getKV('nickname', $match[1]);
}
}
if($user instanceof User) {
if ($user instanceof User) {
return $user;
}
}
return NULL;
return null;
}
function linkback_is_contained_in($entry, $target) {
function linkback_is_contained_in($entry, $target)
{
foreach ((array)$entry['properties'] as $key => $values) {
if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target) !== FALSE; })) > 0) {
if (count(array_filter($values, function ($x) use ($target) {
return linkback_lenient_target_match($x, $target) !== false;
})) > 0) {
return $entry['properties'];
}
// check included h-* formats and their links
foreach ($values as $obj) {
if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
isset($obj['properties']) && isset($obj['properties']['url']) &&
count(array_filter($obj['properties']['url'],
function($x) use ($target) { return linkback_lenient_target_match($x, $target) !== FALSE; })) > 0
if (
array_key_exists('type', $obj)
&& array_intersect(['h-cite', 'h-entry'], $obj['type'])
&& array_key_exists('properties', $obj)
&& array_key_exists('url', $obj['properties'])
&& count(array_filter(
$obj['properties']['url'],
function ($x) use ($target) {
return linkback_lenient_target_match($x, $target) !== false;
}
)) > 0
) {
return $entry['properties'];
}
@@ -94,8 +130,8 @@ function linkback_is_contained_in($entry, $target) {
}
}
foreach((array)$entry['children'] as $mf2) {
if(linkback_is_contained_in($mf2, $target)) {
foreach ((array) $entry['children'] as $mf2) {
if (linkback_is_contained_in($mf2, $target)) {
return $entry['properties'];
}
}
@@ -104,33 +140,43 @@ function linkback_is_contained_in($entry, $target) {
}
// Based on https://github.com/acegiak/Semantic-Linkbacks/blob/master/semantic-linkbacks-microformats-handler.php, GPL-2.0+
function linkback_find_entry($mf2, $target) {
if(isset($mf2['items'][0]['type']) && in_array("h-feed", $mf2['items'][0]["type"]) && isset($mf2['items'][0]['children'])) {
function linkback_find_entry($mf2, $target)
{
if (
array_key_exists('type', $mf2['items'][0])
&& in_array('h-feed', $mf2['items'][0]['type'])
&& array_key_exists('children', $mf2['items'][0])
) {
$mf2['items'] = $mf2['items'][0]['children'];
}
$entries = array_filter($mf2['items'], function($x) { return isset($x['type']) && in_array('h-entry', $x['type']); });
$entries = array_filter($mf2['items'], function ($x) {
return array_key_exists('type', $x) && in_array('h-entry', $x['type']);
});
foreach ($entries as $entry) {
if($prop = linkback_is_contained_in($entry, $target)) {
if (($prop = linkback_is_contained_in($entry, $target))) {
return $prop;
}
}
// Default to first one
if(count($entries) > 0) {
if (count($entries) > 0) {
return $entries[0]['properties'];
}
return NULL;
return null;
}
function linkback_entry_type($entry, $mf2, $target) {
if(!$entry) { return 'mention'; }
function linkback_entry_type($entry, $mf2, $target)
{
if (!$entry) {
return 'mention';
}
if($mf2['rels'] && $mf2['rels']['in-reply-to']) {
foreach($mf2['rels']['in-reply-to'] as $url) {
if(linkback_lenient_target_match($url, $target) !== FALSE) {
if ($mf2['rels'] && $mf2['rels']['in-reply-to']) {
foreach ($mf2['rels']['in-reply-to'] as $url) {
if (linkback_lenient_target_match($url, $target) !== false) {
return 'reply';
}
}
@@ -143,18 +189,31 @@ function linkback_entry_type($entry, $mf2, $target) {
'tag-of' => 'tag'
);
foreach((array)$entry as $key => $values) {
if(count(array_filter($values, function($x) use ($target) { return linkback_lenient_target_match($x, $target) != FALSE; })) > 0) {
if($classes[$key]) { return $classes[$key]; }
foreach ((array) $entry as $key => $values) {
if (count(array_filter($values, function ($x) use ($target) {
return linkback_lenient_target_match($x, $target) !== false;
})) > 0) {
if ($classes[$key]) {
return $classes[$key];
}
}
foreach ($values as $obj) {
if(isset($obj['type']) && array_intersect(array('h-cite', 'h-entry'), $obj['type']) &&
isset($obj['properties']) && isset($obj['properties']['url']) &&
count(array_filter($obj['properties']['url'],
function($x) use ($target) { return linkback_lenient_target_match($x, $target) != FALSE; })) > 0
if (
array_key_exists('type', $obj)
&& array_intersect(['h-cite', 'h-entry'], $obj['type'])
&& array_key_exists('properties', $obj)
&& array_key_exists('url', $obj['properties'])
&& count(array_filter(
$obj['properties']['url'],
function ($x) use ($target) {
return linkback_lenient_target_match($x, $target) !== false;
}
)) > 0
) {
if($classes[$key]) { return $classes[$key]; }
if ($classes[$key]) {
return $classes[$key];
}
}
}
}
@@ -162,7 +221,8 @@ function linkback_entry_type($entry, $mf2, $target) {
return 'mention';
}
function linkback_is_dupe($key, $url) {
function linkback_is_dupe($key, $url)
{
$dupe = Notice::getKV($key, $url);
if ($dupe instanceof Notice) {
return $dupe;
@@ -172,19 +232,23 @@ function linkback_is_dupe($key, $url) {
}
function linkback_hcard($mf2, $url) {
if(empty($mf2['items'])) {
function linkback_hcard($mf2, $url)
{
if (empty($mf2['items'])) {
return null;
}
$hcards = array();
foreach($mf2['items'] as $item) {
if(!in_array('h-card', $item['type'])) {
foreach ($mf2['items'] as $item) {
if (!in_array('h-card', $item['type'])) {
continue;
}
// We found a match, return it immediately
if(isset($item['properties']['url']) && in_array($url, $item['properties']['url'])) {
if (
array_key_exists('url', $item['properties'])
&& in_array($url, $item['properties']['url'])
) {
return $item['properties'];
}
@@ -200,23 +264,26 @@ function linkback_hcard($mf2, $url) {
return null;
}
function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
function linkback_notice($source, $notice_or_user, $entry, $author, $mf2)
{
$content = isset($entry['content']) ? $entry['content'][0]['html'] :
(isset($entry['summary']) ? $entry['summary'][0] : $entry['name'][0]);
$rendered = common_purify($content);
if($notice_or_user instanceof Notice && $entry['type'] == 'mention') {
if ($notice_or_user instanceof Notice && $entry['type'] === 'mention') {
$name = isset($entry['name']) ? $entry['name'][0] : substr(common_strip_html($content), 0, 20).'…';
$rendered = _m('linked to this from <a href="'.htmlspecialchars($source).'">'.htmlspecialchars($name).'</a>');
}
$content = common_strip_html($rendered);
$shortened = common_shorten_links($content);
if(Notice::contentTooLong($shortened)) {
$content = substr($content,
0,
Notice::maxContent() - (mb_strlen($source) + 2));
if (Notice::contentTooLong($shortened)) {
$content = substr(
$content,
0,
(Notice::maxContent() - (mb_strlen($source) + 2))
);
$rendered = $content . '<a href="'.htmlspecialchars($source).'">…</a>';
$content .= ' ' . $source;
}
@@ -231,10 +298,10 @@ function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
'tags' => array(),
'urls' => array());
if($notice_or_user instanceof User) {
if ($notice_or_user instanceof User) {
$options['replies'][] = $notice_or_user->getUri();
} else {
if($entry['type'] == 'repost') {
if ($entry['type'] === 'repost') {
$options['repeat_of'] = $notice_or_user->id;
} else {
$options['reply_to'] = $notice_or_user->id;
@@ -253,74 +320,75 @@ function linkback_notice($source, $notice_or_user, $entry, $author, $mf2) {
common_debug('Linkback got invalid HTTP URL for photo: '._ve($entry['photo']));
}
foreach((array)$entry['category'] as $tag) {
foreach ((array) $entry['category'] as $tag) {
$tag = common_canonical_tag($tag);
if($tag) { $options['tags'][] = $tag; }
if ($tag) {
$options['tags'][] = $tag;
}
}
if($mf2['rels'] && $mf2['rels']['enclosure']) {
foreach($mf2['rels']['enclosure'] as $url) {
if ($mf2['rels'] && $mf2['rels']['enclosure']) {
foreach ($mf2['rels']['enclosure'] as $url) {
$options['urls'][] = $url;
}
}
if($mf2['rels'] && $mf2['rels']['tag']) {
foreach($mf2['rels']['tag'] as $url) {
if ($mf2['rels'] && $mf2['rels']['tag']) {
foreach ($mf2['rels']['tag'] as $url) {
preg_match('/\/([^\/]+)\/*$/', $url, $match);
$tag = common_canonical_tag($match[1]);
if($tag) { $options['tags'][] = $tag; }
}
if ($tag) {
$options['tags'][] = $tag;
}
}
}
if($entry['type'] != 'reply' && $entry['type'] != 'repost') {
$options['urls'] = array();
if ($entry['type'] !== 'reply' && $entry['type'] !== 'repost') {
$options['urls'] = [];
}
return array($content, $options);
return [$content, $options];
}
function linkback_avatar($profile, $url) {
function linkback_avatar($profile, $url)
{
// Ripped from OStatus plugin for now
$temp_filename = tempnam(sys_get_temp_dir(), 'linback_avatar');
try {
$imgData = HTTPClient::quickGet($url);
// Make sure it's at least an image file. ImageFile can do the rest.
if (false === getimagesizefromstring($imgData)) {
return false;
}
file_put_contents($temp_filename, $imgData);
unset($imgData); // No need to carry this in memory.
$imagefile = new ImageFile(null, $temp_filename);
$filename = Avatar::filename($profile->id,
image_type_to_extension($imagefile->type),
null,
common_timestamp());
rename($temp_filename, Avatar::path($filename));
} catch (Exception $e) {
unlink($temp_filename);
throw $e;
$tempfile = new TemporaryFile('gs-avatarlinback');
$img_data = HTTPClient::quickGet($url);
// Make sure it's at least an image file. ImageFile can do the rest.
if (getimagesizefromstring($img_data) === false) {
return false;
}
// @todo FIXME: Hardcoded chmod is lame, but seems to be necessary to
// keep from accidentally saving images from command-line (queues)
// that can't be read from web server, which causes hard-to-notice
// problems later on:
//
// http://status.net/open-source/issues/2663
chmod(Avatar::path($filename), 0644);
fwrite($tempfile->getResource(), $img_data);
fflush($tempfile->getResource());
// No need to carry this in memory.
unset($img_data);
$imagefile = new ImageFile(-1, $tempfile->getRealPath());
$filename = Avatar::filename(
$profile->id,
image_type_to_extension($imagefile->type),
null,
common_timestamp()
);
$tempfile->commit(Avatar::path($filename));
$profile->setOriginal($filename);
}
function linkback_profile($entry, $mf2, $response, $target) {
if(isset($entry['author']) && isset($entry['author'][0]['properties'])) {
function linkback_profile($entry, $mf2, $response, $target)
{
if (
array_key_exists('author', $entry)
&& array_key_exists('properties', $entry['author'][0])
) {
$author = $entry['author'][0]['properties'];
} else {
$author = linkback_hcard($mf2, $response->getEffectiveUrl());
}
if(!$author) {
if (!$author) {
$author = array('name' => $entry['name']);
}
@@ -336,7 +404,7 @@ function linkback_profile($entry, $mf2, $response, $target) {
try {
$profile = Profile::fromUri($author['url'][0]);
} catch(UnknownUriException $ex) {
} catch (UnknownUriException $ex) {
$profile = Profile::getKV('profileurl', $author['url'][0]);
}
@@ -349,7 +417,7 @@ function linkback_profile($entry, $mf2, $response, $target) {
$profile->created = common_sql_now();
$profile->insert();
if($author['photo'] && $author['photo'][0]) {
if ($author['photo'] && $author['photo'][0]) {
linkback_avatar($profile, $author['photo'][0]);
}
}
@@ -357,17 +425,24 @@ function linkback_profile($entry, $mf2, $response, $target) {
return array($profile, $author);
}
function linkback_save($source, $target, $response, $notice_or_user) {
function linkback_save($source, $target, $response, $notice_or_user)
{
$dupe = linkback_is_dupe('uri', $response->getEffectiveUrl());
if(!$dupe) { $dupe = linkback_is_dupe('url', $response->getEffectiveUrl()); }
if(!$dupe) { $dupe = linkback_is_dupe('uri', $source); }
if(!$dupe) { $dupe = linkback_is_dupe('url', $source); }
if (!$dupe) {
$dupe = linkback_is_dupe('url', $response->getEffectiveUrl());
}
if (!$dupe) {
$dupe = linkback_is_dupe('uri', $source);
}
if (!$dupe) {
$dupe = linkback_is_dupe('url', $source);
}
$mf2 = new Mf2\Parser($response->getBody(), $response->getEffectiveUrl());
$mf2 = $mf2->parse();
$entry = linkback_find_entry($mf2, $target);
if(!$entry) {
if (!$entry) {
preg_match('/<title>([^<]+)', $response->getBody(), $match);
$entry = array(
'content' => array('html' => $response->getBody()),
@@ -375,25 +450,38 @@ function linkback_save($source, $target, $response, $notice_or_user) {
);
}
if(!$entry['url']) {
if (!$entry['url']) {
$entry['url'] = array($response->getEffectiveUrl());
}
if(!$dupe) { $dupe = linkback_is_dupe('uri', $entry['url'][0]); }
if(!$dupe) { $dupe = linkback_is_dupe('url', $entry['url'][0]); }
if (!$dupe) {
$dupe = linkback_is_dupe('uri', $entry['url'][0]);
}
if (!$dupe) {
$dupe = linkback_is_dupe('url', $entry['url'][0]);
}
$entry['type'] = linkback_entry_type($entry, $mf2, $target);
list($profile, $author) = linkback_profile($entry, $mf2, $response, $target);
list($content, $options) = linkback_notice($source, $notice_or_user, $entry, $author, $mf2);
if($dupe) {
if ($dupe) {
$orig = clone($dupe);
try {
// Ignore duplicate save error
try { $dupe->saveKnownReplies($options['replies']); } catch (ServerException $ex) {}
try { $dupe->saveKnownTags($options['tags']); } catch (ServerException $ex) {}
try { $dupe->saveKnownUrls($options['urls']); } catch (ServerException $ex) {}
try {
$dupe->saveKnownReplies($options['replies']);
} catch (ServerException $ex) {
}
try {
$dupe->saveKnownTags($options['tags']);
} catch (ServerException $ex) {
}
try {
$dupe->saveKnownUrls($options['urls']);
} catch (ServerException $ex) {
}
if (isset($options['reply_to'])) {
$dupe->reply_to = $options['reply_to'];
@@ -403,13 +491,18 @@ function linkback_save($source, $target, $response, $notice_or_user) {
}
if ($dupe->reply_to != $orig->reply_to || $dupe->repeat_of != $orig->repeat_of) {
$parent = Notice::getKV('id', $dupe->repeat_of ?: $dupe->reply_to);
if($parent instanceof Notice) {
if ($parent instanceof Notice) {
// If we changed the reply_to or repeat_of we might live in a new conversation now
$dupe->conversation = $parent->conversation;
}
}
if($dupe->update($orig)) { $saved = $dupe; }
if($dupe->conversation != $orig->conversation && Conversation::noticeCount($orig->conversation) < 1) {
if ($dupe->update($orig)) {
$saved = $dupe;
}
if (
$dupe->conversation !== $orig->conversation
&& Conversation::noticeCount($orig->conversation) < 1
) {
// Delete empty conversation
$emptyConversation = Conversation::getKV('id', $orig->conversation);
$emptyConversation->delete();
@@ -419,7 +512,10 @@ function linkback_save($source, $target, $response, $notice_or_user) {
return false;
}
common_log(LOG_INFO, "Linkback updated remote message $source as notice id $saved->id");
} else if($entry['type'] == 'like' || ($entry['type'] == 'reply' && $entry['rsvp'])) {
} elseif (
$entry['type'] === 'like'
|| ($entry['type'] === 'reply' && $entry['rsvp'])
) {
$act = new Activity();
$act->type = ActivityObject::ACTIVITY;
$act->time = $options['created'] ? strtotime($options['created']) : time();
@@ -430,19 +526,22 @@ function linkback_save($source, $target, $response, $notice_or_user) {
// TRANS: Message that is the "content" of a favorite (%1$s is the actor's nickname, %2$ is the favorited
// notice's nickname and %3$s is the content of the favorited notice.)
$act->content = sprintf(_('%1$s favorited something by %2$s: %3$s'),
$profile->getNickname(), $notice_or_user->getProfile()->getNickname(),
$notice_or_user->getRendered());
if($entry['rsvp']) {
$act->content = sprintf(
_('%1$s favorited something by %2$s: %3$s'),
$profile->getNickname(),
$notice_or_user->getProfile()->getNickname(),
$notice_or_user->getRendered()
);
if ($entry['rsvp']) {
$act->content = $options['rendered'];
}
$act->verb = ActivityVerb::FAVORITE;
if(strtolower($entry['rsvp'][0]) == 'yes') {
if (strtolower($entry['rsvp'][0]) === 'yes') {
$act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-yes';
} else if(strtolower($entry['rsvp'][0]) == 'no') {
} elseif (strtolower($entry['rsvp'][0]) === 'no') {
$act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-no';
} else if(strtolower($entry['rsvp'][0]) == 'maybe') {
} elseif (strtolower($entry['rsvp'][0]) === 'maybe') {
$act->verb = 'http://activitystrea.ms/schema/1.0/rsvp-maybe';
}
@@ -464,10 +563,12 @@ function linkback_save($source, $target, $response, $notice_or_user) {
} else {
// Fallback is to make a notice manually
try {
$saved = Notice::saveNew($profile->id,
$content,
'linkback',
$options);
$saved = Notice::saveNew(
$profile->id,
$content,
'linkback',
$options
);
} catch (Exception $e) {
common_log(LOG_ERR, "Linkback save of remote message $source failed: " . $e->getMessage());
return false;

View File

@@ -1,51 +1,38 @@
<?php
// This file is part of GNU social - https://www.gnu.org/software/social
//
// GNU social is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// GNU social 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with GNU social. If not, see <http://www.gnu.org/licenses/>.
/**
* StatusNet - the distributed open-source microblogging tool
* Copyright (C) 2010, StatusNet, Inc.
*
* Plugin to pull WikiHow-style user avatars at OpenID setup time.
* These are not currently exposed via OpenID.
*
* PHP version 5
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* 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 Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* @category Plugins
* @package StatusNet
* @package GNUsocial
* @author Brion Vibber <brion@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
if (!defined('STATUSNET')) {
// This check helps protect against security problems;
// your code file can't be executed directly from the web.
exit(1);
}
defined('GNUSOCIAL') || die();
/**
* Sample plugin main class
*
* Each plugin requires a main class to interact with the StatusNet system.
*
* @category Plugins
* @package WikiHowProfilePlugin
* @author Brion Vibber <brion@status.net>
* @copyright 2010 StatusNet, Inc.
* @license http://www.fsf.org/licensing/licenses/agpl-3.0.html AGPL 3.0
* @link http://status.net/
* @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
*/
class WikiHowProfilePlugin extends Plugin
{
@@ -70,7 +57,7 @@ class WikiHowProfilePlugin extends Plugin
* @param string $canonical OpenID provider URL
* @param array $sreg query data from provider
*/
function onEndOpenIDCreateNewUser($user, $canonical, $sreg)
public function onEndOpenIDCreateNewUser($user, $canonical, $sreg)
{
$this->updateProfile($user, $canonical);
return true;
@@ -83,7 +70,7 @@ class WikiHowProfilePlugin extends Plugin
* @param string $canonical OpenID provider URL (wiki profile page)
* @param array $sreg query data from provider
*/
function onEndOpenIDUpdateUser($user, $canonical, $sreg)
public function onEndOpenIDUpdateUser($user, $canonical, $sreg)
{
$this->updateProfile($user, $canonical);
return true;
@@ -180,26 +167,25 @@ class WikiHowProfilePlugin extends Plugin
// @todo FIXME: This should be better encapsulated
// ripped from OStatus via oauthstore.php (for old OMB client)
$temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
try {
if (!copy($url, $temp_filename)) {
// TRANS: Exception thrown when fetching an avatar from a URL fails.
// TRANS: %s is a URL.
throw new ServerException(sprintf(_m('Unable to fetch avatar from %s.'), $url));
}
$profile = $user->getProfile();
$id = $profile->id;
$imagefile = new ImageFile(null, $temp_filename);
$filename = Avatar::filename($id,
image_type_to_extension($imagefile->type),
null,
common_timestamp());
rename($temp_filename, Avatar::path($filename));
} catch (Exception $e) {
unlink($temp_filename);
throw $e;
$tempfile = new TemporaryFile('gs-avatarlisten');
$img_data = HTTPClient::quickGet($url);
// Make sure it's at least an image file. ImageFile can do the rest.
if (getimagesizefromstring($img_data) === false) {
return false;
}
fwrite($tempfile->getResource(), $img_data);
fflush($tempfile->getResource());
$profile = $user->getProfile();
$id = $profile->id;
$imagefile = new ImageFile(-1, $tempfile->getRealPath());
$filename = Avatar::filename(
$id,
image_type_to_extension($imagefile->type),
null,
common_timestamp()
);
$tempfile->commit(Avatar::path($filename));
$profile->setOriginal($filename);
}
}