Soshot/app/Soshot/GetOg.php

90 lines
3.3 KiB
PHP

<?php
namespace App\Soshot;
use App\Soshot\GetThumb;
use Embed\Embed;
use App\Utils\ConvertToPng;
class GetOg extends GetThumb {
/**
* Generate the OG image for a given URL.
*
* This method retrieves the OG image from the provided URL using the Embed library.
* If the image cannot be retrieved, an error image is used instead. The image is
* then saved to the specified file path. If the image format is not PNG, it is
* converted to PNG using the ConvertToPng class. The method updates the database
* with the status of the OG image creation.
*
* @return bool True if the OG image was successfully created, false otherwise.
*/
public function makeOg() {
if (!is_dir($this->filePath)) {
mkdir($this->demande->filePath);
}
try {
$embed = new Embed();
$info = $embed->get($this->demande->url);
if (!is_null($info->image)) {
if (!$image = file_get_contents($info->image)) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2, $this->type);
return true;
}
} else {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2, $this->type);
return true;
}
if (empty($image)) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2, $this->type);
return true;
}
file_put_contents($this->demande->requestImg, $image);
if (in_array(mime_content_type($this->demande->requestImg), ['image/jpg', 'image/jpeg', 'image/bmp', 'image/webp']) && $this->fileFormat === 'png') {
// @todo convertToWebp convertToJpg
ConvertToPng::convertToPng($this->demande);
}
} catch (\Exception $e) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2, $this->type);
}
if (!is_file($this->demande->requestImg)) {
copy(__DIR__ . '/../../src/images/error_thumb.png', $this->demande->requestImg);
$this->db->addUpdate(2, $this->type);
} else {
$this->db->addUpdate(1, $this->type);
}
}
/**
* Display the OG image for a given URL.
*
* This method checks if the OG image file exists and if the type is 'og'. If the
* file does not exist, it calls the makeOg() method to generate the OG image. It
* then sets the appropriate headers and outputs the contents of the OG image file.
*
* @return void
*/
public function show() {
if (file_exists($this->requestImg) && $this->type === 'og') {
} else {
$this->makeOg();
}
//echo '<img src="data:' . mime_content_type($this->requestImg) . ';base64,' . base64_encode(file_get_contents($this->requestImg)) . '">';
header("Content-type: " . mime_content_type($this->requestImg));
header('Expires: ', gmdate('D, d M Y H:i:s', time()) . ' GMT');
echo file_get_contents($this->requestImg);
exit();
}
}