Advertisement
Guest User

Untitled

a guest
Aug 14th, 2013
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. <?php
  2.  
  3. class Tl_Base_Image {
  4.    
  5.     // Runs when class is instantiated
  6.     public function __construct() {
  7.        
  8.         add_action( 'wp_ajax_nopriv_tl_get_image', array( $this, 'get_image_ajax' ) );
  9.         add_action( 'wp_ajax_tl_get_image', array( $this, 'get_image_ajax' ) );
  10.        
  11.         // Deletes the resized images when the original image is deleted from the WordPress Media Library.
  12.         add_action( 'delete_attachment', array( $this, 'mr_delete_resized_images' ) );
  13.        
  14.     }
  15.  
  16.     // Get resized image and return result
  17.     public function get_image( $url, $width = null, $height = null, $crop = true, $align = '', $retina = false ) {
  18.        
  19.         return $this->mr_image_resize( $url, $width, $height, $crop, $align, $retina );
  20.        
  21.     }
  22.    
  23.     //Get resized image and echo result
  24.     public function the_image( $url, $width = null, $height = null, $crop = true, $align = '', $retina = false ) {
  25.        
  26.         echo $this->mr_image_resize( $url, $width, $height, $crop, $align, $retina );
  27.        
  28.     }
  29.    
  30.     // Get image via AJAX
  31.     public function get_image_ajax() {
  32.        
  33.         //nonce check
  34.         check_ajax_referer( 'tl_nonce', 'nonce' );
  35.    
  36.         $url = esc_url_raw( $_POST['url'] );
  37.        
  38.         $width = isset( $_POST['width'] ) ? absint( $_POST['width'] ) : null;
  39.         $height = isset( $_POST['height'] ) ? absint( $_POST['height'] ) : null;
  40.        
  41.         $crop = isset( $_POST['crop'] ) ? (bool) $_POST['crop'] : true;
  42.        
  43.         $align = isset( $_POST['align'] ) ? sanitize_text_field( $_POST['align'] ) : '';
  44.        
  45.         $retina = isset( $_POST['retina'] ) ? (bool) $_POST['retina'] : false;
  46.        
  47.         $response = $this->get_image( $url, $width, $height, $crop, $align, $retina );
  48.        
  49.         wp_send_json( $response );
  50.        
  51.     }
  52.    
  53.    
  54.     /**
  55.       *  Resizes an image and returns the resized URL. Uses native WordPress functionality.
  56.       *
  57.       *  The first function (3.5+) supports GD Library and ImageMagick. WordPress will pick whichever is most appropriate.
  58.       *  The second function (3.4.x and lower) only supports the GD Library. If none of the supported libraries are available,
  59.       *  the function will return the original image.
  60.       *
  61.       *  Images are saved to the WordPress uploads directory, just like images uploaded through the Media Library.
  62.       *
  63.       *  Based on resize.php by Matthew Ruddy (GPLv2 Licensed, Copyright (c) 2012, 2013)
  64.       *  https://github.com/MatthewRuddy/Wordpress-Timthumb-alternative
  65.       *
  66.       *  License: GPLv2
  67.       *  http://www.gnu.org/licenses/gpl-2.0.html
  68.       *
  69.       *  @author Ernesto Méndez (http://der-design.com)
  70.       *  @author Matthew Ruddy (http://rivaslider.com)
  71.       *
  72.       *  @modified Ante Sepic: removed compatibility with WP < 3.5
  73.       */
  74.    
  75.     public function mr_image_resize( $url, $width = null, $height = null, $crop = true, $align = '', $retina = false ) {
  76.    
  77.         global $wpdb;
  78.        
  79.         // Get common vars
  80.         $args = func_get_args();
  81.         $common = $this->mr_common_info($args);
  82.        
  83.         // Unpack vars if got an array...
  84.         if (is_array($common))
  85.             extract($common);
  86.        
  87.         // ... Otherwise, return error, null or image
  88.         else return $common;
  89.        
  90.         if ( !file_exists( $dest_file_name ) ) {
  91.        
  92.             // We only want to resize Media Library images, so we can be sure they get deleted correctly when appropriate.
  93.             $query = $wpdb->prepare( "SELECT * FROM $wpdb->posts WHERE guid='%s'", $url );
  94.             $get_attachment = $wpdb->get_results( $query );
  95.            
  96.             // Load WordPress Image Editor
  97.             $editor = wp_get_image_editor( $file_path );
  98.            
  99.             // Print possible wp error
  100.             if ( is_wp_error($editor) ) {
  101.                 if (is_user_logged_in())
  102.                     print_r($editor);
  103.                 return null;
  104.             }
  105.            
  106.             if ( $crop ) {
  107.            
  108.                 $src_x = $src_y = 0;
  109.                 $src_w = $orig_width;
  110.                 $src_h = $orig_height;
  111.                
  112.                 $cmp_x = $orig_width / $dest_width;
  113.                 $cmp_y = $orig_height / $dest_height;
  114.                
  115.                 // Calculate x or y coordinate and width or height of source
  116.                 if ($cmp_x > $cmp_y) {
  117.                
  118.                     $src_w = round ($orig_width / $cmp_x * $cmp_y);
  119.                     $src_x = round (($orig_width - ($orig_width / $cmp_x * $cmp_y)) / 2);
  120.                
  121.                 } else if ($cmp_y > $cmp_x) {
  122.                
  123.                     $src_h = round ($orig_height / $cmp_y * $cmp_x);
  124.                     $src_y = round (($orig_height - ($orig_height / $cmp_y * $cmp_x)) / 2);
  125.                
  126.                 }
  127.                
  128.                 // Positional cropping. Uses code from timthumb.php under the GPL
  129.                 if ( $align ) {
  130.                     if (strpos ($align, 't') !== false) {
  131.                         $src_y = 0;
  132.                     }
  133.                     if (strpos ($align, 'b') !== false) {
  134.                         $src_y = $orig_height - $src_h;
  135.                     }
  136.                     if (strpos ($align, 'l') !== false) {
  137.                         $src_x = 0;
  138.                     }
  139.                     if (strpos ($align, 'r') !== false) {
  140.                         $src_x = $orig_width - $src_w;
  141.                     }
  142.                 }
  143.            
  144.             }
  145.            
  146.             // Crop image
  147.             $editor->crop( $src_x, $src_y, $src_w, $src_h, $dest_width, $dest_height );
  148.            
  149.             // Save image
  150.             $saved = $editor->save( $dest_file_name );
  151.            
  152.             // Print possible out of memory error
  153.             if ( is_wp_error($saved) ) {
  154.                 @unlink($dest_file_name);
  155.                 if (is_user_logged_in())
  156.                     print_r($saved);
  157.                 return null;
  158.             }
  159.            
  160.             // Add the resized dimensions and alignment to original image metadata, so the images
  161.             // can be deleted when the original image is delete from the Media Library.
  162.             if ( $get_attachment ) {
  163.                 $metadata = wp_get_attachment_metadata( $get_attachment[0]->ID );
  164.                 if ( isset( $metadata['image_meta'] ) ) {
  165.                     $md = $saved['width'] .'x'. $saved['height']; if ($align) $md .= "_$align";
  166.                     $metadata['image_meta']['resized_images'][] = $md;
  167.                     wp_update_attachment_metadata( $get_attachment[0]->ID, $metadata );
  168.                 }
  169.             }
  170.                
  171.             // Resized image url
  172.             $resized_url = str_replace( basename( $url ), basename( $saved['path'] ), $url );
  173.        
  174.         } else {
  175.        
  176.             // Resized image url
  177.             $resized_url = str_replace( basename( $url ), basename( $dest_file_name ), $url );
  178.        
  179.         }
  180.        
  181.         // Return resized url
  182.         return $resized_url;
  183.    
  184.     }
  185.    
  186.     // Returns common information shared by processing functions
  187.     public function mr_common_info($args) {
  188.        
  189.         global $der;
  190.    
  191.         // Unpack arguments
  192.         list($url, $width, $height, $crop, $align, $retina) = $args;
  193.        
  194.         // Return null if url empty
  195.         if ( empty( $url ) )
  196.             return is_user_logged_in() ? "image_not_specified" : null;
  197.        
  198.         // Return if nocrop is set on query string
  199.         if (preg_match('/(\?|&)nocrop/', $url))
  200.             return $url;
  201.        
  202.         // Get the image file path
  203.         $pathinfo = parse_url( $url );
  204.         $uploads_dir = is_multisite() ? '/files/' : '/wp-content/';
  205.         $file_path = ABSPATH . str_replace(dirname($_SERVER['SCRIPT_NAME']) . '/', '', strstr($pathinfo['path'], $uploads_dir));
  206.        
  207.         // Adjust path on multisite
  208.         if ( is_multisite() ) {
  209.             global $blog_id;
  210.             $file_path = str_replace($uploads_dir, "/wp-content/blogs.dir/${blog_id}/files/", $file_path);
  211.         }
  212.        
  213.         // Remove any double slashes
  214.         $file_path = preg_replace('/\/+/', '/', $file_path);
  215.        
  216.         // Don't process a file that doesn't exist
  217.         if ( !file_exists($file_path) )
  218.             return null; // Degrade gracefully
  219.        
  220.         // Get original image size
  221.         $size = @getimagesize($file_path);
  222.        
  223.         // If no size data obtained, return error or null
  224.         if (!$size)
  225.             return is_user_logged_in() ? "getimagesize_error_common" : null;
  226.        
  227.         // Set original width and height
  228.         list($orig_width, $orig_height, $orig_type) = $size;
  229.        
  230.         // Generate width or height if not provided
  231.         if ($width && !$height) {
  232.             $height = floor ($orig_height * ($width / $orig_width));
  233.         } else if ($height && !$width) {
  234.             $width = floor ($orig_width * ($height / $orig_height));
  235.         } else if (!$width && !$height) {
  236.             return $url; // Return original url if no width/height provided
  237.         }
  238.        
  239.         // Allow for different retina sizes
  240.         $retina = $retina ? ( $retina === true ? 2 : $retina ) : 1;
  241.        
  242.         // Destination width and height variables
  243.         $dest_width = $width * $retina;
  244.         $dest_height = $height * $retina;
  245.        
  246.         // File name suffix (appended to original file name)
  247.         $suffix = "{$dest_width}x{$dest_height}";
  248.        
  249.         // Some additional info about the image
  250.         $info = pathinfo( $file_path );
  251.         $dir = $info['dirname'];
  252.         $ext = $info['extension'];
  253.         $name = wp_basename( $file_path, ".$ext" );
  254.        
  255.         // Suffix applied to filename
  256.         $suffix = "{$dest_width}x{$dest_height}";
  257.        
  258.         // Set align info on file
  259.         if ($align)
  260.             $suffix .= "_$align";
  261.        
  262.         // Get the destination file name
  263.         $dest_file_name = "{$dir}/{$name}-{$suffix}.{$ext}";
  264.        
  265.         // Return info
  266.         return array(
  267.             'dir' => $dir,
  268.             'name' => $name,
  269.             'ext' => $ext,
  270.             'suffix' => $suffix,
  271.             'orig_width' => $orig_width,
  272.             'orig_height' => $orig_height,
  273.             'orig_type' => $orig_type,
  274.             'dest_width' => $dest_width,
  275.             'dest_height' => $dest_height,
  276.             'file_path' => $file_path,
  277.             'dest_file_name' => $dest_file_name,
  278.         );
  279.    
  280.     }
  281.    
  282.     public function mr_delete_resized_images( $post_id ) {
  283.    
  284.         // Get attachment image metadata
  285.         $metadata = wp_get_attachment_metadata( $post_id );
  286.        
  287.         if ( !$metadata )
  288.             return;
  289.        
  290.         // Do some bailing if we cannot continue
  291.         if ( !isset( $metadata['file'] ) || !isset( $metadata['image_meta']['resized_images'] ) )
  292.             return;
  293.        
  294.         $pathinfo = pathinfo( $metadata['file'] );
  295.         $resized_images = $metadata['image_meta']['resized_images'];
  296.        
  297.         // Get WordPress uploads directory (and bail if it doesn't exist)
  298.         $wp_upload_dir = wp_upload_dir();
  299.         $upload_dir = $wp_upload_dir['basedir'];
  300.        
  301.         if ( !is_dir( $upload_dir ) )
  302.             return;
  303.        
  304.         // Delete the resized images
  305.         foreach ( $resized_images as $dims ) {
  306.        
  307.             // Get the resized images filename
  308.             $file = $upload_dir .'/'. $pathinfo['dirname'] .'/'. $pathinfo['filename'] .'-'. $dims .'.'. $pathinfo['extension'];
  309.            
  310.             // Delete the resized image
  311.             @unlink( $file );
  312.        
  313.         }
  314.    
  315.     }
  316.    
  317. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement