/**
  * Creates a cropped version of an image for a given attachment ID.
  *
  * @param int $attachment_id The attachment for which to generate a cropped image.
  * @param int $width The width of the cropped image in pixels.
  * @param int $height The height of the cropped image in pixels.
  * @param bool $crop Whether to crop the generated image.
  * @return string The full path to the cropped image.  Empty if failed.
  */
 private function _generate_attachment($attachment_id = 0, $width = 0, $height = 0, $crop = true)
 {
     $attachment_id = (int) $attachment_id;
     $width = (int) $width;
     $height = (int) $height;
     $crop = (bool) $crop;
     $original_path = get_attached_file($attachment_id);
     // fix a WP bug up to 2.9.2
     if (!function_exists('wp_load_image')) {
         require_once ABSPATH . 'wp-admin/includes/image.php';
     }
     $resized_path = @image_resize($original_path, $width, $height, $crop);
     if (!is_wp_error($resized_path) && !is_array($resized_path)) {
         return $resized_path;
         // perhaps this image already exists.  If so, return it.
     } else {
         $orig_info = pathinfo($original_path);
         $suffix = "{$width}x{$height}";
         $dir = $orig_info['dirname'];
         $ext = $orig_info['extension'];
         $name = basename($original_path, ".{$ext}");
         $destfilename = "{$dir}/{$name}-{$suffix}.{$ext}";
         if (file_exists($destfilename)) {
             return $destfilename;
         }
     }
     return '';
 }
Example #2
0
 function prepare_image($url, $x, $y)
 {
     $wpcurl = strlen(WP_CONTENT_URL);
     if (substr($url, 0, $wpcurl) != WP_CONTENT_URL) {
         return $url;
     } else {
         $path = WP_CONTENT_DIR . substr($url, $wpcurl);
         if (!file_exists($path)) {
             return $url;
         } else {
             $new_path = strlen($path) - 1 - strlen(end(explode(".", $path)));
             $new_path = substr($path, 0, $new_path) . "-" . $x . "x" . $y . "." . end(explode(".", $path));
             if (!file_exists($new_path)) {
                 require_once ABSPATH . 'wp-admin/includes/image.php';
                 $img = image_resize($path, $x, $y, true);
                 if (!is_string($img)) {
                     return $url;
                 } else {
                     return trailingslashit(dirname($url)) . basename($img);
                 }
             } else {
                 $new_url = strlen($url) - 1 - strlen(end(explode(".", $url)));
                 return substr($url, 0, $new_url) . "-" . $x . "x" . $y . "." . end(explode(".", $url));
             }
         }
     }
 }
 /**
  * Retrieve resized image URL
  *
  * @param int $id Post ID or Attachment ID
  * @param int $width desired width of image (optional)
  * @param int $height desired height of image (optional)
  * @return string URL
  * @author Shane & Peter, Inc. (Peter Chester)
  */
 function get_image_url($id, $width = false, $height = false)
 {
     /**/
     // Get attachment and resize but return attachment path (needs to return url)
     $attachment = wp_get_attachment_metadata($id);
     $attachment_url = wp_get_attachment_url($id);
     if (isset($attachment_url)) {
         if ($width && $height) {
             $uploads = wp_upload_dir();
             $imgpath = $uploads['basedir'] . '/' . $attachment['file'];
             error_log($imgpath);
             $image = image_resize($imgpath, $width, $height);
             if ($image && !is_wp_error($image)) {
                 error_log(is_wp_error($image));
                 $image = path_join(dirname($attachment_url), basename($image));
             } else {
                 $image = $attachment_url;
             }
         } else {
             $image = $attachment_url;
         }
         if (isset($image)) {
             return $image;
         }
     }
 }
Example #4
0
 public function index()
 {
     if ($this->config->get('google_base_status')) {
         $output = '<?xml version="1.0" encoding="UTF-8" ?>';
         $output .= '<rss version="2.0" xmlns:g="http://base.google.com/ns/1.0">';
         $output .= '<channel>';
         $output .= '<title>' . $this->config->get('config_store') . '</title>';
         $output .= '<description>' . $this->config->get('config_meta_description') . '</description>';
         $output .= '<link>' . HTTP_SERVER . '</link>';
         $this->load->model('catalog/category');
         $this->load->model('catalog/product');
         $this->load->helper('image');
         $products = $this->model_catalog_product->getProducts();
         foreach ($products as $product) {
             if ($product['description']) {
                 $output .= '<item>';
                 $output .= '<title>' . $product['name'] . '</title>';
                 $output .= '<g:brand>' . $product['manufacturer'] . '</g:brand>';
                 $output .= '<g:condition>new</g:condition>';
                 $output .= '<description>' . $product['description'] . '</description>';
                 $output .= '<guid>' . $product['product_id'] . '</guid>';
                 if ($product['image']) {
                     $output .= '<g:image_link>' . image_resize($product['image'], 500, 500) . '</g:image_link>';
                 } else {
                     $output .= '<g:image_link>' . image_resize('no_image.jpg', 500, 500) . '</g:image_link>';
                 }
                 $output .= '<link>' . $this->url->http('product/product&product_id=' . $product['product_id']) . '</link>';
                 $output .= '<g:mpn>' . $product['model'] . '</g:mpn>';
                 $output .= '<g:price>' . $this->tax->calculate($product['price'], $product['tax_class_id']) . '</g:price>';
                 $categories = $this->model_catalog_product->getCategories($product['product_id']);
                 foreach ($categories as $category) {
                     $path = $this->getPath($category['category_id']);
                     if ($path) {
                         $string = '';
                         foreach (explode('_', $path) as $path_id) {
                             $category_info = $this->model_catalog_category->getCategory($path_id);
                             if ($category_info) {
                                 if (!$string) {
                                     $string = $category_info['name'];
                                 } else {
                                     $string .= ' &gt; ' . $category_info['name'];
                                 }
                             }
                         }
                         $output .= '<g:product_type>' . $string . '</g:product_type>';
                     }
                 }
                 $output .= '<g:quantity>' . $product['quantity'] . '</g:quantity>';
                 $output .= '<g:upc>' . $product['model'] . '</g:upc>';
                 $output .= '<g:weight>' . $this->weight->format($product['weight'], $product['weight_class_id']) . '</g:weight>';
                 $output .= '</item>';
             }
         }
         $output .= '</channel>';
         $output .= '</rss>';
         $this->response->addHeader('Content-Type', 'application/rss+xml');
         $this->response->setOutput($output);
     }
 }
/**
* Title		: Aqua Resizer
* Description	: Resizes WordPress images on the fly
* Version	: 1.1.5
* Author	: Syamil MJ
* Author URI	: http://aquagraphite.com
* License	: WTFPL - http://sam.zoy.org/wtfpl/
* Documentation	: https://github.com/sy4mil/Aqua-Resizer/
*
* @param string $url - (required) must be uploaded using wp media uploader
* @param int $width - (required)
* @param int $height - (optional)
* @param bool $crop - (optional) default to soft crop
* @param bool $single - (optional) returns an array if false
* @uses wp_upload_dir()
* @uses image_resize_dimensions()
* @uses image_resize()
*
* @return str|array
*/
function aq_resize($url, $width, $height = null, $crop = null, $single = true)
{
    //validate inputs
    if (!$url or !$width) {
        return false;
    }
    //define upload path & dir
    $upload_info = wp_upload_dir();
    $upload_dir = $upload_info['basedir'];
    $upload_url = $upload_info['baseurl'];
    //check if $img_url is local
    if (strpos($url, $upload_url) === false) {
        return false;
    }
    //define path of image
    $rel_path = str_replace($upload_url, '', $url);
    $img_path = $upload_dir . $rel_path;
    //check if img path exists, and is an image indeed
    if (!file_exists($img_path) or !getimagesize($img_path)) {
        return false;
    }
    //get image info
    $info = pathinfo($img_path);
    $ext = $info['extension'];
    list($orig_w, $orig_h) = getimagesize($img_path);
    //get image size after cropping
    $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
    $dst_w = $dims[4];
    $dst_h = $dims[5];
    //use this to check if cropped image already exists, so we can return that instead
    $suffix = "{$dst_w}x{$dst_h}";
    $dst_rel_path = str_replace('.' . $ext, '', $rel_path);
    $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";
    if (!$dst_h) {
        //can't resize, so return original url
        $img_url = $url;
        $dst_w = $orig_w;
        $dst_h = $orig_h;
    } elseif (file_exists($destfilename) && getimagesize($destfilename)) {
        $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
    } else {
        $resized_img_path = image_resize($img_path, $width, $height, $crop);
        if (!is_wp_error($resized_img_path)) {
            $resized_rel_path = str_replace($upload_dir, '', $resized_img_path);
            $img_url = $upload_url . $resized_rel_path;
        } else {
            return false;
        }
    }
    //return the output
    if ($single) {
        //str return
        $image = $img_url;
    } else {
        //array return
        $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h);
    }
    return $image;
}
Example #6
0
/**
 * Create a thumbnail from an Image given a maximum side size.
 *
 * This function can handle most image file formats which PHP supports. If PHP
 * does not have the functionality to save in a file of the same format, the
 * thumbnail will be created as a jpeg.
 *
 * @since 1.2.0
 *
 * @param mixed $file Filename of the original image, Or attachment id.
 * @param int $max_side Maximum length of a single side for the thumbnail.
 * @param mixed $deprecated Never used.
 * @return string Thumbnail path on success, Error string on failure.
 */
function wp_create_thumbnail($file, $max_side, $deprecated = '')
{
    if (!empty($deprecated)) {
        _deprecated_argument(__FUNCTION__, '1.2');
    }
    $thumbpath = image_resize($file, $max_side, $max_side);
    return apply_filters('wp_create_thumbnail', $thumbpath);
}
Example #7
0
function vt_resize($attach_id = null, $img_url = null, $width, $height, $crop = false)
{
    // this is an attachment, so we have the ID
    if ($attach_id) {
        $image_src = wp_get_attachment_image_src($attach_id, 'full');
        $file_path = get_attached_file($attach_id);
        // this is not an attachment, let's use the image url
    } else {
        if ($img_url) {
            $file_path = parse_url($img_url);
            $file_path = $_SERVER['DOCUMENT_ROOT'] . $file_path['path'];
            //$file_path = ltrim( $file_path['path'], '/' );
            //$file_path = rtrim( ABSPATH, '/' ).$file_path['path'];
            $orig_size = getimagesize($file_path);
            $image_src[0] = $img_url;
            $image_src[1] = $orig_size[0];
            $image_src[2] = $orig_size[1];
        }
    }
    $file_info = pathinfo($file_path);
    $extension = '.' . $file_info['extension'];
    // the image path without the extension
    $no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
    $cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . $extension;
    // checking if the file size is larger than the target size
    // if it is smaller or the same size, stop right here and return
    if ($image_src[1] > $width || $image_src[2] > $height) {
        // the file is larger, check if the resized version already exists (for $crop = true but will also work for $crop = false if the sizes match)
        if (file_exists($cropped_img_path)) {
            $cropped_img_url = str_replace(basename($image_src[0]), basename($cropped_img_path), $image_src[0]);
            $vt_image = array('url' => $cropped_img_url, 'width' => $width, 'height' => $height);
            return $vt_image;
        }
        // $crop = false
        if ($crop == false) {
            // calculate the size proportionaly
            $proportional_size = wp_constrain_dimensions($image_src[1], $image_src[2], $width, $height);
            $resized_img_path = $no_ext_path . '-' . $proportional_size[0] . 'x' . $proportional_size[1] . $extension;
            // checking if the file already exists
            if (file_exists($resized_img_path)) {
                $resized_img_url = str_replace(basename($image_src[0]), basename($resized_img_path), $image_src[0]);
                $vt_image = array('url' => $resized_img_url, 'width' => $proportional_size[0], 'height' => $proportional_size[1]);
                return $vt_image;
            }
        }
        // no cache files - let's finally resize it
        $new_img_path = image_resize($file_path, $width, $height, $crop);
        $new_img_size = getimagesize($new_img_path);
        $new_img = str_replace(basename($image_src[0]), basename($new_img_path), $image_src[0]);
        // resized output
        $vt_image = array('url' => $new_img, 'width' => $new_img_size[0], 'height' => $new_img_size[1]);
        return $vt_image;
    }
    // default output - without resizing
    $vt_image = array('url' => $image_src[0], 'width' => $image_src[1], 'height' => $image_src[2]);
    return $vt_image;
}
 /**
  * Image moving and resizing routine.
  *
  * Relies on WP built-in image resizing.
  *
  * @param array Image paths to move from temp directory
  * @return mixed Array of new image paths, or (bool)false on failure.
  * @access private
  */
 function move_images($imgs)
 {
     if (!$imgs) {
         return false;
     }
     if (!is_array($imgs)) {
         $imgs = array($imgs);
     }
     global $bp;
     $ret = array();
     $thumb_w = get_option('thumbnail_size_w');
     $thumb_w = $thumb_w ? $thumb_w : 100;
     $thumb_h = get_option('thumbnail_size_h');
     $thumb_h = $thumb_h ? $thumb_h : 100;
     // Override thumbnail image size in wp-config.php
     if (defined('BPFB_THUMBNAIL_IMAGE_SIZE')) {
         list($tw, $th) = explode('x', BPFB_THUMBNAIL_IMAGE_SIZE);
         $thumb_w = (int) $tw ? (int) $tw : $thumb_w;
         $thumb_h = (int) $th ? (int) $th : $thumb_h;
     }
     $processed = 0;
     foreach ($imgs as $img) {
         $processed++;
         if (BPFB_IMAGE_LIMIT && $processed > BPFB_IMAGE_LIMIT) {
             break;
         }
         // Do not even bother to process more.
         if (preg_match('!^https?:\\/\\/!i', $img)) {
             // Just add remote images
             $ret[] = $img;
             continue;
         }
         $pfx = $bp->loggedin_user->id . '_' . preg_replace('/ /', '', microtime());
         $tmp_img = realpath(BPFB_TEMP_IMAGE_DIR . $img);
         $new_img = BPFB_BASE_IMAGE_DIR . "{$pfx}_{$img}";
         if (@rename($tmp_img, $new_img)) {
             if (function_exists('wp_get_image_editor')) {
                 // New way of resizing the image
                 $image = wp_get_image_editor($new_img);
                 if (!is_wp_error($image)) {
                     $thumb_filename = $image->generate_filename('bpfbt');
                     $image->resize($thumb_w, $thumb_h, false);
                     $image->save($thumb_filename);
                 }
             } else {
                 // Old school fallback
                 image_resize($new_img, $thumb_w, $thumb_h, false, 'bpfbt');
             }
             $ret[] = pathinfo($new_img, PATHINFO_BASENAME);
         } else {
             return false;
         }
     }
     return $ret;
 }
Example #9
0
 public function index()
 {
     $this->language->load('common/home');
     $this->document->title = $this->config->get('config_title');
     $this->document->description = $this->config->get('config_meta_description');
     $this->document->breadcrumbs = array();
     $this->document->breadcrumbs[] = array('href' => $this->url->http('common/home'), 'text' => $this->language->get('text_home'), 'separator' => FALSE);
     $this->data['heading_title'] = sprintf($this->language->get('heading_title'), $this->config->get('config_store'));
     $this->data['welcome'] = html_entity_decode($this->config->get('config_welcome_' . $this->language->getId()));
     $this->data['text_latest'] = $this->language->get('text_latest');
     $this->load->model('catalog/product');
     $this->load->model('catalog/review');
     $this->load->model('tool/seo_url');
     $this->load->helper('image');
     $this->data['products'] = array();
     foreach ($this->model_catalog_product->getLatestProducts(8) as $result) {
         if ($result['image']) {
             $image = $result['image'];
         } else {
             $image = 'no_image.jpg';
         }
         $rating = $this->model_catalog_review->getAverageRating($result['product_id']);
         $special = FALSE;
         $discount = $this->model_catalog_product->getProductDiscount($result['product_id']);
         if ($discount) {
             $price = $this->currency->format($this->tax->calculate($discount, $result['tax_class_id'], $this->config->get('config_tax')));
         } else {
             $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
             $special = $this->model_catalog_product->getProductSpecial($result['product_id']);
             if ($special) {
                 $special = $this->currency->format($this->tax->calculate($special, $result['tax_class_id'], $this->config->get('config_tax')));
             }
         }
         $this->data['products'][] = array('name' => $result['name'], 'model' => $result['model'], 'rating' => $rating, 'stars' => sprintf($this->language->get('text_stars'), $rating), 'thumb' => image_resize($image, $this->config->get('config_image_product_width'), $this->config->get('config_image_product_height')), 'price' => $price, 'special' => $special, 'href' => $this->model_tool_seo_url->rewrite($this->url->http('product/product&product_id=' . $result['product_id'])));
     }
     if (!$this->config->get('config_customer_price')) {
         $this->data['display_price'] = TRUE;
     } elseif ($this->customer->isLogged()) {
         $this->data['display_price'] = TRUE;
     } else {
         $this->data['display_price'] = FALSE;
     }
     if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/common/home.tpl')) {
         $this->template = $this->config->get('config_template') . '/template/common/home.tpl';
     } else {
         $this->template = 'default/template/common/home.tpl';
     }
     $this->children = array('common/header', 'common/footer', 'common/column_left', 'common/column_right');
     $this->response->setOutput($this->render(TRUE), $this->config->get('config_compression'));
 }
Example #10
0
function generate_overlayed_image($string)
{
    global $mtimgpath, $maxsize;
    $result = image_new($maxsize, $maxsize);
    $parts = explode('^', $string);
    foreach ($parts as $part) {
        if ($part != '' && $part[0] != '[') {
            $overlay = imagecreatefrompng($mtimgpath . '/' . $part);
            image_resize($overlay, $maxsize, $maxsize);
            imagecopy($result, $overlay, 0, 0, 0, 0, imagesx($overlay), imagesy($overlay));
            imagedestroy($overlay);
        }
    }
    return $result;
}
Example #11
0
/**
 * Replacement for deprecated image_resize function
 * @param string $file Image file path.
 * @param int $max_w Maximum width to resize to.
 * @param int $max_h Maximum height to resize to.
 * @param bool $crop Optional. Whether to crop image or resize.
 * @param string $suffix Optional. File suffix.
 * @param string $dest_path Optional. New image file path.
 * @param int $jpeg_quality Optional, default is 90. Image quality percentage.
 * @return mixed WP_Error on failure. String with new destination path.
 */
function imsanity_image_resize($file, $max_w, $max_h, $crop = false, $suffix = null, $dest_path = null, $jpeg_quality = 90)
{
    if (function_exists('wp_get_image_editor')) {
        // WP 3.5 and up use the image editor
        $editor = wp_get_image_editor($file);
        if (is_wp_error($editor)) {
            return $editor;
        }
        $editor->set_quality($jpeg_quality);
        // try to correct for auto-rotation if the info is available
        if (function_exists('exif_read_data')) {
            $exif = exif_read_data($file);
            $orientation = is_array($exif) && array_key_exists('Orientation', $exif) ? $exif['Orientation'] : 0;
            switch ($orientation) {
                case 3:
                    $editor->rotate(180);
                    break;
                case 6:
                    $editor->rotate(-90);
                    break;
                case 8:
                    $editor->rotate(90);
                    break;
            }
        }
        $resized = $editor->resize($max_w, $max_h, $crop);
        if (is_wp_error($resized)) {
            return $resized;
        }
        $dest_file = $editor->generate_filename($suffix, $dest_path);
        // FIX: make sure that the destination file does not exist.  this fixes
        // an issue during bulk resize where one of the optimized media filenames may get
        // used as the temporary file, which causes it to be deleted.
        while (file_exists($dest_file)) {
            $dest_file = $editor->generate_filename('TMP', $dest_path);
        }
        $saved = $editor->save($dest_file);
        if (is_wp_error($saved)) {
            return $saved;
        }
        return $dest_file;
    } else {
        // wordpress prior to 3.5 uses the old image_resize function
        return image_resize($file, $max_w, $max_h, $crop, $suffix, $dest_path, $jpeg_quality);
    }
}
Example #12
0
 protected function index()
 {
     $this->language->load('module/bestseller');
     $this->data['heading_title'] = $this->language->get('heading_title');
     $this->load->model('catalog/product');
     $this->load->model('catalog/review');
     $this->load->model('tool/seo_url');
     $this->load->helper('image');
     $this->data['products'] = array();
     $results = $this->model_catalog_product->getBestSellerProducts($this->config->get('bestseller_limit'));
     foreach ($results as $result) {
         if ($result['image']) {
             $image = $result['image'];
         } else {
             $image = 'no_image.jpg';
         }
         $rating = $this->model_catalog_review->getAverageRating($result['product_id']);
         $special = FALSE;
         $discount = $this->model_catalog_product->getProductDiscount($result['product_id']);
         if ($discount) {
             $price = $this->currency->format($this->tax->calculate($discount, $result['tax_class_id'], $this->config->get('config_tax')));
         } else {
             $price = $this->currency->format($this->tax->calculate($result['price'], $result['tax_class_id'], $this->config->get('config_tax')));
             $special = $this->model_catalog_product->getProductSpecial($result['product_id']);
             if ($special) {
                 $special = $this->currency->format($this->tax->calculate($special, $result['tax_class_id'], $this->config->get('config_tax')));
             }
         }
         $this->data['products'][] = array('name' => $result['name'], 'price' => $price, 'special' => $special, 'image' => image_resize($image, 38, 38), 'href' => $this->model_tool_seo_url->rewrite($this->url->http('product/product&product_id=' . $result['product_id'])));
     }
     if (!$this->config->get('config_customer_price')) {
         $this->data['display_price'] = TRUE;
     } elseif ($this->customer->isLogged()) {
         $this->data['display_price'] = TRUE;
     } else {
         $this->data['display_price'] = FALSE;
     }
     $this->id = 'bestseller';
     if (file_exists(DIR_TEMPLATE . $this->config->get('config_template') . '/template/module/bestseller.tpl')) {
         $this->template = $this->config->get('config_template') . '/template/module/bestseller.tpl';
     } else {
         $this->template = 'default/template/module/bestseller.tpl';
     }
     $this->render();
 }
Example #13
0
 function validate($data = null)
 {
     $this->errors = array();
     if (!empty($data)) {
         $data = empty($data[$this->model]) ? $data : $data[$this->model];
         foreach ($data as $dkey => $dval) {
             $this->data->{$dkey} = stripslashes($dval);
         }
         extract($data, EXTR_SKIP);
         if (empty($title)) {
             $this->errors['title'] = __('Please fill in a title', $this->plugin_name);
         }
         if (empty($description)) {
             $this->errors['description'] = __('Please fill in a description', $this->plugin_name);
         }
         if (empty($image_url)) {
             $this->errors['image_url'] = __('Please specify an image', $this->plugin_name);
         } else {
             if ($image = wp_remote_fopen($image_url)) {
                 $filename = basename($image_url);
                 $filepath = ABSPATH . 'wp-content' . DS . 'uploads' . DS . $this->plugin_name . DS;
                 $filefull = $filepath . $filename;
                 if (!file_exists($filefull)) {
                     $fh = @fopen($filefull, "w");
                     @fwrite($fh, $image);
                     @fclose($fh);
                     $name = GalleryHtmlHelper::strip_ext($filename, 'filename');
                     $ext = GalleryHtmlHelper::strip_ext($filename, 'ext');
                     $thumbfull = $filepath . $name . '-thumb.' . $ext;
                     $smallfull = $filepath . $name . '-small.' . $ext;
                     image_resize($filefull, $width = null, $height = 75, $crop = false, $append = 'thumb', $dest = null, $quality = 100);
                     image_resize($filefull, $width = 50, $height = 50, $crop = true, $append = 'small', $dest = null, $quality = 100);
                     @chmod($filefull, 0777);
                     @chmod($thumbfull, 0777);
                     @chmod($smallfull, 0777);
                 }
             }
         }
     } else {
         $this->errors[] = __('No data was posted', $this->plugin_name);
     }
     return $this->errors;
 }
function ml_image_resize($img_url, $width, $height, $crop = false, $jpeg_quality = 90)
{
    $file_path = parse_url($img_url);
    //$file_path = ltrim( $file_path['path'], '/' );
    $file_path = rtrim(ABSPATH, '/') . $file_path['path'];
    $orig_size = @getimagesize($file_path);
    $image_src[0] = $img_url;
    $image_src[1] = $orig_size[0];
    $image_src[2] = $orig_size[1];
    $file_info = pathinfo($file_path);
    $extension = '.' . $file_info['extension'];
    // the image path without the extension
    $no_ext_path = $file_info['dirname'] . '/' . $file_info['filename'];
    $cropped_img_path = $no_ext_path . '-' . $width . 'x' . $height . $extension;
    // checking if the file size is larger than the target size
    // if it is smaller or the same size, stop right here and return
    if ($image_src[1] > $width || $image_src[2] > $height) {
        // the file is larger, check if the resized version already exists (for crop = true but will also work for crop = false if the sizes match)
        if (file_exists($cropped_img_path)) {
            $cropped_img_url = str_replace(basename($image_src[0]), basename($cropped_img_path), $image_src[0]);
            return $cropped_img_url;
        }
        // crop = false
        if ($crop == false) {
            // calculate the size proportionaly
            $proportional_size = wp_constrain_dimensions($image_src[1], $image_src[2], $width, $height);
            $resized_img_path = $no_ext_path . '-' . $proportional_size[0] . 'x' . $proportional_size[1] . $extension;
            // checking if the file already exists
            if (file_exists($resized_img_path)) {
                $resized_img_url = str_replace(basename($image_src[0]), basename($resized_img_path), $image_src[0]);
                return $resized_img_url;
            }
        }
        // no cached files - let's finally resize it
        $new_img_path = image_resize($file_path, $width, $height, $crop, NULL, $cropped_img_path, $jpeg_quality);
        $new_img_size = @getimagesize($new_img_path);
        $new_img = str_replace(basename($image_src[0]), basename($new_img_path), $image_src[0]);
        // resized output
        return $new_img;
    }
    return $image_src[0];
}
 private static function _generate_image_size($attachment_id, $size)
 {
     $attachment = get_post($attachment_id);
     $file = self::_load_image_to_edit_path($attachment_id);
     $size_data = self::get_image_size($size);
     $metadata = wp_get_attachment_metadata($attachment_id);
     if (!$metadata || !is_array($metadata)) {
         if ($attached_file = get_post_meta($attachment_id, '_wp_attached_file', true)) {
             $upload_dir = wp_upload_dir();
             if (!function_exists('wp_generate_attachment_metadata')) {
                 require_once ABSPATH . 'wp-admin/includes/image.php';
             }
             $metadata = wp_generate_attachment_metadata($attachment_id, $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $attached_file);
             if (!$metadata) {
                 return false;
             }
         } else {
             return false;
         }
     }
     if ($size && !empty($size_data) && $file && preg_match('!^image/!', get_post_mime_type($attachment)) && self::file_is_displayable_image($file)) {
         if (function_exists('wp_get_image_editor')) {
             $editor = wp_get_image_editor($file);
             if (!is_wp_error($editor) && $editor) {
                 $new_size = $editor->multi_resize(array($size => $size_data));
                 if (empty($metadata['sizes'])) {
                     $metadata['sizes'] = $new_size;
                 } else {
                     $metadata['sizes'] = array_merge($metadata['sizes'], $new_size);
                 }
             }
         } else {
             extract($size_data);
             $file_path = image_resize($file, $width, $height, $crop);
             if (!is_wp_error($file_path) && $file_path) {
                 $file = basename($file_path);
                 $metadata['sizes'][$size] = array('file' => $file, 'width' => $width, 'height' => $height);
             }
         }
         wp_update_attachment_metadata($attachment_id, $metadata);
     }
 }
function dynimg_404_handler()
{
    if (!is_404()) {
        return;
    }
    if (preg_match('/(.*)-([0-9]+)x([0-9]+)(c)?\\.(jpg|png|gif)/i', $_SERVER['REQUEST_URI'], $matches)) {
        $filename = $matches[1] . '.' . $matches[5];
        $width = $matches[2];
        $height = $matches[3];
        $crop = !empty($matches[4]);
        $uploads_dir = wp_upload_dir();
        $temp = parse_url($uploads_dir['baseurl']);
        $upload_path = $temp['path'];
        $findfile = str_replace($upload_path, '', $filename);
        $basefile = $uploads_dir['basedir'] . $findfile;
        $suffix = $width . 'x' . $height;
        if ($crop) {
            $suffix .= 'c';
        }
        if (file_exists($basefile)) {
            // we have the file, so call the wp function to actually resize the image
            //			$resized = image_resize($basefile, $width, $height, $crop, $suffix);
            $resized = image_resize($basefile, $width, $height, true, $suffix);
            // find the mime type
            foreach (get_allowed_mime_types() as $exts => $mime) {
                if (preg_match('!^(' . $exts . ')$!i', $matches[5])) {
                    $type = $mime;
                    break;
                }
            }
            // serve the image this one time (next time the webserver will do it for us)
            header('Content-Type: ' . $type);
            header('Content-Length: ' . filesize($resized));
            readfile($resized);
            exit;
        }
    }
}
 /**
  * Image moving and resizing routine.
  *
  * Relies on WP built-in image resizing.
  *
  * @param array Image paths to move from temp directory
  * @return mixed Array of new image paths, or (bool)false on failure.
  * @access private
  */
 function move_images($imgs)
 {
     if (!$imgs) {
         return false;
     }
     if (!is_array($imgs)) {
         $imgs = array($imgs);
     }
     global $bp;
     $ret = array();
     $thumb_w = get_option('thumbnail_size_w');
     $thumb_w = $thumb_w ? $thumb_w : 100;
     $thumb_h = get_option('thumbnail_size_h');
     $thumb_h = $thumb_h ? $thumb_h : 100;
     // Override thumbnail image size in wp-config.php
     if (defined('BPFB_THUMBNAIL_IMAGE_SIZE')) {
         list($tw, $th) = explode('x', BPFB_THUMBNAIL_IMAGE_SIZE);
         $thumb_w = (int) $tw ? (int) $tw : $thumb_w;
         $thumb_h = (int) $th ? (int) $th : $thumb_h;
     }
     foreach ($imgs as $img) {
         if (preg_match('!^' . preg_quote('http://') . '!i', $img)) {
             // Just add remote images
             $ret[] = $img;
             continue;
         }
         $pfx = $bp->loggedin_user->id . '_' . preg_replace('/ /', '', microtime());
         $tmp_img = realpath(BPFB_TEMP_IMAGE_DIR . $img);
         $new_img = BPFB_BASE_IMAGE_DIR . "{$pfx}_{$img}";
         if (@rename($tmp_img, $new_img)) {
             image_resize($new_img, $thumb_w, $thumb_h, false, 'bpfbt');
             $ret[] = pathinfo($new_img, PATHINFO_BASENAME);
         } else {
             return false;
         }
     }
     return $ret;
 }
Example #18
0
 public function check_image_size($array)
 {
     if (eregi("image", $array['type'])) {
         // the content type says its an image so lets run with it
         $path_to_file = $array['file'];
         // check the width and height against the maximum allowed
         $image_size = getimagesize($path_to_file);
         // if they are greater then scale the image down
         $options = get_option('ROU_Options', "");
         // ok actually check the size of the image and not just
         // ignore it like....
         if ($image_size[0] > $options['rou_max_width'] || $image_size[1] > $options['rou_max_height']) {
             $new_path = image_resize($path_to_file, $options['rou_max_width'], $options['rou_max_height']);
             // wp-include/media.php/image_resize()
             // DEBUG dump the array info in the options
             update_option('ROU_attach_id', $new_path);
             unlink($path_to_file);
             rename($new_path, $path_to_file);
         }
         // save image
     }
     return $array;
 }
Example #19
0
 public function index()
 {
     $result = array();
     $result['status_code'] = 403;
     $result['message'] = "Invalid file namez";
     if (!$this->is_ajax_request()) {
         header('Content-type: text/plain');
     }
     if (!empty($_FILES)) {
         $config = array();
         $config['upload_path'] = './iu-assets/' . $this->user->id . '/';
         $config['allowed_types'] = 'gif|jpg|png';
         $this->load->library('upload', $config);
         if (!$this->upload->do_upload('file')) {
             $result['message'] = $this->upload->display_errors();
         } else {
             $data = $this->upload->data();
             if (empty($data['is_image'])) {
                 die(json_encode($result));
             }
             $content_width = $_POST['max_width'];
             $img_width = $data['image_width'];
             if ($img_width > $content_width) {
                 $img = image_create_from_file('iu-assets/' . $this->user->id . '/' . $data['file_name']);
                 $img = image_resize($img, $content_width);
                 image_to_file($img, 'iu-assets/' . $this->user->id . '/' . $content_width . '_' . $data['file_name']);
                 $result['url'] = base_url() . 'iu-assets/' . $this->user->id . '/' . $content_width . '_' . $data['file_name'];
             } else {
                 $result['url'] = base_url() . 'iu-assets/' . $this->user->id . '/' . $data['file_name'];
             }
             $result['message'] = 'Success';
             $result['status_code'] = 200;
         }
     }
     die(json_encode($result));
 }
Example #20
0
 public function get_avatar($avatar = '', $id_or_email, $size = 96, $default = '', $alt = false)
 {
     if (is_numeric($id_or_email)) {
         $user_id = (int) $id_or_email;
     } elseif (is_string($id_or_email) && ($user = get_user_by('email', $id_or_email))) {
         $user_id = $user->ID;
     } elseif (is_object($id_or_email) && !empty($id_or_email->user_id)) {
         $user_id = (int) $id_or_email->user_id;
     }
     if (empty($user_id)) {
         return $avatar;
     }
     $local_avatars = get_user_meta($user_id, 'simple_local_avatar', true);
     if (empty($local_avatars) || empty($local_avatars['full'])) {
         return $avatar;
     }
     $size = (int) $size;
     if (empty($alt)) {
         $alt = get_the_author_meta('display_name', $user_id);
     }
     // generate a new size
     if (empty($local_avatars[$size])) {
         $upload_path = wp_upload_dir();
         $avatar_full_path = str_replace($upload_path['baseurl'], $upload_path['basedir'], $local_avatars['full']);
         $image_sized = image_resize($avatar_full_path, $size, $size, true);
         // deal with original being >= to original image (or lack of sizing ability)
         $local_avatars[$size] = is_wp_error($image_sized) ? $local_avatars[$size] = $local_avatars['full'] : str_replace($upload_path['basedir'], $upload_path['baseurl'], $image_sized);
         // save updated avatar sizes
         update_user_meta($user_id, 'simple_local_avatar', $local_avatars);
     } elseif (substr($local_avatars[$size], 0, 4) != 'http') {
         $local_avatars[$size] = home_url($local_avatars[$size]);
     }
     $author_class = is_author($user_id) ? ' current-author' : '';
     $avatar = "<img alt='" . esc_attr($alt) . "' src='" . $local_avatars[$size] . "' class='avatar avatar-{$size}{$author_class} photo' height='{$size}' width='{$size}' />";
     return apply_filters('simple_local_avatar', $avatar);
 }
Example #21
0
 /**
  * 后台修改专题
  */
 function onedit()
 {
     if (isset($this->post['submit'])) {
         $title = $this->post['title'];
         $desrc = $this->post['desc'];
         $tid = intval($this->post['id']);
         $imgname = strtolower($_FILES['image']['name']);
         if ('' == $title || '' == $desrc) {
             $this->ondefault('请完整填写专题相关参数!', 'errormsg');
             exit;
         }
         if ($imgname) {
             $type = substr(strrchr($imgname, '.'), 1);
             if (!isimage($type)) {
                 $this->ondefault('当前图片图片格式不支持,目前仅支持jpg、gif、png格式!', 'errormsg');
                 exit;
             }
             $filepath = '/data/attach/topic/topic' . random(6, 0) . '.' . $type;
             $upload_tmp_file = TIPASK_ROOT . '/data/tmp/topic_' . random(6, 0) . '.' . $type;
             forcemkdir(TIPASK_ROOT . '/data/attach/topic');
             if (move_uploaded_file($_FILES['image']['tmp_name'], $upload_tmp_file)) {
                 image_resize($upload_tmp_file, TIPASK_ROOT . $filepath, 270, 220);
                 $_ENV['topic']->update($tid, $title, $desrc, $filepath);
                 $this->ondefault('专题修改成功!');
             } else {
                 $this->ondefault('服务器忙,请稍后再试!');
             }
         } else {
             $_ENV['topic']->update($tid, $title, $desrc);
             $this->ondefault('专题修改成功!');
         }
     } else {
         $topic = $_ENV['topic']->get(intval($this->get[2]));
         include template("addtopic", 'admin');
     }
 }
Example #22
0
/**
 * This was once used to create a thumbnail from an Image given a maximum side size.
 *
 * @since 1.2.0
 * @deprecated 3.5.0
 * @deprecated Use image_resize()
 * @see image_resize()
 *
 * @param mixed $file Filename of the original image, Or attachment id.
 * @param int $max_side Maximum length of a single side for the thumbnail.
 * @param mixed $deprecated Never used.
 * @return string Thumbnail path on success, Error string on failure.
 */
function wp_create_thumbnail($file, $max_side, $deprecated = '')
{
    _deprecated_function(__FUNCTION__, '3.5', 'image_resize()');
    return apply_filters('wp_create_thumbnail', image_resize($file, $max_side, $max_side));
}
Example #23
0
/**
 * Get Image Source.
 *
 * Return a uri to a custom image size.
 *
 * If size doesn't exist, attempt to create a resized version.
 * The output of this function should be escaped before printing to the browser.
 *
 * @param     int       Image ID.
 * @return    string    URI of custom image on success; emtpy string otherwise.
 *
 * @access    private.
 * @since     2010-10-28
 */
function taxonomy_image_plugin_get_image_src($id)
{
    $detail = taxonomy_image_plugin_detail_image_size();
    /* Return url to custom intermediate size if it exists. */
    $img = image_get_intermediate_size($id, $detail['name']);
    if (isset($img['url'])) {
        return $img['url'];
    }
    /* Detail image does not exist, attempt to create it. */
    $wp_upload_dir = wp_upload_dir();
    if (isset($wp_upload_dir['basedir'])) {
        /* Create path to original uploaded image. */
        $path = trailingslashit($wp_upload_dir['basedir']) . get_post_meta($id, '_wp_attached_file', true);
        if (is_file($path)) {
            /* Attempt to create a new downsized version of the original image. */
            $new = image_resize($path, $detail['size'][0], $detail['size'][1], $detail['size'][2]);
            /* Image creation successful. Generate and cache image metadata. Return url. */
            if (!is_wp_error($new)) {
                $meta = wp_generate_attachment_metadata($id, $path);
                wp_update_attachment_metadata($id, $meta);
                $img = image_get_intermediate_size($id, $detail['name']);
                if (isset($img['url'])) {
                    return $img['url'];
                }
            }
        }
    }
    /* Custom intermediate size cannot be created, try for thumbnail. */
    $img = image_get_intermediate_size($id, 'thumbnail');
    if (isset($img['url'])) {
        return $img['url'];
    }
    /* Thumbnail cannot be found, try fullsize. */
    $url = wp_get_attachment_url($id);
    if (!empty($url)) {
        return $url;
    }
    /**
     * No image can be found.
     * This is most likely caused by a user deleting an attachment before deleting it's association with a taxonomy.
     * If we are in the administration panels:
     * - Delete the association.
     * - Return uri to default.png.
     */
    if (is_admin()) {
        $assoc = taxonomy_image_plugin_get_associations();
        foreach ($assoc as $term => $img) {
            if ($img === $id) {
                unset($assoc[$term]);
            }
        }
        update_option('taxonomy_image_plugin', $assoc);
        return taxonomy_image_plugin_url('default.png');
    }
    /*
     * No image can be found.
     * Return path to blank-image.png.
     */
    return taxonomy_image_plugin_url('blank.png');
}
Example #24
0
function lambda_resize($url, $width = null, $height = null, $crop = null, $single = true, $upscale = false)
{
    if (!$url || !$width && !$height) {
        return false;
    }
    // Caipt'n, ready to hook.
    if (true === $upscale) {
        add_filter('image_resize_dimensions', 'lambda_upscale', 10, 6);
    }
    // Define upload path & dir.
    $upload_info = wp_upload_dir();
    $upload_dir = $upload_info['basedir'];
    $upload_url = $upload_info['baseurl'];
    $http_prefix = "http://";
    $https_prefix = "https://";
    /* if the $url scheme differs from $upload_url scheme, make them match 
       if the schemes differe, images don't show up. */
    if (!strncmp($url, $https_prefix, strlen($https_prefix))) {
        //if url begins with https:// make $upload_url begin with https:// as well
        $upload_url = str_replace($http_prefix, $https_prefix, $upload_url);
    } elseif (!strncmp($url, $http_prefix, strlen($http_prefix))) {
        //if url begins with http:// make $upload_url begin with http:// as well
        $upload_url = str_replace($https_prefix, $http_prefix, $upload_url);
    }
    // Check if $img_url is local.
    if (false === strpos($url, $upload_url)) {
        return false;
    }
    // Define path of image.
    $rel_path = str_replace($upload_url, '', $url);
    $img_path = $upload_dir . $rel_path;
    // Check if img path exists, and is an image indeed.
    if (!file_exists($img_path) or !getimagesize($img_path)) {
        return false;
    }
    // Get image info.
    $info = pathinfo($img_path);
    $ext = $info['extension'];
    list($orig_w, $orig_h) = getimagesize($img_path);
    // Get image size after cropping.
    $dims = image_resize_dimensions($orig_w, $orig_h, $width, $height, $crop);
    $dst_w = $dims[4];
    $dst_h = $dims[5];
    // Return the original image only if it exactly fits the needed measures.
    if (!$dims && (null === $height && $orig_w == $width xor null === $width && $orig_h == $height xor $height == $orig_h && $width == $orig_w)) {
        $img_url = $url;
        $dst_w = $orig_w;
        $dst_h = $orig_h;
    } else {
        // Use this to check if cropped image already exists, so we can return that instead.
        $suffix = "{$dst_w}x{$dst_h}";
        $dst_rel_path = str_replace('.' . $ext, '', $rel_path);
        $destfilename = "{$upload_dir}{$dst_rel_path}-{$suffix}.{$ext}";
        if (!$dims || true == $crop && false == $upscale && ($dst_w < $width || $dst_h < $height)) {
            // Can't resize, so return false saying that the action to do could not be processed as planned.
            return $url;
        } elseif (file_exists($destfilename) && getimagesize($destfilename)) {
            $img_url = "{$upload_url}{$dst_rel_path}-{$suffix}.{$ext}";
        } else {
            // Note: This pre-3.5 fallback check will edited out in subsequent version.
            if (function_exists('wp_get_image_editor')) {
                $editor = wp_get_image_editor($img_path);
                if (is_wp_error($editor) || is_wp_error($editor->resize($width, $height, $crop))) {
                    return false;
                }
                $resized_file = $editor->save();
                if (!is_wp_error($resized_file)) {
                    $resized_rel_path = str_replace($upload_dir, '', $resized_file['path']);
                    $img_url = $upload_url . $resized_rel_path;
                } else {
                    return false;
                }
            } else {
                $resized_img_path = image_resize($img_path, $width, $height, $crop);
                // Fallback foo.
                if (!is_wp_error($resized_img_path)) {
                    $resized_rel_path = str_replace($upload_dir, '', $resized_img_path);
                    $img_url = $upload_url . $resized_rel_path;
                } else {
                    return false;
                }
            }
        }
    }
    // Okay, leave the ship.
    if (true === $upscale) {
        remove_filter('image_resize_dimensions', 'lambda_upscale');
    }
    // Return the output.
    if ($single) {
        // str return.
        $image = $img_url;
    } else {
        // array return.
        $image = array(0 => $img_url, 1 => $dst_w, 2 => $dst_h);
    }
    return $image;
}
Example #25
0
        $imageHeight = $Config['_ImageSizeY'][$Field] == 'auto' ? '0' : $Config['_ImageSizeY'][$Field];
        $iconWidth = $Config['_IconSizeX'][$Field] == 'auto' ? '0' : $Config['_IconSizeX'][$Field];
        $iconHeight = $Config['_IconSizeY'][$Field] == 'auto' ? '0' : $Config['_IconSizeY'][$Field];
        $uploadVars = wp_upload_dir();
        $SourceFile = str_replace($uploadVars['url'], $uploadVars['path'], $Value);
        if (!file_exists($SourceFile)) {
            $Return .= 'Image does not exists.';
        }
        $dim = getimagesize($SourceFile);
        $newDim = image_resize_dimensions($dim[0], $dim[1], $iconWidth, $iconHeight, true);
        $Sourcepath = pathinfo($SourceFile);
        $URLpath = pathinfo($Value);
        $iconURL = $URLpath['dirname'] . '/' . $URLpath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $URLpath['extension'];
        if (!file_exists($Sourcepath['dirname'] . '/' . $Sourcepath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $Sourcepath['extension'])) {
            $image = image_resize($SourceFile, $imageWidth, $imageHeight, true);
            $icon = image_resize($SourceFile, $iconWidth, $iconHeight, true);
        }
        $ClassName = '';
        if (!empty($Config['_ImageClassName'][$Field])) {
            $ClassName = 'class="' . $Config['_ImageClassName'][$Field] . '" ';
        }
        if (!empty($Config['_IconURLOnly'][$Field])) {
            $Return .= $iconURL;
        }
        $Return .= '<img src="' . $iconURL . '" ' . $ClassName . image_hwstring($iconWidth, $iconHeight) . '>';
    }
    $Return .= '<input type="file" name="dataForm[' . $Element['ID'] . '][' . $Field . ']" id="entry_' . $Element['ID'] . '_' . $Field . '" style="width:97%;" class="' . $Req . '" />';
}
if ($FieldSet[1] == 'file') {
    $Return = '';
    if (!empty($Defaults[$Field])) {
Example #26
0
 function et_resize_image($thumb, $new_width, $new_height, $crop)
 {
     if (is_ssl()) {
         $thumb = preg_replace('#^http://#', 'https://', $thumb);
     }
     $info = pathinfo($thumb);
     $ext = $info['extension'];
     $name = wp_basename($thumb, ".{$ext}");
     $is_jpeg = false;
     $site_uri = apply_filters('et_resize_image_site_uri', site_url());
     $site_dir = apply_filters('et_resize_image_site_dir', ABSPATH);
     #get main site url on multisite installation
     if (is_multisite()) {
         switch_to_blog(1);
         $site_uri = site_url();
         restore_current_blog();
     }
     if ('jpeg' == $ext) {
         $ext = 'jpg';
         $name = preg_replace('#.jpeg$#', '', $name);
         $is_jpeg = true;
     }
     $suffix = "{$new_width}x{$new_height}";
     $destination_dir = '' != get_option('et_images_temp_folder') ? preg_replace('#\\/\\/#', '/', get_option('et_images_temp_folder')) : null;
     $matches = apply_filters('et_resize_image_site_dir', array(), $site_dir);
     if (!empty($matches)) {
         preg_match('#' . $matches[1] . '$#', $site_uri, $site_uri_matches);
         if (!empty($site_uri_matches)) {
             $site_uri = str_replace($matches[1], '', $site_uri);
             $site_uri = preg_replace('#/$#', '', $site_uri);
             $site_dir = str_replace($matches[1], '', $site_dir);
             $site_dir = preg_replace('#\\\\/$#', '', $site_dir);
         }
     }
     #get local name for use in file_exists() and get_imagesize() functions
     $localfile = str_replace(apply_filters('et_resize_image_localfile', $site_uri, $site_dir, et_multisite_thumbnail($thumb)), $site_dir, et_multisite_thumbnail($thumb));
     $add_to_suffix = '';
     if (file_exists($localfile)) {
         $add_to_suffix = filesize($localfile) . '_';
     }
     #prepend image filesize to be able to use images with the same filename
     $suffix = $add_to_suffix . $suffix;
     $destfilename_attributes = '-' . $suffix . '.' . $ext;
     $checkfilename = '' != $destination_dir && null !== $destination_dir ? path_join($destination_dir, $name) : path_join(dirname($localfile), $name);
     $checkfilename .= $destfilename_attributes;
     if ($is_jpeg) {
         $checkfilename = preg_replace('#.jpeg$#', '.jpg', $checkfilename);
     }
     $uploads_dir = wp_upload_dir();
     $uploads_dir['basedir'] = preg_replace('#\\/\\/#', '/', $uploads_dir['basedir']);
     if (null !== $destination_dir && '' != $destination_dir && apply_filters('et_enable_uploads_detection', true)) {
         $site_dir = trailingslashit(preg_replace('#\\/\\/#', '/', $uploads_dir['basedir']));
         $site_uri = trailingslashit($uploads_dir['baseurl']);
     }
     #check if we have an image with specified width and height
     if (file_exists($checkfilename)) {
         return str_replace($site_dir, trailingslashit($site_uri), $checkfilename);
     }
     $size = @getimagesize($localfile);
     if (!$size) {
         return new WP_Error('invalid_image_path', __('Image doesn\'t exist'), $thumb);
     }
     list($orig_width, $orig_height, $orig_type) = $size;
     #check if we're resizing the image to smaller dimensions
     if ($orig_width > $new_width || $orig_height > $new_height) {
         if ($orig_width < $new_width || $orig_height < $new_height) {
             #don't resize image if new dimensions > than its original ones
             if ($orig_width < $new_width) {
                 $new_width = $orig_width;
             }
             if ($orig_height < $new_height) {
                 $new_height = $orig_height;
             }
             #regenerate suffix and appended attributes in case we changed new width or new height dimensions
             $suffix = "{$add_to_suffix}{$new_width}x{$new_height}";
             $destfilename_attributes = '-' . $suffix . '.' . $ext;
             $checkfilename = '' != $destination_dir && null !== $destination_dir ? path_join($destination_dir, $name) : path_join(dirname($localfile), $name);
             $checkfilename .= $destfilename_attributes;
             #check if we have an image with new calculated width and height parameters
             if (file_exists($checkfilename)) {
                 return str_replace($site_dir, trailingslashit($site_uri), $checkfilename);
             }
         }
         #we didn't find the image in cache, resizing is done here
         $result = image_resize($localfile, $new_width, $new_height, $crop, $suffix, $destination_dir);
         if (!is_wp_error($result)) {
             #transform local image path into URI
             if ($is_jpeg) {
                 $thumb = preg_replace('#.jpeg$#', '.jpg', $thumb);
             }
             $site_dir = str_replace('\\', '/', $site_dir);
             $result = str_replace('\\', '/', $result);
             $result = str_replace('//', '/', $result);
             $result = str_replace($site_dir, trailingslashit($site_uri), $result);
         }
         #returns resized image path or WP_Error ( if something went wrong during resizing )
         return $result;
     }
     #returns unmodified image, for example in case if the user is trying to resize 800x600px to 1920x1080px image
     return $thumb;
 }
Example #27
0
$rules = array('username' => array('label' => '{lang username}', 'value' => $username, 'rules' => 'required', 'check' => function ($value) use($username) {
    if ($value != $username && NeoFrag::loader()->db->select('1')->from('nf_users')->where('username', $value)->row()) {
        return i18n('username_unavailable');
    }
}), 'email' => array('label' => '{lang email}', 'value' => $email, 'type' => 'email', 'rules' => 'required', 'check' => function ($value) use($email) {
    if ($value != $email && NeoFrag::loader()->db->select('1')->from('nf_users')->where('email', $value)->row()) {
        return i18n('email_unavailable');
    }
}), 'first_name' => array('label' => '{lang first_name}', 'value' => $first_name), 'last_name' => array('label' => '{lang last_name}', 'value' => $last_name), 'avatar' => array('label' => '{lang avatar}', 'value' => $avatar, 'upload' => 'members', 'type' => 'file', 'info' => i18n('file_icon', 250, file_upload_max_size() / 1024 / 1024), 'check' => function ($filename, $ext) {
    if (!in_array($ext, array('gif', 'jpeg', 'jpg', 'png'))) {
        return i18n('select_image_file');
    }
    list($w, $h) = getimagesize($filename);
    if ($w != $h) {
        return i18n('avatar_must_be_square');
    } else {
        if ($w < 250) {
            return i18n('avatar_size_error', 250);
        }
    }
}, 'post_upload' => function ($filename) {
    image_resize($filename, 250, 250);
}), 'date_of_birth' => array('label' => '{lang birth_date}', 'value' => $date_of_birth && $date_of_birth != '0000-00-00' ? timetostr(NeoFrag::loader()->lang('date_short'), strtotime($date_of_birth)) : '', 'type' => 'date', 'check' => function ($value) {
    if ($value && strtotime($value) > strtotime(date('Y-m-d'))) {
        return i18n('invalid_birth_date');
    }
}), 'sex' => array('label' => '{lang gender}', 'value' => $sex, 'values' => array('female' => icon('fa-female') . ' {lang female}', 'male' => icon('fa-male') . ' {lang male}'), 'type' => 'radio'), 'location' => array('label' => '{lang location}', 'value' => $location), 'website' => array('label' => '{lang website}', 'value' => $website, 'type' => 'url'), 'quote' => array('label' => '{lang quote}', 'value' => $quote), 'signature' => array('label' => '{lang signature}', 'value' => $signature, 'type' => 'editor'));
/*
NeoFrag Alpha 0.1.2
./neofrag/modules/members/forms/members.php
*/
Example #28
0
 function et_resize_image($thumb, $new_width, $new_height, $crop)
 {
     /*
      * Fixes the issue with x symbol between width and height values in the filename.
      * For instance, sports-400x400.jpg file results in 'image not found' in getimagesize() function.
      */
     $thumb = str_replace('%26%23215%3B', 'x', rawurlencode($thumb));
     $thumb = rawurldecode($thumb);
     if (is_ssl()) {
         $thumb = preg_replace('#^http://#', 'https://', $thumb);
     }
     $info = pathinfo($thumb);
     $ext = $info['extension'];
     $name = wp_basename($thumb, ".{$ext}");
     $is_jpeg = false;
     $site_uri = apply_filters('et_resize_image_site_uri', site_url());
     $site_dir = apply_filters('et_resize_image_site_dir', ABSPATH);
     // If multisite, not the main site, WordPress version < 3.5 or ms-files rewriting is enabled ( not the fresh WordPress installation, updated from the 3.4 version )
     if (is_multisite() && !is_main_site() && (!function_exists('wp_get_mime_types') || get_site_option('ms_files_rewriting'))) {
         //Get main site url on multisite installation
         switch_to_blog(1);
         $site_uri = site_url();
         restore_current_blog();
     }
     /*
      * If we're dealing with an external image ( might be the result of Grab the first image function ),
      * return original image url
      */
     if (false === strpos($thumb, $site_uri)) {
         return $thumb;
     }
     if ('jpeg' == $ext) {
         $ext = 'jpg';
         $name = preg_replace('#.jpeg$#', '', $name);
         $is_jpeg = true;
     }
     $suffix = "{$new_width}x{$new_height}";
     $destination_dir = '' != get_option('et_images_temp_folder') ? preg_replace('#\\/\\/#', '/', get_option('et_images_temp_folder')) : null;
     $matches = apply_filters('et_resize_image_site_dir', array(), $site_dir);
     if (!empty($matches)) {
         preg_match('#' . $matches[1] . '$#', $site_uri, $site_uri_matches);
         if (!empty($site_uri_matches)) {
             $site_uri = str_replace($matches[1], '', $site_uri);
             $site_uri = preg_replace('#/$#', '', $site_uri);
             $site_dir = str_replace($matches[1], '', $site_dir);
             $site_dir = preg_replace('#\\\\/$#', '', $site_dir);
         }
     }
     #get local name for use in file_exists() and get_imagesize() functions
     $localfile = str_replace(apply_filters('et_resize_image_localfile', $site_uri, $site_dir, et_multisite_thumbnail($thumb)), $site_dir, et_multisite_thumbnail($thumb));
     $add_to_suffix = '';
     if (file_exists($localfile)) {
         $add_to_suffix = filesize($localfile) . '_';
     }
     #prepend image filesize to be able to use images with the same filename
     $suffix = $add_to_suffix . $suffix;
     $destfilename_attributes = '-' . $suffix . '.' . strtolower($ext);
     $checkfilename = '' != $destination_dir && null !== $destination_dir ? path_join($destination_dir, $name) : path_join(dirname($localfile), $name);
     $checkfilename .= $destfilename_attributes;
     if ($is_jpeg) {
         $checkfilename = preg_replace('#.jpg$#', '.jpeg', $checkfilename);
     }
     $uploads_dir = wp_upload_dir();
     $uploads_dir['basedir'] = preg_replace('#\\/\\/#', '/', $uploads_dir['basedir']);
     if (null !== $destination_dir && '' != $destination_dir && apply_filters('et_enable_uploads_detection', true)) {
         $site_dir = trailingslashit(preg_replace('#\\/\\/#', '/', $uploads_dir['basedir']));
         $site_uri = trailingslashit($uploads_dir['baseurl']);
     }
     #check if we have an image with specified width and height
     if (file_exists($checkfilename)) {
         return str_replace($site_dir, trailingslashit($site_uri), $checkfilename);
     }
     $size = @getimagesize($localfile);
     if (!$size) {
         return new WP_Error('invalid_image_path', __('Image doesn\'t exist'), $thumb);
     }
     list($orig_width, $orig_height, $orig_type) = $size;
     #check if we're resizing the image to smaller dimensions
     if ($orig_width > $new_width || $orig_height > $new_height) {
         if ($orig_width < $new_width || $orig_height < $new_height) {
             #don't resize image if new dimensions > than its original ones
             if ($orig_width < $new_width) {
                 $new_width = $orig_width;
             }
             if ($orig_height < $new_height) {
                 $new_height = $orig_height;
             }
             #regenerate suffix and appended attributes in case we changed new width or new height dimensions
             $suffix = "{$add_to_suffix}{$new_width}x{$new_height}";
             $destfilename_attributes = '-' . $suffix . '.' . $ext;
             $checkfilename = '' != $destination_dir && null !== $destination_dir ? path_join($destination_dir, $name) : path_join(dirname($localfile), $name);
             $checkfilename .= $destfilename_attributes;
             #check if we have an image with new calculated width and height parameters
             if (file_exists($checkfilename)) {
                 return str_replace($site_dir, trailingslashit($site_uri), $checkfilename);
             }
         }
         #we didn't find the image in cache, resizing is done here
         if (!function_exists('wp_get_image_editor')) {
             // compatibility with versions of WordPress prior to 3.5.
             $result = image_resize($localfile, $new_width, $new_height, $crop, $suffix, $destination_dir);
         } else {
             $et_image_editor = wp_get_image_editor($localfile);
             if (!is_wp_error($et_image_editor)) {
                 $et_image_editor->resize($new_width, $new_height, $crop);
                 // generate correct file name/path
                 $et_new_image_name = $et_image_editor->generate_filename($suffix, $destination_dir);
                 do_action('et_resize_image_before_save', $et_image_editor, $et_new_image_name);
                 $et_image_editor->save($et_new_image_name);
                 // assign new image path
                 $result = $et_new_image_name;
             } else {
                 // assign a WP_ERROR ( WP_Image_Editor instance wasn't created properly )
                 $result = $et_image_editor;
             }
         }
         if (!is_wp_error($result)) {
             // transform local image path into URI
             if ($is_jpeg) {
                 $thumb = preg_replace('#.jpeg$#', '.jpg', $thumb);
             }
             $site_dir = str_replace('\\', '/', $site_dir);
             $result = str_replace('\\', '/', $result);
             $result = str_replace('//', '/', $result);
             $result = str_replace($site_dir, trailingslashit($site_uri), $result);
         }
         #returns resized image path or WP_Error ( if something went wrong during resizing )
         return $result;
     }
     #returns unmodified image, for example in case if the user is trying to resize 800x600px to 1920x1080px image
     return $thumb;
 }
Example #29
0
function file_processValue($Value, $Type, $Field, $Config, $EID)
{
    if (!empty($Value)) {
        //dump($Value);
        //dump($Type);
        //dump($Field);
        //dump($Config);
        //die;
        switch ($Type) {
            case 'image':
                $Value = strtok($Value, '?');
                $imageWidth = $Config['_ImageSizeX'][$Field] == 'auto' ? '100' : $Config['_ImageSizeX'][$Field];
                $imageHeight = $Config['_ImageSizeY'][$Field] == 'auto' ? '100' : $Config['_ImageSizeY'][$Field];
                $iconWidth = $Config['_IconSizeX'][$Field] == 'auto' ? '100' : $Config['_IconSizeX'][$Field];
                $iconHeight = $Config['_IconSizeY'][$Field] == 'auto' ? '100' : $Config['_IconSizeY'][$Field];
                $uploadVars = wp_upload_dir();
                $SourceFile = str_replace($uploadVars['baseurl'], $uploadVars['basedir'], $Value);
                if (!file_exists($SourceFile)) {
                    return 'Image does not exists.';
                }
                $dim = getimagesize($SourceFile);
                $newDim = image_resize_dimensions($dim[0], $dim[1], $iconWidth, $iconHeight, true);
                if (!empty($newDim)) {
                    $Sourcepath = pathinfo($SourceFile);
                    $URLpath = pathinfo($Value);
                    $iconURL = $URLpath['dirname'] . '/' . $URLpath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $URLpath['extension'];
                    if (!file_exists($Sourcepath['dirname'] . '/' . $Sourcepath['filename'] . '-' . $newDim[4] . 'x' . $newDim[5] . '.' . $Sourcepath['extension'])) {
                        $image = image_resize($SourceFile, $imageWidth, $imageHeight, true);
                        $icon = image_resize($SourceFile, $iconWidth, $iconHeight, true);
                    }
                } else {
                    $iconURL = $Value;
                    $iconWidth = $dim[0];
                    $iconHeight = $dim[1];
                }
                $ClassName = '';
                if (!empty($Config['_ImageClassName'][$Field])) {
                    $ClassName = 'class="' . $Config['_ImageClassName'][$Field] . '" ';
                }
                if (!empty($Config['_IconURLOnly'][$Field])) {
                    return $iconURL;
                }
                return '<img src="' . $iconURL . '" ' . $ClassName . image_hwstring($iconWidth, $iconHeight) . '>';
                break;
            case 'mp3':
                $File = explode('?', $Value);
                $UniID = uniqid($EID . '_');
                //$ReturnData = '<span id="'.$UniID.'">'.$File[1].'</span>';
                $ReturnData = '<audio id="' . $UniID . '" src="' . $File[0] . '">unavailable</audio>';
                $_SESSION['dataform']['OutScripts'] .= "\n\t\t\t\t\tAudioPlayer.embed(\"" . $UniID . "\", {\n\t\t\t\t\t";
                if (!empty($Config['_PlayerCFG']['Autoplay'][$Field])) {
                    $_SESSION['dataform']['OutScripts'] .= " autostart: 'yes', ";
                }
                if (!empty($Config['_PlayerCFG']['Animation'][$Field])) {
                    $_SESSION['dataform']['OutScripts'] .= " animation: 'yes', ";
                }
                $_SESSION['dataform']['OutScripts'] .= "\n                                                transparentpagebg: 'yes',\n\t\t\t\t\t\tsoundFile: \"" . $File[0] . "\",\n\t\t\t\t\t\ttitles: \"" . $File[1] . "\"\n\t\t\t\t\t});\n\n\t\t\t\t";
                $_SESSION['dataform']['OutScripts'] .= "\n                                jQuery(document).ready(function(\$) {\n                                    AudioPlayer.setup(\"" . WP_PLUGIN_URL . "/db-toolkit/data_form/fieldtypes/file/player.swf\", {\n                                        width: '100%',\n                                        initialvolume: 100,\n                                        transparentpagebg: \"yes\",\n                                        left: \"000000\",\n                                        lefticon: \"FFFFFF\"\n                                    });\n                                 });";
                return $ReturnData;
                break;
            case 'file':
            case 'multi':
                if (empty($Config['_fileReturnValue'][$Field])) {
                    $Config['_fileReturnValue'][$Field] = 'iconlink';
                }
                $pathInfo = pathinfo($Value);
                $s3Enabled = false;
                $prime = $Field;
                if (!empty($Config['_CloneField'][$Field]['Master'])) {
                    $prime = $Config['_CloneField'][$Field]['Master'];
                }
                if (!empty($Config['_enableS3'][$prime]) && !empty($Config['_AWSAccessKey'][$prime]) && !empty($Config['_AWSSecretKey'][$prime])) {
                    include_once DB_TOOLKIT . 'data_form/fieldtypes/file/s3.php';
                    $s3 = new S3($Config['_AWSAccessKey'][$prime], $Config['_AWSSecretKey'][$prime]);
                    $s3Enabled = true;
                }
                switch ($Config['_fileReturnValue'][$Field]) {
                    case 'iconlink':
                        if (empty($Value)) {
                            return 'no file uploaded';
                        }
                        if (!empty($Config['_enableS3'][$prime]) && !empty($Config['_AWSAccessKey'][$prime]) && !empty($Config['_AWSSecretKey'][$prime])) {
                            $File = 'http://' . $Config['_AWSBucket'][$prime] . '.s3.amazonaws.com/' . $Value;
                        } else {
                            $File = $Value;
                        }
                        $Dets = pathinfo($File);
                        $ext = strtolower($Dets['extension']);
                        if (file_exists(WP_PLUGIN_DIR . '/db-toolkit/data_form/fieldtypes/file/icons/' . $ext . '.gif')) {
                            $Icon = '<img src="' . WP_PLUGIN_URL . '/db-toolkit/data_form/fieldtypes/file/icons/' . $ext . '.gif" align="absmiddle" />&nbsp;';
                        } else {
                            $Icon = '<img src="' . WP_PLUGIN_URL . '/db-toolkit/data_form/fieldtypes/file/icons/file.gif" align="absmiddle" />&nbsp;';
                        }
                        return '<a href="' . $File . '">' . $Icon . ' ' . basename($File) . '</a>';
                        break;
                    case 'filesize':
                        if (!empty($s3Enabled)) {
                            $object = $s3->getObjectInfo($Config['_AWSBucket'][$prime], $Value);
                            return file_return_bytes($object['size']);
                        } else {
                            $uploadDir = wp_upload_dir();
                            $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value);
                            return file_return_bytes(filesize($file));
                        }
                        break;
                    case 'filesizeraw':
                        if (!empty($s3Enabled)) {
                            $object = $s3->getObjectInfo($Config['_AWSBucket'][$prime], $Value);
                            return $object['size'];
                        } else {
                            $uploadDir = wp_upload_dir();
                            $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value);
                            return filesize($file);
                        }
                        break;
                    case 'filename':
                        if (!empty($s3Enabled)) {
                            return basename($Value);
                        } else {
                            return $pathInfo['basename'];
                        }
                        break;
                    case 'filepath':
                        return $Value;
                        break;
                    case 'ext':
                        return $pathInfo['extension'];
                        break;
                    case 'mimetype':
                        $uploadDir = wp_upload_dir();
                        $file = str_replace($uploadDir['baseurl'], $uploadDir['basedir'], $Value);
                        $type = wp_check_filetype($file);
                        return $type['type'];
                        break;
                }
                break;
        }
        return;
    }
}
Example #30
0
             $valid = false;
             $error = gettext('Attachment mimetype is not allowed');
         } else {
             if ($max_user_attachment_space > 0 && $free_upload_space > -1 && $free_upload_space < $file_size) {
                 @unlink($file_path);
                 @unlink($temp_file);
                 $valid = false;
                 $error = gettext('You do not have enough free attachment space');
             } else {
                 $image_width = null;
                 $image_height = null;
                 $thumbnail = false;
                 if (($image_info = @getimagesize($file_path)) !== false) {
                     $image_width = $image_info[0];
                     $image_height = $image_info[1];
                     $thumbnail = image_resize($file_path, $file_path . '.thumb');
                 }
                 if (($attachment_aid = attachments_add($_SESSION['UID'], $file_name, $file_hash, $file_type, $file_size, $image_width, $image_height, $thumbnail)) !== false) {
                     $attachment_details = attachments_get_by_aid($attachment_aid, $_SESSION['UID']);
                 } else {
                     @unlink($file_path);
                     @unlink($file_path . '.thumb');
                     @unlink($temp_file);
                     $valid = false;
                     $error = gettext('Attachment failed to upload. Please try again.');
                 }
             }
         }
     }
     $content = json_encode(array('error' => $error, 'attachment' => $attachment_details, 'preventRetry' => true, 'success' => $valid));
 }