Skip to content

Instantly share code, notes, and snippets.

@jtsternberg
Created May 8, 2014 18:08
Show Gist options
  • Save jtsternberg/30d94c65add3c9b89407 to your computer and use it in GitHub Desktop.
Save jtsternberg/30d94c65add3c9b89407 to your computer and use it in GitHub Desktop.
Handles migrating images to local database/file-system
<?php
/*
Plugin Name: Fix Image Paths
Plugin URI: http://webdevstudios.com
Description: Plugin used to fix images that did not import properly in the MigrationService Plugin.
Author: WebDevStudios
Author URI: http://webdevstudios.com
Version: 1.0.0
License: GPLv2
*/
///wp-admin?run-trisha-import=true&posts-offset=0
add_action( 'admin_menu', 'add_image_path_fix_menu' );
function add_image_path_fix_menu() {
add_management_page(
'Fix Image Paths',
'Fix Image Paths',
'manage_options',
'fix-image-paths',
'display_fix_image_path_page'
);
}
function display_fix_image_path_page() {?>
<form name="form1" method="post" action="">
<p><label for="accepted"><input type="checkbox" value="Accept" id="accepted" name="accepted" /> I have reviewed the settings above and want to run the tool.</label></p>
<p class="submit">
<input type="submit" name="Submit" class="button-primary" value="<?php esc_attr_e('Fix the Image Paths') ?>" />
</p>
</form>
<?
}
class TrishasImageImporter {
public function __construct( $args, $test_run ) {
$this->test_run = $test_run;
$this->process_all_posts( $args );
}
public function process_all_posts( $args ) {
$posts = get_posts( $args );
if ( $posts ) {
foreach ( $posts as $post ) {
$this->post_id = $post->ID;
$post->post_content = $this->formatHTML( $post->post_content, true );
if ( $this->test_run ) {
wp_die( '<xmp>'. print_r( $post->post_content, true ) .'</xmp>' );
}
wp_update_post( $post );
}
}
}
public function maybe_import_this( $content ) {
$pattern = '([^\"]*\.(jpg|png|bmp|JPG))';
$found_match = preg_match( $pattern, $content, $matches );
if ( ! $found_match ) {
// No images to import here
return false;
}
if ( false != stripos( $matches[0], site_url() ) ) {
// Image is already local to this site.. do not import
return false;
}
return $matches[0];
}
public function maybe_sideload( $image, $attr ) {
$imagesrc = $image->getAttribute( $attr );
if ( isset( $this->images_imported[ $imagesrc ] ) ) {
$image->setAttribute( $attr, $this->images_imported[ $imagesrc ][ 'url' ] );
return false;
}
$imagesrc = $this->maybe_import_this( $imagesrc );
if ( ! $imagesrc ) {
return false;
}
echo '<xmp>'. print_r( $imagesrc, true ) .'</xmp>';
$attachment = $this->handle_sideload( $image_src );
//wp_die( '<xmp>'. print_r( $attachment, true ) .'</xmp>' );
echo 'Error Messages: ';
if ( is_wp_error( $attachment ) ) {
// log error, show error
echo $attachment->get_error_message( $this->post_id ) . '<br />';
return false;
}
$new_url = $attachment[ 'url' ];
$image->setAttribute( $attr, $new_url );
return $image;
}
/**
* @param $html_content
* @param string|bool $replaceUrl If string, replace URLs, if set to true then it will import
*
* @return mixed
*/
public function formatHTML( $html_content, $replaceUrl ) {
if ( empty( $html_content ) ) {
return $html_content;
}
// check for emojicons
$html_content = str_replace( "\xF0\x9F\x98\x83", ":)", $html_content );
$dom = new DOMDocument;
libxml_use_internal_errors( true ); //hide errors on the load due to the HTML 5 glitch
$dom->loadHTML( $html_content );
libxml_use_internal_errors( false ); //show errors moving forward
// Check for images
$images = $dom->getElementsByTagName( 'img' );
foreach ( $images as $image ) {
$image = $this->maybe_sideload( $image, 'src' );
}
// check for links to images/files that are full size.
$imagelinks = $dom->getElementsByTagName( 'a' );
foreach ( $imagelinks as $imagelink ) {
$imagelink = $this->maybe_sideload( $imagelink, 'href' );
}
// //now check for internal links that do not have the full bing blogs url
// $links = $dom->getElementsByTagName( 'a' );
// foreach ( $links as $link ) {
// if ( substr( $link->getAttribute( 'href' ), 0, 3 ) == "/b/" ) {
// $link->setAttribute( 'href', 'http://' . $this->this_domain . $link->getAttribute( 'href' ) );
// }
// }
$updated_html_content = preg_replace( '/^<!DOCTYPE.+?>/', '', str_replace( array(
'<html>',
'</html>',
'<body>',
'</body>'
), array(
'',
'',
'',
''
), $dom->saveHTML() ) );
//$updated_html_content = $dom->saveHTML();
return $updated_html_content;
}
public function handle_sideload( $file, $generate_metadata = false ) {
if ( isset( $this->images_imported[ $file ] ) ) {
return $this->images_imported[ $file ];
}
// Download file to temp location
$tmp = download_url( $file );
// Set variables for storage
// fix file filename for query strings
preg_match( '/[^\?]+\.(jpe?g|jpe|JPG|gif|png|bmp)\b/i', $file, $matches );
$file_array = array(
'name' => basename( $matches[1] ),
'tmp_name' => $tmp
);
// If error storing temporarily
if ( is_wp_error( $tmp ) ) {
$file_array[ 'tmp_name' ] = '';
return $tmp;
}
// do the validation and storage stuff
$id = media_handle_sideload( $file_array, $this->post_id );
// If error storing permanently, unlink
if ( is_wp_error( $id ) ) {
if ( !empty( $file_array[ 'tmp_name' ] ) ) {
@unlink( $file_array[ 'tmp_name' ] );
}
return $id;
}
$fullsizepath = get_attached_file( $id );
if ( false === $fullsizepath || ! file_exists( $fullsizepath ) ) {
return new WP_Error( '', 'Image not saved correctly for resizing' );
}
if ( $generate_metadata ) {
$metadata = wp_generate_attachment_metadata( $id, $fullsizepath );
if ( is_wp_error( $metadata ) ) {
return $metadata;
}
elseif ( empty( $metadata ) ) {
return new WP_Error( '', 'Image resizing incomplete' );
}
// If this fails, then it just means that nothing was changed (old value == new value)
wp_update_attachment_metadata( $id, $metadata );
}
$url = wp_get_attachment_url( $id );
return array( 'ID' => $id, 'url' => $url );
}
}
add_action( 'admin_init', 'trisha_script_init' );
function trisha_script_init() {
if ( isset( $_GET['run-trisha-import'] ) ) {
$per_page = 5;
$args = array(
'posts_per_page' => $per_page,
'offset' => isset( $_GET['posts-offset'] ) ? ( absint( $_GET['posts-offset'] ) * $per_page ) : 0,
);
$test_run = 'test-run' == $_GET['run-trisha-import'];
new TrishasImageImporter( $args, $test_run );
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment