有的网站图片无法被外站引用,这时候最好的是图片本地化。那就动动手改一版
修改src/AppBundle/Controller/Admin/ArticleController.php 代码
修改createFromUrlAction方法。添加两个新方法saveImage,processImages
头部添加引用 use Topxia\Service\Common\ServiceKernel;
public function createFromUrlAction(Request $request)
{
//如果携带url参数,尝试识别url对应页面的资讯
$url = $request->query->get('url');
$isSafeDoman = $this->isSafeDoman($url);
$article = ['title' => '', 'body' => ''];
if ($url) {
$url = urldecode($url);
$readability = new Readability(new Configuration());
$html = file_get_contents($url);
try {
$readability->parse($html);
$article['title'] = $readability->getTitle();
$article['body'] = $this->processImages($readability->getContent());
$article['sourceUrl'] = $url;
$article['thumb'] = $this->saveImage($readability->getImage());
$article['originalThumb'] = $this->saveImage($readability->getImage());
} catch (ParseException $e) {
// echo sprintf('Error processing text: %s', $e->getMessage());
}
}
if ('POST' == $request->getMethod()) {
$formData = $request->request->all();
$article['tags'] = array_filter(explode(',', $formData['tags']));
$article = $this->getArticleService()->createArticle($formData);
$attachment = $request->request->get('attachment');
$this->getUploadFileService()->createUseFiles($attachment['fileIds'], $article['id'], $attachment['targetType'], $attachment['type']);
return $this->redirect($this->generateUrl('admin_article'));
}
$categoryTree = $this->getCategoryService()->getCategoryTree();
return $this->render('admin/article/article-from-url-modal.html.twig', [
'url' => $url,
'article' => $article,
'categoryTree' => $categoryTree,
'category' => ['id' => 0, 'parentId' => 0],
'isSafeDoman' => $isSafeDoman,
]);
}
public function saveImage($image){
$smallPath = ServiceKernel::instance()->getParameter('topxia.upload.public_directory').'/tmp/';
$imageContent = file_get_contents($image);
$name = time().rand(0,time()).".png";
file_put_contents($smallPath.$name,$imageContent);
return "tmp/".$name;
}
public function processImages($content){
$matched = preg_match_all('/<img (.*?) src="(.*?)"/', $content, $matches);
$images = $matches[2];
foreach ($images as $image){
$content = str_replace($image, "/files/".$this->saveImage($image), $content);
}
$matched = preg_match_all('/<img (.*?) data-src="(.*?)"/', $content, $matches2);
foreach ($matches2[2] as $image){
$content = str_replace($image, "/files/".$this->saveImage($image), $content);
}
$content = str_replace('data-src', "src", $content);
return $content;
}
这样就搞定了