Example #1
0
/**
 * AJAX handler for cropping an image.
 *
 * @since 4.3.0
 *
 * @global WP_Site_Icon $wp_site_icon
 */
function wp_ajax_crop_image()
{
    $attachment_id = absint($_POST['id']);
    check_ajax_referer('image_editor-' . $attachment_id, 'nonce');
    if (!current_user_can('customize')) {
        wp_send_json_error();
    }
    $context = str_replace('_', '-', $_POST['context']);
    $data = array_map('absint', $_POST['cropDetails']);
    $cropped = wp_crop_image($attachment_id, $data['x1'], $data['y1'], $data['width'], $data['height'], $data['dst_width'], $data['dst_height']);
    if (!$cropped || is_wp_error($cropped)) {
        wp_send_json_error(array('message' => __('Image could not be processed.')));
    }
    switch ($context) {
        case 'site-icon':
            require_once ABSPATH . '/wp-admin/includes/class-wp-site-icon.php';
            global $wp_site_icon;
            // Skip creating a new attachment if the attachment is a Site Icon.
            if (get_post_meta($attachment_id, '_wp_attachment_context', true) == $context) {
                // Delete the temporary cropped file, we don't need it.
                wp_delete_file($cropped);
                // Additional sizes in wp_prepare_attachment_for_js().
                add_filter('image_size_names_choose', array($wp_site_icon, 'additional_sizes'));
                break;
            }
            /** This filter is documented in wp-admin/custom-header.php */
            $cropped = apply_filters('wp_create_file_in_uploads', $cropped, $attachment_id);
            // For replication.
            $object = $wp_site_icon->create_attachment_object($cropped, $attachment_id);
            unset($object['ID']);
            // Update the attachment.
            add_filter('intermediate_image_sizes_advanced', array($wp_site_icon, 'additional_sizes'));
            $attachment_id = $wp_site_icon->insert_attachment($object, $cropped);
            remove_filter('intermediate_image_sizes_advanced', array($wp_site_icon, 'additional_sizes'));
            // Additional sizes in wp_prepare_attachment_for_js().
            add_filter('image_size_names_choose', array($wp_site_icon, 'additional_sizes'));
            break;
        default:
            /**
             * Fires before a cropped image is saved.
             *
             * Allows to add filters to modify the way a cropped image is saved.
             *
             * @since 4.3.0
             *
             * @param string $context       The Customizer control requesting the cropped image.
             * @param int    $attachment_id The attachment ID of the original image.
             * @param string $cropped       Path to the cropped image file.
             */
            do_action('wp_ajax_crop_image_pre_save', $context, $attachment_id, $cropped);
            /** This filter is documented in wp-admin/custom-header.php */
            $cropped = apply_filters('wp_create_file_in_uploads', $cropped, $attachment_id);
            // For replication.
            $parent_url = wp_get_attachment_url($attachment_id);
            $url = str_replace(basename($parent_url), basename($cropped), $parent_url);
            $size = @getimagesize($cropped);
            $image_type = $size ? $size['mime'] : 'image/jpeg';
            $object = array('post_title' => basename($cropped), 'post_content' => $url, 'post_mime_type' => $image_type, 'guid' => $url, 'context' => $context);
            $attachment_id = wp_insert_attachment($object, $cropped);
            $metadata = wp_generate_attachment_metadata($attachment_id, $cropped);
            /**
             * Filter the cropped image attachment metadata.
             *
             * @since 4.3.0
             *
             * @see wp_generate_attachment_metadata()
             *
             * @param array $metadata Attachment metadata.
             */
            $metadata = apply_filters('wp_ajax_cropped_attachment_metadata', $metadata);
            wp_update_attachment_metadata($attachment_id, $metadata);
            /**
             * Filter the attachment ID for a cropped image.
             *
             * @since 4.3.0
             *
             * @param int    $attachment_id The attachment ID of the cropped image.
             * @param string $context       The Customizer control requesting the cropped image.
             */
            $attachment_id = apply_filters('wp_ajax_cropped_attachment_id', $attachment_id, $context);
    }
    wp_send_json_success(wp_prepare_attachment_for_js($attachment_id));
}
Example #2
0
/**
 * Saves image to post along with enqueued changes
 * in $_REQUEST['history']
 *
 * @param int $post_id
 * @return \stdClass
 */
function wp_save_image($post_id)
{
    global $_wp_additional_image_sizes;
    $return = new stdClass();
    $success = $delete = $scaled = $nocrop = false;
    $post = get_post($post_id);
    $img = wp_get_image_editor(_load_image_to_edit_path($post_id, 'full'));
    if (is_wp_error($img)) {
        $return->error = esc_js(__('Unable to create new image.'));
        return $return;
    }
    $fwidth = !empty($_REQUEST['fwidth']) ? intval($_REQUEST['fwidth']) : 0;
    $fheight = !empty($_REQUEST['fheight']) ? intval($_REQUEST['fheight']) : 0;
    $target = !empty($_REQUEST['target']) ? preg_replace('/[^a-z0-9_-]+/i', '', $_REQUEST['target']) : '';
    $scale = !empty($_REQUEST['do']) && 'scale' == $_REQUEST['do'];
    if ($scale && $fwidth > 0 && $fheight > 0) {
        $size = $img->get_size();
        $sX = $size['width'];
        $sY = $size['height'];
        // Check if it has roughly the same w / h ratio.
        $diff = round($sX / $sY, 2) - round($fwidth / $fheight, 2);
        if (-0.1 < $diff && $diff < 0.1) {
            // Scale the full size image.
            if ($img->resize($fwidth, $fheight)) {
                $scaled = true;
            }
        }
        if (!$scaled) {
            $return->error = esc_js(__('Error while saving the scaled image. Please reload the page and try again.'));
            return $return;
        }
    } elseif (!empty($_REQUEST['history'])) {
        $changes = json_decode(wp_unslash($_REQUEST['history']));
        if ($changes) {
            $img = image_edit_apply_changes($img, $changes);
        }
    } else {
        $return->error = esc_js(__('Nothing to save, the image has not changed.'));
        return $return;
    }
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    if (!is_array($meta)) {
        $return->error = esc_js(__('Image data does not exist. Please re-upload the image.'));
        return $return;
    }
    if (!is_array($backup_sizes)) {
        $backup_sizes = array();
    }
    // Generate new filename.
    $path = get_attached_file($post_id);
    $path_parts = pathinfo($path);
    $filename = $path_parts['filename'];
    $suffix = time() . rand(100, 999);
    if (defined('IMAGE_EDIT_OVERWRITE') && IMAGE_EDIT_OVERWRITE && isset($backup_sizes['full-orig']) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
        if ('thumbnail' == $target) {
            $new_path = "{$path_parts['dirname']}/{$filename}-temp.{$path_parts['extension']}";
        } else {
            $new_path = $path;
        }
    } else {
        while (true) {
            $filename = preg_replace('/-e([0-9]+)$/', '', $filename);
            $filename .= "-e{$suffix}";
            $new_filename = "{$filename}.{$path_parts['extension']}";
            $new_path = "{$path_parts['dirname']}/{$new_filename}";
            if (file_exists($new_path)) {
                $suffix++;
            } else {
                break;
            }
        }
    }
    // Save the full-size file, also needed to create sub-sizes.
    if (!wp_save_image_file($new_path, $img, $post->post_mime_type, $post_id)) {
        $return->error = esc_js(__('Unable to save the image.'));
        return $return;
    }
    if ('nothumb' == $target || 'all' == $target || 'full' == $target || $scaled) {
        $tag = false;
        if (isset($backup_sizes['full-orig'])) {
            if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes['full-orig']['file'] != $path_parts['basename']) {
                $tag = "full-{$suffix}";
            }
        } else {
            $tag = 'full-orig';
        }
        if ($tag) {
            $backup_sizes[$tag] = array('width' => $meta['width'], 'height' => $meta['height'], 'file' => $path_parts['basename']);
        }
        $success = $path === $new_path || update_attached_file($post_id, $new_path);
        $meta['file'] = _wp_relative_upload_path($new_path);
        $size = $img->get_size();
        $meta['width'] = $size['width'];
        $meta['height'] = $size['height'];
        if ($success && ('nothumb' == $target || 'all' == $target)) {
            $sizes = get_intermediate_image_sizes();
            if ('nothumb' == $target) {
                $sizes = array_diff($sizes, array('thumbnail'));
            }
        }
        $return->fw = $meta['width'];
        $return->fh = $meta['height'];
    } elseif ('thumbnail' == $target) {
        $sizes = array('thumbnail');
        $success = $delete = $nocrop = true;
    }
    if (isset($sizes)) {
        $_sizes = array();
        foreach ($sizes as $size) {
            $tag = false;
            if (isset($meta['sizes'][$size])) {
                if (isset($backup_sizes["{$size}-orig"])) {
                    if ((!defined('IMAGE_EDIT_OVERWRITE') || !IMAGE_EDIT_OVERWRITE) && $backup_sizes["{$size}-orig"]['file'] != $meta['sizes'][$size]['file']) {
                        $tag = "{$size}-{$suffix}";
                    }
                } else {
                    $tag = "{$size}-orig";
                }
                if ($tag) {
                    $backup_sizes[$tag] = $meta['sizes'][$size];
                }
            }
            if (isset($_wp_additional_image_sizes[$size])) {
                $width = intval($_wp_additional_image_sizes[$size]['width']);
                $height = intval($_wp_additional_image_sizes[$size]['height']);
                $crop = $nocrop ? false : $_wp_additional_image_sizes[$size]['crop'];
            } else {
                $height = get_option("{$size}_size_h");
                $width = get_option("{$size}_size_w");
                $crop = $nocrop ? false : get_option("{$size}_crop");
            }
            $_sizes[$size] = array('width' => $width, 'height' => $height, 'crop' => $crop);
        }
        $meta['sizes'] = array_merge($meta['sizes'], $img->multi_resize($_sizes));
    }
    unset($img);
    if ($success) {
        wp_update_attachment_metadata($post_id, $meta);
        update_post_meta($post_id, '_wp_attachment_backup_sizes', $backup_sizes);
        if ($target == 'thumbnail' || $target == 'all' || $target == 'full') {
            // Check if it's an image edit from attachment edit screen
            if (!empty($_REQUEST['context']) && 'edit-attachment' == $_REQUEST['context']) {
                $thumb_url = wp_get_attachment_image_src($post_id, array(900, 600), true);
                $return->thumbnail = $thumb_url[0];
            } else {
                $file_url = wp_get_attachment_url($post_id);
                if (!empty($meta['sizes']['thumbnail']) && ($thumb = $meta['sizes']['thumbnail'])) {
                    $return->thumbnail = path_join(dirname($file_url), $thumb['file']);
                } else {
                    $return->thumbnail = "{$file_url}?w=128&h=128";
                }
            }
        }
    } else {
        $delete = true;
    }
    if ($delete) {
        wp_delete_file($new_path);
    }
    $return->msg = esc_js(__('Image saved'));
    return $return;
}
Example #3
0
/**
 * Trash or delete an attachment.
 *
 * When an attachment is permanently deleted, the file will also be removed.
 * Deletion removes all post meta fields, taxonomy, comments, etc. associated
 * with the attachment (except the main post).
 *
 * The attachment is moved to the trash instead of permanently deleted unless trash
 * for media is disabled, item is already in the trash, or $force_delete is true.
 *
 * @since 2.0.0
 *
 * @global wpdb $wpdb WordPress database abstraction object.
 *
 * @param int  $post_id      Attachment ID.
 * @param bool $force_delete Optional. Whether to bypass trash and force deletion.
 *                           Default false.
 * @return mixed False on failure. Post data on success.
 */
function wp_delete_attachment($post_id, $force_delete = false)
{
    global $wpdb;
    if (!($post = $wpdb->get_row($wpdb->prepare("SELECT * FROM {$wpdb->posts} WHERE ID = %d", $post_id)))) {
        return $post;
    }
    if ('attachment' != $post->post_type) {
        return false;
    }
    if (!$force_delete && EMPTY_TRASH_DAYS && MEDIA_TRASH && 'trash' != $post->post_status) {
        return wp_trash_post($post_id);
    }
    delete_post_meta($post_id, '_wp_trash_meta_status');
    delete_post_meta($post_id, '_wp_trash_meta_time');
    $meta = wp_get_attachment_metadata($post_id);
    $backup_sizes = get_post_meta($post->ID, '_wp_attachment_backup_sizes', true);
    $file = get_attached_file($post_id);
    if (is_multisite()) {
        delete_transient('dirsize_cache');
    }
    /**
     * Fires before an attachment is deleted, at the start of wp_delete_attachment().
     *
     * @since 2.0.0
     *
     * @param int $post_id Attachment ID.
     */
    do_action('delete_attachment', $post_id);
    wp_delete_object_term_relationships($post_id, array('category', 'post_tag'));
    wp_delete_object_term_relationships($post_id, get_object_taxonomies($post->post_type));
    // Delete all for any posts.
    delete_metadata('post', null, '_thumbnail_id', $post_id, true);
    wp_defer_comment_counting(true);
    $comment_ids = $wpdb->get_col($wpdb->prepare("SELECT comment_ID FROM {$wpdb->comments} WHERE comment_post_ID = %d", $post_id));
    foreach ($comment_ids as $comment_id) {
        wp_delete_comment($comment_id, true);
    }
    wp_defer_comment_counting(false);
    $post_meta_ids = $wpdb->get_col($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE post_id = %d ", $post_id));
    foreach ($post_meta_ids as $mid) {
        delete_metadata_by_mid('post', $mid);
    }
    /** This action is documented in wp-includes/post.php */
    do_action('delete_post', $post_id);
    $result = $wpdb->delete($wpdb->posts, array('ID' => $post_id));
    if (!$result) {
        return false;
    }
    /** This action is documented in wp-includes/post.php */
    do_action('deleted_post', $post_id);
    $uploadpath = wp_upload_dir();
    if (!empty($meta['thumb'])) {
        // Don't delete the thumb if another attachment uses it.
        if (!$wpdb->get_row($wpdb->prepare("SELECT meta_id FROM {$wpdb->postmeta} WHERE meta_key = '_wp_attachment_metadata' AND meta_value LIKE %s AND post_id <> %d", '%' . $wpdb->esc_like($meta['thumb']) . '%', $post_id))) {
            $thumbfile = str_replace(basename($file), $meta['thumb'], $file);
            /** This filter is documented in wp-includes/functions.php */
            $thumbfile = apply_filters('wp_delete_file', $thumbfile);
            @unlink(path_join($uploadpath['basedir'], $thumbfile));
        }
    }
    // Remove intermediate and backup images if there are any.
    if (isset($meta['sizes']) && is_array($meta['sizes'])) {
        foreach ($meta['sizes'] as $size => $sizeinfo) {
            $intermediate_file = str_replace(basename($file), $sizeinfo['file'], $file);
            /** This filter is documented in wp-includes/functions.php */
            $intermediate_file = apply_filters('wp_delete_file', $intermediate_file);
            @unlink(path_join($uploadpath['basedir'], $intermediate_file));
        }
    }
    if (is_array($backup_sizes)) {
        foreach ($backup_sizes as $size) {
            $del_file = path_join(dirname($meta['file']), $size['file']);
            /** This filter is documented in wp-includes/functions.php */
            $del_file = apply_filters('wp_delete_file', $del_file);
            @unlink(path_join($uploadpath['basedir'], $del_file));
        }
    }
    wp_delete_file($file);
    clean_post_cache($post);
    return $post;
}
 /**
  * Remove the avatar of a user.
  *
  * @access public
  * @since 1.0.0
  * @return void
  */
 public function remove_user_file()
 {
     $form = esc_attr($_REQUEST['submitted_form']);
     check_ajax_referer($form, 'wpaam_removal_nonce');
     $field_id = $_REQUEST['field_id'];
     $user_id = get_current_user_id();
     // Functionality to remove avatar.
     if ($field_id == 'user_avatar') {
         if ($field_id && is_user_logged_in()) {
             delete_user_meta($user_id, "current_{$field_id}");
             // Deletes previously selected avatar.
             $previous_avatar = get_user_meta($user_id, "_current_{$field_id}_path", true);
             if ($previous_avatar) {
                 wp_delete_file($previous_avatar);
             }
             delete_user_meta($user_id, "_current_{$field_id}_path");
             $return = array('valid' => true, 'message' => apply_filters('wpaam_avatar_deleted_success_message', __('Your profile picture has been deleted.', 'wpaam')));
             wp_send_json_success($return);
         } else {
             $return = array('valid' => false, 'message' => __('Something went wrong.', 'wpaam'));
             wp_send_json_error($return);
         }
         // This is needed for all the other field types.
     } else {
         if ($field_id && is_user_logged_in()) {
             $field_files = get_user_meta($user_id, $field_id, true);
             $field_files = maybe_unserialize($field_files);
             if (is_array($field_files)) {
                 if (wpaam_is_multi_array($field_files)) {
                     foreach ($field_files as $key => $file) {
                         wp_delete_file($file['path']);
                     }
                 } else {
                     wp_delete_file($field_files['path']);
                 }
             }
             delete_user_meta($user_id, $field_id);
             $return = array('valid' => true, 'message' => apply_filters('wpaam_files_deleted_success_message', __('Files successfully removed.', 'wpaam')));
             wp_send_json_success($return);
         }
     }
 }
 /**
  * Upload the given file to an Azure Storage container as a block blob.
  *
  * Block blobs are comprised of blocks, each of which is identified by a block ID.
  * This allows creation or modification of a block blob by writing a set of blocks
  * and committing them by their block IDs, resulting in an overall efficient upload.
  *
  * If writing a block blob that is no more than 64MB in size, upload it
  * in its entirety with a single write operation. Otherwise, chunk the blob into discrete
  * blocks and upload each of them, then commit the blob ID to signal to Azure that they
  * should be combined into a blob. Files over 64MB are then deleted from temporary local storage.
  *
  * When you upload a block to a blob in your storage account, it is associated with the
  * specified block blob, but it does  not become part of the blob until you commit a list
  * of blocks that includes the new block's ID.
  *
  * @param string $containerName   The container to add the blob to.
  * @param string $blobName        The name of the blob to upload.
  * @param string $localFileName   The full path to local file to be uploaded.
  * @param string $blobContentType Optional. Content type of the blob.
  * @param array  $metadata        Optional. Metadata to describe the blob.
  *
  * @throws \Exception|ServiceException Exception if local file can't be read;
  *                                     ServiceException if response code is incorrect.
  */
 public static function putBlockBlob($containerName, $blobName, $localFileName, $blobContentType = null, $metadata = array())
 {
     $copyBlobResult = null;
     $is_large_file = false;
     // Open file
     $handle = fopen($localFileName, 'r');
     if ($handle === false) {
         throw new Exception('Could not open the local file ' . $localFileName);
     }
     /** @var \WindowsAzure\Blob\BlobRestProxy $blobRestProxy */
     $blobRestProxy = WindowsAzureStorageUtil::getStorageClient();
     try {
         if (filesize($localFileName) < self::MAX_BLOB_SIZE) {
             $createBlobOptions = new CreateBlobOptions();
             $createBlobOptions->setBlobContentType($blobContentType);
             $createBlobOptions->setMetadata($metadata);
             $blobRestProxy->createBlockBlob($containerName, $blobName, $handle, $createBlobOptions);
             fclose($handle);
         } else {
             $is_large_file = true;
             // Determine number of page blocks
             $numberOfBlocks = ceil(filesize($localFileName) / self::MAX_BLOB_TRANSFER_SIZE);
             // Generate block id's
             $blocks = array();
             for ($i = 0; $i < $numberOfBlocks; $i++) {
                 /** @var WindowsAzure\Blob\Models\Block */
                 $block = new Block();
                 $block->setBlockId(self::_generateBlockId($i));
                 $block->setType(BlobBlockType::LATEST_TYPE);
                 // Seek position in file
                 fseek($handle, $i * self::MAX_BLOB_TRANSFER_SIZE);
                 // Read contents
                 $fileContents = fread($handle, self::MAX_BLOB_TRANSFER_SIZE);
                 // Put block
                 $blobRestProxy->createBlobBlock($containerName, $blobName, $block->getBlockId(), $fileContents);
                 // Save it for later
                 $blocks[$i] = $block;
             }
             // Close file
             fclose($handle);
             // Set Block Blob's content type and metadata
             $commitBlockBlobOptions = new CommitBlobBlocksOptions();
             $commitBlockBlobOptions->setBlobContentType($blobContentType);
             $commitBlockBlobOptions->setMetadata($metadata);
             // Commit the block list
             $blobRestProxy->commitBlobBlocks($containerName, $blobName, $blocks, $commitBlockBlobOptions);
             if ($is_large_file) {
                 // Delete large temp files when we're done
                 try {
                     //TODO: add option to keep this file if so desired
                     if (self::blob_exists_in_container($blobName, $containerName)) {
                         wp_delete_file($localFileName);
                         // Dispose file contents
                         $fileContents = null;
                         unset($fileContents);
                     } else {
                         throw new Exception(sprintf(__('The blob %1$2 was not uploaded to container %2$2. Please try again.', 'windows-azure-storage'), $blobName, $containerName));
                     }
                 } catch (Exception $ex) {
                     echo '<p class="notice">' . esc_html($ex->getMessage()) . '</p>';
                 }
             }
         }
     } catch (ServiceException $exception) {
         if (!$handle) {
             fclose($handle);
         }
         throw $exception;
     }
 }
Example #6
0
 /**
  *
  * @param type $attachments
  * @param type $file_object
  *
  * @return array $updated_attachment_ids
  * @throws Exception
  */
 function insert_attachment($attachments, $file_object)
 {
     $updated_attachment_ids = array();
     foreach ($attachments as $key => $attachment) {
         $attachment_id = wp_insert_attachment($attachment, $file_object[$key]['file'], $attachment['post_parent']);
         if (!is_wp_error($attachment_id)) {
             add_filter('intermediate_image_sizes', array($this, 'image_sizes'), 99);
             /**
              * FIX WORDPRESS 3.6 METADATA
              */
             require_once ABSPATH . 'wp-admin/includes/media.php';
             /**
              *
              */
             wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $file_object[$key]['file']));
         } else {
             $file = $file_object[$key]['file'];
             if (function_exists('wp_delete_file')) {
                 // wp_delete_file is introduced in WordPress 4.2
                 wp_delete_file($file);
             } else {
                 unlink($file);
                 // @codingStandardsIgnoreLine
             }
             throw new Exception(esc_html__('Error creating attachment for the media file, please try again', 'buddypress-media'));
         }
         $updated_attachment_ids[] = $attachment_id;
     }
     return $updated_attachment_ids;
 }
Example #7
0
 /**
  * Display third step of custom header image page.
  *
  * @since 2.1.0
  */
 public function step_3()
 {
     check_admin_referer('custom-header-crop-image');
     if (!current_theme_supports('custom-header', 'uploads')) {
         wp_die(__('Cheatin&#8217; uh?'), 403);
     }
     if (!empty($_POST['skip-cropping']) && !(current_theme_supports('custom-header', 'flex-height') || current_theme_supports('custom-header', 'flex-width'))) {
         wp_die(__('Cheatin&#8217; uh?'), 403);
     }
     if ($_POST['oitar'] > 1) {
         $_POST['x1'] = $_POST['x1'] * $_POST['oitar'];
         $_POST['y1'] = $_POST['y1'] * $_POST['oitar'];
         $_POST['width'] = $_POST['width'] * $_POST['oitar'];
         $_POST['height'] = $_POST['height'] * $_POST['oitar'];
     }
     $attachment_id = absint($_POST['attachment_id']);
     $original = get_attached_file($attachment_id);
     $dimensions = $this->get_header_dimensions(array('height' => $_POST['height'], 'width' => $_POST['width']));
     $height = $dimensions['dst_height'];
     $width = $dimensions['dst_width'];
     if (empty($_POST['skip-cropping'])) {
         $cropped = wp_crop_image($attachment_id, (int) $_POST['x1'], (int) $_POST['y1'], (int) $_POST['width'], (int) $_POST['height'], $width, $height);
     } elseif (!empty($_POST['create-new-attachment'])) {
         $cropped = _copy_image_file($attachment_id);
     } else {
         $cropped = get_attached_file($attachment_id);
     }
     if (!$cropped || is_wp_error($cropped)) {
         wp_die(__('Image could not be processed. Please go back and try again.'), __('Image Processing Error'));
     }
     /** This filter is documented in wp-admin/custom-header.php */
     $cropped = apply_filters('wp_create_file_in_uploads', $cropped, $attachment_id);
     // For replication
     $object = $this->create_attachment_object($cropped, $attachment_id);
     if (!empty($_POST['create-new-attachment'])) {
         unset($object['ID']);
     }
     // Update the attachment
     $attachment_id = $this->insert_attachment($object, $cropped);
     $url = $object['guid'];
     $this->set_header_image(compact('url', 'attachment_id', 'width', 'height'));
     // Cleanup.
     $medium = str_replace(basename($original), 'midsize-' . basename($original), $original);
     if (file_exists($medium)) {
         wp_delete_file($medium);
     }
     if (empty($_POST['create-new-attachment']) && empty($_POST['skip-cropping'])) {
         wp_delete_file($original);
     }
     return $this->finished();
 }
Example #8
0
				<input class="button" type="button" name="Continue" value="' . $lang['ok'] . '" onClick="document.location.replace(\'' . WP_WEB_DIRECTORY . 'document.php' . $query_string . '\')">
				</form>
				</div>');
            }
        } else {
            wp_delete_file($directory . $_POST['document_field'] . '.TEMP');
            document_exit('<p>&nbsp;</p>
			<div class="helpMessage">
			<form>
			<p> ' . $lang['dir_exists'] . ' </p>
			<input class="button" type="button" name="Continue" value="' . $lang['ok'] . '" onClick="document.location.replace(\'' . WP_WEB_DIRECTORY . 'document.php' . $query_string . '\')">
			</form>
			</div>');
        }
    } elseif ($_POST['ok_to_overwrite'] == $lang['cancel']) {
        wp_delete_file($directory . $_POST['document_field'] . '.TEMP');
    } else {
        $message .= '<div class="helpMessage"><p>' . $lang['copy_error'] . '</p></div>';
    }
}
// upload files
if (isset($_FILES['document_field']) ? $_FILES['document_field'] : '') {
    if (is_uploaded_file($_FILES['document_field']['tmp_name'])) {
        $extension = strrchr(strtolower($_FILES['document_field']['name']), '.');
        //exit ($_FILES['document_field']['tmp_name']);
        // check filetype against accepted files
        if (!wp_extension_ok($extension, $document_types)) {
            document_exit('<p>&nbsp;</p>
			<div class="helpMessage">
			<form>
			<p> ' . wp_var_replace($lang['bad_filetype'], array('filetypes' => $document_types)) . ' </p>
Example #9
0
 function safe_unlink($file_path)
 {
     if (file_exists($file_path)) {
         if (function_exists('wp_delete_file')) {
             // wp_delete_file is introduced in WordPress 4.2
             wp_delete_file($file_path);
         } else {
             unlink($file_path);
             // @codingStandardsIgnoreLine
         }
     }
 }
 /**
  * Remove the avatar of a user.
  *
  * @access public
  * @since 1.0.0
  * @return void
  */
 public function remove_user_avatar()
 {
     // Check our nonce and make sure it's correct.
     check_ajax_referer('profile', 'wpum_removal_nonce');
     $field_id = $_REQUEST['field_id'];
     $user_id = get_current_user_id();
     if ($field_id && is_user_logged_in()) {
         delete_user_meta($user_id, "current_{$field_id}");
         // Deletes previously selected avatar.
         $previous_avatar = get_user_meta($user_id, "_current_{$field_id}_path", true);
         if ($previous_avatar) {
             wp_delete_file($previous_avatar);
         }
         delete_user_meta($user_id, "_current_{$field_id}_path");
         $return = array('valid' => true, 'message' => apply_filters('wpum_avatar_deleted_success_message', __('Your profile picture has been deleted.', 'wpum')));
         wp_send_json_success($return);
     } else {
         $return = array('valid' => false, 'message' => __('Something went wrong.', 'wpum'));
         wp_send_json_error($return);
     }
 }
 public function removeFile()
 {
     if ($this->isFile()) {
         wp_delete_file($this->getFilePath());
     }
     delete_post_meta($this->post->ID, $this->meta_key);
 }
Example #12
0
				<input class="button" type="button" name="Continue" value="' . $lang['ok'] . '" onClick="document.location.replace(\'' . WP_WEB_DIRECTORY . 'image.php' . $query_string . '\')">
				</form>
				</div>');
            }
        } else {
            wp_delete_file($directory . $_POST['image_field'] . '.TEMP');
            image_exit('<p>&nbsp;</p>
			<div class="helpMessage">
			<form>
			<p> ' . $lang['dir_exists'] . ' </p>
			<input class="button" type="button" name="Continue" value="' . $lang['ok'] . '" onClick="document.location.replace(\'' . WP_WEB_DIRECTORY . 'image.php' . $query_string . '\')">
			</form>
			</div>');
        }
    } elseif ($_POST['ok_to_overwrite'] == $lang['cancel']) {
        wp_delete_file($directory . $_POST['image_field'] . '.TEMP');
    } else {
        $message .= '<div class="helpMessage"><p>' . $lang['copy_error'] . '</p></div>';
    }
}
// upload files
if (isset($_FILES['image_field']) ? $_FILES['image_field'] : '') {
    if (is_uploaded_file($_FILES['image_field']['tmp_name'])) {
        $extension = strrchr(strtolower($_FILES['image_field']['name']), '.');
        // check filetype against accepted files
        if (!wp_extension_ok($extension, $image_types)) {
            image_exit('<p>&nbsp;</p>
			<div class="helpMessage">
			<form>
			<p> ' . wp_var_replace($lang['bad_filetype'], array('filetypes' => $image_types)) . ' </p>
			<input class="button" type="button" name="Continue" value="' . $lang['ok'] . '" onClick="document.location.replace(\'' . WP_WEB_DIRECTORY . 'image.php' . $query_string . '\')">
    /**
     * Crop a the image admin view.
     *
     * @since 4.3.0
     */
    public function crop_page()
    {
        check_admin_referer('crop-site-icon');
        if (isset($_GET['file'])) {
            $attachment_id = absint($_GET['file']);
            $file = get_attached_file($attachment_id, true);
            $url = wp_get_attachment_image_src($attachment_id, 'full');
            $url = $url[0];
        } else {
            $upload = $this->handle_upload();
            $attachment_id = $upload['attachment_id'];
            $file = $upload['file'];
            $url = $upload['url'];
        }
        $image_size = getimagesize($file);
        if ($image_size[0] < $this->min_size) {
            add_settings_error('site-icon', 'too-small', sprintf(__('The selected image is smaller than %upx in width.'), $this->min_size));
            // back to step one
            $this->select_page();
            return;
        }
        if ($image_size[1] < $this->min_size) {
            add_settings_error('site-icon', 'too-small', sprintf(__('The selected image is smaller than %upx in height.'), $this->min_size));
            // Back to step one.
            $this->select_page();
            return;
        }
        // Let's resize the image so that the user can easier crop a image that in the admin view.
        $crop_height = absint($this->page_crop * $image_size[1] / $image_size[0]);
        $cropped = wp_crop_image($attachment_id, 0, 0, 0, 0, $this->page_crop, $crop_height);
        if (!$cropped || is_wp_error($cropped)) {
            wp_die(__('Image could not be processed. Please go back and try again.'), __('Image Processing Error'));
        }
        $cropped_size = getimagesize($cropped);
        // set default values (in case of no JS)
        $crop_ratio = $image_size[0] / $cropped_size[0];
        if ($cropped_size[0] < $cropped_size[1]) {
            $crop_x = 0;
            $crop_y = absint(($cropped_size[1] - $cropped_size[0]) / 2);
            $crop_size = $cropped_size[0];
        } elseif ($cropped_size[0] > $cropped_size[1]) {
            $crop_x = absint(($cropped_size[0] - $cropped_size[1]) / 2);
            $crop_y = 0;
            $crop_size = $cropped_size[1];
        } else {
            $crop_x = 0;
            $crop_y = 0;
            $crop_size = $cropped_size[0];
        }
        wp_delete_file($cropped);
        wp_localize_script('site-icon-crop', 'wpSiteIconCropData', $this->initial_crop_data($crop_ratio, $cropped_size));
        ?>

		<div class="wrap">
			<h2 class="site-icon-title"><?php 
        _e('Site Icon');
        ?>
</h2>
			<?php 
        settings_errors('site-icon');
        ?>

			<div class="site-icon-crop-shell">
				<form action="options-general.php" method="post" enctype="multipart/form-data">
					<p class="hide-if-no-js description"><?php 
        _e('Choose the part of the image you want to use as your site icon.');
        ?>
</p>
					<p class="hide-if-js description"><strong><?php 
        _e('You need Javascript to choose a part of the image.');
        ?>
</strong></p>

					<div class="site-icon-crop-preview-shell hide-if-no-js">
						<h3><?php 
        _e('Preview');
        ?>
</h3>
						<strong><?php 
        _e('As your favicon');
        ?>
</strong>
						<div class="site-icon-crop-favicon-preview-shell">
							<img src="images/browser.png" class="site-icon-browser-preview" width="182" height="" alt="<?php 
        esc_attr_e('Browser Chrome');
        ?>
"/>

							<div class="site-icon-crop-preview-favicon">
								<img src="<?php 
        echo esc_url($url);
        ?>
" id="preview-favicon" alt="<?php 
        esc_attr_e('Preview Favicon');
        ?>
"/>
							</div>
							<span class="site-icon-browser-title"><?php 
        bloginfo('name');
        ?>
</span>
						</div>

						<strong><?php 
        _e('As a mobile icon');
        ?>
</strong>
						<div class="site-icon-crop-preview-homeicon">
							<img src="<?php 
        echo esc_url($url);
        ?>
" id="preview-homeicon" alt="<?php 
        esc_attr_e('Preview Home Icon');
        ?>
"/>
						</div>
					</div>
					<img src="<?php 
        echo esc_url($url);
        ?>
" id="crop-image" class="site-icon-crop-image" width="<?php 
        echo esc_attr($cropped_size[0]);
        ?>
" height="<?php 
        echo esc_attr($cropped_size[1]);
        ?>
" alt="<?php 
        esc_attr_e('Image to be cropped');
        ?>
"/>

					<input type="hidden" id="crop-x" name="crop-x" value="<?php 
        echo esc_attr($crop_x);
        ?>
" />
					<input type="hidden" id="crop-y" name="crop-y" value="<?php 
        echo esc_attr($crop_y);
        ?>
" />
					<input type="hidden" id="crop-width" name="crop-w" value="<?php 
        echo esc_attr($crop_size);
        ?>
" />
					<input type="hidden" id="crop-height" name="crop-h" value="<?php 
        echo esc_attr($crop_size);
        ?>
" />

					<input type="hidden" name="action" value="set_site_icon" />
					<input type="hidden" name="attachment_id" value="<?php 
        echo esc_attr($attachment_id);
        ?>
" />
					<input type="hidden" name="crop_ratio" value="<?php 
        echo esc_attr($crop_ratio);
        ?>
" />
					<?php 
        if (empty($_POST) && isset($_GET['file'])) {
            ?>
						<input type="hidden" name="create-new-attachment" value="true" />
					<?php 
        }
        ?>
					<?php 
        wp_nonce_field('set-site-icon');
        ?>

					<p class="submit">
						<?php 
        submit_button(__('Crop and Publish'), 'primary hide-if-no-js', 'submit', false);
        ?>
						<?php 
        submit_button(__('Publish'), 'primary hide-if-js', 'submit', false);
        ?>
						<a class="button secondary" href="options-general.php"><?php 
        _e('Cancel');
        ?>
</a>
					</p>
				</form>
			</div>
		</div>
	<?php 
    }
 /**
  * Add avatar to user custom field.
  * Also deletes previously selected avatar.
  *
  * @access public
  * @since 1.0.0
  * @return void
  */
 public static function add_avatar($user_data, $values, $user_id)
 {
     $avatar_field = $values['profile']['user_avatar'];
     if (!empty($avatar_field) && is_array($avatar_field)) {
         // Deletes previously selected avatar.
         $previous_avatar = get_user_meta($user_id, '_current_user_avatar_path', true);
         if ($previous_avatar) {
             wp_delete_file($previous_avatar);
         }
         update_user_meta($user_id, "current_user_avatar", esc_url($avatar_field['url']));
         update_user_meta($user_id, '_current_user_avatar_path', $avatar_field['path']);
     }
 }