diff --git a/CHANGELOG.md b/CHANGELOG.md new file mode 100644 index 0000000..a46c75b --- /dev/null +++ b/CHANGELOG.md @@ -0,0 +1,9 @@ +# Craft Silktide Changelog + +All notable changes to this project will be documented in this file. + +The format is based on [Keep a Changelog](http://keepachangelog.com/) and this project adheres to [Semantic Versioning](http://semver.org/). + +## 1.0.0 - 2019-01-24 +### Added +- Initial release diff --git a/LICENSE.md b/LICENSE.md new file mode 100644 index 0000000..420d963 --- /dev/null +++ b/LICENSE.md @@ -0,0 +1,9 @@ +The MIT License (MIT) + +Copyright (c) 2019 Silktide Ltd + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/README.md b/README.md new file mode 100644 index 0000000..297aab1 --- /dev/null +++ b/README.md @@ -0,0 +1,41 @@ +# Silktide Craft plugin for Craft CMS 3.x + +Integrate [Silktide](https://www.silktide.com) with Craft CMS 3. + +![Screenshot](src/icon.svg) + +## Requirements + +* Craft 3.0 RC1+ +* PHP 7.0+ +* An account with [Silktide](https://www.silktide.com) + +## Installation + +To install the plugin, follow these instructions. + +1. Open your terminal and go to your Craft project: + + cd /path/to/project + +2. Then tell Composer to load the plugin: + + composer require silktide/craft-silktide + +3. In the Control Panel, go to Settings → Plugins and click the “Settings” button for Silktide. + +4. Enter the API key as provided by Silktide. + +## Silktide Craft Overview + +Enables Silktide to be notified of new and updated pages on your Craft CMS 3 powered website and for you to easily edit pages within Craft from Silktide. + +## Configuring Silktide Craft + +1. Go to the Craft CMS admin dashboard + +2. Click 'Settings' and under the 'Plugins' heading, select the 'Silktide' plugin + +3. Provide your Silktide API key. This can be found in the 'Settings -> CMS' section of your Silktide account. + +Brought to you by [Silktide](https://www.silktide.com) diff --git a/composer.json b/composer.json new file mode 100644 index 0000000..c71540a --- /dev/null +++ b/composer.json @@ -0,0 +1,45 @@ +{ + "name": "silktide/craft-silktide", + "description": "Integrate Silktide with Craft", + "type": "craft-plugin", + "version": "1.0.0", + "keywords": [ + "craft", + "cms", + "craftcms", + "craft-plugin", + "silktide craft", + "silktide" + ], + "support": { + "docs": "https://github.com/silktide/cms-plugin-craft3/blob/master/README.md", + "issues": "https://github.com/silktide/cms-plugin-craft3/issues" + }, + "license": "MIT", + "authors": [ + { + "name": "silktide", + "homepage": "https://www.silktide.com" + } + ], + "require": { + "php": "^7.0", + "ext-openssl": "*", + "ext-json": "*", + "craftcms/cms": "^3.0.0-RC1" + }, + "autoload": { + "psr-4": { + "silktide\\craftsilktide\\": "src/" + } + }, + "extra": { + "name": "Silktide", + "handle": "craft-silktide", + "hasCpSettings": true, + "hasSettings" : false, + "hasCpSection": false, + "changelogUrl": "https://raw.githubusercontent.com/silktide/cms-plugin-craft3/master/CHANGELOG.md", + "class": "silktide\\craftsilktide\\CraftSilktide" + } +} diff --git a/src/CraftSilktide.php b/src/CraftSilktide.php new file mode 100644 index 0000000..056255f --- /dev/null +++ b/src/CraftSilktide.php @@ -0,0 +1,235 @@ +isInstalled) { + return; + } + + if (!$this->isInstalled) { + return; + } + // check if we've been configured, and if we haven't then return. + $apiKey = $this->getSettings()->apiKey; + if ($apiKey === '') { + Craft::info( + Craft::t( + 'craft-silktide', + '{name} plugin loaded, but not configured', + ['name' => $this->name] + ), + __METHOD__ + ); + return; + } + + $this->initSaveEntry($apiKey); + + $this->initMetaTag($apiKey); + + Craft::info( + Craft::t( + 'craft-silktide', + '{name} plugin loaded', + ['name' => $this->name] + ), + __METHOD__ + ); + } + + // Protected Methods + // ========================================================================= + + /** + * Setup our save event. + * @param string $apiKey + */ + protected function initSaveEntry(string $apiKey) + { + Event::on(Entry::class, Entry::EVENT_AFTER_SAVE, function (Event $e) use ($apiKey) { + /* @var Entry $sender */ + $sender = $e->sender; + if ($sender->status === Entry::STATUS_LIVE) { + /** + * If we have an entry which has been saved and is 'live', send notification to silktide. + */ + Craft::$app->getQueue()->push(new CraftSilktideJob([ + 'apiKey' => $apiKey, + 'urls' => $sender->url, + 'userAgent' => 'SilktideCraft/' . + $this->getVersion() . + ' (compatible; CraftCMS ' . + Craft::$app->getVersion() . + ')' + ])); + } + }); + } + + /** + * Setup the meta tag event. + * @param string $apiKey + */ + protected function initMetaTag(string $apiKey) + { + Event::on(View::class, View::EVENT_BEFORE_RENDER_PAGE_TEMPLATE, function (TemplateEvent $e) use ($apiKey) { + // make sure we are public view only + if (Craft::$app->request->getIsSiteRequest() && + !Craft::$app->request->getIsCpRequest() && + !Craft::$app->request->getIsConsoleRequest() && + !(Craft::$app->request->hasMethod('getIsAjax') && Craft::$app->request->getIsAjax()) && + !(Craft::$app->request->hasMethod('getIsLivePreview') && Craft::$app->request->getIsLivePreview()) + ) { + // get current page element + $element = Craft::$app->urlManager->getMatchedElement(); + if (!empty($element)) { + $editLink = $element->getCpEditUrl(); + if ($editLink !== null) { + $this->createMetaTag($apiKey, $editLink); + } + } + } + + }); + } + + /** + * Created the encrypted meta tag. + * + * @param string $apiKey + * @param string $editLink + */ + protected function createMetaTag(string $apiKey, string $editLink) + { + $ivlen = openssl_cipher_iv_length('AES-256-CBC'); + $iv = openssl_random_pseudo_bytes($ivlen); + if ($iv === false) { + return; + } + $ciphertext_raw = openssl_encrypt( + json_encode( + [ + 'editorUrl' => $editLink + ] + ), + 'AES-256-CBC', + $apiKey, + OPENSSL_RAW_DATA, + $iv + ); + + $hmac = hash_hmac('sha256', $ciphertext_raw, $apiKey, true); + $ciphertext = base64_encode($iv . $hmac . $ciphertext_raw); + Craft::$app->getView()->registerMetaTag( + [ + 'name' => 'silktide-cms', + 'content' => htmlspecialchars($ciphertext, ENT_QUOTES) + ] + ); + } + + /** + * Creates and returns the model used to store the plugin’s settings. + * + * @return Settings + */ + protected function createSettingsModel(): Settings + { + return new Settings(); + } + + /** + * Returns the rendered settings HTML, which will be inserted into the content + * block on the settings page. + * + * @return string The rendered settings HTML + * + * @throws \Twig_Error_Loader + * @throws \yii\base\Exception + */ + protected function settingsHtml(): string + { + return Craft::$app->view->renderTemplate( + 'craft-silktide/_settings', + [ + 'settings' => $this->getSettings() + ] + ); + } + + +} diff --git a/src/CraftSilktideJob.php b/src/CraftSilktideJob.php new file mode 100644 index 0000000..86e36e6 --- /dev/null +++ b/src/CraftSilktideJob.php @@ -0,0 +1,130 @@ + implode($this->urls, ', ') + ] + ), + __METHOD__ + ); + $options = [ + RequestOptions::BODY => http_build_query([ + 'apiKey' => $this->apiKey, + 'urls' => [ + $this->urls + ] + ]) + ]; + $client = Craft::createGuzzleClient( + [ + 'headers' => [ + 'User-Agent' => $this->userAgent + ] + ] + ); + + try { + $response = $client->request('post', self::SILKTIDE_API_URL, $options); + $this->handleValidResponse($response); + } catch (RequestException $e) { + $message = Craft::t( + 'craft-silktide', + 'Failed to notify Silktide - exception type {exception} message: {message}', + [ + 'exception' => get_class($e), + 'message' => $e->getMessage() + ] + ); + Craft::warning($message, __METHOD__); + } + } + + /** + * @param ResponseInterface $response + */ + protected function handleValidResponse(ResponseInterface $response) + { + $responseCode = (int)$response->getStatusCode(); + $body = $response->getBody()->getContents(); + if ($responseCode >= 200 && $responseCode <= 299) { + $decoded = json_decode($body, true); + if (is_array($decoded) && isset($decoded['status']) && $decoded['status'] === 'ok') { + Craft::info( + Craft::t( + 'craft-silktide', + 'Notified Silktide and received a {status} code back with {body}', + ['status' => $responseCode, + 'body' => $body + ] + ), + __METHOD__ + ); + } + } + $message = Craft::t( + 'craft-silktide', + 'Failed to notify Silktide - HTTP request failed with status {status} and body {body}', + [ + 'status' => $responseCode, + 'body' => $body + ] + ); + Craft::warning($message, __METHOD__); + } + +} diff --git a/src/config.php b/src/config.php new file mode 100644 index 0000000..f3b1336 --- /dev/null +++ b/src/config.php @@ -0,0 +1,21 @@ + '' + +]; diff --git a/src/icon.svg b/src/icon.svg new file mode 100644 index 0000000..76c7145 --- /dev/null +++ b/src/icon.svg @@ -0,0 +1,12 @@ + + + + + + + + + + diff --git a/src/models/Settings.php b/src/models/Settings.php new file mode 100644 index 0000000..36ee2d4 --- /dev/null +++ b/src/models/Settings.php @@ -0,0 +1,100 @@ + + \Craft::t( + 'craft-silktide', + 'Please provide the API key as presented in Silktide for your site.' + ) + ], + ['apiKey', 'trim'], + ['apiKey', 'string', 'max' => 32], + ['apiKey', 'validateApiKey'] + ]; + } + + + /** + * Validate the API key. + * + * @param string $attribute + * @param $params + * @param $validator + * @return void + */ + public function validateApiKey(string $attribute, $params, $validator) + { + $input = trim($this->$attribute); + if (preg_match('/^[a-z0-9]{32}$/i', $input)) { + return; + } + $this->addError( + $attribute, + \Craft::t( + 'craft-silktide', + 'Sorry, that API key was invalid. It must be a 32 character long code from Silktide.' + ) + ); + } + + /** + * @return array + */ + public function attributeLabels(): array + { + return [ + 'apiKey' => \Craft::t('craft-silktide', 'The API key provided by Silktide.') + ]; + } +} diff --git a/src/templates/_settings.twig b/src/templates/_settings.twig new file mode 100644 index 0000000..0995189 --- /dev/null +++ b/src/templates/_settings.twig @@ -0,0 +1,38 @@ +{# @var craft \craft\web\twig\variables\CraftVariable #} +{# +/** + * Silktide Craft plugin for Craft CMS 3.x + * + * Silktide Craft _settings.twig + * + * @author silktide + * @copyright Copyright (c) 2019 Silktide Ltd + * @link https://www.silktide.com + * @package craftsilktide + * @since 1.0.0 + */ +#} + +{% import "_includes/forms" as forms %} + +{# Link for the ? icon at the bottom of the page #} +{% set docsUrl = "https://github.com/silktide/craft-silktide/blob/master/README.md" %} + +{# The title of this CP section #} +{% set title = "Silktide" %} + +{# The URL to this plugin's base CP section #} +{% set pluginCpUrl = url('craft-silktide') %} + + {{ forms.textField({ + label: 'Please enter the API key provided by Silktide.' | t('craft-silktide'), + class: 'required', + id: 'apiKey', + name: 'apiKey', + instructions: 'For guidance, please see the Silktide Craft CMS installation guide.' | t('craft-silktide'), + errors: settings.getErrors('apiKey'), + size: 32, + maxlength: 32, + value: settings['apiKey'] + }) }} + diff --git a/src/translations/en/craft-silktide.php b/src/translations/en/craft-silktide.php new file mode 100644 index 0000000..8db81c8 --- /dev/null +++ b/src/translations/en/craft-silktide.php @@ -0,0 +1,34 @@ + 'Silktide Craft plugin loaded', + 'Please enter the API key provided by Silktide.' => 'Please enter the API key provided by Silktide.', + 'Sorry, that API key was invalid. It must be a 32 character long code from Silktide.' => 'Sorry, that API key was invalid. It must be a 32 character long code from Silktide.', + 'For guidance, please see the Silktide Craft CMS installation guide.' => 'For guidance, please see the Silktide Craft CMS installation guide.', + 'The API key provided by Silktide.' => 'The API key provided by Silktide.', + 'Notifying Silktide' => 'Notifying Silktide', + 'Notifying Silktide about a change to URLs {urls}' => 'Notifying Silktide about a change to URLs {urls}', + 'Failed to notify Silktide - exception type {exception} message: {message}' => 'Failed to notify Silktide - exception type {exception} message: {message}', + 'Notified Silktide and received a {status} code back with {body}' => 'Notified Silktide and received a {status} code back with {body}', + 'Failed to notify Silktide - HTTP request failed with status {status} and body {body}' => 'Failed to notify Silktide - HTTP request failed with status {status} and body {body}' +];