mademedia/silverstripe-cloudinary

Adds the Cloudinary browser to the CMS.

Installs: 3 661

Dependents: 0

Suggesters: 0

Security: 0

Stars: 11

Watchers: 23

Forks: 7

Open Issues: 27

Type:silverstripe-vendormodule

8.0.3 2024-10-31 10:04 UTC

This package is auto-updated.

Last update: 2024-10-31 10:05:42 UTC


README

Bring the power of Cloudinary to SilverStripe!

Cloudinary is a cloud-based media management platform that provides an easy solution for developers to store, manage, and serve highly optimised on-the-fly digital assets.

A note on branches, releases, and PHP versions

If you're using anyting under PHP 8, please use the legacy branch and 6.x.x releases.

The main branch and ^7.x.x should be used for any projects running on PHP 8.1 and over.

Table of Contents

SilverStripe has a asset manager, why do I need this?

The out of the box asset manager has one fatal flaw: the assets live on the server. You may be thinking "well, duh, where else are they gonna live?"

Assets being stored a server is fine for smaller sites that don't require much more than a server and some good caching. It becomes a problem when you have a multi-server setup and all instances need to serve the same asset.

Keeping assets in sync across multiple servers is a real pain in the ass. Yes, it could be automated, but it needs to be done, which means there has to be some devop nerd who has to put the processes in place for it to happen, and some code monkey who has to be on hand in case something inadvertently goes wrong. A real headache.

The simplest solution is to move the assets to the cloud. Here's that voice again saying "there's already an S3 module that does this."

Yes, there is. But you have to go through putting it in place. Then you have to setup S3, probably stick a caching layer in there somewhere. It can get pretty time consuming, especially if you're doing it frequently.

Cloudinary fixes that problem.

It offers a media manager, cloud storage, on-the-fly asset manipulations and transformations, and much more. The only thing you have to worry about is keeping track of the asset in the database.

Actually, that's a lie. You don't even have to worry about that, because this module takes care of that for you.

Provide Cloudinary config

You'll need to provide the Cloud Name, API Key, and API Secret. These values are the core requirements that enables the module to talk to Cloudinary.

Put these values in any YAML file you may be using to configure other parts of SilverStripe.

I believe a fresh install of SilverStripe comes with a _config/mysite.yml file. If you're having trouble fiding this, you may have renamed it.

MadeHQ\Cloudinary:
    cloud_name: 'CLOUDINARY_CLOUD_NAME'
    api_key: 'CLOUDINARY_API_KEY'
    api_secret: 'CLOUDINARY_API_SECRET'

Create database fields

The provides support for six database fields:

  • CloudinaryImage – store an image
  • CloudinaryMedia – store a video or audio1
  • CloudinaryFile – store a raw file such as documents
  • CloudinaryMultiImage – store multiple images
  • CloudinaryMultiMedia – store multiple videos or audio1
  • CloudinaryMultiFile – store multiple files

Use these as you would use any other database fields – add an entry in the $db static:

private static $db = [
    'MainImage' => 'CloudinaryImage',
    'BackgroundVideo' => 'CloudinaryMedia',
    'Brochure' => 'CloudinaryFile',
    'ImageGallery' => 'CloudinaryMultiImage',
    'VideoGallery' => 'CloudinaryMultiMedia',
    'Downloads' => 'CloudinaryMultiFile',
];

The beauty of these fields is at their core they're just text fields, so absolutely no relationships or additional tables.

Set form fields

All classes that extends DataObject excluding SiteTree should automatically scaffold the necessary form field based on the database field.

For SiteTree extended classes, including Page, the form fields must be manually provided via getCMSFields:

use MadeHQ\Cloudinary\Forms\ImageField;
use MadeHQ\Cloudinary\Forms\MediaField;
use MadeHQ\Cloudinary\Forms\FileField;

// [...]
public function getCMSFields()
{
    $fields = parent::getCMSFields();

    // Single asset fields
    $fields->addToTab('Root.Main', ImageField::create('MainImage'));
    $fields->addToTab('Root.Main', MediaField::create('BackgroundVideo'));
    $fields->addToTab('Root.Main', FileField::create('Brochure'));

    // Multiple asset fields
    $fields->addToTab('Root.Main', ImageField::create('ImageGallery')->setMultiple(true));
    $fields->addToTab('Root.Main', MediaField::create('VideoGallery')->setMultiple(true));
    $fields->addToTab('Root.Main', FileField::create('Downloads')->setMultiple(true));

    return $fields;
}

Additional methods

ImageField, MediaField, and FileField provides the following methods:

List of supplementary fields supported by each core field type

Inline editor

The default media (ssmedia) handler in the WYSIWYG is replaced to use cloudinary as opposed to the Silverstripe Files browser

Additional Settings for inline editor

See Cloudinary's configuration options for reference to any of the below

default_transformations option

Set to an array of objects (automatically wrapped in the extra array in the JS).

\SilverStripe\Forms\HTMLEditor\HTMLEditorConfig::get('cms')
    ->setOptions([
        // This means that inline images will be limited to 1500px width by default (uses `limit` crop to keep aspect ratio)
        'default_transformations' => [['crop' => 'limit', 'width' => 1500]],
    ]);

Rendering the assets

To give the developer more control over how they use the asset, this module will simply output the URL to the asset instead of outputting any HTML tags.

There's not an easy way to go around outputting a HTML tag directly, because each site may have a different requirement, and it's simply not enough to just output an img tag in the day of modern web development – we now have to consider different screen sizes, alternative file formats, etc.

It's just easier to give the developer a URL and they choose to deal with that as they please.

Images

Render an image as is:

<img src="$MainImage" alt="$MainImage.Description" />

The description in this example is one of the supplementary fields.

Render a resized image:

<img src="$MainImage.Fill(640, 480)" alt="$MainImage.Description" />

Render a picture tag for better device support and art direction:

<picture>
    <source media="(max-width: 420px)" srcset="$MainImage.Fill(420, 220), $MainImage.Fill(420, 220).DPR(2.0) 2x">
    <source media="(min-width: 421px) and (max-width: 768px)" srcset="$MainImage.Fill(708, 371), $MainImage.Fill(708, 371).DPR(2.0) 2x">
    <source media="(min-width: 769px) and (max-width: 1023px)" srcset="$MainImage.Fill(963, 504), $MainImage.Fill(963, 504).DPR(2.0) 2x">
    <source media="(min-width: 1024px) and (max-width: 1366px)" srcset="$MainImage.Fill(375, 196), $MainImage.Fill(375, 196).DPR(2.0) 2x">
    <source media="(min-width: 1367px) and (max-width: 1920px)" srcset="$MainImage.Fill(560, 293), $MainImage.Fill(560, 293).DPR(2.0) 2x">
    <source media="(min-width: 1921px)" srcset="$MainImage.Fill(1208, 632), $MainImage.Fill(1208, 632).DPR(2.0) 2x">
    <img src="$MainImage.Fill(420, 220)" alt="$MainImage.Description">
</picture>
Supported transformations

Videos

Render a cross-browser compatible video:

<video autoplay muted>
    <source src="$MainVideo.FitByWidth(1024).Format('videoWebm')" type="video/webm">
    <source src="$MainVideo.FitByWidth(1024).Format('videoMp4')" type="video/mp4">
</video>
Supported transformations

Files

Render a download link for a file:

<a href="$Brochure" target="_blank">Download our brochure</a>
Supported transformations

Cloudinary has no support for transforming files.

Supplementary methods

In addition to the transformation methods, the module also exposes additional methods to help output information about the asset themselves.

Some of these are available for all fields as standard while others can be filled in by content editors, given the corresponding fields have been enabled using the ->setFields method documented above.

Global configuration

Some global configuration options are provided in case your requirements don't change across the project, or to further enhance the module.

These can go inside a YAML file you may be using to configure your SilverStripe such as the _config/mysite.yml.

MadeHQ\Cloudinary\FieldType\DBImageResource:
    # Set the default output format of the images
    default_format: 'auto'
    # Set the default output quality of the images
    default_quality: 'auto'

MadeHQ\Cloudinary\Forms\BaseField:
    # Set the default number of files that can be selected for all the resources in it's multiple mode
    default_max_files: 25

MadeHQ\Cloudinary\Forms\ImageField:
    # Same as above but only for images
    default_max_files: 25
    # Set the list of available gravity options to choose from for images
    default_gravity_options:
        auto: 'Auto'
        auto:face: 'Auto (Face)'
        auto:faces: 'Auto (Faces)'
        auto:no_faces: 'Auto (No Faces)'
        center: 'Center'
        east: 'East'
        face: 'Face'
        faces: 'Faces'
        face:auto: 'Face (Auto)'
        faces:auto: 'Faces (Auto)'
        face:center: 'Face (Center)'
        faces:center: 'Faces (Center)'
        north: 'North'
        north_east: 'North East'
        north_west: 'North West'
        south: 'South'
        south_east: 'South East'
        south_west: 'South West'
        west: 'West'
    # Set the default supplementary fields that appear in the CMS
    default_fields:
        - title
        - description
        - credit

MadeHQ\Cloudinary\Forms\MediaField:
    # Same as above but only for media
    default_max_files: 25
    # Set the list of available gravity options to choose from for media
    default_gravity_options:
        auto: 'Auto'
        center: 'Center'
        east: 'East'
        north: 'North'
        north_east: 'North East'
        north_west: 'North West'
        south: 'South'
        south_east: 'South East'
        south_west: 'South West'
        west: 'West'
    # Set the default supplementary fields that appear in the CMS
    default_fields:
        - title
        - description

MadeHQ\Cloudinary\Forms\FileField:
    # Same as above but only for files
    default_max_files: 25
    # Set the default supplementary fields that appear in the CMS
    default_fields:
        - title

Multi resource fields

As mentioned above, using the ->setMultiple(boolean $multiple) method on one of the three fields enables support to select multiple resources from Cloudinary. This is great for instances where you're building a carousel, or providing a list of downloads.

At it's core, all this really does is provide each chosen resource as an iterator that can be looped through in the template. The methods, transformation or otherwise, available on each individual resource within the list remains the same as documented above, however, enabling this mode does expose the ->getLink() or $Link method which can be used to let the end-user download all the assets in single zipped file.

Example usuage:

<ul>
    <% loop Downloads %>
        <li><a href="$Me" target="_blank">$Me.Title ($Me.FriendlyFileSize)</a></li>
    <% end_loop %>
</ul>

<p><a href="$Downloads.Link" target="_blank">Download all</a></p>

Retaining transformations

By default, the module will skip any user applied transformations on resources to give the developer more control over how they wish the assets to be displayed.

The reasoning behind this is the developer should control the overall look of the assets including, but not limited to, setting the sizes, crops, effects, etc.

But, we're also aware some content editors may wish to have at least some control over how they want their images to appear, so they may wish to use the media library to pick out their transformations before inserting the asset.

A sensible middle ground to overcome this issue is to let the developer specify a list of transformations that can be applied by content editors.

The module exposes the following configuration option to make this possible:

MadeHQ\Cloudinary\FieldType\DBImageResource:
    retain_transformations:
        - effect

MadeHQ\Cloudinary\FieldType\DBMediaResource:
    retain_transformations:
        - effect
        - video_sampling
        - keyframe_interval

Only the transformations mentioned in the supported transformations documented previously can be retained for the time being. This may change as we add more supported transformations.

Predominant Colours

When an image is selected, the module will automatically extract the most predominant colours from it. This is returned as an ArrayList so it can be both easily looped through in templates or in PHP code. This can be accessed by ->getTopColours() or $TopColours.

The ArrayList is ordered by how predominant a colour is with most predominant being first, and least being the last.

Each item within the array is comprised of Predominance and a neat Colour object that provides a nice selection of helper functions to allow easy manipulation of the colour:

The base colour used for above examples was #775313 and all enhancements were made by 10 percent.

It's worth noting that all methods here that returns a colour will return a Colour object so you can effectively carry out chained manipulations e.g. $Grayscale.Darken(10).FadeOut(10). When used in PHP, Colour can be cast as a string to get the literal value. The type of colour format (rgb, hex, etc.) will depend on the original input colour and/or the manipulation method.

The module uses Iris to provide colour manipulation and conversion functionality.

Contributing

This version of the module is still in its infancy. We will flesh it out as our scope increases. If you think there's something we're missing out on, feel free to raise an issue and we'll be happy to review and see if it can be accommodated.

Todo

  • Document the code further
  • Update the README to include descriptions about the transformation methods
  • Update the README to include examples screenshots
  • Make the supplemtary fields easily extensible
  • Reduce duplicate code in the React components
  • Provide more transformations
  • Provide better support for colours
  • Add handling for Edit/Remove functionality in WYSIWYG

Migration

If you are migrating from the prior (non-widget) version of the code that made use of the Silverstripe filesystem and the MadeHQ\Cloudinary\Model\ImageLink or MadeHQ\Cloudinary\Model\FileLink classes for relationships then you can run the following 2 tasks to migrate the data to the new format. Note: you will need to make code changes in the PHP files

Step 1:

Run the dev/tasks/MadeHQ-Cloudinary-Tasks-MigrationTaskStep1 task. This will give you a list of files/classes that are using MadeHQ\Cloudinary\Model\FileLink or a decendent in the has_one or many_many relationships

Step 2:

Update the code base to move the has_one and many_many fields into db with an appropriate new field type (see Create database fields above).

Other code changes required would include changing calls to ::<ImageFieldName>() to ::dbObject('<ImageFieldName>') (this could possibly be done via the ::__call() magic method but will leave that to individuals)

Step 3:

Run dev/build?flush=all to generate the new fields. Due to the legacy fields being relationships there is no worry about a conflict with field names.

Step 4:

Run the dev/tasks/MadeHQ-Cloudinary-Tasks-MigrationTaskStep2 task. This will get the PublicID from the legacy relationship and request the file data directly from Cloudinary via the Admin API.

NOTE: There is a limit of 2000 API requests per hour that can be made to cloudinary. There is currently no way to re-start the process if you hit this limit (possibly need to look into this). It seems that it is possible to raise the limit by contacting Cloudinary