コード例 #1
1
ファイル: img.php プロジェクト: rgrasiano/viabasica-hering
 /**
  * Creates new image size.
  *
  * @uses get_attached_file()
  * @uses image_make_intermediate_size()
  * @uses wp_update_attachment_metadata()
  * @uses get_post_meta()
  * @uses update_post_meta()
  *
  * @param $attachment_id
  * @param $width
  * @param $height
  * @param $meta
  * @param $original_src
  *
  * @return array
  */
 function themify_make_image_size($attachment_id, $width, $height, $meta, $original_src)
 {
     setlocale(LC_CTYPE, get_locale() . '.UTF-8');
     $attached_file = get_attached_file($attachment_id);
     if (apply_filters('themify_image_script_use_large_size', true) && isset($meta['sizes']['large']['file'])) {
         $attached_file = str_replace($meta['file'], trailingslashit(dirname($meta['file'])) . $meta['sizes']['large']['file'], $attached_file);
     }
     $resized = image_make_intermediate_size($attached_file, $width, $height, true);
     if ($resized && !is_wp_error($resized)) {
         // Save the new size in meta data
         $key = sprintf('resized-%dx%d', $width, $height);
         $meta['sizes'][$key] = $resized;
         $src = str_replace(basename($original_src), $resized['file'], $original_src);
         wp_update_attachment_metadata($attachment_id, $meta);
         // Save size in backup sizes so it's deleted when original attachment is deleted.
         $backup_sizes = get_post_meta($attachment_id, '_wp_attachment_backup_sizes', true);
         if (!is_array($backup_sizes)) {
             $backup_sizes = array();
         }
         $backup_sizes[$key] = $resized;
         update_post_meta($attachment_id, '_wp_attachment_backup_sizes', $backup_sizes);
         // Return resized image url, width and height.
         return array('url' => esc_url($src), 'width' => $width, 'height' => $height);
     }
     // Return resized image url, width and height.
     return array('url' => $original_src, 'width' => $width, 'height' => $height);
 }
コード例 #2
0
 public function regenerateThumbnails($image_id)
 {
     require_once 'wp-admin/includes/image.php';
     $fullsizepath = get_attached_file($image_id);
     $metadata = wp_generate_attachment_metadata($image_id, $fullsizepath);
     wp_update_attachment_metadata($image_id, $metadata);
 }
 /**
  * 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 = @new_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 '';
 }
コード例 #4
0
function cycloneslider_thumb($original_attachment_id, $width, $height, $refresh = false, $slide_meta = array())
{
    $dir = wp_upload_dir();
    // Get full path to the slide image
    $image_path = get_attached_file($original_attachment_id);
    $image_path = apply_filters('cycloneslider_image_path', $image_path, $slide_meta);
    if (empty($image_path)) {
        return false;
    }
    // Full url to the slide image
    $image_url = wp_get_attachment_url($original_attachment_id);
    $image_url = apply_filters('cycloneslider_image_url', $image_url, $slide_meta);
    if (empty($image_url)) {
        return false;
    }
    $info = pathinfo($image_path);
    $dirname = isset($info['dirname']) ? $info['dirname'] : '';
    // Path to directory
    $ext = isset($info['extension']) ? $info['extension'] : '';
    // File extension Eg. "jpg"
    $thumb = wp_basename($image_path, ".{$ext}") . "-{$width}x{$height}.{$ext}";
    // Thumbname. Eg. [imagename]-[width]x[height].hpg
    // Check if thumb already exists. If it is, return its url, unless refresh is true
    if (file_exists($dirname . '/' . $thumb) and !$refresh) {
        return dirname($image_url) . '/' . $thumb;
        //We used dirname() since we need the URL format not the path
    }
    $resizeObj = new Image_Resizer($image_path);
    $resizeObj->resizeImage($width, $height);
    $resizeObj->saveImage($dirname . '/' . $thumb, 80);
    return dirname($image_url) . '/' . $thumb;
}
コード例 #5
0
/**
 * Customize the <title> tag content for the Tag Gallery and Single Image pages
 *
 * @param string The default page title
 * @param string $sep How to separate the various items within the page title
 * @param string $seplocation Optional. Direction to display title, 'right'.
 *
 * @return string updated title value
 */
function mla_wp_title_filter($title, $sep, $seplocation)
{
    $sep = " {$sep} ";
    if (is_page()) {
        $page = single_post_title('', false);
        /*
         * Match specific page titles and replace the default, page title,
         * with more interesting term or file information.
         */
        if ('Tag Gallery' == $page) {
            $taxonomy = isset($_REQUEST['my_taxonomy']) ? $_REQUEST['my_taxonomy'] : NULL;
            $slug = isset($_REQUEST['my_term']) ? $_REQUEST['my_term'] : NULL;
            if ($taxonomy && $slug) {
                $term = get_term_by('slug', $slug, $taxonomy);
                return $term->name . $sep;
            }
        } elseif ('Single Image' == $page) {
            $post_id = isset($_REQUEST['post_id']) ? $_REQUEST['post_id'] : 0;
            if ($post_id) {
                $file = get_attached_file($post_id);
                $pathinfo = pathinfo($file);
                return $pathinfo['basename'] . $sep;
            }
        }
    }
    // is_page
    return $title;
}
コード例 #6
0
ファイル: opml-importer.php プロジェクト: kivivuori/jotain
 /**
  * Shows The Import Page and import form for step 1.
  * Calls the parsing and importing function for step 2.
  * 
  * @since 3.3
  * @return void
  */
 public function opml_import()
 {
     // Show the Icon and Title
     echo '<div class="wrap">';
     screen_icon();
     echo '<h2>Import OPML</h2>';
     // Get the current step from URL query string
     $step = empty($_GET['step']) ? 0 : (int) $_GET['step'];
     // Check the current step
     switch ($step) {
         default:
         case 0:
             // Show the Import Message and the import upload form
             echo '<p>' . __('Howdy! Import your feeds here from an OPML (.xml) export file.', 'wprss') . '</p>';
             echo '<p>' . __("Click the button below, choose your file, and click 'Upload'.", 'wprss') . '</p>';
             echo '<p>' . __('We will take care of the rest.', 'wprss') . '</p>';
             // Show an import upload form that submits to the same page, with GET parameter step=1
             wp_import_upload_form('admin.php?import=wprss_opml_importer&amp;step=1');
             break;
         case 1:
             // Check referer
             check_admin_referer('import-upload');
             // If the handle_upload function returns true
             if ($this->handle_upload()) {
                 // Get the uploaded file
                 $file = get_attached_file($this->id);
                 set_time_limit(0);
                 // Parse the File and Import the feeds
                 $this->parse_and_import($file);
             }
             break;
     }
     echo '</div>';
 }
コード例 #7
0
ファイル: image.php プロジェクト: laiello/cartonbank
/**
 * Crop an Image to a given size.
 *
 * @since 2.1.0
 *
 * @param string|int $src_file The source file or Attachment ID.
 * @param int $src_x The start x position to crop from.
 * @param int $src_y The start y position to crop from.
 * @param int $src_w The width to crop.
 * @param int $src_h The height to crop.
 * @param int $dst_w The destination width.
 * @param int $dst_h The destination height.
 * @param int $src_abs Optional. If the source crop points are absolute.
 * @param string $dst_file Optional. The destination file to write to.
 * @return string|WP_Error|false New filepath on success, WP_Error or false on failure.
 */
function wp_crop_image($src_file, $src_x, $src_y, $src_w, $src_h, $dst_w, $dst_h, $src_abs = false, $dst_file = false)
{
    if (is_numeric($src_file)) {
        // Handle int as attachment ID
        $src_file = get_attached_file($src_file);
    }
    $src = wp_load_image($src_file);
    if (!is_resource($src)) {
        return new WP_Error('error_loading_image', $src, $src_file);
    }
    $dst = wp_imagecreatetruecolor($dst_w, $dst_h);
    if ($src_abs) {
        $src_w -= $src_x;
        $src_h -= $src_y;
    }
    if (function_exists('imageantialias')) {
        imageantialias($dst, true);
    }
    imagecopyresampled($dst, $src, 0, 0, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);
    imagedestroy($src);
    // Free up memory
    if (!$dst_file) {
        $dst_file = str_replace(basename($src_file), 'cropped-' . basename($src_file), $src_file);
    }
    $dst_file = preg_replace('/\\.[^\\.]+$/', '.jpg', $dst_file);
    if (imagejpeg($dst, $dst_file, apply_filters('jpeg_quality', 90, 'wp_crop_image'))) {
        return $dst_file;
    } else {
        return false;
    }
}
コード例 #8
0
 /**
  * Change the slide image.
  *
  * This creates a copy of the selected (new) image and assigns the copy to our existing media file/slide.
  */
 public function ajax_change_slide_image()
 {
     if (!wp_verify_nonce($_REQUEST['_wpnonce'], 'metaslider_changeslide')) {
         wp_die(json_encode(array('status' => 'fail', 'msg' => __("Security check failed. Refresh page and try again.", "ml-slider"))));
     }
     $slide_from = absint($_POST['slide_from']);
     $slide_to = absint($_POST['slide_to']);
     // find the paths for the image we want to change to
     // Absolute path
     $abs_path = get_attached_file($slide_to);
     $abs_path_parts = pathinfo($abs_path);
     $abs_file_directory = $abs_path_parts['dirname'];
     // Relative path
     $rel_path = get_post_meta($slide_to, '_wp_attached_file', true);
     $rel_path_parts = pathinfo($rel_path);
     $rel_file_directory = $rel_path_parts['dirname'];
     // old file name
     $file_name = $abs_path_parts['basename'];
     // new file name
     $dest_file_name = wp_unique_filename($abs_file_directory, $file_name);
     // generate absolute and relative paths for the new file name
     $dest_abs_path = trailingslashit($abs_file_directory) . $dest_file_name;
     $dest_rel_path = trailingslashit($rel_file_directory) . $dest_file_name;
     // make a copy of the image
     if (@copy($abs_path, $dest_abs_path)) {
         // update the path on our slide
         update_post_meta($slide_from, '_wp_attached_file', $dest_rel_path);
         wp_update_attachment_metadata($slide_from, wp_generate_attachment_metadata($slide_from, $dest_abs_path));
         update_attached_file($slide_from, $dest_rel_path);
         wp_die(json_encode(array('status' => 'success')));
     }
     wp_die(json_encode(array('status' => 'fail', 'msg' => __("File copy failed. Please check upload directory permissions.", "ml-slider"))));
 }
コード例 #9
0
 /**
  * @ticket 32171
  */
 public function testImageEditOverwriteConstant()
 {
     define('IMAGE_EDIT_OVERWRITE', true);
     include_once ABSPATH . 'wp-admin/includes/image-edit.php';
     $filename = DIR_TESTDATA . '/images/canola.jpg';
     $contents = file_get_contents($filename);
     $upload = wp_upload_bits(basename($filename), null, $contents);
     $id = $this->_make_attachment($upload);
     $_REQUEST['action'] = 'image-editor';
     $_REQUEST['context'] = 'edit-attachment';
     $_REQUEST['postid'] = $id;
     $_REQUEST['target'] = 'all';
     $_REQUEST['do'] = 'save';
     $_REQUEST['history'] = '[{"c":{"x":5,"y":8,"w":289,"h":322}}]';
     $ret = wp_save_image($id);
     $media_meta = wp_get_attachment_metadata($id);
     $sizes1 = $media_meta['sizes'];
     $_REQUEST['history'] = '[{"c":{"x":5,"y":8,"w":189,"h":322}}]';
     $ret = wp_save_image($id);
     $media_meta = wp_get_attachment_metadata($id);
     $sizes2 = $media_meta['sizes'];
     $file_path = dirname(get_attached_file($id));
     foreach ($sizes1 as $key => $size) {
         if ($sizes2[$key]['file'] !== $size['file']) {
             $files_that_shouldnt_exist[] = $file_path . '/' . $size['file'];
         }
     }
     foreach ($files_that_shouldnt_exist as $file) {
         $this->assertFileNotExists($file, 'IMAGE_EDIT_OVERWRITE is leaving garbage image files behind.');
     }
 }
コード例 #10
0
ファイル: intheme-utils.php プロジェクト: hungrig4leben/my-gp
 function it_regenerate_wp_images()
 {
     return false;
     set_time_limit(0);
     echo "<pre>";
     echo "Regenerating thumbnails...\n";
     $args = array('post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null);
     $attachments = get_posts($args);
     if ($attachments) {
         echo count($attachments) . " images were found.\n";
         foreach ($attachments as $attachment) {
             $full_size_path = get_attached_file($attachment->ID);
             if (false === $full_size_path || !file_exists($full_size_path)) {
                 echo "Image ID " . $attachment->ID . " was not found.\n";
                 continue;
             }
             $meta_data = wp_generate_attachment_metadata($attachment->ID, $full_size_path);
             if (is_wp_error($meta_data)) {
                 echo "Image ID " . $attachment->ID . " raised an error: " . $mata_data->get_error_message() . "\n";
                 continue;
             }
             if (empty($meta_data)) {
                 echo "Image ID " . $attachment->ID . " failed with unknown reason\n";
                 continue;
             }
             wp_update_attachment_metadata($attachment->ID, $meta_data);
         }
         echo "Done.";
     }
     echo "</pre>";
 }
コード例 #11
0
 /** generate new image sizes for old uploads
  * 
  * @param mixed $out
  * @param int $id
  * @param string|array $size
  * @return mixed
  */
 function circleflip_make_missing_intermediate_size($out, $id, $size)
 {
     $skip_sizes = array('full', 'large', 'medium', 'thumbnail', 'thumb');
     if (is_array($size) || in_array($size, $skip_sizes)) {
         return $out;
     }
     // the size exists and the attachment doesn't have a pre-generated file of that size
     // or the intermediate size defintion changed ( during development )
     if (circleflip_intermediate_size_exists($size) && (!circleflip_image_has_intermediate_size($id, $size) || circleflip_has_intermediate_size_changed($id, $size))) {
         // get info registerd by add_image_size
         $size_info = circleflip_get_intermediate_size_info($size);
         // get path to the original file
         $file_path = get_attached_file($id);
         // resize the image
         $resized_file = image_make_intermediate_size($file_path, $size_info['width'], $size_info['height'], $size_info['crop']);
         if ($resized_file) {
             // we have a resized image, get the attachment metadata and add the new size to it
             $metadata = wp_get_attachment_metadata($id);
             $metadata['sizes'][$size] = $resized_file;
             if (wp_update_attachment_metadata($id, $metadata)) {
                 // update succeded, call image_downsize again , DRY
                 return image_downsize($id, $size);
             }
         } else {
             // failed to generate the resized image
             // call image_downsize with `full` to prevent infinit loop
             return image_downsize($id, 'full');
         }
     }
     // pre-existing intermediate size
     return $out;
 }
コード例 #12
0
ファイル: brad_iconfont.php プロジェクト: jmead/trucell-cms
 function add_zipped_font()
 {
     //check if referer is ok
     if (function_exists('check_ajax_referer')) {
         if (check_ajax_referer('redux_file_upload_nonce', 'nonce', false) == false) {
             exit("Error : Your page has been expired");
         }
     }
     //check if capability is ok
     $cap = apply_filters('brad_file_upload_capability', 'update_plugins');
     if (!current_user_can($cap)) {
         exit("Error : Using this feature is reserved for Super Admins. You unfortunately don't have the necessary permissions.");
     }
     //get the file path of the zip file
     $attachment = $_POST['attachment'];
     $path = realpath(get_attached_file($attachment));
     $unzipped = $this->zip_flatten($path, array('\\.eot', '\\.svg', '\\.ttf', '\\.woff', '\\.css', '.json'));
     // if we were able to unzip the file and save it to our temp folder extract the svg file
     if ($unzipped) {
         $this->create_config();
     }
     //if we got no name for the font dont add it and delete the temp folder
     if ($this->font_name == 'empty') {
         $this->delete_folder($this->paths['tempdir']);
         exit('Error : Was not able to retrieve the Font name from your Uploaded Folder');
     }
     $response = array('name' => $this->font_name, 'prefix' => $this->font_prefix, 'css_url' => trailingslashit(trailingslashit($this->paths['fonturl']) . $this->font_name) . $this->css_file, 'css_file' => trailingslashit(trailingslashit($this->paths['fontdir']) . $this->font_name) . $this->css_file);
     // response output
     echo json_encode($response);
     exit;
 }
コード例 #13
0
 public function wp_generate_attachment_metadata($metadata, $attachment_id)
 {
     $attachment = get_attached_file($attachment_id);
     if (!preg_match('!^image/!', get_post_mime_type($attachment_id)) || !file_is_displayable_image($attachment)) {
         return $metadata;
     }
     $image_sizes = Helper::get_image_sizes();
     foreach ($image_sizes as $size_name => $size_attributes) {
         if (!empty($metadata['sizes'][$size_name])) {
             continue;
         }
         $image = wp_get_image_editor($attachment);
         if (is_wp_error($image)) {
             continue;
         }
         $resized = $image->resize($size_attributes['width'], $size_attributes['height'], $size_attributes['crop']);
         $image_size = $image->get_size();
         if (!is_wp_error($resized) && !empty($image_size)) {
             $filename = wp_basename($image->generate_filename());
             $extension = pathinfo($filename, PATHINFO_EXTENSION);
             $mime_type = $this->get_mime_type($extension);
             $metadata['sizes'][$size_name] = array('file' => $filename, 'width' => $image_size['width'], 'height' => $image_size['height'], 'mime-type' => $mime_type);
         }
     }
     return $metadata;
 }
 /**
  * Registered callback function for the Lightspeed Importer
  *
  * Manages the separate stages of the import process
  */
 function dispatch()
 {
     $this->header();
     // This all from the WordPress Importer plugin, handles most cases
     $step = empty($_GET['step']) ? 0 : (int) $_GET['step'];
     switch ($step) {
         case 0:
             $this->greet();
             break;
         case 1:
             check_admin_referer('import-lightspeed-upload');
             $this->language = isset($_POST['lightspeed_language']) && $_POST['lightspeed_language'] !== '' ? $_POST['lightspeed_language'] : $this->defaults['lightspeed_language'];
             $result = $this->import();
             if (is_wp_error($result)) {
                 echo $result->get_error_message();
             }
             break;
         case 2:
             check_admin_referer('import-lightspeed');
             $this->fetch_attachments = !empty($_POST['fetch_attachments']) && $this->allow_fetch_attachments();
             $this->id = (int) $_POST['import_id'];
             // Provides the actual file upload form
             $file = get_attached_file($this->id);
             set_time_limit(0);
             $this->import($file);
             break;
     }
     $this->footer();
 }
コード例 #15
0
/**
 * The default mimetype match is for "application/*". For other types, you
 * will need to specifically override that attribute.
 * Examples:
 *
 * Just .XLS files:
 *   [documents ext="xls"]
 *
 * All .DOC, .DOCX, or .PDF files:
 *   [documents ext="doc,docx,pdf"]
 * 
 * Only 'video' types with a .MOV extension:
 *   [documents mimetype="video" ext="mov"]
 * 
 * Just application/pdf mimetypes:
 *   [documents mimetype="application/pdf"]
 */
function dc_document_shortcode($atts)
{
    extract(shortcode_atts(array('mimetype' => 'application', 'ext' => null), $atts));
    $mime = "&post_mime_type={$mimetype}";
    $kids =& get_children('post_type=attachment&post_parent=' . get_the_id() . $mime);
    if (empty($kids)) {
        return '';
    }
    $exts = array();
    if ($ext) {
        $exts = explode(',', $ext);
        $exts = array_map('trim', $exts);
        $exts = array_map('strtolower', $exts);
    }
    $documents = '';
    foreach ($kids as $id => $doc) {
        $url = wp_get_attachment_url($id);
        $file = get_attached_file($id);
        $filetype = wp_check_filetype($file);
        $file_ext = strtolower($filetype['ext']);
        if (count($exts) && !in_array($file_ext, $exts)) {
            // Not in list of requested extensions. Skip it!
            continue;
        }
        $name = $doc->post_title;
        $mime = sanitize_title_with_dashes($file_ext);
        $documents .= "<li class='{$mime}'><a href='{$url}'>{$name}</a></li>\n";
    }
    if (!empty($documents)) {
        // Wrap it up:
        $documents = "<ul class='dc_documents'>\n" . $documents;
        $documents .= "</ul>\n";
    }
    return $documents;
}
コード例 #16
0
/**
 * Functions for handling WordPress import to make it compatable with WooCommerce
 *
 * WordPress import should work - however, it fails to import custom product attribute taxonomies.
 * This code grabs the file before it is imported and ensures the taxonomies are created.
 *
 * @author 		WooThemes
 * @category 	Admin
 * @package 	WooCommerce
 */
function woocommerce_import_start()
{
    global $wpdb;
    $id = (int) $_POST['import_id'];
    $file = get_attached_file($id);
    $parser = new WXR_Parser();
    $import_data = $parser->parse($file);
    if (isset($import_data['posts'])) {
        $posts = $import_data['posts'];
        if ($posts && sizeof($posts) > 0) {
            foreach ($posts as $post) {
                if ($post['post_type'] == 'product') {
                    if ($post['terms'] && sizeof($post['terms']) > 0) {
                        foreach ($post['terms'] as $term) {
                            $domain = $term['domain'];
                            if (strstr($domain, 'pa_')) {
                                // Make sure it exists!
                                if (!taxonomy_exists($domain)) {
                                    $nicename = strtolower(sanitize_title(str_replace('pa_', '', $domain)));
                                    $exists_in_db = $wpdb->get_var("SELECT attribute_id FROM " . $wpdb->prefix . "woocommerce_attribute_taxonomies WHERE attribute_name = '" . $nicename . "';");
                                    if (!$exists_in_db) {
                                        // Create the taxonomy
                                        $wpdb->insert($wpdb->prefix . "woocommerce_attribute_taxonomies", array('attribute_name' => $nicename, 'attribute_type' => 'select'), array('%s', '%s'));
                                    }
                                    // Register the taxonomy now so that the import works!
                                    register_taxonomy($domain, array('product'), array('hierarchical' => true, 'labels' => array('name' => $nicename, 'singular_name' => $nicename, 'search_items' => __('Search', 'woothemes') . ' ' . $nicename, 'all_items' => __('All', 'woothemes') . ' ' . $nicename, 'parent_item' => __('Parent', 'woothemes') . ' ' . $nicename, 'parent_item_colon' => __('Parent', 'woothemes') . ' ' . $nicename . ':', 'edit_item' => __('Edit', 'woothemes') . ' ' . $nicename, 'update_item' => __('Update', 'woothemes') . ' ' . $nicename, 'add_new_item' => __('Add New', 'woothemes') . ' ' . $nicename, 'new_item_name' => __('New', 'woothemes') . ' ' . $nicename), 'show_ui' => false, 'query_var' => true, 'rewrite' => array('slug' => strtolower(sanitize_title($nicename)), 'with_front' => false, 'hierarchical' => true)));
                                }
                            }
                        }
                    }
                }
            }
        }
    }
}
コード例 #17
0
 /**
  * Run the converter now
  *
  * @since 1.0
  *
  * @param array $args can be extension
  * @param array $vars
  */
 function update_attachments($args = array(), $vars = array())
 {
     $images = Tiff_Converter::get_images();
     $mime_type = 'image/jpg';
     // Maybe $args[0] for changing it
     if ($images) {
         $succeed = $failed = 0;
         foreach ($images as $image) {
             $file = get_attached_file($image->ID);
             $result = Tiff_Converter_Handle::convert_image($file, $mime_type);
             if (!is_wp_error($result)) {
                 $update_args = array('ID' => $image->ID, 'post_mime_type' => $result['mime-type']);
                 $result2 = wp_update_post($update_args, true);
                 if ($result2 && !is_wp_error($result2)) {
                     unlink($file);
                     update_attached_file($image->ID, $result['path']);
                     wp_update_attachment_metadata($image->ID, wp_generate_attachment_metadata($image->ID, $result['path']));
                     $succeed++;
                 } else {
                     unlink($result['path']);
                     $failed++;
                 }
             } else {
                 $failed++;
             }
         }
         WP_CLI::success(sprintf('%d images are converted and %s failed', $succeed, $failed));
     } else {
         WP_CLI::success('No images to convert');
     }
 }
 public function regenerateMetadata($id)
 {
     // Get attachment path
     $path = get_attached_file($id);
     $skip = false;
     $error = null;
     if ($path === false || !file_exists($path)) {
         $error = 'Error: file does not exists for ID ' . $id;
         $skip = true;
     }
     // Generate new metadata
     $metadata = \wp_generate_attachment_metadata($id, $path);
     if (!$skip && empty($metadata)) {
         $error = 'Error: metadata error for ID ' . $id;
         $skip = true;
     }
     if (!$skip && is_wp_error($metadata)) {
         $error = 'Error: metadata error for ID ' . $image->ID . ': "' . $metadata->get_error_message() . '"';
         $skip = true;
     }
     // Update metadata
     if (!$skip) {
         \wp_update_attachment_metadata($id, $metadata);
         if ($this->remove) {
             $this->removeOld($metadata);
         }
     }
     return $error;
 }
コード例 #19
0
ファイル: nev-admin.php プロジェクト: pmarki/next_events
function nev_admin_upload_file()
{
    if (!function_exists('wp_handle_upload')) {
        require_once ABSPATH . 'wp_admin/includes/file.php';
    }
    if (empty($_FILES['file_path'])) {
        return;
    }
    $uploadedFile = $_FILES['file_path'];
    $uploaded_overrides = array('test_form' => false);
    $moveFile = wp_handle_upload($uploadedFile, $uploaded_overrides);
    if (!empty($moveFile['error'])) {
        echo $moveFile['error'];
        return;
    }
    if ($moveFile) {
        $wp_filetype = $moveFile['type'];
        $filename = $moveFile['file'];
        $wp_upload_dir = wp_upload_dir();
        $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($filename), 'post_mime_type' => $wp_filetype, 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit');
        $attach_id = wp_insert_attachment($attachment, $filename);
        $file_path = get_attached_file($attach_id);
        update_option("nev-file_path", $file_path);
        echo "File uploaded to " . $file_path;
    } else {
        echo "Failed!";
    }
}
コード例 #20
0
ファイル: Public.php プロジェクト: helsingborg-stad/Municipio
 function municipio_get_logotype($type = 'standard', $tooltip = false, $logo_include = true, $tagline = false)
 {
     if ($type == '') {
         $type = 'standard';
     }
     $siteName = apply_filters('Municipio/logotype_text', get_bloginfo('name'));
     $logotype = array('standard' => get_field('logotype', 'option'), 'negative' => get_field('logotype_negative', 'option'));
     // Get the symbol to use (blog name or image)
     $symbol = '<span class="h1 no-margin no-padding">' . $siteName . '</span>';
     if (isset($logotype[$type]['url']) && $logo_include === false) {
         $symbol = sprintf('<img src="%s" alt="%s">', $logotype[$type]['url'], $siteName);
     }
     // Get the symbol to use (by file include)
     if (isset($logotype[$type]['id']) && $logo_include === true) {
         $symbol = \Municipio\Helper\Svg::extract(get_attached_file($logotype[$type]['id']));
     }
     $classes = apply_filters('Municipio/logotype_class', array('logotype'));
     $tooltip = apply_filters('Municipio/logotype_tooltip', $tooltip);
     $taglineHtml = '';
     if ($tagline === true) {
         $taglineText = get_bloginfo('description');
         if (get_field('header_tagline_type', 'option') == 'custom') {
             $taglineText = get_field('header_tagline_text', 'option');
         }
         $taglineHtml = '<span class="tagline">' . $taglineText . '</span>';
     }
     // Build the markup
     $markup = sprintf('<a href="%s" class="%s" %s>%s%s</a>', home_url(), implode(' ', $classes), $tooltip !== false && !empty($tooltip) ? 'data-tooltip="' . $tooltip . '"' : '', $symbol, $taglineHtml);
     return $markup;
 }
コード例 #21
0
 /**
  * Rebuild the attachment metadata for an attachment
  *
  * @param mixed $attachment
  *
  * @return bool
  */
 protected function upgrade_item($attachment)
 {
     $s3object = unserialize($attachment->s3object);
     if (false === $s3object) {
         AS3CF_Error::log('Failed to unserialize S3 meta for attachment ' . $attachment->ID . ': ' . $attachment->s3object);
         $this->error_count++;
         return false;
     }
     $file = get_attached_file($attachment->ID, true);
     if (!file_exists($file)) {
         // Copy back the file to the server if doesn't exist so we can successfully
         // regenerate the attachment metadata
         try {
             $args = array('Bucket' => $s3object['bucket'], 'Key' => $s3object['key'], 'SaveAs' => $file);
             $this->as3cf->get_s3client($s3object['region'], true)->getObject($args);
         } catch (Exception $e) {
             AS3CF_Error::log(sprintf(__('There was an error attempting to download the file %s from S3: %s', 'amazon-s3-and-cloudfront'), $s3object['key'], $e->getMessage()));
             return false;
         }
     }
     // Remove corrupted meta
     delete_post_meta($attachment->ID, '_wp_attachment_metadata');
     require_once ABSPATH . '/wp-admin/includes/image.php';
     // Generate new attachment meta
     wp_update_attachment_metadata($attachment->ID, wp_generate_attachment_metadata($attachment->ID, $file));
     return true;
 }
コード例 #22
0
 /**
  * From regenerate thumbnails plugin
  */
 public function regenerate_thumbnail()
 {
     @error_reporting(0);
     // Don't break the JSON result
     header('Content-type: application/json');
     $id = (int) $_REQUEST['id'];
     $image = get_post($id);
     if (!$image || 'attachment' != $image->post_type || 'image/' != substr($image->post_mime_type, 0, 6)) {
         die(json_encode(array('error' => sprintf(__('Failed resize: %s is an invalid image ID.', 'wc_csv_import'), esc_html($_REQUEST['id'])))));
     }
     if (!current_user_can('manage_woocommerce')) {
         $this->die_json_error_msg($image->ID, __("Your user account doesn't have permission to resize images", 'wc_csv_import'));
     }
     $fullsizepath = get_attached_file($image->ID);
     if (false === $fullsizepath || !file_exists($fullsizepath)) {
         $this->die_json_error_msg($image->ID, sprintf(__('The originally uploaded image file cannot be found at %s', 'wc_csv_import'), '<code>' . esc_html($fullsizepath) . '</code>'));
     }
     @set_time_limit(900);
     // 5 minutes per image should be PLENTY
     $metadata = wp_generate_attachment_metadata($image->ID, $fullsizepath);
     if (is_wp_error($metadata)) {
         $this->die_json_error_msg($image->ID, $metadata->get_error_message());
     }
     if (empty($metadata)) {
         $this->die_json_error_msg($image->ID, __('Unknown failure reason.', 'wc_csv_import'));
     }
     // If this fails, then it just means that nothing was changed (old value == new value)
     wp_update_attachment_metadata($image->ID, $metadata);
     die(json_encode(array('success' => sprintf(__('&quot;%1$s&quot; (ID %2$s) was successfully resized in %3$s seconds.', 'wc_csv_import'), esc_html(get_the_title($image->ID)), $image->ID, timer_stop()))));
 }
コード例 #23
0
ファイル: gallery.php プロジェクト: uweb/story-central
 function image_assets()
 {
     // TODO: check if ziparchive is installed cms/cmsdev
     $zip = new ZipArchive();
     $ids = explode(',', $_GET['ids']);
     $name = $_GET['name'] . '.zip';
     $path = get_temp_dir() . $name;
     if ($zip->open($path, ZIPARCHIVE::CREATE | ZIPARCHIVE::OVERWRITE) !== TRUE) {
         die(json_encode(array('error' => 'Could not retrieve files.')));
     }
     foreach ($ids as $id) {
         $image = get_attached_file($id);
         if (file_exists($image)) {
             $zip->addFile($image, basename($image));
         } else {
             // die("File $filepath doesnt exit");
         }
     }
     $zip->close();
     header('Content-Type: application/zip');
     header('Content-disposition: attachment; filename=' . $name);
     header('Content-Length: ' . filesize($path));
     //TODO: alternate method to make zip file work?
     ob_clean();
     flush();
     readfile($path);
     wp_die();
 }
コード例 #24
0
 function dispatch()
 {
     //holds all notices messages from xml import
     $notice_messages = '';
     $info = $this->bbt_install_attachments();
     if (empty($info['id'])) {
         return array('install' => 'no', 'message' => $info['message'], 'notices' => '');
     }
     $this->fetch_attachments = true;
     $this->id = !empty($info['id']) ? (int) $info['id'] : '';
     $file = get_attached_file($this->id);
     set_time_limit(0);
     //call import function
     //in $result can be an error so we will display it
     $result = $this->import($file);
     //if error display it
     if (is_wp_error($result)) {
         return array('install' => 'no', 'message' => $result->get_error_message(), 'notices' => '');
     } elseif (isset($result['notices'])) {
         $notice_messages = $result['notices'];
     }
     //echo footer in any case
     $this->footer();
     return array('install' => 'yes', 'message' => $this->finish_msg, 'notices' => $notice_messages);
 }
コード例 #25
0
ファイル: grayscale.php プロジェクト: jeffhertzler/grayscale
function grayscale_check_grayscale_image($metadata, $attachment_id)
{
    global $_wp_additional_image_sizes;
    $attachment = get_post($attachment_id);
    if (preg_match('!image!', get_post_mime_type($attachment))) {
        require_once 'class-grayscale-image-editor.php';
        foreach ($_wp_additional_image_sizes as $size => $size_data) {
            if (isset($size_data['grayscale']) && $size_data['grayscale']) {
                if (is_array($metadata['sizes']) && isset($metadata['sizes'][$size])) {
                    $file = pathinfo(get_attached_file($attachment_id));
                    $filename = $file['dirname'] . '/' . $metadata['sizes'][$size]['file'];
                    $metadata['sizes'][$size . '-gray'] = $metadata['sizes'][$size];
                } else {
                    // this size has no image attached, probably because the original is too small
                    // create the grayscale image from the original file
                    $file = wp_upload_dir();
                    $filename = $file['basedir'] . '/' . $metadata['file'];
                    $metadata['sizes'][$size . '-gray'] = array('width' => $metadata['width'], 'height' => $metadata['height']);
                }
                $image = new Grayscale_Image_Editor($filename);
                $image->load();
                $image->make_grayscale();
                $result = $image->save($image->generate_filename('gray'));
                $metadata['sizes'][$size . '-gray']['file'] = $result['file'];
            }
        }
    }
    return $metadata;
}
コード例 #26
0
 function add_zipped_font()
 {
     //check if referer is ok
     if (function_exists('check_ajax_referer')) {
         check_ajax_referer('avia_nonce_save_backend');
     }
     //check if capability is ok
     $cap = apply_filters('avf_file_upload_capability', 'update_plugins');
     if (!current_user_can($cap)) {
         exit("Using this feature is reserved for Super Admins. You unfortunately don't have the necessary permissions.");
     }
     //get the file path of the zip file
     $attachment = $_POST['values'];
     $path = realpath(get_attached_file($attachment['id']));
     $unzipped = $this->zip_flatten($path, array('\\.eot', '\\.svg', '\\.ttf', '\\.woff', '\\.json'));
     // if we were able to unzip the file and save it to our temp folder extract the svg file
     if ($unzipped) {
         $this->create_config();
     }
     //if we got no name for the font dont add it and delete the temp folder
     if ($this->font_name == 'unknown') {
         $this->delete_folder($this->paths['tempdir']);
         exit('Was not able to retrieve the Font name from your Uploaded Folder');
     }
     exit('avia_font_added:' . $this->font_name);
 }
コード例 #27
0
 /**
  * Registered callback function for the WordPress Importer
  *
  * Manages the three separate stages of the WXR import process
  */
 function dispatch()
 {
     $this->header();
     $step = empty($_GET['step']) ? 0 : (int) $_GET['step'];
     switch ($step) {
         case 0:
             $this->greet();
             break;
         case 1:
             check_admin_referer('import-upload');
             if ($this->handle_upload()) {
                 $this->import_options();
             }
             break;
         case 2:
             check_admin_referer('import-wordpress');
             $this->fetch_attachments = !empty($_POST['fetch_attachments']) && $this->allow_fetch_attachments();
             $this->id = (int) $_POST['import_id'];
             $file = get_attached_file($this->id);
             set_time_limit(0);
             $this->import($file);
             break;
     }
     $this->footer();
 }
コード例 #28
0
ファイル: ajax.php プロジェクト: KimcoBlogSC/Blog
 public function ajax_upload_image()
 {
     require_once dirname(__FILE__) . '/polldaddy-client.php';
     check_admin_referer('send-media');
     $attach_id = $media_id = $user_code = 0;
     $name = $url = '';
     if (isset($_POST['attach-id'])) {
         $attach_id = (int) $_POST['attach-id'];
     }
     if (isset($_POST['media-id'])) {
         $media_id = (int) $_POST['media-id'];
     }
     if (isset($_POST['uc'])) {
         $user_code = $_POST['uc'];
     }
     if (isset($_POST['url'])) {
         $url = $_POST['url'];
     }
     $parts = pathinfo($url);
     $name = preg_replace('/\\?.*/', '', $parts['basename']);
     $polldaddy = new api_client(WP_POLLDADDY__PARTNERGUID, $user_code);
     $data = '';
     if (function_exists('is_private_blog') && is_private_blog()) {
         $file_path = get_attached_file($attach_id);
         $data = base64_encode(@file_get_contents($file_path));
     }
     $response = $polldaddy->upload_image($name, $url, 'poll', $media_id > 1000 ? $media_id : 0, $data);
     if (is_a($response, "PollDaddy_Media")) {
         echo urldecode($response->upload_result) . '||' . $media_id;
     }
     die;
 }
コード例 #29
0
 /**
  * Registered callback function for the WordPress Importer
  *
  * Manages the three separate stages of the CSV import process
  */
 function dispatch()
 {
     $this->header();
     if (!empty($_POST['delimiter'])) {
         $this->delimiter = stripslashes(trim($_POST['delimiter']));
     }
     if (!$this->delimiter) {
         $this->delimiter = ',';
     }
     $step = empty($_GET['step']) ? 0 : (int) $_GET['step'];
     switch ($step) {
         case 0:
             $this->greet();
             break;
         case 1:
             check_admin_referer('import-upload');
             if ($this->handle_upload()) {
                 if ($this->id) {
                     $file = get_attached_file($this->id);
                 } else {
                     $file = ABSPATH . $this->file_url;
                 }
                 add_filter('http_request_timeout', array($this, 'bump_request_timeout'));
                 if (function_exists('gc_enable')) {
                     gc_enable();
                 }
                 @set_time_limit(0);
                 @ob_flush();
                 @flush();
                 $this->import($file);
             }
             break;
     }
     $this->footer();
 }
コード例 #30
0
ファイル: functions.php プロジェクト: ArgiaCyber/alfath
 /**
  * callback for ajax action restore_backup
  *
  * @return string
  */
 function wp_ajax_restore_backup_callback()
 {
     if (isset($_POST['restore_id']) && !empty($_POST['restore_id'])) {
         ob_start();
         $attachment_id = $_POST['restore_id'];
         $attachment_path = get_attached_file($attachment_id);
         $response = array();
         if ($attachment_path != '') {
             require_once ADMIN_DIR . '/class-alfath-backup.php';
             $restore = AlfathBackup::restore($attachment_path);
             if ($restore['info']) {
                 unlink($attachment_path);
                 $response['status'] = 'success';
                 $response['message'] = __('Database restore success.', 'alfath');
                 $response['warning'] = isset($restore['warning']) ? $restore['warning'] : '';
             } else {
                 wp_delete_attachment($attachment_id, true);
                 $response['status'] = 'error';
                 $response['message'] = __('Database restore failed.', 'alfath');
                 $response['warning'] = isset($restore['warning']) ? $restore['warning'] : '';
             }
         } else {
             $response['status'] = 'error';
             $response['message'] = __('Database restore failed.', 'alfath');
             $response['warning'] = isset($restore['warning']) ? $restore['warning'] : __('File not found', 'alfath');
         }
         ob_end_clean();
         if (!empty($response)) {
             echo json_encode($response);
         }
     }
     die;
 }