File: /var/www/html/wp-content/plugins/adnkronos/src/Import/ImageImporter.php
<?php
namespace AdnKronos\Import;
use AdnKronos\Psr\Log\LoggerInterface;
/**
* Downloads an image from a URL and attaches it as the featured image of a post.
*/
class ImageImporter {
/** @var LoggerInterface */
private $logger;
public function __construct(LoggerInterface $logger) {
$this->logger = $logger;
}
/**
* @param int $postId
* @param string $imageUrl
* @param string $photoName Used as the filename base (without extension)
* @param string $ownerEmail
*/
public function import($postId, $imageUrl, $photoName, $ownerEmail) {
$imageOwner = get_user_by('email', $ownerEmail);
$imageAuthorId = $imageOwner ? $imageOwner->ID : 0;
if (!$imageOwner && !empty($ownerEmail)) {
$this->logger->warning('ImageImporter: owner not found for email [' . $ownerEmail . '], using author ID 0');
}
$http = new \WP_Http();
$photo = $http->request($imageUrl, array('timeout' => 10));
if (!is_array($photo)) {
$this->logger->error('ImageImporter: download failed for ' . $imageUrl);
return;
}
$lastModified = isset($photo['headers']['last-modified']) ? $photo['headers']['last-modified'] : null;
$uploadDate = $lastModified ? gmdate('Y-m', strtotime($lastModified)) : null;
$attachment = wp_upload_bits($photoName . '.jpg', null, $photo['body'], $uploadDate);
if (!empty($attachment['error'])) {
$this->logger->error('ImageImporter: wp_upload_bits error: ' . $attachment['error']);
return;
}
$filetype = wp_check_filetype(basename($attachment['file']), null);
$postInfo = array(
'post_mime_type' => $filetype['type'],
'post_title' => get_the_title($postId) . ' ',
'post_content' => '',
'post_status' => 'inherit',
'post_author' => $imageAuthorId,
);
$attachId = wp_insert_attachment($postInfo, $attachment['file'], $postId);
if (!function_exists('wp_generate_attachment_metadata')) {
require_once ABSPATH . 'wp-admin/includes/image.php';
}
$attachData = wp_generate_attachment_metadata($attachId, $attachment['file']);
wp_update_attachment_metadata($attachId, $attachData);
set_post_thumbnail($postId, $attachId);
}
}