public function actionSaveImage() { if (!empty($_POST['imageUrl'])) { $url = \parse_url($_POST['imageUrl']); if ($curlDescriptor = \curl_init($_POST['imageUrl'])) { \curl_setopt($curlDescriptor, CURLOPT_HEADER, 0); \curl_setopt($curlDescriptor, CURLOPT_RETURNTRANSFER, 1); \curl_setopt($curlDescriptor, CURLOPT_BINARYTRANSFER, 1); $rawImage = \curl_exec($curlDescriptor); \curl_close($curlDescriptor); if ($rawImage) { include_once ABSPATH . 'wp-admin/includes/image.php'; include_once ABSPATH . 'wp-admin/includes/file.php'; include_once ABSPATH . 'wp-admin/includes/media.php'; $wpFileType = \wp_check_filetype(\basename($url['path']), null); $tmpDir = \ini_get('upload_tmp_dir') ? \ini_get('upload_tmp_dir') : \sys_get_temp_dir(); $tempName = $tmpDir . '/' . \uniqid() . '.' . $wpFileType['ext']; \file_put_contents($tempName, $rawImage); $_FILES['async-upload'] = array('name' => \trim(\str_replace(' ', '', basename($tempName))), 'type' => $wpFileType['type'], 'tmp_name' => $tempName, 'error' => 0, 'size' => \filesize($tempName)); \media_handle_upload('async-upload', 0, array(), array('test_form' => false, 'action' => 'upload-attachment')); \wp_send_json(array('status' => 'success')); } } } \wp_send_json(array('status' => 'error')); }
public function process_async_upload() { header('Content-Type: text/html; charset=' . get_option('blog_charset')); if (!current_user_can('upload_files')) { wp_die(__('You do not have permission to upload files.')); } check_admin_referer($this->nonce_name); try { $attachment_id = media_handle_upload('async-upload', 0, [], ['mimes' => ['mp3|m4a' => 'audio/mpeg'], 'action' => $this->action]); $this->exception_if_error($attachment_id); require_once WPPPT_PLUGIN_PATH . '/migrations/functions.php'; $post_id = \WPPPT\create_new_post(get_post($attachment_id)); $this->exception_if_error($post_id); $podcast_id = intval($_REQUEST['podcast_id']); if (!empty($podcast_id)) { p2p_create_connection('podcast_clip_to_podcast', array('from' => $post_id, 'to' => $podcast_id)); } echo apply_filters('wpppt_async_upload', $attachment_id); } catch (\Exception $e) { echo '<div class="error-div error"> <a class="dismiss" href="#" onclick="jQuery(this).parents(\'div.media-item\').slideUp(200, function(){jQuery(this).remove();});">' . __('Dismiss') . '</a> <strong>' . sprintf(__('“%s” has failed to upload.'), esc_html($_FILES['async-upload']['name'])) . '</strong><br />' . esc_html($e->getMessage()) . '</div>'; exit; } }
function wpp_upload_image() { if (count($_FILES) === 1) { $filetype = $_FILES['image']['type']; $allowed = '/image\\/(?:jpeg|png)/'; if (preg_match($allowed, $filetype)) { if (!function_exists('wp_generate_attachment_metadata')) { require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; } foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { return "upload error : " . $_FILES[$file]['error']; } $attach_id = media_handle_upload($file, 0); } //check for errors if (is_wp_error($attach_id)) { echo 'false'; } else { echo $attach_id; } } else { _e('Please only use jpeg or png images!', 'wpp'); } } else { _e('Please select only ONE image!', 'wpp'); } wp_die(); //immediately end our ajax response }
/** * Faz a validação dos dados * */ function theme_options_validate_callback_function($input) { if (!empty($_FILES['logo']['name'])) { $allowed_file_types = array('jpg' => 'image/jpg', 'jpeg' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png'); if (!in_array($_FILES['logo']['type'], $allowed_file_types)) { wp_die(__('Sorry, this file type is not permitted for security reasons.')); } /* * O antigo wp_handle_upload( $_FILES[$field], array( 'test_form' => false ) ); foi substituído */ $upload = media_handle_upload('logo', 0); if ($upload) { $input['logo'] = $upload; } } else { if (isset($_POST['restore-default-image']) && $_POST['restore-default-image'] == 1) { unset($input['logo']); } else { $logo = get_theme_option('logo'); if (!empty($logo)) { $input['logo'] = get_theme_option('logo'); } } } return $input; }
/** * Uploads file * * @param string Key to $_FILES * @return int Attachment ID * * @abstract */ static function upload($file) { if (!isset($file)) { return; } $file = media_handle_upload($file, 0, array(), array('test_form' => false, 'mimes' => array('csv' => 'text/csv'))); return $file; }
/** * Upload file and return relevant attachment info * * @param string $value * @param int $field_id * @since 6.4 * @return array|int */ public function handle_file($value, $field_id) { $slug = get_post_meta($field_id, 'ccf_field_slug', true); $file_id = media_handle_upload('ccf_field_' . $slug, 0); if (is_wp_error($file_id)) { return 0; } $url = wp_get_attachment_url($file_id); return array('id' => $file_id, 'url' => $url, 'file_name' => basename($url)); }
function wplf_ajax_submit_handler() { $return = new stdClass(); $return->ok = 1; // allow user to pre-process the post fields do_action('wplf_pre_validate_submission'); // validate form fields // @see: wplf-form-validation.php $return = apply_filters('wplf_validate_submission', $return); if ($return->ok) { // form existence has already been validated via filters $form = get_post(intval($_POST['_form_id'])); // the title is the value of whatever the first field was in the form $title_format = get_post_meta($form->ID, '_wplf_title_format', true); // substitute the %..% tags with field values $post_title = $title_format; preg_match_all('/%(.+?)%/', $post_title, $toks); foreach ($toks[1] as $tok) { $replace = ''; if (array_key_exists($tok, $_POST)) { $replace = sanitize_text_field($_POST[$tok]); } $post_title = preg_replace('/%.+?%/', $replace, $post_title, 1); } // create submission post $post_id = wp_insert_post(array('post_title' => $post_title, 'post_status' => 'publish', 'post_type' => 'wplf-submission')); // add submission data as meta values foreach ($_POST as $key => $value) { if (!is_array($value)) { add_post_meta($post_id, $key, esc_html($value), true); } else { add_post_meta($post_id, $key, esc_html(json_encode($value)), true); } } // handle files foreach ($_FILES as $key => $file) { // Is this enough security wise? // Currenly only supports 1 file per input $attach_id = media_handle_upload($key, 0, array(), array("test_form" => false)); add_post_meta($post_id, $key, wp_get_attachment_url($attach_id)); add_post_meta($post_id, $key . "_attachment", $attach_id); } $return->submission_id = $post_id; $return->submission_title = $post_title; $return->form_id = $form->ID; // return the success message for the form $return->success = apply_filters('the_content', get_post_meta($form->ID, '_wplf_thank_you', true)); // allow user to attach custom actions after the submission has been received // these could be confirmation emails, additional processing for the submission fields, e.g. do_action('wplf_post_validate_submission', $return); } // respond with json wp_send_json($return); wp_die(); }
function anno_popup_images_iframe_html() { $errors = array(); if (isset($_POST['html-upload']) && !empty($_FILES)) { check_admin_referer('media-form'); // Upload File button was clicked $id = media_handle_upload('async-upload', $_REQUEST['post_id']); unset($_FILES); if (is_wp_error($id)) { $errors['upload_error'] = $id; $id = false; } } global $tab; $post_id = anno_get_post_id(); $attachments = get_posts(array('post_type' => 'attachment', 'posts_per_page' => -1, 'post_parent' => $post_id, 'post_mime_type' => 'image', 'order' => 'ASC')); ?> <body id="anno-popup-images"> <div id="anno-popup-images-inside" class="anno-mce-popup"> <div class="anno-mce-popup-fields"> <?php if (!empty($id)) { if (is_wp_error($id)) { echo '<div id="media-upload-error">' . esc_html($id->get_error_message()) . '</div>'; exit; } } ?> <table class="anno-images"> <thead> <tr> <th scope="col" class="img-list-img"></th> <th scope="col" class="img-list-title"></th> <th scope="col" class="img-list-actions"></th> </tr> </thead> <tbody id="media-items"> <?php foreach ($attachments as $attachment_key => $attachment) { anno_popup_images_row_display($attachment); anno_popup_images_row_edit($attachment); } ?> </tbody> </table> <?php anno_upload_form(); ?> </div> </body> <?php }
/** * Create or update pins. */ function mapasdevista_save_pins() { $error = array(); if (isset($_POST['submit_pin']) && $_POST['submit_pin'] === 'new') { if (isset($_FILES['pin_file']) && $_FILES['pin_file']['size'] > 0) { include ABSPATH . 'wp-admin/includes/file.php'; // para funcionar o include ABSPATH . 'wp-admin/includes/image.php'; // media_handle_upload include ABSPATH . 'wp-admin/includes/media.php'; // $r = media_handle_upload('pin_file', NULL); if (is_wp_error($r)) { function mapasdevista_save_pin_error_notice() { echo '<div class="error"><p>' . __('Could not create directory.') . '</p></div>'; } add_action('all_admin_notices', 'mapasdevista_save_pin_error_notice'); } else { update_post_meta($r, '_pin_anchor', array('x' => 0, 'y' => 0)); wp_redirect(add_query_arg(array('action' => 'edit', 'pin' => $r))); } } } elseif (isset($_POST['submit_pin']) && $_POST['submit_pin'] === 'edit') { if (isset($_GET['pin']) && is_numeric($_GET['pin'])) { $pin_id = intval(sprintf("%d", $_GET['pin'])); if (isset($_POST['pin_anchor']) && preg_match('/^([0-9]+),([0-9]+)$/', $_POST['pin_anchor'], $coords)) { $anchor = array('x' => intval($coords[1]), 'y' => intval($coords[2])); update_post_meta($pin_id, '_pin_anchor', $anchor); } if (isset($_POST['pin_clickable']) && $_POST['pin_clickable'] === 'no') { update_post_meta($pin_id, '_pin_clickable', 'no'); } else { delete_post_meta($pin_id, '_pin_clickable'); } wp_redirect(add_query_arg(array('action' => 'edit', 'pin' => $pin_id))); } } else { if (isset($_GET['action']) && $_GET['action'] === 'delete' && isset($_GET['pin'])) { if (isset($_GET['pin']) && is_numeric($_GET['pin'])) { $pin_id = intval(sprintf("%d", $_GET['pin'])); $pin = get_post($pin_id); if ($pin) { remove_pin($pin_id); wp_redirect(admin_url('admin.php?page=mapasdevista_pins_page&msg=pin-deleted')); die; } } wp_redirect(admin_url('admin.php?page=mapasdevista_pins_page&msg=pin-does-not-exist')); die; } } }
public function set_feautured_image($data, $item_id) { if ($item_id) { require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $this->attachment_id = media_handle_upload($data, $item_id); set_post_thumbnail($item_id, $this->attachment_id); } else { return false; } }
/** * Upload file and return relevant attachment info * * @param string $value * @param int $field_id * @since 6.4 * @return array|int */ public function handle_file($value, $field_id) { require_once trailingslashit(ABSPATH) . 'wp-admin/includes/file.php'; require_once trailingslashit(ABSPATH) . 'wp-admin/includes/image.php'; require_once trailingslashit(ABSPATH) . 'wp-admin/includes/media.php'; $slug = get_post_meta($field_id, 'ccf_field_slug', true); $file_id = media_handle_upload('ccf_field_' . $slug, 0); if (is_wp_error($file_id)) { return 0; } $url = wp_get_attachment_url($file_id); return array('id' => $file_id, 'url' => $url, 'file_name' => basename($url)); }
/** * <input type="file" name="my_image_upload" accept="image/jpeg,image/png,image/gif"/> * @return boolean/int */ public function upload() { require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; // Позволим WordPress перехвалить загрузку. // не забываем указать атрибут name поля input - 'my_image_upload' $attachment_id = media_handle_upload('my_image_upload', 0); if (is_wp_error($attachment_id)) { return FALSE; } else { return $attachment_id; } }
public function uploadImage($uploadname, $post_id = 0, $meta_key = false) { if (isset($_FILES[$uploadname]) && !empty($_FILES[$uploadname])) { require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $attachment_id = media_handle_upload($uploadname, $post_id); if (is_wp_error($attachment_id)) { do_action('Error_throw', array($uploadname => $attachment_id->get_error_message())); } elseif ($post_id > 0) { self::setImage($post_id, $attachment_id, $meta_key); } } }
public function attach() { $attachment_ids = array(); $original_files = $_FILES; /* * Get file upload global settings */ $multiple = get_option('rm_option_allow_multiple_file_uploads'); /* * Handling multiple attachments */ if ($multiple == "yes") { foreach ($_FILES as $f_name => $name) { // var_dump($f_name); $files = $_FILES[$f_name]; foreach ($files['name'] as $key => $value) { if ($files['name'][$key]) { $file = array('name' => $files['name'][$key], 'type' => $files['type'][$key], 'tmp_name' => $files['tmp_name'][$key], 'error' => $files['error'][$key], 'size' => $files['size'][$key]); $_FILES = array($f_name => $file); foreach ($_FILES as $file => $array) { $attach_id = $this->media_handle_attachment($file, 0); if (is_wp_error($attach_id)) { break; } else { $attachment_ids[$f_name][] = $attach_id; } } } $_FILES = $original_files; } } } else { /* * Handling single attachment */ foreach ($_FILES as $key => $file) { require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; $attach_id = media_handle_upload($key, 0); if (is_wp_error($attach_id)) { break; } else { $attachment_ids[$key] = $attach_id; } } } return $attachment_ids; }
public function upload_file() { require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; if ($_FILES) { foreach ($_FILES as $file => $array) { if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { echo "upload error : " . $_FILES[$file]['error']; die; } return media_handle_upload($file, 0); } } }
/** * Attach files to a ticket. * * @since 1.0 * @param arr $attachment $_FILES * @param int $ticket_id The ticket ID * @return int The attachment ID. */ function kbs_attach_file_to_ticket($attachment, $ticket_id) { if (!kbs_file_uploads_are_enabled()) { return false; } add_filter('upload_dir', 'kbs_set_upload_dir'); if ($_FILES[$attachment]['error'] !== UPLOAD_ERR_OK) { return false; } require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $attach_id = media_handle_upload($attachment, $ticket_id); return $attach_id; }
function insert_attachment($file_handler, $post_id, $setthumb = 'false') { // check to make sure its a successful upload if ($_FILES[$file_handler]['error'] !== UPLOAD_ERR_OK) { __return_false(); } require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; $attach_id = media_handle_upload($file_handler, $post_id); if ($setthumb) { update_post_meta($post_id, '_thumbnail_id', $attach_id); } return $attach_id; }
function callback($path = '', $blog_id = 0) { $blog_id = $this->api->switch_to_blog_and_validate_user($this->api->get_blog_id($blog_id)); if (is_wp_error($blog_id)) { return $blog_id; } if (!current_user_can('upload_files')) { return new WP_Error('unauthorized', 'User cannot upload media.', 403); } $input = $this->input(true); $has_media = isset($input['media']) && $input['media'] ? count($input['media']) : false; $has_media_urls = isset($input['media_urls']) && $input['media_urls'] ? count($input['media_urls']) : false; $media_ids = $files = $errors = array(); if ($has_media) { $this->api->trap_wp_die('upload_error'); foreach ($input['media'] as $index => $media_item) { $_FILES['.api.media.item.'] = $media_item; // check for WP_Error if we ever actually need $media_id $media_id = media_handle_upload('.api.media.item.', 0); if (is_wp_error($media_id)) { if (1 === count($input['media']) && !$has_media_urls) { unset($_FILES['.api.media.item.']); return $media_id; } $errors[$index]['error'] = $media_id->get_error_code(); $errors[$index]['message'] = $media_id->get_error_message(); } else { $media_ids[$index] = $media_id; } $files[] = $media_item; } $this->api->trap_wp_die(null); unset($_FILES['.api.media.item.']); } if ($has_media_urls) { foreach ($input['media_urls'] as $url) { $id = $this->handle_media_sideload($url); if (!empty($id) && is_int($id)) { $media_ids[] = $id; } } } $results = array(); foreach ($media_ids as $media_id) { $results[] = $this->get_media_item($media_id); } return array('media' => $results, 'errors' => $errors); }
public function zo_insert_image($input, $post_id) { if ($input) { foreach ($input as $file => $array) { if ($input[$file]['error'] !== UPLOAD_ERR_OK) { return "upload error."; } require_once ABSPATH . 'wp-admin/includes/image.php'; require_once ABSPATH . 'wp-admin/includes/file.php'; require_once ABSPATH . 'wp-admin/includes/media.php'; $attach_id = media_handle_upload($file, $post_id); update_post_meta($post_id, '_thumbnail_id', $attach_id); return $attach_id; } } }
/** * Upload a new file to an album (please check if a user has access, before calling this feature) * * @param $post_id * @param $file * @param $nr * * @return bool */ public function upload_file($post_id, $file, $nr) { if (false === current_user_can('edit_post', $post_id)) { $this->error = __('You are not allowed to edit posts and upload photos.', 'apg'); return false; } if ($_FILES[$file]['error'] !== UPLOAD_ERR_OK) { $this->error = __('There was an upload error. Is your uploads folder writable?', 'apg'); return false; } $attachment_id = media_handle_upload($file, $post_id); if (is_wp_error($attachment_id)) { $this->error = $attachment_id->get_error_message(); return false; } update_post_meta($post_id, '_apg_photos', $nr); return true; }
function addImage($fileId, $postId, $postType) { include_once ABSPATH . "wp-admin" . '/includes/image.php'; include_once ABSPATH . "wp-admin" . '/includes/file.php'; include_once ABSPATH . "wp-admin" . '/includes/media.php'; $post = get_post($postId); $imageTitle = $post->post_title . the_date('yyyymmdd') . the_time('hhmmss'); $response = media_handle_upload($fileId, $postId, array(title => $imageTitle)); if (gettype($response) == 'integer') { $urlImage = get_post_meta($response, '_wp_attached_file'); add_post_meta($postId, 'wpcf-imagenes', get_site_url() . '/wp-content/uploads/' . $urlImage[0]); //Guarda los ids de las imagenes relacionadas add_post_meta($postId, 'wpcf-ids-imagenes', $response); return true; } else { return $response; } }
function ajax_upload_user_company_logo() { $member = wp_get_current_user(); $res = null; if (!$member) { $res = array('status' => 'error', 'message' => 'restricted method'); } else { $image_id = media_handle_upload('user_company_logo', 0); if ($image_id) { update_user_meta($member->ID, 'user_company_logo', $image_id); $res = array('status' => 'ok', 'image' => str_replace(array('<', '>'), '', wp_get_attachment_image($image_id, 'logo'))); } else { $res = array('status' => 'error', 'message' => 'upload image error'); } } if (!$res) { $res = array('status' => 'error', 'message' => 'unkown error'); } die(json_encode($res)); }
public function menuImageSavePostAction($post_id, $post) { if (!empty($_FILES["menu-item-image_{$post_id}"])) { require_once ABSPATH . "wp-admin" . '/includes/image.php'; require_once ABSPATH . "wp-admin" . '/includes/file.php'; require_once ABSPATH . "wp-admin" . '/includes/media.php'; $attachment_id = media_handle_upload("menu-item-image_{$post_id}", $post_id); if ($attachment_id && is_int($attachment_id)) { set_post_thumbnail($post, $attachment_id); } } if (isset($_POST['menu_item_remove_image'][$post_id]) && !empty($_POST['menu_item_remove_image'][$post_id])) { $args = array('post_type' => 'attachment', 'post_status' => null, 'post_parent' => $post_id); $attachments = get_posts($args); if ($attachments) { foreach ($attachments as $attachment) { wp_delete_attachment($attachment->ID); } } } }
/** * Settings - replace default thumbnail */ function wp_rp_upload_default_thumbnail_file() { if (empty($_FILES['wp_rp_default_thumbnail'])) { return new WP_Error('upload_error'); } $file = $_FILES['wp_rp_default_thumbnail']; if (isset($file['error']) && $file['error'] === UPLOAD_ERR_NO_FILE) { return false; } if ($image_id = media_handle_upload('wp_rp_default_thumbnail', 0)) { $image_data = wp_rp_get_image_data($image_id); $platform_options = wp_rp_get_platform_options(); $img_width = $platform_options['custom_size_thumbnail_enabled'] ? $platform_options['custom_thumbnail_width'] : WP_RP_THUMBNAILS_WIDTH; $img_height = $platform_options['custom_size_thumbnail_enabled'] ? $platform_options['custom_thumbnail_height'] : WP_RP_THUMBNAILS_HEIGHT; if ($image = wp_rp_get_image_with_exact_size($image_data, array($img_width, $img_height))) { $upload_dir = wp_upload_dir(); return $upload_dir['url'] . '/' . $image['file']; } } return new WP_Error('upload_error'); }
/** * Modified from media_upload_file in WordPress 3.2.1 * {@internal Missing Short Description}} * * @since 2.5.0 * * @return unknown */ function s2sfu_media_upload_handler() { add_filter('media_upload_tabs', '__return_false'); add_filter('upload_dir', 's2sfu_upload_dir'); $errors = array(); $id = 0; if (isset($_POST['html-upload']) && !empty($_FILES)) { check_admin_referer('media-form'); // Upload File button was clicked $id = media_handle_upload('async-upload', $_REQUEST['post_id']); unset($_FILES); if (is_wp_error($id)) { $errors['upload_error'] = $id; $id = false; } //http://domain/?s2member_file_download= $filename = get_post_meta($id, '_wp_attached_file', true); $html = '<a href="' . site_url() . '/?s2member_file_download=' . $filename . '">' . $filename . '</a>'; return media_send_to_editor($html); } return wp_iframe('media_upload_type_s2sfu', 's2sfu', $errors, $id); }
} unset($current_user); require_once 'admin.php'; header('Content-Type: text/plain; charset=' . get_option('blog_charset')); if (!current_user_can('upload_files')) { wp_die(__('You do not have permission to upload files.')); } // just fetch the detail form for that attachment if (isset($_REQUEST['attachment_id']) && ($id = intval($_REQUEST['attachment_id'])) && $_REQUEST['fetch']) { if (2 == $_REQUEST['fetch']) { add_filter('attachment_fields_to_edit', 'media_single_attachment_fields_to_edit', 10, 2); echo get_media_item($id, array('send' => false, 'delete' => false)); } else { echo get_media_item($id); } exit; } check_admin_referer('media-form'); $id = media_handle_upload('async-upload', $_REQUEST['post_id']); if (is_wp_error($id)) { echo '<div id="media-upload-error">' . wp_specialchars($id->get_error_message()) . '</div>'; exit; } if ($_REQUEST['short']) { // short form response - attachment ID only echo $id; } else { // long form response - big chunk o html $type = $_REQUEST['type']; echo apply_filters("async_upload_{$type}", $id); }
/** * Update user meta. * * @param int $user_id */ public function update($user_id) { if (!empty($_FILES) && isset($_FILES[$this->name]) && !empty($_FILES[$this->name]['tmp_name'])) { $current_attachment_id = get_user_meta($user_id, $this->name, true); if ($current_attachment_id) { wp_delete_attachment($current_attachment_id); } $filetype = wp_check_filetype_and_ext($_FILES[$this->name]['tmp_name'], $_FILES[$this->name]['name']); if (!wp_match_mime_types('image', $filetype['type'])) { die; } $attachment_id = media_handle_upload($this->name, 0); if (!is_wp_error($attachment_id)) { update_user_meta($user_id, $this->name, $attachment_id); } } }
/** * Ajax handler for uploading attachments * * @since 3.3.0 */ function wp_ajax_upload_attachment() { check_ajax_referer('media-form'); /* * This function does not use wp_send_json_success() / wp_send_json_error() * as the html4 Plupload handler requires a text/html content-type for older IE. * See https://core.trac.wordpress.org/ticket/31037 */ if (!current_user_can('upload_files')) { echo wp_json_encode(array('success' => false, 'data' => array('message' => __('You do not have permission to upload files.'), 'filename' => $_FILES['async-upload']['name']))); wp_die(); } if (isset($_REQUEST['post_id'])) { $post_id = $_REQUEST['post_id']; if (!current_user_can('edit_post', $post_id)) { echo wp_json_encode(array('success' => false, 'data' => array('message' => __("You don't have permission to attach files to this post."), 'filename' => $_FILES['async-upload']['name']))); wp_die(); } } else { $post_id = null; } $post_data = isset($_REQUEST['post_data']) ? $_REQUEST['post_data'] : array(); // If the context is custom header or background, make sure the uploaded file is an image. if (isset($post_data['context']) && in_array($post_data['context'], array('custom-header', 'custom-background'))) { $wp_filetype = wp_check_filetype_and_ext($_FILES['async-upload']['tmp_name'], $_FILES['async-upload']['name']); if (!wp_match_mime_types('image', $wp_filetype['type'])) { echo wp_json_encode(array('success' => false, 'data' => array('message' => __('The uploaded file is not a valid image. Please try again.'), 'filename' => $_FILES['async-upload']['name']))); wp_die(); } } $attachment_id = media_handle_upload('async-upload', $post_id, $post_data); if (is_wp_error($attachment_id)) { echo wp_json_encode(array('success' => false, 'data' => array('message' => $attachment_id->get_error_message(), 'filename' => $_FILES['async-upload']['name']))); wp_die(); } if (isset($post_data['context']) && isset($post_data['theme'])) { if ('custom-background' === $post_data['context']) { update_post_meta($attachment_id, '_wp_attachment_is_custom_background', $post_data['theme']); } if ('custom-header' === $post_data['context']) { update_post_meta($attachment_id, '_wp_attachment_is_custom_header', $post_data['theme']); } } if (!($attachment = wp_prepare_attachment_for_js($attachment_id))) { wp_die(); } echo wp_json_encode(array('success' => true, 'data' => $attachment)); wp_die(); }
function upload_handler() { if ('POST' !== strtoupper($_SERVER['REQUEST_METHOD'])) { return new Jetpack_Error(405, get_status_header_desc(405), 405); } $user = wp_authenticate('', ''); if (!$user || is_wp_error($user)) { return new Jetpack_Error(403, get_status_header_desc(403), 403); } wp_set_current_user($user->ID); if (!current_user_can('upload_files')) { return new Jetpack_Error('cannot_upload_files', 'User does not have permission to upload files', 403); } if (empty($_FILES)) { return new Jetpack_Error('no_files_uploaded', 'No files were uploaded: nothing to process', 400); } foreach (array_keys($_FILES) as $files_key) { if (!isset($_POST["_jetpack_file_hmac_{$files_key}"])) { return new Jetpack_Error('missing_hmac', 'An HMAC for one or more files is missing', 400); } } $media_keys = array_keys($_FILES['media']); $token = Jetpack_Data::get_access_token(get_current_user_id()); if (!$token || is_wp_error($token)) { return new Jetpack_Error('unknown_token', 'Unknown Jetpack token', 403); } $uploaded_files = array(); $global_post = isset($GLOBALS['post']) ? $GLOBALS['post'] : null; unset($GLOBALS['post']); foreach ($_FILES['media']['name'] as $index => $name) { $file = array(); foreach ($media_keys as $media_key) { $file[$media_key] = $_FILES['media'][$media_key][$index]; } list($hmac_provided, $salt) = explode(':', $_POST['_jetpack_file_hmac_media'][$index]); $hmac_file = hash_hmac_file('sha1', $file['tmp_name'], $salt . $token->secret); if ($hmac_provided !== $hmac_file) { $uploaded_files[$index] = (object) array('error' => 'invalid_hmac', 'error_description' => 'The corresponding HMAC for this file does not match'); continue; } $_FILES['.jetpack.upload.'] = $file; $post_id = isset($_POST['post_id'][$index]) ? absint($_POST['post_id'][$index]) : 0; if (!current_user_can('edit_post', $post_id)) { $post_id = 0; } $attachment_id = media_handle_upload('.jetpack.upload.', $post_id, array(), array('action' => 'jetpack_upload_file')); if (!$attachment_id) { $uploaded_files[$index] = (object) array('error' => 'unknown', 'error_description' => 'An unknown problem occurred processing the upload on the Jetpack site'); } elseif (is_wp_error($attachment_id)) { $uploaded_files[$index] = (object) array('error' => 'attachment_' . $attachment_id->get_error_code(), 'error_description' => $attachment_id->get_error_message()); } else { $attachment = get_post($attachment_id); $uploaded_files[$index] = (object) array('id' => (string) $attachment_id, 'file' => $attachment->post_title, 'url' => wp_get_attachment_url($attachment_id), 'type' => $attachment->post_mime_type, 'meta' => wp_get_attachment_metadata($attachment_id)); } } if (!is_null($global_post)) { $GLOBALS['post'] = $global_post; } return $uploaded_files; }
public function save_pdf_data($pos_id) { if (!wp_verify_nonce($_POST['wp_pdf_attachment_nonce'], plugin_basename(__FILE__))) { return $pos_id; } if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) { return $pos_id; } if ('page' == $_POST['post_type']) { if (!current_user_can('edit_page', $pos_id)) { return $pos_id; } } else { if (!current_user_can('edit_page', $pos_id)) { return $pos_id; } } if (!empty($_FILES['wp_pdf_attachment']['name'])) { $types = array('application/pdf'); $files = wp_check_filetype(basename($_FILES['wp_pdf_attachment']['name'])); // return array $uploaded_types = $files['type']; if (in_array($uploaded_type, $types)) { $upload = media_handle_upload("wp_pdf_attachment", $pos_id, file_get_contents($_FILES['wp_pdf_attachment']['tmp_name'])); if (isset($upload['error']) && $upload['error'] != 0) { wp_die('Error: ' . $upload['error']); } else { add_post_meta($pos_id, 'wp_pdf_attachment', $upload); update_post_meta($pos_id, 'wp_pdf_attachment', $upload); } } else { wp_die("The file type that you've uploaded is not a PDF."); } } }