Skip to content

Commit

Permalink
Merge pull request #79 from uploadcare/feature/modern-js
Browse files Browse the repository at this point in the history
Feature/modern js
  • Loading branch information
andrew72ru committed Feb 16, 2021
2 parents 4580de0 + a2cec73 commit 341b343
Show file tree
Hide file tree
Showing 24 changed files with 506 additions and 326 deletions.
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based now on [Keep a Changelog](http://keepachangelog.com/en/1.0.0/)
and this project adheres to [Semantic Versioning](http://semver.org/spec/v2.0.0.html).

## [3.0.3] — 2021-02-16

* Fixed upload button position on "Add media" page.
* Refactored code for better performance and control.
* Now you can use Uploadcare Image Editor to modify images from Media Library.

## [3.0.2] — 2021-01-13

* Plugin as class.
Expand Down
148 changes: 116 additions & 32 deletions admin/UcAdmin.php
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
use Uploadcare\Configuration;
use Uploadcare\Interfaces\File\FileInfoInterface;
use Uploadcare\Interfaces\File\ImageInfoInterface;
use Uploadcare\Interfaces\Response\ProjectInfoInterface;

class UcAdmin
{
Expand Down Expand Up @@ -44,7 +45,7 @@ public function __construct($plugin_name, $version)
$this->api = new Api($this->ucConfig);
}

public function projectInfo()
public function projectInfo(): ProjectInfoInterface
{
return $this->api->project()->getProjectInfo();
}
Expand Down Expand Up @@ -83,11 +84,15 @@ public function uploadcare_plugin_init()
\wp_register_script('uploadcare-widget', self::WIDGET_URL, ['jquery'], $this->version);
\wp_register_script('uploadcare-config', $pluginDirUrl.'js/config.js', ['uploadcare-widget'], $this->version);
\wp_localize_script('uploadcare-config', 'WP_UC_PARAMS', $this->getJsConfig());
\wp_register_script('uploadcare-main', $pluginDirUrl.'js/main.js', ['uploadcare-config'], $this->version);
\wp_register_script('image-block', $pluginDirUrl.'/compiled-js/blocks.js', [], $this->version, true);
\wp_register_script('image-block', $pluginDirUrl.'compiled-js/blocks.js', [], $this->version, true);
\wp_localize_script('uc-config', 'WP_UC_PARAMS', $this->getJsConfig());
\wp_register_style('uploadcare-style', $pluginDirUrl.'css/uploadcare.css', [], $this->version);
\wp_register_style('uc-editor', $pluginDirUrl.'/compiled-js/blocks.css', [], $this->version);
\wp_register_style('uc-editor', $pluginDirUrl.'compiled-js/blocks.css', [], $this->version);

\wp_register_script('admin-js', $pluginDirUrl . 'compiled-js/admin.js', [
'image-edit', 'jquery', 'media', 'uploadcare-config',
], $this->version);
\wp_register_style('admin-css', $pluginDirUrl . 'compiled-js/admin.css', [], $this->version);
}

/**
Expand All @@ -109,9 +114,12 @@ public function add_uploadcare_js_to_admin($hook)
\wp_enqueue_script('uploadcare-elements');
\wp_enqueue_style('uc-editor');

\wp_enqueue_style('admin-css');
\wp_enqueue_script('admin-js', null, require \dirname(__DIR__) . '/compiled-js/admin.asset.php');

if (\in_array($hook, ['post.php', 'post-new.php'], true)) {
$scr = \get_current_screen();
if (\method_exists($scr, 'is_block_editor') && $scr->is_block_editor()) {
if ($scr !== null && \method_exists($scr, 'is_block_editor') && $scr->is_block_editor()) {
\wp_enqueue_script('image-block', null, require \dirname(__DIR__).'/compiled-js/blocks.asset.php');
}
}
Expand All @@ -125,37 +133,62 @@ public function add_uploadcare_js_to_admin($hook)
public function uploadcare_handle()
{
$cdnUrl = $_POST['file_url'];
$id = $this->fileId($cdnUrl);
$uuid = $this->fileId($cdnUrl);

$file = $this->api->file()->fileInfo($id);
$attachment_id = $this->attach($file, null, $cdnUrl);
$file = $this->api->file()->fileInfo($uuid);
$modifiers = $_POST['uploadcare_url_modifiers'] ?? '';
if ($modifiers === 'null') {
$modifiers = '';
}

$attachment_id = $this->attach($file, $this->loadPostByUuid($uuid), [
'uploadcare_url_modifiers' => $modifiers,
]);

$result = [
'attach_id' => $attachment_id,
'fileUrl' => $cdnUrl,
'isLocal' => false,
'uploadcare_url_modifiers' => $modifiers,
];

echo \json_encode($result);
\wp_die();
}

public function loadPostByUuid(string $uuid): ?\WP_Post
{
global $wpdb;
$query = \sprintf('SELECT post_id FROM `%s` WHERE meta_value=\'%s\' AND meta_key=\'uploadcare_uuid\'', \sprintf('%spostmeta', $wpdb->prefix), $uuid);
$result = $wpdb->get_results($query, ARRAY_A);

if (($postId = ($result[0]['post_id'] ?? null)) === null) {
return null;
}

return \get_post($postId);
}

/**
* Calls on `post-upload-ui`, adds uploadcare button to media library.
*/
public function uploadcare_media_upload()
{
\wp_enqueue_script('uc-config');
\wp_enqueue_script('admin-js', null, require \dirname(__DIR__) . '/compiled-js/admin.asset.php');
$sign = __('Click to upload any file up to 5GB from anywhere', $this->plugin_name);
$btn = __('Upload via Uploadcare', $this->plugin_name);
$href = 'javascript:ucPostUploadUiBtn();';
$href = '#';

$styleDef = \get_current_screen() !== null ? \get_current_screen()->action : null;
if (\get_current_screen() !== null && 'add' !== \get_current_screen()->action) {
$href = \admin_url().'media-new.php';
$sign .= ' '.__('from Wordpress upload page');
$sign .= ' <br><strong>'.__('from Wordpress upload page') . '</strong>';
$styleDef = 'wrap-margin';
}

echo <<<HTML
<div class="uc-picker-wrapper">
<div class="uc-picker-wrapper $styleDef">
<p class="uploadcare-picker">
<a id="uploadcare-post-upload-ui-btn"
class="button button-hero"
Expand Down Expand Up @@ -189,20 +222,39 @@ public function uploadcare_settings()
* @param int $postId
* @param \WP_Post $post
*/
public function attachmentDelete($postId, $post)
public function attachmentDelete($postId, $post): void
{
if (!$post instanceof \WP_Post || !($url = \get_post_meta($postId, 'uploadcare_url', true))) {
$uuid = \get_post_meta($postId, 'uploadcare_uuid', true);
if (empty($uuid)) {
$uuid = UploadcareMain::getUuid(\get_post_meta($postId, 'uploadcare_url', true) ?: null);
}

if (empty($uuid)) {
return;
}

$uuid = $this->fileId($url);
try {
$this->api->file()->deleteFile($uuid);
} catch (\Exception $e) {
\ULog(\sprintf('Unable to delete file %s', $uuid));
}
}

protected function makeModifiedUrl(int $postId, string $modifiers = ''): ?string
{
$uuid = \get_post_meta($postId, 'uploadcare_uuid', true);
if (empty($uuid)) {
return null;
}

$base = \get_option('uploadcare_cdn_base');
if (\strpos($base, 'http') !== 0) {
$base = \sprintf('https://%s', $base);
}

return \sprintf('%s/%s/%s', $base, $uuid, $modifiers);
}

// filters

/**
Expand All @@ -213,13 +265,25 @@ public function attachmentDelete($postId, $post)
*
* @return string
*/
public function uc_get_attachment_url($url, $post_id)
public function uc_get_attachment_url(string $url, int $post_id): string
{
if (!($uc_url = \get_post_meta($post_id, 'uploadcare_url', true))) {
$uuid = \get_post_meta($post_id, 'uploadcare_uuid', true);
if ($uuid === false) {
$ucUrl = \get_post_meta($post_id, 'uploadcare_url', true);
if ($ucUrl) {
$uuid = UploadcareMain::getUuid($ucUrl);
}
if ($uuid !== null) {
\update_post_meta($post_id, 'uploadcare_uuid', $uuid);
}
}

if (empty($uuid)) {
return $url;
}
$modifiers = \get_post_meta($post_id, 'uploadcare_url_modifiers', true);

return $uc_url;
return $this->makeModifiedUrl($post_id, !empty($modifiers) ? $modifiers : '');
}

/**
Expand Down Expand Up @@ -254,6 +318,7 @@ public function uc_load($url, $id)
* @return mixed
*
* @throws Exception
* @todo do wee need this?
*/
public function uc_save_image_editor_file($override, $filename, $image, $mime_type, $post_id)
{
Expand Down Expand Up @@ -431,17 +496,26 @@ private function storeTempFile($editor, FileInfoInterface $info)
*/
public function uploadcare_image_downsize($value, $id, $size = 'medium')
{
if (!$uc_url = get_post_meta($id, 'uploadcare_url', true)) {
$uuid = \get_post_meta($id, 'uploadcare_uuid', true);
if ($uuid === false) {
$url = \get_post_meta($id, 'uploadcare_url', true);
if ($url === false) {
return false;
}

$uuid = UploadcareMain::getUuid($url);
}

if (empty($uuid)) {
return false;
}
$baseUrl = $this->makeModifiedUrl($id, \get_post_meta($id, 'uploadcare_url_modifiers', true));

$sz = $this->thumbnailSize($size);
if ($sz) {
// chop filename part
$url = preg_replace('/[^\/]*$/', '', $uc_url);
$url = \sprintf(UploadcareMain::SCALE_CROP_TEMPLATE, $url, $sz);
$url = \sprintf(UploadcareMain::SCALE_CROP_TEMPLATE, $baseUrl, $sz);
} else {
$url = $uc_url;
$url = $baseUrl;
}

return [
Expand Down Expand Up @@ -560,11 +634,11 @@ private function getSizes()
/**
* @param FileInfoInterface $file
* @param int|null $id existing Post ID
* @param string|null $modifiedUrl
* @param array $options
*
* @return int|WP_Error
*/
public function attach(FileInfoInterface $file, $id = null, $modifiedUrl = null)
public function attach(FileInfoInterface $file, $id = null, $options = [])
{
$userId = get_current_user_id();
$filename = $file->getOriginalFilename();
Expand Down Expand Up @@ -592,12 +666,21 @@ public function attach(FileInfoInterface $file, $id = null, $modifiedUrl = null)
$attachment_id = \wp_insert_post($attachment, true);
$meta = $isImage ? $this->getFinalDim($file) : ['width' => null, 'height' => null];

$attached_file = $modifiedUrl !== null ? $modifiedUrl : \sprintf('https://%s/%s/', \get_option('uploadcare_cdn_base'), $file->getUuid());
\add_post_meta($attachment_id, 'uploadcare_url', $attached_file, true);
\add_post_meta($attachment_id, 'uploadcare_uuid', $file->getUuid(), true);

\add_post_meta($attachment_id, '_wp_attached_file', $attached_file, true);
\add_post_meta($attachment_id, '_wp_attachment_metadata', $meta, true);
$attached_file = \sprintf('https://%s/%s/', \get_option('uploadcare_cdn_base'), $file->getUuid());
if ($id === null) {
\add_post_meta($attachment_id, 'uploadcare_url', $attached_file, true);
\add_post_meta($attachment_id, 'uploadcare_uuid', $file->getUuid(), true);
\add_post_meta($attachment_id, 'uploadcare_url_modifiers', ($options['uploadcare_url_modifiers'] ?? ''), true);
\add_post_meta($attachment_id, '_wp_attached_file', $attached_file, true);
\add_post_meta($attachment_id, '_wp_attachment_metadata', $meta, true);
}
if ($id !== null) {
\update_post_meta($attachment_id, 'uploadcare_url', $attached_file);
\update_post_meta($attachment_id, 'uploadcare_uuid', $file->getUuid());
\update_post_meta($attachment_id, 'uploadcare_url_modifiers', ($options['uploadcare_url_modifiers'] ?? ''));
\update_post_meta($attachment_id, '_wp_attached_file', $attached_file);
\update_post_meta($attachment_id, '_wp_attachment_metadata', $meta);
}

return $attachment_id;
}
Expand Down Expand Up @@ -636,15 +719,16 @@ private function getJsConfig()

$baseParams = [
'public_key' => get_option('uploadcare_public'),
'previewStep' => false,
'previewStep' => true,
'ajaxurl' => \admin_url('admin-ajax.php'),
'tabs' => $tabs,
'cdnBase' => 'https://'.\get_option('uploadcare_cdn_base', 'ucarecdn.com'),
'multiple' => true,
];
if (null !== \get_option('uploadcare_finetuning', null)) {
$fineTuning = \json_decode(\stripcslashes(\get_option('uploadcare_finetuning')), true);
if (JSON_ERROR_NONE === \json_last_error()) {
$baseParams = \array_merge($fineTuning, $baseParams);
$baseParams = \array_merge($baseParams, $fineTuning);
}
}

Expand Down
51 changes: 48 additions & 3 deletions includes/UcFront.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,32 @@ public function __construct($pluginName, $pluginVersion)
$this->secureUploads = (bool) \get_option('uploadcare_upload_lifetime', 0) > 0;
}

public function editorPostMeta(): void
{
$parameters = [
'show_in_rest' => true,
'type' => 'string',
];

\register_post_meta('attachment', 'uploadcare_url_modifiers', $parameters);
\register_post_meta('attachment', 'uploadcare_url', $parameters);
\register_post_meta('attachment', 'uploadcare_uuid', $parameters);
}

public function prepareAttachment(array $response, \WP_Post $attachment, $meta): array
{
if (empty(\get_post_meta($attachment->ID, 'uploadcare_url', true)))
return $response;

$response['meta'] = [
'uploadcare_url_modifiers' => \get_post_meta($attachment->ID, 'uploadcare_url_modifiers', true),
'uploadcare_url' => \get_post_meta($attachment->ID, 'uploadcare_url', true),
'uploadcare_uuid' => \get_post_meta($attachment->ID, 'uploadcare_uuid', true),
];

return $response;
}

/**
* Calls on `wp_enqueue_scripts`
* @see UploadcareMain::defineFrontHooks()
Expand Down Expand Up @@ -90,7 +116,9 @@ protected function changeContent($content, $imageId)
{
$crawler = new Crawler($content);
$collation = [];
$crawler->filterXPath('//img')->each(function (Crawler $node) use (&$collation, $imageId) {
$modifiers = \get_post_meta($imageId, 'uploadcare_url_modifiers', true);

$crawler->filterXPath('//img')->each(function (Crawler $node) use (&$collation, $imageId, $modifiers) {
$imageUrl = $node->attr('src');
$attachedFile = \get_post_meta($imageId, '_wp_attached_file', true);
$isLocal = true;
Expand All @@ -106,7 +134,18 @@ protected function changeContent($content, $imageId)
}
// If Adaptive delivery is on and Secure uploads is on too we have to change url to uuid and ignore all local files
if ($this->adaptiveDelivery && $this->secureUploads) {
$imageUrl = !$isLocal ? \get_post_meta($imageId, 'uploadcare_uuid', true) : null;
$uuid = \get_post_meta($imageId, 'uploadcare_uuid', true);
if (!$uuid) {
$uuid = UploadcareMain::getUuid(\get_post_meta($imageId, 'uploadcare_url', true));
if ($uuid !== null) {
\update_post_meta($imageId, 'uploadcare_uuid', $uuid);
}
}

$imageUrl = !$isLocal ? $uuid : null;
}
if ($imageUrl !== null && $isLocal === false) {
$imageUrl = \sprintf('%s/%s', \rtrim($imageUrl, '/'), $modifiers);
}

$collation[$node->attr('src')] = $imageUrl;
Expand All @@ -121,6 +160,7 @@ protected function changeContent($content, $imageId)
// If Adaptive delivery is on and Secure uploads is off it changes everything to `data-blink-src`.
// In this case, the `collation` array contains all images (remote and local) and all this images can be shown throw Adaptive delivery.
if ($this->adaptiveDelivery && !$this->secureUploads) {
$content = (string) \preg_replace('/' . \preg_quote($src, '/') . '/mu', $target, $content);
$content = (string) \preg_replace('/src=/mu', 'data-blink-src=', $content);
}
// If adaptive delivery and secure uploads both enabled we have to change all sources to uuids and also change `src` attribute to `data-blink-uuid`.
Expand Down Expand Up @@ -162,8 +202,13 @@ public function postFeaturedImage($html, $post_id, $post_thumbnail_id, $size, $a
if ($this->adaptiveDelivery === false) {
return $this->replaceImageUrl(\sprintf('<img src="%s" />', $result[0]), $resizeParam);
}
$uuid = \pathinfo($result[0], PATHINFO_BASENAME);
$uuid = UploadcareMain::getUuid($result[0]);
$modifiers = \get_post_meta($post_id, 'uploadcare_url_modifiers', true);
if (!empty($modifiers)) {
$uuid = \sprintf('%s/%s', $uuid, $modifiers);
}

/** @noinspection RequiredAttributes */
return \sprintf('<img data-blink-uuid="%s" alt="post-%d">', $uuid, $post_id);
}

Expand Down
Loading

0 comments on commit 341b343

Please sign in to comment.