Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

VIP #8

Open
wants to merge 29 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
29 commits
Select commit Hold shift + click to select a range
0961ef4
vip
mattheu Aug 13, 2015
946e1ad
pass parent id
mattheu Aug 13, 2015
9a4328b
bugfixes
mattheu Aug 13, 2015
45ea0a5
More bugfixes
mattheu Aug 13, 2015
e11750d
instructions
mattheu Aug 13, 2015
d1c6e14
disable admin
mattheu Aug 14, 2015
b05d994
use POST not REQUEST
mattheu Aug 14, 2015
a4cb55e
store meta data
mattheu Aug 14, 2015
1d1d6c7
fix JS error
mattheu Aug 14, 2015
136d66f
Get the admin frame working
mattheu Aug 26, 2015
91e4a3a
sync
mattheu Aug 26, 2015
687b2cf
Switched plugins_loaded hook to init, required VIP
tcrsavage Sep 4, 2015
abdf4d6
Featured image tab
mattheu Sep 29, 2015
378df93
Handle setting featured image
mattheu Sep 30, 2015
fbf6c97
Allow plugins to hook in and add do stuff on import
mattheu Sep 30, 2015
6aa1f05
Merge pull request #9 from humanmade/featured-image
mattheu Sep 30, 2015
2a26f56
remove test
mattheu Sep 30, 2015
075220a
Merge pull request #10 from humanmade/meta-2
mattheu Sep 30, 2015
66be5fb
fix php error
mattheu Sep 30, 2015
a70b3bd
Don't use prettyfieldnames
mattheu Sep 30, 2015
66adf06
allow defining custom path/urls
mattheu Sep 30, 2015
617f79a
merged vip escaping
Oct 29, 2015
d50687a
remove unnecessary function
Nov 2, 2015
a071e17
Remove debug
mattheu Nov 12, 2015
2338094
bump version to ensure user caps are correct
mattheu Nov 12, 2015
0c93063
Encode request args - breaks 2 word searches
mattheu Nov 17, 2015
24e0605
Merge pull request #12 from humanmade/fix-2-word-search
pdewouters Nov 19, 2015
103193d
remove site specific code
mattheu Dec 7, 2015
fcc6d54
fix admin frame loading bug
mattheu Dec 7, 2015
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions helpers.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
<?php

if ( ! function_exists( 'wpcom_vip_download_image' ) ) {

/**
* Downloads an external image and optionally attaches it to a post.
*
* Contains most of core's media_sideload_image() but returns an attachment ID instead of HTML.
*
* Note: this function does not validate the domain that the image is coming from. Please make sure
* to validate this before downloading the image. Should only pull down images from trusted sources.
*
* @param string $image_url URL of the image.
* @param int $post_ID ID of the post it should be attached to.
* @return $thumbnail_id id of the thumbnail attachment post id
*/
function wpcom_vip_download_image( $image_url, $post_id = 0, $description = '' ) {
if ( isset( $_SERVER['REQUEST_METHOD'] ) && strtoupper( $_SERVER['REQUEST_METHOD'] ) == 'GET' ) {
return new WP_Error( 'invalid-request-method', 'Media sideloading is not supported via GET. Use POST.' );
}

if ( ! is_admin() ) {
return new WP_Error( 'not-in-admin', 'Media sideloading can only be done in when `true === is_admin()`.' );
}

if ( $post_id < 0 ) {
return new WP_Error( 'invalid-post-id', 'Please specify a valid post ID.' );
}

if ( ! filter_var( $image_url, FILTER_VALIDATE_URL ) ) {
return new WP_Error( 'not-a-url', 'Please specify a valid URL.' );
}

$image_url_path = parse_url( $image_url, PHP_URL_PATH );
$image_path_info = pathinfo( $image_url_path );

if ( ! in_array( strtolower( $image_path_info['extension'] ), array( 'jpg', 'jpe', 'jpeg', 'gif', 'png' ) ) ) {
return new WP_Error( 'not-an-image', 'Specified URL does not have a valid image extension.' );
}

// Download file to temp location; short timeout, because we don't have all day.
$downloaded_url = download_url( $image_url, 30 );

// We couldn't download and store to a temporary location, so bail.
if ( is_wp_error( $downloaded_url ) ) {
return $downloaded_url;
}

$file_array['name'] = $image_path_info['basename'];
$file_array['tmp_name'] = $downloaded_url;

if ( empty( $description ) ) {
$description = $image_path_info['filename'];
}

// Now, let's sideload it.
$attachment_id = media_handle_sideload( $file_array, $post_id, $description );

// If error storing permanently, unlink and return the error
if ( is_wp_error( $attachment_id ) ) {
@unlink( $file_array['tmp_name'] ); // unlink can throw errors if the file isn't there
return $attachment_id;
}

return $attachment_id;
}

}
12 changes: 5 additions & 7 deletions inc/class-mexp-resource-space-service.php
Original file line number Diff line number Diff line change
Expand Up @@ -50,19 +50,17 @@ public function request( array $request ) {
$request['page'] = ( $request['page'] < 1 ) ? 1 : $request['page'];

// Build the request URL.
$api_url = add_query_arg(
apply_filters( 'resourcespace_request_args', array(
$args = array_map( 'rawurlencode', apply_filters( 'resourcespace_request_args', array(
'search' => sanitize_text_field( $request['params']['q'] ),
'key' => PJ_RESOURCE_SPACE_KEY,
'previewsize' => 'pre',
'prettyfieldnames' => true,
'original' => true,
'results_per_page' => PJ_RESOURCE_SPACE_RESULTS_PER_PAGE,
'page' => absint( $request['page'] ),
'restypes' => 1, // Restrict to images only.
) ),
sprintf( '%s/plugins/api_search/', PJ_RESOURCE_SPACE_DOMAIN )
);
) ) );

$api_url = add_query_arg( $args, sprintf( '%s/plugins/api_search/', PJ_RESOURCE_SPACE_DOMAIN ) );

$request_args = array(
'headers' => array()
Expand All @@ -88,7 +86,7 @@ public function request( array $request ) {
'date' => strtotime( $resource->creation_date ),
'id' => $resource->ref,
'thumbnail' => $resource->preview,
'url' => $resource->original_link,
'url' => null,
);

$dirty_data = apply_filters( 'resourcespace_parse_raw_image_data', $dirty_data, $resource );
Expand Down
7 changes: 6 additions & 1 deletion inc/class-resource-space-admin.php
Original file line number Diff line number Diff line change
Expand Up @@ -65,13 +65,18 @@ function admin_enqueue_scripts() {
$deps = array( 'jquery', 'backbone', 'media' );
wp_enqueue_script( 'resource-space-admin', PJ_RESOURCE_SPACE_PLUGIN_URL . '/js/admin.js', $deps, PJ_RESOURCESPACE_PLUGIN_VERSION, true );

wp_localize_script( 'media-grid', '_wpMediaGridSettings', array(
'adminUrl' => parse_url( self_admin_url(), PHP_URL_PATH ),
'queryVars' => (object) array( 'meta_query' => 'resource_space' ),
) );

}

}

function ajax_query_attachments_args( $query ) {

if ( isset( $_REQUEST['query']['meta_query'] ) && 'resource_space' === $_REQUEST['query']['meta_query'] ) {
if ( isset( $_POST['query']['meta_query'] ) && 'resource_space' === $_POST['query']['meta_query'] ) {
$query['meta_query'] = array(
array(
'key' => 'resource_space',
Expand Down
89 changes: 12 additions & 77 deletions inc/class-resource-space-loader.php
Original file line number Diff line number Diff line change
Expand Up @@ -35,17 +35,15 @@ function ajax_get_image() {
wp_send_json_error( esc_html__( 'Empty resource id', 'resourcespace' ) );
}

$url = PJ_RESOURCE_SPACE_DOMAIN . '/plugins/api_search/';
$key = PJ_RESOURCE_SPACE_KEY;

$url = add_query_arg( array(
'key' => $key,
$args = array_map( 'rawurlencode', array(
'key' => PJ_RESOURCE_SPACE_KEY,
'search' => $resource_id,
'prettyfieldnames' => 1,
'previewsize' => 'pre',
'prettyfieldnames' => false,
'original' => true,
), $url );
'previewsize' => 'scr',
) );

$url = add_query_arg( $args, PJ_RESOURCE_SPACE_DOMAIN . '/plugins/api_search/' );
$request_args = array( 'headers' => array() );

// Pass basic auth header if available.
Expand All @@ -66,10 +64,13 @@ function ajax_get_image() {
}

// Request original URL.
// $attachment_id = $this->sideload_image( $data[0]->original );
$attachment_id = wpcom_vip_download_image( $data[0]->preview );

// Update Metadata.
update_post_meta( $attachment_id, 'resource_space', 1 );

// Request preview size.
$attachment_id = $this->sideload_image( $data[0]->preview );
// Allow plugins to hook in here.
do_action( 'resourcespace_import_complete', $attachment_id, $data[0] );

if ( is_wp_error( $attachment_id ) ) {
wp_send_json_error( $attachment_id->get_error_message() );
Expand All @@ -81,70 +82,4 @@ function ajax_get_image() {

}

private function sideload_image( $url ) {

$request_args = array( 'headers' => array() );

// Pass basic auth header if available.
if ( defined( 'PJ_RESOURCE_SPACE_AUTHL' ) && defined( 'PJ_RESOURCE_SPACE_AUTHP' ) ) {
$request_args['headers']['Authorization'] = 'Basic ' . base64_encode( PJ_RESOURCE_SPACE_AUTHL . ':' . PJ_RESOURCE_SPACE_AUTHP );
}

// TODO test. Advice from Kirill was to use the users cookie.
// Hopefully it isn't required as this isn't as robust as using basic auth.
$response = wp_remote_get( $url, $request_args );

if ( 200 == wp_remote_retrieve_response_code( $response ) ) {

$file = get_temp_dir() . sanitize_file_name( $data[0]->Original_filename );
file_put_contents( $file, wp_remote_retrieve_body( $response ) );

$filename = basename( $file );

$upload_file = wp_upload_bits( $filename, null, file_get_contents( $file ) );

if ( ! $upload_file['error'] ) {

$wp_filetype = wp_check_filetype( $filename, null );

$attachment = array(
'post_mime_type' => $wp_filetype['type'],
'post_parent' => 0,
'post_title' => $data[0]->{'Légende'},
'post_content' => 'Downloaded ' . current_time( 'd/m/Y \a\t H:i:s' ),
'post_status' => 'inherit',
);

$attachment_id = wp_insert_attachment( $attachment, $upload_file['file'], $parent_post_id );

if ( ! is_wp_error( $attachment_id ) ) {

require_once( trailingslashit( ABSPATH ) . 'wp-admin/includes/image.php' );

$attachment_data = wp_generate_attachment_metadata( $attachment_id, $upload_file['file'] );
$attachment_data['image_meta']['created_timestamp'] = current_time( 'Y-m-d H:i:s', true );

wp_update_attachment_metadata( $attachment_id, $attachment_data );

add_post_meta( $attachment_id, 'resource_space', true, true );

return $attachment_id;

} else {
unlink( $file );
return new WP_Error( 'broke', esc_html__( 'Could not create attachment', 'resourcespace' ) );
}
} else {
unlink( $file );
return new WP_Error( 'broke', esc_html__( 'Upload error', 'resourcespace' ) );
}

unlink( $file );

} else {
return new WP_Error( 'broke', esc_html__( 'Unable to retrieve image', 'resourcespace' ) );
}

}

}
58 changes: 24 additions & 34 deletions js/admin.js
Original file line number Diff line number Diff line change
@@ -1,8 +1,16 @@
(function ( $ ) {

var $oldContainer = ('#resource-space-images');
var $oldContainer = $('#resource-space-images');
var $newContainer = $('#resource-space-new-images');

var wp_media_frame;

var library = window.wp.media({
frame: 'manage',
container: $oldContainer,
library: _wpMediaGridSettings.queryVars,
}).open();

jQuery('#resource-space-add-new').on( 'click', function( event ) {

event.preventDefault();
Expand All @@ -13,51 +21,33 @@
$newContainer.show();
}

// Loop through attachments and build image element HTML.
_.each( this.attachments, function( attachment ) {
library.state().attributes.library.add( attachment );
});

var $img = $('<img />');
var size = 'medium';

if ( attachment.sizes[ size ] ) {
$img.attr( 'src', attachment.sizes[ size ].url );
$img.attr( 'width', attachment.sizes[ size ].width );
$img.attr( 'height', attachment.sizes[ size ].height );
} else {
$img.attr( 'src', attachment.url );
$img.attr( 'width', attachment.width );
$img.attr( 'height', attachment.height );
}

$img.attr( 'alt', attachment.title );

$img.addClass( 'alignnone' );
$img.addClass( 'size-' + size );
$img.addClass( 'wp-image-' + attachment.id );
this.complete();

$newContainer.append( $img );
}

if ( ! wp_media_frame ) {
wp_media_frame = wp.media.frames.wp_media_frame = wp.media({
frame : "post",
state : 'mexp-service-resource-space',
resourceSpaceInsertCallback: insertImages,
});

this.complete();
// Hack to get load more working.
wp_media_frame.on( 'open', function() {
jQuery( '#resource-space-loadmore' ).click( function( event ) {
wp.media.frame.views.get('.media-frame-content' )[0].paginate( event );
} );
} );

}

var wp_media_frame = wp.media.frames.wp_media_frame = wp.media({
frame : "post",
state : 'mexp-service-resource-space',
resourceSpaceInsertCallback: insertImages,
});

wp_media_frame.open();
wp_media_frame.$el.addClass( 'hide-menu' );

});

window.wp.media({
frame: 'manage',
container: $oldContainer,
library: { 'meta_query': 'resource_space' },
}).open();

}( jQuery ));
Loading