private static function handle_upload(&$file)
 {
     global $ESS_Notices;
     $file = apply_filters('wp_handle_upload_prefilter', $file);
     if (isset($file['error']) && !is_numeric($file['error']) && $file['error']) {
         $ESS_Notices->add_error($file['error']);
     }
     $time = current_time('mysql');
     extract(wp_check_filetype_and_ext($file['tmp_name'], $file['name'], false));
     $ext = !$ext ? $file['mime'] : ltrim(strrchr($file['name'], '.'), '.');
     $type = !$type ? $file['type'] : $type;
     if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
         $ESS_Notices->add_error(sprintf(__('Sorry, this file type is not permitted for security reasons (%s or %s).'), $type, $ext));
     }
     if (!(($uploads = wp_upload_dir($time)) && $uploads['error'] === false)) {
         $ESS_Notices->add_error($uploads['error']);
     }
     //var_dump( $uploads );
     //echo "ABSPATH: ". ABSPATH;
     $filename = wp_unique_filename($uploads['path'], $file['name'], null);
     // Move the file to the uploads dir
     $new_file = $uploads['path'] . "/" . $filename . "." . $ext;
     //if ( move_uploaded_file( $file['tmp_name'], $new_file ) === false )
     if (rename($file['tmp_name'], $new_file) === false) {
         $ESS_Notices->add_error(sprintf(__('The uploaded file could not be moved to %s.'), strpos($uploads['basedir'], ABSPATH) === 0 ? str_replace(ABSPATH, '', $uploads['basedir']) . $uploads['subdir'] : basename($uploads['basedir']) . $uploads['subdir']));
     }
     // Set correct file permissions
     $stat = stat(dirname($new_file));
     $perms = $stat['mode'] & 0666;
     @chmod($new_file, $perms);
     if (is_multisite()) {
         delete_transient('dirsize_cache');
     }
     return apply_filters('wp_handle_upload', array('file' => $new_file, 'url' => $uploads['url'] . "/" . $filename . "." . $ext, 'type' => $type), 'upload');
 }
Пример #2
0
/**
 * Force download of certain file types via ?download=path/filename.type
 *
 * This prompts "Save As" -- handy for MP3, PDF, etc. Only works on local files.
 *
 * This information was useful: http://wordpress.stackexchange.com/questions/3480/how-can-i-force-a-file-download-in-the-wordpress-backend
 *
 * Use add_theme_support( 'ctfw_force_downloads' );
 *
 * @since 0.9
 * @global object $wp_query
 * @global object $wp_filesystem;
 */
function ctfw_force_download()
{
    global $wp_query, $wp_filesystem;
    // Theme supports this?
    if (!current_theme_supports('ctfw-force-downloads')) {
        return;
    }
    // Check if this URL is a request for file download
    if (is_front_page() && !empty($_GET['download'])) {
        // relative file path
        $relative_file_path = ltrim($_GET['download'], '/');
        // remove preceding slash, if any
        // check for directory traversal attack
        if (!validate_file($relative_file_path)) {
            // false means it passed validation
            // path to file in uploads folder (only those can be downloaded)
            $upload_dir = wp_upload_dir();
            $upload_file_path = $upload_dir['basedir'] . '/' . $relative_file_path;
            // file exists in uploads folder?
            if (file_exists($upload_file_path)) {
                // make sure file valid as upload (valid type, extension, etc.)
                $validate = wp_check_filetype_and_ext($upload_file_path, basename($upload_file_path));
                if ($validate['type'] && $validate['ext']) {
                    // empty if type not in upload_mimes, doesn't exist, etc.
                    // headers to prompt "save as"
                    $filename = basename($upload_file_path);
                    $filesize = filesize($upload_file_path);
                    header('Content-Type: application/octet-stream', true, 200);
                    // replace WordPress 404 Not Found with 200 Okay
                    header('Content-Disposition: attachment; filename=' . $filename);
                    header('Expires: 0');
                    header('Cache-Control: must-revalidate');
                    header('Pragma: public');
                    header('Content-Length: ' . $filesize);
                    // clear buffering just in case
                    @ob_end_clean();
                    flush();
                    // Prepare to use WP_Filesystem
                    /* See comments below
                    			if ( ! class_exists( 'WP_Filesystem_Base') ) {
                    				require_once ABSPATH . 'wp-admin/includes/file.php';
                    			}
                    			WP_Filesystem();
                    			*/
                    // Output file contents using Direct method
                    // readfile more efficient; WP_Filesystem security used, causes Theme Check warning
                    //echo $wp_filesystem->get_contents( $upload_file_path );
                    @readfile($upload_file_path);
                    // we're done, stop further execution
                    exit;
                }
            }
        }
        // failure of any type results in 404 file not found
        $wp_query->set_404();
        status_header(404);
    }
}
 /**
  * Constructs instance of Document.
  *
  * @param WP_Post $attachment Attachment object used to initalize fields.
  * @param DG_Gallery $gallery Instance of Gallery class.
  */
 public function __construct($attachment, $gallery)
 {
     // init general document data
     $this->gallery = $gallery;
     $this->description = wptexturize($attachment->post_content);
     $this->ID = $attachment->ID;
     $this->link = $gallery->linkToAttachmentPg() ? get_attachment_link($attachment->ID) : wp_get_attachment_url($attachment->ID);
     $this->title = wptexturize($attachment->post_title);
     $this->title_attribute = esc_attr(strip_tags($this->title));
     $this->path = get_attached_file($attachment->ID);
     $wp_filetype = wp_check_filetype_and_ext($this->path, basename($this->path));
     $this->extension = $wp_filetype['ext'];
     $this->size = size_format(filesize($this->path));
 }
 function file_info($file)
 {
     if (!@is_uploaded_file($file['tmp_name'])) {
         return "something went wrong in the upload process";
     }
     if (!($file['size'] > 0)) {
         return "the file is empty. Please upload something more substantial";
     }
     $file_info = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], false);
     if (!($file_info['type'] && $file_info['ext']) && !current_user_can('unfiltered_upload')) {
         return "the file type is not permitted for security reasons";
     }
     $file['type'] = $file_info['type'];
     $file['ext'] = $file_info['ext'];
     return $file;
 }
Пример #5
0
/**
 * Upload import file
 *
 * @since 0.3
 */
function wie_upload_import_file()
{
    // Check nonce for security since form was posted
    if (!empty($_POST) && !empty($_FILES['wie_import_file']) && check_admin_referer('wie_import', 'wie_import_nonce')) {
        // check_admin_referer prints fail page and dies
        // Uploaded file
        $uploaded_file = $_FILES['wie_import_file'];
        // Check file type
        // This will also fire if no file uploaded
        $wp_filetype = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name'], false);
        if ('wie' != $wp_filetype['ext'] && !wp_match_mime_types('wie', $wp_filetype['type'])) {
            wp_die(__('You must upload a <b>.wie</b> file generated by this plugin.', 'widget-importer-exporter'), '', array('back_link' => true));
        }
        // Check and move file to uploads dir, get file data
        // Will show die with WP errors if necessary (file too large, quota exceeded, etc.)
        $overrides = array('test_form' => false);
        $file_data = wp_handle_upload($uploaded_file, $overrides);
        if (isset($file_data['error'])) {
            wp_die($file_data['error'], '', array('back_link' => true));
        }
        // Process import file
        wie_process_import_file($file_data['file']);
    }
}
Пример #6
0
 /**
  * Upload the file to be cropped in the second step.
  *
  * @since 4.3.0
  */
 public function handle_upload()
 {
     $uploaded_file = $_FILES['site-icon'];
     $file_type = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name']);
     if (!wp_match_mime_types('image', $file_type['type'])) {
         wp_die(__('The uploaded file is not a valid image. Please try again.'));
     }
     $file = wp_handle_upload($uploaded_file, array('test_form' => false));
     if (isset($file['error'])) {
         wp_die($file['error'], __('Image Upload 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' => 'site-icon');
     // Save the data
     $attachment_id = wp_insert_attachment($object, $file);
     return compact('attachment_id', 'file', 'filename', 'url', 'type');
 }
Пример #7
0
function wppb_resize_avatar($userID, $userlisting_size = null, $userlisting_crop = null)
{
    // include the admin image API
    require_once ABSPATH . '/wp-admin/includes/image.php';
    // retrieve first a list of all the current custom fields
    $wppb_manage_fields = get_option('wppb_manage_fields');
    foreach ($wppb_manage_fields as $key => $value) {
        if ($value['field'] == 'Avatar') {
            // retrieve width and height of the image
            $width = $height = '';
            //this checks if it only has 1 component
            if (is_numeric($value['avatar-size'])) {
                $width = $height = $value['avatar-size'];
            } else {
                //this checks if the entered value has 2 components
                $sentValue = explode(',', $value['avatar-size']);
                $width = $sentValue[0];
                $height = $sentValue[1];
            }
            $width = !empty($userlisting_size) ? $userlisting_size : $width;
            $height = !empty($userlisting_size) ? $userlisting_size : $height;
            if (!strpos(get_user_meta($userID, 'resized_avatar_' . $value['id'], true), $width . 'x' . $height)) {
                // retrieve the original image (in original size)
                $avatar_directory_path = get_user_meta($userID, 'avatar_directory_path_' . $value['id'], true);
                $image = wp_get_image_editor($avatar_directory_path);
                if (!is_wp_error($image)) {
                    do_action('wppb_before_avatar_resizing', $image, $userID, $value['meta-name'], $value['avatar-size']);
                    $crop = apply_filters('wppb_avatar_crop_resize', !empty($userlisting_crop) ? $userlisting_crop : false);
                    $resize = $image->resize($width, $height, $crop);
                    if ($resize !== FALSE) {
                        do_action('wppb_avatar_resizing', $image, $resize);
                        $fileType = apply_filters('wppb_resized_file_extension', 'png');
                        $wp_upload_array = wp_upload_dir();
                        // Array of key => value pairs
                        //create file(name); both with directory and url
                        $fileName_dir = $image->generate_filename(NULL, $wp_upload_array['basedir'] . '/profile_builder/avatars/', $fileType);
                        if (PHP_OS == "WIN32" || PHP_OS == "WINNT") {
                            $fileName_dir = str_replace('\\', '/', $fileName_dir);
                        }
                        $fileName_url = str_replace(str_replace('\\', '/', $wp_upload_array['basedir']), $wp_upload_array['baseurl'], $fileName_dir);
                        //save the newly created (resized) avatar on the disc
                        $saved_image = $image->save($fileName_dir);
                        /* the image save sometimes doesn't save with the desired extension so we need to see with what extension it saved it with and
                           if it differs replace the extension	in the path and url that we save as meta */
                        $validate_saved_image = wp_check_filetype_and_ext($saved_image['path'], $saved_image['path']);
                        $ext = substr($fileName_dir, strrpos($fileName_dir, '.', -1), strlen($fileName_dir));
                        if (!empty($validate_saved_image['ext']) && $validate_saved_image['ext'] != $ext) {
                            $fileName_url = str_replace($ext, '.' . $validate_saved_image['ext'], $fileName_url);
                            $fileName_dir = str_replace($ext, '.' . $validate_saved_image['ext'], $fileName_dir);
                        }
                        update_user_meta($userID, 'resized_avatar_' . $value['id'], $fileName_url);
                        update_user_meta($userID, 'resized_avatar_' . $value['id'] . '_relative_path', $fileName_dir);
                        do_action('wppb_after_avatar_resizing', $image, $fileName_dir, $fileName_url);
                    }
                }
            }
        }
    }
}
Пример #8
0
/**
 * 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();
}
Пример #9
0
 $ret = array();
 if (class_exists('finfo')) {
     $finfo = new finfo();
     $fileinfo = $finfo->file($_FILES["userpro_file"]["tmp_name"], FILEINFO_MIME_TYPE);
 } else {
     $fileinfo = $_FILES['userpro_file']['type'];
 }
 $accepted_file_mime_types = array('image/gif', 'image/jpg', 'image/jpeg', 'image/png', 'application/pdf', 'application/zip', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/msword', 'text/plain', 'audio/wav', 'audio/mp3', 'audio/mp4');
 $file_extension = strtolower(strrchr($_FILES["userpro_file"]["name"], "."));
 if (!in_array($file_extension, array('.gif', '.jpg', '.jpeg', '.png', '.pdf', '.txt', '.zip', '.doc', '.docx', '.wav', '.mp3', '.mp4')) || !in_array($fileinfo, $accepted_file_mime_types)) {
     $ret['status'] = 0;
     echo json_encode($ret);
     die;
 } else {
     if (!is_array($_FILES["userpro_file"]["name"])) {
         $wp_filetype = wp_check_filetype_and_ext($_FILES["userpro_file"]["tmp_name"], $_FILES["userpro_file"]["name"]);
         $ext = empty($wp_filetype['ext']) ? '' : $wp_filetype['ext'];
         $type = empty($wp_filetype['type']) ? '' : $wp_filetype['type'];
         $proper_filename = empty($wp_filetype['proper_filename']) ? '' : $wp_filetype['proper_filename'];
         if ($proper_filename) {
             $file['name'] = $proper_filename;
         }
         if (!$type || !$ext) {
             die;
         }
         if (!$type) {
             $type = $file['type'];
         }
         $unique_id = uniqid();
         $ret = array();
         $target_file = $userpro->get_uploads_dir() . $unique_id . $file_extension;
Пример #10
0
function wp_ajax_upload_attachment()
{
    check_ajax_referer('media-form');
    if (!current_user_can('upload_files')) {
        wp_die();
    }
    if (isset($_REQUEST['post_id'])) {
        $post_id = $_REQUEST['post_id'];
        if (!current_user_can('edit_post', $post_id)) {
            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'], false);
        if (!wp_match_mime_types('image', $wp_filetype['type'])) {
            echo 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 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 json_encode(array('success' => true, 'data' => $attachment));
    wp_die();
}
 /**
  * Handle uploading of the files
  *
  * @since 0.4
  *
  * @uses media_handle_sideload
  *
  * @param int  $post_id Parent post id
  * @return array Combined result of media ids and errors if any
  */
 function _upload_files($post_id = 0)
 {
     $media_ids = $errors = array();
     // Bail if there are no files
     if (empty($_FILES)) {
         return false;
     }
     // File field name could be user defined, so we just get the first file
     $files = current($_FILES);
     // There can be multiple files
     // So we need to iterate over each of the files to process
     for ($i = 0; $i < count($files['name']); $i++) {
         $fields = array('name', 'type', 'tmp_name', 'error', 'size');
         foreach ($fields as $field) {
             $k[$field] = $files[$field][$i];
         }
         $k['name'] = sanitize_file_name($k['name']);
         // Skip to the next file if upload went wrong
         if ($k['tmp_name'] == "") {
             continue;
         }
         $typecheck = wp_check_filetype_and_ext($k['tmp_name'], $k['name'], false);
         // Add an error message if MIME-type is not allowed
         if (!in_array($typecheck['type'], (array) $this->allowed_mime_types)) {
             $errors['fu-disallowed-mime-type'][] = array('name' => $k['name'], 'mime' => $k['type']);
             continue;
         }
         // Setup some default values
         // However, you can make additional changes on 'fu_after_upload' action
         $caption = '';
         // Try to set post caption if the field is set on request
         // Fallback to post_content if the field is not set
         if (isset($_POST['caption'])) {
             $caption = sanitize_text_field($_POST['caption']);
         } elseif (isset($_POST['post_content'])) {
             $caption = sanitize_text_field($_POST['post_content']);
         }
         // TODO: remove or refactor
         $filename = !empty($this->settings['default_file_name']) ? $this->settings['default_file_name'] : pathinfo($k['name'], PATHINFO_FILENAME);
         $post_overrides = array('post_status' => $this->_is_public() ? 'publish' : 'private', 'post_title' => isset($_POST['post_title']) && !empty($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : sanitize_text_field($filename), 'post_content' => empty($caption) ? __('Unnamed', 'frontend-uploader') : $caption, 'post_excerpt' => empty($caption) ? __('Unnamed', 'frontend-uploader') : $caption);
         // Trying to upload the file
         $upload_id = media_handle_sideload($k, (int) $post_id, $post_overrides['post_title'], $post_overrides);
         if (!is_wp_error($upload_id)) {
             $media_ids[] = $upload_id;
         } else {
             $errors['fu-error-media'][] = $k['name'];
         }
     }
     /**
      * $success determines the rest of upload flow
      * Setting this to true if no errors were produced even if there's was no files to upload
      */
     $success = empty($errors) ? true : false;
     if ($success) {
         foreach ($media_ids as $media_id) {
             $this->_save_post_meta_fields($media_id);
         }
     }
     // Allow additional setup
     // Pass array of attachment ids
     do_action('fu_after_upload', $media_ids, $success, $post_id);
     return array('success' => $success, 'media_ids' => $media_ids, 'errors' => $errors);
 }
Пример #12
0
 /**
  * Handle an Image upload for the background image.
  *
  * @since 3.0.0
  */
 public function handle_upload()
 {
     if (empty($_FILES)) {
         return;
     }
     check_admin_referer('custom-background-upload', '_wpnonce-custom-background-upload');
     $overrides = array('test_form' => false);
     $uploaded_file = $_FILES['import'];
     $wp_filetype = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name']);
     if (!wp_match_mime_types('image', $wp_filetype['type'])) {
         wp_die(__('The uploaded file is not a valid image. Please try again.'));
     }
     $file = wp_handle_upload($uploaded_file, $overrides);
     if (isset($file['error'])) {
         wp_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 = wp_insert_attachment($object, $file);
     // Add the meta-data
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file));
     update_post_meta($id, '_wp_attachment_is_custom_background', get_option('stylesheet'));
     set_theme_mod('background_image', esc_url_raw($url));
     $thumbnail = wp_get_attachment_image_src($id, 'thumbnail');
     set_theme_mod('background_image_thumb', esc_url_raw($thumbnail[0]));
     /** This action is documented in wp-admin/custom-header.php */
     do_action('wp_create_file_in_uploads', $file, $id);
     // For replication
     $this->updated = true;
 }
 /**
  * Handle uploading of the files
  *
  * @since 0.4
  *
  * @uses media_handle_sideload
  *
  * @param int  $post_id Parent post id
  * @return array Combined result of media ids and errors if any
  */
 function _upload_files($post_id = 0)
 {
     // Only filter mimes just before the upload
     add_filter('upload_mimes', array($this, '_get_mime_types'), 999);
     $media_ids = $errors = array();
     // Bail if there are no files
     if (empty($_FILES)) {
         return array();
     }
     // File field name could be user defined, so we just get the first file
     $files = current($_FILES);
     // There can be multiple files
     // So we need to iterate over each of the files to process
     for ($i = 0; $i < count($files['name']); $i++) {
         $fields = array('name', 'type', 'tmp_name', 'error', 'size');
         foreach ($fields as $field) {
             $k[$field] = $files[$field][$i];
         }
         $k['name'] = sanitize_file_name($k['name']);
         //
         if ($k['error'] === 4) {
             continue;
         }
         // Skip to the next file if upload went wrong
         if ($k['error'] !== 0) {
             $errors['fu-error-media'][] = array('name' => $k['name'], 'code' => $k['error']);
             continue;
         }
         $typecheck = wp_check_filetype_and_ext($k['tmp_name'], $k['name'], false);
         // Add an error message if MIME-type is not allowed
         if (!in_array($typecheck['type'], (array) $this->allowed_mime_types)) {
             $errors['fu-disallowed-mime-type'][] = array('name' => $k['name'], 'mime' => $k['type']);
             continue;
         }
         // Now let's try to catch eval( base64() ) et al
         if (0 !== $this->_invoke_paranoia_on_file_contents(file_get_contents($k['tmp_name']))) {
             $errors['fu-suspicious-file'][] = array('name' => $k['name']);
             continue;
         }
         // Setup some default values
         // However, you can make additional changes on 'fu_after_upload' action
         $caption = '';
         // Try to set post caption if the field is set on request
         // Fallback to post_content if the field is not set
         if (isset($_POST['caption'])) {
             $caption = sanitize_text_field($_POST['caption']);
         } elseif (isset($_POST['post_content'])) {
             $caption = sanitize_text_field($_POST['post_content']);
         }
         $filename = pathinfo($k['name'], PATHINFO_FILENAME);
         $post_overrides = array('post_status' => $this->_is_public() ? 'publish' : 'private', 'post_title' => isset($_POST['post_title']) && !empty($_POST['post_title']) ? sanitize_text_field($_POST['post_title']) : sanitize_text_field($filename), 'post_content' => empty($caption) ? __('Unnamed', 'frontend-uploader') : $caption, 'post_excerpt' => empty($caption) ? __('Unnamed', 'frontend-uploader') : $caption);
         $m = $k;
         // Obfuscate filename if setting is present
         if (isset($this->settings['obfuscate_file_name']) && 'on' == $this->settings['obfuscate_file_name']) {
             $fn = explode('.', $k['name']);
             $m['name'] = uniqid(mt_rand(1, 1000), true) . '.' . end($fn);
         }
         // Trying to upload the file
         $upload_id = media_handle_sideload($m, (int) $post_id, $post_overrides['post_title'], $post_overrides);
         if (!is_wp_error($upload_id)) {
             $media_ids[] = $upload_id;
         } else {
             $errors['fu-error-media'][] = $k['name'];
         }
     }
     /**
      * $success determines the rest of upload flow
      * Setting this to true if no errors were produced even if there's was no files to upload
      */
     $success = empty($errors) ? true : false;
     if ($success) {
         foreach ($media_ids as $media_id) {
             $this->_save_post_meta_fields($media_id);
         }
     }
     // Allow additional setup
     // Pass array of attachment ids
     do_action('fu_after_upload', $media_ids, $success, $post_id);
     return array('success' => $success, 'media_ids' => $media_ids, 'errors' => $errors);
 }
Пример #14
0
 public static function check_type_and_ext($file, $file_name = '')
 {
     if (empty($file_name)) {
         $file_name = $file['name'];
     }
     $tmp_name = $file['tmp_name'];
     // Whitelist the mime type and extension
     $wp_filetype = wp_check_filetype_and_ext($tmp_name, $file_name);
     $ext = empty($wp_filetype['ext']) ? '' : $wp_filetype['ext'];
     $type = empty($wp_filetype['type']) ? '' : $wp_filetype['type'];
     $proper_filename = empty($wp_filetype['proper_filename']) ? '' : $wp_filetype['proper_filename'];
     if ($proper_filename) {
         return new WP_Error('invalid_file', esc_html__('There was an problem while verifying your file.'));
     }
     if (!$ext) {
         return new WP_Error('illegal_extension', esc_html__('Sorry, this file extension is not permitted for security reasons.'));
     }
     if (!$type) {
         return new WP_Error('illegal_type', esc_html__('Sorry, this file type is not permitted for security reasons.'));
     }
     return true;
 }
Пример #15
0
function ewf_import_uploadFile()
{
    // check_admin_referer prints fail page and dies
    if (!empty($_POST) && !empty($_FILES['ewf_import_file']) && check_admin_referer('ewf_import', 'ewf_import_nonce')) {
        $uploaded_file = $_FILES['ewf_import_file'];
        $uploaded_file_type = wp_check_filetype_and_ext($uploaded_file['tmp_name'], $uploaded_file['name']);
        if ('txt' != $uploaded_file_type['ext'] && !wp_match_mime_types('txt', $uploaded_file_type['type'])) {
            echo '<div>' . '<strong>' . 'Error: ' . '</strong>' . 'You must upload a <b>.txt</b> file.' . '</div>';
            return false;
        }
        $uploaded_file_data = wp_handle_upload($uploaded_file, array('test_form' => false));
        if (isset($uploaded_file_data['error'])) {
            echo '<div>' . '<strong>' . 'Error: ' . '</strong>' . $uploaded_file_data['error'] . '</div>';
            return false;
        }
        // echo '<pre>';
        // print_r( $uploaded_file_data );
        // echo '</pre>';
        // }else{
        // echo '<div>'.'<strong>'.'Error: '.'</strong>'.'Something went wrong!'.'</div>';
    }
}
 /**
  * Install routine
  * All of the heavy lifting happens here
  */
 public function do_install()
 {
     // Don't time out
     set_time_limit(0);
     // Don't abort the site in a bad state if the connection drops
     ignore_user_abort(true);
     // Ask the API what to do
     $result = $this->api->get_setup_instructions($_POST['site_type'], $_POST['theme_slug']);
     if (is_wp_error($result)) {
         wp_die(__('There was a problem fetching the data', 'gd_quicksetup'));
     } else {
         $result = json_decode($result['body'], true);
     }
     // Start the installation process
     do_action('gd_quicksetup_install');
     // Install plugins
     $this->_current_plugin_options = array();
     $plugin_installer_skin = new GD_QuickSetup_Installer_Skin();
     $plugin_installer = new GD_QuickSetup_Plugin_Upgrader($plugin_installer_skin);
     do_action('gd_quicksetup_install_plugins');
     foreach ((array) $result['plugins'] as $plugin) {
         $this->_current_plugin_options = isset($plugin['options']) ? $plugin['options'] : array();
         $this->flush();
         $plugin_installer->install($plugin['url']);
         $plugin_installer->activate_plugin($plugin['slug']);
         $this->flush();
     }
     do_action('gd_quicksetup_install_plugins_done');
     // Theme
     do_action('gd_quicksetup_install_theme');
     $this->_current_theme_options = isset($result['theme']['options']) ? $result['theme']['options'] : array();
     $theme_installer_skin = new GD_QuickSetup_Installer_Skin();
     $theme_installer = new GD_QuickSetup_Theme_Upgrader($theme_installer_skin);
     $this->flush();
     $theme_installer->install($result['theme']['url']);
     $this->flush();
     $theme_installer->switch_theme($result['theme']['stylesheet']);
     do_action('gd_quicksetup_install_theme_done');
     // Content
     do_action('gd_quicksetup_install_content');
     // Start the menu at 30
     // home = 10
     // gallery = 20
     // location = 700
     // contact = 800
     // blog = 999
     $menu = 30;
     // Create pages
     $this->flush();
     foreach ((array) $_POST['type'] as $k => $v) {
         if (!$_POST['enabled'][$k] || 'false' === $_POST['enabled'][$k]) {
             continue;
         }
         if ('page' === $v) {
             if (!isset($_POST['title'][$k]) || empty($_POST['title'][$k])) {
                 $title = __('Untitled', 'gd_quicksetup');
             } else {
                 $title = $_POST['title'][$k];
             }
             $pageid = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => wp_kses($_POST['content'][$k], wp_kses_allowed_html('post')), 'post_name' => sanitize_title($title), 'post_title' => strip_tags($title), 'post_type' => 'page', 'post_status' => 'publish', 'menu_order' => $_POST['home'][$k] ? 10 : ($menu += 10)));
             if ($_POST['home'][$k] && 0 !== strcasecmp($_POST['home'][$k], 'false')) {
                 update_option('show_on_front', 'page');
                 update_option('page_on_front', $pageid);
             }
         }
     }
     $this->flush();
     // Create gallery
     $this->flush();
     foreach ((array) $_POST['type'] as $k => $v) {
         if (!$_POST['enabled'][$k] || 'false' === $_POST['enabled'][$k]) {
             continue;
         }
         if ('gallery' === $v) {
             $gallery_ids = array();
             foreach ($_FILES as $k2 => $v2) {
                 if (0 === strpos($k2, 'upload_image_' . $k . '_') && is_uploaded_file($_FILES[$k2]['tmp_name'])) {
                     // Check mime type, only allow "image/*" files
                     $info = wp_check_filetype_and_ext($_FILES[$k2]['tmp_name'], $_FILES[$k2]['name']);
                     if (isset($info['type']) && 0 === stripos($info['type'], 'image/')) {
                         $id = media_handle_upload($k2, 0);
                         if (!is_wp_error($id) && is_numeric($id)) {
                             $gallery_ids[] = $id;
                         }
                     }
                 }
             }
             if (empty($gallery_ids)) {
                 continue;
             }
             $pageid = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => '[gallery ids="' . implode(',', $gallery_ids) . '"]', 'post_name' => __('gallery', 'gd_quicksetup'), 'post_title' => __('Gallery', 'gd_quicksetup'), 'post_type' => 'page', 'post_status' => 'publish', 'menu_order' => 20));
             if ($_POST['home'][$k] && 0 !== strcasecmp($_POST['home'][$k], 'false')) {
                 update_option('show_on_front', 'page');
                 update_option('page_on_front', $pageid);
             }
         }
     }
     $this->flush();
     // Create blog post
     $this->flush();
     foreach ((array) $_POST['type'] as $k => $v) {
         if (!$_POST['enabled'][$k] || 'false' === $_POST['enabled'][$k]) {
             continue;
         }
         if ('blog' === $v) {
             if (!isset($_POST['title'][$k]) || empty($_POST['title'][$k])) {
                 $title = __('Untitled', 'gd_quicksetup');
             } else {
                 $title = $_POST['title'][$k];
             }
             wp_insert_post(array('post_content' => wp_kses($_POST['content'][$k], wp_kses_allowed_html('post')), 'post_name' => sanitize_title($title), 'post_title' => strip_tags($title), 'post_type' => 'post', 'post_status' => 'publish'));
             if ('page' === get_option('show_on_front', 'page')) {
                 $pageid = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_content' => '', 'post_name' => __('blog', 'gd_quicksetup'), 'post_title' => __('Blog', 'gd_quicksetup'), 'post_type' => 'page', 'post_status' => 'publish', 'menu_order' => 999));
                 update_option('page_for_posts', $pageid);
             }
         }
     }
     $this->flush();
     do_action('gd_quicksetup_install_content_done');
     // Done
     do_action('gd_quicksetup_install_done');
     // Stash $_POST in a fake transient (needed for communicating with the install_after_done action
     // we can't use a real transient because of volatility with the database and object cache after
     // resetting the site
     update_option('gd_quicksetup_last_post', $_POST);
     // Save the response as a fake transient so the theme skin (and any other options) can be switched
     // (deleted after ajax call is done, we don't need it for longer than that)
     set_transient('gd_quicksetup_last_api_response', $result, 3600);
     // "Done" Flag
     update_option('gd_quicksetup_wizard_complete', time());
 }
Пример #17
0
/**
 * Clone of wp_handle_upload function
 * with this function, we allowed to define the upload_path and upload_url
 */
function wip_handle_upload(&$file, $overrides = false, $time = null, $upload_path = "", $upload_url = "")
{
    // The default error handler.
    if (!function_exists('wip_handle_upload_error')) {
        function wip_handle_upload_error(&$file, $message)
        {
            return array('error' => $message);
        }
    }
    $file = apply_filters('wp_handle_upload_prefilter', $file);
    // You may define your own function and pass the name in $overrides['upload_error_handler']
    $upload_error_handler = 'wip_handle_upload_error';
    // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file.  Handle that gracefully.
    if (isset($file['error']) && !is_numeric($file['error']) && $file['error']) {
        return $upload_error_handler($file, $file['error']);
    }
    // You may define your own function and pass the name in $overrides['unique_filename_callback']
    $unique_filename_callback = null;
    // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
    $action = 'wip_handle_upload';
    // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
    $upload_error_strings = array(false, __("The uploaded file exceeds the upload_max_filesize directive in php.ini.", 'wip'), __("The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.", 'wip'), __("The uploaded file was only partially uploaded.", 'wip'), __("No file was uploaded.", 'wip'), '', __("Missing a temporary folder.", 'wip'), __("Failed to write file to disk.", 'wip'), __("File upload stopped by extension.", 'wip'));
    // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
    $test_form = true;
    $test_size = true;
    $test_upload = true;
    // If you override this, you must provide $ext and $type!!!!
    $test_type = true;
    $mimes = false;
    // Install user overrides. Did we mention that this voids your warranty?
    if (is_array($overrides)) {
        extract($overrides, EXTR_OVERWRITE);
    }
    // A correct form post will pass this test.
    if ($test_form && (!isset($_POST['action']) || $_POST['action'] != $action)) {
        return call_user_func($upload_error_handler, $file, __('Invalid form submission.', 'wip'));
    }
    // A successful upload will pass this test. It makes no sense to override this one.
    if ($file['error'] > 0) {
        return call_user_func($upload_error_handler, $file, $upload_error_strings[$file['error']]);
    }
    // A non-empty file will pass this test.
    if ($test_size && !($file['size'] > 0)) {
        if (is_multisite()) {
            $error_msg = __('File is empty. Please upload something more substantial.', 'wip');
        } else {
            $error_msg = __('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.', 'wip');
        }
        return call_user_func($upload_error_handler, $file, $error_msg);
    }
    // A properly uploaded file will pass this test. There should be no reason to override this one.
    if ($test_upload && !@is_uploaded_file($file['tmp_name'])) {
        return call_user_func($upload_error_handler, $file, __('Specified file failed upload test.', 'wip'));
    }
    // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
    if ($test_type) {
        $wp_filetype = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $mimes);
        extract($wp_filetype);
        // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
        if ($proper_filename) {
            $file['name'] = $proper_filename;
        }
        if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
            return call_user_func($upload_error_handler, $file, __('Sorry, this file type is not permitted for security reasons.', 'wip'));
        }
        if (!$ext) {
            $ext = ltrim(strrchr($file['name'], '.'), '.');
        }
        if (!$type) {
            $type = $file['type'];
        }
    } else {
        $type = '';
    }
    // A writable uploads dir will pass this test. Again, there's no point overriding this one.
    if (!(($uploads = wip_check_upload_dir($upload_path)) && false === $uploads['error'])) {
        return call_user_func($upload_error_handler, $file, $uploads['error']);
    }
    $filename = wp_unique_filename($upload_path, $file['name'], $unique_filename_callback);
    $tmp_file = wp_tempnam($filename, $upload_path);
    // Move the file to the uploads dir
    if (false === @move_uploaded_file($file['tmp_name'], $tmp_file)) {
        return $upload_error_handler($file, sprintf(__('The uploaded file could not be moved to %s.', 'wip'), $upload_path));
    }
    // Copy the temporary file into its destination
    $new_file = $upload_path . "/{$filename}";
    copy($tmp_file, $new_file);
    unlink($tmp_file);
    // Set correct file permissions
    $stat = stat(dirname($new_file));
    $perms = $stat['mode'] & 0666;
    @chmod($new_file, $perms);
    // Compute the URL
    $url = $upload_url . "/{$filename}";
    if (is_multisite()) {
        delete_transient('dirsize_cache');
    }
    $throwed = array('file' => $new_file, 'url' => $url, 'type' => $type, 'filename' => $filename);
    return $throwed;
}
Пример #18
0
 /**
  * AJAX behavior to process uploaded files intended as digital downloads
  *
  * Handles processing a file upload from a temporary file to a
  * the correct storage container (DB, file system, etc)
  *
  * @author Jonathan Davis
  * @return string JSON encoded result with DB id, filename, type & size
  **/
 public static function downloads()
 {
     $error = false;
     if (isset($_FILES['Filedata']['error'])) {
         $error = $_FILES['Filedata']['error'];
     }
     if ($error) {
         die(json_encode(array('error' => Lookup::errors('uploads', $error))));
     }
     if (!@is_uploaded_file($_FILES['Filedata']['tmp_name'])) {
         die(json_encode(array('error' => Shopp::__('The file could not be saved because the upload was not found on the server.'))));
     }
     if (0 == $_FILES['Filedata']['size']) {
         die(json_encode(array('error' => Shopp::__('The file could not be saved because the uploaded file is empty.'))));
     }
     FileAsset::mimetypes();
     // Save the uploaded file
     $File = new ProductDownload();
     $File->parent = 0;
     $File->context = "price";
     $File->type = "download";
     $File->name = $_FILES['Filedata']['name'];
     $File->filename = $File->name;
     list($extension, $mimetype, $properfile) = wp_check_filetype_and_ext($_FILES['Filedata']['tmp_name'], $File->name);
     if (empty($mimetype)) {
         $mimetype = 'application/octet-stream';
     }
     $File->mime = $mimetype;
     if (!empty($properfile)) {
         $File->name = $File->filename = $properfile;
     }
     $File->size = filesize($_FILES['Filedata']['tmp_name']);
     $File->store($_FILES['Filedata']['tmp_name'], 'upload');
     $Error = ShoppErrors()->code('storage_engine_save');
     if (!empty($Error)) {
         die(json_encode(array('error' => $Error->message(true))));
     }
     $File->save();
     do_action('add_product_download', $File, $_FILES['Filedata']);
     echo json_encode(array('id' => $File->id, 'name' => stripslashes($File->name), 'type' => $File->mime, 'size' => $File->size));
 }
Пример #19
0
 /**
  * Checks if the file extension matches its mimetype, returns a modified
  * filename if they don't match.
  *
  * @param string $path_to_file
  * @param string $filename
  *
  * @return string - modified filename if the extension did not match the mimetype,
  * otherwise returns the filename that was passed to it
  */
 protected function properImageExtension($path_to_file, $filename)
 {
     $mimes = array('jpg|jpeg|jpe' => 'image/jpeg', 'gif' => 'image/gif', 'png' => 'image/png');
     // Attempt to determine the real file type of a file.
     $validate = wp_check_filetype_and_ext($path_to_file, $filename, $mimes);
     // change filename to the extension that matches its mimetype
     if (false !== $validate['proper_filename']) {
         return $validate['proper_filename'];
     } else {
         return $filename;
     }
 }
Пример #20
0
 public static function add_to_media_library($file, $args = array())
 {
     if (is_bool($args)) {
         $args = array('move_to_uploads' => false);
     }
     $default_args = array('move_to_uploads' => true, 'url' => null, 'type' => null, 'name' => null, 'title' => null, 'content' => null, 'attachment_id' => null);
     $args = array_merge($default_args, $args);
     if (is_null($args['name'])) {
         $args['name'] = basename($file);
     }
     if (is_null($args['type'])) {
         $wp_filetype = wp_check_filetype_and_ext($file, $file);
         if (false !== $wp_filetype['proper_filename']) {
             $args['name'] = $wp_filetype['proper_filename'];
         }
         if (false !== $wp_filetype['type']) {
             $args['type'] = $wp_filetype['type'];
         } else {
             $args['type'] = '';
         }
     }
     if (true === $args['move_to_uploads']) {
         $uploads = wp_upload_dir();
         if (!is_array($uploads) || false !== $uploads['error']) {
             return false;
         }
         $filename = wp_unique_filename($uploads['path'], $args['name']);
         $new_file = "{$uploads['path']}/{$filename}";
         if (false === @copy($file, $new_file)) {
             return false;
         }
         $stat = stat(dirname($new_file));
         $perms = $stat['mode'] & 0666;
         @chmod($new_file, $perms);
         $args['url'] = "{$uploads['url']}/{$filename}";
         $file = $new_file;
         if (is_multisite()) {
             delete_transient('dirsize_cache');
         }
     }
     if (is_null($args['url'])) {
         $args['url'] = ITFileUtility::get_url_from_file($file);
     }
     if (is_null($args['title'])) {
         $title = preg_replace('/\\.[^.]+$/', '', basename($file));
     }
     if (is_null($args['content'])) {
         $args['content'] = '';
     }
     require_once ABSPATH . '/wp-admin/includes/image.php';
     if (false !== ($image_meta = @wp_read_image_metadata($file))) {
         if ('' !== trim($image_meta['title'])) {
             $args['title'] = $image_meta['title'];
         }
         if ('' !== trim($image_meta['caption'])) {
             $args['content'] = $image_meta['caption'];
         }
     }
     $attachment = array('post_mime_type' => $args['type'], 'guid' => $args['url'], 'post_title' => $args['title'], 'post_content' => $args['content']);
     $id = wp_insert_attachment($attachment, $file);
     if (!is_wp_error($id)) {
         wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $file));
     }
     $data = array('id' => $id, 'file' => $file, 'url' => $args['url'], 'type' => $args['type'], 'title' => $args['title'], 'caption' => $args['content']);
     return $data;
 }
function pmprorh_rf_pmpro_registration_checks($okay)
{
    global $current_user;
    //arrays to store fields that were required and missed
    $required = array();
    $required_labels = array();
    //any fields?
    global $pmprorh_registration_fields;
    if (!empty($pmprorh_registration_fields)) {
        //cycle through groups
        foreach ($pmprorh_registration_fields as $where => $fields) {
            //cycle through fields
            foreach ($fields as $field) {
                //handle arrays
                $field->name = preg_replace('/\\[\\]$/', '', $field->name);
                //if the field is not for this level, skip it
                if (!pmprorh_checkFieldForLevel($field)) {
                    continue;
                }
                if (isset($_REQUEST[$field->name])) {
                    $value = $_REQUEST[$field->name];
                } elseif (isset($_FILES[$field->name])) {
                    $value = $_FILES[$field->name]['name'];
                    //handle empty file but the user already has a file
                    if (empty($value) && !empty($_REQUEST[$field->name . "_old"])) {
                        $value = $_REQUEST[$field->name . "_old"];
                    } elseif (!empty($value)) {
                        //check extension against allowed extensions
                        $filetype = wp_check_filetype_and_ext($_FILES[$field->name]['tmp_name'], $_FILES[$field->name]['name']);
                        if ((!$filetype['type'] || !$filetype['ext']) && !current_user_can('unfiltered_upload')) {
                            if ($okay) {
                                //only want to update message if there is no previous error
                                pmpro_setMessage(sprintf(__("Sorry, the file type for %s is not permitted for security reasons.", "pmpro"), $_FILES[$field->name]['name']), "pmpro_error");
                            }
                            return false;
                        } else {
                            //check for specific extensions anyway
                            if (!empty($field->ext) && !in_array($filetype['ext'], $field->ext)) {
                                if ($okay) {
                                    //only want to update message if there is no previous error
                                    pmpro_setMessage(sprintf(__("Sorry, the file type for %s is not permitted for security reasons.", "pmpro"), $_FILES[$field->name]['name']), "pmpro_error");
                                }
                                return false;
                            }
                        }
                    }
                } else {
                    $value = false;
                }
                if (!empty($field->required) && empty($value)) {
                    $required[] = $field->name;
                    $required_labels[] = $field->label;
                }
            }
        }
    }
    if (!empty($required)) {
        $required = array_unique($required);
        //add them to error fields
        global $pmpro_error_fields;
        $pmpro_error_fields = array_merge((array) $pmpro_error_fields, $required);
        if (count($required) == 1) {
            $pmpro_msg = "The " . implode(", ", $required_labels) . " field is required.";
        } else {
            $pmpro_msg = "The " . implode(", ", $required_labels) . " fields are required.";
        }
        $pmpro_msgt = "pmpro_error";
        if ($okay) {
            pmpro_setMessage($pmpro_msg, $pmpro_msgt);
        }
        return false;
    }
    //return whatever status was before
    return $okay;
}
Пример #22
0
 /**
  * Uploads a file
  * 
  * @param type $file, name of the file field in html .e.g _mpp_file in <input type='file' name='_mpp_file' />
  * @param array $args{
  *	
  *	@type string $component
  *	@type int $component_id
  *	@type int $gallery_id
  * 
  * }
  * 
  * @return boolean
  */
 public function upload($file, $args)
 {
     extract($args);
     if (empty($file_id)) {
         return false;
     }
     //setup error
     $this->setup_upload_errors($component_id);
     $ms_flag = false;
     if (is_multisite() && has_filter('upload_mimes', 'check_upload_mimes')) {
         remove_filter('upload_mimes', 'check_upload_mimes');
         $ms_flag = true;
     }
     //$_FILE['_mpp_file']
     $file = $file[$file_id];
     $unique_filename_callback = null;
     //include from wp-admin dir for media processing
     require_once ABSPATH . 'wp-admin/includes/file.php';
     require_once ABSPATH . 'wp-admin/includes/image.php';
     if (!function_exists('mpp_handle_upload_error')) {
         function mpp_handle_upload_error($file, $message)
         {
             return array('error' => $message);
         }
     }
     $upload_error_handler = 'mpp_handle_upload_error';
     $file = apply_filters('mpp_upload_prefilter', $file);
     // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
     $test_form = true;
     $test_size = true;
     $test_upload = true;
     // If you override this, you must provide $ext and $type!!!!
     $test_type = true;
     $mimes = false;
     // Install user overrides. Did we mention that this voids your warranty?
     if (!empty($overrides) && is_array($overrides)) {
         extract($overrides, EXTR_OVERWRITE);
     }
     // A successful upload will pass this test. It makes no sense to override this one.
     if ($file['error'] > 0) {
         return call_user_func($upload_error_handler, $file, $this->upload_errors[$file['error']]);
     }
     // A non-empty file will pass this test.
     if ($test_size && !($file['size'] > 0)) {
         if (is_multisite()) {
             $error_msg = _x('File is empty. Please upload something more substantial.', 'upload error message', 'mediapress');
         } else {
             $error_msg = _x('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.', 'upload error message', 'mediapress');
         }
         return call_user_func($upload_error_handler, $file, $error_msg);
     }
     // A properly uploaded file will pass this test. There should be no reason to override this one.
     if ($test_upload && !@is_uploaded_file($file['tmp_name'])) {
         return call_user_func($upload_error_handler, $file, _x('Specified file failed upload test.', 'upload error message', 'mediapress'));
     }
     // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
     if ($test_type) {
         $wp_filetype = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $mimes);
         extract($wp_filetype);
         // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
         if ($proper_filename) {
             $file['name'] = $proper_filename;
         }
         if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
             return call_user_func($upload_error_handler, $file, _x('Sorry, this file type is not permitted for security reasons.', 'upload error message', 'mediapress'));
         }
         if (!$ext) {
             $ext = ltrim(strrchr($file['name'], '.'), '.');
         }
         if (!$type) {
             $type = $file['type'];
         }
     } else {
         $type = '';
     }
     // A writable uploads dir will pass this test. Again, there's no point overriding this one.
     if (!(($uploads = $this->get_upload_dir($args)) && false === $uploads['error'])) {
         return call_user_func($upload_error_handler, $file, $uploads['error']);
     }
     $filename = wp_unique_filename($uploads['path'], $file['name'], $unique_filename_callback);
     // Move the file to the uploads dir
     $new_file = $uploads['path'] . "/{$filename}";
     if (!file_exists($uploads['path'])) {
         wp_mkdir_p($uploads['path']);
     }
     if (false === @move_uploaded_file($file['tmp_name'], $new_file)) {
         if (0 === strpos($uploads['basedir'], ABSPATH)) {
             $error_path = str_replace(ABSPATH, '', $uploads['basedir']) . $uploads['subdir'];
         } else {
             $error_path = basename($uploads['basedir']) . $uploads['subdir'];
         }
         return $upload_error_handler($file, sprintf(_x('The uploaded file could not be moved to %s.', 'upload error message', 'mediapress'), $error_path));
     }
     // Set correct file permissions
     $stat = stat(dirname($new_file));
     $perms = $stat['mode'] & 0666;
     @chmod($new_file, $perms);
     // Compute the URL
     $url = $uploads['url'] . "/{$filename}";
     $this->invalidate_transient($component, $component_id);
     //if required, fix rotation
     $this->fix_rotation($new_file);
     return apply_filters('mpp_handle_upload', array('file' => $new_file, 'url' => $url, 'type' => $type), 'upload');
 }
Пример #23
0
/**
 * Handle sideloads, which is the process of retrieving a media item from another server instead of
 * a traditional media upload. This process involves sanitizing the filename, checking extensions
 * for mime type, and moving the file to the appropriate directory within the uploads directory.
 *
 * @since 2.6.0
 *
 * @uses wp_handle_upload_error
 * @uses apply_filters
 * @uses wp_check_filetype_and_ext
 * @uses current_user_can
 * @uses wp_upload_dir
 * @uses wp_unique_filename
 * @param array $file an array similar to that of a PHP $_FILES POST array
 * @param array $overrides Optional. An associative array of names=>values to override default variables with extract( $overrides, EXTR_OVERWRITE ).
 * @param string $time Optional. Time formatted in 'yyyy/mm'.
 * @return array On success, returns an associative array of file attributes. On failure, returns $overrides['upload_error_handler'](&$file, $message ) or array( 'error'=>$message ).
 */
function wp_handle_sideload(&$file, $overrides = false, $time = null)
{
    // The default error handler.
    if (!function_exists('wp_handle_upload_error')) {
        function wp_handle_upload_error(&$file, $message)
        {
            return array('error' => $message);
        }
    }
    // You may define your own function and pass the name in $overrides['upload_error_handler']
    $upload_error_handler = 'wp_handle_upload_error';
    // You may define your own function and pass the name in $overrides['unique_filename_callback']
    $unique_filename_callback = null;
    // $_POST['action'] must be set and its value must equal $overrides['action'] or this:
    $action = 'wp_handle_sideload';
    // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
    $upload_error_strings = array(false, __("The uploaded file exceeds the <code>upload_max_filesize</code> directive in <code>php.ini</code>."), __("The uploaded file exceeds the <em>MAX_FILE_SIZE</em> directive that was specified in the HTML form."), __("The uploaded file was only partially uploaded."), __("No file was uploaded."), '', __("Missing a temporary folder."), __("Failed to write file to disk."), __("File upload stopped by extension."));
    // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
    $test_form = true;
    $test_size = true;
    // If you override this, you must provide $ext and $type!!!!
    $test_type = true;
    $mimes = false;
    // Install user overrides. Did we mention that this voids your warranty?
    if (is_array($overrides)) {
        extract($overrides, EXTR_OVERWRITE);
    }
    // A correct form post will pass this test.
    if ($test_form && (!isset($_POST['action']) || $_POST['action'] != $action)) {
        return $upload_error_handler($file, __('Invalid form submission.'));
    }
    // A successful upload will pass this test. It makes no sense to override this one.
    if (!empty($file['error'])) {
        return $upload_error_handler($file, $upload_error_strings[$file['error']]);
    }
    // A non-empty file will pass this test.
    if ($test_size && !(filesize($file['tmp_name']) > 0)) {
        return $upload_error_handler($file, __('File is empty. Please upload something more substantial. This error could also be caused by uploads being disabled in your php.ini.'));
    }
    // A properly uploaded file will pass this test. There should be no reason to override this one.
    if (!@is_file($file['tmp_name'])) {
        return $upload_error_handler($file, __('Specified file does not exist.'));
    }
    // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
    if ($test_type) {
        $wp_filetype = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $mimes);
        extract($wp_filetype);
        // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
        if ($proper_filename) {
            $file['name'] = $proper_filename;
        }
        if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
            return $upload_error_handler($file, __('Sorry, this file type is not permitted for security reasons.'));
        }
        if (!$ext) {
            $ext = ltrim(strrchr($file['name'], '.'), '.');
        }
        if (!$type) {
            $type = $file['type'];
        }
    }
    // A writable uploads dir will pass this test. Again, there's no point overriding this one.
    if (!(($uploads = wp_upload_dir($time)) && false === $uploads['error'])) {
        return $upload_error_handler($file, $uploads['error']);
    }
    $filename = wp_unique_filename($uploads['path'], $file['name'], $unique_filename_callback);
    // Strip the query strings.
    $filename = str_replace('?', '-', $filename);
    $filename = str_replace('&', '-', $filename);
    // Move the file to the uploads dir
    $new_file = $uploads['path'] . "/{$filename}";
    if (false === @rename($file['tmp_name'], $new_file)) {
        if (0 === strpos($uploads['basedir'], ABSPATH)) {
            $error_path = str_replace(ABSPATH, '', $uploads['basedir']) . $uploads['subdir'];
        } else {
            $error_path = basename($uploads['basedir']) . $uploads['subdir'];
        }
        return $upload_error_handler($file, sprintf(__('The uploaded file could not be moved to %s.'), $error_path));
    }
    // Set correct file permissions
    $stat = stat(dirname($new_file));
    $perms = $stat['mode'] & 0666;
    @chmod($new_file, $perms);
    // Compute the URL
    $url = $uploads['url'] . "/{$filename}";
    $return = apply_filters('wp_handle_upload', array('file' => $new_file, 'url' => $url, 'type' => $type), 'sideload');
    return $return;
}
/**
 * Imports data from CSV file using ajax.
 *
 * @since 1.0.0
 * @package GeoDirectory
 * @global object $wpdb WordPress Database object.
 * @global string $plugin_prefix Geodirectory plugin table prefix.
 * @global object $current_user Current user object.
 */
function geodir_ajax_import_csv()
{
    error_reporting(0);
    // hide error to get clean json response
    global $wpdb, $plugin_prefix, $current_user;
    $uploads = wp_upload_dir();
    ini_set('auto_detect_line_endings', true);
    $wp_post_statuses = get_post_statuses();
    // All of the WordPress supported post statuses.
    $task = isset($_POST['task']) ? $_POST['task'] : '';
    $uploadedFile = isset($_POST['gddata']['uploadedFile']) ? $_POST['gddata']['uploadedFile'] : NULL;
    $filename = $uploadedFile;
    $uploads = wp_upload_dir();
    $uploads_dir = $uploads['path'];
    $image_name_arr = explode('/', $filename);
    $filename = end($image_name_arr);
    $target_path = $uploads_dir . '/temp_' . $current_user->data->ID . '/' . $filename;
    $return = array();
    $return['file'] = $uploadedFile;
    $return['error'] = __('The uploaded file is not a valid csv file. Please try again.', 'geodirectory');
    if (is_file($target_path) && file_exists($target_path) && $uploadedFile) {
        $wp_filetype = wp_check_filetype_and_ext($target_path, $filename);
        if (!empty($wp_filetype) && isset($wp_filetype['ext']) && geodir_strtolower($wp_filetype['ext']) == 'csv') {
            $return['error'] = NULL;
            $return['rows'] = 0;
            if (($handle = fopen($target_path, "r")) !== FALSE) {
                while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
                    if (is_array($data) && !empty($data)) {
                        $file[] = '"' . implode('","', $data) . '"';
                    }
                }
                fclose($handle);
                $file = $file;
            }
            $return['rows'] = !empty($file) && count($file) > 1 ? count($file) - 1 : 0;
            if (!$return['rows'] > 0) {
                $return['error'] = __('No data found in csv file.', 'geodirectory');
            }
        }
    }
    if ($task == 'prepare' || !empty($return['error'])) {
        echo json_encode($return);
        exit;
    }
    $totRecords = isset($_POST['gddata']['totRecords']) ? $_POST['gddata']['totRecords'] : NULL;
    $importlimit = isset($_POST['gddata']['importlimit']) ? $_POST['gddata']['importlimit'] : 1;
    $count = $importlimit;
    $requested_limit = $importlimit;
    $tmpCnt = isset($_POST['gddata']['tmpcount']) ? $_POST['gddata']['tmpcount'] : 0;
    if ($count < $totRecords) {
        $count = $tmpCnt + $count;
        if ($count > $totRecords) {
            $count = $totRecords;
        }
    } else {
        $count = $totRecords;
    }
    $total_records = 0;
    $rowcount = 0;
    $address_invalid = 0;
    $blank_address = 0;
    $upload_files = 0;
    $invalid_post_type = 0;
    $invalid_title = 0;
    $customKeyarray = array();
    $gd_post_info = array();
    $post_location = array();
    $countpost = 0;
    if (!empty($file)) {
        $columns = isset($file[0]) ? geodir_str_getcsv($file[0]) : NULL;
        $customKeyarray = $columns;
        if (empty($columns) || !empty($columns) && $columns[0] == '') {
            $return['error'] = CSV_INVAILD_FILE;
            echo json_encode($return);
            exit;
        }
        for ($i = 1; $i <= $importlimit; $i++) {
            $current_index = $tmpCnt + $i;
            if (isset($file[$current_index])) {
                $total_records++;
                $buffer = geodir_str_getcsv($file[$current_index]);
                $post_title = addslashes($buffer[0]);
                $current_post_author = $buffer[1];
                $post_desc = addslashes($buffer[2]);
                $post_cat = array();
                $catids_arr = array();
                $post_cat = trim($buffer[3]);
                // comma seperated category name
                if ($post_cat) {
                    $post_cat_arr = explode(',', $post_cat);
                    for ($c = 0; $c < count($post_cat_arr); $c++) {
                        $catid = wp_kses_normalize_entities(trim($post_cat_arr[$c]));
                        if (!empty($buffer[5])) {
                            if (in_array($buffer[5], geodir_get_posttypes())) {
                                $p_taxonomy = geodir_get_taxonomies(addslashes($buffer[5]));
                                if (get_term_by('name', $catid, $p_taxonomy[0])) {
                                    $cat = get_term_by('name', $catid, $p_taxonomy[0]);
                                    $catids_arr[] = $cat->slug;
                                } else {
                                    if (get_term_by('slug', $catid, $p_taxonomy[0])) {
                                        $cat = get_term_by('slug', $catid, $p_taxonomy[0]);
                                        $catids_arr[] = $cat->slug;
                                    } else {
                                        $ret = wp_insert_term($catid, $p_taxonomy[0]);
                                        if ($ret && !is_wp_error($ret)) {
                                            if (get_term_by('name', $catid, $p_taxonomy[0])) {
                                                $cat = get_term_by('name', $catid, $p_taxonomy[0]);
                                                $catids_arr[] = $cat->slug;
                                            } elseif (get_term_by('slug', $catid, $p_taxonomy[0])) {
                                                $cat = get_term_by('slug', $catid, $p_taxonomy[0]);
                                                $catids_arr[] = $cat->slug;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                if (!$catids_arr) {
                    $catids_arr[] = 1;
                }
                $post_tags = trim($buffer[4]);
                // comma seperated tags
                $tag_arr = '';
                if ($post_tags) {
                    $tag_arr = explode(',', $post_tags);
                }
                $table = $plugin_prefix . $buffer[5] . '_detail';
                // check table in database
                $error = '';
                if ($wpdb->get_var("SHOW TABLES LIKE '" . $table . "'") != $table) {
                    $invalid_post_type++;
                    continue;
                }
                if ($post_title != '') {
                    $menu_order = 0;
                    $image_folder_name = 'uplaod/';
                    $image_names = array();
                    for ($c = 5; $c < count($customKeyarray); $c++) {
                        $gd_post_info[$customKeyarray[$c]] = addslashes($buffer[$c]);
                        if ($customKeyarray[$c] == 'IMAGE') {
                            $buffer[$c] = trim($buffer[$c]);
                            if (!empty($buffer[$c])) {
                                $image_names[] = $buffer[$c];
                            }
                        }
                        if ($customKeyarray[$c] == 'alive_days') {
                            if ($buffer[$c] != '0' && $buffer[$c] != '') {
                                $submitdata = date('Y-m-d');
                                $gd_post_info['expire_date'] = date('Y-m-d', strtotime($submitdata . "+" . addslashes($buffer[$c]) . " days"));
                            } else {
                                $gd_post_info['expire_date'] = 'Never';
                            }
                        }
                        if ($customKeyarray[$c] == 'post_city') {
                            $post_city = addslashes($buffer[$c]);
                        }
                        if ($customKeyarray[$c] == 'post_region') {
                            $post_region = addslashes($buffer[$c]);
                        }
                        if ($customKeyarray[$c] == 'post_country') {
                            $post_country = addslashes($buffer[$c]);
                        }
                        if ($customKeyarray[$c] == 'post_latitude') {
                            $post_latitude = addslashes($buffer[$c]);
                        }
                        if ($customKeyarray[$c] == 'post_longitude') {
                            $post_longitude = addslashes($buffer[$c]);
                        }
                        // Post status
                        if ($customKeyarray[$c] == 'post_status') {
                            $post_status = sanitize_key($buffer[$c]);
                        }
                    }
                    /* ================ before array create ============== */
                    $location_result = geodir_get_default_location();
                    if (!isset($gd_post_info['post_city']) || $gd_post_info['post_city'] == '' || (!isset($gd_post_info['post_region']) || $gd_post_info['post_region'] == '') || (!isset($gd_post_info['post_country']) || $gd_post_info['post_country'] == '') || (!isset($gd_post_info['post_address']) || $gd_post_info['post_address'] == '') || (!isset($gd_post_info['post_latitude']) || $gd_post_info['post_latitude'] == '') || (!isset($gd_post_info['post_longitude']) || $gd_post_info['post_longitude'] == '')) {
                        $blank_address++;
                        continue;
                    } else {
                        if ($location_result->location_id == 0) {
                            if (geodir_strtolower($gd_post_info['post_city']) != geodir_strtolower($location_result->city) || geodir_strtolower($gd_post_info['post_region']) != geodir_strtolower($location_result->region) || geodir_strtolower($gd_post_info['post_country']) != geodir_strtolower($location_result->country)) {
                                $address_invalid++;
                                continue;
                            }
                        }
                    }
                    // Default post status
                    $default_status = 'publish';
                    $post_status = !empty($post_status) ? sanitize_key($post_status) : $default_status;
                    $post_status = !empty($wp_post_statuses) && !isset($wp_post_statuses[$post_status]) ? $default_status : $post_status;
                    $my_post['post_title'] = $post_title;
                    $my_post['post_content'] = $post_desc;
                    $my_post['post_type'] = addslashes($buffer[5]);
                    $my_post['post_author'] = $current_post_author;
                    $my_post['post_status'] = $post_status;
                    $my_post['post_category'] = $catids_arr;
                    $my_post['post_tags'] = $tag_arr;
                    $gd_post_info['post_tags'] = $tag_arr;
                    $gd_post_info['post_title'] = $post_title;
                    $gd_post_info['post_status'] = $post_status;
                    $gd_post_info['submit_time'] = time();
                    $gd_post_info['submit_ip'] = $_SERVER['REMOTE_ADDR'];
                    $last_postid = wp_insert_post($my_post);
                    $countpost++;
                    // Check if we need to save post location as new location
                    if ($location_result->location_id > 0) {
                        if (isset($post_city) && isset($post_region)) {
                            $request_info['post_location'] = array('city' => $post_city, 'region' => $post_region, 'country' => $post_country, 'geo_lat' => $post_latitude, 'geo_lng' => $post_longitude);
                            $post_location_info = $request_info['post_location'];
                            if ($location_id = geodir_add_new_location($post_location_info)) {
                                $post_location_id = $location_id;
                            }
                        } else {
                            $post_location_id = 0;
                        }
                    } else {
                        $post_location_id = 0;
                    }
                    /* ------- get default package info ----- */
                    $payment_info = array();
                    $package_info = array();
                    $package_info = (array) geodir_post_package_info($package_info, '', $buffer[5]);
                    $package_id = '';
                    if (isset($gd_post_info['package_id']) && $gd_post_info['package_id'] != '') {
                        $package_id = $gd_post_info['package_id'];
                    }
                    if (!empty($package_info)) {
                        $payment_info['package_id'] = $package_info['pid'];
                        if (isset($package_info['alive_days']) && $package_info['alive_days'] != 0) {
                            $payment_info['expire_date'] = date('Y-m-d', strtotime("+" . $package_info['alive_days'] . " days"));
                        } else {
                            $payment_info['expire_date'] = 'Never';
                        }
                        $gd_post_info = array_merge($gd_post_info, $payment_info);
                    }
                    $gd_post_info['post_location_id'] = $post_location_id;
                    $post_type = get_post_type($last_postid);
                    $table = $plugin_prefix . $post_type . '_detail';
                    geodir_save_post_info($last_postid, $gd_post_info);
                    if (!empty($image_names)) {
                        $upload_files++;
                        $menu_order = 1;
                        foreach ($image_names as $image_name) {
                            $img_name_arr = explode('.', $image_name);
                            $uploads = wp_upload_dir();
                            $sub_dir = $uploads['subdir'];
                            $arr_file_type = wp_check_filetype($image_name);
                            $uploaded_file_type = $arr_file_type['type'];
                            $attachment = array();
                            $attachment['post_id'] = $last_postid;
                            $attachment['title'] = $img_name_arr[0];
                            $attachment['content'] = '';
                            $attachment['file'] = $sub_dir . '/' . $image_name;
                            $attachment['mime_type'] = $uploaded_file_type;
                            $attachment['menu_order'] = $menu_order;
                            $attachment['is_featured'] = 0;
                            $attachment_set = '';
                            foreach ($attachment as $key => $val) {
                                if ($val != '') {
                                    $attachment_set .= $key . " = '" . $val . "', ";
                                }
                            }
                            $attachment_set = trim($attachment_set, ", ");
                            $wpdb->query("INSERT INTO " . GEODIR_ATTACHMENT_TABLE . " SET " . $attachment_set);
                            if ($menu_order == 1) {
                                $post_type = get_post_type($last_postid);
                                $wpdb->query($wpdb->prepare("UPDATE " . $table . " SET featured_image = %s where post_id =%d", array($sub_dir . '/' . $image_name, $last_postid)));
                            }
                            $menu_order++;
                        }
                    }
                    $gd_post_info['package_id'] = $package_id;
                    /** This action is documented in geodirectory-functions/post-functions.php */
                    do_action('geodir_after_save_listing', $last_postid, $gd_post_info);
                    if (!empty($buffer[5])) {
                        if (in_array($buffer[5], geodir_get_posttypes())) {
                            $taxonomies = geodir_get_posttype_info(addslashes($buffer[5]));
                            wp_set_object_terms($last_postid, $my_post['post_tags'], $taxonomy = $taxonomies['taxonomies'][1]);
                            wp_set_object_terms($last_postid, $my_post['post_category'], $taxonomy = $taxonomies['taxonomies'][0]);
                            $post_default_category = isset($my_post['post_default_category']) ? $my_post['post_default_category'] : '';
                            $post_category_str = isset($my_post['post_category_str']) ? $my_post['post_category_str'] : '';
                            geodir_set_postcat_structure($last_postid, $taxonomy, $post_default_category, $post_category_str);
                        }
                    }
                } else {
                    $invalid_title++;
                }
            }
        }
    }
    $return['rowcount'] = $countpost;
    $return['invalidcount'] = $address_invalid;
    $return['blank_address'] = $blank_address;
    $return['upload_files'] = $upload_files;
    $return['invalid_post_type'] = $invalid_post_type;
    $return['invalid_title'] = $invalid_title;
    $return['total_records'] = $total_records;
    echo json_encode($return);
    exit;
}
Пример #25
0
}
// Get old guid and filetype from DB
$sql = "SELECT guid, post_mime_type FROM {$table_name} WHERE ID = '" . (int) $_POST["ID"] . "'";
list($current_filename, $current_filetype) = $wpdb->get_row($sql, ARRAY_N);
// Massage a bunch of vars
$current_guid = $current_filename;
$current_filename = substr($current_filename, strrpos($current_filename, "/") + 1);
$current_file = get_attached_file((int) $_POST["ID"], true);
$current_path = substr($current_file, 0, strrpos($current_file, "/"));
$current_file = str_replace("//", "/", $current_file);
$current_filename = basename($current_file);
$replace_type = $_POST["replace_type"];
// We have two types: replace / replace_and_search
if (is_uploaded_file($_FILES["userfile"]["tmp_name"])) {
    // New method for validating that the uploaded file is allowed, using WP:s internal wp_check_filetype_and_ext() function.
    $filedata = wp_check_filetype_and_ext($_FILES["userfile"]["tmp_name"], $_FILES["userfile"]["name"]);
    if ($filedata["ext"] == "") {
        echo __("File type does not meet security guidelines. Try another.");
        exit;
    }
    $new_filename = $_FILES["userfile"]["name"];
    $new_filesize = $_FILES["userfile"]["size"];
    $new_filetype = $filedata["type"];
    // save original file permissions
    $original_file_perms = fileperms($current_file) & 0777;
    if ($replace_type == "replace") {
        // Drop-in replace and we don't even care if you uploaded something that is the wrong file-type.
        // That's your own fault, because we warned you!
        emr_delete_current_files($current_file);
        // Move new file to old location/name
        move_uploaded_file($_FILES["userfile"]["tmp_name"], $current_file);
Пример #26
0
 function saveFile($user_id, $name, $value)
 {
     //setup some vars
     $file = $_FILES[$name];
     $user = get_userdata($user_id);
     //no file?
     if (empty($file['name'])) {
         return;
     }
     //check extension against allowed extensions
     $filetype = wp_check_filetype_and_ext($file['tmp_name'], $file['name']);
     if ((!$filetype['type'] || !$filetype['ext']) && !current_user_can('unfiltered_upload')) {
         //we throw an error earlier, but this just bails on the upload just in case
         return false;
     } else {
         //need to check this in case we are in class context or not
         if (!empty($this)) {
             if (!empty($this->ext)) {
                 $ext = $this->ext;
             } else {
                 $ext = false;
             }
         } else {
             global $pmprorh_registration_fields;
             foreach ($pmprorh_registration_fields as $checkout_box) {
                 foreach ($checkout_box as $field) {
                     if ($field->name == $name) {
                         if (!empty($field->ext)) {
                             $ext = $field->ext;
                         } else {
                             $ext = false;
                         }
                         break 2;
                     }
                 }
             }
         }
         //check for specific extensions anyway
         if (!empty($ext) && !in_array($filetype['ext'], $ext)) {
             pmpro_setMessage(sprintf(__("Sorry, the file type for %s is not permitted for security reasons.", "pmpro"), $file['name']), "pmpro_error");
             return false;
         }
     }
     /*
     	save file in uploads
     */
     //check for a register helper directory in wp-content
     $upload_dir = wp_upload_dir();
     $pmprorh_dir = $upload_dir['basedir'] . "/pmpro-register-helper/" . $user->user_login . "/";
     //create the dir and subdir if needed
     if (!is_dir($pmprorh_dir)) {
         wp_mkdir_p($pmprorh_dir);
     }
     //if we already have a file for this field, delete it
     $old_file = get_user_meta($user->ID, $name, true);
     if (!empty($old_file) && !empty($old_file['fullpath']) && file_exists($old_file['fullpath'])) {
         unlink($old_file['fullpath']);
     }
     //figure out new filename
     $filename = $file['name'];
     $count = 0;
     while (file_exists($pmprorh_dir . $filename)) {
         if ($count) {
             $filename = str_lreplace("-" . $count . "." . $filetype['ext'], "-" . strval($count + 1) . "." . $filetype['ext'], $filename);
         } else {
             $filename = str_lreplace("." . $filetype['ext'], "-1." . $filetype['ext'], $filename);
         }
         $count++;
         //let's not expect more than 50 files with the same name
         if ($count > 50) {
             die("Error uploading file. Too many files with the same name.");
         }
     }
     //save file
     if (strpos($file['tmp_name'], $upload_dir['basedir']) !== false) {
         //was uploaded and saved to $_SESSION
         rename($file['tmp_name'], $pmprorh_dir . $filename);
     } else {
         //it was just uploaded
         move_uploaded_file($file['tmp_name'], $pmprorh_dir . $filename);
     }
     //save filename in usermeta
     update_user_meta($user_id, $name, array("original_filename" => $file['name'], "filename" => $filename, "fullpath" => $pmprorh_dir . $filename, "fullurl" => content_url("/uploads/pmpro-register-helper/" . $user->user_login . "/" . $filename), "size" => $file['size']));
 }
function lpr_import_handle_upload($file, $overrides = array())
{
    // The default error handler.
    if (!function_exists('lpr_handle_upload_error')) {
        function lpr_handle_upload_error($file, $message)
        {
            return array('error' => $message);
        }
    }
    $action = 'lpr_import_handle_upload';
    /**
     * The dynamic portion of the hook name, $action, refers to the post action.
     *
     * @since 2.9.0 as 'wp_handle_upload_prefilter'
     * @since 4.0.0 Converted to a dynamic hook with $action
     *
     * @param array $file An array of data for a single file.
     */
    $file = apply_filters("lpr_import_handle_upload_prefilter", $file);
    // You may define your own function and pass the name in $overrides['upload_error_handler']
    $upload_error_handler = 'lpr_handle_upload_error';
    if (isset($overrides['upload_error_handler'])) {
        $upload_error_handler = $overrides['upload_error_handler'];
    }
    // You may have had one or more 'wp_handle_upload_prefilter' functions error out the file. Handle that gracefully.
    if (isset($file['error']) && !is_numeric($file['error']) && $file['error']) {
        return $upload_error_handler($file, $file['error']);
    }
    // Install user overrides. Did we mention that this voids your warranty?
    // You may define your own function and pass the name in $overrides['unique_filename_callback']
    $unique_filename_callback = null;
    if (isset($overrides['unique_filename_callback'])) {
        $unique_filename_callback = $overrides['unique_filename_callback'];
    }
    /*
     * This may not have orignially been intended to be overrideable,
     * but historically has been.
     */
    if (isset($overrides['upload_error_strings'])) {
        $upload_error_strings = $overrides['upload_error_strings'];
    } else {
        // Courtesy of php.net, the strings that describe the error indicated in $_FILES[{form field}]['error'].
        $upload_error_strings = array(false, __('The uploaded file exceeds the upload_max_filesize directive in php.ini.'), __('The uploaded file exceeds the MAX_FILE_SIZE directive that was specified in the HTML form.'), __('The uploaded file was only partially uploaded.'), __('No file was uploaded.'), '', __('Missing a temporary folder.'), __('Failed to write file to disk.'), __('File upload stopped by extension.'));
    }
    // All tests are on by default. Most can be turned off by $overrides[{test_name}] = false;
    $test_form = isset($overrides['test_form']) ? $overrides['test_form'] : true;
    $test_size = isset($overrides['test_size']) ? $overrides['test_size'] : true;
    // If you override this, you must provide $ext and $type!!
    $test_type = isset($overrides['test_type']) ? $overrides['test_type'] : true;
    $mimes = isset($overrides['mimes']) ? $overrides['mimes'] : false;
    $test_upload = isset($overrides['test_upload']) ? $overrides['test_upload'] : true;
    // A correct form post will pass this test.
    /*if ( $test_form && ( ! isset( $_POST['action'] ) || ( $_POST['action'] != $action ) ) ) {
    		return call_user_func( $upload_error_handler, $file, __( 'Invalid form submission.' ) );
    	}*/
    // A successful upload will pass this test. It makes no sense to override this one.
    if (isset($file['error']) && $file['error'] > 0) {
        return call_user_func($upload_error_handler, $file, $upload_error_strings[$file['error']]);
    }
    $test_file_size = 'wp_handle_upload' === $action ? $file['size'] : filesize($file['tmp_name']);
    // A non-empty file will pass this test.
    if ($test_size && !($test_file_size > 0)) {
        if (is_multisite()) {
            $error_msg = __('File is empty. Please upload something more substantial.');
        } else {
            $error_msg = __('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 call_user_func($upload_error_handler, $file, $error_msg);
    }
    // A properly uploaded file will pass this test. There should be no reason to override this one.
    $test_uploaded_file = 'wp_handle_upload' === $action ? @is_uploaded_file($file['tmp_name']) : @is_file($file['tmp_name']);
    if ($test_upload && !$test_uploaded_file) {
        return call_user_func($upload_error_handler, $file, __('Specified file failed upload test.'));
    }
    // A correct MIME type will pass this test. Override $mimes or use the upload_mimes filter.
    if ($test_type) {
        //print_r($file);
        $wp_filetype = wp_check_filetype_and_ext($file['tmp_name'], $file['name'], $mimes);
        $ext = empty($wp_filetype['ext']) ? '' : $wp_filetype['ext'];
        $type = empty($wp_filetype['type']) ? '' : $wp_filetype['type'];
        $proper_filename = empty($wp_filetype['proper_filename']) ? '' : $wp_filetype['proper_filename'];
        // Check to see if wp_check_filetype_and_ext() determined the filename was incorrect
        if ($proper_filename) {
            $file['name'] = $proper_filename;
        }
        if ((!$type || !$ext) && !current_user_can('unfiltered_upload')) {
            return call_user_func($upload_error_handler, $file, __('Sorry, this file type is not permitted for security reasons.'));
        }
        if (!$type) {
            $type = $file['type'];
        }
    } else {
        $type = '';
    }
    /*
     * A writable uploads dir will pass this test. Again, there's no point
     * overriding this one.
     */
    if (!(($uploads = wp_upload_dir()) && false === $uploads['error'])) {
        return call_user_func($upload_error_handler, $file, $uploads['error']);
    }
    $filename = wp_unique_filename($uploads['path'], $file['name'], $unique_filename_callback);
    // Move the file to the uploads dir.
    $new_file = $uploads['path'] . "/{$filename}";
    if ('lpr_handle_upload' === $action) {
        $move_new_file = @move_uploaded_file($file['tmp_name'], $new_file);
    } else {
        $move_new_file = @rename($file['tmp_name'], $new_file);
    }
    if (false === $move_new_file) {
        return $upload_error_handler($file, sprintf(__('The uploaded file could not be moved')));
    }
    // Set correct file permissions.
    $stat = stat(dirname($new_file));
    $perms = $stat['mode'] & 0666;
    @chmod($new_file, $perms);
    // Compute the URL.
    $url = $uploads['url'] . "/{$filename}";
    if (is_multisite()) {
        delete_transient('dirsize_cache');
    }
    /**
     * Filter the data array for the uploaded file.
     *
     * @since 2.1.0
     *
     * @param array  $upload {
     *     Array of upload data.
     *
     *     @type string $file Filename of the newly-uploaded file.
     *     @type string $url  URL of the uploaded file.
     *     @type string $type File type.
     * }
     * @param string $context The type of upload action. Values include 'upload' or 'sideload'.
     */
    return apply_filters('lpr_handle_upload', array('file' => $new_file, 'url' => $url, 'type' => $type), 'upload');
}
Пример #28
0
/**
 * Check the uploaded attachment type is allowed
 *
 * @since  2.4.0
 *
 * @param  string $file          Full path to the file.
 * @param  string $filename      The name of the file (may differ from $file due to $file being
 *                               in a tmp directory).
 * @param  array  $allowed_mimes The attachment allowed mimes (Required)
 * @return bool                  True if the attachment type is allowed. False otherwise
 */
function bp_attachments_check_filetype($file, $filename, $allowed_mimes)
{
    $filetype = wp_check_filetype_and_ext($file, $filename, $allowed_mimes);
    if (!empty($filetype['ext']) && !empty($filetype['type'])) {
        return true;
    }
    return false;
}
Пример #29
0
 /**
  * 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);
         }
     }
 }
 /**
  * Save the file to the specified path
  * @return boolean TRUE on success
  */
 function save($path)
 {
     $input = fopen("php://input", "r");
     $temp = tmpfile();
     if (false === $temp) {
         $upload_dir = wp_upload_dir();
         $filename = tempnam($upload_dir['path'], 'tmp_uload') . "<br >";
         $temp = fopen($filename, 'w+');
     }
     $metaDatas = stream_get_meta_data($temp);
     $tmpFilename = $metaDatas['uri'];
     $realSize = stream_copy_to_stream($input, $temp);
     fclose($input);
     //----- attempt to validate the content.
     $allowed_mime_types = get_allowed_mime_types();
     //error_log( print_r($allowed_mime_types,true)."\n",3,ABSPATH.'save.log' );
     if (!function_exists('wp_check_filetype_and_ext')) {
         require_once ABSPATH . 'wp-admin/includes/file.php';
     }
     $wp_filetype = wp_check_filetype_and_ext($tmpFilename, $this->getName(), false);
     //extract( $wp_filetype );
     if (false !== $wp_filetype['proper_filename']) {
         fclose($temp);
         return false;
     }
     if ((!$wp_filetype['type'] || !$wp_filetype['ext']) && !current_user_can('unfiltered_upload')) {
         $this->error = __('Sorry, this file type is not permitted for security reasons.', 'pop');
         fclose($temp);
         return false;
     }
     if (!in_array($wp_filetype['type'], $allowed_mime_types)) {
         $this->error = __('Sorry, this file type is not permitted for security reasons.', 'pop');
         fclose($temp);
         return false;
     }
     if (function_exists('finfo_open')) {
         $finfo = finfo_open(FILEINFO_MIME_TYPE);
         $mime_type = finfo_file($finfo, $tmpFilename);
         finfo_close($finfo);
         if (false !== $mime_type && !in_array($mime_type, $allowed_mime_types)) {
             $this->error = __('Sorry, this file type is not permitted for security reasons.', 'pop');
             fclose($temp);
             return false;
         }
     } else {
         if (function_exists('mime_content_type')) {
             $mime_type = mime_content_type($tmpFilename);
             if (false !== $mime_type && !in_array($mime_type, $allowed_mime_types)) {
                 $this->error = __('Sorry, this file type is not permitted for security reasons.', 'pop');
                 fclose($temp);
                 return false;
             }
         }
     }
     //-----
     if ($realSize != $this->getSize()) {
         fclose($temp);
         return false;
     }
     $target = fopen($path, "w");
     fseek($temp, 0, SEEK_SET);
     stream_copy_to_stream($temp, $target);
     fclose($target);
     fclose($temp);
     return true;
 }