/**
  * @param strin $file_url
  *
  * @return int
  */
 private function upload_file($file_url)
 {
     if (!filter_var($file_url, FILTER_VALIDATE_URL)) {
         return false;
     }
     $contents = @file_get_contents($file_url);
     if ($contents === false) {
         return false;
     }
     $upload = wp_upload_bits(basename($file_url), null, $contents);
     if (isset($upload['error']) && $upload['error']) {
         return false;
     }
     $type = '';
     if (!empty($upload['type'])) {
         $type = $upload['type'];
     } else {
         $mime = wp_check_filetype($upload['file']);
         if ($mime) {
             $type = $mime['type'];
         }
     }
     $attachment = array('post_title' => basename($upload['file']), 'post_content' => '', 'post_type' => 'attachment', 'post_mime_type' => $type, 'guid' => $upload['url']);
     $id = wp_insert_attachment($attachment, $upload['file']);
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file']));
     return $id;
 }
function programmatically_create_post()
{
    $url = 'http://widgets.pinterest.com/v3/pidgets/boards/bradleyblose/my-stuff/pins/';
    $json_O = json_decode(file_get_contents($url), true);
    $id = $json_O['data']['pins'][0]['id'];
    $titlelink = 'https://www.pinterest.com/pin/' . $id . '/';
    $title = get_title($titlelink);
    var_dump($title);
    $original = $json_O['data']['pins'][0]['images']['237x']['url'];
    $image_url = preg_replace('/237x/', '736x', $original);
    $description = $json_O['data']['pins'][0]['description'];
    // Initialize the page ID to -1. This indicates no action has been taken.
    $post_id = -1;
    // Setup the author, slug, and title for the post
    $author_id = 1;
    $mytitle = get_page_by_title($title, OBJECT, 'post');
    var_dump($mytitle);
    // If the page doesn't already exist, then create it
    if (NULL == get_page_by_title($title, OBJECT, 'post')) {
        // Set the post ID so that we know the post was created successfully
        $post_id = wp_insert_post(array('comment_status' => 'closed', 'ping_status' => 'closed', 'post_author' => $author_id, 'post_name' => $title, 'post_title' => $title, 'post_content' => $description, 'post_status' => 'publish', 'post_type' => 'post'));
        //upload featured image
        $upload_dir = wp_upload_dir();
        $image_data = file_get_contents($image_url);
        $filename = basename($image_url);
        if (wp_mkdir_p($upload_dir['path'])) {
            $file = $upload_dir['path'] . '/' . $filename;
            $path = $upload_dir['path'] . '/';
        } else {
            $file = $upload_dir['basedir'] . '/' . $filename;
            $path = $upload_dir['basedir'] . '/';
        }
        file_put_contents($file, $image_data);
        //edit featured image to correct specs to fit theme
        $pngfilename = $filename . '.png';
        $targetThumb = $path . '/' . $pngfilename;
        $img = new Imagick($file);
        $img->scaleImage(250, 250, true);
        $img->setImageBackgroundColor('None');
        $w = $img->getImageWidth();
        $h = $img->getImageHeight();
        $img->extentImage(250, 250, ($w - 250) / 2, ($h - 250) / 2);
        $img->writeImage($targetThumb);
        unlink($file);
        //Attach featured image
        $wp_filetype = wp_check_filetype($pngfilename, null);
        $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($pngfilename), 'post_content' => '', 'post_status' => 'inherit');
        $attach_id = wp_insert_attachment($attachment, $targetThumb, $post_id);
        require_once ABSPATH . 'wp-admin/includes/image.php';
        $attach_data = wp_generate_attachment_metadata($attach_id, $targetThumb);
        wp_update_attachment_metadata($attach_id, $attach_data);
        set_post_thumbnail($post_id, $attach_id);
        // Otherwise, we'll stop
    } else {
        // Arbitrarily use -2 to indicate that the page with the title already exists
        $post_id = -2;
    }
    // end if
}
Example #3
0
 static function add_image($image_url)
 {
     if (empty($image_url)) {
         return FALSE;
     }
     // Add Featured Image to Post
     $upload_dir = wp_upload_dir();
     // Set upload folder
     $image_data = file_get_contents($image_url);
     // Get image data
     $filename = basename($image_url);
     // Create image file name
     // Check folder permission and define file location
     if (wp_mkdir_p($upload_dir['path'])) {
         $file = $upload_dir['path'] . '/' . $filename;
     } else {
         $file = $upload_dir['basedir'] . '/' . $filename;
     }
     // Create the image  file on the server
     file_put_contents($file, $image_data);
     // Check image file type
     $wp_filetype = wp_check_filetype($filename, NULL);
     // Set attachment data
     $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => sanitize_file_name($filename), 'post_content' => '', 'post_status' => 'inherit');
     // Create the attachment
     $attach_id = wp_insert_attachment($attachment, $file);
     // Include image.php
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Define attachment metadata
     $attach_data = wp_generate_attachment_metadata($attach_id, $file);
     // Assign metadata to attachment
     wp_update_attachment_metadata($attach_id, $attach_data);
     return $attach_id;
 }
function process_attachment($post, $url)
{
    // if the URL is absolute, but does not contain address, then upload it assuming base_site_url
    //if ( preg_match( '|^/[\w\W]+$|', $url ) )
    //	$url = rtrim( $this->base_url, '/' ) . $url;
    global $url_remap;
    $upload = fetch_remote_file($url, $post);
    if (is_wp_error($upload)) {
        return $upload;
    }
    if ($info = wp_check_filetype($upload['file'])) {
        $post['post_mime_type'] = $info['type'];
    } else {
        return new WP_Error('attachment_processing_error', __('Invalid file type', 'wordpress-importer'));
    }
    $post['guid'] = $upload['url'];
    // as per wp-admin/includes/upload.php
    $post_id = wp_insert_attachment($post, $upload['file']);
    wp_update_attachment_metadata($post_id, wp_generate_attachment_metadata($post_id, $upload['file']));
    // remap resized image URLs, works by stripping the extension and remapping the URL stub.
    if (preg_match('!^image/!', $info['type'])) {
        $parts = pathinfo($url);
        $name = basename($parts['basename'], ".{$parts['extension']}");
        // PATHINFO_FILENAME in PHP 5.2
        $parts_new = pathinfo($upload['url']);
        $name_new = basename($parts_new['basename'], ".{$parts_new['extension']}");
        $url_remap[$parts['dirname'] . '/' . $name] = $parts_new['dirname'] . '/' . $name_new;
    }
    return $post_id;
}
 public function wpua_avatar_upload($file)
 {
     $filetype = wp_check_filetype($file->name);
     $media_upload = array();
     $media_upload['file'] = array('name' => $file->name, 'type' => $filetype['type'], 'tmp_name' => $file->path, 'error' => 0, 'size' => filesize($file->path));
     $media_file = wp_handle_upload($media_upload['file'], array('test_form' => false, 'test_upload' => false, 'action' => 'custom_action'));
     if ($media_file['file']) {
         $url = $media_file['url'];
         $filepath = $media_file['file'];
         if ($image_meta = @wp_read_image_metadata($filepath)) {
             if (trim($image_meta['title']) && !is_numeric(sanitize_title($image_meta['title']))) {
                 $title = $image_meta['title'];
             }
         }
         $attachment = array('guid' => $url, 'post_mime_type' => $filetype['type'], 'post_title' => $title);
         $attachment_id = wp_insert_attachment($attachment, $filepath);
         if (!is_wp_error($attachment_id)) {
             $this->delete_attachment_by_user($this->user_id);
             wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $filepath));
             update_post_meta($attachment_id, '_wp_attachment_wp_user_avatar', $this->user_id);
             $arr = wp_get_attachment_image_src($attachment_id, 'full');
             $this->avatar_url = $arr[0];
             $this->avatar_filename = basename($filepath);
             $this->resource = $attachment_id;
             $saved = $this->save();
             if (!$saved) {
                 $this->delete_attachment($attachment_id);
                 return $saved;
             }
             return $saved;
         }
     } else {
         return WP_Error('file_upload_problem', __("Media avatar could't uploading please check you have right permission for uploads folder.", 'wp-user-avatar-pro'));
     }
 }
Example #6
0
 public function actionSaveImage()
 {
     if (!empty($_POST['imageUrl'])) {
         $url = \parse_url($_POST['imageUrl']);
         if ($curlDescriptor = \curl_init($_POST['imageUrl'])) {
             \curl_setopt($curlDescriptor, CURLOPT_HEADER, 0);
             \curl_setopt($curlDescriptor, CURLOPT_RETURNTRANSFER, 1);
             \curl_setopt($curlDescriptor, CURLOPT_BINARYTRANSFER, 1);
             $rawImage = \curl_exec($curlDescriptor);
             \curl_close($curlDescriptor);
             if ($rawImage) {
                 include_once ABSPATH . 'wp-admin/includes/image.php';
                 include_once ABSPATH . 'wp-admin/includes/file.php';
                 include_once ABSPATH . 'wp-admin/includes/media.php';
                 $wpFileType = \wp_check_filetype(\basename($url['path']), null);
                 $tmpDir = \ini_get('upload_tmp_dir') ? \ini_get('upload_tmp_dir') : \sys_get_temp_dir();
                 $tempName = $tmpDir . '/' . \uniqid() . '.' . $wpFileType['ext'];
                 \file_put_contents($tempName, $rawImage);
                 $_FILES['async-upload'] = array('name' => \trim(\str_replace(' ', '', basename($tempName))), 'type' => $wpFileType['type'], 'tmp_name' => $tempName, 'error' => 0, 'size' => \filesize($tempName));
                 \media_handle_upload('async-upload', 0, array(), array('test_form' => false, 'action' => 'upload-attachment'));
                 \wp_send_json(array('status' => 'success'));
             }
         }
     }
     \wp_send_json(array('status' => 'error'));
 }
Example #7
0
function simple_upload_csv_products_file()
{
    $upload_feedback = '';
    if (isset($_FILES['product_csv']) && $_FILES['product_csv']['size'] > 0) {
        $arr_file_type = wp_check_filetype(basename($_FILES['product_csv']['name']));
        $uploaded_file_type = $arr_file_type['ext'];
        $allowed_file_type = 'csv';
        if ($uploaded_file_type == $allowed_file_type) {
            $wp_uploads_dir = wp_upload_dir();
            $filepath = $wp_uploads_dir['basedir'] . '/simple-products.csv';
            if (move_uploaded_file($_FILES['product_csv']['tmp_name'], $filepath)) {
                simple_import_product_from_csv();
            } else {
                $upload_feedback = '<div class="al-box warning">' . __('There was a problem with your upload.', 'al-ecommerce-product-catalog') . '</div>';
            }
        } else {
            $upload_feedback = '<div class="al-box warning">' . __('Please upload only CSV files.', 'al-ecommerce-product-catalog') . '</div>';
        }
        echo $upload_feedback;
    } else {
        $url = sample_import_file_url();
        echo '<form method="POST" enctype="multipart/form-data"><input type="file" accept=".csv" name="product_csv" id="product_csv" /><input type="submit" class="button" value="' . __('Import Products', 'al-ecommerce-product-catalog') . '" /></form>';
        echo '<div class="al-box info"><p>' . __("The CSV fields should be in following order: Image URL, Product Name, Product Price, Product Categories, Short Description, Long Description.", "al-ecommerce-product-catalog") . '</p><p>' . __("The first row should contain the field names. Semicolon should be used as the CSV separator.", "al-ecommerce-product-catalog") . '</p><a href="' . $url . '" class="button-primary">' . __('Download CSV Template', 'al-ecommerce-product-catalog') . '</a></div>';
    }
}
Example #8
0
/**
 * Upload theme default site icon
 *
 * @return void
 */
function dswoddil_site_icon_upload()
{
    $image_name = 'site-icon';
    if (!function_exists('wp_update_attachment_metadata')) {
        require_once ABSPATH . 'wp-admin/includes/image.php';
    }
    if (!dswoddil_get_attachment_by_post_name('dswoddil-' . $image_name)) {
        $site_icon = get_template_directory() . '/img/' . $image_name . '.png';
        // create $file array with the indexes show below
        $file['name'] = $site_icon;
        $file['type'] = 'image/png';
        // get image size
        $file['size'] = filesize($file['name']);
        $file['tmp_name'] = $image_name . '.png';
        $file['error'] = 1;
        $file_content = file_get_contents($site_icon);
        $upload_image = wp_upload_bits($file['tmp_name'], null, $file_content);
        // Check the type of tile. We'll use this as the 'post_mime_type'.
        $filetype = wp_check_filetype(basename($upload_image['file']), null);
        $attachment = array('guid' => $upload_image['file'], 'post_mime_type' => $filetype['type'], 'post_title' => 'dswoddil-' . $image_name, 'post_content' => '', 'post_status' => 'inherit');
        //insert wordpress attachment of uploaded image to get attachmen ID
        $attachment_id = wp_insert_attachment($attachment, $upload_image['file']);
        //generate attachment thumbnail
        wp_update_attachment_metadata($attachment_id, wp_generate_attachment_metadata($attachment_id, $upload_image['file']));
        add_post_meta($attachment_id, '_wp_attachment_context', $image_name);
    }
}
Example #9
0
function post_acme_article($post)
{
    //if($post['post_title']) {
    $post_data = array('post_title' => wp_strip_all_tags($post['post_title']), 'post_content' => $post['post_desc'], 'tax_input' => array('article_country_cat' => $post['post_country'], 'article_cat' => $post['post_category']), 'post_status' => $post['save'] != '' ? 'draft' : 'publish', 'post_type' => $post['custom_post_type'], 'post_author' => get_current_user_id());
    $post_id = wp_insert_post($post_data);
    // add_post_meta( $post_id, '_custom_image_link', $post['paste_featured_img'], true );
    if (!empty($_FILES['post_featured_img']['name'])) {
        $uploaddir = wp_upload_dir();
        $file = $_FILES["post_featured_img"]["name"];
        $uploadfile = $uploaddir['path'] . '/' . basename($file);
        move_uploaded_file($file, $uploadfile);
        $filename = basename($uploadfile);
        $wp_filetype = wp_check_filetype(basename($filename), null);
        $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', $filename), 'post_content' => '', 'post_status' => 'inherit');
        foreach ($_FILES as $file => $value) {
            require_once ABSPATH . "wp-admin" . '/includes/image.php';
            require_once ABSPATH . "wp-admin" . '/includes/file.php';
            require_once ABSPATH . "wp-admin" . '/includes/media.php';
            $attach_id = media_handle_upload($file, $post_id);
            set_post_thumbnail($post_id, $attach_id);
            update_post_meta($post_id, '_thumbnail_id', $attach_id);
        }
        $image_url = wp_get_attachment_url(get_post_thumbnail_id($post_id));
    } else {
        $image_url = '';
    }
    $result = array('status' => 'success', 'post_id' => $post_id, 'image_url' => $image_url, 'featured_img' => $image_url, 'msg' => 'Post Save.');
    // }
    // }  else {
    //   $result = array( 'status' => 'error', 'post_id' => $post_id, 'image_url' => $image_url, 'featured_img' => $image_url, 'msg' => 'Please fill-up the required fields.');
    // }
    return $result;
}
 static function post_attachment($download, $product_id)
 {
     // $filename should be the path to a file in the upload directory.
     // example $filename = 'woocommerce_uploads/2015/07/aka_Matrix42_Tool_CleanDatabase_7.2.1.20150625.aka.zip';
     $download = json_decode($download);
     $filename = $download->file;
     $web_url = $download->web_url;
     $wp_upload_dir = wp_upload_dir();
     $file = $wp_upload_dir['path'] . '/' . $filename;
     //Check the type of file. We'll use this as the 'post_mime_type'.
     $filetype = wp_check_filetype(basename($file), null);
     $attachment = array('guid' => $wp_upload_dir['url'] . '/' . basename($file), 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($file)), 'post_content' => '', 'post_status' => 'inherit');
     // Insert the attachment.
     $attach_id = wp_insert_attachment($attachment, $file, $product_id);
     // Make sure that this file is included, as wp_generate_attachment_metadata() depends on it.
     require_once ABSPATH . 'wp-admin/includes/image.php';
     // Generate the metadata for the attachment, and update the database record.
     $attach_data = wp_generate_attachment_metadata($attach_id, $file);
     wp_update_attachment_metadata($attach_id, $attach_data);
     // Get all existing post downloads and
     $files = array();
     $wc_product = wc_get_product($product_id);
     $untyped_array_of_downloads = $wc_product->get_files();
     foreach ($untyped_array_of_downloads as $download_key => $download_value) {
         $download_name = $download_value['name'];
         $download_url = $download_value['file'];
         $files[md5($download_url)] = array('name' => $download_name, 'file' => $download_url);
     }
     // Extend the existing post downloads by the new one
     $files[md5($download_url)] = array('name' => $filename, 'file' => $web_url);
     // Update post meta (_downloadable_files)
     update_post_meta($product_id, '_downloadable_files', $files);
     return 1;
 }
 /**
  * Helper function: insert an attachment to test properties of.
  *
  * @param int $parent_post_id
  * @param str path to image to use
  * @param array $post_fields Fields, in the format to be sent to `wp_insert_post()`
  * @return int Post ID of inserted attachment
  */
 private function insert_attachment($parent_post_id = 0, $image = null, $post_fields = array())
 {
     $filename = rand_str() . '.jpg';
     $contents = rand_str();
     if ($image) {
         // @codingStandardsIgnoreStart
         $filename = basename($image);
         $contents = file_get_contents($image);
         // @codingStandardsIgnoreEnd
     }
     $upload = wp_upload_bits($filename, null, $contents);
     $this->assertTrue(empty($upload['error']));
     $type = '';
     if (!empty($upload['type'])) {
         $type = $upload['type'];
     } else {
         $mime = wp_check_filetype($upload['file']);
         if ($mime) {
             $type = $mime['type'];
         }
     }
     $attachment = wp_parse_args($post_fields, array('post_title' => basename($upload['file']), 'post_content' => 'Test Attachment', 'post_type' => 'attachment', 'post_parent' => $parent_post_id, 'post_mime_type' => $type, 'guid' => $upload['url']));
     // Save the data
     $id = wp_insert_attachment($attachment, $upload['file'], $parent_post_id);
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file']));
     return $id;
 }
	function _make_attachment( $upload, $parent_post_id = 0 ) {

		$type = '';
		if ( !empty($upload['type']) ) {
			$type = $upload['type'];
		} else {
			$mime = wp_check_filetype( $upload['file'] );
			if ($mime)
				$type = $mime['type'];
		}

		$attachment = array(
			'post_title' => basename( $upload['file'] ),
			'post_content' => '',
			'post_type' => 'attachment',
			'post_parent' => $parent_post_id,
			'post_mime_type' => $type,
			'guid' => $upload[ 'url' ],
		);

		// Save the data
		$id = wp_insert_attachment( $attachment, $upload[ 'file' ], $parent_post_id );
		wp_update_attachment_metadata( $id, wp_generate_attachment_metadata( $id, $upload['file'] ) );

		return $this->ids[] = $id;

	}
 /**
  * @param strin $file_url
  *
  * @return int
  */
 private function upload_file($file_url)
 {
     if (!filter_var($file_url, FILTER_VALIDATE_URL)) {
         return false;
     }
     $contents = @file_get_contents($file_url);
     if ($contents === false) {
         return false;
     }
     $upload = wp_upload_bits(basename($file_url), null, $contents);
     if (isset($upload['error']) && $upload['error']) {
         return false;
     }
     $type = '';
     if (!empty($upload['type'])) {
         $type = $upload['type'];
     } else {
         $mime = wp_check_filetype($upload['file']);
         if ($mime) {
             $type = $mime['type'];
         }
     }
     $attachment = array('post_title' => basename($upload['file']), 'post_content' => '', 'post_type' => 'attachment', 'post_mime_type' => $type, 'guid' => $upload['url']);
     $id = wp_insert_attachment($attachment, $upload['file']);
     wp_update_attachment_metadata($id, wp_generate_attachment_metadata($id, $upload['file']));
     update_post_meta($id, '_tribe_importer_original_url', $file_url);
     $this->maybe_init_attachment_guids_cache();
     $this->maybe_init_attachment_original_urls_cache();
     self::$attachment_guids_cache[get_post($id)->guid] = $id;
     self::$original_urls_cache[$file_url] = $id;
     return $id;
 }
Example #14
0
 /**
  * Generates a new attachemnt.
  *
  * @since 1.0.0
  *
  * @access protected
  * @param array $args The array of arguments to use during a new attachment creation.
  * @return int The newly created attachment's ID on success, otherwise 0.
  */
 protected function _createObject($args = array())
 {
     if (empty($args['post_mime_type'])) {
         if (!empty($args['file']) && is_readable($args['file'])) {
             $this->_debug('Reading mime type of the file: ' . $args['file']);
             $filetype = wp_check_filetype(basename($args['file']), null);
             if (!empty($filetype['type'])) {
                 $args['post_mime_type'] = $filetype['type'];
                 $this->_debug('Mime type found: ' . $filetype['type']);
             } else {
                 $this->_debug('Mime type not found');
             }
         }
     }
     $attachment_id = wp_insert_attachment($args);
     if ($attachment_id) {
         $this->_debug('Generated attachment ID: %d (file: %s)', $attachment_id, !empty($args['file']) ? $args['file'] : 'not-provided');
         $this->_debug('Generating attachment metadata');
         $metadata = wp_generate_attachment_metadata($attachment_id, $args['file']);
         if (is_wp_error($metadata)) {
             $this->_debug('Attachment metadata generation failed with error [%s] %s', $metadata->get_error_code(), $metadata->get_error_message());
         } elseif (empty($metadata)) {
             $this->_debug('Attachment metadata generation failed');
         } else {
             wp_update_attachment_metadata($attachment_id, $metadata);
         }
     } else {
         $this->_debug('Attachment generation failed');
     }
     return $attachment_id;
 }
 static function uploadImage($img_url)
 {
     include_once ABSPATH . 'wp-admin/includes/file.php';
     //Contains download_url
     //Download $img_url
     $temporary_file = download_url($img_url);
     if (is_wp_error($temporary_file)) {
         throw new Exception('Error: ' . $temporary_file->get_error_message());
     } else {
         $upload_dir = wp_upload_dir();
         $local_img_path = $upload_dir['path'] . DIRECTORY_SEPARATOR . basename($img_url);
         //Local name
         $local_img_url = $upload_dir['url'] . '/' . basename($img_url);
         $moved = @rename($temporary_file, $local_img_path);
         if ($moved) {
             $wp_filetype = wp_check_filetype(basename($img_url), null);
             //Get the filetype to set the mimetype
             $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($img_url)), 'post_content' => '', 'post_status' => 'inherit');
             $attach_id = wp_insert_attachment($attachment, $local_img_path);
             //Insert the image in the database
             require_once ABSPATH . 'wp-admin/includes/image.php';
             $attach_data = wp_generate_attachment_metadata($attach_id, $local_img_path);
             wp_update_attachment_metadata($attach_id, $attach_data);
             //Update generated metadata
             return array('id' => $attach_id, 'url' => $local_img_url);
         }
     }
     if (file_exists($temporary_file)) {
         unlink($temporary_file);
     }
     return null;
 }
Example #16
0
 public function import($attachment)
 {
     $saved_image = $this->_return_saved_image($attachment);
     if ($saved_image) {
         return $saved_image;
     }
     // Extract the file name and extension from the url
     $filename = basename($attachment['url']);
     if (function_exists('file_get_contents')) {
         $options = ['http' => ['user_agent' => 'Mozilla/5.0 (X11; Ubuntu; Linux i686 on x86_64; rv:49.0) Gecko/20100101 Firefox/49.0']];
         $context = stream_context_create($options);
         $file_content = file_get_contents($attachment['url'], false, $context);
     } else {
         $file_content = wp_remote_retrieve_body(wp_safe_remote_get($attachment['url']));
     }
     if (empty($file_content)) {
         return false;
     }
     $upload = wp_upload_bits($filename, null, $file_content);
     $post = ['post_title' => $filename, 'guid' => $upload['url']];
     $info = wp_check_filetype($upload['file']);
     if ($info) {
         $post['post_mime_type'] = $info['type'];
     } else {
         // For now just return the origin attachment
         return $attachment;
         //return new \WP_Error( 'attachment_processing_error', __( 'Invalid file type', 'elementor' ) );
     }
     $post_id = wp_insert_attachment($post, $upload['file']);
     wp_update_attachment_metadata($post_id, wp_generate_attachment_metadata($post_id, $upload['file']));
     update_post_meta($post_id, '_elementor_source_image_hash', $this->_get_hash_image($attachment['url']));
     $new_attachment = ['id' => $post_id, 'url' => $upload['url']];
     $this->_replace_image_ids[$attachment['id']] = $new_attachment;
     return $new_attachment;
 }
/**
 * The default mimetype match is for "application/*". For other types, you
 * will need to specifically override that attribute.
 * Examples:
 *
 * Just .XLS files:
 *   [documents ext="xls"]
 *
 * All .DOC, .DOCX, or .PDF files:
 *   [documents ext="doc,docx,pdf"]
 * 
 * Only 'video' types with a .MOV extension:
 *   [documents mimetype="video" ext="mov"]
 * 
 * Just application/pdf mimetypes:
 *   [documents mimetype="application/pdf"]
 */
function dc_document_shortcode($atts)
{
    extract(shortcode_atts(array('mimetype' => 'application', 'ext' => null), $atts));
    $mime = "&post_mime_type={$mimetype}";
    $kids =& get_children('post_type=attachment&post_parent=' . get_the_id() . $mime);
    if (empty($kids)) {
        return '';
    }
    $exts = array();
    if ($ext) {
        $exts = explode(',', $ext);
        $exts = array_map('trim', $exts);
        $exts = array_map('strtolower', $exts);
    }
    $documents = '';
    foreach ($kids as $id => $doc) {
        $url = wp_get_attachment_url($id);
        $file = get_attached_file($id);
        $filetype = wp_check_filetype($file);
        $file_ext = strtolower($filetype['ext']);
        if (count($exts) && !in_array($file_ext, $exts)) {
            // Not in list of requested extensions. Skip it!
            continue;
        }
        $name = $doc->post_title;
        $mime = sanitize_title_with_dashes($file_ext);
        $documents .= "<li class='{$mime}'><a href='{$url}'>{$name}</a></li>\n";
    }
    if (!empty($documents)) {
        // Wrap it up:
        $documents = "<ul class='dc_documents'>\n" . $documents;
        $documents .= "</ul>\n";
    }
    return $documents;
}
Example #18
0
 /**
  * Returns an array that holds the field data, suitable for JSON representation.
  * This data will be available in the Underscore template and the Backbone Model.
  *
  * @param bool $load  Should the value be loaded from the database or use the value from the current instance.
  * @return array
  */
 public function to_json($load)
 {
     $field_data = parent::to_json($load);
     $url = '';
     $thumb_url = '';
     $default_thumb_url = includes_url('/images/media/default.png');
     $file_ext = '';
     $file_type = '';
     $value = $this->get_value();
     if ($value) {
         $url = is_numeric($value) ? wp_get_attachment_url($value) : $value;
         $filetype = wp_check_filetype($url);
         $file_ext = $filetype['ext'];
         // png, mp3, etc..
         $file_type = preg_replace('~\\/.+$~', '', $filetype['type']);
         // image, video, etc..
         if ($file_type == 'image') {
             $thumb_url = $url;
             if ($this->value_type == 'id') {
                 $thumb_src = wp_get_attachment_image_src($value, 'thumbnail');
                 $thumb_url = $thumb_src[0];
             }
         } else {
             $thumb_url = $default_thumb_url;
         }
     }
     $field_data = array_merge($field_data, array('url' => (string) $url, 'thumb_url' => $thumb_url, 'default_thumb_url' => $default_thumb_url, 'file_ext' => $file_ext, 'file_type' => $file_type, 'button_label' => $this->button_label, 'window_button_label' => $this->window_button_label, 'window_label' => $this->window_label, 'type_filter' => $this->field_type, 'value_type' => $this->value_type));
     return $field_data;
 }
 function get_template_variables($instance, $args)
 {
     static $player_id = 1;
     $poster = '';
     $video_host = $instance['host_type'];
     if ($video_host == 'self') {
         if (!empty($instance['video']['self_video'])) {
             // Handle an attachment video
             $src = wp_get_attachment_url($instance['video']['self_video']);
             $vid_info = wp_get_attachment_metadata($instance['video']['self_video']);
             $video_type = 'video/' . empty($vid_info['fileformat']) ? '' : $vid_info['fileformat'];
         } else {
             if (!empty($instance['video']['self_video_fallback'])) {
                 // Handle an external URL video
                 $src = $instance['video']['self_video_fallback'];
                 $vid_info = wp_check_filetype(basename($instance['video']['self_video_fallback']));
                 $video_type = $vid_info['type'];
             }
         }
         $poster = !empty($instance['video']['self_poster']) ? wp_get_attachment_url($instance['video']['self_poster']) : '';
     } else {
         $video_host = $this->get_host_from_url($instance['video']['external_video']);
         $video_type = 'video/' . $video_host;
         $src = !empty($instance['video']['external_video']) ? $instance['video']['external_video'] : '';
     }
     $return = array('player_id' => 'sow-player-' . $player_id++, 'host_type' => $instance['host_type'], 'src' => $src, 'video_type' => $video_type, 'is_skinnable_video_host' => $this->is_skinnable_video_host($video_host), 'poster' => $poster, 'autoplay' => !empty($instance['playback']['autoplay']), 'skin_class' => 'default');
     // Force oEmbed for this video
     if ($instance['host_type'] == 'external' && $instance['playback']['oembed']) {
         $return['is_skinnable_video_host'] = false;
     }
     return $return;
 }
Example #20
0
function filter_year_post()
{
    global $wpdb;
    error_reporting(0);
    if (!wp_verify_nonce($_POST['nonce'], 'yearpost')) {
        die;
    }
    $post = get_post($_POST['postid']);
    $post->url = wp_get_attachment_url($post->ID);
    $post->year = $post->post_title;
    $post->has_excel = false;
    // Default is that year does not have any excel files associated with it
    $title_exists = $wpdb->get_results($wpdb->prepare("SELECT ID FROM wp_posts\n            WHERE post_title = %s\n            AND post_type = 'attachment'", $post->year));
    foreach ($title_exists as $title_exist) {
        // checks to see if the file is an excel file and then adds an icon
        $attachmentPathExcel = wp_get_attachment_url($title_exist->ID);
        if (wp_check_filetype($attachmentPathExcel)['ext'] == 'xlsx' || wp_check_filetype($attachmentPathExcel)['ext'] == 'xls') {
            $post->has_excel = true;
            $post->excel_url = $attachmentPathExcel;
        }
    }
    if (empty($post) || !is_object($post)) {
        die;
    }
    header('Cache-Control: no-cache, must-revalidate');
    header('Content-type: application/json');
    echo json_encode($post);
    die;
}
Example #21
0
 function file_import()
 {
     if (wp_verify_nonce($_POST['nonce'], "molie_admin_file")) {
         $post = get_post($_POST['course_post']);
         $file_system = get_post_meta($post->ID, "courseFileSystem", true);
         $file_contents = file_get_contents($_POST['url']);
         file_put_contents($file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename'], $file_contents);
         $filetype = wp_check_filetype(basename($file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename']), null);
         echo $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename'] . "<br />";
         $attachment = array('guid' => $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename'], 'post_mime_type' => $filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($_POST['filename'])), 'post_content' => '', 'post_status' => 'inherit');
         $attach_id = wp_insert_attachment($attachment, $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename']);
         $data = wp_generate_attachment_metadata($attach_id, $file_system[$_POST['folder']]['actual_path'] . "/" . $_POST['filename']);
         update_post_meta($attach_id, "_wp_attachment_metadata", $data, true);
         update_post_meta($post->ID, "molie_file_" . $_POST['item'], $attach_id);
         update_post_meta($attach_id, "CanvasCourse", get_post_meta($post->ID, "courseID", true));
         update_post_meta($attach_id, "CanvasFileVerifier", $_POST['verifier']);
         update_post_meta($attach_id, "CanvasCourseIDFileID", get_post_meta($post->ID, "courseID", true) . "," . $_POST['item']);
         $file_url = get_post_meta($post->ID, "courseURL", true) . "/courses/" . get_post_meta($post->ID, "courseID", true) . "/files/" . $_POST['item'] . "/download?verifier=" . $_POST['verifier'];
         update_post_meta($attach_id, "CanvasFileURL", $file_url);
         echo __("File Downloaded");
     } else {
         echo "Nonce failed";
     }
     wp_die();
 }
 /**
  *
  */
 public static function validate_file_upload($file_upload_param)
 {
     $count = 0;
     $max_file_size = 200000000;
     $validation_errors = array();
     if (!empty($_FILES)) {
         foreach ($_FILES[$file_upload_param]['name'] as $filename) {
             if ($_FILES[$file_upload_param]['tmp_name'][$count] != '') {
                 // Setup the array of supported file types. In this case, it's just PDF.
                 $supported_types = array('image/jpeg', 'image/png', 'image/gif', 'application/pdf', 'application/vnd.ms-excel', 'application/msword', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.openxmlformats-officedocument.wordprocessingml.document');
                 // Get the file type of the upload
                 $arr_file_type = wp_check_filetype(basename($_FILES[$file_upload_param]['name'][$count]));
                 $uploaded_type = $arr_file_type['type'];
                 // Check if the type is supported. If not, throw an error.
                 if (!in_array($uploaded_type, $supported_types)) {
                     $supported = 'Supported files types are: Ms Word, Ms Excel, PDF';
                     $validation_errors['file_upload_error_msg'][$count] = 'The type of file you have uploaded is not supported. ' . $filename . '. ' . $supported;
                 }
                 // Check file size
                 if ($_FILES[$file_upload_param]['size'][$count] > $max_file_size) {
                     $validation_errors['file_upload_error_msg'][$count] = 'The file size is beyond the allowed maximum of 20MB';
                 }
             }
             $count++;
         }
     }
     return $validation_errors;
 }
Example #23
0
/**
 * Checks for valid EPUB3 video or audio file names.
 *
 * @param string $pathToFile
 * @param string $filename
 *
 * @return boolean
 */
function is_valid_media($pathToFile, $filename)
{
    $validate = wp_check_filetype($filename, add_mime_types());
    if (false === $validate['ext'] || false === $validate['type']) {
        return false;
    }
    return true;
}
function of_sanitize_upload( $input ) {
	$output = '';
	$filetype = wp_check_filetype($input);
	if ( $filetype["ext"] ) {
		$output = $input;
	}
	return $output;
}
 /**
  * Sanitizing uploads
  *
  * @param $input_image
  */
 function horizon_theme_sanitize_image($input_image)
 {
     $output = '';
     $filetype = wp_check_filetype($input_image);
     if ($filetype["ext"]) {
         $output = $input_image;
     }
     return $output;
 }
Example #26
0
function ce_upload_attachment($filename, $post_id)
{
    $wp_filetype = wp_check_filetype(basename($filename), null);
    $wp_upload_dir = wp_upload_dir();
    $attachment = array('guid' => $filename, 'post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($filename)), 'post_content' => '', 'post_status' => 'inherit');
    $attach_id = wp_insert_attachment($attachment, $filename, $post_id);
    wp_update_post(array('ID' => $attach_id, 'post_title' => '123', 'guid' => $filename));
    return $attach_id;
}
/**
 * Returns a sanitized filepath if it has a valid extension.
 */
function NovelLite_sanitize_upload($upload)
{
    $return = '';
    $fype = wp_check_filetype($upload);
    if ($fype["ext"]) {
        $return = esc_url_raw($upload);
    }
    return $return;
}
 /**
  * Sanitize the url of uploaded media.
  *
  * @since 1.0.0.
  *
  * @param  string    $value      The url to sanitize
  * @return string    $output     The sanitized url.
  */
 function customizer_library_sanitize_file_url($url)
 {
     $output = '';
     $filetype = wp_check_filetype($url);
     if ($filetype["ext"]) {
         $output = esc_url($input);
     }
     return $output;
 }
Example #29
-1
function wpmp_add_product()
{
    if (wp_verify_nonce($_POST['__product_wpmp'], 'wpmp-product') && $_POST['task'] == '') {
        if ($_POST['post_type'] == "wpmarketplace") {
            global $current_user, $wpdb;
            get_currentuserinfo();
            $my_post = array('post_title' => $_POST['product']['post_title'], 'post_content' => $_POST['product']['post_content'], 'post_excerpt' => $_POST['product']['post_excerpt'], 'post_status' => "draft", 'post_author' => $current_user->ID, 'post_type' => "wpmarketplace");
            //echo $_POST['id'];
            if ($_POST['id']) {
                //update post
                $my_post['ID'] = $_REQUEST['id'];
                wp_update_post($my_post);
                $postid = $_REQUEST['id'];
            } else {
                //insert post
                $postid = wp_insert_post($my_post);
            }
            update_post_meta($postid, "wpmp_list_opts", $_POST['wpmp_list']);
            foreach ($_POST['wpmp_list'] as $k => $v) {
                update_post_meta($postid, $k, $v);
            }
            //echo $_POST['wpmp_list']['fimage'];
            if ($_POST['wpmp_list']['fimage']) {
                $wp_filetype = wp_check_filetype(basename($_POST['wpmp_list']['fimage']), null);
                $attachment = array('post_mime_type' => $wp_filetype['type'], 'post_title' => preg_replace('/\\.[^.]+$/', '', basename($_POST['wpmp_list']['fimage'])), 'post_content' => '', 'guid' => $_POST['wpmp_list']['fimage'], 'post_status' => 'inherit');
                $attach_id = wp_insert_attachment($attachment, $_POST['wpmp_list']['fimage'], $postid);
                set_post_thumbnail($postid, $attach_id);
            }
        }
        //echo $_SERVER['HTTP_REFERER'];
        header("Location: " . $_SERVER['HTTP_REFERER']);
        die;
    }
}
 public function save_pdf_data($pos_id)
 {
     if (!wp_verify_nonce($_POST['wp_pdf_attachment_nonce'], plugin_basename(__FILE__))) {
         return $pos_id;
     }
     if (defined('DOING_AUTOSAVE') && DOING_AUTOSAVE) {
         return $pos_id;
     }
     if ('page' == $_POST['post_type']) {
         if (!current_user_can('edit_page', $pos_id)) {
             return $pos_id;
         }
     } else {
         if (!current_user_can('edit_page', $pos_id)) {
             return $pos_id;
         }
     }
     if (!empty($_FILES['wp_pdf_attachment']['name'])) {
         $types = array('application/pdf');
         $files = wp_check_filetype(basename($_FILES['wp_pdf_attachment']['name']));
         // return array
         $uploaded_types = $files['type'];
         if (in_array($uploaded_type, $types)) {
             $upload = media_handle_upload("wp_pdf_attachment", $pos_id, file_get_contents($_FILES['wp_pdf_attachment']['tmp_name']));
             if (isset($upload['error']) && $upload['error'] != 0) {
                 wp_die('Error: ' . $upload['error']);
             } else {
                 add_post_meta($pos_id, 'wp_pdf_attachment', $upload);
                 update_post_meta($pos_id, 'wp_pdf_attachment', $upload);
             }
         } else {
             wp_die("The file type that you've uploaded is not a PDF.");
         }
     }
 }