PluginProbe
Brizy – Page Builder / trunk
Brizy – Page Builder vtrunk
2.8.23 2.8.22 2.8.21 2.8.20 2.8.19 2.8.18 2.8.17 2.8.16 2.8.15 2.8.14 2.6.4 2.6.5 2.6.6 2.6.7 2.6.8 2.6.9 2.7.0 2.7.1 2.7.10 2.7.11 2.7.12 2.7.13 2.7.14 2.7.15 2.7.16 All 188 releases
brizy / admin / blocks / api.php

api.php in Brizy – Page Builder trunk, at admin/blocks/api.php

775 lines 30.3 KB
No matching file
Up and down to move Enter to open Esc to close
Raw Download Zip
1 <?php
2 /**
3 * Created by PhpStorm.
4 * User: alex
5 * Date: 7/18/18
6 * Time: 10:48 AM
7 */
8
9 class Brizy_Admin_Blocks_Api extends Brizy_Admin_AbstractApi
10 {
11
12 const nonce = 'brizy-api';
13
14 const GET_SAVED_BLOCK_ACTION = '-get-saved-block';
15 const GET_GLOBAL_BLOCKS_ACTION = '-get-global-blocks';
16 const GET_SAVED_BLOCKS_ACTION = '-get-saved-blocks';
17 const CREATE_GLOBAL_BLOCK_ACTION = '-create-global-block';
18 const CREATE_SAVED_BLOCK_ACTION = '-create-saved-block';
19 const UPDATE_GLOBAL_BLOCK_ACTION = '-update-global-block';
20 const UPDATE_GLOBAL_BLOCKS_ACTION = '-update-global-blocks';
21 const UPDATE_SAVED_BLOCK_ACTION = '-saved-global-block';
22 const DELETE_GLOBAL_BLOCK_ACTION = '-delete-global-block';
23 const DELETE_SAVED_BLOCK_ACTION = '-delete-saved-block';
24 const UPDATE_POSITIONS_ACTION = '-update-block-positions';
25 const DOWNLOAD_BLOCKS = '-download-blocks';
26 const UPLOAD_BLOCKS = '-upload-blocks';
27
28 /**
29 * @var Brizy_Admin_Rules_Manager
30 */
31 private $ruleManager;
32
33 /**
34 * @return Brizy_Admin_Blocks_Api
35 */
36 public static function _init()
37 {
38 static $instance;
39 if (!$instance) {
40 $instance = new self(new Brizy_Admin_Rules_Manager());
41 }
42
43 return $instance;
44 }
45
46 /**
47 * Brizy_Admin_Blocks_Api constructor.
48 *
49 * @param Brizy_Admin_Rules_Manager $ruleManager
50 */
51 public function __construct($ruleManager)
52 {
53 $this->ruleManager = $ruleManager;
54 parent::__construct();
55 }
56
57 protected function getRequestNonce()
58 {
59 return $this->param('hash');
60 }
61
62 /**
63 * Saving a page also saves the global blocks it contains, so this path cannot require
64 * edit_pages without locking out roles that may edit posts but not pages (ex: contributor).
65 * CAP_EDIT_WHOLE_PAGE is togglable per role in Brizy settings and excludes content-only editors.
66 *
67 * @return void
68 */
69 private function verifyGlobalBlockWriteAccess()
70 {
71 if (!current_user_can(Brizy_Admin_Capabilities::CAP_EDIT_WHOLE_PAGE) && !Brizy_Editor_User::is_administrator()) {
72 $this->error(403, 'Unauthorized.');
73 }
74 }
75
76 protected function initializeApiActions()
77 {
78 $pref = 'wp_ajax_' . Brizy_Editor::prefix();
79 add_action($pref . self::DOWNLOAD_BLOCKS, array($this, 'actionDownloadBlocks'));
80 add_action($pref . self::UPLOAD_BLOCKS, array($this, 'actionUploadBlocks'));
81 add_action($pref . self::GET_GLOBAL_BLOCKS_ACTION, array($this, 'actionGetGlobalBlocks'));
82 add_action($pref . self::CREATE_GLOBAL_BLOCK_ACTION, array($this, 'actionCreateGlobalBlock'));
83 add_action($pref . self::UPDATE_GLOBAL_BLOCK_ACTION, array($this, 'actionUpdateGlobalBlock'));
84 add_action($pref . self::UPDATE_GLOBAL_BLOCKS_ACTION, array($this, 'actionUpdateGlobalBlocks'));
85 add_action($pref . self::DELETE_GLOBAL_BLOCK_ACTION, array($this, 'actionDeleteGlobalBlock'));
86 add_action($pref . self::GET_SAVED_BLOCKS_ACTION, array($this, 'actionGetSavedBlocks'));
87 add_action($pref . self::GET_SAVED_BLOCK_ACTION, array($this, 'actionGetSavedBlockByUid'));
88 add_action($pref . self::UPDATE_SAVED_BLOCK_ACTION, array($this, 'actionUpdateSavedBlock'));
89 add_action($pref . self::CREATE_SAVED_BLOCK_ACTION, array($this, 'actionCreateSavedBlock'));
90 add_action($pref . self::DELETE_SAVED_BLOCK_ACTION, array($this, 'actionDeleteSavedBlock'));
91 add_action($pref . self::UPDATE_POSITIONS_ACTION, array($this, 'actionUpdateBlockPositions'));
92 }
93
94 public function actionDownloadBlocks()
95 {
96 $this->verifyAuthorization(self::nonce);
97 if (!$this->param('uid')) {
98 $this->error(400, 'Invalid block uid param');
99 }
100 try {
101 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
102 $uids = [];
103 // this is not a very eficien solution if you have a big array of uids
104 $explode = explode(',', $this->param('uid'));
105 $items = array_map(function ($auid) use ($uids, $bockManager) {
106 list($uid, $isPro) = explode(':', $auid);
107 $uids[] = $uid;
108 $item = new Brizy_Editor_Zip_ArchiveItem($uid, $isPro);
109 if ($post = $bockManager->getEntity($uid)) {
110 $item->setPost($post);
111
112 return $item;
113 }
114
115 return null;
116 }, $explode);
117 $items = array_filter($items);
118 if (count($items) == 0) {
119 $this->error(404, __('There are no blocks to be archived', 'brizy'));
120 }
121 $fontManager = new Brizy_Admin_Fonts_Manager();
122 $zip = new Brizy_Editor_Zip_Archiver(Brizy_Editor_Project::get(), $fontManager, BRIZY_SYNC_VERSION);
123 switch ($this->param('type')) {
124 case 'popup':
125 $zipPath = "Popup-" . date(DATE_ATOM) . ".zip";
126 break;
127 default:
128 $zipPath = "Block-" . date(DATE_ATOM) . ".zip";
129 break;
130 }
131 $zipPath = $zip->createZip($items, $zipPath);
132 header("Pragma: public");
133 header("Expires: 0");
134 header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
135 header("Cache-Control: private", false);
136 header("Content-Type: application/octet-stream");
137 header("Content-Disposition: attachment; filename=\"" . basename($zipPath) . "\";");
138 header("Content-Transfer-Encoding: binary");
139 echo file_get_contents($zipPath);
140 exit;
141 } catch (Exception $exception) {
142 $this->error(400, __($exception->getMessage(), 'brizy'));
143 }
144 }
145
146 public function actionUploadBlocks()
147 {
148 try {
149 $this->verifyAuthorization(self::nonce);
150 if (!isset($_FILES['files'])) {
151 $this->error(400, __('Invalid block file'));
152 }
153 $fields = $this->param('fields') ? $this->param('fields') : [];
154 if (!function_exists('wp_handle_upload')) {
155 require_once(ABSPATH . 'wp-admin/includes/file.php');
156 }
157 $file = [
158 'name' => $_FILES['files']['name'][0],
159 'type' => $_FILES['files']['type'][0],
160 'tmp_name' => $_FILES['files']['tmp_name'][0],
161 'error' => $_FILES['files']['error'][0],
162 'size' => $_FILES['files']['size'][0],
163 ];
164 $uploadedFile = wp_handle_upload($file, ['test_form' => false]);
165 if (isset($uploadedFile['file'])) {
166 $zip = new Brizy_Editor_Zip_Archiver(Brizy_Editor_Project::get(), new Brizy_Admin_Fonts_Manager(), BRIZY_SYNC_VERSION);
167 list($instances, $errors) = $zip->createFromZip($uploadedFile['file']);
168 unset($uploadedFile['file']);
169 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
170 $this->success([
171 'success' => $bockManager->createResponseForEntities($instances, $fields),
172 'errors' => $errors,
173 ]);
174 } else {
175 if (isset($uploadedFile['error'])) {
176 $this->error(400, $uploadedFile['error']);
177 } else {
178 $this->error(400, __("Invalid zip file provided"));
179 }
180 }
181
182 } catch (Exception $exception) {
183 $this->error(400, $exception->getMessage());
184 }
185 }
186
187 public function actionGetGlobalBlocks()
188 {
189 $this->verifyAuthorization(self::nonce);
190 try {
191 $fields = $this->param('fields') ? $this->param('fields') : [];
192 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL);
193 $blocks = $bockManager->getEntities([
194 'post_status' => 'any',
195 'order' => $this->param('order') ?: 'DESC',
196 'orderby' => $this->param('orderby') ?: 'ID'
197 ]);
198 $this->success($bockManager->createResponseForEntities($blocks, $fields));
199 } catch (Exception $exception) {
200 $this->error(400, $exception->getMessage());
201 }
202 }
203
204 public function actionCreateGlobalBlock()
205 {
206 $this->verifyAuthorization(self::nonce);
207 if (!$this->param('uid')) {
208 $this->error(400, 'Invalid uid');
209 }
210 if (!$this->param('data')) {
211 $this->error(400, 'Invalid data');
212 }
213 if (!$this->param('meta')) {
214 $this->error(400, 'Invalid meta data');
215 }
216 try {
217 $compiledData = stripslashes($this->param('compiled'));
218 $editorData = $this->sanitizeJson(stripslashes($this->param('data')));
219 $position = stripslashes($this->param('position'));
220 $status = stripslashes($this->param('status'));
221 $rulesData = stripslashes($this->param('rules'));
222 $dependencies = stripslashes($this->param('dependencies'));
223 if (!in_array($status, ['publish', 'draft'])) {
224 $this->error(400, "Invalid status");
225 }
226 if (json_decode($editorData) === null && json_last_error() !== JSON_ERROR_NONE) {
227 $this->error(400, "Invalid JSON data");
228 }
229 if ($status == 'publish' && is_null($compiledData)) {
230 $this->error(400, "The compiled data is missing");
231 }
232 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL);
233 /**
234 * @var Brizy_Editor_Block $block ;
235 */
236 $block = $bockManager->createEntity($this->param('uid'), $status);
237 $block->setMeta(stripslashes($this->param('meta')));
238 $block->setEditorData($editorData);
239 $block->set_needs_compile(true);
240
241 if (is_array($dependencies) && count($dependencies) > 0) {
242 $block->setDependencies($dependencies);
243 }
244 if ($status == 'publish' && $compiledData) {
245
246 $compiled = json_decode($compiledData, true);
247 if (is_null($compiled)) {
248 $this->error(400, "The compiled data is invalid");
249 }
250 $section_manager = $block->getCompiledSectionManager();
251 $section_manager->merge(json_decode($compiledData, true));
252 $block->setCompiledSections($section_manager->asJson());
253 $block->set_compiler_version(BRIZY_EDITOR_VERSION);
254 }
255 if ($this->param('title')) {
256 $block->setTitle(stripslashes($this->param('title')));
257 }
258 if ($this->param('tags')) {
259 $block->setTags(stripslashes($this->param('tags')));
260 }
261 if ($position) {
262 $block->setPosition(Brizy_Editor_BlockPosition::createFromSerializedData(get_object_vars(json_decode($position))));
263 }
264 // rules
265 if ($rulesData) {
266 $rules = $this->ruleManager->createRulesFromJson($rulesData, Brizy_Admin_Blocks_Main::CP_GLOBAL);
267 $this->ruleManager->addRules($block->getWpPostId(), $rules);
268 }
269 if (!current_user_can('edit_pages')) {
270 $this->error(403, 'Unauthorized.');
271 }
272 $block->save();
273 do_action('brizy_global_block_created', $block);
274 $this->success($block->createResponse());
275
276 } catch (Exception $exception) {
277 $this->error(400, $exception->getMessage());
278 }
279 }
280
281 public function actionUpdateGlobalBlock()
282 {
283 $this->verifyAuthorization(self::nonce);
284 try {
285
286 if (!$this->param('uid')) {
287 $this->error('400', 'Invalid uid');
288 }
289 $compiledData = stripslashes($this->param('compiled'));
290 $status = stripslashes($this->param('status'));
291 $dependencies = json_decode(stripslashes($this->param('dependencies')));
292 if (!in_array($status, ['publish', 'draft'])) {
293 $this->error(400, "Invalid post type");
294 }
295 if ($status == 'publish' && is_null($compiledData)) {
296 $this->error(400, "The compiled data is missing");
297 }
298 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL);
299 $block = $bockManager->getEntity($this->param('uid'));
300 if (!$block) {
301 $this->error(400, "Global block not found");
302 }
303 // some setters below write straight to post meta, so this must run before them
304 $this->verifyGlobalBlockWriteAccess();
305 /**
306 * @var Brizy_Editor_Block $block ;
307 */
308 if ($this->param('meta')) {
309 $block->setMeta(stripslashes($this->param('meta')));
310 }
311 if ($this->param('data')) {
312 $data = $this->sanitizeJson(stripslashes($this->param('data')));
313 if (json_decode($data) !== null && !json_last_error()) {
314 $block->setEditorData($data);
315 }
316 }
317
318 $compiled_section_manager = $block->getCompiledSectionManager();
319
320 if ($this->param('title')) {
321 $block->setTitle(stripslashes($this->param('title')));
322 }
323
324 if ($compiledData) {
325 $block->set_compiler(Brizy_Editor_Post::COMPILER_EXTERNAL);
326 $compiled_sections = json_decode($compiledData, true);
327 if (!$compiled_sections) {
328 $this->error(400, "The compiled data is invalid");
329 }
330 $compiled_section_manager->merge($compiled_sections);
331 $block->setCompiledSections($compiled_section_manager->asJson());
332 $block->setHtml('');
333 }
334
335 if ($this->param('tags')) {
336 $block->setTags(stripslashes($this->param('tags')));
337 }
338 if (is_array($dependencies)) {
339 $block->setDependencies($dependencies);
340 }
341 if ((int)$this->param('is_autosave')) {
342 $block->save(1);
343 } else {
344 // issue: #14271
345 //$block->setDataVersion( $this->param( 'dataVersion' ) );
346 $block->getWpPost()->post_status = $status;
347 // position
348 $position = stripslashes($this->param('position'));
349 if ($position) {
350 $block->setPosition(Brizy_Editor_BlockPosition::createFromSerializedData(get_object_vars(json_decode($position))));
351 }
352 // rules
353 $rulesData = stripslashes($this->param('rules'));
354 if ($rulesData) {
355 $rules = $this->ruleManager->createRulesFromJson($rulesData, Brizy_Admin_Blocks_Main::CP_GLOBAL);
356 $this->ruleManager->setRules($block->getWpPostId(), $rules);
357 }
358 $block->save(0);
359 do_action('brizy_global_block_updated', $block);
360 }
361 Brizy_Editor_Block::cleanClassCache();
362 $this->success(Brizy_Editor_Block::get($block->getWpPostId())->createResponse());
363 } catch (Exception $exception) {
364 $this->error(400, $exception->getMessage());
365 }
366 }
367
368 public function actionUpdateGlobalBlocks()
369 {
370 $this->verifyAuthorization(self::nonce);
371 try {
372
373 $this->verifyGlobalBlockWriteAccess();
374 if (!$this->param('uid')) {
375 $this->success([]);
376 }
377 foreach ((array)$this->param('uid') as $i => $uid) {
378
379 if (!$this->param('uid')[$i]) {
380 $this->error('400', 'Invalid uid');
381 }
382 $status = stripslashes($this->param('status')[$i]);
383 if (!in_array($status, ['publish', 'draft'])) {
384 $this->error(400, "Invalid post type");
385 }
386 }
387 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL);
388 $blocks = $bockManager->getEntity((array)$this->param('uid'));
389 foreach ((array)$this->param('uid') as $i => $uid) {
390
391 if (!isset($blocks[$uid])) {
392 $this->error(400, "Global block not found");
393 }
394 /**
395 * @var Brizy_Editor_Block $block ;
396 */
397 $status = stripslashes($this->param('status')[$i]);
398 $block = $blocks[$uid];
399 if (isset($this->param('meta')[$i])) {
400 $block->setMeta(stripslashes($this->param('meta')[$i]));
401 }
402 $compiled_section_manager = $block->getCompiledSectionManager();
403 if (isset($this->param('compiled')[$i])) {
404 $compiled_sections = stripslashes($this->param('compiled')[$i]);
405 $compiled_sections = json_decode($compiled_sections, true);
406 if (!$compiled_sections) {
407 $this->error(400, "The compiled data is invalid");
408 }
409 $compiled_section_manager->merge($compiled_sections);
410 $block->setCompiledSections($compiled_section_manager->asJson());
411 $block->set_compiler_version(BRIZY_EDITOR_VERSION);
412 $block->set_needs_compile(false);
413 $block->set_compiler(Brizy_Editor_Entity::COMPILER_BROWSER);
414 }
415 if (isset($this->param('title')[$i])) {
416 $block->setTitle(stripslashes($this->param('title')[$i]));
417 }
418 if (is_array($this->param('dependencies')[$i]) && count($this->param('dependencies')[$i]) > 0) {
419 $block->setDependencies($this->param('dependencies')[$i]);
420 }
421 if (isset($this->param('tags')[$i])) {
422 $block->setTags(stripslashes($this->param('tags')[$i]));
423 }
424 if (isset($this->param('data')[$i]) && !empty($this->param('data')[$i])) {
425 $data = $this->sanitizeJson(stripslashes($this->param('data')[$i]));
426 if (json_decode($data) !== null && !json_last_error()) {
427 $block->setEditorData($data);
428 }
429 }
430
431 if (isset($this->param('is_autosave')[$i]) && (int)$this->param('is_autosave')[$i] === 1) {
432 $block->save(1);
433 } else {
434
435 // issue: #14271
436 //$block->setDataVersion( $this->param( 'dataVersion' )[ $i ] );
437 $block->getWpPost()->post_status = $status;
438 // position
439 $position = stripslashes($this->param('position')[$i]);
440 if ($position && ($positionObject = json_decode($position))) {
441 $block->setPosition(Brizy_Editor_BlockPosition::createFromSerializedData(get_object_vars($positionObject)));
442 }
443 // rules
444 $rulesData = stripslashes($this->param('rules')[$i]);
445 if ($rulesData) {
446 $rules = $this->ruleManager->createRulesFromJson($rulesData, Brizy_Admin_Blocks_Main::CP_GLOBAL);
447 $this->ruleManager->setRules($block->getWpPostId(), $rules);
448 }
449 $block->save();
450 do_action('brizy_global_block_updated', $block);
451 }
452 }
453 $this->success([]);
454
455 } catch (Exception $exception) {
456 $this->error(400, $exception->getMessage());
457 }
458 }
459
460 public function actionDeleteGlobalBlock()
461 {
462 $this->verifyAuthorization(self::nonce);
463 if (!current_user_can('edit_pages')) {
464 $this->error(403, 'Unauthorized.');
465 }
466 if (!$this->param('uid')) {
467 $this->error('400', 'Invalid uid');
468 }
469 $block = $this->getBlock($this->param('uid'), Brizy_Admin_Blocks_Main::CP_GLOBAL);
470 if ($block) {
471 do_action('brizy_global_block_deleted', $block);
472 do_action('brizy_global_data_deleted');
473 $this->deleteBlock($block, Brizy_Admin_Blocks_Main::CP_GLOBAL);
474 $this->success(null);
475 }
476 $this->error('404', 'Block not found');
477 }
478
479 public function actionGetSavedBlocks()
480 {
481 $this->verifyAuthorization(self::nonce);
482 try {
483 $fields = $this->param('fields') ? $this->param('fields') : [];
484 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
485 $blocks = $bockManager->getEntities([
486 'paged' => (int)($this->param('page') ?: 1),
487 'posts_per_page' => (int)($this->param('count') ?: -1),
488 'order' => $this->param('order') ?: 'ASC',
489 'orderby' => $this->param('orderby') ?: 'ID',
490 ]);
491 $blocks = apply_filters('brizy_get_saved_blocks', $bockManager->createResponseForEntities($blocks, $fields), $fields, $bockManager);
492 $this->success($blocks);
493 } catch (Exception $exception) {
494 $this->error(400, $exception->getMessage());
495 }
496 }
497
498 public function actionGetSavedBlockByUid()
499 {
500 $this->verifyAuthorization(self::nonce);
501 if (!$this->param('uid')) {
502 $this->error(400, 'Invalid uid');
503 }
504 $fields = $this->param('fields') ? $this->param('fields') : [];
505 try {
506
507 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
508 $block = $bockManager->getEntity($this->param('uid'));
509 $block = apply_filters('brizy_get_saved_block', $block, $this->param('uid'), $bockManager);
510 if (!$block) {
511 $this->error(404, 'Block not found');
512 }
513 $this->success($block->createResponse($fields));
514 } catch (Exception $exception) {
515 $this->error(400, $exception->getMessage());
516 }
517 }
518
519 public function actionCreateSavedBlock()
520 {
521 $this->verifyAuthorization(self::nonce);
522 if (!current_user_can('edit_pages')) {
523 $this->error(403, 'Unauthorized.');
524 }
525 if (!$this->param('uid')) {
526 $this->error(400, 'Invalid uid');
527 }
528 if (!$this->param('data')) {
529 $this->error(400, 'Invalid data');
530 }
531 if (!$this->param('meta')) {
532 $this->error(400, 'Invalid meta data');
533 }
534 if (!$this->param('media')) {
535 $this->error(400, 'Invalid media data provided');
536 }
537 try {
538 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
539 $block = $bockManager->createEntity($this->param('uid'));
540 $block->setMedia(stripslashes($this->param('media')));
541 $block->setMeta(stripslashes($this->param('meta')));
542 if ($this->param('title')) {
543 $block->setTitle(stripslashes($this->param('title')));
544 }
545 if ($this->param('tags')) {
546 $block->setTags(stripslashes($this->param('tags')));
547 }
548 $block->setEditorData($this->sanitizeJson(stripslashes($this->param('data'))));
549 $block->set_needs_compile(true);
550 //$block->setCloudUpdateRequired( true );
551 $block->save();
552 do_action('brizy_saved_block_created', $block);
553 $this->success($block->createResponse());
554
555 } catch (Exception $exception) {
556 $this->error(400, $exception->getMessage());
557 }
558 }
559
560 public function actionUpdateSavedBlock()
561 {
562 $this->verifyAuthorization(self::nonce);
563 if (!current_user_can('edit_pages')) {
564 $this->error(403, 'Unauthorized.');
565 }
566 try {
567 if (!$this->param('uid')) {
568 $this->error('400', 'Invalid uid');
569 }
570 if ($this->param('dataVersion') === null) {
571 $this->error('400', 'Invalid data version');
572 }
573 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
574 $block = $bockManager->getEntity($this->param('uid'));
575 if (!$block instanceof Brizy_Editor_Block) {
576 $this->error('404', 'Block not found');
577 }
578 $block->setDataVersion($this->param('dataVersion'));
579 if ($this->param('data')) {
580 $block->setEditorData($this->sanitizeJson(stripslashes($this->param('data'))));
581 }
582 if ($this->param('media')) {
583 $block->setMedia(stripslashes($this->param('media')));
584 }
585 if ($this->param('meta')) {
586 $block->setMeta(stripslashes($this->param('meta')));
587 }
588 if ($this->param('title')) {
589 $block->setTitle(stripslashes($this->param('title')));
590 }
591 if ($this->param('tags')) {
592 $block->setTags(stripslashes($this->param('tags')));
593 }
594 if ((int)$this->param('is_autosave')) {
595 $block->save(1);
596 } else {
597 $block->save();
598 do_action('brizy_saved_block_updated', $block);
599 }
600 Brizy_Editor_Block::cleanClassCache();
601 $this->success(Brizy_Editor_Block::get($block->getWpPostId())->createResponse());
602 } catch (Exception $exception) {
603 $this->error(400, $exception->getMessage());
604 }
605 }
606
607 public function actionDeleteSavedBlock()
608 {
609 $this->verifyAuthorization(self::nonce);
610 if (!current_user_can('edit_pages')) {
611 $this->error(403, 'Unauthorized.');
612 }
613 if (!$this->param('uid')) {
614 $this->error('400', 'Invalid uid');
615 }
616 try {
617 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED);
618 $block = $bockManager->getEntity($this->param('uid'));
619 do_action('brizy_saved_block_delete', $this->param('uid'));
620 if ($block) {
621 do_action('brizy_global_data_deleted');
622 $bockManager->deleteEntity($block);
623 } else {
624 $this->error('404', 'Block not found');
625 }
626 } catch (Exception $e) {
627 $this->error('500', 'Unable to delete block');
628 }
629 $this->success(null);
630 }
631
632 public function actionUpdateBlockPositions()
633 {
634
635 global $wpdb;
636 $this->verifyAuthorization(self::nonce);
637 $this->verifyGlobalBlockWriteAccess();
638 $data = file_get_contents("php://input");
639 $dataObject = json_decode($data);
640 if (!$dataObject) {
641 $this->error(400, 'Invalid position data provided');
642 }
643 $wpdb->query('START TRANSACTION');
644 try {
645
646 foreach (get_object_vars($dataObject) as $uid => $position) {
647
648 if (!(isset($position->top) && isset($position->bottom) && isset($position->align))) {
649 throw new Exception();
650 }
651 $positionObj = new Brizy_Editor_BlockPosition($position->top, $position->bottom, $position->align);
652 $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL);
653 $block = $bockManager->getEntity($uid);
654 if (!$block) {
655 throw new Exception();
656 }
657 $block->setPosition($positionObj);
658 if ($this->param('is_autosave') == 1) {
659 $block->save(1);
660 } else {
661 $block->saveStorage();
662 }
663 do_action('brizy_global_block_updated', $block);
664 }
665 $wpdb->query('COMMIT');
666
667 } catch (Exception $e) {
668 $wpdb->query('ROLLBACK');
669 $this->error('400', 'Unable to save block positions');
670 }
671 $this->success(json_encode($dataObject));
672 }
673
674
675 /**
676 * @param $uid
677 * @param $postType
678 *
679 * @return string|null
680 */
681 private function getBlockIdByUidAndBlockType($uid, $postType)
682 {
683 global $wpdb;
684 $prepare = $wpdb->prepare("SELECT ID FROM {$wpdb->posts} p
685 JOIN {$wpdb->postmeta} pm ON
686 pm.post_id=p.ID and
687 meta_key='brizy_post_uid' and
688 meta_value='%s'
689 WHERE p.post_type IN ('%s')
690 ORDER BY p.ID DESC
691 LIMIT 1", array($uid, $postType));
692
693 return $wpdb->get_var($prepare);
694 }
695
696 /**
697 * @param $uid
698 * @param $postType
699 *
700 * @return string|null
701 */
702 private function getBlockIdByUid($uid)
703 {
704 global $wpdb;
705 $prepare = $wpdb->prepare("SELECT ID FROM {$wpdb->posts} p
706 JOIN {$wpdb->postmeta} pm ON pm.post_id=p.ID and meta_key='brizy_post_uid' and meta_value='%s'
707 WHERE p.post_type <> 'attachment'
708 ORDER BY p.ID DESC
709 LIMIT 1", array($uid,));
710
711 return $wpdb->get_var($prepare);
712 }
713
714 /**
715 * @param $id
716 * @param $postType
717 *
718 * @return Brizy_Editor_Block|null
719 * @throws Brizy_Editor_Exceptions_NotFound
720 */
721 private function getBlock($id, $postType)
722 {
723 $postId = $this->getBlockIdByUidAndBlockType($id, $postType);
724 if ($postId) {
725 return Brizy_Editor_Block::get($postId);
726 }
727
728 return null;
729 }
730
731 /**
732 * @param $uid
733 * @param $status
734 * @param $type
735 *
736 * @return Brizy_Editor_Block
737 * @throws Brizy_Editor_Exceptions_NotFound
738 */
739 private function createBlock($uid, $status, $type)
740 {
741 $name = md5(time());
742 $post = wp_insert_post(array(
743 'post_title' => '',
744 'post_name' => $name,
745 'post_status' => $status,
746 'post_type' => $type,
747 ));
748 if ($post) {
749 $brizyPost = Brizy_Editor_Block::get($post, $uid);
750 $brizyPost->set_uses_editor(true);
751 $brizyPost->set_needs_compile(true);
752 $brizyPost->setDataVersion(1);
753
754 return $brizyPost;
755 }
756 throw new Exception('Unable to create block');
757 }
758
759 /**
760 * @param $postUid
761 * @param $postType
762 *
763 * @return false|WP_Post|null
764 */
765 private function deleteBlock($block, $postType)
766 {
767
768 if ($postType === Brizy_Admin_Blocks_Main::CP_SAVED) {
769
770 }
771
772 return wp_delete_post($block->getWpPostId());
773 }
774 }
775