protected function WordPressAttachment::replaceImgs in WordPress Migrate 7.2
If we have an image reference, replace it with media tags.
Parameters
array $matches:
File
- ./
wordpress_attachment.inc, line 358
Class
- WordPressAttachment
- Implementation of WordPressMigration, for attachments
Code
protected function replaceImgs(array $matches) {
// Default to the original <img> tag.
$result = $matches[0];
// The src parameter is required
if (preg_match('|src=[\'"](.*?)[\'"]|i', $result, $src_matches)) {
$src = $src_matches[1];
}
else {
return $result;
}
// Strip off any URL parameters.
if ($question = strpos($src, '?')) {
$src = substr($src, 0, $question);
}
// Get the fid, if any. If none, let the img tag stand
$fid = db_select('wordpress_migrate_attachment', 'a')
->fields('a', array(
'new_fid',
))
->condition('original_url', $src)
->execute()
->fetchField();
if (!$fid) {
// We have an image that wasn't pulled over as an attachment - if it's not
// on the existing WordPress site, leave it be; if it is, copy it directly
// and create the file entity.
$blog_url = $this->blog
->getBlogUrl();
$prefix_pattern = '|^' . $blog_url . '/|';
if (preg_match($prefix_pattern, $src)) {
$file = array(
'destination_file' => preg_replace($prefix_pattern, '', $src),
'file_replace' => FILE_EXISTS_RENAME,
);
$source = new MigrateFileUri($file);
// @todo: uid from parent node
if ($file = $source
->processFile($src, 1)) {
$fid = $file->fid;
}
else {
return $result;
}
}
else {
return $result;
}
}
else {
$file = file_load($fid);
}
// Extract the width, height, and classes for the media tag, if present
$attributes = array(
'class' => 'media-image',
'typeof' => 'foaf:Image',
'style' => '',
);
if (preg_match('|width=[\'"](.*?)[\'"]|i', $result, $width_matches)) {
$attributes['width'] = $width_matches[1];
}
if (preg_match('|height=[\'"](.*?)[\'"]|i', $result, $height_matches)) {
$attributes['height'] = $height_matches[1];
}
if (preg_match('|title=[\'"](.*?)[\'"]|i', $result, $title_matches)) {
$attributes['title'] = $title_matches[1];
}
if (preg_match('|alt=[\'"](.*?)[\'"]|i', $result, $alt_matches)) {
$attributes['alt'] = $alt_matches[1];
}
if (preg_match('|class=[\'"](.*?)[\'"]|i', $result, $class_matches)) {
$attributes['class'] .= ' ' . $class_matches[1];
}
// Build the media tag
$img_info = array(
'type' => 'media',
'view_mode' => 'media_large',
'fid' => $fid,
'attributes' => $attributes,
);
$result = '[[' . drupal_json_encode($img_info) . ']]';
// Track file references so we can add to an attachment field (if any).
$file->display = 1;
$file->description = '';
$this->referencedFiles[] = (array) $file;
return $result;
}