networked = is_multisite();
}
elseif (defined("WPMU")) { // WPMU
if (WPMU) {
$this->networked = true;
}
}
$this->requestURI = $_SERVER['SCRIPT_NAME'] . '?page=' . @$_GET['page'];
// Default options...
$this->avatar_options = ($this->networked) ? get_site_option('plugin_avatars') : get_option('plugin_avatars') ;
if(!is_array($this->avatar_options)) {
// Options do not exist or have not yet been loaded so we define standard options...
$this->avatar_options = array(
'size' => '30',
'scale' => SCALED_SIZE,
'resize' => 'off',
'upsize' => 'off',
'snapshots' => 'off',
'in_posts' => 'on',
'credit' => 'on',
'twitter' => 'off',
'consumer_key' => '',
'consumer_secret' => '',
'access_token' => '',
'access_token_secret' => '',
'default' => '',
'upload_dir' => '',
'name' => 'on',
'widget_enabled' => 'on',
'url_wrap' => 'on',
'location' => 'website',
'legacy' => 'off',
'upload_allowed' => 'Y'
);
if($this->networked) {
update_site_option('plugin_avatars', $this->avatar_options);
}
else {
update_option('plugin_avatars', $this->avatar_options);
}
}
if(!isset($this->avatar_options['credit'])) {
$this->avatar_options['credit'] = 'on';
if($this->networked) {
update_site_option('plugin_avatars', $this->avatar_options);
}
else {
update_option('plugin_avatars', $this->avatar_options);
}
}
// User profile widget included?
if(file_exists(WP_PLUGIN_DIR . '/add-local-avatar/avatars-widget.php')) {
include(WP_PLUGIN_DIR . '/add-local-avatar/avatars-widget.php');
if(function_exists('avatars_logged_in_user_widget_init')) {
if($this->avatar_options['widget_enabled'] == 'on') {
add_action('plugins_loaded', 'avatars_logged_in_user_widget_init');
}
}
}
// Hooks...
add_action('admin_menu', array(&$this, 'avatar_menu')); // Plugin menu addition.
add_action('network_admin_menu', array(&$this, 'network_admin_menu')); // Multi-site menu.
add_filter('the_content', array(&$this, 'generate_avatar_in_posts')); // Insert avatar in to post content.
add_action('get_footer', array(&$this, 'avatar_footer')); // Footer; for plugin credit etc.
// add_action('profile_personal_options', array(&$this, 'avatar_uploader_option'));
add_action('show_user_profile', array(&$this, 'avatar_uploader_option')); // Show user's profile.
add_action('edit_user_profile', array(&$this, 'avatar_uploader_option')); // Edit user's profile.
// add_action('profile_update', array(&$this, 'avatar_upload')); // Perform avatar image upload.
add_action('init', array(&$this, 'avatars_initialise')); // Setup plugin.
add_filter('plugin_row_meta', array(&$this, 'avatar_links'), 10, 2); // Links on plugins admin area.
add_action('plugin_action_links_' . plugin_basename(__FILE__), array(&$this, 'avatar_shortcuts'), 10, 2); // Action links.
add_action('wp_ajax_avatars_manage', array(&$this, 'avatars_manage')); // Ajax handler for avatar uploads.
} // end constructor
// Helper function to find root directory.
function avatar_root()
{
if($this->avatar_options['legacy'] == 'on') {
return $_SERVER['DOCUMENT_ROOT'];
}
else {
return substr(ABSPATH, 0, -strlen(strrchr(substr(ABSPATH, 0, -1), '/')) - 1);
}
}
// Avatars initialise.
function avatars_initialise()
{
// Avatars admin styles.
if(is_admin()) {
wp_enqueue_style('avatars', plugins_url('/add-local-avatar/avatars-admin.css'), 'css');
}
else {
wp_enqueue_style('avatars', plugins_url('/add-local-avatar/avatars.css'), 'css');
}
// Image area select jQuery library.
wp_enqueue_style('imgareaselect');
wp_enqueue_script('imgareaselect');
// Thickbox styling for avatar upload faux-popup.
wp_enqueue_style('thickbox');
wp_enqueue_script('thickbox', null, array('jquery'));
// Text domain setup.
$test = WPLANG;
if(!empty($test)) {
load_plugin_textdomain('avatars', false, dirname(plugin_basename(__FILE__)));
}
}
// Try to get a Twitter avatar.
function get_twitter_avatar($id)
{
require_once('TwitterAPIExchange.php');
$settings = array(
'oauth_access_token' => $this->avatar_options['access_token'],
'oauth_access_token_secret' => $this->avatar_options['access_token_secret'],
'consumer_key' => $this->avatar_options['consumer_key'],
'consumer_secret' => $this->avatar_options['consumer_secret']
);
$twitter = new TwitterAPIExchange($settings);
$dat = json_decode($twitter->setGetfield(sprintf('?screen_name=%s', $id)) ->buildOauth('https://api.twitter.com/1.1/users/show.json', 'GET') ->performRequest(), true);
// Check Twitter URI for default Twitter (little birdie) icon use.
if(strpos($dat['profile_image_url'], TWITTER_STATIC) !== false) return '';
return $dat['profile_image_url'];
}
// Helper function to select correct default avatar image.
function check_switch($chk, $default, $size = SCALED_SIZE)
{
switch ($chk) {
case 'custom': return $default;
case 'mystery': return urlencode(FALLBACK . "?s=" . $size);
case 'blank': return includes_url('images/blank.gif');
case 'gravatar_default': return "";
default: return urlencode($chk);
}
}
// Return the type of avatar last returned.
function get_avatar_type()
{
global $avatar_type;
switch($avatar_type) {
case TYPE_TWITTER: return __('Twitter', 'avatars');
case TYPE_GLOBAL: return __('Global', 'avatars');
case TYPE_LOCAL: return __('Local', 'avatars');
default: return __('Unknown (!)', 'avatars');
}
}
// Manage avatars...
function manage_avatar_cache()
{
global $wpdb;
$msg = '';
// Show commenter avatars too?
$all = (@$_GET['act'] == 'all');
// Check table updates...
if(isset($_GET['user_id'])) {
$msg = __('Avatar', 'avatars') . ' ' . (empty($_GET['avatar']) ? __('removed', 'avatars') : __('updated', 'avatars')) . '.';
update_usermeta($_GET['user_id'], 'avatar', $_GET['avatar']);
update_usermeta($_GET['user_id'], 'twitter_id', $_GET['twitter_id']);
}
// Check form submission and update options...
if(isset($_POST['submit'])) {
$options_update = array (
'size' => $_POST['size'],
'scale' => $_POST['scale'],
'resize' => $_POST['resize'],
'upsize' => $_POST['upsize'],
'snapshots' => $_POST['snapshots'],
'in_posts' => $_POST['in_posts'],
'credit' => $_POST['credit'],
'twitter' => $_POST['twitter'],
'consumer_key' => $_POST['consumer_key'],
'consumer_secret' => $_POST['consumer_secret'],
'access_token' => $_POST['access_token'],
'access_token_secret' => $_POST['access_token_secret'],
'default' => $_POST['default'],
'upload_dir' => $_POST['upload_dir'],
'url_wrap' => $_POST['url_wrap'],
'name' => $_POST['name'],
'location' => $_POST['location'],
'legacy' => $_POST['legacy'],
'widget_enabled' => $_POST['widget_enabled'],
'upload_allowed' => $_POST['upload_allowed']
);
if ($this->networked) {
update_site_option('plugin_avatars', $options_update);
}
else {
update_option('plugin_avatars', $options_update);
update_option('show_avatars', ($_POST['show_avatars'] == 'on' ? 1 : 0));
update_option('avatar_rating', $_POST['avatar_rating']);
update_option('avatar_default', $_POST['wavatar']);
}
$msg = __('Options saved', 'avatars');
}
// Get options and set form action var
if ($this->networked) {
$this->avatar_options = get_site_option('plugin_avatars');
$form_action = $_SERVER['PHP_SELF'] . '?page=add_local_avatar&updated=true';
}
else {
$this->avatar_options = get_option('plugin_avatars');
$wavatar = get_option('avatar_default');
$form_action = $_SERVER['PHP_SELF'] . '?page=' . basename(__FILE__) . '&updated=true';
}
// Output any action message (note, can only be from a POST or GET not both).
if(!empty($msg)) echo "
"; ?>
Sterling Adventures, ...
Settings > Discussion', "avatars");
}
else {
$paged = (isset($_GET['userspage'])) ? $_GET['userspage'] : 1;
$paged -= 1;
$per_page = 20;
$offset = $paged * $per_page;
$args = array(
'number' => $per_page,
'offset' => $offset,
);
$user_search = new WP_User_Query($args);
// Do we have to page the results?
if($user_search->get_total() > $per_page) {
if ($this->networked) {
$paging_base = basename($this->requestURI) . '&%_%';
}
else {
$paging_base = 'users.php?page=avatars.php&%_%';
}
$paginating = paginate_links(array(
'total' => ceil($user_search->get_total() / $per_page),
'current' => $paged + 1,
'base' => $paging_base,
'format' => 'userspage=%#%'
)); ?>
|
|
|
|
|
|
|
|
get_results() as $user) {
printf('', ($i % 2 == 0 ? " class='alternate'" : ""));
printf('| %s | ', $user->ID, $user->user_login);
printf('%s %s%s | ', $user->first_name, $user->last_name, (empty($user->nickname) ? '' : ' (' . $user->nickname . ')'));
printf('%1$s | ', $user->user_email);
printf(' | ', $user->twitter_id, $i);
printf(' | ', $user->avatar, $i);
printf('%s | ', get_avatar($user->ID));
printf('%s | ', $this->get_avatar_type());
printf('%4$s | ', $this->requestURI, $user->ID, $i, __('Update', 'avatars'));
echo "
\n";
$i++;
}
?>
get_total() > $per_page) : ?>
requestURI . "&act=all'>", __('Click here', 'avatars'), ' ', __("to show commenter avatars.", 'avatars');
else echo __("Showing avatars for commenters.", 'avatars'), " ", __('Click here', 'avatars'), ' ', __("to hide commenter avatars.", 'avatars');
?>
get_var("select count(distinct comment_author_email) from $wpdb->comments where comment_author_email != ''");
$limit_start = ($com_page - 1) * $per_page;
$coms = $wpdb->get_results("select comment_author_email EML, comment_author ATH, count(comment_content) CNT from $wpdb->comments where comment_author_email != '' group by comment_author_email order by CNT DESC limit $limit_start, $per_page");
if($total > $per_page) {
$paging_text = paginate_links(array(
'total' => ceil($total / $per_page),
'current' => $com_page,
'base' => 'users.php?page=avatars.php&act=all&%_%',
'format' => 'comspage=%#%'
));
}
if($coms) { ?>
| | | |
EML)) {
printf('', ($i % 2 == 0 ? " class='alternate'" : ""));
printf('| %s | ', $com->ATH);
printf('%1$s | ', $com->EML);
printf('%s | ', $com->CNT);
printf('%s | ', get_avatar($com->EML));
echo "
\n";
$i++;
} ?>
FAQ & Installation
<?php $avtr = get_avatar(id [, size [, default-image-url]]); echo $avtr; ?>
id:
size:
default-image-url:
style.css
-
.avatar { float: left; padding: 2px; margin: 0; border: 1px solid #ddd; background: white; }
-
.post_avatar { padding: 2px; margin: 0; border: 1px solid #ddd; background: white; }
-
single.php <?php global $post; ?> <?php echo get_avatar($post->post_author); ?>
-
comments.php <?php echo get_avatar($comment); ?>
Donate';
}
return $links;
}
// Add link to Avatar settings on plugin list.
function avatar_shortcuts($links, $file)
{
if($file == plugin_basename(__FILE__)) {
$links[] = '' . __('Settings', 'avatars') . '';
}
return $links;
}
// Add credit.
function avatar_footer()
{
if($this->avatar_options['credit'] != 'off') {
printf("\n", ($this->avatar_options['credit'] == 'vis' ? '' : "style='display: none;'"));
}
}
// Add sub-menus...
function avatar_menu()
{
global $wp_version;
if ($this->networked) {
if( is_site_admin() ) {
if(version_compare($wp_version, '3.1', '<')) {
add_submenu_page('wpmu-admin.php', __('Avatars', 'avatars'), __('Avatars', 'avatars'), 'unfiltered_html', 'add_local_avatar', array(&$this, 'manage_avatar_cache'));
}
}
}
else {
add_users_page(__('Avatars', 'avatars'), __('Avatars', 'avatars'), 'manage_options', basename(__FILE__), array(&$this, 'manage_avatar_cache') );
}
}
// WP 3.1 network admin menu
function network_admin_menu()
{
add_submenu_page('settings.php', __('Avatars', 'avatars'), __('Avatars', 'avatars'), 'manage_options', 'add_local_avatar', array(&$this, 'manage_avatar_cache'));
}
// Replace in post content with an avatar.
function generate_avatar_in_posts($content)
{
// Is there content to work with?
if(!empty($content)) {
$matches = array();
$replacement = array();
$counter = 0;
// Look for all instances of in the content...
preg_match_all("//", $content, $matches);
// For each instance, let's try to parse it...
foreach($matches['1'] as $email) {
// Check if we should replace with an avatar or with 'nothing' (to protect email addresses from prying eyes/robots.
if(!get_option('show_avatars') || $this->avatar_options['in_posts'] != 'on') $replacement[$counter] = '';
else $replacement[$counter] = get_avatar($email, $this->avatar_options['size'], $this->avatar_options['default'], true);
$counter++;
}
// Replace...
for($i = 0; $i <= $counter; $i++) {
if(isset($replacement[$i])) {
$content = str_replace($matches[0][$i], $replacement[$i], $content);
}
}
}
return $content;
}
// Display any error text.
function output_avatar_error_message($usr)
{
if($usr->avatar_error) {
printf("%s %s
", __('Upload error:', 'avatars'), $usr->avatar_error);
}
delete_user_meta($usr->ID, 'avatar_error');
}
// Add upload option to user profile page.
function avatar_uploader_option($profileuser)
{ ?>
%s", __('Avatar', 'avatars')); ?>
avatar_uploader_table($profileuser, PRESENTATION_SIZE); ?>
ID, $size); ?>
%s %s.",
$this->get_avatar_type(),
__('avatar', 'avatars')
);
}
if($this->avatar_options['upload_allowed'] == 'on' || current_user_can('edit_users')) {
printf('%s',
admin_url('admin-ajax.php'),
$user->ID,
__('Avatar Management', 'avatars'),
__('Manage', 'avatars')
);
}
else {
if($widget) _e('Current avatar, Administrator may change.', 'avatars');
else _e('Avatar uploads not allowed (Administrator may set on Users » Avatars page).', 'avatars');
}
echo '';
}
// Figure out the (possible) three local avatar files.
function avatar_strip_suffix($file)
{
$parts = pathinfo($file);
$base = basename($file, '.' . $parts['extension']);
if(substr($base, -(strlen(AVATAR_SUFFIX) + 1)) == ('-' . AVATAR_SUFFIX)) {
$base = substr($base, 0, strlen($base) - (strlen(AVATAR_SUFFIX) + 1));
}
if(substr($base, -(strlen(AVATAR_CROPPED) + 1)) == ('-' . AVATAR_CROPPED)) {
$base = substr($base, 0, strlen($base) - (strlen(AVATAR_CROPPED) + 1));
}
$f[BASE_FILE] = $parts['dirname'] . '/' . $base . '.' . $parts['extension'];
$f[AVTR_FILE] = $parts['dirname'] . '/' . $base . '-' . AVATAR_SUFFIX . '.' . $parts['extension'];
$f[CROP_FILE] = $parts['dirname'] . '/' . $base . '-' . AVATAR_CROPPED . '.' . $parts['extension'];
return $f;
}
// AJAX function for thickbox faux-popup to manage avatar upload.
function avatars_manage()
{
global $current_user;
$uid = $_GET['uid'];
$user = get_userdata($uid);
$img_insert = "";
if(($uid == $current_user->ID || current_user_can('edit_users')) && is_numeric($_GET['uid'])) { ?>
>
Avatar Management
avatars_initialise();
do_action('admin_print_styles');
do_action('admin_print_scripts');
do_action('admin_head');
?>
avatar_strip_suffix($user->avatar);
$root = $this->avatar_root();
switch($_REQUEST['act']) {
case 'DEL':
// Check NONCE...
if(!wp_verify_nonce($_REQUEST['n'], AVATARS_NONCE_KEY)) die('(1) Security check.');
// Remove local avatar files.
foreach($files as $f) {
if(file_exists($root . $f)) @unlink($root . $f);
}
delete_usermeta($uid, 'avatar');
break;
case 'TWIT':
// Check NONCE...
if(!wp_verify_nonce($_REQUEST['n'], AVATARS_NONCE_KEY)) die('(2) Security check.');
// Save Twitter ID.
update_usermeta($uid, 'twitter_id', $_REQUEST['twitter_id']);
break;
case 'SAVE':
// Check NONCE...
if(!wp_verify_nonce($_REQUEST[AVATARS_NONCE_KEY], AVATARS_NONCE_KEY)) die('(3) Security check.');
if($_POST['x1'] != '') {
$files = $this->avatar_strip_suffix($user->avatar);
$this->avatar_crop($user, $files[BASE_FILE]);
}
else {
$this->avatar_upload($uid);
$files = $this->avatar_strip_suffix($user->avatar);
}
break;
}
$this->output_avatar_error_message($user);
printf("
avatar_root() . $file);
$image_functions = array(
IMAGETYPE_GIF => 'imagecreatefromgif',
IMAGETYPE_JPEG => 'imagecreatefromjpeg',
IMAGETYPE_PNG => 'imagecreatefrompng',
IMAGETYPE_WBMP => 'imagecreatefromwbmp',
IMAGETYPE_XBM => 'imagecreatefromxbm'
);
$src = $image_functions[$type]($this->avatar_root() . $file);
if($src) {
$dst = imagecreatetruecolor($this->avatar_options['size'], $this->avatar_options['size']);
imagesavealpha($dst, true);
$trans = imagecolorallocatealpha($dst, 0, 0, 0, 127);
imagefill($dst, 0, 0, $trans);
$chk = imagecopyresampled($dst, $src, 0, 0, $_POST['x1'], $_POST['y1'], $this->avatar_options['size'], $this->avatar_options['size'], $_POST['w'], $_POST['h']);
if($chk) {
$parts = pathinfo($file);
$base = basename($parts['basename'], '.' . $parts['extension']);
$file = $parts['dirname'] . '/' . $base . '-' . AVATAR_CROPPED . '.' . $parts['extension'];
$image_functions = array(
IMAGETYPE_GIF => 'imagegif',
IMAGETYPE_JPEG => 'imagejpeg',
IMAGETYPE_PNG => 'imagepng',
IMAGETYPE_WBMP => 'imagewbmp',
IMAGETYPE_XBM => 'imagexbm'
);
$image_functions[$type]($dst, $this->avatar_root() . $file);
// Save the new local avatar for this user.
update_usermeta($user->ID, 'avatar', $file);
imagedestroy($dst);
}
}
}
// Save the uploaded avatar.
function avatar_upload($user_id)
{
$info = '';
// Make sure WP's media library is available.
if(!function_exists('image_resize')) include_once(ABSPATH . '/wp-includes/media.php');
// Make sure WP's filename sanitizer is available.
if(!function_exists('sanitize_file_name')) include_once(ABSPATH . '/wp-includes/formatting.php');
// Valid file types for upload.
$valid_file_types = array(
"image/jpeg" => true,
"image/pjpeg" => true,
"image/gif" => true,
"image/png" => true,
"image/x-png" => true
);
// The web-server root directory. Used to create absolute paths.
$root = $this->avatar_root();
// Upload a local avatar.
if(isset($_FILES['avatar_file']) && @$_FILES['avatar_file']['name']) { // Something uploaded?
if($_FILES['avatar_file']['error']) $error = 'Upload error.'; // Any errors?
else if(@$valid_file_types[$_FILES['avatar_file']['type']]) { // Valid types?
$path = trailingslashit($this->avatar_options['upload_dir']);
$file = sanitize_file_name($_FILES['avatar_file']['name']);
// Directory exists?
if(!file_exists($root . $path) && @!mkdir($root . $path, 0777)) $error = __("Upload directory doesn't exist.", 'avatars');
else {
// Get a unique filename.
// First, if already there, include the User's ID; this should be enough.
if(file_exists($root . $path . $file)) {
$parts = pathinfo($file);
$file = basename($parts['basename'], '.' . $parts['extension']) . '-' . $user_id . '.' . $parts['extension'];
}
// Second, if required loop to create a unique file name.
$i = 0;
while(file_exists($root . $path . $file) && $i < UPLOAD_TRIES) {
$i++;
$parts = pathinfo($file);
$file = substr(basename($parts['basename'], '.' . $parts['extension']), 0, strlen(basename($parts['basename'], '.' . $parts['extension'])) - ($i > 1 ? 2 : 0)) . '-' . $i . '.' . $parts['extension'];
}
if($i >= UPLOAD_TRIES) $error = __('Too many tries to find non-existent file.', 'avatars');
$file = strtolower($file);
// Copy uploaded file.
if(!move_uploaded_file($_FILES['avatar_file']['tmp_name'], $root . $path . $file)) $error = __('File upload failed.', 'avatars');
else chmod($root . $path . $file, 0644);
// Remember uploaded file information.
$info = getimagesize($root . $path . $file);
$info[4] = $path . $file;
// Resize required?
if($this->avatar_options['resize'] == 'on') {
$scaled_size = (empty($this->avatar_options['scale']) ? SCALED_SIZE : $this->avatar_options['scale']);
if($info[0] > $scaled_size || $info[1] > $scaled_size) {
// Resize required and needed...
$resized_file = image_resize($root . $path . $file, $scaled_size, $scaled_size, true, AVATAR_SUFFIX);
if(!is_wp_error($resized_file) && $resized_file) {
$parts = pathinfo($file);
$file = basename($resized_file, '.' . $parts['extension']) . '.' . $parts['extension'];
}
else $error = __('Unable to resize image.', 'avatars');
}
// Image is too small, and upscale turned on...
else if($this->avatar_options['upsize'] == 'on') {
$resized_file = $this->image_upsize($root . $path . $file, $scaled_size, $scaled_size, "FFFFFF", AVATAR_SUFFIX);
if(!is_wp_error($resized_file) && $resized_file) {
$parts = pathinfo($file);
$file = basename($resized_file, '.' . $parts['extension']) . '.' . $parts['extension'];
}
else $error = __('Unable to upsize image.', 'avatars');
}
}
}
}
else $error = __('Wrong type.', 'avatars');
// Save the new local avatar for this user.
if(empty($error)) update_usermeta($user_id, 'avatar', $path . $file);
}
// If there was an an error, record the text for display.
if(!empty($error)) update_usermeta($user_id, 'avatar_error', $error);
return $info;
}
// Upsize Avatar images that are too small.
function image_upsize($file, $max_w, $max_h, $color = null, $suffix = null, $dest_path = null, $jpeg_quality = 90 )
{
$image = wp_load_image($file);
if(!is_resource($image)) return new WP_Error('error_loading_image', $image, $file);
$size = @getimagesize($file);
if(!$size) return new WP_Error('invalid_image', __('Could not read image size'), $file);
list($orig_w, $orig_h, $orig_type) = $size;
$dst_x = (int)($max_w/2) - ($orig_w/2);
$dst_y = (int)($max_h/2) - ($orig_h/2);
$src_x = 0;
$src_y = 0;
$dst_w = $max_w;
$dst_h = $max_h;
$src_w = $orig_w;
$src_h = $orig_h;
$newimage = wp_imagecreatetruecolor($dst_w, $dst_h);
if(!empty($color)) {
$r = base_convert(substr($color, 0, 2), 16, 10);
$g = base_convert(substr($color, 2, 2), 16, 10);
$b = base_convert(substr($color, 4, 2), 16, 10);
$background = imagecolorallocate($newimage, $r, $g, $b);
imagefill($newimage, 0, 0, $background);
}
imagecopyresampled($newimage, $image, $dst_x, $dst_y, $src_x, $src_y, $src_w, $src_h, $src_w, $src_h);
// Convert from full colors to index colors, like original PNG.
if(IMAGETYPE_PNG == $orig_type && function_exists('imageistruecolor') && !imageistruecolor($image)) imagetruecolortopalette($newimage, false, imagecolorstotal($image));
// We don't need the original in memory anymore.
imagedestroy($image);
// $suffix will be appended to the destination filename, just before the extension.
if(!$suffix) $suffix = "{$dst_w}x{$dst_h}";
$info = pathinfo($file);
$dir = $info['dirname'];
$ext = $info['extension'];
$name = basename($file, ".{$ext}");
if(!is_null($dest_path) && $_dest_path = realpath($dest_path)) $dir = $_dest_path;
$destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
if(IMAGETYPE_GIF == $orig_type) {
if(!imagegif($newimage, $destfilename)) return new WP_Error('resize_path_invalid', __('Resize path invalid'));
}
elseif(IMAGETYPE_PNG == $orig_type) {
if(!imagepng($newimage, $destfilename)) return new WP_Error('resize_path_invalid', __('Resize path invalid'));
}
else {
// All other formats are converted to jpg.
$destfilename = "{$dir}/{$name}-{$suffix}.jpg";
if(!imagejpeg($newimage, $destfilename, apply_filters('jpeg_quality', $jpeg_quality, 'image_resize'))) return new WP_Error('resize_path_invalid', __('Resize path invalid'));
}
imagedestroy($newimage);
// Set correct file permissions.
$stat = stat(dirname($destfilename));
$perms = $stat['mode'] & 0000666; // Same permissions as parent folder, strip off the executable bits.
@chmod( $destfilename, $perms);
// Delete old image.
unlink($file);
return $destfilename;
}
} // end class.
endif;
// do the magic
$add_local_avatars = new add_local_avatars();
// Main template tag - outputs the avatar (returns false if avatars are switched off)...
if(!function_exists('get_avatar')) :
function get_avatar($id_or_email, $size = '', $default = '', $post = false)
{
global $avatar_type, $add_local_avatars;
if(!get_option('show_avatars')) return false; // Check if avatars are turned on.
if(!is_numeric($size) || $size == '') $size = $add_local_avatars->avatar_options['size']; // Check default avatar size.
$email = ''; // E-mail key for Gravatar.com
$name = ''; // Name for anchor title attribute.
$url = ''; // Anchor.
$id = ''; // User ID.
$src = ''; // Image source;
$avatar_type = ''; // Global to advertise type of Avatar.
if(is_numeric($id_or_email)) { // Numeric - user ID...
$id = (int)$id_or_email;
$user = get_userdata($id);
if($user) {
$email = $user->user_email;
$name = ($add_local_avatars->avatar_options['name'] == 'on' ? $user->nickname : $user->first_name . ' ' . $user->last_name);
$url = $user->user_url;
}
}
elseif(is_object($id_or_email)) { // Comment object...
if(!empty($id_or_email->user_id)) { // Object has a user ID, commenter was registered & logged in...
$id = (int)$id_or_email->user_id;
$user = get_userdata($id);
if($user) {
$email = $user->user_email;
$name = ($add_local_avatars->avatar_options['name'] == 'on' ? $user->nickname : $user->first_name . ' ' . $user->last_name);
$url = $user->user_url;
}
}
else { // Comment object...
$name = $id_or_email->comment_author;
switch($id_or_email->comment_type) {
case 'trackback': // Trackback...
case 'pingback':
if(!empty($add_local_avatars->avatar_options['default'])) $src = $add_local_avatars->avatar_options['default'];
$url_array = parse_url($id_or_email->comment_author_url);
$url = "http://" . $url_array['host'];
break;
case 'comment': // Comment...
case '':
if(!empty($id_or_email->comment_author_email)) $email = $id_or_email->comment_author_email;
$user = get_user_by('email', $email);
if($user) $id = $user->ID; // Set ID if we can to check for local avatar.
$url = $id_or_email->comment_author_url;
break;
}
}
}
else { // Assume we have been passed an e-mail address...
if(!empty($id_or_email)) $email = $id_or_email;
$user = get_user_by('email', $email);
if($user) $id = $user->ID; // Set ID if we can to check for local avatar.
}
// What class to apply to avatar images?
$class = ($post ? 'post_avatar no-rate' : 'avatar');
// Try to use local avatar.
if($id) {
$local = get_user_meta($id, 'avatar', true);
if(!empty($local)) {
$src = $local;
$avatar_type = TYPE_LOCAL;
}
}
// No local avatar source, Twitter is turned on, and we have a Twitter ID; so see if a Twitter avatar is available...
if(!$src && $add_local_avatars->avatar_options['twitter'] == 'on') {
if(!empty($user->twitter_id)) {
$twitter = $add_local_avatars->get_twitter_avatar($user->twitter_id);
if(!empty($twitter)) {
$src = $twitter;
$avatar_type = TYPE_TWITTER;
}
}
}
// No local avatar source, so build global avatar source...
if(!$src) {
if ( !empty($email) )
$email_hash = md5( strtolower( $email ) );
if ( is_ssl() ) {
$src = 'https://secure.gravatar.com/avatar/';
} else {
if ( !empty($email) )
$src = sprintf( "http://%d.gravatar.com/avatar/", ( hexdec( $email_hash{0} ) % 2 ) );
else
$src = 'http://0.gravatar.com/avatar/';
}
if(empty($email)) $src .= md5(strtolower((empty($default) ? UNKNOWN : BLANK)));
else $src .= md5(strtolower($email));
$src .= '?s=' . $size;
$wavatar = get_option('avatar_default');
$src .= '&d=';
if (!empty($wavatar) && !empty($email) && empty($default))
$src .= $add_local_avatars->check_switch($wavatar, $add_local_avatars->avatar_options['default'], $size);
elseif (!empty($default))
$src .= $add_local_avatars->check_switch($default, $add_local_avatars->avatar_options['default'], $size);
else
$src .= urlencode(FALLBACK);
$rating = get_option('avatar_rating');
if(!empty($rating)) $src .= "&r={$rating}";
$avatar_type = TYPE_GLOBAL;
}
$avatar = "
";
// Hack to stop URL wrapping if the caller is the 'Admin Bar'.
$backtrace = debug_backtrace();
if(!isset($backtrace[1]['function']) || ($backtrace[1]['function'] != 'wp_admin_bar_my_account_item' && $backtrace[1]['function'] != 'wp_admin_bar_my_account_menu')) {
// If not in admin pages and there is a URL, wrap the avatar markup with an anchor.
if(!empty($url) && $url != 'http://' && !is_admin() && $add_local_avatars->avatar_options['url_wrap'] == 'on') {
$avatar = sprintf("%s", esc_attr($url), ($user ? "" : "target='_blank'"), (empty($name) ? '' : __('Visit', 'avatars') . " $name’" . (substr($name, -1) == 's' ? "" : "s") . " " . (empty($add_local_avatars->avatar_options['location']) ? 'website' : $add_local_avatars->avatar_options['location'])), ($add_local_avatars->avatar_options['snapshots'] == 'on' ? '' : "class='snap_noshots'"), $avatar);
}
}
// Return the filtered result.
return apply_filters('get_avatar', $avatar, $id_or_email, $size, $default);
}
endif;
?>