├── .github
├── FUNDING.yml
└── dependabot.yml
├── .gitignore
├── LICENSE
├── README.md
├── composer.json
├── example.php
└── src
├── ContentTools.php
├── actions
├── InsertAction.php
├── RotateAction.php
└── UploadAction.php
├── assets
├── ContentToolsAsset.php
├── ContentToolsImagesAsset.php
└── ContentToolsTranslationsAsset.php
├── js
└── content-tools-images.js
└── models
└── ImageForm.php
/.github/FUNDING.yml:
--------------------------------------------------------------------------------
1 | # These are supported funding model platforms
2 |
3 | github: bizley
4 |
--------------------------------------------------------------------------------
/.github/dependabot.yml:
--------------------------------------------------------------------------------
1 | version: 2
2 | updates:
3 | - package-ecosystem: composer
4 | directory: "/"
5 | schedule:
6 | interval: daily
7 | time: "04:00"
8 | open-pull-requests-limit: 10
9 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .idea
2 | vendor
3 | docker
4 | runtime
5 | composer.lock
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Apache License
2 | Version 2.0, January 2004
3 | http://www.apache.org/licenses/
4 |
5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6 |
7 | 1. Definitions.
8 |
9 | "License" shall mean the terms and conditions for use, reproduction,
10 | and distribution as defined by Sections 1 through 9 of this document.
11 |
12 | "Licensor" shall mean the copyright owner or entity authorized by
13 | the copyright owner that is granting the License.
14 |
15 | "Legal Entity" shall mean the union of the acting entity and all
16 | other entities that control, are controlled by, or are under common
17 | control with that entity. For the purposes of this definition,
18 | "control" means (i) the power, direct or indirect, to cause the
19 | direction or management of such entity, whether by contract or
20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the
21 | outstanding shares, or (iii) beneficial ownership of such entity.
22 |
23 | "You" (or "Your") shall mean an individual or Legal Entity
24 | exercising permissions granted by this License.
25 |
26 | "Source" form shall mean the preferred form for making modifications,
27 | including but not limited to software source code, documentation
28 | source, and configuration files.
29 |
30 | "Object" form shall mean any form resulting from mechanical
31 | transformation or translation of a Source form, including but
32 | not limited to compiled object code, generated documentation,
33 | and conversions to other media types.
34 |
35 | "Work" shall mean the work of authorship, whether in Source or
36 | Object form, made available under the License, as indicated by a
37 | copyright notice that is included in or attached to the work
38 | (an example is provided in the Appendix below).
39 |
40 | "Derivative Works" shall mean any work, whether in Source or Object
41 | form, that is based on (or derived from) the Work and for which the
42 | editorial revisions, annotations, elaborations, or other modifications
43 | represent, as a whole, an original work of authorship. For the purposes
44 | of this License, Derivative Works shall not include works that remain
45 | separable from, or merely link (or bind by name) to the interfaces of,
46 | the Work and Derivative Works thereof.
47 |
48 | "Contribution" shall mean any work of authorship, including
49 | the original version of the Work and any modifications or additions
50 | to that Work or Derivative Works thereof, that is intentionally
51 | submitted to Licensor for inclusion in the Work by the copyright owner
52 | or by an individual or Legal Entity authorized to submit on behalf of
53 | the copyright owner. For the purposes of this definition, "submitted"
54 | means any form of electronic, verbal, or written communication sent
55 | to the Licensor or its representatives, including but not limited to
56 | communication on electronic mailing lists, source code control systems,
57 | and issue tracking systems that are managed by, or on behalf of, the
58 | Licensor for the purpose of discussing and improving the Work, but
59 | excluding communication that is conspicuously marked or otherwise
60 | designated in writing by the copyright owner as "Not a Contribution."
61 |
62 | "Contributor" shall mean Licensor and any individual or Legal Entity
63 | on behalf of whom a Contribution has been received by Licensor and
64 | subsequently incorporated within the Work.
65 |
66 | 2. Grant of Copyright License. Subject to the terms and conditions of
67 | this License, each Contributor hereby grants to You a perpetual,
68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69 | copyright license to reproduce, prepare Derivative Works of,
70 | publicly display, publicly perform, sublicense, and distribute the
71 | Work and such Derivative Works in Source or Object form.
72 |
73 | 3. Grant of Patent License. Subject to the terms and conditions of
74 | this License, each Contributor hereby grants to You a perpetual,
75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76 | (except as stated in this section) patent license to make, have made,
77 | use, offer to sell, sell, import, and otherwise transfer the Work,
78 | where such license applies only to those patent claims licensable
79 | by such Contributor that are necessarily infringed by their
80 | Contribution(s) alone or by combination of their Contribution(s)
81 | with the Work to which such Contribution(s) was submitted. If You
82 | institute patent litigation against any entity (including a
83 | cross-claim or counterclaim in a lawsuit) alleging that the Work
84 | or a Contribution incorporated within the Work constitutes direct
85 | or contributory patent infringement, then any patent licenses
86 | granted to You under this License for that Work shall terminate
87 | as of the date such litigation is filed.
88 |
89 | 4. Redistribution. You may reproduce and distribute copies of the
90 | Work or Derivative Works thereof in any medium, with or without
91 | modifications, and in Source or Object form, provided that You
92 | meet the following conditions:
93 |
94 | (a) You must give any other recipients of the Work or
95 | Derivative Works a copy of this License; and
96 |
97 | (b) You must cause any modified files to carry prominent notices
98 | stating that You changed the files; and
99 |
100 | (c) You must retain, in the Source form of any Derivative Works
101 | that You distribute, all copyright, patent, trademark, and
102 | attribution notices from the Source form of the Work,
103 | excluding those notices that do not pertain to any part of
104 | the Derivative Works; and
105 |
106 | (d) If the Work includes a "NOTICE" text file as part of its
107 | distribution, then any Derivative Works that You distribute must
108 | include a readable copy of the attribution notices contained
109 | within such NOTICE file, excluding those notices that do not
110 | pertain to any part of the Derivative Works, in at least one
111 | of the following places: within a NOTICE text file distributed
112 | as part of the Derivative Works; within the Source form or
113 | documentation, if provided along with the Derivative Works; or,
114 | within a display generated by the Derivative Works, if and
115 | wherever such third-party notices normally appear. The contents
116 | of the NOTICE file are for informational purposes only and
117 | do not modify the License. You may add Your own attribution
118 | notices within Derivative Works that You distribute, alongside
119 | or as an addendum to the NOTICE text from the Work, provided
120 | that such additional attribution notices cannot be construed
121 | as modifying the License.
122 |
123 | You may add Your own copyright statement to Your modifications and
124 | may provide additional or different license terms and conditions
125 | for use, reproduction, or distribution of Your modifications, or
126 | for any such Derivative Works as a whole, provided Your use,
127 | reproduction, and distribution of the Work otherwise complies with
128 | the conditions stated in this License.
129 |
130 | 5. Submission of Contributions. Unless You explicitly state otherwise,
131 | any Contribution intentionally submitted for inclusion in the Work
132 | by You to the Licensor shall be under the terms and conditions of
133 | this License, without any additional terms or conditions.
134 | Notwithstanding the above, nothing herein shall supersede or modify
135 | the terms of any separate license agreement you may have executed
136 | with Licensor regarding such Contributions.
137 |
138 | 6. Trademarks. This License does not grant permission to use the trade
139 | names, trademarks, service marks, or product names of the Licensor,
140 | except as required for reasonable and customary use in describing the
141 | origin of the Work and reproducing the content of the NOTICE file.
142 |
143 | 7. Disclaimer of Warranty. Unless required by applicable law or
144 | agreed to in writing, Licensor provides the Work (and each
145 | Contributor provides its Contributions) on an "AS IS" BASIS,
146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147 | implied, including, without limitation, any warranties or conditions
148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149 | PARTICULAR PURPOSE. You are solely responsible for determining the
150 | appropriateness of using or redistributing the Work and assume any
151 | risks associated with Your exercise of permissions under this License.
152 |
153 | 8. Limitation of Liability. In no event and under no legal theory,
154 | whether in tort (including negligence), contract, or otherwise,
155 | unless required by applicable law (such as deliberate and grossly
156 | negligent acts) or agreed to in writing, shall any Contributor be
157 | liable to You for damages, including any direct, indirect, special,
158 | incidental, or consequential damages of any character arising as a
159 | result of this License or out of the use or inability to use the
160 | Work (including but not limited to damages for loss of goodwill,
161 | work stoppage, computer failure or malfunction, or any and all
162 | other commercial damages or losses), even if such Contributor
163 | has been advised of the possibility of such damages.
164 |
165 | 9. Accepting Warranty or Additional Liability. While redistributing
166 | the Work or Derivative Works thereof, You may choose to offer,
167 | and charge a fee for, acceptance of support, warranty, indemnity,
168 | or other liability obligations and/or rights consistent with this
169 | License. However, in accepting such obligations, You may act only
170 | on Your own behalf and on Your sole responsibility, not on behalf
171 | of any other Contributor, and only if You agree to indemnify,
172 | defend, and hold each Contributor harmless for any liability
173 | incurred by, or claims asserted against, such Contributor by reason
174 | of your accepting any such warranty or additional liability.
175 |
176 | END OF TERMS AND CONDITIONS
177 |
178 | APPENDIX: How to apply the Apache License to your work.
179 |
180 | To apply the Apache License to your work, attach the following
181 | boilerplate notice, with the fields enclosed by brackets "{}"
182 | replaced with your own identifying information. (Don't include
183 | the brackets!) The text should be enclosed in the appropriate
184 | comment syntax for the file format. We also recommend that a
185 | file or class name and description of purpose be included on the
186 | same "printed page" as the copyright notice for easier
187 | identification within third-party archives.
188 |
189 | Copyright 2015 Pawel Bizley Brzozowski
190 |
191 | Licensed under the Apache License, Version 2.0 (the "License");
192 | you may not use this file except in compliance with the License.
193 | You may obtain a copy of the License at
194 |
195 | http://www.apache.org/licenses/LICENSE-2.0
196 |
197 | Unless required by applicable law or agreed to in writing, software
198 | distributed under the License is distributed on an "AS IS" BASIS,
199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200 | See the License for the specific language governing permissions and
201 | limitations under the License.
202 |
203 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # yii2-content-tools
2 |
3 | 
4 | 
5 | 
6 |
7 | ContentTools editor implementation for Yii 2.
8 |
9 | ## ContentTools
10 |
11 | Check out ContentTools website http://getcontenttools.com for more information about the editor.
12 |
13 | ## Installation
14 |
15 | Add the package to your composer.json:
16 |
17 | {
18 | "require": {
19 | "bizley/contenttools": "^1.4"
20 | }
21 | }
22 |
23 | and run `composer update` or alternatively run `composer require bizley/contenttools`
24 |
25 | ## Bower Asset
26 |
27 | This package depends on Bower package fetched through https://asset-packagist.org/
28 | Make sure you can fetch it by configuring your composer.json properly (see instructions at the link above).
29 |
30 | ## Usage
31 |
32 | ### 1. The widget.
33 |
34 | Wrap any part of the content in `\bizley\contenttools\ContentTools::begin();` and `\bizley\contenttools\ContentTools::end();`.
35 |
36 |
37 | This is the part of view that is editable.
38 |
There are paragraphs
39 | and more...
40 |
41 |
42 | You can use the widget multiple times on one page.
43 |
44 | ### 2. Backend.
45 |
46 | Yii 2 ContentTools saves content and uploaded images asynchronously and it requires some preparation on the backend side.
47 |
48 | You have to create few controllers' actions:
49 | - "upload new image" action,
50 | - "rotate uploaded image" action,
51 | - "insert & crop uploaded image" action,
52 | - "save content" action.
53 |
54 | Three first actions are already prepared if you don't want any special operations. You can find them in 'actions' folder.
55 | - _UploadAction_ - takes care of validating the uploaded images using `\bizley\contenttools\models\ImageForm`
56 | (jpg, png and gif images are allowed, maximum width and height is 1000px and maximum size is 2 MB), images are saved
57 | in `content-tools-uploads` folder accessible from web.
58 | - _RotateAction_ - takes care of rotating the uploaded image using Imagine library (through `yii2-imagine` extension
59 | required in the composer.json).
60 | - _InsertAction_ - takes care of inserting image into the content with optional cropping using Imagine library.
61 |
62 | The default option for the image URLs is:
63 |
64 | 'imagesEngine' => [
65 | 'upload' => '/site/content-tools-image-upload',
66 | 'rotate' => '/site/content-tools-image-rotate',
67 | 'insert' => '/site/content-tools-image-insert',
68 | ],
69 |
70 | So if you don't want to change the `imagesEngine` parameter add in your SiteController:
71 |
72 | public function actions()
73 | {
74 | return [
75 | 'content-tools-image-upload' => \bizley\contenttools\actions\UploadAction::className(),
76 | 'content-tools-image-insert' => \bizley\contenttools\actions\InsertAction::className(),
77 | 'content-tools-image-rotate' => \bizley\contenttools\actions\RotateAction::className(),
78 | ];
79 | }
80 |
81 | See [Standalone Actions section in Yii 2 Guide](https://www.yiiframework.com/doc/guide/2.0/en/structure-controllers#standalone-actions)
82 | for more info about adding actions.
83 |
84 | The last "save content" action is not prepared because it depends on the business logic of your application.
85 | See *Saving content* part at the end of this file.
86 |
87 | Default configuration for this is:
88 |
89 | 'saveEngine' => [
90 | 'save' => '/site/save-content',
91 | ],
92 |
93 |
94 | ## Options
95 |
96 | You can add options for the widget by passing the configuration array in the `begin()` method.
97 |
98 | ### id
99 |
100 | _default:_ `null`
101 | Identifier of the editable region (must be unique).
102 | If left empty it is automatically set to 'contentToolsXXX' where XXX is the number of next widget.
103 |
104 | ### page
105 |
106 | _default:_ `null`
107 | Page identifier. If `null` it is set to the current URL.
108 |
109 | ### tag
110 |
111 | _default:_ `'div'`
112 | HTML tag that is used to wrap the editable content.
113 |
114 | ### dataName
115 |
116 | _default:_ `'name'`
117 | Name of the `data-*` attribute that stores the identifier of editable region.
118 |
119 | ### dataInit
120 |
121 | _default:_ `'editable'`
122 | Name of the `data-*` attribute that marks the region as editable.
123 |
124 | ### options
125 |
126 | _default:_ `[]`
127 | Array of HTML options that are applied to editable region's tag.
128 |
129 | ### imagesEngine
130 |
131 | _default:_
132 |
133 | [
134 | 'upload' => '/site/content-tools-image-upload',
135 | 'rotate' => '/site/content-tools-image-rotate',
136 | 'insert' => '/site/content-tools-image-insert',
137 | ]
138 |
139 | Array of the URLs of the image actions *OR* `false` to switch off the default image engine (you will have to prepare JS
140 | for handling images on your own).
141 |
142 | ### saveEngine
143 |
144 | _default:_
145 |
146 | [
147 | 'save' => '/site/save-content',
148 | ]
149 |
150 | Array with the URL of the content saving action *OR* `false` to switch off the default saving engine (you will have to
151 | prepare JS for handling content saving on your own).
152 |
153 | ### styles
154 |
155 | _default:_ `[]`
156 | Array of styles that can be applied to the edited content.
157 | Every style should be added in separate array like:
158 |
159 | 'Name of the style' => [
160 | 'class' => 'Name of the CSS class',
161 | 'tags' => [Array of the html tags this can be applied to] or 'comma-separated list of the html tags this can be applied to'
162 | ],
163 |
164 | Example:
165 |
166 | 'Bootstrap Green' => [
167 | 'class' => 'text-success',
168 | 'tags' => ['p', 'h2', 'h1']
169 | ],
170 |
171 | `tags` key is optional and if omitted style can be applied to every element.
172 |
173 | ### language
174 |
175 | _default:_ `false`
176 | Boolean flag or language code of the widget translation.
177 | You can find the list of prepared translations in `@bower/contenttools/translations` folder.
178 | `false` means that widget will not be translated (default language is English).
179 | `true` means that widget will be translated using the application language.
180 | If this parameter is a string widget tries to load the translation file with the given name.
181 | If it cannot be found and string is longer that 2 characters widget tries again this time with parameter shortened to 2 characters.
182 | If again it cannot be found language sets back to default.
183 |
184 | ### globalConfig
185 |
186 | _default:_ `true`
187 | Boolean flag whether the configuration should be global.
188 | Global configuration means that every succeeding widget ignores `page`, `tag`, `dataName`, `dataInit`, `imagesEngine`,
189 | `saveEngine`, and `language` parameters and sets them to be the same as in the first one. Also `styles` are added only
190 | if they've got unique names.
191 |
192 | ### customJs
193 |
194 | _default:_ `null`
195 | String with custom JS to be initialized with editor.
196 | Use `editor` variable to point to instance of `ContentTools.EditorApp.get()`.
197 | See http://getcontenttools.com/api/content-tools for more details about CT API.
198 |
199 | ## Actions callbacks
200 |
201 | The default JS image callbacks assume the following action response:
202 |
203 | {
204 | 'size': [image-width-in-px, image-height-in-px],
205 | 'url': image-url
206 | }
207 |
208 | with optional `'alt'` for insert-action. In case of any errors response should be:
209 |
210 | {
211 | 'errors': [array-of-error-descriptions]
212 | }
213 |
214 | At the moment errors are only displayed in browser's console (user sees only the big transparent cross).
215 |
216 |
217 | ## Saving content
218 |
219 | Action responsible for saving the content should expect the array of every page region data in pairs
220 | `'region-identifier' => 'region-content'`.
221 |
222 | Typical structure could look like this:
223 |
224 | [
225 | 'contentTools0' => '...', // HTML content of the contentTools0 region
226 | 'contentTools1' => '...', // HTML content of the contentTools1 region
227 | '_csrf' => '...', // CRSF token value
228 | 'page' => '/site/index' // page identifier
229 | ]
230 |
231 | Now you just need to validate and save the regions linked to the page with the given identifier.
232 |
233 | **Example implementation of saving content can be found in the https://github.com/bizley/yii2-content-tools/blob/master/example.php**
234 |
--------------------------------------------------------------------------------
/composer.json:
--------------------------------------------------------------------------------
1 | {
2 | "name": "bizley/contenttools",
3 | "type": "yii2-extension",
4 | "description": "ContentTools editor implementation for Yii 2.",
5 | "keywords": ["contenttools", "yii2", "extension", "widget", "editor", "wysiwyg", "html"],
6 | "license": "Apache-2.0",
7 | "support": {
8 | "issues": "https://github.com/bizley/yii2-content-tools/issues",
9 | "source": "https://github.com/bizley/yii2-content-tools"
10 | },
11 | "authors": [
12 | {
13 | "name": "Pawel Bizley Brzozowski",
14 | "email": "pawel@positive.codes"
15 | }
16 | ],
17 | "require": {
18 | "bower-asset/contenttools": "^1.0",
19 | "yiisoft/yii2": ">=2.0.5 <2.1.0",
20 | "yiisoft/yii2-imagine": "^2.0"
21 | },
22 | "require-dev": {
23 | "roave/security-advisories": "dev-master"
24 | },
25 | "repositories": [
26 | {
27 | "type": "composer",
28 | "url": "https://asset-packagist.org"
29 | }
30 | ],
31 | "autoload": {
32 | "psr-4": {
33 | "bizley\\contenttools\\": "src/"
34 | }
35 | }
36 | }
37 |
--------------------------------------------------------------------------------
/example.php:
--------------------------------------------------------------------------------
1 | \bizley\contenttools\actions\UploadAction::class,
25 | 'image-insert' => \bizley\contenttools\actions\InsertAction::class,
26 | 'image-rotate' => \bizley\contenttools\actions\RotateAction::class,
27 | ];
28 | }
29 |
30 | /**
31 | * This action handles displaying the content.
32 | * Here we fetch content stored for URL '/example/show' (or null if it's not saved yet) and pass it to the view.
33 | * @return string
34 | */
35 | public function actionShow()
36 | {
37 | $model = Content::findOne(['page' => '/example/show']);
38 |
39 | return $this->render('show', ['model' => $model]);
40 | }
41 |
42 | /**
43 | * This action handles saving the content.
44 | * Actual data is saved in database and represented by Content model.
45 | * @return string
46 | */
47 | public function actionSave()
48 | {
49 | if (Yii::$app->request->isPost) {
50 | // By default widget sends page key indicating the URL where the data was changed.
51 | $page = Yii::$app->request->post('page');
52 |
53 | // In case data has been previously saved let's find it for an update
54 | $model = Content::findOne(['page' => $page]);
55 |
56 | // In case it's not found because this is first time of saving it let's take new object instance
57 | if ($model === null) {
58 | $model = new Content();
59 | }
60 |
61 | // By default yii2-content-tools saves each editable region in 'contentToolsX' POST array key
62 | // where X is the next number starting from 0. In this example we've got only one region.
63 | $model->setAttributes([
64 | 'data' => Yii::$app->request->post('contentTools0'),
65 | 'page' => $page,
66 | ]);
67 |
68 | if (!$model->save()) {
69 | return $this->asJson(['errors' => $model->errors]);
70 | }
71 |
72 | return $this->asJson(true);
73 | }
74 |
75 | return $this->asJson(['errors' => ['No data sent in POST.']]);
76 | }
77 | }
78 |
79 | use yii\db\ActiveRecord;
80 | use yii\helpers\HtmlPurifier;
81 |
82 | /**
83 | * This model represents data stored in DB.
84 | * In example let's use very simple table with only two columns.
85 | *
86 | * @property string $page Primary key of the table, identifies page URL
87 | * @property string $data Stored content
88 | */
89 | class Content extends ActiveRecord
90 | {
91 | /**
92 | * @return string
93 | */
94 | public static function tableName()
95 | {
96 | return 'content';
97 | }
98 |
99 | /**
100 | * In this example validation rules are simple:
101 | * - data and page are required,
102 | * - data is filtered using HtmlPurifier to prevent malicious HTML being saved,
103 | * - data must be a string with minimum 1 character length after purification,
104 | * - page must one of the allowed URLs (in this example only one).
105 | * @return array
106 | */
107 | public function rules()
108 | {
109 | return [
110 | [['page', 'data'], 'required'],
111 | ['data', 'filter', 'filter' => static function ($value) {
112 | return HtmlPurifier::process($value);
113 | }],
114 | ['data', 'string', 'min' => 1],
115 | ['page', 'in', 'range' => ['/example/show']],
116 | ];
117 | }
118 | }
119 |
120 | /**
121 | * ---------------------------------------------------------------------------------------------------------------------
122 | * 'show' view file below
123 | * ---------------------------------------------------------------------------------------------------------------------
124 | */
125 |
126 | use bizley\contenttools\ContentTools;
127 |
128 | /* @var $model Content */
129 | ?>
130 |
131 |
132 | [
134 | 'upload' => '/example/image-upload',
135 | 'rotate' => '/example/image-rotate',
136 | 'insert' => '/example/image-insert',
137 | ],
138 | 'saveEngine' => [
139 | 'save' => '/example/save',
140 | ]
141 | ]); ?>
142 |
143 | = $model->data ?>
144 |
145 |
This is heading example
146 |
Here is the default text that can be changed using yii2-content-tools.
147 |
148 |
149 |
150 |
--------------------------------------------------------------------------------
/src/ContentTools.php:
--------------------------------------------------------------------------------
1 |
32 | * This is the part of view that is editable.
33 | * There are paragraphs
34 | * and more...
35 | *
36 | * ~~~
37 | *
38 | * You can use the widget multiple times on one page.
39 | *
40 | * Yii 2 ContentTools saves content and uploaded images asynchronously and it requires some preparation on the backend side.
41 | * You have to create few controllers' actions:
42 | * - "upload new image" action,
43 | * - "rotate uploaded image" action,
44 | * - "insert & crop uploaded image" action,
45 | * - "save content" action.
46 | *
47 | * Three first actions are already prepared if you don't want any special operations. You can find them in
48 | * `/vendor/bizley/contenttools/actions` folder:
49 | *
50 | * - `UploadAction` - takes care of validating the uploaded images using `bizley\contenttools\models\ImageForm`
51 | * (jpg, png, and gif images are allowed, maximum width and height is 1000px and maximum size is 2 MB), images are
52 | * saved in `content-tools-uploads` folder accessible from web.
53 | * - `RotateAction` - takes care of rotating the uploaded image using Imagine library (through yii2-imagine extension
54 | * required in the composer.json).
55 | * - `InsertAction` - takes care of inserting image into the content with optional cropping using Imagine library.
56 | *
57 | * The default option for the image urls is:
58 | *
59 | * ~~~
60 | * 'imagesEngine' => [
61 | * 'upload' => '/site/content-tools-image-upload',
62 | * 'rotate' => '/site/content-tools-image-rotate',
63 | * 'insert' => '/site/content-tools-image-insert',
64 | * ],
65 | * ~~~
66 | *
67 | * So if you don't want to change the 'imagesEngine' parameter add in your SiteController:
68 | *
69 | * ~~~
70 | * public function actions()
71 | * {
72 | * return [
73 | * 'content-tools-image-upload' => \bizley\contenttools\actions\UploadAction::className(),
74 | * 'content-tools-image-insert' => \bizley\contenttools\actions\InsertAction::className(),
75 | * 'content-tools-image-rotate' => \bizley\contenttools\actions\RotateAction::className(),
76 | * ];
77 | * }
78 | * ~~~
79 | *
80 | * See Standalone Actions section in Yii 2 Guide for more info about adding actions
81 | * https://www.yiiframework.com/doc/guide/2.0/en/structure-controllers#standalone-actions
82 | *
83 | * The last "save content" action is not prepared because it depends on the business logic of your application.
84 | * Default configuration for this is:
85 | *
86 | * ~~~
87 | * 'saveEngine' => [
88 | * 'save' => '/site/save-content',
89 | * ],
90 | * ~~~
91 | */
92 | class ContentTools extends Widget
93 | {
94 | /**
95 | * @var string Page identifier. If null it is set as the current URL.
96 | */
97 | public $page;
98 |
99 | /**
100 | * @var string HTML tag that is used to wrap the editable content.
101 | */
102 | public $tag = 'div';
103 |
104 | /**
105 | * @var string Name of the data-* attribute that stores the identifier of editable region.
106 | */
107 | public $dataName = 'name';
108 |
109 | /**
110 | * @var string Name of the data-* attribute that marks the region as editable.
111 | */
112 | public $dataInit = 'editable';
113 |
114 | /**
115 | * @var array Array of HTML options that are applied to editable region's tag.
116 | */
117 | public $options = [];
118 |
119 | /**
120 | * @var array|bool Array of the URLs of the image actions OR false to switch off the default image engine
121 | * (you need to prepare JS for handling images on your own in the second case).
122 | */
123 | public $imagesEngine = [
124 | 'upload' => '/site/content-tools-image-upload',
125 | 'rotate' => '/site/content-tools-image-rotate',
126 | 'insert' => '/site/content-tools-image-insert',
127 | ];
128 |
129 | /**
130 | * @var array|bool Array with the URL of the content saving action OR false to switch off the default saving engine
131 | * (you need to prepare JS for handling content saving on your own in the second case).
132 | */
133 | public $saveEngine = [
134 | 'save' => '/site/save-content',
135 | ];
136 |
137 | /**
138 | * @var array Array of styles that can be applied to the edited content.
139 | * Every style should be added in separate array like:
140 | * ~~~
141 | * 'Name of the style' => [
142 | * 'class' => 'Name of the CSS class',
143 | * 'tags' => // [Array of the html tags this can be applied to] or
144 | * // 'comma-separated list of the html tags this can be applied to'
145 | * ],
146 | * ~~~
147 | * Example:
148 | * ~~~
149 | * 'Bootstrap Green' => [
150 | * 'class' => 'text-success',
151 | * 'tags' => ['p', 'h2', 'h1'], // or 'p,h2,h1'
152 | * ],
153 | * ~~~
154 | * 'tags' key is optional and if omitted style can be applied to every element.
155 | */
156 | public $styles = [];
157 |
158 | /**
159 | * @var bool|string Boolean flag or language code of the widget translation.
160 | * You can see the list of prepared translations in `@bower/contenttools/translations` folder.
161 | * `false` means that widget is not translated (default language is English).
162 | * `true` means that widget is translated using the application's language.
163 | * If this parameter is a string widget tries to load the translation file with the given name. If it can not be
164 | * found and string is longer that 2 characters widget tries again this time with parameter shortened to 2
165 | * characters. If again it can not be found language sets back to default.
166 | */
167 | public $language = false;
168 |
169 | /**
170 | * @var bool Boolean flag whether the configuration should be global.
171 | * Global configuration means that every succeeding widget instance ignores `tag`, `dataName`, `dataInit`,
172 | * `imagesEngine`, `saveEngine`, and `language` parameters and sets them to be the same as in the first one.
173 | * Also `styles` are added only if they've got unique names.
174 | */
175 | public $globalConfig = true;
176 |
177 | /**
178 | * @var string Custom JS to be initialized with editor.
179 | * Use `editor` variable to point to instance of ContentTools.EditorApp.get()
180 | * See http://getcontenttools.com/api/content-tools for more details about CT API
181 | * @since 1.3.0
182 | */
183 | public $customJs;
184 |
185 | /**
186 | * {@inheritdoc}
187 | */
188 | public static $autoIdPrefix = 'contentTools';
189 |
190 | const GLOBAL_PARAMS_KEY = 'content-tools-global-configuration';
191 |
192 | private $_global;
193 | private $_addedStyles = [];
194 |
195 | /**
196 | * Checks if global configuration array is set.
197 | * If so it sets properties for global values.
198 | * If not and the `globalConfig` is set to true the current properties are saved in global configuration.
199 | */
200 | public function globalConfig()
201 | {
202 | $this->_global = isset($this->getView()->params[self::GLOBAL_PARAMS_KEY]);
203 |
204 | if ($this->_global) {
205 | $globalConfig = $this->getView()->params[self::GLOBAL_PARAMS_KEY];
206 |
207 | $this->page = $globalConfig['page'];
208 | $this->dataName = $globalConfig['dataName'];
209 | $this->dataInit = $globalConfig['dataInit'];
210 | $this->imagesEngine = $globalConfig['imagesEngine'];
211 | $this->saveEngine = $globalConfig['saveEngine'];
212 | $this->language = $globalConfig['language'];
213 | $this->_addedStyles = $globalConfig['styles'];
214 | } elseif ($this->globalConfig) {
215 | $this->getView()->params[self::GLOBAL_PARAMS_KEY] = [
216 | 'page' => $this->page,
217 | 'dataName' => $this->dataName,
218 | 'dataInit' => $this->dataInit,
219 | 'imagesEngine' => $this->imagesEngine,
220 | 'saveEngine' => $this->saveEngine,
221 | 'language' => $this->language,
222 | 'styles' => [],
223 | ];
224 | }
225 | }
226 |
227 | /**
228 | * Returns the default JS part for saving the content if `saveEngine` is not set to `false`. `saveEngine` should be
229 | * boolean `false` or the array with `save` key.
230 | * @return string
231 | * @throws InvalidConfigException
232 | */
233 | public function initSaveEngine()
234 | {
235 | $js = '';
236 |
237 | if ($this->saveEngine !== false) {
238 | if (empty($this->saveEngine['save'])) {
239 | throw new InvalidConfigException('Invalid options for the saveEngine configuration!');
240 | }
241 |
242 | $csrfParam = Yii::$app->request->csrfParam;
243 | $csrfToken = Yii::$app->request->csrfToken;
244 |
245 | $page = $this->page;
246 | if (empty($page)) {
247 | $page = Url::current();
248 | }
249 |
250 | $js = <<saveEngine['save']}');
291 | xhr.send(payload);
292 | });
293 | JS;
294 | }
295 |
296 | return $js;
297 | }
298 |
299 | /**
300 | * Returns the custom JS part.
301 | * @return string
302 | * @since 1.3.0
303 | */
304 | public function initCustom()
305 | {
306 | return $this->customJs;
307 | }
308 |
309 | /**
310 | * Registers ContentToolsAsset.
311 | * Initiates ContentTools editor engine.
312 | */
313 | public function initEditor()
314 | {
315 | ContentToolsAsset::register($this->getView());
316 |
317 | $dataInit = static::dataAttribute($this->dataInit);
318 | $dataName = static::dataAttribute($this->dataName);
319 |
320 | $this->getView()->registerJs(<<initCustom()}
326 | {$this->initSaveEngine()}
327 | });
328 | JS
329 | , View::POS_END);
330 | }
331 |
332 | /**
333 | * Adds translation for the editor if language is not set to false.
334 | */
335 | public function addTranslation()
336 | {
337 | if ($this->language === true) {
338 | $this->language = Yii::$app->language;
339 | }
340 |
341 | if ($this->language !== false) {
342 | $lang = strtolower(basename($this->language));
343 | $shortlang = strlen($lang) > 2 ? substr($lang, 0, 2) : null;
344 |
345 | $assets = ContentToolsTranslationsAsset::register($this->getView());
346 | $baseAssetUrl = $assets ? $assets->baseUrl : '';
347 |
348 | if (!empty($shortlang)) {
349 | $this->getView()->registerJs(<<getView()->registerJs(<<imagesEngine !== false) {
398 | if (
399 | empty($this->imagesEngine['upload'])
400 | || empty($this->imagesEngine['rotate'])
401 | || empty($this->imagesEngine['insert'])
402 | ) {
403 | throw new InvalidConfigException('Invalid options for the imagesEngine configuration!');
404 | }
405 |
406 | ContentToolsImagesAsset::register($this->getView());
407 |
408 | $this->registerCsrfToken();
409 |
410 | $this->getView()->registerJs(
411 | ";var _CTImagesUrl = ['{$this->imagesEngine['upload']}', '{$this->imagesEngine['rotate']}', '{$this->imagesEngine['insert']}'];",
412 | View::POS_BEGIN
413 | );
414 | } else {
415 | $this->registerCsrfToken(true);
416 |
417 | $this->getView()->registerJs(';var _CTImagesUrl = [];', View::POS_BEGIN);
418 | }
419 | }
420 |
421 | /**
422 | * Registers CSRF parameters.
423 | * @param bool $empty Whether to add parameters or just set the empty array
424 | */
425 | public function registerCsrfToken($empty = false)
426 | {
427 | $csrf = $empty ? '' : "'" . Yii::$app->request->csrfParam . "', '" . Yii::$app->request->csrfToken . "'";
428 |
429 | $this->getView()->registerJs(";var _CTCSRF = [$csrf];", View::POS_BEGIN);
430 | }
431 |
432 | /**
433 | * Adds the styles for the editor.
434 | * If `globalConfig` is set to `true` it will only add new styles (with new name).
435 | * @throws InvalidConfigException
436 | */
437 | public function addStyles()
438 | {
439 | if (count($this->styles)) {
440 | $newStyles = [];
441 |
442 | foreach ($this->styles as $name => $style) {
443 | if (empty($style['class']) || !is_string($style['class'])) {
444 | throw new InvalidConfigException('Invalid options for styles configuration!');
445 | }
446 |
447 | if (!empty($style['tags']) && !is_string($style['tags']) && !is_array($style['tags'])) {
448 | throw new InvalidConfigException('Invalid options for styles configuration!');
449 | }
450 |
451 | if (empty($this->_addedStyles) || !in_array(Html::encode($name), $this->_addedStyles, true)) {
452 | $tmp = "new ContentTools.Style('" . Html::encode($name) . "', '" . Html::encode($style['class']) . "'";
453 |
454 | if (!empty($style['tags'])) {
455 | $addTags = [];
456 |
457 | if (is_string($style['tags'])) {
458 | $tags = explode(',', $style['tags']);
459 |
460 | foreach ($tags as $tag) {
461 | $possibleTag = str_replace("'", '', trim($tag));
462 |
463 | if (!empty($possibleTag)) {
464 | $addTags[] = $possibleTag;
465 | }
466 | }
467 | } else {
468 | foreach ($style['tags'] as $tag) {
469 | if (!is_string($tag)) {
470 | throw new InvalidConfigException('Invalid options for styles configuration!');
471 | }
472 |
473 | $possibleTag = str_replace("'", '', trim($tag));
474 |
475 | if (!empty($possibleTag)) {
476 | $addTags[] = $possibleTag;
477 | }
478 | }
479 | }
480 |
481 | if (!empty($addTags)) {
482 | $tmp .= ", ['" . implode("','", $addTags) . "']";
483 | }
484 | }
485 |
486 | $tmp .= ')';
487 |
488 | $newStyles[] = $tmp;
489 |
490 | if ($this->globalConfig) {
491 | $this->getView()->params[self::GLOBAL_PARAMS_KEY]['styles'][] = Html::encode($name);
492 | }
493 | }
494 | }
495 |
496 | if (!empty($newStyles)) {
497 | $this->getView()->registerJs(
498 | 'ContentTools.StylePalette.add([' . implode(',', $newStyles) . ']);',
499 | View::POS_END
500 | );
501 | }
502 | }
503 | }
504 |
505 | /**
506 | * Closes the widget.
507 | * Adds engines, styles and translation.
508 | * @return string
509 | * @throws InvalidConfigException
510 | */
511 | public function run()
512 | {
513 | if (!$this->_global) {
514 | $this->addTranslation();
515 | $this->initImagesEngine();
516 | $this->initEditor();
517 | }
518 |
519 | $this->addStyles();
520 |
521 | return Html::endTag($this->tag);
522 | }
523 |
524 | /**
525 | * Initiates the widget.
526 | * Checks configuration.
527 | * @throws InvalidConfigException
528 | */
529 | public function init()
530 | {
531 | parent::init();
532 |
533 | if ($this->page !== null && (!is_string($this->page) || $this->page === '')) {
534 | throw new InvalidConfigException('Invalid page configuration!');
535 | }
536 | if (!is_string($this->tag) || $this->tag === '') {
537 | throw new InvalidConfigException('Invalid tag configuration!');
538 | }
539 | if (!is_string($this->dataInit) || $this->dataInit === '') {
540 | throw new InvalidConfigException('Invalid dataInit configuration!');
541 | }
542 | if (!is_string($this->dataName) || $this->dataName === '') {
543 | throw new InvalidConfigException('Invalid dataName configuration!');
544 | }
545 | if (!is_array($this->options)) {
546 | throw new InvalidConfigException('Invalid options configuration!');
547 | }
548 | if (!is_array($this->imagesEngine) && $this->imagesEngine !== false) {
549 | throw new InvalidConfigException('Invalid imagesEngine configuration!');
550 | }
551 | if (!is_array($this->saveEngine) && $this->saveEngine !== false) {
552 | throw new InvalidConfigException('Invalid saveEngine configuration!');
553 | }
554 | if (!is_array($this->styles)) {
555 | throw new InvalidConfigException('Invalid styles configuration!');
556 | }
557 | if ($this->language === '' || (!is_string($this->language) && !is_bool($this->language))) {
558 | throw new InvalidConfigException('Invalid language configuration!');
559 | }
560 | if (!is_bool($this->globalConfig)) {
561 | throw new InvalidConfigException('Invalid globalConfig configuration!');
562 | }
563 |
564 | $this->globalConfig();
565 |
566 | echo Html::beginTag($this->tag, $this->prepareOptions());
567 | }
568 |
569 | /**
570 | * Returns data-* attribute with the given name.
571 | * Since 1.5.0 attribute value is HTML-encoded.
572 | * @param string $attribute Attribute name,
573 | * @return string
574 | */
575 | public static function dataAttribute($attribute)
576 | {
577 | return 'data-' . Html::encode($attribute);
578 | }
579 |
580 | /**
581 | * Merges the dataInit and dataName attributes with the rest of the options array.
582 | * @return array
583 | */
584 | public function prepareOptions()
585 | {
586 | return array_merge(
587 | [
588 | static::dataAttribute($this->dataInit) => true,
589 | static::dataAttribute($this->dataName) => $this->id
590 | ],
591 | $this->options
592 | );
593 | }
594 | }
595 |
--------------------------------------------------------------------------------
/src/actions/InsertAction.php:
--------------------------------------------------------------------------------
1 | request->isPost) {
65 | return Json::encode(['errors' => ['POST parameters are missing!']]);
66 | }
67 |
68 | try {
69 | $data = Yii::$app->request->post();
70 |
71 | if (empty($data['url'])) {
72 | throw new InvalidParamException('Parameter "url" is missing!');
73 | }
74 |
75 | $url = trim($data['url']);
76 | $imageName = substr($url, strrpos($url, '/') + 1);
77 | if (strpos($imageName, '?_ignore=') !== false) {
78 | $imageName = substr($imageName, 0, strpos($imageName, '?_ignore='));
79 | }
80 | $imagePath = FileHelper::normalizePath(
81 | Yii::getAlias(FileHelper::normalizePath($this->uploadDir, '/'))
82 | . DIRECTORY_SEPARATOR
83 | . $imageName
84 | );
85 |
86 | $imageSizeInfo = @getimagesize($imagePath);
87 |
88 | if ($imageSizeInfo === false) {
89 | throw new InvalidParamException('Parameter "url" seems to be invalid!');
90 | }
91 |
92 | if (!empty($data['crop'])) {
93 | $crop = explode(',', $data['crop']);
94 |
95 | if (count($crop) !== 4) {
96 | throw new InvalidParamException('Parameter "crop" is invalid!');
97 | }
98 |
99 | $positions = [];
100 |
101 | foreach ($crop as $position) {
102 | $position = trim($position);
103 |
104 | if (!is_numeric($position) || $position < 0 || $position > 1) {
105 | throw new InvalidParamException('Parameter "crop" contains invalid value!');
106 | }
107 |
108 | $positions[] = $position;
109 | }
110 |
111 | list($width, $height) = $imageSizeInfo;
112 |
113 | Image::crop(
114 | $imagePath,
115 | floor($width * $positions[3] - $width * $positions[1]),
116 | floor($height * $positions[2] - $height * $positions[0]),
117 | [
118 | floor($width * $positions[1]),
119 | floor($height * $positions[0])
120 | ]
121 | )->save($imagePath);
122 | }
123 |
124 | return Json::encode([
125 | 'size' => @getimagesize($imagePath), // not using $imageSizeInfo because it's new size
126 | 'url' => Yii::getAlias(FileHelper::normalizePath($this->viewPath, '/') . '/' . $imageName),
127 | 'alt' => $imageName
128 | ]);
129 |
130 | } catch (Exception $e) {
131 | return Json::encode(['errors' => [$e->getMessage()]]);
132 | }
133 | }
134 | }
135 |
--------------------------------------------------------------------------------
/src/actions/RotateAction.php:
--------------------------------------------------------------------------------
1 | request->isPost) {
54 | return Json::encode(['errors' => ['POST parameters are missing!']]);
55 | }
56 |
57 | try {
58 | $data = Yii::$app->request->post();
59 |
60 | if (
61 | empty($data['url'])
62 | || empty($data['direction'])
63 | || !in_array($data['direction'], ['CW', 'CCW'], true)
64 | ) {
65 | throw new InvalidParamException('Invalid rotate options!');
66 | }
67 |
68 | $url = trim($data['url']);
69 | $imageName = substr($url, strrpos($url, '/') + 1);
70 | if (strpos($imageName, '?_ignore=') !== false) {
71 | $imageName = substr($imageName, 0, strpos($imageName, '?_ignore='));
72 | }
73 | $imagePath = FileHelper::normalizePath(
74 | Yii::getAlias(FileHelper::normalizePath($this->uploadDir, '/'))
75 | . DIRECTORY_SEPARATOR
76 | . $imageName
77 | );
78 |
79 | $imageSizeInfo = @getimagesize($imagePath);
80 |
81 | if ($imageSizeInfo === false) {
82 | throw new InvalidParamException('Parameter "url" seems to be invalid!');
83 | }
84 |
85 | Image::getImagine()
86 | ->open($imagePath)
87 | ->copy()
88 | ->rotate($data['direction'] === 'CW' ? 90 : -90)
89 | ->save($imagePath);
90 |
91 | return Json::encode([
92 | 'size' => @getimagesize($imagePath), // new size
93 | 'url' => Yii::getAlias(FileHelper::normalizePath($this->viewPath, '/') . '/' . $imageName),
94 | ]);
95 |
96 | } catch (Exception $e) {
97 | return Json::encode(['errors' => [$e->getMessage()]]);
98 | }
99 | }
100 | }
101 |
--------------------------------------------------------------------------------
/src/actions/UploadAction.php:
--------------------------------------------------------------------------------
1 | request->isPost) {
47 | return Json::encode(['errors' => ['POST data is missing!']]);
48 | }
49 |
50 | $model = new ImageForm([
51 | 'uploadDir' => $this->uploadDir,
52 | 'viewPath' => $this->viewPath,
53 | 'image' => UploadedFile::getInstanceByName('image'),
54 | ]);
55 |
56 | if ($model->validate()) {
57 | if ($model->upload()) {
58 | $imageSizeInfo = @getimagesize($model->path);
59 |
60 | if ($imageSizeInfo === false) {
61 | return Json::encode(['errors' => ['Image upload path seems to be invalid!']]);
62 | }
63 |
64 | return Json::encode([
65 | 'size' => $imageSizeInfo,
66 | 'url' => $model->url
67 | ]);
68 | }
69 |
70 | return Json::encode(['errors' => ['Image upload error!']]);
71 | }
72 |
73 | $errors = [];
74 | $modelErrors = $model->getErrors();
75 |
76 | foreach ($modelErrors as $field => $fieldErrors) {
77 | foreach ($fieldErrors as $fieldError) {
78 | $errors[] = $fieldError;
79 | }
80 | }
81 |
82 | if (empty($errors)) {
83 | $errors = ['Unknown file upload validation error!'];
84 | }
85 |
86 | return Json::encode(['errors' => $errors]);
87 | }
88 | }
89 |
--------------------------------------------------------------------------------
/src/assets/ContentToolsAsset.php:
--------------------------------------------------------------------------------
1 | [
56 | 'png',
57 | 'jpg',
58 | 'jpeg',
59 | 'gif'
60 | ],
61 | 'maxWidth' => 1000,
62 | 'maxHeight' => 1000,
63 | 'maxSize' => 2 * 1024 * 1024
64 | ]
65 | ];
66 | }
67 |
68 | private $_uploadDir;
69 |
70 | /**
71 | * Sets image upload folder. This can be Yii alias.
72 | * @param string $path
73 | * @since 1.4.0
74 | */
75 | public function setUploadDir($path)
76 | {
77 | $this->_uploadDir = $path;
78 | }
79 |
80 | private $_viewPath;
81 |
82 | /**
83 | * Sets web accesible path to upload folder. This can be Yii alias.
84 | * @param string $path
85 | * @since 1.4.0
86 | */
87 | public function setViewPath($path)
88 | {
89 | $this->_viewPath = $path;
90 | }
91 |
92 | /**
93 | * Validates and saves the image.
94 | * Creates the folder to store images if necessary.
95 | * @return bool
96 | */
97 | public function upload()
98 | {
99 | if (!$this->validate()) {
100 | return false;
101 | }
102 |
103 | try {
104 | // first normalize for alias translating then for OS
105 | $save_path = FileHelper::normalizePath(Yii::getAlias(FileHelper::normalizePath($this->_uploadDir, '/')));
106 | FileHelper::createDirectory($save_path);
107 |
108 | $image = $this->image->baseName . '.' . $this->image->extension;
109 | $this->path = $save_path . DIRECTORY_SEPARATOR . $image;
110 | $this->url = Yii::getAlias(FileHelper::normalizePath($this->_viewPath, '/') . '/' . $image);
111 |
112 | return $this->image->saveAs($this->path);
113 |
114 | } catch (Exception $e) {
115 | Yii::error($e->getMessage());
116 | }
117 |
118 | return false;
119 | }
120 | }
121 |
--------------------------------------------------------------------------------