Exemple #1
0
/**
 * Handle importer uploading and add attachment.
 *
 * @since 2.0.0
 *
 * @return array Uploaded file's details on success, error message on failure
 */
function nxt_import_handle_upload()
{
    if (!isset($_FILES['import'])) {
        $file['error'] = __('File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini or by post_max_size being defined as smaller than upload_max_filesize in php.ini.');
        return $file;
    }
    $overrides = array('test_form' => false, 'test_type' => false);
    $_FILES['import']['name'] .= '.txt';
    $file = nxt_handle_upload($_FILES['import'], $overrides);
    if (isset($file['error'])) {
        return $file;
    }
    $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' => 'import', 'post_status' => 'private');
    // Save the data
    $id = nxt_insert_attachment($object, $file);
    // schedule a cleanup for one day from now in case of failed import or missing nxt_import_cleanup() call
    nxt_schedule_single_event(time() + 86400, 'importer_scheduled_cleanup', array($id));
    return array('file' => $file, 'id' => $id);
}
Exemple #2
0
/**
 * 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;
}
Exemple #3
0
/**
 * Update a post with new post data.
 *
 * The date does not have to be set for drafts. You can set the date and it will
 * not be overridden.
 *
 * @since 1.0.0
 *
 * @param array|object $postarr Post data. Arrays are expected to be escaped, objects are not.
 * @return int 0 on failure, Post ID on success.
 */
function nxt_update_post($postarr = array())
{
    if (is_object($postarr)) {
        // non-escaped post was passed
        $postarr = get_object_vars($postarr);
        $postarr = add_magic_quotes($postarr);
    }
    // First, get all of the original fields
    $post = nxt_get_single_post($postarr['ID'], ARRAY_A);
    // Escape data pulled from DB.
    $post = add_magic_quotes($post);
    // Passed post category list overwrites existing category list if not empty.
    if (isset($postarr['post_category']) && is_array($postarr['post_category']) && 0 != count($postarr['post_category'])) {
        $post_cats = $postarr['post_category'];
    } else {
        $post_cats = $post['post_category'];
    }
    // Drafts shouldn't be assigned a date unless explicitly done so by the user
    if (isset($post['post_status']) && in_array($post['post_status'], array('draft', 'pending', 'auto-draft')) && empty($postarr['edit_date']) && '0000-00-00 00:00:00' == $post['post_date_gmt']) {
        $clear_date = true;
    } else {
        $clear_date = false;
    }
    // Merge old and new fields with new fields overwriting old ones.
    $postarr = array_merge($post, $postarr);
    $postarr['post_category'] = $post_cats;
    if ($clear_date) {
        $postarr['post_date'] = current_time('mysql');
        $postarr['post_date_gmt'] = '';
    }
    if ($postarr['post_type'] == 'attachment') {
        return nxt_insert_attachment($postarr);
    }
    return nxt_insert_post($postarr);
}
Exemple #4
0
 /**
  * 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));
                 }
             }
         }
     }
 }
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));
}
 function __construct($form, $urlholder)
 {
     if (empty($_FILES[$form]['name']) && empty($_GET[$urlholder])) {
         nxt_die(__('Please select a file'));
     }
     //Handle a newly uploaded file, Else assume its already been uploaded
     if (!empty($_FILES)) {
         $overrides = array('test_form' => false, 'test_type' => false);
         $file = nxt_handle_upload($_FILES[$form], $overrides);
         if (isset($file['error'])) {
             nxt_die($file['error']);
         }
         $this->filename = $_FILES[$form]['name'];
         $this->package = $file['file'];
         // Construct the object array
         $object = array('post_title' => $this->filename, 'post_content' => $file['url'], 'post_mime_type' => $file['type'], 'guid' => $file['url'], 'context' => 'upgrader', 'post_status' => 'private');
         // Save the data
         $this->id = nxt_insert_attachment($object, $file['file']);
         // schedule a cleanup for 2 hours from now in case of failed install
         nxt_schedule_single_event(time() + 7200, 'upgrader_scheduled_cleanup', array($this->id));
     } elseif (is_numeric($_GET[$urlholder])) {
         // Numeric Package = previously uploaded file, see above.
         $this->id = (int) $_GET[$urlholder];
         $attachment = get_post($this->id);
         if (empty($attachment)) {
             nxt_die(__('Please select a file'));
         }
         $this->filename = $attachment->post_title;
         $this->package = get_attached_file($attachment->ID);
     } else {
         // Else, It's set to something, Back compat for plugins using the old (pre-3.3) File_Uploader handler.
         if (!(($uploads = nxt_upload_dir()) && false === $uploads['error'])) {
             nxt_die($uploads['error']);
         }
         $this->filename = $_GET[$urlholder];
         $this->package = $uploads['basedir'] . '/' . $this->filename;
     }
 }
Exemple #7
0
 /**
  * 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&#8217; 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;
 }
 /**
  * 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;
 }