From 4af0029ed19169ab2befbe38b611b1a4214456b5 Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Wed, 24 Nov 2021 19:16:26 +0200 Subject: [PATCH 01/44] new: Made te fields optional for update blocks/popups/layouts --- admin/blocks/api.php | 44 ++++++++++++++++++++----------------------- admin/layouts/api.php | 43 ++++++++++++++++++++---------------------- 2 files changed, 40 insertions(+), 47 deletions(-) diff --git a/admin/blocks/api.php b/admin/blocks/api.php index 07304d1c1a..18c74e3cef 100644 --- a/admin/blocks/api.php +++ b/admin/blocks/api.php @@ -111,8 +111,8 @@ public function actionDownloadBlocks() $items = array_filter($items); if (count($items) == 0) { - $this->error(404, __('There are no blocks to be archived', 'brizy' ) ); - } + $this->error(404, __('There are no blocks to be archived', 'brizy')); + } $fontManager = new Brizy_Admin_Fonts_Manager(); $zip = new Brizy_Editor_Zip_Archiver( @@ -236,16 +236,14 @@ public function actionCreateGlobalBlock() } $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL); - - /** + /** * @var Brizy_Editor_Post $block; - */ - $block = $bockManager->createEntity($this->param('uid'), $status); + */$block = $bockManager->createEntity($this->param('uid'), $status); $block->setMeta(stripslashes($this->param('meta'))); $block->set_editor_data($editorData); $block->set_needs_compile(true); - if($this->param('title')) + if($this->param('title')) { $block->setTitle(stripslashes($this->param('title'))); } @@ -253,9 +251,7 @@ public function actionCreateGlobalBlock() if($this->param('tags')) { $block->setTags(stripslashes($this->param('tags'))); - } - - if ($position) { + }if ($position) { $block->setPosition( Brizy_Editor_BlockPosition::createFromSerializedData(get_object_vars(json_decode($position))) ); @@ -380,7 +376,7 @@ public function actionUpdateGlobalBlocks() } $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL); - $blocks = $bockManager->getEntity((array)$this->param('uid')); + $blocks = $bockManager->getEntity((array)$this->param('uid')); foreach ((array)$this->param('uid') as $i => $uid) { @@ -442,11 +438,13 @@ public function actionUpdateGlobalBlocks() $block->save(); do_action('brizy_global_block_updated', $block); + } - } +} do_action('brizy_global_data_updated'); + $this->success([]); } catch (Exception $exception) { @@ -479,18 +477,19 @@ public function actionGetSavedBlocks() $this->verifyNonce(self::nonce); try { - $fields = $this->param('fields') ? $this->param('fields') : []; + $fields = $this->param('fields') ? $this->param('fields') : []; $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED); - $blocks = $bockManager->getEntities([ - 'paged' => (int)($this->param('page') ?: 1), + $blocks = $bockManager->getEntities([ + 'paged' => (int)($this->param('page') ?: 1), 'posts_per_page' => (int)($this->param('count') ?: -1), 'order' => $this->param('order') ?: 'ASC', 'orderby' => $this->param('orderby') ?: 'ID' - ]); - $blocks = apply_filters('brizy_get_saved_blocks', + ]);$blocks = apply_filters( + 'brizy_get_saved_blocks', $bockManager->createResponseForEntities($blocks, $fields), $fields, - $bockManager); + $bockManager + ); $this->success($blocks); } catch (Exception $exception) { $this->error(400, $exception->getMessage()); @@ -546,10 +545,9 @@ public function actionCreateSavedBlock() try { $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_SAVED); - $block = $bockManager->createEntity($this->param('uid')); + $block = $bockManager->createEntity($this->param('uid')); $block->setMedia(stripslashes($this->param('media'))); $block->setMeta(stripslashes($this->param('meta'))); - if($this->param('title')) { $block->setTitle(stripslashes($this->param('title'))); @@ -557,9 +555,7 @@ public function actionCreateSavedBlock() if($this->param('tags')) { $block->setTags(stripslashes($this->param('tags'))); - } - - $block->set_editor_data(stripslashes($this->param('data'))); + }$block->set_editor_data(stripslashes($this->param('data'))); $block->set_needs_compile(true); //$block->setCloudUpdateRequired( true ); $block->save(); @@ -619,7 +615,7 @@ public function actionUpdateSavedBlock() } - if ((int)$this->param('is_autosave')) { + if ((int)$this->param('is_autosave')) { $block->save(1); } else { $block->save(); diff --git a/admin/layouts/api.php b/admin/layouts/api.php index 8eab29d543..7aac51c123 100644 --- a/admin/layouts/api.php +++ b/admin/layouts/api.php @@ -41,13 +41,13 @@ protected function getRequestNonce() protected function initializeApiActions() { - $pref = 'wp_ajax_' . Brizy_Editor::prefix(); - add_action($pref . self::DOWNLOAD_LAYOUTS, array($this, 'actionDownloadLayouts')); - add_action($pref . self::GET_LAYOUT_BY_UID_ACTION, array($this, 'actionGetLayoutByUid')); - add_action($pref . self::GET_LAYOUTS_ACTION, array($this, 'actionGetLayouts')); - add_action($pref . self::CREATE_LAYOUT_ACTION, array($this, 'actionCreateLayout')); - add_action($pref . self::UPDATE_LAYOUT_ACTION, array($this, 'actionUpdateLayout')); - add_action($pref . self::DELETE_LAYOUT_ACTION, array($this, 'actionDeleteLayout')); + $pref = 'wp_ajax_'.Brizy_Editor::prefix(); + add_action($pref.self::DOWNLOAD_LAYOUTS, array($this, 'actionDownloadLayouts')); + add_action($pref.self::GET_LAYOUT_BY_UID_ACTION, array($this, 'actionGetLayoutByUid')); + add_action($pref.self::GET_LAYOUTS_ACTION, array($this, 'actionGetLayouts')); + add_action($pref.self::CREATE_LAYOUT_ACTION, array($this, 'actionCreateLayout')); + add_action($pref.self::UPDATE_LAYOUT_ACTION, array($this, 'actionUpdateLayout')); + add_action($pref.self::DELETE_LAYOUT_ACTION, array($this, 'actionDeleteLayout')); } public function actionDownloadLayouts() @@ -77,26 +77,26 @@ public function actionDownloadLayouts() return null; }, $explode); - $items = array_filter($items); + $items = array_filter($items); if (count($items) == 0) { $this->error(404, __('There are no layouts to be archived')); } - $zipPath = "Layout-" . date(DATE_ATOM) . ".zip"; + $zipPath = "Layout-".date(DATE_ATOM).".zip"; $fontManager = new Brizy_Admin_Fonts_Manager(); - $zip = new Brizy_Editor_Zip_Archiver( + $zip = new Brizy_Editor_Zip_Archiver( Brizy_Editor_Project::get(), $fontManager, BRIZY_SYNC_VERSION ); - $zipPath = $zip->createZip($items, $zipPath); + $zipPath = $zip->createZip($items, $zipPath); header("Pragma: public"); header("Expires: 0"); header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); header("Cache-Control: private", false); header("Content-Type: application/octet-stream"); - header("Content-Disposition: attachment; filename=\"" . basename($zipPath) . "\";"); + header("Content-Disposition: attachment; filename=\"".basename($zipPath)."\";"); header("Content-Transfer-Encoding: binary"); echo file_get_contents($zipPath); @@ -143,18 +143,19 @@ public function actionGetLayouts() $layoutManager = new Brizy_Admin_Layouts_Manager(); $fields = $this->param('fields') ? $this->param('fields') : []; - $layouts = $layoutManager->getEntities( - [ + + $layouts = $layoutManager->getEntities([ 'paged' => (int)($this->param('page') ?: 1), 'posts_per_page' => (int)($this->param('count') ?: -1), 'order' => $this->param('order') ?: 'ASC', 'orderby' => $this->param('orderby') ?: 'ID' - ] - ); - $layouts = apply_filters('brizy_get_layouts', + ]); + $layouts = apply_filters( + 'brizy_get_layouts', $layoutManager->createResponseForEntities($layouts, $fields), $fields, - $layoutManager); + $layoutManager + ); $this->success($layouts); } catch (Exception $exception) { @@ -191,17 +192,13 @@ public function actionCreateLayout() $layout->setMeta(stripslashes($this->param('meta'))); $layout->set_editor_data($editorData); $layout->set_needs_compile(true); - if ($this->param('title')) { $layout->setTitle(stripslashes($this->param('title'))); } if ($this->param('tags')) { $layout->setTags(stripslashes($this->param('tags'))); - } - - - //$layout->setCloudUpdateRequired( true ); + }//$layout->setCloudUpdateRequired( true ); $layout->setDataVersion(1); $layout->save(); From 5d94065fecc9039c919df653ce0d46d4d12bc437 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Wed, 1 Dec 2021 14:34:31 +0200 Subject: [PATCH 02/44] new: html changes in page.html.twig issue: #16367 --- public/views/page.php | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/public/views/page.php b/public/views/page.php index 4ad96ad637..8df40b2501 100755 --- a/public/views/page.php +++ b/public/views/page.php @@ -10,7 +10,7 @@ - +
@@ -18,7 +18,11 @@

Your theme must use the the_content filter in order for Brizy to work

- +
+ +
+
+ From 6c1312229c4ff3094817e963a63d1416bcc22dfe Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Wed, 1 Dec 2021 11:45:24 +0200 Subject: [PATCH 03/44] new: Added title and tags for block/layouts/popups --- admin/blocks/api.php | 19 +- admin/layouts/api.php | 18 +- editor/entity.php | 614 +++++++++++++++++++--------------------- editor/popup.php | 2 +- editor/post.php | 37 +-- editor/zip/archiver.php | 1 + 6 files changed, 342 insertions(+), 349 deletions(-) diff --git a/admin/blocks/api.php b/admin/blocks/api.php index 18c74e3cef..cc3a35f2c6 100644 --- a/admin/blocks/api.php +++ b/admin/blocks/api.php @@ -236,14 +236,16 @@ public function actionCreateGlobalBlock() } $bockManager = new Brizy_Admin_Blocks_Manager(Brizy_Admin_Blocks_Main::CP_GLOBAL); - /** + + /** * @var Brizy_Editor_Post $block; - */$block = $bockManager->createEntity($this->param('uid'), $status); + */ + $block = $bockManager->createEntity($this->param('uid'), $status); $block->setMeta(stripslashes($this->param('meta'))); $block->set_editor_data($editorData); $block->set_needs_compile(true); - if($this->param('title')) + if($this->param('title')) { $block->setTitle(stripslashes($this->param('title'))); } @@ -251,7 +253,9 @@ public function actionCreateGlobalBlock() if($this->param('tags')) { $block->setTags(stripslashes($this->param('tags'))); - }if ($position) { + } + + if ($position) { $block->setPosition( Brizy_Editor_BlockPosition::createFromSerializedData(get_object_vars(json_decode($position))) ); @@ -548,6 +552,7 @@ public function actionCreateSavedBlock() $block = $bockManager->createEntity($this->param('uid')); $block->setMedia(stripslashes($this->param('media'))); $block->setMeta(stripslashes($this->param('meta'))); + if($this->param('title')) { $block->setTitle(stripslashes($this->param('title'))); @@ -555,7 +560,9 @@ public function actionCreateSavedBlock() if($this->param('tags')) { $block->setTags(stripslashes($this->param('tags'))); - }$block->set_editor_data(stripslashes($this->param('data'))); + } + + $block->set_editor_data(stripslashes($this->param('data'))); $block->set_needs_compile(true); //$block->setCloudUpdateRequired( true ); $block->save(); @@ -615,7 +622,7 @@ public function actionUpdateSavedBlock() } - if ((int)$this->param('is_autosave')) { + if ((int)$this->param('is_autosave')) { $block->save(1); } else { $block->save(); diff --git a/admin/layouts/api.php b/admin/layouts/api.php index 7aac51c123..7a2ef8b705 100644 --- a/admin/layouts/api.php +++ b/admin/layouts/api.php @@ -192,13 +192,19 @@ public function actionCreateLayout() $layout->setMeta(stripslashes($this->param('meta'))); $layout->set_editor_data($editorData); $layout->set_needs_compile(true); - if ($this->param('title')) { - $layout->setTitle(stripslashes($this->param('title'))); - } - if ($this->param('tags')) { - $layout->setTags(stripslashes($this->param('tags'))); - }//$layout->setCloudUpdateRequired( true ); + if($this->param('title')) + { + $layout->setTitle(stripslashes($this->param('title'))); + } + + if($this->param('tags')) + { + $layout->setTags(stripslashes($this->param('tags'))); + } + + + //$layout->setCloudUpdateRequired( true ); $layout->setDataVersion(1); $layout->save(); diff --git a/editor/entity.php b/editor/entity.php index 3ab01fe3a4..1347b8f516 100644 --- a/editor/entity.php +++ b/editor/entity.php @@ -1,85 +1,80 @@ setWpPostId($postId); + $this->setWpPostId( $postId ); - $this->loadInstanceData(); - } + $this->loadInstanceData(); + } /** * @return bool */ public function can_edit_posts() - { - return current_user_can('edit_posts'); - } + {return current_user_can( 'edit_posts' ); + } /** - * @return bool - */ - static public function canEditPosts() - { - return current_user_can('edit_posts'); - } + * @return bool + */ + static public function canEditPosts() { + return current_user_can( 'edit_posts' ); + } - static public function get($postId, $uid = null) - { - $type = get_post_type($postId); + static public function get( $postId, $uid = null ) { + $type = get_post_type( $postId ); - switch ($type) { + switch ( $type ) { - case Brizy_Admin_Blocks_Main::CP_GLOBAL: - case Brizy_Admin_Blocks_Main::CP_SAVED: - return Brizy_Editor_Block::get($postId, $uid); + case Brizy_Admin_Blocks_Main::CP_GLOBAL: + case Brizy_Admin_Blocks_Main::CP_SAVED: + return Brizy_Editor_Block::get( $postId, $uid ); - default: - case 'page': - case 'post': - case Brizy_Admin_Popups_Main::CP_POPUP: - return Brizy_Editor_Post::get($postId, $uid); - } - } + default: + case 'page': + case 'post': + case Brizy_Admin_Popups_Main::CP_POPUP: + return Brizy_Editor_Post::get( $postId, $uid ); + } + } /** @@ -87,20 +82,20 @@ static public function get($postId, $uid = null) */ public function uses_editor() { - return self::isBrizyEnabled($this->getWpPostId()); + return self::isBrizyEnabled( $this->getWpPostId() ); } /** * @return bool */ - static public function isBrizyEnabled($post) + static public function isBrizyEnabled( $post ) { - if ($post instanceof WP_Post) { - $post = $post->ID; - } + if ( $post instanceof WP_Post ) { + $post = $post->ID; + } - return (bool)get_post_meta($post, Brizy_Editor_Constants::BRIZY_ENABLED, true); + return (bool) get_post_meta( $post, Brizy_Editor_Constants::BRIZY_ENABLED, true ); } /** @@ -110,33 +105,32 @@ static public function isBrizyEnabled($post) * @throws Brizy_Editor_Exceptions_AccessDenied */ public function set_uses_editor($value) - { - self::setBrizyEnabled($this->getWpPostId(), $value); + {self::setBrizyEnabled( $this->getWpPostId(), $value ); - return $this; - } + return $this; + } /** * @return bool */ - static public function setBrizyEnabled($post, $value) + static public function setBrizyEnabled( $post, $value ) { if (!self::canEditPosts()) { throw new Brizy_Editor_Exceptions_AccessDenied('Current user cannot edit page'); } - if ($post instanceof WP_Post) { - $post = $post->ID; - } + if ( $post instanceof WP_Post ) { + $post = $post->ID; + } - update_post_meta($post, Brizy_Editor_Constants::BRIZY_ENABLED, (int)$value); + update_post_meta( $post, Brizy_Editor_Constants::BRIZY_ENABLED, (int) $value ); } /** * @return string */ - static public function getEditUrl($post) + static public function getEditUrl( $post ) { if ($post instanceof WP_Post) { @@ -156,250 +150,234 @@ static public function getEditUrl($post) ); } - /** - * @param $postId - * - * @return Brizy_Editor_Block|Brizy_Editor_Post|mixed - * @throws Exception - */ - public function duplicateTo($postId) - { - // check post types - if (get_post_type($postId) !== $this->getWpPost()->post_type) { - throw new Exception('Cannot duplicate post. Invalid target post type'); - } - - if (!$this->uses_editor()) { - throw new Exception('The source post is not using Brizy.'); - } - - // copy current date the the new post - $newPost = self::get($postId); - - if ($newPost->uses_editor()) { - throw new Exception('Target post is using Brizy.'); - } - - $newPost->set_needs_compile(true); - $newPost->set_uses_editor(true); - $newPost->setDataVersion(1); - $newPost->createUid(); - - return $newPost; - } - - - /** - * Will return the key on witch the object data will be saved in storage - * - * @return mixed - */ - abstract protected function getObjectKey(); - - /** - * Load all object data - */ - abstract protected function loadInstanceData(); - - /** - * @return mixed - */ - abstract public function createResponse($fields = array()); - - /** - * Save post data and and trigger post update - * - * @return mixed - */ - abstract public function savePost(); - - /** - * This will save ro create an autosave object the the data from entity - * Also before saving the data version will be checked - * - * @return $this - * @throws Exception - */ - public function save($autosave = 0) - { - - // check entity versions before saving. - if ((int)$autosave === 0) { - $this->saveDataVersion(); - } - - $this->createUid(); - - return $this; - } - - /** - * This will take all values from entity and save them to database - */ - public function saveStorage() - { - $value = $this->convertToOptionValue(); - $this->getStorage()->set($this->getObjectKey(), $value); - } - - - /** - * @return Brizy_Editor_Post[] - * @throws Brizy_Editor_Exceptions_NotFound - * @throws Brizy_Editor_Exceptions_UnsupportedPostType - */ - public static function get_all_brizy_post_ids() - { - global $wpdb; - $posts = $wpdb->get_results( - $wpdb->prepare( - "SELECT p.ID FROM {$wpdb->postmeta} pm + /** + * @param $postId + * + * @return Brizy_Editor_Block|Brizy_Editor_Post|mixed + * @throws Exception + */ + public function duplicateTo( $postId ) { + // check post types + if ( get_post_type( $postId ) !== $this->getWpPost()->post_type ) { + throw new Exception( 'Cannot duplicate post. Invalid target post type' ); + } + + if (!$this->uses_editor() ) { + throw new Exception( 'The source post is not using Brizy.' ); + } + + // copy current date the the new post + $newPost = self::get( $postId ); + + if ( $newPost->uses_editor() ) { + throw new Exception( 'Target post is using Brizy.' ); + } + + $newPost->set_needs_compile( true ); + $newPost->set_uses_editor( true ); + $newPost->setDataVersion( 1 ); + $newPost->createUid(); + + return $newPost; + } + + + /** + * Will return the key on witch the object data will be saved in storage + * + * @return mixed + */ + abstract protected function getObjectKey(); + + /** + * Load all object data + */ + abstract protected function loadInstanceData(); + + /** + * @return mixed + */ + abstract public function createResponse( $fields = array() ); + + /** + * Save post data and and trigger post update + * + * @return mixed + */ + abstract public function savePost(); + + /** + * This will save ro create an autosave object the the data from entity + * Also before saving the data version will be checked + * + * @return $this + * @throws Exception + */ + public function save( $autosave = 0 ) { + + // check entity versions before saving. + if ( (int) $autosave === 0 ) { + $this->saveDataVersion(); + } + + $this->createUid(); + + return $this; + } + + /** + * This will take all values from entity and save them to database + */ + public function saveStorage() { + $value = $this->convertToOptionValue(); + $this->getStorage()->set( $this->getObjectKey(), $value ); + } + + + /** + * @return Brizy_Editor_Post[] + * @throws Brizy_Editor_Exceptions_NotFound + * @throws Brizy_Editor_Exceptions_UnsupportedPostType + */ + public static function get_all_brizy_post_ids() { + global $wpdb; + $posts = $wpdb->get_results( + $wpdb->prepare( + "SELECT p.ID FROM {$wpdb->postmeta} pm JOIN {$wpdb->posts} p ON p.ID=pm.post_id and p.post_type <> 'revision' and p.post_type<>'attachment' and p.post_status='publish' WHERE pm.meta_key = %s ", - Brizy_Editor_Storage_Post::META_KEY - ), ARRAY_A - ); - - return array_column($posts, 'ID'); - } - - /** - * @return int - */ - public function getWpPostId() - { - return $this->wp_post_id; - } - - /** - * @param int $wp_post_id - * - * @return Brizy_Editor_Entity - */ - public function setWpPostId($wp_post_id) - { - $this->wp_post_id = $wp_post_id; - - return $this; - } - - /** - * Return the post parent id - * - * @return int - */ - public function getWpPostParentId() - { - return $this->getWpPost()->post_parent ?: $this->getWpPostId(); - } - - /** - * @return WP_Post - */ - public function getWpPost() - { - return $this->wp_post ?: ($this->wp_post = get_post($this->getWpPostId())); - } - - /** - * @return $this - */ - protected function saveDataVersion() - { - $version = $this->getCurrentDataVersion(); - - if ($this->dataVersion !== $version + 1) { - Brizy_Logger::instance()->critical( - 'Unable to save entity. The data version is wrong.', - [ - 'post_id' => $this->getWpPostId(), - 'currentVersion' => $version, - 'newVersion' => $this->dataVersion, - ] - ); - throw new Brizy_Editor_Exceptions_DataVersionMismatch('Unable to save entity. The data version is wrong.'); - } - - update_post_meta($this->getWpPostId(), self::BRIZY_DATA_VERSION_KEY, $this->dataVersion); - - return $this; - } - - /** - * @return int - */ - public function getCurrentDataVersion() - { - return (int)(get_post_meta($this->getWpPostId(), self::BRIZY_DATA_VERSION_KEY, true) ?: 0); - } - - - /** - * @param $dataVersion - * - * @return $this - */ - public function setDataVersion($dataVersion) - { - $this->dataVersion = (int)$dataVersion; - - return $this; - } - - /** - * @return string - */ - public function getUid() - { - return $this->uid; - } - - public function getTitle() - { - return $this->getWpPost()->post_title; - } - - public function setTitle($title) - { - $this->getWpPost()->post_title = $title; - - return $this; - } - - /** - * Return an instance of Brizy_Editor_Storage_Abstract that will store the object data - * - * @return Brizy_Editor_Storage_Post - */ - protected function getStorage() - { - return Brizy_Editor_Storage_Post::instance($this->wp_post_id); - } - - /** - * @return mixed|string - */ - protected function createUid() - { - $WPPost = $this->getWpPost(); - $post_id = $WPPost->post_type != 'revision' ? $this->getWpPostId() : $WPPost->post_parent; - - if ($uid = $this->getUid()) { - $uid = get_post_meta($post_id, 'brizy_post_uid', true); - if (!$uid) { - update_post_meta($post_id, 'brizy_post_uid', $this->getUid()); - } - - return $uid; - } - - $uid = get_post_meta($post_id, 'brizy_post_uid', true); - - if (!$uid) { - $uid = md5($post_id . time()); - update_post_meta($post_id, 'brizy_post_uid', $uid); - } - - return $this->uid = $uid; - } + Brizy_Editor_Storage_Post::META_KEY + ), ARRAY_A + ); + + return array_column( $posts, 'ID' ); + } + + /** + * @return int + */ + public function getWpPostId() { + return $this->wp_post_id; + } + + /** + * @param int $wp_post_id + * + * @return Brizy_Editor_Entity + */ + public function setWpPostId( $wp_post_id ) { + $this->wp_post_id = $wp_post_id; + + return $this; + } + + /** + * Return the post parent id + * + * @return int + */ + public function getWpPostParentId() { + return $this->getWpPost()->post_parent ?: $this->getWpPostId(); + } + + /** + * @return WP_Post + */ + public function getWpPost() { + return $this->wp_post ?: ( $this->wp_post = get_post( $this->getWpPostId() ) ); + } + + /** + * @return $this + */ + protected function saveDataVersion() { + $version = $this->getCurrentDataVersion(); + + if ( $this->dataVersion !== $version + 1 ) { + Brizy_Logger::instance()->critical( + 'Unable to save entity. The data version is wrong.', + [ + 'post_id' => $this->getWpPostId(), + 'currentVersion' => $version, + 'newVersion' => $this->dataVersion, + ] + ); + throw new Brizy_Editor_Exceptions_DataVersionMismatch( 'Unable to save entity. The data version is wrong.' ); + } + + update_post_meta( $this->getWpPostId(), self::BRIZY_DATA_VERSION_KEY, $this->dataVersion ); + + return $this; + } + + /** + * @return int + */ + public function getCurrentDataVersion() { + return (int) ( get_post_meta( $this->getWpPostId(), self::BRIZY_DATA_VERSION_KEY, true ) ?: 0 ); + } + + + /** + * @param $dataVersion + * + * @return $this + */ + public function setDataVersion( $dataVersion ) { + $this->dataVersion = (int) $dataVersion; + + return $this; + } + + /** + * @return string + */ + public function getUid() { + return $this->uid; + } + + public function getTitle() { + return $this->getWpPost()->post_title; + } + + public function setTitle( $title ) { + $this->getWpPost()->post_title = $title; + + return $this; + } + + /** + * Return an instance of Brizy_Editor_Storage_Abstract that will store the object data + * + * @return Brizy_Editor_Storage_Post + */ + protected function getStorage() { + return Brizy_Editor_Storage_Post::instance( $this->wp_post_id ); + } + + /** + * @return mixed|string + */ + protected function createUid() { + $WPPost = $this->getWpPost(); + $post_id = $WPPost->post_type != 'revision' ? $this->getWpPostId() : $WPPost->post_parent; + + if ( $uid = $this->getUid() ) { + $uid = get_post_meta( $post_id, 'brizy_post_uid', true ); + if (!$uid ) { + update_post_meta( $post_id, 'brizy_post_uid', $this->getUid() ); + } + + return $uid; + } + + $uid = get_post_meta( $post_id, 'brizy_post_uid', true ); + + if (!$uid ) { + $uid = md5( $post_id . time() ); + update_post_meta( $post_id, 'brizy_post_uid', $uid ); + } + + return $this->uid = $uid; + } } diff --git a/editor/popup.php b/editor/popup.php index a4c8af387d..c49ea1aaa9 100644 --- a/editor/popup.php +++ b/editor/popup.php @@ -1,4 +1,4 @@ - $this->getWpPostId(), - 'post_title' => $this->getTitle(), - 'post_content' => $this->getPostContent($createRevision) + 'post_title' => $this->getTitle(), + 'post_content' => $this->getPostContent($createRevision) ]; $this->deleteOldAutosaves($this->getWpPostId()); @@ -762,14 +762,14 @@ protected function loadInstanceData() //$storageData = $storage->get_storage(); $storage_post = $storage->get($this->getObjectKey(), false); - $this->setTitle(get_the_title($this->getWpPostId())); + $this->setTitle( get_the_title( $this->getWpPostId() ) ); - // check for deprecated forms of posts - if ($storage_post instanceof self) { - $this->set_editor_data($storage_post->editor_data); - $this->set_needs_compile(true); - $this->save(); - } else if (is_array($storage_post)) { + // check for deprecated forms of posts + if ( $storage_post instanceof self ) { + $this->set_editor_data( $storage_post->editor_data ); + $this->set_needs_compile( true ); + $this->save(); + } else if ( is_array( $storage_post ) ) { if (isset($storage_post['compiled_html'])) { $this->set_encoded_compiled_html($storage_post['compiled_html']); @@ -802,7 +802,8 @@ protected function loadInstanceData() protected function populateAutoSavedData($autosave) { $autosave->setTitle($this->getTitle()); - $autosave->set_template($this->get_template()); + $autosave->setTitle( $this->getTitle() ); + $autosave->set_template($this->get_template()); $autosave->set_editor_data($this->get_editor_data()); $autosave->set_editor_version($this->get_editor_version()); $autosave->set_needs_compile(true); diff --git a/editor/zip/archiver.php b/editor/zip/archiver.php index 992376bbe3..0ff17fe9ad 100644 --- a/editor/zip/archiver.php +++ b/editor/zip/archiver.php @@ -84,6 +84,7 @@ public function addEntityToZip(ZipArchive $z, Brizy_Editor_Zip_ArchiveItem $item $data = array( 'class' => get_class($block), 'title' => $block->getTitle(), + 'title' => $block->getTitle(), 'meta' => $block->getMeta(), 'media' => $block->getMedia(), 'data' => $block->get_editor_data(), From 67d442d4c35035cbc3191bc2c125371cd2e72970 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 6 Dec 2021 15:02:44 +0200 Subject: [PATCH 04/44] new: Added filter to be able to change the story rewrite slug --- admin/stories/main.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/admin/stories/main.php b/admin/stories/main.php index fdc9aa0929..db67a9bb1b 100644 --- a/admin/stories/main.php +++ b/admin/stories/main.php @@ -59,7 +59,7 @@ static public function registerCustomPosts() 'public' => true, 'description' => __bt( 'brizy', 'Brizy' ) . ' ' . __( 'stories', 'brizy' ) . '.', 'show_in_menu' => Brizy_Admin_Settings::menu_slug(), - 'rewrite' => [ 'slug' => self::CP_STORY ], + 'rewrite' => [ 'slug' => apply_filters('brizy_story_rewrite_slug',self::CP_STORY) ], 'capability_type' => 'page', 'exclude_from_search' => true, 'supports' => [ 'title', 'post_content', 'revisions' ], From de25d6a1ea260901cd5125601a5e281f9683e3b1 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Tue, 7 Dec 2021 11:18:15 +0200 Subject: [PATCH 05/44] fix: decode the htmlentity encoded title and tags --- editor/entity.php | 2 +- editor/post-tags-aware.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/editor/entity.php b/editor/entity.php index 1347b8f516..726ddfe320 100644 --- a/editor/entity.php +++ b/editor/entity.php @@ -337,7 +337,7 @@ public function getUid() { } public function getTitle() { - return $this->getWpPost()->post_title; + return html_entity_decode($this->getWpPost()->post_title); } public function setTitle( $title ) { diff --git a/editor/post-tags-aware.php b/editor/post-tags-aware.php index df3fb7c5c9..cbcf390121 100644 --- a/editor/post-tags-aware.php +++ b/editor/post-tags-aware.php @@ -11,7 +11,7 @@ trait Brizy_Editor_PostTagsAware { * @return string */ public function getTags() { - return $this->tags; + return html_entity_decode($this->tags); } /** From ac42e111eaf75e3312155e2d59b72ee89fb95e0e Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Mon, 17 Jan 2022 11:14:10 +0200 Subject: [PATCH 06/44] new: Added ignore dc placeholder issue: #16516 --- content/placeholders/ignore-dc.php | 40 +++++++++++++++++++++++++++++ content/providers/free-provider.php | 1 + 2 files changed, 41 insertions(+) create mode 100644 content/placeholders/ignore-dc.php diff --git a/content/placeholders/ignore-dc.php b/content/placeholders/ignore-dc.php new file mode 100644 index 0000000000..64a1da7c31 --- /dev/null +++ b/content/placeholders/ignore-dc.php @@ -0,0 +1,40 @@ +setLabel($label); + $this->setPlaceholder('brizy_dc_ignore_dc'); + $this->setDisplay($display); + $this->setGroup($group); + } + + /** + * @param ContextInterface $context + * @param ContentPlaceholder $placeholder + * + * @return mixed + */ + public function getValue(ContextInterface $context, ContentPlaceholder $placeholder) + { + return $placeholder->getContent(); + } +} \ No newline at end of file diff --git a/content/providers/free-provider.php b/content/providers/free-provider.php index b4772096ec..5846627fb1 100644 --- a/content/providers/free-provider.php +++ b/content/providers/free-provider.php @@ -200,6 +200,7 @@ public function __construct() { $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_product_order_tracking', function () { return do_shortcode('[woocommerce_order_tracking]'); }) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_IgnoreDc('') ); $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple(__( 'WooCommerce Notices', 'brizy' ), 'editor_woo_notice', function () { return wc_print_notices( true ); From 0643f34a830a4fb01f6b16a1b0f13aaa36d55b88 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Wed, 19 Jan 2022 12:17:33 +0200 Subject: [PATCH 07/44] new: Added simple post aware and fixed few placeholders --- content/placeholders/simple-post-aware.php | 45 ++ content/providers/free-provider.php | 529 +++++++++------------ 2 files changed, 276 insertions(+), 298 deletions(-) create mode 100644 content/placeholders/simple-post-aware.php diff --git a/content/placeholders/simple-post-aware.php b/content/placeholders/simple-post-aware.php new file mode 100644 index 0000000000..0a4b38417a --- /dev/null +++ b/content/placeholders/simple-post-aware.php @@ -0,0 +1,45 @@ +getAttribute('post_id'); + + if ($postId) { + $newContext = Brizy_Content_ContextFactory::createContext( + $context->getProject(), + null, + get_post($postId), + null, + false + ); + + return parent::getValue($newContext, $contentPlaceholder); + } + + if ( ! $context->getWpPost()) { + return; + } + + return parent::getValue($context, $contentPlaceholder); + } + + /** + * @return mixed|string + */ + protected function getOptionValue() + { + return $this->getReplacePlaceholder(); + } +} \ No newline at end of file diff --git a/content/providers/free-provider.php b/content/providers/free-provider.php index 5846627fb1..b82614670e 100644 --- a/content/providers/free-provider.php +++ b/content/providers/free-provider.php @@ -3,359 +3,292 @@ use BrizyPlaceholders\ContentPlaceholder; use \BrizyPlaceholders\Registry; -class Brizy_Content_Providers_FreeProvider extends Brizy_Content_Providers_AbstractProvider -{ - public function __construct() { - - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'Internal Display Block By User Role', 'display_by_roles', function ( Brizy_Content_Context $context, ContentPlaceholder $contentPlaceholder ) { - - $attrs = $contentPlaceholder->getAttributes(); - - if ( ! empty( $attrs['roles'] ) ) { - $roles = explode( ',', $attrs['roles'] ); - $userRoles = (array) wp_get_current_user()->roles; - - if ( in_array( 'logged', $roles ) && is_user_logged_in() ) { - $userRoles[] = 'logged'; - } - - if ( Brizy_Editor_User::is_user_allowed() ) { - - if ( ! empty( $_GET['role'] ) ) { - - if ( $_GET['role'] === 'default' ) { - $roles[] = 'default'; - $userRoles[] = 'default'; - } else { - $userRoles = []; - - if ( $_GET['role'] == 'not_logged' ) { - - if ( in_array( 'not_logged', $roles ) ) { - $roles[] = 'default'; - $userRoles[] = 'default'; - } - } else { - $userRoles[] = $_GET['role']; - } - } - } - } - - if ( in_array( 'not_logged', $roles ) ) { +class Brizy_Content_Providers_FreeProvider extends Brizy_Content_Providers_AbstractProvider { + public function __construct() { + + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'Internal Display Block By User Role', 'display_by_roles', function ( Brizy_Content_Context $context, ContentPlaceholder $contentPlaceholder ) { + + $attrs = $contentPlaceholder->getAttributes(); + + if ( ! empty( $attrs['roles'] ) ) { + $roles = explode( ',', $attrs['roles'] ); + $userRoles = (array) wp_get_current_user()->roles; + + if ( in_array( 'logged', $roles ) && is_user_logged_in() ) { + $userRoles[] = 'logged'; + } + + if ( Brizy_Editor_User::is_user_allowed() ) { + + if ( ! empty( $_GET['role'] ) ) { + + if ( $_GET['role'] === 'default' ) { + $roles[] = 'default'; + $userRoles[] = 'default'; + } else { + $userRoles = []; + + if ( $_GET['role'] == 'not_logged' ) { + + if ( in_array( 'not_logged', $roles ) ) { + $roles[] = 'default'; + $userRoles[] = 'default'; + } + } else { + $userRoles[] = $_GET['role']; + } + } + } + } + + if ( in_array( 'not_logged', $roles ) ) { + + $roles = array_diff( $roles, [ 'not_logged' ] ); + + if ( is_user_logged_in() ) { + if ( ! array_intersect( $roles, $userRoles ) ) { + return ''; + } + } + } else { + if ( ! array_intersect( $roles, $userRoles ) ) { + return ''; + } + } + } + + $replacer = new \BrizyPlaceholders\Replacer( $context->getProvider() ); + + return $replacer->replacePlaceholders( $contentPlaceholder->getContent(), $context ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_ImageTitleAttribute( 'Internal Title Attributes', 'brizy_dc_image_title' ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_ImageAltAttribute( 'Internal Alt Attributes', 'brizy_dc_image_alt' ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_UniquePageUrl( 'Uniquer page url', 'brizy_dc_current_page_unique_url' ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'WP Language', 'brizy_dc_page_language', get_locale() ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'Ajax Url', 'brizy_dc_ajax_url', admin_url( 'admin-ajax.php' ) ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_SimplePostAware('Permalink', 'brizy_dc_permalink',function ( $context, $contentPlaceholder ) { + return get_permalink( (int)$context->getWpPost()->ID ); + }) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_sidebar', function ( $context, $contentPlaceholder ) { - $roles = array_diff( $roles, [ 'not_logged' ] ); + $attrs = $contentPlaceholder->getAttributes(); - if ( is_user_logged_in() ) { - if ( ! array_intersect( $roles, $userRoles ) ) { - return ''; - } - } - } else { - if ( ! array_intersect( $roles, $userRoles ) ) { - return ''; - } - } - } + $id = isset( $attrs['id'] ) ? $attrs['id'] : null; - $replacer = new \BrizyPlaceholders\Replacer( $context->getProvider() ); + if ( $id ) { + ob_start(); - return $replacer->replacePlaceholders( $contentPlaceholder->getContent(), $context ); - } ) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_ImageTitleAttribute('Internal Title Attributes', 'brizy_dc_image_title') ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_ImageAltAttribute('Internal Alt Attributes', 'brizy_dc_image_alt') ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_UniquePageUrl('Uniquer page url', 'brizy_dc_current_page_unique_url') ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('WP Language', 'brizy_dc_page_language', get_locale()) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('Ajax Url', 'brizy_dc_ajax_url', admin_url('admin-ajax.php')) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Permalink() ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_sidebar', function ($context, $contentPlaceholder) { + dynamic_sidebar( $id ); - $attrs = $contentPlaceholder->getAttributes(); + return ob_get_clean(); + } - $id = isset($attrs['id']) ? $attrs['id'] : null; + return ''; + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_navigation', function ( $context, $contentPlaceholder ) { - if ($id) { - ob_start(); + $attrs = $contentPlaceholder->getAttributes(); - dynamic_sidebar($id); + return $attrs['name'] ? wp_nav_menu( array( 'menu' => $attrs['name'], 'echo' => false ) ) : ''; + } ) ); - return ob_get_clean(); - } + $this->registerPlaceholder( new Brizy_Content_Placeholders_SimplePostAware( '', 'editor_post_field', function ( $context, $contentPlaceholder ) { - return ''; - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_navigation', function ($context, $contentPlaceholder) { + $attrs = $contentPlaceholder->getAttributes(); - $attrs = $contentPlaceholder->getAttributes(); + $post = $context->getWpPost(); - return $attrs['name'] ? wp_nav_menu(array('menu' => $attrs['name'], 'echo' => false)) : ''; - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_post_field', function ($context, $contentPlaceholder) { + if ( ! $post || ! isset( $attrs['property'] ) ) { + return ''; + } - $attrs = $contentPlaceholder->getAttributes(); + return $this->filterData( $attrs['property'], $post ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_post_info', function ( $context, $contentPlaceholder ) { - $post = ($context = Brizy_Content_ContextFactory::getGlobalContext()) ? $context->getWpPost() : get_post(); + $post = $context->getWpPost(); - if (!$post || !isset($attrs['property'])) { - return ''; - } - - return $this->filterData($attrs['property'], $post); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_post_info', function () { + if ( $post ) { + $commentsCount = get_approved_comments( $post->ID, [ 'count' => true ] ); + $params = []; - $post = ($context = Brizy_Content_ContextFactory::getGlobalContext()) ? $context->getWpPost() : get_post(); + $params['author'] = get_the_author_meta( 'display_name', $post->post_author ); + $params['date'] = get_the_date( '', $post ); + $params['time'] = get_the_time( '', $post ); + $params['comments'] = sprintf( _n( '%s comment', '%s comments', $commentsCount, 'brizy' ), number_format_i18n( $commentsCount ) ); - if ( $post ) { - $commentsCount = get_approved_comments( $post->ID, [ 'count' => true ] ); - $params = []; - $params['author'] = get_the_author_meta( 'display_name', $post->post_author ); - $params['date'] = get_the_date( '', $post ); - $params['time'] = get_the_time( '', $post ); - $params['comments'] = sprintf( _n( '%s comment', '%s comments', $commentsCount, 'brizy' ), number_format_i18n( $commentsCount ) ); + return Brizy_Editor_View::get( BRIZY_PLUGIN_PATH . '/public/views/post-info', $params ); + } - return Brizy_Editor_View::get( BRIZY_PLUGIN_PATH . '/public/views/post-info', $params ); - } + return ''; + } ) ); - return ''; - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_posts', function ($context, $contentPlaceholder) { + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_posts', function ( $context, $contentPlaceholder ) { - $atts = $contentPlaceholder->getAttributes(); + $atts = $contentPlaceholder->getAttributes(); - // shortcode to use in page: {{editor_posts posts_per_page="5" category="1,2" orderby="date" order="DESC" columns="1" display_date="1" display_author="1"}} + // shortcode to use in page: {{editor_posts posts_per_page="5" category="1,2" orderby="date" order="DESC" columns="1" display_date="1" display_author="1"}} - // this array is used as default values for displayPosts - $extra_atts = array( - "columns" => 1, - "display_date" => 1, - "display_author" => 1, - ); + // this array is used as default values for displayPosts + $extra_atts = array( + "columns" => 1, + "display_date" => 1, + "display_author" => 1, + ); - $extra_atts = array_merge($extra_atts, $atts); + $extra_atts = array_merge( $extra_atts, $atts ); - $posts = $this->getPosts($atts); + $posts = $this->getPosts( $atts ); - return $this->displayPosts($posts, $extra_atts); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('Product Page', 'editor_product_page', function ($context, $contentPlaceholder) { + return $this->displayPosts( $posts, $extra_atts ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'Product Page', 'editor_product_page', function ( $context, $contentPlaceholder ) { - $atts = $contentPlaceholder->getAttributes(); + $atts = $contentPlaceholder->getAttributes(); // if ( ! empty( $atts['id'] ) ) { // $product_data = get_post( $atts['id'] ); // $product = ! empty( $product_data ) && in_array( $product_data->post_type, [ 'product', 'product_variation' ] ) ? wc_setup_product_data( $product_data ) : false; // } - if (empty($atts['id']) && current_user_can('manage_options')) { - return __('Please set a valid product', 'brizy'); - } - - $this->setScriptDependency('brizy-preview', ['zoom', 'photoswipe', 'flexslider', 'wc-single-product']); - - // Avoid infinite loop. There's a call of the function the_content() in the woocommerce/single-product/tabs/description.php - remove_filter('the_content', [Brizy_Admin_Templates::instance(), 'filterPageContent'], -12000); - - $html = do_shortcode('[product_page id="' . $atts['id'] . '"]'); - - add_filter('the_content', [Brizy_Admin_Templates::instance(), 'filterPageContent'], -12000); - - return $html; - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('Products Page', 'editor_product_products', function ($context, $contentPlaceholder) { - - $atts = $contentPlaceholder->getAttributes(); - - $shortcodeAttributes = []; - - if (isset($atts['limit'])) { - $shortcodeAttributes[] = sprintf("limit=\"%d\"", (int)$atts['limit']); - } - if (isset($atts['columns'])) { - $shortcodeAttributes[] = sprintf("columns=\"%d\"", (int)$atts['columns']); - } - if (isset($atts['category'])) { - $shortcodeAttributes[] = sprintf("category=\"%s\"", $atts['category']); - } - if (isset($atts['orderby'])) { - $shortcodeAttributes[] = sprintf("orderby=\"%s\"", $atts['orderby']); - } - if (isset($atts['order'])) { - $shortcodeAttributes[] = sprintf("order=\"%s\"", $atts['order']); - } - - $shortcodeAttributes = implode(' ', $shortcodeAttributes); - - return do_shortcode('[products ' . $shortcodeAttributes . ' ]'); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_product_default_cart', function () { - return do_shortcode('[woocommerce_cart]'); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_product_checkout', function () { - return do_shortcode('[woocommerce_checkout]'); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_product_my_account', function () { - return do_shortcode('[woocommerce_my_account]'); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple('', 'editor_product_order_tracking', function () { - return do_shortcode('[woocommerce_order_tracking]'); - }) ); - $this->registerPlaceholder( new Brizy_Content_Placeholders_IgnoreDc('') ); + if ( empty( $atts['id'] ) && current_user_can( 'manage_options' ) ) { + return __( 'Please set a valid product', 'brizy' ); + } + + $this->setScriptDependency( 'brizy-preview', [ 'zoom', 'photoswipe', 'flexslider', 'wc-single-product' ] ); + + // Avoid infinite loop. There's a call of the function the_content() in the woocommerce/single-product/tabs/description.php + remove_filter( 'the_content', [ Brizy_Admin_Templates::instance(), 'filterPageContent' ], - 12000 ); + + $html = do_shortcode( '[product_page id="' . $atts['id'] . '"]' ); + + add_filter( 'the_content', [ Brizy_Admin_Templates::instance(), 'filterPageContent' ], - 12000 ); + + return $html; + } ) ); + + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'Products Page', 'editor_product_products', function ( $context, $contentPlaceholder ) { + + $atts = $contentPlaceholder->getAttributes(); + + $shortcodeAttributes = []; + + if ( isset( $atts['limit'] ) ) { + $shortcodeAttributes[] = sprintf( "limit=\"%d\"", (int) $atts['limit'] ); + } + if ( isset( $atts['columns'] ) ) { + $shortcodeAttributes[] = sprintf( "columns=\"%d\"", (int) $atts['columns'] ); + } + if ( isset( $atts['category'] ) ) { + $shortcodeAttributes[] = sprintf( "category=\"%s\"", $atts['category'] ); + } + if ( isset( $atts['orderby'] ) ) { + $shortcodeAttributes[] = sprintf( "orderby=\"%s\"", $atts['orderby'] ); + } + if ( isset( $atts['order'] ) ) { + $shortcodeAttributes[] = sprintf( "order=\"%s\"", $atts['order'] ); + } + + $shortcodeAttributes = implode( ' ', $shortcodeAttributes ); + + return do_shortcode( '[products ' . $shortcodeAttributes . ' ]' ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_product_default_cart', function () { + return do_shortcode( '[woocommerce_cart]' ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_product_checkout', function () { + return do_shortcode( '[woocommerce_checkout]' ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_product_my_account', function () { + return do_shortcode( '[woocommerce_my_account]' ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( '', 'editor_product_order_tracking', function () { + return do_shortcode( '[woocommerce_order_tracking]' ); + } ) ); + $this->registerPlaceholder( new Brizy_Content_Placeholders_IgnoreDc('') ); $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple(__( 'WooCommerce Notices', 'brizy' ), 'editor_woo_notice', function () { return wc_print_notices( true ); }, self::CONFIG_KEY_TEXT ) ); } - private function filterData($property, $post) - { - switch ($property) { - case 'post_title': - return get_the_title($post); - case 'post_excerpt': - return get_the_excerpt($post); - case 'post_content': - return get_the_content($post); - case 'post_password': - return ''; - default: - return $post->{$property}; - } - } - - /** - * It rewrite the wodpress function wp_trim_excerpt. - * The only thing we do is exclude the appling of the hook the_content. - * Further information read the description of the function getValue of this class. - * - * @param string $text - * @param null $post - * - * @return string - */ - public static function wp_trim_excerpt($text = '', $post = null) - { - global $pages; - - // not sure why this is null (this happens on author pages.. maybe there are more) - // - if (is_null($pages)) - $pages = []; - - $raw_excerpt = $text; - if ('' == $text) { - - $post = get_post($post); - $text = get_the_content('', false, $post); - - - $text = strip_shortcodes($text); - $text = excerpt_remove_blocks($text); - - /** This filter is documented in wp-includes/post-template.php */ - $text = apply_filters('the_content', $text); - $text = str_replace(']]>', ']]>', $text); - - - /** - * Filters the number of words in an excerpt. - * - * @param int $number The number of words. Default 55. - * - * @since 2.7.0 - * - */ - $excerpt_length = apply_filters('excerpt_length', 55); - - /** - * Filters the string in the "more" link displayed after a trimmed excerpt. - * - * @param string $more_string The string shown within the more link. - * - * @since 2.9.0 - * - */ - $excerpt_more = apply_filters('excerpt_more', ' ' . '[…]'); - $text = wp_trim_words($text, $excerpt_length, $excerpt_more); - } - - /** - * Filters the trimmed excerpt string. - * - * @param string $text The trimmed text. - * @param string $raw_excerpt The text prior to trimming. - * - * @since 2.8.0 - * - */ - return apply_filters('wp_trim_excerpt', $text, $raw_excerpt); - } - - private function getPosts($atts) - { - // here are default posts arguments: https://codex.wordpress.org/Template_Tags/get_posts - // maybe here we need to change some attributes, unset or add something before make query - $posts = get_posts($atts); - - return $posts; - } - - private function displayPosts($posts, $extra_atts) - { - ob_start(); - - $thumbnail_size = ''; // possible sizes: thumbnail, medium, medium_large, large - if ((int)$extra_atts['columns'] > 1) { - $thumbnail_size = 'large'; - } - - foreach ($posts as $post) { ?> + private function filterData( $property, $post ) { + switch ( $property ) { + case 'post_title': + return get_the_title( $post ); + case 'post_excerpt': + return get_the_excerpt( $post ); + case 'post_content': + return get_the_content( $post ); + case 'post_password': + return ''; + default: + return $post->{$property}; + } + } + + private function getPosts( $atts ) { + // here are default posts arguments: https://codex.wordpress.org/Template_Tags/get_posts + // maybe here we need to change some attributes, unset or add something before make query + $posts = get_posts( $atts ); + + return $posts; + } + + private function displayPosts( $posts, $extra_atts ) { + ob_start(); + + $thumbnail_size = ''; // possible sizes: thumbnail, medium, medium_large, large + if ( (int) $extra_atts['columns'] > 1 ) { + $thumbnail_size = 'large'; + } + + foreach ( $posts as $post ) { ?> - post_excerpt)) { - // if !empty excerpt - return $post->post_excerpt; - } + private function getPostExcerpt( $post ) { + if ( ! empty( $post->post_excerpt ) ) { + // if !empty excerpt + return $post->post_excerpt; + } - $the_excerpt = strip_tags(strip_shortcodes($post->post_content)); // Strips tags and shortcodes - $excerpt_length = 50; // Sets excerpt length by word count, default in WP is 55 - $words = explode(' ', $the_excerpt, $excerpt_length + 1); + $the_excerpt = strip_tags( strip_shortcodes( $post->post_content ) ); // Strips tags and shortcodes + $excerpt_length = 50; // Sets excerpt length by word count, default in WP is 55 + $words = explode( ' ', $the_excerpt, $excerpt_length + 1 ); - if (count($words) > $excerpt_length) { - array_pop($words); - $the_excerpt = implode(' ', $words); // put in excerpt only the number of word that is set in $excerpt_length - } + if ( count( $words ) > $excerpt_length ) { + array_pop( $words ); + $the_excerpt = implode( ' ', $words ); // put in excerpt only the number of word that is set in $excerpt_length + } - return $the_excerpt; - } + return $the_excerpt; + } } From 5976d354d83315def69c83facba7dc9c6a520716 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Sat, 20 Feb 2021 11:57:59 +0200 Subject: [PATCH 08/44] Upodated editor build branch --- .github/.build-env | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/.build-env b/.github/.build-env index 8226cbc437..969f3ea23f 100644 --- a/.github/.build-env +++ b/.github/.build-env @@ -1,4 +1,4 @@ BUILD_ENVIRONMENT=develop FREE_BRANCH=develop PRO_BRANCH=develop -EDITOR_BRANCH=dev \ No newline at end of file +EDITOR_BRANCH=improved/docker From cb1a8987febdf31440586dd6bed3c02e4b5b95b7 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Sun, 21 Feb 2021 21:28:21 +0200 Subject: [PATCH 09/44] Added post action to delete the context folder --- .github/.build-env | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/.github/.build-env b/.github/.build-env index 969f3ea23f..a5e67b68d3 100644 --- a/.github/.build-env +++ b/.github/.build-env @@ -1,4 +1,4 @@ -BUILD_ENVIRONMENT=develop -FREE_BRANCH=develop -PRO_BRANCH=develop -EDITOR_BRANCH=improved/docker +BUILD_ENVIRONMENT=master +FREE_BRANCH=master +PRO_BRANCH=master +EDITOR_BRANCH=master From b34b8afb70eb46badb034dd63ba93ebba46fedb7 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Tue, 16 Mar 2021 11:54:58 +0200 Subject: [PATCH 10/44] feat: Added support for placeholders in Wordpress and SMTP form integration All fields are available as placeholders: Ex: {{field_label}} Also emails for all user except for subscribers: Ex {{email_[user_login]}}, {{email_[user_nicename]}} or {{email_[display_name]}} --- brizy.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/brizy.php b/brizy.php index d5679f154f..595bf0e1ff 100755 --- a/brizy.php +++ b/brizy.php @@ -17,7 +17,7 @@ $_SERVER['HTTPS'] = 'on'; } -define('BRIZY_DEVELOPMENT', false ); +define('BRIZY_DEVELOPMENT', true ); define('BRIZY_LOG', false ); define('BRIZY_VERSION', '2.4.26'); define('BRIZY_MINIMUM_PRO_VERSION', '2.4.15'); From 3b211493204f19595b30643061814b486eaa2417 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 10 Jun 2021 16:10:22 +0300 Subject: [PATCH 11/44] fix: Added additional data about the post in editor config. issue: #14426 --- editor/editor/editor.php | 85 +++++++++++++++++++++++++--------------- 1 file changed, 53 insertions(+), 32 deletions(-) diff --git a/editor/editor/editor.php b/editor/editor/editor.php index 1279b3d22a..5d73d7a3a7 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -7,10 +7,10 @@ class Brizy_Editor_Editor_Editor { const COMPILE_CONTEXT = 'compile'; const EDITOR_CONTEXT = 'editor'; - /** - * @var self - */ - static private $insance; + /** + * @var self + */ + static private $insance; /** * @var array @@ -99,7 +99,8 @@ public function getClientConfig( $editorConfig, $context ) { * @throws Exception */ public function config( $context = self::COMPILE_CONTEXT ) { - do_action( 'brizy_create_editor_config_before' ); + do_action( 'brizy_create_editor_config_before') + ; $cachePostId = ( $this->post ? $this->post->getWpPostId() : 0 ) . '_' . $context; if ( isset( self::$config[ $cachePostId ] ) ) { @@ -217,10 +218,10 @@ public function config( $context = self::COMPILE_CONTEXT ) { self::$config[ $cachePostId ] = apply_filters( 'brizy_editor_config', $config, $context ); - do_action( 'brizy_create_editor_config_after' ); + do_action( 'brizy_create_editor_config_after'); - return self::$config[ $cachePostId ]; - } + return self::$config[$cachePostId] ; + } private function addUIConfig( $config, $context ) { @@ -580,7 +581,26 @@ private function addGlobalBlocksData( $config ) { $postTermsByKeys[ $term->term_id ] = $term; } - $config['wp']['postTerms'] = $postTerms; + $config['wp']['post_terms'] = $postTerms; + $config['wp']['post_term_parents'] = array_diff_key($this->getAllParents($postTermsByKeys),$postTermsByKeys); + $config['wp']['post_author'] = (int)$this->post->getWpPost()->post_author; + return $config; + } + + private function addGlobalBlocksData($config) { + + $postTaxonomies = get_post_taxonomies($wp_post_id = (int)$config['wp']['page']); + $postTerms = []; + foreach ($postTaxonomies as $tax) { + $postTerms = array_merge($postTerms, wp_get_post_terms($wp_post_id, $tax)); + } + + $postTermsByKeys = []; + foreach ($postTerms as $term) { + $postTermsByKeys[$term->term_id] = $term; + } + + $config['wp']['postTerms'] = $postTerms; $config['wp']['postTermParents'] = array_diff_key( $this->getAllParents( $postTermsByKeys ), $postTermsByKeys ); $config['wp']['postAuthor'] = (int) $this->post->getWpPost()->post_author; @@ -1011,7 +1031,7 @@ private function addSocialAccounts( Brizy_Editor_Accounts_ServiceAccountManager } - private function fileUploadMaxSize() { + private function fileUploadMaxSize() { static $max_size = - 1; if ( $max_size < 0 ) { @@ -1044,7 +1064,8 @@ private function parseSize( $size ) { } - private function getOneArchiveLink( $args = '' ) { + + private function getOneArchiveLink($args = ''){ global $wpdb, $wp_locale; $defaults = array( @@ -1160,7 +1181,8 @@ private function getTexts() { return (object) $brizy_public_editor_build_texts::get_editor_texts(); } - private function addTemplateFields( $config, $is_template, $wp_post_id, $context ) { + private function addTemplateFields($config, $is_template, $wp_post_id, $context) + { $template_rules = []; if ( $is_template ) { @@ -1187,24 +1209,23 @@ private function getTemplateRuleMatches( $isTemplate, $wpPostId, $templateRules if ( $isTemplate ) { - foreach ( $templateRules as $rule ) { - /** - * @var Brizy_Admin_Rule $rule ; - */ - $ruleMatches[] = array( - 'type' => $rule->getType(), - 'group' => $rule->getAppliedFor(), - 'entityType' => $rule->getEntityType(), - 'values' => $rule->getEntityValues(), - ); - } - $ruleMatches[] = array( - 'type' => Brizy_Admin_Rule::TYPE_INCLUDE, - 'group' => Brizy_Admin_Rule::BRIZY_TEMPLATE, - 'entityType' => $this->post->getWpPost()->post_type, - 'values' => array( $wpPostId ), - ); - } else { + foreach ($templateRules as $rule) { + /** + * @var Brizy_Admin_Rule $rule ; + */ + $ruleMatches[] = array( + 'type' => $rule->getType(), + 'group' => $rule->getAppliedFor(), + 'entityType' => $rule->getEntityType(), + 'values' => $rule->getEntityValues(), + ); + } + $ruleMatches[] = array( + 'type' => Brizy_Admin_Rule::TYPE_INCLUDE, + 'group' => Brizy_Admin_Rule::BRIZY_TEMPLATE, + 'entityType' => $this->post->getWpPost()->post_type, + 'values' => array($wpPostId), + );} else { $ruleMatches[] = array( 'type' => Brizy_Admin_Rule::TYPE_INCLUDE, 'group' => Brizy_Admin_Rule::POSTS, @@ -1308,8 +1329,8 @@ public function getApiActions( $config = [], $context = null ) { $pref = Brizy_Editor::prefix(); $actions = array( - 'hash' => wp_create_nonce( Brizy_Editor_API::nonce ), - 'url' => set_url_scheme( admin_url( 'admin-ajax.php' ) ), + 'hash' => wp_create_nonce(Brizy_Editor_API::nonce), + 'url' => set_url_scheme(admin_url('admin-ajax.php')), 'heartBeat' => $pref . Brizy_Editor_API::AJAX_HEARTBEAT, 'takeOver' => $pref . Brizy_Editor_API::AJAX_TAKE_OVER, 'lockProject' => $pref . Brizy_Editor_API::AJAX_LOCK_PROJECT, From b08d62bbb0aad9f9d3ecabeb22caaa02381f158d Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Fri, 9 Oct 2020 11:08:40 +0300 Subject: [PATCH 12/44] feat: Filters for post loops For more details see #11810 --- admin/abstract-api.php | 10 +++- admin/main.php | 1 - compatibilities/polylang.php | 2 +- config.php | 36 ++++++++++++++ content/context-factory.php | 14 +++--- content/context.php | 77 ++++++++++++++++++++++++++++- content/main-processor.php | 18 +++++++ content/placeholder-extractor.php | 21 ++++++-- content/placeholder-provider.php | 4 +- content/placeholder-replacer.php | 27 +++++++--- content/providers/free-provider.php | 4 +- editor/api.php | 62 ++++++++++++----------- editor/filters/api.php | 17 +++++++ public/main.php | 1 + 14 files changed, 239 insertions(+), 55 deletions(-) create mode 100644 editor/filters/api.php diff --git a/admin/abstract-api.php b/admin/abstract-api.php index 76499875ec..952f007e69 100644 --- a/admin/abstract-api.php +++ b/admin/abstract-api.php @@ -38,6 +38,14 @@ protected function verifyNonce( $action ) { } } + protected function addAjaxAction($action,$callable) { + add_action( 'wp_ajax_' . Brizy_Editor::prefix($action), $callable ); + } + + protected function addNoPrivAjaxAction($action,$callable) { + add_action( 'wp_ajax_nopriv_' . Brizy_Editor::prefix($action), $callable ); + } + /** * @param int|string $name * @@ -65,4 +73,4 @@ protected function error( $code, $message ) { protected function success( $data ) { wp_send_json_success( $data ); } -} \ No newline at end of file +} diff --git a/admin/main.php b/admin/main.php index 6ac2f4ac90..d92fe018d0 100755 --- a/admin/main.php +++ b/admin/main.php @@ -490,7 +490,6 @@ private function enable_brizy_for_post( $p ) { wp_update_post( $p ); } do_action( 'brizy_before_enabled_for_post', $p ); - $post->enable_editor(); $post->set_template( Brizy_Config::BRIZY_BLANK_TEMPLATE_FILE_NAME ); $post->set_plugin_version( BRIZY_VERSION ); diff --git a/compatibilities/polylang.php b/compatibilities/polylang.php index 994286e533..345b7863a9 100644 --- a/compatibilities/polylang.php +++ b/compatibilities/polylang.php @@ -5,7 +5,7 @@ class Brizy_Compatibilities_Polylang { public function __construct() { - add_action( 'brizy_post_loop_args', [ $this, 'post_loop_args' ] ); + add_filter( 'brizy_post_loop_args', [ $this, 'post_loop_args' ] ); add_filter( 'pll_home_url_white_list', [ $this, 'home_url_white_list' ] ); } diff --git a/config.php b/config.php index af58fef2ec..fabea8603c 100755 --- a/config.php +++ b/config.php @@ -104,3 +104,39 @@ static public function getTermsOfServiceUrl() { return apply_filters( 'brizy_config_terms_of_service_url', self::TERMS_OF_SERVICE_URL ); } } + + +/* + * // input +{{ filter_option + type="input" + dataSource="manual" +}} + +// range +{{ filter_option + type="range" + dataSource="manual" +}} + +// radio +{{ filter_option + type="radio" + dataSource="manual|query" + matchQuery="entity=taxonomy&entityName=category&valueMatch[property]=name&valueMatch[value]=string&valueMatch[operation]=in|like|<|>|<=|>=|<>|=" +}} + +// checkboxes posts by property match +{{ filter_option + type="checkbox" + dataSource="manual|query" + matchQuery="entity=post&entityName=page&orderBy=name&order=ASC&valueMatch[property]=post_title&valueMatch[value]=Page&valueMatch[operation]=in|like|<|>|<=|>=|<>|=" +}} + +// checkboxes posts by meta match +{{ filter_option + type="checkbox" + dataSource="manual|query" + matchQuery="entity=post&entityName=page&valueMatch[meta]=metaName&valueMatch[value]=Page&valueMatch[operation]=in|like|<|>|<=|>=|<>|=" +}} +*/ diff --git a/content/context-factory.php b/content/context-factory.php index a8070924bf..1b31b8120a 100644 --- a/content/context-factory.php +++ b/content/context-factory.php @@ -17,16 +17,16 @@ class Brizy_Content_ContextFactory * * @return Brizy_Content_Context */ - static public function createContext($project = null, $wp_post = null, $isLoop = false) + static public function createContext($project = null, $wp_post = null, $parentContext = false) { - $context = self::getContext($project, $wp_post); + $context = new Brizy_Content_Context($project, null, $wp_post, null, $parentContext ); - if ($isLoop) { - return apply_filters('brizy_loop_context_create', $context, $wp_post); - } + if ($wp_post) { + $context->setAuthor( $wp_post->post_author ); + } - return apply_filters('brizy_context_create', $context, $wp_post); - } + return apply_filters( 'brizy_context_create', $context ); + } static public function createEmptyContext() { diff --git a/content/context.php b/content/context.php index 9295d24529..44b44daec1 100644 --- a/content/context.php +++ b/content/context.php @@ -5,7 +5,12 @@ class Brizy_Content_Context implements ContextInterface { - private $data = array(); + protected $data = array(); + + /** + * @var Brizy_Content_ContentPlaceholder[] + */ + protected $placeholders = []; /** * @param $name @@ -81,4 +86,72 @@ public function __construct($project = null, $wp_post = null) $this->setWpPost($wp_post); $this->setEntity($wp_post); } -} \ No newline at end of file + + /** + * @return array + */ + public function getPlaceholders() { + return $this->placeholders; + } + + /** + * @param array $placeholders + * + * @return Brizy_Content_Context + */ + public function setPlaceholders( array $placeholders ) { + $this->placeholders = $placeholders; + + return $this; + } + + /** + * @param $id + * + * @return Brizy_Content_ContentPlaceholder|null + */ + public function getPlaceholderById( $id ) { + + $results = $this->getPlaceholdersByAttrValue( 'id', $id ); + + return isset( $results[0] ) ? $results[0] : null; + } + + /** + * @param $key + * @param $value + * + * @return Brizy_Content_ContentPlaceholder|null + * @throws Exception + */ + public function getPlaceholdersByAttrValue( $key, $value ) { + + $results = []; + if ( isset( $this->placeholders ) ) { + foreach ( $this->placeholders as $placeholder ) { + if ( $placeholder->getAttr( $key ) === $value ) { + $results[] = $placeholder; + } + } + } + + return $results; + } + + /** + * @param $attributes + * @return Brizy_Content_ContentPlaceholder|null + */ + public function getPlaceholderByAttrValues( $attributes ) { + + if ( isset( $this->placeholders ) ) { + foreach ( $this->placeholders as $placeholder ) { + if ( count(array_intersect($placeholder->getAttributes(),$attributes))==count($attributes) ) { + return $placeholder; + } + } + } + + return null; + } +} diff --git a/content/main-processor.php b/content/main-processor.php index 1e2a04850c..25ef2d6ac7 100644 --- a/content/main-processor.php +++ b/content/main-processor.php @@ -28,6 +28,24 @@ public function __construct( Brizy_Content_Context $context ) { $this->processors[] = new Brizy_Editor_Asset_MediaProcessor(); $this->processors = apply_filters( 'brizy_content_processors', $this->processors, $context ); + + /* CODE BEFORE REBASE. + $urlBuilder = new Brizy_Editor_UrlBuilder( $context->getProject(), $context->getWpPost() ? $context->getWpPost()->ID : null ); + $asset_storage = new Brizy_Editor_Asset_AssetProxyStorage( $urlBuilder ); + $media_storage = new Brizy_Editor_Asset_MediaProxyStorage( $urlBuilder ); + + $this->processors[] = new Brizy_Editor_Asset_AssetProxyProcessor( $asset_storage ); + $this->processors[] = new Brizy_Editor_Asset_MediaAssetProcessor( $media_storage ); + $this->processors[] = new Brizy_Editor_Asset_SvgAssetProcessor( ); + + $this->processors = apply_filters( 'brizy_content_processors', $this->processors, $context ); + + array_unshift( $this->processors, + new Brizy_Editor_Asset_DomainProcessor(), + new Brizy_Content_ShortcodeToPlaceholderProcessor(), + new Brizy_Content_DynamicContentProcessor() + ); + */ } /** diff --git a/content/placeholder-extractor.php b/content/placeholder-extractor.php index 3528a6adf6..62c7d0fafb 100644 --- a/content/placeholder-extractor.php +++ b/content/placeholder-extractor.php @@ -27,7 +27,7 @@ public function __construct($provider) private static function getPlaceholderRegexExpression() { - return "/(?{{\s*(?.+?)(?(?:\s+)((?:\w+\s*=\s*(?:'|\"|\"|\')(?:.[^\"']*|)(?:'|\"|\"|\')\s*)*))?}}(?:(?.*?){{\s*end_(\g{placeholderName})\s*}})?)/ims";; + return "/(?{{\s*(?.+?)\s*(?(?:\s+)((?:\w+(?:\[(?:\w+)?\])?\s*=\s*(?:'|\"|\"|\')(?:.[^\"']*|)(?:'|\"|\"|\')\s*)*))?}}(?:(?.*?){{\s*end_(\g{placeholderName})\s*}})?)/ims"; } public static function stripPlaceholders($content) @@ -96,11 +96,24 @@ private function getPlaceholderAttributes($attributeString) $attrString = trim($attributeString); $attrMatches = array(); $attributes = array(); - preg_match_all("/(\w+)\s*=\s*(?'|\"|\"|\')(.*?)(\g{quote})/mi", $attrString, $attrMatches); + preg_match_all("/((?\w+)(?\[(?\w+)?\])?)\s*=\s*(?'|\"|\"|\')(?.*?)(\g{quote})/mi", $attrString, $attrMatches); if (isset($attrMatches[0]) && is_array($attrMatches[0])) { - foreach ($attrMatches[1] as $i => $name) { - $attributes[$name] = $attrMatches[3][$i]; + foreach ($attrMatches[0] as $i => $attStr) { + $attrName = $attrMatches['attr_name'][$i]; + $attrValue = urldecode($attrMatches['attr_value'][$i]); + $isArray = $attrMatches['array'][$i]!=''; + $arrayKey = $attrMatches['array_key'][$i]; + // check if the attribute is an array + if($isArray) + { + if($arrayKey) + $attributes[$attrName][$arrayKey] = $attrValue; + else + $attributes[$attrName][] = $attrValue; + } else { + $attributes[$attrName] = $attrValue; + } } } diff --git a/content/placeholder-provider.php b/content/placeholder-provider.php index 43d0fb8916..7e58bdc0f1 100644 --- a/content/placeholder-provider.php +++ b/content/placeholder-provider.php @@ -35,12 +35,12 @@ public function __construct($context = null) */ public function getPlaceholders() { - $out = array(); + if (self::$cache_all_placeholders) { return self::$cache_all_placeholders; } - + $out = []; foreach ($this->providers as $provider) { $out = array_merge($out, $provider->getPlaceholders()); } diff --git a/content/placeholder-replacer.php b/content/placeholder-replacer.php index 063f123f36..2c7b11ade9 100644 --- a/content/placeholder-replacer.php +++ b/content/placeholder-replacer.php @@ -19,9 +19,12 @@ class Brizy_Content_PlaceholderReplacer { * * @param $context * @param $placeholderProvider + * @param $extractor */ - public function __construct( $context, $placeholderProvider ) { + public function __construct( $context, $placeholderProvider, $extractor ) { + $this->context = $context; $this->placeholderProvider = $placeholderProvider; + $this->placeholderExtractor = $extractor; } /** @@ -31,37 +34,47 @@ public function __construct( $context, $placeholderProvider ) { * * @return string|string[] */ - public function getContent( $placeholders, $content, $context= null) { + public function getContent( $content) { $toReplace = array(); $toReplaceWithValues = array(); + list( $placeholders, $acontent ) = $this->placeholderExtractor->extract( $content ); - if(!$context) + if(!$this->context) { - $context = Brizy_Content_ContextFactory::createEmptyContext(); + $this->context = Brizy_Content_ContextFactory::createEmptyContext(); } + // set the placeholders found at this level + $this->context->setPlaceholders($placeholders); + + if ( $placeholders ) { foreach ( $placeholders as $contentPlaceholder ) { try { $placeholder = $this->placeholderProvider->getPlaceholder( $contentPlaceholder->getName() ); if ( $placeholder ) { $toReplace[] = $contentPlaceholder->getUid(); - $toReplaceWithValues[] = $placeholder->getValue( $context , $contentPlaceholder ); + $toReplaceWithValues[] = $placeholder->getValue( $this->context , $contentPlaceholder ); } else { $toReplace[] = $contentPlaceholder->getPlaceholder(); $toReplaceWithValues[] = ''; } } catch ( Exception $e ) { + + if (defined('WP_DEBUG') && true === WP_DEBUG) { + var_dump($e); + } + continue; } } } - $content = str_replace( $toReplace, $toReplaceWithValues, $content ); + $acontent = str_replace( $toReplace, $toReplaceWithValues, $acontent ); - return $content; + return $acontent; } } diff --git a/content/providers/free-provider.php b/content/providers/free-provider.php index b82614670e..1e00a8005c 100644 --- a/content/providers/free-provider.php +++ b/content/providers/free-provider.php @@ -6,7 +6,9 @@ class Brizy_Content_Providers_FreeProvider extends Brizy_Content_Providers_AbstractProvider { public function __construct() { - $this->registerPlaceholder( new Brizy_Content_Placeholders_Simple( 'Internal Display Block By User Role', 'display_by_roles', function ( Brizy_Content_Context $context, ContentPlaceholder $contentPlaceholder ) { + $this->registerPlaceholder( + + new Brizy_Content_Placeholders_Simple( 'Internal Display Block By User Role', 'display_by_roles', function( Brizy_Content_Context $context, ContentPlaceholder $contentPlaceholder ) { $attrs = $contentPlaceholder->getAttributes(); diff --git a/editor/api.php b/editor/api.php index 58c99b4e02..f83011e53c 100755 --- a/editor/api.php +++ b/editor/api.php @@ -22,6 +22,7 @@ class Brizy_Editor_API extends Brizy_Admin_AbstractApi const AJAX_REMOVE_LOCK = '_remove_lock'; const AJAX_HEARTBEAT = '_heartbeat'; const AJAX_TAKE_OVER = '_take_over'; + const AJAX_DOWNLOAD_MEDIA = '_download_media'; const AJAX_JWT_TOKEN = '_multipass_create'; const AJAX_UPDATE_MENU_DATA = '_update_menu_data'; const AJAX_UPDATE_EDITOR_META_DATA = '_update_editor_meta_data'; @@ -71,34 +72,34 @@ protected function initializeApiActions() return; } - $p = 'wp_ajax_'.Brizy_Editor::prefix(); - add_action($p.self::AJAX_REMOVE_LOCK, array($this, 'removeProjectLock')); - add_action($p.self::AJAX_HEARTBEAT, array($this, 'heartbeat')); - add_action($p.self::AJAX_TAKE_OVER, array($this, 'takeOver')); - add_action($p.self::AJAX_GET, array($this, 'get_item')); - add_action($p.self::AJAX_GET_POST_INFO, array($this, 'get_post_info')); - add_action($p.self::AJAX_UPDATE, array($this, 'update_item')); - add_action($p.self::AJAX_GET_PROJECT, array($this, 'get_project')); - add_action($p.self::AJAX_SET_PROJECT, array($this, 'set_project')); - add_action($p.self::AJAX_LOCK_PROJECT, array($this, 'lock_project')); - add_action($p.self::AJAX_SIDEBARS, array($this, 'get_sidebars')); - add_action($p.self::AJAX_SHORTCODE_CONTENT, array($this, 'shortcode_content')); - add_action($p.self::AJAX_PLACEHOLDER_CONTENT, array($this, 'placeholder_content')); - add_action($p.self::AJAX_PLACEHOLDERS_CONTENT, array($this, 'placeholders_content')); - add_action($p.self::AJAX_GET_POST_OBJECTS, array($this, 'get_post_objects')); - add_action($p.self::AJAX_SEARCH_POST, array($this, 'search_post')); - add_action($p.self::AJAX_GET_MENU_LIST, array($this, 'get_menu_list')); - add_action($p.self::AJAX_GET_TERMS, array($this, 'get_terms')); - add_action($p.self::AJAX_GET_USERS, array($this, 'get_users')); - add_action($p.self::AJAX_GET_TERMS_BY, array($this, 'get_terms_by')); - add_action($p.self::AJAX_MEDIA_METAKEY, array($this, 'get_media_key')); - add_action($p.self::AJAX_CREATE_ATTACHMENT_UID, array($this, 'get_attachment_key')); - add_action($p.self::AJAX_SET_FEATURED_IMAGE, array($this, 'set_featured_image')); - add_action($p.self::AJAX_SET_IMAGE_FOCAL_PT, array($this, 'set_featured_image_focal_point')); - add_action($p.self::AJAX_TIMESTAMP, array($this, 'timestamp')); - add_action($p.self::AJAX_SET_TEMPLATE_TYPE, array($this, 'setTemplateType')); - add_action($p.self::AJAX_GET_POST_TAXONOMIES, array($this, 'addPostTaxonomies')); - add_action($p.'nopriv_'.Brizy_Editor::prefix(self::AJAX_TIMESTAMP), array($this, 'timestamp')); + + $this->addAjaxAction( self::AJAX_REMOVE_LOCK, array( $this, 'removeProjectLock' ) ); + $this->addAjaxAction( self::AJAX_HEARTBEAT, array( $this, 'heartbeat' ) ); + $this->addAjaxAction( self::AJAX_TAKE_OVER, array( $this, 'takeOver' ) ); + $this->addAjaxAction( self::AJAX_GET, array( $this, 'get_item' ) ); + $this->addAjaxAction( self::AJAX_GET_POST_INFO, array( $this, 'get_post_info' ) ); + $this->addAjaxAction( self::AJAX_UPDATE, array( $this, 'update_item' ) ); + $this->addAjaxAction( self::AJAX_GET_PROJECT, array( $this, 'get_project' ) ); + $this->addAjaxAction( self::AJAX_SET_PROJECT, array( $this, 'set_project' ) ); + $this->addAjaxAction( self::AJAX_LOCK_PROJECT, array( $this, 'lock_project' ) ); + $this->addAjaxAction( self::AJAX_SIDEBARS, array( $this, 'get_sidebars' ) ); + $this->addAjaxAction( self::AJAX_SHORTCODE_CONTENT, array( $this, 'shortcode_content' ) ); + $this->addAjaxAction( self::AJAX_PLACEHOLDER_CONTENT, array( $this, 'placeholder_content' ) ); + $this->addAjaxAction( self::AJAX_GET_POST_OBJECTS, array( $this, 'get_post_objects' ) ); + $this->addAjaxAction( self::AJAX_SEARCH_POST, array( $this, 'search_post' ) ); + $this->addAjaxAction( self::AJAX_GET_MENU_LIST, array( $this, 'get_menu_list' ) ); + $this->addAjaxAction( self::AJAX_GET_TERMS, array( $this, 'get_terms' ) ); + $this->addAjaxAction( self::AJAX_GET_USERS, array( $this, 'get_users' ) ); + $this->addAjaxAction( self::AJAX_GET_TERMS_BY, array( $this, 'get_terms_by' ) ); + $this->addAjaxAction( self::AJAX_DOWNLOAD_MEDIA, array( $this, 'download_media' ) ); + $this->addAjaxAction( self::AJAX_MEDIA_METAKEY, array( $this, 'get_media_key' ) ); + $this->addAjaxAction( self::AJAX_CREATE_ATTACHMENT_UID, array( $this, 'get_attachment_key' ) ); + $this->addAjaxAction( self::AJAX_SET_FEATURED_IMAGE, array( $this, 'set_featured_image' ) ); + $this->addAjaxAction( self::AJAX_SET_IMAGE_FOCAL_PT, array( $this, 'set_featured_image_focal_point' ) ); + $this->addAjaxAction( self::AJAX_TIMESTAMP, array( $this, 'timestamp' ) ); + $this->addAjaxAction( self::AJAX_SET_TEMPLATE_TYPE, array( $this, 'setTemplateType' ) ); + $this->addAjaxAction( self::AJAX_GET_POST_TAXONOMIES, array( $this, 'addPostTaxonomies' ) ); + $this->addNoPrivAjaxAction( Brizy_Editor::prefix( self::AJAX_TIMESTAMP ), array( $this, 'timestamp' ) ); } @@ -605,7 +606,10 @@ private function getPostSample($templateId) if (empty($values[0])) { // For All condition $posts = get_posts($args); - } else { + + } else { + + $filter = $values[0]; if (is_numeric($filter)) { diff --git a/editor/filters/api.php b/editor/filters/api.php new file mode 100644 index 0000000000..dd5dfdf2b5 --- /dev/null +++ b/editor/filters/api.php @@ -0,0 +1,17 @@ +addAjaxAction( self::AJAX_FILTER, array( $this, 'removeProjectLock' ) ); + } + + protected function getRequestNonce() { + return $this->param( 'hash' ); + } +} diff --git a/public/main.php b/public/main.php index f6c0d8bdb4..dd79c7a023 100755 --- a/public/main.php +++ b/public/main.php @@ -1,5 +1,6 @@ Date: Fri, 2 Apr 2021 10:40:06 +0300 Subject: [PATCH 13/44] .... --- brizy.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/brizy.php b/brizy.php index 595bf0e1ff..ce6d6dd568 100755 --- a/brizy.php +++ b/brizy.php @@ -132,4 +132,4 @@ function brizy_load_text_domain() load_plugin_textdomain('brizy', false, dirname(plugin_basename(__FILE__)) . '/languages'); } -new Brizy_Compatibilities_Init(); +new Brizy_Compatibilities_Init(); \ No newline at end of file From 85dd21e363e08ba61cefb3aa58326338dbe096ab Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Wed, 28 Apr 2021 15:09:46 +0300 Subject: [PATCH 14/44] ... --- content/context.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/content/context.php b/content/context.php index 44b44daec1..b52d9e8ef0 100644 --- a/content/context.php +++ b/content/context.php @@ -129,7 +129,7 @@ public function getPlaceholdersByAttrValue( $key, $value ) { $results = []; if ( isset( $this->placeholders ) ) { foreach ( $this->placeholders as $placeholder ) { - if ( $placeholder->getAttr( $key ) === $value ) { + if ( $placeholder->getAttr( $key ) == $value ) { $results[] = $placeholder; } } From 4c370c22fadd192412995f12e8b3ef739dd67fb9 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 29 Apr 2021 15:50:18 +0300 Subject: [PATCH 15/44] feat: added nested filters --- content/context.php | 2 ++ 1 file changed, 2 insertions(+) diff --git a/content/context.php b/content/context.php index b52d9e8ef0..b7edc5c780 100644 --- a/content/context.php +++ b/content/context.php @@ -126,6 +126,8 @@ public function getPlaceholderById( $id ) { */ public function getPlaceholdersByAttrValue( $key, $value ) { + if(is_null($value)) return null; + $results = []; if ( isset( $this->placeholders ) ) { foreach ( $this->placeholders as $placeholder ) { From fcab15ac733f286fec5e4692c6cea54b7994fa29 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 29 Jul 2021 14:52:15 +0300 Subject: [PATCH 16/44] fix: changes after rebase --- content/context.php | 52 ++++++++++++++++--------------- content/placeholder-replacer.php | 1 - content/placeholders/abstract.php | 2 +- 3 files changed, 28 insertions(+), 27 deletions(-) diff --git a/content/context.php b/content/context.php index b7edc5c780..b4ac31505a 100644 --- a/content/context.php +++ b/content/context.php @@ -1,5 +1,6 @@ data[$key] = $value; } - /** - * BrizyPro_Content_Context constructor. - * - * @param $project - * @param $wp_post - */ - public function __construct($project = null, $wp_post = null) - { - $this->setProject($project); - $this->setWpPost($wp_post); - $this->setEntity($wp_post); + /** + * BrizyPro_Content_Context constructor. + * + * @param $project + * @param $wp_post + */ + public function __construct($project, $brizy_post, $wp_post, $contentHtml, $parentContext = null ) { + $this->setProject( $project ); + $this->setWpPost( $wp_post ); + $this->setParentContext( $parentContext ); + $this->setEntity($wp_post); + } + + public function afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor) { + $this->setPlaceholders($contentPlaceholders); } /** @@ -105,11 +110,10 @@ public function setPlaceholders( array $placeholders ) { return $this; } - /** - * @param $id - * - * @return Brizy_Content_ContentPlaceholder|null - */ + /** + * @param $id + * @return mixed|null + */ public function getPlaceholderById( $id ) { $results = $this->getPlaceholdersByAttrValue( 'id', $id ); @@ -117,13 +121,11 @@ public function getPlaceholderById( $id ) { return isset( $results[0] ) ? $results[0] : null; } - /** - * @param $key - * @param $value - * - * @return Brizy_Content_ContentPlaceholder|null - * @throws Exception - */ + /** + * @param $key + * @param $value + * @return array|null + */ public function getPlaceholdersByAttrValue( $key, $value ) { if(is_null($value)) return null; @@ -131,7 +133,7 @@ public function getPlaceholdersByAttrValue( $key, $value ) { $results = []; if ( isset( $this->placeholders ) ) { foreach ( $this->placeholders as $placeholder ) { - if ( $placeholder->getAttr( $key ) == $value ) { + if ( $placeholder->getAttribute( $key ) == $value ) { $results[] = $placeholder; } } diff --git a/content/placeholder-replacer.php b/content/placeholder-replacer.php index 2c7b11ade9..a30aa448d7 100644 --- a/content/placeholder-replacer.php +++ b/content/placeholder-replacer.php @@ -48,7 +48,6 @@ public function getContent( $content) { // set the placeholders found at this level $this->context->setPlaceholders($placeholders); - if ( $placeholders ) { foreach ( $placeholders as $contentPlaceholder ) { try { diff --git a/content/placeholders/abstract.php b/content/placeholders/abstract.php index 31ba30bc0c..f6db12d66d 100644 --- a/content/placeholders/abstract.php +++ b/content/placeholders/abstract.php @@ -67,7 +67,7 @@ public function support($placeholderName) public function shouldFallbackValue($value, ContextInterface $context, ContentPlaceholder $placeholder) { - return empty($value); + return is_null($value) || $value==""; } public function getFallbackValue(ContextInterface $context, ContentPlaceholder $placeholder) From 1921a496071bd65ad48a2cc38ec2b8c897f5239e Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Wed, 27 Oct 2021 15:26:24 +0300 Subject: [PATCH 17/44] ... --- content/context.php | 12 ++++++++---- editor/editor/editor.php | 38 ++++++++++++++++++++++---------------- 2 files changed, 30 insertions(+), 20 deletions(-) diff --git a/content/context.php b/content/context.php index b4ac31505a..9d33973b66 100644 --- a/content/context.php +++ b/content/context.php @@ -88,10 +88,6 @@ public function __construct($project, $brizy_post, $wp_post, $contentHtml, $pare $this->setEntity($wp_post); } - public function afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor) { - $this->setPlaceholders($contentPlaceholders); - } - /** * @return array */ @@ -139,6 +135,10 @@ public function getPlaceholdersByAttrValue( $key, $value ) { } } + if($context = $this->getParentContext()) { + $results = array_merge($results,$context->getPlaceholdersByAttrValue($key, $value)); + } + return $results; } @@ -156,6 +156,10 @@ public function getPlaceholderByAttrValues( $attributes ) { } } + if($context = $this->getParentContext()) { + return $context->getPlaceholderByAttrValues($attributes); + } + return null; } } diff --git a/editor/editor/editor.php b/editor/editor/editor.php index 5d73d7a3a7..ff461e4788 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -587,25 +587,31 @@ private function addGlobalBlocksData( $config ) { return $config; } - private function addGlobalBlocksData($config) { - - $postTaxonomies = get_post_taxonomies($wp_post_id = (int)$config['wp']['page']); - $postTerms = []; - foreach ($postTaxonomies as $tax) { - $postTerms = array_merge($postTerms, wp_get_post_terms($wp_post_id, $tax)); - } + /** + * @return object + */ + private function get_page_attachments() + { + global $wpdb; + $query = $wpdb->prepare( + "SELECT + pm.* + FROM + {$wpdb->prefix}postmeta pm + JOIN {$wpdb->prefix}postmeta pm2 ON pm2.post_id=pm.post_id AND pm2.meta_key='brizy_post_uid' AND pm2.meta_value=%s + WHERE pm.meta_key='brizy_attachment_uid' + GROUP BY pm.post_id", + $this->post->getUid() + ); - $postTermsByKeys = []; - foreach ($postTerms as $term) { - $postTermsByKeys[$term->term_id] = $term; + $results = $wpdb->get_results($query); + $attachment_data = array(); + foreach ($results as $row) { + $attachment_data[$row->meta_value] = true; } - $config['wp']['postTerms'] = $postTerms; - $config['wp']['postTermParents'] = array_diff_key( $this->getAllParents( $postTermsByKeys ), $postTermsByKeys ); - $config['wp']['postAuthor'] = (int) $this->post->getWpPost()->post_author; - - return $config; - } + return (object)$attachment_data; + } /** * @return object From c0d7c62f688f19e326d023dd98b434179c59aa45 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 29 Nov 2021 14:12:39 +0200 Subject: [PATCH 18/44] fix: placehodersContent action --- editor/api.php | 7 +--- editor/editor/editor.php | 80 ++++++++++++++++++++-------------------- 2 files changed, 42 insertions(+), 45 deletions(-) diff --git a/editor/api.php b/editor/api.php index f83011e53c..23d0a6bc39 100755 --- a/editor/api.php +++ b/editor/api.php @@ -85,6 +85,7 @@ protected function initializeApiActions() $this->addAjaxAction( self::AJAX_SIDEBARS, array( $this, 'get_sidebars' ) ); $this->addAjaxAction( self::AJAX_SHORTCODE_CONTENT, array( $this, 'shortcode_content' ) ); $this->addAjaxAction( self::AJAX_PLACEHOLDER_CONTENT, array( $this, 'placeholder_content' ) ); + $this->addAjaxAction( self::AJAX_PLACEHOLDERS_CONTENT, array( $this, 'placeholder_content' ) ); $this->addAjaxAction( self::AJAX_GET_POST_OBJECTS, array( $this, 'get_post_objects' ) ); $this->addAjaxAction( self::AJAX_SEARCH_POST, array( $this, 'search_post' ) ); $this->addAjaxAction( self::AJAX_GET_MENU_LIST, array( $this, 'get_menu_list' ) ); @@ -516,11 +517,7 @@ public function placeholder_content() $contents[] = apply_filters('brizy_content', $placeholder, Brizy_Editor_Project::get(), $post); } - $this->success( - array( - 'placeholders' => $contents, - ) - ); + $this->success(array('placeholders' => $contents)); } catch (Exception $exception) { Brizy_Logger::instance()->exception($exception); $this->error($exception->getCode(), $exception->getMessage()); diff --git a/editor/editor/editor.php b/editor/editor/editor.php index ff461e4788..b69ba71040 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -1380,46 +1380,46 @@ public function getApiActions( $config = [], $context = null ) { 'downloadLayouts' => $pref . Brizy_Admin_Layouts_Api::DOWNLOAD_LAYOUTS, 'uploadLayouts' => $pref . Brizy_Admin_Layouts_Api::UPLOAD_LAYOUTS, 'media' => $pref . Brizy_Editor_API::AJAX_MEDIA, - 'getMediaUid' => $pref . Brizy_Editor_API::AJAX_MEDIA_METAKEY, - 'getAttachmentUid' => $pref . Brizy_Editor_API::AJAX_CREATE_ATTACHMENT_UID, - 'getServerTimeStamp' => $pref . Brizy_Editor_API::AJAX_TIMESTAMP, - 'createBlockScreenshot' => $pref . Brizy_Editor_BlockScreenshotApi::AJAX_CREATE_BLOCK_SCREENSHOT, - 'updateBlockScreenshot' => $pref . Brizy_Editor_BlockScreenshotApi::AJAX_UPDATE_BLOCK_SCREENSHOT, - 'getSidebars' => $pref . Brizy_Editor_API::AJAX_SIDEBARS, - 'shortcodeContent' => $pref . Brizy_Editor_API::AJAX_SHORTCODE_CONTENT, - 'placeholderContent' => $pref . Brizy_Editor_API::AJAX_PLACEHOLDER_CONTENT, - 'placeholdersContent' => $pref . Brizy_Editor_API::AJAX_PLACEHOLDERS_CONTENT, - 'getPostTaxonomies' => $pref . Brizy_Editor_API::AJAX_GET_POST_TAXONOMIES, - 'getMenus' => $pref . Brizy_Editor_API::AJAX_GET_MENU_LIST, - 'getTerms' => $pref . Brizy_Editor_API::AJAX_GET_TERMS, - 'getTermsBy' => $pref . Brizy_Editor_API::AJAX_GET_TERMS_BY, - 'getUsers' => $pref . Brizy_Editor_API::AJAX_GET_USERS, - 'getPostObjects' => $pref . Brizy_Editor_API::AJAX_GET_POST_OBJECTS, // ??? - 'searchPosts' => $pref . Brizy_Editor_API::AJAX_SEARCH_POST, - 'setFeaturedImage' => $pref . Brizy_Editor_API::AJAX_SET_FEATURED_IMAGE, - 'setFeaturedImageFocalPoint' => $pref . Brizy_Editor_API::AJAX_SET_IMAGE_FOCAL_PT, - 'removeFeaturedImage' => $pref . Brizy_Editor_API::AJAX_REMOVE_FEATURED_IMAGE, - 'getForm' => $pref . Brizy_Editor_Forms_Api::AJAX_GET_FORM, - 'createForm' => $pref . Brizy_Editor_Forms_Api::AJAX_CREATE_FORM, - 'updateForm' => $pref . Brizy_Editor_Forms_Api::AJAX_UPDATE_FORM, - 'deleteForm' => $pref . Brizy_Editor_Forms_Api::AJAX_DELETE_FORM, - 'getIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_GET_INTEGRATION, - 'createIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_CREATE_INTEGRATION, - 'updateIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_UPDATE_INTEGRATION, - 'deleteIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_DELETE_INTEGRATION, - 'createFont' => $pref . Brizy_Admin_Fonts_Api::AJAX_CREATE_FONT_ACTION, - 'deleteFont' => $pref . Brizy_Admin_Fonts_Api::AJAX_DELETE_FONT_ACTION, - 'getFonts' => $pref . Brizy_Admin_Fonts_Api::AJAX_GET_FONTS_ACTION, - 'getAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_GET_ACCOUNT, - 'getAccounts' => $pref . Brizy_Editor_Accounts_Api::BRIZY_GET_ACCOUNTS, - 'addAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_ADD_ACCOUNT, - 'updateAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_UPDATE_ACCOUNT, - 'deleteAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_DELETE_ACCOUNT, - 'validateRecaptchaAccount' => $pref . Brizy_Editor_Forms_Api::AJAX_VALIDATE_RECAPTCHA_ACCOUNT, - 'rulePostsGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_POSTS_GROUP_LIST, - 'ruleArchiveGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_ARCHIVE_GROUP_LIST, - 'ruleTemplateGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_TEMPLATE_GROUP_LIST, - 'symbolCreate' => $pref . Brizy_Admin_Symbols_Api::CREATE_ACTION, + 'getMediaUid' => $pref . Brizy_Editor_API::AJAX_MEDIA_METAKEY, + 'getAttachmentUid' => $pref . Brizy_Editor_API::AJAX_CREATE_ATTACHMENT_UID, + 'getServerTimeStamp' => $pref . Brizy_Editor_API::AJAX_TIMESTAMP, + 'createBlockScreenshot' => $pref . Brizy_Editor_BlockScreenshotApi::AJAX_CREATE_BLOCK_SCREENSHOT, + 'updateBlockScreenshot' => $pref . Brizy_Editor_BlockScreenshotApi::AJAX_UPDATE_BLOCK_SCREENSHOT, + 'getSidebars' => $pref . Brizy_Editor_API::AJAX_SIDEBARS, + 'shortcodeContent' => $pref . Brizy_Editor_API::AJAX_SHORTCODE_CONTENT, + 'placeholderContent' => $pref . Brizy_Editor_API::AJAX_PLACEHOLDER_CONTENT, + 'placeholdersContent' => $pref . Brizy_Editor_API::AJAX_PLACEHOLDERS_CONTENT, + 'getPostTaxonomies' => $pref . Brizy_Editor_API::AJAX_GET_POST_TAXONOMIES, + 'getMenus' => $pref . Brizy_Editor_API::AJAX_GET_MENU_LIST, + 'getTerms' => $pref . Brizy_Editor_API::AJAX_GET_TERMS, + 'getTermsBy' => $pref . Brizy_Editor_API::AJAX_GET_TERMS_BY, + 'getUsers' => $pref . Brizy_Editor_API::AJAX_GET_USERS, + 'getPostObjects' => $pref . Brizy_Editor_API::AJAX_GET_POST_OBJECTS, // ??? + 'searchPosts' => $pref . Brizy_Editor_API::AJAX_SEARCH_POST, + 'setFeaturedImage' => $pref . Brizy_Editor_API::AJAX_SET_FEATURED_IMAGE, + 'setFeaturedImageFocalPoint' => $pref . Brizy_Editor_API::AJAX_SET_IMAGE_FOCAL_PT, + 'removeFeaturedImage' => $pref . Brizy_Editor_API::AJAX_REMOVE_FEATURED_IMAGE, + 'getForm' => $pref . Brizy_Editor_Forms_Api::AJAX_GET_FORM, + 'createForm' => $pref . Brizy_Editor_Forms_Api::AJAX_CREATE_FORM, + 'updateForm' => $pref . Brizy_Editor_Forms_Api::AJAX_UPDATE_FORM, + 'deleteForm' => $pref . Brizy_Editor_Forms_Api::AJAX_DELETE_FORM, + 'getIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_GET_INTEGRATION, + 'createIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_CREATE_INTEGRATION, + 'updateIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_UPDATE_INTEGRATION, + 'deleteIntegration' => $pref . Brizy_Editor_Forms_Api::AJAX_DELETE_INTEGRATION, + 'createFont' => $pref . Brizy_Admin_Fonts_Api::AJAX_CREATE_FONT_ACTION, + 'deleteFont' => $pref . Brizy_Admin_Fonts_Api::AJAX_DELETE_FONT_ACTION, + 'getFonts' => $pref . Brizy_Admin_Fonts_Api::AJAX_GET_FONTS_ACTION, + 'getAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_GET_ACCOUNT, + 'getAccounts' => $pref . Brizy_Editor_Accounts_Api::BRIZY_GET_ACCOUNTS, + 'addAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_ADD_ACCOUNT, + 'updateAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_UPDATE_ACCOUNT, + 'deleteAccount' => $pref . Brizy_Editor_Accounts_Api::BRIZY_DELETE_ACCOUNT, + 'validateRecaptchaAccount' => $pref . Brizy_Editor_Forms_Api::AJAX_VALIDATE_RECAPTCHA_ACCOUNT, + 'rulePostsGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_POSTS_GROUP_LIST, + 'ruleArchiveGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_ARCHIVE_GROUP_LIST, + 'ruleTemplateGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_TEMPLATE_GROUP_LIST, + 'symbolCreate' => $pref . Brizy_Admin_Symbols_Api::CREATE_ACTION, 'symbolUpdate' => $pref . Brizy_Admin_Symbols_Api::UPDATE_ACTION, 'symbolDelete' => $pref . Brizy_Admin_Symbols_Api::DELETE_ACTION, 'symbolList' => $pref . Brizy_Admin_Symbols_Api::LIST_ACTION, From f4532af44c859c58894562194a824d3887ad4ff9 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 29 Nov 2021 16:08:18 +0200 Subject: [PATCH 19/44] fix: fixed get placeholders content action --- editor/api.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/editor/api.php b/editor/api.php index 23d0a6bc39..700807b105 100755 --- a/editor/api.php +++ b/editor/api.php @@ -85,7 +85,7 @@ protected function initializeApiActions() $this->addAjaxAction( self::AJAX_SIDEBARS, array( $this, 'get_sidebars' ) ); $this->addAjaxAction( self::AJAX_SHORTCODE_CONTENT, array( $this, 'shortcode_content' ) ); $this->addAjaxAction( self::AJAX_PLACEHOLDER_CONTENT, array( $this, 'placeholder_content' ) ); - $this->addAjaxAction( self::AJAX_PLACEHOLDERS_CONTENT, array( $this, 'placeholder_content' ) ); + $this->addAjaxAction( self::AJAX_PLACEHOLDERS_CONTENT, array( $this, 'placeholders_content' ) ); $this->addAjaxAction( self::AJAX_GET_POST_OBJECTS, array( $this, 'get_post_objects' ) ); $this->addAjaxAction( self::AJAX_SEARCH_POST, array( $this, 'search_post' ) ); $this->addAjaxAction( self::AJAX_GET_MENU_LIST, array( $this, 'get_menu_list' ) ); From ffb94ee062bb1d68fef414c653c00acd23c004ec Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 14 Feb 2022 14:50:47 +0200 Subject: [PATCH 20/44] new: filter placeholder content ... --- editor/api.php | 1 + editor/filters/api.php | 46 ++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 45 insertions(+), 2 deletions(-) diff --git a/editor/api.php b/editor/api.php index 700807b105..8c69f0408c 100755 --- a/editor/api.php +++ b/editor/api.php @@ -39,6 +39,7 @@ class Brizy_Editor_API extends Brizy_Admin_AbstractApi const AJAX_GET_TERMS_BY = '_get_terms_by'; const AJAX_GET_POST_TAXONOMIES = '_get_post_taxonomies'; + /** * @var Brizy_Editor_Post */ diff --git a/editor/filters/api.php b/editor/filters/api.php index dd5dfdf2b5..b8e11bcaa0 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -2,16 +2,58 @@ class Brizy_Editor_Filters_Api extends Brizy_Admin_AbstractApi { - const AJAX_FILTER = 'asss'; + const nonce = 'brizy-api'; + const AJAX_FILTER_PLACEHOLDERS_CONTENT = '_filter_placeholders_content'; protected function initializeApiActions() { if ( ! Brizy_Editor_User::is_user_allowed() ) { return; } - $this->addAjaxAction( self::AJAX_FILTER, array( $this, 'removeProjectLock' ) ); + $this->addAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); } protected function getRequestNonce() { return $this->param( 'hash' ); } + + public function filterPlaceholdersContent() { + $this->verifyNonce(self::nonce); + + if(empty($postId = $this->param('post_id'))) { + $this->error(400, 'Please provide the post id'); + } + + if(empty($postLoopId = $this->param('post_loop_id'))) { + $this->error(400, 'Please provide the post loop id'); + } + + if(empty($placeholders = $this->param('placeholders'))) { + $this->error(400, 'Please provide the placeholders param'); + } + + $brizyPost = Brizy_Editor_Post::get($postId); + $postContent = $this->getBrizyPostContent(Brizy_Editor_Project::get(), $brizyPost); + + } + + private function getBrizyPostContent(Brizy_Editor_Project $project,Brizy_Editor_Post $post) { + $project = Brizy_Editor_Project::get(); + + if (!$post->get_compiled_html()) { + $compiled_html_body = $post->get_compiled_html_body(); + $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); + $post->set_needs_compile(true)->saveStorage(); + } else { + $compiled_page = $post->get_compiled_page(); + $content = $compiled_page->get_body(); + } + + return apply_filters( + 'brizy_content', + $content, + $project, + $post->getWpPost(), + 'body' + ); + } } From 8ef3d8c61ecc527d1434b555e3b2afb319ec71e8 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Tue, 15 Feb 2022 10:22:54 +0200 Subject: [PATCH 21/44] new: filter placeholder content --- editor.php | 5 +++-- editor/editor/editor.php | 3 ++- editor/filters/api.php | 30 ++++++++++++++++++++++++++---- 3 files changed, 31 insertions(+), 7 deletions(-) diff --git a/editor.php b/editor.php index f6a7494383..ddd6b2a4d3 100755 --- a/editor.php +++ b/editor.php @@ -339,8 +339,9 @@ private function loadEditorApi($post, $user) new Brizy_Editor_RestExtend(); new Brizy_Editor_API($post); new Brizy_Editor_BlockScreenshotApi($post); - Brizy_Editor_Accounts_Api::_init(); - } + new Brizy_Editor_Filters_Api( ); + Brizy_Editor_Accounts_Api::_init(); + } new Brizy_Editor_Forms_Api($post); diff --git a/editor/editor/editor.php b/editor/editor/editor.php index b69ba71040..fd82612007 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -1419,10 +1419,11 @@ public function getApiActions( $config = [], $context = null ) { 'rulePostsGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_POSTS_GROUP_LIST, 'ruleArchiveGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_ARCHIVE_GROUP_LIST, 'ruleTemplateGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_TEMPLATE_GROUP_LIST, - 'symbolCreate' => $pref . Brizy_Admin_Symbols_Api::CREATE_ACTION, + 'symbolCreate' => $pref . Brizy_Admin_Symbols_Api::CREATE_ACTION, 'symbolUpdate' => $pref . Brizy_Admin_Symbols_Api::UPDATE_ACTION, 'symbolDelete' => $pref . Brizy_Admin_Symbols_Api::DELETE_ACTION, 'symbolList' => $pref . Brizy_Admin_Symbols_Api::LIST_ACTION, + 'filterPlaceholderContents' => $pref . Brizy_Editor_Filters_Api::AJAX_FILTER_PLACEHOLDERS_CONTENT, ); return $actions; diff --git a/editor/filters/api.php b/editor/filters/api.php index b8e11bcaa0..d2285c8487 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -23,17 +23,39 @@ public function filterPlaceholdersContent() { $this->error(400, 'Please provide the post id'); } - if(empty($postLoopId = $this->param('post_loop_id'))) { - $this->error(400, 'Please provide the post loop id'); - } - if(empty($placeholders = $this->param('placeholders'))) { $this->error(400, 'Please provide the placeholders param'); } + $placeholderContents = []; $brizyPost = Brizy_Editor_Post::get($postId); $postContent = $this->getBrizyPostContent(Brizy_Editor_Project::get(), $brizyPost); + $placeholderProvider = new Brizy_Content_PlaceholderProvider(); + $context = new Brizy_Content_Context(Brizy_Editor_Project::get(),$brizyPost,$brizyPost->getWpPost(),''); + $context->setProvider( $placeholderProvider ); + $extractor = new \BrizyPlaceholders\Extractor( $placeholderProvider ); + + /** + * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders; + */ + list( $contentPlaceholders, $placeholderInstances, $newPostContent ) = $extractor->extract( $postContent ); + $context->setPlaceholders($contentPlaceholders); + + foreach( $placeholders as $placeholderId) { + /** + * @var \BrizyPlaceholders\ContentPlaceholder $placeholder; + */ + $placeholder = $context->getPlaceholderById($placeholderId); + /** + * @var Brizy_Content_Placeholders_Abstract $placeholderInstance; + */ + $placeholderInstance = $placeholderProvider->getPlaceholderSupportingName($placeholder->getName()); + $placeholderContents[$placeholderId] = $placeholderInstance->getValue($context,$placeholder); + } + + + $this->success(['placeholders'=>$placeholderContents]); } private function getBrizyPostContent(Brizy_Editor_Project $project,Brizy_Editor_Post $post) { From b0a3eef3706a1849f32511cb3923ba97d5af591b Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 17 Feb 2022 09:41:04 +0200 Subject: [PATCH 22/44] fix: made the filter placeholder content action public --- editor.php | 11 ++++++----- editor/filters/api.php | 9 ++++----- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/editor.php b/editor.php index ddd6b2a4d3..c185d0c4f7 100755 --- a/editor.php +++ b/editor.php @@ -335,11 +335,12 @@ public function registerCustomPostTemplates() private function loadEditorApi($post, $user) { try { - if (Brizy_Editor_User::is_user_allowed()) { - new Brizy_Editor_RestExtend(); - new Brizy_Editor_API($post); - new Brizy_Editor_BlockScreenshotApi($post); - new Brizy_Editor_Filters_Api( ); + new Brizy_Editor_Filters_Api( ); + + if ( Brizy_Editor_User::is_user_allowed() ) { + new Brizy_Editor_RestExtend(); + new Brizy_Editor_API( $post ); + new Brizy_Editor_BlockScreenshotApi( $post ); Brizy_Editor_Accounts_Api::_init(); } diff --git a/editor/filters/api.php b/editor/filters/api.php index d2285c8487..fa2f741bae 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -6,10 +6,7 @@ class Brizy_Editor_Filters_Api extends Brizy_Admin_AbstractApi { const AJAX_FILTER_PLACEHOLDERS_CONTENT = '_filter_placeholders_content'; protected function initializeApiActions() { - if ( ! Brizy_Editor_User::is_user_allowed() ) { - return; - } - $this->addAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); + $this->addNoPrivAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); } protected function getRequestNonce() { @@ -17,7 +14,6 @@ protected function getRequestNonce() { } public function filterPlaceholdersContent() { - $this->verifyNonce(self::nonce); if(empty($postId = $this->param('post_id'))) { $this->error(400, 'Please provide the post id'); @@ -47,6 +43,9 @@ public function filterPlaceholdersContent() { * @var \BrizyPlaceholders\ContentPlaceholder $placeholder; */ $placeholder = $context->getPlaceholderById($placeholderId); + + if(!$placeholder) continue; + /** * @var Brizy_Content_Placeholders_Abstract $placeholderInstance; */ From c6dac6a5e7efa7155fb7ae121b3a70bf9ae280de Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 17 Feb 2022 10:49:51 +0200 Subject: [PATCH 23/44] fix: fixed the content parsed for filter placeholders --- editor/filters/api.php | 9 ++------- 1 file changed, 2 insertions(+), 7 deletions(-) diff --git a/editor/filters/api.php b/editor/filters/api.php index fa2f741bae..1595f34d38 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -7,6 +7,7 @@ class Brizy_Editor_Filters_Api extends Brizy_Admin_AbstractApi { protected function initializeApiActions() { $this->addNoPrivAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); + $this->addAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); } protected function getRequestNonce() { @@ -69,12 +70,6 @@ private function getBrizyPostContent(Brizy_Editor_Project $project,Brizy_Editor_ $content = $compiled_page->get_body(); } - return apply_filters( - 'brizy_content', - $content, - $project, - $post->getWpPost(), - 'body' - ); + return $content; } } From 0935f93b4af6dbbb3a55a7a13f5c64c8d7972c78 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Wed, 18 May 2022 16:49:04 +0300 Subject: [PATCH 24/44] fix: added page placeholders in context --- content/dynamic-content-processor.php | 25 +++++++++++++++++++++++++ 1 file changed, 25 insertions(+) diff --git a/content/dynamic-content-processor.php b/content/dynamic-content-processor.php index 3b24270cf6..4c0db9013d 100644 --- a/content/dynamic-content-processor.php +++ b/content/dynamic-content-processor.php @@ -18,6 +18,15 @@ public function process( $content, Brizy_Content_Context $context ) { $context->setProvider( $placeholderProvider ); + // load all page placeholders + $postContent = $this->getBrizyPostContent($context->getProject(), Brizy_Editor_Post::get($context->getWpPost())); + /** + * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders; + */ + list( $contentPlaceholders, $placeholderInstances, $newPostContent ) = $extractor->extract( $postContent ); + $context->setPlaceholders($contentPlaceholders); + + list( $contentPlaceholders, $placeholderInstances, $content ) = $extractor->extract( $content ); $replacer = new Replacer( $placeholderProvider ); @@ -26,4 +35,20 @@ public function process( $content, Brizy_Content_Context $context ) { return $content; } + + + private function getBrizyPostContent(Brizy_Editor_Project $project,Brizy_Editor_Post $post) { + $project = Brizy_Editor_Project::get(); + + if (!$post->get_compiled_html()) { + $compiled_html_body = $post->get_compiled_html_body(); + $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); + $post->set_needs_compile(true)->saveStorage(); + } else { + $compiled_page = $post->get_compiled_page(); + $content = $compiled_page->get_body(); + } + + return $content; + } } From 6d41c6498fa6961260125675f75862d424eabbf1 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 19 May 2022 15:31:19 +0300 Subject: [PATCH 25/44] fix: added placeholders in context --- editor/post.php | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/editor/post.php b/editor/post.php index 3cbd22e0d0..1efaaa3e7f 100755 --- a/editor/post.php +++ b/editor/post.php @@ -317,7 +317,9 @@ private function getPostContent($noFilters) list($placeholders, $placeholderInstances, $content) = $extractor->extract($this->get_compiled_page()->getPageContent()); - $replacer = new \BrizyPlaceholders\Replacer($placeholderProvider); + $context->setPlaceholders($placeholders); + + $replacer = new \BrizyPlaceholders\Replacer($placeholderProvider); $content = $replacer->replaceWithExtractedData($placeholders, $placeholderInstances, $content, $context); $content = $extractor->stripPlaceholders($content); From 25dea39d981de6a6f34aebd1c7f1a8765e7adc2a Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Fri, 20 May 2022 15:49:47 +0300 Subject: [PATCH 26/44] fix: optimized dynamic content processor --- content/dynamic-content-processor.php | 72 ++++++++++++++++----------- 1 file changed, 43 insertions(+), 29 deletions(-) diff --git a/content/dynamic-content-processor.php b/content/dynamic-content-processor.php index 4c0db9013d..9383cc27e2 100644 --- a/content/dynamic-content-processor.php +++ b/content/dynamic-content-processor.php @@ -3,50 +3,64 @@ use BrizyPlaceholders\Extractor; use BrizyPlaceholders\Replacer; -class Brizy_Content_DynamicContentProcessor implements Brizy_Editor_Content_ProcessorInterface { +class Brizy_Content_DynamicContentProcessor implements Brizy_Editor_Content_ProcessorInterface +{ - /** - * @param string $content - * @param Brizy_Content_Context $context - * - * @return mixed - */ - public function process( $content, Brizy_Content_Context $context ) { + /** + * @param string $content + * @param Brizy_Content_Context $context + * + * @return mixed + */ + public function process($targetContent, Brizy_Content_Context $context) + { - $placeholderProvider = new Brizy_Content_PlaceholderProvider( $context ); - $extractor = new Extractor( $placeholderProvider ); + $placeholderProvider = new Brizy_Content_PlaceholderProvider($context); + $extractor = new Extractor($placeholderProvider); - $context->setProvider( $placeholderProvider ); + $context->setProvider($placeholderProvider); - // load all page placeholders - $postContent = $this->getBrizyPostContent($context->getProject(), Brizy_Editor_Post::get($context->getWpPost())); - /** - * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders; - */ - list( $contentPlaceholders, $placeholderInstances, $newPostContent ) = $extractor->extract( $postContent ); - $context->setPlaceholders($contentPlaceholders); + list($contentPlaceholders, $placeholderInstances, $content) = $extractor->extract($targetContent); + if (count($contentPlaceholders) > 0) { + $context->setPlaceholders($contentPlaceholders); - list( $contentPlaceholders, $placeholderInstances, $content ) = $extractor->extract( $content ); + // load all page placeholders + $postContent = $this->getBrizyPostContent( + $context->getProject(), + Brizy_Editor_Post::get($context->getWpPost()) + ); + if ($targetContent != $postContent) { + /** + * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders ; + */ + list($newContentPlaceholders, $placeholderInstances, $newPostContent) = $extractor->extract($postContent); - $replacer = new Replacer( $placeholderProvider ); + $context->setPlaceholders(array_merge($contentPlaceholders,$newContentPlaceholders)); + } - $content = $replacer->replaceWithExtractedData( $contentPlaceholders, $placeholderInstances, $content ,$context); - - return $content; - } + $replacer = new Replacer($placeholderProvider); + $content = $replacer->replaceWithExtractedData( + $contentPlaceholders, + $placeholderInstances, + $content, + $context + ); + } + return $content; + } - private function getBrizyPostContent(Brizy_Editor_Project $project,Brizy_Editor_Post $post) { - $project = Brizy_Editor_Project::get(); - if (!$post->get_compiled_html()) { + private function getBrizyPostContent(Brizy_Editor_Project $project, Brizy_Editor_Post $post) + { + if ( ! $post->get_compiled_html()) { $compiled_html_body = $post->get_compiled_html_body(); - $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); + $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); $post->set_needs_compile(true)->saveStorage(); } else { $compiled_page = $post->get_compiled_page(); - $content = $compiled_page->get_body(); + $content = $compiled_page->get_body(); } return $content; From e7ea25a80b883b878ba735527e3f25454750a3b5 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 23 May 2022 08:36:24 +0300 Subject: [PATCH 27/44] ... --- content/context.php | 138 ++++++++++++++++---------- content/dynamic-content-processor.php | 2 +- editor/filters/api.php | 28 +++--- 3 files changed, 100 insertions(+), 68 deletions(-) diff --git a/content/context.php b/content/context.php index 9d33973b66..cfabafa4f5 100644 --- a/content/context.php +++ b/content/context.php @@ -8,10 +8,11 @@ class Brizy_Content_Context implements ContextInterface protected $data = array(); - /** - * @var ContentPlaceholder[] - */ - protected $placeholders = []; + /** + * @var ContentPlaceholder[] + */ + protected $placeholders = []; + /** * @param $name @@ -22,7 +23,7 @@ class Brizy_Content_Context implements ContextInterface public function __call($name, $arguments) { $method = substr($name, 0, 3); - $key = substr($name, 3); + $key = substr($name, 3); switch ($method) { case 'set': @@ -56,7 +57,7 @@ protected function get($name) public function afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor) { - $this->setPlaceholders($contentPlaceholders); + $this->setPlaceholders(array_merge( $this->getPlaceholders(),$contentPlaceholders )); } @@ -75,88 +76,115 @@ protected function set($key, $value) return $this->data[$key] = $value; } - /** - * BrizyPro_Content_Context constructor. - * - * @param $project - * @param $wp_post - */ - public function __construct($project, $brizy_post, $wp_post, $contentHtml, $parentContext = null ) { - $this->setProject( $project ); - $this->setWpPost( $wp_post ); - $this->setParentContext( $parentContext ); - $this->setEntity($wp_post); + /** + * BrizyPro_Content_Context constructor. + * + * @param $project + * @param $wp_post + */ + public function __construct($project, $brizy_post, $wp_post, $contentHtml, $parentContext = null) + { + $this->setProject($project); + $this->setWpPost($wp_post); + $this->setParentContext($parentContext); + $this->setEntity($wp_post); } - /** - * @return array - */ - public function getPlaceholders() { - return $this->placeholders; - } + /** + * @return array + */ + public function getPlaceholders() + { + return $this->placeholders; + } - /** - * @param array $placeholders - * - * @return Brizy_Content_Context - */ - public function setPlaceholders( array $placeholders ) { - $this->placeholders = $placeholders; + /** + * @param array $placeholders + * + * @return Brizy_Content_Context + */ + public function setPlaceholders(array $placeholders) + { + $this->placeholders = $placeholders; - return $this; - } + return $this; + } /** * @param $id + * * @return mixed|null */ - public function getPlaceholderById( $id ) { + public function getPlaceholderById($id) + { - $results = $this->getPlaceholdersByAttrValue( 'id', $id ); + $results = $this->getPlaceholdersByAttrValue('id', $id); - return isset( $results[0] ) ? $results[0] : null; - } + return isset($results[0]) ? $results[0] : null; + } /** * @param $key * @param $value + * * @return array|null */ - public function getPlaceholdersByAttrValue( $key, $value ) { + public function getPlaceholdersByAttrValue($key, $value) + { - if(is_null($value)) return null; + if (is_null($value)) { + return null; + } - $results = []; - if ( isset( $this->placeholders ) ) { - foreach ( $this->placeholders as $placeholder ) { - if ( $placeholder->getAttribute( $key ) == $value ) { - $results[] = $placeholder; - } - } - } + $results = []; + if (isset($this->placeholders)) { + foreach ($this->placeholders as $placeholder) { + if ($placeholder->getAttribute($key) == $value) { + $results[] = $placeholder; + } + } + } - if($context = $this->getParentContext()) { - $results = array_merge($results,$context->getPlaceholdersByAttrValue($key, $value)); + if ($context = $this->getParentContext()) { + $results = array_merge($results, $context->getPlaceholdersByAttrValue($key, $value)); } - return $results; - } + return $results; + } + + /** + * @return array + */ + public function getProvider() + { + if ($provider = $this->get('Provider')) { + return $provider; + } + + if ($parentContext = $this->getParentContext()) { + return $parentContext->getProvider(); + } + + return null; + } /** * @param $attributes + * * @return Brizy_Content_ContentPlaceholder|null */ - public function getPlaceholderByAttrValues( $attributes ) { + public function getPlaceholderByAttrValues($attributes) + { - if ( isset( $this->placeholders ) ) { - foreach ( $this->placeholders as $placeholder ) { - if ( count(array_intersect($placeholder->getAttributes(),$attributes))==count($attributes) ) { + if (isset($this->placeholders)) { + foreach ($this->placeholders as $placeholder) { + if (count(array_intersect($placeholder->getAttributes(), $attributes)) == count($attributes)) { return $placeholder; } } } - if($context = $this->getParentContext()) { + if ($context = $this->getParentContext()) { return $context->getPlaceholderByAttrValues($attributes); } diff --git a/content/dynamic-content-processor.php b/content/dynamic-content-processor.php index 9383cc27e2..97120c3600 100644 --- a/content/dynamic-content-processor.php +++ b/content/dynamic-content-processor.php @@ -36,7 +36,7 @@ public function process($targetContent, Brizy_Content_Context $context) */ list($newContentPlaceholders, $placeholderInstances, $newPostContent) = $extractor->extract($postContent); - $context->setPlaceholders(array_merge($contentPlaceholders,$newContentPlaceholders)); + $context->afterExtract($newContentPlaceholders, $placeholderInstances, $newPostContent); } $replacer = new Replacer($placeholderProvider); diff --git a/editor/filters/api.php b/editor/filters/api.php index 1595f34d38..821c7d60f9 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -40,18 +40,22 @@ public function filterPlaceholdersContent() { $context->setPlaceholders($contentPlaceholders); foreach( $placeholders as $placeholderId) { - /** - * @var \BrizyPlaceholders\ContentPlaceholder $placeholder; - */ - $placeholder = $context->getPlaceholderById($placeholderId); - - if(!$placeholder) continue; - - /** - * @var Brizy_Content_Placeholders_Abstract $placeholderInstance; - */ - $placeholderInstance = $placeholderProvider->getPlaceholderSupportingName($placeholder->getName()); - $placeholderContents[$placeholderId] = $placeholderInstance->getValue($context,$placeholder); + try { + /** + * @var \BrizyPlaceholders\ContentPlaceholder $placeholder; + */ + $placeholder = $context->getPlaceholderById($placeholderId); + + if(!$placeholder) continue; + + /** + * @var Brizy_Content_Placeholders_Abstract $placeholderInstance; + */ + $placeholderInstance = $placeholderProvider->getPlaceholderSupportingName($placeholder->getName()); + $placeholderContents[$placeholderId] = $placeholderInstance->getValue($context,$placeholder); + } catch (\Exception $e) { + $placeholderContents[$placeholderId] = null; + } } From c5e881d38bd3ba77ecef076c4cf575d941a76a7e Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 23 May 2022 13:28:38 +0300 Subject: [PATCH 28/44] fix: dynamic content processor --- editor/api.php | 1841 ++++++++++++++++++++++++------------------------ 1 file changed, 905 insertions(+), 936 deletions(-) diff --git a/editor/api.php b/editor/api.php index 8c69f0408c..16acf083d8 100755 --- a/editor/api.php +++ b/editor/api.php @@ -1,77 +1,73 @@ post; - } - - /** - * Brizy_Editor_API constructor. - * - * @param Brizy_Editor_Project $project - * @param Brizy_Editor_Post $post - */ - public function __construct($post) - { - - $this->post = $post; - - parent::__construct(); - } - - protected function initializeApiActions() - { - if ( ! Brizy_Editor_User::is_user_allowed()) { - return; - } + const AJAX_JWT_TOKEN = '_multipass_create'; + const AJAX_UPDATE_MENU_DATA = '_update_menu_data'; + const AJAX_UPDATE_EDITOR_META_DATA = '_update_editor_meta_data'; + const AJAX_UPDATE_MENU_ITEM_DATA = '_update_menu_item_data'; + const AJAX_MEDIA_METAKEY = '_get_media_key'; + const AJAX_CREATE_ATTACHMENT_UID = '_create_attachment_uid'; + const AJAX_SET_FEATURED_IMAGE = '_set_featured_image'; + const AJAX_SET_IMAGE_FOCAL_PT = '_set_featured_image_focal_point'; + const AJAX_REMOVE_FEATURED_IMAGE = '_remove_featured_image'; + const AJAX_TIMESTAMP = '_timestamp'; + const AJAX_SET_TEMPLATE_TYPE = '_set_template_type'; + const AJAX_GET_USERS = '_get_users'; + const AJAX_GET_TERMS = '_get_terms'; + const AJAX_GET_TERMS_BY = '_get_terms_by'; + const AJAX_GET_POST_TAXONOMIES = '_get_post_taxonomies'; + + + /** + * @var Brizy_Editor_Post + */ + private $post; + + /** + * @return Brizy_Editor_Post + */ + public function get_post() { + return $this->post; + } + + /** + * Brizy_Editor_API constructor. + * + * @param Brizy_Editor_Project $project + * @param Brizy_Editor_Post $post + */ + public function __construct( $post ) { + + $this->post = $post; + + parent::__construct(); + } + + protected function initializeApiActions() { + if ( ! Brizy_Editor_User::is_user_allowed() ) { + return; + } $this->addAjaxAction( self::AJAX_REMOVE_LOCK, array( $this, 'removeProjectLock' ) ); @@ -103,143 +99,133 @@ protected function initializeApiActions() $this->addAjaxAction( self::AJAX_GET_POST_TAXONOMIES, array( $this, 'addPostTaxonomies' ) ); $this->addNoPrivAjaxAction( Brizy_Editor::prefix( self::AJAX_TIMESTAMP ), array( $this, 'timestamp' ) ); - } + } - protected function getRequestNonce() - { - return $this->param('hash'); - } + protected function getRequestNonce() { + return $this->param( 'hash' ); + } - public function addPostTaxonomies() - { + public function addPostTaxonomies() { - $this->verifyNonce(self::nonce); + $this->verifyNonce( self::nonce ); - if (empty($postType = $this->param('post_type'))) { - $this->error(400, 'Bad request'); - } + if ( empty( $postType = $this->param( 'post_type' ) ) ) { + $this->error( 400, 'Bad request' ); + } - $taxonomies = get_object_taxonomies($postType, 'objects'); - $post_taxonomies = array_map(function (WP_Taxonomy $taxonomy) { - return [ - 'name' => $taxonomy->name, - 'label' => $taxonomy->label, - 'labels' => $taxonomy->labels, - 'public' => $taxonomy->public, - 'hierarchical' => $taxonomy->hierarchical, - ]; - }, array_values($taxonomies)); + $taxonomies = get_object_taxonomies( $postType, 'objects' ); + $post_taxonomies = array_map( function ( WP_Taxonomy $taxonomy ) { + return [ + 'name' => $taxonomy->name, + 'label' => $taxonomy->label, + 'labels' => $taxonomy->labels, + 'public' => $taxonomy->public, + 'hierarchical' => $taxonomy->hierarchical, + ]; + }, array_values( $taxonomies ) ); - $this->success($post_taxonomies); - } + $this->success( $post_taxonomies ); + } - public function lock_project() - { - $this->verifyNonce(self::nonce); + public function lock_project() { + $this->verifyNonce( self::nonce ); - if (Brizy_Editor::get()->checkIfProjectIsLocked() === false) { - Brizy_Editor::get()->lockProject(); - } + if ( Brizy_Editor::get()->checkIfProjectIsLocked() === false ) { + Brizy_Editor::get()->lockProject(); + } - $editor = new Brizy_Editor_Editor_Editor(Brizy_Editor_Project::get(), null); - $this->success($editor->getProjectStatus()); - } + $editor = new Brizy_Editor_Editor_Editor( Brizy_Editor_Project::get(), null ); + $this->success( $editor->getProjectStatus() ); + } - public function removeProjectLock() - { - $this->verifyNonce(self::nonce); + public function removeProjectLock() { + $this->verifyNonce( self::nonce ); - if (Brizy_Editor::get()->checkIfProjectIsLocked() === false) { - Brizy_Editor::get()->removeProjectLock(); - } + if ( Brizy_Editor::get()->checkIfProjectIsLocked() === false ) { + Brizy_Editor::get()->removeProjectLock(); + } - $editor = new Brizy_Editor_Editor_Editor(Brizy_Editor_Project::get(), null); - $this->success($editor->getProjectStatus()); - } + $editor = new Brizy_Editor_Editor_Editor( Brizy_Editor_Project::get(), null ); + $this->success( $editor->getProjectStatus() ); + } - public function heartbeat() - { - $this->verifyNonce(self::nonce); + public function heartbeat() { + $this->verifyNonce( self::nonce ); - if (Brizy_Editor::get()->checkIfProjectIsLocked() === false) { - Brizy_Editor::get()->lockProject(); - } - $editor = new Brizy_Editor_Editor_Editor(Brizy_Editor_Project::get(), null); - $this->success($editor->getProjectStatus()); - } + if ( Brizy_Editor::get()->checkIfProjectIsLocked() === false ) { + Brizy_Editor::get()->lockProject(); + } + $editor = new Brizy_Editor_Editor_Editor( Brizy_Editor_Project::get(), null ); + $this->success( $editor->getProjectStatus() ); + } - public function takeOver() - { - $this->verifyNonce(self::nonce); + public function takeOver() { + $this->verifyNonce( self::nonce ); - Brizy_Editor::get()->lockProject(); + Brizy_Editor::get()->lockProject(); - $editor = new Brizy_Editor_Editor_Editor(Brizy_Editor_Project::get(), null); - $this->success($editor->getProjectStatus()); - } + $editor = new Brizy_Editor_Editor_Editor( Brizy_Editor_Project::get(), null ); + $this->success( $editor->getProjectStatus() ); + } - public function timestamp() - { - $this->success(array('timestamp' => time())); - } + public function timestamp() { + $this->success( array( 'timestamp' => time() ) ); + } - public function set_featured_image() - { - $this->verifyNonce(self::nonce); + public function set_featured_image() { + $this->verifyNonce( self::nonce ); - if ( ! isset($_REQUEST['attachmentId'])) { - $this->error(400, 'Bad request'); - } + if ( ! isset( $_REQUEST['attachmentId'] ) ) { + $this->error( 400, 'Bad request' ); + } - if ($this->post && $this->post->uses_editor()) { - set_post_thumbnail($this->post->getWpPostId(), (int)$_REQUEST['attachmentId']); + if ( $this->post && $this->post->uses_editor() ) { + set_post_thumbnail( $this->post->getWpPostId(), (int) $_REQUEST['attachmentId'] ); - $uid = $this->createMediaKey($this->post->getWpPostId(), (int)$_REQUEST['attachmentId']); + $uid = $this->createMediaKey( $this->post->getWpPostId(), (int) $_REQUEST['attachmentId'] ); - $this->success(array('uid' => $uid)); - } + $this->success( array( 'uid' => $uid ) ); + } - $this->error(400, 'Invalid post'); - } + $this->error( 400, 'Invalid post' ); + } - public function set_featured_image_focal_point() - { - $this->verifyNonce(self::nonce); + public function set_featured_image_focal_point() { + $this->verifyNonce( self::nonce ); - if ( ! isset($_REQUEST['attachmentId']) || ! isset($_REQUEST['pointX']) || ! isset($_REQUEST['pointY'])) { - $this->error(400, 'Bad request'); - } + if ( ! isset( $_REQUEST['attachmentId'] ) || ! isset( $_REQUEST['pointX'] ) || ! isset( $_REQUEST['pointY'] ) ) { + $this->error( 400, 'Bad request' ); + } - if ($this->post && $this->post->uses_editor()) { + if ( $this->post && $this->post->uses_editor() ) { - update_post_meta( - $this->post->getWpPostId(), - 'brizy_attachment_focal_point', - array( - 'x' => $_REQUEST['pointX'], - 'y' => $_REQUEST['pointY'], - ) - ); + update_post_meta( + $this->post->getWpPostId(), + 'brizy_attachment_focal_point', + array( + 'x' => $_REQUEST['pointX'], + 'y' => $_REQUEST['pointY'], + ) + ); - $this->success(array()); - } + $this->success( array() ); + } - $this->error(400, 'Invalid post'); - } + $this->error( 400, 'Invalid post' ); + } - public function remove_featured_image() - { - $this->verifyNonce(self::nonce); + public function remove_featured_image() { + $this->verifyNonce( self::nonce ); - if ($this->post && $this->post->uses_editor()) { - delete_post_thumbnail($this->post->getWpPostId()); - delete_post_meta($this->post->getWpPostId(), 'brizy_attachment_focal_point'); - $this->success(null); - } + if ( $this->post && $this->post->uses_editor() ) { + delete_post_thumbnail( $this->post->getWpPostId() ); + delete_post_meta( $this->post->getWpPostId(), 'brizy_attachment_focal_point' ); + $this->success( null ); + } - $this->error(400, 'Invalid post'); - } + $this->error( 400, 'Invalid post' ); + } // public function multipass_create() { @@ -294,807 +280,790 @@ public function remove_featured_image() // } // } - /** - * @internal - **/ - public function get_project() - { - try { - $this->verifyNonce(self::nonce); - $data = Brizy_Editor_Project::get()->createResponse(); - $this->success($data); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error($exception->getCode(), $exception->getMessage()); - } - } - - /** - * @internal - */ - public function set_project() - { - try { - $this->verifyNonce(self::nonce); - - // update project globas - $meta = stripslashes($this->param('data')); - $dataVersion = (int)stripslashes($this->param('dataVersion')); - - if ( ! $meta) { - Brizy_Logger::instance()->error('Invalid project meta provided', ['data' => $meta]); - throw new Exception('', 400); - } - - if ( ! $dataVersion) { - Brizy_Logger::instance()->error('No data version provided', ['data' => $dataVersion]); - throw new Exception('', 400); - } - - $project = Brizy_Editor_Project::get(); - $project->setDataAsJson($meta); - $project->setDataVersion($dataVersion); - - - if ((int)$this->param('is_autosave') === 1) { - $project->save(1); - } else { - $project->save(); - $project->savePost(); - Brizy_Editor::get()->lockProject(); - do_action('brizy_global_data_updated'); - } - - $this->success($project->createResponse()); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error(400, $exception->getMessage()); - exit; - } - } - - /** - * @internal - **/ - public function get_item() - { - try { - $this->verifyNonce(self::nonce); - - if ( ! $this->post) { - throw new Exception('Invalid post provided'); - } - - $data = $this->post->createResponse(); - $data['is_index'] = true; - - $this->success(array($data)); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error(500, $exception->getMessage()); - exit; - } - } - - /** - * @internal - **/ - public function get_post_info() - { - try { - $this->verifyNonce(self::nonce); - - $postId = (int)$this->param('post_id'); - $defaultFields = ['ID', 'post_title', 'post_content']; - $post_fields = array_intersect((array)$this->param('fields'), $defaultFields); - - if (count($post_fields) == 0) { - $post_fields = $defaultFields; - } - - if ( ! $postId) { - $this->error(400, 'Invalid post id'); - } - - $post = get_post($postId, ARRAY_A); - - if ( ! $post) { - $this->error(404, 'Invalid post id'); - } - - $data = array_intersect_key($post, array_flip($defaultFields)); - - $this->success($data); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error(500, $exception->getMessage()); - exit; - } - } - - /** - * @internal - **/ - public function update_item() - { - try { - $this->verifyNonce(self::nonce); - - $data = stripslashes($this->param('data')); - $atemplate = $this->param('template'); - $dataVersion = (int)stripslashes($this->param('dataVersion')); - $status = stripslashes($this->param('status')); - - if ( ! in_array($status, ['publish', 'draft', 'pending', 'private', 'future'])) { - $this->error(400, "Invalid post type"); - } - - if ($atemplate) { - $this->post->set_template($atemplate); - } - - if ($data) { - $this->post->set_editor_data($data); - $this->post->set_editor_version(BRIZY_EDITOR_VERSION); - $this->post->set_needs_compile(true); - } - - $this->post->getWpPost()->post_status = $status; - - if ((int)$this->param('is_autosave') == 1) { - $this->post->save(1); - } else { - $this->post->setDataVersion($dataVersion); - $this->post->setLastUserEdited(get_current_user_id()); - $this->post->save(0); - $this->post->savePost(true); - } - - $this->success($this->post->createResponse()); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error(500, $exception->getMessage()); - } - } - - /* - * Used for elements like Woocommerce pages. - */ - public function shortcode_content() - { - try { - - $this->verifyNonce(self::nonce); - - if (isset($_REQUEST['shortcode'])) { - $shortcode = stripslashes($_REQUEST['shortcode']); - } else { - throw new Exception('Shortcode string not provided.', 500); - } - - $shortcode_content = do_shortcode($shortcode); - - $this->success( - array( - 'shortcode' => $shortcode_content, - ) - ); - - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error($exception->getCode(), $exception->getMessage()); - } - } - - public function placeholder_content() - { - try { - $this->verifyNonce(self::nonce); - $postId = $this->param('post_id'); - $placeholders = $this->param('placeholders'); - - if ( ! $placeholders) { - throw new Exception('Placeholder string not provided.', 400); - } - - global $post, $wp_query; - - $post = $this->getPostSample($postId); - - if ($post instanceof WP_Post) { - setup_postdata($post); - $wp_query->is_single = true; - - if (function_exists('wc_get_product')) { - global $product; - - $product = wc_get_product($post->ID); - } - } - - $contents = []; - foreach ($placeholders as $placeholder) { - $placeholder = stripslashes($placeholder); - $contents[] = apply_filters('brizy_content', $placeholder, Brizy_Editor_Project::get(), $post); - } - - $this->success(array('placeholders' => $contents)); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error($exception->getCode(), $exception->getMessage()); - } - } - - public function placeholders_content() - { - global $post, $wp_query; - try { - $this->verifyNonce(self::nonce); - $posts = $this->param('p'); - $contents = []; - foreach ($posts as $postId => $placeholders) { - $post = $this->getPostSample($postId); - $contents[$postId] = []; - - if ($post instanceof WP_Post) { - setup_postdata($post); - $wp_query->is_single = true; - } - foreach ($placeholders as $placeholder) { - $placeholder = stripslashes($placeholder); - $contents[$postId][] = apply_filters( - 'brizy_content', - $placeholder, - Brizy_Editor_Project::get(), - $post - ); - } - } - $this->success( - array( - 'placeholders' => $contents, - ) - ); - } catch (Exception $exception) { - Brizy_Logger::instance()->exception($exception); - $this->error($exception->getCode(), $exception->getMessage()); - } - } - - private function getPostSample($templateId) - { - global $wp_query; - $wp_post = get_post($templateId); - if ($wp_post->post_type !== Brizy_Admin_Templates::CP_TEMPLATE) { - return $wp_post; - } - - - $ruleManager = new Brizy_Admin_Rules_Manager(); - $rules = $ruleManager->getRules($wp_post->ID); - $rule = null; - - // find first include rule - foreach ($rules as $rule) { - /** - * @var Brizy_Admin_Rule $rule ; - */ - if ($rule->getType() == Brizy_Admin_Rule::TYPE_INCLUDE) { - break; - } - } - - if ($rule) { - switch ($rule->getAppliedFor()) { - case Brizy_Admin_Rule::POSTS : - $args = [ - 'fields' => 'ids', - 'post_type' => $rule->getEntityType(), - 'posts_per_page' => -1, - 'meta_query' => [ - [ - 'key' => Brizy_Editor_Constants::BRIZY_ENABLED, - 'compare' => 'NOT EXISTS', - ], - ], - ]; - - $values = $rule->getEntityValues(); - $posts = []; - if (empty($values[0])) { - // For All condition - $posts = get_posts($args); - + /** + * @internal + **/ + public function get_project() { + try { + $this->verifyNonce( self::nonce ); + $data = Brizy_Editor_Project::get()->createResponse(); + $this->success( $data ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( $exception->getCode(), $exception->getMessage() ); + } + } + + /** + * @internal + */ + public function set_project() { + try { + $this->verifyNonce( self::nonce ); + + // update project globas + $meta = stripslashes( $this->param( 'data' ) ); + $dataVersion = (int) stripslashes( $this->param( 'dataVersion' ) ); + + if ( ! $meta ) { + Brizy_Logger::instance()->error( 'Invalid project meta provided', [ 'data' => $meta ] ); + throw new Exception( '', 400 ); + } + + if ( ! $dataVersion ) { + Brizy_Logger::instance()->error( 'No data version provided', [ 'data' => $dataVersion ] ); + throw new Exception( '', 400 ); + } + + $project = Brizy_Editor_Project::get(); + $project->setDataAsJson( $meta ); + $project->setDataVersion( $dataVersion ); + + + if ( (int) $this->param( 'is_autosave' ) === 1 ) { + $project->save( 1 ); + } else { + $project->save(); + $project->savePost(); + Brizy_Editor::get()->lockProject(); + do_action( 'brizy_global_data_updated' ); + } + + $this->success( $project->createResponse() ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( 400, $exception->getMessage() ); + exit; + } + } + + /** + * @internal + **/ + public function get_item() { + try { + $this->verifyNonce( self::nonce ); + + if ( ! $this->post ) { + throw new Exception( 'Invalid post provided' ); + } + + $data = $this->post->createResponse(); + $data['is_index'] = true; + + $this->success( array( $data ) ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( 500, $exception->getMessage() ); + exit; + } + } + + /** + * @internal + **/ + public function get_post_info() { + try { + $this->verifyNonce( self::nonce ); + + $postId = (int) $this->param( 'post_id' ); + $defaultFields = [ 'ID', 'post_title', 'post_content' ]; + $post_fields = array_intersect( (array) $this->param( 'fields' ), $defaultFields ); + + if ( count( $post_fields ) == 0 ) { + $post_fields = $defaultFields; + } + + if ( ! $postId ) { + $this->error( 400, 'Invalid post id' ); + } + + $post = get_post( $postId, ARRAY_A ); + + if ( ! $post ) { + $this->error( 404, 'Invalid post id' ); + } + + $data = array_intersect_key( $post, array_flip( $defaultFields ) ); + + $this->success( $data ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( 500, $exception->getMessage() ); + exit; + } + } + + /** + * @internal + **/ + public function update_item() { + try { + $this->verifyNonce( self::nonce ); + + $data = stripslashes( $this->param( 'data' ) ); + $atemplate = $this->param( 'template' ); + $dataVersion = (int) stripslashes( $this->param( 'dataVersion' ) ); + $status = stripslashes( $this->param( 'status' ) ); + + if ( ! in_array( $status, [ 'publish', 'draft', 'pending', 'private', 'future' ] ) ) { + $this->error( 400, "Invalid post type" ); + } + + if ( $atemplate ) { + $this->post->set_template( $atemplate ); + } + + if ( $data ) { + $this->post->set_editor_data( $data ); + $this->post->set_editor_version( BRIZY_EDITOR_VERSION ); + $this->post->set_needs_compile( true ); + } + + $this->post->getWpPost()->post_status = $status; + + if ( (int) $this->param( 'is_autosave' ) == 1 ) { + $this->post->save( 1 ); + } else { + $this->post->setDataVersion( $dataVersion ); + $this->post->setLastUserEdited( get_current_user_id() ); + $this->post->save( 0 ); + $this->post->savePost( true ); + } + + $this->success( $this->post->createResponse() ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( 500, $exception->getMessage() ); + } + } + + /* + * Used for elements like Woocommerce pages. + */ + public function shortcode_content() { + try { + + $this->verifyNonce( self::nonce ); + + if ( isset( $_REQUEST['shortcode'] ) ) { + $shortcode = stripslashes( $_REQUEST['shortcode'] ); + } else { + throw new Exception( 'Shortcode string not provided.', 500 ); + } + + $shortcode_content = do_shortcode( $shortcode ); + + $this->success( + array( + 'shortcode' => $shortcode_content, + ) + ); + + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( $exception->getCode(), $exception->getMessage() ); + } + } + + public function placeholder_content() { + try { + $this->verifyNonce( self::nonce ); + $postId = $this->param( 'post_id' ); + $placeholders = $this->param( 'placeholders' ); + + if ( ! $placeholders ) { + throw new Exception( 'Placeholder string not provided.', 400 ); + } + + global $post, $wp_query; + + $post = $this->getPostSample( $postId ); + + if ( $post instanceof WP_Post ) { + setup_postdata( $post ); + $wp_query->is_single = true; + + if ( function_exists( 'wc_get_product' ) ) { + global $product; + + $product = wc_get_product( $post->ID ); + } + } + + $contents = []; + foreach ( $placeholders as $placeholder ) { + $placeholder = stripslashes( $placeholder ); + $contents[] = apply_filters( 'brizy_content', $placeholder, Brizy_Editor_Project::get(), $post ); + } + + $this->success( array( 'placeholders' => $contents ) ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + $this->error( $exception->getCode(), $exception->getMessage() ); + } + } + + public function placeholders_content() { + global $post, $wp_query; + + $this->verifyNonce( self::nonce ); + $posts = $this->param( 'p' ); + $contents = []; + foreach ( $posts as $postId => $placeholders ) { + + $post = $this->getPostSample( $postId ); + $contents[ $postId ] = []; + + if ( $post instanceof WP_Post ) { + setup_postdata( $post ); + $wp_query->is_single = true; + } + foreach ( $placeholders as $placeholder ) { + try { + $placeholder = stripslashes( $placeholder ); + $contents[ $postId ][] = apply_filters( + 'brizy_content', + $placeholder, + Brizy_Editor_Project::get(), + $post + ); + } catch ( Exception $exception ) { + Brizy_Logger::instance()->exception( $exception ); + continue; + } + } + + + } + $this->success( + array( + 'placeholders' => $contents, + ) + ); + + } + + private function getPostSample( $templateId ) { + global $wp_query; + $wp_post = get_post( $templateId ); + if ( $wp_post->post_type !== Brizy_Admin_Templates::CP_TEMPLATE ) { + return $wp_post; + } + + + $ruleManager = new Brizy_Admin_Rules_Manager(); + $rules = $ruleManager->getRules( $wp_post->ID ); + $rule = null; + + // find first include rule + foreach ( $rules as $rule ) { + /** + * @var Brizy_Admin_Rule $rule ; + */ + if ( $rule->getType() == Brizy_Admin_Rule::TYPE_INCLUDE ) { + break; + } + } + + if ( $rule ) { + switch ( $rule->getAppliedFor() ) { + case Brizy_Admin_Rule::POSTS : + $args = [ + 'fields' => 'ids', + 'post_type' => $rule->getEntityType(), + 'posts_per_page' => - 1, + 'meta_query' => [ + [ + 'key' => Brizy_Editor_Constants::BRIZY_ENABLED, + 'compare' => 'NOT EXISTS', + ], + ], + ]; + + $values = $rule->getEntityValues(); + $posts = []; + if ( empty( $values[0] ) ) { + // For All condition + $posts = get_posts( $args ); + } else { + $filter = $values[0]; + + if ( is_numeric( $filter ) ) { + $args['post__in'] = [ $filter ]; } else { + // $filter = in|category|12 OR in|genre|48 OR in|category|45 OR author|2 + $explode = explode( '|', $filter ); + + if ( $explode[0] === 'in' ) { + $args['tax_query'] = [ + [ + 'taxonomy' => $explode[1], + 'terms' => $explode[2], + ], + ]; + } else { + $args['author'] = $explode[1]; + } + } + + $posts = get_posts( $args ); + } + + if ( $post = array_pop( $posts ) ) { + return get_post( $post ); + } else { + return $wp_post; + } + + case Brizy_Admin_Rule::TAXONOMY : + $args = array( + 'taxonomy' => $rule->getEntityType(), + 'hide_empty' => true, + ); + + if ( count( $rule->getEntityValues() ) ) { + $args['term_taxonomy_id'] = $rule->getEntityValues(); + } + + $terms = get_terms( $args ); + $term = array_pop( $terms ); + + if ( $term ) { + $wp_query = new WP_Query( + [ + 'tax_query' => [ + [ + 'taxonomy' => $rule->getEntityType(), + 'field' => 'term_id', + 'terms' => $term->term_id, + ], + ], + ] + ); + + $wp_query->is_tax = true; + } + + + return array_pop( $terms ); + + case Brizy_Admin_Rule::WOO_SHOP_PAGE : + $wp_query = new WP_Query( [ 'post_type' => 'product', 'fields' => 'ids' ] ); + if ( function_exists( 'wc_get_page_id' ) && wc_get_page_id( 'shop' ) ) { + return get_post( wc_get_page_id( 'shop' ) ); + } + break; + case Brizy_Admin_Rule::ARCHIVE : + if ( $rule->getEntityType() == 'product' ) { + $wp_query = new WP_Query( [ 'post_type' => 'product', 'fields' => 'ids' ] ); + $posts = $wp_query->get_posts(); + + return get_post( array_pop( $posts ) ); + } + $posts = $wp_query->get_posts(); + + return get_post( array_pop( $posts ) );; + case Brizy_Admin_Rule::TEMPLATE : + + switch ( $rule->getEntityType() ) { + case 'author': + $authors = get_users(); + $wp_query = new WP_Query( + [ 'author_name' => get_userdata( get_current_user_id() )->data->user_nicename ] + ); + $wp_query->is_author = true; + + return array_pop( $authors ); + + + case '404': + $wp_query->is_404 = true; + + return null; + case 'search': + $wp_query->is_search = true; + + return null; + + case 'home_page': + $get_option = get_option( 'page_for_posts' ); + + if ( $get_option ) { + return get_post( $get_option ); + } + break; + case 'front_page': + $get_option = get_option( 'page_on_front' ); + + if ( $get_option ) { + return get_post( $get_option ); + } + break; + } + + break; + case Brizy_Admin_Rule::YEAR_ARCHIVE: + + $wp_query = new WP_Query( 'year=' . date( 'Y' ) ); + $wp_query->is_year = true; + + return null; + case Brizy_Admin_Rule::MONTH_ARCHIVE: + + $wp_query = new WP_Query( 'year=' . date( 'Y' ) . '&monthnum=' . date( 'm' ) ); + $wp_query->is_month = true; + return null; + case Brizy_Admin_Rule::DAY_ARCHIVE: - $filter = $values[0]; - - if (is_numeric($filter)) { - $args['post__in'] = [$filter]; - } else { - // $filter = in|category|12 OR in|genre|48 OR in|category|45 OR author|2 - $explode = explode('|', $filter); - - if ($explode[0] === 'in') { - $args['tax_query'] = [ - [ - 'taxonomy' => $explode[1], - 'terms' => $explode[2], - ], - ]; - } else { - $args['author'] = $explode[1]; - } - } - - $posts = get_posts($args); - } - - if ($post = array_pop($posts)) { - return get_post($post); - } else { - return $wp_post; - } - - case Brizy_Admin_Rule::TAXONOMY : - $args = array( - 'taxonomy' => $rule->getEntityType(), - 'hide_empty' => true, - ); - - if (count($rule->getEntityValues())) { - $args['term_taxonomy_id'] = $rule->getEntityValues(); - } - - $terms = get_terms($args); - $term = array_pop($terms); - - if ($term) { - $wp_query = new WP_Query( - [ - 'tax_query' => [ - [ - 'taxonomy' => $rule->getEntityType(), - 'field' => 'term_id', - 'terms' => $term->term_id, - ], - ], - ] - ); - - $wp_query->is_tax = true; - } - - return array_pop($terms); - - case Brizy_Admin_Rule::WOO_SHOP_PAGE : - $wp_query = new WP_Query(['post_type' => 'product', 'fields' => 'ids']); - if (function_exists('wc_get_page_id') && wc_get_page_id('shop')) { - return get_post(wc_get_page_id('shop')); - } - break; - case Brizy_Admin_Rule::ARCHIVE : - if ($rule->getEntityType() == 'product') { - $wp_query = new WP_Query(['post_type' => 'product', 'fields' => 'ids']); - $posts = $wp_query->get_posts(); - - return get_post(array_pop($posts)); - } - $posts = $wp_query->get_posts(); - - return get_post(array_pop($posts));; - case Brizy_Admin_Rule::TEMPLATE : - - switch ($rule->getEntityType()) { - case 'author': - $authors = get_users(); - $wp_query = new WP_Query( - ['author_name' => get_userdata(get_current_user_id())->data->user_nicename] - ); - $wp_query->is_author = true; - - return array_pop($authors); - - - case '404': - $wp_query->is_404 = true; - - return null; - case 'search': - $wp_query->is_search = true; - - return null; - - case 'home_page': - $get_option = get_option('page_for_posts'); - - if ($get_option) { - return get_post($get_option); - } - break; - case 'front_page': - $get_option = get_option('page_on_front'); - - if ($get_option) { - return get_post($get_option); - } - break; - } - - break; - case Brizy_Admin_Rule::YEAR_ARCHIVE: - - $wp_query = new WP_Query('year='.date('Y')); - $wp_query->is_year = true; + $wp_query = new WP_Query( 'year=' . date( 'Y' ) . '&monthnum=' . date( 'm' ) . '&day=' . date( 'd' ) ); + $wp_query->is_day = true; - return null; - case Brizy_Admin_Rule::MONTH_ARCHIVE: + return null; + } + } + } - $wp_query = new WP_Query('year='.date('Y').'&monthnum='.date('m')); - $wp_query->is_month = true; + public function get_post_objects() { - return null; - case Brizy_Admin_Rule::DAY_ARCHIVE: + global $wp_post_types; + $this->verifyNonce( self::nonce ); - $wp_query = new WP_Query('year='.date('Y').'&monthnum='.date('m').'&day='.date('d')); - $wp_query->is_day = true; + $searchTerm = $this->param( 'filterTerm' ); + $postType = $this->param( 'postType' ) ? $this->param( 'postType' ) : null; + $excludePostType = $this->param( 'excludePostTypes' ) ? $this->param( 'excludePostTypes' ) : array(); - return null; - } - } - } + if ( ! $postType ) { + $postType = array_keys( + array_filter( + $wp_post_types, + function ( $type ) { + return ! in_array( $type->name, array( 'brizy_template' ) ) && $type->show_ui; + } + ) + ); + } - public function get_post_objects() - { + add_filter( 'posts_where', array( $this, 'brizy_post_title_filter' ), 10, 2 ); + $posts = Brizy_Editor_Post::get_post_list( $searchTerm, $postType, $excludePostType, 0, 10000 ); + remove_filter( 'posts_where', array( $this, 'brizy_post_title_filter' ), 10 ); - global $wp_post_types; - $this->verifyNonce(self::nonce); + $this->success( array( 'filter_term' => $searchTerm, 'posts' => $posts ) ); + } - $searchTerm = $this->param('filterTerm'); - $postType = $this->param('postType') ? $this->param('postType') : null; - $excludePostType = $this->param('excludePostTypes') ? $this->param('excludePostTypes') : array(); + public function get_sidebars() { + global $wp_registered_sidebars; - if ( ! $postType) { - $postType = array_keys( - array_filter( - $wp_post_types, - function ($type) { - return ! in_array($type->name, array('brizy_template')) && $type->show_ui; - } - ) - ); - } + $this->verifyNonce( self::nonce ); - add_filter('posts_where', array($this, 'brizy_post_title_filter'), 10, 2); - $posts = Brizy_Editor_Post::get_post_list($searchTerm, $postType, $excludePostType, 0, 10000); - remove_filter('posts_where', array($this, 'brizy_post_title_filter'), 10); + $items = array(); - $this->success(array('filter_term' => $searchTerm, 'posts' => $posts)); - } + foreach ( $wp_registered_sidebars as $sidebar ) { + $item = array( + 'id' => $sidebar['id'], + 'title' => $sidebar['name'], + ); + $items[] = $item; + } - public function get_sidebars() - { - global $wp_registered_sidebars; + $this->success( $items ); + } - $this->verifyNonce(self::nonce); + public function brizy_post_title_filter( $where, $wp_query = null ) { - $items = array(); + global $wpdb; - foreach ($wp_registered_sidebars as $sidebar) { - $item = array( - 'id' => $sidebar['id'], - 'title' => $sidebar['name'], - ); - $items[] = $item; - } - $this->success($items); - } + if ( $wp_query instanceof WP_Query && $term = $wp_query->get( 'post_title_term' ) ) { + $search_term = $wpdb->esc_like( $term ); + $search_term = ' \'%' . $search_term . '%\''; - public function brizy_post_title_filter($where, $wp_query = null) - { + $where .= ' AND ' . $wpdb->posts . '.post_title LIKE ' . $search_term; + } + + return $where; + } + + public function get_menu_list() { + $this->success( wp_get_nav_menus( array( 'hide_empty' => true ) ), 200 ); + } + + /** + * Used in woocomerce producs, block conditions + */ + public function get_terms() { + + try { + $this->verifyNonce( self::nonce ); + + $taxonomy = $this->param( 'taxonomy' ); + + $terms = (array) get_terms( array( 'taxonomy' => $taxonomy, 'hide_empty' => false ) ); + + $this->success( array_values( $terms ) ); + + } catch ( Exception $e ) { + Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] ); + $this->error( 500, $e->getMessage() ); + } + } + + /** + * Used in posts filter element + */ + public function get_terms_by() { + + $this->verifyNonce( self::nonce ); + + $args = []; + + foreach ( [ 'taxonomy', 'search', 'include' ] as $field ) { + $value = $this->param( $field ); + if ( ! empty( $value ) ) { + $args[ $field ] = $value; + } + } + + $terms = get_terms( $args ); + + if ( is_wp_error( $terms ) ) { + $this->error( 200, $terms ); + } + + + $out = []; + foreach ( $terms as $term ) { + $out[] = [ + 'term_id' => $term->term_id, + 'name' => $term->name, + 'taxonomy' => $term->taxonomy, + 'taxonomy_name' => get_taxonomy( $term->taxonomy )->labels->singular_name, + ]; + } + + $this->success( $out ); + } + + /** + * Used in posts filter element + */ + public function search_post() { + $this->verifyNonce( self::nonce ); + $args = [ 'numberposts' => - 1 ]; + $args['post_type'] = array_values( get_post_types( [ 'public' => true ] ) ); + + // exclude attachments + if ( ( $key = array_search( 'attachment', $args['post_type'] ) ) !== false ) { + unset( $args['post_type'][ $key ] ); + } + + // se post types + if ( $requiredTypes = $this->param( 'post_type' ) ) { + if ( is_string( $requiredTypes ) ) { + $args['post_type'] = [ $requiredTypes ]; + } else { + $args['post_type'] = $requiredTypes; + } + } + + // exclude post types + if ( $excludeTypes = $this->param( 'exclude_post_type' ) ) { + if ( is_string( $excludeTypes ) ) { + if ( ( $key = array_search( $excludeTypes, $args['post_type'] ) ) !== false ) { + unset( $args['post_type'][ $key ] ); + } + } else { + $args['post_type'] = array_diff( $args['post_type'], $excludeTypes ); + } + } + + // include posts by id + if ( $this->param( 'include' ) ) { + $args['post__in'] = $this->param( 'include' ); + } elseif ( $this->param( 'search' ) /*&& strlen($this->param('search')) >= 3*/ ) { + $args['s'] = $this->param( 'search' ); + } else { + $this->success( [] ); + } + + $posts = get_posts( $args ); + + if ( is_wp_error( $posts ) ) { + $this->error( 200, $posts ); + } + + $out = []; + foreach ( $posts as $post ) { + $pt = get_post_type_object( $post->post_type ); + $out[] = [ + 'ID' => $post->ID, + 'title' => $post->post_title, + 'permalink' => "{{brizy_dc_permalink post_id=\"{$post->ID}\"}}", + 'postType' => [ + 'type' => $post->post_type, + 'singular_name' => $pt->labels->singular_name, + 'name' => $pt->labels->name + ] + ]; + } + + $this->success( $out ); + } + + public function get_users() { + $this->verifyNonce( self::nonce ); + + $args = []; + $search = $this->param( 'search' ); + $include = $this->param( 'include' ); + + $args['fields'] = $this->param( 'fields' ) ? $this->param( 'fields' ) : [ 'ID', 'display_name' ]; + + if ( $this->param( 'roles' ) && is_array( $this->param( 'roles' ) ) ) { + $args['role__in'] = $this->param( 'roles' ); + } + + if ( ! empty( $search ) ) { + $args['search'] = '*' . $search . '*'; + $args['search_columns'] = [ 'display_name' ]; + } + + if ( is_array( $include ) && ! empty( $include ) ) { + $args['include'] = $include; + } + + $users = get_users( $args ); + + $users = array_map( + function ( $user ) { + $user->ID = (int) $user->ID; + + return $user; + }, + $users + ); + + $this->success( $users ); + } + + public function get_media_key() { + try { + session_write_close(); + $this->verifyNonce( self::nonce ); + $apost = (int) $_REQUEST['post_id']; + $attachment_id = (int) $_REQUEST['attachment_id']; + + if ( ! $attachment_id || get_post_status( $attachment_id ) === false ) { + $this->error( 400, 'Invalid attachment id' ); + } + $uid = $this->createMediaKey( $apost, $attachment_id ); + + $this->success( array( 'uid' => $uid ) ); + + } catch ( Exception $e ) { + Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] ); + + return; + } + } + + /** + * @see Brizy_Admin_Migrations_AttachmentUidMigration + */ + public function get_attachment_key() { + try { + session_write_close(); + + $this->verifyNonce( self::nonce ); + $attachmentId = isset( $_REQUEST['attachment_id'] ) ? (int) $_REQUEST['attachment_id'] : null; + + if ( ! $attachmentId || get_post_status( $attachmentId ) === false ) { + $this->error( 400, 'Invalid attachment id' ); + } + + $uid = get_post_meta( $attachmentId, 'brizy_post_uid', true ); - global $wpdb; + if ( ! $uid ) { + $file = get_attached_file( $attachmentId ); + $path_parts = pathinfo( $file ); + $uid = "wp-" . md5( $attachmentId . time() ) . '.' . $path_parts['extension']; + // this is a bit wrong as the attachment is attached to itself + // (we used brizy_post_uid to mark the attachments as attached to the post with uid in this key) + // we also migrated the attachment that does not have brizy_attachment_uid meta and + // does have only brizy_post_uid meta: see the Brizy_Admin_Migrations_AttachmentUidMigration class + update_post_meta( $attachmentId, 'brizy_post_uid', $uid ); + + // we added this here as the correct way to create a brizy_attachment_uid key + update_post_meta( $attachmentId, 'brizy_attachment_uid', $uid ); + } - if ($wp_query instanceof WP_Query && $term = $wp_query->get('post_title_term')) { - $search_term = $wpdb->esc_like($term); - $search_term = ' \'%'.$search_term.'%\''; - - $where .= ' AND '.$wpdb->posts.'.post_title LIKE '.$search_term; - } - - return $where; - } - - public function get_menu_list() - { - $this->success(wp_get_nav_menus(array('hide_empty' => true)), 200); - } - - /** - * Used in woocomerce producs, block conditions - */ - public function get_terms() - { - - try { - $this->verifyNonce(self::nonce); - - $taxonomy = $this->param('taxonomy'); - - $terms = (array)get_terms(array('taxonomy' => $taxonomy, 'hide_empty' => false)); - - $this->success(array_values($terms)); - - } catch (Exception $e) { - Brizy_Logger::instance()->error($e->getMessage(), [$e]); - $this->error(500, $e->getMessage()); - } - } - - /** - * Used in posts filter element - */ - public function get_terms_by() - { - - $this->verifyNonce(self::nonce); - - $args = []; - - foreach (['taxonomy', 'search', 'include'] as $field) { - $value = $this->param($field); - if ( ! empty($value)) { - $args[$field] = $value; - } - } - - $terms = get_terms($args); - - if (is_wp_error($terms)) { - $this->error(200, $terms); - } - - - $out = []; - foreach ($terms as $term) { - $out[] = [ - 'term_id' => $term->term_id, - 'name' => $term->name, - 'taxonomy' => $term->taxonomy, - 'taxonomy_name' => get_taxonomy($term->taxonomy)->labels->singular_name, - ]; - } - - $this->success($out); - } - - /** - * Used in posts filter element - */ - public function search_post() - { - $this->verifyNonce(self::nonce); - $args = ['numberposts' => -1]; - $args['post_type'] = array_values(get_post_types(['public' => true])); - - // exclude attachments - if (($key = array_search('attachment', $args['post_type'])) !== false) { - unset($args['post_type'][$key]); - } - - // se post types - if ($requiredTypes = $this->param('post_type')) { - if (is_string($requiredTypes)) { - $args['post_type'] = [$requiredTypes]; - } else { - $args['post_type'] = $requiredTypes; - } - } - - // exclude post types - if ($excludeTypes = $this->param('exclude_post_type')) { - if (is_string($excludeTypes)) { - if (($key = array_search($excludeTypes, $args['post_type'])) !== false) { - unset($args['post_type'][$key]); - } - } else { - $args['post_type'] = array_diff($args['post_type'], $excludeTypes); - } - } - - // include posts by id - if ($this->param('include')) { - $args['post__in'] = $this->param('include'); - } elseif ($this->param('search') /*&& strlen($this->param('search')) >= 3*/) { - $args['s'] = $this->param('search'); - } else { - $this->success([]); - } - - $posts = get_posts($args); - - if (is_wp_error($posts)) { - $this->error(200, $posts); - } - - $out = []; - foreach ($posts as $post) { - $pt = get_post_type_object( $post->post_type ); - $out[] = [ - 'ID' => $post->ID, - 'title' => $post->post_title, - 'permalink'=>"{{brizy_dc_permalink post_id=\"{$post->ID}\"}}", - 'postType' => [ 'type' => $post->post_type, - 'singular_name' => $pt->labels->singular_name, - 'name' => $pt->labels->name - ] - ]; - } - - $this->success($out); - } - - public function get_users() - { - $this->verifyNonce(self::nonce); - - $args = []; - $search = $this->param('search'); - $include = $this->param('include'); - - $args['fields'] = $this->param('fields') ? $this->param('fields') : ['ID', 'display_name']; - - if ($this->param('roles') && is_array($this->param('roles'))) { - $args['role__in'] = $this->param('roles'); - } - - if ( ! empty($search)) { - $args['search'] = '*'.$search.'*'; - $args['search_columns'] = ['display_name']; - } - - if (is_array($include) && ! empty($include)) { - $args['include'] = $include; - } - - $users = get_users($args); - - $users = array_map( - function ($user) { - $user->ID = (int)$user->ID; - - return $user; - }, - $users - ); - - $this->success($users); - } - - public function get_media_key() - { - try { - session_write_close(); - $this->verifyNonce(self::nonce); - $apost = (int)$_REQUEST['post_id']; - $attachment_id = (int)$_REQUEST['attachment_id']; - - if ( ! $attachment_id || get_post_status($attachment_id) === false) { - $this->error(400, 'Invalid attachment id'); - } - $uid = $this->createMediaKey($apost, $attachment_id); - - $this->success(array('uid' => $uid)); - - } catch (Exception $e) { - Brizy_Logger::instance()->error($e->getMessage(), [$e]); - - return; - } - } - - /** - * @see Brizy_Admin_Migrations_AttachmentUidMigration - */ - public function get_attachment_key() - { - try { - session_write_close(); - - $this->verifyNonce(self::nonce); - $attachmentId = isset($_REQUEST['attachment_id']) ? (int)$_REQUEST['attachment_id'] : null; - - if ( ! $attachmentId || get_post_status($attachmentId) === false) { - $this->error(400, 'Invalid attachment id'); - } - - $uid = get_post_meta($attachmentId, 'brizy_post_uid', true); - - if ( ! $uid) { - $file = get_attached_file($attachmentId); - $path_parts = pathinfo($file); - $uid = "wp-".md5($attachmentId.time()).'.'.$path_parts['extension']; - - // this is a bit wrong as the attachment is attached to itself - // (we used brizy_post_uid to mark the attachments as attached to the post with uid in this key) - // we also migrated the attachment that does not have brizy_attachment_uid meta and - // does have only brizy_post_uid meta: see the Brizy_Admin_Migrations_AttachmentUidMigration class - update_post_meta($attachmentId, 'brizy_post_uid', $uid); - - // we added this here as the correct way to create a brizy_attachment_uid key - update_post_meta($attachmentId, 'brizy_attachment_uid', $uid); - } - - $this->success(array('uid' => $uid)); + $this->success( array( 'uid' => $uid ) ); - } catch (Exception $e) { - Brizy_Logger::instance()->error($e->getMessage(), [$e]); + } catch ( Exception $e ) { + Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] ); - return; - } - } + return; + } + } - public function setTemplateType() - { - try { + public function setTemplateType() { + try { - $this->verifyNonce(self::nonce); - $templateId = $this->param('template_id'); - $templateType = $this->param('template_type'); + $this->verifyNonce( self::nonce ); + $templateId = $this->param( 'template_id' ); + $templateType = $this->param( 'template_type' ); - if (get_post_type($templateId) != Brizy_Admin_Templates::CP_TEMPLATE) { - $this->error(400, 'Invalid template'); - } + if ( get_post_type( $templateId ) != Brizy_Admin_Templates::CP_TEMPLATE ) { + $this->error( 400, 'Invalid template' ); + } - $allowedTypes = [ - Brizy_Admin_Templates::TYPE_SINGLE, - Brizy_Admin_Templates::TYPE_ARCHIVE, - Brizy_Admin_Templates::TYPE_SINGLE_PRODUCT, - Brizy_Admin_Templates::TYPE_PRODUCT_ARCHIVE, - ]; + $allowedTypes = [ + Brizy_Admin_Templates::TYPE_SINGLE, + Brizy_Admin_Templates::TYPE_ARCHIVE, + Brizy_Admin_Templates::TYPE_SINGLE_PRODUCT, + Brizy_Admin_Templates::TYPE_PRODUCT_ARCHIVE, + ]; - if ( ! in_array($templateType, $allowedTypes, true)) { - $this->error(400, 'Invalid template type'); - } + if ( ! in_array( $templateType, $allowedTypes, true ) ) { + $this->error( 400, 'Invalid template type' ); + } - update_post_meta($templateId, Brizy_Admin_Templates::TEMPLATE_TYPE_KEY, $templateType); + update_post_meta( $templateId, Brizy_Admin_Templates::TEMPLATE_TYPE_KEY, $templateType ); - $this->success([]); + $this->success( [] ); - } catch (Exception $e) { - Brizy_Logger::instance()->error($e->getMessage(), [$e]); - $this->error(500, $e->getMessage()); + } catch ( Exception $e ) { + Brizy_Logger::instance()->error( $e->getMessage(), [ $e ] ); + $this->error( 500, $e->getMessage() ); - return; - } - } + return; + } + } - private function createMediaKey($postId, $attachmentId) - { - $uid = get_post_meta($attachmentId, 'brizy_attachment_uid', true); + private function createMediaKey( $postId, $attachmentId ) { + $uid = get_post_meta( $attachmentId, 'brizy_attachment_uid', true ); - if ( ! $uid) { - $file = get_attached_file($attachmentId); - $path_parts = pathinfo($file); - $uid = "wp-".md5($attachmentId.time()).'.'.$path_parts['extension']; - update_post_meta($attachmentId, 'brizy_attachment_uid', $uid); - } + if ( ! $uid ) { + $file = get_attached_file( $attachmentId ); + $path_parts = pathinfo( $file ); + $uid = "wp-" . md5( $attachmentId . time() ) . '.' . $path_parts['extension']; + update_post_meta( $attachmentId, 'brizy_attachment_uid', $uid ); + } - if ($postId) { - $post = Brizy_Editor_Post::get($postId); - $post_ui = $post->getUid(); + if ( $postId ) { + $post = Brizy_Editor_Post::get( $postId ); + $post_ui = $post->getUid(); - $post_uids = get_post_meta($attachmentId, 'brizy_post_uid'); + $post_uids = get_post_meta( $attachmentId, 'brizy_post_uid' ); - if ( ! in_array($post_ui, $post_uids)) { - add_post_meta($attachmentId, 'brizy_post_uid', $post_ui); - } - } + if ( ! in_array( $post_ui, $post_uids ) ) { + add_post_meta( $attachmentId, 'brizy_post_uid', $post_ui ); + } + } - return $uid; - } + return $uid; + } } From 12fe07785afb3e1ae86996710643a117e9154d60 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 23 May 2022 13:28:55 +0300 Subject: [PATCH 29/44] fix: dynamic content processor --- content/dynamic-content-processor.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/content/dynamic-content-processor.php b/content/dynamic-content-processor.php index 97120c3600..8086cd426f 100644 --- a/content/dynamic-content-processor.php +++ b/content/dynamic-content-processor.php @@ -34,9 +34,9 @@ public function process($targetContent, Brizy_Content_Context $context) /** * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders ; */ - list($newContentPlaceholders, $placeholderInstances, $newPostContent) = $extractor->extract($postContent); + list($newContentPlaceholders, $newPlaceholderInstances, $newPostContent) = $extractor->extract($postContent); - $context->afterExtract($newContentPlaceholders, $placeholderInstances, $newPostContent); + $context->afterExtract($newContentPlaceholders, $newPlaceholderInstances, $newPostContent); } $replacer = new Replacer($placeholderProvider); From 5b5f0e5cf46a795f64b7c1f7ff8b548fb4b8c25c Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 9 Jun 2022 15:54:09 +0300 Subject: [PATCH 30/44] fix: compile page when asking for a placeholder html --- content/dynamic-content-processor.php | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/content/dynamic-content-processor.php b/content/dynamic-content-processor.php index 8086cd426f..8062e16792 100644 --- a/content/dynamic-content-processor.php +++ b/content/dynamic-content-processor.php @@ -54,13 +54,18 @@ public function process($targetContent, Brizy_Content_Context $context) private function getBrizyPostContent(Brizy_Editor_Project $project, Brizy_Editor_Post $post) { + if($post->get_needs_compile()) + { + $post->compile_page(); + } + if ( ! $post->get_compiled_html()) { $compiled_html_body = $post->get_compiled_html_body(); $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); $post->set_needs_compile(true)->saveStorage(); } else { $compiled_page = $post->get_compiled_page(); - $content = $compiled_page->get_body(); + $content = $compiled_page->getBody(); } return $content; From dd0d30c87deadee60af1bfbb97fe3096f402c92c Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Mon, 13 Jun 2022 17:09:24 +0300 Subject: [PATCH 31/44] fix: small fix when wrong placeholder id is required --- editor/filters/api.php | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/editor/filters/api.php b/editor/filters/api.php index 821c7d60f9..7f2993d527 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -46,7 +46,10 @@ public function filterPlaceholdersContent() { */ $placeholder = $context->getPlaceholderById($placeholderId); - if(!$placeholder) continue; + if(!$placeholder) { + $placeholderContents[$placeholderId] = ''; + continue; + } /** * @var Brizy_Content_Placeholders_Abstract $placeholderInstance; From fa27af672eb6c35eff4ffb72394aa10f74b31f1b Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 23 Jun 2022 09:53:03 +0300 Subject: [PATCH 32/44] fix: use $_REQUEST instead if $_POST --- editor.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/editor.php b/editor.php index c185d0c4f7..608a6e1149 100755 --- a/editor.php +++ b/editor.php @@ -426,7 +426,7 @@ function currentPostId() $pid = (int)$_REQUEST['page_id']; } elseif (isset($_REQUEST['post_ID'])) { - $pid = (int)$_POST['post_ID']; + $pid = (int)$_REQUEST['post_ID']; } elseif (isset($_REQUEST['id'])) { $pid = (int)$_REQUEST['id']; From 950c783a07e8be462fb3704e3b379e5fca4858c3 Mon Sep 17 00:00:00 2001 From: Viorel Date: Tue, 26 Jul 2022 10:52:46 +0300 Subject: [PATCH 33/44] Fix: #19185 - Fix condition modal editor by global rules --- admin/rules/api.php | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/admin/rules/api.php b/admin/rules/api.php index bc9f2cd528..da4529362c 100644 --- a/admin/rules/api.php +++ b/admin/rules/api.php @@ -342,7 +342,7 @@ public function getGroupList() { $groups = []; - if ( $templateType == 'single' || $templateType == 'single_product' || $context == 'popup-rules' || $context == 'global-block-rules' ) { + if ($templateType == 'single' || $templateType == 'single_product' || $context == 'popup-rules' || $context == 'global-block-rules' ) { $groups[] = array( 'title' => 'Main Content', 'value' => Brizy_Admin_Rule::POSTS, @@ -360,7 +360,7 @@ public function getGroupList() { ) : null; } - if ( $templateType == 'archive' || $templateType == 'product_archive' || $context == 'popup-rules' || $context == 'global-block-rules' ) { + if ($templateType == 'archive' || $templateType == 'product_archive' || $context == 'popup-rules' || $context == 'global-block-rules' ) { $archiveItems = array_map( $closure, $this->getArchivesList( Brizy_Admin_Rule::ARCHIVE, $templateType ) ); $taxonomyItems = array_map( $closure, $this->getTaxonomyList( Brizy_Admin_Rule::TAXONOMY, $templateType ) ); From 29c9667533382d75c837346de8d14cc87caf402d Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Tue, 9 Aug 2022 16:00:54 +0300 Subject: [PATCH 34/44] fix: filter refactoring --- content/placeholders/abstract.php | 2 +- editor/filters/api.php | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/content/placeholders/abstract.php b/content/placeholders/abstract.php index f6db12d66d..4f159381bc 100644 --- a/content/placeholders/abstract.php +++ b/content/placeholders/abstract.php @@ -67,7 +67,7 @@ public function support($placeholderName) public function shouldFallbackValue($value, ContextInterface $context, ContentPlaceholder $placeholder) { - return is_null($value) || $value==""; + return is_null($value) || $value===""; } public function getFallbackValue(ContextInterface $context, ContentPlaceholder $placeholder) diff --git a/editor/filters/api.php b/editor/filters/api.php index 7f2993d527..a8435cfaf6 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -28,7 +28,7 @@ public function filterPlaceholdersContent() { $brizyPost = Brizy_Editor_Post::get($postId); $postContent = $this->getBrizyPostContent(Brizy_Editor_Project::get(), $brizyPost); - $placeholderProvider = new Brizy_Content_PlaceholderProvider(); + $placeholderProvider = new Brizy_Content_PlaceholderProvider(); $context = new Brizy_Content_Context(Brizy_Editor_Project::get(),$brizyPost,$brizyPost->getWpPost(),''); $context->setProvider( $placeholderProvider ); $extractor = new \BrizyPlaceholders\Extractor( $placeholderProvider ); From bc7ba18d991ac9f848db9fa55376b483fa424863 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Thu, 22 Sep 2022 09:48:44 +0300 Subject: [PATCH 35/44] fix: Config values in dev mode 2 --- config.dev.php | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/config.dev.php b/config.dev.php index 0c472a8b39..3ebef1dc77 100755 --- a/config.dev.php +++ b/config.dev.php @@ -47,7 +47,7 @@ class Brizy_Config { const CLOUD_LAYOUTS = '/api/layouts'; const CLOUD_SCREENSHOT = '/screenshot/%s'; const CLOUD_SCREENSHOTS = '/api/screenshots'; - const CLOUD_CUSTOM_FILES = '/api/custom_files'; + const CLOUD_CUSTOM_FILES = '/api/custom_files'; const WP_HTTP_TIMEOUT = 600; static public function getCompilerUrls() { From cedbc9d10020eae0ee0b833f123e767fc355d964 Mon Sep 17 00:00:00 2001 From: Alex Zaharia Date: Fri, 7 Oct 2022 11:57:37 +0300 Subject: [PATCH 36/44] fix: Context factor --- content/context-factory.php | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/content/context-factory.php b/content/context-factory.php index 1b31b8120a..0bedc353ed 100644 --- a/content/context-factory.php +++ b/content/context-factory.php @@ -17,16 +17,16 @@ class Brizy_Content_ContextFactory * * @return Brizy_Content_Context */ - static public function createContext($project = null, $wp_post = null, $parentContext = false) + static public function createContext($project= null, $wp_post = null, $parentContext = false) { - $context = new Brizy_Content_Context($project, null, $wp_post, null, $parentContext ); + $context = new Brizy_Content_Context($project, null, $wp_post, null, $parentContext); if ($wp_post) { - $context->setAuthor( $wp_post->post_author ); - } + $context->setAuthor($wp_post->post_author); + } - return apply_filters( 'brizy_context_create', $context ); - } + return apply_filters('brizy_context_create', $context, $wp_post); + } static public function createEmptyContext() { @@ -58,7 +58,7 @@ private static function getContext($project, $wp_post) { $context = new Brizy_Content_Context($project, $wp_post); - if ($wp_post instanceof WP_Post) { + if ($wp_postinstanceof WP_Post) { $context->setAuthor($wp_post->post_author); } From cc5b834e423148a524d5735b06b8a58dc8d2ec85 Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Tue, 18 Jul 2023 10:09:45 +0300 Subject: [PATCH 37/44] fix: small fixes after rebase. --- content/context-factory.php | 4 +- editor/editor/editor.php | 2742 ++++++++++++++++++----------------- 2 files changed, 1379 insertions(+), 1367 deletions(-) diff --git a/content/context-factory.php b/content/context-factory.php index 0bedc353ed..d4e33aa854 100644 --- a/content/context-factory.php +++ b/content/context-factory.php @@ -17,7 +17,7 @@ class Brizy_Content_ContextFactory * * @return Brizy_Content_Context */ - static public function createContext($project= null, $wp_post = null, $parentContext = false) + static public function createContext($project = null, $wp_post = null, $parentContext = false) { $context = new Brizy_Content_Context($project, null, $wp_post, null, $parentContext); @@ -58,7 +58,7 @@ private static function getContext($project, $wp_post) { $context = new Brizy_Content_Context($project, $wp_post); - if ($wp_postinstanceof WP_Post) { + if ($wp_post instanceof WP_Post) { $context->setAuthor($wp_post->post_author); } diff --git a/editor/editor/editor.php b/editor/editor/editor.php index fd82612007..d5a49cfa60 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -1,523 +1,536 @@ getWpPostId() ? $post->getWpPostId() : 0; + if (isset(self::$insance[$postId])) { + return self::$insance[$postId]; + } - /** - * @var Brizy_Editor_UrlBuilder - */ - private $urlBuilder; + return self::$insance[$postId] = new self($project, $post); + } /** - * @param Brizy_Editor_Project $project - * @param Brizy_Editor_Post $post - * - * @return Brizy_Editor_Editor_Editor - */ - public static function get( Brizy_Editor_Project $project, Brizy_Editor_Post $post ) { - - $postId = $post && $post->getWpPostId() ? $post->getWpPostId() : 0; - if ( isset( self::$insance[ $postId ] ) ) { - return self::$insance[ $postId ]; - } - - return self::$insance[ $postId ] = new self( $project, $post ); - } - - /** - * Brizy_Editor_Editor_Editor constructor. - * - * @param Brizy_Editor_Project $project - * @param Brizy_Editor_Post $post - */ - public function __construct( Brizy_Editor_Project $project, Brizy_Editor_Post $post = null ) { - $this->post = $post; - $this->project = $project; - $this->urlBuilder = new Brizy_Editor_UrlBuilder( $project, $post ? $post->getWpPostId() : null ); - } - - private function getMode( $postType ) { - switch ( $postType ) { - case Brizy_Admin_Stories_Main::CP_STORY: - return 'internal_story'; - case Brizy_Admin_Templates::CP_TEMPLATE: - return 'template'; - case Brizy_Admin_Popups_Main::CP_POPUP: - return 'internal_popup'; - case 'product': - case 'product_variation': - return 'product'; - default: - return 'page'; - } - } - - public function getClientConfig( $editorConfig, $context ) { - if ( !isset($editorConfig['wp']['postLoopSources']) ) { + * Brizy_Editor_Editor_Editor constructor. + * + * @param Brizy_Editor_Project $project + * @param Brizy_Editor_Post $post + */ + public function __construct(Brizy_Editor_Project $project, Brizy_Editor_Post $post = null) + { + $this->post = $post; + $this->project = $project; + $this->urlBuilder = new Brizy_Editor_UrlBuilder($project, $post ? $post->getWpPostId() : null); + } + + private function getMode($postType) + { + switch ($postType) { + case Brizy_Admin_Stories_Main::CP_STORY: + return 'internal_story'; + case Brizy_Admin_Templates::CP_TEMPLATE: + return 'template'; + case Brizy_Admin_Popups_Main::CP_POPUP: + return 'internal_popup'; + case 'product': + case 'product_variation': + return 'product'; + default: + return 'page'; + } + } + + public function getClientConfig($editorConfig, $context) + { + if (!isset($editorConfig['wp']['postLoopSources'])) { throw new \Exception("Unable to locate the \$config['wp']['postLoopSources']"); } - $config = [ - 'hash' => wp_create_nonce( Brizy_Editor_API::nonce ), - 'editorVersion' => BRIZY_EDITOR_VERSION, - 'url' => set_url_scheme( admin_url( 'admin-ajax.php' ) ), - 'actions' => $this->getApiActions(), - 'pageId' => $this->post->getWpPostId(), + $config = [ + 'hash' => wp_create_nonce(Brizy_Editor_API::nonce), + 'editorVersion' => BRIZY_EDITOR_VERSION, + 'url' => set_url_scheme(admin_url('admin-ajax.php')), + 'actions' => $this->getApiActions(), + 'pageId' => $this->post->getWpPostId(), 'collectionTypes' => $editorConfig['wp']['postLoopSources'] ]; - $config = $this->getApiConfigFields( $config, $context ); - - return $config; - } - - /** - * @throws Exception - */ - public function config( $context = self::COMPILE_CONTEXT ) { - do_action( 'brizy_create_editor_config_before') - ; - - $cachePostId = ( $this->post ? $this->post->getWpPostId() : 0 ) . '_' . $context; - if ( isset( self::$config[ $cachePostId ] ) ) { - return self::$config[ $cachePostId ]; - } - - global $wp_registered_sidebars; - - $parent_post_type = get_post_type( $this->post->getWpPostId() ); - $wp_post_id = $this->post->getWpPostId(); - $preview_post_link = $this->getPreviewUrl( $this->post->getWpPost() ); - - $change_template_url = set_url_scheme( - admin_url( 'admin-post.php?post=' . $this->post->getWpPostId() . '&action=_brizy_change_template' ) - ); - $mode = $this->getMode( $parent_post_type ); - - $heartBeatInterval = (int) apply_filters( 'wp_check_post_lock_window', 150 ); - $config = array( - 'user' => array( - 'role' => 'admin', - 'isAuthorized' => $this->project->getMetaValue( 'brizy-cloud-token' ) !== null, - 'allowScripts' => $this->isUserAllowedToAddScripts( $context ), - ), - 'project' => array( - 'id' => $this->project->getId(), - 'status' => $this->getProjectStatus(), - 'heartBeatInterval' => ( $heartBeatInterval > 10 && $heartBeatInterval < 30 ? $heartBeatInterval : 30 ) * 1000, - ), - 'urls' => array( - 'site' => home_url(), - 'api' => home_url( '/wp-json/v1' ), - 'assets' => $context == self::COMPILE_CONTEXT ? Brizy_Config::EDITOR_BUILD_RELATIVE_PATH : $this->urlBuilder->editor_build_url(), - 'image' => $this->urlBuilder->external_media_url() . "", - 'blockThumbnails' => $this->urlBuilder->external_asset_url( 'thumbs' ) . "", - 'templateThumbnails' => $this->urlBuilder->external_asset_url( 'thumbs' ) . "", - 'templateIcons' => $this->urlBuilder->proxy_url( 'editor/icons' ), - 'templateFonts' => $this->urlBuilder->external_fonts_url(), - 'editorFonts' => home_url( '/' ), - 'pagePreview' => $preview_post_link, - 'about' => __bt( 'about-url', apply_filters( 'brizy_about_url', Brizy_Config::ABOUT_URL ) ), - 'backToDashboard' => get_edit_post_link( $wp_post_id, null ), - 'assetsExternal' => $this->urlBuilder->external_asset_url() . "", - 'termsOfService' => Brizy_Config::getTermsOfServiceUrl(), - - // wp specific - 'changeTemplate' => $change_template_url, - 'upgradeToPro' => Brizy_Config::getUpgradeUrl(), - - 'support' => Brizy_Config::getSupportUrl(), - 'pluginSettings' => admin_url( 'admin.php?page=' . Brizy_Admin_Settings::menu_slug() ), - 'dashboardNavMenu' => admin_url( 'nav-menus.php' ), - 'customFile' => home_url( '?' . Brizy_Editor::prefix( '_attachment' ) . '=' ), - ), - 'form' => array( - 'submitUrl' => '{{brizy_dc_ajax_url}}?action=' . Brizy_Editor::prefix( - Brizy_Editor_Forms_Api::AJAX_SUBMIT_FORM - ), - ), - 'serverTimestamp' => time(), - 'menuData' => $this->get_menu_data(), - 'wp' => array( - 'pluginPrefix' => Brizy_Editor::prefix(), - 'permalink' => get_permalink( $wp_post_id ), - 'page' => $wp_post_id, - 'postType' => get_post_type( $wp_post_id ), - 'featuredImage' => $this->getThumbnailData( $wp_post_id ), - 'templates' => $this->post->get_templates(), - - 'plugins' => array( - 'dummy' => true, - 'woocommerce' => self::get_woocomerce_plugin_info(), - ), - 'hasSidebars' => count( $wp_registered_sidebars ) > 0, - 'l10n' => $this->getTexts(), - 'pageData' => apply_filters( 'brizy_page_data', array() ), - 'availableRoles' => Brizy_Admin_Membership_Membership::roleList(), - 'usersCanRegister' => get_option( 'users_can_register' ), - ), - 'mode' => $mode, - 'applications' => array( - 'form' => array( - 'submitUrl' => '{{brizy_dc_ajax_url}}?action=' . Brizy_Editor::prefix( - Brizy_Editor_Forms_Api::AJAX_SUBMIT_FORM - ), - ), - ), - 'ui' => [], - 'server' => array( - 'maxUploadFileSize' => $this->fileUploadMaxSize(), - ), - 'branding' => array( 'name' => __bt( 'brizy', 'Brizy' ) ), - 'prefix' => Brizy_Editor::prefix(), - 'cloud' => $this->getCloudInfo(), - 'editorVersion' => BRIZY_EDITOR_VERSION, - 'imageSizes' => $this->getImgSizes(), - 'moduleGroups' => [] - ); - $manager = new Brizy_Editor_Accounts_ServiceAccountManager( Brizy_Editor_Project::get() ); - - $config = $this->addRecaptchaAccounts( $manager, $config, $context ); - $config = $this->addSocialAccounts( $manager, $config, $context ); - $config = $this->addWpPostTypes( $config, $context ); - $config = $this->addTemplateFields( $config, $mode === 'template', $wp_post_id, $context ); - $config['wp']['api'] = $this->getApiActions( $config, $context ); - $config = $this->addGlobalBlocksData( $config ); - $config = $this->addGlobalBlocksData( $config ); - $config = $this->getPostLoopSources( $config, $mode === 'template', $wp_post_id, $context ); - $config = $this->getApiConfigFields( $config, $context ); - $config = $this->addContentDefaults( $config, $context ); - $config = $this->addUIConfig( $config, $context ); - $config = $this->addProjectData( $config, $context ); - $config = $this->addModuleGroups( $config, $context ); - $config = $this->addPageData( $config, $context ); - - self::$config[ $cachePostId ] = apply_filters( 'brizy_editor_config', $config, $context ); - - do_action( 'brizy_create_editor_config_after'); - - return self::$config[$cachePostId] ; + $config = $this->getApiConfigFields($config, $context); + + return $config; + } + + /** + * @throws Exception + */ + public function config($context = self::COMPILE_CONTEXT) + { + do_action('brizy_create_editor_config_before'); + + $cachePostId = ($this->post ? $this->post->getWpPostId() : 0) . '_' . $context; + if (isset(self::$config[$cachePostId])) { + return self::$config[$cachePostId]; + } + + global $wp_registered_sidebars; + + $parent_post_type = get_post_type($this->post->getWpPostId()); + $wp_post_id = $this->post->getWpPostId(); + $preview_post_link = $this->getPreviewUrl($this->post->getWpPost()); + + $change_template_url = set_url_scheme( + admin_url('admin-post.php?post=' . $this->post->getWpPostId() . '&action=_brizy_change_template') + ); + $mode = $this->getMode($parent_post_type); + + $heartBeatInterval = (int)apply_filters('wp_check_post_lock_window', 150); + $config = array( + 'user' => array( + 'role' => 'admin', + 'isAuthorized' => $this->project->getMetaValue('brizy-cloud-token') !== null, + 'allowScripts' => $this->isUserAllowedToAddScripts($context), + ), + 'project' => array( + 'id' => $this->project->getId(), + 'status' => $this->getProjectStatus(), + 'heartBeatInterval' => ($heartBeatInterval > 10 && $heartBeatInterval < 30 ? $heartBeatInterval : 30) * 1000, + ), + 'urls' => array( + 'site' => home_url(), + 'api' => home_url('/wp-json/v1'), + 'assets' => $context == self::COMPILE_CONTEXT ? Brizy_Config::EDITOR_BUILD_RELATIVE_PATH : $this->urlBuilder->editor_build_url(), + 'image' => $this->urlBuilder->external_media_url() . "", + 'blockThumbnails' => $this->urlBuilder->external_asset_url('thumbs') . "", + 'templateThumbnails' => $this->urlBuilder->external_asset_url('thumbs') . "", + 'templateIcons' => $this->urlBuilder->proxy_url('editor/icons'), + 'templateFonts' => $this->urlBuilder->external_fonts_url(), + 'editorFonts' => home_url('/'), + 'pagePreview' => $preview_post_link, + 'about' => __bt('about-url', apply_filters('brizy_about_url', Brizy_Config::ABOUT_URL)), + 'backToDashboard' => get_edit_post_link($wp_post_id, null), + 'assetsExternal' => $this->urlBuilder->external_asset_url() . "", + 'termsOfService' => Brizy_Config::getTermsOfServiceUrl(), + + // wp specific + 'changeTemplate' => $change_template_url, + 'upgradeToPro' => Brizy_Config::getUpgradeUrl(), + + 'support' => Brizy_Config::getSupportUrl(), + 'pluginSettings' => admin_url('admin.php?page=' . Brizy_Admin_Settings::menu_slug()), + 'dashboardNavMenu' => admin_url('nav-menus.php'), + 'customFile' => home_url('?' . Brizy_Editor::prefix('_attachment') . '='), + ), + 'form' => array( + 'submitUrl' => '{{brizy_dc_ajax_url}}?action=' . Brizy_Editor::prefix( + Brizy_Editor_Forms_Api::AJAX_SUBMIT_FORM + ), + ), + 'serverTimestamp' => time(), + 'menuData' => $this->get_menu_data(), + 'wp' => array( + 'pluginPrefix' => Brizy_Editor::prefix(), + 'permalink' => get_permalink($wp_post_id), + 'page' => $wp_post_id, + 'postType' => get_post_type($wp_post_id), + 'featuredImage' => $this->getThumbnailData($wp_post_id), + 'templates' => $this->post->get_templates(), + + 'plugins' => array( + 'dummy' => true, + 'woocommerce' => self::get_woocomerce_plugin_info(), + ), + 'hasSidebars' => count($wp_registered_sidebars) > 0, + 'l10n' => $this->getTexts(), + 'pageData' => apply_filters('brizy_page_data', array()), + 'availableRoles' => Brizy_Admin_Membership_Membership::roleList(), + 'usersCanRegister' => get_option('users_can_register'), + ), + 'mode' => $mode, + 'applications' => array( + 'form' => array( + 'submitUrl' => '{{brizy_dc_ajax_url}}?action=' . Brizy_Editor::prefix( + Brizy_Editor_Forms_Api::AJAX_SUBMIT_FORM + ), + ), + ), + 'ui' => [], + 'server' => array( + 'maxUploadFileSize' => $this->fileUploadMaxSize(), + ), + 'branding' => array('name' => __bt('brizy', 'Brizy')), + 'prefix' => Brizy_Editor::prefix(), + 'cloud' => $this->getCloudInfo(), + 'editorVersion' => BRIZY_EDITOR_VERSION, + 'imageSizes' => $this->getImgSizes(), + 'moduleGroups' => [] + ); + $manager = new Brizy_Editor_Accounts_ServiceAccountManager(Brizy_Editor_Project::get()); + + $config = $this->addRecaptchaAccounts($manager, $config, $context); + $config = $this->addSocialAccounts($manager, $config, $context); + $config = $this->addWpPostTypes($config, $context); + $config = $this->addTemplateFields($config, $mode === 'template', $wp_post_id, $context); + $config['wp']['api'] = $this->getApiActions($config, $context); + $config = $this->addGlobalBlocksData($config); + $config = $this->addGlobalBlocksData($config); + $config = $this->getPostLoopSources($config, $mode === 'template', $wp_post_id, $context); + $config = $this->getApiConfigFields($config, $context); + $config = $this->addContentDefaults($config, $context); + $config = $this->addUIConfig($config, $context); + $config = $this->addProjectData($config, $context); + $config = $this->addModuleGroups($config, $context); + $config = $this->addPageData($config, $context); + + self::$config[$cachePostId] = apply_filters('brizy_editor_config', $config, $context); + + do_action('brizy_create_editor_config_after'); + + return self::$config[$cachePostId]; } - private function addUIConfig( $config, $context ) { - - $is_popup = $this->isPopup( $config ); - $is_story = $this->isStory( $config ); - $is_template = $this->isTemplate( $config ); - - $options = [ - ! Brizy_Compatibilities_BrizyProCompatibility::isPro() ? - [ - "type" => "link", - "icon" => "nc-unlock", - "label" => __bt( "Upgrade to Pro", "Upgrade to Pro", 'brizy' ), - "link" => $config['urls']['upgradeToPro'], - "linkTarget" => "_blank", - ] : null, - [ - "type" => "link", - "icon" => "nc-info", - "label" => __bt( "About us", "About us", 'brizy' ), - "link" => $config['urls']['about'], - "linkTarget" => "_blank" - ], - [ - "type" => "link", - "icon" => "nc-help-docs", - "label" => __bt( "Support", "Support", 'brizy' ), - "link" => $config['urls']['support'], - "linkTarget" => "_blank", - "roles" => [ "admin" ] - ], - [ - "type" => "shortcuts", - "icon" => "nc-alert-circle-que", - "label" => __bt( "Shortcuts", "Shortcuts", 'brizy' ), - "link" => "#" - ], - [ - "type" => "link", - "icon" => "nc-cog", - "label" => __bt( "Plugin Settings", "Plugin Settings", 'brizy' ), - "link" => $config['urls']['pluginSettings'], - "linkTarget" => "_blank", - "roles" => [ "admin" ] - ], - [ - "type" => "link", - "icon" => "nc-back", - "label" => __bt( "Go to Dashboard", "Go to Dashboard", 'brizy' ), - "link" => $config['urls']['backToDashboard'] - ] - ]; - $config['ui']['leftSidebar'] = [ - "topTabsOrder" => [ "addElements", "reorderBlock", "globalStyle" ], - "bottomTabsOrder" => [ "deviceMode", "pageSettings", "more" ], - "pageSettings" => [ - "options" => [ - "template" => ! ( $is_popup || $is_story ), - "membership" => ! ( $is_popup || $is_story ), - "featuredImage" => ! ( $is_popup || $is_story ) && ! $is_template - ] - ], - "more" => [ - "options" => array_values( array_filter( $options ) ) - ] - ]; - - $config['ui']['popupSettings'] = [ - "horizontalAlign" => true, - "verticalAlign" => true, - "embedded" => false, - "displayCondition" => $is_popup, - "scrollPageBehind" => true, - "clickOutsideToClose" => true, - "deletePopup" => $is_popup, - "backgroundPreviewUrl" => $config['urls']['pagePreview'] - ]; - - return $config; - } - - /** - * @param $config - * - * @return string[]|WP_Post_Type[] - */ - private function addWpPostTypes( $config, $context ) { - $excludePostTypes = [ 'attachment' ]; - - $types = get_post_types( [ 'public' => true ] ); - $result = []; - foreach ( $types as $type ) { - if ( in_array( $type, $excludePostTypes ) ) { - continue; - } - $typeObj = get_post_type_object( $type ); - $typeDto = [ - 'name' => $typeObj->name, - 'label' => $typeObj->label, - ]; - $result[] = $typeDto; - - } - - $config['wp']['postTypes'] = $result; - - return $config; - } - - private function addPageData( $config, $context ) { - - $config['pageData'] = $this->post->createConfigData(); - - return $config; - } - - private function addModuleGroups( $config, $context ) { - - $moduleGroupCollector = new Brizy_Editor_Editor_ModuleGroups_Manager(); - - $config['ui']['leftSidebar'] = array_merge( $config['ui']['leftSidebar'], [ 'moduleGroups' => $moduleGroupCollector->getAll( $config ) ] ); - - return $config; - } - - - private function addProjectData( $config, $context ) { - - $response = Brizy_Editor_Project::get()->createResponse(); - $response['data'] = json_decode( $response['data'] ); - $config['projectData'] = $response; - - return $config; - } - - - private function getApiConfigFields( $config, $context ) { - $config['api'] = [ - 'media' => [ - 'mediaResizeUrl' => home_url() - ], - 'customFile' => [ - 'customFileUrl' => home_url() - ], - 'templates' => [ - 'kitsUrl' => Brizy_Config::getEditorTemplatesUrl('kits'), + private function addUIConfig($config, $context) + { + + $is_popup = $this->isPopup($config); + $is_story = $this->isStory($config); + $is_template = $this->isTemplate($config); + + $options = [ + !Brizy_Compatibilities_BrizyProCompatibility::isPro() ? + [ + "type" => "link", + "icon" => "nc-unlock", + "label" => __bt("Upgrade to Pro", "Upgrade to Pro", 'brizy'), + "link" => $config['urls']['upgradeToPro'], + "linkTarget" => "_blank", + ] : null, + [ + "type" => "link", + "icon" => "nc-info", + "label" => __bt("About us", "About us", 'brizy'), + "link" => $config['urls']['about'], + "linkTarget" => "_blank" + ], + [ + "type" => "link", + "icon" => "nc-help-docs", + "label" => __bt("Support", "Support", 'brizy'), + "link" => $config['urls']['support'], + "linkTarget" => "_blank", + "roles" => ["admin"] + ], + [ + "type" => "shortcuts", + "icon" => "nc-alert-circle-que", + "label" => __bt("Shortcuts", "Shortcuts", 'brizy'), + "link" => "#" + ], + [ + "type" => "link", + "icon" => "nc-cog", + "label" => __bt("Plugin Settings", "Plugin Settings", 'brizy'), + "link" => $config['urls']['pluginSettings'], + "linkTarget" => "_blank", + "roles" => ["admin"] + ], + [ + "type" => "link", + "icon" => "nc-back", + "label" => __bt("Go to Dashboard", "Go to Dashboard", 'brizy'), + "link" => $config['urls']['backToDashboard'] + ] + ]; + $config['ui']['leftSidebar'] = [ + "topTabsOrder" => ["addElements", "reorderBlock", "globalStyle"], + "bottomTabsOrder" => ["deviceMode", "pageSettings", "more"], + "pageSettings" => [ + "options" => [ + "template" => !($is_popup || $is_story), + "membership" => !($is_popup || $is_story), + "featuredImage" => !($is_popup || $is_story) && !$is_template + ] + ], + "more" => [ + "options" => array_values(array_filter($options)) + ] + ]; + + $config['ui']['popupSettings'] = [ + "horizontalAlign" => true, + "verticalAlign" => true, + "embedded" => false, + "displayCondition" => $is_popup, + "scrollPageBehind" => true, + "clickOutsideToClose" => true, + "deletePopup" => $is_popup, + "backgroundPreviewUrl" => $config['urls']['pagePreview'] + ]; + + return $config; + } + + /** + * @param $config + * + * @return string[]|WP_Post_Type[] + */ + private function addWpPostTypes($config, $context) + { + $excludePostTypes = ['attachment']; + + $types = get_post_types(['public' => true]); + $result = []; + foreach ($types as $type) { + if (in_array($type, $excludePostTypes)) { + continue; + } + $typeObj = get_post_type_object($type); + $typeDto = [ + 'name' => $typeObj->name, + 'label' => $typeObj->label, + ]; + $result[] = $typeDto; + + } + + $config['wp']['postTypes'] = $result; + + return $config; + } + + private function addPageData($config, $context) + { + + $config['pageData'] = $this->post->createConfigData(); + + return $config; + } + + private function addModuleGroups($config, $context) + { + + $moduleGroupCollector = new Brizy_Editor_Editor_ModuleGroups_Manager(); + + $config['ui']['leftSidebar'] = array_merge($config['ui']['leftSidebar'], ['moduleGroups' => $moduleGroupCollector->getAll($config)]); + + return $config; + } + + + private function addProjectData($config, $context) + { + + $response = Brizy_Editor_Project::get()->createResponse(); + $response['data'] = json_decode($response['data']); + $config['projectData'] = $response; + + return $config; + } + + + private function getApiConfigFields($config, $context) + { + $config['api'] = [ + 'media' => [ + 'mediaResizeUrl' => home_url() + ], + 'customFile' => [ + 'customFileUrl' => home_url() + ], + 'templates' => [ + 'kitsUrl' => Brizy_Config::getEditorTemplatesUrl('kits'), 'layoutsUrl' => Brizy_Config::getEditorTemplatesUrl('layouts'), - 'popupsUrl' => Brizy_Config::getEditorTemplatesUrl('popups'), + 'popupsUrl' => Brizy_Config::getEditorTemplatesUrl('popups'), 'storiesUrl' => Brizy_Config::getEditorTemplatesUrl('stories') ] - ]; - - return $config; - } - - private function addContentDefaults( $config, $context ) { - $config['contentDefaults'] = [ - 'ProductMetafield' => ['linkSource' => 'page'], - 'Row' => [ - 'linkSource' => 'page', - 'linkType' => 'page', - 'items' => [ - [ - 'type' => 'Column', - 'value' => [ - '_styles' => ['column'], - 'linkSource' => 'page', - 'linkType' => 'page', - 'items' => [] - ] - ], - [ - 'type' => 'Column', - 'value' => [ - '_styles' => ['column'], - 'linkSource' => 'page', - 'linkType' => 'page', - 'items' => [] - ] - ] - ] + ]; + + return $config; + } + + private function addContentDefaults($config, $context) + { + $config['contentDefaults'] = [ + 'ProductMetafield' => ['linkSource' => 'page'], + 'Row' => [ + 'linkSource' => 'page', + 'linkType' => 'page', + 'items' => [ + [ + 'type' => 'Column', + 'value' => [ + '_styles' => ['column'], + 'linkSource' => 'page', + 'linkType' => 'page', + 'items' => [] + ] + ], + [ + 'type' => 'Column', + 'value' => [ + '_styles' => ['column'], + 'linkSource' => 'page', + 'linkType' => 'page', + 'items' => [] + ] + ] + ] ], - 'Button' => ['linkSource' => 'page', 'linkType' => 'page'], - 'RichText' => ['linkSource' => 'page', 'linkType' => 'page'], - 'Icon' => ['linkSource' => 'page', 'linkType' => 'page'], - 'Image' => ['linkSource' => 'page', 'linkType' => 'page'], - 'Lottie' => ['linkSource' => 'page', 'linkType' => 'page'], - 'FeaturedImage' => ['linkSource' => 'page', 'linkType' => 'page'], - 'PostExcerpt' => ['linkSource' => 'page', 'linkType' => 'page', 'textPopulation' => '{{brizy_dc_post_excerpt}}', 'textPopulationEntityType' => '', 'textPopulationEntityId' => '', '_population' => [ + 'Button' => ['linkSource' => 'page', 'linkType' => 'page'], + 'RichText' => ['linkSource' => 'page', 'linkType' => 'page'], + 'Icon' => ['linkSource' => 'page', 'linkType' => 'page'], + 'Image' => ['linkSource' => 'page', 'linkType' => 'page'], + 'Lottie' => ['linkSource' => 'page', 'linkType' => 'page'], + 'FeaturedImage' => ['linkSource' => 'page', 'linkType' => 'page'], + 'PostExcerpt' => ['linkSource' => 'page', 'linkType' => 'page', 'textPopulation' => '{{brizy_dc_post_excerpt}}', 'textPopulationEntityType' => '', 'textPopulationEntityId' => '', '_population' => [ 'name' => 'brizy_dc_post_excerpt', 'placeholder' => '{{brizy_dc_post_excerpt}}'] ], - 'Column' => [ - [ 'type' => 'Column', 'value' => [ 'linkSource' => 'page', 'linkType' => 'page', 'items' => []]], - [ 'type' => 'Column', 'value' => [ 'linkSource' => 'page', 'linkType' => 'page', 'items' => []]] - ], - 'PostContent' => ['linkSource' => 'page', 'textPopulation' => '{{brizy_dc_post_content}}', 'textPopulationEntityType' => '', 'textPopulationEntityId' => '', '_population' => ['name' => 'brizy_dc_post_content', 'placeholder' => '{{brizy_dc_post_content}}']], - 'PostTitle' => ['linkSource' => 'page', 'linkType' => 'page', 'textPopulation' => '{{brizy_dc_post_title}}', 'textPopulationEntityType' => '', 'textPopulationEntityId' => '', '_population' => ['name' => 'brizy_dc_post_title', 'placeholder' => '{{brizy_dc_post_title}}']], - 'Posts' => [ - '_styles' => [ 'posts', 'posts-posts' ], - '_version' => 3, - 'order' => 'ASC', - 'orderBy' => 'ID', - 'source' => 'post', - 'type' => 'posts', - 'items' => [ - [ - 'type' => 'Column', - 'value' => [ - '_styles' => [ 'posts--column' ], - 'items' => [ - [ - 'type' => 'Wrapper', - 'value' => [ - '_styles' => [ 'wrapper', 'wrapper--image' ], - 'items' => [ - [ - 'type' => 'Image', - 'value' => [ - '_styles' => [ 'image', 'image--dynamic' ], - 'imagePopulation' => '{{brizy_dc_img_featured_image}}', - ], - ], - ], - ], - ], - [ - 'type' => 'Wrapper', - 'value' => [ - '_styles' => [ - 'wrapper', - 'wrapper-postTitle', - 'wrapper-postTitle-posts', - 'wrapper-postTitle-posts-posts' - ], - 'items' => [ - [ - 'type' => 'WPPostsTitle', - 'value' => [ - '_styles' => [ - 'postTitle', - 'postTitle-posts', - 'postTitle-posts-posts' - ], - ], - ], - ], - ], - ], - [ - 'type' => 'Wrapper', - 'value' => [ - '_styles' => [ - 'wrapper', - 'wrapper-postExcerpt', - 'wrapper-postExcerpt-posts', - 'wrapper-postExcerpt-posts-posts' - ], - 'items' => [ - [ - 'type' => 'WPPostExcerpt', - 'value' => [ - '_styles' => [ - 'postExcerpt', - 'postExcerpt-posts', - 'postExcerpt-posts-posts' - ], - ], - ], - ], - ], - ], - [ - 'type' => 'Cloneable', - 'value' => [ - '_styles' => [ 'wrapper-clone', 'wrapper-clone--button' ], - 'items' => [ - [ - 'type' => 'Button', - 'value' => [ - '_styles' => [ 'button', 'button--dynamic' ], - ], - ], - ], - ], - ], - ], - ], - ], - ], - ], - ]; - - return $config; - } - - private function getPostLoopSources( $config, $isTemplate, $wp_post_id, $context ) { + 'Column' => [ + ['type' => 'Column', 'value' => ['linkSource' => 'page', 'linkType' => 'page', 'items' => []]], + ['type' => 'Column', 'value' => ['linkSource' => 'page', 'linkType' => 'page', 'items' => []]] + ], + 'PostContent' => ['linkSource' => 'page', 'textPopulation' => '{{brizy_dc_post_content}}', 'textPopulationEntityType' => '', 'textPopulationEntityId' => '', '_population' => ['name' => 'brizy_dc_post_content', 'placeholder' => '{{brizy_dc_post_content}}']], + 'PostTitle' => ['linkSource' => 'page', 'linkType' => 'page', 'textPopulation' => '{{brizy_dc_post_title}}', 'textPopulationEntityType' => '', 'textPopulationEntityId' => '', '_population' => ['name' => 'brizy_dc_post_title', 'placeholder' => '{{brizy_dc_post_title}}']], + 'Posts' => [ + '_styles' => ['posts', 'posts-posts'], + '_version' => 3, + 'order' => 'ASC', + 'orderBy' => 'ID', + 'source' => 'post', + 'type' => 'posts', + 'items' => [ + [ + 'type' => 'Column', + 'value' => [ + '_styles' => ['posts--column'], + 'items' => [ + [ + 'type' => 'Wrapper', + 'value' => [ + '_styles' => ['wrapper', 'wrapper--image'], + 'items' => [ + [ + 'type' => 'Image', + 'value' => [ + '_styles' => ['image', 'image--dynamic'], + 'imagePopulation' => '{{brizy_dc_img_featured_image}}', + ], + ], + ], + ], + ], + [ + 'type' => 'Wrapper', + 'value' => [ + '_styles' => [ + 'wrapper', + 'wrapper-postTitle', + 'wrapper-postTitle-posts', + 'wrapper-postTitle-posts-posts' + ], + 'items' => [ + [ + 'type' => 'WPPostsTitle', + 'value' => [ + '_styles' => [ + 'postTitle', + 'postTitle-posts', + 'postTitle-posts-posts' + ], + ], + ], + ], + ], + ], + [ + 'type' => 'Wrapper', + 'value' => [ + '_styles' => [ + 'wrapper', + 'wrapper-postExcerpt', + 'wrapper-postExcerpt-posts', + 'wrapper-postExcerpt-posts-posts' + ], + 'items' => [ + [ + 'type' => 'WPPostExcerpt', + 'value' => [ + '_styles' => [ + 'postExcerpt', + 'postExcerpt-posts', + 'postExcerpt-posts-posts' + ], + ], + ], + ], + ], + ], + [ + 'type' => 'Cloneable', + 'value' => [ + '_styles' => ['wrapper-clone', 'wrapper-clone--button'], + 'items' => [ + [ + 'type' => 'Button', + 'value' => [ + '_styles' => ['button', 'button--dynamic'], + ], + ], + ], + ], + ], + ], + ], + ], + ], + ], + ]; + + return $config; + } + + private function getPostLoopSources($config, $isTemplate, $wp_post_id, $context) + { $types = get_post_types(['public' => true]); $typesSort = ['page', 'post', 'editor-story']; @@ -529,64 +542,66 @@ private function getPostLoopSources( $config, $isTemplate, $wp_post_id, $context $result = []; - $templateTypeArchive = false; - if ( $isTemplate ) { - $template_type = Brizy_Admin_Templates::getTemplateType( $wp_post_id ); - if ( $template_type == Brizy_Admin_Templates::TYPE_ARCHIVE || $template_type == Brizy_Admin_Templates::TYPE_PRODUCT_ARCHIVE ) { - $templateTypeArchive = true; - } - } - - if ( $templateTypeArchive ) { - $result[] = [ - "name" => "brz_current_context", - "label" => "Current Query", - ]; - } - - foreach ( $types as $type ) { - $typeObj = get_post_type_object( $type ); - $typeDto = [ - 'name' => $typeObj->name, - 'label' => $typeObj->label, - ]; - $result[] = $typeDto; - - } - - $config['wp']['postLoopSources'] = $result; - - # as stated in this issue: https://github.com/bagrinsergiu/blox-editor/issues/21795 - # we have to add in config the post sources - $config['posts']['sources'] = array_map( function ( $source ) { - return [ - 'value' => $source['name'], - 'title' => $source['label'] - ]; - }, $result ); + $templateTypeArchive = false; + if ($isTemplate) { + $template_type = Brizy_Admin_Templates::getTemplateType($wp_post_id); + if ($template_type == Brizy_Admin_Templates::TYPE_ARCHIVE || $template_type == Brizy_Admin_Templates::TYPE_PRODUCT_ARCHIVE) { + $templateTypeArchive = true; + } + } + + if ($templateTypeArchive) { + $result[] = [ + "name" => "brz_current_context", + "label" => "Current Query", + ]; + } + + foreach ($types as $type) { + $typeObj = get_post_type_object($type); + $typeDto = [ + 'name' => $typeObj->name, + 'label' => $typeObj->label, + ]; + $result[] = $typeDto; + + } + + $config['wp']['postLoopSources'] = $result; + + # as stated in this issue: https://github.com/bagrinsergiu/blox-editor/issues/21795 + # we have to add in config the post sources + $config['posts']['sources'] = array_map(function ($source) { + return [ + 'value' => $source['name'], + 'title' => $source['label'] + ]; + }, $result); return $config; - } + } - private function addGlobalBlocksData( $config ) { + private function addGlobalBlocksData($config) + { - $postTaxonomies = get_post_taxonomies( $wp_post_id = (int) $config['wp']['page'] ); - $postTerms = []; - foreach ( $postTaxonomies as $tax ) { - $postTerms = array_merge( $postTerms, wp_get_post_terms( $wp_post_id, $tax ) ); - } + $postTaxonomies = get_post_taxonomies($wp_post_id = (int)$config['wp']['page']); + $postTerms = []; + foreach ($postTaxonomies as $tax) { + $postTerms = array_merge($postTerms, wp_get_post_terms($wp_post_id, $tax)); + } - $postTermsByKeys = []; - foreach ( $postTerms as $term ) { - $postTermsByKeys[ $term->term_id ] = $term; - } + $postTermsByKeys = []; + foreach ($postTerms as $term) { + $postTermsByKeys[$term->term_id] = $term; + } - $config['wp']['post_terms'] = $postTerms; - $config['wp']['post_term_parents'] = array_diff_key($this->getAllParents($postTermsByKeys),$postTermsByKeys); + $config['wp']['post_terms'] = $postTerms; + $config['wp']['post_term_parents'] = array_diff_key($this->getAllParents($postTermsByKeys), $postTermsByKeys); $config['wp']['post_author'] = (int)$this->post->getWpPost()->post_author; return $config; } + /** * @return object */ @@ -613,607 +628,597 @@ private function get_page_attachments() return (object)$attachment_data; } - /** - * @return object - */ - private function get_page_attachments() { - global $wpdb; - $query = $wpdb->prepare( - "SELECT - pm.* - FROM - {$wpdb->prefix}postmeta pm - JOIN {$wpdb->prefix}postmeta pm2 ON pm2.post_id=pm.post_id AND pm2.meta_key='brizy_post_uid' AND pm2.meta_value=%s - WHERE pm.meta_key='brizy_attachment_uid' - GROUP BY pm.post_id", - $this->post->getUid() - ); - - $results = $wpdb->get_results( $query ); - $attachment_data = array(); - foreach ( $results as $row ) { - $attachment_data[ $row->meta_value ] = true; - } - - return (object) $attachment_data; - } - - /** - * @return array|null - */ - public static function get_woocomerce_plugin_info() { - if ( function_exists( 'wc' ) && defined( 'WC_PLUGIN_FILE' ) ) { - return array( 'version' => WooCommerce::instance()->version ); - } - - return null; - } - - /** - * @param $wp_post_id - * - * @return array|null - */ - private function getThumbnailData( $wp_post_id ) { - $post_thumbnail_id = get_post_thumbnail_id( $wp_post_id ); - $post_thumbnail = ""; - - if ( $post_thumbnail_id ) { - $post_thumbnail_focal_point = get_post_meta( $wp_post_id, 'brizy_attachment_focal_point', true ); - - if ( ! is_array( $post_thumbnail_focal_point ) ) { - $post_thumbnail_focal_point = array( 'x' => "", 'y' => "" ); - } - - $post_thumbnail = array( - 'id' => $post_thumbnail_id, - 'url' => get_the_post_thumbnail_url( $wp_post_id ), - 'pointX' => isset( $post_thumbnail_focal_point['x'] ) ? $post_thumbnail_focal_point['x'] : "", - 'pointY' => isset( $post_thumbnail_focal_point['y'] ) ? $post_thumbnail_focal_point['y'] : "", - ); - } - - return $post_thumbnail; - } - - private function getAllParents( $terms ) { - $result = []; - foreach ( $terms as $i => $term ) { - foreach ( $this->getTermParents( $term ) as $aTerm ) { - if ( ! isset( $result[ $aTerm->term_id ] ) ) { - $result[ $aTerm->term_id ] = $aTerm; - } - } - } - - return $result; - } - - private function getTermParents( $term ) { - $parents = []; - if ( $term->parent ) { - $parent = get_term_by( 'id', $term->parent, $term->taxonomy ); - - if ( $parent ) { - $parents[ $parent->term_id ] = $parent; - if ( $parent->parent > 0 ) { - $parents = array_merge( $parents, $this->getTermParents( $parent ) ); - } - } - } - - return $parents; - } - - /** - * @param $wp_post - * - * @return null|string - * @throws Brizy_Editor_Exceptions_NotFound - * @throws Brizy_Editor_Exceptions_UnsupportedPostType - */ - private function getPreviewUrl( $wp_post ) { - - if ( $wp_post->post_type == Brizy_Admin_Templates::CP_TEMPLATE ) { - - $ruleManager = new Brizy_Admin_Rules_Manager(); - $rules = $ruleManager->getRules( $wp_post->ID ); - $rule = null; - - - if ( ! function_exists( 'addQueryStringToUrl' ) ) { - function addQueryStringToUrl( $link, $query ) { - $parsedUrl = parse_url( $link ); - $separator = ( ! isset( $parsedUrl['query'] ) || $parsedUrl['query'] == null ) ? '?' : '&'; - $link .= $separator . $query; - - return $link; - } - } - - - // find first include rule - foreach ( $rules as $rule ) { - /** - * @var Brizy_Admin_Rule $rule ; - */ - if ( $rule->getType() == Brizy_Admin_Rule::TYPE_INCLUDE ) { - break; - } - } - - if ( $rule ) { - - switch ( $rule->getAppliedFor() ) { - case Brizy_Admin_Rule::WOO_SHOP_PAGE: - if ( function_exists( 'wc_get_page_id' ) && wc_get_page_id( 'shop' ) ) { - $wp_post = get_post( wc_get_page_id( 'shop' ) ); - } - break; - case Brizy_Admin_Rule::POSTS : - $args = array( - 'post_type' => $rule->getEntityType(), - ); - - if ( count( $rule->getEntityValues() ) ) { - $args['post__in'] = $rule->getEntityValues(); - } - - $array = get_posts( $args ); - - foreach ( $array as $p ) { - - if ( $p->post_type == 'attachment' ) { - return addQueryStringToUrl( get_attachment_link( $p->ID ), 'preview=1' ); - } - - if ( ! Brizy_Editor::checkIfPostTypeIsSupported( $p->ID, false ) || - ! Brizy_Editor_Entity::isBrizyEnabled( $p->ID ) ) { - $wp_post = $p; - break; - } - - } - break; - case Brizy_Admin_Rule::TAXONOMY : - $args = array( - 'taxonomy' => $rule->getEntityType(), - 'hide_empty' => true, - ); - if ( count( $rule->getEntityValues() ) ) { - $args['term_taxonomy_id'] = $rule->getEntityValues(); - } - - $array = get_terms( $args ); - - if ( count( $array ) == 0 ) { - break; - } - $term = array_pop( $array ); - $link = get_term_link( $term ); - - return addQueryStringToUrl( $link, 'preview=1' ); - break; - case Brizy_Admin_Rule::ARCHIVE : - if ( $rule->getEntityType() ) { - $link = get_post_type_archive_link( $rule->getEntityType() ); - - return addQueryStringToUrl( $link, 'preview=1' ); - } - - $link = $this->getOneArchiveLink(); - - return addQueryStringToUrl( $link, 'preview=1' ); - break; - case Brizy_Admin_Rule::TEMPLATE : - - // array( 'title' => 'Author page', 'value' => 'author', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), - // array( 'title' => 'Search page', 'value' => 'search', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), - // array( 'title' => 'Home page', 'value' => 'front_page', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), - // array( 'title' => '404 page', 'value' => '404', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), - // array( 'title' => 'Archive page', 'value' => '', 'groupValue' => Brizy_Admin_Rule::ARCHIVE ), - switch ( $rule->getEntityType() ) { - case 'author': - $authors = get_users(); - $author = array_pop( $authors ); - $link = get_author_posts_url( $author->ID ); - - return addQueryStringToUrl( $link, 'preview=1' ); - break; - - case 'search': - return addQueryStringToUrl( get_search_link( 'find-me' ), 'preview=1' ); - break; - case '404': - return addQueryStringToUrl( get_home_url( null, (string) time() ), 'preview=1' ); - break; - case 'home_page': - $get_option = get_option( 'page_for_posts' ); - - if ( $get_option ) { - return addQueryStringToUrl( get_permalink( $get_option ), 'preview=1' ); - } - break; - case 'front_page': - return addQueryStringToUrl( home_url(), 'preview=1' ); - break; - } - - break; - } - - } - } - - return get_preview_post_link( - $wp_post, - array( - 'preview_id' => $wp_post->ID, - 'preview_nonce' => wp_create_nonce( 'post_preview_' . $wp_post->ID ), - ) - ); - } - - /** - * @return array - */ - private function get_menu_data() { - $menus = wp_get_nav_menus(); - $menu_data = array(); - - foreach ( $menus as $menu ) { - - $custom_menu_data = get_term_meta( $menu->term_id, 'brizy_data', true ); - - $menu_uid = get_term_meta( $menu->term_id, 'brizy_uid', true ); - if ( ! $menu_uid ) { - $menu_uid = md5( $menu->term_id . time() ); - update_term_meta( $menu->term_id, 'brizy_uid', $menu_uid ); - } - - $amenu = array( - 'id' => $menu_uid, - 'name' => $menu->name, - 'items' => array(), - ); - - $amenu = (object) array_merge( - $amenu, - get_object_vars( is_object( $custom_menu_data ) ? $custom_menu_data : (object) array() ) - ); - - $menuItems = []; - - add_action( 'wp_get_nav_menu_items', function ( $items ) use ( &$menuItems ) { - foreach ( $items as $item ) { - $menuItems[ $item->ID ] = $item; - } - - return $items; - }, - 1000 ); - - $currentItems = wp_get_nav_menu_items( $menu->term_id ); - - _wp_menu_item_classes_by_context( $menuItems ); - - $currentItemsAssociative = []; - foreach ( $currentItems as $currentItem ) { - $currentItemsAssociative[ $currentItem->ID ] = $currentItem; - } - - $menuItems = $currentItemsAssociative + $menuItems; - - $menu_items = $this->get_menu_tree( $menuItems ); - - if ( count( $menu_items ) > 0 ) { - $amenu->items = $menu_items; - } - - $menu_data[] = $amenu; - } - - return apply_filters( 'brizy_menu_data', $menu_data ); - } - - /** - * @param $items - * @param int $parent - * - * @return array - */ - private function get_menu_tree( $items, $parent = 0 ) { - $result_items = array(); - - foreach ( $items as $item ) { - if ( (string) $item->menu_item_parent !== (string) $parent ) { - continue; - } - - $menu_uid = get_post_meta( $item->ID, 'brizy_post_uid', true ); - - if ( ! $menu_uid ) { - $menu_uid = md5( $item->ID . time() ); - $update = update_post_meta( $item->ID, 'brizy_post_uid', $menu_uid ); - - if ( ! $update ) { - $menu_uid = $item->ID; - } - } - - $megaMenuItems = $this->getMegaMenuItems(); - - $menu_data = get_post_meta( $item->ID, 'brizy_data', true ); - - $item_value = array( - 'id' => $menu_uid, - 'title' => $item->title, - 'url' => $item->url, - 'megaMenuItems' => $megaMenuItems, - 'description' => $item->post_content, - 'position' => $item->menu_order, - 'attrTitle' => $item->post_excerpt, - 'current' => count( - array_intersect( - [ - 'current-menu-parent', - 'current-menu-item', - ], - $item->classes - ) - ) > 0, - 'target' => get_post_meta( $item->ID, '_menu_item_target', true ), - 'classes' => array_values( array_filter( $item->classes ) ), - 'xfn' => get_post_meta( $item->ID, '_menu_item_xfn', true ), - ); - - $an_item = (object) array( - 'type' => 'MenuItem', - ); - - $an_item->value = (object) array_merge( - $item_value, - get_object_vars( is_object( $menu_data ) ? $menu_data : (object) array() ) - ); - - $child_items = $this->get_menu_tree( $items, $item->ID ); - - $an_item->value->items = array(); - - if ( count( $child_items ) > 0 ) { - $an_item->value->items = $child_items; - } - - $result_items[] = $an_item; - } - - return $result_items; - } - - /** - * @return array - */ - private function getMegaMenuItems() { - - return array( - (object) ( array( - 'type' => "SectionMegaMenu", - 'value' => (object) array( 'items' => array() ), - ) ), - ); - } - - /** - * @param Brizy_Editor_Accounts_ServiceAccountManager $manager - * @param array $config - * - * @return array - */ - private function addRecaptchaAccounts( Brizy_Editor_Accounts_ServiceAccountManager $manager, array $config, $context ) { - $accounts = $manager->getAccountsByGroup( Brizy_Editor_Accounts_AbstractAccount::RECAPTCHA_GROUP ); - - if ( isset( $accounts[0] ) && $accounts[0] instanceof Brizy_Editor_Accounts_RecaptchaAccount ) { - $config['applications']['form']['recaptcha']['siteKey'] = $accounts[0]->getSiteKey(); - } - - return $config; - } - - /** - * @param Brizy_Editor_Accounts_ServiceAccountManager $manager - * @param array $config - * - * @return array - */ - private function addSocialAccounts( Brizy_Editor_Accounts_ServiceAccountManager $manager, array $config, $context ) { - $accounts = $manager->getAccountsByGroup( Brizy_Editor_Accounts_AbstractAccount::SOCIAL_GROUP ); - - foreach ( $accounts as $account ) { - if ( isset( $account ) && $account instanceof Brizy_Editor_Accounts_SocialAccount ) { - $config['applications'][ $account->getGroup() ][] = $account->convertToOptionValue(); - } - } - - return $config; - } - - - private function fileUploadMaxSize() { - static $max_size = - 1; - - if ( $max_size < 0 ) { - // Start with post_max_size. - $post_max_size = $this->parseSize( ini_get( 'post_max_size' ) ); - if ( $post_max_size > 0 ) { - $max_size = number_format( $post_max_size / 1048576, 2, '.', '' ); - } - - // If upload_max_size is less, then reduce. Except if upload_max_size is - // zero, which indicates no limit. - $upload_max = $this->parseSize( ini_get( 'upload_max_filesize' ) ); - if ( $upload_max > 0 && $upload_max < $max_size ) { - $max_size = number_format( $upload_max / 1048576, 2, '.', '' ); - } - } - - return $max_size; - } - - private function parseSize( $size ) { - $unit = preg_replace( '/[^bkmgtpezy]/i', '', $size ); // Remove the non-unit characters from the size. - $size = preg_replace( '/[^0-9\.]/', '', $size ); // Remove the non-numeric characters from the size. - if ( $unit ) { - // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. - return round( $size * pow( 1024, stripos( 'bkmgtpezy', $unit[0] ) ) ); - } else { - return round( $size ); - } - } - - - - private function getOneArchiveLink($args = ''){ - global $wpdb, $wp_locale; - - $defaults = array( - 'type' => 'monthly', - 'limit' => '', - 'order' => 'DESC', - 'post_type' => 'post', - 'year' => get_query_var( 'year' ), - 'monthnum' => get_query_var( 'monthnum' ), - 'day' => get_query_var( 'day' ), - 'w' => get_query_var( 'w' ), - ); - - $r = wp_parse_args( $args, $defaults ); - - $post_type_object = get_post_type_object( $r['post_type'] ); - if ( ! is_post_type_viewable( $post_type_object ) ) { - return; - } - $r['post_type'] = $post_type_object->name; - - if ( '' == $r['type'] ) { - $r['type'] = 'monthly'; - } - - if ( ! empty( $r['limit'] ) ) { - $r['limit'] = absint( $r['limit'] ); - $r['limit'] = ' LIMIT ' . $r['limit']; - } - - $order = strtoupper( $r['order'] ); - if ( $order !== 'ASC' ) { - $order = 'DESC'; - } - - // this is what will separate dates on weekly archive links - $archive_week_separator = '–'; - - $sql_where = $wpdb->prepare( "WHERE post_type = %s AND post_status = 'publish'", $r['post_type'] ); - - /** - * Filters the SQL WHERE clause for retrieving archives. - * - * @param string $sql_where Portion of SQL query containing the WHERE clause. - * @param array $r An array of default arguments. - * - * @since 2.2.0 - * - */ - $where = apply_filters( 'getarchives_where', $sql_where, $r ); - - /** - * Filters the SQL JOIN clause for retrieving archives. - * - * @param string $sql_join Portion of SQL query containing JOIN clause. - * @param array $r An array of default arguments. - * - * @since 2.2.0 - * - */ - $join = apply_filters( 'getarchives_join', '', $r ); - - $output = ''; - - $last_changed = wp_cache_get_last_changed( 'posts' ); - - $limit = $r['limit']; - - if ( 'monthly' == $r['type'] ) { - $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date $order $limit"; - $key = md5( $query ); - $key = "wp_get_archives:$key:$last_changed"; - if ( ! $results = wp_cache_get( $key, 'posts' ) ) { - $results = $wpdb->get_results( $query ); - wp_cache_set( $key, $results, 'posts' ); - } - if ( $results ) { - foreach ( (array) $results as $result ) { - $url = get_month_link( $result->year, $result->month ); - if ( 'post' !== $r['post_type'] ) { - $url = add_query_arg( 'post_type', $r['post_type'], $url ); - } - - return $url; - } - } - } - } - - /** - * @return string - * @throws Exception - */ - private function getTexts() { - if ( BRIZY_DEVELOPMENT ) { - $brizy_public_editor_build_texts = '\Brizy_Public_EditorBuild_Dev_Texts'; - } else { - $version = ''; - foreach ( explode( '-', BRIZY_EDITOR_VERSION ) as $tmp ) { - $version .= ucfirst( $tmp ); - } - $brizy_public_editor_build_texts = '\Brizy_Public_EditorBuild_' . $version . '_Texts'; - } - - if ( ! class_exists( $brizy_public_editor_build_texts ) ) { - if ( BRIZY_DEVELOPMENT ) { - throw new \Exception( 'You must build the editor first.' ); - } else { - throw new \Exception( 'Unable to find class ' . $brizy_public_editor_build_texts ); - } - } - - return (object) $brizy_public_editor_build_texts::get_editor_texts(); - } + /** + * @return array|null + */ + public static function get_woocomerce_plugin_info() + { + if (function_exists('wc') && defined('WC_PLUGIN_FILE')) { + return array('version' => WooCommerce::instance()->version); + } + + return null; + } + + /** + * @param $wp_post_id + * + * @return array|null + */ + private function getThumbnailData($wp_post_id) + { + $post_thumbnail_id = get_post_thumbnail_id($wp_post_id); + $post_thumbnail = ""; + + if ($post_thumbnail_id) { + $post_thumbnail_focal_point = get_post_meta($wp_post_id, 'brizy_attachment_focal_point', true); + + if (!is_array($post_thumbnail_focal_point)) { + $post_thumbnail_focal_point = array('x' => "", 'y' => ""); + } + + $post_thumbnail = array( + 'id' => $post_thumbnail_id, + 'url' => get_the_post_thumbnail_url($wp_post_id), + 'pointX' => isset($post_thumbnail_focal_point['x']) ? $post_thumbnail_focal_point['x'] : "", + 'pointY' => isset($post_thumbnail_focal_point['y']) ? $post_thumbnail_focal_point['y'] : "", + ); + } + + return $post_thumbnail; + } + + private function getAllParents($terms) + { + $result = []; + foreach ($terms as $i => $term) { + foreach ($this->getTermParents($term) as $aTerm) { + if (!isset($result[$aTerm->term_id])) { + $result[$aTerm->term_id] = $aTerm; + } + } + } + + return $result; + } + + private function getTermParents($term) + { + $parents = []; + if ($term->parent) { + $parent = get_term_by('id', $term->parent, $term->taxonomy); + + if ($parent) { + $parents[$parent->term_id] = $parent; + if ($parent->parent > 0) { + $parents = array_merge($parents, $this->getTermParents($parent)); + } + } + } + + return $parents; + } + + /** + * @param $wp_post + * + * @return null|string + * @throws Brizy_Editor_Exceptions_NotFound + * @throws Brizy_Editor_Exceptions_UnsupportedPostType + */ + private function getPreviewUrl($wp_post) + { + + if ($wp_post->post_type == Brizy_Admin_Templates::CP_TEMPLATE) { + + $ruleManager = new Brizy_Admin_Rules_Manager(); + $rules = $ruleManager->getRules($wp_post->ID); + $rule = null; + + + if (!function_exists('addQueryStringToUrl')) { + function addQueryStringToUrl($link, $query) + { + $parsedUrl = parse_url($link); + $separator = (!isset($parsedUrl['query']) || $parsedUrl['query'] == null) ? '?' : '&'; + $link .= $separator . $query; + + return $link; + } + } + + + // find first include rule + foreach ($rules as $rule) { + /** + * @var Brizy_Admin_Rule $rule ; + */ + if ($rule->getType() == Brizy_Admin_Rule::TYPE_INCLUDE) { + break; + } + } + + if ($rule) { + + switch ($rule->getAppliedFor()) { + case Brizy_Admin_Rule::WOO_SHOP_PAGE: + if (function_exists('wc_get_page_id') && wc_get_page_id('shop')) { + $wp_post = get_post(wc_get_page_id('shop')); + } + break; + case Brizy_Admin_Rule::POSTS : + $args = array( + 'post_type' => $rule->getEntityType(), + ); + + if (count($rule->getEntityValues())) { + $args['post__in'] = $rule->getEntityValues(); + } + + $array = get_posts($args); + + foreach ($array as $p) { + + if ($p->post_type == 'attachment') { + return addQueryStringToUrl(get_attachment_link($p->ID), 'preview=1'); + } + + if (!Brizy_Editor::checkIfPostTypeIsSupported($p->ID, false) || + !Brizy_Editor_Entity::isBrizyEnabled($p->ID)) { + $wp_post = $p; + break; + } + + } + break; + case Brizy_Admin_Rule::TAXONOMY : + $args = array( + 'taxonomy' => $rule->getEntityType(), + 'hide_empty' => true, + ); + if (count($rule->getEntityValues())) { + $args['term_taxonomy_id'] = $rule->getEntityValues(); + } + + $array = get_terms($args); + + if (count($array) == 0) { + break; + } + $term = array_pop($array); + $link = get_term_link($term); + + return addQueryStringToUrl($link, 'preview=1'); + break; + case Brizy_Admin_Rule::ARCHIVE : + if ($rule->getEntityType()) { + $link = get_post_type_archive_link($rule->getEntityType()); + + return addQueryStringToUrl($link, 'preview=1'); + } + + $link = $this->getOneArchiveLink(); + + return addQueryStringToUrl($link, 'preview=1'); + break; + case Brizy_Admin_Rule::TEMPLATE : + + // array( 'title' => 'Author page', 'value' => 'author', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), + // array( 'title' => 'Search page', 'value' => 'search', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), + // array( 'title' => 'Home page', 'value' => 'front_page', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), + // array( 'title' => '404 page', 'value' => '404', 'groupValue' => Brizy_Admin_Rule::TEMPLATE ), + // array( 'title' => 'Archive page', 'value' => '', 'groupValue' => Brizy_Admin_Rule::ARCHIVE ), + switch ($rule->getEntityType()) { + case 'author': + $authors = get_users(); + $author = array_pop($authors); + $link = get_author_posts_url($author->ID); + + return addQueryStringToUrl($link, 'preview=1'); + break; + + case 'search': + return addQueryStringToUrl(get_search_link('find-me'), 'preview=1'); + break; + case '404': + return addQueryStringToUrl(get_home_url(null, (string)time()), 'preview=1'); + break; + case 'home_page': + $get_option = get_option('page_for_posts'); + + if ($get_option) { + return addQueryStringToUrl(get_permalink($get_option), 'preview=1'); + } + break; + case 'front_page': + return addQueryStringToUrl(home_url(), 'preview=1'); + break; + } + + break; + } + + } + } + + return get_preview_post_link( + $wp_post, + array( + 'preview_id' => $wp_post->ID, + 'preview_nonce' => wp_create_nonce('post_preview_' . $wp_post->ID), + ) + ); + } + + /** + * @return array + */ + private function get_menu_data() + { + $menus = wp_get_nav_menus(); + $menu_data = array(); + + foreach ($menus as $menu) { + + $custom_menu_data = get_term_meta($menu->term_id, 'brizy_data', true); + + $menu_uid = get_term_meta($menu->term_id, 'brizy_uid', true); + if (!$menu_uid) { + $menu_uid = md5($menu->term_id . time()); + update_term_meta($menu->term_id, 'brizy_uid', $menu_uid); + } + + $amenu = array( + 'id' => $menu_uid, + 'name' => $menu->name, + 'items' => array(), + ); + + $amenu = (object)array_merge( + $amenu, + get_object_vars(is_object($custom_menu_data) ? $custom_menu_data : (object)array()) + ); + + $menuItems = []; + + add_action('wp_get_nav_menu_items', function ($items) use (&$menuItems) { + foreach ($items as $item) { + $menuItems[$item->ID] = $item; + } + + return $items; + }, -1000); + + $currentItems = wp_get_nav_menu_items($menu->term_id); + + _wp_menu_item_classes_by_context($menuItems); + + $currentItemsAssociative = []; + foreach ($currentItems as $currentItem) { + $currentItemsAssociative[$currentItem->ID] = $currentItem; + } + + $menuItems = $currentItemsAssociative + $menuItems; + + $menu_items = $this->get_menu_tree($menuItems); + + if (count($menu_items) > 0) { + $amenu->items = $menu_items; + } + + $menu_data[] = $amenu; + } + + return apply_filters('brizy_menu_data', $menu_data); + } + + /** + * @param $items + * @param int $parent + * + * @return array + */ + private function get_menu_tree($items, $parent = 0) + { + $result_items = array(); + + foreach ($items as $item) { + if ((string)$item->menu_item_parent !== (string)$parent) { + continue; + } + + $menu_uid = get_post_meta($item->ID, 'brizy_post_uid', true); + + if (!$menu_uid) { + $menu_uid = md5($item->ID . time()); + $update = update_post_meta($item->ID, 'brizy_post_uid', $menu_uid); + + if (!$update) { + $menu_uid = $item->ID; + } + } + + $megaMenuItems = $this->getMegaMenuItems(); + + $menu_data = get_post_meta($item->ID, 'brizy_data', true); + + $item_value = array( + 'id' => $menu_uid, + 'title' => $item->title, + 'url' => $item->url, + 'megaMenuItems' => $megaMenuItems, + 'description' => $item->post_content, + 'position' => $item->menu_order, + 'attrTitle' => $item->post_excerpt, + 'current' => count( + array_intersect( + [ + 'current-menu-parent', + 'current-menu-item', + ], + $item->classes + ) + ) > 0, + 'target' => get_post_meta($item->ID, '_menu_item_target', true), + 'classes' => array_values(array_filter($item->classes)), + 'xfn' => get_post_meta($item->ID, '_menu_item_xfn', true), + ); + + $an_item = (object)array( + 'type' => 'MenuItem', + ); + + $an_item->value = (object)array_merge( + $item_value, + get_object_vars(is_object($menu_data) ? $menu_data : (object)array()) + ); + + $child_items = $this->get_menu_tree($items, $item->ID); + + $an_item->value->items = array(); + + if (count($child_items) > 0) { + $an_item->value->items = $child_items; + } + + $result_items[] = $an_item; + } + + return $result_items; + } + + /** + * @return array + */ + private function getMegaMenuItems() + { + + return array( + (object)(array( + 'type' => "SectionMegaMenu", + 'value' => (object)array('items' => array()), + )), + ); + } + + /** + * @param Brizy_Editor_Accounts_ServiceAccountManager $manager + * @param array $config + * + * @return array + */ + private function addRecaptchaAccounts(Brizy_Editor_Accounts_ServiceAccountManager $manager, array $config, $context) + { + $accounts = $manager->getAccountsByGroup(Brizy_Editor_Accounts_AbstractAccount::RECAPTCHA_GROUP); + + if (isset($accounts[0]) && $accounts[0] instanceof Brizy_Editor_Accounts_RecaptchaAccount) { + $config['applications']['form']['recaptcha']['siteKey'] = $accounts[0]->getSiteKey(); + } + + return $config; + } + + /** + * @param Brizy_Editor_Accounts_ServiceAccountManager $manager + * @param array $config + * + * @return array + */ + private function addSocialAccounts(Brizy_Editor_Accounts_ServiceAccountManager $manager, array $config, $context) + { + $accounts = $manager->getAccountsByGroup(Brizy_Editor_Accounts_AbstractAccount::SOCIAL_GROUP); + + foreach ($accounts as $account) { + if (isset($account) && $account instanceof Brizy_Editor_Accounts_SocialAccount) { + $config['applications'][$account->getGroup()][] = $account->convertToOptionValue(); + } + } + + return $config; + } + + + private function fileUploadMaxSize() + { + static $max_size = -1; + + if ($max_size < 0) { + // Start with post_max_size. + $post_max_size = $this->parseSize(ini_get('post_max_size')); + if ($post_max_size > 0) { + $max_size = number_format($post_max_size / 1048576, 2, '.', ''); + } + + // If upload_max_size is less, then reduce. Except if upload_max_size is + // zero, which indicates no limit. + $upload_max = $this->parseSize(ini_get('upload_max_filesize')); + if ($upload_max > 0 && $upload_max < $max_size) { + $max_size = number_format($upload_max / 1048576, 2, '.', ''); + } + } + + return $max_size; + } + + private function parseSize($size) + { + $unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size. + $size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size. + if ($unit) { + // Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by. + return round($size * pow(1024, stripos('bkmgtpezy', $unit[0]))); + } else { + return round($size); + } + } + + + private function getOneArchiveLink($args = '') + { + global $wpdb, $wp_locale; + + $defaults = array( + 'type' => 'monthly', + 'limit' => '', + 'order' => 'DESC', + 'post_type' => 'post', + 'year' => get_query_var('year'), + 'monthnum' => get_query_var('monthnum'), + 'day' => get_query_var('day'), + 'w' => get_query_var('w'), + ); + + $r = wp_parse_args($args, $defaults); + + $post_type_object = get_post_type_object($r['post_type']); + if (!is_post_type_viewable($post_type_object)) { + return; + } + $r['post_type'] = $post_type_object->name; + + if ('' == $r['type']) { + $r['type'] = 'monthly'; + } + + if (!empty($r['limit'])) { + $r['limit'] = absint($r['limit']); + $r['limit'] = ' LIMIT ' . $r['limit']; + } + + $order = strtoupper($r['order']); + if ($order !== 'ASC') { + $order = 'DESC'; + } + + // this is what will separate dates on weekly archive links + $archive_week_separator = '–'; + + $sql_where = $wpdb->prepare("WHERE post_type = %s AND post_status = 'publish'", $r['post_type']); + + /** + * Filters the SQL WHERE clause for retrieving archives. + * + * @param string $sql_where Portion of SQL query containing the WHERE clause. + * @param array $r An array of default arguments. + * + * @since 2.2.0 + * + */ + $where = apply_filters('getarchives_where', $sql_where, $r); + + /** + * Filters the SQL JOIN clause for retrieving archives. + * + * @param string $sql_join Portion of SQL query containing JOIN clause. + * @param array $r An array of default arguments. + * + * @since 2.2.0 + * + */ + $join = apply_filters('getarchives_join', '', $r); + + $output = ''; + + $last_changed = wp_cache_get_last_changed('posts'); + + $limit = $r['limit']; + + if ('monthly' == $r['type']) { + $query = "SELECT YEAR(post_date) AS `year`, MONTH(post_date) AS `month`, count(ID) as posts FROM $wpdb->posts $join $where GROUP BY YEAR(post_date), MONTH(post_date) ORDER BY post_date $order $limit"; + $key = md5($query); + $key = "wp_get_archives:$key:$last_changed"; + if (!$results = wp_cache_get($key, 'posts')) { + $results = $wpdb->get_results($query); + wp_cache_set($key, $results, 'posts'); + } + if ($results) { + foreach ((array)$results as $result) { + $url = get_month_link($result->year, $result->month); + if ('post' !== $r['post_type']) { + $url = add_query_arg('post_type', $r['post_type'], $url); + } + + return $url; + } + } + } + } + + /** + * @return string + * @throws Exception + */ + private function getTexts() + { + if (BRIZY_DEVELOPMENT) { + $brizy_public_editor_build_texts = '\Brizy_Public_EditorBuild_Dev_Texts'; + } else { + $version = ''; + foreach (explode('-', BRIZY_EDITOR_VERSION) as $tmp) { + $version .= ucfirst($tmp); + } + $brizy_public_editor_build_texts = '\Brizy_Public_EditorBuild_' . $version . '_Texts'; + } + + if (!class_exists($brizy_public_editor_build_texts)) { + if (BRIZY_DEVELOPMENT) { + throw new \Exception('You must build the editor first.'); + } else { + throw new \Exception('Unable to find class ' . $brizy_public_editor_build_texts); + } + } + + return (object)$brizy_public_editor_build_texts::get_editor_texts(); + } private function addTemplateFields($config, $is_template, $wp_post_id, $context) { - $template_rules = []; - if ( $is_template ) { - $rule_manager = new Brizy_Admin_Rules_Manager(); - $template_rules = $rule_manager->getRules( $wp_post_id ); - $config['template_type'] = $this->getTemplateType( $template_rules ); - } + $template_rules = []; + if ($is_template) { + $rule_manager = new Brizy_Admin_Rules_Manager(); + $template_rules = $rule_manager->getRules($wp_post_id); + $config['template_type'] = $this->getTemplateType($template_rules); + } - $config['wp']['ruleMatches'] = $this->getTemplateRuleMatches( $is_template, $wp_post_id, $template_rules ); + $config['wp']['ruleMatches'] = $this->getTemplateRuleMatches($is_template, $wp_post_id, $template_rules); - return $config; - } + return $config; + } - /** - * @param $isTemplate - * @param $wpPostId - * @param $templateRules - * - * @return array - */ - private function getTemplateRuleMatches( $isTemplate, $wpPostId, $templateRules ) { + /** + * @param $isTemplate + * @param $wpPostId + * @param $templateRules + * + * @return array + */ + private function getTemplateRuleMatches($isTemplate, $wpPostId, $templateRules) + { - $ruleMatches = array(); + $ruleMatches = array(); - if ( $isTemplate ) { + if ($isTemplate) { foreach ($templateRules as $rule) { /** @@ -1226,161 +1231,165 @@ private function getTemplateRuleMatches( $isTemplate, $wpPostId, $templateRules 'values' => $rule->getEntityValues(), ); } - $ruleMatches[] = array( + $ruleMatches[] = array( 'type' => Brizy_Admin_Rule::TYPE_INCLUDE, 'group' => Brizy_Admin_Rule::BRIZY_TEMPLATE, 'entityType' => $this->post->getWpPost()->post_type, 'values' => array($wpPostId), - );} else { - $ruleMatches[] = array( - 'type' => Brizy_Admin_Rule::TYPE_INCLUDE, - 'group' => Brizy_Admin_Rule::POSTS, - 'entityType' => $this->post->getWpPost()->post_type, - 'values' => array( $wpPostId ), - ); - } - - return $ruleMatches; - } - - - /** - * - * @param $template_rules - */ - private function getTemplateType( $template_rules ) { - foreach ( $template_rules as $rule ) { - - if ( $rule->getType() != Brizy_Admin_Rule::TYPE_INCLUDE ) { - continue; - } - - // single mode - if ( $rule->getAppliedFor() == Brizy_Admin_Rule::POSTS ) { - if ( $rule->getEntityType() == 'product' ) { - return 'product'; - } else { - return 'single'; - } - } - - - // single mode - if ( $rule->getAppliedFor() == Brizy_Admin_Rule::TEMPLATE ) { - if ( in_array( $rule->getEntityType(), [ '404', 'front_page' ] ) ) { - return 'single'; - } - - if ( in_array( $rule->getEntityType(), [ 'search', 'author', 'home_page' ] ) ) { - return 'archive'; - } - } - - // archive mode - if ( $rule->getAppliedFor() == Brizy_Admin_Rule::TAXONOMY ) { - if ( in_array( $rule->getEntityType(), [ 'product_cat', 'product_tag' ] ) ) { - return 'product_archive'; - } - if ( in_array( $rule->getEntityType(), [ 'category', 'post_tag', ] ) ) { - return 'archive'; - } - } - - // product archive mode - if ( in_array( $rule->getAppliedFor(), [ - Brizy_Admin_Rule::ARCHIVE, - Brizy_Admin_Rule::DATE_ARCHIVE, - Brizy_Admin_Rule::DAY_ARCHIVE, - Brizy_Admin_Rule::MONTH_ARCHIVE, - Brizy_Admin_Rule::YEAR_ARCHIVE, - Brizy_Admin_Rule::TAXONOMY, - Brizy_Admin_Rule::WOO_SHOP_PAGE, - ] ) ) { - if ( $rule->getAppliedFor() == Brizy_Admin_Rule::WOO_SHOP_PAGE && in_array( $rule->getEntityType(), [ - 'product', - 'shop_page', - ] ) ) { - return 'product_archive'; - } else { - return 'archive'; - } - } - } - - return ''; - } - - /** - * @return array - */ - public function getProjectStatus() { - $projectLockedBy = Brizy_Editor::get()->checkIfProjectIsLocked(); - $userData = WP_User::get_data_by( 'id', $projectLockedBy ); - unset( $userData->user_pass ); - unset( $userData->user_registered ); - unset( $userData->user_status ); - unset( $userData->user_activation_key ); - - return [ - 'locked' => $projectLockedBy !== false, - 'lockedBy' => $userData, - ]; - } - - /** - * @return array - */ - public function getApiActions( $config = [], $context = null ) { - - $pref = Brizy_Editor::prefix(); - - $actions = array( + ); + } else { + $ruleMatches[] = array( + 'type' => Brizy_Admin_Rule::TYPE_INCLUDE, + 'group' => Brizy_Admin_Rule::POSTS, + 'entityType' => $this->post->getWpPost()->post_type, + 'values' => array($wpPostId), + ); + } + + return $ruleMatches; + } + + + /** + * + * @param $template_rules + */ + private function getTemplateType($template_rules) + { + foreach ($template_rules as $rule) { + + if ($rule->getType() != Brizy_Admin_Rule::TYPE_INCLUDE) { + continue; + } + + // single mode + if ($rule->getAppliedFor() == Brizy_Admin_Rule::POSTS) { + if ($rule->getEntityType() == 'product') { + return 'product'; + } else { + return 'single'; + } + } + + + // single mode + if ($rule->getAppliedFor() == Brizy_Admin_Rule::TEMPLATE) { + if (in_array($rule->getEntityType(), ['404', 'front_page'])) { + return 'single'; + } + + if (in_array($rule->getEntityType(), ['search', 'author', 'home_page'])) { + return 'archive'; + } + } + + // archive mode + if ($rule->getAppliedFor() == Brizy_Admin_Rule::TAXONOMY) { + if (in_array($rule->getEntityType(), ['product_cat', 'product_tag'])) { + return 'product_archive'; + } + if (in_array($rule->getEntityType(), ['category', 'post_tag',])) { + return 'archive'; + } + } + + // product archive mode + if (in_array($rule->getAppliedFor(), [ + Brizy_Admin_Rule::ARCHIVE, + Brizy_Admin_Rule::DATE_ARCHIVE, + Brizy_Admin_Rule::DAY_ARCHIVE, + Brizy_Admin_Rule::MONTH_ARCHIVE, + Brizy_Admin_Rule::YEAR_ARCHIVE, + Brizy_Admin_Rule::TAXONOMY, + Brizy_Admin_Rule::WOO_SHOP_PAGE, + ])) { + if ($rule->getAppliedFor() == Brizy_Admin_Rule::WOO_SHOP_PAGE && in_array($rule->getEntityType(), [ + 'product', + 'shop_page', + ])) { + return 'product_archive'; + } else { + return 'archive'; + } + } + } + + return ''; + } + + /** + * @return array + */ + public function getProjectStatus() + { + $projectLockedBy = Brizy_Editor::get()->checkIfProjectIsLocked(); + $userData = WP_User::get_data_by('id', $projectLockedBy); + unset($userData->user_pass); + unset($userData->user_registered); + unset($userData->user_status); + unset($userData->user_activation_key); + + return [ + 'locked' => $projectLockedBy !== false, + 'lockedBy' => $userData, + ]; + } + + /** + * @return array + */ + public function getApiActions($config = [], $context = null) + { + + $pref = Brizy_Editor::prefix(); + + $actions = array( 'hash' => wp_create_nonce(Brizy_Editor_API::nonce), 'url' => set_url_scheme(admin_url('admin-ajax.php')), - 'heartBeat' => $pref . Brizy_Editor_API::AJAX_HEARTBEAT, - 'takeOver' => $pref . Brizy_Editor_API::AJAX_TAKE_OVER, - 'lockProject' => $pref . Brizy_Editor_API::AJAX_LOCK_PROJECT, - 'removeLock' => $pref . Brizy_Editor_API::AJAX_REMOVE_LOCK, - 'getPage' => $pref . Brizy_Editor_API::AJAX_GET, - 'getPostInfo' => $pref . Brizy_Editor_API::AJAX_GET_POST_INFO, - 'updatePage' => $pref . Brizy_Editor_API::AJAX_UPDATE, - 'getProject' => $pref . Brizy_Editor_API::AJAX_GET_PROJECT, - 'setProject' => $pref . Brizy_Editor_API::AJAX_SET_PROJECT, - 'setProjectMeta' => $pref . Brizy_Editor_API::AJAX_UPDATE_EDITOR_META_DATA, - 'getGlobalBlockList' => $pref . Brizy_Admin_Blocks_Api::GET_GLOBAL_BLOCKS_ACTION, - 'createGlobalBlock' => $pref . Brizy_Admin_Blocks_Api::CREATE_GLOBAL_BLOCK_ACTION, - 'updateGlobalBlock' => $pref . Brizy_Admin_Blocks_Api::UPDATE_GLOBAL_BLOCK_ACTION, - 'updateGlobalBlocks' => $pref . Brizy_Admin_Blocks_Api::UPDATE_GLOBAL_BLOCKS_ACTION, - 'deleteGlobalBlock' => $pref . Brizy_Admin_Blocks_Api::DELETE_GLOBAL_BLOCK_ACTION, - 'getRuleGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_GROUP_LIST, - 'getLayoutByUid' => $pref . Brizy_Admin_Layouts_Api::GET_LAYOUT_BY_UID_ACTION, - 'getLayoutList' => $pref . Brizy_Admin_Layouts_Api::GET_LAYOUTS_ACTION, - 'createLayout' => $pref . Brizy_Admin_Layouts_Api::CREATE_LAYOUT_ACTION, - 'updateLayout' => $pref . Brizy_Admin_Layouts_Api::UPDATE_LAYOUT_ACTION, - 'deleteLayout' => $pref . Brizy_Admin_Layouts_Api::DELETE_LAYOUT_ACTION, - 'cloudSignIn' => $pref . Brizy_Admin_Cloud_Api::AJAX_SIGNIN_ACTION, - 'cloudSignUp' => $pref . Brizy_Admin_Cloud_Api::AJAX_SIGNUP_ACTION, - 'cloudSignOut' => $pref . Brizy_Admin_Cloud_Api::AJAX_SIGNOUT_ACTION, - 'cloudSyncAllowed' => $pref . Brizy_Admin_Cloud_Api::AJAX_SYNC_ALLOWED, - 'cloudResetPassword' => $pref . Brizy_Admin_Cloud_Api::AJAX_RESET_PASSWORD_ACTION, - 'cloudSync' => $pref . Brizy_Admin_Cloud_Api::AJAX_TRIGGER_SYNC_ACTION, - 'createRule' => $pref . Brizy_Admin_Rules_Api::CREATE_RULE_ACTION, - 'createRules' => $pref . Brizy_Admin_Rules_Api::CREATE_RULES_ACTION, - 'updateRules' => $pref . Brizy_Admin_Rules_Api::UPDATE_RULES_ACTION, - 'deleteRule' => $pref . Brizy_Admin_Rules_Api::DELETE_RULE_ACTION, - 'getRuleList' => $pref . Brizy_Admin_Rules_Api::LIST_RULE_ACTION, - 'updateBlockPositions' => $pref . Brizy_Admin_Blocks_Api::UPDATE_POSITIONS_ACTION, - 'getSavedBlockByUid' => $pref . Brizy_Admin_Blocks_Api::GET_SAVED_BLOCK_ACTION, - 'getSavedBlockList' => $pref . Brizy_Admin_Blocks_Api::GET_SAVED_BLOCKS_ACTION, - 'createSavedBlock' => $pref . Brizy_Admin_Blocks_Api::CREATE_SAVED_BLOCK_ACTION, - 'updateSavedBlock' => $pref . Brizy_Admin_Blocks_Api::UPDATE_SAVED_BLOCK_ACTION, - 'deleteSavedBlock' => $pref . Brizy_Admin_Blocks_Api::DELETE_SAVED_BLOCK_ACTION, - 'downloadBlocks' => $pref . Brizy_Admin_Blocks_Api::DOWNLOAD_BLOCKS, - 'uploadBlocks' => $pref . Brizy_Admin_Blocks_Api::UPLOAD_BLOCKS, - 'downloadLayouts' => $pref . Brizy_Admin_Layouts_Api::DOWNLOAD_LAYOUTS, - 'uploadLayouts' => $pref . Brizy_Admin_Layouts_Api::UPLOAD_LAYOUTS, - 'media' => $pref . Brizy_Editor_API::AJAX_MEDIA, - 'getMediaUid' => $pref . Brizy_Editor_API::AJAX_MEDIA_METAKEY, + 'heartBeat' => $pref . Brizy_Editor_API::AJAX_HEARTBEAT, + 'takeOver' => $pref . Brizy_Editor_API::AJAX_TAKE_OVER, + 'lockProject' => $pref . Brizy_Editor_API::AJAX_LOCK_PROJECT, + 'removeLock' => $pref . Brizy_Editor_API::AJAX_REMOVE_LOCK, + 'getPage' => $pref . Brizy_Editor_API::AJAX_GET, + 'getPostInfo' => $pref . Brizy_Editor_API::AJAX_GET_POST_INFO, + 'updatePage' => $pref . Brizy_Editor_API::AJAX_UPDATE, + 'getProject' => $pref . Brizy_Editor_API::AJAX_GET_PROJECT, + 'setProject' => $pref . Brizy_Editor_API::AJAX_SET_PROJECT, + 'setProjectMeta' => $pref . Brizy_Editor_API::AJAX_UPDATE_EDITOR_META_DATA, + 'getGlobalBlockList' => $pref . Brizy_Admin_Blocks_Api::GET_GLOBAL_BLOCKS_ACTION, + 'createGlobalBlock' => $pref . Brizy_Admin_Blocks_Api::CREATE_GLOBAL_BLOCK_ACTION, + 'updateGlobalBlock' => $pref . Brizy_Admin_Blocks_Api::UPDATE_GLOBAL_BLOCK_ACTION, + 'updateGlobalBlocks' => $pref . Brizy_Admin_Blocks_Api::UPDATE_GLOBAL_BLOCKS_ACTION, + 'deleteGlobalBlock' => $pref . Brizy_Admin_Blocks_Api::DELETE_GLOBAL_BLOCK_ACTION, + 'getRuleGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_GROUP_LIST, + 'getLayoutByUid' => $pref . Brizy_Admin_Layouts_Api::GET_LAYOUT_BY_UID_ACTION, + 'getLayoutList' => $pref . Brizy_Admin_Layouts_Api::GET_LAYOUTS_ACTION, + 'createLayout' => $pref . Brizy_Admin_Layouts_Api::CREATE_LAYOUT_ACTION, + 'updateLayout' => $pref . Brizy_Admin_Layouts_Api::UPDATE_LAYOUT_ACTION, + 'deleteLayout' => $pref . Brizy_Admin_Layouts_Api::DELETE_LAYOUT_ACTION, + 'cloudSignIn' => $pref . Brizy_Admin_Cloud_Api::AJAX_SIGNIN_ACTION, + 'cloudSignUp' => $pref . Brizy_Admin_Cloud_Api::AJAX_SIGNUP_ACTION, + 'cloudSignOut' => $pref . Brizy_Admin_Cloud_Api::AJAX_SIGNOUT_ACTION, + 'cloudSyncAllowed' => $pref . Brizy_Admin_Cloud_Api::AJAX_SYNC_ALLOWED, + 'cloudResetPassword' => $pref . Brizy_Admin_Cloud_Api::AJAX_RESET_PASSWORD_ACTION, + 'cloudSync' => $pref . Brizy_Admin_Cloud_Api::AJAX_TRIGGER_SYNC_ACTION, + 'createRule' => $pref . Brizy_Admin_Rules_Api::CREATE_RULE_ACTION, + 'createRules' => $pref . Brizy_Admin_Rules_Api::CREATE_RULES_ACTION, + 'updateRules' => $pref . Brizy_Admin_Rules_Api::UPDATE_RULES_ACTION, + 'deleteRule' => $pref . Brizy_Admin_Rules_Api::DELETE_RULE_ACTION, + 'getRuleList' => $pref . Brizy_Admin_Rules_Api::LIST_RULE_ACTION, + 'updateBlockPositions' => $pref . Brizy_Admin_Blocks_Api::UPDATE_POSITIONS_ACTION, + 'getSavedBlockByUid' => $pref . Brizy_Admin_Blocks_Api::GET_SAVED_BLOCK_ACTION, + 'getSavedBlockList' => $pref . Brizy_Admin_Blocks_Api::GET_SAVED_BLOCKS_ACTION, + 'createSavedBlock' => $pref . Brizy_Admin_Blocks_Api::CREATE_SAVED_BLOCK_ACTION, + 'updateSavedBlock' => $pref . Brizy_Admin_Blocks_Api::UPDATE_SAVED_BLOCK_ACTION, + 'deleteSavedBlock' => $pref . Brizy_Admin_Blocks_Api::DELETE_SAVED_BLOCK_ACTION, + 'downloadBlocks' => $pref . Brizy_Admin_Blocks_Api::DOWNLOAD_BLOCKS, + 'uploadBlocks' => $pref . Brizy_Admin_Blocks_Api::UPLOAD_BLOCKS, + 'downloadLayouts' => $pref . Brizy_Admin_Layouts_Api::DOWNLOAD_LAYOUTS, + 'uploadLayouts' => $pref . Brizy_Admin_Layouts_Api::UPLOAD_LAYOUTS, + 'media' => $pref . Brizy_Editor_API::AJAX_MEDIA, + 'getMediaUid' => $pref . Brizy_Editor_API::AJAX_MEDIA_METAKEY, 'getAttachmentUid' => $pref . Brizy_Editor_API::AJAX_CREATE_ATTACHMENT_UID, 'getServerTimeStamp' => $pref . Brizy_Editor_API::AJAX_TIMESTAMP, 'createBlockScreenshot' => $pref . Brizy_Editor_BlockScreenshotApi::AJAX_CREATE_BLOCK_SCREENSHOT, @@ -1389,7 +1398,7 @@ public function getApiActions( $config = [], $context = null ) { 'shortcodeContent' => $pref . Brizy_Editor_API::AJAX_SHORTCODE_CONTENT, 'placeholderContent' => $pref . Brizy_Editor_API::AJAX_PLACEHOLDER_CONTENT, 'placeholdersContent' => $pref . Brizy_Editor_API::AJAX_PLACEHOLDERS_CONTENT, - 'getPostTaxonomies' => $pref . Brizy_Editor_API::AJAX_GET_POST_TAXONOMIES, + 'getPostTaxonomies' => $pref . Brizy_Editor_API::AJAX_GET_POST_TAXONOMIES, 'getMenus' => $pref . Brizy_Editor_API::AJAX_GET_MENU_LIST, 'getTerms' => $pref . Brizy_Editor_API::AJAX_GET_TERMS, 'getTermsBy' => $pref . Brizy_Editor_API::AJAX_GET_TERMS_BY, @@ -1419,89 +1428,92 @@ public function getApiActions( $config = [], $context = null ) { 'rulePostsGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_POSTS_GROUP_LIST, 'ruleArchiveGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_ARCHIVE_GROUP_LIST, 'ruleTemplateGroupList' => $pref . Brizy_Admin_Rules_Api::RULE_TEMPLATE_GROUP_LIST, - 'symbolCreate' => $pref . Brizy_Admin_Symbols_Api::CREATE_ACTION, - 'symbolUpdate' => $pref . Brizy_Admin_Symbols_Api::UPDATE_ACTION, - 'symbolDelete' => $pref . Brizy_Admin_Symbols_Api::DELETE_ACTION, - 'symbolList' => $pref . Brizy_Admin_Symbols_Api::LIST_ACTION, - 'filterPlaceholderContents' => $pref . Brizy_Editor_Filters_Api::AJAX_FILTER_PLACEHOLDERS_CONTENT, - ); - - return $actions; - } - - /** - * @return array - * @throws Exception - */ - public function getCloudInfo() { - // the cloud will be always initialized with the exception when the white label is enabled - // we wil return isSyncAllowed = false just in case - if ( class_exists( 'BrizyPro_Admin_WhiteLabel' ) && BrizyPro_Admin_WhiteLabel::_init()->getEnabled() ) { - return array( - 'isSyncAllowed' => false, - ); - } - - $response = array( - 'isSyncAllowed' => true, - ); - - if ( $this->project->getMetaValue( 'brizy-cloud-token' ) !== null ) { - try { - $cloudClient = Brizy_Admin_Cloud_Client::instance( - Brizy_Editor_Project::get(), - new WP_Http() - ); - $versions = $cloudClient->getCloudEditorVersions(); - $response['isSyncAllowed'] = $versions['sync'] == BRIZY_SYNC_VERSION; - } catch ( Exception $e ) { - return [ 'isSyncAllowed' => false ]; - } - } - - return $response; - } - - /** - * Do not use: $userId = get_post_meta( $this->post->getWpPostId(), '_edit_last', true ); - * This meta _edit_last is often deleted by plugins dealing with optimize database - * - * @param $context - * - * @return bool - */ - private function isUserAllowedToAddScripts( $context ) { - - if ( $context == self::COMPILE_CONTEXT ) { - - $userId = $this->post->getLastUserEdited(); - - if ( $userId === null ) { - return true; - } - - } else { - $userId = get_current_user_id(); - } - - $userCan = user_can( $userId, 'unfiltered_html' ); - - return $userCan; - } - - private function getImgSizes() { - - $sizes = []; - - foreach ( Brizy_Editor::get_all_image_sizes() as $name => $size ) { - if ( isset( $size['crop'] ) ) { - unset( $size['crop'] ); - } - $size['name'] = $name; - $sizes[] = $size; - } - - return $sizes; - } + 'symbolCreate' => $pref . Brizy_Admin_Symbols_Api::CREATE_ACTION, + 'symbolUpdate' => $pref . Brizy_Admin_Symbols_Api::UPDATE_ACTION, + 'symbolDelete' => $pref . Brizy_Admin_Symbols_Api::DELETE_ACTION, + 'symbolList' => $pref . Brizy_Admin_Symbols_Api::LIST_ACTION, + 'filterPlaceholderContents' => $pref . Brizy_Editor_Filters_Api::AJAX_FILTER_PLACEHOLDERS_CONTENT, + ); + + return $actions; + } + + /** + * @return array + * @throws Exception + */ + public function getCloudInfo() + { + // the cloud will be always initialized with the exception when the white label is enabled + // we wil return isSyncAllowed = false just in case + if (class_exists('BrizyPro_Admin_WhiteLabel') && BrizyPro_Admin_WhiteLabel::_init()->getEnabled()) { + return array( + 'isSyncAllowed' => false, + ); + } + + $response = array( + 'isSyncAllowed' => true, + ); + + if ($this->project->getMetaValue('brizy-cloud-token') !== null) { + try { + $cloudClient = Brizy_Admin_Cloud_Client::instance( + Brizy_Editor_Project::get(), + new WP_Http() + ); + $versions = $cloudClient->getCloudEditorVersions(); + $response['isSyncAllowed'] = $versions['sync'] == BRIZY_SYNC_VERSION; + } catch (Exception $e) { + return ['isSyncAllowed' => false]; + } + } + + return $response; + } + + /** + * Do not use: $userId = get_post_meta( $this->post->getWpPostId(), '_edit_last', true ); + * This meta _edit_last is often deleted by plugins dealing with optimize database + * + * @param $context + * + * @return bool + */ + private function isUserAllowedToAddScripts($context) + { + + if ($context == self::COMPILE_CONTEXT) { + + $userId = $this->post->getLastUserEdited(); + + if ($userId === null) { + return true; + } + + } else { + $userId = get_current_user_id(); + } + + $userCan = user_can($userId, 'unfiltered_html'); + + return $userCan; + } + + private function getImgSizes() + { + + $sizes = []; + + foreach (Brizy_Editor::get_all_image_sizes() as $name => $size) { + if (isset($size['crop'])) { + unset($size['crop']); + } + $size['name'] = $name; + $sizes[] = $size; + } + + return $sizes; + } } From 49e524396edf95bbf9030bfb0c84bb6b90673b26 Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Wed, 19 Jul 2023 10:21:03 +0300 Subject: [PATCH 38/44] fix: added filters in module groups --- editor/editor/module-groups/essential-provider.php | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/editor/editor/module-groups/essential-provider.php b/editor/editor/module-groups/essential-provider.php index 7605089c1c..9a58cd287c 100644 --- a/editor/editor/module-groups/essential-provider.php +++ b/editor/editor/module-groups/essential-provider.php @@ -21,7 +21,8 @@ public function collect( $context ) { "Line", "MenuSimple", "Menu", - "Search" + "Search", + "Filters" ], 300 ), ]; } From 7068ff43ef4f667155fe4352f40ba58396679435 Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Tue, 1 Aug 2023 13:15:10 +0300 Subject: [PATCH 39/44] fix: added a new method in context to find by name and id --- composer.json | 2 +- content/context.php | 22 +++++-- editor/filters/api.php | 144 ++++++++++++++++++++++------------------- 3 files changed, 95 insertions(+), 73 deletions(-) diff --git a/composer.json b/composer.json index 3b3c35d5ef..3692959410 100755 --- a/composer.json +++ b/composer.json @@ -13,7 +13,7 @@ "knplabs/gaufrette": "0.7", "bagrinsergiu/brizy-migration-utils": "^1.4", "bagrinsergiu/brizy-merge-page-assets": "dev-master", - "bagrinsergiu/content-placeholder": "^2.0.8", + "bagrinsergiu/content-placeholder": "^2.0.9", "enshrined/svg-sanitize": "^0.13", "select2/select2": "^4.0", "symfony/dotenv": "^3", diff --git a/content/context.php b/content/context.php index cfabafa4f5..a04492a246 100644 --- a/content/context.php +++ b/content/context.php @@ -23,7 +23,7 @@ class Brizy_Content_Context implements ContextInterface public function __call($name, $arguments) { $method = substr($name, 0, 3); - $key = substr($name, 3); + $key = substr($name, 3); switch ($method) { case 'set': @@ -57,7 +57,7 @@ protected function get($name) public function afterExtract($contentPlaceholders, $instancePlaceholders, $contentAfterExtractor) { - $this->setPlaceholders(array_merge( $this->getPlaceholders(),$contentPlaceholders )); + $this->setPlaceholders(array_merge($this->getPlaceholders(), $contentPlaceholders)); } @@ -87,8 +87,8 @@ public function __construct($project, $brizy_post, $wp_post, $contentHtml, $pare $this->setProject($project); $this->setWpPost($wp_post); $this->setParentContext($parentContext); - $this->setEntity($wp_post); - } + $this->setEntity($wp_post); + } /** * @return array @@ -117,12 +117,23 @@ public function setPlaceholders(array $placeholders) */ public function getPlaceholderById($id) { - $results = $this->getPlaceholdersByAttrValue('id', $id); return isset($results[0]) ? $results[0] : null; } + public function getPlaceholderByNameAndId($name, $id) + { + if (isset($this->placeholders)) { + foreach ($this->placeholders as $placeholder) { + if ($placeholder->getName() == $name && $placeholder->getAttribute('id') == $id) { + return $placeholder; + } + } + } + return null; + } + /** * @param $key * @param $value @@ -131,7 +142,6 @@ public function getPlaceholderById($id) */ public function getPlaceholdersByAttrValue($key, $value) { - if (is_null($value)) { return null; } diff --git a/editor/filters/api.php b/editor/filters/api.php index a8435cfaf6..290544e27c 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -1,82 +1,94 @@ addNoPrivAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); - $this->addAjaxAction( self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array( $this, 'filterPlaceholdersContent' ) ); - } + protected function initializeApiActions() + { + $this->addNoPrivAjaxAction(self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array($this, 'filterPlaceholdersContent')); + $this->addAjaxAction(self::AJAX_FILTER_PLACEHOLDERS_CONTENT, array($this, 'filterPlaceholdersContent')); + } - protected function getRequestNonce() { - return $this->param( 'hash' ); - } + protected function getRequestNonce() + { + return $this->param('hash'); + } - public function filterPlaceholdersContent() { + public function filterPlaceholdersContent() + { - if(empty($postId = $this->param('post_id'))) { - $this->error(400, 'Please provide the post id'); - } + if (empty($postId = $this->param('post_id'))) { + $this->error(400, 'Please provide the post id'); + } - if(empty($placeholders = $this->param('placeholders'))) { - $this->error(400, 'Please provide the placeholders param'); - } + if (empty($placeholders = $this->param('placeholders'))) { + $this->error(400, 'Please provide the placeholders param'); + } - $placeholderContents = []; - $brizyPost = Brizy_Editor_Post::get($postId); - $postContent = $this->getBrizyPostContent(Brizy_Editor_Project::get(), $brizyPost); + $placeholderContents = []; + $brizyPost = Brizy_Editor_Post::get($postId); + $postContent = $this->getBrizyPostContent(Brizy_Editor_Project::get(), $brizyPost); $placeholderProvider = new Brizy_Content_PlaceholderProvider(); - $context = new Brizy_Content_Context(Brizy_Editor_Project::get(),$brizyPost,$brizyPost->getWpPost(),''); - $context->setProvider( $placeholderProvider ); - $extractor = new \BrizyPlaceholders\Extractor( $placeholderProvider ); - - /** - * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders; - */ - list( $contentPlaceholders, $placeholderInstances, $newPostContent ) = $extractor->extract( $postContent ); - $context->setPlaceholders($contentPlaceholders); - - foreach( $placeholders as $placeholderId) { - try { - /** - * @var \BrizyPlaceholders\ContentPlaceholder $placeholder; - */ - $placeholder = $context->getPlaceholderById($placeholderId); - - if(!$placeholder) { + $context = new Brizy_Content_Context(Brizy_Editor_Project::get(), $brizyPost, $brizyPost->getWpPost(), ''); + $context->setProvider($placeholderProvider); + $extractor = new \BrizyPlaceholders\Extractor($placeholderProvider); + + /** + * @var \BrizyPlaceholders\ContentPlaceholder[] $contentPlaceholders ; + */ + list($contentPlaceholders, $placeholderInstances, $newPostContent) = $extractor->extract($postContent); + $context->setPlaceholders($contentPlaceholders); + + foreach ($placeholders as $placeholderId) { + try { + /** + * @var \BrizyPlaceholders\ContentPlaceholder $placeholder ; + */ + $cleanId = str_replace(['-tag', '-pag'], '', $placeholderId); + if (strpos($placeholderId, "-tag") !== false) { + $placeholder = $context->getPlaceholderByNameAndId("brizy_dc_post_loop_tags", $cleanId); + } elseif (strpos($placeholderId, "-pag") !== false) { + $placeholder = $context->getPlaceholderByNameAndId("brizy_dc_post_loop_pagination", $cleanId); + } else { + $placeholder = $context->getPlaceholderById($placeholderId); + } + + if (!$placeholder) { $placeholderContents[$placeholderId] = ''; continue; } - /** - * @var Brizy_Content_Placeholders_Abstract $placeholderInstance; - */ - $placeholderInstance = $placeholderProvider->getPlaceholderSupportingName($placeholder->getName()); - $placeholderContents[$placeholderId] = $placeholderInstance->getValue($context,$placeholder); - } catch (\Exception $e) { - $placeholderContents[$placeholderId] = null; - } - } - - - $this->success(['placeholders'=>$placeholderContents]); - } - - private function getBrizyPostContent(Brizy_Editor_Project $project,Brizy_Editor_Post $post) { - $project = Brizy_Editor_Project::get(); - - if (!$post->get_compiled_html()) { - $compiled_html_body = $post->get_compiled_html_body(); - $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); - $post->set_needs_compile(true)->saveStorage(); - } else { - $compiled_page = $post->get_compiled_page(); - $content = $compiled_page->get_body(); - } - - return $content; - } + /** + * @var Brizy_Content_Placeholders_Abstract $placeholderInstance ; + */ + $placeholderInstance = $placeholderProvider->getPlaceholderSupportingName($placeholder->getName()); + $placeholderContents[$placeholderId] = $placeholderInstance->getValue($context, $placeholder); + } catch (\Exception $e) { + $placeholderContents[$placeholderId] = null; + } + } + + + $this->success(['placeholders' => $placeholderContents]); + } + + private function getBrizyPostContent(Brizy_Editor_Project $project, Brizy_Editor_Post $post) + { + $project = Brizy_Editor_Project::get(); + + if (!$post->get_compiled_html()) { + $compiled_html_body = $post->get_compiled_html_body(); + $content = Brizy_SiteUrlReplacer::restoreSiteUrl($compiled_html_body); + $post->set_needs_compile(true)->saveStorage(); + } else { + $compiled_page = $post->get_compiled_page(); + $content = $compiled_page->get_body(); + } + + return $content; + } } From 2cfaecf761af5e1e951e749a06a479ce87d4fc4a Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Wed, 2 Aug 2023 08:53:49 +0300 Subject: [PATCH 40/44] fix: updated composer.lock --- composer.lock | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/composer.lock b/composer.lock index 34195312b2..8f2f7c3c1f 100644 --- a/composer.lock +++ b/composer.lock @@ -4,14 +4,14 @@ "Read more about it at https://getcomposer.org/doc/01-basic-usage.md#installing-dependencies", "This file is @generated automatically" ], - "content-hash": "3304adb878f0b8cdc35383de6c064419", + "content-hash": "396f55004f56c13112b3cc191037766b", "packages": [ { "name": "bagrinsergiu/brizy-merge-page-assets", "version": "dev-master", "source": { "type": "git", - "url": "git@github.com:bagrinsergiu/brizy-merge-page-assets.git", + "url": "https://github.com/bagrinsergiu/brizy-merge-page-assets.git", "reference": "61eea2244cb34ff8666b802aafa74f74dec869da" }, "dist": { @@ -40,6 +40,10 @@ "brizy", "brizy merge assets" ], + "support": { + "source": "https://github.com/bagrinsergiu/brizy-merge-page-assets/tree/master", + "issues": "https://github.com/bagrinsergiu/brizy-merge-page-assets/issues" + }, "time": "2022-09-27T14:56:05+00:00" }, { @@ -47,7 +51,7 @@ "version": "1.5.4", "source": { "type": "git", - "url": "git@github.com:bagrinsergiu/brizy-migration-utils.git", + "url": "https://github.com/bagrinsergiu/brizy-migration-utils.git", "reference": "81523e89975e56d192bb3a5622ddbe1d06e10809" }, "dist": { @@ -77,6 +81,10 @@ } ], "description": "Data migration utils", + "support": { + "source": "https://github.com/bagrinsergiu/brizy-migration-utils/tree/1.5.4", + "issues": "https://github.com/bagrinsergiu/brizy-migration-utils/issues" + }, "time": "2022-07-08T10:43:38+00:00" }, { From a185c03445bdb05ddbdf5781b55c3b5407b324bc Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Thu, 3 Aug 2023 11:35:15 +0300 Subject: [PATCH 41/44] fix: removed notion of -tag and -pag logic from api --- editor/filters/api.php | 9 +-------- 1 file changed, 1 insertion(+), 8 deletions(-) diff --git a/editor/filters/api.php b/editor/filters/api.php index 290544e27c..004be87e04 100644 --- a/editor/filters/api.php +++ b/editor/filters/api.php @@ -48,14 +48,7 @@ public function filterPlaceholdersContent() /** * @var \BrizyPlaceholders\ContentPlaceholder $placeholder ; */ - $cleanId = str_replace(['-tag', '-pag'], '', $placeholderId); - if (strpos($placeholderId, "-tag") !== false) { - $placeholder = $context->getPlaceholderByNameAndId("brizy_dc_post_loop_tags", $cleanId); - } elseif (strpos($placeholderId, "-pag") !== false) { - $placeholder = $context->getPlaceholderByNameAndId("brizy_dc_post_loop_pagination", $cleanId); - } else { - $placeholder = $context->getPlaceholderById($placeholderId); - } + $placeholder = $context->getPlaceholderById($placeholderId); if (!$placeholder) { $placeholderContents[$placeholderId] = ''; From 00004d6e4d4309005b39e26c329c161bc24008e2 Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Wed, 23 Aug 2023 09:43:44 +0300 Subject: [PATCH 42/44] new: added filter placeholders url in config. --- editor/editor/editor.php | 1 + 1 file changed, 1 insertion(+) diff --git a/editor/editor/editor.php b/editor/editor/editor.php index d5a49cfa60..b697d5c849 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -159,6 +159,7 @@ public function config($context = self::COMPILE_CONTEXT) 'pluginSettings' => admin_url('admin.php?page=' . Brizy_Admin_Settings::menu_slug()), 'dashboardNavMenu' => admin_url('nav-menus.php'), 'customFile' => home_url('?' . Brizy_Editor::prefix('_attachment') . '='), + 'filterPlaceholders'=> home_url("/wp-admin/admin-ajax.php?action=".Brizy_Editor::prefix('_filter_placeholders_content')) ), 'form' => array( 'submitUrl' => '{{brizy_dc_ajax_url}}?action=' . Brizy_Editor::prefix( From a69fd4a307941747ff63edfe34e682afb3d4c0d8 Mon Sep 17 00:00:00 2001 From: Zaharia Alexandru Date: Thu, 21 Sep 2023 15:05:46 +0300 Subject: [PATCH 43/44] new: added editor client config filter --- editor/editor/editor.php | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/editor/editor/editor.php b/editor/editor/editor.php index b697d5c849..a5aeb6e581 100755 --- a/editor/editor/editor.php +++ b/editor/editor/editor.php @@ -96,7 +96,7 @@ public function getClientConfig($editorConfig, $context) ]; $config = $this->getApiConfigFields($config, $context); - + $config = apply_filters('brizy_client_config', $config, $context); return $config; } @@ -1341,7 +1341,6 @@ public function getProjectStatus() */ public function getApiActions($config = [], $context = null) { - $pref = Brizy_Editor::prefix(); $actions = array( From 264b8fd9b68b5a1f0889b7c6c2b55b0e10e6353c Mon Sep 17 00:00:00 2001 From: Artur Gunca Date: Wed, 23 Aug 2023 14:53:44 +0300 Subject: [PATCH 44/44] moved to API from editor --- .../src/Elements/filters/index.ts | 134 ++++++++++++++++++ public/editor-client/src/api/index.ts | 38 +++++ public/editor-client/src/config.ts | 8 +- public/editor-client/src/index.ts | 14 ++ public/editor-client/src/types/Filters.ts | 61 ++++++++ public/editor-client/src/types/global.d.ts | 9 ++ 6 files changed, 263 insertions(+), 1 deletion(-) create mode 100644 public/editor-client/src/Elements/filters/index.ts create mode 100644 public/editor-client/src/types/Filters.ts diff --git a/public/editor-client/src/Elements/filters/index.ts b/public/editor-client/src/Elements/filters/index.ts new file mode 100644 index 0000000000..554333b32c --- /dev/null +++ b/public/editor-client/src/Elements/filters/index.ts @@ -0,0 +1,134 @@ +import { getFields } from "../../api"; +import { + Choice, + FilterFieldsData, + Filters, + PossibleValue, + QueryTypeSource +} from "../../types/Filters"; +import { t } from "../../utils/i18n"; + +export const handler: Filters["handler"] = async (res, rej, data) => { + try { + const result = await getFields(data); + + const convertedValue = converter(result); + + res(convertedValue ?? []); + } catch (e) { + rej(t("Failed to load sources")); + } +}; + +export const possibleValues: Filters["possibleValues"] = async ( + res, + rej, + { type, search, optionSource, postId, loopAttributes } +) => { + try { + const result = await getFields({ postId, loopAttributes }); + + const convertPossibleValues = parseFields( + result, + optionSource, + type, + search + ); + + res(convertPossibleValues ?? []); + } catch (e) { + rej(t("Failed to load sources")); + } +}; + +const createQueryTypeSource = ( + query: string, + type: string, + source: string, + filterBy: string +): QueryTypeSource => { + return `${query}|||${type}|||${source}|||${filterBy}` as QueryTypeSource; +}; + +const converter = (data: FilterFieldsData): Choice[] => { + const arr = Object.values(data).reduce((acc: Choice[], cur) => { + const field = cur.map((item) => { + return { + value: createQueryTypeSource( + item.filterQuery + ? item.filterQuery + : item.optionQuery + ? item.optionQuery + : `metaKey=${item.optionSource}`, + item.type, + item.optionSource, + item.filterBy + ), + title: item.label + }; + }); + return [...acc, ...field]; + }, []); + + return arr ?? []; +}; + +const parseFields = ( + data: FilterFieldsData, + optionSource: string, + type: string, + search?: string +): Choice[] => { + const allItem = { value: "all", title: type === "inc" ? "All" : "None" }; + + const selectedItem = Object.values(data).reduce((acc, cur) => { + const field = cur.filter((item) => item.optionQuery === optionSource); + + return [...acc, ...field]; + }, [])[0]; + + if (selectedItem.optionSource === "tax") { + const items: Choice[] = ( + selectedItem.possibleValues as PossibleValue[] + ).map((it: PossibleValue) => ({ + value: it.term_id, + title: it.name + })); + + if (search) { + return [ + allItem, + ...items.filter((it) => + it.title.toLocaleLowerCase().includes(search.toLocaleLowerCase()) + ) + ]; + } + + if (checkNotNullOrUndefinedValues(items)) { + return [allItem, ...items]; + } + } + + if (selectedItem.optionSource === "meta") { + const items = selectedItem.possibleValues as Choice[]; + + if (search) { + return [ + allItem, + ...items.filter((it) => + it.title.toLocaleLowerCase().includes(search.toLocaleLowerCase()) + ) + ]; + } + + if (checkNotNullOrUndefinedValues(items)) { + return [allItem, ...items]; + } + } + + return [allItem]; +}; + +function checkNotNullOrUndefinedValues(arr: unknown[]) { + return arr.every((value) => value !== null && value !== undefined); +} diff --git a/public/editor-client/src/api/index.ts b/public/editor-client/src/api/index.ts index bedc6751e3..86679bd973 100644 --- a/public/editor-client/src/api/index.ts +++ b/public/editor-client/src/api/index.ts @@ -589,6 +589,7 @@ export const uploadSaveLayouts = async ( formData.append("version", editorVersion); formData.append("hash", hash); + formData.append("action", actions.uploadBlocks); const r = await request(url, { method: "POST", body: formData }); @@ -763,3 +764,40 @@ export const updatePopupRules = async ( }; //#endregion + +//#region FiltersFields + +export const getFields = async (data: { + postId: string; + loopAttributes: string; +}) => { + try { + const config = getConfig(); + + if (!config) { + throw new Error(t("Invalid __BRZ_PLUGIN_ENV__")); + } + + const { editorVersion, url, hash, actions } = config; + + const body = new URLSearchParams({ + hash: hash, + version: editorVersion, + action: actions.filterFields ?? "brizy_filter_fields", + ...data + }); + + const result = await request(url, { + method: "POST", + body: body + }); + + const r = await result.json(); + + return r.data; + } catch (e) { + throw new Error(t("Fail to load fields!")); + } +}; + +//#endregion diff --git a/public/editor-client/src/config.ts b/public/editor-client/src/config.ts index 8d09aabd49..92af087f59 100644 --- a/public/editor-client/src/config.ts +++ b/public/editor-client/src/config.ts @@ -39,6 +39,8 @@ interface Actions { getPostObjects: string; searchPosts: string; + + filterFields: string; } interface API { @@ -178,7 +180,11 @@ const actionsReader = parseStrict({ ), searchPosts: pipe( mPipe(Obj.readKey("searchPosts"), Str.read), - throwOnNullish("INvalid actions: searchPosts") + throwOnNullish("Invalid actions: searchPosts") + ), + filterFields: pipe( + mPipe(Obj.readKey("filterFields"), Str.read), + throwOnNullish("Invalid actions: filterFields") ) }); diff --git a/public/editor-client/src/index.ts b/public/editor-client/src/index.ts index 8b9338aea3..fe016183a0 100644 --- a/public/editor-client/src/index.ts +++ b/public/editor-client/src/index.ts @@ -12,6 +12,7 @@ import { } from "./defaultTemplates"; import { explodePlaceholder } from "./dynamicContent/explodePlaceholder"; import { makePlaceholder } from "./dynamicContent/makePlaceholder"; +import { handler as filters, possibleValues } from "./Elements/filters"; import { addMedia } from "./media/addMedia"; import { addMediaGallery } from "./media/addMediaGallery"; import { onChange } from "./onChange"; @@ -75,4 +76,17 @@ if (window.__VISUAL_CONFIG__) { window.__VISUAL_CONFIG__.dynamicContent.explodePlaceholder = explodePlaceholder; } + + // Elements + if ( + window.__VISUAL_CONFIG__.elements && + window.__VISUAL_CONFIG__.elements.filters + ) { + window.__VISUAL_CONFIG__.elements.filters.handler = filters; + window.__VISUAL_CONFIG__.elements.filters.possibleValues = possibleValues; + } else { + window.__VISUAL_CONFIG__.elements = { + filters: { handler: filters, possibleValues: possibleValues } + }; + } } diff --git a/public/editor-client/src/types/Filters.ts b/public/editor-client/src/types/Filters.ts new file mode 100644 index 0000000000..edcd71598c --- /dev/null +++ b/public/editor-client/src/types/Filters.ts @@ -0,0 +1,61 @@ +import { NewType } from "./NewType"; +import { Response } from "./Response"; + +export type Choice = { title: string; value: string | number }; + +export type QueryTypeSource = NewType; + +interface FieldsCommon { + filterQuery: string; + label: string; + optionQuery: string; + optionSource: string; + filterBy: string; + type: string; +} + +export interface FilterField extends FieldsCommon { + possibleValues: PossibleValue[] | Choice[]; +} + +export type PossibleValue = { + count: number; + description: string; + filter: string; + name: string; + parent: number; + slug: string; + taxonomy: string; + term_group: number; + term_id: number; + term_taxonomy_id: number; +}; + +export type FilterFieldsData = { + fields: FilterField[]; + taxonomies: FilterField[]; + metaFields: FilterField[]; + authors: FilterField[]; +}; + +export interface Filters { + handler: ( + res: Response, + rej: Response, + args: { + postId: string; + loopAttributes: string; + } + ) => void; + possibleValues: ( + res: Response, + rej: Response, + data: { + postId: string; + loopAttributes: string; + optionSource: string; + type: string; + search?: string; + } + ) => void; +} diff --git a/public/editor-client/src/types/global.d.ts b/public/editor-client/src/types/global.d.ts index 68b35673c6..6df8dddfd1 100644 --- a/public/editor-client/src/types/global.d.ts +++ b/public/editor-client/src/types/global.d.ts @@ -17,6 +17,7 @@ import { OnChange } from "./OnChange"; import { PopupConditions } from "./PopupConditions"; import { PublishData } from "./Project"; import { SavedBlocks, SavedLayouts, SavedPopups } from "./SavedBlocks"; +import { Filters } from "./Filters"; declare class WPMediaLibrary { get: (selector: string) => import("backbone").Collection; @@ -146,6 +147,14 @@ export interface VISUAL_CONFIG { }; //#endregion + + // #region Elements + + elements?: { + filters: Filters; + }; + + //#endregion } declare global {