Advertisement
gserafini

User Avatar 1.4.1 complete file (fixed)

Oct 4th, 2011
227
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 25.05 KB | None | 0 0
  1. <?php
  2. /*
  3. Plugin Name: User Avatar
  4. Plugin URI: http://wordpress.org/extend/plugins/user-avatar/
  5. Description: Allows users to associate photos with their accounts by accessing their "Your Profile" page that default as Gravatar or WordPress Default image (from Discussion Page).
  6. Version: 1.4.1
  7. Author: Enej Bajgoric / Gagan Sandhu / CTLT DEV
  8.  
  9.  
  10. GNU General Public License, Free Software Foundation <http://creativecommons.org/licenses/GPL/2.0/>
  11. This program is free software; you can redistribute it and/or modify
  12. it under the terms of the GNU General Public License as published by
  13. the Free Software Foundation; either version 2 of the License, or
  14. (at your option) any later version.
  15.  
  16. This program is distributed in the hope that it will be useful,
  17. but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  19. GNU General Public License for more details.
  20.  
  21. You should have received a copy of the GNU General Public License
  22. along with this program; if not, write to the Free Software
  23. Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
  24. */
  25.  
  26. add_action('init', 'user_avatar_core_set_avatar_constants', 8 );
  27. add_action('show_user_profile', 'user_avatar_form');
  28. add_action('edit_user_profile', 'user_avatar_form');
  29. add_action('wp_ajax_user_avatar_add_photo', 'user_avatar_add_photo');
  30. add_action('user_avatar_iframe_head','user_avatar_init');
  31.  
  32.  
  33. add_action('admin_print_styles-user-edit.php', 'user_avatar_admin_print_styles');
  34. add_action('admin_print_styles-profile.php', 'user_avatar_admin_print_styles');
  35. function user_avatar_admin_print_styles() {
  36.     global $hook_suffix;
  37.     wp_enqueue_script("thickbox");
  38.     wp_enqueue_style("thickbox");
  39.     wp_enqueue_style('user-avatar', plugins_url('/user-avatar/css/user-avatar.css'), 'css');
  40. }
  41.  
  42.  
  43. /**
  44.  * user_avatar_init function.
  45.  * Description: Initializing user avatar style.
  46.  * @access public
  47.  * @return void
  48.  */
  49. function user_avatar_init(){
  50.    
  51.     wp_enqueue_style( 'global' );
  52.     wp_enqueue_style( 'wp-admin' );
  53.     wp_enqueue_style( 'colors' );
  54.     wp_enqueue_style( 'ie' );
  55.     wp_enqueue_style('user-avatar', plugins_url('/user-avatar/css/user-avatar.css'), 'css');
  56.     wp_enqueue_style('imgareaselect');
  57.     wp_enqueue_script('imgareaselect');
  58.     do_action('admin_print_styles');
  59.     do_action('admin_print_scripts');
  60.     do_action('admin_head');
  61.  
  62. }
  63. /**
  64.  * user_avatar_core_set_avatar_constants function.
  65.  * Description: Establishing restraints on sizes of files and dimensions of images.
  66.  * Sets the default constants
  67.  * @access public
  68.  * @return void
  69.  */
  70. function user_avatar_core_set_avatar_constants() {
  71.    
  72.     global $bp;
  73.  
  74.     if ( !defined( 'USER_AVATAR_UPLOAD_PATH' ) )
  75.         define( 'USER_AVATAR_UPLOAD_PATH', user_avatar_core_avatar_upload_path() );
  76.  
  77.     if ( !defined( 'USER_AVATAR_URL' ) )
  78.         define( 'USER_AVATAR_URL', user_avatar_core_avatar_url() );
  79.  
  80.     if ( !defined( 'USER_AVATAR_THUMB_WIDTH' ) )
  81.         define( 'USER_AVATAR_THUMB_WIDTH', 50 );
  82.  
  83.     if ( !defined( 'USER_AVATAR_THUMB_HEIGHT' ) )
  84.         define( 'USER_AVATAR_THUMB_HEIGHT', 50 );
  85.  
  86.     if ( !defined( 'USER_AVATAR_FULL_WIDTH' ) )
  87.         define( 'USER_AVATAR_FULL_WIDTH', 150 );
  88.  
  89.     if ( !defined( 'USER_AVATAR_FULL_HEIGHT' ) )
  90.         define( 'USER_AVATAR_FULL_HEIGHT', 150 );
  91.  
  92.     if ( !defined( 'USER_AVATAR_ORIGINAL_MAX_FILESIZE' ) ) {
  93.         if ( !get_site_option( 'fileupload_maxk', 1500 ) )
  94.             define( 'USER_AVATAR_ORIGINAL_MAX_FILESIZE', 5120000 ); /* 5mb */
  95.         else
  96.             define( 'USER_AVATAR_ORIGINAL_MAX_FILESIZE', get_site_option( 'fileupload_maxk', 1500 ) * 1024 );
  97.     }
  98.  
  99.     if ( !defined( 'USER_AVATAR_DEFAULT' ) )
  100.         define( 'USER_AVATAR_DEFAULT', plugins_url('/user-avatar/images/mystery-man.jpg') );
  101.  
  102.     if ( !defined( 'USER_AVATAR_DEFAULT_THUMB' ) )
  103.         define( 'USER_AVATAR_DEFAULT_THUMB', plugins_url('/user-avatar/images/mystery-man-50.jpg') );
  104.        
  105.        
  106.     // set the language
  107.     load_plugin_textdomain( 'user-avatar', false , basename( dirname( __FILE__ ) ) . '/languages' );
  108. }
  109.  
  110. /**
  111.  * user_avatar_core_avatar_upload_path function.
  112.  * Description: Establishing upload path/area where images that are uploaded will be stored.
  113.  * @access public
  114.  * @return void
  115.  */
  116. function user_avatar_core_avatar_upload_path()
  117. {
  118.     if( !file_exists(WP_CONTENT_DIR."/uploads/avatars/") )
  119.         mkdir(WP_CONTENT_DIR."/uploads/avatars/", 0777 ,true);
  120.    
  121.     return WP_CONTENT_DIR."/uploads/avatars/";
  122. }
  123.  
  124. /**
  125.  * user_avatar_core_avatar_url function.
  126.  * Description: Establishing the path of the core content avatar area.
  127.  * @access public
  128.  * @return void
  129.  */
  130. function user_avatar_core_avatar_url()
  131. {  
  132.     return WP_CONTENT_URL."/uploads/avatars/";
  133. }
  134.  
  135. /**
  136.  * user_avatar_add_photo function.
  137.  * The content inside the iframe
  138.  * Description: Creating panels for the different steps users take to upload a file and checking their uploads.
  139.  * @access public
  140.  * @return void
  141.  */
  142. function user_avatar_add_photo() {
  143.     global $current_user;
  144.    
  145.     if(($_GET['uid'] == $current_user->ID || current_user_can('edit_users')) &&  is_numeric($_GET['uid']))
  146.     {
  147.         $uid = $_GET['uid'];
  148.     ?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  149. <html xmlns="http://www.w3.org/1999/xhtml" <?php do_action('admin_xml_ns'); ?> <?php language_attributes(); ?>>
  150. <head>
  151. <meta http-equiv="Content-Type" content="<?php bloginfo('html_type'); ?>; charset=<?php echo get_option('blog_charset'); ?>" />
  152. <title><?php bloginfo('name') ?> &rsaquo; <?php _e('Uploads'); ?> &#8212; <?php _e('WordPress'); ?></title>
  153. <script type="text/javascript">
  154. //<![CDATA[
  155. addLoadEvent = function(func){if(typeof jQuery!="undefined")jQuery(document).ready(func);else if(typeof wpOnload!='function'){wpOnload=func;}else{var oldonload=wpOnload;wpOnload=function(){oldonload();func();}}};
  156. var userSettings = {
  157.         'url': '<?php echo SITECOOKIEPATH; ?>',
  158.         'uid': '<?php if ( ! isset($current_user) ) $current_user = wp_get_current_user(); echo $current_user->ID; ?>',
  159.         'time':'<?php echo time() ?>'
  160.     },
  161.     ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>',
  162.     pagenow = '<?php echo $current_screen->id; ?>',
  163.     typenow = '<?php if ( isset($current_screen->post_type) ) echo $current_screen->post_type; ?>',
  164.     adminpage = '<?php echo $admin_body_class; ?>',
  165.     thousandsSeparator = '<?php echo addslashes( $wp_locale->number_format['thousands_sep'] ); ?>',
  166.     decimalPoint = '<?php echo addslashes( $wp_locale->number_format['decimal_point'] ); ?>',
  167.     isRtl = <?php echo (int) is_rtl(); ?>;
  168. //]]>
  169. </script>
  170. <?php
  171.  
  172.    
  173.     do_action('user_avatar_iframe_head');
  174.    
  175.    
  176. ?>
  177.  
  178. </head>
  179. <body>
  180. <?php
  181.     switch($_GET['step'])
  182.     {
  183.         case 1:
  184.             user_avatar_add_photo_step1($uid);
  185.         break;
  186.        
  187.         case 2:
  188.             user_avatar_add_photo_step2($uid);
  189.         break;
  190.        
  191.         case 3:
  192.             user_avatar_add_photo_step3($uid);
  193.         break;
  194.     }
  195.        
  196.     do_action('admin_print_footer_scripts');
  197. ?>
  198. <script type="text/javascript">if(typeof wpOnload=='function')wpOnload();</script>
  199. </body>
  200. </html>
  201. <?php
  202.     }else {
  203.         wp_die(__("You are not allowed to do that.",'user-avatar'));
  204.     }
  205.     die();
  206. }
  207.  
  208. /**
  209.  * user_avatar_add_photo_step1 function.
  210.  * The First Step in the process
  211.  * Description: Displays the users photo and they can choose to upload another if they please.
  212.  * @access public
  213.  * @param mixed $uid
  214.  * @return void
  215.  */
  216. function user_avatar_add_photo_step1($uid)
  217. {
  218.     ?>
  219.     <p id="step1-image" >
  220.     <?php
  221.     echo user_avatar_get_avatar( $uid , 150);
  222.     ?>
  223.     </p>
  224.     <div id="user-avatar-step1">
  225.     <form enctype="multipart/form-data" id="uploadForm" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>?action=user_avatar_add_photo&step=2&uid=<?php echo $uid; ?>" >
  226.             <label for="upload"><?php _e('Choose an image from your computer:','user-avatar'); ?></label><br /><input type="file" id="upload" name="uploadedfile" />
  227.             <input type="hidden" name="action" value="save" />
  228.             <?php wp_nonce_field('user-avatar') ?>
  229.         <p class="submit"><input type="submit" value="<?php esc_attr_e('Upload'); ?>" /></p>
  230.     </form>
  231.     </div>
  232.    
  233.     <?php
  234. }
  235.  
  236. /**
  237.  * user_avatar_add_photo_step2 function.
  238.  * The Second Step in the process
  239.  * Description: Takes the uploaded photo and saves it to database.
  240.  * @access public
  241.  * @param mixed $uid
  242.  * @return void
  243.  */
  244. function user_avatar_add_photo_step2($uid)
  245. {
  246.    
  247.    
  248.         if (!(($_FILES["uploadedfile"]["type"] == "image/gif") || ($_FILES["uploadedfile"]["type"] == "image/jpeg") || ($_FILES["uploadedfile"]["type"] == "image/png") || ($_FILES["uploadedfile"]["type"] == "image/pjpeg") || ($_FILES["uploadedfile"]["type"] == "image/x-png"))){
  249.             echo "<div class='error'><p>".__("Please upload an image file (.jpeg, .gif, .png).",'user-avatar')."</p></div>";
  250.             user_avatar_add_photo_step1($uid);
  251.             die();
  252.         }
  253.         $overrides = array('test_form' => false);
  254.         $file = wp_handle_upload($_FILES['uploadedfile'], $overrides);
  255.  
  256.         if ( isset($file['error']) ){
  257.             die( $file['error'] );
  258.         }
  259.        
  260.         $url = $file['url'];
  261.         $type = $file['type'];
  262.         $file = $file['file'];
  263.         $filename = basename($file);
  264.        
  265.         // Construct the object array
  266.         $object = array(
  267.         'post_title' => $filename,
  268.         'post_content' => $url,
  269.         'post_mime_type' => $type,
  270.         'guid' => $url);
  271.  
  272.         // Save the data
  273.         list($width, $height, $type, $attr) = getimagesize( $file );
  274.        
  275.         if ( $width > 500 ) {
  276.             $oitar = $width / 500;
  277.             $image = wp_crop_image($file, 0, 0, $width, $height, 500, $height / $oitar, false, str_replace(basename($file), 'midsize-'.basename($file), $file));
  278.            
  279.  
  280.             $url = str_replace(basename($url), basename($image), $url);
  281.             $width = $width / $oitar;
  282.             $height = $height / $oitar;
  283.         } else {
  284.             $oitar = 1;
  285.         }
  286.        
  287.        
  288.         ?>
  289.         <form id="iframe-crop-form" method="POST" action="<?php echo admin_url('admin-ajax.php'); ?>?action=user_avatar_add_photo&step=3&uid=<?php echo esc_attr($uid); ?>">
  290.        
  291.         <h4><?php _e('Choose the part of the image you want to use as your profile image.','user-avatar'); ?></h4>
  292.        
  293.         <div id="testWrap">
  294.         <img src="<?php echo $url; ?>" id="upload" width="<?php echo esc_attr($width); ?>" height="<?php echo esc_attr($height); ?>" />
  295.         </div>
  296.         <div id="user-avatar-preview">
  297.         <h4>Preview</h4>
  298.         <div id="preview" style="width: <?php echo USER_AVATAR_FULL_WIDTH; ?>px; height: <?php echo USER_AVATAR_FULL_HEIGHT; ?>px; overflow: hidden;">
  299.         <img src="<?php echo esc_url_raw($url); ?>" width="<?php echo esc_attr($width); ?>" height="<?php echo $height; ?>">
  300.         </div>
  301.         <p class="submit" >
  302.         <input type="hidden" name="x1" id="x1" value="0" />
  303.         <input type="hidden" name="y1" id="y1" value="0" />
  304.         <input type="hidden" name="x2" id="x2" />
  305.         <input type="hidden" name="y2" id="y2" />
  306.         <input type="hidden" name="width" id="width" value="<?php echo esc_attr($width) ?>" />
  307.         <input type="hidden" name="height" id="height" value="<?php echo esc_attr($height) ?>" />
  308.         <input type="hidden" name="attachment_file" id="attachment_file" value="<?php echo esc_attr($file); ?>" />
  309.         <input type="hidden" name="oitar" id="oitar" value="<?php echo esc_attr($oitar); ?>" />
  310.         <?php wp_nonce_field('user-avatar'); ?>
  311.         <input type="submit" id="user-avatar-crop-button" value="<?php esc_attr_e('Crop Image','user-avatar'); ?>" /></p>
  312.         </div>
  313.         </form>
  314.        
  315.         <script type="text/javascript">
  316.  
  317.     function onEndCrop( coords ) {
  318.         jQuery( '#x1' ).val(coords.x);
  319.         jQuery( '#y1' ).val(coords.y);
  320.         jQuery( '#width' ).val(coords.w);
  321.         jQuery( '#height' ).val(coords.h);
  322.     }
  323.  
  324.     jQuery(document).ready(function() {
  325.         var xinit = <?php echo USER_AVATAR_FULL_WIDTH; ?>;
  326.         var yinit = <?php echo USER_AVATAR_FULL_HEIGHT; ?>;
  327.         var ratio = xinit / yinit;
  328.         var ximg = jQuery('img#upload').width();
  329.         var yimg = jQuery('img#upload').height();
  330.  
  331.         if ( yimg < yinit || ximg < xinit ) {
  332.             if ( ximg / yimg > ratio ) {
  333.                 yinit = yimg;
  334.                 xinit = yinit * ratio;
  335.             } else {
  336.                 xinit = ximg;
  337.                 yinit = xinit / ratio;
  338.             }
  339.         }
  340.  
  341.         jQuery('img#upload').imgAreaSelect({
  342.             handles: true,
  343.             keys: true,
  344.             aspectRatio: xinit + ':' + yinit,
  345.             show: true,
  346.             x1: 0,
  347.             y1: 0,
  348.             x2: xinit,
  349.             y2: yinit,
  350.             //maxHeight: <?php echo USER_AVATAR_FULL_HEIGHT; ?>,
  351.             //maxWidth: <?php echo USER_AVATAR_FULL_WIDTH; ?>,
  352.             onInit: function () {
  353.                 jQuery('#width').val(xinit);
  354.                 jQuery('#height').val(yinit);
  355.             },
  356.             onSelectChange: function(img, c) {
  357.                 jQuery('#x1').val(c.x1);
  358.                 jQuery('#y1').val(c.y1);
  359.                 jQuery('#width').val(c.width);
  360.                 jQuery('#height').val(c.height);
  361.                
  362.                
  363.                
  364.                 if (!c.width || !c.height)
  365.                     return;
  366.    
  367.                 var scaleX = <?php echo USER_AVATAR_FULL_WIDTH; ?> / c.width;
  368.                 var scaleY = <?php echo USER_AVATAR_FULL_HEIGHT; ?> / c.height;
  369.                
  370.                 jQuery('#preview img').css({
  371.                     width: Math.round(scaleX * <?php echo $width; ?>),
  372.                     height: Math.round(scaleY * <?php echo $height; ?>),
  373.                     marginLeft: -Math.round(scaleX * c.x1),
  374.                     marginTop: -Math.round(scaleY * c.y1)
  375.                 });
  376.  
  377.             }
  378.         });
  379.     });
  380. </script>
  381.         <?php
  382. }
  383. /**
  384.  * user_avatar_add_photo_step3 function.
  385.  * The Third Step in the Process
  386.  * Description: Deletes previous uploaded picture and creates a new cropped image in its place.
  387.  * @access public
  388.  * @param mixed $uid
  389.  * @return void
  390.  */
  391. function user_avatar_add_photo_step3($uid)
  392. {
  393.    
  394.    
  395.     if ( $_POST['oitar'] > 1 ) {
  396.         $_POST['x1'] = $_POST['x1'] * $_POST['oitar'];
  397.         $_POST['y1'] = $_POST['y1'] * $_POST['oitar'];
  398.         $_POST['width'] = $_POST['width'] * $_POST['oitar'];
  399.         $_POST['height'] = $_POST['height'] * $_POST['oitar'];
  400.     }
  401.        
  402.     if( !file_exists($_POST['attachment_file']) ) {
  403.         echo "<div class='error'><p>". __('Sorry, No file available','user-avatar')."</p></div>";
  404.         return true;
  405.     }
  406.    
  407.     $original_file = $_POST['attachment_file'];
  408.        
  409.     $cropped_full = USER_AVATAR_UPLOAD_PATH."{$uid}/".time()."-bpfull.jpg";
  410.     $cropped_thumb = USER_AVATAR_UPLOAD_PATH."{$uid}/".time()."-bpthumb.jpg";
  411.    
  412.     // delete the previous files
  413.     user_avatar_delete_files($uid);
  414.    
  415.     if(!file_exists(USER_AVATAR_UPLOAD_PATH."{$uid}/"))
  416.         mkdir(USER_AVATAR_UPLOAD_PATH."{$uid}/");
  417.    
  418.     // update the files
  419.     $cropped_full = wp_crop_image( $original_file, $_POST['x1'], $_POST['y1'], $_POST['width'], $_POST['height'], USER_AVATAR_FULL_WIDTH, USER_AVATAR_FULL_HEIGHT, false, $cropped_full );
  420.    
  421.     $cropped_thumb = wp_crop_image( $original_file, $_POST['x1'], $_POST['y1'], $_POST['width'], $_POST['height'], USER_AVATAR_THUMB_WIDTH, USER_AVATAR_THUMB_HEIGHT, false, $cropped_thumb );
  422.    
  423.     /* Remove the original */
  424.     @unlink( $original_file );
  425.        
  426.     if ( is_wp_error( $cropped_full ) )
  427.         wp_die( __( 'Image could not be processed.  Please go back and try again.' ), __( 'Image Processing Error' ) );    
  428.     ?>
  429.     <script type="text/javascript">
  430.         self.parent.user_avatar_refresh_image('<?php echo user_avatar_get_avatar($uid, 150); ?>');
  431.         self.parent.add_remove_avatar_link();
  432.     </script>
  433.     <div id="user-avatar-step3">
  434.         <h3><?php _e("Here's your new profile picture...",'user-avatar'); ?></h3>
  435.         <span style="float:left;">
  436.         <?php
  437.         echo user_avatar_get_avatar( $uid, 150);
  438.         ?>
  439.         </span>
  440.         <a id="user-avatar-step3-close" class="button" onclick="self.parent.tb_remove();" ><?php _e('Close','user-avatar'); ?></a>
  441.     </div>
  442. <?php  
  443. }  
  444. /**
  445.  * user_avatar_delete_files function.
  446.  * Description: Deletes the avatar files based on the user id.
  447.  * @access public
  448.  * @param mixed $uid
  449.  * @return void
  450.  */
  451. function user_avatar_delete_files($uid)
  452. {
  453.     $avatar_folder_dir = USER_AVATAR_UPLOAD_PATH."{$uid}/";
  454.     if ( !file_exists( $avatar_folder_dir ) )
  455.         return false;
  456.  
  457.     if ( is_dir( $avatar_folder_dir ) && $av_dir = opendir( $avatar_folder_dir ) ) {
  458.         while ( false !== ( $avatar_file = readdir($av_dir) ) ) {
  459.                 @unlink( $avatar_folder_dir . '/' . $avatar_file );
  460.         }
  461.         closedir($av_dir);
  462.     }
  463.  
  464.     @rmdir( $avatar_folder_dir );
  465.  
  466. }
  467.  
  468. /**
  469.  * Based on the
  470.  * user_avatar_core_fetch_avatar_filter() 1.2.5 BP
  471.  *
  472.  * Description: Attempts to filter get_avatar function and let Word/BuddyPress have a go at  
  473.  *              finding an avatar that may have been uploaded locally.
  474.  *
  475.  * @global array $authordata
  476.  * @param string $avatar The result of get_avatar from before-filter
  477.  * @param int|string|object $user A user ID, email address, or comment object
  478.  * @param int $size Size of the avatar image (thumb/full)
  479.  * @param string $default URL to a default image to use if no avatar is available
  480.  * @param string $alt Alternate text to use in image tag. Defaults to blank
  481.  * @return <type>
  482.  */
  483. function user_avatar_fetch_avatar_filter( $avatar, $user, $size, $default, $alt ) {
  484.     global $pagenow;
  485.    
  486.     //If user is on discussion page, return $avatar
  487.     if($pagenow == "options-discussion.php")
  488.         return $avatar;
  489.        
  490.     // If passed an object, assume $user->user_id
  491.     if ( is_object( $user ) )
  492.         $id = $user->user_id;
  493.  
  494.     // If passed a number, assume it was a $user_id
  495.     else if ( is_numeric( $user ) )
  496.         $id = $user;
  497.  
  498.     // If passed a string and that string returns a user, get the $id
  499.     else if ( is_string( $user ) && ( $user_by_email = get_user_by_email( $user ) ) )
  500.         $id = $user_by_email->ID;
  501.  
  502.     // If somehow $id hasn't been assigned, return the result of get_avatar
  503.     if ( empty( $id ) )
  504.         return !empty( $avatar ) ? $avatar : $default;
  505.        
  506.     // check yo see if there is a file that was uploaded by the user
  507.     if( user_avatar_avatar_exists($id) ):
  508.    
  509.         $user_avatar = user_avatar_fetch_avatar( array( 'item_id' => $id, 'width' => $size, 'height' => $size, 'alt' => $alt ) );
  510.         if($user_avatar)
  511.             return $user_avatar;
  512.         else
  513.             return !empty( $avatar ) ? $avatar : $default;
  514.     else:
  515.         return !empty( $avatar ) ? $avatar : $default;
  516.     endif;
  517.     // for good measure
  518.     return !empty( $avatar ) ? $avatar : $default;
  519. }
  520.  
  521. add_filter( 'get_avatar', 'user_avatar_fetch_avatar_filter', 10, 5 );
  522.  
  523. /**
  524.  * user_avatar_core_fetch_avatar()
  525.  *
  526.  * Description: Fetches an avatar from a BuddyPress object. Supports user/group/blog as
  527.  *              default, but can be extended to include your own custom components too.
  528.  *
  529.  * @global object $bp
  530.  * @global object $current_blog
  531.  * @param array $args Determine the output of this function
  532.  * @return string Formatted HTML <img> element, or raw avatar URL based on $html arg
  533.  */
  534. function user_avatar_fetch_avatar( $args = '' ) {
  535.    
  536.     $defaults = array(
  537.         'item_id'       => false,
  538.         'object'        => "user",  // user/group/blog/custom type (if you use filters)
  539.         'type'          => $def_type,   // thumb or full
  540.         'avatar_dir'    => false,       // Specify a custom avatar directory for your object
  541.         'width'         => false,       // Custom width (int)
  542.         'height'        => false,       // Custom height (int)
  543.         'class'         => $def_class,  // Custom <img> class (string)
  544.         'css_id'        => false,       // Custom <img> ID (string)
  545.         'alt'           => $def_alt,    // Custom <img> alt (string)
  546.         'email'         => false,       // Pass the user email (for gravatar) to prevent querying the DB for it
  547.         'no_grav'       => false,       // If there is no avatar found, return false instead of a grav?
  548.         'html'          => true         // Wrap the return img URL in <img />
  549.     );
  550.    
  551.     // Compare defaults to passed and extract
  552.     $params = wp_parse_args( $args, $defaults );
  553.     extract( $params, EXTR_SKIP );
  554.  
  555.     $avatar_folder_dir = USER_AVATAR_UPLOAD_PATH."{$item_id}/";
  556.     $avatar_folder_url = USER_AVATAR_URL."{$item_id}";
  557.    
  558.     if($width > 50)
  559.         $type = "full";
  560.        
  561.     $avatar_size = ( 'full' == $type ) ? '-bpfull' : '-bpthumb';
  562.     $class .= " avatar ";
  563.     $class .= " avatar-". $width ." ";
  564.     $class .= " photo";
  565.    
  566.     if ( false === $alt)
  567.         $safe_alt = '';
  568.     else
  569.         $safe_alt = esc_attr( $alt );
  570.    
  571.    
  572.     // Add an identifying class to each item
  573.     $class .= ' ' . $object . '-' . $item_id . '-avatar';
  574.  
  575.     // Set CSS ID if passed
  576.     if ( !empty( $css_id ) )
  577.         $css_id = " id=\"".esc_attr($css_id)."\"";
  578.    
  579.     // Set avatar width
  580.     if ( $width )
  581.         $html_width = " width=\"".esc_attr($width)."\"";
  582.     else
  583.         $html_width = ( 'thumb' == $type ) ? ' width="' . esc_attr(USER_AVATAR_THUMB_WIDTH) . '"' : ' width="' . esc_attr(USER_AVATAR_FULL_WIDTH) . '"';
  584.  
  585.     // Set avatar height
  586.     if ( $height )
  587.         $html_height = " height=\"".esc_attr($height)."\"";
  588.     else
  589.         $html_height = ( 'thumb' == $type ) ? ' height="' . esc_attr(USER_AVATAR_THUMB_HEIGHT) . '"' : ' height="' . esc_attr(USER_AVATAR_FULL_HEIGHT) . '"';
  590.    
  591.  
  592.    
  593.     if( $avatar_img = user_avatar_avatar_exists( $item_id ) ):
  594.    
  595.         $avatar_src = "/wp-content/uploads/avatars/".$item_id."/".$avatar_img;
  596.        
  597.         $avatar_folder_dir = USER_AVATAR_UPLOAD_PATH."{$item_id}/";
  598.        
  599.         $file_time = filemtime ($avatar_folder_dir."/".$avatar_img);
  600.        
  601.         $avatar_url = plugins_url('/user-avatar/user-avatar-pic.php')."?src=".$avatar_src ."&w=".$width."&id=".$item_id."&random=".$file_time;
  602.        
  603.         // Return it wrapped in an <img> element
  604.         if ( true === $html ) { // this helps validate stuff
  605.             return '<img src="' . esc_url($avatar_url) . '" alt="' . esc_attr($alt) . '" class="' . esc_attr($class) . '"' . $css_id . $html_width . $html_height . ' />';
  606.         // ...or only the URL
  607.         } else {
  608.             return  $avatar_url ;
  609.         }
  610.     else:
  611.         return false;
  612.     endif;
  613. }
  614. add_action("admin_init", "user_avatar_delete");
  615. /**
  616.  * user_avatar_delete function.
  617.  *
  618.  * @access public
  619.  * @return void
  620.  */
  621. function user_avatar_delete(){
  622.        
  623.         global $pagenow;
  624.        
  625.         $current_user = wp_get_current_user();
  626.        
  627.         // If user clicks the remove avatar button, in URL deleter_avatar=true
  628.         if( isset($_GET['delete_avatar']) && wp_verify_nonce($_GET['_nononce'], 'user_avatar') && ( $_GET['u'] == $current_user->id || current_user_can('edit_users')) )
  629.         {
  630.             $user_id = $_GET['user_id'];
  631.             if(is_numeric($user_id))
  632.                 $user_id = "?user_id=".$user_id;
  633.                
  634.             user_avatar_delete_files($_GET['u']);
  635.             wp_redirect(get_option('siteurl') . '/wp-admin/'.$pagenow.$user_id);
  636.            
  637.         }      
  638. }
  639. /**
  640.  * user_avatar_form function.
  641.  * Description: Creation and calling of appropriate functions on the overlay form.
  642.  * @access public
  643.  * @param mixed $profile
  644.  * @return void
  645.  */
  646. function user_avatar_form($profile)
  647. {
  648.     global $current_user;
  649.    
  650.     // Check if it is current user or super admin role
  651.     if(($profile->ID == $current_user->ID || is_super_admin($current_user->ID)))
  652.     {
  653.         $avatar_folder_dir = USER_AVATAR_UPLOAD_PATH."{$profile->ID}/";
  654.     ?>
  655.     <div id="user-avatar-display" class="submitbox" >
  656.     <h3 ><?php _e('Picture','user-avatar'); ?></h3>
  657.     <p id="user-avatar-display-image"><?php echo user_avatar_get_avatar($profile->ID, 150); ?></p>
  658.     <a id="user-avatar-link" class="button-primary thickbox" href="<?php echo admin_url('admin-ajax.php'); ?>?action=user_avatar_add_photo&step=1&uid=<?php echo $profile->ID; ?>&TB_iframe=true&width=720&height=450" title="<?php _e('Upload and Crop an Image to be Displayed','user-avatar'); ?>" ><?php _e('Update Picture','user-avatar'); ?></a>
  659.    
  660.     <?php
  661.         // Remove the User-Avatar button if there is no uploaded image
  662.        
  663.         if($_GET['user_id']):
  664.             $remove_url = admin_url('user-edit.php')."?user_id=".$_GET['user_id']."&delete_avatar=true&_nononce=". wp_create_nonce('user_avatar')."&u=".$profile->ID;
  665.         else:
  666.             $remove_url = admin_url('profile.php')."?delete_avatar=true&_nononce=". wp_create_nonce('user_avatar')."&u=".$profile->ID;
  667.        
  668.         endif;
  669.         if ( user_avatar_avatar_exists($profile->ID) ):?>
  670.             <a id="user-avatar-remove" class="submitdelete deleteaction" href="<?php echo esc_url_raw($remove_url); ?>" title="<?php _e('Remove User Avatar Image','user-avatar'); ?>" ><?php _e('Remove','user-avatar'); ?></a>
  671.             <?php
  672.         endif;
  673.     ?>
  674.     </div>
  675.     <script type="text/javascript">
  676.     function user_avatar_refresh_image(img){
  677.      jQuery('#user-avatar-display-image').html(img);
  678.     }
  679.     function add_remove_avatar_link(){
  680.         if(!jQuery("#user-avatar-remove").is('a')){
  681.             jQuery('#user-avatar-link').after(" <a href='<?php echo $remove_url; ?>' class='submitdelete'  id='user-avatar-remove' ><?php _e('Remove','user-avatar'); ?></a>")
  682.         }
  683.            
  684.    
  685.     }
  686.    
  687.     </script>
  688.     <?php
  689.     }
  690. }
  691.  
  692. /*-- HELPER FUNCTIONS --*/
  693. function user_avatar_avatar_exists($id){
  694.    
  695.     $avatar_folder_dir = USER_AVATAR_UPLOAD_PATH."{$id}/";
  696.     $return = false;
  697.    
  698.     if ( is_dir( $avatar_folder_dir ) && $av_dir = opendir( $avatar_folder_dir ) ) {
  699.            
  700.             // Stash files in an array once to check for one that matches
  701.             $avatar_files = array();
  702.             while ( false !== ( $avatar_file = readdir($av_dir) ) ) {
  703.                 // Only add files to the array (skip directories)
  704.                 if ( 2 < strlen( $avatar_file ) )
  705.                     $avatar_files[] = $avatar_file;
  706.             }
  707.            
  708.             // Check for array
  709.             if ( 0 < count( $avatar_files ) ) {
  710.                 // Check for current avatar
  711.                 if( is_array($avatar_files) ):
  712.                     foreach( $avatar_files as $key => $value ) {
  713.                         if(strpos($value, "-bpfull")):
  714.                             $return =  $value;
  715.                         endif;
  716.                     }
  717.                 endif;
  718.                
  719.             }
  720.  
  721.         // Close the avatar directory
  722.         closedir( $av_dir );
  723.  
  724.     }
  725.    
  726.     return $return;
  727. }
  728.  
  729. function user_avatar_get_avatar($id,$width) {
  730.    
  731.     if(! get_option('show_avatars')):
  732.    
  733.         if( user_avatar_avatar_exists($id) ):
  734.    
  735.             $user_avatar = user_avatar_fetch_avatar( array( 'item_id' => $id, 'width' => $width, 'height' => $width, 'alt' => '' ) );
  736.             if($user_avatar):
  737.                 return $user_avatar;
  738.             else:
  739.                 return '<img src="'.USER_AVATAR_DEFAULT.'" width="'.$width.'" height="'.$width.'" class="avatar" />';
  740.             endif;
  741.         else:
  742.             return '<img src="'.USER_AVATAR_DEFAULT.'" width="'.$width.'" height="'.$width.'" class="avatar" />';
  743.         endif;
  744.     else:
  745.         return get_avatar($id,$width);
  746.     endif;
  747. }
  748. /* --- END OF FILE --- */
  749.  
  750.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement