function express_uploadFile($args) { global $nxtdb; global $nxt_xmlrpc_server; $blog_ID = (int) $args[0]; $username = $nxtdb->escape($args[1]); $password = $nxtdb->escape($args[2]); $data = $args[3]; $name = sanitize_file_name($data['name']); $type = $data['type']; $bits = $data['bits']; logIO('O', '(MW) Received ' . strlen($bits) . ' bytes'); if (!($user = $nxt_xmlrpc_server->login($username, $password))) { return $nxt_xmlrpc_server->error; } do_action('xmlrpc_call', 'metaWeblog.newMediaObject'); if (!current_user_can('upload_files')) { logIO('O', '(MW) User does not have upload_files capability'); return new IXR_Error(401, __('You are not allowed to upload files to this site.', 'woothemes')); } if ($upload_err = apply_filters("pre_upload_error", false)) { return new IXR_Error(500, $upload_err); } if (!empty($data["overwrite"]) && $data["overwrite"] == true) { // Get postmeta info on the object. $old_file = $nxtdb->get_row("\n\t\t\tSELECT ID\n\t\t\tFROM {$nxtdb->posts}\n\t\t\tWHERE post_title = '{$name}'\n\t\t\t\tAND post_type = 'attachment'\n\t\t"); // Delete previous file. nxt_delete_attachment($old_file->ID); // Make sure the new name is different by pre-pending the // previous post id. $filename = preg_replace("/^nxtid\\d+-/", "", $name); $name = "nxtid{$old_file->ID}-{$filename}"; } $upload = nxt_upload_bits($name, $type, $bits); if (!empty($upload['error'])) { $errorString = sprintf(__('Could not write file %1$s (%2$s)', 'woothemes'), $name, $upload['error']); logIO('O', '(MW) ' . $errorString); return new IXR_Error(500, $errorString); } // Construct the attachment array // attach to post_id 0 $post_id = 0; $attachment = array('post_title' => $name, 'post_content' => '', 'post_type' => 'attachment', 'post_parent' => $post_id, 'post_mime_type' => $type, 'guid' => $upload['url']); // Save the data $id = nxt_insert_attachment($attachment, $upload['file'], $post_id); nxt_update_attachment_metadata($id, nxt_generate_attachment_metadata($id, $upload['file'])); return apply_filters('nxt_handle_upload', array('file' => $name, 'url' => $upload['url'], 'type' => $type, 'id' => $id)); }
/** * This handles a sideloaded file in the same way as an uploaded file is handled by {@link media_handle_upload()} * * @since 2.6.0 * * @param array $file_array Array similar to a {@link $_FILES} upload array * @param int $post_id The post ID the media is associated with * @param string $desc Description of the sideloaded file * @param array $post_data allows you to overwrite some of the attachment * @return int|object The ID of the attachment or a nxt_Error on failure */ function media_handle_sideload($file_array, $post_id, $desc = null, $post_data = array()) { $overrides = array('test_form' => false); $file = nxt_handle_sideload($file_array, $overrides); if (isset($file['error'])) { return new nxt_Error('upload_error', $file['error']); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $title = preg_replace('/\\.[^.]+$/', '', basename($file)); $content = ''; // use image exif/iptc data for title and caption defaults if possible if ($image_meta = @nxt_read_image_metadata($file)) { if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) { $title = $image_meta['title']; } if (trim($image_meta['caption'])) { $content = $image_meta['caption']; } } if (isset($desc)) { $title = $desc; } // Construct the attachment array $attachment = array_merge(array('post_mime_type' => $type, 'guid' => $url, 'post_parent' => $post_id, 'post_title' => $title, 'post_content' => $content), $post_data); // This should never be set as it would then overwrite an existing attachment. if (isset($attachment['ID'])) { unset($attachment['ID']); } // Save the attachment metadata $id = nxt_insert_attachment($attachment, $file, $post_id); if (!is_nxt_error($id)) { nxt_update_attachment_metadata($id, nxt_generate_attachment_metadata($id, $file)); } return $id; }
$post = get_post_to_edit($post_id); if (post_type_supports($post_type, 'comments')) { nxt_enqueue_script('admin-comments'); enqueue_comment_hotkeys_js(); } include './edit-form-advanced.php'; break; case 'editattachment': check_admin_referer('update-attachment_' . $post_id); // Don't let these be changed unset($_POST['guid']); $_POST['post_type'] = 'attachment'; // Update the thumbnail filename $newmeta = nxt_get_attachment_metadata($post_id, true); $newmeta['thumb'] = $_POST['thumb']; nxt_update_attachment_metadata($post_id, $newmeta); case 'editpost': check_admin_referer('update-' . $post_type . '_' . $post_id); $post_id = edit_post(); redirect_post($post_id); // Send user on their way while we keep working exit; break; case 'trash': check_admin_referer('trash-' . $post_type . '_' . $post_id); $post =& get_post($post_id); if (!current_user_can($post_type_object->cap->delete_post, $post_id)) { nxt_die(__('You are not allowed to move this item to the Trash.')); } if (!nxt_trash_post($post_id)) { nxt_die(__('Error in moving to Trash.'));
/** * Imports library * * @param integer $limit * @param integer $offset * @param integer $count * @param integer $total * @param array $results * @return boolean */ function import_library($limit, $offset, &$count, &$total, &$results) { global $nxtdb; $count = 0; $total = 0; $results = array(); $upload_info = w3_upload_info(); $uploads_use_yearmonth_folders = get_option('uploads_use_yearmonth_folders'); $document_root = w3_get_document_root(); @set_time_limit($this->_config->get_integer('timelimit.cdn_import')); if ($upload_info) { /** * Search for posts with links or images */ $sql = sprintf('SELECT ID, post_content, post_date FROM %sposts WHERE post_status = "publish" AND (post_type = "post" OR post_type = "page") AND (post_content LIKE "%%src=%%" OR post_content LIKE "%%href=%%") ', $nxtdb->prefix); if ($limit) { $sql .= sprintf(' LIMIT %d', $limit); if ($offset) { $sql .= sprintf(' OFFSET %d', $offset); } } $posts = $nxtdb->get_results($sql); if ($posts) { $count = count($posts); $total = $this->get_import_posts_count(); $regexp = '~(' . $this->get_regexp_by_mask($this->_config->get_string('cdn.import.files')) . ')$~'; $import_external = $this->_config->get_boolean('cdn.import.external'); foreach ($posts as $post) { $matches = null; $replaced = array(); $attachments = array(); $post_content = $post->post_content; /** * Search for all link and image sources */ if (preg_match_all('~(href|src)=[\'"]?([^\'"<>\\s]+)[\'"]?~', $post_content, $matches, PREG_SET_ORDER)) { foreach ($matches as $match) { list($search, $attribute, $origin) = $match; /** * Check if $search is already replaced */ if (isset($replaced[$search])) { continue; } $error = ''; $result = false; $src = w3_normalize_file_minify($origin); $dst = ''; /** * Check if file exists in the library */ if (stristr($origin, $upload_info['baseurl']) === false) { /** * Check file extension */ $check_src = $src; if (w3_is_url($check_src)) { $qpos = strpos($check_src, '?'); if ($qpos !== false) { $check_src = substr($check_src, 0, $qpos); } } if (preg_match($regexp, $check_src)) { /** * Check for already uploaded attachment */ if (isset($attachments[$src])) { list($dst, $dst_url) = $attachments[$src]; $result = true; } else { if ($uploads_use_yearmonth_folders) { $upload_subdir = date('Y/m', strtotime($post->post_date)); $upload_dir = sprintf('%s/%s', $upload_info['basedir'], $upload_subdir); $upload_url = sprintf('%s/%s', $upload_info['baseurl'], $upload_subdir); } else { $upload_subdir = ''; $upload_dir = $upload_info['basedir']; $upload_url = $upload_info['baseurl']; } $src_filename = pathinfo($src, PATHINFO_FILENAME); $src_extension = pathinfo($src, PATHINFO_EXTENSION); /** * Get available filename */ for ($i = 0;; $i++) { $dst = sprintf('%s/%s%s%s', $upload_dir, $src_filename, $i ? $i : '', $src_extension ? '.' . $src_extension : ''); if (!file_exists($dst)) { break; } } $dst_basename = basename($dst); $dst_url = sprintf('%s/%s', $upload_url, $dst_basename); $dst_path = ltrim(str_replace($document_root, '', w3_path($dst)), '/'); if ($upload_subdir) { w3_mkdir($upload_subdir, 0777, $upload_info['basedir']); } $download_result = false; /** * Check if file is remote URL */ if (w3_is_url($src)) { /** * Download file */ if ($import_external) { $download_result = w3_download($src, $dst); if (!$download_result) { $error = 'Unable to download file'; } } else { $error = 'External file import is disabled'; } } else { /** * Otherwise copy file from local path */ $src_path = $document_root . '/' . urldecode($src); if (file_exists($src_path)) { $download_result = @copy($src_path, $dst); if (!$download_result) { $error = 'Unable to copy file'; } } else { $error = 'Source file doesn\'t exists'; } } /** * Check if download or copy was successful */ if ($download_result) { require_once W3TC_INC_DIR . '/functions/mime.php'; $title = $dst_basename; $guid = ltrim($upload_info['baseurlpath'] . $title, ','); $mime_type = w3_get_mime_type($dst); @($GLOBALS['nxt_rewrite'] =& new nxt_Rewrite()); /** * Insert attachment */ $id = nxt_insert_attachment(array('post_mime_type' => $mime_type, 'guid' => $guid, 'post_title' => $title, 'post_content' => '', 'post_parent' => $post->ID), $dst); if (!is_nxt_error($id)) { /** * Generate attachment metadata and upload to CDN */ require_once ABSPATH . 'nxt-admin/includes/image.php'; nxt_update_attachment_metadata($id, nxt_generate_attachment_metadata($id, $dst)); $attachments[$src] = array($dst, $dst_url); $result = true; } else { $error = 'Unable to insert attachment'; } } } /** * If attachment was successfully created then replace links */ if ($result) { $replace = sprintf('%s="%s"', $attribute, $dst_url); // replace $search with $replace $post_content = str_replace($search, $replace, $post_content); $replaced[$search] = $replace; $error = 'OK'; } } else { $error = 'File type rejected'; } } else { $error = 'File already exists in the media library'; } /** * Add new entry to the log file */ $results[] = array('src' => $src, 'dst' => $dst_path, 'result' => $result, 'error' => $error); } } /** * If post content was chenged then update DB */ if ($post_content != $post->post_content) { nxt_update_post(array('ID' => $post->ID, 'post_content' => $post_content)); } } } } }
/** * Display third step of custom header image page. * * @since 2.1.0 */ function step_3() { check_admin_referer('custom-header-crop-image'); if (!current_theme_supports('custom-header-uploads')) { nxt_die(__('Cheatin’ uh?')); } 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); $cropped = nxt_crop_image($attachment_id, (int) $_POST['x1'], (int) $_POST['y1'], (int) $_POST['width'], (int) $_POST['height'], HEADER_IMAGE_WIDTH, HEADER_IMAGE_HEIGHT); if (is_nxt_error($cropped)) { nxt_die(__('Image could not be processed. Please go back and try again.'), __('Image Processing Error')); } $cropped = apply_filters('nxt_create_file_in_uploads', $cropped, $attachment_id); // For replication $parent = get_post($attachment_id); $parent_url = $parent->guid; $url = str_replace(basename($parent_url), basename($cropped), $parent_url); // Construct the object array $object = array('ID' => $attachment_id, 'post_title' => basename($cropped), 'post_content' => $url, 'post_mime_type' => 'image/jpeg', 'guid' => $url, 'context' => 'custom-header'); // Update the attachment nxt_insert_attachment($object, $cropped); nxt_update_attachment_metadata($attachment_id, nxt_generate_attachment_metadata($attachment_id, $cropped)); update_post_meta($attachment_id, '_nxt_attachment_is_custom_header', get_option('stylesheet')); set_theme_mod('header_image', $url); // cleanup $medium = str_replace(basename($original), 'midsize-' . basename($original), $original); @unlink(apply_filters('nxt_delete_file', $medium)); @unlink(apply_filters('nxt_delete_file', $original)); return $this->finished(); }
function woo_tumblog_file_upload() { global $nxtdb; //Upload overrides $filename = $_FILES['userfile']; // [name] [tmp_name] $override['test_form'] = false; $override['action'] = 'nxt_handle_upload'; //Handle Uploaded File $uploaded_file = nxt_handle_upload($filename, $override); // [file] [url] [type] //Create Attachment Object $attachment['post_title'] = $filename['name']; //post_title, post_content (the value for this key should be the empty string), post_status and post_mime_type $attachment['post_content'] = ''; $attachment['post_status'] = 'inherit'; $attachment['post_mime_type'] = $uploaded_file['type']; $attachment['guid'] = $uploaded_file['url']; //Prepare file attachment $wud = nxt_upload_dir(); // [path] [url] [subdir] [basedir] [baseurl] [error] $filename_attach = $wud['basedir'] . $uploaded_file['file']; //Insert Attachment $attach_id = nxt_insert_attachment($attachment, $filename_attach, 0); $attach_data = nxt_generate_attachment_metadata($attach_id, $filename_attach); nxt_update_attachment_metadata($attach_id, $attach_data); //Handle Errors and Response if (!empty($uploaded_file['error'])) { echo 'Upload Error: ' . $uploaded_file['error']; } else { echo $uploaded_file['url'] . '|' . $attach_id . '|'; } // Is the Response }
/** * Handle an Image upload for the background image. * * @since 3.0.0 */ function handle_upload() { if (empty($_FILES)) { return; } check_admin_referer('custom-background-upload', '_nxtnonce-custom-background-upload'); $overrides = array('test_form' => false); $file = nxt_handle_upload($_FILES['import'], $overrides); if (isset($file['error'])) { nxt_die($file['error']); } $url = $file['url']; $type = $file['type']; $file = $file['file']; $filename = basename($file); // Construct the object array $object = array('post_title' => $filename, 'post_content' => $url, 'post_mime_type' => $type, 'guid' => $url, 'context' => 'custom-background'); // Save the data $id = nxt_insert_attachment($object, $file); // Add the meta-data nxt_update_attachment_metadata($id, nxt_generate_attachment_metadata($id, $file)); update_post_meta($id, '_nxt_attachment_is_custom_background', get_option('stylesheet')); set_theme_mod('background_image', esc_url($url)); $thumbnail = nxt_get_attachment_image_src($id, 'thumbnail'); set_theme_mod('background_image_thumb', esc_url($thumbnail[0])); do_action('nxt_create_file_in_uploads', $file, $id); // For replication $this->updated = true; }
function nxt_save_image($post_id) { $return = new stdClass(); $success = $delete = $scaled = $nocrop = false; $post = get_post($post_id); @ini_set('memory_limit', apply_filters('admin_memory_limit', nxt_MAX_MEMORY_LIMIT)); $img = load_image_to_edit($post_id, $post->post_mime_type); if (!is_resource($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) { $sX = imagesx($img); $sY = imagesy($img); // 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 $dst = nxt_imagecreatetruecolor($fwidth, $fheight); if (imagecopyresampled($dst, $img, 0, 0, 0, 0, $fwidth, $fheight, $sX, $sY)) { imagedestroy($img); $img = $dst; $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(stripslashes($_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 = nxt_get_attachment_metadata($post_id); $backup_sizes = get_post_meta($post->ID, '_nxt_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 (!nxt_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 = update_attached_file($post_id, $new_path); $meta['file'] = _nxt_relative_upload_path($new_path); $meta['width'] = imagesx($img); $meta['height'] = imagesy($img); list($uwidth, $uheight) = nxt_constrain_dimensions($meta['width'], $meta['height'], 128, 96); $meta['hwstring_small'] = "height='{$uheight}' width='{$uwidth}'"; 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)) { 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]; } } $crop = $nocrop ? false : get_option("{$size}_crop"); $resized = image_make_intermediate_size($new_path, get_option("{$size}_size_w"), get_option("{$size}_size_h"), $crop); if ($resized) { $meta['sizes'][$size] = $resized; } else { unset($meta['sizes'][$size]); } } } if ($success) { nxt_update_attachment_metadata($post_id, $meta); update_post_meta($post_id, '_nxt_attachment_backup_sizes', $backup_sizes); if ($target == 'thumbnail' || $target == 'all' || $target == 'full') { $file_url = nxt_get_attachment_url($post_id); if ($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) { $delpath = apply_filters('nxt_delete_file', $new_path); @unlink($delpath); } imagedestroy($img); $return->msg = esc_js(__('Image saved')); return $return; }
/** * If fetching attachments is enabled then attempt to create a new attachment * * @param array $post Attachment post details from WXR * @param string $url URL to fetch attachment from * @return int|nxt_Error Post ID on success, nxt_Error otherwise */ function process_attachment($post, $url) { if (!$this->fetch_attachments) { return new nxt_Error('attachment_processing_error', __('Fetching attachments is not enabled', 'nxtclass-importer')); } // if the URL is absolute, but does not contain address, then upload it assuming base_site_url if (preg_match('|^/[\\w\\W]+$|', $url)) { $url = rtrim($this->base_url, '/') . $url; } $upload = $this->fetch_remote_file($url, $post); if (is_nxt_error($upload)) { return $upload; } if ($info = nxt_check_filetype($upload['file'])) { $post['post_mime_type'] = $info['type']; } else { return new nxt_Error('attachment_processing_error', __('Invalid file type', 'nxtclass-importer')); } $post['guid'] = $upload['url']; // as per nxt-admin/includes/upload.php $post_id = nxt_insert_attachment($post, $upload['file']); nxt_update_attachment_metadata($post_id, nxt_generate_attachment_metadata($post_id, $upload['file'])); // remap resized image URLs, works by stripping the extension and remapping the URL stub. if (preg_match('!^image/!', $info['type'])) { $parts = pathinfo($url); $name = basename($parts['basename'], ".{$parts['extension']}"); // PATHINFO_FILENAME in PHP 5.2 $parts_new = pathinfo($upload['url']); $name_new = basename($parts_new['basename'], ".{$parts_new['extension']}"); $this->url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new; } return $post_id; }