Skip to content

Instantly share code, notes, and snippets.

@zrothauser
Last active October 19, 2017 22:26
Show Gist options
  • Save zrothauser/e870bf7db582780fe3ec138b33f13872 to your computer and use it in GitHub Desktop.
Save zrothauser/e870bf7db582780fe3ec138b33f13872 to your computer and use it in GitHub Desktop.
<?php
/**
* Importer for XML events out of the old Ektron CMS into
* All-in-One Events Calendar events, with the custom fields
* set up for the Warhol site.
*/
namespace Carnegie_Museums\Warhol\Event_Importer;
// Constants
define( 'ONE_DAY_IN_SECONDS', (60 * 60 * 24) );
// Set timezone
date_default_timezone_set( 'America/New_York' );
// Starts a keyed array mapping the "old" event IDs to the new ones
$imported_post_id_table = array();
$i = 0;
// Load each xml file
foreach ( $args as $arg ) {
\WP_CLI::log( $i );
$i++;
// Check the file
if ( ! is_readable( $arg ) ) {
\WP_CLI::warning( "Can't read '$file' file." );
continue;
}
// Import the file
$data = get_file_data( $arg );
if ( empty( $data ) ) {
// The get_file_data() will have already logged an error
continue;
}
// Create an Event post
$post_id = create_event_post( $data );
if ( isset( $post_id ) ) {
$imported_post_id_table[ $data['old_id'] ] = intval( $post_id );
}
// Create a 301 redirect post
$redirect = create_redirect( $post_id, $data['old_id'] );
}
// Sort back through the data - we need to look up the "old"
// event IDs that are in the related_events_x_related_event
global $wpdb;
$related_events_results = $wpdb->get_results(
"SELECT post_id as post_id, meta_value as meta_value
FROM wp_postmeta
WHERE meta_key='related_events'");
// Update our values
foreach ( $related_events_results as $row ) {
if ( empty( $row->post_id ) || empty( $row->meta_value ) ) {
continue;
}
$array_of_event_ids = maybe_unserialize( $row->meta_value );
$new_array_of_event_ids = array();
// Rebuild the array of actual event IDs based on the old ones
foreach ( $array_of_event_ids as $value ) {
// We have to do a double lookup against the secondary ID...
// not sure why they were stored that way, but they are
require dirname( __FILE__ ) . '/category-import-script-secondary-id-table.php';
if ( isset( $secondary_id_table[ $value ] ) ) {
$old_id_value = $secondary_id_table[ $value ];
} else {
continue;
}
// Now that we have the correct "old" id, look up against the value from the new IDs
if ( isset( $imported_post_id_table[ $old_id_value ] ) ) {
$new_array_of_event_ids[] = $imported_post_id_table[ $old_id_value ];
}
}
// And save the post meta
update_post_meta( $row->post_id, 'related_events', $new_array_of_event_ids );
}
/**
* Parses the XML file and returns a keyed array with the data.
*
* @param string $file_path
* @return array Event data.
*/
function get_file_data( $file_path ) {
$internal_errors = libxml_use_internal_errors( true );
$dom = new \DOMDocument;
$old_value = null;
if ( function_exists( 'libxml_disable_entity_loader' ) ) {
$old_value = libxml_disable_entity_loader( true );
}
$success = $dom->loadXML( file_get_contents( $file_path ) );
if ( ! is_null( $old_value ) ) {
libxml_disable_entity_loader( $old_value );
}
if ( ! $success || isset( $dom->doctype ) ) {
\WP_CLI::warning( 'There was an error when reading this XML file' );
\WP_CLI::warning( libxml_get_errors(), true );
return false;
}
$xml = simplexml_import_dom( $dom );
unset( $dom );
// halt if loading produces an error
if ( ! $xml ) {
\WP_CLI::warning( 'There was an error when reading this XML file' );
\WP_CLI::warning( libxml_get_errors(), true );
return false;
}
if ( empty( $xml->CalendarEvents ) ) {
\WP_CLI::warning( 'There was an error with the XML structure' );
\WP_CLI::warning( libxml_get_errors(), true );
return false;
}
// Get the data from the file
$event_data = array();
// Save the old event ID
$filepath_parts = pathinfo( $file_path );
$event_data['old_id'] = $filepath_parts['filename'];
// Easier to access CalendarEvents element
$event_element = $xml->CalendarEvents;
if ( ! empty( $event_element->EventTitle ) ) {
$event_data['title'] = get_element_as_string( $event_element->EventTitle );
$event_data['title_plain'] = get_element_as_string( $event_element->EventTitle, true, true );
}
if ( ! empty( $event_element->EventDescription ) ) {
update_html_content_img_sources( $event_element->EventDescription );
$event_data['description'] = get_element_as_string( $event_element->EventDescription );
}
if ( ! empty( $event_element->EventFootnote ) ) {
update_html_content_img_sources( $event_element->EventFootnote );
$event_data['footnote'] = get_element_as_string( $event_element->EventFootnote );
}
if ( ! empty( $event_element->EventDates ) ) {
$event_data['dates'] = get_element_as_string( $event_element->EventDates, true, true );
}
if ( ! empty( $event_element->sysdate ) ) {
$event_data['sysdate'] = get_element_as_string( $event_element->sysdate, true, true );
}
if ( ! empty( $xml->datetimestart ) ) {
$event_data['datetimestart'] = get_element_as_string( $xml->datetimestart, true, true );
}
if ( ! empty( $xml->datetimeend ) ) {
$event_data['datetimeend'] = get_element_as_string( $xml->datetimeend, true, true );
}
if ( ! empty( $xml->EvtDayOfWeek ) ) {
$event_data['day_of_week'] = get_element_as_string( $xml->EvtDayOfWeek, true, true );
}
if ( ! empty( $event_element->EventLocation ) ) {
$event_data['location'] = array();
if ( ! empty( $event_element->EventLocation->ExhibitionHallOther ) ) {
$event_data['location']['exhibition_hall_other'] = (string) $event_element->EventLocation->ExhibitionHallOther;
}
if ( ! empty( $event_element->EventLocation->Location ) ) {
$event_data['location']['location'] = (string) $event_element->EventLocation->Location;
}
if ( ! empty( $event_element->EventLocation->LocationOther ) ) {
$event_data['location']['location_other'] = (string) $event_element->EventLocation->LocationOther;
}
}
if ( ! empty( $event_element->Tickets ) ) {
$event_data['tickets'] = array();
if ( ! empty( $event_element->Tickets->BuyTickets ) ) {
$event_data['tickets']['buy_tickets'] = (string) $event_element->Tickets->BuyTickets;
}
if ( ! empty( $event_element->Tickets->SoldOut ) ) {
$event_data['tickets']['sold_out'] = (string) $event_element->Tickets->SoldOut;
}
if ( ! empty( $event_element->Tickets->EventTicketLink ) ) {
$event_data['tickets']['ticket_link'] = (string) $event_element->Tickets->EventTicketLink;
}
if ( ! empty( $event_element->Tickets->TicketButtonText ) ) {
$event_data['tickets']['button_text'] = (string) $event_element->Tickets->TicketButtonText;
}
if ( ! empty( $event_element->Tickets->CostYes ) && 'true' === (string) $event_element->Tickets->CostYes ) {
$event_data['tickets']['has_cost'] = true;
}
if ( ! empty( $event_element->Tickets->FreeYes ) && 'true' === (string) $event_element->Tickets->FreeYes ) {
$event_data['tickets']['is_free'] = true;
}
if ( ! empty( $event_element->Tickets->GeneralPrice ) ) {
$event_data['tickets']['general_price'] = (string) $event_element->Tickets->GeneralPrice;
}
if ( ! empty( $event_element->Tickets->StudentPrice ) ) {
$event_data['tickets']['student_price'] = (string) $event_element->Tickets->StudentPrice;
}
if ( ! empty( $event_element->Tickets->CMPMemberPrice ) ) {
$event_data['tickets']['cmp_member_price'] = (string) $event_element->Tickets->CMPMemberPrice;
}
if ( ! empty( $event_element->Tickets->TicketOther ) ) {
$event_data['tickets']['ticket_other'] = (string) $event_element->Tickets->TicketOther;
}
if ( ! empty( $event_element->Tickets->OtherPrice ) ) {
$event_data['tickets']['other_price'] = (string) $event_element->Tickets->OtherPrice;
}
}
if ( ! empty( $event_element->EventAdditionalInfo ) ) {
update_html_content_img_sources( $event_element->EventAdditionalInfo );
$event_data['additional_info'] = get_element_as_string( $event_element->EventAdditionalInfo );
}
if ( ! empty( $event_element->EventMainImage ) && isset( $event_element->EventMainImage->img ) ) {
$event_data['image'] = array();
if ( ! empty( $event_element->EventMainImage->img['src'] ) ) {
$event_data['image']['src'] = (string) $event_element->EventMainImage->img['src'];
}
if ( ! empty( $event_element->EventMainImage->img['alt'] ) ) {
$event_data['image']['alt'] = (string) $event_element->EventMainImage->img['alt'];
}
if ( ! empty( $event_element->EventMainPhotoCaption ) ) {
$event_data['image']['credit'] = get_element_as_string( $event_element->EventMainPhotoCaption, true );
}
}
if ( ! empty( $xml->LobbyImage ) && isset( $xml->LobbyImage->img ) ) {
$event_data['lobby_image'] = array();
if ( ! empty( $xml->LobbyImage->img['src'] ) ) {
$event_data['lobby_image']['src'] = (string) $xml->LobbyImage->img['src'];
}
if ( ! empty( $xml->LobbyImage->img['alt'] ) ) {
$event_data['lobby_image']['alt'] = (string) $xml->LobbyImage->img['alt'];
}
// Same credit as the main image
if ( ! empty( $event_data['image'] ) && ! empty( $event_data['image']['credit'] ) ) {
$event_data['lobby_image']['credit'] = $event_data['image']['credit'];
}
}
if ( ! empty( $event_element->EventRelatedLinks ) ) {
update_html_content_img_sources( $event_element->EventRelatedLinks );
$event_data['related_links'] = get_element_as_string( $event_element->EventRelatedLinks );
}
if ( ! empty( $event_element->RelatedEvents ) ) {
$event_data['related_events'] = array();
// There may be multiple of this tag
foreach ( $event_element->RelatedEvents as $related_event ) {
$event_old_id = intval( get_element_as_string( $related_event, true, true ) );
if ( empty( $event_old_id ) ) {
continue;
}
$event_data['related_events'][] = $event_old_id;
}
}
if ( ! empty( $event_element->AdditionalMediaVideo ) ) {
$event_data['additional_video'] = array();
// There may be multiple of this tag
foreach ( $event_element->AdditionalMediaVideo as $additional_video ) {
$video_data = array();
if ( ! empty( $additional_video->EventAdditionalVideo ) ) {
$video_data['embed'] = get_element_as_string( $additional_video->EventAdditionalVideo );
}
if ( ! empty( $additional_video->EventAdditionalVideoCaption ) ) {
$video_data['caption'] = get_element_as_string( $additional_video->EventAdditionalVideoCaption );
}
if ( ! empty( $video_data ) ) {
$event_data['additional_video'][] = $video_data;
}
}
}
if ( ! empty( $event_element->AdditionalMediaSoundClip ) ) {
$event_data['additional_audio'] = array();
// There may be multiple of this tag
foreach ( $event_element->AdditionalMediaSoundClip as $additional_audio ) {
$audio_data = array();
if ( ! empty( $additional_audio->AdditionalMediaSoundClip ) ) {
$audio_data['embed'] = get_element_as_string( $additional_audio->AdditionalMediaSoundClip );
}
// Yes, that's a typo with "Additioinal" in all of the XML files, not a typo here
if ( ! empty( $additional_audio->AdditioinalMediaSoundClipCaption ) ) {
$audio_data['caption'] = get_element_as_string( $additional_audio->AdditioinalMediaSoundClipCaption );
}
if ( ! empty( $audio_data ) ) {
$event_data['additional_audio'][] = $audio_data;
}
}
}
// Look up the event category - this isn't in the XML file, but in another file with a list
// of all events with their categories
$category = get_event_category_from_table( $event_data['old_id'] );
if ( ! empty( $category ) ) {
$event_data['category'] = $category;
}
return $event_data;
}
/**
* Looks up the Event's category in the table and returns it based on the original ID.
*
* @see calendar-import-script-category-table.php
*/
function get_event_category_from_table( $old_id ) {
require dirname( __FILE__ ) . '/calendar-import-script-category-table.php';
if ( isset( $category_table[ $old_id ] ) ) {
return $category_table[ $old_id ];
} else {
return null;
}
}
/**
* Returns a SimpleXMLElement as a string.
*
* @param SimpleXMLElement $element Element containing the HTML content.
* @param bool $trim_interior Remove extra spaces inside the string.
* @param bool $strip_tags Strip tags.
*
* @return string The element's children as a string of markup.
*/
function get_element_as_string( $element, $trim_interior = false, $strip_tags = false ) {
// Bail
if ( empty( $element ) ) {
return null;
}
$content = (string) $element->asXML();
// Strip the element's tag
$tagname = $element->getName();
$pattern = "#<\s*?$tagname\b[^>]*>(.*?)</$tagname\b[^>]*>#s";
preg_match( $pattern, $content, $matches );
$content = $matches[1];
// Strip all tags, if needed
if ( $strip_tags ) {
$content = strip_tags( $content );
}
// Either trim the ends of the string, or remove extra tabs inside
if ( $trim_interior ) {
$content = preg_replace( '/[ \t]+/', ' ', preg_replace( '/[\r\n]+/', '', $content ) );
} else {
$content = trim( $content );
}
return $content;
}
/**
* Sideloads any image sources found in the content, and modifies any <img>
* src attributes in the SimpleXMLElement object passed in.
*
* @param Object $element SimpleXMLElement node.
* @return SimpleXMLElement Updated element
*/
function update_html_content_img_sources( $element ) {
$result = $element->xpath( './/img' );
if ( empty( $result ) ) {
return;
}
foreach( $result as $node ) {
if ( ! isset( $node['src'] ) ) {
continue;
}
if ( isset( $node['alt'] ) ) {
$alt_text = $node['alt'];
} else {
$alt_text = '';
}
$new_image_id = download_image_from_url( $node['src'], 0, $alt_text );
if ( empty( $new_image_id ) ) {
continue;
}
$image_src = wp_get_attachment_image_url( $new_image_id, 'full' );
if ( empty( $image_src ) ) {
continue;
}
$node['src'] = $image_src;
}
return $element;
}
/**
* Once we have the normalized data, create an Event post.
*
* @param array $data An array of the event data. See format of get_file_data().
* @return WP_Post|WP_Error Either the created event post or an error.
*/
function create_event_post( $data ) {
global $ai1ec_registry;
// Pull out the data that gets passed to Ai1 Events to create the actual event
$event_post_data = array();
/**
* Start & end times:
*
* First tries to parse the "dates" string, but this may not work (see below). If that
* fails, try the sysdate or the datetimestart, which may have a date in the format of "20121202".
* If the datetimeend is set, use that as the end date.
*
* The "dates" string can be very difficult to parse. Some will be valid,
* and can be parsed and have the Event start time set (but probably not the end time).
* Check the results from date_parse() to see if we have a valid date that will work here.
*
* If sysdate and datetimestart are not set, prompt the user to set the date manually after reading
* the "dates" string.
*/
$parsed_date = date_parse( $data['dates'] );
if ( empty( $parsed_date['error_count'] ) && empty( $parsed_date['warning_count'] ) ) {
// If there were no errors in the parsed date, our start time should be valid
$event_post_data['start'] = absint( strtotime( $data['dates'] ) );
} else {
// Prompt the user to manually enter the date, based on the "dates" string
\WP_CLI::log( 'Event ' . $data['title_plain'] . ' (' . $data['old_id'] . ') had an error with the start/end times: ' );
\WP_CLI::log( $data['dates'] );
// Make some guesses based on the sysdate, datetimestart. These may not be set,
// or probably only have the date but not the time.
if ( isset( $data['sysdate'] ) ) {
$date_to_try = $data['sysdate'];
} else if ( isset( $data['datetimestart'] ) ) {
$date_to_try = $data['datetimestart'];
}
if ( isset( $date_to_try ) ) {
$start_date_object = \DateTime::createFromFormat( 'Ymd', $date_to_try );
// Try another format, like 201210051200
if ( false === $start_date_object ) {
$start_date_object = \DateTime::createFromFormat( 'YmdHi', $date_to_try );
}
// Or try one more format, like February 17, 2016
if ( false === $start_date_object ) {
$start_date_object = \DateTime::createFromFormat( 'F j, Y', $date_to_try );
}
// If we could find a start date, get the formatted version
if ( ! empty( $start_date_object ) ) {
$start_time_guess = $start_date_object->format('F j, Y');
}
}
// Prompt for the start date
if ( isset( $start_time_guess ) ) {
\WP_CLI::log( 'What is the correct start date and time? (Leave blank to use the guess)' );
\WP_CLI::log( 'My guess is: ' . $start_time_guess );
$corrected_start_date = trim( fgets( STDIN ) );
if ( ! empty( $corrected_start_date ) ) {
$event_post_data['start'] = absint( strtotime( $corrected_start_date ) );
} else {
$event_post_data['start'] = $start_date_object->getTimestamp();
}
} else {
\WP_CLI::log( 'What is the correct start date and time?' );
$corrected_start_date = trim( fgets( STDIN ) );
if ( ! empty( $corrected_start_date ) ) {
$event_post_data['start'] = absint( strtotime( $corrected_start_date ) );
}
}
// Prompt for the end time
\WP_CLI::log( 'What is the correct end date and time? (Leave blank for no end date).' );
$corrected_end_date = trim( fgets( STDIN ) );
if ( ! empty( $corrected_end_date ) ) {
$event_post_data['end'] = absint( strtotime( $corrected_end_date ) );
}
}
// If the start time = the end time, mark it as an all-day event
if ( ! empty( $event_post_data['start'] ) &&
! empty( $event_post_data['end'] ) &&
$event_post_data['end'] === $event_post_data['start'] ) {
$event_post_data['allday'] = true;
}
// If there's no hour set, mark it as an all-day event
if ( empty( $parsed_date['hour'] ) ) {
if ( ! empty( $event_post_data['start'] ) && empty( $event_post_data['end'] ) ) {
$event_post_data['end'] = absint( $event_post_data['start'] ) + ONE_DAY_IN_SECONDS;
}
$event_post_data['allday'] = true;
}
// Set the timezone
$event_post_data['timezone_name'] = 'America/New_York';
/**
* Cost and Ticket URLs
*/
if ( isset( $data['tickets'] ) ) {
if ( isset( $data['tickets']['general_price'] ) ) {
$event_post_data['cost'] = sanitize_text_field( $data['tickets']['general_price'] );
}
if ( isset( $data['tickets']['ticket_link'] ) ) {
$event_post_data['ticket_url'] = sanitize_text_field( $data['tickets']['ticket_link'] );
}
if ( isset( $data['tickets']['is_free'] ) ) {
$event_post_data['is_free'] = (bool) $data['tickets']['is_free'];
}
}
/**
* Post Data
*/
$event_post_data['post'] = array();
$event_post_data['post']['post_status'] = 'publish';
$event_post_data['post']['post_type'] = 'ai1ec_event';
$event_post_data['post']['post_author'] = 5; // Desi's user
if ( isset( $data['title_plain'] ) ) {
$event_post_data['post']['post_title'] = sanitize_text_field( $data['title_plain'] );
}
if ( isset( $data['description'] ) ) {
$event_post_data['post']['post_content'] = wp_kses_post( $data['description'] );
}
// Create the event
$event = $ai1ec_registry->get( 'model.event', $event_post_data );
// Handle the end time ("no end time") if needed
if ( ! isset( $event_post_data['end'] ) ) {
$event->set_no_end_time();
}
// Handle creating the cost serialized setting for the Event
if ( isset( $data['tickets']['is_free'] ) ) {
$event->set( 'is_free', (bool) $event_post_data['is_free'] );
}
// Save the event
$post_id = $event->save();
if ( is_wp_error( $post_id ) || empty( $post_id ) ) {
return false;
}
// Set the Event metadata
if ( isset( $event_post_data['ticket_url'] ) ) {
update_post_meta( $post_id, '_ai1ec_cost_type', 'external' );
}
// Set our custom fields
if ( isset( $data['old_id'] ) ) {
update_post_meta( $post_id, 'old_id', absint( $data['old_id'] ) );
}
if ( isset( $data['dates'] ) ) {
update_post_meta( $post_id, 'readable_date', sanitize_text_field( $data['dates'] ) );
}
if ( isset( $data['title'] ) ) {
update_post_meta( $post_id, 'formatted_title', wp_kses_post( $data['title'] ) );
}
if ( isset( $data['footnote'] ) ) {
update_post_meta( $post_id, 'footnote', wp_kses_post( $data['footnote'] ) );
}
if ( isset( $data['tickets'] ) ) {
if ( isset( $data['tickets']['sold_out'] ) && 'true' === $data['tickets']['sold_out'] ) {
update_post_meta( $post_id, 'sold_out', true );
}
if ( isset( $data['tickets']['button_text'] ) ) {
update_post_meta(
$post_id,
'ticket_button_label',
sanitize_text_field( $data['tickets']['button_text'] )
);
}
if ( isset( $data['tickets']['student_price'] ) ) {
update_post_meta(
$post_id,
'student_price',
sanitize_text_field( $data['tickets']['student_price'] )
);
}
if ( isset( $data['tickets']['cmp_member_price'] ) ) {
update_post_meta(
$post_id,
'cmp_member_price',
sanitize_text_field( $data['tickets']['cmp_member_price'] )
);
}
if ( isset( $data['tickets']['ticket_other'] ) ) {
update_post_meta(
$post_id,
'other_ticket_option',
sanitize_text_field( $data['tickets']['ticket_other'] )
);
}
if ( isset( $data['tickets']['other_price'] ) ) {
update_post_meta(
$post_id,
'other_ticket_price',
sanitize_text_field( $data['tickets']['other_price'] )
);
}
}
if ( isset( $data['additional_info'] ) ) {
update_post_meta(
$post_id,
'additional_info',
wp_kses_post( $data['additional_info'] )
);
}
if ( isset( $data['related_links'] ) ) {
update_post_meta(
$post_id,
'related_links',
wp_kses_post( $data['related_links'] )
);
}
if ( ! empty( $data['related_events'] ) && is_array( $data['related_events'] ) ) {
update_post_meta( $post_id, 'related_events', $data['related_events'] );
}
if ( ! empty( $data['additional_video'] ) && is_array( $data['additional_video'] ) ) {
update_post_meta( $post_id, 'additional_video', count( $data['additional_video'] ) );
foreach ( $data['additional_video'] as $key => $value ) {
if ( isset( $value['embed'] ) ) {
update_post_meta( $post_id, 'additional_video_' . $key . '_embed', $value['embed'] );
}
if ( isset( $value['caption'] ) ) {
update_post_meta( $post_id, 'additional_video_' . $key . '_caption', $value['caption'] );
}
}
}
if ( ! empty( $data['additional_audio'] ) && is_array( $data['additional_audio'] ) ) {
update_post_meta( $post_id, 'additional_audio', count( $data['additional_audio'] ) );
foreach ( $data['additional_audio'] as $key => $value ) {
if ( isset( $value['embed'] ) ) {
update_post_meta( $post_id, 'additional_audio_' . $key . '_embed', $value['embed'] );
}
if ( isset( $value['caption'] ) ) {
update_post_meta( $post_id, 'additional_audio_' . $key . '_caption', $value['caption'] );
}
}
}
// Set the Category
if ( isset( $data['category'] ) ) {
// Check if the term exists yet
$term = term_exists( $data['category'], 'events_categories' );
// If not, create it
if ( empty( $term ) || ! isset( $term['term_id'] ) ) {
$term = wp_insert_term( $data['category'], 'events_categories' );
}
// And get the term ID, typecast as an integer
$term_id = intval( $term['term_id'] );
wp_set_object_terms( $post_id, $term_id, 'events_categories', true );
}
// Set the Location taxonomy term
// This may be stored a few different ways, but we're combining them all
// to taxonomy terms.
if ( isset( $data['location']['location'] ) ) {
$location = $data['location']['location'];
if ( isset( $data['location']['exhibition_hall_other'] ) ) {
$location .= ' - ' . $data['location']['exhibition_hall_other'];
}
} else if ( isset( $data['location']['location_other'] ) ) {
$location = $data['location']['location_other'];
}
if ( isset( $location ) ) {
// Check if the term exists yet
$term = term_exists( $location, 'locations' );
// If not, create it
if ( empty( $term ) || ! isset( $term['term_id'] ) ) {
$term = wp_insert_term( $location, 'locations' );
}
// And get the term ID, typecast as an integer
$term_id = intval( $term['term_id'] );
wp_set_object_terms( $post_id, $term_id, 'locations', true );
}
// Download and set the featured image
if ( ! empty( $data['image'] ) && ! empty( $data['image']['src'] ) ) {
// Get the old URL
$image_old_url = $data['image']['src'];
// Get any attributes, if set
if ( ! empty( $data['image']['alt'] ) ) {
$image_alt = $data['image']['alt'];
} else {
$image_alt = false;
}
// Credit could have some unneeded tags added, like paragraphs and divs
$credit_allowed_tags = array(
'em' => array(),
'i' => array(),
'strong' => array(),
'b' => array(),
);
if ( ! empty( $data['image']['credit'] ) ) {
$image_credit = wp_kses( $data['image']['credit'], $credit_allowed_tags );
} else {
$image_credit = false;
}
// Download the image
$image_id = download_image_from_url( $image_old_url, $post_id, $image_alt, $image_credit );
if ( ! empty( $image_id ) && ! is_wp_error( $image_id ) ) {
set_post_thumbnail( $post_id, $image_id );
}
}
// Download and set the lobby image
if ( ! empty( $data['lobby_image'] ) && ! empty( $data['lobby_image']['src'] ) ) {
// Get the old URL
$lobby_image_old_url = $data['lobby_image']['src'];
// Get any attributes, if set
if ( ! empty( $data['lobby_image']['alt'] ) ) {
$lobby_image_alt = $data['lobby_image']['alt'];
} else {
$lobby_image_alt = false;
}
// Reuse the image credit from the featured image, and download the image
if ( isset( $image_credit ) ) {
$lobby_image_id = download_image_from_url( $lobby_image_old_url, $post_id, $lobby_image_alt, $image_credit );
} else {
$lobby_image_id = download_image_from_url( $lobby_image_old_url, $post_id, $lobby_image_alt );
}
if ( ! empty( $lobby_image_id ) && ! is_wp_error( $lobby_image_id ) ) {
update_post_meta( $post_id, 'lobby_image', $lobby_image_id );
}
}
return $post_id;
}
/**
* Downloads an image and adds it to the Media Library.
*
* @param string $url URL for original source for the image to add.
* @param int $post_id Post ID to attach the image to.
* @param string $alt Alt text for the image.
* @param string $credit Credit (a custom meta field) for the image.
*
* @return int Image ID, or false if the import failed.
*/
function download_image_from_url( $url, $post_id, $alt = '', $credit = '' ) {
if ( empty( $url ) ) {
return false;
}
// Some of the image src's may contain a relative path, fix that if it's the case
$parsed_url = parse_url( $url );
// If it's very deformed
if ( false === $parsed_url ) {
return false;
}
// Prepend the correct URL at the beginning if needed
if ( ! isset( $parsed_url['host'] ) ) {
$url = 'http://www.warhol.org' . $url;
}
$tmp = download_url( $url );
$file_array = array(
'name' => basename( $url ),
'tmp_name' => $tmp
);
if ( is_wp_error( $tmp ) ) {
@unlink( $file_array[ 'tmp_name' ] );
return false;
}
$id = media_handle_sideload( $file_array, $post_id );
if ( is_wp_error( $id ) ) {
@unlink( $file_array['tmp_name'] );
return false;
}
@unlink( $tmp );
// Set the alt text if set
if ( ! empty( $alt ) ) {
update_post_meta( $id, '_wp_attachment_image_alt', sanitize_text_field( $alt ) );
}
// Set the credit, and it's ACF field
if ( ! empty( $credit ) ) {
update_post_meta( $id, 'credit', wp_kses_post( $credit ) );
update_post_meta( $id, '_credit', 'field_584212b6e880a' );
}
return $id;
}
/**
* After creating the post, create a redirect from the old URL to the new one.
*
* Uses Safe Redirect Manager, requires it to be installed.
*
* @param int $post_id The ID of the new Event post.
* @param int $old_id The Event's old ID from the old site.
*
* @return WP_Post|WP_Error Either the created redirect post or an error.
*/
function create_redirect( $post_id, $old_id ) {
global $safe_redirect_manager;
if ( empty( $post_id ) || empty( $old_id ) ) {
return false;
}
$old_url = 'http://www.warhol.org/responsive/event.aspx?id=' . absint( $old_id );
$new_url = get_the_permalink( $post_id );
if ( empty( $new_url ) ) {
return false;
}
$redirect_id = $safe_redirect_manager->create_redirect( $old_url, $new_url );
return $redirect_id;
}
// Success
\WP_CLI::success( 'The script has run!' );
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment